blob: d6d3792b6af3f7458b1b87b47cd2586c5d7ae5e0 [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) {
49 // The ABI assumes that lambda closure types that occur within
50 // 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
52 // not the case: the lambda closure type ends up living in the context
53 // 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 }
Guy Benyei11169dd2012-12-18 14:30:41 +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
326 std::sort(TagList.begin(), TagList.end());
327 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
328
329 writeSortedUniqueAbiTags(Out, TagList);
330 }
331
332 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
333 void setUsedAbiTags(const AbiTagList &AbiTags) {
334 UsedAbiTags = AbiTags;
335 }
336
337 const AbiTagList &getEmittedAbiTags() const {
338 return EmittedAbiTags;
339 }
340
341 const AbiTagList &getSortedUniqueUsedAbiTags() {
342 std::sort(UsedAbiTags.begin(), UsedAbiTags.end());
343 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
344 UsedAbiTags.end());
345 return UsedAbiTags;
346 }
347
348 private:
349 //! All abi tags used implicitly or explicitly.
350 AbiTagList UsedAbiTags;
351 //! All explicit abi tags (i.e. not from namespace).
352 AbiTagList EmittedAbiTags;
353
354 AbiTagState *&LinkHead;
355 AbiTagState *Parent = nullptr;
356
357 void pop() {
358 assert(LinkHead == this &&
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);
444
445private:
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);
Tim Northover2fe823a2013-08-01 09:23:19 +0000542 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000543
544 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000545 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000546 void mangleMemberExpr(const Expr *base, bool isArrow,
547 NestedNameSpecifier *qualifier,
548 NamedDecl *firstQualifierLookup,
549 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000550 const TemplateArgumentLoc *TemplateArgs,
551 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000552 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000553 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000554 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000555 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
Richard Smith5179eb72016-06-28 19:03:57 +0000556 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +0000557 void mangleCXXDtorType(CXXDtorType T);
558
James Y Knight04ec5bf2015-12-24 02:59:37 +0000559 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
560 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000561 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
562 unsigned NumTemplateArgs);
563 void mangleTemplateArgs(const TemplateArgumentList &AL);
564 void mangleTemplateArg(TemplateArgument A);
565
566 void mangleTemplateParameter(unsigned Index);
567
568 void mangleFunctionParam(const ParmVarDecl *parm);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000569
570 void writeAbiTags(const NamedDecl *ND,
571 const AbiTagList *AdditionalAbiTags);
572
573 // Returns sorted unique list of ABI tags.
574 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
575 // Returns sorted unique list of ABI tags.
576 AbiTagList makeVariableTypeTags(const VarDecl *VD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000577};
578
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000579}
Guy Benyei11169dd2012-12-18 14:30:41 +0000580
Rafael Espindola002667c2013-10-16 01:40:34 +0000581bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000582 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000583 if (FD) {
584 LanguageLinkage L = FD->getLanguageLinkage();
585 // Overloadable functions need mangling.
586 if (FD->hasAttr<OverloadableAttr>())
587 return true;
588
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000589 // "main" is not mangled.
590 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000591 return false;
592
593 // C++ functions and those whose names are not a simple identifier need
594 // mangling.
595 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
596 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000597
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000598 // C functions are not mangled.
599 if (L == CLanguageLinkage)
600 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000601 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000602
603 // Otherwise, no mangling is done outside C++ mode.
604 if (!getASTContext().getLangOpts().CPlusPlus)
605 return false;
606
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000607 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithbdb84f32016-07-22 23:36:59 +0000608 if (VD && !isa<DecompositionDecl>(D)) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000609 // C variables are not mangled.
610 if (VD->isExternC())
611 return false;
612
613 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000614 const DeclContext *DC = getEffectiveDeclContext(D);
615 // Check for extern variable declared locally.
616 if (DC->isFunctionOrMethod() && D->hasLinkage())
617 while (!DC->isNamespace() && !DC->isTranslationUnit())
618 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000619 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000620 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
Larisse Voufo39a1e502013-08-06 01:03:05 +0000621 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000622 return false;
623 }
624
Guy Benyei11169dd2012-12-18 14:30:41 +0000625 return true;
626}
627
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000628void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
629 const AbiTagList *AdditionalAbiTags) {
630 assert(AbiTags && "require AbiTagState");
631 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
632}
633
634void CXXNameMangler::mangleSourceNameWithAbiTags(
635 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
636 mangleSourceName(ND->getIdentifier());
637 writeAbiTags(ND, AdditionalAbiTags);
638}
639
David Majnemer7ff7eb72015-02-18 07:47:09 +0000640void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000641 // <mangled-name> ::= _Z <encoding>
642 // ::= <data name>
643 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000644 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000645 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
646 mangleFunctionEncoding(FD);
647 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
648 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000649 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
650 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000651 else
652 mangleName(cast<FieldDecl>(D));
653}
654
655void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
656 // <encoding> ::= <function name> <bare-function-type>
Guy Benyei11169dd2012-12-18 14:30:41 +0000657
658 // Don't mangle in the type if this isn't a decl we should typically mangle.
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000659 if (!Context.shouldMangleDeclName(FD)) {
660 mangleName(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000661 return;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000662 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000663
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000664 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
665 if (ReturnTypeAbiTags.empty()) {
666 // There are no tags for return type, the simplest case.
667 mangleName(FD);
668 mangleFunctionEncodingBareType(FD);
669 return;
670 }
671
672 // Mangle function name and encoding to temporary buffer.
673 // We have to output name and encoding to the same mangler to get the same
674 // substitution as it will be in final mangling.
675 SmallString<256> FunctionEncodingBuf;
676 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
677 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
678 // Output name of the function.
679 FunctionEncodingMangler.disableDerivedAbiTags();
680 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
681
682 // Remember length of the function name in the buffer.
683 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
684 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
685
686 // Get tags from return type that are not present in function name or
687 // encoding.
688 const AbiTagList &UsedAbiTags =
689 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
690 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
691 AdditionalAbiTags.erase(
692 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
693 UsedAbiTags.begin(), UsedAbiTags.end(),
694 AdditionalAbiTags.begin()),
695 AdditionalAbiTags.end());
696
697 // Output name with implicit tags and function encoding from temporary buffer.
698 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
699 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000700
701 // Function encoding could create new substitutions so we have to add
702 // temp mangled substitutions to main mangler.
703 extendSubstitutions(&FunctionEncodingMangler);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000704}
705
706void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000707 if (FD->hasAttr<EnableIfAttr>()) {
708 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
709 Out << "Ua9enable_ifI";
710 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
711 // it here.
712 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
713 E = FD->getAttrs().rend();
714 I != E; ++I) {
715 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
716 if (!EIA)
717 continue;
718 Out << 'X';
719 mangleExpression(EIA->getCond());
720 Out << 'E';
721 }
722 Out << 'E';
723 FunctionTypeDepth.pop(Saved);
724 }
725
Richard Smith5179eb72016-06-28 19:03:57 +0000726 // When mangling an inheriting constructor, the bare function type used is
727 // that of the inherited constructor.
728 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
729 if (auto Inherited = CD->getInheritedConstructor())
730 FD = Inherited.getConstructor();
731
Guy Benyei11169dd2012-12-18 14:30:41 +0000732 // Whether the mangling of a function type includes the return type depends on
733 // the context and the nature of the function. The rules for deciding whether
734 // the return type is included are:
735 //
736 // 1. Template functions (names or types) have return types encoded, with
737 // the exceptions listed below.
738 // 2. Function types not appearing as part of a function name mangling,
739 // e.g. parameters, pointer types, etc., have return type encoded, with the
740 // exceptions listed below.
741 // 3. Non-template function names do not have return types encoded.
742 //
743 // The exceptions mentioned in (1) and (2) above, for which the return type is
744 // never included, are
745 // 1. Constructors.
746 // 2. Destructors.
747 // 3. Conversion operator functions, e.g. operator int.
748 bool MangleReturnType = false;
749 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
750 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
751 isa<CXXConversionDecl>(FD)))
752 MangleReturnType = true;
753
754 // Mangle the type of the primary template.
755 FD = PrimaryTemplate->getTemplatedDecl();
756 }
757
John McCall07daf722016-03-01 22:18:03 +0000758 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000759 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000760}
761
762static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
763 while (isa<LinkageSpecDecl>(DC)) {
764 DC = getEffectiveParentContext(DC);
765 }
766
767 return DC;
768}
769
Justin Bognere8d762e2015-05-22 06:48:13 +0000770/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000771static bool isStd(const NamespaceDecl *NS) {
772 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
773 ->isTranslationUnit())
774 return false;
775
776 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
777 return II && II->isStr("std");
778}
779
780// isStdNamespace - Return whether a given decl context is a toplevel 'std'
781// namespace.
782static bool isStdNamespace(const DeclContext *DC) {
783 if (!DC->isNamespace())
784 return false;
785
786 return isStd(cast<NamespaceDecl>(DC));
787}
788
789static const TemplateDecl *
790isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
791 // Check if we have a function template.
Richard Smith5179eb72016-06-28 19:03:57 +0000792 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000793 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
794 TemplateArgs = FD->getTemplateSpecializationArgs();
795 return TD;
796 }
797 }
798
799 // Check if we have a class template.
800 if (const ClassTemplateSpecializationDecl *Spec =
801 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
802 TemplateArgs = &Spec->getTemplateArgs();
803 return Spec->getSpecializedTemplate();
804 }
805
Larisse Voufo39a1e502013-08-06 01:03:05 +0000806 // Check if we have a variable template.
807 if (const VarTemplateSpecializationDecl *Spec =
808 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
809 TemplateArgs = &Spec->getTemplateArgs();
810 return Spec->getSpecializedTemplate();
811 }
812
Craig Topper36250ad2014-05-12 05:36:57 +0000813 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000814}
815
Guy Benyei11169dd2012-12-18 14:30:41 +0000816void CXXNameMangler::mangleName(const NamedDecl *ND) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000817 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
818 // Variables should have implicit tags from its type.
819 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
820 if (VariableTypeAbiTags.empty()) {
821 // Simple case no variable type tags.
822 mangleNameWithAbiTags(VD, nullptr);
823 return;
824 }
825
826 // Mangle variable name to null stream to collect tags.
827 llvm::raw_null_ostream NullOutStream;
828 CXXNameMangler VariableNameMangler(*this, NullOutStream);
829 VariableNameMangler.disableDerivedAbiTags();
830 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
831
832 // Get tags from variable type that are not present in its name.
833 const AbiTagList &UsedAbiTags =
834 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
835 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
836 AdditionalAbiTags.erase(
837 std::set_difference(VariableTypeAbiTags.begin(),
838 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
839 UsedAbiTags.end(), AdditionalAbiTags.begin()),
840 AdditionalAbiTags.end());
841
842 // Output name with implicit tags.
843 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
844 } else {
845 mangleNameWithAbiTags(ND, nullptr);
846 }
847}
848
849void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
850 const AbiTagList *AdditionalAbiTags) {
Richard Smithdd8b5332017-09-04 05:37:53 +0000851 // <name> ::= [<module-name>] <nested-name>
852 // ::= [<module-name>] <unscoped-name>
853 // ::= [<module-name>] <unscoped-template-name> <template-args>
Guy Benyei11169dd2012-12-18 14:30:41 +0000854 // ::= <local-name>
855 //
856 const DeclContext *DC = getEffectiveDeclContext(ND);
857
858 // If this is an extern variable declared locally, the relevant DeclContext
859 // is that of the containing namespace, or the translation unit.
860 // FIXME: This is a hack; extern variables declared locally should have
861 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000862 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000863 while (!DC->isNamespace() && !DC->isTranslationUnit())
864 DC = getEffectiveParentContext(DC);
865 else if (GetLocalClassDecl(ND)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000866 mangleLocalName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000867 return;
868 }
869
870 DC = IgnoreLinkageSpecDecls(DC);
871
Richard Smithdd8b5332017-09-04 05:37:53 +0000872 if (isLocalContainerContext(DC)) {
873 mangleLocalName(ND, AdditionalAbiTags);
874 return;
875 }
876
877 // Do not mangle the owning module for an external linkage declaration.
878 // This enables backwards-compatibility with non-modular code, and is
879 // a valid choice since conflicts are not permitted by C++ Modules TS
880 // [basic.def.odr]/6.2.
881 if (!ND->hasExternalFormalLinkage())
882 if (Module *M = ND->getOwningModuleForLinkage())
883 mangleModuleName(M);
884
Guy Benyei11169dd2012-12-18 14:30:41 +0000885 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
886 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000887 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000888 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000889 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000890 mangleTemplateArgs(*TemplateArgs);
891 return;
892 }
893
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000894 mangleUnscopedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000895 return;
896 }
897
Richard Smithdd8b5332017-09-04 05:37:53 +0000898 mangleNestedName(ND, DC, AdditionalAbiTags);
899}
900
901void CXXNameMangler::mangleModuleName(const Module *M) {
902 // Implement the C++ Modules TS name mangling proposal; see
903 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
904 //
905 // <module-name> ::= W <unscoped-name>+ E
906 // ::= W <module-subst> <unscoped-name>* E
907 Out << 'W';
908 mangleModuleNamePrefix(M->Name);
909 Out << 'E';
910}
911
912void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
913 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
914 // ::= W <seq-id - 10> _ # otherwise
915 auto It = ModuleSubstitutions.find(Name);
916 if (It != ModuleSubstitutions.end()) {
917 if (It->second < 10)
918 Out << '_' << static_cast<char>('0' + It->second);
919 else
920 Out << 'W' << (It->second - 10) << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +0000921 return;
922 }
923
Richard Smithdd8b5332017-09-04 05:37:53 +0000924 // FIXME: Preserve hierarchy in module names rather than flattening
925 // them to strings; use Module*s as substitution keys.
926 auto Parts = Name.rsplit('.');
927 if (Parts.second.empty())
928 Parts.second = Parts.first;
929 else
930 mangleModuleNamePrefix(Parts.first);
931
932 Out << Parts.second.size() << Parts.second;
933 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
Guy Benyei11169dd2012-12-18 14:30:41 +0000934}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000935
936void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
937 const TemplateArgument *TemplateArgs,
938 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000939 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
940
941 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000942 mangleUnscopedTemplateName(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000943 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
944 } else {
945 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
946 }
947}
948
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000949void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
950 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000951 // <unscoped-name> ::= <unqualified-name>
952 // ::= St <unqualified-name> # ::std::
953
954 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
955 Out << "St";
956
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000957 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000958}
959
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000960void CXXNameMangler::mangleUnscopedTemplateName(
961 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000962 // <unscoped-template-name> ::= <unscoped-name>
963 // ::= <substitution>
964 if (mangleSubstitution(ND))
965 return;
966
967 // <template-template-param> ::= <template-param>
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000968 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
969 assert(!AdditionalAbiTags &&
970 "template template param cannot have abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +0000971 mangleTemplateParameter(TTP->getIndex());
David Majnemer6d2b60a2016-07-12 16:48:17 +0000972 } else if (isa<BuiltinTemplateDecl>(ND)) {
973 mangleUnscopedName(ND, AdditionalAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000974 } else {
975 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
976 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000977
Guy Benyei11169dd2012-12-18 14:30:41 +0000978 addSubstitution(ND);
979}
980
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000981void CXXNameMangler::mangleUnscopedTemplateName(
982 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 // <unscoped-template-name> ::= <unscoped-name>
984 // ::= <substitution>
985 if (TemplateDecl *TD = Template.getAsTemplateDecl())
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000986 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000987
988 if (mangleSubstitution(Template))
989 return;
990
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000991 assert(!AdditionalAbiTags &&
992 "dependent template name cannot have abi tags");
993
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
995 assert(Dependent && "Not a dependent template name?");
996 if (const IdentifierInfo *Id = Dependent->getIdentifier())
997 mangleSourceName(Id);
998 else
999 mangleOperatorName(Dependent->getOperator(), UnknownArity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001000
Guy Benyei11169dd2012-12-18 14:30:41 +00001001 addSubstitution(Template);
1002}
1003
1004void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1005 // ABI:
1006 // Floating-point literals are encoded using a fixed-length
1007 // lowercase hexadecimal string corresponding to the internal
1008 // representation (IEEE on Itanium), high-order bytes first,
1009 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1010 // on Itanium.
1011 // The 'without leading zeroes' thing seems to be an editorial
1012 // mistake; see the discussion on cxx-abi-dev beginning on
1013 // 2012-01-16.
1014
1015 // Our requirements here are just barely weird enough to justify
1016 // using a custom algorithm instead of post-processing APInt::toString().
1017
1018 llvm::APInt valueBits = f.bitcastToAPInt();
1019 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1020 assert(numCharacters != 0);
1021
1022 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +00001023 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +00001024
1025 // Fill the buffer left-to-right.
1026 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1027 // The bit-index of the next hex digit.
1028 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1029
1030 // Project out 4 bits starting at 'digitIndex'.
Craig Topperc396c532017-03-30 05:48:58 +00001031 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1032 hexDigit >>= (digitBitIndex % 64);
Guy Benyei11169dd2012-12-18 14:30:41 +00001033 hexDigit &= 0xF;
1034
1035 // Map that over to a lowercase hex digit.
1036 static const char charForHex[16] = {
1037 '0', '1', '2', '3', '4', '5', '6', '7',
1038 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1039 };
1040 buffer[stringIndex] = charForHex[hexDigit];
1041 }
1042
1043 Out.write(buffer.data(), numCharacters);
1044}
1045
1046void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1047 if (Value.isSigned() && Value.isNegative()) {
1048 Out << 'n';
1049 Value.abs().print(Out, /*signed*/ false);
1050 } else {
1051 Value.print(Out, /*signed*/ false);
1052 }
1053}
1054
1055void CXXNameMangler::mangleNumber(int64_t Number) {
1056 // <number> ::= [n] <non-negative decimal integer>
1057 if (Number < 0) {
1058 Out << 'n';
1059 Number = -Number;
1060 }
1061
1062 Out << Number;
1063}
1064
1065void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1066 // <call-offset> ::= h <nv-offset> _
1067 // ::= v <v-offset> _
1068 // <nv-offset> ::= <offset number> # non-virtual base override
1069 // <v-offset> ::= <offset number> _ <virtual offset number>
1070 // # virtual base override, with vcall offset
1071 if (!Virtual) {
1072 Out << 'h';
1073 mangleNumber(NonVirtual);
1074 Out << '_';
1075 return;
1076 }
1077
1078 Out << 'v';
1079 mangleNumber(NonVirtual);
1080 Out << '_';
1081 mangleNumber(Virtual);
1082 Out << '_';
1083}
1084
1085void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +00001086 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001087 if (!mangleSubstitution(QualType(TST, 0))) {
1088 mangleTemplatePrefix(TST->getTemplateName());
1089
1090 // FIXME: GCC does not appear to mangle the template arguments when
1091 // the template in question is a dependent template name. Should we
1092 // emulate that badness?
1093 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1094 addSubstitution(QualType(TST, 0));
1095 }
David Majnemera88b3592015-02-18 02:28:01 +00001096 } else if (const auto *DTST =
1097 type->getAs<DependentTemplateSpecializationType>()) {
1098 if (!mangleSubstitution(QualType(DTST, 0))) {
1099 TemplateName Template = getASTContext().getDependentTemplateName(
1100 DTST->getQualifier(), DTST->getIdentifier());
1101 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +00001102
David Majnemera88b3592015-02-18 02:28:01 +00001103 // FIXME: GCC does not appear to mangle the template arguments when
1104 // the template in question is a dependent template name. Should we
1105 // emulate that badness?
1106 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1107 addSubstitution(QualType(DTST, 0));
1108 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 } else {
1110 // We use the QualType mangle type variant here because it handles
1111 // substitutions.
1112 mangleType(type);
1113 }
1114}
1115
1116/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1117///
Guy Benyei11169dd2012-12-18 14:30:41 +00001118/// \param recursive - true if this is being called recursively,
1119/// i.e. if there is more prefix "to the right".
1120void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +00001121 bool recursive) {
1122
1123 // x, ::x
1124 // <unresolved-name> ::= [gs] <base-unresolved-name>
1125
1126 // T::x / decltype(p)::x
1127 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1128
1129 // T::N::x /decltype(p)::N::x
1130 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1131 // <base-unresolved-name>
1132
1133 // A::x, N::y, A<T>::z; "gs" means leading "::"
1134 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1135 // <base-unresolved-name>
1136
1137 switch (qualifier->getKind()) {
1138 case NestedNameSpecifier::Global:
1139 Out << "gs";
1140
1141 // We want an 'sr' unless this is the entire NNS.
1142 if (recursive)
1143 Out << "sr";
1144
1145 // We never want an 'E' here.
1146 return;
1147
Nikola Smiljanic67860242014-09-26 00:28:20 +00001148 case NestedNameSpecifier::Super:
1149 llvm_unreachable("Can't mangle __super specifier");
1150
Guy Benyei11169dd2012-12-18 14:30:41 +00001151 case NestedNameSpecifier::Namespace:
1152 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001153 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001154 /*recursive*/ true);
1155 else
1156 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001157 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
Guy Benyei11169dd2012-12-18 14:30:41 +00001158 break;
1159 case NestedNameSpecifier::NamespaceAlias:
1160 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001161 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001162 /*recursive*/ true);
1163 else
1164 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001165 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
Guy Benyei11169dd2012-12-18 14:30:41 +00001166 break;
1167
1168 case NestedNameSpecifier::TypeSpec:
1169 case NestedNameSpecifier::TypeSpecWithTemplate: {
1170 const Type *type = qualifier->getAsType();
1171
1172 // We only want to use an unresolved-type encoding if this is one of:
1173 // - a decltype
1174 // - a template type parameter
1175 // - a template template parameter with arguments
1176 // In all of these cases, we should have no prefix.
1177 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001178 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001179 /*recursive*/ true);
1180 } else {
1181 // Otherwise, all the cases want this.
1182 Out << "sr";
1183 }
1184
David Majnemerb8014dd2015-02-19 02:16:16 +00001185 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +00001186 return;
1187
Guy Benyei11169dd2012-12-18 14:30:41 +00001188 break;
1189 }
1190
1191 case NestedNameSpecifier::Identifier:
1192 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +00001193 if (qualifier->getPrefix())
1194 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001195 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +00001196 else
Guy Benyei11169dd2012-12-18 14:30:41 +00001197 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +00001198
1199 mangleSourceName(qualifier->getAsIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001200 // An Identifier has no type information, so we can't emit abi tags for it.
Guy Benyei11169dd2012-12-18 14:30:41 +00001201 break;
1202 }
1203
1204 // If this was the innermost part of the NNS, and we fell out to
1205 // here, append an 'E'.
1206 if (!recursive)
1207 Out << 'E';
1208}
1209
1210/// Mangle an unresolved-name, which is generally used for names which
1211/// weren't resolved to specific entities.
Richard Smithafecd832016-10-24 20:47:04 +00001212void CXXNameMangler::mangleUnresolvedName(
1213 NestedNameSpecifier *qualifier, DeclarationName name,
1214 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1215 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001216 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001217 switch (name.getNameKind()) {
1218 // <base-unresolved-name> ::= <simple-id>
1219 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +00001220 mangleSourceName(name.getAsIdentifierInfo());
1221 break;
1222 // <base-unresolved-name> ::= dn <destructor-name>
1223 case DeclarationName::CXXDestructorName:
1224 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +00001225 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +00001226 break;
1227 // <base-unresolved-name> ::= on <operator-name>
1228 case DeclarationName::CXXConversionFunctionName:
1229 case DeclarationName::CXXLiteralOperatorName:
1230 case DeclarationName::CXXOperatorName:
1231 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +00001232 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001233 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +00001234 case DeclarationName::CXXConstructorName:
1235 llvm_unreachable("Can't mangle a constructor name!");
1236 case DeclarationName::CXXUsingDirective:
1237 llvm_unreachable("Can't mangle a using directive name!");
Richard Smith35845152017-02-07 01:37:30 +00001238 case DeclarationName::CXXDeductionGuideName:
1239 llvm_unreachable("Can't mangle a deduction guide name!");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001240 case DeclarationName::ObjCMultiArgSelector:
1241 case DeclarationName::ObjCOneArgSelector:
1242 case DeclarationName::ObjCZeroArgSelector:
1243 llvm_unreachable("Can't mangle Objective-C selector names here!");
1244 }
Richard Smithafecd832016-10-24 20:47:04 +00001245
1246 // The <simple-id> and on <operator-name> productions end in an optional
1247 // <template-args>.
1248 if (TemplateArgs)
1249 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00001250}
1251
Guy Benyei11169dd2012-12-18 14:30:41 +00001252void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1253 DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001254 unsigned KnownArity,
1255 const AbiTagList *AdditionalAbiTags) {
David Majnemera88b3592015-02-18 02:28:01 +00001256 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +00001257 // <unqualified-name> ::= <operator-name>
1258 // ::= <ctor-dtor-name>
1259 // ::= <source-name>
1260 switch (Name.getNameKind()) {
1261 case DeclarationName::Identifier: {
Richard Smithbdb84f32016-07-22 23:36:59 +00001262 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1263
Richard Smithda383632016-08-15 01:33:41 +00001264 // We mangle decomposition declarations as the names of their bindings.
Richard Smithbdb84f32016-07-22 23:36:59 +00001265 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
Richard Smithda383632016-08-15 01:33:41 +00001266 // FIXME: Non-standard mangling for decomposition declarations:
1267 //
1268 // <unqualified-name> ::= DC <source-name>* E
1269 //
1270 // These can never be referenced across translation units, so we do
1271 // not need a cross-vendor mangling for anything other than demanglers.
1272 // Proposed on cxx-abi-dev on 2016-08-12
1273 Out << "DC";
1274 for (auto *BD : DD->bindings())
1275 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1276 Out << 'E';
1277 writeAbiTags(ND, AdditionalAbiTags);
1278 break;
Richard Smithbdb84f32016-07-22 23:36:59 +00001279 }
1280
1281 if (II) {
Richard Smithdd8b5332017-09-04 05:37:53 +00001282 // Match GCC's naming convention for internal linkage symbols, for
1283 // symbols that are not actually visible outside of this TU. GCC
1284 // distinguishes between internal and external linkage symbols in
1285 // its mangling, to support cases like this that were valid C++ prior
1286 // to DR426:
1287 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001288 // void test() { extern void foo(); }
1289 // static void foo();
Richard Smithdf963a32017-09-22 22:21:44 +00001290 //
1291 // Don't bother with the L marker for names in anonymous namespaces; the
1292 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1293 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1294 // implying internal linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001295 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Richard Smithdd8b5332017-09-04 05:37:53 +00001296 !ND->isExternallyVisible() &&
Richard Smithdf963a32017-09-22 22:21:44 +00001297 getEffectiveDeclContext(ND)->isFileContext() &&
1298 !ND->isInAnonymousNamespace())
Guy Benyei11169dd2012-12-18 14:30:41 +00001299 Out << 'L';
1300
Erich Keane757d3172016-11-02 18:29:35 +00001301 auto *FD = dyn_cast<FunctionDecl>(ND);
1302 bool IsRegCall = FD &&
1303 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1304 clang::CC_X86RegCall;
1305 if (IsRegCall)
1306 mangleRegCallName(II);
1307 else
1308 mangleSourceName(II);
1309
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001310 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 break;
1312 }
1313
1314 // Otherwise, an anonymous entity. We must have a declaration.
1315 assert(ND && "mangling empty name without declaration");
1316
1317 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1318 if (NS->isAnonymousNamespace()) {
1319 // This is how gcc mangles these names.
1320 Out << "12_GLOBAL__N_1";
1321 break;
1322 }
1323 }
1324
1325 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1326 // We must have an anonymous union or struct declaration.
George Burgess IV00f70bd2018-03-01 05:43:23 +00001327 const RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001328
Guy Benyei11169dd2012-12-18 14:30:41 +00001329 // Itanium C++ ABI 5.1.2:
1330 //
1331 // For the purposes of mangling, the name of an anonymous union is
1332 // considered to be the name of the first named data member found by a
1333 // pre-order, depth-first, declaration-order walk of the data members of
1334 // the anonymous union. If there is no such data member (i.e., if all of
1335 // the data members in the union are unnamed), then there is no way for
1336 // a program to refer to the anonymous union, and there is therefore no
1337 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001338 assert(RD->isAnonymousStructOrUnion()
1339 && "Expected anonymous struct or union!");
1340 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +00001341
1342 // It's actually possible for various reasons for us to get here
1343 // with an empty anonymous struct / union. Fortunately, it
1344 // doesn't really matter what name we generate.
1345 if (!FD) break;
1346 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001347
Guy Benyei11169dd2012-12-18 14:30:41 +00001348 mangleSourceName(FD->getIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001349 // Not emitting abi tags: internal name anyway.
Guy Benyei11169dd2012-12-18 14:30:41 +00001350 break;
1351 }
John McCall924046f2013-04-10 06:08:21 +00001352
1353 // Class extensions have no name as a category, and it's possible
1354 // for them to be the semantic parent of certain declarations
1355 // (primarily, tag decls defined within declarations). Such
1356 // declarations will always have internal linkage, so the name
1357 // doesn't really matter, but we shouldn't crash on them. For
1358 // safety, just handle all ObjC containers here.
1359 if (isa<ObjCContainerDecl>(ND))
1360 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001361
1362 // We must have an anonymous struct.
1363 const TagDecl *TD = cast<TagDecl>(ND);
1364 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1365 assert(TD->getDeclContext() == D->getDeclContext() &&
1366 "Typedef should not be in another decl context!");
1367 assert(D->getDeclName().getAsIdentifierInfo() &&
1368 "Typedef was not named!");
1369 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001370 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1371 // Explicit abi tags are still possible; take from underlying type, not
1372 // from typedef.
1373 writeAbiTags(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 break;
1375 }
1376
1377 // <unnamed-type-name> ::= <closure-type-name>
1378 //
1379 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1380 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1381 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1382 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001383 assert(!AdditionalAbiTags &&
1384 "Lambda type cannot have additional abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +00001385 mangleLambda(Record);
1386 break;
1387 }
1388 }
1389
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001390 if (TD->isExternallyVisible()) {
1391 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001392 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001393 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001394 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001395 Out << '_';
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001396 writeAbiTags(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 break;
1398 }
1399
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001400 // Get a unique id for the anonymous struct. If it is not a real output
1401 // ID doesn't matter so use fake one.
1402 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001403
1404 // Mangle it as a source name in the form
1405 // [n] $_<id>
1406 // where n is the length of the string.
1407 SmallString<8> Str;
1408 Str += "$_";
1409 Str += llvm::utostr(AnonStructId);
1410
1411 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001412 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001413 break;
1414 }
1415
1416 case DeclarationName::ObjCZeroArgSelector:
1417 case DeclarationName::ObjCOneArgSelector:
1418 case DeclarationName::ObjCMultiArgSelector:
1419 llvm_unreachable("Can't mangle Objective-C selector names here!");
1420
Richard Smith5179eb72016-06-28 19:03:57 +00001421 case DeclarationName::CXXConstructorName: {
1422 const CXXRecordDecl *InheritedFrom = nullptr;
1423 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1424 if (auto Inherited =
1425 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1426 InheritedFrom = Inherited.getConstructor()->getParent();
1427 InheritedTemplateArgs =
1428 Inherited.getConstructor()->getTemplateSpecializationArgs();
1429 }
1430
Guy Benyei11169dd2012-12-18 14:30:41 +00001431 if (ND == Structor)
1432 // If the named decl is the C++ constructor we're mangling, use the type
1433 // we were given.
Richard Smith5179eb72016-06-28 19:03:57 +00001434 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00001435 else
1436 // Otherwise, use the complete constructor name. This is relevant if a
1437 // class with a constructor is declared within a constructor.
Richard Smith5179eb72016-06-28 19:03:57 +00001438 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1439
1440 // FIXME: The template arguments are part of the enclosing prefix or
1441 // nested-name, but it's more convenient to mangle them here.
1442 if (InheritedTemplateArgs)
1443 mangleTemplateArgs(*InheritedTemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001444
1445 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001446 break;
Richard Smith5179eb72016-06-28 19:03:57 +00001447 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001448
1449 case DeclarationName::CXXDestructorName:
1450 if (ND == Structor)
1451 // If the named decl is the C++ destructor we're mangling, use the type we
1452 // were given.
1453 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1454 else
1455 // Otherwise, use the complete destructor name. This is relevant if a
1456 // class with a destructor is declared within a destructor.
1457 mangleCXXDtorType(Dtor_Complete);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001458 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001459 break;
1460
David Majnemera88b3592015-02-18 02:28:01 +00001461 case DeclarationName::CXXOperatorName:
1462 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001463 Arity = cast<FunctionDecl>(ND)->getNumParams();
1464
David Majnemera88b3592015-02-18 02:28:01 +00001465 // If we have a member function, we need to include the 'this' pointer.
1466 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1467 if (!MD->isStatic())
1468 Arity++;
1469 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001470 LLVM_FALLTHROUGH;
David Majnemera88b3592015-02-18 02:28:01 +00001471 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001472 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001473 mangleOperatorName(Name, Arity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001474 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001475 break;
1476
Richard Smith35845152017-02-07 01:37:30 +00001477 case DeclarationName::CXXDeductionGuideName:
1478 llvm_unreachable("Can't mangle a deduction guide name!");
1479
Guy Benyei11169dd2012-12-18 14:30:41 +00001480 case DeclarationName::CXXUsingDirective:
1481 llvm_unreachable("Can't mangle a using directive name!");
1482 }
1483}
1484
Erich Keane757d3172016-11-02 18:29:35 +00001485void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1486 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1487 // <number> ::= [n] <non-negative decimal integer>
1488 // <identifier> ::= <unqualified source code identifier>
1489 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1490 << II->getName();
1491}
1492
Guy Benyei11169dd2012-12-18 14:30:41 +00001493void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1494 // <source-name> ::= <positive length number> <identifier>
1495 // <number> ::= [n] <non-negative decimal integer>
1496 // <identifier> ::= <unqualified source code identifier>
1497 Out << II->getLength() << II->getName();
1498}
1499
1500void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1501 const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001502 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +00001503 bool NoFunction) {
1504 // <nested-name>
1505 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1506 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1507 // <template-args> E
1508
1509 Out << 'N';
1510 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001511 Qualifiers MethodQuals =
Roger Ferrer Ibanezcb895132017-04-19 12:23:28 +00001512 Qualifiers::fromCVRUMask(Method->getTypeQualifiers());
David Majnemer42350df2013-11-03 23:51:28 +00001513 // We do not consider restrict a distinguishing attribute for overloading
1514 // purposes so we must not mangle it.
1515 MethodQuals.removeRestrict();
1516 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 mangleRefQualifier(Method->getRefQualifier());
1518 }
1519
1520 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001521 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001522 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001523 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 mangleTemplateArgs(*TemplateArgs);
1525 }
1526 else {
1527 manglePrefix(DC, NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001528 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 }
1530
1531 Out << 'E';
1532}
1533void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1534 const TemplateArgument *TemplateArgs,
1535 unsigned NumTemplateArgs) {
1536 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1537
1538 Out << 'N';
1539
1540 mangleTemplatePrefix(TD);
1541 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1542
1543 Out << 'E';
1544}
1545
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001546void CXXNameMangler::mangleLocalName(const Decl *D,
1547 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001548 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1549 // := Z <function encoding> E s [<discriminator>]
1550 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1551 // _ <entity name>
1552 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001553 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001554 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001555 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001556
1557 Out << 'Z';
1558
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001559 {
1560 AbiTagState LocalAbiTags(AbiTags);
1561
1562 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1563 mangleObjCMethodName(MD);
1564 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1565 mangleBlockForPrefix(BD);
1566 else
1567 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1568
1569 // Implicit ABI tags (from namespace) are not available in the following
1570 // entity; reset to actually emitted tags, which are available.
1571 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1572 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001573
Eli Friedman92821742013-07-02 02:01:18 +00001574 Out << 'E';
1575
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001576 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1577 // be a bug that is fixed in trunk.
1578
Eli Friedman92821742013-07-02 02:01:18 +00001579 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001580 // The parameter number is omitted for the last parameter, 0 for the
1581 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1582 // <entity name> will of course contain a <closure-type-name>: Its
1583 // numbering will be local to the particular argument in which it appears
1584 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001585 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithcb2ba5a2016-07-18 22:37:35 +00001586 if (CXXRD && CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001587 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001588 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001589 if (const FunctionDecl *Func
1590 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1591 Out << 'd';
1592 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1593 if (Num > 1)
1594 mangleNumber(Num - 2);
1595 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001596 }
1597 }
1598 }
1599
1600 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001601 // equality ok because RD derived from ND above
1602 if (D == RD) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001603 mangleUnqualifiedName(RD, AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +00001604 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1605 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001606 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman95f50122013-07-02 17:52:28 +00001607 mangleUnqualifiedBlock(BD);
1608 } else {
1609 const NamedDecl *ND = cast<NamedDecl>(D);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001610 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1611 true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001612 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001613 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1614 // Mangle a block in a default parameter; see above explanation for
1615 // lambdas.
1616 if (const ParmVarDecl *Parm
1617 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1618 if (const FunctionDecl *Func
1619 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1620 Out << 'd';
1621 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1622 if (Num > 1)
1623 mangleNumber(Num - 2);
1624 Out << '_';
1625 }
1626 }
1627
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001628 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman0cd23352013-07-10 01:33:19 +00001629 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001630 } else {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001631 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001632 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001633
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001634 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1635 unsigned disc;
1636 if (Context.getNextDiscriminator(ND, disc)) {
1637 if (disc < 10)
1638 Out << '_' << disc;
1639 else
1640 Out << "__" << disc << '_';
1641 }
1642 }
Eli Friedman95f50122013-07-02 17:52:28 +00001643}
1644
1645void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1646 if (GetLocalClassDecl(Block)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001647 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001648 return;
1649 }
1650 const DeclContext *DC = getEffectiveDeclContext(Block);
1651 if (isLocalContainerContext(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001652 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001653 return;
1654 }
1655 manglePrefix(getEffectiveDeclContext(Block));
1656 mangleUnqualifiedBlock(Block);
1657}
1658
1659void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1660 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1661 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1662 Context->getDeclContext()->isRecord()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001663 const auto *ND = cast<NamedDecl>(Context);
1664 if (ND->getIdentifier()) {
1665 mangleSourceNameWithAbiTags(ND);
1666 Out << 'M';
Eli Friedman95f50122013-07-02 17:52:28 +00001667 }
1668 }
1669 }
1670
1671 // If we have a block mangling number, use it.
1672 unsigned Number = Block->getBlockManglingNumber();
1673 // Otherwise, just make up a number. It doesn't matter what it is because
1674 // the symbol in question isn't externally visible.
1675 if (!Number)
1676 Number = Context.getBlockId(Block, false);
Richard Smith48b35d92017-09-07 05:41:24 +00001677 else {
1678 // Stored mangling numbers are 1-based.
1679 --Number;
1680 }
Eli Friedman95f50122013-07-02 17:52:28 +00001681 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001682 if (Number > 0)
1683 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001684 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001685}
1686
1687void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1688 // If the context of a closure type is an initializer for a class member
1689 // (static or nonstatic), it is encoded in a qualified name with a final
1690 // <prefix> of the form:
1691 //
1692 // <data-member-prefix> := <member source-name> M
1693 //
1694 // Technically, the data-member-prefix is part of the <prefix>. However,
1695 // since a closure type will always be mangled with a prefix, it's easier
1696 // to emit that last part of the prefix here.
1697 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1698 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
Richard Smithc95d2c52017-09-22 04:25:05 +00001699 !isa<ParmVarDecl>(Context)) {
1700 // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1701 // reasonable mangling here.
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 if (const IdentifierInfo *Name
1703 = cast<NamedDecl>(Context)->getIdentifier()) {
1704 mangleSourceName(Name);
Richard Smithc95d2c52017-09-22 04:25:05 +00001705 const TemplateArgumentList *TemplateArgs = nullptr;
Simon Pilgrimb2eda762017-09-22 16:26:17 +00001706 if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
Richard Smithc95d2c52017-09-22 04:25:05 +00001707 mangleTemplateArgs(*TemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001708 Out << 'M';
Guy Benyei11169dd2012-12-18 14:30:41 +00001709 }
1710 }
1711 }
1712
1713 Out << "Ul";
1714 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1715 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001716 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1717 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001718 Out << "E";
1719
1720 // The number is omitted for the first closure type with a given
1721 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1722 // (in lexical order) with that same <lambda-sig> and context.
1723 //
1724 // The AST keeps track of the number for us.
1725 unsigned Number = Lambda->getLambdaManglingNumber();
1726 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1727 if (Number > 1)
1728 mangleNumber(Number - 2);
1729 Out << '_';
1730}
1731
1732void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1733 switch (qualifier->getKind()) {
1734 case NestedNameSpecifier::Global:
1735 // nothing
1736 return;
1737
Nikola Smiljanic67860242014-09-26 00:28:20 +00001738 case NestedNameSpecifier::Super:
1739 llvm_unreachable("Can't mangle __super specifier");
1740
Guy Benyei11169dd2012-12-18 14:30:41 +00001741 case NestedNameSpecifier::Namespace:
1742 mangleName(qualifier->getAsNamespace());
1743 return;
1744
1745 case NestedNameSpecifier::NamespaceAlias:
1746 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1747 return;
1748
1749 case NestedNameSpecifier::TypeSpec:
1750 case NestedNameSpecifier::TypeSpecWithTemplate:
1751 manglePrefix(QualType(qualifier->getAsType(), 0));
1752 return;
1753
1754 case NestedNameSpecifier::Identifier:
1755 // Member expressions can have these without prefixes, but that
1756 // should end up in mangleUnresolvedPrefix instead.
1757 assert(qualifier->getPrefix());
1758 manglePrefix(qualifier->getPrefix());
1759
1760 mangleSourceName(qualifier->getAsIdentifier());
1761 return;
1762 }
1763
1764 llvm_unreachable("unexpected nested name specifier");
1765}
1766
1767void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1768 // <prefix> ::= <prefix> <unqualified-name>
1769 // ::= <template-prefix> <template-args>
1770 // ::= <template-param>
1771 // ::= # empty
1772 // ::= <substitution>
1773
1774 DC = IgnoreLinkageSpecDecls(DC);
1775
1776 if (DC->isTranslationUnit())
1777 return;
1778
Eli Friedman95f50122013-07-02 17:52:28 +00001779 if (NoFunction && isLocalContainerContext(DC))
1780 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001781
Eli Friedman95f50122013-07-02 17:52:28 +00001782 assert(!isLocalContainerContext(DC));
1783
Guy Benyei11169dd2012-12-18 14:30:41 +00001784 const NamedDecl *ND = cast<NamedDecl>(DC);
1785 if (mangleSubstitution(ND))
1786 return;
1787
1788 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001789 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001790 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1791 mangleTemplatePrefix(TD);
1792 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001793 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001794 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001795 mangleUnqualifiedName(ND, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001796 }
1797
1798 addSubstitution(ND);
1799}
1800
1801void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1802 // <template-prefix> ::= <prefix> <template unqualified-name>
1803 // ::= <template-param>
1804 // ::= <substitution>
1805 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1806 return mangleTemplatePrefix(TD);
1807
1808 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1809 manglePrefix(Qualified->getQualifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001810
Guy Benyei11169dd2012-12-18 14:30:41 +00001811 if (OverloadedTemplateStorage *Overloaded
1812 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001813 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001814 UnknownArity, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001815 return;
1816 }
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001817
Guy Benyei11169dd2012-12-18 14:30:41 +00001818 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1819 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001820 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1821 manglePrefix(Qualifier);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001822 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001823}
1824
Eli Friedman86af13f02013-07-05 18:41:30 +00001825void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1826 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001827 // <template-prefix> ::= <prefix> <template unqualified-name>
1828 // ::= <template-param>
1829 // ::= <substitution>
1830 // <template-template-param> ::= <template-param>
1831 // <substitution>
1832
1833 if (mangleSubstitution(ND))
1834 return;
1835
1836 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001837 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001838 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001839 } else {
1840 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
David Majnemer6d2b60a2016-07-12 16:48:17 +00001841 if (isa<BuiltinTemplateDecl>(ND))
1842 mangleUnqualifiedName(ND, nullptr);
1843 else
1844 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001845 }
1846
Guy Benyei11169dd2012-12-18 14:30:41 +00001847 addSubstitution(ND);
1848}
1849
1850/// Mangles a template name under the production <type>. Required for
1851/// template template arguments.
1852/// <type> ::= <class-enum-type>
1853/// ::= <template-param>
1854/// ::= <substitution>
1855void CXXNameMangler::mangleType(TemplateName TN) {
1856 if (mangleSubstitution(TN))
1857 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001858
1859 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001860
1861 switch (TN.getKind()) {
1862 case TemplateName::QualifiedTemplate:
1863 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1864 goto HaveDecl;
1865
1866 case TemplateName::Template:
1867 TD = TN.getAsTemplateDecl();
1868 goto HaveDecl;
1869
1870 HaveDecl:
1871 if (isa<TemplateTemplateParmDecl>(TD))
1872 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1873 else
1874 mangleName(TD);
1875 break;
1876
1877 case TemplateName::OverloadedTemplate:
1878 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1879
1880 case TemplateName::DependentTemplate: {
1881 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1882 assert(Dependent->isIdentifier());
1883
1884 // <class-enum-type> ::= <name>
1885 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001886 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001887 mangleSourceName(Dependent->getIdentifier());
1888 break;
1889 }
1890
1891 case TemplateName::SubstTemplateTemplateParm: {
1892 // Substituted template parameters are mangled as the substituted
1893 // template. This will check for the substitution twice, which is
1894 // fine, but we have to return early so that we don't try to *add*
1895 // the substitution twice.
1896 SubstTemplateTemplateParmStorage *subst
1897 = TN.getAsSubstTemplateTemplateParm();
1898 mangleType(subst->getReplacement());
1899 return;
1900 }
1901
1902 case TemplateName::SubstTemplateTemplateParmPack: {
1903 // FIXME: not clear how to mangle this!
1904 // template <template <class> class T...> class A {
1905 // template <template <class> class U...> void foo(B<T,U> x...);
1906 // };
1907 Out << "_SUBSTPACK_";
1908 break;
1909 }
1910 }
1911
1912 addSubstitution(TN);
1913}
1914
David Majnemerb8014dd2015-02-19 02:16:16 +00001915bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1916 StringRef Prefix) {
1917 // Only certain other types are valid as prefixes; enumerate them.
1918 switch (Ty->getTypeClass()) {
1919 case Type::Builtin:
1920 case Type::Complex:
1921 case Type::Adjusted:
1922 case Type::Decayed:
1923 case Type::Pointer:
1924 case Type::BlockPointer:
1925 case Type::LValueReference:
1926 case Type::RValueReference:
1927 case Type::MemberPointer:
1928 case Type::ConstantArray:
1929 case Type::IncompleteArray:
1930 case Type::VariableArray:
1931 case Type::DependentSizedArray:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001932 case Type::DependentAddressSpace:
David Majnemerb8014dd2015-02-19 02:16:16 +00001933 case Type::DependentSizedExtVector:
1934 case Type::Vector:
1935 case Type::ExtVector:
1936 case Type::FunctionProto:
1937 case Type::FunctionNoProto:
1938 case Type::Paren:
1939 case Type::Attributed:
1940 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001941 case Type::DeducedTemplateSpecialization:
David Majnemerb8014dd2015-02-19 02:16:16 +00001942 case Type::PackExpansion:
1943 case Type::ObjCObject:
1944 case Type::ObjCInterface:
1945 case Type::ObjCObjectPointer:
Manman Rene6be26c2016-09-13 17:25:08 +00001946 case Type::ObjCTypeParam:
David Majnemerb8014dd2015-02-19 02:16:16 +00001947 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001948 case Type::Pipe:
David Majnemerb8014dd2015-02-19 02:16:16 +00001949 llvm_unreachable("type is illegal as a nested name specifier");
1950
1951 case Type::SubstTemplateTypeParmPack:
1952 // FIXME: not clear how to mangle this!
1953 // template <class T...> class A {
1954 // template <class U...> void foo(decltype(T::foo(U())) x...);
1955 // };
1956 Out << "_SUBSTPACK_";
1957 break;
1958
1959 // <unresolved-type> ::= <template-param>
1960 // ::= <decltype>
1961 // ::= <template-template-param> <template-args>
1962 // (this last is not official yet)
1963 case Type::TypeOfExpr:
1964 case Type::TypeOf:
1965 case Type::Decltype:
1966 case Type::TemplateTypeParm:
1967 case Type::UnaryTransform:
1968 case Type::SubstTemplateTypeParm:
1969 unresolvedType:
1970 // Some callers want a prefix before the mangled type.
1971 Out << Prefix;
1972
1973 // This seems to do everything we want. It's not really
1974 // sanctioned for a substituted template parameter, though.
1975 mangleType(Ty);
1976
1977 // We never want to print 'E' directly after an unresolved-type,
1978 // so we return directly.
1979 return true;
1980
1981 case Type::Typedef:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001982 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001983 break;
1984
1985 case Type::UnresolvedUsing:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001986 mangleSourceNameWithAbiTags(
1987 cast<UnresolvedUsingType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001988 break;
1989
1990 case Type::Enum:
1991 case Type::Record:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001992 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001993 break;
1994
1995 case Type::TemplateSpecialization: {
1996 const TemplateSpecializationType *TST =
1997 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00001998 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00001999 switch (TN.getKind()) {
2000 case TemplateName::Template:
2001 case TemplateName::QualifiedTemplate: {
2002 TemplateDecl *TD = TN.getAsTemplateDecl();
2003
2004 // If the base is a template template parameter, this is an
2005 // unresolved type.
2006 assert(TD && "no template for template specialization type");
2007 if (isa<TemplateTemplateParmDecl>(TD))
2008 goto unresolvedType;
2009
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002010 mangleSourceNameWithAbiTags(TD);
David Majnemerb8014dd2015-02-19 02:16:16 +00002011 break;
David Majnemera88b3592015-02-18 02:28:01 +00002012 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002013
2014 case TemplateName::OverloadedTemplate:
2015 case TemplateName::DependentTemplate:
2016 llvm_unreachable("invalid base for a template specialization type");
2017
2018 case TemplateName::SubstTemplateTemplateParm: {
2019 SubstTemplateTemplateParmStorage *subst =
2020 TN.getAsSubstTemplateTemplateParm();
2021 mangleExistingSubstitution(subst->getReplacement());
2022 break;
2023 }
2024
2025 case TemplateName::SubstTemplateTemplateParmPack: {
2026 // FIXME: not clear how to mangle this!
2027 // template <template <class U> class T...> class A {
2028 // template <class U...> void foo(decltype(T<U>::foo) x...);
2029 // };
2030 Out << "_SUBSTPACK_";
2031 break;
2032 }
2033 }
2034
David Majnemera88b3592015-02-18 02:28:01 +00002035 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00002036 break;
David Majnemera88b3592015-02-18 02:28:01 +00002037 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002038
2039 case Type::InjectedClassName:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002040 mangleSourceNameWithAbiTags(
2041 cast<InjectedClassNameType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002042 break;
2043
2044 case Type::DependentName:
2045 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2046 break;
2047
2048 case Type::DependentTemplateSpecialization: {
2049 const DependentTemplateSpecializationType *DTST =
2050 cast<DependentTemplateSpecializationType>(Ty);
2051 mangleSourceName(DTST->getIdentifier());
2052 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2053 break;
2054 }
2055
2056 case Type::Elaborated:
2057 return mangleUnresolvedTypeOrSimpleId(
2058 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2059 }
2060
2061 return false;
David Majnemera88b3592015-02-18 02:28:01 +00002062}
2063
2064void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2065 switch (Name.getNameKind()) {
2066 case DeclarationName::CXXConstructorName:
2067 case DeclarationName::CXXDestructorName:
Richard Smith35845152017-02-07 01:37:30 +00002068 case DeclarationName::CXXDeductionGuideName:
David Majnemera88b3592015-02-18 02:28:01 +00002069 case DeclarationName::CXXUsingDirective:
2070 case DeclarationName::Identifier:
2071 case DeclarationName::ObjCMultiArgSelector:
2072 case DeclarationName::ObjCOneArgSelector:
2073 case DeclarationName::ObjCZeroArgSelector:
2074 llvm_unreachable("Not an operator name");
2075
2076 case DeclarationName::CXXConversionFunctionName:
2077 // <operator-name> ::= cv <type> # (cast)
2078 Out << "cv";
2079 mangleType(Name.getCXXNameType());
2080 break;
2081
2082 case DeclarationName::CXXLiteralOperatorName:
2083 Out << "li";
2084 mangleSourceName(Name.getCXXLiteralIdentifier());
2085 return;
2086
2087 case DeclarationName::CXXOperatorName:
2088 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2089 break;
2090 }
2091}
2092
Guy Benyei11169dd2012-12-18 14:30:41 +00002093void
2094CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2095 switch (OO) {
2096 // <operator-name> ::= nw # new
2097 case OO_New: Out << "nw"; break;
2098 // ::= na # new[]
2099 case OO_Array_New: Out << "na"; break;
2100 // ::= dl # delete
2101 case OO_Delete: Out << "dl"; break;
2102 // ::= da # delete[]
2103 case OO_Array_Delete: Out << "da"; break;
2104 // ::= ps # + (unary)
2105 // ::= pl # + (binary or unknown)
2106 case OO_Plus:
2107 Out << (Arity == 1? "ps" : "pl"); break;
2108 // ::= ng # - (unary)
2109 // ::= mi # - (binary or unknown)
2110 case OO_Minus:
2111 Out << (Arity == 1? "ng" : "mi"); break;
2112 // ::= ad # & (unary)
2113 // ::= an # & (binary or unknown)
2114 case OO_Amp:
2115 Out << (Arity == 1? "ad" : "an"); break;
2116 // ::= de # * (unary)
2117 // ::= ml # * (binary or unknown)
2118 case OO_Star:
2119 // Use binary when unknown.
2120 Out << (Arity == 1? "de" : "ml"); break;
2121 // ::= co # ~
2122 case OO_Tilde: Out << "co"; break;
2123 // ::= dv # /
2124 case OO_Slash: Out << "dv"; break;
2125 // ::= rm # %
2126 case OO_Percent: Out << "rm"; break;
2127 // ::= or # |
2128 case OO_Pipe: Out << "or"; break;
2129 // ::= eo # ^
2130 case OO_Caret: Out << "eo"; break;
2131 // ::= aS # =
2132 case OO_Equal: Out << "aS"; break;
2133 // ::= pL # +=
2134 case OO_PlusEqual: Out << "pL"; break;
2135 // ::= mI # -=
2136 case OO_MinusEqual: Out << "mI"; break;
2137 // ::= mL # *=
2138 case OO_StarEqual: Out << "mL"; break;
2139 // ::= dV # /=
2140 case OO_SlashEqual: Out << "dV"; break;
2141 // ::= rM # %=
2142 case OO_PercentEqual: Out << "rM"; break;
2143 // ::= aN # &=
2144 case OO_AmpEqual: Out << "aN"; break;
2145 // ::= oR # |=
2146 case OO_PipeEqual: Out << "oR"; break;
2147 // ::= eO # ^=
2148 case OO_CaretEqual: Out << "eO"; break;
2149 // ::= ls # <<
2150 case OO_LessLess: Out << "ls"; break;
2151 // ::= rs # >>
2152 case OO_GreaterGreater: Out << "rs"; break;
2153 // ::= lS # <<=
2154 case OO_LessLessEqual: Out << "lS"; break;
2155 // ::= rS # >>=
2156 case OO_GreaterGreaterEqual: Out << "rS"; break;
2157 // ::= eq # ==
2158 case OO_EqualEqual: Out << "eq"; break;
2159 // ::= ne # !=
2160 case OO_ExclaimEqual: Out << "ne"; break;
2161 // ::= lt # <
2162 case OO_Less: Out << "lt"; break;
2163 // ::= gt # >
2164 case OO_Greater: Out << "gt"; break;
2165 // ::= le # <=
2166 case OO_LessEqual: Out << "le"; break;
2167 // ::= ge # >=
2168 case OO_GreaterEqual: Out << "ge"; break;
2169 // ::= nt # !
2170 case OO_Exclaim: Out << "nt"; break;
2171 // ::= aa # &&
2172 case OO_AmpAmp: Out << "aa"; break;
2173 // ::= oo # ||
2174 case OO_PipePipe: Out << "oo"; break;
2175 // ::= pp # ++
2176 case OO_PlusPlus: Out << "pp"; break;
2177 // ::= mm # --
2178 case OO_MinusMinus: Out << "mm"; break;
2179 // ::= cm # ,
2180 case OO_Comma: Out << "cm"; break;
2181 // ::= pm # ->*
2182 case OO_ArrowStar: Out << "pm"; break;
2183 // ::= pt # ->
2184 case OO_Arrow: Out << "pt"; break;
2185 // ::= cl # ()
2186 case OO_Call: Out << "cl"; break;
2187 // ::= ix # []
2188 case OO_Subscript: Out << "ix"; break;
2189
2190 // ::= qu # ?
2191 // The conditional operator can't be overloaded, but we still handle it when
2192 // mangling expressions.
2193 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00002194 // Proposal on cxx-abi-dev, 2015-10-21.
2195 // ::= aw # co_await
2196 case OO_Coawait: Out << "aw"; break;
Richard Smithd30b23d2017-12-01 02:13:10 +00002197 // Proposed in cxx-abi github issue 43.
2198 // ::= ss # <=>
2199 case OO_Spaceship: Out << "ss"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002200
2201 case OO_None:
2202 case NUM_OVERLOADED_OPERATORS:
2203 llvm_unreachable("Not an overloaded operator");
2204 }
2205}
2206
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002207void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002208 // Vendor qualifiers come first and if they are order-insensitive they must
2209 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
Guy Benyei11169dd2012-12-18 14:30:41 +00002210
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002211 // <type> ::= U <addrspace-expr>
2212 if (DAST) {
2213 Out << "U2ASI";
2214 mangleExpression(DAST->getAddrSpaceExpr());
2215 Out << "E";
2216 }
2217
John McCall07daf722016-03-01 22:18:03 +00002218 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00002219 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00002220 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00002221 //
David Tweed31d09b02013-09-13 12:04:22 +00002222 // <type> ::= U <target-addrspace>
2223 // <type> ::= U <OpenCL-addrspace>
2224 // <type> ::= U <CUDA-addrspace>
2225
Guy Benyei11169dd2012-12-18 14:30:41 +00002226 SmallString<64> ASString;
Alexander Richardson6d989432017-10-15 18:48:14 +00002227 LangAS AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00002228
2229 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2230 // <target-addrspace> ::= "AS" <address-space-number>
2231 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Yaxun Liub7318e02017-10-13 03:37:48 +00002232 if (TargetAS != 0)
2233 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00002234 } else {
2235 switch (AS) {
2236 default: llvm_unreachable("Not a language specific address space");
Yaxun Liub7318e02017-10-13 03:37:48 +00002237 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2238 // "private"| "generic" ]
David Tweed31d09b02013-09-13 12:04:22 +00002239 case LangAS::opencl_global: ASString = "CLglobal"; break;
2240 case LangAS::opencl_local: ASString = "CLlocal"; break;
2241 case LangAS::opencl_constant: ASString = "CLconstant"; break;
Yaxun Liub7318e02017-10-13 03:37:48 +00002242 case LangAS::opencl_private: ASString = "CLprivate"; break;
Anastasia Stulova81a25e352017-03-10 15:23:07 +00002243 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
David Tweed31d09b02013-09-13 12:04:22 +00002244 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2245 case LangAS::cuda_device: ASString = "CUdevice"; break;
2246 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2247 case LangAS::cuda_shared: ASString = "CUshared"; break;
2248 }
2249 }
Yaxun Liub7318e02017-10-13 03:37:48 +00002250 if (!ASString.empty())
2251 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00002252 }
John McCall07daf722016-03-01 22:18:03 +00002253
2254 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00002255 // Objective-C ARC Extension:
2256 //
2257 // <type> ::= U "__strong"
2258 // <type> ::= U "__weak"
2259 // <type> ::= U "__autoreleasing"
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002260 //
2261 // Note: we emit __weak first to preserve the order as
2262 // required by the Itanium ABI.
2263 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2264 mangleVendorQualifier("__weak");
2265
2266 // __unaligned (from -fms-extensions)
2267 if (Quals.hasUnaligned())
2268 mangleVendorQualifier("__unaligned");
2269
2270 // Remaining ARC ownership qualifiers.
2271 switch (Quals.getObjCLifetime()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002272 case Qualifiers::OCL_None:
2273 break;
2274
2275 case Qualifiers::OCL_Weak:
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002276 // Do nothing as we already handled this case above.
Guy Benyei11169dd2012-12-18 14:30:41 +00002277 break;
2278
2279 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00002280 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00002281 break;
2282
2283 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00002284 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00002285 break;
2286
2287 case Qualifiers::OCL_ExplicitNone:
2288 // The __unsafe_unretained qualifier is *not* mangled, so that
2289 // __unsafe_unretained types in ARC produce the same manglings as the
2290 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2291 // better ABI compatibility.
2292 //
2293 // It's safe to do this because unqualified 'id' won't show up
2294 // in any type signatures that need to be mangled.
2295 break;
2296 }
John McCall07daf722016-03-01 22:18:03 +00002297
2298 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2299 if (Quals.hasRestrict())
2300 Out << 'r';
2301 if (Quals.hasVolatile())
2302 Out << 'V';
2303 if (Quals.hasConst())
2304 Out << 'K';
2305}
2306
2307void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2308 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002309}
2310
2311void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2312 // <ref-qualifier> ::= R # lvalue reference
2313 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00002314 switch (RefQualifier) {
2315 case RQ_None:
2316 break;
2317
2318 case RQ_LValue:
2319 Out << 'R';
2320 break;
2321
2322 case RQ_RValue:
2323 Out << 'O';
2324 break;
2325 }
2326}
2327
2328void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2329 Context.mangleObjCMethodName(MD, Out);
2330}
2331
David Majnemereea02ee2014-11-28 22:22:46 +00002332static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
2333 if (Quals)
2334 return true;
2335 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2336 return true;
2337 if (Ty->isOpenCLSpecificType())
2338 return true;
2339 if (Ty->isBuiltinType())
2340 return false;
2341
2342 return true;
2343}
2344
Guy Benyei11169dd2012-12-18 14:30:41 +00002345void CXXNameMangler::mangleType(QualType T) {
2346 // If our type is instantiation-dependent but not dependent, we mangle
2347 // it as it was written in the source, removing any top-level sugar.
2348 // Otherwise, use the canonical type.
2349 //
2350 // FIXME: This is an approximation of the instantiation-dependent name
2351 // mangling rules, since we should really be using the type as written and
2352 // augmented via semantic analysis (i.e., with implicit conversions and
2353 // default template arguments) for any instantiation-dependent type.
2354 // Unfortunately, that requires several changes to our AST:
2355 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2356 // uniqued, so that we can handle substitutions properly
2357 // - Default template arguments will need to be represented in the
2358 // TemplateSpecializationType, since they need to be mangled even though
2359 // they aren't written.
2360 // - Conversions on non-type template arguments need to be expressed, since
2361 // they can affect the mangling of sizeof/alignof.
Richard Smithfda59e52016-10-26 01:05:54 +00002362 //
2363 // FIXME: This is wrong when mapping to the canonical type for a dependent
2364 // type discards instantiation-dependent portions of the type, such as for:
2365 //
2366 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2367 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2368 //
2369 // It's also wrong in the opposite direction when instantiation-dependent,
2370 // canonically-equivalent types differ in some irrelevant portion of inner
2371 // type sugar. In such cases, we fail to form correct substitutions, eg:
2372 //
2373 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2374 //
2375 // We should instead canonicalize the non-instantiation-dependent parts,
2376 // regardless of whether the type as a whole is dependent or instantiation
2377 // dependent.
Guy Benyei11169dd2012-12-18 14:30:41 +00002378 if (!T->isInstantiationDependentType() || T->isDependentType())
2379 T = T.getCanonicalType();
2380 else {
2381 // Desugar any types that are purely sugar.
2382 do {
2383 // Don't desugar through template specialization types that aren't
2384 // type aliases. We need to mangle the template arguments as written.
2385 if (const TemplateSpecializationType *TST
2386 = dyn_cast<TemplateSpecializationType>(T))
2387 if (!TST->isTypeAlias())
2388 break;
2389
2390 QualType Desugared
2391 = T.getSingleStepDesugaredType(Context.getASTContext());
2392 if (Desugared == T)
2393 break;
2394
2395 T = Desugared;
2396 } while (true);
2397 }
2398 SplitQualType split = T.split();
2399 Qualifiers quals = split.Quals;
2400 const Type *ty = split.Ty;
2401
David Majnemereea02ee2014-11-28 22:22:46 +00002402 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00002403 if (isSubstitutable && mangleSubstitution(T))
2404 return;
2405
2406 // If we're mangling a qualified array type, push the qualifiers to
2407 // the element type.
2408 if (quals && isa<ArrayType>(T)) {
2409 ty = Context.getASTContext().getAsArrayType(T);
2410 quals = Qualifiers();
2411
2412 // Note that we don't update T: we want to add the
2413 // substitution at the original type.
2414 }
2415
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002416 if (quals || ty->isDependentAddressSpaceType()) {
2417 if (const DependentAddressSpaceType *DAST =
2418 dyn_cast<DependentAddressSpaceType>(ty)) {
2419 SplitQualType splitDAST = DAST->getPointeeType().split();
2420 mangleQualifiers(splitDAST.Quals, DAST);
2421 mangleType(QualType(splitDAST.Ty, 0));
2422 } else {
2423 mangleQualifiers(quals);
2424
2425 // Recurse: even if the qualified type isn't yet substitutable,
2426 // the unqualified type might be.
2427 mangleType(QualType(ty, 0));
2428 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002429 } else {
2430 switch (ty->getTypeClass()) {
2431#define ABSTRACT_TYPE(CLASS, PARENT)
2432#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2433 case Type::CLASS: \
2434 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2435 return;
2436#define TYPE(CLASS, PARENT) \
2437 case Type::CLASS: \
2438 mangleType(static_cast<const CLASS##Type*>(ty)); \
2439 break;
2440#include "clang/AST/TypeNodes.def"
2441 }
2442 }
2443
2444 // Add the substitution.
2445 if (isSubstitutable)
2446 addSubstitution(T);
2447}
2448
2449void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2450 if (!mangleStandardSubstitution(ND))
2451 mangleName(ND);
2452}
2453
2454void CXXNameMangler::mangleType(const BuiltinType *T) {
2455 // <type> ::= <builtin-type>
2456 // <builtin-type> ::= v # void
2457 // ::= w # wchar_t
2458 // ::= b # bool
2459 // ::= c # char
2460 // ::= a # signed char
2461 // ::= h # unsigned char
2462 // ::= s # short
2463 // ::= t # unsigned short
2464 // ::= i # int
2465 // ::= j # unsigned int
2466 // ::= l # long
2467 // ::= m # unsigned long
2468 // ::= x # long long, __int64
2469 // ::= y # unsigned long long, __int64
2470 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002471 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 // ::= f # float
2473 // ::= d # double
2474 // ::= e # long double, __float80
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002475 // ::= g # __float128
Guy Benyei11169dd2012-12-18 14:30:41 +00002476 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2477 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2478 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2479 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002480 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 // ::= Di # char32_t
2482 // ::= Ds # char16_t
2483 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2484 // ::= u <source-name> # vendor extended type
Alexey Bader954ba212016-04-08 13:40:33 +00002485 std::string type_name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002486 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002487 case BuiltinType::Void:
2488 Out << 'v';
2489 break;
2490 case BuiltinType::Bool:
2491 Out << 'b';
2492 break;
2493 case BuiltinType::Char_U:
2494 case BuiltinType::Char_S:
2495 Out << 'c';
2496 break;
2497 case BuiltinType::UChar:
2498 Out << 'h';
2499 break;
2500 case BuiltinType::UShort:
2501 Out << 't';
2502 break;
2503 case BuiltinType::UInt:
2504 Out << 'j';
2505 break;
2506 case BuiltinType::ULong:
2507 Out << 'm';
2508 break;
2509 case BuiltinType::ULongLong:
2510 Out << 'y';
2511 break;
2512 case BuiltinType::UInt128:
2513 Out << 'o';
2514 break;
2515 case BuiltinType::SChar:
2516 Out << 'a';
2517 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002518 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002519 case BuiltinType::WChar_U:
2520 Out << 'w';
2521 break;
2522 case BuiltinType::Char16:
2523 Out << "Ds";
2524 break;
2525 case BuiltinType::Char32:
2526 Out << "Di";
2527 break;
2528 case BuiltinType::Short:
2529 Out << 's';
2530 break;
2531 case BuiltinType::Int:
2532 Out << 'i';
2533 break;
2534 case BuiltinType::Long:
2535 Out << 'l';
2536 break;
2537 case BuiltinType::LongLong:
2538 Out << 'x';
2539 break;
2540 case BuiltinType::Int128:
2541 Out << 'n';
2542 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002543 case BuiltinType::Float16:
2544 Out << "DF16_";
2545 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002546 case BuiltinType::Half:
2547 Out << "Dh";
2548 break;
2549 case BuiltinType::Float:
2550 Out << 'f';
2551 break;
2552 case BuiltinType::Double:
2553 Out << 'd';
2554 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002555 case BuiltinType::LongDouble:
2556 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2557 ? 'g'
2558 : 'e');
2559 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002560 case BuiltinType::Float128:
2561 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2562 Out << "U10__float128"; // Match the GCC mangling
2563 else
2564 Out << 'g';
2565 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002566 case BuiltinType::NullPtr:
2567 Out << "Dn";
2568 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002569
2570#define BUILTIN_TYPE(Id, SingletonId)
2571#define PLACEHOLDER_TYPE(Id, SingletonId) \
2572 case BuiltinType::Id:
2573#include "clang/AST/BuiltinTypes.def"
2574 case BuiltinType::Dependent:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002575 if (!NullOut)
2576 llvm_unreachable("mangling a placeholder type");
2577 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002578 case BuiltinType::ObjCId:
2579 Out << "11objc_object";
2580 break;
2581 case BuiltinType::ObjCClass:
2582 Out << "10objc_class";
2583 break;
2584 case BuiltinType::ObjCSel:
2585 Out << "13objc_selector";
2586 break;
Alexey Bader954ba212016-04-08 13:40:33 +00002587#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2588 case BuiltinType::Id: \
2589 type_name = "ocl_" #ImgType "_" #Suffix; \
2590 Out << type_name.size() << type_name; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00002591 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00002592#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00002593 case BuiltinType::OCLSampler:
2594 Out << "11ocl_sampler";
2595 break;
2596 case BuiltinType::OCLEvent:
2597 Out << "9ocl_event";
2598 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002599 case BuiltinType::OCLClkEvent:
2600 Out << "12ocl_clkevent";
2601 break;
2602 case BuiltinType::OCLQueue:
2603 Out << "9ocl_queue";
2604 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002605 case BuiltinType::OCLReserveID:
2606 Out << "13ocl_reserveid";
2607 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002608 }
2609}
2610
John McCall07daf722016-03-01 22:18:03 +00002611StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2612 switch (CC) {
2613 case CC_C:
2614 return "";
2615
2616 case CC_X86StdCall:
2617 case CC_X86FastCall:
2618 case CC_X86ThisCall:
2619 case CC_X86VectorCall:
2620 case CC_X86Pascal:
Martin Storsjo022e7822017-07-17 20:49:45 +00002621 case CC_Win64:
John McCall07daf722016-03-01 22:18:03 +00002622 case CC_X86_64SysV:
Erich Keane757d3172016-11-02 18:29:35 +00002623 case CC_X86RegCall:
John McCall07daf722016-03-01 22:18:03 +00002624 case CC_AAPCS:
2625 case CC_AAPCS_VFP:
2626 case CC_IntelOclBicc:
2627 case CC_SpirFunction:
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00002628 case CC_OpenCLKernel:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00002629 case CC_PreserveMost:
2630 case CC_PreserveAll:
John McCall07daf722016-03-01 22:18:03 +00002631 // FIXME: we should be mangling all of the above.
2632 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002633
2634 case CC_Swift:
2635 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002636 }
2637 llvm_unreachable("bad calling convention");
2638}
2639
2640void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2641 // Fast path.
2642 if (T->getExtInfo() == FunctionType::ExtInfo())
2643 return;
2644
2645 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2646 // This will get more complicated in the future if we mangle other
2647 // things here; but for now, since we mangle ns_returns_retained as
2648 // a qualifier on the result type, we can get away with this:
2649 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2650 if (!CCQualifier.empty())
2651 mangleVendorQualifier(CCQualifier);
2652
2653 // FIXME: regparm
2654 // FIXME: noreturn
2655}
2656
2657void
2658CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2659 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2660
2661 // Note that these are *not* substitution candidates. Demanglers might
2662 // have trouble with this if the parameter type is fully substituted.
2663
John McCall477f2bb2016-03-03 06:39:32 +00002664 switch (PI.getABI()) {
2665 case ParameterABI::Ordinary:
2666 break;
2667
2668 // All of these start with "swift", so they come before "ns_consumed".
2669 case ParameterABI::SwiftContext:
2670 case ParameterABI::SwiftErrorResult:
2671 case ParameterABI::SwiftIndirectResult:
2672 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2673 break;
2674 }
2675
John McCall07daf722016-03-01 22:18:03 +00002676 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002677 mangleVendorQualifier("ns_consumed");
Akira Hatanaka98a49332017-09-22 00:41:05 +00002678
2679 if (PI.isNoEscape())
2680 mangleVendorQualifier("noescape");
John McCall07daf722016-03-01 22:18:03 +00002681}
2682
Guy Benyei11169dd2012-12-18 14:30:41 +00002683// <type> ::= <function-type>
2684// <function-type> ::= [<CV-qualifiers>] F [Y]
2685// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002686void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002687 mangleExtFunctionInfo(T);
2688
Guy Benyei11169dd2012-12-18 14:30:41 +00002689 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2690 // e.g. "const" in "int (A::*)() const".
2691 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2692
Richard Smithfda59e52016-10-26 01:05:54 +00002693 // Mangle instantiation-dependent exception-specification, if present,
2694 // per cxx-abi-dev proposal on 2016-10-11.
2695 if (T->hasInstantiationDependentExceptionSpec()) {
2696 if (T->getExceptionSpecType() == EST_ComputedNoexcept) {
Richard Smithef09aa92016-11-03 00:27:54 +00002697 Out << "DO";
Richard Smithfda59e52016-10-26 01:05:54 +00002698 mangleExpression(T->getNoexceptExpr());
2699 Out << "E";
2700 } else {
2701 assert(T->getExceptionSpecType() == EST_Dynamic);
Richard Smithef09aa92016-11-03 00:27:54 +00002702 Out << "Dw";
Richard Smithfda59e52016-10-26 01:05:54 +00002703 for (auto ExceptTy : T->exceptions())
2704 mangleType(ExceptTy);
2705 Out << "E";
2706 }
2707 } else if (T->isNothrow(getASTContext())) {
Richard Smithef09aa92016-11-03 00:27:54 +00002708 Out << "Do";
Richard Smithfda59e52016-10-26 01:05:54 +00002709 }
2710
Guy Benyei11169dd2012-12-18 14:30:41 +00002711 Out << 'F';
2712
2713 // FIXME: We don't have enough information in the AST to produce the 'Y'
2714 // encoding for extern "C" function types.
2715 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2716
2717 // Mangle the ref-qualifier, if present.
2718 mangleRefQualifier(T->getRefQualifier());
2719
2720 Out << 'E';
2721}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002722
Guy Benyei11169dd2012-12-18 14:30:41 +00002723void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002724 // Function types without prototypes can arise when mangling a function type
2725 // within an overloadable function in C. We mangle these as the absence of any
2726 // parameter types (not even an empty parameter list).
2727 Out << 'F';
2728
2729 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2730
2731 FunctionTypeDepth.enterResultType();
2732 mangleType(T->getReturnType());
2733 FunctionTypeDepth.leaveResultType();
2734
2735 FunctionTypeDepth.pop(saved);
2736 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002737}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002738
John McCall07daf722016-03-01 22:18:03 +00002739void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002740 bool MangleReturnType,
2741 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002742 // Record that we're in a function type. See mangleFunctionParam
2743 // for details on what we're trying to achieve here.
2744 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2745
2746 // <bare-function-type> ::= <signature type>+
2747 if (MangleReturnType) {
2748 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002749
2750 // Mangle ns_returns_retained as an order-sensitive qualifier here.
Nico Weberfb420782016-05-25 14:15:08 +00002751 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
John McCall07daf722016-03-01 22:18:03 +00002752 mangleVendorQualifier("ns_returns_retained");
2753
2754 // Mangle the return type without any direct ARC ownership qualifiers.
2755 QualType ReturnTy = Proto->getReturnType();
2756 if (ReturnTy.getObjCLifetime()) {
2757 auto SplitReturnTy = ReturnTy.split();
2758 SplitReturnTy.Quals.removeObjCLifetime();
2759 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2760 }
2761 mangleType(ReturnTy);
2762
Guy Benyei11169dd2012-12-18 14:30:41 +00002763 FunctionTypeDepth.leaveResultType();
2764 }
2765
Alp Toker9cacbab2014-01-20 20:26:09 +00002766 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002767 // <builtin-type> ::= v # void
2768 Out << 'v';
2769
2770 FunctionTypeDepth.pop(saved);
2771 return;
2772 }
2773
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002774 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2775 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002776 // Mangle extended parameter info as order-sensitive qualifiers here.
Nico Weberfb420782016-05-25 14:15:08 +00002777 if (Proto->hasExtParameterInfos() && FD == nullptr) {
John McCall07daf722016-03-01 22:18:03 +00002778 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2779 }
2780
2781 // Mangle the type.
2782 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002783 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2784
2785 if (FD) {
2786 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2787 // Attr can only take 1 character, so we can hardcode the length below.
2788 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2789 Out << "U17pass_object_size" << Attr->getType();
2790 }
2791 }
2792 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002793
2794 FunctionTypeDepth.pop(saved);
2795
2796 // <builtin-type> ::= z # ellipsis
2797 if (Proto->isVariadic())
2798 Out << 'z';
2799}
2800
2801// <type> ::= <class-enum-type>
2802// <class-enum-type> ::= <name>
2803void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2804 mangleName(T->getDecl());
2805}
2806
2807// <type> ::= <class-enum-type>
2808// <class-enum-type> ::= <name>
2809void CXXNameMangler::mangleType(const EnumType *T) {
2810 mangleType(static_cast<const TagType*>(T));
2811}
2812void CXXNameMangler::mangleType(const RecordType *T) {
2813 mangleType(static_cast<const TagType*>(T));
2814}
2815void CXXNameMangler::mangleType(const TagType *T) {
2816 mangleName(T->getDecl());
2817}
2818
2819// <type> ::= <array-type>
2820// <array-type> ::= A <positive dimension number> _ <element type>
2821// ::= A [<dimension expression>] _ <element type>
2822void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2823 Out << 'A' << T->getSize() << '_';
2824 mangleType(T->getElementType());
2825}
2826void CXXNameMangler::mangleType(const VariableArrayType *T) {
2827 Out << 'A';
2828 // decayed vla types (size 0) will just be skipped.
2829 if (T->getSizeExpr())
2830 mangleExpression(T->getSizeExpr());
2831 Out << '_';
2832 mangleType(T->getElementType());
2833}
2834void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2835 Out << 'A';
2836 mangleExpression(T->getSizeExpr());
2837 Out << '_';
2838 mangleType(T->getElementType());
2839}
2840void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2841 Out << "A_";
2842 mangleType(T->getElementType());
2843}
2844
2845// <type> ::= <pointer-to-member-type>
2846// <pointer-to-member-type> ::= M <class type> <member type>
2847void CXXNameMangler::mangleType(const MemberPointerType *T) {
2848 Out << 'M';
2849 mangleType(QualType(T->getClass(), 0));
2850 QualType PointeeType = T->getPointeeType();
2851 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2852 mangleType(FPT);
2853
2854 // Itanium C++ ABI 5.1.8:
2855 //
2856 // The type of a non-static member function is considered to be different,
2857 // for the purposes of substitution, from the type of a namespace-scope or
2858 // static member function whose type appears similar. The types of two
2859 // non-static member functions are considered to be different, for the
2860 // purposes of substitution, if the functions are members of different
2861 // classes. In other words, for the purposes of substitution, the class of
2862 // which the function is a member is considered part of the type of
2863 // function.
2864
2865 // Given that we already substitute member function pointers as a
2866 // whole, the net effect of this rule is just to unconditionally
2867 // suppress substitution on the function type in a member pointer.
2868 // We increment the SeqID here to emulate adding an entry to the
2869 // substitution table.
2870 ++SeqID;
2871 } else
2872 mangleType(PointeeType);
2873}
2874
2875// <type> ::= <template-param>
2876void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2877 mangleTemplateParameter(T->getIndex());
2878}
2879
2880// <type> ::= <template-param>
2881void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2882 // FIXME: not clear how to mangle this!
2883 // template <class T...> class A {
2884 // template <class U...> void foo(T(*)(U) x...);
2885 // };
2886 Out << "_SUBSTPACK_";
2887}
2888
2889// <type> ::= P <type> # pointer-to
2890void CXXNameMangler::mangleType(const PointerType *T) {
2891 Out << 'P';
2892 mangleType(T->getPointeeType());
2893}
2894void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2895 Out << 'P';
2896 mangleType(T->getPointeeType());
2897}
2898
2899// <type> ::= R <type> # reference-to
2900void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2901 Out << 'R';
2902 mangleType(T->getPointeeType());
2903}
2904
2905// <type> ::= O <type> # rvalue reference-to (C++0x)
2906void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2907 Out << 'O';
2908 mangleType(T->getPointeeType());
2909}
2910
2911// <type> ::= C <type> # complex pair (C 2000)
2912void CXXNameMangler::mangleType(const ComplexType *T) {
2913 Out << 'C';
2914 mangleType(T->getElementType());
2915}
2916
2917// ARM's ABI for Neon vector types specifies that they should be mangled as
2918// if they are structs (to match ARM's initial implementation). The
2919// vector type must be one of the special types predefined by ARM.
2920void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2921 QualType EltType = T->getElementType();
2922 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002923 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002924 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2925 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002926 case BuiltinType::SChar:
2927 case BuiltinType::UChar:
2928 EltName = "poly8_t";
2929 break;
2930 case BuiltinType::Short:
2931 case BuiltinType::UShort:
2932 EltName = "poly16_t";
2933 break;
2934 case BuiltinType::ULongLong:
2935 EltName = "poly64_t";
2936 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002937 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2938 }
2939 } else {
2940 switch (cast<BuiltinType>(EltType)->getKind()) {
2941 case BuiltinType::SChar: EltName = "int8_t"; break;
2942 case BuiltinType::UChar: EltName = "uint8_t"; break;
2943 case BuiltinType::Short: EltName = "int16_t"; break;
2944 case BuiltinType::UShort: EltName = "uint16_t"; break;
2945 case BuiltinType::Int: EltName = "int32_t"; break;
2946 case BuiltinType::UInt: EltName = "uint32_t"; break;
2947 case BuiltinType::LongLong: EltName = "int64_t"; break;
2948 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002949 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002950 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002951 case BuiltinType::Half: EltName = "float16_t";break;
2952 default:
2953 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002954 }
2955 }
Craig Topper36250ad2014-05-12 05:36:57 +00002956 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002957 unsigned BitSize = (T->getNumElements() *
2958 getASTContext().getTypeSize(EltType));
2959 if (BitSize == 64)
2960 BaseName = "__simd64_";
2961 else {
2962 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2963 BaseName = "__simd128_";
2964 }
2965 Out << strlen(BaseName) + strlen(EltName);
2966 Out << BaseName << EltName;
2967}
2968
Tim Northover2fe823a2013-08-01 09:23:19 +00002969static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2970 switch (EltType->getKind()) {
2971 case BuiltinType::SChar:
2972 return "Int8";
2973 case BuiltinType::Short:
2974 return "Int16";
2975 case BuiltinType::Int:
2976 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002977 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002978 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002979 return "Int64";
2980 case BuiltinType::UChar:
2981 return "Uint8";
2982 case BuiltinType::UShort:
2983 return "Uint16";
2984 case BuiltinType::UInt:
2985 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002986 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002987 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002988 return "Uint64";
2989 case BuiltinType::Half:
2990 return "Float16";
2991 case BuiltinType::Float:
2992 return "Float32";
2993 case BuiltinType::Double:
2994 return "Float64";
2995 default:
2996 llvm_unreachable("Unexpected vector element base type");
2997 }
2998}
2999
3000// AArch64's ABI for Neon vector types specifies that they should be mangled as
3001// the equivalent internal name. The vector type must be one of the special
3002// types predefined by ARM.
3003void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3004 QualType EltType = T->getElementType();
3005 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3006 unsigned BitSize =
3007 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00003008 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00003009
3010 assert((BitSize == 64 || BitSize == 128) &&
3011 "Neon vector type not 64 or 128 bits");
3012
Tim Northover2fe823a2013-08-01 09:23:19 +00003013 StringRef EltName;
3014 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3015 switch (cast<BuiltinType>(EltType)->getKind()) {
3016 case BuiltinType::UChar:
3017 EltName = "Poly8";
3018 break;
3019 case BuiltinType::UShort:
3020 EltName = "Poly16";
3021 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00003022 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00003023 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00003024 EltName = "Poly64";
3025 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00003026 default:
3027 llvm_unreachable("unexpected Neon polynomial vector element type");
3028 }
3029 } else
3030 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3031
3032 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00003033 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00003034 Out << TypeName.length() << TypeName;
3035}
3036
Guy Benyei11169dd2012-12-18 14:30:41 +00003037// GNU extension: vector types
3038// <type> ::= <vector-type>
3039// <vector-type> ::= Dv <positive dimension number> _
3040// <extended element type>
3041// ::= Dv [<dimension expression>] _ <element type>
3042// <extended element type> ::= <element type>
3043// ::= p # AltiVec vector pixel
3044// ::= b # Altivec vector bool
3045void CXXNameMangler::mangleType(const VectorType *T) {
3046 if ((T->getVectorKind() == VectorType::NeonVector ||
3047 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003048 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00003049 llvm::Triple::ArchType Arch =
3050 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00003051 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00003052 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00003053 mangleAArch64NeonVectorType(T);
3054 else
3055 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00003056 return;
3057 }
3058 Out << "Dv" << T->getNumElements() << '_';
3059 if (T->getVectorKind() == VectorType::AltiVecPixel)
3060 Out << 'p';
3061 else if (T->getVectorKind() == VectorType::AltiVecBool)
3062 Out << 'b';
3063 else
3064 mangleType(T->getElementType());
3065}
3066void CXXNameMangler::mangleType(const ExtVectorType *T) {
3067 mangleType(static_cast<const VectorType*>(T));
3068}
3069void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3070 Out << "Dv";
3071 mangleExpression(T->getSizeExpr());
3072 Out << '_';
3073 mangleType(T->getElementType());
3074}
3075
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003076void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3077 SplitQualType split = T->getPointeeType().split();
3078 mangleQualifiers(split.Quals, T);
3079 mangleType(QualType(split.Ty, 0));
3080}
3081
Guy Benyei11169dd2012-12-18 14:30:41 +00003082void CXXNameMangler::mangleType(const PackExpansionType *T) {
3083 // <type> ::= Dp <type> # pack expansion (C++0x)
3084 Out << "Dp";
3085 mangleType(T->getPattern());
3086}
3087
3088void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3089 mangleSourceName(T->getDecl()->getIdentifier());
3090}
3091
3092void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00003093 // Treat __kindof as a vendor extended type qualifier.
3094 if (T->isKindOfType())
3095 Out << "U8__kindof";
3096
Eli Friedman5f508952013-06-18 22:41:37 +00003097 if (!T->qual_empty()) {
3098 // Mangle protocol qualifiers.
3099 SmallString<64> QualStr;
3100 llvm::raw_svector_ostream QualOS(QualStr);
3101 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00003102 for (const auto *I : T->quals()) {
3103 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00003104 QualOS << name.size() << name;
3105 }
Eli Friedman5f508952013-06-18 22:41:37 +00003106 Out << 'U' << QualStr.size() << QualStr;
3107 }
Douglas Gregorab209d82015-07-07 03:58:42 +00003108
Guy Benyei11169dd2012-12-18 14:30:41 +00003109 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00003110
3111 if (T->isSpecialized()) {
3112 // Mangle type arguments as I <type>+ E
3113 Out << 'I';
3114 for (auto typeArg : T->getTypeArgs())
3115 mangleType(typeArg);
3116 Out << 'E';
3117 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003118}
3119
3120void CXXNameMangler::mangleType(const BlockPointerType *T) {
3121 Out << "U13block_pointer";
3122 mangleType(T->getPointeeType());
3123}
3124
3125void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3126 // Mangle injected class name types as if the user had written the
3127 // specialization out fully. It may not actually be possible to see
3128 // this mangling, though.
3129 mangleType(T->getInjectedSpecializationType());
3130}
3131
3132void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3133 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003134 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003135 } else {
3136 if (mangleSubstitution(QualType(T, 0)))
3137 return;
3138
3139 mangleTemplatePrefix(T->getTemplateName());
3140
3141 // FIXME: GCC does not appear to mangle the template arguments when
3142 // the template in question is a dependent template name. Should we
3143 // emulate that badness?
3144 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3145 addSubstitution(QualType(T, 0));
3146 }
3147}
3148
3149void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00003150 // Proposal by cxx-abi-dev, 2014-03-26
3151 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3152 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003153 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00003154 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003155 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00003156 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003157 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00003158 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003159 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00003160 switch (T->getKeyword()) {
Richard Smith91fb1f42017-01-20 18:50:12 +00003161 case ETK_None:
David Majnemer64e40c52014-04-10 00:49:24 +00003162 case ETK_Typename:
3163 break;
3164 case ETK_Struct:
3165 case ETK_Class:
3166 case ETK_Interface:
3167 Out << "Ts";
3168 break;
3169 case ETK_Union:
3170 Out << "Tu";
3171 break;
3172 case ETK_Enum:
3173 Out << "Te";
3174 break;
David Majnemer64e40c52014-04-10 00:49:24 +00003175 }
David Majnemer2e159fb2014-04-15 05:51:25 +00003176 // Typename types are always nested
3177 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00003178 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00003179 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00003180 Out << 'E';
3181}
3182
3183void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3184 // Dependently-scoped template types are nested if they have a prefix.
3185 Out << 'N';
3186
3187 // TODO: avoid making this TemplateName.
3188 TemplateName Prefix =
3189 getASTContext().getDependentTemplateName(T->getQualifier(),
3190 T->getIdentifier());
3191 mangleTemplatePrefix(Prefix);
3192
3193 // FIXME: GCC does not appear to mangle the template arguments when
3194 // the template in question is a dependent template name. Should we
3195 // emulate that badness?
3196 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3197 Out << 'E';
3198}
3199
3200void CXXNameMangler::mangleType(const TypeOfType *T) {
3201 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3202 // "extension with parameters" mangling.
3203 Out << "u6typeof";
3204}
3205
3206void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3207 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3208 // "extension with parameters" mangling.
3209 Out << "u6typeof";
3210}
3211
3212void CXXNameMangler::mangleType(const DecltypeType *T) {
3213 Expr *E = T->getUnderlyingExpr();
3214
3215 // type ::= Dt <expression> E # decltype of an id-expression
3216 // # or class member access
3217 // ::= DT <expression> E # decltype of an expression
3218
3219 // This purports to be an exhaustive list of id-expressions and
3220 // class member accesses. Note that we do not ignore parentheses;
3221 // parentheses change the semantics of decltype for these
3222 // expressions (and cause the mangler to use the other form).
3223 if (isa<DeclRefExpr>(E) ||
3224 isa<MemberExpr>(E) ||
3225 isa<UnresolvedLookupExpr>(E) ||
3226 isa<DependentScopeDeclRefExpr>(E) ||
3227 isa<CXXDependentScopeMemberExpr>(E) ||
3228 isa<UnresolvedMemberExpr>(E))
3229 Out << "Dt";
3230 else
3231 Out << "DT";
3232 mangleExpression(E);
3233 Out << 'E';
3234}
3235
3236void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3237 // If this is dependent, we need to record that. If not, we simply
3238 // mangle it as the underlying type since they are equivalent.
3239 if (T->isDependentType()) {
3240 Out << 'U';
3241
3242 switch (T->getUTTKind()) {
3243 case UnaryTransformType::EnumUnderlyingType:
3244 Out << "3eut";
3245 break;
3246 }
3247 }
3248
David Majnemer140065a2016-06-08 00:34:15 +00003249 mangleType(T->getBaseType());
Guy Benyei11169dd2012-12-18 14:30:41 +00003250}
3251
3252void CXXNameMangler::mangleType(const AutoType *T) {
3253 QualType D = T->getDeducedType();
3254 // <builtin-type> ::= Da # dependent auto
Richard Smithe301ba22015-11-11 02:02:15 +00003255 if (D.isNull()) {
3256 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3257 "shouldn't need to mangle __auto_type!");
Richard Smith74aeef52013-04-26 16:15:35 +00003258 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Richard Smithe301ba22015-11-11 02:02:15 +00003259 } else
Guy Benyei11169dd2012-12-18 14:30:41 +00003260 mangleType(D);
3261}
3262
Richard Smith600b5262017-01-26 20:40:47 +00003263void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3264 // FIXME: This is not the right mangling. We also need to include a scope
3265 // here in some cases.
3266 QualType D = T->getDeducedType();
3267 if (D.isNull())
3268 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3269 else
3270 mangleType(D);
3271}
3272
Guy Benyei11169dd2012-12-18 14:30:41 +00003273void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00003274 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00003275 // (Until there's a standardized mangling...)
3276 Out << "U7_Atomic";
3277 mangleType(T->getValueType());
3278}
3279
Xiuli Pan9c14e282016-01-09 12:53:17 +00003280void CXXNameMangler::mangleType(const PipeType *T) {
3281 // Pipe type mangling rules are described in SPIR 2.0 specification
3282 // A.1 Data types and A.3 Summary of changes
3283 // <type> ::= 8ocl_pipe
3284 Out << "8ocl_pipe";
3285}
3286
Guy Benyei11169dd2012-12-18 14:30:41 +00003287void CXXNameMangler::mangleIntegerLiteral(QualType T,
3288 const llvm::APSInt &Value) {
3289 // <expr-primary> ::= L <type> <value number> E # integer literal
3290 Out << 'L';
3291
3292 mangleType(T);
3293 if (T->isBooleanType()) {
3294 // Boolean values are encoded as 0/1.
3295 Out << (Value.getBoolValue() ? '1' : '0');
3296 } else {
3297 mangleNumber(Value);
3298 }
3299 Out << 'E';
3300
3301}
3302
David Majnemer1dabfdc2015-02-14 13:23:54 +00003303void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3304 // Ignore member expressions involving anonymous unions.
3305 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3306 if (!RT->getDecl()->isAnonymousStructOrUnion())
3307 break;
3308 const auto *ME = dyn_cast<MemberExpr>(Base);
3309 if (!ME)
3310 break;
3311 Base = ME->getBase();
3312 IsArrow = ME->isArrow();
3313 }
3314
3315 if (Base->isImplicitCXXThis()) {
3316 // Note: GCC mangles member expressions to the implicit 'this' as
3317 // *this., whereas we represent them as this->. The Itanium C++ ABI
3318 // does not specify anything here, so we follow GCC.
3319 Out << "dtdefpT";
3320 } else {
3321 Out << (IsArrow ? "pt" : "dt");
3322 mangleExpression(Base);
3323 }
3324}
3325
Guy Benyei11169dd2012-12-18 14:30:41 +00003326/// Mangles a member expression.
3327void CXXNameMangler::mangleMemberExpr(const Expr *base,
3328 bool isArrow,
3329 NestedNameSpecifier *qualifier,
3330 NamedDecl *firstQualifierLookup,
3331 DeclarationName member,
Richard Smithafecd832016-10-24 20:47:04 +00003332 const TemplateArgumentLoc *TemplateArgs,
3333 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00003334 unsigned arity) {
3335 // <expression> ::= dt <expression> <unresolved-name>
3336 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00003337 if (base)
3338 mangleMemberExprBase(base, isArrow);
Richard Smithafecd832016-10-24 20:47:04 +00003339 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003340}
3341
3342/// Look at the callee of the given call expression and determine if
3343/// it's a parenthesized id-expression which would have triggered ADL
3344/// otherwise.
3345static bool isParenthesizedADLCallee(const CallExpr *call) {
3346 const Expr *callee = call->getCallee();
3347 const Expr *fn = callee->IgnoreParens();
3348
3349 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3350 // too, but for those to appear in the callee, it would have to be
3351 // parenthesized.
3352 if (callee == fn) return false;
3353
3354 // Must be an unresolved lookup.
3355 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3356 if (!lookup) return false;
3357
3358 assert(!lookup->requiresADL());
3359
3360 // Must be an unqualified lookup.
3361 if (lookup->getQualifier()) return false;
3362
3363 // Must not have found a class member. Note that if one is a class
3364 // member, they're all class members.
3365 if (lookup->getNumDecls() > 0 &&
3366 (*lookup->decls_begin())->isCXXClassMember())
3367 return false;
3368
3369 // Otherwise, ADL would have been triggered.
3370 return true;
3371}
3372
David Majnemer9c775c72014-09-23 04:27:55 +00003373void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3374 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3375 Out << CastEncoding;
3376 mangleType(ECE->getType());
3377 mangleExpression(ECE->getSubExpr());
3378}
3379
Richard Smith520449d2015-02-05 06:15:50 +00003380void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3381 if (auto *Syntactic = InitList->getSyntacticForm())
3382 InitList = Syntactic;
3383 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3384 mangleExpression(InitList->getInit(i));
3385}
3386
Guy Benyei11169dd2012-12-18 14:30:41 +00003387void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3388 // <expression> ::= <unary operator-name> <expression>
3389 // ::= <binary operator-name> <expression> <expression>
3390 // ::= <trinary operator-name> <expression> <expression> <expression>
3391 // ::= cv <type> expression # conversion with one argument
3392 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00003393 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3394 // ::= sc <type> <expression> # static_cast<type> (expression)
3395 // ::= cc <type> <expression> # const_cast<type> (expression)
3396 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003397 // ::= st <type> # sizeof (a type)
3398 // ::= at <type> # alignof (a type)
3399 // ::= <template-param>
3400 // ::= <function-param>
3401 // ::= sr <type> <unqualified-name> # dependent name
3402 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3403 // ::= ds <expression> <expression> # expr.*expr
3404 // ::= sZ <template-param> # size of a parameter pack
3405 // ::= sZ <function-param> # size of a function parameter pack
3406 // ::= <expr-primary>
3407 // <expr-primary> ::= L <type> <value number> E # integer literal
3408 // ::= L <type <value float> E # floating literal
3409 // ::= L <mangled-name> E # external name
3410 // ::= fpT # 'this' expression
3411 QualType ImplicitlyConvertedToType;
3412
3413recurse:
3414 switch (E->getStmtClass()) {
3415 case Expr::NoStmtClass:
3416#define ABSTRACT_STMT(Type)
3417#define EXPR(Type, Base)
3418#define STMT(Type, Base) \
3419 case Expr::Type##Class:
3420#include "clang/AST/StmtNodes.inc"
3421 // fallthrough
3422
3423 // These all can only appear in local or variable-initialization
3424 // contexts and so should never appear in a mangling.
3425 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003426 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003427 case Expr::ImplicitValueInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003428 case Expr::ArrayInitLoopExprClass:
3429 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003430 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003431 case Expr::ParenListExprClass:
3432 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00003433 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003434 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003435 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003436 case Expr::OMPArraySectionExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00003437 case Expr::CXXInheritedCtorInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003438 llvm_unreachable("unexpected statement kind");
3439
3440 // FIXME: invent manglings for all these.
3441 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003442 case Expr::ChooseExprClass:
3443 case Expr::CompoundLiteralExprClass:
3444 case Expr::ExtVectorElementExprClass:
3445 case Expr::GenericSelectionExprClass:
3446 case Expr::ObjCEncodeExprClass:
3447 case Expr::ObjCIsaExprClass:
3448 case Expr::ObjCIvarRefExprClass:
3449 case Expr::ObjCMessageExprClass:
3450 case Expr::ObjCPropertyRefExprClass:
3451 case Expr::ObjCProtocolExprClass:
3452 case Expr::ObjCSelectorExprClass:
3453 case Expr::ObjCStringLiteralClass:
3454 case Expr::ObjCBoxedExprClass:
3455 case Expr::ObjCArrayLiteralClass:
3456 case Expr::ObjCDictionaryLiteralClass:
3457 case Expr::ObjCSubscriptRefExprClass:
3458 case Expr::ObjCIndirectCopyRestoreExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003459 case Expr::ObjCAvailabilityCheckExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003460 case Expr::OffsetOfExprClass:
3461 case Expr::PredefinedExprClass:
3462 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003463 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003464 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003465 case Expr::TypeTraitExprClass:
3466 case Expr::ArrayTypeTraitExprClass:
3467 case Expr::ExpressionTraitExprClass:
3468 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003469 case Expr::CUDAKernelCallExprClass:
3470 case Expr::AsTypeExprClass:
3471 case Expr::PseudoObjectExprClass:
3472 case Expr::AtomicExprClass:
3473 {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003474 if (!NullOut) {
3475 // As bad as this diagnostic is, it's better than crashing.
3476 DiagnosticsEngine &Diags = Context.getDiags();
3477 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3478 "cannot yet mangle expression type %0");
3479 Diags.Report(E->getExprLoc(), DiagID)
3480 << E->getStmtClassName() << E->getSourceRange();
3481 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003482 break;
3483 }
3484
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00003485 case Expr::CXXUuidofExprClass: {
3486 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3487 if (UE->isTypeOperand()) {
3488 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3489 Out << "u8__uuidoft";
3490 mangleType(UuidT);
3491 } else {
3492 Expr *UuidExp = UE->getExprOperand();
3493 Out << "u8__uuidofz";
3494 mangleExpression(UuidExp, Arity);
3495 }
3496 break;
3497 }
3498
Guy Benyei11169dd2012-12-18 14:30:41 +00003499 // Even gcc-4.5 doesn't mangle this.
3500 case Expr::BinaryConditionalOperatorClass: {
3501 DiagnosticsEngine &Diags = Context.getDiags();
3502 unsigned DiagID =
3503 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3504 "?: operator with omitted middle operand cannot be mangled");
3505 Diags.Report(E->getExprLoc(), DiagID)
3506 << E->getStmtClassName() << E->getSourceRange();
3507 break;
3508 }
3509
3510 // These are used for internal purposes and cannot be meaningfully mangled.
3511 case Expr::OpaqueValueExprClass:
3512 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3513
3514 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00003516 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00003517 Out << "E";
3518 break;
3519 }
3520
Richard Smith39eca9b2017-08-23 22:12:08 +00003521 case Expr::DesignatedInitExprClass: {
3522 auto *DIE = cast<DesignatedInitExpr>(E);
3523 for (const auto &Designator : DIE->designators()) {
3524 if (Designator.isFieldDesignator()) {
3525 Out << "di";
3526 mangleSourceName(Designator.getFieldName());
3527 } else if (Designator.isArrayDesignator()) {
3528 Out << "dx";
3529 mangleExpression(DIE->getArrayIndex(Designator));
3530 } else {
3531 assert(Designator.isArrayRangeDesignator() &&
3532 "unknown designator kind");
3533 Out << "dX";
3534 mangleExpression(DIE->getArrayRangeStart(Designator));
3535 mangleExpression(DIE->getArrayRangeEnd(Designator));
3536 }
3537 }
3538 mangleExpression(DIE->getInit());
3539 break;
3540 }
3541
Guy Benyei11169dd2012-12-18 14:30:41 +00003542 case Expr::CXXDefaultArgExprClass:
3543 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3544 break;
3545
Richard Smith852c9db2013-04-20 22:23:05 +00003546 case Expr::CXXDefaultInitExprClass:
3547 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3548 break;
3549
Richard Smithcc1b96d2013-06-12 22:31:48 +00003550 case Expr::CXXStdInitializerListExprClass:
3551 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3552 break;
3553
Guy Benyei11169dd2012-12-18 14:30:41 +00003554 case Expr::SubstNonTypeTemplateParmExprClass:
3555 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3556 Arity);
3557 break;
3558
3559 case Expr::UserDefinedLiteralClass:
3560 // We follow g++'s approach of mangling a UDL as a call to the literal
3561 // operator.
3562 case Expr::CXXMemberCallExprClass: // fallthrough
3563 case Expr::CallExprClass: {
3564 const CallExpr *CE = cast<CallExpr>(E);
3565
3566 // <expression> ::= cp <simple-id> <expression>* E
3567 // We use this mangling only when the call would use ADL except
3568 // for being parenthesized. Per discussion with David
3569 // Vandervoorde, 2011.04.25.
3570 if (isParenthesizedADLCallee(CE)) {
3571 Out << "cp";
3572 // The callee here is a parenthesized UnresolvedLookupExpr with
3573 // no qualifier and should always get mangled as a <simple-id>
3574 // anyway.
3575
3576 // <expression> ::= cl <expression>* E
3577 } else {
3578 Out << "cl";
3579 }
3580
David Majnemer67a8ec62015-02-19 21:41:48 +00003581 unsigned CallArity = CE->getNumArgs();
3582 for (const Expr *Arg : CE->arguments())
3583 if (isa<PackExpansionExpr>(Arg))
3584 CallArity = UnknownArity;
3585
3586 mangleExpression(CE->getCallee(), CallArity);
3587 for (const Expr *Arg : CE->arguments())
3588 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003589 Out << 'E';
3590 break;
3591 }
3592
3593 case Expr::CXXNewExprClass: {
3594 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3595 if (New->isGlobalNew()) Out << "gs";
3596 Out << (New->isArray() ? "na" : "nw");
3597 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3598 E = New->placement_arg_end(); I != E; ++I)
3599 mangleExpression(*I);
3600 Out << '_';
3601 mangleType(New->getAllocatedType());
3602 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003603 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3604 Out << "il";
3605 else
3606 Out << "pi";
3607 const Expr *Init = New->getInitializer();
3608 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3609 // Directly inline the initializers.
3610 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3611 E = CCE->arg_end();
3612 I != E; ++I)
3613 mangleExpression(*I);
3614 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3615 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3616 mangleExpression(PLE->getExpr(i));
3617 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3618 isa<InitListExpr>(Init)) {
3619 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003620 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003621 } else
3622 mangleExpression(Init);
3623 }
3624 Out << 'E';
3625 break;
3626 }
3627
David Majnemer1dabfdc2015-02-14 13:23:54 +00003628 case Expr::CXXPseudoDestructorExprClass: {
3629 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3630 if (const Expr *Base = PDE->getBase())
3631 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003632 NestedNameSpecifier *Qualifier = PDE->getQualifier();
David Majnemerb8014dd2015-02-19 02:16:16 +00003633 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3634 if (Qualifier) {
3635 mangleUnresolvedPrefix(Qualifier,
3636 /*Recursive=*/true);
3637 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3638 Out << 'E';
3639 } else {
3640 Out << "sr";
3641 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3642 Out << 'E';
3643 }
3644 } else if (Qualifier) {
3645 mangleUnresolvedPrefix(Qualifier);
3646 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003647 // <base-unresolved-name> ::= dn <destructor-name>
3648 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003649 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003650 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003651 break;
3652 }
3653
Guy Benyei11169dd2012-12-18 14:30:41 +00003654 case Expr::MemberExprClass: {
3655 const MemberExpr *ME = cast<MemberExpr>(E);
3656 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003657 ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003658 ME->getMemberDecl()->getDeclName(),
3659 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3660 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003661 break;
3662 }
3663
3664 case Expr::UnresolvedMemberExprClass: {
3665 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003666 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3667 ME->isArrow(), ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003668 ME->getMemberName(),
3669 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3670 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003671 break;
3672 }
3673
3674 case Expr::CXXDependentScopeMemberExprClass: {
3675 const CXXDependentScopeMemberExpr *ME
3676 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003677 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3678 ME->isArrow(), ME->getQualifier(),
3679 ME->getFirstQualifierFoundInScope(),
Richard Smithafecd832016-10-24 20:47:04 +00003680 ME->getMember(),
3681 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3682 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003683 break;
3684 }
3685
3686 case Expr::UnresolvedLookupExprClass: {
3687 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00003688 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3689 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3690 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003691 break;
3692 }
3693
3694 case Expr::CXXUnresolvedConstructExprClass: {
3695 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3696 unsigned N = CE->arg_size();
3697
Richard Smith39eca9b2017-08-23 22:12:08 +00003698 if (CE->isListInitialization()) {
3699 assert(N == 1 && "unexpected form for list initialization");
3700 auto *IL = cast<InitListExpr>(CE->getArg(0));
3701 Out << "tl";
3702 mangleType(CE->getType());
3703 mangleInitListElements(IL);
3704 Out << "E";
3705 return;
3706 }
3707
Guy Benyei11169dd2012-12-18 14:30:41 +00003708 Out << "cv";
3709 mangleType(CE->getType());
3710 if (N != 1) Out << '_';
3711 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3712 if (N != 1) Out << 'E';
3713 break;
3714 }
3715
Guy Benyei11169dd2012-12-18 14:30:41 +00003716 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003717 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003718 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003719 assert(
3720 CE->getNumArgs() >= 1 &&
3721 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3722 "implicit CXXConstructExpr must have one argument");
3723 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3724 }
3725 Out << "il";
3726 for (auto *E : CE->arguments())
3727 mangleExpression(E);
3728 Out << "E";
3729 break;
3730 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003731
Richard Smith520449d2015-02-05 06:15:50 +00003732 case Expr::CXXTemporaryObjectExprClass: {
3733 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3734 unsigned N = CE->getNumArgs();
3735 bool List = CE->isListInitialization();
3736
3737 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003738 Out << "tl";
3739 else
3740 Out << "cv";
3741 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003742 if (!List && N != 1)
3743 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003744 if (CE->isStdInitListInitialization()) {
3745 // We implicitly created a std::initializer_list<T> for the first argument
3746 // of a constructor of type U in an expression of the form U{a, b, c}.
3747 // Strip all the semantic gunk off the initializer list.
3748 auto *SILE =
3749 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3750 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3751 mangleInitListElements(ILE);
3752 } else {
3753 for (auto *E : CE->arguments())
3754 mangleExpression(E);
3755 }
Richard Smith520449d2015-02-05 06:15:50 +00003756 if (List || N != 1)
3757 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003758 break;
3759 }
3760
3761 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003762 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003763 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003764 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003765 break;
3766
3767 case Expr::CXXNoexceptExprClass:
3768 Out << "nx";
3769 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3770 break;
3771
3772 case Expr::UnaryExprOrTypeTraitExprClass: {
3773 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3774
3775 if (!SAE->isInstantiationDependent()) {
3776 // Itanium C++ ABI:
3777 // If the operand of a sizeof or alignof operator is not
3778 // instantiation-dependent it is encoded as an integer literal
3779 // reflecting the result of the operator.
3780 //
3781 // If the result of the operator is implicitly converted to a known
3782 // integer type, that type is used for the literal; otherwise, the type
3783 // of std::size_t or std::ptrdiff_t is used.
3784 QualType T = (ImplicitlyConvertedToType.isNull() ||
3785 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3786 : ImplicitlyConvertedToType;
3787 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3788 mangleIntegerLiteral(T, V);
3789 break;
3790 }
3791
3792 switch(SAE->getKind()) {
3793 case UETT_SizeOf:
3794 Out << 's';
3795 break;
3796 case UETT_AlignOf:
3797 Out << 'a';
3798 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003799 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003800 DiagnosticsEngine &Diags = Context.getDiags();
3801 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3802 "cannot yet mangle vec_step expression");
3803 Diags.Report(DiagID);
3804 return;
3805 }
Alexey Bataev00396512015-07-02 03:40:19 +00003806 case UETT_OpenMPRequiredSimdAlign:
3807 DiagnosticsEngine &Diags = Context.getDiags();
3808 unsigned DiagID = Diags.getCustomDiagID(
3809 DiagnosticsEngine::Error,
3810 "cannot yet mangle __builtin_omp_required_simd_align expression");
3811 Diags.Report(DiagID);
3812 return;
3813 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003814 if (SAE->isArgumentType()) {
3815 Out << 't';
3816 mangleType(SAE->getArgumentType());
3817 } else {
3818 Out << 'z';
3819 mangleExpression(SAE->getArgumentExpr());
3820 }
3821 break;
3822 }
3823
3824 case Expr::CXXThrowExprClass: {
3825 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003826 // <expression> ::= tw <expression> # throw expression
3827 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003828 if (TE->getSubExpr()) {
3829 Out << "tw";
3830 mangleExpression(TE->getSubExpr());
3831 } else {
3832 Out << "tr";
3833 }
3834 break;
3835 }
3836
3837 case Expr::CXXTypeidExprClass: {
3838 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003839 // <expression> ::= ti <type> # typeid (type)
3840 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003841 if (TIE->isTypeOperand()) {
3842 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003843 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003844 } else {
3845 Out << "te";
3846 mangleExpression(TIE->getExprOperand());
3847 }
3848 break;
3849 }
3850
3851 case Expr::CXXDeleteExprClass: {
3852 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003853 // <expression> ::= [gs] dl <expression> # [::] delete expr
3854 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003855 if (DE->isGlobalDelete()) Out << "gs";
3856 Out << (DE->isArrayForm() ? "da" : "dl");
3857 mangleExpression(DE->getArgument());
3858 break;
3859 }
3860
3861 case Expr::UnaryOperatorClass: {
3862 const UnaryOperator *UO = cast<UnaryOperator>(E);
3863 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3864 /*Arity=*/1);
3865 mangleExpression(UO->getSubExpr());
3866 break;
3867 }
3868
3869 case Expr::ArraySubscriptExprClass: {
3870 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3871
3872 // Array subscript is treated as a syntactically weird form of
3873 // binary operator.
3874 Out << "ix";
3875 mangleExpression(AE->getLHS());
3876 mangleExpression(AE->getRHS());
3877 break;
3878 }
3879
3880 case Expr::CompoundAssignOperatorClass: // fallthrough
3881 case Expr::BinaryOperatorClass: {
3882 const BinaryOperator *BO = cast<BinaryOperator>(E);
3883 if (BO->getOpcode() == BO_PtrMemD)
3884 Out << "ds";
3885 else
3886 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3887 /*Arity=*/2);
3888 mangleExpression(BO->getLHS());
3889 mangleExpression(BO->getRHS());
3890 break;
3891 }
3892
3893 case Expr::ConditionalOperatorClass: {
3894 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3895 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3896 mangleExpression(CO->getCond());
3897 mangleExpression(CO->getLHS(), Arity);
3898 mangleExpression(CO->getRHS(), Arity);
3899 break;
3900 }
3901
3902 case Expr::ImplicitCastExprClass: {
3903 ImplicitlyConvertedToType = E->getType();
3904 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3905 goto recurse;
3906 }
3907
3908 case Expr::ObjCBridgedCastExprClass: {
3909 // Mangle ownership casts as a vendor extended operator __bridge,
3910 // __bridge_transfer, or __bridge_retain.
3911 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3912 Out << "v1U" << Kind.size() << Kind;
3913 }
3914 // Fall through to mangle the cast itself.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00003915 LLVM_FALLTHROUGH;
Guy Benyei11169dd2012-12-18 14:30:41 +00003916
3917 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003918 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003919 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003920
Richard Smith520449d2015-02-05 06:15:50 +00003921 case Expr::CXXFunctionalCastExprClass: {
3922 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3923 // FIXME: Add isImplicit to CXXConstructExpr.
3924 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3925 if (CCE->getParenOrBraceRange().isInvalid())
3926 Sub = CCE->getArg(0)->IgnoreImplicit();
3927 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3928 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3929 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3930 Out << "tl";
3931 mangleType(E->getType());
3932 mangleInitListElements(IL);
3933 Out << "E";
3934 } else {
3935 mangleCastExpression(E, "cv");
3936 }
3937 break;
3938 }
3939
David Majnemer9c775c72014-09-23 04:27:55 +00003940 case Expr::CXXStaticCastExprClass:
3941 mangleCastExpression(E, "sc");
3942 break;
3943 case Expr::CXXDynamicCastExprClass:
3944 mangleCastExpression(E, "dc");
3945 break;
3946 case Expr::CXXReinterpretCastExprClass:
3947 mangleCastExpression(E, "rc");
3948 break;
3949 case Expr::CXXConstCastExprClass:
3950 mangleCastExpression(E, "cc");
3951 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003952
3953 case Expr::CXXOperatorCallExprClass: {
3954 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3955 unsigned NumArgs = CE->getNumArgs();
Richard Smith4631be72016-10-24 20:29:40 +00003956 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
3957 // (the enclosing MemberExpr covers the syntactic portion).
3958 if (CE->getOperator() != OO_Arrow)
3959 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00003960 // Mangle the arguments.
3961 for (unsigned i = 0; i != NumArgs; ++i)
3962 mangleExpression(CE->getArg(i));
3963 break;
3964 }
3965
3966 case Expr::ParenExprClass:
3967 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3968 break;
3969
3970 case Expr::DeclRefExprClass: {
3971 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3972
3973 switch (D->getKind()) {
3974 default:
3975 // <expr-primary> ::= L <mangled-name> E # external name
3976 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003977 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003978 Out << 'E';
3979 break;
3980
3981 case Decl::ParmVar:
3982 mangleFunctionParam(cast<ParmVarDecl>(D));
3983 break;
3984
3985 case Decl::EnumConstant: {
3986 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3987 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3988 break;
3989 }
3990
3991 case Decl::NonTypeTemplateParm: {
3992 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3993 mangleTemplateParameter(PD->getIndex());
3994 break;
3995 }
3996
3997 }
3998
3999 break;
4000 }
4001
4002 case Expr::SubstNonTypeTemplateParmPackExprClass:
4003 // FIXME: not clear how to mangle this!
4004 // template <unsigned N...> class A {
4005 // template <class U...> void foo(U (&x)[N]...);
4006 // };
4007 Out << "_SUBSTPACK_";
4008 break;
4009
4010 case Expr::FunctionParmPackExprClass: {
4011 // FIXME: not clear how to mangle this!
4012 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4013 Out << "v110_SUBSTPACK";
4014 mangleFunctionParam(FPPE->getParameterPack());
4015 break;
4016 }
4017
4018 case Expr::DependentScopeDeclRefExprClass: {
4019 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00004020 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4021 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4022 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00004023 break;
4024 }
4025
4026 case Expr::CXXBindTemporaryExprClass:
4027 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4028 break;
4029
4030 case Expr::ExprWithCleanupsClass:
4031 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4032 break;
4033
4034 case Expr::FloatingLiteralClass: {
4035 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4036 Out << 'L';
4037 mangleType(FL->getType());
4038 mangleFloat(FL->getValue());
4039 Out << 'E';
4040 break;
4041 }
4042
4043 case Expr::CharacterLiteralClass:
4044 Out << 'L';
4045 mangleType(E->getType());
4046 Out << cast<CharacterLiteral>(E)->getValue();
4047 Out << 'E';
4048 break;
4049
4050 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4051 case Expr::ObjCBoolLiteralExprClass:
4052 Out << "Lb";
4053 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4054 Out << 'E';
4055 break;
4056
4057 case Expr::CXXBoolLiteralExprClass:
4058 Out << "Lb";
4059 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4060 Out << 'E';
4061 break;
4062
4063 case Expr::IntegerLiteralClass: {
4064 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4065 if (E->getType()->isSignedIntegerType())
4066 Value.setIsSigned(true);
4067 mangleIntegerLiteral(E->getType(), Value);
4068 break;
4069 }
4070
4071 case Expr::ImaginaryLiteralClass: {
4072 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4073 // Mangle as if a complex literal.
4074 // Proposal from David Vandevoorde, 2010.06.30.
4075 Out << 'L';
4076 mangleType(E->getType());
4077 if (const FloatingLiteral *Imag =
4078 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4079 // Mangle a floating-point zero of the appropriate type.
4080 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4081 Out << '_';
4082 mangleFloat(Imag->getValue());
4083 } else {
4084 Out << "0_";
4085 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4086 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4087 Value.setIsSigned(true);
4088 mangleNumber(Value);
4089 }
4090 Out << 'E';
4091 break;
4092 }
4093
4094 case Expr::StringLiteralClass: {
4095 // Revised proposal from David Vandervoorde, 2010.07.15.
4096 Out << 'L';
4097 assert(isa<ConstantArrayType>(E->getType()));
4098 mangleType(E->getType());
4099 Out << 'E';
4100 break;
4101 }
4102
4103 case Expr::GNUNullExprClass:
4104 // FIXME: should this really be mangled the same as nullptr?
4105 // fallthrough
4106
4107 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004108 Out << "LDnE";
4109 break;
4110 }
4111
4112 case Expr::PackExpansionExprClass:
4113 Out << "sp";
4114 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4115 break;
4116
4117 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00004118 auto *SPE = cast<SizeOfPackExpr>(E);
4119 if (SPE->isPartiallySubstituted()) {
4120 Out << "sP";
4121 for (const auto &A : SPE->getPartialArguments())
4122 mangleTemplateArg(A);
4123 Out << "E";
4124 break;
4125 }
4126
Guy Benyei11169dd2012-12-18 14:30:41 +00004127 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00004128 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00004129 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4130 mangleTemplateParameter(TTP->getIndex());
4131 else if (const NonTypeTemplateParmDecl *NTTP
4132 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4133 mangleTemplateParameter(NTTP->getIndex());
4134 else if (const TemplateTemplateParmDecl *TempTP
4135 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4136 mangleTemplateParameter(TempTP->getIndex());
4137 else
4138 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4139 break;
4140 }
Richard Smith0f0af192014-11-08 05:07:16 +00004141
Guy Benyei11169dd2012-12-18 14:30:41 +00004142 case Expr::MaterializeTemporaryExprClass: {
4143 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
4144 break;
4145 }
Richard Smith0f0af192014-11-08 05:07:16 +00004146
4147 case Expr::CXXFoldExprClass: {
4148 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00004149 if (FE->isLeftFold())
4150 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00004151 else
Richard Smith8e6923b2014-11-10 19:44:15 +00004152 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00004153
4154 if (FE->getOperator() == BO_PtrMemD)
4155 Out << "ds";
4156 else
4157 mangleOperatorName(
4158 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4159 /*Arity=*/2);
4160
4161 if (FE->getLHS())
4162 mangleExpression(FE->getLHS());
4163 if (FE->getRHS())
4164 mangleExpression(FE->getRHS());
4165 break;
4166 }
4167
Guy Benyei11169dd2012-12-18 14:30:41 +00004168 case Expr::CXXThisExprClass:
4169 Out << "fpT";
4170 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00004171
4172 case Expr::CoawaitExprClass:
4173 // FIXME: Propose a non-vendor mangling.
4174 Out << "v18co_await";
4175 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4176 break;
4177
Eric Fiselier20f25cb2017-03-06 23:38:15 +00004178 case Expr::DependentCoawaitExprClass:
4179 // FIXME: Propose a non-vendor mangling.
4180 Out << "v18co_await";
4181 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4182 break;
4183
Richard Smith9f690bd2015-10-27 06:02:45 +00004184 case Expr::CoyieldExprClass:
4185 // FIXME: Propose a non-vendor mangling.
4186 Out << "v18co_yield";
4187 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4188 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004189 }
4190}
4191
4192/// Mangle an expression which refers to a parameter variable.
4193///
4194/// <expression> ::= <function-param>
4195/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4196/// <function-param> ::= fp <top-level CV-qualifiers>
4197/// <parameter-2 non-negative number> _ # L == 0, I > 0
4198/// <function-param> ::= fL <L-1 non-negative number>
4199/// p <top-level CV-qualifiers> _ # L > 0, I == 0
4200/// <function-param> ::= fL <L-1 non-negative number>
4201/// p <top-level CV-qualifiers>
4202/// <I-1 non-negative number> _ # L > 0, I > 0
4203///
4204/// L is the nesting depth of the parameter, defined as 1 if the
4205/// parameter comes from the innermost function prototype scope
4206/// enclosing the current context, 2 if from the next enclosing
4207/// function prototype scope, and so on, with one special case: if
4208/// we've processed the full parameter clause for the innermost
4209/// function type, then L is one less. This definition conveniently
4210/// makes it irrelevant whether a function's result type was written
4211/// trailing or leading, but is otherwise overly complicated; the
4212/// numbering was first designed without considering references to
4213/// parameter in locations other than return types, and then the
4214/// mangling had to be generalized without changing the existing
4215/// manglings.
4216///
4217/// I is the zero-based index of the parameter within its parameter
4218/// declaration clause. Note that the original ABI document describes
4219/// this using 1-based ordinals.
4220void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4221 unsigned parmDepth = parm->getFunctionScopeDepth();
4222 unsigned parmIndex = parm->getFunctionScopeIndex();
4223
4224 // Compute 'L'.
4225 // parmDepth does not include the declaring function prototype.
4226 // FunctionTypeDepth does account for that.
4227 assert(parmDepth < FunctionTypeDepth.getDepth());
4228 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4229 if (FunctionTypeDepth.isInResultType())
4230 nestingDepth--;
4231
4232 if (nestingDepth == 0) {
4233 Out << "fp";
4234 } else {
4235 Out << "fL" << (nestingDepth - 1) << 'p';
4236 }
4237
4238 // Top-level qualifiers. We don't have to worry about arrays here,
4239 // because parameters declared as arrays should already have been
4240 // transformed to have pointer type. FIXME: apparently these don't
4241 // get mangled if used as an rvalue of a known non-class type?
4242 assert(!parm->getType()->isArrayType()
4243 && "parameter's type is still an array type?");
Andrew Gozillon572bbb02017-10-02 06:25:51 +00004244
4245 if (const DependentAddressSpaceType *DAST =
4246 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4247 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4248 } else {
4249 mangleQualifiers(parm->getType().getQualifiers());
4250 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004251
4252 // Parameter index.
4253 if (parmIndex != 0) {
4254 Out << (parmIndex - 1);
4255 }
4256 Out << '_';
4257}
4258
Richard Smith5179eb72016-06-28 19:03:57 +00004259void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4260 const CXXRecordDecl *InheritedFrom) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004261 // <ctor-dtor-name> ::= C1 # complete object constructor
4262 // ::= C2 # base object constructor
Richard Smith5179eb72016-06-28 19:03:57 +00004263 // ::= CI1 <type> # complete inheriting constructor
4264 // ::= CI2 <type> # base inheriting constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00004265 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004266 // In addition, C5 is a comdat name with C1 and C2 in it.
Richard Smith5179eb72016-06-28 19:03:57 +00004267 Out << 'C';
4268 if (InheritedFrom)
4269 Out << 'I';
Guy Benyei11169dd2012-12-18 14:30:41 +00004270 switch (T) {
4271 case Ctor_Complete:
Richard Smith5179eb72016-06-28 19:03:57 +00004272 Out << '1';
Guy Benyei11169dd2012-12-18 14:30:41 +00004273 break;
4274 case Ctor_Base:
Richard Smith5179eb72016-06-28 19:03:57 +00004275 Out << '2';
Guy Benyei11169dd2012-12-18 14:30:41 +00004276 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004277 case Ctor_Comdat:
Richard Smith5179eb72016-06-28 19:03:57 +00004278 Out << '5';
Guy Benyei11169dd2012-12-18 14:30:41 +00004279 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00004280 case Ctor_DefaultClosure:
4281 case Ctor_CopyingClosure:
4282 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00004283 }
Richard Smith5179eb72016-06-28 19:03:57 +00004284 if (InheritedFrom)
4285 mangleName(InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00004286}
4287
4288void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4289 // <ctor-dtor-name> ::= D0 # deleting destructor
4290 // ::= D1 # complete object destructor
4291 // ::= D2 # base object destructor
4292 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004293 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 switch (T) {
4295 case Dtor_Deleting:
4296 Out << "D0";
4297 break;
4298 case Dtor_Complete:
4299 Out << "D1";
4300 break;
4301 case Dtor_Base:
4302 Out << "D2";
4303 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004304 case Dtor_Comdat:
4305 Out << "D5";
4306 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004307 }
4308}
4309
James Y Knight04ec5bf2015-12-24 02:59:37 +00004310void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4311 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004312 // <template-args> ::= I <template-arg>+ E
4313 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00004314 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4315 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00004316 Out << 'E';
4317}
4318
4319void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4320 // <template-args> ::= I <template-arg>+ E
4321 Out << 'I';
4322 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4323 mangleTemplateArg(AL[i]);
4324 Out << 'E';
4325}
4326
4327void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4328 unsigned NumTemplateArgs) {
4329 // <template-args> ::= I <template-arg>+ E
4330 Out << 'I';
4331 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4332 mangleTemplateArg(TemplateArgs[i]);
4333 Out << 'E';
4334}
4335
4336void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4337 // <template-arg> ::= <type> # type or template
4338 // ::= X <expression> E # expression
4339 // ::= <expr-primary> # simple expressions
4340 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00004341 if (!A.isInstantiationDependent() || A.isDependent())
4342 A = Context.getASTContext().getCanonicalTemplateArgument(A);
4343
4344 switch (A.getKind()) {
4345 case TemplateArgument::Null:
4346 llvm_unreachable("Cannot mangle NULL template argument");
4347
4348 case TemplateArgument::Type:
4349 mangleType(A.getAsType());
4350 break;
4351 case TemplateArgument::Template:
4352 // This is mangled as <type>.
4353 mangleType(A.getAsTemplate());
4354 break;
4355 case TemplateArgument::TemplateExpansion:
4356 // <type> ::= Dp <type> # pack expansion (C++0x)
4357 Out << "Dp";
4358 mangleType(A.getAsTemplateOrTemplatePattern());
4359 break;
4360 case TemplateArgument::Expression: {
4361 // It's possible to end up with a DeclRefExpr here in certain
4362 // dependent cases, in which case we should mangle as a
4363 // declaration.
4364 const Expr *E = A.getAsExpr()->IgnoreParens();
4365 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4366 const ValueDecl *D = DRE->getDecl();
4367 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00004368 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004369 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004370 Out << 'E';
4371 break;
4372 }
4373 }
4374
4375 Out << 'X';
4376 mangleExpression(E);
4377 Out << 'E';
4378 break;
4379 }
4380 case TemplateArgument::Integral:
4381 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4382 break;
4383 case TemplateArgument::Declaration: {
4384 // <expr-primary> ::= L <mangled-name> E # external name
4385 // Clang produces AST's where pointer-to-member-function expressions
4386 // and pointer-to-function expressions are represented as a declaration not
4387 // an expression. We compensate for it here to produce the correct mangling.
4388 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00004389 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 if (compensateMangling) {
4391 Out << 'X';
4392 mangleOperatorName(OO_Amp, 1);
4393 }
4394
4395 Out << 'L';
4396 // References to external entities use the mangled name; if the name would
Nico Weberfb420782016-05-25 14:15:08 +00004397 // not normally be mangled then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00004398 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004399 Out << 'E';
4400
4401 if (compensateMangling)
4402 Out << 'E';
4403
4404 break;
4405 }
4406 case TemplateArgument::NullPtr: {
4407 // <expr-primary> ::= L <type> 0 E
4408 Out << 'L';
4409 mangleType(A.getNullPtrType());
4410 Out << "0E";
4411 break;
4412 }
4413 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00004414 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00004415 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00004416 for (const auto &P : A.pack_elements())
4417 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00004418 Out << 'E';
4419 }
4420 }
4421}
4422
4423void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4424 // <template-param> ::= T_ # first template parameter
4425 // ::= T <parameter-2 non-negative number> _
4426 if (Index == 0)
4427 Out << "T_";
4428 else
4429 Out << 'T' << (Index - 1) << '_';
4430}
4431
David Majnemer3b3bdb52014-05-06 22:49:16 +00004432void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4433 if (SeqID == 1)
4434 Out << '0';
4435 else if (SeqID > 1) {
4436 SeqID--;
4437
4438 // <seq-id> is encoded in base-36, using digits and upper case letters.
4439 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00004440 MutableArrayRef<char> BufferRef(Buffer);
4441 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00004442
4443 for (; SeqID != 0; SeqID /= 36) {
4444 unsigned C = SeqID % 36;
4445 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4446 }
4447
4448 Out.write(I.base(), I - BufferRef.rbegin());
4449 }
4450 Out << '_';
4451}
4452
Guy Benyei11169dd2012-12-18 14:30:41 +00004453void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4454 bool result = mangleSubstitution(tname);
4455 assert(result && "no existing substitution for template name");
4456 (void) result;
4457}
4458
4459// <substitution> ::= S <seq-id> _
4460// ::= S_
4461bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4462 // Try one of the standard substitutions first.
4463 if (mangleStandardSubstitution(ND))
4464 return true;
4465
4466 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4467 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4468}
4469
Justin Bognere8d762e2015-05-22 06:48:13 +00004470/// Determine whether the given type has any qualifiers that are relevant for
4471/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00004472static bool hasMangledSubstitutionQualifiers(QualType T) {
4473 Qualifiers Qs = T.getQualifiers();
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00004474 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
Guy Benyei11169dd2012-12-18 14:30:41 +00004475}
4476
4477bool CXXNameMangler::mangleSubstitution(QualType T) {
4478 if (!hasMangledSubstitutionQualifiers(T)) {
4479 if (const RecordType *RT = T->getAs<RecordType>())
4480 return mangleSubstitution(RT->getDecl());
4481 }
4482
4483 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4484
4485 return mangleSubstitution(TypePtr);
4486}
4487
4488bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4489 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4490 return mangleSubstitution(TD);
4491
4492 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4493 return mangleSubstitution(
4494 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4495}
4496
4497bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4498 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4499 if (I == Substitutions.end())
4500 return false;
4501
4502 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00004503 Out << 'S';
4504 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00004505
4506 return true;
4507}
4508
4509static bool isCharType(QualType T) {
4510 if (T.isNull())
4511 return false;
4512
4513 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4514 T->isSpecificBuiltinType(BuiltinType::Char_U);
4515}
4516
Justin Bognere8d762e2015-05-22 06:48:13 +00004517/// Returns whether a given type is a template specialization of a given name
4518/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00004519static bool isCharSpecialization(QualType T, const char *Name) {
4520 if (T.isNull())
4521 return false;
4522
4523 const RecordType *RT = T->getAs<RecordType>();
4524 if (!RT)
4525 return false;
4526
4527 const ClassTemplateSpecializationDecl *SD =
4528 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4529 if (!SD)
4530 return false;
4531
4532 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4533 return false;
4534
4535 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4536 if (TemplateArgs.size() != 1)
4537 return false;
4538
4539 if (!isCharType(TemplateArgs[0].getAsType()))
4540 return false;
4541
4542 return SD->getIdentifier()->getName() == Name;
4543}
4544
4545template <std::size_t StrLen>
4546static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4547 const char (&Str)[StrLen]) {
4548 if (!SD->getIdentifier()->isStr(Str))
4549 return false;
4550
4551 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4552 if (TemplateArgs.size() != 2)
4553 return false;
4554
4555 if (!isCharType(TemplateArgs[0].getAsType()))
4556 return false;
4557
4558 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4559 return false;
4560
4561 return true;
4562}
4563
4564bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4565 // <substitution> ::= St # ::std::
4566 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4567 if (isStd(NS)) {
4568 Out << "St";
4569 return true;
4570 }
4571 }
4572
4573 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4574 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4575 return false;
4576
4577 // <substitution> ::= Sa # ::std::allocator
4578 if (TD->getIdentifier()->isStr("allocator")) {
4579 Out << "Sa";
4580 return true;
4581 }
4582
4583 // <<substitution> ::= Sb # ::std::basic_string
4584 if (TD->getIdentifier()->isStr("basic_string")) {
4585 Out << "Sb";
4586 return true;
4587 }
4588 }
4589
4590 if (const ClassTemplateSpecializationDecl *SD =
4591 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4592 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4593 return false;
4594
4595 // <substitution> ::= Ss # ::std::basic_string<char,
4596 // ::std::char_traits<char>,
4597 // ::std::allocator<char> >
4598 if (SD->getIdentifier()->isStr("basic_string")) {
4599 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4600
4601 if (TemplateArgs.size() != 3)
4602 return false;
4603
4604 if (!isCharType(TemplateArgs[0].getAsType()))
4605 return false;
4606
4607 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4608 return false;
4609
4610 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4611 return false;
4612
4613 Out << "Ss";
4614 return true;
4615 }
4616
4617 // <substitution> ::= Si # ::std::basic_istream<char,
4618 // ::std::char_traits<char> >
4619 if (isStreamCharSpecialization(SD, "basic_istream")) {
4620 Out << "Si";
4621 return true;
4622 }
4623
4624 // <substitution> ::= So # ::std::basic_ostream<char,
4625 // ::std::char_traits<char> >
4626 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4627 Out << "So";
4628 return true;
4629 }
4630
4631 // <substitution> ::= Sd # ::std::basic_iostream<char,
4632 // ::std::char_traits<char> >
4633 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4634 Out << "Sd";
4635 return true;
4636 }
4637 }
4638 return false;
4639}
4640
4641void CXXNameMangler::addSubstitution(QualType T) {
4642 if (!hasMangledSubstitutionQualifiers(T)) {
4643 if (const RecordType *RT = T->getAs<RecordType>()) {
4644 addSubstitution(RT->getDecl());
4645 return;
4646 }
4647 }
4648
4649 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4650 addSubstitution(TypePtr);
4651}
4652
4653void CXXNameMangler::addSubstitution(TemplateName Template) {
4654 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4655 return addSubstitution(TD);
4656
4657 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4658 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4659}
4660
4661void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4662 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4663 Substitutions[Ptr] = SeqID++;
4664}
4665
Dmitry Polukhinfda467b2016-09-21 08:27:03 +00004666void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4667 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4668 if (Other->SeqID > SeqID) {
4669 Substitutions.swap(Other->Substitutions);
4670 SeqID = Other->SeqID;
4671 }
4672}
4673
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004674CXXNameMangler::AbiTagList
4675CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4676 // When derived abi tags are disabled there is no need to make any list.
4677 if (DisableDerivedAbiTags)
4678 return AbiTagList();
4679
4680 llvm::raw_null_ostream NullOutStream;
4681 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4682 TrackReturnTypeTags.disableDerivedAbiTags();
4683
4684 const FunctionProtoType *Proto =
4685 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004686 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004687 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4688 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4689 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004690 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004691
4692 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4693}
4694
4695CXXNameMangler::AbiTagList
4696CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4697 // When derived abi tags are disabled there is no need to make any list.
4698 if (DisableDerivedAbiTags)
4699 return AbiTagList();
4700
4701 llvm::raw_null_ostream NullOutStream;
4702 CXXNameMangler TrackVariableType(*this, NullOutStream);
4703 TrackVariableType.disableDerivedAbiTags();
4704
4705 TrackVariableType.mangleType(VD->getType());
4706
4707 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4708}
4709
4710bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4711 const VarDecl *VD) {
4712 llvm::raw_null_ostream NullOutStream;
4713 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4714 TrackAbiTags.mangle(VD);
4715 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4716}
4717
Guy Benyei11169dd2012-12-18 14:30:41 +00004718//
4719
Justin Bognere8d762e2015-05-22 06:48:13 +00004720/// Mangles the name of the declaration D and emits that name to the given
4721/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004722///
4723/// If the declaration D requires a mangled name, this routine will emit that
4724/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4725/// and this routine will return false. In this case, the caller should just
4726/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4727/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004728void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4729 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004730 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4731 "Invalid mangleName() call, argument is not a variable or function!");
4732 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4733 "Invalid mangleName() call on 'structor decl!");
4734
4735 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4736 getASTContext().getSourceManager(),
4737 "Mangling declaration");
4738
4739 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004740 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004741}
4742
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004743void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4744 CXXCtorType Type,
4745 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004746 CXXNameMangler Mangler(*this, Out, D, Type);
4747 Mangler.mangle(D);
4748}
4749
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004750void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4751 CXXDtorType Type,
4752 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004753 CXXNameMangler Mangler(*this, Out, D, Type);
4754 Mangler.mangle(D);
4755}
4756
Rafael Espindola1e4df922014-09-16 15:18:21 +00004757void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4758 raw_ostream &Out) {
4759 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4760 Mangler.mangle(D);
4761}
4762
4763void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4764 raw_ostream &Out) {
4765 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4766 Mangler.mangle(D);
4767}
4768
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004769void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4770 const ThunkInfo &Thunk,
4771 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004772 // <special-name> ::= T <call-offset> <base encoding>
4773 // # base is the nominal target function of thunk
4774 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4775 // # base is the nominal target function of thunk
4776 // # first call-offset is 'this' adjustment
4777 // # second call-offset is result adjustment
4778
4779 assert(!isa<CXXDestructorDecl>(MD) &&
4780 "Use mangleCXXDtor for destructor decls!");
4781 CXXNameMangler Mangler(*this, Out);
4782 Mangler.getStream() << "_ZT";
4783 if (!Thunk.Return.isEmpty())
4784 Mangler.getStream() << 'c';
4785
4786 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004787 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4788 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4789
Guy Benyei11169dd2012-12-18 14:30:41 +00004790 // Mangle the return pointer adjustment if there is one.
4791 if (!Thunk.Return.isEmpty())
4792 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004793 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4794
Guy Benyei11169dd2012-12-18 14:30:41 +00004795 Mangler.mangleFunctionEncoding(MD);
4796}
4797
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004798void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4799 const CXXDestructorDecl *DD, CXXDtorType Type,
4800 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004801 // <special-name> ::= T <call-offset> <base encoding>
4802 // # base is the nominal target function of thunk
4803 CXXNameMangler Mangler(*this, Out, DD, Type);
4804 Mangler.getStream() << "_ZT";
4805
4806 // Mangle the 'this' pointer adjustment.
4807 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004808 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004809
4810 Mangler.mangleFunctionEncoding(DD);
4811}
4812
Justin Bognere8d762e2015-05-22 06:48:13 +00004813/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004814void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4815 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004816 // <special-name> ::= GV <object name> # Guard variable for one-time
4817 // # initialization
4818 CXXNameMangler Mangler(*this, Out);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004819 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4820 // be a bug that is fixed in trunk.
Guy Benyei11169dd2012-12-18 14:30:41 +00004821 Mangler.getStream() << "_ZGV";
4822 Mangler.mangleName(D);
4823}
4824
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004825void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4826 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004827 // These symbols are internal in the Itanium ABI, so the names don't matter.
4828 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4829 // avoid duplicate symbols.
4830 Out << "__cxx_global_var_init";
4831}
4832
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004833void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4834 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004835 // Prefix the mangling of D with __dtor_.
4836 CXXNameMangler Mangler(*this, Out);
4837 Mangler.getStream() << "__dtor_";
4838 if (shouldMangleDeclName(D))
4839 Mangler.mangle(D);
4840 else
4841 Mangler.getStream() << D->getName();
4842}
4843
Reid Kleckner1d59f992015-01-22 01:36:17 +00004844void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4845 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4846 CXXNameMangler Mangler(*this, Out);
4847 Mangler.getStream() << "__filt_";
4848 if (shouldMangleDeclName(EnclosingDecl))
4849 Mangler.mangle(EnclosingDecl);
4850 else
4851 Mangler.getStream() << EnclosingDecl->getName();
4852}
4853
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004854void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4855 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4856 CXXNameMangler Mangler(*this, Out);
4857 Mangler.getStream() << "__fin_";
4858 if (shouldMangleDeclName(EnclosingDecl))
4859 Mangler.mangle(EnclosingDecl);
4860 else
4861 Mangler.getStream() << EnclosingDecl->getName();
4862}
4863
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004864void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4865 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004866 // <special-name> ::= TH <object name>
4867 CXXNameMangler Mangler(*this, Out);
4868 Mangler.getStream() << "_ZTH";
4869 Mangler.mangleName(D);
4870}
4871
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004872void
4873ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4874 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004875 // <special-name> ::= TW <object name>
4876 CXXNameMangler Mangler(*this, Out);
4877 Mangler.getStream() << "_ZTW";
4878 Mangler.mangleName(D);
4879}
4880
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004881void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004882 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004883 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004884 // We match the GCC mangling here.
4885 // <special-name> ::= GR <object name>
4886 CXXNameMangler Mangler(*this, Out);
4887 Mangler.getStream() << "_ZGR";
4888 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004889 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004890 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004891}
4892
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004893void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4894 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004895 // <special-name> ::= TV <type> # virtual table
4896 CXXNameMangler Mangler(*this, Out);
4897 Mangler.getStream() << "_ZTV";
4898 Mangler.mangleNameOrStandardSubstitution(RD);
4899}
4900
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004901void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4902 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004903 // <special-name> ::= TT <type> # VTT structure
4904 CXXNameMangler Mangler(*this, Out);
4905 Mangler.getStream() << "_ZTT";
4906 Mangler.mangleNameOrStandardSubstitution(RD);
4907}
4908
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004909void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4910 int64_t Offset,
4911 const CXXRecordDecl *Type,
4912 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004913 // <special-name> ::= TC <type> <offset number> _ <base type>
4914 CXXNameMangler Mangler(*this, Out);
4915 Mangler.getStream() << "_ZTC";
4916 Mangler.mangleNameOrStandardSubstitution(RD);
4917 Mangler.getStream() << Offset;
4918 Mangler.getStream() << '_';
4919 Mangler.mangleNameOrStandardSubstitution(Type);
4920}
4921
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004922void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004923 // <special-name> ::= TI <type> # typeinfo structure
4924 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4925 CXXNameMangler Mangler(*this, Out);
4926 Mangler.getStream() << "_ZTI";
4927 Mangler.mangleType(Ty);
4928}
4929
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004930void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4931 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004932 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4933 CXXNameMangler Mangler(*this, Out);
4934 Mangler.getStream() << "_ZTS";
4935 Mangler.mangleType(Ty);
4936}
4937
Reid Klecknercc99e262013-11-19 23:23:00 +00004938void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4939 mangleCXXRTTIName(Ty, Out);
4940}
4941
David Majnemer58e5bee2014-03-24 21:43:36 +00004942void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4943 llvm_unreachable("Can't mangle string literals");
4944}
4945
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004946ItaniumMangleContext *
4947ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4948 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004949}