blob: e99549850acd6e3893bee4cd96a6f5074aad8d53 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Implements C++ name mangling according to the Itanium C++ ABI,
11// which is used in GCC 3.2 and newer (and many compilers that are
12// ABI-compatible with GCC):
13//
Vlad Tsyrklevichb1bb99d2017-09-12 00:21:17 +000014// http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling
Guy Benyei11169dd2012-12-18 14:30:41 +000015//
16//===----------------------------------------------------------------------===//
17#include "clang/AST/Mangle.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000023#include "clang/AST/DeclOpenMP.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/DeclTemplate.h"
David Majnemer58e5bee2014-03-24 21:43:36 +000025#include "clang/AST/Expr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/Basic/ABI.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "llvm/ADT/StringExtras.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35
36#define MANGLE_CHECKER 0
37
38#if MANGLE_CHECKER
39#include <cxxabi.h>
40#endif
41
42using namespace clang;
43
44namespace {
45
Justin Bognere8d762e2015-05-22 06:48:13 +000046/// Retrieve the declaration context that should be used when mangling the given
47/// declaration.
Guy Benyei11169dd2012-12-18 14:30:41 +000048static const DeclContext *getEffectiveDeclContext(const Decl *D) {
Fangrui Song6907ce22018-07-30 19:24:48 +000049 // The ABI assumes that lambda closure types that occur within
Guy Benyei11169dd2012-12-18 14:30:41 +000050 // default arguments live in the context of the function. However, due to
51 // the way in which Clang parses and creates function declarations, this is
Fangrui Song6907ce22018-07-30 19:24:48 +000052 // not the case: the lambda closure type ends up living in the context
Guy Benyei11169dd2012-12-18 14:30:41 +000053 // where the function itself resides, because the function declaration itself
54 // had not yet been created. Fix the context here.
55 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
56 if (RD->isLambda())
57 if (ParmVarDecl *ContextParam
58 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
59 return ContextParam->getDeclContext();
60 }
Eli Friedman0cd23352013-07-10 01:33:19 +000061
62 // Perform the same check for block literals.
63 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
64 if (ParmVarDecl *ContextParam
65 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
66 return ContextParam->getDeclContext();
67 }
Fangrui Song6907ce22018-07-30 19:24:48 +000068
Eli Friedman95f50122013-07-02 17:52:28 +000069 const DeclContext *DC = D->getDeclContext();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000070 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
71 return getEffectiveDeclContext(cast<Decl>(DC));
72 }
Eli Friedman95f50122013-07-02 17:52:28 +000073
David Majnemerf8c02e62015-02-18 19:08:11 +000074 if (const auto *VD = dyn_cast<VarDecl>(D))
75 if (VD->isExternC())
76 return VD->getASTContext().getTranslationUnitDecl();
77
78 if (const auto *FD = dyn_cast<FunctionDecl>(D))
79 if (FD->isExternC())
80 return FD->getASTContext().getTranslationUnitDecl();
81
Richard Smithec24bbe2016-04-29 01:23:20 +000082 return DC->getRedeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +000083}
84
85static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
86 return getEffectiveDeclContext(cast<Decl>(DC));
87}
Eli Friedman95f50122013-07-02 17:52:28 +000088
89static bool isLocalContainerContext(const DeclContext *DC) {
90 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
91}
92
Eli Friedmaneecc09a2013-07-05 20:27:40 +000093static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman92821742013-07-02 02:01:18 +000094 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000095 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman95f50122013-07-02 17:52:28 +000096 if (isLocalContainerContext(DC))
Eli Friedmaneecc09a2013-07-05 20:27:40 +000097 return dyn_cast<RecordDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +000098 D = cast<Decl>(DC);
99 DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000100 }
Craig Topper36250ad2014-05-12 05:36:57 +0000101 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000102}
103
104static const FunctionDecl *getStructor(const FunctionDecl *fn) {
105 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
106 return ftd->getTemplatedDecl();
107
108 return fn;
109}
110
111static const NamedDecl *getStructor(const NamedDecl *decl) {
112 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
113 return (fn ? getStructor(fn) : decl);
114}
David Majnemer2206bf52014-03-05 08:57:59 +0000115
116static bool isLambda(const NamedDecl *ND) {
117 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
118 if (!Record)
119 return false;
120
121 return Record->isLambda();
122}
123
Guy Benyei11169dd2012-12-18 14:30:41 +0000124static const unsigned UnknownArity = ~0U;
125
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000126class ItaniumMangleContextImpl : public ItaniumMangleContext {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000127 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
128 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei11169dd2012-12-18 14:30:41 +0000129 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000130
Guy Benyei11169dd2012-12-18 14:30:41 +0000131public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000132 explicit ItaniumMangleContextImpl(ASTContext &Context,
133 DiagnosticsEngine &Diags)
134 : ItaniumMangleContext(Context, Diags) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000135
Guy Benyei11169dd2012-12-18 14:30:41 +0000136 /// @name Mangler Entry Points
137 /// @{
138
Craig Toppercbce6e92014-03-11 06:22:39 +0000139 bool shouldMangleCXXName(const NamedDecl *D) override;
David Majnemer58e5bee2014-03-24 21:43:36 +0000140 bool shouldMangleStringLiteral(const StringLiteral *) override {
141 return false;
142 }
Craig Toppercbce6e92014-03-11 06:22:39 +0000143 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
144 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
145 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000146 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
147 const ThisAdjustment &ThisAdjustment,
Craig Toppercbce6e92014-03-11 06:22:39 +0000148 raw_ostream &) override;
David Majnemerdaff3702014-05-01 17:50:17 +0000149 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
150 raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000151 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
152 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000153 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
Craig Toppercbce6e92014-03-11 06:22:39 +0000154 const CXXRecordDecl *Type, raw_ostream &) override;
155 void mangleCXXRTTI(QualType T, raw_ostream &) override;
156 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
157 void mangleTypeName(QualType T, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000159 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000160 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000161 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000162
Rafael Espindola1e4df922014-09-16 15:18:21 +0000163 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
164 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000165 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
166 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
167 void mangleDynamicAtExitDestructor(const VarDecl *D,
168 raw_ostream &Out) override;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000169 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
170 raw_ostream &Out) override;
Reid Klecknerebaf28d2015-04-14 20:59:00 +0000171 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
172 raw_ostream &Out) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000173 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
174 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
175 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000176
David Majnemer58e5bee2014-03-24 21:43:36 +0000177 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
178
Guy Benyei11169dd2012-12-18 14:30:41 +0000179 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000180 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000181 if (isLambda(ND))
182 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000183
184 // Anonymous tags are already numbered.
185 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
186 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
187 return false;
188 }
189
190 // Use the canonical number for externally visible decls.
191 if (ND->isExternallyVisible()) {
192 unsigned discriminator = getASTContext().getManglingNumber(ND);
193 if (discriminator == 1)
194 return false;
195 disc = discriminator - 2;
196 return true;
197 }
198
199 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000201 if (!discriminator) {
202 const DeclContext *DC = getEffectiveDeclContext(ND);
203 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
204 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000205 if (discriminator == 1)
206 return false;
207 disc = discriminator-2;
208 return true;
209 }
210 /// @}
211};
212
Justin Bognere8d762e2015-05-22 06:48:13 +0000213/// Manage the mangling of a single name.
Guy Benyei11169dd2012-12-18 14:30:41 +0000214class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000215 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000216 raw_ostream &Out;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000217 bool NullOut = false;
218 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
219 /// This mode is used when mangler creates another mangler recursively to
220 /// calculate ABI tags for the function return value or the variable type.
221 /// Also it is required to avoid infinite recursion in some cases.
222 bool DisableDerivedAbiTags = false;
Guy Benyei11169dd2012-12-18 14:30:41 +0000223
224 /// The "structor" is the top-level declaration being mangled, if
225 /// that's not a template specialization; otherwise it's the pattern
226 /// for that specialization.
227 const NamedDecl *Structor;
228 unsigned StructorType;
229
Justin Bognere8d762e2015-05-22 06:48:13 +0000230 /// The next substitution sequence number.
Guy Benyei11169dd2012-12-18 14:30:41 +0000231 unsigned SeqID;
232
233 class FunctionTypeDepthState {
234 unsigned Bits;
235
236 enum { InResultTypeMask = 1 };
237
238 public:
239 FunctionTypeDepthState() : Bits(0) {}
240
241 /// The number of function types we're inside.
242 unsigned getDepth() const {
243 return Bits >> 1;
244 }
245
246 /// True if we're in the return type of the innermost function type.
247 bool isInResultType() const {
248 return Bits & InResultTypeMask;
249 }
250
251 FunctionTypeDepthState push() {
252 FunctionTypeDepthState tmp = *this;
253 Bits = (Bits & ~InResultTypeMask) + 2;
254 return tmp;
255 }
256
257 void enterResultType() {
258 Bits |= InResultTypeMask;
259 }
260
261 void leaveResultType() {
262 Bits &= ~InResultTypeMask;
263 }
264
265 void pop(FunctionTypeDepthState saved) {
266 assert(getDepth() == saved.getDepth() + 1);
267 Bits = saved.Bits;
268 }
269
270 } FunctionTypeDepth;
271
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000272 // abi_tag is a gcc attribute, taking one or more strings called "tags".
273 // The goal is to annotate against which version of a library an object was
274 // built and to be able to provide backwards compatibility ("dual abi").
275 // For more information see docs/ItaniumMangleAbiTags.rst.
276 typedef SmallVector<StringRef, 4> AbiTagList;
277
278 // State to gather all implicit and explicit tags used in a mangled name.
279 // Must always have an instance of this while emitting any name to keep
280 // track.
281 class AbiTagState final {
282 public:
283 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
284 Parent = LinkHead;
285 LinkHead = this;
286 }
287
288 // No copy, no move.
289 AbiTagState(const AbiTagState &) = delete;
290 AbiTagState &operator=(const AbiTagState &) = delete;
291
292 ~AbiTagState() { pop(); }
293
294 void write(raw_ostream &Out, const NamedDecl *ND,
295 const AbiTagList *AdditionalAbiTags) {
296 ND = cast<NamedDecl>(ND->getCanonicalDecl());
297 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
298 assert(
299 !AdditionalAbiTags &&
300 "only function and variables need a list of additional abi tags");
301 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
302 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
303 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
304 AbiTag->tags().end());
305 }
306 // Don't emit abi tags for namespaces.
307 return;
308 }
309 }
310
311 AbiTagList TagList;
312 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
313 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
314 AbiTag->tags().end());
315 TagList.insert(TagList.end(), AbiTag->tags().begin(),
316 AbiTag->tags().end());
317 }
318
319 if (AdditionalAbiTags) {
320 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
321 AdditionalAbiTags->end());
322 TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
323 AdditionalAbiTags->end());
324 }
325
Fangrui Song55fab262018-09-26 22:16:28 +0000326 llvm::sort(TagList);
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() {
Fangrui Song55fab262018-09-26 22:16:28 +0000342 llvm::sort(UsedAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000343 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
344 UsedAbiTags.end());
345 return UsedAbiTags;
346 }
347
348 private:
349 //! All abi tags used implicitly or explicitly.
350 AbiTagList UsedAbiTags;
351 //! All explicit abi tags (i.e. not from namespace).
352 AbiTagList EmittedAbiTags;
353
354 AbiTagState *&LinkHead;
355 AbiTagState *Parent = nullptr;
356
357 void pop() {
358 assert(LinkHead == this &&
359 "abi tag link head must point to us on destruction");
360 if (Parent) {
361 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
362 UsedAbiTags.begin(), UsedAbiTags.end());
363 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
364 EmittedAbiTags.begin(),
365 EmittedAbiTags.end());
366 }
367 LinkHead = Parent;
368 }
369
370 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
371 for (const auto &Tag : AbiTags) {
372 EmittedAbiTags.push_back(Tag);
373 Out << "B";
374 Out << Tag.size();
375 Out << Tag;
376 }
377 }
378 };
379
380 AbiTagState *AbiTags = nullptr;
381 AbiTagState AbiTagsRoot;
382
Guy Benyei11169dd2012-12-18 14:30:41 +0000383 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
Richard Smithdd8b5332017-09-04 05:37:53 +0000384 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions;
Guy Benyei11169dd2012-12-18 14:30:41 +0000385
386 ASTContext &getASTContext() const { return Context.getASTContext(); }
387
388public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000389 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000390 const NamedDecl *D = nullptr, bool NullOut_ = false)
391 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
392 StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000393 // These can't be mangled without a ctor type or dtor type.
394 assert(!D || (!isa<CXXDestructorDecl>(D) &&
395 !isa<CXXConstructorDecl>(D)));
396 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000397 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000398 const CXXConstructorDecl *D, CXXCtorType Type)
399 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000400 SeqID(0), AbiTagsRoot(AbiTags) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000401 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000402 const CXXDestructorDecl *D, CXXDtorType Type)
403 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000404 SeqID(0), AbiTagsRoot(AbiTags) { }
405
406 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
407 : Context(Outer.Context), Out(Out_), NullOut(false),
408 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000409 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
410 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000411
412 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
413 : Context(Outer.Context), Out(Out_), NullOut(true),
414 Structor(Outer.Structor), StructorType(Outer.StructorType),
Alex Lorenz7ba609a2016-10-06 09:37:15 +0000415 SeqID(Outer.SeqID), FunctionTypeDepth(Outer.FunctionTypeDepth),
416 AbiTagsRoot(AbiTags), Substitutions(Outer.Substitutions) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000417
418#if MANGLE_CHECKER
419 ~CXXNameMangler() {
420 if (Out.str()[0] == '\01')
421 return;
422
423 int status = 0;
424 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
425 assert(status == 0 && "Could not demangle mangled name!");
426 free(result);
427 }
428#endif
429 raw_ostream &getStream() { return Out; }
430
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000431 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
432 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
433
David Majnemer7ff7eb72015-02-18 07:47:09 +0000434 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000435 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
436 void mangleNumber(const llvm::APSInt &I);
437 void mangleNumber(int64_t Number);
438 void mangleFloat(const llvm::APFloat &F);
439 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000440 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000441 void mangleName(const NamedDecl *ND);
442 void mangleType(QualType T);
443 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
Fangrui Song6907ce22018-07-30 19:24:48 +0000444
Guy Benyei11169dd2012-12-18 14:30:41 +0000445private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000446
Guy Benyei11169dd2012-12-18 14:30:41 +0000447 bool mangleSubstitution(const NamedDecl *ND);
448 bool mangleSubstitution(QualType T);
449 bool mangleSubstitution(TemplateName Template);
450 bool mangleSubstitution(uintptr_t Ptr);
451
Guy Benyei11169dd2012-12-18 14:30:41 +0000452 void mangleExistingSubstitution(TemplateName name);
453
454 bool mangleStandardSubstitution(const NamedDecl *ND);
455
456 void addSubstitution(const NamedDecl *ND) {
457 ND = cast<NamedDecl>(ND->getCanonicalDecl());
458
459 addSubstitution(reinterpret_cast<uintptr_t>(ND));
460 }
461 void addSubstitution(QualType T);
462 void addSubstitution(TemplateName Template);
463 void addSubstitution(uintptr_t Ptr);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000464 // Destructive copy substitutions from other mangler.
465 void extendSubstitutions(CXXNameMangler* Other);
Guy Benyei11169dd2012-12-18 14:30:41 +0000466
467 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000468 bool recursive = false);
469 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000470 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000471 const TemplateArgumentLoc *TemplateArgs,
472 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000473 unsigned KnownArity = UnknownArity);
474
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000475 void mangleFunctionEncodingBareType(const FunctionDecl *FD);
476
477 void mangleNameWithAbiTags(const NamedDecl *ND,
478 const AbiTagList *AdditionalAbiTags);
Richard Smithdd8b5332017-09-04 05:37:53 +0000479 void mangleModuleName(const Module *M);
480 void mangleModuleNamePrefix(StringRef Name);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000481 void mangleTemplateName(const TemplateDecl *TD,
482 const TemplateArgument *TemplateArgs,
483 unsigned NumTemplateArgs);
484 void mangleUnqualifiedName(const NamedDecl *ND,
485 const AbiTagList *AdditionalAbiTags) {
486 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
487 AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000488 }
489 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000490 unsigned KnownArity,
491 const AbiTagList *AdditionalAbiTags);
492 void mangleUnscopedName(const NamedDecl *ND,
493 const AbiTagList *AdditionalAbiTags);
494 void mangleUnscopedTemplateName(const TemplateDecl *ND,
495 const AbiTagList *AdditionalAbiTags);
496 void mangleUnscopedTemplateName(TemplateName,
497 const AbiTagList *AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000498 void mangleSourceName(const IdentifierInfo *II);
Erich Keane757d3172016-11-02 18:29:35 +0000499 void mangleRegCallName(const IdentifierInfo *II);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000500 void mangleSourceNameWithAbiTags(
501 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
502 void mangleLocalName(const Decl *D,
503 const AbiTagList *AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +0000504 void mangleBlockForPrefix(const BlockDecl *Block);
505 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000506 void mangleLambda(const CXXRecordDecl *Lambda);
507 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000508 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +0000509 bool NoFunction=false);
510 void mangleNestedName(const TemplateDecl *TD,
511 const TemplateArgument *TemplateArgs,
512 unsigned NumTemplateArgs);
513 void manglePrefix(NestedNameSpecifier *qualifier);
514 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
515 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000516 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000517 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000518 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
519 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000520 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000521 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
John McCall07daf722016-03-01 22:18:03 +0000522 void mangleVendorQualifier(StringRef qualifier);
Andrew Gozillon572bbb02017-10-02 06:25:51 +0000523 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000524 void mangleRefQualifier(RefQualifierKind RefQualifier);
525
526 void mangleObjCMethodName(const ObjCMethodDecl *MD);
527
528 // Declare manglers for every type class.
529#define ABSTRACT_TYPE(CLASS, PARENT)
530#define NON_CANONICAL_TYPE(CLASS, PARENT)
531#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
532#include "clang/AST/TypeNodes.def"
533
534 void mangleType(const TagType*);
535 void mangleType(TemplateName);
John McCall07daf722016-03-01 22:18:03 +0000536 static StringRef getCallingConvQualifierName(CallingConv CC);
537 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
538 void mangleExtFunctionInfo(const FunctionType *T);
539 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000540 const FunctionDecl *FD = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000541 void mangleNeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000542 void mangleNeonVectorType(const DependentVectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000543 void mangleAArch64NeonVectorType(const VectorType *T);
Erich Keanef702b022018-07-13 19:46:04 +0000544 void mangleAArch64NeonVectorType(const DependentVectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000545
546 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000547 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000548 void mangleMemberExpr(const Expr *base, bool isArrow,
549 NestedNameSpecifier *qualifier,
550 NamedDecl *firstQualifierLookup,
551 DeclarationName name,
Richard Smithafecd832016-10-24 20:47:04 +0000552 const TemplateArgumentLoc *TemplateArgs,
553 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +0000554 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000555 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000556 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000557 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
Richard Smith5179eb72016-06-28 19:03:57 +0000558 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +0000559 void mangleCXXDtorType(CXXDtorType T);
560
James Y Knight04ec5bf2015-12-24 02:59:37 +0000561 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
562 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000563 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
564 unsigned NumTemplateArgs);
565 void mangleTemplateArgs(const TemplateArgumentList &AL);
566 void mangleTemplateArg(TemplateArgument A);
567
568 void mangleTemplateParameter(unsigned Index);
569
570 void mangleFunctionParam(const ParmVarDecl *parm);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000571
572 void writeAbiTags(const NamedDecl *ND,
573 const AbiTagList *AdditionalAbiTags);
574
575 // Returns sorted unique list of ABI tags.
576 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
577 // Returns sorted unique list of ABI tags.
578 AbiTagList makeVariableTypeTags(const VarDecl *VD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000579};
580
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000581}
Guy Benyei11169dd2012-12-18 14:30:41 +0000582
Rafael Espindola002667c2013-10-16 01:40:34 +0000583bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000584 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000585 if (FD) {
586 LanguageLinkage L = FD->getLanguageLinkage();
587 // Overloadable functions need mangling.
588 if (FD->hasAttr<OverloadableAttr>())
589 return true;
590
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000591 // "main" is not mangled.
592 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000593 return false;
594
Martin Storsjo92e26612018-07-16 05:42:25 +0000595 // The Windows ABI expects that we would never mangle "typical"
596 // user-defined entry points regardless of visibility or freestanding-ness.
597 //
598 // N.B. This is distinct from asking about "main". "main" has a lot of
599 // special rules associated with it in the standard while these
600 // user-defined entry points are outside of the purview of the standard.
601 // For example, there can be only one definition for "main" in a standards
602 // compliant program; however nothing forbids the existence of wmain and
603 // WinMain in the same translation unit.
604 if (FD->isMSVCRTEntryPoint())
605 return false;
606
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000607 // C++ functions and those whose names are not a simple identifier need
608 // mangling.
609 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
610 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000611
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000612 // C functions are not mangled.
613 if (L == CLanguageLinkage)
614 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000615 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000616
617 // Otherwise, no mangling is done outside C++ mode.
618 if (!getASTContext().getLangOpts().CPlusPlus)
619 return false;
620
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000621 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithbdb84f32016-07-22 23:36:59 +0000622 if (VD && !isa<DecompositionDecl>(D)) {
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000623 // C variables are not mangled.
624 if (VD->isExternC())
625 return false;
626
627 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000628 const DeclContext *DC = getEffectiveDeclContext(D);
629 // Check for extern variable declared locally.
630 if (DC->isFunctionOrMethod() && D->hasLinkage())
631 while (!DC->isNamespace() && !DC->isTranslationUnit())
632 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000633 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000634 !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
Larisse Voufo39a1e502013-08-06 01:03:05 +0000635 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000636 return false;
637 }
638
Guy Benyei11169dd2012-12-18 14:30:41 +0000639 return true;
640}
641
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000642void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
643 const AbiTagList *AdditionalAbiTags) {
644 assert(AbiTags && "require AbiTagState");
645 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
646}
647
648void CXXNameMangler::mangleSourceNameWithAbiTags(
649 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
650 mangleSourceName(ND->getIdentifier());
651 writeAbiTags(ND, AdditionalAbiTags);
652}
653
David Majnemer7ff7eb72015-02-18 07:47:09 +0000654void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000655 // <mangled-name> ::= _Z <encoding>
656 // ::= <data name>
657 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000658 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000659 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
660 mangleFunctionEncoding(FD);
661 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
662 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000663 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
664 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000665 else
666 mangleName(cast<FieldDecl>(D));
667}
668
669void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
670 // <encoding> ::= <function name> <bare-function-type>
Guy Benyei11169dd2012-12-18 14:30:41 +0000671
672 // Don't mangle in the type if this isn't a decl we should typically mangle.
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000673 if (!Context.shouldMangleDeclName(FD)) {
674 mangleName(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000675 return;
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000676 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000677
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000678 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
679 if (ReturnTypeAbiTags.empty()) {
680 // There are no tags for return type, the simplest case.
681 mangleName(FD);
682 mangleFunctionEncodingBareType(FD);
683 return;
684 }
685
686 // Mangle function name and encoding to temporary buffer.
687 // We have to output name and encoding to the same mangler to get the same
688 // substitution as it will be in final mangling.
689 SmallString<256> FunctionEncodingBuf;
690 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
691 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
692 // Output name of the function.
693 FunctionEncodingMangler.disableDerivedAbiTags();
694 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
695
696 // Remember length of the function name in the buffer.
697 size_t EncodingPositionStart = FunctionEncodingStream.str().size();
698 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
699
700 // Get tags from return type that are not present in function name or
701 // encoding.
702 const AbiTagList &UsedAbiTags =
703 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
704 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
705 AdditionalAbiTags.erase(
706 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
707 UsedAbiTags.begin(), UsedAbiTags.end(),
708 AdditionalAbiTags.begin()),
709 AdditionalAbiTags.end());
710
711 // Output name with implicit tags and function encoding from temporary buffer.
712 mangleNameWithAbiTags(FD, &AdditionalAbiTags);
713 Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
Dmitry Polukhinfda467b2016-09-21 08:27:03 +0000714
715 // Function encoding could create new substitutions so we have to add
716 // temp mangled substitutions to main mangler.
717 extendSubstitutions(&FunctionEncodingMangler);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000718}
719
720void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000721 if (FD->hasAttr<EnableIfAttr>()) {
722 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
723 Out << "Ua9enable_ifI";
Michael Krusedc5ce722018-08-03 01:21:16 +0000724 for (AttrVec::const_iterator I = FD->getAttrs().begin(),
725 E = FD->getAttrs().end();
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000726 I != E; ++I) {
727 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
728 if (!EIA)
729 continue;
730 Out << 'X';
731 mangleExpression(EIA->getCond());
732 Out << 'E';
733 }
734 Out << 'E';
735 FunctionTypeDepth.pop(Saved);
736 }
737
Richard Smith5179eb72016-06-28 19:03:57 +0000738 // When mangling an inheriting constructor, the bare function type used is
739 // that of the inherited constructor.
740 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
741 if (auto Inherited = CD->getInheritedConstructor())
742 FD = Inherited.getConstructor();
743
Guy Benyei11169dd2012-12-18 14:30:41 +0000744 // Whether the mangling of a function type includes the return type depends on
745 // the context and the nature of the function. The rules for deciding whether
746 // the return type is included are:
747 //
748 // 1. Template functions (names or types) have return types encoded, with
749 // the exceptions listed below.
750 // 2. Function types not appearing as part of a function name mangling,
751 // e.g. parameters, pointer types, etc., have return type encoded, with the
752 // exceptions listed below.
753 // 3. Non-template function names do not have return types encoded.
754 //
755 // The exceptions mentioned in (1) and (2) above, for which the return type is
756 // never included, are
757 // 1. Constructors.
758 // 2. Destructors.
759 // 3. Conversion operator functions, e.g. operator int.
760 bool MangleReturnType = false;
761 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
762 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
763 isa<CXXConversionDecl>(FD)))
764 MangleReturnType = true;
765
766 // Mangle the type of the primary template.
767 FD = PrimaryTemplate->getTemplatedDecl();
768 }
769
John McCall07daf722016-03-01 22:18:03 +0000770 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000771 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000772}
773
774static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
775 while (isa<LinkageSpecDecl>(DC)) {
776 DC = getEffectiveParentContext(DC);
777 }
778
779 return DC;
780}
781
Justin Bognere8d762e2015-05-22 06:48:13 +0000782/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000783static bool isStd(const NamespaceDecl *NS) {
784 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
785 ->isTranslationUnit())
786 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000787
Guy Benyei11169dd2012-12-18 14:30:41 +0000788 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
789 return II && II->isStr("std");
790}
791
792// isStdNamespace - Return whether a given decl context is a toplevel 'std'
793// namespace.
794static bool isStdNamespace(const DeclContext *DC) {
795 if (!DC->isNamespace())
796 return false;
797
798 return isStd(cast<NamespaceDecl>(DC));
799}
800
801static const TemplateDecl *
802isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
803 // Check if we have a function template.
Richard Smith5179eb72016-06-28 19:03:57 +0000804 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000805 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
806 TemplateArgs = FD->getTemplateSpecializationArgs();
807 return TD;
808 }
809 }
810
811 // Check if we have a class template.
812 if (const ClassTemplateSpecializationDecl *Spec =
813 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
814 TemplateArgs = &Spec->getTemplateArgs();
815 return Spec->getSpecializedTemplate();
816 }
817
Larisse Voufo39a1e502013-08-06 01:03:05 +0000818 // Check if we have a variable template.
819 if (const VarTemplateSpecializationDecl *Spec =
820 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
821 TemplateArgs = &Spec->getTemplateArgs();
822 return Spec->getSpecializedTemplate();
823 }
824
Craig Topper36250ad2014-05-12 05:36:57 +0000825 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000826}
827
Guy Benyei11169dd2012-12-18 14:30:41 +0000828void CXXNameMangler::mangleName(const NamedDecl *ND) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000829 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
830 // Variables should have implicit tags from its type.
831 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
832 if (VariableTypeAbiTags.empty()) {
833 // Simple case no variable type tags.
834 mangleNameWithAbiTags(VD, nullptr);
835 return;
836 }
837
838 // Mangle variable name to null stream to collect tags.
839 llvm::raw_null_ostream NullOutStream;
840 CXXNameMangler VariableNameMangler(*this, NullOutStream);
841 VariableNameMangler.disableDerivedAbiTags();
842 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
843
844 // Get tags from variable type that are not present in its name.
845 const AbiTagList &UsedAbiTags =
846 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
847 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
848 AdditionalAbiTags.erase(
849 std::set_difference(VariableTypeAbiTags.begin(),
850 VariableTypeAbiTags.end(), UsedAbiTags.begin(),
851 UsedAbiTags.end(), AdditionalAbiTags.begin()),
852 AdditionalAbiTags.end());
853
854 // Output name with implicit tags.
855 mangleNameWithAbiTags(VD, &AdditionalAbiTags);
856 } else {
857 mangleNameWithAbiTags(ND, nullptr);
858 }
859}
860
861void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
862 const AbiTagList *AdditionalAbiTags) {
Richard Smithdd8b5332017-09-04 05:37:53 +0000863 // <name> ::= [<module-name>] <nested-name>
864 // ::= [<module-name>] <unscoped-name>
865 // ::= [<module-name>] <unscoped-template-name> <template-args>
Guy Benyei11169dd2012-12-18 14:30:41 +0000866 // ::= <local-name>
867 //
868 const DeclContext *DC = getEffectiveDeclContext(ND);
869
870 // If this is an extern variable declared locally, the relevant DeclContext
871 // is that of the containing namespace, or the translation unit.
872 // FIXME: This is a hack; extern variables declared locally should have
873 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000874 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000875 while (!DC->isNamespace() && !DC->isTranslationUnit())
876 DC = getEffectiveParentContext(DC);
877 else if (GetLocalClassDecl(ND)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000878 mangleLocalName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000879 return;
880 }
881
882 DC = IgnoreLinkageSpecDecls(DC);
883
Richard Smithdd8b5332017-09-04 05:37:53 +0000884 if (isLocalContainerContext(DC)) {
885 mangleLocalName(ND, AdditionalAbiTags);
886 return;
887 }
888
889 // Do not mangle the owning module for an external linkage declaration.
890 // This enables backwards-compatibility with non-modular code, and is
891 // a valid choice since conflicts are not permitted by C++ Modules TS
892 // [basic.def.odr]/6.2.
893 if (!ND->hasExternalFormalLinkage())
894 if (Module *M = ND->getOwningModuleForLinkage())
895 mangleModuleName(M);
896
Guy Benyei11169dd2012-12-18 14:30:41 +0000897 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
898 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000899 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000900 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000901 mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000902 mangleTemplateArgs(*TemplateArgs);
903 return;
904 }
905
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000906 mangleUnscopedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000907 return;
908 }
909
Richard Smithdd8b5332017-09-04 05:37:53 +0000910 mangleNestedName(ND, DC, AdditionalAbiTags);
911}
912
913void CXXNameMangler::mangleModuleName(const Module *M) {
914 // Implement the C++ Modules TS name mangling proposal; see
915 // https://gcc.gnu.org/wiki/cxx-modules?action=AttachFile
916 //
917 // <module-name> ::= W <unscoped-name>+ E
918 // ::= W <module-subst> <unscoped-name>* E
919 Out << 'W';
920 mangleModuleNamePrefix(M->Name);
921 Out << 'E';
922}
923
924void CXXNameMangler::mangleModuleNamePrefix(StringRef Name) {
925 // <module-subst> ::= _ <seq-id> # 0 < seq-id < 10
926 // ::= W <seq-id - 10> _ # otherwise
927 auto It = ModuleSubstitutions.find(Name);
928 if (It != ModuleSubstitutions.end()) {
929 if (It->second < 10)
930 Out << '_' << static_cast<char>('0' + It->second);
931 else
932 Out << 'W' << (It->second - 10) << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +0000933 return;
934 }
935
Richard Smithdd8b5332017-09-04 05:37:53 +0000936 // FIXME: Preserve hierarchy in module names rather than flattening
937 // them to strings; use Module*s as substitution keys.
938 auto Parts = Name.rsplit('.');
939 if (Parts.second.empty())
940 Parts.second = Parts.first;
941 else
942 mangleModuleNamePrefix(Parts.first);
943
944 Out << Parts.second.size() << Parts.second;
945 ModuleSubstitutions.insert({Name, ModuleSubstitutions.size()});
Guy Benyei11169dd2012-12-18 14:30:41 +0000946}
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000947
948void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
949 const TemplateArgument *TemplateArgs,
950 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000951 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
952
953 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000954 mangleUnscopedTemplateName(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000955 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
956 } else {
957 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
958 }
959}
960
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000961void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
962 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000963 // <unscoped-name> ::= <unqualified-name>
964 // ::= St <unqualified-name> # ::std::
965
966 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
967 Out << "St";
968
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000969 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +0000970}
971
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000972void CXXNameMangler::mangleUnscopedTemplateName(
973 const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 // <unscoped-template-name> ::= <unscoped-name>
975 // ::= <substitution>
976 if (mangleSubstitution(ND))
977 return;
978
979 // <template-template-param> ::= <template-param>
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000980 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
981 assert(!AdditionalAbiTags &&
982 "template template param cannot have abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +0000983 mangleTemplateParameter(TTP->getIndex());
David Majnemer6d2b60a2016-07-12 16:48:17 +0000984 } else if (isa<BuiltinTemplateDecl>(ND)) {
985 mangleUnscopedName(ND, AdditionalAbiTags);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000986 } else {
987 mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
988 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000989
Guy Benyei11169dd2012-12-18 14:30:41 +0000990 addSubstitution(ND);
991}
992
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000993void CXXNameMangler::mangleUnscopedTemplateName(
994 TemplateName Template, const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000995 // <unscoped-template-name> ::= <unscoped-name>
996 // ::= <substitution>
997 if (TemplateDecl *TD = Template.getAsTemplateDecl())
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +0000998 return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
Fangrui Song6907ce22018-07-30 19:24:48 +0000999
Guy Benyei11169dd2012-12-18 14:30:41 +00001000 if (mangleSubstitution(Template))
1001 return;
1002
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001003 assert(!AdditionalAbiTags &&
1004 "dependent template name cannot have abi tags");
1005
Guy Benyei11169dd2012-12-18 14:30:41 +00001006 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1007 assert(Dependent && "Not a dependent template name?");
1008 if (const IdentifierInfo *Id = Dependent->getIdentifier())
1009 mangleSourceName(Id);
1010 else
1011 mangleOperatorName(Dependent->getOperator(), UnknownArity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001012
Guy Benyei11169dd2012-12-18 14:30:41 +00001013 addSubstitution(Template);
1014}
1015
1016void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
1017 // ABI:
1018 // Floating-point literals are encoded using a fixed-length
1019 // lowercase hexadecimal string corresponding to the internal
1020 // representation (IEEE on Itanium), high-order bytes first,
1021 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
1022 // on Itanium.
1023 // The 'without leading zeroes' thing seems to be an editorial
1024 // mistake; see the discussion on cxx-abi-dev beginning on
1025 // 2012-01-16.
1026
1027 // Our requirements here are just barely weird enough to justify
1028 // using a custom algorithm instead of post-processing APInt::toString().
1029
1030 llvm::APInt valueBits = f.bitcastToAPInt();
1031 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
1032 assert(numCharacters != 0);
1033
1034 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +00001035 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +00001036
1037 // Fill the buffer left-to-right.
1038 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
1039 // The bit-index of the next hex digit.
1040 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
1041
1042 // Project out 4 bits starting at 'digitIndex'.
Craig Topperc396c532017-03-30 05:48:58 +00001043 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
1044 hexDigit >>= (digitBitIndex % 64);
Guy Benyei11169dd2012-12-18 14:30:41 +00001045 hexDigit &= 0xF;
1046
1047 // Map that over to a lowercase hex digit.
1048 static const char charForHex[16] = {
1049 '0', '1', '2', '3', '4', '5', '6', '7',
1050 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
1051 };
1052 buffer[stringIndex] = charForHex[hexDigit];
1053 }
1054
1055 Out.write(buffer.data(), numCharacters);
1056}
1057
1058void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
1059 if (Value.isSigned() && Value.isNegative()) {
1060 Out << 'n';
1061 Value.abs().print(Out, /*signed*/ false);
1062 } else {
1063 Value.print(Out, /*signed*/ false);
1064 }
1065}
1066
1067void CXXNameMangler::mangleNumber(int64_t Number) {
1068 // <number> ::= [n] <non-negative decimal integer>
1069 if (Number < 0) {
1070 Out << 'n';
1071 Number = -Number;
1072 }
1073
1074 Out << Number;
1075}
1076
1077void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1078 // <call-offset> ::= h <nv-offset> _
1079 // ::= v <v-offset> _
1080 // <nv-offset> ::= <offset number> # non-virtual base override
1081 // <v-offset> ::= <offset number> _ <virtual offset number>
1082 // # virtual base override, with vcall offset
1083 if (!Virtual) {
1084 Out << 'h';
1085 mangleNumber(NonVirtual);
1086 Out << '_';
1087 return;
1088 }
1089
1090 Out << 'v';
1091 mangleNumber(NonVirtual);
1092 Out << '_';
1093 mangleNumber(Virtual);
1094 Out << '_';
1095}
1096
1097void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +00001098 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001099 if (!mangleSubstitution(QualType(TST, 0))) {
1100 mangleTemplatePrefix(TST->getTemplateName());
Fangrui Song6907ce22018-07-30 19:24:48 +00001101
Guy Benyei11169dd2012-12-18 14:30:41 +00001102 // FIXME: GCC does not appear to mangle the template arguments when
1103 // the template in question is a dependent template name. Should we
1104 // emulate that badness?
1105 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1106 addSubstitution(QualType(TST, 0));
1107 }
David Majnemera88b3592015-02-18 02:28:01 +00001108 } else if (const auto *DTST =
1109 type->getAs<DependentTemplateSpecializationType>()) {
1110 if (!mangleSubstitution(QualType(DTST, 0))) {
1111 TemplateName Template = getASTContext().getDependentTemplateName(
1112 DTST->getQualifier(), DTST->getIdentifier());
1113 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +00001114
David Majnemera88b3592015-02-18 02:28:01 +00001115 // FIXME: GCC does not appear to mangle the template arguments when
1116 // the template in question is a dependent template name. Should we
1117 // emulate that badness?
1118 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1119 addSubstitution(QualType(DTST, 0));
1120 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001121 } else {
1122 // We use the QualType mangle type variant here because it handles
1123 // substitutions.
1124 mangleType(type);
1125 }
1126}
1127
1128/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1129///
Guy Benyei11169dd2012-12-18 14:30:41 +00001130/// \param recursive - true if this is being called recursively,
1131/// i.e. if there is more prefix "to the right".
1132void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +00001133 bool recursive) {
1134
1135 // x, ::x
1136 // <unresolved-name> ::= [gs] <base-unresolved-name>
1137
1138 // T::x / decltype(p)::x
1139 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1140
1141 // T::N::x /decltype(p)::N::x
1142 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1143 // <base-unresolved-name>
1144
1145 // A::x, N::y, A<T>::z; "gs" means leading "::"
1146 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1147 // <base-unresolved-name>
1148
1149 switch (qualifier->getKind()) {
1150 case NestedNameSpecifier::Global:
1151 Out << "gs";
1152
1153 // We want an 'sr' unless this is the entire NNS.
1154 if (recursive)
1155 Out << "sr";
1156
1157 // We never want an 'E' here.
1158 return;
1159
Nikola Smiljanic67860242014-09-26 00:28:20 +00001160 case NestedNameSpecifier::Super:
1161 llvm_unreachable("Can't mangle __super specifier");
1162
Guy Benyei11169dd2012-12-18 14:30:41 +00001163 case NestedNameSpecifier::Namespace:
1164 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001165 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001166 /*recursive*/ true);
1167 else
1168 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001169 mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
Guy Benyei11169dd2012-12-18 14:30:41 +00001170 break;
1171 case NestedNameSpecifier::NamespaceAlias:
1172 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +00001173 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001174 /*recursive*/ true);
1175 else
1176 Out << "sr";
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001177 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
Guy Benyei11169dd2012-12-18 14:30:41 +00001178 break;
1179
1180 case NestedNameSpecifier::TypeSpec:
1181 case NestedNameSpecifier::TypeSpecWithTemplate: {
1182 const Type *type = qualifier->getAsType();
1183
1184 // We only want to use an unresolved-type encoding if this is one of:
1185 // - a decltype
1186 // - a template type parameter
1187 // - a template template parameter with arguments
1188 // In all of these cases, we should have no prefix.
1189 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001190 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001191 /*recursive*/ true);
1192 } else {
1193 // Otherwise, all the cases want this.
1194 Out << "sr";
1195 }
1196
David Majnemerb8014dd2015-02-19 02:16:16 +00001197 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +00001198 return;
1199
Guy Benyei11169dd2012-12-18 14:30:41 +00001200 break;
1201 }
1202
1203 case NestedNameSpecifier::Identifier:
1204 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +00001205 if (qualifier->getPrefix())
1206 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001207 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +00001208 else
Guy Benyei11169dd2012-12-18 14:30:41 +00001209 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +00001210
1211 mangleSourceName(qualifier->getAsIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001212 // An Identifier has no type information, so we can't emit abi tags for it.
Guy Benyei11169dd2012-12-18 14:30:41 +00001213 break;
1214 }
1215
1216 // If this was the innermost part of the NNS, and we fell out to
1217 // here, append an 'E'.
1218 if (!recursive)
1219 Out << 'E';
1220}
1221
1222/// Mangle an unresolved-name, which is generally used for names which
1223/// weren't resolved to specific entities.
Richard Smithafecd832016-10-24 20:47:04 +00001224void CXXNameMangler::mangleUnresolvedName(
1225 NestedNameSpecifier *qualifier, DeclarationName name,
1226 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
1227 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +00001228 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001229 switch (name.getNameKind()) {
1230 // <base-unresolved-name> ::= <simple-id>
1231 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +00001232 mangleSourceName(name.getAsIdentifierInfo());
1233 break;
1234 // <base-unresolved-name> ::= dn <destructor-name>
1235 case DeclarationName::CXXDestructorName:
1236 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +00001237 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +00001238 break;
1239 // <base-unresolved-name> ::= on <operator-name>
1240 case DeclarationName::CXXConversionFunctionName:
1241 case DeclarationName::CXXLiteralOperatorName:
1242 case DeclarationName::CXXOperatorName:
1243 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +00001244 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001245 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +00001246 case DeclarationName::CXXConstructorName:
1247 llvm_unreachable("Can't mangle a constructor name!");
1248 case DeclarationName::CXXUsingDirective:
1249 llvm_unreachable("Can't mangle a using directive name!");
Richard Smith35845152017-02-07 01:37:30 +00001250 case DeclarationName::CXXDeductionGuideName:
1251 llvm_unreachable("Can't mangle a deduction guide name!");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001252 case DeclarationName::ObjCMultiArgSelector:
1253 case DeclarationName::ObjCOneArgSelector:
1254 case DeclarationName::ObjCZeroArgSelector:
1255 llvm_unreachable("Can't mangle Objective-C selector names here!");
1256 }
Richard Smithafecd832016-10-24 20:47:04 +00001257
1258 // The <simple-id> and on <operator-name> productions end in an optional
1259 // <template-args>.
1260 if (TemplateArgs)
1261 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00001262}
1263
Guy Benyei11169dd2012-12-18 14:30:41 +00001264void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1265 DeclarationName Name,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001266 unsigned KnownArity,
1267 const AbiTagList *AdditionalAbiTags) {
David Majnemera88b3592015-02-18 02:28:01 +00001268 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +00001269 // <unqualified-name> ::= <operator-name>
1270 // ::= <ctor-dtor-name>
1271 // ::= <source-name>
1272 switch (Name.getNameKind()) {
1273 case DeclarationName::Identifier: {
Richard Smithbdb84f32016-07-22 23:36:59 +00001274 const IdentifierInfo *II = Name.getAsIdentifierInfo();
1275
Richard Smithda383632016-08-15 01:33:41 +00001276 // We mangle decomposition declarations as the names of their bindings.
Richard Smithbdb84f32016-07-22 23:36:59 +00001277 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
Richard Smithda383632016-08-15 01:33:41 +00001278 // FIXME: Non-standard mangling for decomposition declarations:
1279 //
1280 // <unqualified-name> ::= DC <source-name>* E
1281 //
1282 // These can never be referenced across translation units, so we do
1283 // not need a cross-vendor mangling for anything other than demanglers.
1284 // Proposed on cxx-abi-dev on 2016-08-12
1285 Out << "DC";
1286 for (auto *BD : DD->bindings())
1287 mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
1288 Out << 'E';
1289 writeAbiTags(ND, AdditionalAbiTags);
1290 break;
Richard Smithbdb84f32016-07-22 23:36:59 +00001291 }
1292
1293 if (II) {
Richard Smithdd8b5332017-09-04 05:37:53 +00001294 // Match GCC's naming convention for internal linkage symbols, for
1295 // symbols that are not actually visible outside of this TU. GCC
1296 // distinguishes between internal and external linkage symbols in
1297 // its mangling, to support cases like this that were valid C++ prior
1298 // to DR426:
1299 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001300 // void test() { extern void foo(); }
1301 // static void foo();
Richard Smithdf963a32017-09-22 22:21:44 +00001302 //
1303 // Don't bother with the L marker for names in anonymous namespaces; the
1304 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
1305 // matches GCC anyway, because GCC does not treat anonymous namespaces as
1306 // implying internal linkage.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001307 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Richard Smithdd8b5332017-09-04 05:37:53 +00001308 !ND->isExternallyVisible() &&
Richard Smithdf963a32017-09-22 22:21:44 +00001309 getEffectiveDeclContext(ND)->isFileContext() &&
1310 !ND->isInAnonymousNamespace())
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 Out << 'L';
1312
Erich Keane757d3172016-11-02 18:29:35 +00001313 auto *FD = dyn_cast<FunctionDecl>(ND);
1314 bool IsRegCall = FD &&
1315 FD->getType()->castAs<FunctionType>()->getCallConv() ==
1316 clang::CC_X86RegCall;
1317 if (IsRegCall)
1318 mangleRegCallName(II);
1319 else
1320 mangleSourceName(II);
1321
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001322 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001323 break;
1324 }
1325
1326 // Otherwise, an anonymous entity. We must have a declaration.
1327 assert(ND && "mangling empty name without declaration");
1328
1329 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1330 if (NS->isAnonymousNamespace()) {
1331 // This is how gcc mangles these names.
1332 Out << "12_GLOBAL__N_1";
1333 break;
1334 }
1335 }
1336
1337 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1338 // We must have an anonymous union or struct declaration.
George Burgess IV00f70bd2018-03-01 05:43:23 +00001339 const RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001340
Guy Benyei11169dd2012-12-18 14:30:41 +00001341 // Itanium C++ ABI 5.1.2:
1342 //
1343 // For the purposes of mangling, the name of an anonymous union is
1344 // considered to be the name of the first named data member found by a
1345 // pre-order, depth-first, declaration-order walk of the data members of
1346 // the anonymous union. If there is no such data member (i.e., if all of
1347 // the data members in the union are unnamed), then there is no way for
1348 // a program to refer to the anonymous union, and there is therefore no
1349 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001350 assert(RD->isAnonymousStructOrUnion()
1351 && "Expected anonymous struct or union!");
1352 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +00001353
1354 // It's actually possible for various reasons for us to get here
1355 // with an empty anonymous struct / union. Fortunately, it
1356 // doesn't really matter what name we generate.
1357 if (!FD) break;
1358 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001359
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 mangleSourceName(FD->getIdentifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001361 // Not emitting abi tags: internal name anyway.
Guy Benyei11169dd2012-12-18 14:30:41 +00001362 break;
1363 }
John McCall924046f2013-04-10 06:08:21 +00001364
1365 // Class extensions have no name as a category, and it's possible
1366 // for them to be the semantic parent of certain declarations
1367 // (primarily, tag decls defined within declarations). Such
1368 // declarations will always have internal linkage, so the name
1369 // doesn't really matter, but we shouldn't crash on them. For
1370 // safety, just handle all ObjC containers here.
1371 if (isa<ObjCContainerDecl>(ND))
1372 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00001373
Guy Benyei11169dd2012-12-18 14:30:41 +00001374 // We must have an anonymous struct.
1375 const TagDecl *TD = cast<TagDecl>(ND);
1376 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1377 assert(TD->getDeclContext() == D->getDeclContext() &&
1378 "Typedef should not be in another decl context!");
1379 assert(D->getDeclName().getAsIdentifierInfo() &&
1380 "Typedef was not named!");
1381 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001382 assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1383 // Explicit abi tags are still possible; take from underlying type, not
1384 // from typedef.
1385 writeAbiTags(TD, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 break;
1387 }
1388
1389 // <unnamed-type-name> ::= <closure-type-name>
Fangrui Song6907ce22018-07-30 19:24:48 +00001390 //
Guy Benyei11169dd2012-12-18 14:30:41 +00001391 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1392 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1393 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1394 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001395 assert(!AdditionalAbiTags &&
1396 "Lambda type cannot have additional abi tags");
Guy Benyei11169dd2012-12-18 14:30:41 +00001397 mangleLambda(Record);
1398 break;
1399 }
1400 }
1401
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001402 if (TD->isExternallyVisible()) {
1403 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001404 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001405 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001406 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001407 Out << '_';
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001408 writeAbiTags(TD, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001409 break;
1410 }
1411
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001412 // Get a unique id for the anonymous struct. If it is not a real output
1413 // ID doesn't matter so use fake one.
1414 unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001415
1416 // Mangle it as a source name in the form
1417 // [n] $_<id>
1418 // where n is the length of the string.
1419 SmallString<8> Str;
1420 Str += "$_";
1421 Str += llvm::utostr(AnonStructId);
1422
1423 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001424 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001425 break;
1426 }
1427
1428 case DeclarationName::ObjCZeroArgSelector:
1429 case DeclarationName::ObjCOneArgSelector:
1430 case DeclarationName::ObjCMultiArgSelector:
1431 llvm_unreachable("Can't mangle Objective-C selector names here!");
1432
Richard Smith5179eb72016-06-28 19:03:57 +00001433 case DeclarationName::CXXConstructorName: {
1434 const CXXRecordDecl *InheritedFrom = nullptr;
1435 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1436 if (auto Inherited =
1437 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1438 InheritedFrom = Inherited.getConstructor()->getParent();
1439 InheritedTemplateArgs =
1440 Inherited.getConstructor()->getTemplateSpecializationArgs();
1441 }
1442
Guy Benyei11169dd2012-12-18 14:30:41 +00001443 if (ND == Structor)
1444 // If the named decl is the C++ constructor we're mangling, use the type
1445 // we were given.
Richard Smith5179eb72016-06-28 19:03:57 +00001446 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00001447 else
1448 // Otherwise, use the complete constructor name. This is relevant if a
1449 // class with a constructor is declared within a constructor.
Richard Smith5179eb72016-06-28 19:03:57 +00001450 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1451
1452 // FIXME: The template arguments are part of the enclosing prefix or
1453 // nested-name, but it's more convenient to mangle them here.
1454 if (InheritedTemplateArgs)
1455 mangleTemplateArgs(*InheritedTemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001456
1457 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001458 break;
Richard Smith5179eb72016-06-28 19:03:57 +00001459 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001460
1461 case DeclarationName::CXXDestructorName:
1462 if (ND == Structor)
1463 // If the named decl is the C++ destructor we're mangling, use the type we
1464 // were given.
1465 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1466 else
1467 // Otherwise, use the complete destructor name. This is relevant if a
1468 // class with a destructor is declared within a destructor.
1469 mangleCXXDtorType(Dtor_Complete);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001470 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001471 break;
1472
David Majnemera88b3592015-02-18 02:28:01 +00001473 case DeclarationName::CXXOperatorName:
1474 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001475 Arity = cast<FunctionDecl>(ND)->getNumParams();
1476
David Majnemera88b3592015-02-18 02:28:01 +00001477 // If we have a member function, we need to include the 'this' pointer.
1478 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1479 if (!MD->isStatic())
1480 Arity++;
1481 }
Adrian Prantlf3b3ccd2017-12-19 22:06:11 +00001482 LLVM_FALLTHROUGH;
David Majnemera88b3592015-02-18 02:28:01 +00001483 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001484 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001485 mangleOperatorName(Name, Arity);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001486 writeAbiTags(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001487 break;
1488
Richard Smith35845152017-02-07 01:37:30 +00001489 case DeclarationName::CXXDeductionGuideName:
1490 llvm_unreachable("Can't mangle a deduction guide name!");
1491
Guy Benyei11169dd2012-12-18 14:30:41 +00001492 case DeclarationName::CXXUsingDirective:
1493 llvm_unreachable("Can't mangle a using directive name!");
1494 }
1495}
1496
Erich Keane757d3172016-11-02 18:29:35 +00001497void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
1498 // <source-name> ::= <positive length number> __regcall3__ <identifier>
1499 // <number> ::= [n] <non-negative decimal integer>
1500 // <identifier> ::= <unqualified source code identifier>
1501 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
1502 << II->getName();
1503}
1504
Guy Benyei11169dd2012-12-18 14:30:41 +00001505void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1506 // <source-name> ::= <positive length number> <identifier>
1507 // <number> ::= [n] <non-negative decimal integer>
1508 // <identifier> ::= <unqualified source code identifier>
1509 Out << II->getLength() << II->getName();
1510}
1511
1512void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1513 const DeclContext *DC,
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001514 const AbiTagList *AdditionalAbiTags,
Guy Benyei11169dd2012-12-18 14:30:41 +00001515 bool NoFunction) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001516 // <nested-name>
Guy Benyei11169dd2012-12-18 14:30:41 +00001517 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
Fangrui Song6907ce22018-07-30 19:24:48 +00001518 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
Guy Benyei11169dd2012-12-18 14:30:41 +00001519 // <template-args> E
1520
1521 Out << 'N';
1522 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001523 Qualifiers MethodQuals =
Roger Ferrer Ibanezcb895132017-04-19 12:23:28 +00001524 Qualifiers::fromCVRUMask(Method->getTypeQualifiers());
David Majnemer42350df2013-11-03 23:51:28 +00001525 // We do not consider restrict a distinguishing attribute for overloading
1526 // purposes so we must not mangle it.
1527 MethodQuals.removeRestrict();
1528 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 mangleRefQualifier(Method->getRefQualifier());
1530 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001531
Guy Benyei11169dd2012-12-18 14:30:41 +00001532 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001533 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001534 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001535 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001536 mangleTemplateArgs(*TemplateArgs);
1537 }
1538 else {
1539 manglePrefix(DC, NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001540 mangleUnqualifiedName(ND, AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001541 }
1542
1543 Out << 'E';
1544}
1545void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1546 const TemplateArgument *TemplateArgs,
1547 unsigned NumTemplateArgs) {
1548 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1549
1550 Out << 'N';
1551
1552 mangleTemplatePrefix(TD);
1553 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1554
1555 Out << 'E';
1556}
1557
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001558void CXXNameMangler::mangleLocalName(const Decl *D,
1559 const AbiTagList *AdditionalAbiTags) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001560 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1561 // := Z <function encoding> E s [<discriminator>]
Fangrui Song6907ce22018-07-30 19:24:48 +00001562 // <local-name> := Z <function encoding> E d [ <parameter number> ]
Guy Benyei11169dd2012-12-18 14:30:41 +00001563 // _ <entity name>
1564 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001565 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001566 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001567 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001568
1569 Out << 'Z';
1570
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001571 {
1572 AbiTagState LocalAbiTags(AbiTags);
1573
1574 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1575 mangleObjCMethodName(MD);
1576 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1577 mangleBlockForPrefix(BD);
1578 else
1579 mangleFunctionEncoding(cast<FunctionDecl>(DC));
1580
1581 // Implicit ABI tags (from namespace) are not available in the following
1582 // entity; reset to actually emitted tags, which are available.
1583 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1584 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001585
Eli Friedman92821742013-07-02 02:01:18 +00001586 Out << 'E';
1587
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001588 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1589 // be a bug that is fixed in trunk.
1590
Eli Friedman92821742013-07-02 02:01:18 +00001591 if (RD) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001592 // The parameter number is omitted for the last parameter, 0 for the
1593 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1594 // <entity name> will of course contain a <closure-type-name>: Its
Guy Benyei11169dd2012-12-18 14:30:41 +00001595 // numbering will be local to the particular argument in which it appears
1596 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001597 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithcb2ba5a2016-07-18 22:37:35 +00001598 if (CXXRD && CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001599 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001600 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 if (const FunctionDecl *Func
1602 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1603 Out << 'd';
1604 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1605 if (Num > 1)
1606 mangleNumber(Num - 2);
1607 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001608 }
1609 }
1610 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001611
Guy Benyei11169dd2012-12-18 14:30:41 +00001612 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001613 // equality ok because RD derived from ND above
1614 if (D == RD) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001615 mangleUnqualifiedName(RD, AdditionalAbiTags);
Eli Friedman95f50122013-07-02 17:52:28 +00001616 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1617 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001618 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman95f50122013-07-02 17:52:28 +00001619 mangleUnqualifiedBlock(BD);
1620 } else {
1621 const NamedDecl *ND = cast<NamedDecl>(D);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001622 mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1623 true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001624 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001625 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1626 // Mangle a block in a default parameter; see above explanation for
1627 // lambdas.
1628 if (const ParmVarDecl *Parm
1629 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1630 if (const FunctionDecl *Func
1631 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1632 Out << 'd';
1633 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1634 if (Num > 1)
1635 mangleNumber(Num - 2);
1636 Out << '_';
1637 }
1638 }
1639
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001640 assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
Eli Friedman0cd23352013-07-10 01:33:19 +00001641 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001642 } else {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001643 mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
Guy Benyei11169dd2012-12-18 14:30:41 +00001644 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001645
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001646 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1647 unsigned disc;
1648 if (Context.getNextDiscriminator(ND, disc)) {
1649 if (disc < 10)
1650 Out << '_' << disc;
1651 else
1652 Out << "__" << disc << '_';
1653 }
1654 }
Eli Friedman95f50122013-07-02 17:52:28 +00001655}
1656
1657void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1658 if (GetLocalClassDecl(Block)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001659 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001660 return;
1661 }
1662 const DeclContext *DC = getEffectiveDeclContext(Block);
1663 if (isLocalContainerContext(DC)) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001664 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
Eli Friedman95f50122013-07-02 17:52:28 +00001665 return;
1666 }
1667 manglePrefix(getEffectiveDeclContext(Block));
1668 mangleUnqualifiedBlock(Block);
1669}
1670
1671void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1672 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1673 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1674 Context->getDeclContext()->isRecord()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001675 const auto *ND = cast<NamedDecl>(Context);
1676 if (ND->getIdentifier()) {
1677 mangleSourceNameWithAbiTags(ND);
1678 Out << 'M';
Eli Friedman95f50122013-07-02 17:52:28 +00001679 }
1680 }
1681 }
1682
1683 // If we have a block mangling number, use it.
1684 unsigned Number = Block->getBlockManglingNumber();
1685 // Otherwise, just make up a number. It doesn't matter what it is because
1686 // the symbol in question isn't externally visible.
1687 if (!Number)
1688 Number = Context.getBlockId(Block, false);
Richard Smith48b35d92017-09-07 05:41:24 +00001689 else {
1690 // Stored mangling numbers are 1-based.
1691 --Number;
1692 }
Eli Friedman95f50122013-07-02 17:52:28 +00001693 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001694 if (Number > 0)
1695 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001696 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001697}
1698
1699void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001700 // If the context of a closure type is an initializer for a class member
1701 // (static or nonstatic), it is encoded in a qualified name with a final
Guy Benyei11169dd2012-12-18 14:30:41 +00001702 // <prefix> of the form:
1703 //
1704 // <data-member-prefix> := <member source-name> M
1705 //
1706 // Technically, the data-member-prefix is part of the <prefix>. However,
1707 // since a closure type will always be mangled with a prefix, it's easier
1708 // to emit that last part of the prefix here.
1709 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1710 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
Richard Smithc95d2c52017-09-22 04:25:05 +00001711 !isa<ParmVarDecl>(Context)) {
1712 // FIXME: 'inline auto [a, b] = []{ return ... };' does not get a
1713 // reasonable mangling here.
Guy Benyei11169dd2012-12-18 14:30:41 +00001714 if (const IdentifierInfo *Name
1715 = cast<NamedDecl>(Context)->getIdentifier()) {
1716 mangleSourceName(Name);
Richard Smithc95d2c52017-09-22 04:25:05 +00001717 const TemplateArgumentList *TemplateArgs = nullptr;
Simon Pilgrimb2eda762017-09-22 16:26:17 +00001718 if (isTemplate(cast<NamedDecl>(Context), TemplateArgs))
Richard Smithc95d2c52017-09-22 04:25:05 +00001719 mangleTemplateArgs(*TemplateArgs);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001720 Out << 'M';
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 }
1722 }
1723 }
1724
1725 Out << "Ul";
1726 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1727 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001728 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1729 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001730 Out << "E";
Fangrui Song6907ce22018-07-30 19:24:48 +00001731
1732 // The number is omitted for the first closure type with a given
1733 // <lambda-sig> in a given context; it is n-2 for the nth closure type
Guy Benyei11169dd2012-12-18 14:30:41 +00001734 // (in lexical order) with that same <lambda-sig> and context.
1735 //
1736 // The AST keeps track of the number for us.
1737 unsigned Number = Lambda->getLambdaManglingNumber();
1738 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1739 if (Number > 1)
1740 mangleNumber(Number - 2);
Fangrui Song6907ce22018-07-30 19:24:48 +00001741 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001742}
1743
1744void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1745 switch (qualifier->getKind()) {
1746 case NestedNameSpecifier::Global:
1747 // nothing
1748 return;
1749
Nikola Smiljanic67860242014-09-26 00:28:20 +00001750 case NestedNameSpecifier::Super:
1751 llvm_unreachable("Can't mangle __super specifier");
1752
Guy Benyei11169dd2012-12-18 14:30:41 +00001753 case NestedNameSpecifier::Namespace:
1754 mangleName(qualifier->getAsNamespace());
1755 return;
1756
1757 case NestedNameSpecifier::NamespaceAlias:
1758 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1759 return;
1760
1761 case NestedNameSpecifier::TypeSpec:
1762 case NestedNameSpecifier::TypeSpecWithTemplate:
1763 manglePrefix(QualType(qualifier->getAsType(), 0));
1764 return;
1765
1766 case NestedNameSpecifier::Identifier:
1767 // Member expressions can have these without prefixes, but that
1768 // should end up in mangleUnresolvedPrefix instead.
1769 assert(qualifier->getPrefix());
1770 manglePrefix(qualifier->getPrefix());
1771
1772 mangleSourceName(qualifier->getAsIdentifier());
1773 return;
1774 }
1775
1776 llvm_unreachable("unexpected nested name specifier");
1777}
1778
1779void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1780 // <prefix> ::= <prefix> <unqualified-name>
1781 // ::= <template-prefix> <template-args>
1782 // ::= <template-param>
1783 // ::= # empty
1784 // ::= <substitution>
1785
1786 DC = IgnoreLinkageSpecDecls(DC);
1787
1788 if (DC->isTranslationUnit())
1789 return;
1790
Eli Friedman95f50122013-07-02 17:52:28 +00001791 if (NoFunction && isLocalContainerContext(DC))
1792 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001793
Eli Friedman95f50122013-07-02 17:52:28 +00001794 assert(!isLocalContainerContext(DC));
1795
Fangrui Song6907ce22018-07-30 19:24:48 +00001796 const NamedDecl *ND = cast<NamedDecl>(DC);
Guy Benyei11169dd2012-12-18 14:30:41 +00001797 if (mangleSubstitution(ND))
1798 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001799
Guy Benyei11169dd2012-12-18 14:30:41 +00001800 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001801 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001802 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1803 mangleTemplatePrefix(TD);
1804 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001805 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001806 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001807 mangleUnqualifiedName(ND, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001808 }
1809
1810 addSubstitution(ND);
1811}
1812
1813void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1814 // <template-prefix> ::= <prefix> <template unqualified-name>
1815 // ::= <template-param>
1816 // ::= <substitution>
1817 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1818 return mangleTemplatePrefix(TD);
1819
1820 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1821 manglePrefix(Qualified->getQualifier());
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001822
Guy Benyei11169dd2012-12-18 14:30:41 +00001823 if (OverloadedTemplateStorage *Overloaded
1824 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001825 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001826 UnknownArity, nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001827 return;
1828 }
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001829
Guy Benyei11169dd2012-12-18 14:30:41 +00001830 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1831 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001832 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1833 manglePrefix(Qualifier);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001834 mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001835}
1836
Eli Friedman86af13f02013-07-05 18:41:30 +00001837void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1838 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001839 // <template-prefix> ::= <prefix> <template unqualified-name>
1840 // ::= <template-param>
1841 // ::= <substitution>
1842 // <template-template-param> ::= <template-param>
1843 // <substitution>
1844
1845 if (mangleSubstitution(ND))
1846 return;
1847
1848 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001849 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001850 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001851 } else {
1852 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
David Majnemer6d2b60a2016-07-12 16:48:17 +00001853 if (isa<BuiltinTemplateDecl>(ND))
1854 mangleUnqualifiedName(ND, nullptr);
1855 else
1856 mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001857 }
1858
Guy Benyei11169dd2012-12-18 14:30:41 +00001859 addSubstitution(ND);
1860}
1861
1862/// Mangles a template name under the production <type>. Required for
1863/// template template arguments.
1864/// <type> ::= <class-enum-type>
1865/// ::= <template-param>
1866/// ::= <substitution>
1867void CXXNameMangler::mangleType(TemplateName TN) {
1868 if (mangleSubstitution(TN))
1869 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001870
1871 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001872
1873 switch (TN.getKind()) {
1874 case TemplateName::QualifiedTemplate:
1875 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1876 goto HaveDecl;
1877
1878 case TemplateName::Template:
1879 TD = TN.getAsTemplateDecl();
1880 goto HaveDecl;
1881
1882 HaveDecl:
1883 if (isa<TemplateTemplateParmDecl>(TD))
1884 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1885 else
1886 mangleName(TD);
1887 break;
1888
1889 case TemplateName::OverloadedTemplate:
1890 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1891
1892 case TemplateName::DependentTemplate: {
1893 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1894 assert(Dependent->isIdentifier());
1895
1896 // <class-enum-type> ::= <name>
1897 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001898 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001899 mangleSourceName(Dependent->getIdentifier());
1900 break;
1901 }
1902
1903 case TemplateName::SubstTemplateTemplateParm: {
1904 // Substituted template parameters are mangled as the substituted
1905 // template. This will check for the substitution twice, which is
1906 // fine, but we have to return early so that we don't try to *add*
1907 // the substitution twice.
1908 SubstTemplateTemplateParmStorage *subst
1909 = TN.getAsSubstTemplateTemplateParm();
1910 mangleType(subst->getReplacement());
1911 return;
1912 }
1913
1914 case TemplateName::SubstTemplateTemplateParmPack: {
1915 // FIXME: not clear how to mangle this!
1916 // template <template <class> class T...> class A {
1917 // template <template <class> class U...> void foo(B<T,U> x...);
1918 // };
1919 Out << "_SUBSTPACK_";
1920 break;
1921 }
1922 }
1923
1924 addSubstitution(TN);
1925}
1926
David Majnemerb8014dd2015-02-19 02:16:16 +00001927bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1928 StringRef Prefix) {
1929 // Only certain other types are valid as prefixes; enumerate them.
1930 switch (Ty->getTypeClass()) {
1931 case Type::Builtin:
1932 case Type::Complex:
1933 case Type::Adjusted:
1934 case Type::Decayed:
1935 case Type::Pointer:
1936 case Type::BlockPointer:
1937 case Type::LValueReference:
1938 case Type::RValueReference:
1939 case Type::MemberPointer:
1940 case Type::ConstantArray:
1941 case Type::IncompleteArray:
1942 case Type::VariableArray:
1943 case Type::DependentSizedArray:
Andrew Gozillon572bbb02017-10-02 06:25:51 +00001944 case Type::DependentAddressSpace:
Erich Keanef702b022018-07-13 19:46:04 +00001945 case Type::DependentVector:
David Majnemerb8014dd2015-02-19 02:16:16 +00001946 case Type::DependentSizedExtVector:
1947 case Type::Vector:
1948 case Type::ExtVector:
1949 case Type::FunctionProto:
1950 case Type::FunctionNoProto:
1951 case Type::Paren:
1952 case Type::Attributed:
1953 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00001954 case Type::DeducedTemplateSpecialization:
David Majnemerb8014dd2015-02-19 02:16:16 +00001955 case Type::PackExpansion:
1956 case Type::ObjCObject:
1957 case Type::ObjCInterface:
1958 case Type::ObjCObjectPointer:
Manman Rene6be26c2016-09-13 17:25:08 +00001959 case Type::ObjCTypeParam:
David Majnemerb8014dd2015-02-19 02:16:16 +00001960 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001961 case Type::Pipe:
David Majnemerb8014dd2015-02-19 02:16:16 +00001962 llvm_unreachable("type is illegal as a nested name specifier");
1963
1964 case Type::SubstTemplateTypeParmPack:
1965 // FIXME: not clear how to mangle this!
1966 // template <class T...> class A {
1967 // template <class U...> void foo(decltype(T::foo(U())) x...);
1968 // };
1969 Out << "_SUBSTPACK_";
1970 break;
1971
1972 // <unresolved-type> ::= <template-param>
1973 // ::= <decltype>
1974 // ::= <template-template-param> <template-args>
1975 // (this last is not official yet)
1976 case Type::TypeOfExpr:
1977 case Type::TypeOf:
1978 case Type::Decltype:
1979 case Type::TemplateTypeParm:
1980 case Type::UnaryTransform:
1981 case Type::SubstTemplateTypeParm:
1982 unresolvedType:
1983 // Some callers want a prefix before the mangled type.
1984 Out << Prefix;
1985
1986 // This seems to do everything we want. It's not really
1987 // sanctioned for a substituted template parameter, though.
1988 mangleType(Ty);
1989
1990 // We never want to print 'E' directly after an unresolved-type,
1991 // so we return directly.
1992 return true;
1993
1994 case Type::Typedef:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001995 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00001996 break;
1997
1998 case Type::UnresolvedUsing:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00001999 mangleSourceNameWithAbiTags(
2000 cast<UnresolvedUsingType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002001 break;
2002
2003 case Type::Enum:
2004 case Type::Record:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002005 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002006 break;
2007
2008 case Type::TemplateSpecialization: {
2009 const TemplateSpecializationType *TST =
2010 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00002011 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00002012 switch (TN.getKind()) {
2013 case TemplateName::Template:
2014 case TemplateName::QualifiedTemplate: {
2015 TemplateDecl *TD = TN.getAsTemplateDecl();
2016
2017 // If the base is a template template parameter, this is an
2018 // unresolved type.
2019 assert(TD && "no template for template specialization type");
2020 if (isa<TemplateTemplateParmDecl>(TD))
2021 goto unresolvedType;
2022
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002023 mangleSourceNameWithAbiTags(TD);
David Majnemerb8014dd2015-02-19 02:16:16 +00002024 break;
David Majnemera88b3592015-02-18 02:28:01 +00002025 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002026
2027 case TemplateName::OverloadedTemplate:
2028 case TemplateName::DependentTemplate:
2029 llvm_unreachable("invalid base for a template specialization type");
2030
2031 case TemplateName::SubstTemplateTemplateParm: {
2032 SubstTemplateTemplateParmStorage *subst =
2033 TN.getAsSubstTemplateTemplateParm();
2034 mangleExistingSubstitution(subst->getReplacement());
2035 break;
2036 }
2037
2038 case TemplateName::SubstTemplateTemplateParmPack: {
2039 // FIXME: not clear how to mangle this!
2040 // template <template <class U> class T...> class A {
2041 // template <class U...> void foo(decltype(T<U>::foo) x...);
2042 // };
2043 Out << "_SUBSTPACK_";
2044 break;
2045 }
2046 }
2047
David Majnemera88b3592015-02-18 02:28:01 +00002048 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00002049 break;
David Majnemera88b3592015-02-18 02:28:01 +00002050 }
David Majnemerb8014dd2015-02-19 02:16:16 +00002051
2052 case Type::InjectedClassName:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002053 mangleSourceNameWithAbiTags(
2054 cast<InjectedClassNameType>(Ty)->getDecl());
David Majnemerb8014dd2015-02-19 02:16:16 +00002055 break;
2056
2057 case Type::DependentName:
2058 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
2059 break;
2060
2061 case Type::DependentTemplateSpecialization: {
2062 const DependentTemplateSpecializationType *DTST =
2063 cast<DependentTemplateSpecializationType>(Ty);
2064 mangleSourceName(DTST->getIdentifier());
2065 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
2066 break;
2067 }
2068
2069 case Type::Elaborated:
2070 return mangleUnresolvedTypeOrSimpleId(
2071 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
2072 }
2073
2074 return false;
David Majnemera88b3592015-02-18 02:28:01 +00002075}
2076
2077void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
2078 switch (Name.getNameKind()) {
2079 case DeclarationName::CXXConstructorName:
2080 case DeclarationName::CXXDestructorName:
Richard Smith35845152017-02-07 01:37:30 +00002081 case DeclarationName::CXXDeductionGuideName:
David Majnemera88b3592015-02-18 02:28:01 +00002082 case DeclarationName::CXXUsingDirective:
2083 case DeclarationName::Identifier:
2084 case DeclarationName::ObjCMultiArgSelector:
2085 case DeclarationName::ObjCOneArgSelector:
2086 case DeclarationName::ObjCZeroArgSelector:
2087 llvm_unreachable("Not an operator name");
2088
2089 case DeclarationName::CXXConversionFunctionName:
2090 // <operator-name> ::= cv <type> # (cast)
2091 Out << "cv";
2092 mangleType(Name.getCXXNameType());
2093 break;
2094
2095 case DeclarationName::CXXLiteralOperatorName:
2096 Out << "li";
2097 mangleSourceName(Name.getCXXLiteralIdentifier());
2098 return;
2099
2100 case DeclarationName::CXXOperatorName:
2101 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
2102 break;
2103 }
2104}
2105
Guy Benyei11169dd2012-12-18 14:30:41 +00002106void
2107CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
2108 switch (OO) {
2109 // <operator-name> ::= nw # new
2110 case OO_New: Out << "nw"; break;
2111 // ::= na # new[]
2112 case OO_Array_New: Out << "na"; break;
2113 // ::= dl # delete
2114 case OO_Delete: Out << "dl"; break;
2115 // ::= da # delete[]
2116 case OO_Array_Delete: Out << "da"; break;
2117 // ::= ps # + (unary)
2118 // ::= pl # + (binary or unknown)
2119 case OO_Plus:
2120 Out << (Arity == 1? "ps" : "pl"); break;
2121 // ::= ng # - (unary)
2122 // ::= mi # - (binary or unknown)
2123 case OO_Minus:
2124 Out << (Arity == 1? "ng" : "mi"); break;
2125 // ::= ad # & (unary)
2126 // ::= an # & (binary or unknown)
2127 case OO_Amp:
2128 Out << (Arity == 1? "ad" : "an"); break;
2129 // ::= de # * (unary)
2130 // ::= ml # * (binary or unknown)
2131 case OO_Star:
2132 // Use binary when unknown.
2133 Out << (Arity == 1? "de" : "ml"); break;
2134 // ::= co # ~
2135 case OO_Tilde: Out << "co"; break;
2136 // ::= dv # /
2137 case OO_Slash: Out << "dv"; break;
2138 // ::= rm # %
2139 case OO_Percent: Out << "rm"; break;
2140 // ::= or # |
2141 case OO_Pipe: Out << "or"; break;
2142 // ::= eo # ^
2143 case OO_Caret: Out << "eo"; break;
2144 // ::= aS # =
2145 case OO_Equal: Out << "aS"; break;
2146 // ::= pL # +=
2147 case OO_PlusEqual: Out << "pL"; break;
2148 // ::= mI # -=
2149 case OO_MinusEqual: Out << "mI"; break;
2150 // ::= mL # *=
2151 case OO_StarEqual: Out << "mL"; break;
2152 // ::= dV # /=
2153 case OO_SlashEqual: Out << "dV"; break;
2154 // ::= rM # %=
2155 case OO_PercentEqual: Out << "rM"; break;
2156 // ::= aN # &=
2157 case OO_AmpEqual: Out << "aN"; break;
2158 // ::= oR # |=
2159 case OO_PipeEqual: Out << "oR"; break;
2160 // ::= eO # ^=
2161 case OO_CaretEqual: Out << "eO"; break;
2162 // ::= ls # <<
2163 case OO_LessLess: Out << "ls"; break;
2164 // ::= rs # >>
2165 case OO_GreaterGreater: Out << "rs"; break;
2166 // ::= lS # <<=
2167 case OO_LessLessEqual: Out << "lS"; break;
2168 // ::= rS # >>=
2169 case OO_GreaterGreaterEqual: Out << "rS"; break;
2170 // ::= eq # ==
2171 case OO_EqualEqual: Out << "eq"; break;
2172 // ::= ne # !=
2173 case OO_ExclaimEqual: Out << "ne"; break;
2174 // ::= lt # <
2175 case OO_Less: Out << "lt"; break;
2176 // ::= gt # >
2177 case OO_Greater: Out << "gt"; break;
2178 // ::= le # <=
2179 case OO_LessEqual: Out << "le"; break;
2180 // ::= ge # >=
2181 case OO_GreaterEqual: Out << "ge"; break;
2182 // ::= nt # !
2183 case OO_Exclaim: Out << "nt"; break;
2184 // ::= aa # &&
2185 case OO_AmpAmp: Out << "aa"; break;
2186 // ::= oo # ||
2187 case OO_PipePipe: Out << "oo"; break;
2188 // ::= pp # ++
2189 case OO_PlusPlus: Out << "pp"; break;
2190 // ::= mm # --
2191 case OO_MinusMinus: Out << "mm"; break;
2192 // ::= cm # ,
2193 case OO_Comma: Out << "cm"; break;
2194 // ::= pm # ->*
2195 case OO_ArrowStar: Out << "pm"; break;
2196 // ::= pt # ->
2197 case OO_Arrow: Out << "pt"; break;
2198 // ::= cl # ()
2199 case OO_Call: Out << "cl"; break;
2200 // ::= ix # []
2201 case OO_Subscript: Out << "ix"; break;
2202
2203 // ::= qu # ?
2204 // The conditional operator can't be overloaded, but we still handle it when
2205 // mangling expressions.
2206 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00002207 // Proposal on cxx-abi-dev, 2015-10-21.
2208 // ::= aw # co_await
2209 case OO_Coawait: Out << "aw"; break;
Richard Smithd30b23d2017-12-01 02:13:10 +00002210 // Proposed in cxx-abi github issue 43.
2211 // ::= ss # <=>
2212 case OO_Spaceship: Out << "ss"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002213
2214 case OO_None:
2215 case NUM_OVERLOADED_OPERATORS:
2216 llvm_unreachable("Not an overloaded operator");
2217 }
2218}
2219
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002220void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002221 // Vendor qualifiers come first and if they are order-insensitive they must
2222 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
Guy Benyei11169dd2012-12-18 14:30:41 +00002223
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002224 // <type> ::= U <addrspace-expr>
2225 if (DAST) {
2226 Out << "U2ASI";
2227 mangleExpression(DAST->getAddrSpaceExpr());
2228 Out << "E";
2229 }
2230
John McCall07daf722016-03-01 22:18:03 +00002231 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00002232 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00002233 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00002234 //
David Tweed31d09b02013-09-13 12:04:22 +00002235 // <type> ::= U <target-addrspace>
2236 // <type> ::= U <OpenCL-addrspace>
2237 // <type> ::= U <CUDA-addrspace>
2238
Guy Benyei11169dd2012-12-18 14:30:41 +00002239 SmallString<64> ASString;
Alexander Richardson6d989432017-10-15 18:48:14 +00002240 LangAS AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00002241
2242 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2243 // <target-addrspace> ::= "AS" <address-space-number>
2244 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Yaxun Liub7318e02017-10-13 03:37:48 +00002245 if (TargetAS != 0)
2246 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00002247 } else {
2248 switch (AS) {
2249 default: llvm_unreachable("Not a language specific address space");
Yaxun Liub7318e02017-10-13 03:37:48 +00002250 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2251 // "private"| "generic" ]
David Tweed31d09b02013-09-13 12:04:22 +00002252 case LangAS::opencl_global: ASString = "CLglobal"; break;
2253 case LangAS::opencl_local: ASString = "CLlocal"; break;
2254 case LangAS::opencl_constant: ASString = "CLconstant"; break;
Yaxun Liub7318e02017-10-13 03:37:48 +00002255 case LangAS::opencl_private: ASString = "CLprivate"; break;
Anastasia Stulova81a25e352017-03-10 15:23:07 +00002256 case LangAS::opencl_generic: ASString = "CLgeneric"; break;
David Tweed31d09b02013-09-13 12:04:22 +00002257 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2258 case LangAS::cuda_device: ASString = "CUdevice"; break;
2259 case LangAS::cuda_constant: ASString = "CUconstant"; break;
2260 case LangAS::cuda_shared: ASString = "CUshared"; break;
2261 }
2262 }
Yaxun Liub7318e02017-10-13 03:37:48 +00002263 if (!ASString.empty())
2264 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00002265 }
John McCall07daf722016-03-01 22:18:03 +00002266
2267 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00002268 // Objective-C ARC Extension:
2269 //
2270 // <type> ::= U "__strong"
2271 // <type> ::= U "__weak"
2272 // <type> ::= U "__autoreleasing"
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002273 //
2274 // Note: we emit __weak first to preserve the order as
2275 // required by the Itanium ABI.
2276 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
2277 mangleVendorQualifier("__weak");
2278
2279 // __unaligned (from -fms-extensions)
2280 if (Quals.hasUnaligned())
2281 mangleVendorQualifier("__unaligned");
2282
2283 // Remaining ARC ownership qualifiers.
2284 switch (Quals.getObjCLifetime()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002285 case Qualifiers::OCL_None:
2286 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002287
Guy Benyei11169dd2012-12-18 14:30:41 +00002288 case Qualifiers::OCL_Weak:
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00002289 // Do nothing as we already handled this case above.
Guy Benyei11169dd2012-12-18 14:30:41 +00002290 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002291
Guy Benyei11169dd2012-12-18 14:30:41 +00002292 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00002293 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00002294 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002295
Guy Benyei11169dd2012-12-18 14:30:41 +00002296 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00002297 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00002298 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002299
Guy Benyei11169dd2012-12-18 14:30:41 +00002300 case Qualifiers::OCL_ExplicitNone:
2301 // The __unsafe_unretained qualifier is *not* mangled, so that
2302 // __unsafe_unretained types in ARC produce the same manglings as the
2303 // equivalent (but, naturally, unqualified) types in non-ARC, providing
2304 // better ABI compatibility.
2305 //
2306 // It's safe to do this because unqualified 'id' won't show up
2307 // in any type signatures that need to be mangled.
2308 break;
2309 }
John McCall07daf722016-03-01 22:18:03 +00002310
2311 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
2312 if (Quals.hasRestrict())
2313 Out << 'r';
2314 if (Quals.hasVolatile())
2315 Out << 'V';
2316 if (Quals.hasConst())
2317 Out << 'K';
2318}
2319
2320void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2321 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002322}
2323
2324void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2325 // <ref-qualifier> ::= R # lvalue reference
2326 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00002327 switch (RefQualifier) {
2328 case RQ_None:
2329 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002330
Guy Benyei11169dd2012-12-18 14:30:41 +00002331 case RQ_LValue:
2332 Out << 'R';
2333 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002334
Guy Benyei11169dd2012-12-18 14:30:41 +00002335 case RQ_RValue:
2336 Out << 'O';
2337 break;
2338 }
2339}
2340
2341void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2342 Context.mangleObjCMethodName(MD, Out);
2343}
2344
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002345static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
2346 ASTContext &Ctx) {
David Majnemereea02ee2014-11-28 22:22:46 +00002347 if (Quals)
2348 return true;
2349 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2350 return true;
2351 if (Ty->isOpenCLSpecificType())
2352 return true;
2353 if (Ty->isBuiltinType())
2354 return false;
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002355 // Through to Clang 6.0, we accidentally treated undeduced auto types as
2356 // substitution candidates.
2357 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
2358 isa<AutoType>(Ty))
2359 return false;
David Majnemereea02ee2014-11-28 22:22:46 +00002360 return true;
2361}
2362
Guy Benyei11169dd2012-12-18 14:30:41 +00002363void CXXNameMangler::mangleType(QualType T) {
2364 // If our type is instantiation-dependent but not dependent, we mangle
Fangrui Song6907ce22018-07-30 19:24:48 +00002365 // it as it was written in the source, removing any top-level sugar.
Guy Benyei11169dd2012-12-18 14:30:41 +00002366 // Otherwise, use the canonical type.
2367 //
Fangrui Song6907ce22018-07-30 19:24:48 +00002368 // FIXME: This is an approximation of the instantiation-dependent name
Guy Benyei11169dd2012-12-18 14:30:41 +00002369 // mangling rules, since we should really be using the type as written and
2370 // augmented via semantic analysis (i.e., with implicit conversions and
Fangrui Song6907ce22018-07-30 19:24:48 +00002371 // default template arguments) for any instantiation-dependent type.
Guy Benyei11169dd2012-12-18 14:30:41 +00002372 // Unfortunately, that requires several changes to our AST:
Fangrui Song6907ce22018-07-30 19:24:48 +00002373 // - Instantiation-dependent TemplateSpecializationTypes will need to be
Guy Benyei11169dd2012-12-18 14:30:41 +00002374 // uniqued, so that we can handle substitutions properly
2375 // - Default template arguments will need to be represented in the
2376 // TemplateSpecializationType, since they need to be mangled even though
2377 // they aren't written.
2378 // - Conversions on non-type template arguments need to be expressed, since
2379 // they can affect the mangling of sizeof/alignof.
Richard Smithfda59e52016-10-26 01:05:54 +00002380 //
2381 // FIXME: This is wrong when mapping to the canonical type for a dependent
2382 // type discards instantiation-dependent portions of the type, such as for:
2383 //
2384 // template<typename T, int N> void f(T (&)[sizeof(N)]);
2385 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
2386 //
2387 // It's also wrong in the opposite direction when instantiation-dependent,
2388 // canonically-equivalent types differ in some irrelevant portion of inner
2389 // type sugar. In such cases, we fail to form correct substitutions, eg:
2390 //
2391 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
2392 //
2393 // We should instead canonicalize the non-instantiation-dependent parts,
2394 // regardless of whether the type as a whole is dependent or instantiation
2395 // dependent.
Guy Benyei11169dd2012-12-18 14:30:41 +00002396 if (!T->isInstantiationDependentType() || T->isDependentType())
2397 T = T.getCanonicalType();
2398 else {
2399 // Desugar any types that are purely sugar.
2400 do {
2401 // Don't desugar through template specialization types that aren't
2402 // type aliases. We need to mangle the template arguments as written.
Fangrui Song6907ce22018-07-30 19:24:48 +00002403 if (const TemplateSpecializationType *TST
Guy Benyei11169dd2012-12-18 14:30:41 +00002404 = dyn_cast<TemplateSpecializationType>(T))
2405 if (!TST->isTypeAlias())
2406 break;
2407
Fangrui Song6907ce22018-07-30 19:24:48 +00002408 QualType Desugared
Guy Benyei11169dd2012-12-18 14:30:41 +00002409 = T.getSingleStepDesugaredType(Context.getASTContext());
2410 if (Desugared == T)
2411 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00002412
Guy Benyei11169dd2012-12-18 14:30:41 +00002413 T = Desugared;
2414 } while (true);
2415 }
2416 SplitQualType split = T.split();
2417 Qualifiers quals = split.Quals;
2418 const Type *ty = split.Ty;
2419
Erik Pilkingtone7e87722018-04-28 02:40:28 +00002420 bool isSubstitutable =
2421 isTypeSubstitutable(quals, ty, Context.getASTContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00002422 if (isSubstitutable && mangleSubstitution(T))
2423 return;
2424
2425 // If we're mangling a qualified array type, push the qualifiers to
2426 // the element type.
2427 if (quals && isa<ArrayType>(T)) {
2428 ty = Context.getASTContext().getAsArrayType(T);
2429 quals = Qualifiers();
2430
2431 // Note that we don't update T: we want to add the
2432 // substitution at the original type.
2433 }
2434
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002435 if (quals || ty->isDependentAddressSpaceType()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002436 if (const DependentAddressSpaceType *DAST =
Andrew Gozillon572bbb02017-10-02 06:25:51 +00002437 dyn_cast<DependentAddressSpaceType>(ty)) {
2438 SplitQualType splitDAST = DAST->getPointeeType().split();
2439 mangleQualifiers(splitDAST.Quals, DAST);
2440 mangleType(QualType(splitDAST.Ty, 0));
2441 } else {
2442 mangleQualifiers(quals);
2443
2444 // Recurse: even if the qualified type isn't yet substitutable,
2445 // the unqualified type might be.
2446 mangleType(QualType(ty, 0));
2447 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002448 } else {
2449 switch (ty->getTypeClass()) {
2450#define ABSTRACT_TYPE(CLASS, PARENT)
2451#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2452 case Type::CLASS: \
2453 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2454 return;
2455#define TYPE(CLASS, PARENT) \
2456 case Type::CLASS: \
2457 mangleType(static_cast<const CLASS##Type*>(ty)); \
2458 break;
2459#include "clang/AST/TypeNodes.def"
2460 }
2461 }
2462
2463 // Add the substitution.
2464 if (isSubstitutable)
2465 addSubstitution(T);
2466}
2467
2468void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2469 if (!mangleStandardSubstitution(ND))
2470 mangleName(ND);
2471}
2472
2473void CXXNameMangler::mangleType(const BuiltinType *T) {
2474 // <type> ::= <builtin-type>
2475 // <builtin-type> ::= v # void
2476 // ::= w # wchar_t
2477 // ::= b # bool
2478 // ::= c # char
2479 // ::= a # signed char
2480 // ::= h # unsigned char
2481 // ::= s # short
2482 // ::= t # unsigned short
2483 // ::= i # int
2484 // ::= j # unsigned int
2485 // ::= l # long
2486 // ::= m # unsigned long
2487 // ::= x # long long, __int64
2488 // ::= y # unsigned long long, __int64
2489 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002490 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002491 // ::= f # float
2492 // ::= d # double
2493 // ::= e # long double, __float80
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002494 // ::= g # __float128
Guy Benyei11169dd2012-12-18 14:30:41 +00002495 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2496 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2497 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2498 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002499 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
Guy Benyei11169dd2012-12-18 14:30:41 +00002500 // ::= Di # char32_t
2501 // ::= Ds # char16_t
2502 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2503 // ::= u <source-name> # vendor extended type
Alexey Bader954ba212016-04-08 13:40:33 +00002504 std::string type_name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002505 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002506 case BuiltinType::Void:
2507 Out << 'v';
2508 break;
2509 case BuiltinType::Bool:
2510 Out << 'b';
2511 break;
2512 case BuiltinType::Char_U:
2513 case BuiltinType::Char_S:
2514 Out << 'c';
2515 break;
2516 case BuiltinType::UChar:
2517 Out << 'h';
2518 break;
2519 case BuiltinType::UShort:
2520 Out << 't';
2521 break;
2522 case BuiltinType::UInt:
2523 Out << 'j';
2524 break;
2525 case BuiltinType::ULong:
2526 Out << 'm';
2527 break;
2528 case BuiltinType::ULongLong:
2529 Out << 'y';
2530 break;
2531 case BuiltinType::UInt128:
2532 Out << 'o';
2533 break;
2534 case BuiltinType::SChar:
2535 Out << 'a';
2536 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002537 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002538 case BuiltinType::WChar_U:
2539 Out << 'w';
2540 break;
Richard Smith3a8244d2018-05-01 05:02:45 +00002541 case BuiltinType::Char8:
2542 Out << "Du";
2543 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002544 case BuiltinType::Char16:
2545 Out << "Ds";
2546 break;
2547 case BuiltinType::Char32:
2548 Out << "Di";
2549 break;
2550 case BuiltinType::Short:
2551 Out << 's';
2552 break;
2553 case BuiltinType::Int:
2554 Out << 'i';
2555 break;
2556 case BuiltinType::Long:
2557 Out << 'l';
2558 break;
2559 case BuiltinType::LongLong:
2560 Out << 'x';
2561 break;
2562 case BuiltinType::Int128:
2563 Out << 'n';
2564 break;
Sjoerd Meijercc623ad2017-09-08 15:15:00 +00002565 case BuiltinType::Float16:
2566 Out << "DF16_";
2567 break;
Leonard Chanf921d852018-06-04 16:07:52 +00002568 case BuiltinType::ShortAccum:
2569 case BuiltinType::Accum:
2570 case BuiltinType::LongAccum:
2571 case BuiltinType::UShortAccum:
2572 case BuiltinType::UAccum:
2573 case BuiltinType::ULongAccum:
Leonard Chanab80f3c2018-06-14 14:53:51 +00002574 case BuiltinType::ShortFract:
2575 case BuiltinType::Fract:
2576 case BuiltinType::LongFract:
2577 case BuiltinType::UShortFract:
2578 case BuiltinType::UFract:
2579 case BuiltinType::ULongFract:
2580 case BuiltinType::SatShortAccum:
2581 case BuiltinType::SatAccum:
2582 case BuiltinType::SatLongAccum:
2583 case BuiltinType::SatUShortAccum:
2584 case BuiltinType::SatUAccum:
2585 case BuiltinType::SatULongAccum:
2586 case BuiltinType::SatShortFract:
2587 case BuiltinType::SatFract:
2588 case BuiltinType::SatLongFract:
2589 case BuiltinType::SatUShortFract:
2590 case BuiltinType::SatUFract:
2591 case BuiltinType::SatULongFract:
Leonard Chanf921d852018-06-04 16:07:52 +00002592 llvm_unreachable("Fixed point types are disabled for c++");
Alexey Baderbdf7c842015-09-15 12:18:29 +00002593 case BuiltinType::Half:
2594 Out << "Dh";
2595 break;
2596 case BuiltinType::Float:
2597 Out << 'f';
2598 break;
2599 case BuiltinType::Double:
2600 Out << 'd';
2601 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002602 case BuiltinType::LongDouble:
2603 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2604 ? 'g'
2605 : 'e');
2606 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002607 case BuiltinType::Float128:
2608 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2609 Out << "U10__float128"; // Match the GCC mangling
2610 else
2611 Out << 'g';
2612 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002613 case BuiltinType::NullPtr:
2614 Out << "Dn";
2615 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002616
2617#define BUILTIN_TYPE(Id, SingletonId)
2618#define PLACEHOLDER_TYPE(Id, SingletonId) \
2619 case BuiltinType::Id:
2620#include "clang/AST/BuiltinTypes.def"
2621 case BuiltinType::Dependent:
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00002622 if (!NullOut)
2623 llvm_unreachable("mangling a placeholder type");
2624 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002625 case BuiltinType::ObjCId:
2626 Out << "11objc_object";
2627 break;
2628 case BuiltinType::ObjCClass:
2629 Out << "10objc_class";
2630 break;
2631 case BuiltinType::ObjCSel:
2632 Out << "13objc_selector";
2633 break;
Alexey Bader954ba212016-04-08 13:40:33 +00002634#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2635 case BuiltinType::Id: \
2636 type_name = "ocl_" #ImgType "_" #Suffix; \
2637 Out << type_name.size() << type_name; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00002638 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00002639#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00002640 case BuiltinType::OCLSampler:
2641 Out << "11ocl_sampler";
2642 break;
2643 case BuiltinType::OCLEvent:
2644 Out << "9ocl_event";
2645 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002646 case BuiltinType::OCLClkEvent:
2647 Out << "12ocl_clkevent";
2648 break;
2649 case BuiltinType::OCLQueue:
2650 Out << "9ocl_queue";
2651 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002652 case BuiltinType::OCLReserveID:
2653 Out << "13ocl_reserveid";
2654 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002655 }
2656}
2657
John McCall07daf722016-03-01 22:18:03 +00002658StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2659 switch (CC) {
2660 case CC_C:
2661 return "";
2662
2663 case CC_X86StdCall:
2664 case CC_X86FastCall:
2665 case CC_X86ThisCall:
2666 case CC_X86VectorCall:
2667 case CC_X86Pascal:
Martin Storsjo022e7822017-07-17 20:49:45 +00002668 case CC_Win64:
John McCall07daf722016-03-01 22:18:03 +00002669 case CC_X86_64SysV:
Erich Keane757d3172016-11-02 18:29:35 +00002670 case CC_X86RegCall:
John McCall07daf722016-03-01 22:18:03 +00002671 case CC_AAPCS:
2672 case CC_AAPCS_VFP:
2673 case CC_IntelOclBicc:
2674 case CC_SpirFunction:
Nikolay Haustov8c6538b2016-06-30 09:06:33 +00002675 case CC_OpenCLKernel:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00002676 case CC_PreserveMost:
2677 case CC_PreserveAll:
John McCall07daf722016-03-01 22:18:03 +00002678 // FIXME: we should be mangling all of the above.
2679 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002680
2681 case CC_Swift:
2682 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002683 }
2684 llvm_unreachable("bad calling convention");
2685}
2686
2687void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2688 // Fast path.
2689 if (T->getExtInfo() == FunctionType::ExtInfo())
2690 return;
2691
2692 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2693 // This will get more complicated in the future if we mangle other
2694 // things here; but for now, since we mangle ns_returns_retained as
2695 // a qualifier on the result type, we can get away with this:
2696 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2697 if (!CCQualifier.empty())
2698 mangleVendorQualifier(CCQualifier);
2699
2700 // FIXME: regparm
2701 // FIXME: noreturn
2702}
2703
2704void
2705CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2706 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2707
2708 // Note that these are *not* substitution candidates. Demanglers might
2709 // have trouble with this if the parameter type is fully substituted.
2710
John McCall477f2bb2016-03-03 06:39:32 +00002711 switch (PI.getABI()) {
2712 case ParameterABI::Ordinary:
2713 break;
2714
2715 // All of these start with "swift", so they come before "ns_consumed".
2716 case ParameterABI::SwiftContext:
2717 case ParameterABI::SwiftErrorResult:
2718 case ParameterABI::SwiftIndirectResult:
2719 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2720 break;
2721 }
2722
John McCall07daf722016-03-01 22:18:03 +00002723 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002724 mangleVendorQualifier("ns_consumed");
Akira Hatanaka98a49332017-09-22 00:41:05 +00002725
2726 if (PI.isNoEscape())
2727 mangleVendorQualifier("noescape");
John McCall07daf722016-03-01 22:18:03 +00002728}
2729
Guy Benyei11169dd2012-12-18 14:30:41 +00002730// <type> ::= <function-type>
2731// <function-type> ::= [<CV-qualifiers>] F [Y]
2732// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002733void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002734 mangleExtFunctionInfo(T);
2735
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2737 // e.g. "const" in "int (A::*)() const".
Reid Kleckner267589a2018-03-08 00:55:09 +00002738 mangleQualifiers(Qualifiers::fromCVRUMask(T->getTypeQuals()));
Guy Benyei11169dd2012-12-18 14:30:41 +00002739
Richard Smithfda59e52016-10-26 01:05:54 +00002740 // Mangle instantiation-dependent exception-specification, if present,
2741 // per cxx-abi-dev proposal on 2016-10-11.
2742 if (T->hasInstantiationDependentExceptionSpec()) {
Richard Smitheaf11ad2018-05-03 03:58:32 +00002743 if (isComputedNoexcept(T->getExceptionSpecType())) {
Richard Smithef09aa92016-11-03 00:27:54 +00002744 Out << "DO";
Richard Smithfda59e52016-10-26 01:05:54 +00002745 mangleExpression(T->getNoexceptExpr());
2746 Out << "E";
2747 } else {
2748 assert(T->getExceptionSpecType() == EST_Dynamic);
Richard Smithef09aa92016-11-03 00:27:54 +00002749 Out << "Dw";
Richard Smithfda59e52016-10-26 01:05:54 +00002750 for (auto ExceptTy : T->exceptions())
2751 mangleType(ExceptTy);
2752 Out << "E";
2753 }
Richard Smitheaf11ad2018-05-03 03:58:32 +00002754 } else if (T->isNothrow()) {
Richard Smithef09aa92016-11-03 00:27:54 +00002755 Out << "Do";
Richard Smithfda59e52016-10-26 01:05:54 +00002756 }
2757
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 Out << 'F';
2759
2760 // FIXME: We don't have enough information in the AST to produce the 'Y'
2761 // encoding for extern "C" function types.
2762 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2763
2764 // Mangle the ref-qualifier, if present.
2765 mangleRefQualifier(T->getRefQualifier());
2766
2767 Out << 'E';
2768}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002769
Guy Benyei11169dd2012-12-18 14:30:41 +00002770void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002771 // Function types without prototypes can arise when mangling a function type
2772 // within an overloadable function in C. We mangle these as the absence of any
2773 // parameter types (not even an empty parameter list).
2774 Out << 'F';
2775
2776 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2777
2778 FunctionTypeDepth.enterResultType();
2779 mangleType(T->getReturnType());
2780 FunctionTypeDepth.leaveResultType();
2781
2782 FunctionTypeDepth.pop(saved);
2783 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002784}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002785
John McCall07daf722016-03-01 22:18:03 +00002786void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002787 bool MangleReturnType,
2788 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002789 // Record that we're in a function type. See mangleFunctionParam
2790 // for details on what we're trying to achieve here.
2791 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2792
2793 // <bare-function-type> ::= <signature type>+
2794 if (MangleReturnType) {
2795 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002796
2797 // Mangle ns_returns_retained as an order-sensitive qualifier here.
Nico Weberfb420782016-05-25 14:15:08 +00002798 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
John McCall07daf722016-03-01 22:18:03 +00002799 mangleVendorQualifier("ns_returns_retained");
2800
2801 // Mangle the return type without any direct ARC ownership qualifiers.
2802 QualType ReturnTy = Proto->getReturnType();
2803 if (ReturnTy.getObjCLifetime()) {
2804 auto SplitReturnTy = ReturnTy.split();
2805 SplitReturnTy.Quals.removeObjCLifetime();
2806 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2807 }
2808 mangleType(ReturnTy);
2809
Guy Benyei11169dd2012-12-18 14:30:41 +00002810 FunctionTypeDepth.leaveResultType();
2811 }
2812
Alp Toker9cacbab2014-01-20 20:26:09 +00002813 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002814 // <builtin-type> ::= v # void
2815 Out << 'v';
2816
2817 FunctionTypeDepth.pop(saved);
2818 return;
2819 }
2820
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002821 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2822 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002823 // Mangle extended parameter info as order-sensitive qualifiers here.
Nico Weberfb420782016-05-25 14:15:08 +00002824 if (Proto->hasExtParameterInfos() && FD == nullptr) {
John McCall07daf722016-03-01 22:18:03 +00002825 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2826 }
2827
2828 // Mangle the type.
2829 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002830 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2831
2832 if (FD) {
2833 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2834 // Attr can only take 1 character, so we can hardcode the length below.
2835 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2836 Out << "U17pass_object_size" << Attr->getType();
2837 }
2838 }
2839 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002840
2841 FunctionTypeDepth.pop(saved);
2842
2843 // <builtin-type> ::= z # ellipsis
2844 if (Proto->isVariadic())
2845 Out << 'z';
2846}
2847
2848// <type> ::= <class-enum-type>
2849// <class-enum-type> ::= <name>
2850void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2851 mangleName(T->getDecl());
2852}
2853
2854// <type> ::= <class-enum-type>
2855// <class-enum-type> ::= <name>
2856void CXXNameMangler::mangleType(const EnumType *T) {
2857 mangleType(static_cast<const TagType*>(T));
2858}
2859void CXXNameMangler::mangleType(const RecordType *T) {
2860 mangleType(static_cast<const TagType*>(T));
2861}
2862void CXXNameMangler::mangleType(const TagType *T) {
2863 mangleName(T->getDecl());
2864}
2865
2866// <type> ::= <array-type>
2867// <array-type> ::= A <positive dimension number> _ <element type>
2868// ::= A [<dimension expression>] _ <element type>
2869void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2870 Out << 'A' << T->getSize() << '_';
2871 mangleType(T->getElementType());
2872}
2873void CXXNameMangler::mangleType(const VariableArrayType *T) {
2874 Out << 'A';
2875 // decayed vla types (size 0) will just be skipped.
2876 if (T->getSizeExpr())
2877 mangleExpression(T->getSizeExpr());
2878 Out << '_';
2879 mangleType(T->getElementType());
2880}
2881void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2882 Out << 'A';
2883 mangleExpression(T->getSizeExpr());
2884 Out << '_';
2885 mangleType(T->getElementType());
2886}
2887void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2888 Out << "A_";
2889 mangleType(T->getElementType());
2890}
2891
2892// <type> ::= <pointer-to-member-type>
2893// <pointer-to-member-type> ::= M <class type> <member type>
2894void CXXNameMangler::mangleType(const MemberPointerType *T) {
2895 Out << 'M';
2896 mangleType(QualType(T->getClass(), 0));
2897 QualType PointeeType = T->getPointeeType();
2898 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2899 mangleType(FPT);
Fangrui Song6907ce22018-07-30 19:24:48 +00002900
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 // Itanium C++ ABI 5.1.8:
2902 //
2903 // The type of a non-static member function is considered to be different,
2904 // for the purposes of substitution, from the type of a namespace-scope or
2905 // static member function whose type appears similar. The types of two
2906 // non-static member functions are considered to be different, for the
2907 // purposes of substitution, if the functions are members of different
Fangrui Song6907ce22018-07-30 19:24:48 +00002908 // classes. In other words, for the purposes of substitution, the class of
2909 // which the function is a member is considered part of the type of
Guy Benyei11169dd2012-12-18 14:30:41 +00002910 // function.
2911
2912 // Given that we already substitute member function pointers as a
2913 // whole, the net effect of this rule is just to unconditionally
2914 // suppress substitution on the function type in a member pointer.
2915 // We increment the SeqID here to emulate adding an entry to the
2916 // substitution table.
2917 ++SeqID;
2918 } else
2919 mangleType(PointeeType);
2920}
2921
2922// <type> ::= <template-param>
2923void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2924 mangleTemplateParameter(T->getIndex());
2925}
2926
2927// <type> ::= <template-param>
2928void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2929 // FIXME: not clear how to mangle this!
2930 // template <class T...> class A {
2931 // template <class U...> void foo(T(*)(U) x...);
2932 // };
2933 Out << "_SUBSTPACK_";
2934}
2935
2936// <type> ::= P <type> # pointer-to
2937void CXXNameMangler::mangleType(const PointerType *T) {
2938 Out << 'P';
2939 mangleType(T->getPointeeType());
2940}
2941void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2942 Out << 'P';
2943 mangleType(T->getPointeeType());
2944}
2945
2946// <type> ::= R <type> # reference-to
2947void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2948 Out << 'R';
2949 mangleType(T->getPointeeType());
2950}
2951
2952// <type> ::= O <type> # rvalue reference-to (C++0x)
2953void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2954 Out << 'O';
2955 mangleType(T->getPointeeType());
2956}
2957
2958// <type> ::= C <type> # complex pair (C 2000)
2959void CXXNameMangler::mangleType(const ComplexType *T) {
2960 Out << 'C';
2961 mangleType(T->getElementType());
2962}
2963
2964// ARM's ABI for Neon vector types specifies that they should be mangled as
2965// if they are structs (to match ARM's initial implementation). The
2966// vector type must be one of the special types predefined by ARM.
2967void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2968 QualType EltType = T->getElementType();
2969 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002970 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002971 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2972 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002973 case BuiltinType::SChar:
2974 case BuiltinType::UChar:
2975 EltName = "poly8_t";
2976 break;
2977 case BuiltinType::Short:
2978 case BuiltinType::UShort:
2979 EltName = "poly16_t";
2980 break;
2981 case BuiltinType::ULongLong:
2982 EltName = "poly64_t";
2983 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002984 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2985 }
2986 } else {
2987 switch (cast<BuiltinType>(EltType)->getKind()) {
2988 case BuiltinType::SChar: EltName = "int8_t"; break;
2989 case BuiltinType::UChar: EltName = "uint8_t"; break;
2990 case BuiltinType::Short: EltName = "int16_t"; break;
2991 case BuiltinType::UShort: EltName = "uint16_t"; break;
2992 case BuiltinType::Int: EltName = "int32_t"; break;
2993 case BuiltinType::UInt: EltName = "uint32_t"; break;
2994 case BuiltinType::LongLong: EltName = "int64_t"; break;
2995 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002996 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002997 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002998 case BuiltinType::Half: EltName = "float16_t";break;
2999 default:
3000 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 }
3002 }
Craig Topper36250ad2014-05-12 05:36:57 +00003003 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00003004 unsigned BitSize = (T->getNumElements() *
3005 getASTContext().getTypeSize(EltType));
3006 if (BitSize == 64)
3007 BaseName = "__simd64_";
3008 else {
3009 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
3010 BaseName = "__simd128_";
3011 }
3012 Out << strlen(BaseName) + strlen(EltName);
3013 Out << BaseName << EltName;
3014}
3015
Erich Keanef702b022018-07-13 19:46:04 +00003016void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
3017 DiagnosticsEngine &Diags = Context.getDiags();
3018 unsigned DiagID = Diags.getCustomDiagID(
3019 DiagnosticsEngine::Error,
3020 "cannot mangle this dependent neon vector type yet");
3021 Diags.Report(T->getAttributeLoc(), DiagID);
3022}
3023
Tim Northover2fe823a2013-08-01 09:23:19 +00003024static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
3025 switch (EltType->getKind()) {
3026 case BuiltinType::SChar:
3027 return "Int8";
3028 case BuiltinType::Short:
3029 return "Int16";
3030 case BuiltinType::Int:
3031 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003032 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00003033 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003034 return "Int64";
3035 case BuiltinType::UChar:
3036 return "Uint8";
3037 case BuiltinType::UShort:
3038 return "Uint16";
3039 case BuiltinType::UInt:
3040 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00003041 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00003042 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00003043 return "Uint64";
3044 case BuiltinType::Half:
3045 return "Float16";
3046 case BuiltinType::Float:
3047 return "Float32";
3048 case BuiltinType::Double:
3049 return "Float64";
3050 default:
3051 llvm_unreachable("Unexpected vector element base type");
3052 }
3053}
3054
3055// AArch64's ABI for Neon vector types specifies that they should be mangled as
3056// the equivalent internal name. The vector type must be one of the special
3057// types predefined by ARM.
3058void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
3059 QualType EltType = T->getElementType();
3060 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
3061 unsigned BitSize =
3062 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00003063 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00003064
3065 assert((BitSize == 64 || BitSize == 128) &&
3066 "Neon vector type not 64 or 128 bits");
3067
Tim Northover2fe823a2013-08-01 09:23:19 +00003068 StringRef EltName;
3069 if (T->getVectorKind() == VectorType::NeonPolyVector) {
3070 switch (cast<BuiltinType>(EltType)->getKind()) {
3071 case BuiltinType::UChar:
3072 EltName = "Poly8";
3073 break;
3074 case BuiltinType::UShort:
3075 EltName = "Poly16";
3076 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00003077 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00003078 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00003079 EltName = "Poly64";
3080 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00003081 default:
3082 llvm_unreachable("unexpected Neon polynomial vector element type");
3083 }
3084 } else
3085 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
3086
3087 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00003088 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00003089 Out << TypeName.length() << TypeName;
3090}
Erich Keanef702b022018-07-13 19:46:04 +00003091void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
3092 DiagnosticsEngine &Diags = Context.getDiags();
3093 unsigned DiagID = Diags.getCustomDiagID(
3094 DiagnosticsEngine::Error,
3095 "cannot mangle this dependent neon vector type yet");
3096 Diags.Report(T->getAttributeLoc(), DiagID);
3097}
Tim Northover2fe823a2013-08-01 09:23:19 +00003098
Guy Benyei11169dd2012-12-18 14:30:41 +00003099// GNU extension: vector types
3100// <type> ::= <vector-type>
3101// <vector-type> ::= Dv <positive dimension number> _
3102// <extended element type>
3103// ::= Dv [<dimension expression>] _ <element type>
3104// <extended element type> ::= <element type>
3105// ::= p # AltiVec vector pixel
3106// ::= b # Altivec vector bool
3107void CXXNameMangler::mangleType(const VectorType *T) {
3108 if ((T->getVectorKind() == VectorType::NeonVector ||
3109 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00003110 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00003111 llvm::Triple::ArchType Arch =
3112 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00003113 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00003114 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00003115 mangleAArch64NeonVectorType(T);
3116 else
3117 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00003118 return;
3119 }
3120 Out << "Dv" << T->getNumElements() << '_';
3121 if (T->getVectorKind() == VectorType::AltiVecPixel)
3122 Out << 'p';
3123 else if (T->getVectorKind() == VectorType::AltiVecBool)
3124 Out << 'b';
3125 else
3126 mangleType(T->getElementType());
3127}
Erich Keanef702b022018-07-13 19:46:04 +00003128
3129void CXXNameMangler::mangleType(const DependentVectorType *T) {
3130 if ((T->getVectorKind() == VectorType::NeonVector ||
3131 T->getVectorKind() == VectorType::NeonPolyVector)) {
3132 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
3133 llvm::Triple::ArchType Arch =
3134 getASTContext().getTargetInfo().getTriple().getArch();
3135 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
3136 !Target.isOSDarwin())
3137 mangleAArch64NeonVectorType(T);
3138 else
3139 mangleNeonVectorType(T);
3140 return;
3141 }
3142
3143 Out << "Dv";
3144 mangleExpression(T->getSizeExpr());
3145 Out << '_';
3146 if (T->getVectorKind() == VectorType::AltiVecPixel)
3147 Out << 'p';
3148 else if (T->getVectorKind() == VectorType::AltiVecBool)
3149 Out << 'b';
3150 else
3151 mangleType(T->getElementType());
3152}
3153
Guy Benyei11169dd2012-12-18 14:30:41 +00003154void CXXNameMangler::mangleType(const ExtVectorType *T) {
3155 mangleType(static_cast<const VectorType*>(T));
3156}
3157void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
3158 Out << "Dv";
3159 mangleExpression(T->getSizeExpr());
3160 Out << '_';
3161 mangleType(T->getElementType());
3162}
3163
Andrew Gozillon572bbb02017-10-02 06:25:51 +00003164void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
3165 SplitQualType split = T->getPointeeType().split();
3166 mangleQualifiers(split.Quals, T);
3167 mangleType(QualType(split.Ty, 0));
3168}
3169
Guy Benyei11169dd2012-12-18 14:30:41 +00003170void CXXNameMangler::mangleType(const PackExpansionType *T) {
3171 // <type> ::= Dp <type> # pack expansion (C++0x)
3172 Out << "Dp";
3173 mangleType(T->getPattern());
3174}
3175
3176void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
3177 mangleSourceName(T->getDecl()->getIdentifier());
3178}
3179
3180void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00003181 // Treat __kindof as a vendor extended type qualifier.
3182 if (T->isKindOfType())
3183 Out << "U8__kindof";
3184
Eli Friedman5f508952013-06-18 22:41:37 +00003185 if (!T->qual_empty()) {
3186 // Mangle protocol qualifiers.
3187 SmallString<64> QualStr;
3188 llvm::raw_svector_ostream QualOS(QualStr);
3189 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00003190 for (const auto *I : T->quals()) {
3191 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00003192 QualOS << name.size() << name;
3193 }
Eli Friedman5f508952013-06-18 22:41:37 +00003194 Out << 'U' << QualStr.size() << QualStr;
3195 }
Douglas Gregorab209d82015-07-07 03:58:42 +00003196
Guy Benyei11169dd2012-12-18 14:30:41 +00003197 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00003198
3199 if (T->isSpecialized()) {
3200 // Mangle type arguments as I <type>+ E
3201 Out << 'I';
3202 for (auto typeArg : T->getTypeArgs())
3203 mangleType(typeArg);
3204 Out << 'E';
3205 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003206}
3207
3208void CXXNameMangler::mangleType(const BlockPointerType *T) {
3209 Out << "U13block_pointer";
3210 mangleType(T->getPointeeType());
3211}
3212
3213void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
3214 // Mangle injected class name types as if the user had written the
3215 // specialization out fully. It may not actually be possible to see
3216 // this mangling, though.
3217 mangleType(T->getInjectedSpecializationType());
3218}
3219
3220void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
3221 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003222 mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003223 } else {
3224 if (mangleSubstitution(QualType(T, 0)))
3225 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00003226
Guy Benyei11169dd2012-12-18 14:30:41 +00003227 mangleTemplatePrefix(T->getTemplateName());
Fangrui Song6907ce22018-07-30 19:24:48 +00003228
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 // FIXME: GCC does not appear to mangle the template arguments when
3230 // the template in question is a dependent template name. Should we
3231 // emulate that badness?
3232 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
3233 addSubstitution(QualType(T, 0));
3234 }
3235}
3236
3237void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00003238 // Proposal by cxx-abi-dev, 2014-03-26
3239 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
3240 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003241 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00003242 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003243 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00003244 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003245 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00003246 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00003247 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00003248 switch (T->getKeyword()) {
Richard Smith91fb1f42017-01-20 18:50:12 +00003249 case ETK_None:
David Majnemer64e40c52014-04-10 00:49:24 +00003250 case ETK_Typename:
3251 break;
3252 case ETK_Struct:
3253 case ETK_Class:
3254 case ETK_Interface:
3255 Out << "Ts";
3256 break;
3257 case ETK_Union:
3258 Out << "Tu";
3259 break;
3260 case ETK_Enum:
3261 Out << "Te";
3262 break;
David Majnemer64e40c52014-04-10 00:49:24 +00003263 }
David Majnemer2e159fb2014-04-15 05:51:25 +00003264 // Typename types are always nested
3265 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00003266 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00003267 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00003268 Out << 'E';
3269}
3270
3271void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
3272 // Dependently-scoped template types are nested if they have a prefix.
3273 Out << 'N';
3274
3275 // TODO: avoid making this TemplateName.
3276 TemplateName Prefix =
3277 getASTContext().getDependentTemplateName(T->getQualifier(),
3278 T->getIdentifier());
3279 mangleTemplatePrefix(Prefix);
3280
3281 // FIXME: GCC does not appear to mangle the template arguments when
3282 // the template in question is a dependent template name. Should we
3283 // emulate that badness?
Fangrui Song6907ce22018-07-30 19:24:48 +00003284 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003285 Out << 'E';
3286}
3287
3288void CXXNameMangler::mangleType(const TypeOfType *T) {
3289 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3290 // "extension with parameters" mangling.
3291 Out << "u6typeof";
3292}
3293
3294void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3295 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3296 // "extension with parameters" mangling.
3297 Out << "u6typeof";
3298}
3299
3300void CXXNameMangler::mangleType(const DecltypeType *T) {
3301 Expr *E = T->getUnderlyingExpr();
3302
3303 // type ::= Dt <expression> E # decltype of an id-expression
3304 // # or class member access
3305 // ::= DT <expression> E # decltype of an expression
3306
3307 // This purports to be an exhaustive list of id-expressions and
3308 // class member accesses. Note that we do not ignore parentheses;
3309 // parentheses change the semantics of decltype for these
3310 // expressions (and cause the mangler to use the other form).
3311 if (isa<DeclRefExpr>(E) ||
3312 isa<MemberExpr>(E) ||
3313 isa<UnresolvedLookupExpr>(E) ||
3314 isa<DependentScopeDeclRefExpr>(E) ||
3315 isa<CXXDependentScopeMemberExpr>(E) ||
3316 isa<UnresolvedMemberExpr>(E))
3317 Out << "Dt";
3318 else
3319 Out << "DT";
3320 mangleExpression(E);
3321 Out << 'E';
3322}
3323
3324void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3325 // If this is dependent, we need to record that. If not, we simply
3326 // mangle it as the underlying type since they are equivalent.
3327 if (T->isDependentType()) {
3328 Out << 'U';
Fangrui Song6907ce22018-07-30 19:24:48 +00003329
Guy Benyei11169dd2012-12-18 14:30:41 +00003330 switch (T->getUTTKind()) {
3331 case UnaryTransformType::EnumUnderlyingType:
3332 Out << "3eut";
3333 break;
3334 }
3335 }
3336
David Majnemer140065a2016-06-08 00:34:15 +00003337 mangleType(T->getBaseType());
Guy Benyei11169dd2012-12-18 14:30:41 +00003338}
3339
3340void CXXNameMangler::mangleType(const AutoType *T) {
Erik Pilkingtone7e87722018-04-28 02:40:28 +00003341 assert(T->getDeducedType().isNull() &&
3342 "Deduced AutoType shouldn't be handled here!");
3343 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3344 "shouldn't need to mangle __auto_type!");
3345 // <builtin-type> ::= Da # auto
3346 // ::= Dc # decltype(auto)
3347 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00003348}
3349
Richard Smith600b5262017-01-26 20:40:47 +00003350void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
3351 // FIXME: This is not the right mangling. We also need to include a scope
3352 // here in some cases.
3353 QualType D = T->getDeducedType();
3354 if (D.isNull())
3355 mangleUnscopedTemplateName(T->getTemplateName(), nullptr);
3356 else
3357 mangleType(D);
3358}
3359
Guy Benyei11169dd2012-12-18 14:30:41 +00003360void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00003361 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00003362 // (Until there's a standardized mangling...)
3363 Out << "U7_Atomic";
3364 mangleType(T->getValueType());
3365}
3366
Xiuli Pan9c14e282016-01-09 12:53:17 +00003367void CXXNameMangler::mangleType(const PipeType *T) {
3368 // Pipe type mangling rules are described in SPIR 2.0 specification
3369 // A.1 Data types and A.3 Summary of changes
3370 // <type> ::= 8ocl_pipe
3371 Out << "8ocl_pipe";
3372}
3373
Guy Benyei11169dd2012-12-18 14:30:41 +00003374void CXXNameMangler::mangleIntegerLiteral(QualType T,
3375 const llvm::APSInt &Value) {
3376 // <expr-primary> ::= L <type> <value number> E # integer literal
3377 Out << 'L';
3378
3379 mangleType(T);
3380 if (T->isBooleanType()) {
3381 // Boolean values are encoded as 0/1.
3382 Out << (Value.getBoolValue() ? '1' : '0');
3383 } else {
3384 mangleNumber(Value);
3385 }
3386 Out << 'E';
3387
3388}
3389
David Majnemer1dabfdc2015-02-14 13:23:54 +00003390void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3391 // Ignore member expressions involving anonymous unions.
3392 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3393 if (!RT->getDecl()->isAnonymousStructOrUnion())
3394 break;
3395 const auto *ME = dyn_cast<MemberExpr>(Base);
3396 if (!ME)
3397 break;
3398 Base = ME->getBase();
3399 IsArrow = ME->isArrow();
3400 }
3401
3402 if (Base->isImplicitCXXThis()) {
3403 // Note: GCC mangles member expressions to the implicit 'this' as
3404 // *this., whereas we represent them as this->. The Itanium C++ ABI
3405 // does not specify anything here, so we follow GCC.
3406 Out << "dtdefpT";
3407 } else {
3408 Out << (IsArrow ? "pt" : "dt");
3409 mangleExpression(Base);
3410 }
3411}
3412
Guy Benyei11169dd2012-12-18 14:30:41 +00003413/// Mangles a member expression.
3414void CXXNameMangler::mangleMemberExpr(const Expr *base,
3415 bool isArrow,
3416 NestedNameSpecifier *qualifier,
3417 NamedDecl *firstQualifierLookup,
3418 DeclarationName member,
Richard Smithafecd832016-10-24 20:47:04 +00003419 const TemplateArgumentLoc *TemplateArgs,
3420 unsigned NumTemplateArgs,
Guy Benyei11169dd2012-12-18 14:30:41 +00003421 unsigned arity) {
3422 // <expression> ::= dt <expression> <unresolved-name>
3423 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00003424 if (base)
3425 mangleMemberExprBase(base, isArrow);
Richard Smithafecd832016-10-24 20:47:04 +00003426 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003427}
3428
3429/// Look at the callee of the given call expression and determine if
3430/// it's a parenthesized id-expression which would have triggered ADL
3431/// otherwise.
3432static bool isParenthesizedADLCallee(const CallExpr *call) {
3433 const Expr *callee = call->getCallee();
3434 const Expr *fn = callee->IgnoreParens();
3435
3436 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
3437 // too, but for those to appear in the callee, it would have to be
3438 // parenthesized.
3439 if (callee == fn) return false;
3440
3441 // Must be an unresolved lookup.
3442 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3443 if (!lookup) return false;
3444
3445 assert(!lookup->requiresADL());
3446
3447 // Must be an unqualified lookup.
3448 if (lookup->getQualifier()) return false;
3449
3450 // Must not have found a class member. Note that if one is a class
3451 // member, they're all class members.
3452 if (lookup->getNumDecls() > 0 &&
3453 (*lookup->decls_begin())->isCXXClassMember())
3454 return false;
3455
3456 // Otherwise, ADL would have been triggered.
3457 return true;
3458}
3459
David Majnemer9c775c72014-09-23 04:27:55 +00003460void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3461 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3462 Out << CastEncoding;
3463 mangleType(ECE->getType());
3464 mangleExpression(ECE->getSubExpr());
3465}
3466
Richard Smith520449d2015-02-05 06:15:50 +00003467void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3468 if (auto *Syntactic = InitList->getSyntacticForm())
3469 InitList = Syntactic;
3470 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3471 mangleExpression(InitList->getInit(i));
3472}
3473
Guy Benyei11169dd2012-12-18 14:30:41 +00003474void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3475 // <expression> ::= <unary operator-name> <expression>
3476 // ::= <binary operator-name> <expression> <expression>
3477 // ::= <trinary operator-name> <expression> <expression> <expression>
3478 // ::= cv <type> expression # conversion with one argument
3479 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00003480 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
3481 // ::= sc <type> <expression> # static_cast<type> (expression)
3482 // ::= cc <type> <expression> # const_cast<type> (expression)
3483 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003484 // ::= st <type> # sizeof (a type)
3485 // ::= at <type> # alignof (a type)
3486 // ::= <template-param>
3487 // ::= <function-param>
3488 // ::= sr <type> <unqualified-name> # dependent name
3489 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
3490 // ::= ds <expression> <expression> # expr.*expr
3491 // ::= sZ <template-param> # size of a parameter pack
3492 // ::= sZ <function-param> # size of a function parameter pack
3493 // ::= <expr-primary>
3494 // <expr-primary> ::= L <type> <value number> E # integer literal
3495 // ::= L <type <value float> E # floating literal
3496 // ::= L <mangled-name> E # external name
3497 // ::= fpT # 'this' expression
3498 QualType ImplicitlyConvertedToType;
Fangrui Song6907ce22018-07-30 19:24:48 +00003499
Guy Benyei11169dd2012-12-18 14:30:41 +00003500recurse:
3501 switch (E->getStmtClass()) {
3502 case Expr::NoStmtClass:
3503#define ABSTRACT_STMT(Type)
3504#define EXPR(Type, Base)
3505#define STMT(Type, Base) \
3506 case Expr::Type##Class:
3507#include "clang/AST/StmtNodes.inc"
3508 // fallthrough
3509
3510 // These all can only appear in local or variable-initialization
3511 // contexts and so should never appear in a mangling.
3512 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003513 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003514 case Expr::ImplicitValueInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +00003515 case Expr::ArrayInitLoopExprClass:
3516 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00003517 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003518 case Expr::ParenListExprClass:
3519 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00003520 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00003521 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00003522 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00003523 case Expr::OMPArraySectionExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00003524 case Expr::CXXInheritedCtorInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003525 llvm_unreachable("unexpected statement kind");
3526
3527 // FIXME: invent manglings for all these.
3528 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003529 case Expr::ChooseExprClass:
3530 case Expr::CompoundLiteralExprClass:
3531 case Expr::ExtVectorElementExprClass:
3532 case Expr::GenericSelectionExprClass:
3533 case Expr::ObjCEncodeExprClass:
3534 case Expr::ObjCIsaExprClass:
3535 case Expr::ObjCIvarRefExprClass:
3536 case Expr::ObjCMessageExprClass:
3537 case Expr::ObjCPropertyRefExprClass:
3538 case Expr::ObjCProtocolExprClass:
3539 case Expr::ObjCSelectorExprClass:
3540 case Expr::ObjCStringLiteralClass:
3541 case Expr::ObjCBoxedExprClass:
3542 case Expr::ObjCArrayLiteralClass:
3543 case Expr::ObjCDictionaryLiteralClass:
3544 case Expr::ObjCSubscriptRefExprClass:
3545 case Expr::ObjCIndirectCopyRestoreExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +00003546 case Expr::ObjCAvailabilityCheckExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 case Expr::OffsetOfExprClass:
3548 case Expr::PredefinedExprClass:
3549 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00003550 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003551 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003552 case Expr::TypeTraitExprClass:
3553 case Expr::ArrayTypeTraitExprClass:
3554 case Expr::ExpressionTraitExprClass:
3555 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003556 case Expr::CUDAKernelCallExprClass:
3557 case Expr::AsTypeExprClass:
3558 case Expr::PseudoObjectExprClass:
3559 case Expr::AtomicExprClass:
Leonard Chandb01c3a2018-06-20 17:19:40 +00003560 case Expr::FixedPointLiteralClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00003561 {
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00003562 if (!NullOut) {
3563 // As bad as this diagnostic is, it's better than crashing.
3564 DiagnosticsEngine &Diags = Context.getDiags();
3565 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3566 "cannot yet mangle expression type %0");
3567 Diags.Report(E->getExprLoc(), DiagID)
3568 << E->getStmtClassName() << E->getSourceRange();
3569 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003570 break;
3571 }
3572
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00003573 case Expr::CXXUuidofExprClass: {
3574 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3575 if (UE->isTypeOperand()) {
3576 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3577 Out << "u8__uuidoft";
3578 mangleType(UuidT);
3579 } else {
3580 Expr *UuidExp = UE->getExprOperand();
3581 Out << "u8__uuidofz";
3582 mangleExpression(UuidExp, Arity);
3583 }
3584 break;
3585 }
3586
Guy Benyei11169dd2012-12-18 14:30:41 +00003587 // Even gcc-4.5 doesn't mangle this.
3588 case Expr::BinaryConditionalOperatorClass: {
3589 DiagnosticsEngine &Diags = Context.getDiags();
3590 unsigned DiagID =
3591 Diags.getCustomDiagID(DiagnosticsEngine::Error,
3592 "?: operator with omitted middle operand cannot be mangled");
3593 Diags.Report(E->getExprLoc(), DiagID)
3594 << E->getStmtClassName() << E->getSourceRange();
3595 break;
3596 }
3597
3598 // These are used for internal purposes and cannot be meaningfully mangled.
3599 case Expr::OpaqueValueExprClass:
3600 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3601
3602 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003603 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00003604 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00003605 Out << "E";
3606 break;
3607 }
3608
Richard Smith39eca9b2017-08-23 22:12:08 +00003609 case Expr::DesignatedInitExprClass: {
3610 auto *DIE = cast<DesignatedInitExpr>(E);
3611 for (const auto &Designator : DIE->designators()) {
3612 if (Designator.isFieldDesignator()) {
3613 Out << "di";
3614 mangleSourceName(Designator.getFieldName());
3615 } else if (Designator.isArrayDesignator()) {
3616 Out << "dx";
3617 mangleExpression(DIE->getArrayIndex(Designator));
3618 } else {
3619 assert(Designator.isArrayRangeDesignator() &&
3620 "unknown designator kind");
3621 Out << "dX";
3622 mangleExpression(DIE->getArrayRangeStart(Designator));
3623 mangleExpression(DIE->getArrayRangeEnd(Designator));
3624 }
3625 }
3626 mangleExpression(DIE->getInit());
3627 break;
3628 }
3629
Guy Benyei11169dd2012-12-18 14:30:41 +00003630 case Expr::CXXDefaultArgExprClass:
3631 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3632 break;
3633
Richard Smith852c9db2013-04-20 22:23:05 +00003634 case Expr::CXXDefaultInitExprClass:
3635 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3636 break;
3637
Richard Smithcc1b96d2013-06-12 22:31:48 +00003638 case Expr::CXXStdInitializerListExprClass:
3639 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3640 break;
3641
Guy Benyei11169dd2012-12-18 14:30:41 +00003642 case Expr::SubstNonTypeTemplateParmExprClass:
3643 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3644 Arity);
3645 break;
3646
3647 case Expr::UserDefinedLiteralClass:
3648 // We follow g++'s approach of mangling a UDL as a call to the literal
3649 // operator.
3650 case Expr::CXXMemberCallExprClass: // fallthrough
3651 case Expr::CallExprClass: {
3652 const CallExpr *CE = cast<CallExpr>(E);
3653
3654 // <expression> ::= cp <simple-id> <expression>* E
3655 // We use this mangling only when the call would use ADL except
3656 // for being parenthesized. Per discussion with David
3657 // Vandervoorde, 2011.04.25.
3658 if (isParenthesizedADLCallee(CE)) {
3659 Out << "cp";
3660 // The callee here is a parenthesized UnresolvedLookupExpr with
3661 // no qualifier and should always get mangled as a <simple-id>
3662 // anyway.
3663
3664 // <expression> ::= cl <expression>* E
3665 } else {
3666 Out << "cl";
3667 }
3668
David Majnemer67a8ec62015-02-19 21:41:48 +00003669 unsigned CallArity = CE->getNumArgs();
3670 for (const Expr *Arg : CE->arguments())
3671 if (isa<PackExpansionExpr>(Arg))
3672 CallArity = UnknownArity;
3673
3674 mangleExpression(CE->getCallee(), CallArity);
3675 for (const Expr *Arg : CE->arguments())
3676 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003677 Out << 'E';
3678 break;
3679 }
3680
3681 case Expr::CXXNewExprClass: {
3682 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3683 if (New->isGlobalNew()) Out << "gs";
3684 Out << (New->isArray() ? "na" : "nw");
3685 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3686 E = New->placement_arg_end(); I != E; ++I)
3687 mangleExpression(*I);
3688 Out << '_';
3689 mangleType(New->getAllocatedType());
3690 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003691 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3692 Out << "il";
3693 else
3694 Out << "pi";
3695 const Expr *Init = New->getInitializer();
3696 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3697 // Directly inline the initializers.
3698 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3699 E = CCE->arg_end();
3700 I != E; ++I)
3701 mangleExpression(*I);
3702 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3703 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3704 mangleExpression(PLE->getExpr(i));
3705 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3706 isa<InitListExpr>(Init)) {
3707 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003708 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003709 } else
3710 mangleExpression(Init);
3711 }
3712 Out << 'E';
3713 break;
3714 }
3715
David Majnemer1dabfdc2015-02-14 13:23:54 +00003716 case Expr::CXXPseudoDestructorExprClass: {
3717 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3718 if (const Expr *Base = PDE->getBase())
3719 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003720 NestedNameSpecifier *Qualifier = PDE->getQualifier();
David Majnemerb8014dd2015-02-19 02:16:16 +00003721 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3722 if (Qualifier) {
3723 mangleUnresolvedPrefix(Qualifier,
3724 /*Recursive=*/true);
3725 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3726 Out << 'E';
3727 } else {
3728 Out << "sr";
3729 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3730 Out << 'E';
3731 }
3732 } else if (Qualifier) {
3733 mangleUnresolvedPrefix(Qualifier);
3734 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003735 // <base-unresolved-name> ::= dn <destructor-name>
3736 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003737 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003738 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003739 break;
3740 }
3741
Guy Benyei11169dd2012-12-18 14:30:41 +00003742 case Expr::MemberExprClass: {
3743 const MemberExpr *ME = cast<MemberExpr>(E);
3744 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003745 ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003746 ME->getMemberDecl()->getDeclName(),
3747 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3748 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003749 break;
3750 }
3751
3752 case Expr::UnresolvedMemberExprClass: {
3753 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003754 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3755 ME->isArrow(), ME->getQualifier(), nullptr,
Richard Smithafecd832016-10-24 20:47:04 +00003756 ME->getMemberName(),
3757 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3758 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003759 break;
3760 }
3761
3762 case Expr::CXXDependentScopeMemberExprClass: {
3763 const CXXDependentScopeMemberExpr *ME
3764 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003765 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3766 ME->isArrow(), ME->getQualifier(),
3767 ME->getFirstQualifierFoundInScope(),
Richard Smithafecd832016-10-24 20:47:04 +00003768 ME->getMember(),
3769 ME->getTemplateArgs(), ME->getNumTemplateArgs(),
3770 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003771 break;
3772 }
3773
3774 case Expr::UnresolvedLookupExprClass: {
3775 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00003776 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
3777 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
3778 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003779 break;
3780 }
3781
3782 case Expr::CXXUnresolvedConstructExprClass: {
3783 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3784 unsigned N = CE->arg_size();
3785
Richard Smith39eca9b2017-08-23 22:12:08 +00003786 if (CE->isListInitialization()) {
3787 assert(N == 1 && "unexpected form for list initialization");
3788 auto *IL = cast<InitListExpr>(CE->getArg(0));
3789 Out << "tl";
3790 mangleType(CE->getType());
3791 mangleInitListElements(IL);
3792 Out << "E";
3793 return;
3794 }
3795
Guy Benyei11169dd2012-12-18 14:30:41 +00003796 Out << "cv";
3797 mangleType(CE->getType());
3798 if (N != 1) Out << '_';
3799 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3800 if (N != 1) Out << 'E';
3801 break;
3802 }
3803
Guy Benyei11169dd2012-12-18 14:30:41 +00003804 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003805 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003806 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003807 assert(
3808 CE->getNumArgs() >= 1 &&
3809 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3810 "implicit CXXConstructExpr must have one argument");
3811 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3812 }
3813 Out << "il";
3814 for (auto *E : CE->arguments())
3815 mangleExpression(E);
3816 Out << "E";
3817 break;
3818 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003819
Richard Smith520449d2015-02-05 06:15:50 +00003820 case Expr::CXXTemporaryObjectExprClass: {
3821 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3822 unsigned N = CE->getNumArgs();
3823 bool List = CE->isListInitialization();
3824
3825 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003826 Out << "tl";
3827 else
3828 Out << "cv";
3829 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003830 if (!List && N != 1)
3831 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003832 if (CE->isStdInitListInitialization()) {
3833 // We implicitly created a std::initializer_list<T> for the first argument
3834 // of a constructor of type U in an expression of the form U{a, b, c}.
3835 // Strip all the semantic gunk off the initializer list.
3836 auto *SILE =
3837 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3838 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3839 mangleInitListElements(ILE);
3840 } else {
3841 for (auto *E : CE->arguments())
3842 mangleExpression(E);
3843 }
Richard Smith520449d2015-02-05 06:15:50 +00003844 if (List || N != 1)
3845 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003846 break;
3847 }
3848
3849 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003850 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003851 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003852 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003853 break;
3854
3855 case Expr::CXXNoexceptExprClass:
3856 Out << "nx";
3857 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3858 break;
3859
3860 case Expr::UnaryExprOrTypeTraitExprClass: {
3861 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
Fangrui Song6907ce22018-07-30 19:24:48 +00003862
Guy Benyei11169dd2012-12-18 14:30:41 +00003863 if (!SAE->isInstantiationDependent()) {
3864 // Itanium C++ ABI:
Fangrui Song6907ce22018-07-30 19:24:48 +00003865 // If the operand of a sizeof or alignof operator is not
3866 // instantiation-dependent it is encoded as an integer literal
Guy Benyei11169dd2012-12-18 14:30:41 +00003867 // reflecting the result of the operator.
3868 //
Fangrui Song6907ce22018-07-30 19:24:48 +00003869 // If the result of the operator is implicitly converted to a known
3870 // integer type, that type is used for the literal; otherwise, the type
Guy Benyei11169dd2012-12-18 14:30:41 +00003871 // of std::size_t or std::ptrdiff_t is used.
Fangrui Song6907ce22018-07-30 19:24:48 +00003872 QualType T = (ImplicitlyConvertedToType.isNull() ||
Guy Benyei11169dd2012-12-18 14:30:41 +00003873 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3874 : ImplicitlyConvertedToType;
3875 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3876 mangleIntegerLiteral(T, V);
3877 break;
3878 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003879
Guy Benyei11169dd2012-12-18 14:30:41 +00003880 switch(SAE->getKind()) {
3881 case UETT_SizeOf:
3882 Out << 's';
3883 break;
3884 case UETT_AlignOf:
3885 Out << 'a';
3886 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003887 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003888 DiagnosticsEngine &Diags = Context.getDiags();
3889 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3890 "cannot yet mangle vec_step expression");
3891 Diags.Report(DiagID);
3892 return;
3893 }
Alexey Bataev00396512015-07-02 03:40:19 +00003894 case UETT_OpenMPRequiredSimdAlign:
3895 DiagnosticsEngine &Diags = Context.getDiags();
3896 unsigned DiagID = Diags.getCustomDiagID(
3897 DiagnosticsEngine::Error,
3898 "cannot yet mangle __builtin_omp_required_simd_align expression");
3899 Diags.Report(DiagID);
3900 return;
3901 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003902 if (SAE->isArgumentType()) {
3903 Out << 't';
3904 mangleType(SAE->getArgumentType());
3905 } else {
3906 Out << 'z';
3907 mangleExpression(SAE->getArgumentExpr());
3908 }
3909 break;
3910 }
3911
3912 case Expr::CXXThrowExprClass: {
3913 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003914 // <expression> ::= tw <expression> # throw expression
3915 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003916 if (TE->getSubExpr()) {
3917 Out << "tw";
3918 mangleExpression(TE->getSubExpr());
3919 } else {
3920 Out << "tr";
3921 }
3922 break;
3923 }
3924
3925 case Expr::CXXTypeidExprClass: {
3926 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003927 // <expression> ::= ti <type> # typeid (type)
3928 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003929 if (TIE->isTypeOperand()) {
3930 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003931 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003932 } else {
3933 Out << "te";
3934 mangleExpression(TIE->getExprOperand());
3935 }
3936 break;
3937 }
3938
3939 case Expr::CXXDeleteExprClass: {
3940 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003941 // <expression> ::= [gs] dl <expression> # [::] delete expr
3942 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003943 if (DE->isGlobalDelete()) Out << "gs";
3944 Out << (DE->isArrayForm() ? "da" : "dl");
3945 mangleExpression(DE->getArgument());
3946 break;
3947 }
3948
3949 case Expr::UnaryOperatorClass: {
3950 const UnaryOperator *UO = cast<UnaryOperator>(E);
3951 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3952 /*Arity=*/1);
3953 mangleExpression(UO->getSubExpr());
3954 break;
3955 }
3956
3957 case Expr::ArraySubscriptExprClass: {
3958 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3959
3960 // Array subscript is treated as a syntactically weird form of
3961 // binary operator.
3962 Out << "ix";
3963 mangleExpression(AE->getLHS());
3964 mangleExpression(AE->getRHS());
3965 break;
3966 }
3967
3968 case Expr::CompoundAssignOperatorClass: // fallthrough
3969 case Expr::BinaryOperatorClass: {
3970 const BinaryOperator *BO = cast<BinaryOperator>(E);
3971 if (BO->getOpcode() == BO_PtrMemD)
3972 Out << "ds";
3973 else
3974 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3975 /*Arity=*/2);
3976 mangleExpression(BO->getLHS());
3977 mangleExpression(BO->getRHS());
3978 break;
3979 }
3980
3981 case Expr::ConditionalOperatorClass: {
3982 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3983 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3984 mangleExpression(CO->getCond());
3985 mangleExpression(CO->getLHS(), Arity);
3986 mangleExpression(CO->getRHS(), Arity);
3987 break;
3988 }
3989
3990 case Expr::ImplicitCastExprClass: {
3991 ImplicitlyConvertedToType = E->getType();
3992 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3993 goto recurse;
3994 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003995
Guy Benyei11169dd2012-12-18 14:30:41 +00003996 case Expr::ObjCBridgedCastExprClass: {
Fangrui Song6907ce22018-07-30 19:24:48 +00003997 // Mangle ownership casts as a vendor extended operator __bridge,
Guy Benyei11169dd2012-12-18 14:30:41 +00003998 // __bridge_transfer, or __bridge_retain.
3999 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
4000 Out << "v1U" << Kind.size() << Kind;
4001 }
4002 // Fall through to mangle the cast itself.
Galina Kistanovaf87496d2017-06-03 06:31:42 +00004003 LLVM_FALLTHROUGH;
Fangrui Song6907ce22018-07-30 19:24:48 +00004004
Guy Benyei11169dd2012-12-18 14:30:41 +00004005 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00004006 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00004007 break;
David Majnemer9c775c72014-09-23 04:27:55 +00004008
Richard Smith520449d2015-02-05 06:15:50 +00004009 case Expr::CXXFunctionalCastExprClass: {
4010 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
4011 // FIXME: Add isImplicit to CXXConstructExpr.
4012 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
4013 if (CCE->getParenOrBraceRange().isInvalid())
4014 Sub = CCE->getArg(0)->IgnoreImplicit();
4015 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
4016 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
4017 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
4018 Out << "tl";
4019 mangleType(E->getType());
4020 mangleInitListElements(IL);
4021 Out << "E";
4022 } else {
4023 mangleCastExpression(E, "cv");
4024 }
4025 break;
4026 }
4027
David Majnemer9c775c72014-09-23 04:27:55 +00004028 case Expr::CXXStaticCastExprClass:
4029 mangleCastExpression(E, "sc");
4030 break;
4031 case Expr::CXXDynamicCastExprClass:
4032 mangleCastExpression(E, "dc");
4033 break;
4034 case Expr::CXXReinterpretCastExprClass:
4035 mangleCastExpression(E, "rc");
4036 break;
4037 case Expr::CXXConstCastExprClass:
4038 mangleCastExpression(E, "cc");
4039 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004040
4041 case Expr::CXXOperatorCallExprClass: {
4042 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
4043 unsigned NumArgs = CE->getNumArgs();
Richard Smith4631be72016-10-24 20:29:40 +00004044 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
4045 // (the enclosing MemberExpr covers the syntactic portion).
4046 if (CE->getOperator() != OO_Arrow)
4047 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00004048 // Mangle the arguments.
4049 for (unsigned i = 0; i != NumArgs; ++i)
4050 mangleExpression(CE->getArg(i));
4051 break;
4052 }
4053
4054 case Expr::ParenExprClass:
4055 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
4056 break;
4057
4058 case Expr::DeclRefExprClass: {
4059 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
4060
4061 switch (D->getKind()) {
4062 default:
4063 // <expr-primary> ::= L <mangled-name> E # external name
4064 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004065 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004066 Out << 'E';
4067 break;
4068
4069 case Decl::ParmVar:
4070 mangleFunctionParam(cast<ParmVarDecl>(D));
4071 break;
4072
4073 case Decl::EnumConstant: {
4074 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
4075 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
4076 break;
4077 }
4078
4079 case Decl::NonTypeTemplateParm: {
4080 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
4081 mangleTemplateParameter(PD->getIndex());
4082 break;
4083 }
4084
4085 }
4086
4087 break;
4088 }
4089
4090 case Expr::SubstNonTypeTemplateParmPackExprClass:
4091 // FIXME: not clear how to mangle this!
4092 // template <unsigned N...> class A {
4093 // template <class U...> void foo(U (&x)[N]...);
4094 // };
4095 Out << "_SUBSTPACK_";
4096 break;
4097
4098 case Expr::FunctionParmPackExprClass: {
4099 // FIXME: not clear how to mangle this!
4100 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
4101 Out << "v110_SUBSTPACK";
4102 mangleFunctionParam(FPPE->getParameterPack());
4103 break;
4104 }
4105
4106 case Expr::DependentScopeDeclRefExprClass: {
4107 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Richard Smithafecd832016-10-24 20:47:04 +00004108 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
4109 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
4110 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00004111 break;
4112 }
4113
4114 case Expr::CXXBindTemporaryExprClass:
4115 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
4116 break;
4117
4118 case Expr::ExprWithCleanupsClass:
4119 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
4120 break;
4121
4122 case Expr::FloatingLiteralClass: {
4123 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
4124 Out << 'L';
4125 mangleType(FL->getType());
4126 mangleFloat(FL->getValue());
4127 Out << 'E';
4128 break;
4129 }
4130
4131 case Expr::CharacterLiteralClass:
4132 Out << 'L';
4133 mangleType(E->getType());
4134 Out << cast<CharacterLiteral>(E)->getValue();
4135 Out << 'E';
4136 break;
4137
4138 // FIXME. __objc_yes/__objc_no are mangled same as true/false
4139 case Expr::ObjCBoolLiteralExprClass:
4140 Out << "Lb";
4141 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4142 Out << 'E';
4143 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004144
Guy Benyei11169dd2012-12-18 14:30:41 +00004145 case Expr::CXXBoolLiteralExprClass:
4146 Out << "Lb";
4147 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
4148 Out << 'E';
4149 break;
4150
4151 case Expr::IntegerLiteralClass: {
4152 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
4153 if (E->getType()->isSignedIntegerType())
4154 Value.setIsSigned(true);
4155 mangleIntegerLiteral(E->getType(), Value);
4156 break;
4157 }
4158
4159 case Expr::ImaginaryLiteralClass: {
4160 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
4161 // Mangle as if a complex literal.
4162 // Proposal from David Vandevoorde, 2010.06.30.
4163 Out << 'L';
4164 mangleType(E->getType());
4165 if (const FloatingLiteral *Imag =
4166 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
4167 // Mangle a floating-point zero of the appropriate type.
4168 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
4169 Out << '_';
4170 mangleFloat(Imag->getValue());
4171 } else {
4172 Out << "0_";
4173 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
4174 if (IE->getSubExpr()->getType()->isSignedIntegerType())
4175 Value.setIsSigned(true);
4176 mangleNumber(Value);
4177 }
4178 Out << 'E';
4179 break;
4180 }
4181
4182 case Expr::StringLiteralClass: {
4183 // Revised proposal from David Vandervoorde, 2010.07.15.
4184 Out << 'L';
4185 assert(isa<ConstantArrayType>(E->getType()));
4186 mangleType(E->getType());
4187 Out << 'E';
4188 break;
4189 }
4190
4191 case Expr::GNUNullExprClass:
4192 // FIXME: should this really be mangled the same as nullptr?
4193 // fallthrough
4194
4195 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00004196 Out << "LDnE";
4197 break;
4198 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004199
Guy Benyei11169dd2012-12-18 14:30:41 +00004200 case Expr::PackExpansionExprClass:
4201 Out << "sp";
4202 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
4203 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004204
Guy Benyei11169dd2012-12-18 14:30:41 +00004205 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00004206 auto *SPE = cast<SizeOfPackExpr>(E);
4207 if (SPE->isPartiallySubstituted()) {
4208 Out << "sP";
4209 for (const auto &A : SPE->getPartialArguments())
4210 mangleTemplateArg(A);
4211 Out << "E";
4212 break;
4213 }
4214
Guy Benyei11169dd2012-12-18 14:30:41 +00004215 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00004216 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00004217 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
4218 mangleTemplateParameter(TTP->getIndex());
4219 else if (const NonTypeTemplateParmDecl *NTTP
4220 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
4221 mangleTemplateParameter(NTTP->getIndex());
4222 else if (const TemplateTemplateParmDecl *TempTP
4223 = dyn_cast<TemplateTemplateParmDecl>(Pack))
4224 mangleTemplateParameter(TempTP->getIndex());
4225 else
4226 mangleFunctionParam(cast<ParmVarDecl>(Pack));
4227 break;
4228 }
Richard Smith0f0af192014-11-08 05:07:16 +00004229
Guy Benyei11169dd2012-12-18 14:30:41 +00004230 case Expr::MaterializeTemporaryExprClass: {
4231 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
4232 break;
4233 }
Richard Smith0f0af192014-11-08 05:07:16 +00004234
4235 case Expr::CXXFoldExprClass: {
4236 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00004237 if (FE->isLeftFold())
4238 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00004239 else
Richard Smith8e6923b2014-11-10 19:44:15 +00004240 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00004241
4242 if (FE->getOperator() == BO_PtrMemD)
4243 Out << "ds";
4244 else
4245 mangleOperatorName(
4246 BinaryOperator::getOverloadedOperator(FE->getOperator()),
4247 /*Arity=*/2);
4248
4249 if (FE->getLHS())
4250 mangleExpression(FE->getLHS());
4251 if (FE->getRHS())
4252 mangleExpression(FE->getRHS());
4253 break;
4254 }
4255
Guy Benyei11169dd2012-12-18 14:30:41 +00004256 case Expr::CXXThisExprClass:
4257 Out << "fpT";
4258 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00004259
4260 case Expr::CoawaitExprClass:
4261 // FIXME: Propose a non-vendor mangling.
4262 Out << "v18co_await";
4263 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4264 break;
4265
Eric Fiselier20f25cb2017-03-06 23:38:15 +00004266 case Expr::DependentCoawaitExprClass:
4267 // FIXME: Propose a non-vendor mangling.
4268 Out << "v18co_await";
4269 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
4270 break;
4271
Richard Smith9f690bd2015-10-27 06:02:45 +00004272 case Expr::CoyieldExprClass:
4273 // FIXME: Propose a non-vendor mangling.
4274 Out << "v18co_yield";
4275 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
4276 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004277 }
4278}
4279
4280/// Mangle an expression which refers to a parameter variable.
4281///
4282/// <expression> ::= <function-param>
4283/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
4284/// <function-param> ::= fp <top-level CV-qualifiers>
4285/// <parameter-2 non-negative number> _ # L == 0, I > 0
4286/// <function-param> ::= fL <L-1 non-negative number>
4287/// p <top-level CV-qualifiers> _ # L > 0, I == 0
4288/// <function-param> ::= fL <L-1 non-negative number>
4289/// p <top-level CV-qualifiers>
4290/// <I-1 non-negative number> _ # L > 0, I > 0
4291///
4292/// L is the nesting depth of the parameter, defined as 1 if the
4293/// parameter comes from the innermost function prototype scope
4294/// enclosing the current context, 2 if from the next enclosing
4295/// function prototype scope, and so on, with one special case: if
4296/// we've processed the full parameter clause for the innermost
4297/// function type, then L is one less. This definition conveniently
4298/// makes it irrelevant whether a function's result type was written
4299/// trailing or leading, but is otherwise overly complicated; the
4300/// numbering was first designed without considering references to
4301/// parameter in locations other than return types, and then the
4302/// mangling had to be generalized without changing the existing
4303/// manglings.
4304///
4305/// I is the zero-based index of the parameter within its parameter
4306/// declaration clause. Note that the original ABI document describes
4307/// this using 1-based ordinals.
4308void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
4309 unsigned parmDepth = parm->getFunctionScopeDepth();
4310 unsigned parmIndex = parm->getFunctionScopeIndex();
4311
4312 // Compute 'L'.
4313 // parmDepth does not include the declaring function prototype.
4314 // FunctionTypeDepth does account for that.
4315 assert(parmDepth < FunctionTypeDepth.getDepth());
4316 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
4317 if (FunctionTypeDepth.isInResultType())
4318 nestingDepth--;
4319
4320 if (nestingDepth == 0) {
4321 Out << "fp";
4322 } else {
4323 Out << "fL" << (nestingDepth - 1) << 'p';
4324 }
4325
4326 // Top-level qualifiers. We don't have to worry about arrays here,
4327 // because parameters declared as arrays should already have been
4328 // transformed to have pointer type. FIXME: apparently these don't
4329 // get mangled if used as an rvalue of a known non-class type?
4330 assert(!parm->getType()->isArrayType()
4331 && "parameter's type is still an array type?");
Andrew Gozillon572bbb02017-10-02 06:25:51 +00004332
4333 if (const DependentAddressSpaceType *DAST =
4334 dyn_cast<DependentAddressSpaceType>(parm->getType())) {
4335 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
4336 } else {
4337 mangleQualifiers(parm->getType().getQualifiers());
4338 }
Guy Benyei11169dd2012-12-18 14:30:41 +00004339
4340 // Parameter index.
4341 if (parmIndex != 0) {
4342 Out << (parmIndex - 1);
4343 }
4344 Out << '_';
4345}
4346
Richard Smith5179eb72016-06-28 19:03:57 +00004347void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4348 const CXXRecordDecl *InheritedFrom) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004349 // <ctor-dtor-name> ::= C1 # complete object constructor
4350 // ::= C2 # base object constructor
Richard Smith5179eb72016-06-28 19:03:57 +00004351 // ::= CI1 <type> # complete inheriting constructor
4352 // ::= CI2 <type> # base inheriting constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00004353 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004354 // In addition, C5 is a comdat name with C1 and C2 in it.
Richard Smith5179eb72016-06-28 19:03:57 +00004355 Out << 'C';
4356 if (InheritedFrom)
4357 Out << 'I';
Guy Benyei11169dd2012-12-18 14:30:41 +00004358 switch (T) {
4359 case Ctor_Complete:
Richard Smith5179eb72016-06-28 19:03:57 +00004360 Out << '1';
Guy Benyei11169dd2012-12-18 14:30:41 +00004361 break;
4362 case Ctor_Base:
Richard Smith5179eb72016-06-28 19:03:57 +00004363 Out << '2';
Guy Benyei11169dd2012-12-18 14:30:41 +00004364 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004365 case Ctor_Comdat:
Richard Smith5179eb72016-06-28 19:03:57 +00004366 Out << '5';
Guy Benyei11169dd2012-12-18 14:30:41 +00004367 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00004368 case Ctor_DefaultClosure:
4369 case Ctor_CopyingClosure:
4370 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00004371 }
Richard Smith5179eb72016-06-28 19:03:57 +00004372 if (InheritedFrom)
4373 mangleName(InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00004374}
4375
4376void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4377 // <ctor-dtor-name> ::= D0 # deleting destructor
4378 // ::= D1 # complete object destructor
4379 // ::= D2 # base object destructor
4380 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00004381 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00004382 switch (T) {
4383 case Dtor_Deleting:
4384 Out << "D0";
4385 break;
4386 case Dtor_Complete:
4387 Out << "D1";
4388 break;
4389 case Dtor_Base:
4390 Out << "D2";
4391 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00004392 case Dtor_Comdat:
4393 Out << "D5";
4394 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00004395 }
4396}
4397
James Y Knight04ec5bf2015-12-24 02:59:37 +00004398void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4399 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004400 // <template-args> ::= I <template-arg>+ E
4401 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00004402 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4403 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00004404 Out << 'E';
4405}
4406
4407void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4408 // <template-args> ::= I <template-arg>+ E
4409 Out << 'I';
4410 for (unsigned i = 0, e = AL.size(); i != e; ++i)
4411 mangleTemplateArg(AL[i]);
4412 Out << 'E';
4413}
4414
4415void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4416 unsigned NumTemplateArgs) {
4417 // <template-args> ::= I <template-arg>+ E
4418 Out << 'I';
4419 for (unsigned i = 0; i != NumTemplateArgs; ++i)
4420 mangleTemplateArg(TemplateArgs[i]);
4421 Out << 'E';
4422}
4423
4424void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4425 // <template-arg> ::= <type> # type or template
4426 // ::= X <expression> E # expression
4427 // ::= <expr-primary> # simple expressions
4428 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00004429 if (!A.isInstantiationDependent() || A.isDependent())
4430 A = Context.getASTContext().getCanonicalTemplateArgument(A);
Fangrui Song6907ce22018-07-30 19:24:48 +00004431
Guy Benyei11169dd2012-12-18 14:30:41 +00004432 switch (A.getKind()) {
4433 case TemplateArgument::Null:
4434 llvm_unreachable("Cannot mangle NULL template argument");
Fangrui Song6907ce22018-07-30 19:24:48 +00004435
Guy Benyei11169dd2012-12-18 14:30:41 +00004436 case TemplateArgument::Type:
4437 mangleType(A.getAsType());
4438 break;
4439 case TemplateArgument::Template:
4440 // This is mangled as <type>.
4441 mangleType(A.getAsTemplate());
4442 break;
4443 case TemplateArgument::TemplateExpansion:
4444 // <type> ::= Dp <type> # pack expansion (C++0x)
4445 Out << "Dp";
4446 mangleType(A.getAsTemplateOrTemplatePattern());
4447 break;
4448 case TemplateArgument::Expression: {
4449 // It's possible to end up with a DeclRefExpr here in certain
4450 // dependent cases, in which case we should mangle as a
4451 // declaration.
4452 const Expr *E = A.getAsExpr()->IgnoreParens();
4453 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4454 const ValueDecl *D = DRE->getDecl();
4455 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00004456 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00004457 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004458 Out << 'E';
4459 break;
4460 }
4461 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004462
Guy Benyei11169dd2012-12-18 14:30:41 +00004463 Out << 'X';
4464 mangleExpression(E);
4465 Out << 'E';
4466 break;
4467 }
4468 case TemplateArgument::Integral:
4469 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4470 break;
4471 case TemplateArgument::Declaration: {
4472 // <expr-primary> ::= L <mangled-name> E # external name
4473 // Clang produces AST's where pointer-to-member-function expressions
4474 // and pointer-to-function expressions are represented as a declaration not
4475 // an expression. We compensate for it here to produce the correct mangling.
4476 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00004477 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00004478 if (compensateMangling) {
4479 Out << 'X';
4480 mangleOperatorName(OO_Amp, 1);
4481 }
4482
4483 Out << 'L';
4484 // References to external entities use the mangled name; if the name would
Nico Weberfb420782016-05-25 14:15:08 +00004485 // not normally be mangled then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00004486 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004487 Out << 'E';
4488
4489 if (compensateMangling)
4490 Out << 'E';
4491
4492 break;
4493 }
4494 case TemplateArgument::NullPtr: {
4495 // <expr-primary> ::= L <type> 0 E
4496 Out << 'L';
4497 mangleType(A.getNullPtrType());
4498 Out << "0E";
4499 break;
4500 }
4501 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00004502 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00004503 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00004504 for (const auto &P : A.pack_elements())
4505 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00004506 Out << 'E';
4507 }
4508 }
4509}
4510
4511void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4512 // <template-param> ::= T_ # first template parameter
4513 // ::= T <parameter-2 non-negative number> _
4514 if (Index == 0)
4515 Out << "T_";
4516 else
4517 Out << 'T' << (Index - 1) << '_';
4518}
4519
David Majnemer3b3bdb52014-05-06 22:49:16 +00004520void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4521 if (SeqID == 1)
4522 Out << '0';
4523 else if (SeqID > 1) {
4524 SeqID--;
4525
4526 // <seq-id> is encoded in base-36, using digits and upper case letters.
4527 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00004528 MutableArrayRef<char> BufferRef(Buffer);
4529 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00004530
4531 for (; SeqID != 0; SeqID /= 36) {
4532 unsigned C = SeqID % 36;
4533 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4534 }
4535
4536 Out.write(I.base(), I - BufferRef.rbegin());
4537 }
4538 Out << '_';
4539}
4540
Guy Benyei11169dd2012-12-18 14:30:41 +00004541void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4542 bool result = mangleSubstitution(tname);
4543 assert(result && "no existing substitution for template name");
4544 (void) result;
4545}
4546
4547// <substitution> ::= S <seq-id> _
4548// ::= S_
4549bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4550 // Try one of the standard substitutions first.
4551 if (mangleStandardSubstitution(ND))
4552 return true;
4553
4554 ND = cast<NamedDecl>(ND->getCanonicalDecl());
4555 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4556}
4557
Justin Bognere8d762e2015-05-22 06:48:13 +00004558/// Determine whether the given type has any qualifiers that are relevant for
4559/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00004560static bool hasMangledSubstitutionQualifiers(QualType T) {
4561 Qualifiers Qs = T.getQualifiers();
Roger Ferrer Ibanezfd9384a2017-06-02 07:14:34 +00004562 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
Guy Benyei11169dd2012-12-18 14:30:41 +00004563}
4564
4565bool CXXNameMangler::mangleSubstitution(QualType T) {
4566 if (!hasMangledSubstitutionQualifiers(T)) {
4567 if (const RecordType *RT = T->getAs<RecordType>())
4568 return mangleSubstitution(RT->getDecl());
4569 }
4570
4571 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4572
4573 return mangleSubstitution(TypePtr);
4574}
4575
4576bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4577 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4578 return mangleSubstitution(TD);
Fangrui Song6907ce22018-07-30 19:24:48 +00004579
Guy Benyei11169dd2012-12-18 14:30:41 +00004580 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4581 return mangleSubstitution(
4582 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4583}
4584
4585bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4586 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4587 if (I == Substitutions.end())
4588 return false;
4589
4590 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00004591 Out << 'S';
4592 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00004593
4594 return true;
4595}
4596
4597static bool isCharType(QualType T) {
4598 if (T.isNull())
4599 return false;
4600
4601 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4602 T->isSpecificBuiltinType(BuiltinType::Char_U);
4603}
4604
Justin Bognere8d762e2015-05-22 06:48:13 +00004605/// Returns whether a given type is a template specialization of a given name
4606/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00004607static bool isCharSpecialization(QualType T, const char *Name) {
4608 if (T.isNull())
4609 return false;
4610
4611 const RecordType *RT = T->getAs<RecordType>();
4612 if (!RT)
4613 return false;
4614
4615 const ClassTemplateSpecializationDecl *SD =
4616 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4617 if (!SD)
4618 return false;
4619
4620 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4621 return false;
4622
4623 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4624 if (TemplateArgs.size() != 1)
4625 return false;
4626
4627 if (!isCharType(TemplateArgs[0].getAsType()))
4628 return false;
4629
4630 return SD->getIdentifier()->getName() == Name;
4631}
4632
4633template <std::size_t StrLen>
4634static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4635 const char (&Str)[StrLen]) {
4636 if (!SD->getIdentifier()->isStr(Str))
4637 return false;
4638
4639 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4640 if (TemplateArgs.size() != 2)
4641 return false;
4642
4643 if (!isCharType(TemplateArgs[0].getAsType()))
4644 return false;
4645
4646 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4647 return false;
4648
4649 return true;
4650}
4651
4652bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4653 // <substitution> ::= St # ::std::
4654 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4655 if (isStd(NS)) {
4656 Out << "St";
4657 return true;
4658 }
4659 }
4660
4661 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4662 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4663 return false;
4664
4665 // <substitution> ::= Sa # ::std::allocator
4666 if (TD->getIdentifier()->isStr("allocator")) {
4667 Out << "Sa";
4668 return true;
4669 }
4670
4671 // <<substitution> ::= Sb # ::std::basic_string
4672 if (TD->getIdentifier()->isStr("basic_string")) {
4673 Out << "Sb";
4674 return true;
4675 }
4676 }
4677
4678 if (const ClassTemplateSpecializationDecl *SD =
4679 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4680 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4681 return false;
4682
4683 // <substitution> ::= Ss # ::std::basic_string<char,
4684 // ::std::char_traits<char>,
4685 // ::std::allocator<char> >
4686 if (SD->getIdentifier()->isStr("basic_string")) {
4687 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4688
4689 if (TemplateArgs.size() != 3)
4690 return false;
4691
4692 if (!isCharType(TemplateArgs[0].getAsType()))
4693 return false;
4694
4695 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4696 return false;
4697
4698 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4699 return false;
4700
4701 Out << "Ss";
4702 return true;
4703 }
4704
4705 // <substitution> ::= Si # ::std::basic_istream<char,
4706 // ::std::char_traits<char> >
4707 if (isStreamCharSpecialization(SD, "basic_istream")) {
4708 Out << "Si";
4709 return true;
4710 }
4711
4712 // <substitution> ::= So # ::std::basic_ostream<char,
4713 // ::std::char_traits<char> >
4714 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4715 Out << "So";
4716 return true;
4717 }
4718
4719 // <substitution> ::= Sd # ::std::basic_iostream<char,
4720 // ::std::char_traits<char> >
4721 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4722 Out << "Sd";
4723 return true;
4724 }
4725 }
4726 return false;
4727}
4728
4729void CXXNameMangler::addSubstitution(QualType T) {
4730 if (!hasMangledSubstitutionQualifiers(T)) {
4731 if (const RecordType *RT = T->getAs<RecordType>()) {
4732 addSubstitution(RT->getDecl());
4733 return;
4734 }
4735 }
4736
4737 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4738 addSubstitution(TypePtr);
4739}
4740
4741void CXXNameMangler::addSubstitution(TemplateName Template) {
4742 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4743 return addSubstitution(TD);
Fangrui Song6907ce22018-07-30 19:24:48 +00004744
Guy Benyei11169dd2012-12-18 14:30:41 +00004745 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4746 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4747}
4748
4749void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4750 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4751 Substitutions[Ptr] = SeqID++;
4752}
4753
Dmitry Polukhinfda467b2016-09-21 08:27:03 +00004754void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
4755 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
4756 if (Other->SeqID > SeqID) {
4757 Substitutions.swap(Other->Substitutions);
4758 SeqID = Other->SeqID;
4759 }
4760}
4761
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004762CXXNameMangler::AbiTagList
4763CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4764 // When derived abi tags are disabled there is no need to make any list.
4765 if (DisableDerivedAbiTags)
4766 return AbiTagList();
4767
4768 llvm::raw_null_ostream NullOutStream;
4769 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4770 TrackReturnTypeTags.disableDerivedAbiTags();
4771
4772 const FunctionProtoType *Proto =
4773 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004774 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004775 TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4776 TrackReturnTypeTags.mangleType(Proto->getReturnType());
4777 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
Dmitry Polukhind4b3bbc2017-06-14 09:47:47 +00004778 TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004779
4780 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4781}
4782
4783CXXNameMangler::AbiTagList
4784CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4785 // When derived abi tags are disabled there is no need to make any list.
4786 if (DisableDerivedAbiTags)
4787 return AbiTagList();
4788
4789 llvm::raw_null_ostream NullOutStream;
4790 CXXNameMangler TrackVariableType(*this, NullOutStream);
4791 TrackVariableType.disableDerivedAbiTags();
4792
4793 TrackVariableType.mangleType(VD->getType());
4794
4795 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4796}
4797
4798bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4799 const VarDecl *VD) {
4800 llvm::raw_null_ostream NullOutStream;
4801 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4802 TrackAbiTags.mangle(VD);
4803 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4804}
4805
Guy Benyei11169dd2012-12-18 14:30:41 +00004806//
4807
Justin Bognere8d762e2015-05-22 06:48:13 +00004808/// Mangles the name of the declaration D and emits that name to the given
4809/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004810///
4811/// If the declaration D requires a mangled name, this routine will emit that
4812/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4813/// and this routine will return false. In this case, the caller should just
4814/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4815/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004816void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4817 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004818 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4819 "Invalid mangleName() call, argument is not a variable or function!");
4820 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4821 "Invalid mangleName() call on 'structor decl!");
4822
4823 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4824 getASTContext().getSourceManager(),
4825 "Mangling declaration");
4826
4827 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004828 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004829}
4830
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004831void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4832 CXXCtorType Type,
4833 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004834 CXXNameMangler Mangler(*this, Out, D, Type);
4835 Mangler.mangle(D);
4836}
4837
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004838void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4839 CXXDtorType Type,
4840 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004841 CXXNameMangler Mangler(*this, Out, D, Type);
4842 Mangler.mangle(D);
4843}
4844
Rafael Espindola1e4df922014-09-16 15:18:21 +00004845void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4846 raw_ostream &Out) {
4847 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4848 Mangler.mangle(D);
4849}
4850
4851void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4852 raw_ostream &Out) {
4853 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4854 Mangler.mangle(D);
4855}
4856
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004857void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4858 const ThunkInfo &Thunk,
4859 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004860 // <special-name> ::= T <call-offset> <base encoding>
4861 // # base is the nominal target function of thunk
4862 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4863 // # base is the nominal target function of thunk
4864 // # first call-offset is 'this' adjustment
4865 // # second call-offset is result adjustment
Fangrui Song6907ce22018-07-30 19:24:48 +00004866
Guy Benyei11169dd2012-12-18 14:30:41 +00004867 assert(!isa<CXXDestructorDecl>(MD) &&
4868 "Use mangleCXXDtor for destructor decls!");
4869 CXXNameMangler Mangler(*this, Out);
4870 Mangler.getStream() << "_ZT";
4871 if (!Thunk.Return.isEmpty())
4872 Mangler.getStream() << 'c';
Fangrui Song6907ce22018-07-30 19:24:48 +00004873
Guy Benyei11169dd2012-12-18 14:30:41 +00004874 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004875 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4876 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4877
Guy Benyei11169dd2012-12-18 14:30:41 +00004878 // Mangle the return pointer adjustment if there is one.
4879 if (!Thunk.Return.isEmpty())
4880 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004881 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4882
Guy Benyei11169dd2012-12-18 14:30:41 +00004883 Mangler.mangleFunctionEncoding(MD);
4884}
4885
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004886void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4887 const CXXDestructorDecl *DD, CXXDtorType Type,
4888 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004889 // <special-name> ::= T <call-offset> <base encoding>
4890 // # base is the nominal target function of thunk
4891 CXXNameMangler Mangler(*this, Out, DD, Type);
4892 Mangler.getStream() << "_ZT";
4893
4894 // Mangle the 'this' pointer adjustment.
Fangrui Song6907ce22018-07-30 19:24:48 +00004895 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004896 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004897
4898 Mangler.mangleFunctionEncoding(DD);
4899}
4900
Justin Bognere8d762e2015-05-22 06:48:13 +00004901/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004902void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4903 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004904 // <special-name> ::= GV <object name> # Guard variable for one-time
4905 // # initialization
4906 CXXNameMangler Mangler(*this, Out);
Dmitry Polukhin90bb49e2016-06-30 09:40:38 +00004907 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4908 // be a bug that is fixed in trunk.
Guy Benyei11169dd2012-12-18 14:30:41 +00004909 Mangler.getStream() << "_ZGV";
4910 Mangler.mangleName(D);
4911}
4912
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004913void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4914 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004915 // These symbols are internal in the Itanium ABI, so the names don't matter.
4916 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4917 // avoid duplicate symbols.
4918 Out << "__cxx_global_var_init";
4919}
4920
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004921void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4922 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004923 // Prefix the mangling of D with __dtor_.
4924 CXXNameMangler Mangler(*this, Out);
4925 Mangler.getStream() << "__dtor_";
4926 if (shouldMangleDeclName(D))
4927 Mangler.mangle(D);
4928 else
4929 Mangler.getStream() << D->getName();
4930}
4931
Reid Kleckner1d59f992015-01-22 01:36:17 +00004932void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4933 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4934 CXXNameMangler Mangler(*this, Out);
4935 Mangler.getStream() << "__filt_";
4936 if (shouldMangleDeclName(EnclosingDecl))
4937 Mangler.mangle(EnclosingDecl);
4938 else
4939 Mangler.getStream() << EnclosingDecl->getName();
4940}
4941
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004942void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4943 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4944 CXXNameMangler Mangler(*this, Out);
4945 Mangler.getStream() << "__fin_";
4946 if (shouldMangleDeclName(EnclosingDecl))
4947 Mangler.mangle(EnclosingDecl);
4948 else
4949 Mangler.getStream() << EnclosingDecl->getName();
4950}
4951
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004952void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4953 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004954 // <special-name> ::= TH <object name>
4955 CXXNameMangler Mangler(*this, Out);
4956 Mangler.getStream() << "_ZTH";
4957 Mangler.mangleName(D);
4958}
4959
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004960void
4961ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4962 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004963 // <special-name> ::= TW <object name>
4964 CXXNameMangler Mangler(*this, Out);
4965 Mangler.getStream() << "_ZTW";
4966 Mangler.mangleName(D);
4967}
4968
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004969void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004970 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004971 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004972 // We match the GCC mangling here.
4973 // <special-name> ::= GR <object name>
4974 CXXNameMangler Mangler(*this, Out);
4975 Mangler.getStream() << "_ZGR";
4976 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004977 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004978 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004979}
4980
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004981void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4982 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004983 // <special-name> ::= TV <type> # virtual table
4984 CXXNameMangler Mangler(*this, Out);
4985 Mangler.getStream() << "_ZTV";
4986 Mangler.mangleNameOrStandardSubstitution(RD);
4987}
4988
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004989void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4990 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004991 // <special-name> ::= TT <type> # VTT structure
4992 CXXNameMangler Mangler(*this, Out);
4993 Mangler.getStream() << "_ZTT";
4994 Mangler.mangleNameOrStandardSubstitution(RD);
4995}
4996
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004997void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4998 int64_t Offset,
4999 const CXXRecordDecl *Type,
5000 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005001 // <special-name> ::= TC <type> <offset number> _ <base type>
5002 CXXNameMangler Mangler(*this, Out);
5003 Mangler.getStream() << "_ZTC";
5004 Mangler.mangleNameOrStandardSubstitution(RD);
5005 Mangler.getStream() << Offset;
5006 Mangler.getStream() << '_';
5007 Mangler.mangleNameOrStandardSubstitution(Type);
5008}
5009
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005010void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005011 // <special-name> ::= TI <type> # typeinfo structure
5012 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
5013 CXXNameMangler Mangler(*this, Out);
5014 Mangler.getStream() << "_ZTI";
5015 Mangler.mangleType(Ty);
5016}
5017
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005018void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
5019 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00005020 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
5021 CXXNameMangler Mangler(*this, Out);
5022 Mangler.getStream() << "_ZTS";
5023 Mangler.mangleType(Ty);
5024}
5025
Reid Klecknercc99e262013-11-19 23:23:00 +00005026void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
5027 mangleCXXRTTIName(Ty, Out);
5028}
5029
David Majnemer58e5bee2014-03-24 21:43:36 +00005030void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
5031 llvm_unreachable("Can't mangle string literals");
5032}
5033
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00005034ItaniumMangleContext *
5035ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
5036 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00005037}