blob: 2dc04f2f3d8698fb5703b4ca420640d32ab60c06 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Implements C++ name mangling according to the Itanium C++ ABI,
11// which is used in GCC 3.2 and newer (and many compilers that are
12// ABI-compatible with GCC):
13//
Vlad Tsyrklevichb1bb99d2017-09-12 00:21:17 +000014// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
Guy Benyei11169dd2012-12-18 14:30:41 +000015//
16//===----------------------------------------------------------------------===//
17#include "clang/AST/Mangle.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000023#include "clang/AST/DeclOpenMP.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/DeclTemplate.h"
David Majnemer58e5bee2014-03-24 21:43:36 +000025#include "clang/AST/Expr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/Basic/ABI.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "llvm/ADT/StringExtras.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35
36#define MANGLE_CHECKER 0
37
38#if MANGLE_CHECKER
39#include <cxxabi.h>
40#endif
41
42using namespace clang;
43
44namespace {
45
Justin Bognere8d762e2015-05-22 06:48:13 +000046/// Retrieve the declaration context that should be used when mangling the given
47/// declaration.
Guy Benyei11169dd2012-12-18 14:30:41 +000048static const DeclContext *getEffectiveDeclContext(const Decl *D) {
Fangrui Song6907ce22018-07-30 19:24:48 +000049 // The ABI assumes that lambda closure types that occur within
Guy Benyei11169dd2012-12-18 14:30:41 +000050 // default arguments live in the context of the function. However, due to
51 // the way in which Clang parses and creates function declarations, this is
Fangrui Song6907ce22018-07-30 19:24:48 +000052 // not the case: the lambda closure type ends up living in the context
Guy Benyei11169dd2012-12-18 14:30:41 +000053 // where the function itself resides, because the function declaration itself
54 // had not yet been created. Fix the context here.
55 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
56 if (RD->isLambda())
57 if (ParmVarDecl *ContextParam
58 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
59 return ContextParam->getDeclContext();
60 }
Eli Friedman0cd23352013-07-10 01:33:19 +000061
62 // Perform the same check for block literals.
63 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
64 if (ParmVarDecl *ContextParam
65 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
66 return ContextParam->getDeclContext();
67 }
Fangrui Song6907ce22018-07-30 19:24:48 +000068
Eli Friedman95f50122013-07-02 17:52:28 +000069 const DeclContext *DC = D->getDeclContext();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000070 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
71 return getEffectiveDeclContext(cast<Decl>(DC));
72 }
Eli Friedman95f50122013-07-02 17:52:28 +000073
David Majnemerf8c02e62015-02-18 19:08:11 +000074 if (const auto *VD = dyn_cast<VarDecl>(D))
75 if (VD->isExternC())
76 return VD->getASTContext().getTranslationUnitDecl();
77
78 if (const auto *FD = dyn_cast<FunctionDecl>(D))
79 if (FD->isExternC())
80 return FD->getASTContext().getTranslationUnitDecl();
81
Richard Smithec24bbe2016-04-29 01:23:20 +000082 return DC->getRedeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +000083}
84
85static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
86 return getEffectiveDeclContext(cast<Decl>(DC));
87}
Eli Friedman95f50122013-07-02 17:52:28 +000088
89static bool isLocalContainerContext(const DeclContext *DC) {
90 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
91}
92
Eli Friedmaneecc09a2013-07-05 20:27:40 +000093static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman92821742013-07-02 02:01:18 +000094 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000095 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman95f50122013-07-02 17:52:28 +000096 if (isLocalContainerContext(DC))
Eli Friedmaneecc09a2013-07-05 20:27:40 +000097 return dyn_cast<RecordDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +000098 D = cast<Decl>(DC);
99 DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000100 }
Craig Topper36250ad2014-05-12 05:36:57 +0000101 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000102}
103
104static const FunctionDecl *getStructor(const FunctionDecl *fn) {
105 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
106 return ftd->getTemplatedDecl();
107
108 return fn;
109}
110
111static const NamedDecl *getStructor(const NamedDecl *decl) {
112 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
113 return (fn ? getStructor(fn) : decl);
114}
David Majnemer2206bf52014-03-05 08:57:59 +0000115
116static bool isLambda(const NamedDecl *ND) {
117 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
118 if (!Record)
119 return false;
120
121 return Record->isLambda();
122}
123
Guy Benyei11169dd2012-12-18 14:30:41 +0000124static const unsigned UnknownArity = ~0U;
125
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000126class ItaniumMangleContextImpl : public ItaniumMangleContext {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000127 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
128 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei11169dd2012-12-18 14:30:41 +0000129 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000130
Guy Benyei11169dd2012-12-18 14:30:41 +0000131public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000132 explicit ItaniumMangleContextImpl(ASTContext &Context,
133 DiagnosticsEngine &Diags)
134 : ItaniumMangleContext(Context, Diags) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000135
Guy Benyei11169dd2012-12-18 14:30:41 +0000136 /// @name Mangler Entry Points
137 /// @{
138
Craig Toppercbce6e92014-03-11 06:22:39 +0000139 bool shouldMangleCXXName(const NamedDecl *D) override;
David Majnemer58e5bee2014-03-24 21:43:36 +0000140 bool shouldMangleStringLiteral(const StringLiteral *) override {
141 return false;
142 }
Craig Toppercbce6e92014-03-11 06:22:39 +0000143 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
144 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
145 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000146 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
147 const ThisAdjustment &ThisAdjustment,
Craig Toppercbce6e92014-03-11 06:22:39 +0000148 raw_ostream &) override;
David Majnemerdaff3702014-05-01 17:50:17 +0000149 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
150 raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000151 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
152 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000153 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
Craig Toppercbce6e92014-03-11 06:22:39 +0000154 const CXXRecordDecl *Type, raw_ostream &) override;
155 void mangleCXXRTTI(QualType T, raw_ostream &) override;
156 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
157 void mangleTypeName(QualType T, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000159 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000160 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000161 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000162
Rafael Espindola1e4df922014-09-16 15:18:21 +0000163 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
164 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000165 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
166 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
167 void mangleDynamicAtExitDestructor(const VarDecl *D,
168 raw_ostream &Out) override;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000169 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
170 raw_ostream &Out) override;
Reid Klecknerebaf28d2015-04-14 20:59:00 +0000171 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
172 raw_ostream &Out) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000173 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
174 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
175 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000176
David Majnemer58e5bee2014-03-24 21:43:36 +0000177 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
178
Guy Benyei11169dd2012-12-18 14:30:41 +0000179 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000180 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000181 if (isLambda(ND))
182 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000183
184 // Anonymous tags are already numbered.
185 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
186 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
187 return false;
188 }
189
190 // Use the canonical number for externally visible decls.
191 if (ND->isExternallyVisible()) {
192 unsigned discriminator = getASTContext().getManglingNumber(ND);
193 if (discriminator == 1)
194 return false;
195 disc = discriminator - 2;
196 return true;
197 }
198
199 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000201 if (!discriminator) {
202 const DeclContext *DC = getEffectiveDeclContext(ND);
203 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
204 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000205 if (discriminator == 1)
206 return false;
207 disc = discriminator-2;
208 return true;
209 }
210 /// @}
211};
212
Justin Bognere8d762e2015-05-22 06:48:13 +0000213/// Manage the mangling of a single name.
Guy Benyei11169dd2012-12-18 14:30:41 +0000214class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000215 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000216 raw_ostream &Out;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000217 bool NullOut = false;
218 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
219 /// This mode is used when mangler creates another mangler recursively to
220 /// calculate ABI tags for the function return value or the variable type.
221 /// Also it is required to avoid infinite recursion in some cases.
222 bool DisableDerivedAbiTags = false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000223
224 /// The "structor" is the top-level declaration being mangled, if
225 /// that's not a template specialization; otherwise it's the pattern
226 /// for that specialization.
227 const NamedDecl *Structor;
228 unsigned StructorType;
229
Justin Bognere8d762e2015-05-22 06:48:13 +0000230 /// The next substitution sequence number.
Guy Benyei11169dd2012-12-18 14:30:41 +0000231 unsigned SeqID;
232
233 class FunctionTypeDepthState {
234 unsigned Bits;
235
236 enum { InResultTypeMask = 1 };
237
238 public:
239 FunctionTypeDepthState() : Bits(0) {}
240
241 /// The number of function types we're inside.
242 unsigned getDepth() const {
243 return Bits >> 1;
244 }
245
246 /// True if we're in the return type of the innermost function type.
247 bool isInResultType() const {
248 return Bits & InResultTypeMask;
249 }
250
251 FunctionTypeDepthState push() {
252 FunctionTypeDepthState tmp = *this;
253 Bits = (Bits & ~InResultTypeMask) + 2;
254 return tmp;
255 }
256
257 void enterResultType() {
258 Bits |= InResultTypeMask;
259 }
260
261 void leaveResultType() {
262 Bits &= ~InResultTypeMask;
263 }
264
265 void pop(FunctionTypeDepthState saved) {
266 assert(getDepth() == saved.getDepth() + 1);
267 Bits = saved.Bits;
268 }
269
270 } FunctionTypeDepth;
271
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000272 // abi_tag is a gcc attribute, taking one or more strings called "tags".
273 // The goal is to annotate against which version of a library an object was
274 // built and to be able to provide backwards compatibility ("dual abi").
275 // For more information see docs/ItaniumMangleAbiTags.rst.
276 typedef SmallVector<StringRef, 4> AbiTagList;
277
278 // State to gather all implicit and explicit tags used in a mangled name.
279 // Must always have an instance of this while emitting any name to keep
280 // track.
281 class AbiTagState final {
282 public:
283 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
284 Parent = LinkHead;
285 LinkHead = this;
286 }
287
288 // No copy, no move.
289 AbiTagState(const AbiTagState &) = delete;
290 AbiTagState &operator=(const AbiTagState &) = delete;
291
292 ~AbiTagState() { pop(); }
293
294 void write(raw_ostream &Out, const NamedDecl *ND,
295 const AbiTagList *AdditionalAbiTags) {
296 ND = cast<NamedDecl>(ND->getCanonicalDecl());
297 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
298 assert(
299 !AdditionalAbiTags &&
300 "only function and variables need a list of additional abi tags");
301 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
302 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
303 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
304 AbiTag->tags().end());
305 }
306 // Don't emit abi tags for namespaces.
307 return;
308 }
309 }
310
311 AbiTagList TagList;
312 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
313 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
314 AbiTag->tags().end());
315 TagList.insert(TagList.end(), AbiTag->tags().begin(),
316 AbiTag->tags().end());
317 }
318
319 if (AdditionalAbiTags) {
320 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
321 AdditionalAbiTags->end());
322 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
323 AdditionalAbiTags->end());
324 }
325
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +0000326 llvm::sort(TagList.begin(), TagList.end());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000327 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
328
329 writeSortedUniqueAbiTags(Out, TagList);
330 }
331
332 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
333 void setUsedAbiTags(const AbiTagList &AbiTags) {
334 UsedAbiTags = AbiTags;
335 }
336
337 const AbiTagList &getEmittedAbiTags() const {
338 return EmittedAbiTags;
339 }
340
341 const AbiTagList &getSortedUniqueUsedAbiTags() {
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +0000342 llvm::sort(UsedAbiTags.begin(), UsedAbiTags.end());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000343 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
344 UsedAbiTags.end());
345 return UsedAbiTags;
346 }
347
348 private:
349 //! All abi tags used implicitly or explicitly.
350 AbiTagList UsedAbiTags;
351 //! All explicit abi tags (i.e. not from namespace).
352 AbiTagList EmittedAbiTags;
353
354 AbiTagState *&LinkHead;
355 AbiTagState *Parent = nullptr;
356
357 void pop() {
358 assert(LinkHead == this &&
359 "abi tag link head must point to us on destruction");
360 if (Parent) {
361 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
362 UsedAbiTags.begin(), UsedAbiTags.end());
363 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
364 EmittedAbiTags.begin(),
365 EmittedAbiTags.end());
366 }
367 LinkHead = Parent;
368 }
369
370 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
371 for (const auto &Tag : AbiTags) {
372 EmittedAbiTags.push_back(Tag);
373 Out << "B";
374 Out << Tag.size();
375 Out << Tag;
376 }
377 }
378 };
379
380 AbiTagState *AbiTags = nullptr;
381 AbiTagState AbiTagsRoot;
382
Guy Benyei11169dd2012-12-18 14:30:41 +0000383 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
Richard Smithdd8b5332017-09-04 05:37:53 +0000384 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
Guy Benyei11169dd2012-12-18 14:30:41 +0000385
386 ASTContext &getASTContext() const { return Context.getASTContext(); }
387
388public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000389 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000390 const NamedDecl *D = nullptr, bool NullOut_ = false)
391 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
392 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000393 // These can't be mangled without a ctor type or dtor type.
394 assert(!D || (!isa<CXXDestructorDecl>(D) &&
395 !isa<CXXConstructorDecl>(D)));
396 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000397 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000398 const CXXConstructorDecl *D, CXXCtorType Type)
399 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000400 SeqID(0), AbiTagsRoot(AbiTags) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000401 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000402 const CXXDestructorDecl *D, CXXDtorType Type)
403 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000404 SeqID(0), AbiTagsRoot(AbiTags) { }
405
406 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
407 : Context(Outer.Context), Out(Out_), NullOut(false),
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) {}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000411
412 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
413 : Context(Outer.Context), Out(Out_), NullOut(true),
414 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000415 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
416 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000417
418#if MANGLE_CHECKER
419 ~CXXNameMangler() {
420 if (Out.str()[0] == '\01')
421 return;
422
423 int status = 0;
424 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
425 assert(status == 0 && "Could not demangle mangled name!");
426 free(result);
427 }
428#endif
429 raw_ostream &getStream() { return Out; }
430
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000431 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
432 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
433
David Majnemer7ff7eb72015-02-18 07:47:09 +0000434 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000435 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
436 void mangleNumber(const llvm::APSInt &I);
437 void mangleNumber(int64_t Number);
438 void mangleFloat(const llvm::APFloat &F);
439 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000440 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000441 void mangleName(const NamedDecl *ND);
442 void mangleType(QualType T);
443 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
Fangrui Song6907ce22018-07-30 19:24:48 +0000444
Guy Benyei11169dd2012-12-18 14:30:41 +0000445private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000446
Guy Benyei11169dd2012-12-18 14:30:41 +0000447 bool mangleSubstitution(const NamedDecl *ND);
448 bool mangleSubstitution(QualType T);
449 bool mangleSubstitution(TemplateName Template);
450 bool mangleSubstitution(uintptr_t Ptr);
451
Guy Benyei11169dd2012-12-18 14:30:41 +0000452 void mangleExistingSubstitution(TemplateName name);
453
454 bool mangleStandardSubstitution(const NamedDecl *ND);
455
456 void addSubstitution(const NamedDecl *ND) {
457 ND = cast<NamedDecl>(ND->getCanonicalDecl());
458
459 addSubstitution(reinterpret_cast<uintptr_t>(ND));
460 }
461 void addSubstitution(QualType T);
462 void addSubstitution(TemplateName Template);
463 void addSubstitution(uintptr_t Ptr);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000464 // Destructive copy substitutions from other mangler.
465 void extendSubstitutions(CXXNameMangler* Other);
Guy Benyei11169dd2012-12-18 14:30:41 +0000466
467 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000468 bool recursive = false);
469 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000470 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000471 const TemplateArgumentLoc *TemplateArgs,
472 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000473 unsigned KnownArity = UnknownArity);
474
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000475 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
476
477 void mangleNameWithAbiTags(const NamedDecl *ND,
478 const AbiTagList *AdditionalAbiTags);
Richard Smithdd8b5332017-09-04 05:37:53 +0000479 void mangleModuleName(const Module *M);
480 void mangleModuleNamePrefix(StringRef Name);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000481 void mangleTemplateName(const TemplateDecl *TD,
482 const TemplateArgument *TemplateArgs,
483 unsigned NumTemplateArgs);
484 void mangleUnqualifiedName(const NamedDecl *ND,
485 const AbiTagList *AdditionalAbiTags) {
486 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
487 AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000488 }
489 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000490 unsigned KnownArity,
491 const AbiTagList *AdditionalAbiTags);
492 void mangleUnscopedName(const NamedDecl *ND,
493 const AbiTagList *AdditionalAbiTags);
494 void mangleUnscopedTemplateName(const TemplateDecl *ND,
495 const AbiTagList *AdditionalAbiTags);
496 void mangleUnscopedTemplateName(TemplateName,
497 const AbiTagList *AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000498 void mangleSourceName(const IdentifierInfo *II);
Erich Keane757d3172016-11-02 18:29:35 +0000499 void mangleRegCallName(const IdentifierInfo *II);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000500 void mangleSourceNameWithAbiTags(
501 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
502 void mangleLocalName(const Decl *D,
503 const AbiTagList *AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +0000504 void mangleBlockForPrefix(const BlockDecl *Block);
505 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000506 void mangleLambda(const CXXRecordDecl *Lambda);
507 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000508 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 bool NoFunction=false);
510 void mangleNestedName(const TemplateDecl *TD,
511 const TemplateArgument *TemplateArgs,
512 unsigned NumTemplateArgs);
513 void manglePrefix(NestedNameSpecifier *qualifier);
514 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
515 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000516 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000517 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000518 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
519 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000520 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000521 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
John McCall07daf722016-03-01 22:18:03 +0000522 void mangleVendorQualifier(StringRef qualifier);
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000523 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000524 void mangleRefQualifier(RefQualifierKind RefQualifier);
525
526 void mangleObjCMethodName(const ObjCMethodDecl *MD);
527
528 // Declare manglers for every type class.
529#define ABSTRACT_TYPE(CLASS, PARENT)
530#define NON_CANONICAL_TYPE(CLASS, PARENT)
531#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
532#include "clang/AST/TypeNodes.def"
533
534 void mangleType(const TagType*);
535 void mangleType(TemplateName);
John McCall07daf722016-03-01 22:18:03 +0000536 static StringRef getCallingConvQualifierName(CallingConv CC);
537 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
538 void mangleExtFunctionInfo(const FunctionType *T);
539 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000540 const FunctionDecl *FD = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000541 void mangleNeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000542 void mangleNeonVectorType(const DependentVectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000543 void mangleAArch64NeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000544 void mangleAArch64NeonVectorType(const DependentVectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000545
546 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000547 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000548 void mangleMemberExpr(const Expr *base, bool isArrow,
549 NestedNameSpecifier *qualifier,
550 NamedDecl *firstQualifierLookup,
551 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000552 const TemplateArgumentLoc *TemplateArgs,
553 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000554 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000555 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000556 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000557 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
Richard Smith5179eb72016-06-28 19:03:57 +0000558 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +0000559 void mangleCXXDtorType(CXXDtorType T);
560
James Y Knight04ec5bf2015-12-24 02:59:37 +0000561 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
562 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000563 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
564 unsigned NumTemplateArgs);
565 void mangleTemplateArgs(const TemplateArgumentList &AL);
566 void mangleTemplateArg(TemplateArgument A);
567
568 void mangleTemplateParameter(unsigned Index);
569
570 void mangleFunctionParam(const ParmVarDecl *parm);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000571
572 void writeAbiTags(const NamedDecl *ND,
573 const AbiTagList *AdditionalAbiTags);
574
575 // Returns sorted unique list of ABI tags.
576 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
577 // Returns sorted unique list of ABI tags.
578 AbiTagList makeVariableTypeTags(const VarDecl *VD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000579};
580
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000581}
Guy Benyei11169dd2012-12-18 14:30:41 +0000582
Rafael Espindola002667c2013-10-16 01:40:34 +0000583bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000584 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000585 if (FD) {
586 LanguageLinkage L = FD->getLanguageLinkage();
587 // Overloadable functions need mangling.
588 if (FD->hasAttr<OverloadableAttr>())
589 return true;
590
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000591 // "main" is not mangled.
592 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000593 return false;
594
Martin Storsjo92e26612018-07-16 05:42:25 +0000595 // The Windows ABI expects that we would never mangle "typical"
596 // user-defined entry points regardless of visibility or freestanding-ness.
597 //
598 // N.B. This is distinct from asking about "main". "main" has a lot of
599 // special rules associated with it in the standard while these
600 // user-defined entry points are outside of the purview of the standard.
601 // For example, there can be only one definition for "main" in a standards
602 // compliant program; however nothing forbids the existence of wmain and
603 // WinMain in the same translation unit.
604 if (FD->isMSVCRTEntryPoint())
605 return false;
606
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000607 // C++ functions and those whose names are not a simple identifier need
608 // mangling.
609 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
610 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000611
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000612 // C functions are not mangled.
613 if (L == CLanguageLinkage)
614 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000615 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000616
617 // Otherwise, no mangling is done outside C++ mode.
618 if (!getASTContext().getLangOpts().CPlusPlus)
619 return false;
620
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000621 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithbdb84f32016-07-22 23:36:59 +0000622 if (VD && !isa<DecompositionDecl>(D)) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000623 // C variables are not mangled.
624 if (VD->isExternC())
625 return false;
626
627 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000628 const DeclContext *DC = getEffectiveDeclContext(D);
629 // Check for extern variable declared locally.
630 if (DC->isFunctionOrMethod() && D->hasLinkage())
631 while (!DC->isNamespace() && !DC->isTranslationUnit())
632 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000633 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000634 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
Larisse Voufo39a1e502013-08-06 01:03:05 +0000635 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000636 return false;
637 }
638
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 return true;
640}
641
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000642void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
643 const AbiTagList *AdditionalAbiTags) {
644 assert(AbiTags && "require AbiTagState");
645 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
646}
647
648void CXXNameMangler::mangleSourceNameWithAbiTags(
649 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
650 mangleSourceName(ND->getIdentifier());
651 writeAbiTags(ND, AdditionalAbiTags);
652}
653
David Majnemer7ff7eb72015-02-18 07:47:09 +0000654void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000655 // <mangled-name> ::= _Z <encoding>
656 // ::= <data name>
657 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000658 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000659 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
660 mangleFunctionEncoding(FD);
661 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
662 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000663 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
664 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000665 else
666 mangleName(cast<FieldDecl>(D));
667}
668
669void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
670 // <encoding> ::= <function name> <bare-function-type>
Guy Benyei11169dd2012-12-18 14:30:41 +0000671
672 // Don't mangle in the type if this isn't a decl we should typically mangle.
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000673 if (!Context.shouldMangleDeclName(FD)) {
674 mangleName(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000675 return;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000676 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000677
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000678 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
679 if (ReturnTypeAbiTags.empty()) {
680 // There are no tags for return type, the simplest case.
681 mangleName(FD);
682 mangleFunctionEncodingBareType(FD);
683 return;
684 }
685
686 // Mangle function name and encoding to temporary buffer.
687 // We have to output name and encoding to the same mangler to get the same
688 // substitution as it will be in final mangling.
689 SmallString<256> FunctionEncodingBuf;
690 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
691 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
692 // Output name of the function.
693 FunctionEncodingMangler.disableDerivedAbiTags();
694 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
695
696 // Remember length of the function name in the buffer.
697 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
698 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
699
700 // Get tags from return type that are not present in function name or
701 // encoding.
702 const AbiTagList &UsedAbiTags =
703 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
704 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
705 AdditionalAbiTags.erase(
706 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
707 UsedAbiTags.begin(), UsedAbiTags.end(),
708 AdditionalAbiTags.begin()),
709 AdditionalAbiTags.end());
710
711 // Output name with implicit tags and function encoding from temporary buffer.
712 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
713 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000714
715 // Function encoding could create new substitutions so we have to add
716 // temp mangled substitutions to main mangler.
717 extendSubstitutions(&FunctionEncodingMangler);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000718}
719
720void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000721 if (FD->hasAttr<EnableIfAttr>()) {
722 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
723 Out << "Ua9enable_ifI";
Michael Kruse41dd6ce2018-06-25 20:06:13 +0000724 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
725 // it here.
726 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
727 E = FD->getAttrs().rend();
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000728 I != E; ++I) {
729 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
730 if (!EIA)
731 continue;
732 Out << 'X';
733 mangleExpression(EIA->getCond());
734 Out << 'E';
735 }
736 Out << 'E';
737 FunctionTypeDepth.pop(Saved);
738 }
739
Richard Smith5179eb72016-06-28 19:03:57 +0000740 // When mangling an inheriting constructor, the bare function type used is
741 // that of the inherited constructor.
742 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
743 if (auto Inherited = CD->getInheritedConstructor())
744 FD = Inherited.getConstructor();
745
Guy Benyei11169dd2012-12-18 14:30:41 +0000746 // Whether the mangling of a function type includes the return type depends on
747 // the context and the nature of the function. The rules for deciding whether
748 // the return type is included are:
749 //
750 // 1. Template functions (names or types) have return types encoded, with
751 // the exceptions listed below.
752 // 2. Function types not appearing as part of a function name mangling,
753 // e.g. parameters, pointer types, etc., have return type encoded, with the
754 // exceptions listed below.
755 // 3. Non-template function names do not have return types encoded.
756 //
757 // The exceptions mentioned in (1) and (2) above, for which the return type is
758 // never included, are
759 // 1. Constructors.
760 // 2. Destructors.
761 // 3. Conversion operator functions, e.g. operator int.
762 bool MangleReturnType = false;
763 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
764 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
765 isa<CXXConversionDecl>(FD)))
766 MangleReturnType = true;
767
768 // Mangle the type of the primary template.
769 FD = PrimaryTemplate->getTemplatedDecl();
770 }
771
John McCall07daf722016-03-01 22:18:03 +0000772 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000773 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000774}
775
776static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
777 while (isa<LinkageSpecDecl>(DC)) {
778 DC = getEffectiveParentContext(DC);
779 }
780
781 return DC;
782}
783
Justin Bognere8d762e2015-05-22 06:48:13 +0000784/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000785static bool isStd(const NamespaceDecl *NS) {
786 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
787 ->isTranslationUnit())
788 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000789
Guy Benyei11169dd2012-12-18 14:30:41 +0000790 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
791 return II && II->isStr("std");
792}
793
794// isStdNamespace - Return whether a given decl context is a toplevel 'std'
795// namespace.
796static bool isStdNamespace(const DeclContext *DC) {
797 if (!DC->isNamespace())
798 return false;
799
800 return isStd(cast<NamespaceDecl>(DC));
801}
802
803static const TemplateDecl *
804isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
805 // Check if we have a function template.
Richard Smith5179eb72016-06-28 19:03:57 +0000806 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000807 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
808 TemplateArgs = FD->getTemplateSpecializationArgs();
809 return TD;
810 }
811 }
812
813 // Check if we have a class template.
814 if (const ClassTemplateSpecializationDecl *Spec =
815 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
816 TemplateArgs = &Spec->getTemplateArgs();
817 return Spec->getSpecializedTemplate();
818 }
819
Larisse Voufo39a1e502013-08-06 01:03:05 +0000820 // Check if we have a variable template.
821 if (const VarTemplateSpecializationDecl *Spec =
822 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
823 TemplateArgs = &Spec->getTemplateArgs();
824 return Spec->getSpecializedTemplate();
825 }
826
Craig Topper36250ad2014-05-12 05:36:57 +0000827 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000828}
829
Guy Benyei11169dd2012-12-18 14:30:41 +0000830void CXXNameMangler::mangleName(const NamedDecl *ND) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000831 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
832 // Variables should have implicit tags from its type.
833 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
834 if (VariableTypeAbiTags.empty()) {
835 // Simple case no variable type tags.
836 mangleNameWithAbiTags(VD, nullptr);
837 return;
838 }
839
840 // Mangle variable name to null stream to collect tags.
841 llvm::raw_null_ostream NullOutStream;
842 CXXNameMangler VariableNameMangler(*this, NullOutStream);
843 VariableNameMangler.disableDerivedAbiTags();
844 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
845
846 // Get tags from variable type that are not present in its name.
847 const AbiTagList &UsedAbiTags =
848 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
849 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
850 AdditionalAbiTags.erase(
851 std::set_difference(VariableTypeAbiTags.begin(),
852 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
853 UsedAbiTags.end(), AdditionalAbiTags.begin()),
854 AdditionalAbiTags.end());
855
856 // Output name with implicit tags.
857 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
858 } else {
859 mangleNameWithAbiTags(ND, nullptr);
860 }
861}
862
863void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
864 const AbiTagList *AdditionalAbiTags) {
Richard Smithdd8b5332017-09-04 05:37:53 +0000865 // <name> ::= [<module-name>] <nested-name>
866 // ::= [<module-name>] <unscoped-name>
867 // ::= [<module-name>] <unscoped-template-name> <template-args>
Guy Benyei11169dd2012-12-18 14:30:41 +0000868 // ::= <local-name>
869 //
870 const DeclContext *DC = getEffectiveDeclContext(ND);
871
872 // If this is an extern variable declared locally, the relevant DeclContext
873 // is that of the containing namespace, or the translation unit.
874 // FIXME: This is a hack; extern variables declared locally should have
875 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000876 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000877 while (!DC->isNamespace() && !DC->isTranslationUnit())
878 DC = getEffectiveParentContext(DC);
879 else if (GetLocalClassDecl(ND)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000880 mangleLocalName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000881 return;
882 }
883
884 DC = IgnoreLinkageSpecDecls(DC);
885
Richard Smithdd8b5332017-09-04 05:37:53 +0000886 if (isLocalContainerContext(DC)) {
887 mangleLocalName(ND, AdditionalAbiTags);
888 return;
889 }
890
891 // Do not mangle the owning module for an external linkage declaration.
892 // This enables backwards-compatibility with non-modular code, and is
893 // a valid choice since conflicts are not permitted by C++ Modules TS
894 // [basic.def.odr]/6.2.
895 if (!ND->hasExternalFormalLinkage())
896 if (Module *M = ND->getOwningModuleForLinkage())
897 mangleModuleName(M);
898
Guy Benyei11169dd2012-12-18 14:30:41 +0000899 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
900 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000901 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000902 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000903 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000904 mangleTemplateArgs(*TemplateArgs);
905 return;
906 }
907
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000908 mangleUnscopedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000909 return;
910 }
911
Richard Smithdd8b5332017-09-04 05:37:53 +0000912 mangleNestedName(ND, DC, AdditionalAbiTags);
913}
914
915void CXXNameMangler::mangleModuleName(const Module *M) {
916 // Implement the C++ Modules TS name mangling proposal; see
917 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
918 //
919 // <module-name> ::= W <unscoped-name>+ E
920 // ::= W <module-subst> <unscoped-name>* E
921 Out << 'W';
922 mangleModuleNamePrefix(M->Name);
923 Out << 'E';
924}
925
926void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
927 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
928 // ::= W <seq-id - 10> _ # otherwise
929 auto It = ModuleSubstitutions.find(Name);
930 if (It != ModuleSubstitutions.end()) {
931 if (It->second < 10)
932 Out << '_' << static_cast<char>('0' + It->second);
933 else
934 Out << 'W' << (It->second - 10) << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +0000935 return;
936 }
937
Richard Smithdd8b5332017-09-04 05:37:53 +0000938 // FIXME: Preserve hierarchy in module names rather than flattening
939 // them to strings; use Module*s as substitution keys.
940 auto Parts = Name.rsplit('.');
941 if (Parts.second.empty())
942 Parts.second = Parts.first;
943 else
944 mangleModuleNamePrefix(Parts.first);
945
946 Out << Parts.second.size() << Parts.second;
947 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
Guy Benyei11169dd2012-12-18 14:30:41 +0000948}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000949
950void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
951 const TemplateArgument *TemplateArgs,
952 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
954
955 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000956 mangleUnscopedTemplateName(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000957 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
958 } else {
959 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
960 }
961}
962
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000963void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
964 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000965 // <unscoped-name> ::= <unqualified-name>
966 // ::= St <unqualified-name> # ::std::
967
968 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
969 Out << "St";
970
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000971 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000972}
973
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000974void CXXNameMangler::mangleUnscopedTemplateName(
975 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000976 // <unscoped-template-name> ::= <unscoped-name>
977 // ::= <substitution>
978 if (mangleSubstitution(ND))
979 return;
980
981 // <template-template-param> ::= <template-param>
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000982 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
983 assert(!AdditionalAbiTags &&
984 "template template param cannot have abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +0000985 mangleTemplateParameter(TTP->getIndex());
David Majnemer6d2b60a2016-07-12 16:48:17 +0000986 } else if (isa<BuiltinTemplateDecl>(ND)) {
987 mangleUnscopedName(ND, AdditionalAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000988 } else {
989 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
990 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000991
Guy Benyei11169dd2012-12-18 14:30:41 +0000992 addSubstitution(ND);
993}
994
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000995void CXXNameMangler::mangleUnscopedTemplateName(
996 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000997 // <unscoped-template-name> ::= <unscoped-name>
998 // ::= <substitution>
999 if (TemplateDecl *TD = Template.getAsTemplateDecl())
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001000 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Fangrui Song6907ce22018-07-30 19:24:48 +00001001
Guy Benyei11169dd2012-12-18 14:30:41 +00001002 if (mangleSubstitution(Template))
1003 return;
1004
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001005 assert(!AdditionalAbiTags &&
1006 "dependent template name cannot have abi tags");
1007
Guy Benyei11169dd2012-12-18 14:30:41 +00001008 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1009 assert(Dependent && "Not a dependent template name?");
1010 if (const IdentifierInfo *Id = Dependent->getIdentifier())
1011 mangleSourceName(Id);
1012 else
1013 mangleOperatorName(Dependent->getOperator(), UnknownArity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001014
Guy Benyei11169dd2012-12-18 14:30:41 +00001015 addSubstitution(Template);
1016}
1017
1018void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1019 // ABI:
1020 // Floating-point literals are encoded using a fixed-length
1021 // lowercase hexadecimal string corresponding to the internal
1022 // representation (IEEE on Itanium), high-order bytes first,
1023 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1024 // on Itanium.
1025 // The 'without leading zeroes' thing seems to be an editorial
1026 // mistake; see the discussion on cxx-abi-dev beginning on
1027 // 2012-01-16.
1028
1029 // Our requirements here are just barely weird enough to justify
1030 // using a custom algorithm instead of post-processing APInt::toString().
1031
1032 llvm::APInt valueBits = f.bitcastToAPInt();
1033 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1034 assert(numCharacters != 0);
1035
1036 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +00001037 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +00001038
1039 // Fill the buffer left-to-right.
1040 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1041 // The bit-index of the next hex digit.
1042 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1043
1044 // Project out 4 bits starting at 'digitIndex'.
Craig Topperc396c532017-03-30 05:48:58 +00001045 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1046 hexDigit >>= (digitBitIndex % 64);
Guy Benyei11169dd2012-12-18 14:30:41 +00001047 hexDigit &= 0xF;
1048
1049 // Map that over to a lowercase hex digit.
1050 static const char charForHex[16] = {
1051 '0', '1', '2', '3', '4', '5', '6', '7',
1052 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1053 };
1054 buffer[stringIndex] = charForHex[hexDigit];
1055 }
1056
1057 Out.write(buffer.data(), numCharacters);
1058}
1059
1060void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1061 if (Value.isSigned() && Value.isNegative()) {
1062 Out << 'n';
1063 Value.abs().print(Out, /*signed*/ false);
1064 } else {
1065 Value.print(Out, /*signed*/ false);
1066 }
1067}
1068
1069void CXXNameMangler::mangleNumber(int64_t Number) {
1070 // <number> ::= [n] <non-negative decimal integer>
1071 if (Number < 0) {
1072 Out << 'n';
1073 Number = -Number;
1074 }
1075
1076 Out << Number;
1077}
1078
1079void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1080 // <call-offset> ::= h <nv-offset> _
1081 // ::= v <v-offset> _
1082 // <nv-offset> ::= <offset number> # non-virtual base override
1083 // <v-offset> ::= <offset number> _ <virtual offset number>
1084 // # virtual base override, with vcall offset
1085 if (!Virtual) {
1086 Out << 'h';
1087 mangleNumber(NonVirtual);
1088 Out << '_';
1089 return;
1090 }
1091
1092 Out << 'v';
1093 mangleNumber(NonVirtual);
1094 Out << '_';
1095 mangleNumber(Virtual);
1096 Out << '_';
1097}
1098
1099void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +00001100 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001101 if (!mangleSubstitution(QualType(TST, 0))) {
1102 mangleTemplatePrefix(TST->getTemplateName());
Fangrui Song6907ce22018-07-30 19:24:48 +00001103
Guy Benyei11169dd2012-12-18 14:30:41 +00001104 // FIXME: GCC does not appear to mangle the template arguments when
1105 // the template in question is a dependent template name. Should we
1106 // emulate that badness?
1107 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1108 addSubstitution(QualType(TST, 0));
1109 }
David Majnemera88b3592015-02-18 02:28:01 +00001110 } else if (const auto *DTST =
1111 type->getAs<DependentTemplateSpecializationType>()) {
1112 if (!mangleSubstitution(QualType(DTST, 0))) {
1113 TemplateName Template = getASTContext().getDependentTemplateName(
1114 DTST->getQualifier(), DTST->getIdentifier());
1115 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +00001116
David Majnemera88b3592015-02-18 02:28:01 +00001117 // FIXME: GCC does not appear to mangle the template arguments when
1118 // the template in question is a dependent template name. Should we
1119 // emulate that badness?
1120 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1121 addSubstitution(QualType(DTST, 0));
1122 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001123 } else {
1124 // We use the QualType mangle type variant here because it handles
1125 // substitutions.
1126 mangleType(type);
1127 }
1128}
1129
1130/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1131///
Guy Benyei11169dd2012-12-18 14:30:41 +00001132/// \param recursive - true if this is being called recursively,
1133/// i.e. if there is more prefix "to the right".
1134void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +00001135 bool recursive) {
1136
1137 // x, ::x
1138 // <unresolved-name> ::= [gs] <base-unresolved-name>
1139
1140 // T::x / decltype(p)::x
1141 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1142
1143 // T::N::x /decltype(p)::N::x
1144 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1145 // <base-unresolved-name>
1146
1147 // A::x, N::y, A<T>::z; "gs" means leading "::"
1148 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1149 // <base-unresolved-name>
1150
1151 switch (qualifier->getKind()) {
1152 case NestedNameSpecifier::Global:
1153 Out << "gs";
1154
1155 // We want an 'sr' unless this is the entire NNS.
1156 if (recursive)
1157 Out << "sr";
1158
1159 // We never want an 'E' here.
1160 return;
1161
Nikola Smiljanic67860242014-09-26 00:28:20 +00001162 case NestedNameSpecifier::Super:
1163 llvm_unreachable("Can't mangle __super specifier");
1164
Guy Benyei11169dd2012-12-18 14:30:41 +00001165 case NestedNameSpecifier::Namespace:
1166 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001167 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 /*recursive*/ true);
1169 else
1170 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001171 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
Guy Benyei11169dd2012-12-18 14:30:41 +00001172 break;
1173 case NestedNameSpecifier::NamespaceAlias:
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 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001179 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
Guy Benyei11169dd2012-12-18 14:30:41 +00001180 break;
1181
1182 case NestedNameSpecifier::TypeSpec:
1183 case NestedNameSpecifier::TypeSpecWithTemplate: {
1184 const Type *type = qualifier->getAsType();
1185
1186 // We only want to use an unresolved-type encoding if this is one of:
1187 // - a decltype
1188 // - a template type parameter
1189 // - a template template parameter with arguments
1190 // In all of these cases, we should have no prefix.
1191 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001192 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001193 /*recursive*/ true);
1194 } else {
1195 // Otherwise, all the cases want this.
1196 Out << "sr";
1197 }
1198
David Majnemerb8014dd2015-02-19 02:16:16 +00001199 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +00001200 return;
1201
Guy Benyei11169dd2012-12-18 14:30:41 +00001202 break;
1203 }
1204
1205 case NestedNameSpecifier::Identifier:
1206 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +00001207 if (qualifier->getPrefix())
1208 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001209 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +00001210 else
Guy Benyei11169dd2012-12-18 14:30:41 +00001211 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +00001212
1213 mangleSourceName(qualifier->getAsIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001214 // An Identifier has no type information, so we can't emit abi tags for it.
Guy Benyei11169dd2012-12-18 14:30:41 +00001215 break;
1216 }
1217
1218 // If this was the innermost part of the NNS, and we fell out to
1219 // here, append an 'E'.
1220 if (!recursive)
1221 Out << 'E';
1222}
1223
1224/// Mangle an unresolved-name, which is generally used for names which
1225/// weren't resolved to specific entities.
Richard Smithafecd832016-10-24 20:47:04 +00001226void CXXNameMangler::mangleUnresolvedName(
1227 NestedNameSpecifier *qualifier, DeclarationName name,
1228 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1229 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001230 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001231 switch (name.getNameKind()) {
1232 // <base-unresolved-name> ::= <simple-id>
1233 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +00001234 mangleSourceName(name.getAsIdentifierInfo());
1235 break;
1236 // <base-unresolved-name> ::= dn <destructor-name>
1237 case DeclarationName::CXXDestructorName:
1238 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +00001239 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +00001240 break;
1241 // <base-unresolved-name> ::= on <operator-name>
1242 case DeclarationName::CXXConversionFunctionName:
1243 case DeclarationName::CXXLiteralOperatorName:
1244 case DeclarationName::CXXOperatorName:
1245 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +00001246 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001247 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +00001248 case DeclarationName::CXXConstructorName:
1249 llvm_unreachable("Can't mangle a constructor name!");
1250 case DeclarationName::CXXUsingDirective:
1251 llvm_unreachable("Can't mangle a using directive name!");
Richard Smith35845152017-02-07 01:37:30 +00001252 case DeclarationName::CXXDeductionGuideName:
1253 llvm_unreachable("Can't mangle a deduction guide name!");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001254 case DeclarationName::ObjCMultiArgSelector:
1255 case DeclarationName::ObjCOneArgSelector:
1256 case DeclarationName::ObjCZeroArgSelector:
1257 llvm_unreachable("Can't mangle Objective-C selector names here!");
1258 }
Richard Smithafecd832016-10-24 20:47:04 +00001259
1260 // The <simple-id> and on <operator-name> productions end in an optional
1261 // <template-args>.
1262 if (TemplateArgs)
1263 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00001264}
1265
Guy Benyei11169dd2012-12-18 14:30:41 +00001266void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1267 DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001268 unsigned KnownArity,
1269 const AbiTagList *AdditionalAbiTags) {
David Majnemera88b3592015-02-18 02:28:01 +00001270 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +00001271 // <unqualified-name> ::= <operator-name>
1272 // ::= <ctor-dtor-name>
1273 // ::= <source-name>
1274 switch (Name.getNameKind()) {
1275 case DeclarationName::Identifier: {
Richard Smithbdb84f32016-07-22 23:36:59 +00001276 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1277
Richard Smithda383632016-08-15 01:33:41 +00001278 // We mangle decomposition declarations as the names of their bindings.
Richard Smithbdb84f32016-07-22 23:36:59 +00001279 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
Richard Smithda383632016-08-15 01:33:41 +00001280 // FIXME: Non-standard mangling for decomposition declarations:
1281 //
1282 // <unqualified-name> ::= DC <source-name>* E
1283 //
1284 // These can never be referenced across translation units, so we do
1285 // not need a cross-vendor mangling for anything other than demanglers.
1286 // Proposed on cxx-abi-dev on 2016-08-12
1287 Out << "DC";
1288 for (auto *BD : DD->bindings())
1289 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1290 Out << 'E';
1291 writeAbiTags(ND, AdditionalAbiTags);
1292 break;
Richard Smithbdb84f32016-07-22 23:36:59 +00001293 }
1294
1295 if (II) {
Richard Smithdd8b5332017-09-04 05:37:53 +00001296 // Match GCC's naming convention for internal linkage symbols, for
1297 // symbols that are not actually visible outside of this TU. GCC
1298 // distinguishes between internal and external linkage symbols in
1299 // its mangling, to support cases like this that were valid C++ prior
1300 // to DR426:
1301 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001302 // void test() { extern void foo(); }
1303 // static void foo();
Richard Smithdf963a32017-09-22 22:21:44 +00001304 //
1305 // Don't bother with the L marker for names in anonymous namespaces; the
1306 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1307 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1308 // implying internal linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001309 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Richard Smithdd8b5332017-09-04 05:37:53 +00001310 !ND->isExternallyVisible() &&
Richard Smithdf963a32017-09-22 22:21:44 +00001311 getEffectiveDeclContext(ND)->isFileContext() &&
1312 !ND->isInAnonymousNamespace())
Guy Benyei11169dd2012-12-18 14:30:41 +00001313 Out << 'L';
1314
Erich Keane757d3172016-11-02 18:29:35 +00001315 auto *FD = dyn_cast<FunctionDecl>(ND);
1316 bool IsRegCall = FD &&
1317 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1318 clang::CC_X86RegCall;
1319 if (IsRegCall)
1320 mangleRegCallName(II);
1321 else
1322 mangleSourceName(II);
1323
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001324 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001325 break;
1326 }
1327
1328 // Otherwise, an anonymous entity. We must have a declaration.
1329 assert(ND && "mangling empty name without declaration");
1330
1331 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1332 if (NS->isAnonymousNamespace()) {
1333 // This is how gcc mangles these names.
1334 Out << "12_GLOBAL__N_1";
1335 break;
1336 }
1337 }
1338
1339 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1340 // We must have an anonymous union or struct declaration.
George Burgess IV00f70bd2018-03-01 05:43:23 +00001341 const RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001342
Guy Benyei11169dd2012-12-18 14:30:41 +00001343 // Itanium C++ ABI 5.1.2:
1344 //
1345 // For the purposes of mangling, the name of an anonymous union is
1346 // considered to be the name of the first named data member found by a
1347 // pre-order, depth-first, declaration-order walk of the data members of
1348 // the anonymous union. If there is no such data member (i.e., if all of
1349 // the data members in the union are unnamed), then there is no way for
1350 // a program to refer to the anonymous union, and there is therefore no
1351 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001352 assert(RD->isAnonymousStructOrUnion()
1353 && "Expected anonymous struct or union!");
1354 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +00001355
1356 // It's actually possible for various reasons for us to get here
1357 // with an empty anonymous struct / union. Fortunately, it
1358 // doesn't really matter what name we generate.
1359 if (!FD) break;
1360 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001361
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 mangleSourceName(FD->getIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001363 // Not emitting abi tags: internal name anyway.
Guy Benyei11169dd2012-12-18 14:30:41 +00001364 break;
1365 }
John McCall924046f2013-04-10 06:08:21 +00001366
1367 // Class extensions have no name as a category, and it's possible
1368 // for them to be the semantic parent of certain declarations
1369 // (primarily, tag decls defined within declarations). Such
1370 // declarations will always have internal linkage, so the name
1371 // doesn't really matter, but we shouldn't crash on them. For
1372 // safety, just handle all ObjC containers here.
1373 if (isa<ObjCContainerDecl>(ND))
1374 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001375
Guy Benyei11169dd2012-12-18 14:30:41 +00001376 // We must have an anonymous struct.
1377 const TagDecl *TD = cast<TagDecl>(ND);
1378 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1379 assert(TD->getDeclContext() == D->getDeclContext() &&
1380 "Typedef should not be in another decl context!");
1381 assert(D->getDeclName().getAsIdentifierInfo() &&
1382 "Typedef was not named!");
1383 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001384 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1385 // Explicit abi tags are still possible; take from underlying type, not
1386 // from typedef.
1387 writeAbiTags(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001388 break;
1389 }
1390
1391 // <unnamed-type-name> ::= <closure-type-name>
Fangrui Song6907ce22018-07-30 19:24:48 +00001392 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001393 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1394 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1395 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1396 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001397 assert(!AdditionalAbiTags &&
1398 "Lambda type cannot have additional abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 mangleLambda(Record);
1400 break;
1401 }
1402 }
1403
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001404 if (TD->isExternallyVisible()) {
1405 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001406 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001407 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001408 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001409 Out << '_';
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001410 writeAbiTags(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001411 break;
1412 }
1413
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001414 // Get a unique id for the anonymous struct. If it is not a real output
1415 // ID doesn't matter so use fake one.
1416 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001417
1418 // Mangle it as a source name in the form
1419 // [n] $_<id>
1420 // where n is the length of the string.
1421 SmallString<8> Str;
1422 Str += "$_";
1423 Str += llvm::utostr(AnonStructId);
1424
1425 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001426 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001427 break;
1428 }
1429
1430 case DeclarationName::ObjCZeroArgSelector:
1431 case DeclarationName::ObjCOneArgSelector:
1432 case DeclarationName::ObjCMultiArgSelector:
1433 llvm_unreachable("Can't mangle Objective-C selector names here!");
1434
Richard Smith5179eb72016-06-28 19:03:57 +00001435 case DeclarationName::CXXConstructorName: {
1436 const CXXRecordDecl *InheritedFrom = nullptr;
1437 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1438 if (auto Inherited =
1439 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1440 InheritedFrom = Inherited.getConstructor()->getParent();
1441 InheritedTemplateArgs =
1442 Inherited.getConstructor()->getTemplateSpecializationArgs();
1443 }
1444
Guy Benyei11169dd2012-12-18 14:30:41 +00001445 if (ND == Structor)
1446 // If the named decl is the C++ constructor we're mangling, use the type
1447 // we were given.
Richard Smith5179eb72016-06-28 19:03:57 +00001448 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00001449 else
1450 // Otherwise, use the complete constructor name. This is relevant if a
1451 // class with a constructor is declared within a constructor.
Richard Smith5179eb72016-06-28 19:03:57 +00001452 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1453
1454 // FIXME: The template arguments are part of the enclosing prefix or
1455 // nested-name, but it's more convenient to mangle them here.
1456 if (InheritedTemplateArgs)
1457 mangleTemplateArgs(*InheritedTemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001458
1459 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001460 break;
Richard Smith5179eb72016-06-28 19:03:57 +00001461 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001462
1463 case DeclarationName::CXXDestructorName:
1464 if (ND == Structor)
1465 // If the named decl is the C++ destructor we're mangling, use the type we
1466 // were given.
1467 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1468 else
1469 // Otherwise, use the complete destructor name. This is relevant if a
1470 // class with a destructor is declared within a destructor.
1471 mangleCXXDtorType(Dtor_Complete);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001472 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001473 break;
1474
David Majnemera88b3592015-02-18 02:28:01 +00001475 case DeclarationName::CXXOperatorName:
1476 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001477 Arity = cast<FunctionDecl>(ND)->getNumParams();
1478
David Majnemera88b3592015-02-18 02:28:01 +00001479 // If we have a member function, we need to include the 'this' pointer.
1480 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1481 if (!MD->isStatic())
1482 Arity++;
1483 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001484 LLVM_FALLTHROUGH;
David Majnemera88b3592015-02-18 02:28:01 +00001485 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001486 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001487 mangleOperatorName(Name, Arity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001488 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001489 break;
1490
Richard Smith35845152017-02-07 01:37:30 +00001491 case DeclarationName::CXXDeductionGuideName:
1492 llvm_unreachable("Can't mangle a deduction guide name!");
1493
Guy Benyei11169dd2012-12-18 14:30:41 +00001494 case DeclarationName::CXXUsingDirective:
1495 llvm_unreachable("Can't mangle a using directive name!");
1496 }
1497}
1498
Erich Keane757d3172016-11-02 18:29:35 +00001499void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1500 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1501 // <number> ::= [n] <non-negative decimal integer>
1502 // <identifier> ::= <unqualified source code identifier>
1503 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1504 << II->getName();
1505}
1506
Guy Benyei11169dd2012-12-18 14:30:41 +00001507void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1508 // <source-name> ::= <positive length number> <identifier>
1509 // <number> ::= [n] <non-negative decimal integer>
1510 // <identifier> ::= <unqualified source code identifier>
1511 Out << II->getLength() << II->getName();
1512}
1513
1514void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1515 const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001516 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 bool NoFunction) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001518 // <nested-name>
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
Fangrui Song6907ce22018-07-30 19:24:48 +00001520 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
Guy Benyei11169dd2012-12-18 14:30:41 +00001521 // <template-args> E
1522
1523 Out << 'N';
1524 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001525 Qualifiers MethodQuals =
Roger Ferrer Ibanezcb895132017-04-19 12:23:28 +00001526 Qualifiers::fromCVRUMask(Method->getTypeQualifiers());
David Majnemer42350df2013-11-03 23:51:28 +00001527 // We do not consider restrict a distinguishing attribute for overloading
1528 // purposes so we must not mangle it.
1529 MethodQuals.removeRestrict();
1530 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 mangleRefQualifier(Method->getRefQualifier());
1532 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001533
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001535 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001536 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001537 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001538 mangleTemplateArgs(*TemplateArgs);
1539 }
1540 else {
1541 manglePrefix(DC, NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001542 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001543 }
1544
1545 Out << 'E';
1546}
1547void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1548 const TemplateArgument *TemplateArgs,
1549 unsigned NumTemplateArgs) {
1550 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1551
1552 Out << 'N';
1553
1554 mangleTemplatePrefix(TD);
1555 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1556
1557 Out << 'E';
1558}
1559
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001560void CXXNameMangler::mangleLocalName(const Decl *D,
1561 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001562 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1563 // := Z <function encoding> E s [<discriminator>]
Fangrui Song6907ce22018-07-30 19:24:48 +00001564 // <local-name> := Z <function encoding> E d [ <parameter number> ]
Guy Benyei11169dd2012-12-18 14:30:41 +00001565 // _ <entity name>
1566 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001567 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001568 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001569 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001570
1571 Out << 'Z';
1572
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001573 {
1574 AbiTagState LocalAbiTags(AbiTags);
1575
1576 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1577 mangleObjCMethodName(MD);
1578 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1579 mangleBlockForPrefix(BD);
1580 else
1581 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1582
1583 // Implicit ABI tags (from namespace) are not available in the following
1584 // entity; reset to actually emitted tags, which are available.
1585 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1586 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001587
Eli Friedman92821742013-07-02 02:01:18 +00001588 Out << 'E';
1589
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001590 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1591 // be a bug that is fixed in trunk.
1592
Eli Friedman92821742013-07-02 02:01:18 +00001593 if (RD) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001594 // The parameter number is omitted for the last parameter, 0 for the
1595 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1596 // <entity name> will of course contain a <closure-type-name>: Its
Guy Benyei11169dd2012-12-18 14:30:41 +00001597 // numbering will be local to the particular argument in which it appears
1598 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001599 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithcb2ba5a2016-07-18 22:37:35 +00001600 if (CXXRD && CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001602 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001603 if (const FunctionDecl *Func
1604 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1605 Out << 'd';
1606 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1607 if (Num > 1)
1608 mangleNumber(Num - 2);
1609 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001610 }
1611 }
1612 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001613
Guy Benyei11169dd2012-12-18 14:30:41 +00001614 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001615 // equality ok because RD derived from ND above
1616 if (D == RD) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001617 mangleUnqualifiedName(RD, AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +00001618 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1619 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001620 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman95f50122013-07-02 17:52:28 +00001621 mangleUnqualifiedBlock(BD);
1622 } else {
1623 const NamedDecl *ND = cast<NamedDecl>(D);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001624 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1625 true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001626 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001627 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1628 // Mangle a block in a default parameter; see above explanation for
1629 // lambdas.
1630 if (const ParmVarDecl *Parm
1631 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1632 if (const FunctionDecl *Func
1633 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1634 Out << 'd';
1635 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1636 if (Num > 1)
1637 mangleNumber(Num - 2);
1638 Out << '_';
1639 }
1640 }
1641
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001642 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman0cd23352013-07-10 01:33:19 +00001643 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001644 } else {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001645 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001646 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001647
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001648 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1649 unsigned disc;
1650 if (Context.getNextDiscriminator(ND, disc)) {
1651 if (disc < 10)
1652 Out << '_' << disc;
1653 else
1654 Out << "__" << disc << '_';
1655 }
1656 }
Eli Friedman95f50122013-07-02 17:52:28 +00001657}
1658
1659void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1660 if (GetLocalClassDecl(Block)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001661 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001662 return;
1663 }
1664 const DeclContext *DC = getEffectiveDeclContext(Block);
1665 if (isLocalContainerContext(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001666 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001667 return;
1668 }
1669 manglePrefix(getEffectiveDeclContext(Block));
1670 mangleUnqualifiedBlock(Block);
1671}
1672
1673void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1674 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1675 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1676 Context->getDeclContext()->isRecord()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001677 const auto *ND = cast<NamedDecl>(Context);
1678 if (ND->getIdentifier()) {
1679 mangleSourceNameWithAbiTags(ND);
1680 Out << 'M';
Eli Friedman95f50122013-07-02 17:52:28 +00001681 }
1682 }
1683 }
1684
1685 // If we have a block mangling number, use it.
1686 unsigned Number = Block->getBlockManglingNumber();
1687 // Otherwise, just make up a number. It doesn't matter what it is because
1688 // the symbol in question isn't externally visible.
1689 if (!Number)
1690 Number = Context.getBlockId(Block, false);
Richard Smith48b35d92017-09-07 05:41:24 +00001691 else {
1692 // Stored mangling numbers are 1-based.
1693 --Number;
1694 }
Eli Friedman95f50122013-07-02 17:52:28 +00001695 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001696 if (Number > 0)
1697 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001698 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001699}
1700
1701void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001702 // If the context of a closure type is an initializer for a class member
1703 // (static or nonstatic), it is encoded in a qualified name with a final
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 // <prefix> of the form:
1705 //
1706 // <data-member-prefix> := <member source-name> M
1707 //
1708 // Technically, the data-member-prefix is part of the <prefix>. However,
1709 // since a closure type will always be mangled with a prefix, it's easier
1710 // to emit that last part of the prefix here.
1711 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1712 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
Richard Smithc95d2c52017-09-22 04:25:05 +00001713 !isa<ParmVarDecl>(Context)) {
1714 // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1715 // reasonable mangling here.
Guy Benyei11169dd2012-12-18 14:30:41 +00001716 if (const IdentifierInfo *Name
1717 = cast<NamedDecl>(Context)->getIdentifier()) {
1718 mangleSourceName(Name);
Richard Smithc95d2c52017-09-22 04:25:05 +00001719 const TemplateArgumentList *TemplateArgs = nullptr;
Simon Pilgrimb2eda762017-09-22 16:26:17 +00001720 if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
Richard Smithc95d2c52017-09-22 04:25:05 +00001721 mangleTemplateArgs(*TemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001722 Out << 'M';
Guy Benyei11169dd2012-12-18 14:30:41 +00001723 }
1724 }
1725 }
1726
1727 Out << "Ul";
1728 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1729 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001730 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1731 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001732 Out << "E";
Fangrui Song6907ce22018-07-30 19:24:48 +00001733
1734 // The number is omitted for the first closure type with a given
1735 // <lambda-sig> in a given context; it is n-2 for the nth closure type
Guy Benyei11169dd2012-12-18 14:30:41 +00001736 // (in lexical order) with that same <lambda-sig> and context.
1737 //
1738 // The AST keeps track of the number for us.
1739 unsigned Number = Lambda->getLambdaManglingNumber();
1740 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1741 if (Number > 1)
1742 mangleNumber(Number - 2);
Fangrui Song6907ce22018-07-30 19:24:48 +00001743 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001744}
1745
1746void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1747 switch (qualifier->getKind()) {
1748 case NestedNameSpecifier::Global:
1749 // nothing
1750 return;
1751
Nikola Smiljanic67860242014-09-26 00:28:20 +00001752 case NestedNameSpecifier::Super:
1753 llvm_unreachable("Can't mangle __super specifier");
1754
Guy Benyei11169dd2012-12-18 14:30:41 +00001755 case NestedNameSpecifier::Namespace:
1756 mangleName(qualifier->getAsNamespace());
1757 return;
1758
1759 case NestedNameSpecifier::NamespaceAlias:
1760 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1761 return;
1762
1763 case NestedNameSpecifier::TypeSpec:
1764 case NestedNameSpecifier::TypeSpecWithTemplate:
1765 manglePrefix(QualType(qualifier->getAsType(), 0));
1766 return;
1767
1768 case NestedNameSpecifier::Identifier:
1769 // Member expressions can have these without prefixes, but that
1770 // should end up in mangleUnresolvedPrefix instead.
1771 assert(qualifier->getPrefix());
1772 manglePrefix(qualifier->getPrefix());
1773
1774 mangleSourceName(qualifier->getAsIdentifier());
1775 return;
1776 }
1777
1778 llvm_unreachable("unexpected nested name specifier");
1779}
1780
1781void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1782 // <prefix> ::= <prefix> <unqualified-name>
1783 // ::= <template-prefix> <template-args>
1784 // ::= <template-param>
1785 // ::= # empty
1786 // ::= <substitution>
1787
1788 DC = IgnoreLinkageSpecDecls(DC);
1789
1790 if (DC->isTranslationUnit())
1791 return;
1792
Eli Friedman95f50122013-07-02 17:52:28 +00001793 if (NoFunction && isLocalContainerContext(DC))
1794 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001795
Eli Friedman95f50122013-07-02 17:52:28 +00001796 assert(!isLocalContainerContext(DC));
1797
Fangrui Song6907ce22018-07-30 19:24:48 +00001798 const NamedDecl *ND = cast<NamedDecl>(DC);
Guy Benyei11169dd2012-12-18 14:30:41 +00001799 if (mangleSubstitution(ND))
1800 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001801
Guy Benyei11169dd2012-12-18 14:30:41 +00001802 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001803 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001804 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1805 mangleTemplatePrefix(TD);
1806 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001807 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001809 mangleUnqualifiedName(ND, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 }
1811
1812 addSubstitution(ND);
1813}
1814
1815void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1816 // <template-prefix> ::= <prefix> <template unqualified-name>
1817 // ::= <template-param>
1818 // ::= <substitution>
1819 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1820 return mangleTemplatePrefix(TD);
1821
1822 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1823 manglePrefix(Qualified->getQualifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001824
Guy Benyei11169dd2012-12-18 14:30:41 +00001825 if (OverloadedTemplateStorage *Overloaded
1826 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001827 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001828 UnknownArity, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001829 return;
1830 }
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001831
Guy Benyei11169dd2012-12-18 14:30:41 +00001832 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1833 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001834 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1835 manglePrefix(Qualifier);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001836 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001837}
1838
Eli Friedman86af13f02013-07-05 18:41:30 +00001839void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1840 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001841 // <template-prefix> ::= <prefix> <template unqualified-name>
1842 // ::= <template-param>
1843 // ::= <substitution>
1844 // <template-template-param> ::= <template-param>
1845 // <substitution>
1846
1847 if (mangleSubstitution(ND))
1848 return;
1849
1850 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001851 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001852 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001853 } else {
1854 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
David Majnemer6d2b60a2016-07-12 16:48:17 +00001855 if (isa<BuiltinTemplateDecl>(ND))
1856 mangleUnqualifiedName(ND, nullptr);
1857 else
1858 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001859 }
1860
Guy Benyei11169dd2012-12-18 14:30:41 +00001861 addSubstitution(ND);
1862}
1863
1864/// Mangles a template name under the production <type>. Required for
1865/// template template arguments.
1866/// <type> ::= <class-enum-type>
1867/// ::= <template-param>
1868/// ::= <substitution>
1869void CXXNameMangler::mangleType(TemplateName TN) {
1870 if (mangleSubstitution(TN))
1871 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001872
1873 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001874
1875 switch (TN.getKind()) {
1876 case TemplateName::QualifiedTemplate:
1877 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1878 goto HaveDecl;
1879
1880 case TemplateName::Template:
1881 TD = TN.getAsTemplateDecl();
1882 goto HaveDecl;
1883
1884 HaveDecl:
1885 if (isa<TemplateTemplateParmDecl>(TD))
1886 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1887 else
1888 mangleName(TD);
1889 break;
1890
1891 case TemplateName::OverloadedTemplate:
1892 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1893
1894 case TemplateName::DependentTemplate: {
1895 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1896 assert(Dependent->isIdentifier());
1897
1898 // <class-enum-type> ::= <name>
1899 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001900 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001901 mangleSourceName(Dependent->getIdentifier());
1902 break;
1903 }
1904
1905 case TemplateName::SubstTemplateTemplateParm: {
1906 // Substituted template parameters are mangled as the substituted
1907 // template. This will check for the substitution twice, which is
1908 // fine, but we have to return early so that we don't try to *add*
1909 // the substitution twice.
1910 SubstTemplateTemplateParmStorage *subst
1911 = TN.getAsSubstTemplateTemplateParm();
1912 mangleType(subst->getReplacement());
1913 return;
1914 }
1915
1916 case TemplateName::SubstTemplateTemplateParmPack: {
1917 // FIXME: not clear how to mangle this!
1918 // template <template <class> class T...> class A {
1919 // template <template <class> class U...> void foo(B<T,U> x...);
1920 // };
1921 Out << "_SUBSTPACK_";
1922 break;
1923 }
1924 }
1925
1926 addSubstitution(TN);
1927}
1928
David Majnemerb8014dd2015-02-19 02:16:16 +00001929bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1930 StringRef Prefix) {
1931 // Only certain other types are valid as prefixes; enumerate them.
1932 switch (Ty->getTypeClass()) {
1933 case Type::Builtin:
1934 case Type::Complex:
1935 case Type::Adjusted:
1936 case Type::Decayed:
1937 case Type::Pointer:
1938 case Type::BlockPointer:
1939 case Type::LValueReference:
1940 case Type::RValueReference:
1941 case Type::MemberPointer:
1942 case Type::ConstantArray:
1943 case Type::IncompleteArray:
1944 case Type::VariableArray:
1945 case Type::DependentSizedArray:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001946 case Type::DependentAddressSpace:
Erich Keanef702b022018-07-13 19:46:04 +00001947 case Type::DependentVector:
David Majnemerb8014dd2015-02-19 02:16:16 +00001948 case Type::DependentSizedExtVector:
1949 case Type::Vector:
1950 case Type::ExtVector:
1951 case Type::FunctionProto:
1952 case Type::FunctionNoProto:
1953 case Type::Paren:
1954 case Type::Attributed:
1955 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001956 case Type::DeducedTemplateSpecialization:
David Majnemerb8014dd2015-02-19 02:16:16 +00001957 case Type::PackExpansion:
1958 case Type::ObjCObject:
1959 case Type::ObjCInterface:
1960 case Type::ObjCObjectPointer:
Manman Rene6be26c2016-09-13 17:25:08 +00001961 case Type::ObjCTypeParam:
David Majnemerb8014dd2015-02-19 02:16:16 +00001962 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001963 case Type::Pipe:
David Majnemerb8014dd2015-02-19 02:16:16 +00001964 llvm_unreachable("type is illegal as a nested name specifier");
1965
1966 case Type::SubstTemplateTypeParmPack:
1967 // FIXME: not clear how to mangle this!
1968 // template <class T...> class A {
1969 // template <class U...> void foo(decltype(T::foo(U())) x...);
1970 // };
1971 Out << "_SUBSTPACK_";
1972 break;
1973
1974 // <unresolved-type> ::= <template-param>
1975 // ::= <decltype>
1976 // ::= <template-template-param> <template-args>
1977 // (this last is not official yet)
1978 case Type::TypeOfExpr:
1979 case Type::TypeOf:
1980 case Type::Decltype:
1981 case Type::TemplateTypeParm:
1982 case Type::UnaryTransform:
1983 case Type::SubstTemplateTypeParm:
1984 unresolvedType:
1985 // Some callers want a prefix before the mangled type.
1986 Out << Prefix;
1987
1988 // This seems to do everything we want. It's not really
1989 // sanctioned for a substituted template parameter, though.
1990 mangleType(Ty);
1991
1992 // We never want to print 'E' directly after an unresolved-type,
1993 // so we return directly.
1994 return true;
1995
1996 case Type::Typedef:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001997 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001998 break;
1999
2000 case Type::UnresolvedUsing:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002001 mangleSourceNameWithAbiTags(
2002 cast<UnresolvedUsingType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002003 break;
2004
2005 case Type::Enum:
2006 case Type::Record:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002007 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002008 break;
2009
2010 case Type::TemplateSpecialization: {
2011 const TemplateSpecializationType *TST =
2012 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00002013 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00002014 switch (TN.getKind()) {
2015 case TemplateName::Template:
2016 case TemplateName::QualifiedTemplate: {
2017 TemplateDecl *TD = TN.getAsTemplateDecl();
2018
2019 // If the base is a template template parameter, this is an
2020 // unresolved type.
2021 assert(TD && "no template for template specialization type");
2022 if (isa<TemplateTemplateParmDecl>(TD))
2023 goto unresolvedType;
2024
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002025 mangleSourceNameWithAbiTags(TD);
David Majnemerb8014dd2015-02-19 02:16:16 +00002026 break;
David Majnemera88b3592015-02-18 02:28:01 +00002027 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002028
2029 case TemplateName::OverloadedTemplate:
2030 case TemplateName::DependentTemplate:
2031 llvm_unreachable("invalid base for a template specialization type");
2032
2033 case TemplateName::SubstTemplateTemplateParm: {
2034 SubstTemplateTemplateParmStorage *subst =
2035 TN.getAsSubstTemplateTemplateParm();
2036 mangleExistingSubstitution(subst->getReplacement());
2037 break;
2038 }
2039
2040 case TemplateName::SubstTemplateTemplateParmPack: {
2041 // FIXME: not clear how to mangle this!
2042 // template <template <class U> class T...> class A {
2043 // template <class U...> void foo(decltype(T<U>::foo) x...);
2044 // };
2045 Out << "_SUBSTPACK_";
2046 break;
2047 }
2048 }
2049
David Majnemera88b3592015-02-18 02:28:01 +00002050 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00002051 break;
David Majnemera88b3592015-02-18 02:28:01 +00002052 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002053
2054 case Type::InjectedClassName:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002055 mangleSourceNameWithAbiTags(
2056 cast<InjectedClassNameType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002057 break;
2058
2059 case Type::DependentName:
2060 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2061 break;
2062
2063 case Type::DependentTemplateSpecialization: {
2064 const DependentTemplateSpecializationType *DTST =
2065 cast<DependentTemplateSpecializationType>(Ty);
2066 mangleSourceName(DTST->getIdentifier());
2067 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2068 break;
2069 }
2070
2071 case Type::Elaborated:
2072 return mangleUnresolvedTypeOrSimpleId(
2073 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2074 }
2075
2076 return false;
David Majnemera88b3592015-02-18 02:28:01 +00002077}
2078
2079void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2080 switch (Name.getNameKind()) {
2081 case DeclarationName::CXXConstructorName:
2082 case DeclarationName::CXXDestructorName:
Richard Smith35845152017-02-07 01:37:30 +00002083 case DeclarationName::CXXDeductionGuideName:
David Majnemera88b3592015-02-18 02:28:01 +00002084 case DeclarationName::CXXUsingDirective:
2085 case DeclarationName::Identifier:
2086 case DeclarationName::ObjCMultiArgSelector:
2087 case DeclarationName::ObjCOneArgSelector:
2088 case DeclarationName::ObjCZeroArgSelector:
2089 llvm_unreachable("Not an operator name");
2090
2091 case DeclarationName::CXXConversionFunctionName:
2092 // <operator-name> ::= cv <type> # (cast)
2093 Out << "cv";
2094 mangleType(Name.getCXXNameType());
2095 break;
2096
2097 case DeclarationName::CXXLiteralOperatorName:
2098 Out << "li";
2099 mangleSourceName(Name.getCXXLiteralIdentifier());
2100 return;
2101
2102 case DeclarationName::CXXOperatorName:
2103 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2104 break;
2105 }
2106}
2107
Guy Benyei11169dd2012-12-18 14:30:41 +00002108void
2109CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2110 switch (OO) {
2111 // <operator-name> ::= nw # new
2112 case OO_New: Out << "nw"; break;
2113 // ::= na # new[]
2114 case OO_Array_New: Out << "na"; break;
2115 // ::= dl # delete
2116 case OO_Delete: Out << "dl"; break;
2117 // ::= da # delete[]
2118 case OO_Array_Delete: Out << "da"; break;
2119 // ::= ps # + (unary)
2120 // ::= pl # + (binary or unknown)
2121 case OO_Plus:
2122 Out << (Arity == 1? "ps" : "pl"); break;
2123 // ::= ng # - (unary)
2124 // ::= mi # - (binary or unknown)
2125 case OO_Minus:
2126 Out << (Arity == 1? "ng" : "mi"); break;
2127 // ::= ad # & (unary)
2128 // ::= an # & (binary or unknown)
2129 case OO_Amp:
2130 Out << (Arity == 1? "ad" : "an"); break;
2131 // ::= de # * (unary)
2132 // ::= ml # * (binary or unknown)
2133 case OO_Star:
2134 // Use binary when unknown.
2135 Out << (Arity == 1? "de" : "ml"); break;
2136 // ::= co # ~
2137 case OO_Tilde: Out << "co"; break;
2138 // ::= dv # /
2139 case OO_Slash: Out << "dv"; break;
2140 // ::= rm # %
2141 case OO_Percent: Out << "rm"; break;
2142 // ::= or # |
2143 case OO_Pipe: Out << "or"; break;
2144 // ::= eo # ^
2145 case OO_Caret: Out << "eo"; break;
2146 // ::= aS # =
2147 case OO_Equal: Out << "aS"; break;
2148 // ::= pL # +=
2149 case OO_PlusEqual: Out << "pL"; break;
2150 // ::= mI # -=
2151 case OO_MinusEqual: Out << "mI"; break;
2152 // ::= mL # *=
2153 case OO_StarEqual: Out << "mL"; break;
2154 // ::= dV # /=
2155 case OO_SlashEqual: Out << "dV"; break;
2156 // ::= rM # %=
2157 case OO_PercentEqual: Out << "rM"; break;
2158 // ::= aN # &=
2159 case OO_AmpEqual: Out << "aN"; break;
2160 // ::= oR # |=
2161 case OO_PipeEqual: Out << "oR"; break;
2162 // ::= eO # ^=
2163 case OO_CaretEqual: Out << "eO"; break;
2164 // ::= ls # <<
2165 case OO_LessLess: Out << "ls"; break;
2166 // ::= rs # >>
2167 case OO_GreaterGreater: Out << "rs"; break;
2168 // ::= lS # <<=
2169 case OO_LessLessEqual: Out << "lS"; break;
2170 // ::= rS # >>=
2171 case OO_GreaterGreaterEqual: Out << "rS"; break;
2172 // ::= eq # ==
2173 case OO_EqualEqual: Out << "eq"; break;
2174 // ::= ne # !=
2175 case OO_ExclaimEqual: Out << "ne"; break;
2176 // ::= lt # <
2177 case OO_Less: Out << "lt"; break;
2178 // ::= gt # >
2179 case OO_Greater: Out << "gt"; break;
2180 // ::= le # <=
2181 case OO_LessEqual: Out << "le"; break;
2182 // ::= ge # >=
2183 case OO_GreaterEqual: Out << "ge"; break;
2184 // ::= nt # !
2185 case OO_Exclaim: Out << "nt"; break;
2186 // ::= aa # &&
2187 case OO_AmpAmp: Out << "aa"; break;
2188 // ::= oo # ||
2189 case OO_PipePipe: Out << "oo"; break;
2190 // ::= pp # ++
2191 case OO_PlusPlus: Out << "pp"; break;
2192 // ::= mm # --
2193 case OO_MinusMinus: Out << "mm"; break;
2194 // ::= cm # ,
2195 case OO_Comma: Out << "cm"; break;
2196 // ::= pm # ->*
2197 case OO_ArrowStar: Out << "pm"; break;
2198 // ::= pt # ->
2199 case OO_Arrow: Out << "pt"; break;
2200 // ::= cl # ()
2201 case OO_Call: Out << "cl"; break;
2202 // ::= ix # []
2203 case OO_Subscript: Out << "ix"; break;
2204
2205 // ::= qu # ?
2206 // The conditional operator can't be overloaded, but we still handle it when
2207 // mangling expressions.
2208 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00002209 // Proposal on cxx-abi-dev, 2015-10-21.
2210 // ::= aw # co_await
2211 case OO_Coawait: Out << "aw"; break;
Richard Smithd30b23d2017-12-01 02:13:10 +00002212 // Proposed in cxx-abi github issue 43.
2213 // ::= ss # <=>
2214 case OO_Spaceship: Out << "ss"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002215
2216 case OO_None:
2217 case NUM_OVERLOADED_OPERATORS:
2218 llvm_unreachable("Not an overloaded operator");
2219 }
2220}
2221
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002222void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002223 // Vendor qualifiers come first and if they are order-insensitive they must
2224 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
Guy Benyei11169dd2012-12-18 14:30:41 +00002225
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002226 // <type> ::= U <addrspace-expr>
2227 if (DAST) {
2228 Out << "U2ASI";
2229 mangleExpression(DAST->getAddrSpaceExpr());
2230 Out << "E";
2231 }
2232
John McCall07daf722016-03-01 22:18:03 +00002233 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00002234 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00002235 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00002236 //
David Tweed31d09b02013-09-13 12:04:22 +00002237 // <type> ::= U <target-addrspace>
2238 // <type> ::= U <OpenCL-addrspace>
2239 // <type> ::= U <CUDA-addrspace>
2240
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 SmallString<64> ASString;
Alexander Richardson6d989432017-10-15 18:48:14 +00002242 LangAS AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00002243
2244 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2245 // <target-addrspace> ::= "AS" <address-space-number>
2246 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Yaxun Liub7318e02017-10-13 03:37:48 +00002247 if (TargetAS != 0)
2248 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00002249 } else {
2250 switch (AS) {
2251 default: llvm_unreachable("Not a language specific address space");
Yaxun Liub7318e02017-10-13 03:37:48 +00002252 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2253 // "private"| "generic" ]
David Tweed31d09b02013-09-13 12:04:22 +00002254 case LangAS::opencl_global: ASString = "CLglobal"; break;
2255 case LangAS::opencl_local: ASString = "CLlocal"; break;
2256 case LangAS::opencl_constant: ASString = "CLconstant"; break;
Yaxun Liub7318e02017-10-13 03:37:48 +00002257 case LangAS::opencl_private: ASString = "CLprivate"; break;
Anastasia Stulova81a25e352017-03-10 15:23:07 +00002258 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
David Tweed31d09b02013-09-13 12:04:22 +00002259 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2260 case LangAS::cuda_device: ASString = "CUdevice"; break;
2261 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2262 case LangAS::cuda_shared: ASString = "CUshared"; break;
2263 }
2264 }
Yaxun Liub7318e02017-10-13 03:37:48 +00002265 if (!ASString.empty())
2266 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00002267 }
John McCall07daf722016-03-01 22:18:03 +00002268
2269 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00002270 // Objective-C ARC Extension:
2271 //
2272 // <type> ::= U "__strong"
2273 // <type> ::= U "__weak"
2274 // <type> ::= U "__autoreleasing"
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002275 //
2276 // Note: we emit __weak first to preserve the order as
2277 // required by the Itanium ABI.
2278 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2279 mangleVendorQualifier("__weak");
2280
2281 // __unaligned (from -fms-extensions)
2282 if (Quals.hasUnaligned())
2283 mangleVendorQualifier("__unaligned");
2284
2285 // Remaining ARC ownership qualifiers.
2286 switch (Quals.getObjCLifetime()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002287 case Qualifiers::OCL_None:
2288 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002289
Guy Benyei11169dd2012-12-18 14:30:41 +00002290 case Qualifiers::OCL_Weak:
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002291 // Do nothing as we already handled this case above.
Guy Benyei11169dd2012-12-18 14:30:41 +00002292 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002293
Guy Benyei11169dd2012-12-18 14:30:41 +00002294 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00002295 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00002296 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002297
Guy Benyei11169dd2012-12-18 14:30:41 +00002298 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00002299 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002301
Guy Benyei11169dd2012-12-18 14:30:41 +00002302 case Qualifiers::OCL_ExplicitNone:
2303 // The __unsafe_unretained qualifier is *not* mangled, so that
2304 // __unsafe_unretained types in ARC produce the same manglings as the
2305 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2306 // better ABI compatibility.
2307 //
2308 // It's safe to do this because unqualified 'id' won't show up
2309 // in any type signatures that need to be mangled.
2310 break;
2311 }
John McCall07daf722016-03-01 22:18:03 +00002312
2313 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2314 if (Quals.hasRestrict())
2315 Out << 'r';
2316 if (Quals.hasVolatile())
2317 Out << 'V';
2318 if (Quals.hasConst())
2319 Out << 'K';
2320}
2321
2322void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2323 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002324}
2325
2326void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2327 // <ref-qualifier> ::= R # lvalue reference
2328 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00002329 switch (RefQualifier) {
2330 case RQ_None:
2331 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002332
Guy Benyei11169dd2012-12-18 14:30:41 +00002333 case RQ_LValue:
2334 Out << 'R';
2335 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002336
Guy Benyei11169dd2012-12-18 14:30:41 +00002337 case RQ_RValue:
2338 Out << 'O';
2339 break;
2340 }
2341}
2342
2343void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2344 Context.mangleObjCMethodName(MD, Out);
2345}
2346
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002347static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2348 ASTContext &Ctx) {
David Majnemereea02ee2014-11-28 22:22:46 +00002349 if (Quals)
2350 return true;
2351 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2352 return true;
2353 if (Ty->isOpenCLSpecificType())
2354 return true;
2355 if (Ty->isBuiltinType())
2356 return false;
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002357 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2358 // substitution candidates.
2359 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2360 isa<AutoType>(Ty))
2361 return false;
David Majnemereea02ee2014-11-28 22:22:46 +00002362 return true;
2363}
2364
Guy Benyei11169dd2012-12-18 14:30:41 +00002365void CXXNameMangler::mangleType(QualType T) {
2366 // If our type is instantiation-dependent but not dependent, we mangle
Fangrui Song6907ce22018-07-30 19:24:48 +00002367 // it as it was written in the source, removing any top-level sugar.
Guy Benyei11169dd2012-12-18 14:30:41 +00002368 // Otherwise, use the canonical type.
2369 //
Fangrui Song6907ce22018-07-30 19:24:48 +00002370 // FIXME: This is an approximation of the instantiation-dependent name
Guy Benyei11169dd2012-12-18 14:30:41 +00002371 // mangling rules, since we should really be using the type as written and
2372 // augmented via semantic analysis (i.e., with implicit conversions and
Fangrui Song6907ce22018-07-30 19:24:48 +00002373 // default template arguments) for any instantiation-dependent type.
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 // Unfortunately, that requires several changes to our AST:
Fangrui Song6907ce22018-07-30 19:24:48 +00002375 // - Instantiation-dependent TemplateSpecializationTypes will need to be
Guy Benyei11169dd2012-12-18 14:30:41 +00002376 // uniqued, so that we can handle substitutions properly
2377 // - Default template arguments will need to be represented in the
2378 // TemplateSpecializationType, since they need to be mangled even though
2379 // they aren't written.
2380 // - Conversions on non-type template arguments need to be expressed, since
2381 // they can affect the mangling of sizeof/alignof.
Richard Smithfda59e52016-10-26 01:05:54 +00002382 //
2383 // FIXME: This is wrong when mapping to the canonical type for a dependent
2384 // type discards instantiation-dependent portions of the type, such as for:
2385 //
2386 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2387 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2388 //
2389 // It's also wrong in the opposite direction when instantiation-dependent,
2390 // canonically-equivalent types differ in some irrelevant portion of inner
2391 // type sugar. In such cases, we fail to form correct substitutions, eg:
2392 //
2393 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2394 //
2395 // We should instead canonicalize the non-instantiation-dependent parts,
2396 // regardless of whether the type as a whole is dependent or instantiation
2397 // dependent.
Guy Benyei11169dd2012-12-18 14:30:41 +00002398 if (!T->isInstantiationDependentType() || T->isDependentType())
2399 T = T.getCanonicalType();
2400 else {
2401 // Desugar any types that are purely sugar.
2402 do {
2403 // Don't desugar through template specialization types that aren't
2404 // type aliases. We need to mangle the template arguments as written.
Fangrui Song6907ce22018-07-30 19:24:48 +00002405 if (const TemplateSpecializationType *TST
Guy Benyei11169dd2012-12-18 14:30:41 +00002406 = dyn_cast<TemplateSpecializationType>(T))
2407 if (!TST->isTypeAlias())
2408 break;
2409
Fangrui Song6907ce22018-07-30 19:24:48 +00002410 QualType Desugared
Guy Benyei11169dd2012-12-18 14:30:41 +00002411 = T.getSingleStepDesugaredType(Context.getASTContext());
2412 if (Desugared == T)
2413 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002414
Guy Benyei11169dd2012-12-18 14:30:41 +00002415 T = Desugared;
2416 } while (true);
2417 }
2418 SplitQualType split = T.split();
2419 Qualifiers quals = split.Quals;
2420 const Type *ty = split.Ty;
2421
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002422 bool isSubstitutable =
2423 isTypeSubstitutable(quals, ty, Context.getASTContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002424 if (isSubstitutable && mangleSubstitution(T))
2425 return;
2426
2427 // If we're mangling a qualified array type, push the qualifiers to
2428 // the element type.
2429 if (quals && isa<ArrayType>(T)) {
2430 ty = Context.getASTContext().getAsArrayType(T);
2431 quals = Qualifiers();
2432
2433 // Note that we don't update T: we want to add the
2434 // substitution at the original type.
2435 }
2436
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002437 if (quals || ty->isDependentAddressSpaceType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002438 if (const DependentAddressSpaceType *DAST =
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002439 dyn_cast<DependentAddressSpaceType>(ty)) {
2440 SplitQualType splitDAST = DAST->getPointeeType().split();
2441 mangleQualifiers(splitDAST.Quals, DAST);
2442 mangleType(QualType(splitDAST.Ty, 0));
2443 } else {
2444 mangleQualifiers(quals);
2445
2446 // Recurse: even if the qualified type isn't yet substitutable,
2447 // the unqualified type might be.
2448 mangleType(QualType(ty, 0));
2449 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002450 } else {
2451 switch (ty->getTypeClass()) {
2452#define ABSTRACT_TYPE(CLASS, PARENT)
2453#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2454 case Type::CLASS: \
2455 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2456 return;
2457#define TYPE(CLASS, PARENT) \
2458 case Type::CLASS: \
2459 mangleType(static_cast<const CLASS##Type*>(ty)); \
2460 break;
2461#include "clang/AST/TypeNodes.def"
2462 }
2463 }
2464
2465 // Add the substitution.
2466 if (isSubstitutable)
2467 addSubstitution(T);
2468}
2469
2470void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2471 if (!mangleStandardSubstitution(ND))
2472 mangleName(ND);
2473}
2474
2475void CXXNameMangler::mangleType(const BuiltinType *T) {
2476 // <type> ::= <builtin-type>
2477 // <builtin-type> ::= v # void
2478 // ::= w # wchar_t
2479 // ::= b # bool
2480 // ::= c # char
2481 // ::= a # signed char
2482 // ::= h # unsigned char
2483 // ::= s # short
2484 // ::= t # unsigned short
2485 // ::= i # int
2486 // ::= j # unsigned int
2487 // ::= l # long
2488 // ::= m # unsigned long
2489 // ::= x # long long, __int64
2490 // ::= y # unsigned long long, __int64
2491 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002492 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002493 // ::= f # float
2494 // ::= d # double
2495 // ::= e # long double, __float80
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002496 // ::= g # __float128
Guy Benyei11169dd2012-12-18 14:30:41 +00002497 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2498 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2499 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2500 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002501 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
Guy Benyei11169dd2012-12-18 14:30:41 +00002502 // ::= Di # char32_t
2503 // ::= Ds # char16_t
2504 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2505 // ::= u <source-name> # vendor extended type
Alexey Bader954ba212016-04-08 13:40:33 +00002506 std::string type_name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002507 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002508 case BuiltinType::Void:
2509 Out << 'v';
2510 break;
2511 case BuiltinType::Bool:
2512 Out << 'b';
2513 break;
2514 case BuiltinType::Char_U:
2515 case BuiltinType::Char_S:
2516 Out << 'c';
2517 break;
2518 case BuiltinType::UChar:
2519 Out << 'h';
2520 break;
2521 case BuiltinType::UShort:
2522 Out << 't';
2523 break;
2524 case BuiltinType::UInt:
2525 Out << 'j';
2526 break;
2527 case BuiltinType::ULong:
2528 Out << 'm';
2529 break;
2530 case BuiltinType::ULongLong:
2531 Out << 'y';
2532 break;
2533 case BuiltinType::UInt128:
2534 Out << 'o';
2535 break;
2536 case BuiltinType::SChar:
2537 Out << 'a';
2538 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002539 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002540 case BuiltinType::WChar_U:
2541 Out << 'w';
2542 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00002543 case BuiltinType::Char8:
2544 Out << "Du";
2545 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002546 case BuiltinType::Char16:
2547 Out << "Ds";
2548 break;
2549 case BuiltinType::Char32:
2550 Out << "Di";
2551 break;
2552 case BuiltinType::Short:
2553 Out << 's';
2554 break;
2555 case BuiltinType::Int:
2556 Out << 'i';
2557 break;
2558 case BuiltinType::Long:
2559 Out << 'l';
2560 break;
2561 case BuiltinType::LongLong:
2562 Out << 'x';
2563 break;
2564 case BuiltinType::Int128:
2565 Out << 'n';
2566 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002567 case BuiltinType::Float16:
2568 Out << "DF16_";
2569 break;
Leonard Chanf921d852018-06-04 16:07:52 +00002570 case BuiltinType::ShortAccum:
2571 case BuiltinType::Accum:
2572 case BuiltinType::LongAccum:
2573 case BuiltinType::UShortAccum:
2574 case BuiltinType::UAccum:
2575 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002576 case BuiltinType::ShortFract:
2577 case BuiltinType::Fract:
2578 case BuiltinType::LongFract:
2579 case BuiltinType::UShortFract:
2580 case BuiltinType::UFract:
2581 case BuiltinType::ULongFract:
2582 case BuiltinType::SatShortAccum:
2583 case BuiltinType::SatAccum:
2584 case BuiltinType::SatLongAccum:
2585 case BuiltinType::SatUShortAccum:
2586 case BuiltinType::SatUAccum:
2587 case BuiltinType::SatULongAccum:
2588 case BuiltinType::SatShortFract:
2589 case BuiltinType::SatFract:
2590 case BuiltinType::SatLongFract:
2591 case BuiltinType::SatUShortFract:
2592 case BuiltinType::SatUFract:
2593 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00002594 llvm_unreachable("Fixed point types are disabled for c++");
Alexey Baderbdf7c842015-09-15 12:18:29 +00002595 case BuiltinType::Half:
2596 Out << "Dh";
2597 break;
2598 case BuiltinType::Float:
2599 Out << 'f';
2600 break;
2601 case BuiltinType::Double:
2602 Out << 'd';
2603 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002604 case BuiltinType::LongDouble:
2605 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2606 ? 'g'
2607 : 'e');
2608 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002609 case BuiltinType::Float128:
2610 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2611 Out << "U10__float128"; // Match the GCC mangling
2612 else
2613 Out << 'g';
2614 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002615 case BuiltinType::NullPtr:
2616 Out << "Dn";
2617 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002618
2619#define BUILTIN_TYPE(Id, SingletonId)
2620#define PLACEHOLDER_TYPE(Id, SingletonId) \
2621 case BuiltinType::Id:
2622#include "clang/AST/BuiltinTypes.def"
2623 case BuiltinType::Dependent:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002624 if (!NullOut)
2625 llvm_unreachable("mangling a placeholder type");
2626 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002627 case BuiltinType::ObjCId:
2628 Out << "11objc_object";
2629 break;
2630 case BuiltinType::ObjCClass:
2631 Out << "10objc_class";
2632 break;
2633 case BuiltinType::ObjCSel:
2634 Out << "13objc_selector";
2635 break;
Alexey Bader954ba212016-04-08 13:40:33 +00002636#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2637 case BuiltinType::Id: \
2638 type_name = "ocl_" #ImgType "_" #Suffix; \
2639 Out << type_name.size() << type_name; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00002640 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00002641#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00002642 case BuiltinType::OCLSampler:
2643 Out << "11ocl_sampler";
2644 break;
2645 case BuiltinType::OCLEvent:
2646 Out << "9ocl_event";
2647 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002648 case BuiltinType::OCLClkEvent:
2649 Out << "12ocl_clkevent";
2650 break;
2651 case BuiltinType::OCLQueue:
2652 Out << "9ocl_queue";
2653 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002654 case BuiltinType::OCLReserveID:
2655 Out << "13ocl_reserveid";
2656 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002657 }
2658}
2659
John McCall07daf722016-03-01 22:18:03 +00002660StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2661 switch (CC) {
2662 case CC_C:
2663 return "";
2664
2665 case CC_X86StdCall:
2666 case CC_X86FastCall:
2667 case CC_X86ThisCall:
2668 case CC_X86VectorCall:
2669 case CC_X86Pascal:
Martin Storsjo022e7822017-07-17 20:49:45 +00002670 case CC_Win64:
John McCall07daf722016-03-01 22:18:03 +00002671 case CC_X86_64SysV:
Erich Keane757d3172016-11-02 18:29:35 +00002672 case CC_X86RegCall:
John McCall07daf722016-03-01 22:18:03 +00002673 case CC_AAPCS:
2674 case CC_AAPCS_VFP:
2675 case CC_IntelOclBicc:
2676 case CC_SpirFunction:
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00002677 case CC_OpenCLKernel:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00002678 case CC_PreserveMost:
2679 case CC_PreserveAll:
John McCall07daf722016-03-01 22:18:03 +00002680 // FIXME: we should be mangling all of the above.
2681 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002682
2683 case CC_Swift:
2684 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002685 }
2686 llvm_unreachable("bad calling convention");
2687}
2688
2689void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2690 // Fast path.
2691 if (T->getExtInfo() == FunctionType::ExtInfo())
2692 return;
2693
2694 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2695 // This will get more complicated in the future if we mangle other
2696 // things here; but for now, since we mangle ns_returns_retained as
2697 // a qualifier on the result type, we can get away with this:
2698 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2699 if (!CCQualifier.empty())
2700 mangleVendorQualifier(CCQualifier);
2701
2702 // FIXME: regparm
2703 // FIXME: noreturn
2704}
2705
2706void
2707CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2708 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2709
2710 // Note that these are *not* substitution candidates. Demanglers might
2711 // have trouble with this if the parameter type is fully substituted.
2712
John McCall477f2bb2016-03-03 06:39:32 +00002713 switch (PI.getABI()) {
2714 case ParameterABI::Ordinary:
2715 break;
2716
2717 // All of these start with "swift", so they come before "ns_consumed".
2718 case ParameterABI::SwiftContext:
2719 case ParameterABI::SwiftErrorResult:
2720 case ParameterABI::SwiftIndirectResult:
2721 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2722 break;
2723 }
2724
John McCall07daf722016-03-01 22:18:03 +00002725 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002726 mangleVendorQualifier("ns_consumed");
Akira Hatanaka98a49332017-09-22 00:41:05 +00002727
2728 if (PI.isNoEscape())
2729 mangleVendorQualifier("noescape");
John McCall07daf722016-03-01 22:18:03 +00002730}
2731
Guy Benyei11169dd2012-12-18 14:30:41 +00002732// <type> ::= <function-type>
2733// <function-type> ::= [<CV-qualifiers>] F [Y]
2734// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002735void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002736 mangleExtFunctionInfo(T);
2737
Guy Benyei11169dd2012-12-18 14:30:41 +00002738 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2739 // e.g. "const" in "int (A::*)() const".
Reid Kleckner267589a2018-03-08 00:55:09 +00002740 mangleQualifiers(Qualifiers::fromCVRUMask(T->getTypeQuals()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002741
Richard Smithfda59e52016-10-26 01:05:54 +00002742 // Mangle instantiation-dependent exception-specification, if present,
2743 // per cxx-abi-dev proposal on 2016-10-11.
2744 if (T->hasInstantiationDependentExceptionSpec()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00002745 if (isComputedNoexcept(T->getExceptionSpecType())) {
Richard Smithef09aa92016-11-03 00:27:54 +00002746 Out << "DO";
Richard Smithfda59e52016-10-26 01:05:54 +00002747 mangleExpression(T->getNoexceptExpr());
2748 Out << "E";
2749 } else {
2750 assert(T->getExceptionSpecType() == EST_Dynamic);
Richard Smithef09aa92016-11-03 00:27:54 +00002751 Out << "Dw";
Richard Smithfda59e52016-10-26 01:05:54 +00002752 for (auto ExceptTy : T->exceptions())
2753 mangleType(ExceptTy);
2754 Out << "E";
2755 }
Richard Smitheaf11ad2018-05-03 03:58:32 +00002756 } else if (T->isNothrow()) {
Richard Smithef09aa92016-11-03 00:27:54 +00002757 Out << "Do";
Richard Smithfda59e52016-10-26 01:05:54 +00002758 }
2759
Guy Benyei11169dd2012-12-18 14:30:41 +00002760 Out << 'F';
2761
2762 // FIXME: We don't have enough information in the AST to produce the 'Y'
2763 // encoding for extern "C" function types.
2764 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2765
2766 // Mangle the ref-qualifier, if present.
2767 mangleRefQualifier(T->getRefQualifier());
2768
2769 Out << 'E';
2770}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002771
Guy Benyei11169dd2012-12-18 14:30:41 +00002772void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002773 // Function types without prototypes can arise when mangling a function type
2774 // within an overloadable function in C. We mangle these as the absence of any
2775 // parameter types (not even an empty parameter list).
2776 Out << 'F';
2777
2778 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2779
2780 FunctionTypeDepth.enterResultType();
2781 mangleType(T->getReturnType());
2782 FunctionTypeDepth.leaveResultType();
2783
2784 FunctionTypeDepth.pop(saved);
2785 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002786}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002787
John McCall07daf722016-03-01 22:18:03 +00002788void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002789 bool MangleReturnType,
2790 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002791 // Record that we're in a function type. See mangleFunctionParam
2792 // for details on what we're trying to achieve here.
2793 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2794
2795 // <bare-function-type> ::= <signature type>+
2796 if (MangleReturnType) {
2797 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002798
2799 // Mangle ns_returns_retained as an order-sensitive qualifier here.
Nico Weberfb420782016-05-25 14:15:08 +00002800 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
John McCall07daf722016-03-01 22:18:03 +00002801 mangleVendorQualifier("ns_returns_retained");
2802
2803 // Mangle the return type without any direct ARC ownership qualifiers.
2804 QualType ReturnTy = Proto->getReturnType();
2805 if (ReturnTy.getObjCLifetime()) {
2806 auto SplitReturnTy = ReturnTy.split();
2807 SplitReturnTy.Quals.removeObjCLifetime();
2808 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2809 }
2810 mangleType(ReturnTy);
2811
Guy Benyei11169dd2012-12-18 14:30:41 +00002812 FunctionTypeDepth.leaveResultType();
2813 }
2814
Alp Toker9cacbab2014-01-20 20:26:09 +00002815 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002816 // <builtin-type> ::= v # void
2817 Out << 'v';
2818
2819 FunctionTypeDepth.pop(saved);
2820 return;
2821 }
2822
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002823 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2824 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002825 // Mangle extended parameter info as order-sensitive qualifiers here.
Nico Weberfb420782016-05-25 14:15:08 +00002826 if (Proto->hasExtParameterInfos() && FD == nullptr) {
John McCall07daf722016-03-01 22:18:03 +00002827 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2828 }
2829
2830 // Mangle the type.
2831 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002832 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2833
2834 if (FD) {
2835 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2836 // Attr can only take 1 character, so we can hardcode the length below.
2837 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2838 Out << "U17pass_object_size" << Attr->getType();
2839 }
2840 }
2841 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002842
2843 FunctionTypeDepth.pop(saved);
2844
2845 // <builtin-type> ::= z # ellipsis
2846 if (Proto->isVariadic())
2847 Out << 'z';
2848}
2849
2850// <type> ::= <class-enum-type>
2851// <class-enum-type> ::= <name>
2852void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2853 mangleName(T->getDecl());
2854}
2855
2856// <type> ::= <class-enum-type>
2857// <class-enum-type> ::= <name>
2858void CXXNameMangler::mangleType(const EnumType *T) {
2859 mangleType(static_cast<const TagType*>(T));
2860}
2861void CXXNameMangler::mangleType(const RecordType *T) {
2862 mangleType(static_cast<const TagType*>(T));
2863}
2864void CXXNameMangler::mangleType(const TagType *T) {
2865 mangleName(T->getDecl());
2866}
2867
2868// <type> ::= <array-type>
2869// <array-type> ::= A <positive dimension number> _ <element type>
2870// ::= A [<dimension expression>] _ <element type>
2871void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2872 Out << 'A' << T->getSize() << '_';
2873 mangleType(T->getElementType());
2874}
2875void CXXNameMangler::mangleType(const VariableArrayType *T) {
2876 Out << 'A';
2877 // decayed vla types (size 0) will just be skipped.
2878 if (T->getSizeExpr())
2879 mangleExpression(T->getSizeExpr());
2880 Out << '_';
2881 mangleType(T->getElementType());
2882}
2883void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2884 Out << 'A';
2885 mangleExpression(T->getSizeExpr());
2886 Out << '_';
2887 mangleType(T->getElementType());
2888}
2889void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2890 Out << "A_";
2891 mangleType(T->getElementType());
2892}
2893
2894// <type> ::= <pointer-to-member-type>
2895// <pointer-to-member-type> ::= M <class type> <member type>
2896void CXXNameMangler::mangleType(const MemberPointerType *T) {
2897 Out << 'M';
2898 mangleType(QualType(T->getClass(), 0));
2899 QualType PointeeType = T->getPointeeType();
2900 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2901 mangleType(FPT);
Fangrui Song6907ce22018-07-30 19:24:48 +00002902
Guy Benyei11169dd2012-12-18 14:30:41 +00002903 // Itanium C++ ABI 5.1.8:
2904 //
2905 // The type of a non-static member function is considered to be different,
2906 // for the purposes of substitution, from the type of a namespace-scope or
2907 // static member function whose type appears similar. The types of two
2908 // non-static member functions are considered to be different, for the
2909 // purposes of substitution, if the functions are members of different
Fangrui Song6907ce22018-07-30 19:24:48 +00002910 // classes. In other words, for the purposes of substitution, the class of
2911 // which the function is a member is considered part of the type of
Guy Benyei11169dd2012-12-18 14:30:41 +00002912 // function.
2913
2914 // Given that we already substitute member function pointers as a
2915 // whole, the net effect of this rule is just to unconditionally
2916 // suppress substitution on the function type in a member pointer.
2917 // We increment the SeqID here to emulate adding an entry to the
2918 // substitution table.
2919 ++SeqID;
2920 } else
2921 mangleType(PointeeType);
2922}
2923
2924// <type> ::= <template-param>
2925void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2926 mangleTemplateParameter(T->getIndex());
2927}
2928
2929// <type> ::= <template-param>
2930void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2931 // FIXME: not clear how to mangle this!
2932 // template <class T...> class A {
2933 // template <class U...> void foo(T(*)(U) x...);
2934 // };
2935 Out << "_SUBSTPACK_";
2936}
2937
2938// <type> ::= P <type> # pointer-to
2939void CXXNameMangler::mangleType(const PointerType *T) {
2940 Out << 'P';
2941 mangleType(T->getPointeeType());
2942}
2943void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2944 Out << 'P';
2945 mangleType(T->getPointeeType());
2946}
2947
2948// <type> ::= R <type> # reference-to
2949void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2950 Out << 'R';
2951 mangleType(T->getPointeeType());
2952}
2953
2954// <type> ::= O <type> # rvalue reference-to (C++0x)
2955void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2956 Out << 'O';
2957 mangleType(T->getPointeeType());
2958}
2959
2960// <type> ::= C <type> # complex pair (C 2000)
2961void CXXNameMangler::mangleType(const ComplexType *T) {
2962 Out << 'C';
2963 mangleType(T->getElementType());
2964}
2965
2966// ARM's ABI for Neon vector types specifies that they should be mangled as
2967// if they are structs (to match ARM's initial implementation). The
2968// vector type must be one of the special types predefined by ARM.
2969void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2970 QualType EltType = T->getElementType();
2971 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002972 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002973 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2974 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002975 case BuiltinType::SChar:
2976 case BuiltinType::UChar:
2977 EltName = "poly8_t";
2978 break;
2979 case BuiltinType::Short:
2980 case BuiltinType::UShort:
2981 EltName = "poly16_t";
2982 break;
2983 case BuiltinType::ULongLong:
2984 EltName = "poly64_t";
2985 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002986 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2987 }
2988 } else {
2989 switch (cast<BuiltinType>(EltType)->getKind()) {
2990 case BuiltinType::SChar: EltName = "int8_t"; break;
2991 case BuiltinType::UChar: EltName = "uint8_t"; break;
2992 case BuiltinType::Short: EltName = "int16_t"; break;
2993 case BuiltinType::UShort: EltName = "uint16_t"; break;
2994 case BuiltinType::Int: EltName = "int32_t"; break;
2995 case BuiltinType::UInt: EltName = "uint32_t"; break;
2996 case BuiltinType::LongLong: EltName = "int64_t"; break;
2997 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002998 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002999 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00003000 case BuiltinType::Half: EltName = "float16_t";break;
3001 default:
3002 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00003003 }
3004 }
Craig Topper36250ad2014-05-12 05:36:57 +00003005 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 unsigned BitSize = (T->getNumElements() *
3007 getASTContext().getTypeSize(EltType));
3008 if (BitSize == 64)
3009 BaseName = "__simd64_";
3010 else {
3011 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3012 BaseName = "__simd128_";
3013 }
3014 Out << strlen(BaseName) + strlen(EltName);
3015 Out << BaseName << EltName;
3016}
3017
Erich Keanef702b022018-07-13 19:46:04 +00003018void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3019 DiagnosticsEngine &Diags = Context.getDiags();
3020 unsigned DiagID = Diags.getCustomDiagID(
3021 DiagnosticsEngine::Error,
3022 "cannot mangle this dependent neon vector type yet");
3023 Diags.Report(T->getAttributeLoc(), DiagID);
3024}
3025
Tim Northover2fe823a2013-08-01 09:23:19 +00003026static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3027 switch (EltType->getKind()) {
3028 case BuiltinType::SChar:
3029 return "Int8";
3030 case BuiltinType::Short:
3031 return "Int16";
3032 case BuiltinType::Int:
3033 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003034 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00003035 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003036 return "Int64";
3037 case BuiltinType::UChar:
3038 return "Uint8";
3039 case BuiltinType::UShort:
3040 return "Uint16";
3041 case BuiltinType::UInt:
3042 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003043 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00003044 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003045 return "Uint64";
3046 case BuiltinType::Half:
3047 return "Float16";
3048 case BuiltinType::Float:
3049 return "Float32";
3050 case BuiltinType::Double:
3051 return "Float64";
3052 default:
3053 llvm_unreachable("Unexpected vector element base type");
3054 }
3055}
3056
3057// AArch64's ABI for Neon vector types specifies that they should be mangled as
3058// the equivalent internal name. The vector type must be one of the special
3059// types predefined by ARM.
3060void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3061 QualType EltType = T->getElementType();
3062 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3063 unsigned BitSize =
3064 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00003065 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00003066
3067 assert((BitSize == 64 || BitSize == 128) &&
3068 "Neon vector type not 64 or 128 bits");
3069
Tim Northover2fe823a2013-08-01 09:23:19 +00003070 StringRef EltName;
3071 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3072 switch (cast<BuiltinType>(EltType)->getKind()) {
3073 case BuiltinType::UChar:
3074 EltName = "Poly8";
3075 break;
3076 case BuiltinType::UShort:
3077 EltName = "Poly16";
3078 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00003079 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00003080 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00003081 EltName = "Poly64";
3082 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00003083 default:
3084 llvm_unreachable("unexpected Neon polynomial vector element type");
3085 }
3086 } else
3087 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3088
3089 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00003090 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00003091 Out << TypeName.length() << TypeName;
3092}
Erich Keanef702b022018-07-13 19:46:04 +00003093void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3094 DiagnosticsEngine &Diags = Context.getDiags();
3095 unsigned DiagID = Diags.getCustomDiagID(
3096 DiagnosticsEngine::Error,
3097 "cannot mangle this dependent neon vector type yet");
3098 Diags.Report(T->getAttributeLoc(), DiagID);
3099}
Tim Northover2fe823a2013-08-01 09:23:19 +00003100
Guy Benyei11169dd2012-12-18 14:30:41 +00003101// GNU extension: vector types
3102// <type> ::= <vector-type>
3103// <vector-type> ::= Dv <positive dimension number> _
3104// <extended element type>
3105// ::= Dv [<dimension expression>] _ <element type>
3106// <extended element type> ::= <element type>
3107// ::= p # AltiVec vector pixel
3108// ::= b # Altivec vector bool
3109void CXXNameMangler::mangleType(const VectorType *T) {
3110 if ((T->getVectorKind() == VectorType::NeonVector ||
3111 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003112 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00003113 llvm::Triple::ArchType Arch =
3114 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00003115 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00003116 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00003117 mangleAArch64NeonVectorType(T);
3118 else
3119 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00003120 return;
3121 }
3122 Out << "Dv" << T->getNumElements() << '_';
3123 if (T->getVectorKind() == VectorType::AltiVecPixel)
3124 Out << 'p';
3125 else if (T->getVectorKind() == VectorType::AltiVecBool)
3126 Out << 'b';
3127 else
3128 mangleType(T->getElementType());
3129}
Erich Keanef702b022018-07-13 19:46:04 +00003130
3131void CXXNameMangler::mangleType(const DependentVectorType *T) {
3132 if ((T->getVectorKind() == VectorType::NeonVector ||
3133 T->getVectorKind() == VectorType::NeonPolyVector)) {
3134 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3135 llvm::Triple::ArchType Arch =
3136 getASTContext().getTargetInfo().getTriple().getArch();
3137 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3138 !Target.isOSDarwin())
3139 mangleAArch64NeonVectorType(T);
3140 else
3141 mangleNeonVectorType(T);
3142 return;
3143 }
3144
3145 Out << "Dv";
3146 mangleExpression(T->getSizeExpr());
3147 Out << '_';
3148 if (T->getVectorKind() == VectorType::AltiVecPixel)
3149 Out << 'p';
3150 else if (T->getVectorKind() == VectorType::AltiVecBool)
3151 Out << 'b';
3152 else
3153 mangleType(T->getElementType());
3154}
3155
Guy Benyei11169dd2012-12-18 14:30:41 +00003156void CXXNameMangler::mangleType(const ExtVectorType *T) {
3157 mangleType(static_cast<const VectorType*>(T));
3158}
3159void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3160 Out << "Dv";
3161 mangleExpression(T->getSizeExpr());
3162 Out << '_';
3163 mangleType(T->getElementType());
3164}
3165
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003166void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3167 SplitQualType split = T->getPointeeType().split();
3168 mangleQualifiers(split.Quals, T);
3169 mangleType(QualType(split.Ty, 0));
3170}
3171
Guy Benyei11169dd2012-12-18 14:30:41 +00003172void CXXNameMangler::mangleType(const PackExpansionType *T) {
3173 // <type> ::= Dp <type> # pack expansion (C++0x)
3174 Out << "Dp";
3175 mangleType(T->getPattern());
3176}
3177
3178void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3179 mangleSourceName(T->getDecl()->getIdentifier());
3180}
3181
3182void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00003183 // Treat __kindof as a vendor extended type qualifier.
3184 if (T->isKindOfType())
3185 Out << "U8__kindof";
3186
Eli Friedman5f508952013-06-18 22:41:37 +00003187 if (!T->qual_empty()) {
3188 // Mangle protocol qualifiers.
3189 SmallString<64> QualStr;
3190 llvm::raw_svector_ostream QualOS(QualStr);
3191 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00003192 for (const auto *I : T->quals()) {
3193 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00003194 QualOS << name.size() << name;
3195 }
Eli Friedman5f508952013-06-18 22:41:37 +00003196 Out << 'U' << QualStr.size() << QualStr;
3197 }
Douglas Gregorab209d82015-07-07 03:58:42 +00003198
Guy Benyei11169dd2012-12-18 14:30:41 +00003199 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00003200
3201 if (T->isSpecialized()) {
3202 // Mangle type arguments as I <type>+ E
3203 Out << 'I';
3204 for (auto typeArg : T->getTypeArgs())
3205 mangleType(typeArg);
3206 Out << 'E';
3207 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003208}
3209
3210void CXXNameMangler::mangleType(const BlockPointerType *T) {
3211 Out << "U13block_pointer";
3212 mangleType(T->getPointeeType());
3213}
3214
3215void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3216 // Mangle injected class name types as if the user had written the
3217 // specialization out fully. It may not actually be possible to see
3218 // this mangling, though.
3219 mangleType(T->getInjectedSpecializationType());
3220}
3221
3222void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3223 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003224 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003225 } else {
3226 if (mangleSubstitution(QualType(T, 0)))
3227 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003228
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 mangleTemplatePrefix(T->getTemplateName());
Fangrui Song6907ce22018-07-30 19:24:48 +00003230
Guy Benyei11169dd2012-12-18 14:30:41 +00003231 // FIXME: GCC does not appear to mangle the template arguments when
3232 // the template in question is a dependent template name. Should we
3233 // emulate that badness?
3234 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3235 addSubstitution(QualType(T, 0));
3236 }
3237}
3238
3239void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00003240 // Proposal by cxx-abi-dev, 2014-03-26
3241 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3242 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003243 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00003244 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003245 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00003246 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003247 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00003248 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003249 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00003250 switch (T->getKeyword()) {
Richard Smith91fb1f42017-01-20 18:50:12 +00003251 case ETK_None:
David Majnemer64e40c52014-04-10 00:49:24 +00003252 case ETK_Typename:
3253 break;
3254 case ETK_Struct:
3255 case ETK_Class:
3256 case ETK_Interface:
3257 Out << "Ts";
3258 break;
3259 case ETK_Union:
3260 Out << "Tu";
3261 break;
3262 case ETK_Enum:
3263 Out << "Te";
3264 break;
David Majnemer64e40c52014-04-10 00:49:24 +00003265 }
David Majnemer2e159fb2014-04-15 05:51:25 +00003266 // Typename types are always nested
3267 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00003269 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00003270 Out << 'E';
3271}
3272
3273void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3274 // Dependently-scoped template types are nested if they have a prefix.
3275 Out << 'N';
3276
3277 // TODO: avoid making this TemplateName.
3278 TemplateName Prefix =
3279 getASTContext().getDependentTemplateName(T->getQualifier(),
3280 T->getIdentifier());
3281 mangleTemplatePrefix(Prefix);
3282
3283 // FIXME: GCC does not appear to mangle the template arguments when
3284 // the template in question is a dependent template name. Should we
3285 // emulate that badness?
Fangrui Song6907ce22018-07-30 19:24:48 +00003286 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003287 Out << 'E';
3288}
3289
3290void CXXNameMangler::mangleType(const TypeOfType *T) {
3291 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3292 // "extension with parameters" mangling.
3293 Out << "u6typeof";
3294}
3295
3296void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3297 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3298 // "extension with parameters" mangling.
3299 Out << "u6typeof";
3300}
3301
3302void CXXNameMangler::mangleType(const DecltypeType *T) {
3303 Expr *E = T->getUnderlyingExpr();
3304
3305 // type ::= Dt <expression> E # decltype of an id-expression
3306 // # or class member access
3307 // ::= DT <expression> E # decltype of an expression
3308
3309 // This purports to be an exhaustive list of id-expressions and
3310 // class member accesses. Note that we do not ignore parentheses;
3311 // parentheses change the semantics of decltype for these
3312 // expressions (and cause the mangler to use the other form).
3313 if (isa<DeclRefExpr>(E) ||
3314 isa<MemberExpr>(E) ||
3315 isa<UnresolvedLookupExpr>(E) ||
3316 isa<DependentScopeDeclRefExpr>(E) ||
3317 isa<CXXDependentScopeMemberExpr>(E) ||
3318 isa<UnresolvedMemberExpr>(E))
3319 Out << "Dt";
3320 else
3321 Out << "DT";
3322 mangleExpression(E);
3323 Out << 'E';
3324}
3325
3326void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3327 // If this is dependent, we need to record that. If not, we simply
3328 // mangle it as the underlying type since they are equivalent.
3329 if (T->isDependentType()) {
3330 Out << 'U';
Fangrui Song6907ce22018-07-30 19:24:48 +00003331
Guy Benyei11169dd2012-12-18 14:30:41 +00003332 switch (T->getUTTKind()) {
3333 case UnaryTransformType::EnumUnderlyingType:
3334 Out << "3eut";
3335 break;
3336 }
3337 }
3338
David Majnemer140065a2016-06-08 00:34:15 +00003339 mangleType(T->getBaseType());
Guy Benyei11169dd2012-12-18 14:30:41 +00003340}
3341
3342void CXXNameMangler::mangleType(const AutoType *T) {
Erik Pilkingtone7e87722018-04-28 02:40:28 +00003343 assert(T->getDeducedType().isNull() &&
3344 "Deduced AutoType shouldn't be handled here!");
3345 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3346 "shouldn't need to mangle __auto_type!");
3347 // <builtin-type> ::= Da # auto
3348 // ::= Dc # decltype(auto)
3349 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00003350}
3351
Richard Smith600b5262017-01-26 20:40:47 +00003352void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3353 // FIXME: This is not the right mangling. We also need to include a scope
3354 // here in some cases.
3355 QualType D = T->getDeducedType();
3356 if (D.isNull())
3357 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3358 else
3359 mangleType(D);
3360}
3361
Guy Benyei11169dd2012-12-18 14:30:41 +00003362void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00003363 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00003364 // (Until there's a standardized mangling...)
3365 Out << "U7_Atomic";
3366 mangleType(T->getValueType());
3367}
3368
Xiuli Pan9c14e282016-01-09 12:53:17 +00003369void CXXNameMangler::mangleType(const PipeType *T) {
3370 // Pipe type mangling rules are described in SPIR 2.0 specification
3371 // A.1 Data types and A.3 Summary of changes
3372 // <type> ::= 8ocl_pipe
3373 Out << "8ocl_pipe";
3374}
3375
Guy Benyei11169dd2012-12-18 14:30:41 +00003376void CXXNameMangler::mangleIntegerLiteral(QualType T,
3377 const llvm::APSInt &Value) {
3378 // <expr-primary> ::= L <type> <value number> E # integer literal
3379 Out << 'L';
3380
3381 mangleType(T);
3382 if (T->isBooleanType()) {
3383 // Boolean values are encoded as 0/1.
3384 Out << (Value.getBoolValue() ? '1' : '0');
3385 } else {
3386 mangleNumber(Value);
3387 }
3388 Out << 'E';
3389
3390}
3391
David Majnemer1dabfdc2015-02-14 13:23:54 +00003392void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3393 // Ignore member expressions involving anonymous unions.
3394 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3395 if (!RT->getDecl()->isAnonymousStructOrUnion())
3396 break;
3397 const auto *ME = dyn_cast<MemberExpr>(Base);
3398 if (!ME)
3399 break;
3400 Base = ME->getBase();
3401 IsArrow = ME->isArrow();
3402 }
3403
3404 if (Base->isImplicitCXXThis()) {
3405 // Note: GCC mangles member expressions to the implicit 'this' as
3406 // *this., whereas we represent them as this->. The Itanium C++ ABI
3407 // does not specify anything here, so we follow GCC.
3408 Out << "dtdefpT";
3409 } else {
3410 Out << (IsArrow ? "pt" : "dt");
3411 mangleExpression(Base);
3412 }
3413}
3414
Guy Benyei11169dd2012-12-18 14:30:41 +00003415/// Mangles a member expression.
3416void CXXNameMangler::mangleMemberExpr(const Expr *base,
3417 bool isArrow,
3418 NestedNameSpecifier *qualifier,
3419 NamedDecl *firstQualifierLookup,
3420 DeclarationName member,
Richard Smithafecd832016-10-24 20:47:04 +00003421 const TemplateArgumentLoc *TemplateArgs,
3422 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00003423 unsigned arity) {
3424 // <expression> ::= dt <expression> <unresolved-name>
3425 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00003426 if (base)
3427 mangleMemberExprBase(base, isArrow);
Richard Smithafecd832016-10-24 20:47:04 +00003428 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003429}
3430
3431/// Look at the callee of the given call expression and determine if
3432/// it's a parenthesized id-expression which would have triggered ADL
3433/// otherwise.
3434static bool isParenthesizedADLCallee(const CallExpr *call) {
3435 const Expr *callee = call->getCallee();
3436 const Expr *fn = callee->IgnoreParens();
3437
3438 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3439 // too, but for those to appear in the callee, it would have to be
3440 // parenthesized.
3441 if (callee == fn) return false;
3442
3443 // Must be an unresolved lookup.
3444 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3445 if (!lookup) return false;
3446
3447 assert(!lookup->requiresADL());
3448
3449 // Must be an unqualified lookup.
3450 if (lookup->getQualifier()) return false;
3451
3452 // Must not have found a class member. Note that if one is a class
3453 // member, they're all class members.
3454 if (lookup->getNumDecls() > 0 &&
3455 (*lookup->decls_begin())->isCXXClassMember())
3456 return false;
3457
3458 // Otherwise, ADL would have been triggered.
3459 return true;
3460}
3461
David Majnemer9c775c72014-09-23 04:27:55 +00003462void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3463 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3464 Out << CastEncoding;
3465 mangleType(ECE->getType());
3466 mangleExpression(ECE->getSubExpr());
3467}
3468
Richard Smith520449d2015-02-05 06:15:50 +00003469void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3470 if (auto *Syntactic = InitList->getSyntacticForm())
3471 InitList = Syntactic;
3472 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3473 mangleExpression(InitList->getInit(i));
3474}
3475
Guy Benyei11169dd2012-12-18 14:30:41 +00003476void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3477 // <expression> ::= <unary operator-name> <expression>
3478 // ::= <binary operator-name> <expression> <expression>
3479 // ::= <trinary operator-name> <expression> <expression> <expression>
3480 // ::= cv <type> expression # conversion with one argument
3481 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00003482 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3483 // ::= sc <type> <expression> # static_cast<type> (expression)
3484 // ::= cc <type> <expression> # const_cast<type> (expression)
3485 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003486 // ::= st <type> # sizeof (a type)
3487 // ::= at <type> # alignof (a type)
3488 // ::= <template-param>
3489 // ::= <function-param>
3490 // ::= sr <type> <unqualified-name> # dependent name
3491 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3492 // ::= ds <expression> <expression> # expr.*expr
3493 // ::= sZ <template-param> # size of a parameter pack
3494 // ::= sZ <function-param> # size of a function parameter pack
3495 // ::= <expr-primary>
3496 // <expr-primary> ::= L <type> <value number> E # integer literal
3497 // ::= L <type <value float> E # floating literal
3498 // ::= L <mangled-name> E # external name
3499 // ::= fpT # 'this' expression
3500 QualType ImplicitlyConvertedToType;
Fangrui Song6907ce22018-07-30 19:24:48 +00003501
Guy Benyei11169dd2012-12-18 14:30:41 +00003502recurse:
3503 switch (E->getStmtClass()) {
3504 case Expr::NoStmtClass:
3505#define ABSTRACT_STMT(Type)
3506#define EXPR(Type, Base)
3507#define STMT(Type, Base) \
3508 case Expr::Type##Class:
3509#include "clang/AST/StmtNodes.inc"
3510 // fallthrough
3511
3512 // These all can only appear in local or variable-initialization
3513 // contexts and so should never appear in a mangling.
3514 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003515 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003516 case Expr::ImplicitValueInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003517 case Expr::ArrayInitLoopExprClass:
3518 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003519 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003520 case Expr::ParenListExprClass:
3521 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00003522 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003523 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003524 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003525 case Expr::OMPArraySectionExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00003526 case Expr::CXXInheritedCtorInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003527 llvm_unreachable("unexpected statement kind");
3528
3529 // FIXME: invent manglings for all these.
3530 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003531 case Expr::ChooseExprClass:
3532 case Expr::CompoundLiteralExprClass:
3533 case Expr::ExtVectorElementExprClass:
3534 case Expr::GenericSelectionExprClass:
3535 case Expr::ObjCEncodeExprClass:
3536 case Expr::ObjCIsaExprClass:
3537 case Expr::ObjCIvarRefExprClass:
3538 case Expr::ObjCMessageExprClass:
3539 case Expr::ObjCPropertyRefExprClass:
3540 case Expr::ObjCProtocolExprClass:
3541 case Expr::ObjCSelectorExprClass:
3542 case Expr::ObjCStringLiteralClass:
3543 case Expr::ObjCBoxedExprClass:
3544 case Expr::ObjCArrayLiteralClass:
3545 case Expr::ObjCDictionaryLiteralClass:
3546 case Expr::ObjCSubscriptRefExprClass:
3547 case Expr::ObjCIndirectCopyRestoreExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003548 case Expr::ObjCAvailabilityCheckExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003549 case Expr::OffsetOfExprClass:
3550 case Expr::PredefinedExprClass:
3551 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003552 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003553 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 case Expr::TypeTraitExprClass:
3555 case Expr::ArrayTypeTraitExprClass:
3556 case Expr::ExpressionTraitExprClass:
3557 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003558 case Expr::CUDAKernelCallExprClass:
3559 case Expr::AsTypeExprClass:
3560 case Expr::PseudoObjectExprClass:
3561 case Expr::AtomicExprClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003562 case Expr::FixedPointLiteralClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003563 {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003564 if (!NullOut) {
3565 // As bad as this diagnostic is, it's better than crashing.
3566 DiagnosticsEngine &Diags = Context.getDiags();
3567 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3568 "cannot yet mangle expression type %0");
3569 Diags.Report(E->getExprLoc(), DiagID)
3570 << E->getStmtClassName() << E->getSourceRange();
3571 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003572 break;
3573 }
3574
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00003575 case Expr::CXXUuidofExprClass: {
3576 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3577 if (UE->isTypeOperand()) {
3578 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3579 Out << "u8__uuidoft";
3580 mangleType(UuidT);
3581 } else {
3582 Expr *UuidExp = UE->getExprOperand();
3583 Out << "u8__uuidofz";
3584 mangleExpression(UuidExp, Arity);
3585 }
3586 break;
3587 }
3588
Guy Benyei11169dd2012-12-18 14:30:41 +00003589 // Even gcc-4.5 doesn't mangle this.
3590 case Expr::BinaryConditionalOperatorClass: {
3591 DiagnosticsEngine &Diags = Context.getDiags();
3592 unsigned DiagID =
3593 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3594 "?: operator with omitted middle operand cannot be mangled");
3595 Diags.Report(E->getExprLoc(), DiagID)
3596 << E->getStmtClassName() << E->getSourceRange();
3597 break;
3598 }
3599
3600 // These are used for internal purposes and cannot be meaningfully mangled.
3601 case Expr::OpaqueValueExprClass:
3602 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3603
3604 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00003606 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00003607 Out << "E";
3608 break;
3609 }
3610
Richard Smith39eca9b2017-08-23 22:12:08 +00003611 case Expr::DesignatedInitExprClass: {
3612 auto *DIE = cast<DesignatedInitExpr>(E);
3613 for (const auto &Designator : DIE->designators()) {
3614 if (Designator.isFieldDesignator()) {
3615 Out << "di";
3616 mangleSourceName(Designator.getFieldName());
3617 } else if (Designator.isArrayDesignator()) {
3618 Out << "dx";
3619 mangleExpression(DIE->getArrayIndex(Designator));
3620 } else {
3621 assert(Designator.isArrayRangeDesignator() &&
3622 "unknown designator kind");
3623 Out << "dX";
3624 mangleExpression(DIE->getArrayRangeStart(Designator));
3625 mangleExpression(DIE->getArrayRangeEnd(Designator));
3626 }
3627 }
3628 mangleExpression(DIE->getInit());
3629 break;
3630 }
3631
Guy Benyei11169dd2012-12-18 14:30:41 +00003632 case Expr::CXXDefaultArgExprClass:
3633 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3634 break;
3635
Richard Smith852c9db2013-04-20 22:23:05 +00003636 case Expr::CXXDefaultInitExprClass:
3637 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3638 break;
3639
Richard Smithcc1b96d2013-06-12 22:31:48 +00003640 case Expr::CXXStdInitializerListExprClass:
3641 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3642 break;
3643
Guy Benyei11169dd2012-12-18 14:30:41 +00003644 case Expr::SubstNonTypeTemplateParmExprClass:
3645 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3646 Arity);
3647 break;
3648
3649 case Expr::UserDefinedLiteralClass:
3650 // We follow g++'s approach of mangling a UDL as a call to the literal
3651 // operator.
3652 case Expr::CXXMemberCallExprClass: // fallthrough
3653 case Expr::CallExprClass: {
3654 const CallExpr *CE = cast<CallExpr>(E);
3655
3656 // <expression> ::= cp <simple-id> <expression>* E
3657 // We use this mangling only when the call would use ADL except
3658 // for being parenthesized. Per discussion with David
3659 // Vandervoorde, 2011.04.25.
3660 if (isParenthesizedADLCallee(CE)) {
3661 Out << "cp";
3662 // The callee here is a parenthesized UnresolvedLookupExpr with
3663 // no qualifier and should always get mangled as a <simple-id>
3664 // anyway.
3665
3666 // <expression> ::= cl <expression>* E
3667 } else {
3668 Out << "cl";
3669 }
3670
David Majnemer67a8ec62015-02-19 21:41:48 +00003671 unsigned CallArity = CE->getNumArgs();
3672 for (const Expr *Arg : CE->arguments())
3673 if (isa<PackExpansionExpr>(Arg))
3674 CallArity = UnknownArity;
3675
3676 mangleExpression(CE->getCallee(), CallArity);
3677 for (const Expr *Arg : CE->arguments())
3678 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003679 Out << 'E';
3680 break;
3681 }
3682
3683 case Expr::CXXNewExprClass: {
3684 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3685 if (New->isGlobalNew()) Out << "gs";
3686 Out << (New->isArray() ? "na" : "nw");
3687 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3688 E = New->placement_arg_end(); I != E; ++I)
3689 mangleExpression(*I);
3690 Out << '_';
3691 mangleType(New->getAllocatedType());
3692 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003693 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3694 Out << "il";
3695 else
3696 Out << "pi";
3697 const Expr *Init = New->getInitializer();
3698 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3699 // Directly inline the initializers.
3700 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3701 E = CCE->arg_end();
3702 I != E; ++I)
3703 mangleExpression(*I);
3704 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3705 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3706 mangleExpression(PLE->getExpr(i));
3707 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3708 isa<InitListExpr>(Init)) {
3709 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003710 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003711 } else
3712 mangleExpression(Init);
3713 }
3714 Out << 'E';
3715 break;
3716 }
3717
David Majnemer1dabfdc2015-02-14 13:23:54 +00003718 case Expr::CXXPseudoDestructorExprClass: {
3719 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3720 if (const Expr *Base = PDE->getBase())
3721 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003722 NestedNameSpecifier *Qualifier = PDE->getQualifier();
David Majnemerb8014dd2015-02-19 02:16:16 +00003723 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3724 if (Qualifier) {
3725 mangleUnresolvedPrefix(Qualifier,
3726 /*Recursive=*/true);
3727 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3728 Out << 'E';
3729 } else {
3730 Out << "sr";
3731 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3732 Out << 'E';
3733 }
3734 } else if (Qualifier) {
3735 mangleUnresolvedPrefix(Qualifier);
3736 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003737 // <base-unresolved-name> ::= dn <destructor-name>
3738 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003739 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003740 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003741 break;
3742 }
3743
Guy Benyei11169dd2012-12-18 14:30:41 +00003744 case Expr::MemberExprClass: {
3745 const MemberExpr *ME = cast<MemberExpr>(E);
3746 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003747 ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003748 ME->getMemberDecl()->getDeclName(),
3749 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3750 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003751 break;
3752 }
3753
3754 case Expr::UnresolvedMemberExprClass: {
3755 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003756 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3757 ME->isArrow(), ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003758 ME->getMemberName(),
3759 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3760 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 break;
3762 }
3763
3764 case Expr::CXXDependentScopeMemberExprClass: {
3765 const CXXDependentScopeMemberExpr *ME
3766 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003767 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3768 ME->isArrow(), ME->getQualifier(),
3769 ME->getFirstQualifierFoundInScope(),
Richard Smithafecd832016-10-24 20:47:04 +00003770 ME->getMember(),
3771 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3772 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003773 break;
3774 }
3775
3776 case Expr::UnresolvedLookupExprClass: {
3777 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00003778 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3779 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3780 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003781 break;
3782 }
3783
3784 case Expr::CXXUnresolvedConstructExprClass: {
3785 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3786 unsigned N = CE->arg_size();
3787
Richard Smith39eca9b2017-08-23 22:12:08 +00003788 if (CE->isListInitialization()) {
3789 assert(N == 1 && "unexpected form for list initialization");
3790 auto *IL = cast<InitListExpr>(CE->getArg(0));
3791 Out << "tl";
3792 mangleType(CE->getType());
3793 mangleInitListElements(IL);
3794 Out << "E";
3795 return;
3796 }
3797
Guy Benyei11169dd2012-12-18 14:30:41 +00003798 Out << "cv";
3799 mangleType(CE->getType());
3800 if (N != 1) Out << '_';
3801 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3802 if (N != 1) Out << 'E';
3803 break;
3804 }
3805
Guy Benyei11169dd2012-12-18 14:30:41 +00003806 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003807 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003808 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003809 assert(
3810 CE->getNumArgs() >= 1 &&
3811 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3812 "implicit CXXConstructExpr must have one argument");
3813 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3814 }
3815 Out << "il";
3816 for (auto *E : CE->arguments())
3817 mangleExpression(E);
3818 Out << "E";
3819 break;
3820 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003821
Richard Smith520449d2015-02-05 06:15:50 +00003822 case Expr::CXXTemporaryObjectExprClass: {
3823 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3824 unsigned N = CE->getNumArgs();
3825 bool List = CE->isListInitialization();
3826
3827 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003828 Out << "tl";
3829 else
3830 Out << "cv";
3831 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003832 if (!List && N != 1)
3833 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003834 if (CE->isStdInitListInitialization()) {
3835 // We implicitly created a std::initializer_list<T> for the first argument
3836 // of a constructor of type U in an expression of the form U{a, b, c}.
3837 // Strip all the semantic gunk off the initializer list.
3838 auto *SILE =
3839 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3840 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3841 mangleInitListElements(ILE);
3842 } else {
3843 for (auto *E : CE->arguments())
3844 mangleExpression(E);
3845 }
Richard Smith520449d2015-02-05 06:15:50 +00003846 if (List || N != 1)
3847 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003848 break;
3849 }
3850
3851 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003852 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003853 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003854 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003855 break;
3856
3857 case Expr::CXXNoexceptExprClass:
3858 Out << "nx";
3859 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3860 break;
3861
3862 case Expr::UnaryExprOrTypeTraitExprClass: {
3863 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
Fangrui Song6907ce22018-07-30 19:24:48 +00003864
Guy Benyei11169dd2012-12-18 14:30:41 +00003865 if (!SAE->isInstantiationDependent()) {
3866 // Itanium C++ ABI:
Fangrui Song6907ce22018-07-30 19:24:48 +00003867 // If the operand of a sizeof or alignof operator is not
3868 // instantiation-dependent it is encoded as an integer literal
Guy Benyei11169dd2012-12-18 14:30:41 +00003869 // reflecting the result of the operator.
3870 //
Fangrui Song6907ce22018-07-30 19:24:48 +00003871 // If the result of the operator is implicitly converted to a known
3872 // integer type, that type is used for the literal; otherwise, the type
Guy Benyei11169dd2012-12-18 14:30:41 +00003873 // of std::size_t or std::ptrdiff_t is used.
Fangrui Song6907ce22018-07-30 19:24:48 +00003874 QualType T = (ImplicitlyConvertedToType.isNull() ||
Guy Benyei11169dd2012-12-18 14:30:41 +00003875 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3876 : ImplicitlyConvertedToType;
3877 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3878 mangleIntegerLiteral(T, V);
3879 break;
3880 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003881
Guy Benyei11169dd2012-12-18 14:30:41 +00003882 switch(SAE->getKind()) {
3883 case UETT_SizeOf:
3884 Out << 's';
3885 break;
3886 case UETT_AlignOf:
3887 Out << 'a';
3888 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003889 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003890 DiagnosticsEngine &Diags = Context.getDiags();
3891 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3892 "cannot yet mangle vec_step expression");
3893 Diags.Report(DiagID);
3894 return;
3895 }
Alexey Bataev00396512015-07-02 03:40:19 +00003896 case UETT_OpenMPRequiredSimdAlign:
3897 DiagnosticsEngine &Diags = Context.getDiags();
3898 unsigned DiagID = Diags.getCustomDiagID(
3899 DiagnosticsEngine::Error,
3900 "cannot yet mangle __builtin_omp_required_simd_align expression");
3901 Diags.Report(DiagID);
3902 return;
3903 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003904 if (SAE->isArgumentType()) {
3905 Out << 't';
3906 mangleType(SAE->getArgumentType());
3907 } else {
3908 Out << 'z';
3909 mangleExpression(SAE->getArgumentExpr());
3910 }
3911 break;
3912 }
3913
3914 case Expr::CXXThrowExprClass: {
3915 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003916 // <expression> ::= tw <expression> # throw expression
3917 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003918 if (TE->getSubExpr()) {
3919 Out << "tw";
3920 mangleExpression(TE->getSubExpr());
3921 } else {
3922 Out << "tr";
3923 }
3924 break;
3925 }
3926
3927 case Expr::CXXTypeidExprClass: {
3928 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003929 // <expression> ::= ti <type> # typeid (type)
3930 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003931 if (TIE->isTypeOperand()) {
3932 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003933 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003934 } else {
3935 Out << "te";
3936 mangleExpression(TIE->getExprOperand());
3937 }
3938 break;
3939 }
3940
3941 case Expr::CXXDeleteExprClass: {
3942 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003943 // <expression> ::= [gs] dl <expression> # [::] delete expr
3944 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003945 if (DE->isGlobalDelete()) Out << "gs";
3946 Out << (DE->isArrayForm() ? "da" : "dl");
3947 mangleExpression(DE->getArgument());
3948 break;
3949 }
3950
3951 case Expr::UnaryOperatorClass: {
3952 const UnaryOperator *UO = cast<UnaryOperator>(E);
3953 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3954 /*Arity=*/1);
3955 mangleExpression(UO->getSubExpr());
3956 break;
3957 }
3958
3959 case Expr::ArraySubscriptExprClass: {
3960 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3961
3962 // Array subscript is treated as a syntactically weird form of
3963 // binary operator.
3964 Out << "ix";
3965 mangleExpression(AE->getLHS());
3966 mangleExpression(AE->getRHS());
3967 break;
3968 }
3969
3970 case Expr::CompoundAssignOperatorClass: // fallthrough
3971 case Expr::BinaryOperatorClass: {
3972 const BinaryOperator *BO = cast<BinaryOperator>(E);
3973 if (BO->getOpcode() == BO_PtrMemD)
3974 Out << "ds";
3975 else
3976 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3977 /*Arity=*/2);
3978 mangleExpression(BO->getLHS());
3979 mangleExpression(BO->getRHS());
3980 break;
3981 }
3982
3983 case Expr::ConditionalOperatorClass: {
3984 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3985 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3986 mangleExpression(CO->getCond());
3987 mangleExpression(CO->getLHS(), Arity);
3988 mangleExpression(CO->getRHS(), Arity);
3989 break;
3990 }
3991
3992 case Expr::ImplicitCastExprClass: {
3993 ImplicitlyConvertedToType = E->getType();
3994 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3995 goto recurse;
3996 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003997
Guy Benyei11169dd2012-12-18 14:30:41 +00003998 case Expr::ObjCBridgedCastExprClass: {
Fangrui Song6907ce22018-07-30 19:24:48 +00003999 // Mangle ownership casts as a vendor extended operator __bridge,
Guy Benyei11169dd2012-12-18 14:30:41 +00004000 // __bridge_transfer, or __bridge_retain.
4001 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4002 Out << "v1U" << Kind.size() << Kind;
4003 }
4004 // Fall through to mangle the cast itself.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00004005 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004006
Guy Benyei11169dd2012-12-18 14:30:41 +00004007 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00004008 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00004009 break;
David Majnemer9c775c72014-09-23 04:27:55 +00004010
Richard Smith520449d2015-02-05 06:15:50 +00004011 case Expr::CXXFunctionalCastExprClass: {
4012 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4013 // FIXME: Add isImplicit to CXXConstructExpr.
4014 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4015 if (CCE->getParenOrBraceRange().isInvalid())
4016 Sub = CCE->getArg(0)->IgnoreImplicit();
4017 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4018 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4019 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4020 Out << "tl";
4021 mangleType(E->getType());
4022 mangleInitListElements(IL);
4023 Out << "E";
4024 } else {
4025 mangleCastExpression(E, "cv");
4026 }
4027 break;
4028 }
4029
David Majnemer9c775c72014-09-23 04:27:55 +00004030 case Expr::CXXStaticCastExprClass:
4031 mangleCastExpression(E, "sc");
4032 break;
4033 case Expr::CXXDynamicCastExprClass:
4034 mangleCastExpression(E, "dc");
4035 break;
4036 case Expr::CXXReinterpretCastExprClass:
4037 mangleCastExpression(E, "rc");
4038 break;
4039 case Expr::CXXConstCastExprClass:
4040 mangleCastExpression(E, "cc");
4041 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004042
4043 case Expr::CXXOperatorCallExprClass: {
4044 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4045 unsigned NumArgs = CE->getNumArgs();
Richard Smith4631be72016-10-24 20:29:40 +00004046 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4047 // (the enclosing MemberExpr covers the syntactic portion).
4048 if (CE->getOperator() != OO_Arrow)
4049 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00004050 // Mangle the arguments.
4051 for (unsigned i = 0; i != NumArgs; ++i)
4052 mangleExpression(CE->getArg(i));
4053 break;
4054 }
4055
4056 case Expr::ParenExprClass:
4057 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
4058 break;
4059
4060 case Expr::DeclRefExprClass: {
4061 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4062
4063 switch (D->getKind()) {
4064 default:
4065 // <expr-primary> ::= L <mangled-name> E # external name
4066 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004067 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004068 Out << 'E';
4069 break;
4070
4071 case Decl::ParmVar:
4072 mangleFunctionParam(cast<ParmVarDecl>(D));
4073 break;
4074
4075 case Decl::EnumConstant: {
4076 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4077 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4078 break;
4079 }
4080
4081 case Decl::NonTypeTemplateParm: {
4082 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4083 mangleTemplateParameter(PD->getIndex());
4084 break;
4085 }
4086
4087 }
4088
4089 break;
4090 }
4091
4092 case Expr::SubstNonTypeTemplateParmPackExprClass:
4093 // FIXME: not clear how to mangle this!
4094 // template <unsigned N...> class A {
4095 // template <class U...> void foo(U (&x)[N]...);
4096 // };
4097 Out << "_SUBSTPACK_";
4098 break;
4099
4100 case Expr::FunctionParmPackExprClass: {
4101 // FIXME: not clear how to mangle this!
4102 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4103 Out << "v110_SUBSTPACK";
4104 mangleFunctionParam(FPPE->getParameterPack());
4105 break;
4106 }
4107
4108 case Expr::DependentScopeDeclRefExprClass: {
4109 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00004110 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4111 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4112 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00004113 break;
4114 }
4115
4116 case Expr::CXXBindTemporaryExprClass:
4117 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4118 break;
4119
4120 case Expr::ExprWithCleanupsClass:
4121 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4122 break;
4123
4124 case Expr::FloatingLiteralClass: {
4125 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4126 Out << 'L';
4127 mangleType(FL->getType());
4128 mangleFloat(FL->getValue());
4129 Out << 'E';
4130 break;
4131 }
4132
4133 case Expr::CharacterLiteralClass:
4134 Out << 'L';
4135 mangleType(E->getType());
4136 Out << cast<CharacterLiteral>(E)->getValue();
4137 Out << 'E';
4138 break;
4139
4140 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4141 case Expr::ObjCBoolLiteralExprClass:
4142 Out << "Lb";
4143 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4144 Out << 'E';
4145 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004146
Guy Benyei11169dd2012-12-18 14:30:41 +00004147 case Expr::CXXBoolLiteralExprClass:
4148 Out << "Lb";
4149 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4150 Out << 'E';
4151 break;
4152
4153 case Expr::IntegerLiteralClass: {
4154 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4155 if (E->getType()->isSignedIntegerType())
4156 Value.setIsSigned(true);
4157 mangleIntegerLiteral(E->getType(), Value);
4158 break;
4159 }
4160
4161 case Expr::ImaginaryLiteralClass: {
4162 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4163 // Mangle as if a complex literal.
4164 // Proposal from David Vandevoorde, 2010.06.30.
4165 Out << 'L';
4166 mangleType(E->getType());
4167 if (const FloatingLiteral *Imag =
4168 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4169 // Mangle a floating-point zero of the appropriate type.
4170 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4171 Out << '_';
4172 mangleFloat(Imag->getValue());
4173 } else {
4174 Out << "0_";
4175 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4176 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4177 Value.setIsSigned(true);
4178 mangleNumber(Value);
4179 }
4180 Out << 'E';
4181 break;
4182 }
4183
4184 case Expr::StringLiteralClass: {
4185 // Revised proposal from David Vandervoorde, 2010.07.15.
4186 Out << 'L';
4187 assert(isa<ConstantArrayType>(E->getType()));
4188 mangleType(E->getType());
4189 Out << 'E';
4190 break;
4191 }
4192
4193 case Expr::GNUNullExprClass:
4194 // FIXME: should this really be mangled the same as nullptr?
4195 // fallthrough
4196
4197 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004198 Out << "LDnE";
4199 break;
4200 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004201
Guy Benyei11169dd2012-12-18 14:30:41 +00004202 case Expr::PackExpansionExprClass:
4203 Out << "sp";
4204 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4205 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004206
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00004208 auto *SPE = cast<SizeOfPackExpr>(E);
4209 if (SPE->isPartiallySubstituted()) {
4210 Out << "sP";
4211 for (const auto &A : SPE->getPartialArguments())
4212 mangleTemplateArg(A);
4213 Out << "E";
4214 break;
4215 }
4216
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00004218 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00004219 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4220 mangleTemplateParameter(TTP->getIndex());
4221 else if (const NonTypeTemplateParmDecl *NTTP
4222 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4223 mangleTemplateParameter(NTTP->getIndex());
4224 else if (const TemplateTemplateParmDecl *TempTP
4225 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4226 mangleTemplateParameter(TempTP->getIndex());
4227 else
4228 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4229 break;
4230 }
Richard Smith0f0af192014-11-08 05:07:16 +00004231
Guy Benyei11169dd2012-12-18 14:30:41 +00004232 case Expr::MaterializeTemporaryExprClass: {
4233 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
4234 break;
4235 }
Richard Smith0f0af192014-11-08 05:07:16 +00004236
4237 case Expr::CXXFoldExprClass: {
4238 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00004239 if (FE->isLeftFold())
4240 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00004241 else
Richard Smith8e6923b2014-11-10 19:44:15 +00004242 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00004243
4244 if (FE->getOperator() == BO_PtrMemD)
4245 Out << "ds";
4246 else
4247 mangleOperatorName(
4248 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4249 /*Arity=*/2);
4250
4251 if (FE->getLHS())
4252 mangleExpression(FE->getLHS());
4253 if (FE->getRHS())
4254 mangleExpression(FE->getRHS());
4255 break;
4256 }
4257
Guy Benyei11169dd2012-12-18 14:30:41 +00004258 case Expr::CXXThisExprClass:
4259 Out << "fpT";
4260 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00004261
4262 case Expr::CoawaitExprClass:
4263 // FIXME: Propose a non-vendor mangling.
4264 Out << "v18co_await";
4265 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4266 break;
4267
Eric Fiselier20f25cb2017-03-06 23:38:15 +00004268 case Expr::DependentCoawaitExprClass:
4269 // FIXME: Propose a non-vendor mangling.
4270 Out << "v18co_await";
4271 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4272 break;
4273
Richard Smith9f690bd2015-10-27 06:02:45 +00004274 case Expr::CoyieldExprClass:
4275 // FIXME: Propose a non-vendor mangling.
4276 Out << "v18co_yield";
4277 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4278 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 }
4280}
4281
4282/// Mangle an expression which refers to a parameter variable.
4283///
4284/// <expression> ::= <function-param>
4285/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4286/// <function-param> ::= fp <top-level CV-qualifiers>
4287/// <parameter-2 non-negative number> _ # L == 0, I > 0
4288/// <function-param> ::= fL <L-1 non-negative number>
4289/// p <top-level CV-qualifiers> _ # L > 0, I == 0
4290/// <function-param> ::= fL <L-1 non-negative number>
4291/// p <top-level CV-qualifiers>
4292/// <I-1 non-negative number> _ # L > 0, I > 0
4293///
4294/// L is the nesting depth of the parameter, defined as 1 if the
4295/// parameter comes from the innermost function prototype scope
4296/// enclosing the current context, 2 if from the next enclosing
4297/// function prototype scope, and so on, with one special case: if
4298/// we've processed the full parameter clause for the innermost
4299/// function type, then L is one less. This definition conveniently
4300/// makes it irrelevant whether a function's result type was written
4301/// trailing or leading, but is otherwise overly complicated; the
4302/// numbering was first designed without considering references to
4303/// parameter in locations other than return types, and then the
4304/// mangling had to be generalized without changing the existing
4305/// manglings.
4306///
4307/// I is the zero-based index of the parameter within its parameter
4308/// declaration clause. Note that the original ABI document describes
4309/// this using 1-based ordinals.
4310void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4311 unsigned parmDepth = parm->getFunctionScopeDepth();
4312 unsigned parmIndex = parm->getFunctionScopeIndex();
4313
4314 // Compute 'L'.
4315 // parmDepth does not include the declaring function prototype.
4316 // FunctionTypeDepth does account for that.
4317 assert(parmDepth < FunctionTypeDepth.getDepth());
4318 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4319 if (FunctionTypeDepth.isInResultType())
4320 nestingDepth--;
4321
4322 if (nestingDepth == 0) {
4323 Out << "fp";
4324 } else {
4325 Out << "fL" << (nestingDepth - 1) << 'p';
4326 }
4327
4328 // Top-level qualifiers. We don't have to worry about arrays here,
4329 // because parameters declared as arrays should already have been
4330 // transformed to have pointer type. FIXME: apparently these don't
4331 // get mangled if used as an rvalue of a known non-class type?
4332 assert(!parm->getType()->isArrayType()
4333 && "parameter's type is still an array type?");
Andrew Gozillon572bbb02017-10-02 06:25:51 +00004334
4335 if (const DependentAddressSpaceType *DAST =
4336 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4337 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4338 } else {
4339 mangleQualifiers(parm->getType().getQualifiers());
4340 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004341
4342 // Parameter index.
4343 if (parmIndex != 0) {
4344 Out << (parmIndex - 1);
4345 }
4346 Out << '_';
4347}
4348
Richard Smith5179eb72016-06-28 19:03:57 +00004349void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4350 const CXXRecordDecl *InheritedFrom) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 // <ctor-dtor-name> ::= C1 # complete object constructor
4352 // ::= C2 # base object constructor
Richard Smith5179eb72016-06-28 19:03:57 +00004353 // ::= CI1 <type> # complete inheriting constructor
4354 // ::= CI2 <type> # base inheriting constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00004355 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004356 // In addition, C5 is a comdat name with C1 and C2 in it.
Richard Smith5179eb72016-06-28 19:03:57 +00004357 Out << 'C';
4358 if (InheritedFrom)
4359 Out << 'I';
Guy Benyei11169dd2012-12-18 14:30:41 +00004360 switch (T) {
4361 case Ctor_Complete:
Richard Smith5179eb72016-06-28 19:03:57 +00004362 Out << '1';
Guy Benyei11169dd2012-12-18 14:30:41 +00004363 break;
4364 case Ctor_Base:
Richard Smith5179eb72016-06-28 19:03:57 +00004365 Out << '2';
Guy Benyei11169dd2012-12-18 14:30:41 +00004366 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004367 case Ctor_Comdat:
Richard Smith5179eb72016-06-28 19:03:57 +00004368 Out << '5';
Guy Benyei11169dd2012-12-18 14:30:41 +00004369 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00004370 case Ctor_DefaultClosure:
4371 case Ctor_CopyingClosure:
4372 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00004373 }
Richard Smith5179eb72016-06-28 19:03:57 +00004374 if (InheritedFrom)
4375 mangleName(InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00004376}
4377
4378void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4379 // <ctor-dtor-name> ::= D0 # deleting destructor
4380 // ::= D1 # complete object destructor
4381 // ::= D2 # base object destructor
4382 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004383 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00004384 switch (T) {
4385 case Dtor_Deleting:
4386 Out << "D0";
4387 break;
4388 case Dtor_Complete:
4389 Out << "D1";
4390 break;
4391 case Dtor_Base:
4392 Out << "D2";
4393 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004394 case Dtor_Comdat:
4395 Out << "D5";
4396 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004397 }
4398}
4399
James Y Knight04ec5bf2015-12-24 02:59:37 +00004400void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4401 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004402 // <template-args> ::= I <template-arg>+ E
4403 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00004404 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4405 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00004406 Out << 'E';
4407}
4408
4409void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4410 // <template-args> ::= I <template-arg>+ E
4411 Out << 'I';
4412 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4413 mangleTemplateArg(AL[i]);
4414 Out << 'E';
4415}
4416
4417void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4418 unsigned NumTemplateArgs) {
4419 // <template-args> ::= I <template-arg>+ E
4420 Out << 'I';
4421 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4422 mangleTemplateArg(TemplateArgs[i]);
4423 Out << 'E';
4424}
4425
4426void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4427 // <template-arg> ::= <type> # type or template
4428 // ::= X <expression> E # expression
4429 // ::= <expr-primary> # simple expressions
4430 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00004431 if (!A.isInstantiationDependent() || A.isDependent())
4432 A = Context.getASTContext().getCanonicalTemplateArgument(A);
Fangrui Song6907ce22018-07-30 19:24:48 +00004433
Guy Benyei11169dd2012-12-18 14:30:41 +00004434 switch (A.getKind()) {
4435 case TemplateArgument::Null:
4436 llvm_unreachable("Cannot mangle NULL template argument");
Fangrui Song6907ce22018-07-30 19:24:48 +00004437
Guy Benyei11169dd2012-12-18 14:30:41 +00004438 case TemplateArgument::Type:
4439 mangleType(A.getAsType());
4440 break;
4441 case TemplateArgument::Template:
4442 // This is mangled as <type>.
4443 mangleType(A.getAsTemplate());
4444 break;
4445 case TemplateArgument::TemplateExpansion:
4446 // <type> ::= Dp <type> # pack expansion (C++0x)
4447 Out << "Dp";
4448 mangleType(A.getAsTemplateOrTemplatePattern());
4449 break;
4450 case TemplateArgument::Expression: {
4451 // It's possible to end up with a DeclRefExpr here in certain
4452 // dependent cases, in which case we should mangle as a
4453 // declaration.
4454 const Expr *E = A.getAsExpr()->IgnoreParens();
4455 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4456 const ValueDecl *D = DRE->getDecl();
4457 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00004458 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004459 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004460 Out << 'E';
4461 break;
4462 }
4463 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004464
Guy Benyei11169dd2012-12-18 14:30:41 +00004465 Out << 'X';
4466 mangleExpression(E);
4467 Out << 'E';
4468 break;
4469 }
4470 case TemplateArgument::Integral:
4471 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4472 break;
4473 case TemplateArgument::Declaration: {
4474 // <expr-primary> ::= L <mangled-name> E # external name
4475 // Clang produces AST's where pointer-to-member-function expressions
4476 // and pointer-to-function expressions are represented as a declaration not
4477 // an expression. We compensate for it here to produce the correct mangling.
4478 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00004479 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00004480 if (compensateMangling) {
4481 Out << 'X';
4482 mangleOperatorName(OO_Amp, 1);
4483 }
4484
4485 Out << 'L';
4486 // References to external entities use the mangled name; if the name would
Nico Weberfb420782016-05-25 14:15:08 +00004487 // not normally be mangled then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00004488 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004489 Out << 'E';
4490
4491 if (compensateMangling)
4492 Out << 'E';
4493
4494 break;
4495 }
4496 case TemplateArgument::NullPtr: {
4497 // <expr-primary> ::= L <type> 0 E
4498 Out << 'L';
4499 mangleType(A.getNullPtrType());
4500 Out << "0E";
4501 break;
4502 }
4503 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00004504 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00004505 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00004506 for (const auto &P : A.pack_elements())
4507 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00004508 Out << 'E';
4509 }
4510 }
4511}
4512
4513void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4514 // <template-param> ::= T_ # first template parameter
4515 // ::= T <parameter-2 non-negative number> _
4516 if (Index == 0)
4517 Out << "T_";
4518 else
4519 Out << 'T' << (Index - 1) << '_';
4520}
4521
David Majnemer3b3bdb52014-05-06 22:49:16 +00004522void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4523 if (SeqID == 1)
4524 Out << '0';
4525 else if (SeqID > 1) {
4526 SeqID--;
4527
4528 // <seq-id> is encoded in base-36, using digits and upper case letters.
4529 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00004530 MutableArrayRef<char> BufferRef(Buffer);
4531 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00004532
4533 for (; SeqID != 0; SeqID /= 36) {
4534 unsigned C = SeqID % 36;
4535 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4536 }
4537
4538 Out.write(I.base(), I - BufferRef.rbegin());
4539 }
4540 Out << '_';
4541}
4542
Guy Benyei11169dd2012-12-18 14:30:41 +00004543void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4544 bool result = mangleSubstitution(tname);
4545 assert(result && "no existing substitution for template name");
4546 (void) result;
4547}
4548
4549// <substitution> ::= S <seq-id> _
4550// ::= S_
4551bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4552 // Try one of the standard substitutions first.
4553 if (mangleStandardSubstitution(ND))
4554 return true;
4555
4556 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4557 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4558}
4559
Justin Bognere8d762e2015-05-22 06:48:13 +00004560/// Determine whether the given type has any qualifiers that are relevant for
4561/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00004562static bool hasMangledSubstitutionQualifiers(QualType T) {
4563 Qualifiers Qs = T.getQualifiers();
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00004564 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
Guy Benyei11169dd2012-12-18 14:30:41 +00004565}
4566
4567bool CXXNameMangler::mangleSubstitution(QualType T) {
4568 if (!hasMangledSubstitutionQualifiers(T)) {
4569 if (const RecordType *RT = T->getAs<RecordType>())
4570 return mangleSubstitution(RT->getDecl());
4571 }
4572
4573 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4574
4575 return mangleSubstitution(TypePtr);
4576}
4577
4578bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4579 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4580 return mangleSubstitution(TD);
Fangrui Song6907ce22018-07-30 19:24:48 +00004581
Guy Benyei11169dd2012-12-18 14:30:41 +00004582 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4583 return mangleSubstitution(
4584 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4585}
4586
4587bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4588 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4589 if (I == Substitutions.end())
4590 return false;
4591
4592 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00004593 Out << 'S';
4594 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00004595
4596 return true;
4597}
4598
4599static bool isCharType(QualType T) {
4600 if (T.isNull())
4601 return false;
4602
4603 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4604 T->isSpecificBuiltinType(BuiltinType::Char_U);
4605}
4606
Justin Bognere8d762e2015-05-22 06:48:13 +00004607/// Returns whether a given type is a template specialization of a given name
4608/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00004609static bool isCharSpecialization(QualType T, const char *Name) {
4610 if (T.isNull())
4611 return false;
4612
4613 const RecordType *RT = T->getAs<RecordType>();
4614 if (!RT)
4615 return false;
4616
4617 const ClassTemplateSpecializationDecl *SD =
4618 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4619 if (!SD)
4620 return false;
4621
4622 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4623 return false;
4624
4625 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4626 if (TemplateArgs.size() != 1)
4627 return false;
4628
4629 if (!isCharType(TemplateArgs[0].getAsType()))
4630 return false;
4631
4632 return SD->getIdentifier()->getName() == Name;
4633}
4634
4635template <std::size_t StrLen>
4636static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4637 const char (&Str)[StrLen]) {
4638 if (!SD->getIdentifier()->isStr(Str))
4639 return false;
4640
4641 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4642 if (TemplateArgs.size() != 2)
4643 return false;
4644
4645 if (!isCharType(TemplateArgs[0].getAsType()))
4646 return false;
4647
4648 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4649 return false;
4650
4651 return true;
4652}
4653
4654bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4655 // <substitution> ::= St # ::std::
4656 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4657 if (isStd(NS)) {
4658 Out << "St";
4659 return true;
4660 }
4661 }
4662
4663 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4664 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4665 return false;
4666
4667 // <substitution> ::= Sa # ::std::allocator
4668 if (TD->getIdentifier()->isStr("allocator")) {
4669 Out << "Sa";
4670 return true;
4671 }
4672
4673 // <<substitution> ::= Sb # ::std::basic_string
4674 if (TD->getIdentifier()->isStr("basic_string")) {
4675 Out << "Sb";
4676 return true;
4677 }
4678 }
4679
4680 if (const ClassTemplateSpecializationDecl *SD =
4681 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4682 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4683 return false;
4684
4685 // <substitution> ::= Ss # ::std::basic_string<char,
4686 // ::std::char_traits<char>,
4687 // ::std::allocator<char> >
4688 if (SD->getIdentifier()->isStr("basic_string")) {
4689 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4690
4691 if (TemplateArgs.size() != 3)
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 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4701 return false;
4702
4703 Out << "Ss";
4704 return true;
4705 }
4706
4707 // <substitution> ::= Si # ::std::basic_istream<char,
4708 // ::std::char_traits<char> >
4709 if (isStreamCharSpecialization(SD, "basic_istream")) {
4710 Out << "Si";
4711 return true;
4712 }
4713
4714 // <substitution> ::= So # ::std::basic_ostream<char,
4715 // ::std::char_traits<char> >
4716 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4717 Out << "So";
4718 return true;
4719 }
4720
4721 // <substitution> ::= Sd # ::std::basic_iostream<char,
4722 // ::std::char_traits<char> >
4723 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4724 Out << "Sd";
4725 return true;
4726 }
4727 }
4728 return false;
4729}
4730
4731void CXXNameMangler::addSubstitution(QualType T) {
4732 if (!hasMangledSubstitutionQualifiers(T)) {
4733 if (const RecordType *RT = T->getAs<RecordType>()) {
4734 addSubstitution(RT->getDecl());
4735 return;
4736 }
4737 }
4738
4739 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4740 addSubstitution(TypePtr);
4741}
4742
4743void CXXNameMangler::addSubstitution(TemplateName Template) {
4744 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4745 return addSubstitution(TD);
Fangrui Song6907ce22018-07-30 19:24:48 +00004746
Guy Benyei11169dd2012-12-18 14:30:41 +00004747 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4748 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4749}
4750
4751void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4752 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4753 Substitutions[Ptr] = SeqID++;
4754}
4755
Dmitry Polukhinfda467b2016-09-21 08:27:03 +00004756void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4757 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4758 if (Other->SeqID > SeqID) {
4759 Substitutions.swap(Other->Substitutions);
4760 SeqID = Other->SeqID;
4761 }
4762}
4763
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004764CXXNameMangler::AbiTagList
4765CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4766 // When derived abi tags are disabled there is no need to make any list.
4767 if (DisableDerivedAbiTags)
4768 return AbiTagList();
4769
4770 llvm::raw_null_ostream NullOutStream;
4771 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4772 TrackReturnTypeTags.disableDerivedAbiTags();
4773
4774 const FunctionProtoType *Proto =
4775 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004776 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004777 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4778 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4779 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004780 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004781
4782 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4783}
4784
4785CXXNameMangler::AbiTagList
4786CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4787 // When derived abi tags are disabled there is no need to make any list.
4788 if (DisableDerivedAbiTags)
4789 return AbiTagList();
4790
4791 llvm::raw_null_ostream NullOutStream;
4792 CXXNameMangler TrackVariableType(*this, NullOutStream);
4793 TrackVariableType.disableDerivedAbiTags();
4794
4795 TrackVariableType.mangleType(VD->getType());
4796
4797 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4798}
4799
4800bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4801 const VarDecl *VD) {
4802 llvm::raw_null_ostream NullOutStream;
4803 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4804 TrackAbiTags.mangle(VD);
4805 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4806}
4807
Guy Benyei11169dd2012-12-18 14:30:41 +00004808//
4809
Justin Bognere8d762e2015-05-22 06:48:13 +00004810/// Mangles the name of the declaration D and emits that name to the given
4811/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004812///
4813/// If the declaration D requires a mangled name, this routine will emit that
4814/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4815/// and this routine will return false. In this case, the caller should just
4816/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4817/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004818void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4819 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004820 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4821 "Invalid mangleName() call, argument is not a variable or function!");
4822 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4823 "Invalid mangleName() call on 'structor decl!");
4824
4825 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4826 getASTContext().getSourceManager(),
4827 "Mangling declaration");
4828
4829 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004830 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004831}
4832
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004833void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4834 CXXCtorType Type,
4835 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004836 CXXNameMangler Mangler(*this, Out, D, Type);
4837 Mangler.mangle(D);
4838}
4839
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004840void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4841 CXXDtorType Type,
4842 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004843 CXXNameMangler Mangler(*this, Out, D, Type);
4844 Mangler.mangle(D);
4845}
4846
Rafael Espindola1e4df922014-09-16 15:18:21 +00004847void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4848 raw_ostream &Out) {
4849 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4850 Mangler.mangle(D);
4851}
4852
4853void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4854 raw_ostream &Out) {
4855 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4856 Mangler.mangle(D);
4857}
4858
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004859void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4860 const ThunkInfo &Thunk,
4861 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004862 // <special-name> ::= T <call-offset> <base encoding>
4863 // # base is the nominal target function of thunk
4864 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4865 // # base is the nominal target function of thunk
4866 // # first call-offset is 'this' adjustment
4867 // # second call-offset is result adjustment
Fangrui Song6907ce22018-07-30 19:24:48 +00004868
Guy Benyei11169dd2012-12-18 14:30:41 +00004869 assert(!isa<CXXDestructorDecl>(MD) &&
4870 "Use mangleCXXDtor for destructor decls!");
4871 CXXNameMangler Mangler(*this, Out);
4872 Mangler.getStream() << "_ZT";
4873 if (!Thunk.Return.isEmpty())
4874 Mangler.getStream() << 'c';
Fangrui Song6907ce22018-07-30 19:24:48 +00004875
Guy Benyei11169dd2012-12-18 14:30:41 +00004876 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004877 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4878 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4879
Guy Benyei11169dd2012-12-18 14:30:41 +00004880 // Mangle the return pointer adjustment if there is one.
4881 if (!Thunk.Return.isEmpty())
4882 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004883 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4884
Guy Benyei11169dd2012-12-18 14:30:41 +00004885 Mangler.mangleFunctionEncoding(MD);
4886}
4887
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004888void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4889 const CXXDestructorDecl *DD, CXXDtorType Type,
4890 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004891 // <special-name> ::= T <call-offset> <base encoding>
4892 // # base is the nominal target function of thunk
4893 CXXNameMangler Mangler(*this, Out, DD, Type);
4894 Mangler.getStream() << "_ZT";
4895
4896 // Mangle the 'this' pointer adjustment.
Fangrui Song6907ce22018-07-30 19:24:48 +00004897 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004898 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004899
4900 Mangler.mangleFunctionEncoding(DD);
4901}
4902
Justin Bognere8d762e2015-05-22 06:48:13 +00004903/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004904void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4905 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004906 // <special-name> ::= GV <object name> # Guard variable for one-time
4907 // # initialization
4908 CXXNameMangler Mangler(*this, Out);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004909 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4910 // be a bug that is fixed in trunk.
Guy Benyei11169dd2012-12-18 14:30:41 +00004911 Mangler.getStream() << "_ZGV";
4912 Mangler.mangleName(D);
4913}
4914
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004915void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4916 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004917 // These symbols are internal in the Itanium ABI, so the names don't matter.
4918 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4919 // avoid duplicate symbols.
4920 Out << "__cxx_global_var_init";
4921}
4922
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004923void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4924 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004925 // Prefix the mangling of D with __dtor_.
4926 CXXNameMangler Mangler(*this, Out);
4927 Mangler.getStream() << "__dtor_";
4928 if (shouldMangleDeclName(D))
4929 Mangler.mangle(D);
4930 else
4931 Mangler.getStream() << D->getName();
4932}
4933
Reid Kleckner1d59f992015-01-22 01:36:17 +00004934void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4935 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4936 CXXNameMangler Mangler(*this, Out);
4937 Mangler.getStream() << "__filt_";
4938 if (shouldMangleDeclName(EnclosingDecl))
4939 Mangler.mangle(EnclosingDecl);
4940 else
4941 Mangler.getStream() << EnclosingDecl->getName();
4942}
4943
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004944void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4945 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4946 CXXNameMangler Mangler(*this, Out);
4947 Mangler.getStream() << "__fin_";
4948 if (shouldMangleDeclName(EnclosingDecl))
4949 Mangler.mangle(EnclosingDecl);
4950 else
4951 Mangler.getStream() << EnclosingDecl->getName();
4952}
4953
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004954void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4955 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004956 // <special-name> ::= TH <object name>
4957 CXXNameMangler Mangler(*this, Out);
4958 Mangler.getStream() << "_ZTH";
4959 Mangler.mangleName(D);
4960}
4961
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004962void
4963ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4964 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004965 // <special-name> ::= TW <object name>
4966 CXXNameMangler Mangler(*this, Out);
4967 Mangler.getStream() << "_ZTW";
4968 Mangler.mangleName(D);
4969}
4970
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004971void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004972 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004973 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004974 // We match the GCC mangling here.
4975 // <special-name> ::= GR <object name>
4976 CXXNameMangler Mangler(*this, Out);
4977 Mangler.getStream() << "_ZGR";
4978 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004979 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004980 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004981}
4982
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004983void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4984 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004985 // <special-name> ::= TV <type> # virtual table
4986 CXXNameMangler Mangler(*this, Out);
4987 Mangler.getStream() << "_ZTV";
4988 Mangler.mangleNameOrStandardSubstitution(RD);
4989}
4990
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004991void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4992 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004993 // <special-name> ::= TT <type> # VTT structure
4994 CXXNameMangler Mangler(*this, Out);
4995 Mangler.getStream() << "_ZTT";
4996 Mangler.mangleNameOrStandardSubstitution(RD);
4997}
4998
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004999void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
5000 int64_t Offset,
5001 const CXXRecordDecl *Type,
5002 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005003 // <special-name> ::= TC <type> <offset number> _ <base type>
5004 CXXNameMangler Mangler(*this, Out);
5005 Mangler.getStream() << "_ZTC";
5006 Mangler.mangleNameOrStandardSubstitution(RD);
5007 Mangler.getStream() << Offset;
5008 Mangler.getStream() << '_';
5009 Mangler.mangleNameOrStandardSubstitution(Type);
5010}
5011
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005012void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005013 // <special-name> ::= TI <type> # typeinfo structure
5014 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
5015 CXXNameMangler Mangler(*this, Out);
5016 Mangler.getStream() << "_ZTI";
5017 Mangler.mangleType(Ty);
5018}
5019
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005020void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
5021 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005022 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
5023 CXXNameMangler Mangler(*this, Out);
5024 Mangler.getStream() << "_ZTS";
5025 Mangler.mangleType(Ty);
5026}
5027
Reid Klecknercc99e262013-11-19 23:23:00 +00005028void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
5029 mangleCXXRTTIName(Ty, Out);
5030}
5031
David Majnemer58e5bee2014-03-24 21:43:36 +00005032void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
5033 llvm_unreachable("Can't mangle string literals");
5034}
5035
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005036ItaniumMangleContext *
5037ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
5038 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00005039}