blob: 6f7efcbe1bbb815eb0fda999e03767006a021c50 [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
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +0000326 llvm::sort(TagList.begin(), TagList.end());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000327 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
328
329 writeSortedUniqueAbiTags(Out, TagList);
330 }
331
332 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
333 void setUsedAbiTags(const AbiTagList &AbiTags) {
334 UsedAbiTags = AbiTags;
335 }
336
337 const AbiTagList &getEmittedAbiTags() const {
338 return EmittedAbiTags;
339 }
340
341 const AbiTagList &getSortedUniqueUsedAbiTags() {
Mandeep Singh Grangc205d8c2018-03-27 16:50:00 +0000342 llvm::sort(UsedAbiTags.begin(), UsedAbiTags.end());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000343 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
344 UsedAbiTags.end());
345 return UsedAbiTags;
346 }
347
348 private:
349 //! All abi tags used implicitly or explicitly.
350 AbiTagList UsedAbiTags;
351 //! All explicit abi tags (i.e. not from namespace).
352 AbiTagList EmittedAbiTags;
353
354 AbiTagState *&LinkHead;
355 AbiTagState *Parent = nullptr;
356
357 void pop() {
358 assert(LinkHead == this &&
359 "abi tag link head must point to us on destruction");
360 if (Parent) {
361 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
362 UsedAbiTags.begin(), UsedAbiTags.end());
363 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
364 EmittedAbiTags.begin(),
365 EmittedAbiTags.end());
366 }
367 LinkHead = Parent;
368 }
369
370 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
371 for (const auto &Tag : AbiTags) {
372 EmittedAbiTags.push_back(Tag);
373 Out << "B";
374 Out << Tag.size();
375 Out << Tag;
376 }
377 }
378 };
379
380 AbiTagState *AbiTags = nullptr;
381 AbiTagState AbiTagsRoot;
382
Guy Benyei11169dd2012-12-18 14:30:41 +0000383 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
Richard Smithdd8b5332017-09-04 05:37:53 +0000384 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
Guy Benyei11169dd2012-12-18 14:30:41 +0000385
386 ASTContext &getASTContext() const { return Context.getASTContext(); }
387
388public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000389 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000390 const NamedDecl *D = nullptr, bool NullOut_ = false)
391 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
392 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000393 // These can't be mangled without a ctor type or dtor type.
394 assert(!D || (!isa<CXXDestructorDecl>(D) &&
395 !isa<CXXConstructorDecl>(D)));
396 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000397 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000398 const CXXConstructorDecl *D, CXXCtorType Type)
399 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000400 SeqID(0), AbiTagsRoot(AbiTags) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000401 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000402 const CXXDestructorDecl *D, CXXDtorType Type)
403 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000404 SeqID(0), AbiTagsRoot(AbiTags) { }
405
406 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
407 : Context(Outer.Context), Out(Out_), NullOut(false),
408 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000409 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
410 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000411
412 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
413 : Context(Outer.Context), Out(Out_), NullOut(true),
414 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000415 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
416 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000417
418#if MANGLE_CHECKER
419 ~CXXNameMangler() {
420 if (Out.str()[0] == '\01')
421 return;
422
423 int status = 0;
424 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
425 assert(status == 0 && "Could not demangle mangled name!");
426 free(result);
427 }
428#endif
429 raw_ostream &getStream() { return Out; }
430
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000431 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
432 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
433
David Majnemer7ff7eb72015-02-18 07:47:09 +0000434 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000435 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
436 void mangleNumber(const llvm::APSInt &I);
437 void mangleNumber(int64_t Number);
438 void mangleFloat(const llvm::APFloat &F);
439 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000440 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000441 void mangleName(const NamedDecl *ND);
442 void mangleType(QualType T);
443 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
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);
Erich Keanef702b022018-07-13 19:46:04 +0000542 void mangleNeonVectorType(const DependentVectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000543 void mangleAArch64NeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000544 void mangleAArch64NeonVectorType(const DependentVectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000545
546 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000547 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000548 void mangleMemberExpr(const Expr *base, bool isArrow,
549 NestedNameSpecifier *qualifier,
550 NamedDecl *firstQualifierLookup,
551 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000552 const TemplateArgumentLoc *TemplateArgs,
553 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000554 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000555 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000556 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000557 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
Richard Smith5179eb72016-06-28 19:03:57 +0000558 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +0000559 void mangleCXXDtorType(CXXDtorType T);
560
James Y Knight04ec5bf2015-12-24 02:59:37 +0000561 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
562 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000563 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
564 unsigned NumTemplateArgs);
565 void mangleTemplateArgs(const TemplateArgumentList &AL);
566 void mangleTemplateArg(TemplateArgument A);
567
568 void mangleTemplateParameter(unsigned Index);
569
570 void mangleFunctionParam(const ParmVarDecl *parm);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000571
572 void writeAbiTags(const NamedDecl *ND,
573 const AbiTagList *AdditionalAbiTags);
574
575 // Returns sorted unique list of ABI tags.
576 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
577 // Returns sorted unique list of ABI tags.
578 AbiTagList makeVariableTypeTags(const VarDecl *VD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000579};
580
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000581}
Guy Benyei11169dd2012-12-18 14:30:41 +0000582
Rafael Espindola002667c2013-10-16 01:40:34 +0000583bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000584 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000585 if (FD) {
586 LanguageLinkage L = FD->getLanguageLinkage();
587 // Overloadable functions need mangling.
588 if (FD->hasAttr<OverloadableAttr>())
589 return true;
590
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000591 // "main" is not mangled.
592 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000593 return false;
594
595 // C++ functions and those whose names are not a simple identifier need
596 // mangling.
597 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
598 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000599
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000600 // C functions are not mangled.
601 if (L == CLanguageLinkage)
602 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000603 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000604
605 // Otherwise, no mangling is done outside C++ mode.
606 if (!getASTContext().getLangOpts().CPlusPlus)
607 return false;
608
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000609 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithbdb84f32016-07-22 23:36:59 +0000610 if (VD && !isa<DecompositionDecl>(D)) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000611 // C variables are not mangled.
612 if (VD->isExternC())
613 return false;
614
615 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000616 const DeclContext *DC = getEffectiveDeclContext(D);
617 // Check for extern variable declared locally.
618 if (DC->isFunctionOrMethod() && D->hasLinkage())
619 while (!DC->isNamespace() && !DC->isTranslationUnit())
620 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000621 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000622 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
Larisse Voufo39a1e502013-08-06 01:03:05 +0000623 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000624 return false;
625 }
626
Guy Benyei11169dd2012-12-18 14:30:41 +0000627 return true;
628}
629
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000630void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
631 const AbiTagList *AdditionalAbiTags) {
632 assert(AbiTags && "require AbiTagState");
633 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
634}
635
636void CXXNameMangler::mangleSourceNameWithAbiTags(
637 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
638 mangleSourceName(ND->getIdentifier());
639 writeAbiTags(ND, AdditionalAbiTags);
640}
641
David Majnemer7ff7eb72015-02-18 07:47:09 +0000642void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000643 // <mangled-name> ::= _Z <encoding>
644 // ::= <data name>
645 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000646 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000647 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
648 mangleFunctionEncoding(FD);
649 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
650 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000651 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
652 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000653 else
654 mangleName(cast<FieldDecl>(D));
655}
656
657void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
658 // <encoding> ::= <function name> <bare-function-type>
Guy Benyei11169dd2012-12-18 14:30:41 +0000659
660 // Don't mangle in the type if this isn't a decl we should typically mangle.
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000661 if (!Context.shouldMangleDeclName(FD)) {
662 mangleName(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000663 return;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000664 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000665
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000666 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
667 if (ReturnTypeAbiTags.empty()) {
668 // There are no tags for return type, the simplest case.
669 mangleName(FD);
670 mangleFunctionEncodingBareType(FD);
671 return;
672 }
673
674 // Mangle function name and encoding to temporary buffer.
675 // We have to output name and encoding to the same mangler to get the same
676 // substitution as it will be in final mangling.
677 SmallString<256> FunctionEncodingBuf;
678 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
679 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
680 // Output name of the function.
681 FunctionEncodingMangler.disableDerivedAbiTags();
682 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
683
684 // Remember length of the function name in the buffer.
685 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
686 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
687
688 // Get tags from return type that are not present in function name or
689 // encoding.
690 const AbiTagList &UsedAbiTags =
691 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
692 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
693 AdditionalAbiTags.erase(
694 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
695 UsedAbiTags.begin(), UsedAbiTags.end(),
696 AdditionalAbiTags.begin()),
697 AdditionalAbiTags.end());
698
699 // Output name with implicit tags and function encoding from temporary buffer.
700 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
701 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000702
703 // Function encoding could create new substitutions so we have to add
704 // temp mangled substitutions to main mangler.
705 extendSubstitutions(&FunctionEncodingMangler);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000706}
707
708void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000709 if (FD->hasAttr<EnableIfAttr>()) {
710 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
711 Out << "Ua9enable_ifI";
Michael Kruse41dd6ce2018-06-25 20:06:13 +0000712 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
713 // it here.
714 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
715 E = FD->getAttrs().rend();
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000716 I != E; ++I) {
717 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
718 if (!EIA)
719 continue;
720 Out << 'X';
721 mangleExpression(EIA->getCond());
722 Out << 'E';
723 }
724 Out << 'E';
725 FunctionTypeDepth.pop(Saved);
726 }
727
Richard Smith5179eb72016-06-28 19:03:57 +0000728 // When mangling an inheriting constructor, the bare function type used is
729 // that of the inherited constructor.
730 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
731 if (auto Inherited = CD->getInheritedConstructor())
732 FD = Inherited.getConstructor();
733
Guy Benyei11169dd2012-12-18 14:30:41 +0000734 // Whether the mangling of a function type includes the return type depends on
735 // the context and the nature of the function. The rules for deciding whether
736 // the return type is included are:
737 //
738 // 1. Template functions (names or types) have return types encoded, with
739 // the exceptions listed below.
740 // 2. Function types not appearing as part of a function name mangling,
741 // e.g. parameters, pointer types, etc., have return type encoded, with the
742 // exceptions listed below.
743 // 3. Non-template function names do not have return types encoded.
744 //
745 // The exceptions mentioned in (1) and (2) above, for which the return type is
746 // never included, are
747 // 1. Constructors.
748 // 2. Destructors.
749 // 3. Conversion operator functions, e.g. operator int.
750 bool MangleReturnType = false;
751 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
752 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
753 isa<CXXConversionDecl>(FD)))
754 MangleReturnType = true;
755
756 // Mangle the type of the primary template.
757 FD = PrimaryTemplate->getTemplatedDecl();
758 }
759
John McCall07daf722016-03-01 22:18:03 +0000760 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000761 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000762}
763
764static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
765 while (isa<LinkageSpecDecl>(DC)) {
766 DC = getEffectiveParentContext(DC);
767 }
768
769 return DC;
770}
771
Justin Bognere8d762e2015-05-22 06:48:13 +0000772/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000773static bool isStd(const NamespaceDecl *NS) {
774 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
775 ->isTranslationUnit())
776 return false;
777
778 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
779 return II && II->isStr("std");
780}
781
782// isStdNamespace - Return whether a given decl context is a toplevel 'std'
783// namespace.
784static bool isStdNamespace(const DeclContext *DC) {
785 if (!DC->isNamespace())
786 return false;
787
788 return isStd(cast<NamespaceDecl>(DC));
789}
790
791static const TemplateDecl *
792isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
793 // Check if we have a function template.
Richard Smith5179eb72016-06-28 19:03:57 +0000794 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000795 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
796 TemplateArgs = FD->getTemplateSpecializationArgs();
797 return TD;
798 }
799 }
800
801 // Check if we have a class template.
802 if (const ClassTemplateSpecializationDecl *Spec =
803 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
804 TemplateArgs = &Spec->getTemplateArgs();
805 return Spec->getSpecializedTemplate();
806 }
807
Larisse Voufo39a1e502013-08-06 01:03:05 +0000808 // Check if we have a variable template.
809 if (const VarTemplateSpecializationDecl *Spec =
810 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
811 TemplateArgs = &Spec->getTemplateArgs();
812 return Spec->getSpecializedTemplate();
813 }
814
Craig Topper36250ad2014-05-12 05:36:57 +0000815 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000816}
817
Guy Benyei11169dd2012-12-18 14:30:41 +0000818void CXXNameMangler::mangleName(const NamedDecl *ND) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000819 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
820 // Variables should have implicit tags from its type.
821 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
822 if (VariableTypeAbiTags.empty()) {
823 // Simple case no variable type tags.
824 mangleNameWithAbiTags(VD, nullptr);
825 return;
826 }
827
828 // Mangle variable name to null stream to collect tags.
829 llvm::raw_null_ostream NullOutStream;
830 CXXNameMangler VariableNameMangler(*this, NullOutStream);
831 VariableNameMangler.disableDerivedAbiTags();
832 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
833
834 // Get tags from variable type that are not present in its name.
835 const AbiTagList &UsedAbiTags =
836 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
837 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
838 AdditionalAbiTags.erase(
839 std::set_difference(VariableTypeAbiTags.begin(),
840 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
841 UsedAbiTags.end(), AdditionalAbiTags.begin()),
842 AdditionalAbiTags.end());
843
844 // Output name with implicit tags.
845 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
846 } else {
847 mangleNameWithAbiTags(ND, nullptr);
848 }
849}
850
851void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
852 const AbiTagList *AdditionalAbiTags) {
Richard Smithdd8b5332017-09-04 05:37:53 +0000853 // <name> ::= [<module-name>] <nested-name>
854 // ::= [<module-name>] <unscoped-name>
855 // ::= [<module-name>] <unscoped-template-name> <template-args>
Guy Benyei11169dd2012-12-18 14:30:41 +0000856 // ::= <local-name>
857 //
858 const DeclContext *DC = getEffectiveDeclContext(ND);
859
860 // If this is an extern variable declared locally, the relevant DeclContext
861 // is that of the containing namespace, or the translation unit.
862 // FIXME: This is a hack; extern variables declared locally should have
863 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000864 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000865 while (!DC->isNamespace() && !DC->isTranslationUnit())
866 DC = getEffectiveParentContext(DC);
867 else if (GetLocalClassDecl(ND)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000868 mangleLocalName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000869 return;
870 }
871
872 DC = IgnoreLinkageSpecDecls(DC);
873
Richard Smithdd8b5332017-09-04 05:37:53 +0000874 if (isLocalContainerContext(DC)) {
875 mangleLocalName(ND, AdditionalAbiTags);
876 return;
877 }
878
879 // Do not mangle the owning module for an external linkage declaration.
880 // This enables backwards-compatibility with non-modular code, and is
881 // a valid choice since conflicts are not permitted by C++ Modules TS
882 // [basic.def.odr]/6.2.
883 if (!ND->hasExternalFormalLinkage())
884 if (Module *M = ND->getOwningModuleForLinkage())
885 mangleModuleName(M);
886
Guy Benyei11169dd2012-12-18 14:30:41 +0000887 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
888 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000889 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000890 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000891 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000892 mangleTemplateArgs(*TemplateArgs);
893 return;
894 }
895
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000896 mangleUnscopedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000897 return;
898 }
899
Richard Smithdd8b5332017-09-04 05:37:53 +0000900 mangleNestedName(ND, DC, AdditionalAbiTags);
901}
902
903void CXXNameMangler::mangleModuleName(const Module *M) {
904 // Implement the C++ Modules TS name mangling proposal; see
905 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
906 //
907 // <module-name> ::= W <unscoped-name>+ E
908 // ::= W <module-subst> <unscoped-name>* E
909 Out << 'W';
910 mangleModuleNamePrefix(M->Name);
911 Out << 'E';
912}
913
914void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
915 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
916 // ::= W <seq-id - 10> _ # otherwise
917 auto It = ModuleSubstitutions.find(Name);
918 if (It != ModuleSubstitutions.end()) {
919 if (It->second < 10)
920 Out << '_' << static_cast<char>('0' + It->second);
921 else
922 Out << 'W' << (It->second - 10) << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +0000923 return;
924 }
925
Richard Smithdd8b5332017-09-04 05:37:53 +0000926 // FIXME: Preserve hierarchy in module names rather than flattening
927 // them to strings; use Module*s as substitution keys.
928 auto Parts = Name.rsplit('.');
929 if (Parts.second.empty())
930 Parts.second = Parts.first;
931 else
932 mangleModuleNamePrefix(Parts.first);
933
934 Out << Parts.second.size() << Parts.second;
935 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
Guy Benyei11169dd2012-12-18 14:30:41 +0000936}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000937
938void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
939 const TemplateArgument *TemplateArgs,
940 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000941 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
942
943 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000944 mangleUnscopedTemplateName(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000945 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
946 } else {
947 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
948 }
949}
950
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000951void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
952 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000953 // <unscoped-name> ::= <unqualified-name>
954 // ::= St <unqualified-name> # ::std::
955
956 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
957 Out << "St";
958
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000959 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000960}
961
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000962void CXXNameMangler::mangleUnscopedTemplateName(
963 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000964 // <unscoped-template-name> ::= <unscoped-name>
965 // ::= <substitution>
966 if (mangleSubstitution(ND))
967 return;
968
969 // <template-template-param> ::= <template-param>
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000970 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
971 assert(!AdditionalAbiTags &&
972 "template template param cannot have abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +0000973 mangleTemplateParameter(TTP->getIndex());
David Majnemer6d2b60a2016-07-12 16:48:17 +0000974 } else if (isa<BuiltinTemplateDecl>(ND)) {
975 mangleUnscopedName(ND, AdditionalAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000976 } else {
977 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
978 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000979
Guy Benyei11169dd2012-12-18 14:30:41 +0000980 addSubstitution(ND);
981}
982
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000983void CXXNameMangler::mangleUnscopedTemplateName(
984 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000985 // <unscoped-template-name> ::= <unscoped-name>
986 // ::= <substitution>
987 if (TemplateDecl *TD = Template.getAsTemplateDecl())
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000988 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000989
990 if (mangleSubstitution(Template))
991 return;
992
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000993 assert(!AdditionalAbiTags &&
994 "dependent template name cannot have abi tags");
995
Guy Benyei11169dd2012-12-18 14:30:41 +0000996 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
997 assert(Dependent && "Not a dependent template name?");
998 if (const IdentifierInfo *Id = Dependent->getIdentifier())
999 mangleSourceName(Id);
1000 else
1001 mangleOperatorName(Dependent->getOperator(), UnknownArity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001002
Guy Benyei11169dd2012-12-18 14:30:41 +00001003 addSubstitution(Template);
1004}
1005
1006void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1007 // ABI:
1008 // Floating-point literals are encoded using a fixed-length
1009 // lowercase hexadecimal string corresponding to the internal
1010 // representation (IEEE on Itanium), high-order bytes first,
1011 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1012 // on Itanium.
1013 // The 'without leading zeroes' thing seems to be an editorial
1014 // mistake; see the discussion on cxx-abi-dev beginning on
1015 // 2012-01-16.
1016
1017 // Our requirements here are just barely weird enough to justify
1018 // using a custom algorithm instead of post-processing APInt::toString().
1019
1020 llvm::APInt valueBits = f.bitcastToAPInt();
1021 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1022 assert(numCharacters != 0);
1023
1024 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +00001025 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +00001026
1027 // Fill the buffer left-to-right.
1028 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1029 // The bit-index of the next hex digit.
1030 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1031
1032 // Project out 4 bits starting at 'digitIndex'.
Craig Topperc396c532017-03-30 05:48:58 +00001033 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1034 hexDigit >>= (digitBitIndex % 64);
Guy Benyei11169dd2012-12-18 14:30:41 +00001035 hexDigit &= 0xF;
1036
1037 // Map that over to a lowercase hex digit.
1038 static const char charForHex[16] = {
1039 '0', '1', '2', '3', '4', '5', '6', '7',
1040 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1041 };
1042 buffer[stringIndex] = charForHex[hexDigit];
1043 }
1044
1045 Out.write(buffer.data(), numCharacters);
1046}
1047
1048void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1049 if (Value.isSigned() && Value.isNegative()) {
1050 Out << 'n';
1051 Value.abs().print(Out, /*signed*/ false);
1052 } else {
1053 Value.print(Out, /*signed*/ false);
1054 }
1055}
1056
1057void CXXNameMangler::mangleNumber(int64_t Number) {
1058 // <number> ::= [n] <non-negative decimal integer>
1059 if (Number < 0) {
1060 Out << 'n';
1061 Number = -Number;
1062 }
1063
1064 Out << Number;
1065}
1066
1067void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1068 // <call-offset> ::= h <nv-offset> _
1069 // ::= v <v-offset> _
1070 // <nv-offset> ::= <offset number> # non-virtual base override
1071 // <v-offset> ::= <offset number> _ <virtual offset number>
1072 // # virtual base override, with vcall offset
1073 if (!Virtual) {
1074 Out << 'h';
1075 mangleNumber(NonVirtual);
1076 Out << '_';
1077 return;
1078 }
1079
1080 Out << 'v';
1081 mangleNumber(NonVirtual);
1082 Out << '_';
1083 mangleNumber(Virtual);
1084 Out << '_';
1085}
1086
1087void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +00001088 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001089 if (!mangleSubstitution(QualType(TST, 0))) {
1090 mangleTemplatePrefix(TST->getTemplateName());
1091
1092 // FIXME: GCC does not appear to mangle the template arguments when
1093 // the template in question is a dependent template name. Should we
1094 // emulate that badness?
1095 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1096 addSubstitution(QualType(TST, 0));
1097 }
David Majnemera88b3592015-02-18 02:28:01 +00001098 } else if (const auto *DTST =
1099 type->getAs<DependentTemplateSpecializationType>()) {
1100 if (!mangleSubstitution(QualType(DTST, 0))) {
1101 TemplateName Template = getASTContext().getDependentTemplateName(
1102 DTST->getQualifier(), DTST->getIdentifier());
1103 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +00001104
David Majnemera88b3592015-02-18 02:28:01 +00001105 // FIXME: GCC does not appear to mangle the template arguments when
1106 // the template in question is a dependent template name. Should we
1107 // emulate that badness?
1108 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1109 addSubstitution(QualType(DTST, 0));
1110 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001111 } else {
1112 // We use the QualType mangle type variant here because it handles
1113 // substitutions.
1114 mangleType(type);
1115 }
1116}
1117
1118/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1119///
Guy Benyei11169dd2012-12-18 14:30:41 +00001120/// \param recursive - true if this is being called recursively,
1121/// i.e. if there is more prefix "to the right".
1122void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +00001123 bool recursive) {
1124
1125 // x, ::x
1126 // <unresolved-name> ::= [gs] <base-unresolved-name>
1127
1128 // T::x / decltype(p)::x
1129 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1130
1131 // T::N::x /decltype(p)::N::x
1132 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1133 // <base-unresolved-name>
1134
1135 // A::x, N::y, A<T>::z; "gs" means leading "::"
1136 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1137 // <base-unresolved-name>
1138
1139 switch (qualifier->getKind()) {
1140 case NestedNameSpecifier::Global:
1141 Out << "gs";
1142
1143 // We want an 'sr' unless this is the entire NNS.
1144 if (recursive)
1145 Out << "sr";
1146
1147 // We never want an 'E' here.
1148 return;
1149
Nikola Smiljanic67860242014-09-26 00:28:20 +00001150 case NestedNameSpecifier::Super:
1151 llvm_unreachable("Can't mangle __super specifier");
1152
Guy Benyei11169dd2012-12-18 14:30:41 +00001153 case NestedNameSpecifier::Namespace:
1154 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001155 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001156 /*recursive*/ true);
1157 else
1158 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001159 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
Guy Benyei11169dd2012-12-18 14:30:41 +00001160 break;
1161 case NestedNameSpecifier::NamespaceAlias:
1162 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001163 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001164 /*recursive*/ true);
1165 else
1166 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001167 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 break;
1169
1170 case NestedNameSpecifier::TypeSpec:
1171 case NestedNameSpecifier::TypeSpecWithTemplate: {
1172 const Type *type = qualifier->getAsType();
1173
1174 // We only want to use an unresolved-type encoding if this is one of:
1175 // - a decltype
1176 // - a template type parameter
1177 // - a template template parameter with arguments
1178 // In all of these cases, we should have no prefix.
1179 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001180 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001181 /*recursive*/ true);
1182 } else {
1183 // Otherwise, all the cases want this.
1184 Out << "sr";
1185 }
1186
David Majnemerb8014dd2015-02-19 02:16:16 +00001187 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +00001188 return;
1189
Guy Benyei11169dd2012-12-18 14:30:41 +00001190 break;
1191 }
1192
1193 case NestedNameSpecifier::Identifier:
1194 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +00001195 if (qualifier->getPrefix())
1196 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001197 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +00001198 else
Guy Benyei11169dd2012-12-18 14:30:41 +00001199 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +00001200
1201 mangleSourceName(qualifier->getAsIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001202 // An Identifier has no type information, so we can't emit abi tags for it.
Guy Benyei11169dd2012-12-18 14:30:41 +00001203 break;
1204 }
1205
1206 // If this was the innermost part of the NNS, and we fell out to
1207 // here, append an 'E'.
1208 if (!recursive)
1209 Out << 'E';
1210}
1211
1212/// Mangle an unresolved-name, which is generally used for names which
1213/// weren't resolved to specific entities.
Richard Smithafecd832016-10-24 20:47:04 +00001214void CXXNameMangler::mangleUnresolvedName(
1215 NestedNameSpecifier *qualifier, DeclarationName name,
1216 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1217 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001218 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001219 switch (name.getNameKind()) {
1220 // <base-unresolved-name> ::= <simple-id>
1221 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +00001222 mangleSourceName(name.getAsIdentifierInfo());
1223 break;
1224 // <base-unresolved-name> ::= dn <destructor-name>
1225 case DeclarationName::CXXDestructorName:
1226 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +00001227 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +00001228 break;
1229 // <base-unresolved-name> ::= on <operator-name>
1230 case DeclarationName::CXXConversionFunctionName:
1231 case DeclarationName::CXXLiteralOperatorName:
1232 case DeclarationName::CXXOperatorName:
1233 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +00001234 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001235 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +00001236 case DeclarationName::CXXConstructorName:
1237 llvm_unreachable("Can't mangle a constructor name!");
1238 case DeclarationName::CXXUsingDirective:
1239 llvm_unreachable("Can't mangle a using directive name!");
Richard Smith35845152017-02-07 01:37:30 +00001240 case DeclarationName::CXXDeductionGuideName:
1241 llvm_unreachable("Can't mangle a deduction guide name!");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001242 case DeclarationName::ObjCMultiArgSelector:
1243 case DeclarationName::ObjCOneArgSelector:
1244 case DeclarationName::ObjCZeroArgSelector:
1245 llvm_unreachable("Can't mangle Objective-C selector names here!");
1246 }
Richard Smithafecd832016-10-24 20:47:04 +00001247
1248 // The <simple-id> and on <operator-name> productions end in an optional
1249 // <template-args>.
1250 if (TemplateArgs)
1251 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00001252}
1253
Guy Benyei11169dd2012-12-18 14:30:41 +00001254void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1255 DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001256 unsigned KnownArity,
1257 const AbiTagList *AdditionalAbiTags) {
David Majnemera88b3592015-02-18 02:28:01 +00001258 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +00001259 // <unqualified-name> ::= <operator-name>
1260 // ::= <ctor-dtor-name>
1261 // ::= <source-name>
1262 switch (Name.getNameKind()) {
1263 case DeclarationName::Identifier: {
Richard Smithbdb84f32016-07-22 23:36:59 +00001264 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1265
Richard Smithda383632016-08-15 01:33:41 +00001266 // We mangle decomposition declarations as the names of their bindings.
Richard Smithbdb84f32016-07-22 23:36:59 +00001267 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
Richard Smithda383632016-08-15 01:33:41 +00001268 // FIXME: Non-standard mangling for decomposition declarations:
1269 //
1270 // <unqualified-name> ::= DC <source-name>* E
1271 //
1272 // These can never be referenced across translation units, so we do
1273 // not need a cross-vendor mangling for anything other than demanglers.
1274 // Proposed on cxx-abi-dev on 2016-08-12
1275 Out << "DC";
1276 for (auto *BD : DD->bindings())
1277 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1278 Out << 'E';
1279 writeAbiTags(ND, AdditionalAbiTags);
1280 break;
Richard Smithbdb84f32016-07-22 23:36:59 +00001281 }
1282
1283 if (II) {
Richard Smithdd8b5332017-09-04 05:37:53 +00001284 // Match GCC's naming convention for internal linkage symbols, for
1285 // symbols that are not actually visible outside of this TU. GCC
1286 // distinguishes between internal and external linkage symbols in
1287 // its mangling, to support cases like this that were valid C++ prior
1288 // to DR426:
1289 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001290 // void test() { extern void foo(); }
1291 // static void foo();
Richard Smithdf963a32017-09-22 22:21:44 +00001292 //
1293 // Don't bother with the L marker for names in anonymous namespaces; the
1294 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1295 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1296 // implying internal linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001297 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Richard Smithdd8b5332017-09-04 05:37:53 +00001298 !ND->isExternallyVisible() &&
Richard Smithdf963a32017-09-22 22:21:44 +00001299 getEffectiveDeclContext(ND)->isFileContext() &&
1300 !ND->isInAnonymousNamespace())
Guy Benyei11169dd2012-12-18 14:30:41 +00001301 Out << 'L';
1302
Erich Keane757d3172016-11-02 18:29:35 +00001303 auto *FD = dyn_cast<FunctionDecl>(ND);
1304 bool IsRegCall = FD &&
1305 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1306 clang::CC_X86RegCall;
1307 if (IsRegCall)
1308 mangleRegCallName(II);
1309 else
1310 mangleSourceName(II);
1311
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001312 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001313 break;
1314 }
1315
1316 // Otherwise, an anonymous entity. We must have a declaration.
1317 assert(ND && "mangling empty name without declaration");
1318
1319 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1320 if (NS->isAnonymousNamespace()) {
1321 // This is how gcc mangles these names.
1322 Out << "12_GLOBAL__N_1";
1323 break;
1324 }
1325 }
1326
1327 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1328 // We must have an anonymous union or struct declaration.
George Burgess IV00f70bd2018-03-01 05:43:23 +00001329 const RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001330
Guy Benyei11169dd2012-12-18 14:30:41 +00001331 // Itanium C++ ABI 5.1.2:
1332 //
1333 // For the purposes of mangling, the name of an anonymous union is
1334 // considered to be the name of the first named data member found by a
1335 // pre-order, depth-first, declaration-order walk of the data members of
1336 // the anonymous union. If there is no such data member (i.e., if all of
1337 // the data members in the union are unnamed), then there is no way for
1338 // a program to refer to the anonymous union, and there is therefore no
1339 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001340 assert(RD->isAnonymousStructOrUnion()
1341 && "Expected anonymous struct or union!");
1342 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +00001343
1344 // It's actually possible for various reasons for us to get here
1345 // with an empty anonymous struct / union. Fortunately, it
1346 // doesn't really matter what name we generate.
1347 if (!FD) break;
1348 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001349
Guy Benyei11169dd2012-12-18 14:30:41 +00001350 mangleSourceName(FD->getIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001351 // Not emitting abi tags: internal name anyway.
Guy Benyei11169dd2012-12-18 14:30:41 +00001352 break;
1353 }
John McCall924046f2013-04-10 06:08:21 +00001354
1355 // Class extensions have no name as a category, and it's possible
1356 // for them to be the semantic parent of certain declarations
1357 // (primarily, tag decls defined within declarations). Such
1358 // declarations will always have internal linkage, so the name
1359 // doesn't really matter, but we shouldn't crash on them. For
1360 // safety, just handle all ObjC containers here.
1361 if (isa<ObjCContainerDecl>(ND))
1362 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001363
1364 // We must have an anonymous struct.
1365 const TagDecl *TD = cast<TagDecl>(ND);
1366 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1367 assert(TD->getDeclContext() == D->getDeclContext() &&
1368 "Typedef should not be in another decl context!");
1369 assert(D->getDeclName().getAsIdentifierInfo() &&
1370 "Typedef was not named!");
1371 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001372 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1373 // Explicit abi tags are still possible; take from underlying type, not
1374 // from typedef.
1375 writeAbiTags(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001376 break;
1377 }
1378
1379 // <unnamed-type-name> ::= <closure-type-name>
1380 //
1381 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1382 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1383 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1384 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001385 assert(!AdditionalAbiTags &&
1386 "Lambda type cannot have additional abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +00001387 mangleLambda(Record);
1388 break;
1389 }
1390 }
1391
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001392 if (TD->isExternallyVisible()) {
1393 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001394 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001395 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001396 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 Out << '_';
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001398 writeAbiTags(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001399 break;
1400 }
1401
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001402 // Get a unique id for the anonymous struct. If it is not a real output
1403 // ID doesn't matter so use fake one.
1404 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001405
1406 // Mangle it as a source name in the form
1407 // [n] $_<id>
1408 // where n is the length of the string.
1409 SmallString<8> Str;
1410 Str += "$_";
1411 Str += llvm::utostr(AnonStructId);
1412
1413 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001414 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001415 break;
1416 }
1417
1418 case DeclarationName::ObjCZeroArgSelector:
1419 case DeclarationName::ObjCOneArgSelector:
1420 case DeclarationName::ObjCMultiArgSelector:
1421 llvm_unreachable("Can't mangle Objective-C selector names here!");
1422
Richard Smith5179eb72016-06-28 19:03:57 +00001423 case DeclarationName::CXXConstructorName: {
1424 const CXXRecordDecl *InheritedFrom = nullptr;
1425 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1426 if (auto Inherited =
1427 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1428 InheritedFrom = Inherited.getConstructor()->getParent();
1429 InheritedTemplateArgs =
1430 Inherited.getConstructor()->getTemplateSpecializationArgs();
1431 }
1432
Guy Benyei11169dd2012-12-18 14:30:41 +00001433 if (ND == Structor)
1434 // If the named decl is the C++ constructor we're mangling, use the type
1435 // we were given.
Richard Smith5179eb72016-06-28 19:03:57 +00001436 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00001437 else
1438 // Otherwise, use the complete constructor name. This is relevant if a
1439 // class with a constructor is declared within a constructor.
Richard Smith5179eb72016-06-28 19:03:57 +00001440 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1441
1442 // FIXME: The template arguments are part of the enclosing prefix or
1443 // nested-name, but it's more convenient to mangle them here.
1444 if (InheritedTemplateArgs)
1445 mangleTemplateArgs(*InheritedTemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001446
1447 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001448 break;
Richard Smith5179eb72016-06-28 19:03:57 +00001449 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001450
1451 case DeclarationName::CXXDestructorName:
1452 if (ND == Structor)
1453 // If the named decl is the C++ destructor we're mangling, use the type we
1454 // were given.
1455 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1456 else
1457 // Otherwise, use the complete destructor name. This is relevant if a
1458 // class with a destructor is declared within a destructor.
1459 mangleCXXDtorType(Dtor_Complete);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001460 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001461 break;
1462
David Majnemera88b3592015-02-18 02:28:01 +00001463 case DeclarationName::CXXOperatorName:
1464 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001465 Arity = cast<FunctionDecl>(ND)->getNumParams();
1466
David Majnemera88b3592015-02-18 02:28:01 +00001467 // If we have a member function, we need to include the 'this' pointer.
1468 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1469 if (!MD->isStatic())
1470 Arity++;
1471 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001472 LLVM_FALLTHROUGH;
David Majnemera88b3592015-02-18 02:28:01 +00001473 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001474 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001475 mangleOperatorName(Name, Arity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001476 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001477 break;
1478
Richard Smith35845152017-02-07 01:37:30 +00001479 case DeclarationName::CXXDeductionGuideName:
1480 llvm_unreachable("Can't mangle a deduction guide name!");
1481
Guy Benyei11169dd2012-12-18 14:30:41 +00001482 case DeclarationName::CXXUsingDirective:
1483 llvm_unreachable("Can't mangle a using directive name!");
1484 }
1485}
1486
Erich Keane757d3172016-11-02 18:29:35 +00001487void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1488 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1489 // <number> ::= [n] <non-negative decimal integer>
1490 // <identifier> ::= <unqualified source code identifier>
1491 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1492 << II->getName();
1493}
1494
Guy Benyei11169dd2012-12-18 14:30:41 +00001495void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1496 // <source-name> ::= <positive length number> <identifier>
1497 // <number> ::= [n] <non-negative decimal integer>
1498 // <identifier> ::= <unqualified source code identifier>
1499 Out << II->getLength() << II->getName();
1500}
1501
1502void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1503 const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001504 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +00001505 bool NoFunction) {
1506 // <nested-name>
1507 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1508 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1509 // <template-args> E
1510
1511 Out << 'N';
1512 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001513 Qualifiers MethodQuals =
Roger Ferrer Ibanezcb895132017-04-19 12:23:28 +00001514 Qualifiers::fromCVRUMask(Method->getTypeQualifiers());
David Majnemer42350df2013-11-03 23:51:28 +00001515 // We do not consider restrict a distinguishing attribute for overloading
1516 // purposes so we must not mangle it.
1517 MethodQuals.removeRestrict();
1518 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 mangleRefQualifier(Method->getRefQualifier());
1520 }
1521
1522 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001523 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001524 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001525 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001526 mangleTemplateArgs(*TemplateArgs);
1527 }
1528 else {
1529 manglePrefix(DC, NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001530 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001531 }
1532
1533 Out << 'E';
1534}
1535void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1536 const TemplateArgument *TemplateArgs,
1537 unsigned NumTemplateArgs) {
1538 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1539
1540 Out << 'N';
1541
1542 mangleTemplatePrefix(TD);
1543 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1544
1545 Out << 'E';
1546}
1547
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001548void CXXNameMangler::mangleLocalName(const Decl *D,
1549 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001550 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1551 // := Z <function encoding> E s [<discriminator>]
1552 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1553 // _ <entity name>
1554 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001555 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001556 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001557 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001558
1559 Out << 'Z';
1560
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001561 {
1562 AbiTagState LocalAbiTags(AbiTags);
1563
1564 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1565 mangleObjCMethodName(MD);
1566 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1567 mangleBlockForPrefix(BD);
1568 else
1569 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1570
1571 // Implicit ABI tags (from namespace) are not available in the following
1572 // entity; reset to actually emitted tags, which are available.
1573 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1574 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001575
Eli Friedman92821742013-07-02 02:01:18 +00001576 Out << 'E';
1577
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001578 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1579 // be a bug that is fixed in trunk.
1580
Eli Friedman92821742013-07-02 02:01:18 +00001581 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001582 // The parameter number is omitted for the last parameter, 0 for the
1583 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1584 // <entity name> will of course contain a <closure-type-name>: Its
1585 // numbering will be local to the particular argument in which it appears
1586 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001587 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithcb2ba5a2016-07-18 22:37:35 +00001588 if (CXXRD && CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001589 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001590 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001591 if (const FunctionDecl *Func
1592 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1593 Out << 'd';
1594 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1595 if (Num > 1)
1596 mangleNumber(Num - 2);
1597 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001598 }
1599 }
1600 }
1601
1602 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001603 // equality ok because RD derived from ND above
1604 if (D == RD) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001605 mangleUnqualifiedName(RD, AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +00001606 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1607 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001608 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman95f50122013-07-02 17:52:28 +00001609 mangleUnqualifiedBlock(BD);
1610 } else {
1611 const NamedDecl *ND = cast<NamedDecl>(D);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001612 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1613 true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001614 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001615 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1616 // Mangle a block in a default parameter; see above explanation for
1617 // lambdas.
1618 if (const ParmVarDecl *Parm
1619 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1620 if (const FunctionDecl *Func
1621 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1622 Out << 'd';
1623 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1624 if (Num > 1)
1625 mangleNumber(Num - 2);
1626 Out << '_';
1627 }
1628 }
1629
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001630 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman0cd23352013-07-10 01:33:19 +00001631 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001632 } else {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001633 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001634 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001635
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001636 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1637 unsigned disc;
1638 if (Context.getNextDiscriminator(ND, disc)) {
1639 if (disc < 10)
1640 Out << '_' << disc;
1641 else
1642 Out << "__" << disc << '_';
1643 }
1644 }
Eli Friedman95f50122013-07-02 17:52:28 +00001645}
1646
1647void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1648 if (GetLocalClassDecl(Block)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001649 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001650 return;
1651 }
1652 const DeclContext *DC = getEffectiveDeclContext(Block);
1653 if (isLocalContainerContext(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001654 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001655 return;
1656 }
1657 manglePrefix(getEffectiveDeclContext(Block));
1658 mangleUnqualifiedBlock(Block);
1659}
1660
1661void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1662 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1663 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1664 Context->getDeclContext()->isRecord()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001665 const auto *ND = cast<NamedDecl>(Context);
1666 if (ND->getIdentifier()) {
1667 mangleSourceNameWithAbiTags(ND);
1668 Out << 'M';
Eli Friedman95f50122013-07-02 17:52:28 +00001669 }
1670 }
1671 }
1672
1673 // If we have a block mangling number, use it.
1674 unsigned Number = Block->getBlockManglingNumber();
1675 // Otherwise, just make up a number. It doesn't matter what it is because
1676 // the symbol in question isn't externally visible.
1677 if (!Number)
1678 Number = Context.getBlockId(Block, false);
Richard Smith48b35d92017-09-07 05:41:24 +00001679 else {
1680 // Stored mangling numbers are 1-based.
1681 --Number;
1682 }
Eli Friedman95f50122013-07-02 17:52:28 +00001683 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001684 if (Number > 0)
1685 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001686 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001687}
1688
1689void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1690 // If the context of a closure type is an initializer for a class member
1691 // (static or nonstatic), it is encoded in a qualified name with a final
1692 // <prefix> of the form:
1693 //
1694 // <data-member-prefix> := <member source-name> M
1695 //
1696 // Technically, the data-member-prefix is part of the <prefix>. However,
1697 // since a closure type will always be mangled with a prefix, it's easier
1698 // to emit that last part of the prefix here.
1699 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1700 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
Richard Smithc95d2c52017-09-22 04:25:05 +00001701 !isa<ParmVarDecl>(Context)) {
1702 // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1703 // reasonable mangling here.
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 if (const IdentifierInfo *Name
1705 = cast<NamedDecl>(Context)->getIdentifier()) {
1706 mangleSourceName(Name);
Richard Smithc95d2c52017-09-22 04:25:05 +00001707 const TemplateArgumentList *TemplateArgs = nullptr;
Simon Pilgrimb2eda762017-09-22 16:26:17 +00001708 if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
Richard Smithc95d2c52017-09-22 04:25:05 +00001709 mangleTemplateArgs(*TemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001710 Out << 'M';
Guy Benyei11169dd2012-12-18 14:30:41 +00001711 }
1712 }
1713 }
1714
1715 Out << "Ul";
1716 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1717 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001718 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1719 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001720 Out << "E";
1721
1722 // The number is omitted for the first closure type with a given
1723 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1724 // (in lexical order) with that same <lambda-sig> and context.
1725 //
1726 // The AST keeps track of the number for us.
1727 unsigned Number = Lambda->getLambdaManglingNumber();
1728 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1729 if (Number > 1)
1730 mangleNumber(Number - 2);
1731 Out << '_';
1732}
1733
1734void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1735 switch (qualifier->getKind()) {
1736 case NestedNameSpecifier::Global:
1737 // nothing
1738 return;
1739
Nikola Smiljanic67860242014-09-26 00:28:20 +00001740 case NestedNameSpecifier::Super:
1741 llvm_unreachable("Can't mangle __super specifier");
1742
Guy Benyei11169dd2012-12-18 14:30:41 +00001743 case NestedNameSpecifier::Namespace:
1744 mangleName(qualifier->getAsNamespace());
1745 return;
1746
1747 case NestedNameSpecifier::NamespaceAlias:
1748 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1749 return;
1750
1751 case NestedNameSpecifier::TypeSpec:
1752 case NestedNameSpecifier::TypeSpecWithTemplate:
1753 manglePrefix(QualType(qualifier->getAsType(), 0));
1754 return;
1755
1756 case NestedNameSpecifier::Identifier:
1757 // Member expressions can have these without prefixes, but that
1758 // should end up in mangleUnresolvedPrefix instead.
1759 assert(qualifier->getPrefix());
1760 manglePrefix(qualifier->getPrefix());
1761
1762 mangleSourceName(qualifier->getAsIdentifier());
1763 return;
1764 }
1765
1766 llvm_unreachable("unexpected nested name specifier");
1767}
1768
1769void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1770 // <prefix> ::= <prefix> <unqualified-name>
1771 // ::= <template-prefix> <template-args>
1772 // ::= <template-param>
1773 // ::= # empty
1774 // ::= <substitution>
1775
1776 DC = IgnoreLinkageSpecDecls(DC);
1777
1778 if (DC->isTranslationUnit())
1779 return;
1780
Eli Friedman95f50122013-07-02 17:52:28 +00001781 if (NoFunction && isLocalContainerContext(DC))
1782 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001783
Eli Friedman95f50122013-07-02 17:52:28 +00001784 assert(!isLocalContainerContext(DC));
1785
Guy Benyei11169dd2012-12-18 14:30:41 +00001786 const NamedDecl *ND = cast<NamedDecl>(DC);
1787 if (mangleSubstitution(ND))
1788 return;
1789
1790 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001791 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001792 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1793 mangleTemplatePrefix(TD);
1794 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001795 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001796 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001797 mangleUnqualifiedName(ND, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001798 }
1799
1800 addSubstitution(ND);
1801}
1802
1803void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1804 // <template-prefix> ::= <prefix> <template unqualified-name>
1805 // ::= <template-param>
1806 // ::= <substitution>
1807 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1808 return mangleTemplatePrefix(TD);
1809
1810 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1811 manglePrefix(Qualified->getQualifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001812
Guy Benyei11169dd2012-12-18 14:30:41 +00001813 if (OverloadedTemplateStorage *Overloaded
1814 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001815 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001816 UnknownArity, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001817 return;
1818 }
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001819
Guy Benyei11169dd2012-12-18 14:30:41 +00001820 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1821 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001822 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1823 manglePrefix(Qualifier);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001824 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001825}
1826
Eli Friedman86af13f02013-07-05 18:41:30 +00001827void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1828 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001829 // <template-prefix> ::= <prefix> <template unqualified-name>
1830 // ::= <template-param>
1831 // ::= <substitution>
1832 // <template-template-param> ::= <template-param>
1833 // <substitution>
1834
1835 if (mangleSubstitution(ND))
1836 return;
1837
1838 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001839 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001840 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001841 } else {
1842 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
David Majnemer6d2b60a2016-07-12 16:48:17 +00001843 if (isa<BuiltinTemplateDecl>(ND))
1844 mangleUnqualifiedName(ND, nullptr);
1845 else
1846 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001847 }
1848
Guy Benyei11169dd2012-12-18 14:30:41 +00001849 addSubstitution(ND);
1850}
1851
1852/// Mangles a template name under the production <type>. Required for
1853/// template template arguments.
1854/// <type> ::= <class-enum-type>
1855/// ::= <template-param>
1856/// ::= <substitution>
1857void CXXNameMangler::mangleType(TemplateName TN) {
1858 if (mangleSubstitution(TN))
1859 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001860
1861 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001862
1863 switch (TN.getKind()) {
1864 case TemplateName::QualifiedTemplate:
1865 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1866 goto HaveDecl;
1867
1868 case TemplateName::Template:
1869 TD = TN.getAsTemplateDecl();
1870 goto HaveDecl;
1871
1872 HaveDecl:
1873 if (isa<TemplateTemplateParmDecl>(TD))
1874 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1875 else
1876 mangleName(TD);
1877 break;
1878
1879 case TemplateName::OverloadedTemplate:
1880 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1881
1882 case TemplateName::DependentTemplate: {
1883 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1884 assert(Dependent->isIdentifier());
1885
1886 // <class-enum-type> ::= <name>
1887 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001888 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001889 mangleSourceName(Dependent->getIdentifier());
1890 break;
1891 }
1892
1893 case TemplateName::SubstTemplateTemplateParm: {
1894 // Substituted template parameters are mangled as the substituted
1895 // template. This will check for the substitution twice, which is
1896 // fine, but we have to return early so that we don't try to *add*
1897 // the substitution twice.
1898 SubstTemplateTemplateParmStorage *subst
1899 = TN.getAsSubstTemplateTemplateParm();
1900 mangleType(subst->getReplacement());
1901 return;
1902 }
1903
1904 case TemplateName::SubstTemplateTemplateParmPack: {
1905 // FIXME: not clear how to mangle this!
1906 // template <template <class> class T...> class A {
1907 // template <template <class> class U...> void foo(B<T,U> x...);
1908 // };
1909 Out << "_SUBSTPACK_";
1910 break;
1911 }
1912 }
1913
1914 addSubstitution(TN);
1915}
1916
David Majnemerb8014dd2015-02-19 02:16:16 +00001917bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1918 StringRef Prefix) {
1919 // Only certain other types are valid as prefixes; enumerate them.
1920 switch (Ty->getTypeClass()) {
1921 case Type::Builtin:
1922 case Type::Complex:
1923 case Type::Adjusted:
1924 case Type::Decayed:
1925 case Type::Pointer:
1926 case Type::BlockPointer:
1927 case Type::LValueReference:
1928 case Type::RValueReference:
1929 case Type::MemberPointer:
1930 case Type::ConstantArray:
1931 case Type::IncompleteArray:
1932 case Type::VariableArray:
1933 case Type::DependentSizedArray:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001934 case Type::DependentAddressSpace:
Erich Keanef702b022018-07-13 19:46:04 +00001935 case Type::DependentVector:
David Majnemerb8014dd2015-02-19 02:16:16 +00001936 case Type::DependentSizedExtVector:
1937 case Type::Vector:
1938 case Type::ExtVector:
1939 case Type::FunctionProto:
1940 case Type::FunctionNoProto:
1941 case Type::Paren:
1942 case Type::Attributed:
1943 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001944 case Type::DeducedTemplateSpecialization:
David Majnemerb8014dd2015-02-19 02:16:16 +00001945 case Type::PackExpansion:
1946 case Type::ObjCObject:
1947 case Type::ObjCInterface:
1948 case Type::ObjCObjectPointer:
Manman Rene6be26c2016-09-13 17:25:08 +00001949 case Type::ObjCTypeParam:
David Majnemerb8014dd2015-02-19 02:16:16 +00001950 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001951 case Type::Pipe:
David Majnemerb8014dd2015-02-19 02:16:16 +00001952 llvm_unreachable("type is illegal as a nested name specifier");
1953
1954 case Type::SubstTemplateTypeParmPack:
1955 // FIXME: not clear how to mangle this!
1956 // template <class T...> class A {
1957 // template <class U...> void foo(decltype(T::foo(U())) x...);
1958 // };
1959 Out << "_SUBSTPACK_";
1960 break;
1961
1962 // <unresolved-type> ::= <template-param>
1963 // ::= <decltype>
1964 // ::= <template-template-param> <template-args>
1965 // (this last is not official yet)
1966 case Type::TypeOfExpr:
1967 case Type::TypeOf:
1968 case Type::Decltype:
1969 case Type::TemplateTypeParm:
1970 case Type::UnaryTransform:
1971 case Type::SubstTemplateTypeParm:
1972 unresolvedType:
1973 // Some callers want a prefix before the mangled type.
1974 Out << Prefix;
1975
1976 // This seems to do everything we want. It's not really
1977 // sanctioned for a substituted template parameter, though.
1978 mangleType(Ty);
1979
1980 // We never want to print 'E' directly after an unresolved-type,
1981 // so we return directly.
1982 return true;
1983
1984 case Type::Typedef:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001985 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001986 break;
1987
1988 case Type::UnresolvedUsing:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001989 mangleSourceNameWithAbiTags(
1990 cast<UnresolvedUsingType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001991 break;
1992
1993 case Type::Enum:
1994 case Type::Record:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001995 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001996 break;
1997
1998 case Type::TemplateSpecialization: {
1999 const TemplateSpecializationType *TST =
2000 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00002001 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00002002 switch (TN.getKind()) {
2003 case TemplateName::Template:
2004 case TemplateName::QualifiedTemplate: {
2005 TemplateDecl *TD = TN.getAsTemplateDecl();
2006
2007 // If the base is a template template parameter, this is an
2008 // unresolved type.
2009 assert(TD && "no template for template specialization type");
2010 if (isa<TemplateTemplateParmDecl>(TD))
2011 goto unresolvedType;
2012
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002013 mangleSourceNameWithAbiTags(TD);
David Majnemerb8014dd2015-02-19 02:16:16 +00002014 break;
David Majnemera88b3592015-02-18 02:28:01 +00002015 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002016
2017 case TemplateName::OverloadedTemplate:
2018 case TemplateName::DependentTemplate:
2019 llvm_unreachable("invalid base for a template specialization type");
2020
2021 case TemplateName::SubstTemplateTemplateParm: {
2022 SubstTemplateTemplateParmStorage *subst =
2023 TN.getAsSubstTemplateTemplateParm();
2024 mangleExistingSubstitution(subst->getReplacement());
2025 break;
2026 }
2027
2028 case TemplateName::SubstTemplateTemplateParmPack: {
2029 // FIXME: not clear how to mangle this!
2030 // template <template <class U> class T...> class A {
2031 // template <class U...> void foo(decltype(T<U>::foo) x...);
2032 // };
2033 Out << "_SUBSTPACK_";
2034 break;
2035 }
2036 }
2037
David Majnemera88b3592015-02-18 02:28:01 +00002038 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00002039 break;
David Majnemera88b3592015-02-18 02:28:01 +00002040 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002041
2042 case Type::InjectedClassName:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002043 mangleSourceNameWithAbiTags(
2044 cast<InjectedClassNameType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002045 break;
2046
2047 case Type::DependentName:
2048 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2049 break;
2050
2051 case Type::DependentTemplateSpecialization: {
2052 const DependentTemplateSpecializationType *DTST =
2053 cast<DependentTemplateSpecializationType>(Ty);
2054 mangleSourceName(DTST->getIdentifier());
2055 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2056 break;
2057 }
2058
2059 case Type::Elaborated:
2060 return mangleUnresolvedTypeOrSimpleId(
2061 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2062 }
2063
2064 return false;
David Majnemera88b3592015-02-18 02:28:01 +00002065}
2066
2067void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2068 switch (Name.getNameKind()) {
2069 case DeclarationName::CXXConstructorName:
2070 case DeclarationName::CXXDestructorName:
Richard Smith35845152017-02-07 01:37:30 +00002071 case DeclarationName::CXXDeductionGuideName:
David Majnemera88b3592015-02-18 02:28:01 +00002072 case DeclarationName::CXXUsingDirective:
2073 case DeclarationName::Identifier:
2074 case DeclarationName::ObjCMultiArgSelector:
2075 case DeclarationName::ObjCOneArgSelector:
2076 case DeclarationName::ObjCZeroArgSelector:
2077 llvm_unreachable("Not an operator name");
2078
2079 case DeclarationName::CXXConversionFunctionName:
2080 // <operator-name> ::= cv <type> # (cast)
2081 Out << "cv";
2082 mangleType(Name.getCXXNameType());
2083 break;
2084
2085 case DeclarationName::CXXLiteralOperatorName:
2086 Out << "li";
2087 mangleSourceName(Name.getCXXLiteralIdentifier());
2088 return;
2089
2090 case DeclarationName::CXXOperatorName:
2091 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2092 break;
2093 }
2094}
2095
Guy Benyei11169dd2012-12-18 14:30:41 +00002096void
2097CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2098 switch (OO) {
2099 // <operator-name> ::= nw # new
2100 case OO_New: Out << "nw"; break;
2101 // ::= na # new[]
2102 case OO_Array_New: Out << "na"; break;
2103 // ::= dl # delete
2104 case OO_Delete: Out << "dl"; break;
2105 // ::= da # delete[]
2106 case OO_Array_Delete: Out << "da"; break;
2107 // ::= ps # + (unary)
2108 // ::= pl # + (binary or unknown)
2109 case OO_Plus:
2110 Out << (Arity == 1? "ps" : "pl"); break;
2111 // ::= ng # - (unary)
2112 // ::= mi # - (binary or unknown)
2113 case OO_Minus:
2114 Out << (Arity == 1? "ng" : "mi"); break;
2115 // ::= ad # & (unary)
2116 // ::= an # & (binary or unknown)
2117 case OO_Amp:
2118 Out << (Arity == 1? "ad" : "an"); break;
2119 // ::= de # * (unary)
2120 // ::= ml # * (binary or unknown)
2121 case OO_Star:
2122 // Use binary when unknown.
2123 Out << (Arity == 1? "de" : "ml"); break;
2124 // ::= co # ~
2125 case OO_Tilde: Out << "co"; break;
2126 // ::= dv # /
2127 case OO_Slash: Out << "dv"; break;
2128 // ::= rm # %
2129 case OO_Percent: Out << "rm"; break;
2130 // ::= or # |
2131 case OO_Pipe: Out << "or"; break;
2132 // ::= eo # ^
2133 case OO_Caret: Out << "eo"; break;
2134 // ::= aS # =
2135 case OO_Equal: Out << "aS"; break;
2136 // ::= pL # +=
2137 case OO_PlusEqual: Out << "pL"; break;
2138 // ::= mI # -=
2139 case OO_MinusEqual: Out << "mI"; break;
2140 // ::= mL # *=
2141 case OO_StarEqual: Out << "mL"; break;
2142 // ::= dV # /=
2143 case OO_SlashEqual: Out << "dV"; break;
2144 // ::= rM # %=
2145 case OO_PercentEqual: Out << "rM"; break;
2146 // ::= aN # &=
2147 case OO_AmpEqual: Out << "aN"; break;
2148 // ::= oR # |=
2149 case OO_PipeEqual: Out << "oR"; break;
2150 // ::= eO # ^=
2151 case OO_CaretEqual: Out << "eO"; break;
2152 // ::= ls # <<
2153 case OO_LessLess: Out << "ls"; break;
2154 // ::= rs # >>
2155 case OO_GreaterGreater: Out << "rs"; break;
2156 // ::= lS # <<=
2157 case OO_LessLessEqual: Out << "lS"; break;
2158 // ::= rS # >>=
2159 case OO_GreaterGreaterEqual: Out << "rS"; break;
2160 // ::= eq # ==
2161 case OO_EqualEqual: Out << "eq"; break;
2162 // ::= ne # !=
2163 case OO_ExclaimEqual: Out << "ne"; break;
2164 // ::= lt # <
2165 case OO_Less: Out << "lt"; break;
2166 // ::= gt # >
2167 case OO_Greater: Out << "gt"; break;
2168 // ::= le # <=
2169 case OO_LessEqual: Out << "le"; break;
2170 // ::= ge # >=
2171 case OO_GreaterEqual: Out << "ge"; break;
2172 // ::= nt # !
2173 case OO_Exclaim: Out << "nt"; break;
2174 // ::= aa # &&
2175 case OO_AmpAmp: Out << "aa"; break;
2176 // ::= oo # ||
2177 case OO_PipePipe: Out << "oo"; break;
2178 // ::= pp # ++
2179 case OO_PlusPlus: Out << "pp"; break;
2180 // ::= mm # --
2181 case OO_MinusMinus: Out << "mm"; break;
2182 // ::= cm # ,
2183 case OO_Comma: Out << "cm"; break;
2184 // ::= pm # ->*
2185 case OO_ArrowStar: Out << "pm"; break;
2186 // ::= pt # ->
2187 case OO_Arrow: Out << "pt"; break;
2188 // ::= cl # ()
2189 case OO_Call: Out << "cl"; break;
2190 // ::= ix # []
2191 case OO_Subscript: Out << "ix"; break;
2192
2193 // ::= qu # ?
2194 // The conditional operator can't be overloaded, but we still handle it when
2195 // mangling expressions.
2196 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00002197 // Proposal on cxx-abi-dev, 2015-10-21.
2198 // ::= aw # co_await
2199 case OO_Coawait: Out << "aw"; break;
Richard Smithd30b23d2017-12-01 02:13:10 +00002200 // Proposed in cxx-abi github issue 43.
2201 // ::= ss # <=>
2202 case OO_Spaceship: Out << "ss"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002203
2204 case OO_None:
2205 case NUM_OVERLOADED_OPERATORS:
2206 llvm_unreachable("Not an overloaded operator");
2207 }
2208}
2209
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002210void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002211 // Vendor qualifiers come first and if they are order-insensitive they must
2212 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
Guy Benyei11169dd2012-12-18 14:30:41 +00002213
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002214 // <type> ::= U <addrspace-expr>
2215 if (DAST) {
2216 Out << "U2ASI";
2217 mangleExpression(DAST->getAddrSpaceExpr());
2218 Out << "E";
2219 }
2220
John McCall07daf722016-03-01 22:18:03 +00002221 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00002222 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00002223 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00002224 //
David Tweed31d09b02013-09-13 12:04:22 +00002225 // <type> ::= U <target-addrspace>
2226 // <type> ::= U <OpenCL-addrspace>
2227 // <type> ::= U <CUDA-addrspace>
2228
Guy Benyei11169dd2012-12-18 14:30:41 +00002229 SmallString<64> ASString;
Alexander Richardson6d989432017-10-15 18:48:14 +00002230 LangAS AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00002231
2232 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2233 // <target-addrspace> ::= "AS" <address-space-number>
2234 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Yaxun Liub7318e02017-10-13 03:37:48 +00002235 if (TargetAS != 0)
2236 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00002237 } else {
2238 switch (AS) {
2239 default: llvm_unreachable("Not a language specific address space");
Yaxun Liub7318e02017-10-13 03:37:48 +00002240 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2241 // "private"| "generic" ]
David Tweed31d09b02013-09-13 12:04:22 +00002242 case LangAS::opencl_global: ASString = "CLglobal"; break;
2243 case LangAS::opencl_local: ASString = "CLlocal"; break;
2244 case LangAS::opencl_constant: ASString = "CLconstant"; break;
Yaxun Liub7318e02017-10-13 03:37:48 +00002245 case LangAS::opencl_private: ASString = "CLprivate"; break;
Anastasia Stulova81a25e352017-03-10 15:23:07 +00002246 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
David Tweed31d09b02013-09-13 12:04:22 +00002247 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2248 case LangAS::cuda_device: ASString = "CUdevice"; break;
2249 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2250 case LangAS::cuda_shared: ASString = "CUshared"; break;
2251 }
2252 }
Yaxun Liub7318e02017-10-13 03:37:48 +00002253 if (!ASString.empty())
2254 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00002255 }
John McCall07daf722016-03-01 22:18:03 +00002256
2257 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00002258 // Objective-C ARC Extension:
2259 //
2260 // <type> ::= U "__strong"
2261 // <type> ::= U "__weak"
2262 // <type> ::= U "__autoreleasing"
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002263 //
2264 // Note: we emit __weak first to preserve the order as
2265 // required by the Itanium ABI.
2266 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2267 mangleVendorQualifier("__weak");
2268
2269 // __unaligned (from -fms-extensions)
2270 if (Quals.hasUnaligned())
2271 mangleVendorQualifier("__unaligned");
2272
2273 // Remaining ARC ownership qualifiers.
2274 switch (Quals.getObjCLifetime()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002275 case Qualifiers::OCL_None:
2276 break;
2277
2278 case Qualifiers::OCL_Weak:
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002279 // Do nothing as we already handled this case above.
Guy Benyei11169dd2012-12-18 14:30:41 +00002280 break;
2281
2282 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00002283 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00002284 break;
2285
2286 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00002287 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 break;
2289
2290 case Qualifiers::OCL_ExplicitNone:
2291 // The __unsafe_unretained qualifier is *not* mangled, so that
2292 // __unsafe_unretained types in ARC produce the same manglings as the
2293 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2294 // better ABI compatibility.
2295 //
2296 // It's safe to do this because unqualified 'id' won't show up
2297 // in any type signatures that need to be mangled.
2298 break;
2299 }
John McCall07daf722016-03-01 22:18:03 +00002300
2301 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2302 if (Quals.hasRestrict())
2303 Out << 'r';
2304 if (Quals.hasVolatile())
2305 Out << 'V';
2306 if (Quals.hasConst())
2307 Out << 'K';
2308}
2309
2310void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2311 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002312}
2313
2314void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2315 // <ref-qualifier> ::= R # lvalue reference
2316 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00002317 switch (RefQualifier) {
2318 case RQ_None:
2319 break;
2320
2321 case RQ_LValue:
2322 Out << 'R';
2323 break;
2324
2325 case RQ_RValue:
2326 Out << 'O';
2327 break;
2328 }
2329}
2330
2331void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2332 Context.mangleObjCMethodName(MD, Out);
2333}
2334
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002335static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2336 ASTContext &Ctx) {
David Majnemereea02ee2014-11-28 22:22:46 +00002337 if (Quals)
2338 return true;
2339 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2340 return true;
2341 if (Ty->isOpenCLSpecificType())
2342 return true;
2343 if (Ty->isBuiltinType())
2344 return false;
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002345 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2346 // substitution candidates.
2347 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2348 isa<AutoType>(Ty))
2349 return false;
David Majnemereea02ee2014-11-28 22:22:46 +00002350 return true;
2351}
2352
Guy Benyei11169dd2012-12-18 14:30:41 +00002353void CXXNameMangler::mangleType(QualType T) {
2354 // If our type is instantiation-dependent but not dependent, we mangle
2355 // it as it was written in the source, removing any top-level sugar.
2356 // Otherwise, use the canonical type.
2357 //
2358 // FIXME: This is an approximation of the instantiation-dependent name
2359 // mangling rules, since we should really be using the type as written and
2360 // augmented via semantic analysis (i.e., with implicit conversions and
2361 // default template arguments) for any instantiation-dependent type.
2362 // Unfortunately, that requires several changes to our AST:
2363 // - Instantiation-dependent TemplateSpecializationTypes will need to be
2364 // uniqued, so that we can handle substitutions properly
2365 // - Default template arguments will need to be represented in the
2366 // TemplateSpecializationType, since they need to be mangled even though
2367 // they aren't written.
2368 // - Conversions on non-type template arguments need to be expressed, since
2369 // they can affect the mangling of sizeof/alignof.
Richard Smithfda59e52016-10-26 01:05:54 +00002370 //
2371 // FIXME: This is wrong when mapping to the canonical type for a dependent
2372 // type discards instantiation-dependent portions of the type, such as for:
2373 //
2374 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2375 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2376 //
2377 // It's also wrong in the opposite direction when instantiation-dependent,
2378 // canonically-equivalent types differ in some irrelevant portion of inner
2379 // type sugar. In such cases, we fail to form correct substitutions, eg:
2380 //
2381 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2382 //
2383 // We should instead canonicalize the non-instantiation-dependent parts,
2384 // regardless of whether the type as a whole is dependent or instantiation
2385 // dependent.
Guy Benyei11169dd2012-12-18 14:30:41 +00002386 if (!T->isInstantiationDependentType() || T->isDependentType())
2387 T = T.getCanonicalType();
2388 else {
2389 // Desugar any types that are purely sugar.
2390 do {
2391 // Don't desugar through template specialization types that aren't
2392 // type aliases. We need to mangle the template arguments as written.
2393 if (const TemplateSpecializationType *TST
2394 = dyn_cast<TemplateSpecializationType>(T))
2395 if (!TST->isTypeAlias())
2396 break;
2397
2398 QualType Desugared
2399 = T.getSingleStepDesugaredType(Context.getASTContext());
2400 if (Desugared == T)
2401 break;
2402
2403 T = Desugared;
2404 } while (true);
2405 }
2406 SplitQualType split = T.split();
2407 Qualifiers quals = split.Quals;
2408 const Type *ty = split.Ty;
2409
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002410 bool isSubstitutable =
2411 isTypeSubstitutable(quals, ty, Context.getASTContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002412 if (isSubstitutable && mangleSubstitution(T))
2413 return;
2414
2415 // If we're mangling a qualified array type, push the qualifiers to
2416 // the element type.
2417 if (quals && isa<ArrayType>(T)) {
2418 ty = Context.getASTContext().getAsArrayType(T);
2419 quals = Qualifiers();
2420
2421 // Note that we don't update T: we want to add the
2422 // substitution at the original type.
2423 }
2424
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002425 if (quals || ty->isDependentAddressSpaceType()) {
2426 if (const DependentAddressSpaceType *DAST =
2427 dyn_cast<DependentAddressSpaceType>(ty)) {
2428 SplitQualType splitDAST = DAST->getPointeeType().split();
2429 mangleQualifiers(splitDAST.Quals, DAST);
2430 mangleType(QualType(splitDAST.Ty, 0));
2431 } else {
2432 mangleQualifiers(quals);
2433
2434 // Recurse: even if the qualified type isn't yet substitutable,
2435 // the unqualified type might be.
2436 mangleType(QualType(ty, 0));
2437 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002438 } else {
2439 switch (ty->getTypeClass()) {
2440#define ABSTRACT_TYPE(CLASS, PARENT)
2441#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2442 case Type::CLASS: \
2443 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2444 return;
2445#define TYPE(CLASS, PARENT) \
2446 case Type::CLASS: \
2447 mangleType(static_cast<const CLASS##Type*>(ty)); \
2448 break;
2449#include "clang/AST/TypeNodes.def"
2450 }
2451 }
2452
2453 // Add the substitution.
2454 if (isSubstitutable)
2455 addSubstitution(T);
2456}
2457
2458void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2459 if (!mangleStandardSubstitution(ND))
2460 mangleName(ND);
2461}
2462
2463void CXXNameMangler::mangleType(const BuiltinType *T) {
2464 // <type> ::= <builtin-type>
2465 // <builtin-type> ::= v # void
2466 // ::= w # wchar_t
2467 // ::= b # bool
2468 // ::= c # char
2469 // ::= a # signed char
2470 // ::= h # unsigned char
2471 // ::= s # short
2472 // ::= t # unsigned short
2473 // ::= i # int
2474 // ::= j # unsigned int
2475 // ::= l # long
2476 // ::= m # unsigned long
2477 // ::= x # long long, __int64
2478 // ::= y # unsigned long long, __int64
2479 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002480 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002481 // ::= f # float
2482 // ::= d # double
2483 // ::= e # long double, __float80
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002484 // ::= g # __float128
Guy Benyei11169dd2012-12-18 14:30:41 +00002485 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2486 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2487 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2488 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002489 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
Guy Benyei11169dd2012-12-18 14:30:41 +00002490 // ::= Di # char32_t
2491 // ::= Ds # char16_t
2492 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2493 // ::= u <source-name> # vendor extended type
Alexey Bader954ba212016-04-08 13:40:33 +00002494 std::string type_name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002496 case BuiltinType::Void:
2497 Out << 'v';
2498 break;
2499 case BuiltinType::Bool:
2500 Out << 'b';
2501 break;
2502 case BuiltinType::Char_U:
2503 case BuiltinType::Char_S:
2504 Out << 'c';
2505 break;
2506 case BuiltinType::UChar:
2507 Out << 'h';
2508 break;
2509 case BuiltinType::UShort:
2510 Out << 't';
2511 break;
2512 case BuiltinType::UInt:
2513 Out << 'j';
2514 break;
2515 case BuiltinType::ULong:
2516 Out << 'm';
2517 break;
2518 case BuiltinType::ULongLong:
2519 Out << 'y';
2520 break;
2521 case BuiltinType::UInt128:
2522 Out << 'o';
2523 break;
2524 case BuiltinType::SChar:
2525 Out << 'a';
2526 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002527 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002528 case BuiltinType::WChar_U:
2529 Out << 'w';
2530 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00002531 case BuiltinType::Char8:
2532 Out << "Du";
2533 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002534 case BuiltinType::Char16:
2535 Out << "Ds";
2536 break;
2537 case BuiltinType::Char32:
2538 Out << "Di";
2539 break;
2540 case BuiltinType::Short:
2541 Out << 's';
2542 break;
2543 case BuiltinType::Int:
2544 Out << 'i';
2545 break;
2546 case BuiltinType::Long:
2547 Out << 'l';
2548 break;
2549 case BuiltinType::LongLong:
2550 Out << 'x';
2551 break;
2552 case BuiltinType::Int128:
2553 Out << 'n';
2554 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002555 case BuiltinType::Float16:
2556 Out << "DF16_";
2557 break;
Leonard Chanf921d852018-06-04 16:07:52 +00002558 case BuiltinType::ShortAccum:
2559 case BuiltinType::Accum:
2560 case BuiltinType::LongAccum:
2561 case BuiltinType::UShortAccum:
2562 case BuiltinType::UAccum:
2563 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002564 case BuiltinType::ShortFract:
2565 case BuiltinType::Fract:
2566 case BuiltinType::LongFract:
2567 case BuiltinType::UShortFract:
2568 case BuiltinType::UFract:
2569 case BuiltinType::ULongFract:
2570 case BuiltinType::SatShortAccum:
2571 case BuiltinType::SatAccum:
2572 case BuiltinType::SatLongAccum:
2573 case BuiltinType::SatUShortAccum:
2574 case BuiltinType::SatUAccum:
2575 case BuiltinType::SatULongAccum:
2576 case BuiltinType::SatShortFract:
2577 case BuiltinType::SatFract:
2578 case BuiltinType::SatLongFract:
2579 case BuiltinType::SatUShortFract:
2580 case BuiltinType::SatUFract:
2581 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00002582 llvm_unreachable("Fixed point types are disabled for c++");
Alexey Baderbdf7c842015-09-15 12:18:29 +00002583 case BuiltinType::Half:
2584 Out << "Dh";
2585 break;
2586 case BuiltinType::Float:
2587 Out << 'f';
2588 break;
2589 case BuiltinType::Double:
2590 Out << 'd';
2591 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002592 case BuiltinType::LongDouble:
2593 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2594 ? 'g'
2595 : 'e');
2596 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002597 case BuiltinType::Float128:
2598 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2599 Out << "U10__float128"; // Match the GCC mangling
2600 else
2601 Out << 'g';
2602 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002603 case BuiltinType::NullPtr:
2604 Out << "Dn";
2605 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002606
2607#define BUILTIN_TYPE(Id, SingletonId)
2608#define PLACEHOLDER_TYPE(Id, SingletonId) \
2609 case BuiltinType::Id:
2610#include "clang/AST/BuiltinTypes.def"
2611 case BuiltinType::Dependent:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002612 if (!NullOut)
2613 llvm_unreachable("mangling a placeholder type");
2614 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002615 case BuiltinType::ObjCId:
2616 Out << "11objc_object";
2617 break;
2618 case BuiltinType::ObjCClass:
2619 Out << "10objc_class";
2620 break;
2621 case BuiltinType::ObjCSel:
2622 Out << "13objc_selector";
2623 break;
Alexey Bader954ba212016-04-08 13:40:33 +00002624#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2625 case BuiltinType::Id: \
2626 type_name = "ocl_" #ImgType "_" #Suffix; \
2627 Out << type_name.size() << type_name; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00002628 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00002629#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00002630 case BuiltinType::OCLSampler:
2631 Out << "11ocl_sampler";
2632 break;
2633 case BuiltinType::OCLEvent:
2634 Out << "9ocl_event";
2635 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002636 case BuiltinType::OCLClkEvent:
2637 Out << "12ocl_clkevent";
2638 break;
2639 case BuiltinType::OCLQueue:
2640 Out << "9ocl_queue";
2641 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002642 case BuiltinType::OCLReserveID:
2643 Out << "13ocl_reserveid";
2644 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002645 }
2646}
2647
John McCall07daf722016-03-01 22:18:03 +00002648StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2649 switch (CC) {
2650 case CC_C:
2651 return "";
2652
2653 case CC_X86StdCall:
2654 case CC_X86FastCall:
2655 case CC_X86ThisCall:
2656 case CC_X86VectorCall:
2657 case CC_X86Pascal:
Martin Storsjo022e7822017-07-17 20:49:45 +00002658 case CC_Win64:
John McCall07daf722016-03-01 22:18:03 +00002659 case CC_X86_64SysV:
Erich Keane757d3172016-11-02 18:29:35 +00002660 case CC_X86RegCall:
John McCall07daf722016-03-01 22:18:03 +00002661 case CC_AAPCS:
2662 case CC_AAPCS_VFP:
2663 case CC_IntelOclBicc:
2664 case CC_SpirFunction:
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00002665 case CC_OpenCLKernel:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00002666 case CC_PreserveMost:
2667 case CC_PreserveAll:
John McCall07daf722016-03-01 22:18:03 +00002668 // FIXME: we should be mangling all of the above.
2669 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002670
2671 case CC_Swift:
2672 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002673 }
2674 llvm_unreachable("bad calling convention");
2675}
2676
2677void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2678 // Fast path.
2679 if (T->getExtInfo() == FunctionType::ExtInfo())
2680 return;
2681
2682 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2683 // This will get more complicated in the future if we mangle other
2684 // things here; but for now, since we mangle ns_returns_retained as
2685 // a qualifier on the result type, we can get away with this:
2686 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2687 if (!CCQualifier.empty())
2688 mangleVendorQualifier(CCQualifier);
2689
2690 // FIXME: regparm
2691 // FIXME: noreturn
2692}
2693
2694void
2695CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2696 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2697
2698 // Note that these are *not* substitution candidates. Demanglers might
2699 // have trouble with this if the parameter type is fully substituted.
2700
John McCall477f2bb2016-03-03 06:39:32 +00002701 switch (PI.getABI()) {
2702 case ParameterABI::Ordinary:
2703 break;
2704
2705 // All of these start with "swift", so they come before "ns_consumed".
2706 case ParameterABI::SwiftContext:
2707 case ParameterABI::SwiftErrorResult:
2708 case ParameterABI::SwiftIndirectResult:
2709 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2710 break;
2711 }
2712
John McCall07daf722016-03-01 22:18:03 +00002713 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002714 mangleVendorQualifier("ns_consumed");
Akira Hatanaka98a49332017-09-22 00:41:05 +00002715
2716 if (PI.isNoEscape())
2717 mangleVendorQualifier("noescape");
John McCall07daf722016-03-01 22:18:03 +00002718}
2719
Guy Benyei11169dd2012-12-18 14:30:41 +00002720// <type> ::= <function-type>
2721// <function-type> ::= [<CV-qualifiers>] F [Y]
2722// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002723void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002724 mangleExtFunctionInfo(T);
2725
Guy Benyei11169dd2012-12-18 14:30:41 +00002726 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2727 // e.g. "const" in "int (A::*)() const".
Reid Kleckner267589a2018-03-08 00:55:09 +00002728 mangleQualifiers(Qualifiers::fromCVRUMask(T->getTypeQuals()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002729
Richard Smithfda59e52016-10-26 01:05:54 +00002730 // Mangle instantiation-dependent exception-specification, if present,
2731 // per cxx-abi-dev proposal on 2016-10-11.
2732 if (T->hasInstantiationDependentExceptionSpec()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00002733 if (isComputedNoexcept(T->getExceptionSpecType())) {
Richard Smithef09aa92016-11-03 00:27:54 +00002734 Out << "DO";
Richard Smithfda59e52016-10-26 01:05:54 +00002735 mangleExpression(T->getNoexceptExpr());
2736 Out << "E";
2737 } else {
2738 assert(T->getExceptionSpecType() == EST_Dynamic);
Richard Smithef09aa92016-11-03 00:27:54 +00002739 Out << "Dw";
Richard Smithfda59e52016-10-26 01:05:54 +00002740 for (auto ExceptTy : T->exceptions())
2741 mangleType(ExceptTy);
2742 Out << "E";
2743 }
Richard Smitheaf11ad2018-05-03 03:58:32 +00002744 } else if (T->isNothrow()) {
Richard Smithef09aa92016-11-03 00:27:54 +00002745 Out << "Do";
Richard Smithfda59e52016-10-26 01:05:54 +00002746 }
2747
Guy Benyei11169dd2012-12-18 14:30:41 +00002748 Out << 'F';
2749
2750 // FIXME: We don't have enough information in the AST to produce the 'Y'
2751 // encoding for extern "C" function types.
2752 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2753
2754 // Mangle the ref-qualifier, if present.
2755 mangleRefQualifier(T->getRefQualifier());
2756
2757 Out << 'E';
2758}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002759
Guy Benyei11169dd2012-12-18 14:30:41 +00002760void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002761 // Function types without prototypes can arise when mangling a function type
2762 // within an overloadable function in C. We mangle these as the absence of any
2763 // parameter types (not even an empty parameter list).
2764 Out << 'F';
2765
2766 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2767
2768 FunctionTypeDepth.enterResultType();
2769 mangleType(T->getReturnType());
2770 FunctionTypeDepth.leaveResultType();
2771
2772 FunctionTypeDepth.pop(saved);
2773 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002774}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002775
John McCall07daf722016-03-01 22:18:03 +00002776void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002777 bool MangleReturnType,
2778 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002779 // Record that we're in a function type. See mangleFunctionParam
2780 // for details on what we're trying to achieve here.
2781 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2782
2783 // <bare-function-type> ::= <signature type>+
2784 if (MangleReturnType) {
2785 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002786
2787 // Mangle ns_returns_retained as an order-sensitive qualifier here.
Nico Weberfb420782016-05-25 14:15:08 +00002788 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
John McCall07daf722016-03-01 22:18:03 +00002789 mangleVendorQualifier("ns_returns_retained");
2790
2791 // Mangle the return type without any direct ARC ownership qualifiers.
2792 QualType ReturnTy = Proto->getReturnType();
2793 if (ReturnTy.getObjCLifetime()) {
2794 auto SplitReturnTy = ReturnTy.split();
2795 SplitReturnTy.Quals.removeObjCLifetime();
2796 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2797 }
2798 mangleType(ReturnTy);
2799
Guy Benyei11169dd2012-12-18 14:30:41 +00002800 FunctionTypeDepth.leaveResultType();
2801 }
2802
Alp Toker9cacbab2014-01-20 20:26:09 +00002803 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002804 // <builtin-type> ::= v # void
2805 Out << 'v';
2806
2807 FunctionTypeDepth.pop(saved);
2808 return;
2809 }
2810
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002811 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2812 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002813 // Mangle extended parameter info as order-sensitive qualifiers here.
Nico Weberfb420782016-05-25 14:15:08 +00002814 if (Proto->hasExtParameterInfos() && FD == nullptr) {
John McCall07daf722016-03-01 22:18:03 +00002815 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2816 }
2817
2818 // Mangle the type.
2819 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002820 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2821
2822 if (FD) {
2823 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2824 // Attr can only take 1 character, so we can hardcode the length below.
2825 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2826 Out << "U17pass_object_size" << Attr->getType();
2827 }
2828 }
2829 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002830
2831 FunctionTypeDepth.pop(saved);
2832
2833 // <builtin-type> ::= z # ellipsis
2834 if (Proto->isVariadic())
2835 Out << 'z';
2836}
2837
2838// <type> ::= <class-enum-type>
2839// <class-enum-type> ::= <name>
2840void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2841 mangleName(T->getDecl());
2842}
2843
2844// <type> ::= <class-enum-type>
2845// <class-enum-type> ::= <name>
2846void CXXNameMangler::mangleType(const EnumType *T) {
2847 mangleType(static_cast<const TagType*>(T));
2848}
2849void CXXNameMangler::mangleType(const RecordType *T) {
2850 mangleType(static_cast<const TagType*>(T));
2851}
2852void CXXNameMangler::mangleType(const TagType *T) {
2853 mangleName(T->getDecl());
2854}
2855
2856// <type> ::= <array-type>
2857// <array-type> ::= A <positive dimension number> _ <element type>
2858// ::= A [<dimension expression>] _ <element type>
2859void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2860 Out << 'A' << T->getSize() << '_';
2861 mangleType(T->getElementType());
2862}
2863void CXXNameMangler::mangleType(const VariableArrayType *T) {
2864 Out << 'A';
2865 // decayed vla types (size 0) will just be skipped.
2866 if (T->getSizeExpr())
2867 mangleExpression(T->getSizeExpr());
2868 Out << '_';
2869 mangleType(T->getElementType());
2870}
2871void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2872 Out << 'A';
2873 mangleExpression(T->getSizeExpr());
2874 Out << '_';
2875 mangleType(T->getElementType());
2876}
2877void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2878 Out << "A_";
2879 mangleType(T->getElementType());
2880}
2881
2882// <type> ::= <pointer-to-member-type>
2883// <pointer-to-member-type> ::= M <class type> <member type>
2884void CXXNameMangler::mangleType(const MemberPointerType *T) {
2885 Out << 'M';
2886 mangleType(QualType(T->getClass(), 0));
2887 QualType PointeeType = T->getPointeeType();
2888 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2889 mangleType(FPT);
2890
2891 // Itanium C++ ABI 5.1.8:
2892 //
2893 // The type of a non-static member function is considered to be different,
2894 // for the purposes of substitution, from the type of a namespace-scope or
2895 // static member function whose type appears similar. The types of two
2896 // non-static member functions are considered to be different, for the
2897 // purposes of substitution, if the functions are members of different
2898 // classes. In other words, for the purposes of substitution, the class of
2899 // which the function is a member is considered part of the type of
2900 // function.
2901
2902 // Given that we already substitute member function pointers as a
2903 // whole, the net effect of this rule is just to unconditionally
2904 // suppress substitution on the function type in a member pointer.
2905 // We increment the SeqID here to emulate adding an entry to the
2906 // substitution table.
2907 ++SeqID;
2908 } else
2909 mangleType(PointeeType);
2910}
2911
2912// <type> ::= <template-param>
2913void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2914 mangleTemplateParameter(T->getIndex());
2915}
2916
2917// <type> ::= <template-param>
2918void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2919 // FIXME: not clear how to mangle this!
2920 // template <class T...> class A {
2921 // template <class U...> void foo(T(*)(U) x...);
2922 // };
2923 Out << "_SUBSTPACK_";
2924}
2925
2926// <type> ::= P <type> # pointer-to
2927void CXXNameMangler::mangleType(const PointerType *T) {
2928 Out << 'P';
2929 mangleType(T->getPointeeType());
2930}
2931void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2932 Out << 'P';
2933 mangleType(T->getPointeeType());
2934}
2935
2936// <type> ::= R <type> # reference-to
2937void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2938 Out << 'R';
2939 mangleType(T->getPointeeType());
2940}
2941
2942// <type> ::= O <type> # rvalue reference-to (C++0x)
2943void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2944 Out << 'O';
2945 mangleType(T->getPointeeType());
2946}
2947
2948// <type> ::= C <type> # complex pair (C 2000)
2949void CXXNameMangler::mangleType(const ComplexType *T) {
2950 Out << 'C';
2951 mangleType(T->getElementType());
2952}
2953
2954// ARM's ABI for Neon vector types specifies that they should be mangled as
2955// if they are structs (to match ARM's initial implementation). The
2956// vector type must be one of the special types predefined by ARM.
2957void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2958 QualType EltType = T->getElementType();
2959 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002960 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2962 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002963 case BuiltinType::SChar:
2964 case BuiltinType::UChar:
2965 EltName = "poly8_t";
2966 break;
2967 case BuiltinType::Short:
2968 case BuiltinType::UShort:
2969 EltName = "poly16_t";
2970 break;
2971 case BuiltinType::ULongLong:
2972 EltName = "poly64_t";
2973 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002974 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2975 }
2976 } else {
2977 switch (cast<BuiltinType>(EltType)->getKind()) {
2978 case BuiltinType::SChar: EltName = "int8_t"; break;
2979 case BuiltinType::UChar: EltName = "uint8_t"; break;
2980 case BuiltinType::Short: EltName = "int16_t"; break;
2981 case BuiltinType::UShort: EltName = "uint16_t"; break;
2982 case BuiltinType::Int: EltName = "int32_t"; break;
2983 case BuiltinType::UInt: EltName = "uint32_t"; break;
2984 case BuiltinType::LongLong: EltName = "int64_t"; break;
2985 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002986 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002987 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002988 case BuiltinType::Half: EltName = "float16_t";break;
2989 default:
2990 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002991 }
2992 }
Craig Topper36250ad2014-05-12 05:36:57 +00002993 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002994 unsigned BitSize = (T->getNumElements() *
2995 getASTContext().getTypeSize(EltType));
2996 if (BitSize == 64)
2997 BaseName = "__simd64_";
2998 else {
2999 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3000 BaseName = "__simd128_";
3001 }
3002 Out << strlen(BaseName) + strlen(EltName);
3003 Out << BaseName << EltName;
3004}
3005
Erich Keanef702b022018-07-13 19:46:04 +00003006void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3007 DiagnosticsEngine &Diags = Context.getDiags();
3008 unsigned DiagID = Diags.getCustomDiagID(
3009 DiagnosticsEngine::Error,
3010 "cannot mangle this dependent neon vector type yet");
3011 Diags.Report(T->getAttributeLoc(), DiagID);
3012}
3013
Tim Northover2fe823a2013-08-01 09:23:19 +00003014static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3015 switch (EltType->getKind()) {
3016 case BuiltinType::SChar:
3017 return "Int8";
3018 case BuiltinType::Short:
3019 return "Int16";
3020 case BuiltinType::Int:
3021 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003022 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00003023 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003024 return "Int64";
3025 case BuiltinType::UChar:
3026 return "Uint8";
3027 case BuiltinType::UShort:
3028 return "Uint16";
3029 case BuiltinType::UInt:
3030 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003031 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00003032 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003033 return "Uint64";
3034 case BuiltinType::Half:
3035 return "Float16";
3036 case BuiltinType::Float:
3037 return "Float32";
3038 case BuiltinType::Double:
3039 return "Float64";
3040 default:
3041 llvm_unreachable("Unexpected vector element base type");
3042 }
3043}
3044
3045// AArch64's ABI for Neon vector types specifies that they should be mangled as
3046// the equivalent internal name. The vector type must be one of the special
3047// types predefined by ARM.
3048void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3049 QualType EltType = T->getElementType();
3050 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3051 unsigned BitSize =
3052 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00003053 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00003054
3055 assert((BitSize == 64 || BitSize == 128) &&
3056 "Neon vector type not 64 or 128 bits");
3057
Tim Northover2fe823a2013-08-01 09:23:19 +00003058 StringRef EltName;
3059 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3060 switch (cast<BuiltinType>(EltType)->getKind()) {
3061 case BuiltinType::UChar:
3062 EltName = "Poly8";
3063 break;
3064 case BuiltinType::UShort:
3065 EltName = "Poly16";
3066 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00003067 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00003068 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00003069 EltName = "Poly64";
3070 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00003071 default:
3072 llvm_unreachable("unexpected Neon polynomial vector element type");
3073 }
3074 } else
3075 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3076
3077 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00003078 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00003079 Out << TypeName.length() << TypeName;
3080}
Erich Keanef702b022018-07-13 19:46:04 +00003081void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3082 DiagnosticsEngine &Diags = Context.getDiags();
3083 unsigned DiagID = Diags.getCustomDiagID(
3084 DiagnosticsEngine::Error,
3085 "cannot mangle this dependent neon vector type yet");
3086 Diags.Report(T->getAttributeLoc(), DiagID);
3087}
Tim Northover2fe823a2013-08-01 09:23:19 +00003088
Guy Benyei11169dd2012-12-18 14:30:41 +00003089// GNU extension: vector types
3090// <type> ::= <vector-type>
3091// <vector-type> ::= Dv <positive dimension number> _
3092// <extended element type>
3093// ::= Dv [<dimension expression>] _ <element type>
3094// <extended element type> ::= <element type>
3095// ::= p # AltiVec vector pixel
3096// ::= b # Altivec vector bool
3097void CXXNameMangler::mangleType(const VectorType *T) {
3098 if ((T->getVectorKind() == VectorType::NeonVector ||
3099 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003100 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00003101 llvm::Triple::ArchType Arch =
3102 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00003103 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00003104 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00003105 mangleAArch64NeonVectorType(T);
3106 else
3107 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00003108 return;
3109 }
3110 Out << "Dv" << T->getNumElements() << '_';
3111 if (T->getVectorKind() == VectorType::AltiVecPixel)
3112 Out << 'p';
3113 else if (T->getVectorKind() == VectorType::AltiVecBool)
3114 Out << 'b';
3115 else
3116 mangleType(T->getElementType());
3117}
Erich Keanef702b022018-07-13 19:46:04 +00003118
3119void CXXNameMangler::mangleType(const DependentVectorType *T) {
3120 if ((T->getVectorKind() == VectorType::NeonVector ||
3121 T->getVectorKind() == VectorType::NeonPolyVector)) {
3122 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3123 llvm::Triple::ArchType Arch =
3124 getASTContext().getTargetInfo().getTriple().getArch();
3125 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3126 !Target.isOSDarwin())
3127 mangleAArch64NeonVectorType(T);
3128 else
3129 mangleNeonVectorType(T);
3130 return;
3131 }
3132
3133 Out << "Dv";
3134 mangleExpression(T->getSizeExpr());
3135 Out << '_';
3136 if (T->getVectorKind() == VectorType::AltiVecPixel)
3137 Out << 'p';
3138 else if (T->getVectorKind() == VectorType::AltiVecBool)
3139 Out << 'b';
3140 else
3141 mangleType(T->getElementType());
3142}
3143
Guy Benyei11169dd2012-12-18 14:30:41 +00003144void CXXNameMangler::mangleType(const ExtVectorType *T) {
3145 mangleType(static_cast<const VectorType*>(T));
3146}
3147void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3148 Out << "Dv";
3149 mangleExpression(T->getSizeExpr());
3150 Out << '_';
3151 mangleType(T->getElementType());
3152}
3153
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003154void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3155 SplitQualType split = T->getPointeeType().split();
3156 mangleQualifiers(split.Quals, T);
3157 mangleType(QualType(split.Ty, 0));
3158}
3159
Guy Benyei11169dd2012-12-18 14:30:41 +00003160void CXXNameMangler::mangleType(const PackExpansionType *T) {
3161 // <type> ::= Dp <type> # pack expansion (C++0x)
3162 Out << "Dp";
3163 mangleType(T->getPattern());
3164}
3165
3166void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3167 mangleSourceName(T->getDecl()->getIdentifier());
3168}
3169
3170void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00003171 // Treat __kindof as a vendor extended type qualifier.
3172 if (T->isKindOfType())
3173 Out << "U8__kindof";
3174
Eli Friedman5f508952013-06-18 22:41:37 +00003175 if (!T->qual_empty()) {
3176 // Mangle protocol qualifiers.
3177 SmallString<64> QualStr;
3178 llvm::raw_svector_ostream QualOS(QualStr);
3179 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00003180 for (const auto *I : T->quals()) {
3181 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00003182 QualOS << name.size() << name;
3183 }
Eli Friedman5f508952013-06-18 22:41:37 +00003184 Out << 'U' << QualStr.size() << QualStr;
3185 }
Douglas Gregorab209d82015-07-07 03:58:42 +00003186
Guy Benyei11169dd2012-12-18 14:30:41 +00003187 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00003188
3189 if (T->isSpecialized()) {
3190 // Mangle type arguments as I <type>+ E
3191 Out << 'I';
3192 for (auto typeArg : T->getTypeArgs())
3193 mangleType(typeArg);
3194 Out << 'E';
3195 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003196}
3197
3198void CXXNameMangler::mangleType(const BlockPointerType *T) {
3199 Out << "U13block_pointer";
3200 mangleType(T->getPointeeType());
3201}
3202
3203void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3204 // Mangle injected class name types as if the user had written the
3205 // specialization out fully. It may not actually be possible to see
3206 // this mangling, though.
3207 mangleType(T->getInjectedSpecializationType());
3208}
3209
3210void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3211 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003212 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003213 } else {
3214 if (mangleSubstitution(QualType(T, 0)))
3215 return;
3216
3217 mangleTemplatePrefix(T->getTemplateName());
3218
3219 // FIXME: GCC does not appear to mangle the template arguments when
3220 // the template in question is a dependent template name. Should we
3221 // emulate that badness?
3222 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3223 addSubstitution(QualType(T, 0));
3224 }
3225}
3226
3227void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00003228 // Proposal by cxx-abi-dev, 2014-03-26
3229 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3230 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003231 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00003232 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003233 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00003234 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003235 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00003236 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003237 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00003238 switch (T->getKeyword()) {
Richard Smith91fb1f42017-01-20 18:50:12 +00003239 case ETK_None:
David Majnemer64e40c52014-04-10 00:49:24 +00003240 case ETK_Typename:
3241 break;
3242 case ETK_Struct:
3243 case ETK_Class:
3244 case ETK_Interface:
3245 Out << "Ts";
3246 break;
3247 case ETK_Union:
3248 Out << "Tu";
3249 break;
3250 case ETK_Enum:
3251 Out << "Te";
3252 break;
David Majnemer64e40c52014-04-10 00:49:24 +00003253 }
David Majnemer2e159fb2014-04-15 05:51:25 +00003254 // Typename types are always nested
3255 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00003256 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00003257 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00003258 Out << 'E';
3259}
3260
3261void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3262 // Dependently-scoped template types are nested if they have a prefix.
3263 Out << 'N';
3264
3265 // TODO: avoid making this TemplateName.
3266 TemplateName Prefix =
3267 getASTContext().getDependentTemplateName(T->getQualifier(),
3268 T->getIdentifier());
3269 mangleTemplatePrefix(Prefix);
3270
3271 // FIXME: GCC does not appear to mangle the template arguments when
3272 // the template in question is a dependent template name. Should we
3273 // emulate that badness?
3274 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3275 Out << 'E';
3276}
3277
3278void CXXNameMangler::mangleType(const TypeOfType *T) {
3279 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3280 // "extension with parameters" mangling.
3281 Out << "u6typeof";
3282}
3283
3284void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3285 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3286 // "extension with parameters" mangling.
3287 Out << "u6typeof";
3288}
3289
3290void CXXNameMangler::mangleType(const DecltypeType *T) {
3291 Expr *E = T->getUnderlyingExpr();
3292
3293 // type ::= Dt <expression> E # decltype of an id-expression
3294 // # or class member access
3295 // ::= DT <expression> E # decltype of an expression
3296
3297 // This purports to be an exhaustive list of id-expressions and
3298 // class member accesses. Note that we do not ignore parentheses;
3299 // parentheses change the semantics of decltype for these
3300 // expressions (and cause the mangler to use the other form).
3301 if (isa<DeclRefExpr>(E) ||
3302 isa<MemberExpr>(E) ||
3303 isa<UnresolvedLookupExpr>(E) ||
3304 isa<DependentScopeDeclRefExpr>(E) ||
3305 isa<CXXDependentScopeMemberExpr>(E) ||
3306 isa<UnresolvedMemberExpr>(E))
3307 Out << "Dt";
3308 else
3309 Out << "DT";
3310 mangleExpression(E);
3311 Out << 'E';
3312}
3313
3314void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3315 // If this is dependent, we need to record that. If not, we simply
3316 // mangle it as the underlying type since they are equivalent.
3317 if (T->isDependentType()) {
3318 Out << 'U';
3319
3320 switch (T->getUTTKind()) {
3321 case UnaryTransformType::EnumUnderlyingType:
3322 Out << "3eut";
3323 break;
3324 }
3325 }
3326
David Majnemer140065a2016-06-08 00:34:15 +00003327 mangleType(T->getBaseType());
Guy Benyei11169dd2012-12-18 14:30:41 +00003328}
3329
3330void CXXNameMangler::mangleType(const AutoType *T) {
Erik Pilkingtone7e87722018-04-28 02:40:28 +00003331 assert(T->getDeducedType().isNull() &&
3332 "Deduced AutoType shouldn't be handled here!");
3333 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3334 "shouldn't need to mangle __auto_type!");
3335 // <builtin-type> ::= Da # auto
3336 // ::= Dc # decltype(auto)
3337 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00003338}
3339
Richard Smith600b5262017-01-26 20:40:47 +00003340void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3341 // FIXME: This is not the right mangling. We also need to include a scope
3342 // here in some cases.
3343 QualType D = T->getDeducedType();
3344 if (D.isNull())
3345 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3346 else
3347 mangleType(D);
3348}
3349
Guy Benyei11169dd2012-12-18 14:30:41 +00003350void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00003351 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00003352 // (Until there's a standardized mangling...)
3353 Out << "U7_Atomic";
3354 mangleType(T->getValueType());
3355}
3356
Xiuli Pan9c14e282016-01-09 12:53:17 +00003357void CXXNameMangler::mangleType(const PipeType *T) {
3358 // Pipe type mangling rules are described in SPIR 2.0 specification
3359 // A.1 Data types and A.3 Summary of changes
3360 // <type> ::= 8ocl_pipe
3361 Out << "8ocl_pipe";
3362}
3363
Guy Benyei11169dd2012-12-18 14:30:41 +00003364void CXXNameMangler::mangleIntegerLiteral(QualType T,
3365 const llvm::APSInt &Value) {
3366 // <expr-primary> ::= L <type> <value number> E # integer literal
3367 Out << 'L';
3368
3369 mangleType(T);
3370 if (T->isBooleanType()) {
3371 // Boolean values are encoded as 0/1.
3372 Out << (Value.getBoolValue() ? '1' : '0');
3373 } else {
3374 mangleNumber(Value);
3375 }
3376 Out << 'E';
3377
3378}
3379
David Majnemer1dabfdc2015-02-14 13:23:54 +00003380void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3381 // Ignore member expressions involving anonymous unions.
3382 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3383 if (!RT->getDecl()->isAnonymousStructOrUnion())
3384 break;
3385 const auto *ME = dyn_cast<MemberExpr>(Base);
3386 if (!ME)
3387 break;
3388 Base = ME->getBase();
3389 IsArrow = ME->isArrow();
3390 }
3391
3392 if (Base->isImplicitCXXThis()) {
3393 // Note: GCC mangles member expressions to the implicit 'this' as
3394 // *this., whereas we represent them as this->. The Itanium C++ ABI
3395 // does not specify anything here, so we follow GCC.
3396 Out << "dtdefpT";
3397 } else {
3398 Out << (IsArrow ? "pt" : "dt");
3399 mangleExpression(Base);
3400 }
3401}
3402
Guy Benyei11169dd2012-12-18 14:30:41 +00003403/// Mangles a member expression.
3404void CXXNameMangler::mangleMemberExpr(const Expr *base,
3405 bool isArrow,
3406 NestedNameSpecifier *qualifier,
3407 NamedDecl *firstQualifierLookup,
3408 DeclarationName member,
Richard Smithafecd832016-10-24 20:47:04 +00003409 const TemplateArgumentLoc *TemplateArgs,
3410 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00003411 unsigned arity) {
3412 // <expression> ::= dt <expression> <unresolved-name>
3413 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00003414 if (base)
3415 mangleMemberExprBase(base, isArrow);
Richard Smithafecd832016-10-24 20:47:04 +00003416 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003417}
3418
3419/// Look at the callee of the given call expression and determine if
3420/// it's a parenthesized id-expression which would have triggered ADL
3421/// otherwise.
3422static bool isParenthesizedADLCallee(const CallExpr *call) {
3423 const Expr *callee = call->getCallee();
3424 const Expr *fn = callee->IgnoreParens();
3425
3426 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3427 // too, but for those to appear in the callee, it would have to be
3428 // parenthesized.
3429 if (callee == fn) return false;
3430
3431 // Must be an unresolved lookup.
3432 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3433 if (!lookup) return false;
3434
3435 assert(!lookup->requiresADL());
3436
3437 // Must be an unqualified lookup.
3438 if (lookup->getQualifier()) return false;
3439
3440 // Must not have found a class member. Note that if one is a class
3441 // member, they're all class members.
3442 if (lookup->getNumDecls() > 0 &&
3443 (*lookup->decls_begin())->isCXXClassMember())
3444 return false;
3445
3446 // Otherwise, ADL would have been triggered.
3447 return true;
3448}
3449
David Majnemer9c775c72014-09-23 04:27:55 +00003450void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3451 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3452 Out << CastEncoding;
3453 mangleType(ECE->getType());
3454 mangleExpression(ECE->getSubExpr());
3455}
3456
Richard Smith520449d2015-02-05 06:15:50 +00003457void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3458 if (auto *Syntactic = InitList->getSyntacticForm())
3459 InitList = Syntactic;
3460 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3461 mangleExpression(InitList->getInit(i));
3462}
3463
Guy Benyei11169dd2012-12-18 14:30:41 +00003464void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3465 // <expression> ::= <unary operator-name> <expression>
3466 // ::= <binary operator-name> <expression> <expression>
3467 // ::= <trinary operator-name> <expression> <expression> <expression>
3468 // ::= cv <type> expression # conversion with one argument
3469 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00003470 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3471 // ::= sc <type> <expression> # static_cast<type> (expression)
3472 // ::= cc <type> <expression> # const_cast<type> (expression)
3473 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003474 // ::= st <type> # sizeof (a type)
3475 // ::= at <type> # alignof (a type)
3476 // ::= <template-param>
3477 // ::= <function-param>
3478 // ::= sr <type> <unqualified-name> # dependent name
3479 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3480 // ::= ds <expression> <expression> # expr.*expr
3481 // ::= sZ <template-param> # size of a parameter pack
3482 // ::= sZ <function-param> # size of a function parameter pack
3483 // ::= <expr-primary>
3484 // <expr-primary> ::= L <type> <value number> E # integer literal
3485 // ::= L <type <value float> E # floating literal
3486 // ::= L <mangled-name> E # external name
3487 // ::= fpT # 'this' expression
3488 QualType ImplicitlyConvertedToType;
3489
3490recurse:
3491 switch (E->getStmtClass()) {
3492 case Expr::NoStmtClass:
3493#define ABSTRACT_STMT(Type)
3494#define EXPR(Type, Base)
3495#define STMT(Type, Base) \
3496 case Expr::Type##Class:
3497#include "clang/AST/StmtNodes.inc"
3498 // fallthrough
3499
3500 // These all can only appear in local or variable-initialization
3501 // contexts and so should never appear in a mangling.
3502 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003503 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003504 case Expr::ImplicitValueInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003505 case Expr::ArrayInitLoopExprClass:
3506 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003507 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003508 case Expr::ParenListExprClass:
3509 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00003510 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003511 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003512 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003513 case Expr::OMPArraySectionExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00003514 case Expr::CXXInheritedCtorInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003515 llvm_unreachable("unexpected statement kind");
3516
3517 // FIXME: invent manglings for all these.
3518 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003519 case Expr::ChooseExprClass:
3520 case Expr::CompoundLiteralExprClass:
3521 case Expr::ExtVectorElementExprClass:
3522 case Expr::GenericSelectionExprClass:
3523 case Expr::ObjCEncodeExprClass:
3524 case Expr::ObjCIsaExprClass:
3525 case Expr::ObjCIvarRefExprClass:
3526 case Expr::ObjCMessageExprClass:
3527 case Expr::ObjCPropertyRefExprClass:
3528 case Expr::ObjCProtocolExprClass:
3529 case Expr::ObjCSelectorExprClass:
3530 case Expr::ObjCStringLiteralClass:
3531 case Expr::ObjCBoxedExprClass:
3532 case Expr::ObjCArrayLiteralClass:
3533 case Expr::ObjCDictionaryLiteralClass:
3534 case Expr::ObjCSubscriptRefExprClass:
3535 case Expr::ObjCIndirectCopyRestoreExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003536 case Expr::ObjCAvailabilityCheckExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003537 case Expr::OffsetOfExprClass:
3538 case Expr::PredefinedExprClass:
3539 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003540 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003541 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003542 case Expr::TypeTraitExprClass:
3543 case Expr::ArrayTypeTraitExprClass:
3544 case Expr::ExpressionTraitExprClass:
3545 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003546 case Expr::CUDAKernelCallExprClass:
3547 case Expr::AsTypeExprClass:
3548 case Expr::PseudoObjectExprClass:
3549 case Expr::AtomicExprClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003550 case Expr::FixedPointLiteralClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003551 {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003552 if (!NullOut) {
3553 // As bad as this diagnostic is, it's better than crashing.
3554 DiagnosticsEngine &Diags = Context.getDiags();
3555 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3556 "cannot yet mangle expression type %0");
3557 Diags.Report(E->getExprLoc(), DiagID)
3558 << E->getStmtClassName() << E->getSourceRange();
3559 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003560 break;
3561 }
3562
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00003563 case Expr::CXXUuidofExprClass: {
3564 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3565 if (UE->isTypeOperand()) {
3566 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3567 Out << "u8__uuidoft";
3568 mangleType(UuidT);
3569 } else {
3570 Expr *UuidExp = UE->getExprOperand();
3571 Out << "u8__uuidofz";
3572 mangleExpression(UuidExp, Arity);
3573 }
3574 break;
3575 }
3576
Guy Benyei11169dd2012-12-18 14:30:41 +00003577 // Even gcc-4.5 doesn't mangle this.
3578 case Expr::BinaryConditionalOperatorClass: {
3579 DiagnosticsEngine &Diags = Context.getDiags();
3580 unsigned DiagID =
3581 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3582 "?: operator with omitted middle operand cannot be mangled");
3583 Diags.Report(E->getExprLoc(), DiagID)
3584 << E->getStmtClassName() << E->getSourceRange();
3585 break;
3586 }
3587
3588 // These are used for internal purposes and cannot be meaningfully mangled.
3589 case Expr::OpaqueValueExprClass:
3590 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3591
3592 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003593 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00003594 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00003595 Out << "E";
3596 break;
3597 }
3598
Richard Smith39eca9b2017-08-23 22:12:08 +00003599 case Expr::DesignatedInitExprClass: {
3600 auto *DIE = cast<DesignatedInitExpr>(E);
3601 for (const auto &Designator : DIE->designators()) {
3602 if (Designator.isFieldDesignator()) {
3603 Out << "di";
3604 mangleSourceName(Designator.getFieldName());
3605 } else if (Designator.isArrayDesignator()) {
3606 Out << "dx";
3607 mangleExpression(DIE->getArrayIndex(Designator));
3608 } else {
3609 assert(Designator.isArrayRangeDesignator() &&
3610 "unknown designator kind");
3611 Out << "dX";
3612 mangleExpression(DIE->getArrayRangeStart(Designator));
3613 mangleExpression(DIE->getArrayRangeEnd(Designator));
3614 }
3615 }
3616 mangleExpression(DIE->getInit());
3617 break;
3618 }
3619
Guy Benyei11169dd2012-12-18 14:30:41 +00003620 case Expr::CXXDefaultArgExprClass:
3621 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3622 break;
3623
Richard Smith852c9db2013-04-20 22:23:05 +00003624 case Expr::CXXDefaultInitExprClass:
3625 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3626 break;
3627
Richard Smithcc1b96d2013-06-12 22:31:48 +00003628 case Expr::CXXStdInitializerListExprClass:
3629 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3630 break;
3631
Guy Benyei11169dd2012-12-18 14:30:41 +00003632 case Expr::SubstNonTypeTemplateParmExprClass:
3633 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3634 Arity);
3635 break;
3636
3637 case Expr::UserDefinedLiteralClass:
3638 // We follow g++'s approach of mangling a UDL as a call to the literal
3639 // operator.
3640 case Expr::CXXMemberCallExprClass: // fallthrough
3641 case Expr::CallExprClass: {
3642 const CallExpr *CE = cast<CallExpr>(E);
3643
3644 // <expression> ::= cp <simple-id> <expression>* E
3645 // We use this mangling only when the call would use ADL except
3646 // for being parenthesized. Per discussion with David
3647 // Vandervoorde, 2011.04.25.
3648 if (isParenthesizedADLCallee(CE)) {
3649 Out << "cp";
3650 // The callee here is a parenthesized UnresolvedLookupExpr with
3651 // no qualifier and should always get mangled as a <simple-id>
3652 // anyway.
3653
3654 // <expression> ::= cl <expression>* E
3655 } else {
3656 Out << "cl";
3657 }
3658
David Majnemer67a8ec62015-02-19 21:41:48 +00003659 unsigned CallArity = CE->getNumArgs();
3660 for (const Expr *Arg : CE->arguments())
3661 if (isa<PackExpansionExpr>(Arg))
3662 CallArity = UnknownArity;
3663
3664 mangleExpression(CE->getCallee(), CallArity);
3665 for (const Expr *Arg : CE->arguments())
3666 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003667 Out << 'E';
3668 break;
3669 }
3670
3671 case Expr::CXXNewExprClass: {
3672 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3673 if (New->isGlobalNew()) Out << "gs";
3674 Out << (New->isArray() ? "na" : "nw");
3675 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3676 E = New->placement_arg_end(); I != E; ++I)
3677 mangleExpression(*I);
3678 Out << '_';
3679 mangleType(New->getAllocatedType());
3680 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003681 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3682 Out << "il";
3683 else
3684 Out << "pi";
3685 const Expr *Init = New->getInitializer();
3686 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3687 // Directly inline the initializers.
3688 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3689 E = CCE->arg_end();
3690 I != E; ++I)
3691 mangleExpression(*I);
3692 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3693 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3694 mangleExpression(PLE->getExpr(i));
3695 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3696 isa<InitListExpr>(Init)) {
3697 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003698 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003699 } else
3700 mangleExpression(Init);
3701 }
3702 Out << 'E';
3703 break;
3704 }
3705
David Majnemer1dabfdc2015-02-14 13:23:54 +00003706 case Expr::CXXPseudoDestructorExprClass: {
3707 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3708 if (const Expr *Base = PDE->getBase())
3709 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003710 NestedNameSpecifier *Qualifier = PDE->getQualifier();
David Majnemerb8014dd2015-02-19 02:16:16 +00003711 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3712 if (Qualifier) {
3713 mangleUnresolvedPrefix(Qualifier,
3714 /*Recursive=*/true);
3715 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3716 Out << 'E';
3717 } else {
3718 Out << "sr";
3719 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3720 Out << 'E';
3721 }
3722 } else if (Qualifier) {
3723 mangleUnresolvedPrefix(Qualifier);
3724 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003725 // <base-unresolved-name> ::= dn <destructor-name>
3726 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003727 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003728 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003729 break;
3730 }
3731
Guy Benyei11169dd2012-12-18 14:30:41 +00003732 case Expr::MemberExprClass: {
3733 const MemberExpr *ME = cast<MemberExpr>(E);
3734 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003735 ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003736 ME->getMemberDecl()->getDeclName(),
3737 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3738 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003739 break;
3740 }
3741
3742 case Expr::UnresolvedMemberExprClass: {
3743 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003744 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3745 ME->isArrow(), ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003746 ME->getMemberName(),
3747 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3748 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003749 break;
3750 }
3751
3752 case Expr::CXXDependentScopeMemberExprClass: {
3753 const CXXDependentScopeMemberExpr *ME
3754 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003755 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3756 ME->isArrow(), ME->getQualifier(),
3757 ME->getFirstQualifierFoundInScope(),
Richard Smithafecd832016-10-24 20:47:04 +00003758 ME->getMember(),
3759 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3760 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 break;
3762 }
3763
3764 case Expr::UnresolvedLookupExprClass: {
3765 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00003766 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3767 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3768 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003769 break;
3770 }
3771
3772 case Expr::CXXUnresolvedConstructExprClass: {
3773 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3774 unsigned N = CE->arg_size();
3775
Richard Smith39eca9b2017-08-23 22:12:08 +00003776 if (CE->isListInitialization()) {
3777 assert(N == 1 && "unexpected form for list initialization");
3778 auto *IL = cast<InitListExpr>(CE->getArg(0));
3779 Out << "tl";
3780 mangleType(CE->getType());
3781 mangleInitListElements(IL);
3782 Out << "E";
3783 return;
3784 }
3785
Guy Benyei11169dd2012-12-18 14:30:41 +00003786 Out << "cv";
3787 mangleType(CE->getType());
3788 if (N != 1) Out << '_';
3789 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3790 if (N != 1) Out << 'E';
3791 break;
3792 }
3793
Guy Benyei11169dd2012-12-18 14:30:41 +00003794 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003795 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003796 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003797 assert(
3798 CE->getNumArgs() >= 1 &&
3799 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3800 "implicit CXXConstructExpr must have one argument");
3801 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3802 }
3803 Out << "il";
3804 for (auto *E : CE->arguments())
3805 mangleExpression(E);
3806 Out << "E";
3807 break;
3808 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003809
Richard Smith520449d2015-02-05 06:15:50 +00003810 case Expr::CXXTemporaryObjectExprClass: {
3811 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3812 unsigned N = CE->getNumArgs();
3813 bool List = CE->isListInitialization();
3814
3815 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003816 Out << "tl";
3817 else
3818 Out << "cv";
3819 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003820 if (!List && N != 1)
3821 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003822 if (CE->isStdInitListInitialization()) {
3823 // We implicitly created a std::initializer_list<T> for the first argument
3824 // of a constructor of type U in an expression of the form U{a, b, c}.
3825 // Strip all the semantic gunk off the initializer list.
3826 auto *SILE =
3827 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3828 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3829 mangleInitListElements(ILE);
3830 } else {
3831 for (auto *E : CE->arguments())
3832 mangleExpression(E);
3833 }
Richard Smith520449d2015-02-05 06:15:50 +00003834 if (List || N != 1)
3835 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003836 break;
3837 }
3838
3839 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003840 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003841 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003842 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003843 break;
3844
3845 case Expr::CXXNoexceptExprClass:
3846 Out << "nx";
3847 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3848 break;
3849
3850 case Expr::UnaryExprOrTypeTraitExprClass: {
3851 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3852
3853 if (!SAE->isInstantiationDependent()) {
3854 // Itanium C++ ABI:
3855 // If the operand of a sizeof or alignof operator is not
3856 // instantiation-dependent it is encoded as an integer literal
3857 // reflecting the result of the operator.
3858 //
3859 // If the result of the operator is implicitly converted to a known
3860 // integer type, that type is used for the literal; otherwise, the type
3861 // of std::size_t or std::ptrdiff_t is used.
3862 QualType T = (ImplicitlyConvertedToType.isNull() ||
3863 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3864 : ImplicitlyConvertedToType;
3865 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3866 mangleIntegerLiteral(T, V);
3867 break;
3868 }
3869
3870 switch(SAE->getKind()) {
3871 case UETT_SizeOf:
3872 Out << 's';
3873 break;
3874 case UETT_AlignOf:
3875 Out << 'a';
3876 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003877 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003878 DiagnosticsEngine &Diags = Context.getDiags();
3879 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3880 "cannot yet mangle vec_step expression");
3881 Diags.Report(DiagID);
3882 return;
3883 }
Alexey Bataev00396512015-07-02 03:40:19 +00003884 case UETT_OpenMPRequiredSimdAlign:
3885 DiagnosticsEngine &Diags = Context.getDiags();
3886 unsigned DiagID = Diags.getCustomDiagID(
3887 DiagnosticsEngine::Error,
3888 "cannot yet mangle __builtin_omp_required_simd_align expression");
3889 Diags.Report(DiagID);
3890 return;
3891 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003892 if (SAE->isArgumentType()) {
3893 Out << 't';
3894 mangleType(SAE->getArgumentType());
3895 } else {
3896 Out << 'z';
3897 mangleExpression(SAE->getArgumentExpr());
3898 }
3899 break;
3900 }
3901
3902 case Expr::CXXThrowExprClass: {
3903 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003904 // <expression> ::= tw <expression> # throw expression
3905 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003906 if (TE->getSubExpr()) {
3907 Out << "tw";
3908 mangleExpression(TE->getSubExpr());
3909 } else {
3910 Out << "tr";
3911 }
3912 break;
3913 }
3914
3915 case Expr::CXXTypeidExprClass: {
3916 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003917 // <expression> ::= ti <type> # typeid (type)
3918 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003919 if (TIE->isTypeOperand()) {
3920 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003921 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003922 } else {
3923 Out << "te";
3924 mangleExpression(TIE->getExprOperand());
3925 }
3926 break;
3927 }
3928
3929 case Expr::CXXDeleteExprClass: {
3930 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003931 // <expression> ::= [gs] dl <expression> # [::] delete expr
3932 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003933 if (DE->isGlobalDelete()) Out << "gs";
3934 Out << (DE->isArrayForm() ? "da" : "dl");
3935 mangleExpression(DE->getArgument());
3936 break;
3937 }
3938
3939 case Expr::UnaryOperatorClass: {
3940 const UnaryOperator *UO = cast<UnaryOperator>(E);
3941 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3942 /*Arity=*/1);
3943 mangleExpression(UO->getSubExpr());
3944 break;
3945 }
3946
3947 case Expr::ArraySubscriptExprClass: {
3948 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3949
3950 // Array subscript is treated as a syntactically weird form of
3951 // binary operator.
3952 Out << "ix";
3953 mangleExpression(AE->getLHS());
3954 mangleExpression(AE->getRHS());
3955 break;
3956 }
3957
3958 case Expr::CompoundAssignOperatorClass: // fallthrough
3959 case Expr::BinaryOperatorClass: {
3960 const BinaryOperator *BO = cast<BinaryOperator>(E);
3961 if (BO->getOpcode() == BO_PtrMemD)
3962 Out << "ds";
3963 else
3964 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3965 /*Arity=*/2);
3966 mangleExpression(BO->getLHS());
3967 mangleExpression(BO->getRHS());
3968 break;
3969 }
3970
3971 case Expr::ConditionalOperatorClass: {
3972 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3973 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3974 mangleExpression(CO->getCond());
3975 mangleExpression(CO->getLHS(), Arity);
3976 mangleExpression(CO->getRHS(), Arity);
3977 break;
3978 }
3979
3980 case Expr::ImplicitCastExprClass: {
3981 ImplicitlyConvertedToType = E->getType();
3982 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3983 goto recurse;
3984 }
3985
3986 case Expr::ObjCBridgedCastExprClass: {
3987 // Mangle ownership casts as a vendor extended operator __bridge,
3988 // __bridge_transfer, or __bridge_retain.
3989 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3990 Out << "v1U" << Kind.size() << Kind;
3991 }
3992 // Fall through to mangle the cast itself.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00003993 LLVM_FALLTHROUGH;
Guy Benyei11169dd2012-12-18 14:30:41 +00003994
3995 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003996 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003997 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003998
Richard Smith520449d2015-02-05 06:15:50 +00003999 case Expr::CXXFunctionalCastExprClass: {
4000 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4001 // FIXME: Add isImplicit to CXXConstructExpr.
4002 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4003 if (CCE->getParenOrBraceRange().isInvalid())
4004 Sub = CCE->getArg(0)->IgnoreImplicit();
4005 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4006 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4007 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4008 Out << "tl";
4009 mangleType(E->getType());
4010 mangleInitListElements(IL);
4011 Out << "E";
4012 } else {
4013 mangleCastExpression(E, "cv");
4014 }
4015 break;
4016 }
4017
David Majnemer9c775c72014-09-23 04:27:55 +00004018 case Expr::CXXStaticCastExprClass:
4019 mangleCastExpression(E, "sc");
4020 break;
4021 case Expr::CXXDynamicCastExprClass:
4022 mangleCastExpression(E, "dc");
4023 break;
4024 case Expr::CXXReinterpretCastExprClass:
4025 mangleCastExpression(E, "rc");
4026 break;
4027 case Expr::CXXConstCastExprClass:
4028 mangleCastExpression(E, "cc");
4029 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004030
4031 case Expr::CXXOperatorCallExprClass: {
4032 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4033 unsigned NumArgs = CE->getNumArgs();
Richard Smith4631be72016-10-24 20:29:40 +00004034 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4035 // (the enclosing MemberExpr covers the syntactic portion).
4036 if (CE->getOperator() != OO_Arrow)
4037 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 // Mangle the arguments.
4039 for (unsigned i = 0; i != NumArgs; ++i)
4040 mangleExpression(CE->getArg(i));
4041 break;
4042 }
4043
4044 case Expr::ParenExprClass:
4045 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
4046 break;
4047
4048 case Expr::DeclRefExprClass: {
4049 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4050
4051 switch (D->getKind()) {
4052 default:
4053 // <expr-primary> ::= L <mangled-name> E # external name
4054 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004055 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004056 Out << 'E';
4057 break;
4058
4059 case Decl::ParmVar:
4060 mangleFunctionParam(cast<ParmVarDecl>(D));
4061 break;
4062
4063 case Decl::EnumConstant: {
4064 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4065 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4066 break;
4067 }
4068
4069 case Decl::NonTypeTemplateParm: {
4070 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4071 mangleTemplateParameter(PD->getIndex());
4072 break;
4073 }
4074
4075 }
4076
4077 break;
4078 }
4079
4080 case Expr::SubstNonTypeTemplateParmPackExprClass:
4081 // FIXME: not clear how to mangle this!
4082 // template <unsigned N...> class A {
4083 // template <class U...> void foo(U (&x)[N]...);
4084 // };
4085 Out << "_SUBSTPACK_";
4086 break;
4087
4088 case Expr::FunctionParmPackExprClass: {
4089 // FIXME: not clear how to mangle this!
4090 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4091 Out << "v110_SUBSTPACK";
4092 mangleFunctionParam(FPPE->getParameterPack());
4093 break;
4094 }
4095
4096 case Expr::DependentScopeDeclRefExprClass: {
4097 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00004098 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4099 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4100 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00004101 break;
4102 }
4103
4104 case Expr::CXXBindTemporaryExprClass:
4105 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4106 break;
4107
4108 case Expr::ExprWithCleanupsClass:
4109 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4110 break;
4111
4112 case Expr::FloatingLiteralClass: {
4113 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4114 Out << 'L';
4115 mangleType(FL->getType());
4116 mangleFloat(FL->getValue());
4117 Out << 'E';
4118 break;
4119 }
4120
4121 case Expr::CharacterLiteralClass:
4122 Out << 'L';
4123 mangleType(E->getType());
4124 Out << cast<CharacterLiteral>(E)->getValue();
4125 Out << 'E';
4126 break;
4127
4128 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4129 case Expr::ObjCBoolLiteralExprClass:
4130 Out << "Lb";
4131 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4132 Out << 'E';
4133 break;
4134
4135 case Expr::CXXBoolLiteralExprClass:
4136 Out << "Lb";
4137 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4138 Out << 'E';
4139 break;
4140
4141 case Expr::IntegerLiteralClass: {
4142 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4143 if (E->getType()->isSignedIntegerType())
4144 Value.setIsSigned(true);
4145 mangleIntegerLiteral(E->getType(), Value);
4146 break;
4147 }
4148
4149 case Expr::ImaginaryLiteralClass: {
4150 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4151 // Mangle as if a complex literal.
4152 // Proposal from David Vandevoorde, 2010.06.30.
4153 Out << 'L';
4154 mangleType(E->getType());
4155 if (const FloatingLiteral *Imag =
4156 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4157 // Mangle a floating-point zero of the appropriate type.
4158 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4159 Out << '_';
4160 mangleFloat(Imag->getValue());
4161 } else {
4162 Out << "0_";
4163 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4164 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4165 Value.setIsSigned(true);
4166 mangleNumber(Value);
4167 }
4168 Out << 'E';
4169 break;
4170 }
4171
4172 case Expr::StringLiteralClass: {
4173 // Revised proposal from David Vandervoorde, 2010.07.15.
4174 Out << 'L';
4175 assert(isa<ConstantArrayType>(E->getType()));
4176 mangleType(E->getType());
4177 Out << 'E';
4178 break;
4179 }
4180
4181 case Expr::GNUNullExprClass:
4182 // FIXME: should this really be mangled the same as nullptr?
4183 // fallthrough
4184
4185 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004186 Out << "LDnE";
4187 break;
4188 }
4189
4190 case Expr::PackExpansionExprClass:
4191 Out << "sp";
4192 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4193 break;
4194
4195 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00004196 auto *SPE = cast<SizeOfPackExpr>(E);
4197 if (SPE->isPartiallySubstituted()) {
4198 Out << "sP";
4199 for (const auto &A : SPE->getPartialArguments())
4200 mangleTemplateArg(A);
4201 Out << "E";
4202 break;
4203 }
4204
Guy Benyei11169dd2012-12-18 14:30:41 +00004205 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00004206 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00004207 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4208 mangleTemplateParameter(TTP->getIndex());
4209 else if (const NonTypeTemplateParmDecl *NTTP
4210 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4211 mangleTemplateParameter(NTTP->getIndex());
4212 else if (const TemplateTemplateParmDecl *TempTP
4213 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4214 mangleTemplateParameter(TempTP->getIndex());
4215 else
4216 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4217 break;
4218 }
Richard Smith0f0af192014-11-08 05:07:16 +00004219
Guy Benyei11169dd2012-12-18 14:30:41 +00004220 case Expr::MaterializeTemporaryExprClass: {
4221 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
4222 break;
4223 }
Richard Smith0f0af192014-11-08 05:07:16 +00004224
4225 case Expr::CXXFoldExprClass: {
4226 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00004227 if (FE->isLeftFold())
4228 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00004229 else
Richard Smith8e6923b2014-11-10 19:44:15 +00004230 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00004231
4232 if (FE->getOperator() == BO_PtrMemD)
4233 Out << "ds";
4234 else
4235 mangleOperatorName(
4236 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4237 /*Arity=*/2);
4238
4239 if (FE->getLHS())
4240 mangleExpression(FE->getLHS());
4241 if (FE->getRHS())
4242 mangleExpression(FE->getRHS());
4243 break;
4244 }
4245
Guy Benyei11169dd2012-12-18 14:30:41 +00004246 case Expr::CXXThisExprClass:
4247 Out << "fpT";
4248 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00004249
4250 case Expr::CoawaitExprClass:
4251 // FIXME: Propose a non-vendor mangling.
4252 Out << "v18co_await";
4253 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4254 break;
4255
Eric Fiselier20f25cb2017-03-06 23:38:15 +00004256 case Expr::DependentCoawaitExprClass:
4257 // FIXME: Propose a non-vendor mangling.
4258 Out << "v18co_await";
4259 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4260 break;
4261
Richard Smith9f690bd2015-10-27 06:02:45 +00004262 case Expr::CoyieldExprClass:
4263 // FIXME: Propose a non-vendor mangling.
4264 Out << "v18co_yield";
4265 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4266 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004267 }
4268}
4269
4270/// Mangle an expression which refers to a parameter variable.
4271///
4272/// <expression> ::= <function-param>
4273/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4274/// <function-param> ::= fp <top-level CV-qualifiers>
4275/// <parameter-2 non-negative number> _ # L == 0, I > 0
4276/// <function-param> ::= fL <L-1 non-negative number>
4277/// p <top-level CV-qualifiers> _ # L > 0, I == 0
4278/// <function-param> ::= fL <L-1 non-negative number>
4279/// p <top-level CV-qualifiers>
4280/// <I-1 non-negative number> _ # L > 0, I > 0
4281///
4282/// L is the nesting depth of the parameter, defined as 1 if the
4283/// parameter comes from the innermost function prototype scope
4284/// enclosing the current context, 2 if from the next enclosing
4285/// function prototype scope, and so on, with one special case: if
4286/// we've processed the full parameter clause for the innermost
4287/// function type, then L is one less. This definition conveniently
4288/// makes it irrelevant whether a function's result type was written
4289/// trailing or leading, but is otherwise overly complicated; the
4290/// numbering was first designed without considering references to
4291/// parameter in locations other than return types, and then the
4292/// mangling had to be generalized without changing the existing
4293/// manglings.
4294///
4295/// I is the zero-based index of the parameter within its parameter
4296/// declaration clause. Note that the original ABI document describes
4297/// this using 1-based ordinals.
4298void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4299 unsigned parmDepth = parm->getFunctionScopeDepth();
4300 unsigned parmIndex = parm->getFunctionScopeIndex();
4301
4302 // Compute 'L'.
4303 // parmDepth does not include the declaring function prototype.
4304 // FunctionTypeDepth does account for that.
4305 assert(parmDepth < FunctionTypeDepth.getDepth());
4306 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4307 if (FunctionTypeDepth.isInResultType())
4308 nestingDepth--;
4309
4310 if (nestingDepth == 0) {
4311 Out << "fp";
4312 } else {
4313 Out << "fL" << (nestingDepth - 1) << 'p';
4314 }
4315
4316 // Top-level qualifiers. We don't have to worry about arrays here,
4317 // because parameters declared as arrays should already have been
4318 // transformed to have pointer type. FIXME: apparently these don't
4319 // get mangled if used as an rvalue of a known non-class type?
4320 assert(!parm->getType()->isArrayType()
4321 && "parameter's type is still an array type?");
Andrew Gozillon572bbb02017-10-02 06:25:51 +00004322
4323 if (const DependentAddressSpaceType *DAST =
4324 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4325 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4326 } else {
4327 mangleQualifiers(parm->getType().getQualifiers());
4328 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004329
4330 // Parameter index.
4331 if (parmIndex != 0) {
4332 Out << (parmIndex - 1);
4333 }
4334 Out << '_';
4335}
4336
Richard Smith5179eb72016-06-28 19:03:57 +00004337void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4338 const CXXRecordDecl *InheritedFrom) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004339 // <ctor-dtor-name> ::= C1 # complete object constructor
4340 // ::= C2 # base object constructor
Richard Smith5179eb72016-06-28 19:03:57 +00004341 // ::= CI1 <type> # complete inheriting constructor
4342 // ::= CI2 <type> # base inheriting constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00004343 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004344 // In addition, C5 is a comdat name with C1 and C2 in it.
Richard Smith5179eb72016-06-28 19:03:57 +00004345 Out << 'C';
4346 if (InheritedFrom)
4347 Out << 'I';
Guy Benyei11169dd2012-12-18 14:30:41 +00004348 switch (T) {
4349 case Ctor_Complete:
Richard Smith5179eb72016-06-28 19:03:57 +00004350 Out << '1';
Guy Benyei11169dd2012-12-18 14:30:41 +00004351 break;
4352 case Ctor_Base:
Richard Smith5179eb72016-06-28 19:03:57 +00004353 Out << '2';
Guy Benyei11169dd2012-12-18 14:30:41 +00004354 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004355 case Ctor_Comdat:
Richard Smith5179eb72016-06-28 19:03:57 +00004356 Out << '5';
Guy Benyei11169dd2012-12-18 14:30:41 +00004357 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00004358 case Ctor_DefaultClosure:
4359 case Ctor_CopyingClosure:
4360 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00004361 }
Richard Smith5179eb72016-06-28 19:03:57 +00004362 if (InheritedFrom)
4363 mangleName(InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00004364}
4365
4366void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4367 // <ctor-dtor-name> ::= D0 # deleting destructor
4368 // ::= D1 # complete object destructor
4369 // ::= D2 # base object destructor
4370 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004371 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00004372 switch (T) {
4373 case Dtor_Deleting:
4374 Out << "D0";
4375 break;
4376 case Dtor_Complete:
4377 Out << "D1";
4378 break;
4379 case Dtor_Base:
4380 Out << "D2";
4381 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004382 case Dtor_Comdat:
4383 Out << "D5";
4384 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004385 }
4386}
4387
James Y Knight04ec5bf2015-12-24 02:59:37 +00004388void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4389 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004390 // <template-args> ::= I <template-arg>+ E
4391 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00004392 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4393 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00004394 Out << 'E';
4395}
4396
4397void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4398 // <template-args> ::= I <template-arg>+ E
4399 Out << 'I';
4400 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4401 mangleTemplateArg(AL[i]);
4402 Out << 'E';
4403}
4404
4405void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4406 unsigned NumTemplateArgs) {
4407 // <template-args> ::= I <template-arg>+ E
4408 Out << 'I';
4409 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4410 mangleTemplateArg(TemplateArgs[i]);
4411 Out << 'E';
4412}
4413
4414void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4415 // <template-arg> ::= <type> # type or template
4416 // ::= X <expression> E # expression
4417 // ::= <expr-primary> # simple expressions
4418 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00004419 if (!A.isInstantiationDependent() || A.isDependent())
4420 A = Context.getASTContext().getCanonicalTemplateArgument(A);
4421
4422 switch (A.getKind()) {
4423 case TemplateArgument::Null:
4424 llvm_unreachable("Cannot mangle NULL template argument");
4425
4426 case TemplateArgument::Type:
4427 mangleType(A.getAsType());
4428 break;
4429 case TemplateArgument::Template:
4430 // This is mangled as <type>.
4431 mangleType(A.getAsTemplate());
4432 break;
4433 case TemplateArgument::TemplateExpansion:
4434 // <type> ::= Dp <type> # pack expansion (C++0x)
4435 Out << "Dp";
4436 mangleType(A.getAsTemplateOrTemplatePattern());
4437 break;
4438 case TemplateArgument::Expression: {
4439 // It's possible to end up with a DeclRefExpr here in certain
4440 // dependent cases, in which case we should mangle as a
4441 // declaration.
4442 const Expr *E = A.getAsExpr()->IgnoreParens();
4443 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4444 const ValueDecl *D = DRE->getDecl();
4445 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00004446 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004447 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004448 Out << 'E';
4449 break;
4450 }
4451 }
4452
4453 Out << 'X';
4454 mangleExpression(E);
4455 Out << 'E';
4456 break;
4457 }
4458 case TemplateArgument::Integral:
4459 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4460 break;
4461 case TemplateArgument::Declaration: {
4462 // <expr-primary> ::= L <mangled-name> E # external name
4463 // Clang produces AST's where pointer-to-member-function expressions
4464 // and pointer-to-function expressions are represented as a declaration not
4465 // an expression. We compensate for it here to produce the correct mangling.
4466 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00004467 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00004468 if (compensateMangling) {
4469 Out << 'X';
4470 mangleOperatorName(OO_Amp, 1);
4471 }
4472
4473 Out << 'L';
4474 // References to external entities use the mangled name; if the name would
Nico Weberfb420782016-05-25 14:15:08 +00004475 // not normally be mangled then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00004476 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004477 Out << 'E';
4478
4479 if (compensateMangling)
4480 Out << 'E';
4481
4482 break;
4483 }
4484 case TemplateArgument::NullPtr: {
4485 // <expr-primary> ::= L <type> 0 E
4486 Out << 'L';
4487 mangleType(A.getNullPtrType());
4488 Out << "0E";
4489 break;
4490 }
4491 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00004492 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00004493 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00004494 for (const auto &P : A.pack_elements())
4495 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00004496 Out << 'E';
4497 }
4498 }
4499}
4500
4501void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4502 // <template-param> ::= T_ # first template parameter
4503 // ::= T <parameter-2 non-negative number> _
4504 if (Index == 0)
4505 Out << "T_";
4506 else
4507 Out << 'T' << (Index - 1) << '_';
4508}
4509
David Majnemer3b3bdb52014-05-06 22:49:16 +00004510void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4511 if (SeqID == 1)
4512 Out << '0';
4513 else if (SeqID > 1) {
4514 SeqID--;
4515
4516 // <seq-id> is encoded in base-36, using digits and upper case letters.
4517 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00004518 MutableArrayRef<char> BufferRef(Buffer);
4519 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00004520
4521 for (; SeqID != 0; SeqID /= 36) {
4522 unsigned C = SeqID % 36;
4523 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4524 }
4525
4526 Out.write(I.base(), I - BufferRef.rbegin());
4527 }
4528 Out << '_';
4529}
4530
Guy Benyei11169dd2012-12-18 14:30:41 +00004531void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4532 bool result = mangleSubstitution(tname);
4533 assert(result && "no existing substitution for template name");
4534 (void) result;
4535}
4536
4537// <substitution> ::= S <seq-id> _
4538// ::= S_
4539bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4540 // Try one of the standard substitutions first.
4541 if (mangleStandardSubstitution(ND))
4542 return true;
4543
4544 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4545 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4546}
4547
Justin Bognere8d762e2015-05-22 06:48:13 +00004548/// Determine whether the given type has any qualifiers that are relevant for
4549/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00004550static bool hasMangledSubstitutionQualifiers(QualType T) {
4551 Qualifiers Qs = T.getQualifiers();
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00004552 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
Guy Benyei11169dd2012-12-18 14:30:41 +00004553}
4554
4555bool CXXNameMangler::mangleSubstitution(QualType T) {
4556 if (!hasMangledSubstitutionQualifiers(T)) {
4557 if (const RecordType *RT = T->getAs<RecordType>())
4558 return mangleSubstitution(RT->getDecl());
4559 }
4560
4561 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4562
4563 return mangleSubstitution(TypePtr);
4564}
4565
4566bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4567 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4568 return mangleSubstitution(TD);
4569
4570 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4571 return mangleSubstitution(
4572 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4573}
4574
4575bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4576 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4577 if (I == Substitutions.end())
4578 return false;
4579
4580 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00004581 Out << 'S';
4582 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00004583
4584 return true;
4585}
4586
4587static bool isCharType(QualType T) {
4588 if (T.isNull())
4589 return false;
4590
4591 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4592 T->isSpecificBuiltinType(BuiltinType::Char_U);
4593}
4594
Justin Bognere8d762e2015-05-22 06:48:13 +00004595/// Returns whether a given type is a template specialization of a given name
4596/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00004597static bool isCharSpecialization(QualType T, const char *Name) {
4598 if (T.isNull())
4599 return false;
4600
4601 const RecordType *RT = T->getAs<RecordType>();
4602 if (!RT)
4603 return false;
4604
4605 const ClassTemplateSpecializationDecl *SD =
4606 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4607 if (!SD)
4608 return false;
4609
4610 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4611 return false;
4612
4613 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4614 if (TemplateArgs.size() != 1)
4615 return false;
4616
4617 if (!isCharType(TemplateArgs[0].getAsType()))
4618 return false;
4619
4620 return SD->getIdentifier()->getName() == Name;
4621}
4622
4623template <std::size_t StrLen>
4624static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4625 const char (&Str)[StrLen]) {
4626 if (!SD->getIdentifier()->isStr(Str))
4627 return false;
4628
4629 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4630 if (TemplateArgs.size() != 2)
4631 return false;
4632
4633 if (!isCharType(TemplateArgs[0].getAsType()))
4634 return false;
4635
4636 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4637 return false;
4638
4639 return true;
4640}
4641
4642bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4643 // <substitution> ::= St # ::std::
4644 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4645 if (isStd(NS)) {
4646 Out << "St";
4647 return true;
4648 }
4649 }
4650
4651 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4652 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4653 return false;
4654
4655 // <substitution> ::= Sa # ::std::allocator
4656 if (TD->getIdentifier()->isStr("allocator")) {
4657 Out << "Sa";
4658 return true;
4659 }
4660
4661 // <<substitution> ::= Sb # ::std::basic_string
4662 if (TD->getIdentifier()->isStr("basic_string")) {
4663 Out << "Sb";
4664 return true;
4665 }
4666 }
4667
4668 if (const ClassTemplateSpecializationDecl *SD =
4669 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4670 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4671 return false;
4672
4673 // <substitution> ::= Ss # ::std::basic_string<char,
4674 // ::std::char_traits<char>,
4675 // ::std::allocator<char> >
4676 if (SD->getIdentifier()->isStr("basic_string")) {
4677 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4678
4679 if (TemplateArgs.size() != 3)
4680 return false;
4681
4682 if (!isCharType(TemplateArgs[0].getAsType()))
4683 return false;
4684
4685 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4686 return false;
4687
4688 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4689 return false;
4690
4691 Out << "Ss";
4692 return true;
4693 }
4694
4695 // <substitution> ::= Si # ::std::basic_istream<char,
4696 // ::std::char_traits<char> >
4697 if (isStreamCharSpecialization(SD, "basic_istream")) {
4698 Out << "Si";
4699 return true;
4700 }
4701
4702 // <substitution> ::= So # ::std::basic_ostream<char,
4703 // ::std::char_traits<char> >
4704 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4705 Out << "So";
4706 return true;
4707 }
4708
4709 // <substitution> ::= Sd # ::std::basic_iostream<char,
4710 // ::std::char_traits<char> >
4711 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4712 Out << "Sd";
4713 return true;
4714 }
4715 }
4716 return false;
4717}
4718
4719void CXXNameMangler::addSubstitution(QualType T) {
4720 if (!hasMangledSubstitutionQualifiers(T)) {
4721 if (const RecordType *RT = T->getAs<RecordType>()) {
4722 addSubstitution(RT->getDecl());
4723 return;
4724 }
4725 }
4726
4727 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4728 addSubstitution(TypePtr);
4729}
4730
4731void CXXNameMangler::addSubstitution(TemplateName Template) {
4732 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4733 return addSubstitution(TD);
4734
4735 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4736 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4737}
4738
4739void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4740 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4741 Substitutions[Ptr] = SeqID++;
4742}
4743
Dmitry Polukhinfda467b2016-09-21 08:27:03 +00004744void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4745 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4746 if (Other->SeqID > SeqID) {
4747 Substitutions.swap(Other->Substitutions);
4748 SeqID = Other->SeqID;
4749 }
4750}
4751
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004752CXXNameMangler::AbiTagList
4753CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4754 // When derived abi tags are disabled there is no need to make any list.
4755 if (DisableDerivedAbiTags)
4756 return AbiTagList();
4757
4758 llvm::raw_null_ostream NullOutStream;
4759 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4760 TrackReturnTypeTags.disableDerivedAbiTags();
4761
4762 const FunctionProtoType *Proto =
4763 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004764 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004765 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4766 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4767 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004768 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004769
4770 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4771}
4772
4773CXXNameMangler::AbiTagList
4774CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4775 // When derived abi tags are disabled there is no need to make any list.
4776 if (DisableDerivedAbiTags)
4777 return AbiTagList();
4778
4779 llvm::raw_null_ostream NullOutStream;
4780 CXXNameMangler TrackVariableType(*this, NullOutStream);
4781 TrackVariableType.disableDerivedAbiTags();
4782
4783 TrackVariableType.mangleType(VD->getType());
4784
4785 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4786}
4787
4788bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4789 const VarDecl *VD) {
4790 llvm::raw_null_ostream NullOutStream;
4791 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4792 TrackAbiTags.mangle(VD);
4793 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4794}
4795
Guy Benyei11169dd2012-12-18 14:30:41 +00004796//
4797
Justin Bognere8d762e2015-05-22 06:48:13 +00004798/// Mangles the name of the declaration D and emits that name to the given
4799/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004800///
4801/// If the declaration D requires a mangled name, this routine will emit that
4802/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4803/// and this routine will return false. In this case, the caller should just
4804/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4805/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004806void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4807 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004808 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4809 "Invalid mangleName() call, argument is not a variable or function!");
4810 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4811 "Invalid mangleName() call on 'structor decl!");
4812
4813 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4814 getASTContext().getSourceManager(),
4815 "Mangling declaration");
4816
4817 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004818 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004819}
4820
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004821void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4822 CXXCtorType Type,
4823 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004824 CXXNameMangler Mangler(*this, Out, D, Type);
4825 Mangler.mangle(D);
4826}
4827
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004828void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4829 CXXDtorType Type,
4830 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004831 CXXNameMangler Mangler(*this, Out, D, Type);
4832 Mangler.mangle(D);
4833}
4834
Rafael Espindola1e4df922014-09-16 15:18:21 +00004835void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4836 raw_ostream &Out) {
4837 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4838 Mangler.mangle(D);
4839}
4840
4841void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4842 raw_ostream &Out) {
4843 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4844 Mangler.mangle(D);
4845}
4846
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004847void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4848 const ThunkInfo &Thunk,
4849 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004850 // <special-name> ::= T <call-offset> <base encoding>
4851 // # base is the nominal target function of thunk
4852 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4853 // # base is the nominal target function of thunk
4854 // # first call-offset is 'this' adjustment
4855 // # second call-offset is result adjustment
4856
4857 assert(!isa<CXXDestructorDecl>(MD) &&
4858 "Use mangleCXXDtor for destructor decls!");
4859 CXXNameMangler Mangler(*this, Out);
4860 Mangler.getStream() << "_ZT";
4861 if (!Thunk.Return.isEmpty())
4862 Mangler.getStream() << 'c';
4863
4864 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004865 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4866 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4867
Guy Benyei11169dd2012-12-18 14:30:41 +00004868 // Mangle the return pointer adjustment if there is one.
4869 if (!Thunk.Return.isEmpty())
4870 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004871 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4872
Guy Benyei11169dd2012-12-18 14:30:41 +00004873 Mangler.mangleFunctionEncoding(MD);
4874}
4875
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004876void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4877 const CXXDestructorDecl *DD, CXXDtorType Type,
4878 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004879 // <special-name> ::= T <call-offset> <base encoding>
4880 // # base is the nominal target function of thunk
4881 CXXNameMangler Mangler(*this, Out, DD, Type);
4882 Mangler.getStream() << "_ZT";
4883
4884 // Mangle the 'this' pointer adjustment.
4885 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004886 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004887
4888 Mangler.mangleFunctionEncoding(DD);
4889}
4890
Justin Bognere8d762e2015-05-22 06:48:13 +00004891/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004892void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4893 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004894 // <special-name> ::= GV <object name> # Guard variable for one-time
4895 // # initialization
4896 CXXNameMangler Mangler(*this, Out);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004897 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4898 // be a bug that is fixed in trunk.
Guy Benyei11169dd2012-12-18 14:30:41 +00004899 Mangler.getStream() << "_ZGV";
4900 Mangler.mangleName(D);
4901}
4902
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004903void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4904 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004905 // These symbols are internal in the Itanium ABI, so the names don't matter.
4906 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4907 // avoid duplicate symbols.
4908 Out << "__cxx_global_var_init";
4909}
4910
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004911void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4912 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004913 // Prefix the mangling of D with __dtor_.
4914 CXXNameMangler Mangler(*this, Out);
4915 Mangler.getStream() << "__dtor_";
4916 if (shouldMangleDeclName(D))
4917 Mangler.mangle(D);
4918 else
4919 Mangler.getStream() << D->getName();
4920}
4921
Reid Kleckner1d59f992015-01-22 01:36:17 +00004922void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4923 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4924 CXXNameMangler Mangler(*this, Out);
4925 Mangler.getStream() << "__filt_";
4926 if (shouldMangleDeclName(EnclosingDecl))
4927 Mangler.mangle(EnclosingDecl);
4928 else
4929 Mangler.getStream() << EnclosingDecl->getName();
4930}
4931
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004932void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4933 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4934 CXXNameMangler Mangler(*this, Out);
4935 Mangler.getStream() << "__fin_";
4936 if (shouldMangleDeclName(EnclosingDecl))
4937 Mangler.mangle(EnclosingDecl);
4938 else
4939 Mangler.getStream() << EnclosingDecl->getName();
4940}
4941
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004942void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4943 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004944 // <special-name> ::= TH <object name>
4945 CXXNameMangler Mangler(*this, Out);
4946 Mangler.getStream() << "_ZTH";
4947 Mangler.mangleName(D);
4948}
4949
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004950void
4951ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4952 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004953 // <special-name> ::= TW <object name>
4954 CXXNameMangler Mangler(*this, Out);
4955 Mangler.getStream() << "_ZTW";
4956 Mangler.mangleName(D);
4957}
4958
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004959void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004960 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004961 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004962 // We match the GCC mangling here.
4963 // <special-name> ::= GR <object name>
4964 CXXNameMangler Mangler(*this, Out);
4965 Mangler.getStream() << "_ZGR";
4966 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004967 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004968 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004969}
4970
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004971void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4972 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004973 // <special-name> ::= TV <type> # virtual table
4974 CXXNameMangler Mangler(*this, Out);
4975 Mangler.getStream() << "_ZTV";
4976 Mangler.mangleNameOrStandardSubstitution(RD);
4977}
4978
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004979void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4980 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004981 // <special-name> ::= TT <type> # VTT structure
4982 CXXNameMangler Mangler(*this, Out);
4983 Mangler.getStream() << "_ZTT";
4984 Mangler.mangleNameOrStandardSubstitution(RD);
4985}
4986
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004987void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4988 int64_t Offset,
4989 const CXXRecordDecl *Type,
4990 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 // <special-name> ::= TC <type> <offset number> _ <base type>
4992 CXXNameMangler Mangler(*this, Out);
4993 Mangler.getStream() << "_ZTC";
4994 Mangler.mangleNameOrStandardSubstitution(RD);
4995 Mangler.getStream() << Offset;
4996 Mangler.getStream() << '_';
4997 Mangler.mangleNameOrStandardSubstitution(Type);
4998}
4999
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005000void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 // <special-name> ::= TI <type> # typeinfo structure
5002 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
5003 CXXNameMangler Mangler(*this, Out);
5004 Mangler.getStream() << "_ZTI";
5005 Mangler.mangleType(Ty);
5006}
5007
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005008void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
5009 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005010 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
5011 CXXNameMangler Mangler(*this, Out);
5012 Mangler.getStream() << "_ZTS";
5013 Mangler.mangleType(Ty);
5014}
5015
Reid Klecknercc99e262013-11-19 23:23:00 +00005016void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
5017 mangleCXXRTTIName(Ty, Out);
5018}
5019
David Majnemer58e5bee2014-03-24 21:43:36 +00005020void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
5021 llvm_unreachable("Can't mangle string literals");
5022}
5023
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005024ItaniumMangleContext *
5025ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
5026 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00005027}