blob: 8d49c6f586b149f6b80382bbc1c2e7a6c9862c1d [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//
David Majnemer98559942013-12-13 00:54:42 +000014// http://mentorembedded.github.io/cxx-abi/abi.html#mangling
Guy Benyei11169dd2012-12-18 14:30:41 +000015//
16//===----------------------------------------------------------------------===//
17#include "clang/AST/Mangle.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/Attr.h"
20#include "clang/AST/Decl.h"
21#include "clang/AST/DeclCXX.h"
22#include "clang/AST/DeclObjC.h"
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000023#include "clang/AST/DeclOpenMP.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/DeclTemplate.h"
David Majnemer58e5bee2014-03-24 21:43:36 +000025#include "clang/AST/Expr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/AST/ExprCXX.h"
27#include "clang/AST/ExprObjC.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/Basic/ABI.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "llvm/ADT/StringExtras.h"
33#include "llvm/Support/ErrorHandling.h"
34#include "llvm/Support/raw_ostream.h"
35
36#define MANGLE_CHECKER 0
37
38#if MANGLE_CHECKER
39#include <cxxabi.h>
40#endif
41
42using namespace clang;
43
44namespace {
45
Justin Bognere8d762e2015-05-22 06:48:13 +000046/// Retrieve the declaration context that should be used when mangling the given
47/// declaration.
Guy Benyei11169dd2012-12-18 14:30:41 +000048static const DeclContext *getEffectiveDeclContext(const Decl *D) {
49 // The ABI assumes that lambda closure types that occur within
50 // default arguments live in the context of the function. However, due to
51 // the way in which Clang parses and creates function declarations, this is
52 // not the case: the lambda closure type ends up living in the context
53 // where the function itself resides, because the function declaration itself
54 // had not yet been created. Fix the context here.
55 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
56 if (RD->isLambda())
57 if (ParmVarDecl *ContextParam
58 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
59 return ContextParam->getDeclContext();
60 }
Eli Friedman0cd23352013-07-10 01:33:19 +000061
62 // Perform the same check for block literals.
63 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
64 if (ParmVarDecl *ContextParam
65 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
66 return ContextParam->getDeclContext();
67 }
Guy Benyei11169dd2012-12-18 14:30:41 +000068
Eli Friedman95f50122013-07-02 17:52:28 +000069 const DeclContext *DC = D->getDeclContext();
Alexey Bataev94a4f0c2016-03-03 05:21:39 +000070 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
71 return getEffectiveDeclContext(cast<Decl>(DC));
72 }
Eli Friedman95f50122013-07-02 17:52:28 +000073
David Majnemerf8c02e62015-02-18 19:08:11 +000074 if (const auto *VD = dyn_cast<VarDecl>(D))
75 if (VD->isExternC())
76 return VD->getASTContext().getTranslationUnitDecl();
77
78 if (const auto *FD = dyn_cast<FunctionDecl>(D))
79 if (FD->isExternC())
80 return FD->getASTContext().getTranslationUnitDecl();
81
Richard Smithec24bbe2016-04-29 01:23:20 +000082 return DC->getRedeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +000083}
84
85static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
86 return getEffectiveDeclContext(cast<Decl>(DC));
87}
Eli Friedman95f50122013-07-02 17:52:28 +000088
89static bool isLocalContainerContext(const DeclContext *DC) {
90 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
91}
92
Eli Friedmaneecc09a2013-07-05 20:27:40 +000093static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman92821742013-07-02 02:01:18 +000094 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000095 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman95f50122013-07-02 17:52:28 +000096 if (isLocalContainerContext(DC))
Eli Friedmaneecc09a2013-07-05 20:27:40 +000097 return dyn_cast<RecordDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +000098 D = cast<Decl>(DC);
99 DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000100 }
Craig Topper36250ad2014-05-12 05:36:57 +0000101 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000102}
103
104static const FunctionDecl *getStructor(const FunctionDecl *fn) {
105 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
106 return ftd->getTemplatedDecl();
107
108 return fn;
109}
110
111static const NamedDecl *getStructor(const NamedDecl *decl) {
112 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
113 return (fn ? getStructor(fn) : decl);
114}
David Majnemer2206bf52014-03-05 08:57:59 +0000115
116static bool isLambda(const NamedDecl *ND) {
117 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
118 if (!Record)
119 return false;
120
121 return Record->isLambda();
122}
123
Guy Benyei11169dd2012-12-18 14:30:41 +0000124static const unsigned UnknownArity = ~0U;
125
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000126class ItaniumMangleContextImpl : public ItaniumMangleContext {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000127 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
128 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei11169dd2012-12-18 14:30:41 +0000129 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000130
Guy Benyei11169dd2012-12-18 14:30:41 +0000131public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000132 explicit ItaniumMangleContextImpl(ASTContext &Context,
133 DiagnosticsEngine &Diags)
134 : ItaniumMangleContext(Context, Diags) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000135
Guy Benyei11169dd2012-12-18 14:30:41 +0000136 /// @name Mangler Entry Points
137 /// @{
138
Craig Toppercbce6e92014-03-11 06:22:39 +0000139 bool shouldMangleCXXName(const NamedDecl *D) override;
David Majnemer58e5bee2014-03-24 21:43:36 +0000140 bool shouldMangleStringLiteral(const StringLiteral *) override {
141 return false;
142 }
Craig Toppercbce6e92014-03-11 06:22:39 +0000143 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
144 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
145 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000146 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
147 const ThisAdjustment &ThisAdjustment,
Craig Toppercbce6e92014-03-11 06:22:39 +0000148 raw_ostream &) override;
David Majnemerdaff3702014-05-01 17:50:17 +0000149 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
150 raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000151 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
152 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000153 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
Craig Toppercbce6e92014-03-11 06:22:39 +0000154 const CXXRecordDecl *Type, raw_ostream &) override;
155 void mangleCXXRTTI(QualType T, raw_ostream &) override;
156 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
157 void mangleTypeName(QualType T, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000159 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000160 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000161 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000162
Rafael Espindola1e4df922014-09-16 15:18:21 +0000163 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
164 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000165 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
166 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
167 void mangleDynamicAtExitDestructor(const VarDecl *D,
168 raw_ostream &Out) override;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000169 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
170 raw_ostream &Out) override;
Reid Klecknerebaf28d2015-04-14 20:59:00 +0000171 void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
172 raw_ostream &Out) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000173 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
174 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
175 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000176
David Majnemer58e5bee2014-03-24 21:43:36 +0000177 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
178
Guy Benyei11169dd2012-12-18 14:30:41 +0000179 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000180 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000181 if (isLambda(ND))
182 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000183
184 // Anonymous tags are already numbered.
185 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
186 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
187 return false;
188 }
189
190 // Use the canonical number for externally visible decls.
191 if (ND->isExternallyVisible()) {
192 unsigned discriminator = getASTContext().getManglingNumber(ND);
193 if (discriminator == 1)
194 return false;
195 disc = discriminator - 2;
196 return true;
197 }
198
199 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000200 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000201 if (!discriminator) {
202 const DeclContext *DC = getEffectiveDeclContext(ND);
203 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
204 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000205 if (discriminator == 1)
206 return false;
207 disc = discriminator-2;
208 return true;
209 }
210 /// @}
211};
212
Justin Bognere8d762e2015-05-22 06:48:13 +0000213/// Manage the mangling of a single name.
Guy Benyei11169dd2012-12-18 14:30:41 +0000214class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000215 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000216 raw_ostream &Out;
217
218 /// The "structor" is the top-level declaration being mangled, if
219 /// that's not a template specialization; otherwise it's the pattern
220 /// for that specialization.
221 const NamedDecl *Structor;
222 unsigned StructorType;
223
Justin Bognere8d762e2015-05-22 06:48:13 +0000224 /// The next substitution sequence number.
Guy Benyei11169dd2012-12-18 14:30:41 +0000225 unsigned SeqID;
226
227 class FunctionTypeDepthState {
228 unsigned Bits;
229
230 enum { InResultTypeMask = 1 };
231
232 public:
233 FunctionTypeDepthState() : Bits(0) {}
234
235 /// The number of function types we're inside.
236 unsigned getDepth() const {
237 return Bits >> 1;
238 }
239
240 /// True if we're in the return type of the innermost function type.
241 bool isInResultType() const {
242 return Bits & InResultTypeMask;
243 }
244
245 FunctionTypeDepthState push() {
246 FunctionTypeDepthState tmp = *this;
247 Bits = (Bits & ~InResultTypeMask) + 2;
248 return tmp;
249 }
250
251 void enterResultType() {
252 Bits |= InResultTypeMask;
253 }
254
255 void leaveResultType() {
256 Bits &= ~InResultTypeMask;
257 }
258
259 void pop(FunctionTypeDepthState saved) {
260 assert(getDepth() == saved.getDepth() + 1);
261 Bits = saved.Bits;
262 }
263
264 } FunctionTypeDepth;
265
266 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
267
268 ASTContext &getASTContext() const { return Context.getASTContext(); }
269
270public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000271 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Craig Topper36250ad2014-05-12 05:36:57 +0000272 const NamedDecl *D = nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +0000273 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
274 SeqID(0) {
275 // These can't be mangled without a ctor type or dtor type.
276 assert(!D || (!isa<CXXDestructorDecl>(D) &&
277 !isa<CXXConstructorDecl>(D)));
278 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000279 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000280 const CXXConstructorDecl *D, CXXCtorType Type)
281 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
282 SeqID(0) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000283 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000284 const CXXDestructorDecl *D, CXXDtorType Type)
285 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
286 SeqID(0) { }
287
288#if MANGLE_CHECKER
289 ~CXXNameMangler() {
290 if (Out.str()[0] == '\01')
291 return;
292
293 int status = 0;
294 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
295 assert(status == 0 && "Could not demangle mangled name!");
296 free(result);
297 }
298#endif
299 raw_ostream &getStream() { return Out; }
300
David Majnemer7ff7eb72015-02-18 07:47:09 +0000301 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000302 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
303 void mangleNumber(const llvm::APSInt &I);
304 void mangleNumber(int64_t Number);
305 void mangleFloat(const llvm::APFloat &F);
306 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000307 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000308 void mangleName(const NamedDecl *ND);
309 void mangleType(QualType T);
310 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
311
312private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000313
Guy Benyei11169dd2012-12-18 14:30:41 +0000314 bool mangleSubstitution(const NamedDecl *ND);
315 bool mangleSubstitution(QualType T);
316 bool mangleSubstitution(TemplateName Template);
317 bool mangleSubstitution(uintptr_t Ptr);
318
Guy Benyei11169dd2012-12-18 14:30:41 +0000319 void mangleExistingSubstitution(TemplateName name);
320
321 bool mangleStandardSubstitution(const NamedDecl *ND);
322
323 void addSubstitution(const NamedDecl *ND) {
324 ND = cast<NamedDecl>(ND->getCanonicalDecl());
325
326 addSubstitution(reinterpret_cast<uintptr_t>(ND));
327 }
328 void addSubstitution(QualType T);
329 void addSubstitution(TemplateName Template);
330 void addSubstitution(uintptr_t Ptr);
331
332 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000333 bool recursive = false);
334 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000335 DeclarationName name,
336 unsigned KnownArity = UnknownArity);
337
338 void mangleName(const TemplateDecl *TD,
339 const TemplateArgument *TemplateArgs,
340 unsigned NumTemplateArgs);
341 void mangleUnqualifiedName(const NamedDecl *ND) {
342 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
343 }
344 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
345 unsigned KnownArity);
346 void mangleUnscopedName(const NamedDecl *ND);
347 void mangleUnscopedTemplateName(const TemplateDecl *ND);
348 void mangleUnscopedTemplateName(TemplateName);
349 void mangleSourceName(const IdentifierInfo *II);
Eli Friedman95f50122013-07-02 17:52:28 +0000350 void mangleLocalName(const Decl *D);
351 void mangleBlockForPrefix(const BlockDecl *Block);
352 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000353 void mangleLambda(const CXXRecordDecl *Lambda);
354 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
355 bool NoFunction=false);
356 void mangleNestedName(const TemplateDecl *TD,
357 const TemplateArgument *TemplateArgs,
358 unsigned NumTemplateArgs);
359 void manglePrefix(NestedNameSpecifier *qualifier);
360 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
361 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000362 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000363 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000364 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
365 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000366 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000367 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
John McCall07daf722016-03-01 22:18:03 +0000368 void mangleVendorQualifier(StringRef qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +0000369 void mangleQualifiers(Qualifiers Quals);
370 void mangleRefQualifier(RefQualifierKind RefQualifier);
371
372 void mangleObjCMethodName(const ObjCMethodDecl *MD);
373
374 // Declare manglers for every type class.
375#define ABSTRACT_TYPE(CLASS, PARENT)
376#define NON_CANONICAL_TYPE(CLASS, PARENT)
377#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
378#include "clang/AST/TypeNodes.def"
379
380 void mangleType(const TagType*);
381 void mangleType(TemplateName);
John McCall07daf722016-03-01 22:18:03 +0000382 static StringRef getCallingConvQualifierName(CallingConv CC);
383 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
384 void mangleExtFunctionInfo(const FunctionType *T);
385 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000386 const FunctionDecl *FD = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000387 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000388 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000389
390 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000391 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000392 void mangleMemberExpr(const Expr *base, bool isArrow,
393 NestedNameSpecifier *qualifier,
394 NamedDecl *firstQualifierLookup,
395 DeclarationName name,
396 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000397 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000398 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000399 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
Richard Smith5179eb72016-06-28 19:03:57 +0000400 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +0000401 void mangleCXXDtorType(CXXDtorType T);
402
James Y Knight04ec5bf2015-12-24 02:59:37 +0000403 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
404 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000405 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
406 unsigned NumTemplateArgs);
407 void mangleTemplateArgs(const TemplateArgumentList &AL);
408 void mangleTemplateArg(TemplateArgument A);
409
410 void mangleTemplateParameter(unsigned Index);
411
412 void mangleFunctionParam(const ParmVarDecl *parm);
413};
414
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000415}
Guy Benyei11169dd2012-12-18 14:30:41 +0000416
Rafael Espindola002667c2013-10-16 01:40:34 +0000417bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000418 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000419 if (FD) {
420 LanguageLinkage L = FD->getLanguageLinkage();
421 // Overloadable functions need mangling.
422 if (FD->hasAttr<OverloadableAttr>())
423 return true;
424
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000425 // "main" is not mangled.
426 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000427 return false;
428
429 // C++ functions and those whose names are not a simple identifier need
430 // mangling.
431 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
432 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000433
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000434 // C functions are not mangled.
435 if (L == CLanguageLinkage)
436 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000437 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000438
439 // Otherwise, no mangling is done outside C++ mode.
440 if (!getASTContext().getLangOpts().CPlusPlus)
441 return false;
442
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000443 const VarDecl *VD = dyn_cast<VarDecl>(D);
444 if (VD) {
445 // C variables are not mangled.
446 if (VD->isExternC())
447 return false;
448
449 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000450 const DeclContext *DC = getEffectiveDeclContext(D);
451 // Check for extern variable declared locally.
452 if (DC->isFunctionOrMethod() && D->hasLinkage())
453 while (!DC->isNamespace() && !DC->isTranslationUnit())
454 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000455 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
456 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000457 return false;
458 }
459
Guy Benyei11169dd2012-12-18 14:30:41 +0000460 return true;
461}
462
David Majnemer7ff7eb72015-02-18 07:47:09 +0000463void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000464 // <mangled-name> ::= _Z <encoding>
465 // ::= <data name>
466 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000467 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000468 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
469 mangleFunctionEncoding(FD);
470 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
471 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000472 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
473 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000474 else
475 mangleName(cast<FieldDecl>(D));
476}
477
478void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
479 // <encoding> ::= <function name> <bare-function-type>
480 mangleName(FD);
481
482 // Don't mangle in the type if this isn't a decl we should typically mangle.
483 if (!Context.shouldMangleDeclName(FD))
484 return;
485
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000486 if (FD->hasAttr<EnableIfAttr>()) {
487 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
488 Out << "Ua9enable_ifI";
489 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
490 // it here.
491 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
492 E = FD->getAttrs().rend();
493 I != E; ++I) {
494 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
495 if (!EIA)
496 continue;
497 Out << 'X';
498 mangleExpression(EIA->getCond());
499 Out << 'E';
500 }
501 Out << 'E';
502 FunctionTypeDepth.pop(Saved);
503 }
504
Richard Smith5179eb72016-06-28 19:03:57 +0000505 // When mangling an inheriting constructor, the bare function type used is
506 // that of the inherited constructor.
507 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
508 if (auto Inherited = CD->getInheritedConstructor())
509 FD = Inherited.getConstructor();
510
Guy Benyei11169dd2012-12-18 14:30:41 +0000511 // Whether the mangling of a function type includes the return type depends on
512 // the context and the nature of the function. The rules for deciding whether
513 // the return type is included are:
514 //
515 // 1. Template functions (names or types) have return types encoded, with
516 // the exceptions listed below.
517 // 2. Function types not appearing as part of a function name mangling,
518 // e.g. parameters, pointer types, etc., have return type encoded, with the
519 // exceptions listed below.
520 // 3. Non-template function names do not have return types encoded.
521 //
522 // The exceptions mentioned in (1) and (2) above, for which the return type is
523 // never included, are
524 // 1. Constructors.
525 // 2. Destructors.
526 // 3. Conversion operator functions, e.g. operator int.
527 bool MangleReturnType = false;
528 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
529 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
530 isa<CXXConversionDecl>(FD)))
531 MangleReturnType = true;
532
533 // Mangle the type of the primary template.
534 FD = PrimaryTemplate->getTemplatedDecl();
535 }
536
John McCall07daf722016-03-01 22:18:03 +0000537 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000538 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000539}
540
541static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
542 while (isa<LinkageSpecDecl>(DC)) {
543 DC = getEffectiveParentContext(DC);
544 }
545
546 return DC;
547}
548
Justin Bognere8d762e2015-05-22 06:48:13 +0000549/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000550static bool isStd(const NamespaceDecl *NS) {
551 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
552 ->isTranslationUnit())
553 return false;
554
555 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
556 return II && II->isStr("std");
557}
558
559// isStdNamespace - Return whether a given decl context is a toplevel 'std'
560// namespace.
561static bool isStdNamespace(const DeclContext *DC) {
562 if (!DC->isNamespace())
563 return false;
564
565 return isStd(cast<NamespaceDecl>(DC));
566}
567
568static const TemplateDecl *
569isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
570 // Check if we have a function template.
Richard Smith5179eb72016-06-28 19:03:57 +0000571 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000572 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
573 TemplateArgs = FD->getTemplateSpecializationArgs();
574 return TD;
575 }
576 }
577
578 // Check if we have a class template.
579 if (const ClassTemplateSpecializationDecl *Spec =
580 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
581 TemplateArgs = &Spec->getTemplateArgs();
582 return Spec->getSpecializedTemplate();
583 }
584
Larisse Voufo39a1e502013-08-06 01:03:05 +0000585 // Check if we have a variable template.
586 if (const VarTemplateSpecializationDecl *Spec =
587 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
588 TemplateArgs = &Spec->getTemplateArgs();
589 return Spec->getSpecializedTemplate();
590 }
591
Craig Topper36250ad2014-05-12 05:36:57 +0000592 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000593}
594
Guy Benyei11169dd2012-12-18 14:30:41 +0000595void CXXNameMangler::mangleName(const NamedDecl *ND) {
596 // <name> ::= <nested-name>
597 // ::= <unscoped-name>
598 // ::= <unscoped-template-name> <template-args>
599 // ::= <local-name>
600 //
601 const DeclContext *DC = getEffectiveDeclContext(ND);
602
603 // If this is an extern variable declared locally, the relevant DeclContext
604 // is that of the containing namespace, or the translation unit.
605 // FIXME: This is a hack; extern variables declared locally should have
606 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000607 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000608 while (!DC->isNamespace() && !DC->isTranslationUnit())
609 DC = getEffectiveParentContext(DC);
610 else if (GetLocalClassDecl(ND)) {
611 mangleLocalName(ND);
612 return;
613 }
614
615 DC = IgnoreLinkageSpecDecls(DC);
616
617 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
618 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000619 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000620 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
621 mangleUnscopedTemplateName(TD);
622 mangleTemplateArgs(*TemplateArgs);
623 return;
624 }
625
626 mangleUnscopedName(ND);
627 return;
628 }
629
Eli Friedman95f50122013-07-02 17:52:28 +0000630 if (isLocalContainerContext(DC)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000631 mangleLocalName(ND);
632 return;
633 }
634
635 mangleNestedName(ND, DC);
636}
637void CXXNameMangler::mangleName(const TemplateDecl *TD,
638 const TemplateArgument *TemplateArgs,
639 unsigned NumTemplateArgs) {
640 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
641
642 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
643 mangleUnscopedTemplateName(TD);
644 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
645 } else {
646 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
647 }
648}
649
650void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
651 // <unscoped-name> ::= <unqualified-name>
652 // ::= St <unqualified-name> # ::std::
653
654 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
655 Out << "St";
656
657 mangleUnqualifiedName(ND);
658}
659
660void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
661 // <unscoped-template-name> ::= <unscoped-name>
662 // ::= <substitution>
663 if (mangleSubstitution(ND))
664 return;
665
666 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +0000667 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000668 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +0000669 else
670 mangleUnscopedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +0000671
Guy Benyei11169dd2012-12-18 14:30:41 +0000672 addSubstitution(ND);
673}
674
675void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
676 // <unscoped-template-name> ::= <unscoped-name>
677 // ::= <substitution>
678 if (TemplateDecl *TD = Template.getAsTemplateDecl())
679 return mangleUnscopedTemplateName(TD);
680
681 if (mangleSubstitution(Template))
682 return;
683
684 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
685 assert(Dependent && "Not a dependent template name?");
686 if (const IdentifierInfo *Id = Dependent->getIdentifier())
687 mangleSourceName(Id);
688 else
689 mangleOperatorName(Dependent->getOperator(), UnknownArity);
690
691 addSubstitution(Template);
692}
693
694void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
695 // ABI:
696 // Floating-point literals are encoded using a fixed-length
697 // lowercase hexadecimal string corresponding to the internal
698 // representation (IEEE on Itanium), high-order bytes first,
699 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
700 // on Itanium.
701 // The 'without leading zeroes' thing seems to be an editorial
702 // mistake; see the discussion on cxx-abi-dev beginning on
703 // 2012-01-16.
704
705 // Our requirements here are just barely weird enough to justify
706 // using a custom algorithm instead of post-processing APInt::toString().
707
708 llvm::APInt valueBits = f.bitcastToAPInt();
709 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
710 assert(numCharacters != 0);
711
712 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +0000713 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +0000714
715 // Fill the buffer left-to-right.
716 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
717 // The bit-index of the next hex digit.
718 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
719
720 // Project out 4 bits starting at 'digitIndex'.
721 llvm::integerPart hexDigit
722 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
723 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
724 hexDigit &= 0xF;
725
726 // Map that over to a lowercase hex digit.
727 static const char charForHex[16] = {
728 '0', '1', '2', '3', '4', '5', '6', '7',
729 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
730 };
731 buffer[stringIndex] = charForHex[hexDigit];
732 }
733
734 Out.write(buffer.data(), numCharacters);
735}
736
737void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
738 if (Value.isSigned() && Value.isNegative()) {
739 Out << 'n';
740 Value.abs().print(Out, /*signed*/ false);
741 } else {
742 Value.print(Out, /*signed*/ false);
743 }
744}
745
746void CXXNameMangler::mangleNumber(int64_t Number) {
747 // <number> ::= [n] <non-negative decimal integer>
748 if (Number < 0) {
749 Out << 'n';
750 Number = -Number;
751 }
752
753 Out << Number;
754}
755
756void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
757 // <call-offset> ::= h <nv-offset> _
758 // ::= v <v-offset> _
759 // <nv-offset> ::= <offset number> # non-virtual base override
760 // <v-offset> ::= <offset number> _ <virtual offset number>
761 // # virtual base override, with vcall offset
762 if (!Virtual) {
763 Out << 'h';
764 mangleNumber(NonVirtual);
765 Out << '_';
766 return;
767 }
768
769 Out << 'v';
770 mangleNumber(NonVirtual);
771 Out << '_';
772 mangleNumber(Virtual);
773 Out << '_';
774}
775
776void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +0000777 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000778 if (!mangleSubstitution(QualType(TST, 0))) {
779 mangleTemplatePrefix(TST->getTemplateName());
780
781 // FIXME: GCC does not appear to mangle the template arguments when
782 // the template in question is a dependent template name. Should we
783 // emulate that badness?
784 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
785 addSubstitution(QualType(TST, 0));
786 }
David Majnemera88b3592015-02-18 02:28:01 +0000787 } else if (const auto *DTST =
788 type->getAs<DependentTemplateSpecializationType>()) {
789 if (!mangleSubstitution(QualType(DTST, 0))) {
790 TemplateName Template = getASTContext().getDependentTemplateName(
791 DTST->getQualifier(), DTST->getIdentifier());
792 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +0000793
David Majnemera88b3592015-02-18 02:28:01 +0000794 // FIXME: GCC does not appear to mangle the template arguments when
795 // the template in question is a dependent template name. Should we
796 // emulate that badness?
797 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
798 addSubstitution(QualType(DTST, 0));
799 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000800 } else {
801 // We use the QualType mangle type variant here because it handles
802 // substitutions.
803 mangleType(type);
804 }
805}
806
807/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
808///
Guy Benyei11169dd2012-12-18 14:30:41 +0000809/// \param recursive - true if this is being called recursively,
810/// i.e. if there is more prefix "to the right".
811void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000812 bool recursive) {
813
814 // x, ::x
815 // <unresolved-name> ::= [gs] <base-unresolved-name>
816
817 // T::x / decltype(p)::x
818 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
819
820 // T::N::x /decltype(p)::N::x
821 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
822 // <base-unresolved-name>
823
824 // A::x, N::y, A<T>::z; "gs" means leading "::"
825 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
826 // <base-unresolved-name>
827
828 switch (qualifier->getKind()) {
829 case NestedNameSpecifier::Global:
830 Out << "gs";
831
832 // We want an 'sr' unless this is the entire NNS.
833 if (recursive)
834 Out << "sr";
835
836 // We never want an 'E' here.
837 return;
838
Nikola Smiljanic67860242014-09-26 00:28:20 +0000839 case NestedNameSpecifier::Super:
840 llvm_unreachable("Can't mangle __super specifier");
841
Guy Benyei11169dd2012-12-18 14:30:41 +0000842 case NestedNameSpecifier::Namespace:
843 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000844 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000845 /*recursive*/ true);
846 else
847 Out << "sr";
848 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
849 break;
850 case NestedNameSpecifier::NamespaceAlias:
851 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000852 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000853 /*recursive*/ true);
854 else
855 Out << "sr";
856 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
857 break;
858
859 case NestedNameSpecifier::TypeSpec:
860 case NestedNameSpecifier::TypeSpecWithTemplate: {
861 const Type *type = qualifier->getAsType();
862
863 // We only want to use an unresolved-type encoding if this is one of:
864 // - a decltype
865 // - a template type parameter
866 // - a template template parameter with arguments
867 // In all of these cases, we should have no prefix.
868 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000869 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000870 /*recursive*/ true);
871 } else {
872 // Otherwise, all the cases want this.
873 Out << "sr";
874 }
875
David Majnemerb8014dd2015-02-19 02:16:16 +0000876 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +0000877 return;
878
Guy Benyei11169dd2012-12-18 14:30:41 +0000879 break;
880 }
881
882 case NestedNameSpecifier::Identifier:
883 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +0000884 if (qualifier->getPrefix())
885 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000886 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +0000887 else
Guy Benyei11169dd2012-12-18 14:30:41 +0000888 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +0000889
890 mangleSourceName(qualifier->getAsIdentifier());
891 break;
892 }
893
894 // If this was the innermost part of the NNS, and we fell out to
895 // here, append an 'E'.
896 if (!recursive)
897 Out << 'E';
898}
899
900/// Mangle an unresolved-name, which is generally used for names which
901/// weren't resolved to specific entities.
902void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000903 DeclarationName name,
904 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000905 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000906 switch (name.getNameKind()) {
907 // <base-unresolved-name> ::= <simple-id>
908 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +0000909 mangleSourceName(name.getAsIdentifierInfo());
910 break;
911 // <base-unresolved-name> ::= dn <destructor-name>
912 case DeclarationName::CXXDestructorName:
913 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +0000914 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +0000915 break;
916 // <base-unresolved-name> ::= on <operator-name>
917 case DeclarationName::CXXConversionFunctionName:
918 case DeclarationName::CXXLiteralOperatorName:
919 case DeclarationName::CXXOperatorName:
920 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +0000921 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000922 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +0000923 case DeclarationName::CXXConstructorName:
924 llvm_unreachable("Can't mangle a constructor name!");
925 case DeclarationName::CXXUsingDirective:
926 llvm_unreachable("Can't mangle a using directive name!");
927 case DeclarationName::ObjCMultiArgSelector:
928 case DeclarationName::ObjCOneArgSelector:
929 case DeclarationName::ObjCZeroArgSelector:
930 llvm_unreachable("Can't mangle Objective-C selector names here!");
931 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000932}
933
Guy Benyei11169dd2012-12-18 14:30:41 +0000934void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
935 DeclarationName Name,
936 unsigned KnownArity) {
David Majnemera88b3592015-02-18 02:28:01 +0000937 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +0000938 // <unqualified-name> ::= <operator-name>
939 // ::= <ctor-dtor-name>
940 // ::= <source-name>
941 switch (Name.getNameKind()) {
942 case DeclarationName::Identifier: {
943 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
944 // We must avoid conflicts between internally- and externally-
945 // linked variable and function declaration names in the same TU:
946 // void test() { extern void foo(); }
947 // static void foo();
948 // This naming convention is the same as that followed by GCC,
949 // though it shouldn't actually matter.
Rafael Espindola3ae00052013-05-13 00:12:11 +0000950 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei11169dd2012-12-18 14:30:41 +0000951 getEffectiveDeclContext(ND)->isFileContext())
952 Out << 'L';
953
954 mangleSourceName(II);
955 break;
956 }
957
958 // Otherwise, an anonymous entity. We must have a declaration.
959 assert(ND && "mangling empty name without declaration");
960
961 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
962 if (NS->isAnonymousNamespace()) {
963 // This is how gcc mangles these names.
964 Out << "12_GLOBAL__N_1";
965 break;
966 }
967 }
968
969 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
970 // We must have an anonymous union or struct declaration.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000971 const RecordDecl *RD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000972 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000973
Guy Benyei11169dd2012-12-18 14:30:41 +0000974 // Itanium C++ ABI 5.1.2:
975 //
976 // For the purposes of mangling, the name of an anonymous union is
977 // considered to be the name of the first named data member found by a
978 // pre-order, depth-first, declaration-order walk of the data members of
979 // the anonymous union. If there is no such data member (i.e., if all of
980 // the data members in the union are unnamed), then there is no way for
981 // a program to refer to the anonymous union, and there is therefore no
982 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000983 assert(RD->isAnonymousStructOrUnion()
984 && "Expected anonymous struct or union!");
985 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +0000986
987 // It's actually possible for various reasons for us to get here
988 // with an empty anonymous struct / union. Fortunately, it
989 // doesn't really matter what name we generate.
990 if (!FD) break;
991 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000992
Guy Benyei11169dd2012-12-18 14:30:41 +0000993 mangleSourceName(FD->getIdentifier());
994 break;
995 }
John McCall924046f2013-04-10 06:08:21 +0000996
997 // Class extensions have no name as a category, and it's possible
998 // for them to be the semantic parent of certain declarations
999 // (primarily, tag decls defined within declarations). Such
1000 // declarations will always have internal linkage, so the name
1001 // doesn't really matter, but we shouldn't crash on them. For
1002 // safety, just handle all ObjC containers here.
1003 if (isa<ObjCContainerDecl>(ND))
1004 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001005
1006 // We must have an anonymous struct.
1007 const TagDecl *TD = cast<TagDecl>(ND);
1008 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1009 assert(TD->getDeclContext() == D->getDeclContext() &&
1010 "Typedef should not be in another decl context!");
1011 assert(D->getDeclName().getAsIdentifierInfo() &&
1012 "Typedef was not named!");
1013 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1014 break;
1015 }
1016
1017 // <unnamed-type-name> ::= <closure-type-name>
1018 //
1019 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1020 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1021 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1022 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1023 mangleLambda(Record);
1024 break;
1025 }
1026 }
1027
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001028 if (TD->isExternallyVisible()) {
1029 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001030 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001031 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001032 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001033 Out << '_';
1034 break;
1035 }
1036
1037 // Get a unique id for the anonymous struct.
David Majnemer2206bf52014-03-05 08:57:59 +00001038 unsigned AnonStructId = Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001039
1040 // Mangle it as a source name in the form
1041 // [n] $_<id>
1042 // where n is the length of the string.
1043 SmallString<8> Str;
1044 Str += "$_";
1045 Str += llvm::utostr(AnonStructId);
1046
1047 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001048 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001049 break;
1050 }
1051
1052 case DeclarationName::ObjCZeroArgSelector:
1053 case DeclarationName::ObjCOneArgSelector:
1054 case DeclarationName::ObjCMultiArgSelector:
1055 llvm_unreachable("Can't mangle Objective-C selector names here!");
1056
Richard Smith5179eb72016-06-28 19:03:57 +00001057 case DeclarationName::CXXConstructorName: {
1058 const CXXRecordDecl *InheritedFrom = nullptr;
1059 const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1060 if (auto Inherited =
1061 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1062 InheritedFrom = Inherited.getConstructor()->getParent();
1063 InheritedTemplateArgs =
1064 Inherited.getConstructor()->getTemplateSpecializationArgs();
1065 }
1066
Guy Benyei11169dd2012-12-18 14:30:41 +00001067 if (ND == Structor)
1068 // If the named decl is the C++ constructor we're mangling, use the type
1069 // we were given.
Richard Smith5179eb72016-06-28 19:03:57 +00001070 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00001071 else
1072 // Otherwise, use the complete constructor name. This is relevant if a
1073 // class with a constructor is declared within a constructor.
Richard Smith5179eb72016-06-28 19:03:57 +00001074 mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1075
1076 // FIXME: The template arguments are part of the enclosing prefix or
1077 // nested-name, but it's more convenient to mangle them here.
1078 if (InheritedTemplateArgs)
1079 mangleTemplateArgs(*InheritedTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00001080 break;
Richard Smith5179eb72016-06-28 19:03:57 +00001081 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001082
1083 case DeclarationName::CXXDestructorName:
1084 if (ND == Structor)
1085 // If the named decl is the C++ destructor we're mangling, use the type we
1086 // were given.
1087 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1088 else
1089 // Otherwise, use the complete destructor name. This is relevant if a
1090 // class with a destructor is declared within a destructor.
1091 mangleCXXDtorType(Dtor_Complete);
1092 break;
1093
David Majnemera88b3592015-02-18 02:28:01 +00001094 case DeclarationName::CXXOperatorName:
1095 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001096 Arity = cast<FunctionDecl>(ND)->getNumParams();
1097
David Majnemera88b3592015-02-18 02:28:01 +00001098 // If we have a member function, we need to include the 'this' pointer.
1099 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1100 if (!MD->isStatic())
1101 Arity++;
1102 }
1103 // FALLTHROUGH
1104 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001105 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001106 mangleOperatorName(Name, Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00001107 break;
1108
1109 case DeclarationName::CXXUsingDirective:
1110 llvm_unreachable("Can't mangle a using directive name!");
1111 }
1112}
1113
1114void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1115 // <source-name> ::= <positive length number> <identifier>
1116 // <number> ::= [n] <non-negative decimal integer>
1117 // <identifier> ::= <unqualified source code identifier>
1118 Out << II->getLength() << II->getName();
1119}
1120
1121void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1122 const DeclContext *DC,
1123 bool NoFunction) {
1124 // <nested-name>
1125 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1126 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1127 // <template-args> E
1128
1129 Out << 'N';
1130 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001131 Qualifiers MethodQuals =
1132 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1133 // We do not consider restrict a distinguishing attribute for overloading
1134 // purposes so we must not mangle it.
1135 MethodQuals.removeRestrict();
1136 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001137 mangleRefQualifier(Method->getRefQualifier());
1138 }
1139
1140 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001141 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001142 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001143 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001144 mangleTemplateArgs(*TemplateArgs);
1145 }
1146 else {
1147 manglePrefix(DC, NoFunction);
1148 mangleUnqualifiedName(ND);
1149 }
1150
1151 Out << 'E';
1152}
1153void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1154 const TemplateArgument *TemplateArgs,
1155 unsigned NumTemplateArgs) {
1156 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1157
1158 Out << 'N';
1159
1160 mangleTemplatePrefix(TD);
1161 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1162
1163 Out << 'E';
1164}
1165
Eli Friedman95f50122013-07-02 17:52:28 +00001166void CXXNameMangler::mangleLocalName(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001167 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1168 // := Z <function encoding> E s [<discriminator>]
1169 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1170 // _ <entity name>
1171 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001172 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001173 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001174 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001175
1176 Out << 'Z';
1177
Eli Friedman92821742013-07-02 02:01:18 +00001178 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1179 mangleObjCMethodName(MD);
1180 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
Eli Friedman95f50122013-07-02 17:52:28 +00001181 mangleBlockForPrefix(BD);
Eli Friedman92821742013-07-02 02:01:18 +00001182 else
1183 mangleFunctionEncoding(cast<FunctionDecl>(DC));
Guy Benyei11169dd2012-12-18 14:30:41 +00001184
Eli Friedman92821742013-07-02 02:01:18 +00001185 Out << 'E';
1186
1187 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001188 // The parameter number is omitted for the last parameter, 0 for the
1189 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1190 // <entity name> will of course contain a <closure-type-name>: Its
1191 // numbering will be local to the particular argument in which it appears
1192 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001193 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1194 if (CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001195 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001196 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001197 if (const FunctionDecl *Func
1198 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1199 Out << 'd';
1200 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1201 if (Num > 1)
1202 mangleNumber(Num - 2);
1203 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001204 }
1205 }
1206 }
1207
1208 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001209 // equality ok because RD derived from ND above
1210 if (D == RD) {
1211 mangleUnqualifiedName(RD);
1212 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1213 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1214 mangleUnqualifiedBlock(BD);
1215 } else {
1216 const NamedDecl *ND = cast<NamedDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +00001217 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001218 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001219 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1220 // Mangle a block in a default parameter; see above explanation for
1221 // lambdas.
1222 if (const ParmVarDecl *Parm
1223 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1224 if (const FunctionDecl *Func
1225 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1226 Out << 'd';
1227 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1228 if (Num > 1)
1229 mangleNumber(Num - 2);
1230 Out << '_';
1231 }
1232 }
1233
1234 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001235 } else {
Eli Friedman0cd23352013-07-10 01:33:19 +00001236 mangleUnqualifiedName(cast<NamedDecl>(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00001237 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001238
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001239 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1240 unsigned disc;
1241 if (Context.getNextDiscriminator(ND, disc)) {
1242 if (disc < 10)
1243 Out << '_' << disc;
1244 else
1245 Out << "__" << disc << '_';
1246 }
1247 }
Eli Friedman95f50122013-07-02 17:52:28 +00001248}
1249
1250void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1251 if (GetLocalClassDecl(Block)) {
1252 mangleLocalName(Block);
1253 return;
1254 }
1255 const DeclContext *DC = getEffectiveDeclContext(Block);
1256 if (isLocalContainerContext(DC)) {
1257 mangleLocalName(Block);
1258 return;
1259 }
1260 manglePrefix(getEffectiveDeclContext(Block));
1261 mangleUnqualifiedBlock(Block);
1262}
1263
1264void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1265 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1266 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1267 Context->getDeclContext()->isRecord()) {
1268 if (const IdentifierInfo *Name
1269 = cast<NamedDecl>(Context)->getIdentifier()) {
1270 mangleSourceName(Name);
1271 Out << 'M';
1272 }
1273 }
1274 }
1275
1276 // If we have a block mangling number, use it.
1277 unsigned Number = Block->getBlockManglingNumber();
1278 // Otherwise, just make up a number. It doesn't matter what it is because
1279 // the symbol in question isn't externally visible.
1280 if (!Number)
1281 Number = Context.getBlockId(Block, false);
1282 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001283 if (Number > 0)
1284 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001285 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001286}
1287
1288void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1289 // If the context of a closure type is an initializer for a class member
1290 // (static or nonstatic), it is encoded in a qualified name with a final
1291 // <prefix> of the form:
1292 //
1293 // <data-member-prefix> := <member source-name> M
1294 //
1295 // Technically, the data-member-prefix is part of the <prefix>. However,
1296 // since a closure type will always be mangled with a prefix, it's easier
1297 // to emit that last part of the prefix here.
1298 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1299 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1300 Context->getDeclContext()->isRecord()) {
1301 if (const IdentifierInfo *Name
1302 = cast<NamedDecl>(Context)->getIdentifier()) {
1303 mangleSourceName(Name);
1304 Out << 'M';
1305 }
1306 }
1307 }
1308
1309 Out << "Ul";
1310 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1311 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001312 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1313 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001314 Out << "E";
1315
1316 // The number is omitted for the first closure type with a given
1317 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1318 // (in lexical order) with that same <lambda-sig> and context.
1319 //
1320 // The AST keeps track of the number for us.
1321 unsigned Number = Lambda->getLambdaManglingNumber();
1322 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1323 if (Number > 1)
1324 mangleNumber(Number - 2);
1325 Out << '_';
1326}
1327
1328void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1329 switch (qualifier->getKind()) {
1330 case NestedNameSpecifier::Global:
1331 // nothing
1332 return;
1333
Nikola Smiljanic67860242014-09-26 00:28:20 +00001334 case NestedNameSpecifier::Super:
1335 llvm_unreachable("Can't mangle __super specifier");
1336
Guy Benyei11169dd2012-12-18 14:30:41 +00001337 case NestedNameSpecifier::Namespace:
1338 mangleName(qualifier->getAsNamespace());
1339 return;
1340
1341 case NestedNameSpecifier::NamespaceAlias:
1342 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1343 return;
1344
1345 case NestedNameSpecifier::TypeSpec:
1346 case NestedNameSpecifier::TypeSpecWithTemplate:
1347 manglePrefix(QualType(qualifier->getAsType(), 0));
1348 return;
1349
1350 case NestedNameSpecifier::Identifier:
1351 // Member expressions can have these without prefixes, but that
1352 // should end up in mangleUnresolvedPrefix instead.
1353 assert(qualifier->getPrefix());
1354 manglePrefix(qualifier->getPrefix());
1355
1356 mangleSourceName(qualifier->getAsIdentifier());
1357 return;
1358 }
1359
1360 llvm_unreachable("unexpected nested name specifier");
1361}
1362
1363void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1364 // <prefix> ::= <prefix> <unqualified-name>
1365 // ::= <template-prefix> <template-args>
1366 // ::= <template-param>
1367 // ::= # empty
1368 // ::= <substitution>
1369
1370 DC = IgnoreLinkageSpecDecls(DC);
1371
1372 if (DC->isTranslationUnit())
1373 return;
1374
Eli Friedman95f50122013-07-02 17:52:28 +00001375 if (NoFunction && isLocalContainerContext(DC))
1376 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001377
Eli Friedman95f50122013-07-02 17:52:28 +00001378 assert(!isLocalContainerContext(DC));
1379
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 const NamedDecl *ND = cast<NamedDecl>(DC);
1381 if (mangleSubstitution(ND))
1382 return;
1383
1384 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001385 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001386 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1387 mangleTemplatePrefix(TD);
1388 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001389 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1391 mangleUnqualifiedName(ND);
1392 }
1393
1394 addSubstitution(ND);
1395}
1396
1397void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1398 // <template-prefix> ::= <prefix> <template unqualified-name>
1399 // ::= <template-param>
1400 // ::= <substitution>
1401 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1402 return mangleTemplatePrefix(TD);
1403
1404 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1405 manglePrefix(Qualified->getQualifier());
1406
1407 if (OverloadedTemplateStorage *Overloaded
1408 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001409 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001410 UnknownArity);
1411 return;
1412 }
1413
1414 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1415 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001416 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1417 manglePrefix(Qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 mangleUnscopedTemplateName(Template);
1419}
1420
Eli Friedman86af13f02013-07-05 18:41:30 +00001421void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1422 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001423 // <template-prefix> ::= <prefix> <template unqualified-name>
1424 // ::= <template-param>
1425 // ::= <substitution>
1426 // <template-template-param> ::= <template-param>
1427 // <substitution>
1428
1429 if (mangleSubstitution(ND))
1430 return;
1431
1432 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001433 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001434 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001435 } else {
1436 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1437 mangleUnqualifiedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001438 }
1439
Guy Benyei11169dd2012-12-18 14:30:41 +00001440 addSubstitution(ND);
1441}
1442
1443/// Mangles a template name under the production <type>. Required for
1444/// template template arguments.
1445/// <type> ::= <class-enum-type>
1446/// ::= <template-param>
1447/// ::= <substitution>
1448void CXXNameMangler::mangleType(TemplateName TN) {
1449 if (mangleSubstitution(TN))
1450 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001451
1452 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001453
1454 switch (TN.getKind()) {
1455 case TemplateName::QualifiedTemplate:
1456 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1457 goto HaveDecl;
1458
1459 case TemplateName::Template:
1460 TD = TN.getAsTemplateDecl();
1461 goto HaveDecl;
1462
1463 HaveDecl:
1464 if (isa<TemplateTemplateParmDecl>(TD))
1465 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1466 else
1467 mangleName(TD);
1468 break;
1469
1470 case TemplateName::OverloadedTemplate:
1471 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1472
1473 case TemplateName::DependentTemplate: {
1474 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1475 assert(Dependent->isIdentifier());
1476
1477 // <class-enum-type> ::= <name>
1478 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001479 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001480 mangleSourceName(Dependent->getIdentifier());
1481 break;
1482 }
1483
1484 case TemplateName::SubstTemplateTemplateParm: {
1485 // Substituted template parameters are mangled as the substituted
1486 // template. This will check for the substitution twice, which is
1487 // fine, but we have to return early so that we don't try to *add*
1488 // the substitution twice.
1489 SubstTemplateTemplateParmStorage *subst
1490 = TN.getAsSubstTemplateTemplateParm();
1491 mangleType(subst->getReplacement());
1492 return;
1493 }
1494
1495 case TemplateName::SubstTemplateTemplateParmPack: {
1496 // FIXME: not clear how to mangle this!
1497 // template <template <class> class T...> class A {
1498 // template <template <class> class U...> void foo(B<T,U> x...);
1499 // };
1500 Out << "_SUBSTPACK_";
1501 break;
1502 }
1503 }
1504
1505 addSubstitution(TN);
1506}
1507
David Majnemerb8014dd2015-02-19 02:16:16 +00001508bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1509 StringRef Prefix) {
1510 // Only certain other types are valid as prefixes; enumerate them.
1511 switch (Ty->getTypeClass()) {
1512 case Type::Builtin:
1513 case Type::Complex:
1514 case Type::Adjusted:
1515 case Type::Decayed:
1516 case Type::Pointer:
1517 case Type::BlockPointer:
1518 case Type::LValueReference:
1519 case Type::RValueReference:
1520 case Type::MemberPointer:
1521 case Type::ConstantArray:
1522 case Type::IncompleteArray:
1523 case Type::VariableArray:
1524 case Type::DependentSizedArray:
1525 case Type::DependentSizedExtVector:
1526 case Type::Vector:
1527 case Type::ExtVector:
1528 case Type::FunctionProto:
1529 case Type::FunctionNoProto:
1530 case Type::Paren:
1531 case Type::Attributed:
1532 case Type::Auto:
1533 case Type::PackExpansion:
1534 case Type::ObjCObject:
1535 case Type::ObjCInterface:
1536 case Type::ObjCObjectPointer:
1537 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001538 case Type::Pipe:
David Majnemerb8014dd2015-02-19 02:16:16 +00001539 llvm_unreachable("type is illegal as a nested name specifier");
1540
1541 case Type::SubstTemplateTypeParmPack:
1542 // FIXME: not clear how to mangle this!
1543 // template <class T...> class A {
1544 // template <class U...> void foo(decltype(T::foo(U())) x...);
1545 // };
1546 Out << "_SUBSTPACK_";
1547 break;
1548
1549 // <unresolved-type> ::= <template-param>
1550 // ::= <decltype>
1551 // ::= <template-template-param> <template-args>
1552 // (this last is not official yet)
1553 case Type::TypeOfExpr:
1554 case Type::TypeOf:
1555 case Type::Decltype:
1556 case Type::TemplateTypeParm:
1557 case Type::UnaryTransform:
1558 case Type::SubstTemplateTypeParm:
1559 unresolvedType:
1560 // Some callers want a prefix before the mangled type.
1561 Out << Prefix;
1562
1563 // This seems to do everything we want. It's not really
1564 // sanctioned for a substituted template parameter, though.
1565 mangleType(Ty);
1566
1567 // We never want to print 'E' directly after an unresolved-type,
1568 // so we return directly.
1569 return true;
1570
1571 case Type::Typedef:
1572 mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
1573 break;
1574
1575 case Type::UnresolvedUsing:
1576 mangleSourceName(
1577 cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
1578 break;
1579
1580 case Type::Enum:
1581 case Type::Record:
1582 mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
1583 break;
1584
1585 case Type::TemplateSpecialization: {
1586 const TemplateSpecializationType *TST =
1587 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00001588 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00001589 switch (TN.getKind()) {
1590 case TemplateName::Template:
1591 case TemplateName::QualifiedTemplate: {
1592 TemplateDecl *TD = TN.getAsTemplateDecl();
1593
1594 // If the base is a template template parameter, this is an
1595 // unresolved type.
1596 assert(TD && "no template for template specialization type");
1597 if (isa<TemplateTemplateParmDecl>(TD))
1598 goto unresolvedType;
1599
1600 mangleSourceName(TD->getIdentifier());
1601 break;
David Majnemera88b3592015-02-18 02:28:01 +00001602 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001603
1604 case TemplateName::OverloadedTemplate:
1605 case TemplateName::DependentTemplate:
1606 llvm_unreachable("invalid base for a template specialization type");
1607
1608 case TemplateName::SubstTemplateTemplateParm: {
1609 SubstTemplateTemplateParmStorage *subst =
1610 TN.getAsSubstTemplateTemplateParm();
1611 mangleExistingSubstitution(subst->getReplacement());
1612 break;
1613 }
1614
1615 case TemplateName::SubstTemplateTemplateParmPack: {
1616 // FIXME: not clear how to mangle this!
1617 // template <template <class U> class T...> class A {
1618 // template <class U...> void foo(decltype(T<U>::foo) x...);
1619 // };
1620 Out << "_SUBSTPACK_";
1621 break;
1622 }
1623 }
1624
David Majnemera88b3592015-02-18 02:28:01 +00001625 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00001626 break;
David Majnemera88b3592015-02-18 02:28:01 +00001627 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001628
1629 case Type::InjectedClassName:
1630 mangleSourceName(
1631 cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
1632 break;
1633
1634 case Type::DependentName:
1635 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1636 break;
1637
1638 case Type::DependentTemplateSpecialization: {
1639 const DependentTemplateSpecializationType *DTST =
1640 cast<DependentTemplateSpecializationType>(Ty);
1641 mangleSourceName(DTST->getIdentifier());
1642 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1643 break;
1644 }
1645
1646 case Type::Elaborated:
1647 return mangleUnresolvedTypeOrSimpleId(
1648 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1649 }
1650
1651 return false;
David Majnemera88b3592015-02-18 02:28:01 +00001652}
1653
1654void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1655 switch (Name.getNameKind()) {
1656 case DeclarationName::CXXConstructorName:
1657 case DeclarationName::CXXDestructorName:
1658 case DeclarationName::CXXUsingDirective:
1659 case DeclarationName::Identifier:
1660 case DeclarationName::ObjCMultiArgSelector:
1661 case DeclarationName::ObjCOneArgSelector:
1662 case DeclarationName::ObjCZeroArgSelector:
1663 llvm_unreachable("Not an operator name");
1664
1665 case DeclarationName::CXXConversionFunctionName:
1666 // <operator-name> ::= cv <type> # (cast)
1667 Out << "cv";
1668 mangleType(Name.getCXXNameType());
1669 break;
1670
1671 case DeclarationName::CXXLiteralOperatorName:
1672 Out << "li";
1673 mangleSourceName(Name.getCXXLiteralIdentifier());
1674 return;
1675
1676 case DeclarationName::CXXOperatorName:
1677 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1678 break;
1679 }
1680}
1681
1682
1683
Guy Benyei11169dd2012-12-18 14:30:41 +00001684void
1685CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1686 switch (OO) {
1687 // <operator-name> ::= nw # new
1688 case OO_New: Out << "nw"; break;
1689 // ::= na # new[]
1690 case OO_Array_New: Out << "na"; break;
1691 // ::= dl # delete
1692 case OO_Delete: Out << "dl"; break;
1693 // ::= da # delete[]
1694 case OO_Array_Delete: Out << "da"; break;
1695 // ::= ps # + (unary)
1696 // ::= pl # + (binary or unknown)
1697 case OO_Plus:
1698 Out << (Arity == 1? "ps" : "pl"); break;
1699 // ::= ng # - (unary)
1700 // ::= mi # - (binary or unknown)
1701 case OO_Minus:
1702 Out << (Arity == 1? "ng" : "mi"); break;
1703 // ::= ad # & (unary)
1704 // ::= an # & (binary or unknown)
1705 case OO_Amp:
1706 Out << (Arity == 1? "ad" : "an"); break;
1707 // ::= de # * (unary)
1708 // ::= ml # * (binary or unknown)
1709 case OO_Star:
1710 // Use binary when unknown.
1711 Out << (Arity == 1? "de" : "ml"); break;
1712 // ::= co # ~
1713 case OO_Tilde: Out << "co"; break;
1714 // ::= dv # /
1715 case OO_Slash: Out << "dv"; break;
1716 // ::= rm # %
1717 case OO_Percent: Out << "rm"; break;
1718 // ::= or # |
1719 case OO_Pipe: Out << "or"; break;
1720 // ::= eo # ^
1721 case OO_Caret: Out << "eo"; break;
1722 // ::= aS # =
1723 case OO_Equal: Out << "aS"; break;
1724 // ::= pL # +=
1725 case OO_PlusEqual: Out << "pL"; break;
1726 // ::= mI # -=
1727 case OO_MinusEqual: Out << "mI"; break;
1728 // ::= mL # *=
1729 case OO_StarEqual: Out << "mL"; break;
1730 // ::= dV # /=
1731 case OO_SlashEqual: Out << "dV"; break;
1732 // ::= rM # %=
1733 case OO_PercentEqual: Out << "rM"; break;
1734 // ::= aN # &=
1735 case OO_AmpEqual: Out << "aN"; break;
1736 // ::= oR # |=
1737 case OO_PipeEqual: Out << "oR"; break;
1738 // ::= eO # ^=
1739 case OO_CaretEqual: Out << "eO"; break;
1740 // ::= ls # <<
1741 case OO_LessLess: Out << "ls"; break;
1742 // ::= rs # >>
1743 case OO_GreaterGreater: Out << "rs"; break;
1744 // ::= lS # <<=
1745 case OO_LessLessEqual: Out << "lS"; break;
1746 // ::= rS # >>=
1747 case OO_GreaterGreaterEqual: Out << "rS"; break;
1748 // ::= eq # ==
1749 case OO_EqualEqual: Out << "eq"; break;
1750 // ::= ne # !=
1751 case OO_ExclaimEqual: Out << "ne"; break;
1752 // ::= lt # <
1753 case OO_Less: Out << "lt"; break;
1754 // ::= gt # >
1755 case OO_Greater: Out << "gt"; break;
1756 // ::= le # <=
1757 case OO_LessEqual: Out << "le"; break;
1758 // ::= ge # >=
1759 case OO_GreaterEqual: Out << "ge"; break;
1760 // ::= nt # !
1761 case OO_Exclaim: Out << "nt"; break;
1762 // ::= aa # &&
1763 case OO_AmpAmp: Out << "aa"; break;
1764 // ::= oo # ||
1765 case OO_PipePipe: Out << "oo"; break;
1766 // ::= pp # ++
1767 case OO_PlusPlus: Out << "pp"; break;
1768 // ::= mm # --
1769 case OO_MinusMinus: Out << "mm"; break;
1770 // ::= cm # ,
1771 case OO_Comma: Out << "cm"; break;
1772 // ::= pm # ->*
1773 case OO_ArrowStar: Out << "pm"; break;
1774 // ::= pt # ->
1775 case OO_Arrow: Out << "pt"; break;
1776 // ::= cl # ()
1777 case OO_Call: Out << "cl"; break;
1778 // ::= ix # []
1779 case OO_Subscript: Out << "ix"; break;
1780
1781 // ::= qu # ?
1782 // The conditional operator can't be overloaded, but we still handle it when
1783 // mangling expressions.
1784 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00001785 // Proposal on cxx-abi-dev, 2015-10-21.
1786 // ::= aw # co_await
1787 case OO_Coawait: Out << "aw"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001788
1789 case OO_None:
1790 case NUM_OVERLOADED_OPERATORS:
1791 llvm_unreachable("Not an overloaded operator");
1792 }
1793}
1794
1795void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
John McCall07daf722016-03-01 22:18:03 +00001796 // Vendor qualifiers come first.
Guy Benyei11169dd2012-12-18 14:30:41 +00001797
John McCall07daf722016-03-01 22:18:03 +00001798 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00001799 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00001800 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00001801 //
David Tweed31d09b02013-09-13 12:04:22 +00001802 // <type> ::= U <target-addrspace>
1803 // <type> ::= U <OpenCL-addrspace>
1804 // <type> ::= U <CUDA-addrspace>
1805
Guy Benyei11169dd2012-12-18 14:30:41 +00001806 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00001807 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00001808
1809 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1810 // <target-addrspace> ::= "AS" <address-space-number>
1811 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Craig Topperf42e0312016-01-31 04:20:03 +00001812 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00001813 } else {
1814 switch (AS) {
1815 default: llvm_unreachable("Not a language specific address space");
1816 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1817 case LangAS::opencl_global: ASString = "CLglobal"; break;
1818 case LangAS::opencl_local: ASString = "CLlocal"; break;
1819 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1820 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1821 case LangAS::cuda_device: ASString = "CUdevice"; break;
1822 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1823 case LangAS::cuda_shared: ASString = "CUshared"; break;
1824 }
1825 }
John McCall07daf722016-03-01 22:18:03 +00001826 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00001827 }
John McCall07daf722016-03-01 22:18:03 +00001828
1829 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00001830 switch (Quals.getObjCLifetime()) {
1831 // Objective-C ARC Extension:
1832 //
1833 // <type> ::= U "__strong"
1834 // <type> ::= U "__weak"
1835 // <type> ::= U "__autoreleasing"
1836 case Qualifiers::OCL_None:
1837 break;
1838
1839 case Qualifiers::OCL_Weak:
John McCall07daf722016-03-01 22:18:03 +00001840 mangleVendorQualifier("__weak");
Guy Benyei11169dd2012-12-18 14:30:41 +00001841 break;
1842
1843 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00001844 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00001845 break;
1846
1847 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00001848 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00001849 break;
1850
1851 case Qualifiers::OCL_ExplicitNone:
1852 // The __unsafe_unretained qualifier is *not* mangled, so that
1853 // __unsafe_unretained types in ARC produce the same manglings as the
1854 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1855 // better ABI compatibility.
1856 //
1857 // It's safe to do this because unqualified 'id' won't show up
1858 // in any type signatures that need to be mangled.
1859 break;
1860 }
John McCall07daf722016-03-01 22:18:03 +00001861
1862 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1863 if (Quals.hasRestrict())
1864 Out << 'r';
1865 if (Quals.hasVolatile())
1866 Out << 'V';
1867 if (Quals.hasConst())
1868 Out << 'K';
1869}
1870
1871void CXXNameMangler::mangleVendorQualifier(StringRef name) {
1872 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00001873}
1874
1875void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1876 // <ref-qualifier> ::= R # lvalue reference
1877 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00001878 switch (RefQualifier) {
1879 case RQ_None:
1880 break;
1881
1882 case RQ_LValue:
1883 Out << 'R';
1884 break;
1885
1886 case RQ_RValue:
1887 Out << 'O';
1888 break;
1889 }
1890}
1891
1892void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1893 Context.mangleObjCMethodName(MD, Out);
1894}
1895
David Majnemereea02ee2014-11-28 22:22:46 +00001896static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1897 if (Quals)
1898 return true;
1899 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1900 return true;
1901 if (Ty->isOpenCLSpecificType())
1902 return true;
1903 if (Ty->isBuiltinType())
1904 return false;
1905
1906 return true;
1907}
1908
Guy Benyei11169dd2012-12-18 14:30:41 +00001909void CXXNameMangler::mangleType(QualType T) {
1910 // If our type is instantiation-dependent but not dependent, we mangle
1911 // it as it was written in the source, removing any top-level sugar.
1912 // Otherwise, use the canonical type.
1913 //
1914 // FIXME: This is an approximation of the instantiation-dependent name
1915 // mangling rules, since we should really be using the type as written and
1916 // augmented via semantic analysis (i.e., with implicit conversions and
1917 // default template arguments) for any instantiation-dependent type.
1918 // Unfortunately, that requires several changes to our AST:
1919 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1920 // uniqued, so that we can handle substitutions properly
1921 // - Default template arguments will need to be represented in the
1922 // TemplateSpecializationType, since they need to be mangled even though
1923 // they aren't written.
1924 // - Conversions on non-type template arguments need to be expressed, since
1925 // they can affect the mangling of sizeof/alignof.
1926 if (!T->isInstantiationDependentType() || T->isDependentType())
1927 T = T.getCanonicalType();
1928 else {
1929 // Desugar any types that are purely sugar.
1930 do {
1931 // Don't desugar through template specialization types that aren't
1932 // type aliases. We need to mangle the template arguments as written.
1933 if (const TemplateSpecializationType *TST
1934 = dyn_cast<TemplateSpecializationType>(T))
1935 if (!TST->isTypeAlias())
1936 break;
1937
1938 QualType Desugared
1939 = T.getSingleStepDesugaredType(Context.getASTContext());
1940 if (Desugared == T)
1941 break;
1942
1943 T = Desugared;
1944 } while (true);
1945 }
1946 SplitQualType split = T.split();
1947 Qualifiers quals = split.Quals;
1948 const Type *ty = split.Ty;
1949
David Majnemereea02ee2014-11-28 22:22:46 +00001950 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001951 if (isSubstitutable && mangleSubstitution(T))
1952 return;
1953
1954 // If we're mangling a qualified array type, push the qualifiers to
1955 // the element type.
1956 if (quals && isa<ArrayType>(T)) {
1957 ty = Context.getASTContext().getAsArrayType(T);
1958 quals = Qualifiers();
1959
1960 // Note that we don't update T: we want to add the
1961 // substitution at the original type.
1962 }
1963
1964 if (quals) {
1965 mangleQualifiers(quals);
1966 // Recurse: even if the qualified type isn't yet substitutable,
1967 // the unqualified type might be.
1968 mangleType(QualType(ty, 0));
1969 } else {
1970 switch (ty->getTypeClass()) {
1971#define ABSTRACT_TYPE(CLASS, PARENT)
1972#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1973 case Type::CLASS: \
1974 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1975 return;
1976#define TYPE(CLASS, PARENT) \
1977 case Type::CLASS: \
1978 mangleType(static_cast<const CLASS##Type*>(ty)); \
1979 break;
1980#include "clang/AST/TypeNodes.def"
1981 }
1982 }
1983
1984 // Add the substitution.
1985 if (isSubstitutable)
1986 addSubstitution(T);
1987}
1988
1989void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1990 if (!mangleStandardSubstitution(ND))
1991 mangleName(ND);
1992}
1993
1994void CXXNameMangler::mangleType(const BuiltinType *T) {
1995 // <type> ::= <builtin-type>
1996 // <builtin-type> ::= v # void
1997 // ::= w # wchar_t
1998 // ::= b # bool
1999 // ::= c # char
2000 // ::= a # signed char
2001 // ::= h # unsigned char
2002 // ::= s # short
2003 // ::= t # unsigned short
2004 // ::= i # int
2005 // ::= j # unsigned int
2006 // ::= l # long
2007 // ::= m # unsigned long
2008 // ::= x # long long, __int64
2009 // ::= y # unsigned long long, __int64
2010 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002011 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002012 // ::= f # float
2013 // ::= d # double
2014 // ::= e # long double, __float80
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002015 // ::= g # __float128
Guy Benyei11169dd2012-12-18 14:30:41 +00002016 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2017 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2018 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2019 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2020 // ::= Di # char32_t
2021 // ::= Ds # char16_t
2022 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2023 // ::= u <source-name> # vendor extended type
Alexey Bader954ba212016-04-08 13:40:33 +00002024 std::string type_name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002025 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002026 case BuiltinType::Void:
2027 Out << 'v';
2028 break;
2029 case BuiltinType::Bool:
2030 Out << 'b';
2031 break;
2032 case BuiltinType::Char_U:
2033 case BuiltinType::Char_S:
2034 Out << 'c';
2035 break;
2036 case BuiltinType::UChar:
2037 Out << 'h';
2038 break;
2039 case BuiltinType::UShort:
2040 Out << 't';
2041 break;
2042 case BuiltinType::UInt:
2043 Out << 'j';
2044 break;
2045 case BuiltinType::ULong:
2046 Out << 'm';
2047 break;
2048 case BuiltinType::ULongLong:
2049 Out << 'y';
2050 break;
2051 case BuiltinType::UInt128:
2052 Out << 'o';
2053 break;
2054 case BuiltinType::SChar:
2055 Out << 'a';
2056 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002057 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002058 case BuiltinType::WChar_U:
2059 Out << 'w';
2060 break;
2061 case BuiltinType::Char16:
2062 Out << "Ds";
2063 break;
2064 case BuiltinType::Char32:
2065 Out << "Di";
2066 break;
2067 case BuiltinType::Short:
2068 Out << 's';
2069 break;
2070 case BuiltinType::Int:
2071 Out << 'i';
2072 break;
2073 case BuiltinType::Long:
2074 Out << 'l';
2075 break;
2076 case BuiltinType::LongLong:
2077 Out << 'x';
2078 break;
2079 case BuiltinType::Int128:
2080 Out << 'n';
2081 break;
2082 case BuiltinType::Half:
2083 Out << "Dh";
2084 break;
2085 case BuiltinType::Float:
2086 Out << 'f';
2087 break;
2088 case BuiltinType::Double:
2089 Out << 'd';
2090 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002091 case BuiltinType::LongDouble:
2092 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2093 ? 'g'
2094 : 'e');
2095 break;
Nemanja Ivanovicbb1ea2d2016-05-09 08:52:33 +00002096 case BuiltinType::Float128:
2097 if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2098 Out << "U10__float128"; // Match the GCC mangling
2099 else
2100 Out << 'g';
2101 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002102 case BuiltinType::NullPtr:
2103 Out << "Dn";
2104 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002105
2106#define BUILTIN_TYPE(Id, SingletonId)
2107#define PLACEHOLDER_TYPE(Id, SingletonId) \
2108 case BuiltinType::Id:
2109#include "clang/AST/BuiltinTypes.def"
2110 case BuiltinType::Dependent:
2111 llvm_unreachable("mangling a placeholder type");
Alexey Baderbdf7c842015-09-15 12:18:29 +00002112 case BuiltinType::ObjCId:
2113 Out << "11objc_object";
2114 break;
2115 case BuiltinType::ObjCClass:
2116 Out << "10objc_class";
2117 break;
2118 case BuiltinType::ObjCSel:
2119 Out << "13objc_selector";
2120 break;
Alexey Bader954ba212016-04-08 13:40:33 +00002121#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2122 case BuiltinType::Id: \
2123 type_name = "ocl_" #ImgType "_" #Suffix; \
2124 Out << type_name.size() << type_name; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00002125 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00002126#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00002127 case BuiltinType::OCLSampler:
2128 Out << "11ocl_sampler";
2129 break;
2130 case BuiltinType::OCLEvent:
2131 Out << "9ocl_event";
2132 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002133 case BuiltinType::OCLClkEvent:
2134 Out << "12ocl_clkevent";
2135 break;
2136 case BuiltinType::OCLQueue:
2137 Out << "9ocl_queue";
2138 break;
2139 case BuiltinType::OCLNDRange:
2140 Out << "11ocl_ndrange";
2141 break;
2142 case BuiltinType::OCLReserveID:
2143 Out << "13ocl_reserveid";
2144 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002145 }
2146}
2147
John McCall07daf722016-03-01 22:18:03 +00002148StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2149 switch (CC) {
2150 case CC_C:
2151 return "";
2152
2153 case CC_X86StdCall:
2154 case CC_X86FastCall:
2155 case CC_X86ThisCall:
2156 case CC_X86VectorCall:
2157 case CC_X86Pascal:
2158 case CC_X86_64Win64:
2159 case CC_X86_64SysV:
2160 case CC_AAPCS:
2161 case CC_AAPCS_VFP:
2162 case CC_IntelOclBicc:
2163 case CC_SpirFunction:
2164 case CC_SpirKernel:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00002165 case CC_PreserveMost:
2166 case CC_PreserveAll:
John McCall07daf722016-03-01 22:18:03 +00002167 // FIXME: we should be mangling all of the above.
2168 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002169
2170 case CC_Swift:
2171 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002172 }
2173 llvm_unreachable("bad calling convention");
2174}
2175
2176void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2177 // Fast path.
2178 if (T->getExtInfo() == FunctionType::ExtInfo())
2179 return;
2180
2181 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2182 // This will get more complicated in the future if we mangle other
2183 // things here; but for now, since we mangle ns_returns_retained as
2184 // a qualifier on the result type, we can get away with this:
2185 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2186 if (!CCQualifier.empty())
2187 mangleVendorQualifier(CCQualifier);
2188
2189 // FIXME: regparm
2190 // FIXME: noreturn
2191}
2192
2193void
2194CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2195 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2196
2197 // Note that these are *not* substitution candidates. Demanglers might
2198 // have trouble with this if the parameter type is fully substituted.
2199
John McCall477f2bb2016-03-03 06:39:32 +00002200 switch (PI.getABI()) {
2201 case ParameterABI::Ordinary:
2202 break;
2203
2204 // All of these start with "swift", so they come before "ns_consumed".
2205 case ParameterABI::SwiftContext:
2206 case ParameterABI::SwiftErrorResult:
2207 case ParameterABI::SwiftIndirectResult:
2208 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2209 break;
2210 }
2211
John McCall07daf722016-03-01 22:18:03 +00002212 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002213 mangleVendorQualifier("ns_consumed");
John McCall07daf722016-03-01 22:18:03 +00002214}
2215
Guy Benyei11169dd2012-12-18 14:30:41 +00002216// <type> ::= <function-type>
2217// <function-type> ::= [<CV-qualifiers>] F [Y]
2218// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002219void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002220 mangleExtFunctionInfo(T);
2221
Guy Benyei11169dd2012-12-18 14:30:41 +00002222 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2223 // e.g. "const" in "int (A::*)() const".
2224 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2225
2226 Out << 'F';
2227
2228 // FIXME: We don't have enough information in the AST to produce the 'Y'
2229 // encoding for extern "C" function types.
2230 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2231
2232 // Mangle the ref-qualifier, if present.
2233 mangleRefQualifier(T->getRefQualifier());
2234
2235 Out << 'E';
2236}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002237
Guy Benyei11169dd2012-12-18 14:30:41 +00002238void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002239 // Function types without prototypes can arise when mangling a function type
2240 // within an overloadable function in C. We mangle these as the absence of any
2241 // parameter types (not even an empty parameter list).
2242 Out << 'F';
2243
2244 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2245
2246 FunctionTypeDepth.enterResultType();
2247 mangleType(T->getReturnType());
2248 FunctionTypeDepth.leaveResultType();
2249
2250 FunctionTypeDepth.pop(saved);
2251 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002252}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002253
John McCall07daf722016-03-01 22:18:03 +00002254void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002255 bool MangleReturnType,
2256 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002257 // Record that we're in a function type. See mangleFunctionParam
2258 // for details on what we're trying to achieve here.
2259 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2260
2261 // <bare-function-type> ::= <signature type>+
2262 if (MangleReturnType) {
2263 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002264
2265 // Mangle ns_returns_retained as an order-sensitive qualifier here.
Nico Weberfb420782016-05-25 14:15:08 +00002266 if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
John McCall07daf722016-03-01 22:18:03 +00002267 mangleVendorQualifier("ns_returns_retained");
2268
2269 // Mangle the return type without any direct ARC ownership qualifiers.
2270 QualType ReturnTy = Proto->getReturnType();
2271 if (ReturnTy.getObjCLifetime()) {
2272 auto SplitReturnTy = ReturnTy.split();
2273 SplitReturnTy.Quals.removeObjCLifetime();
2274 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2275 }
2276 mangleType(ReturnTy);
2277
Guy Benyei11169dd2012-12-18 14:30:41 +00002278 FunctionTypeDepth.leaveResultType();
2279 }
2280
Alp Toker9cacbab2014-01-20 20:26:09 +00002281 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002282 // <builtin-type> ::= v # void
2283 Out << 'v';
2284
2285 FunctionTypeDepth.pop(saved);
2286 return;
2287 }
2288
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002289 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2290 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002291 // Mangle extended parameter info as order-sensitive qualifiers here.
Nico Weberfb420782016-05-25 14:15:08 +00002292 if (Proto->hasExtParameterInfos() && FD == nullptr) {
John McCall07daf722016-03-01 22:18:03 +00002293 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2294 }
2295
2296 // Mangle the type.
2297 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002298 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2299
2300 if (FD) {
2301 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2302 // Attr can only take 1 character, so we can hardcode the length below.
2303 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2304 Out << "U17pass_object_size" << Attr->getType();
2305 }
2306 }
2307 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002308
2309 FunctionTypeDepth.pop(saved);
2310
2311 // <builtin-type> ::= z # ellipsis
2312 if (Proto->isVariadic())
2313 Out << 'z';
2314}
2315
2316// <type> ::= <class-enum-type>
2317// <class-enum-type> ::= <name>
2318void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2319 mangleName(T->getDecl());
2320}
2321
2322// <type> ::= <class-enum-type>
2323// <class-enum-type> ::= <name>
2324void CXXNameMangler::mangleType(const EnumType *T) {
2325 mangleType(static_cast<const TagType*>(T));
2326}
2327void CXXNameMangler::mangleType(const RecordType *T) {
2328 mangleType(static_cast<const TagType*>(T));
2329}
2330void CXXNameMangler::mangleType(const TagType *T) {
2331 mangleName(T->getDecl());
2332}
2333
2334// <type> ::= <array-type>
2335// <array-type> ::= A <positive dimension number> _ <element type>
2336// ::= A [<dimension expression>] _ <element type>
2337void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2338 Out << 'A' << T->getSize() << '_';
2339 mangleType(T->getElementType());
2340}
2341void CXXNameMangler::mangleType(const VariableArrayType *T) {
2342 Out << 'A';
2343 // decayed vla types (size 0) will just be skipped.
2344 if (T->getSizeExpr())
2345 mangleExpression(T->getSizeExpr());
2346 Out << '_';
2347 mangleType(T->getElementType());
2348}
2349void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2350 Out << 'A';
2351 mangleExpression(T->getSizeExpr());
2352 Out << '_';
2353 mangleType(T->getElementType());
2354}
2355void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2356 Out << "A_";
2357 mangleType(T->getElementType());
2358}
2359
2360// <type> ::= <pointer-to-member-type>
2361// <pointer-to-member-type> ::= M <class type> <member type>
2362void CXXNameMangler::mangleType(const MemberPointerType *T) {
2363 Out << 'M';
2364 mangleType(QualType(T->getClass(), 0));
2365 QualType PointeeType = T->getPointeeType();
2366 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2367 mangleType(FPT);
2368
2369 // Itanium C++ ABI 5.1.8:
2370 //
2371 // The type of a non-static member function is considered to be different,
2372 // for the purposes of substitution, from the type of a namespace-scope or
2373 // static member function whose type appears similar. The types of two
2374 // non-static member functions are considered to be different, for the
2375 // purposes of substitution, if the functions are members of different
2376 // classes. In other words, for the purposes of substitution, the class of
2377 // which the function is a member is considered part of the type of
2378 // function.
2379
2380 // Given that we already substitute member function pointers as a
2381 // whole, the net effect of this rule is just to unconditionally
2382 // suppress substitution on the function type in a member pointer.
2383 // We increment the SeqID here to emulate adding an entry to the
2384 // substitution table.
2385 ++SeqID;
2386 } else
2387 mangleType(PointeeType);
2388}
2389
2390// <type> ::= <template-param>
2391void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2392 mangleTemplateParameter(T->getIndex());
2393}
2394
2395// <type> ::= <template-param>
2396void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2397 // FIXME: not clear how to mangle this!
2398 // template <class T...> class A {
2399 // template <class U...> void foo(T(*)(U) x...);
2400 // };
2401 Out << "_SUBSTPACK_";
2402}
2403
2404// <type> ::= P <type> # pointer-to
2405void CXXNameMangler::mangleType(const PointerType *T) {
2406 Out << 'P';
2407 mangleType(T->getPointeeType());
2408}
2409void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2410 Out << 'P';
2411 mangleType(T->getPointeeType());
2412}
2413
2414// <type> ::= R <type> # reference-to
2415void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2416 Out << 'R';
2417 mangleType(T->getPointeeType());
2418}
2419
2420// <type> ::= O <type> # rvalue reference-to (C++0x)
2421void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2422 Out << 'O';
2423 mangleType(T->getPointeeType());
2424}
2425
2426// <type> ::= C <type> # complex pair (C 2000)
2427void CXXNameMangler::mangleType(const ComplexType *T) {
2428 Out << 'C';
2429 mangleType(T->getElementType());
2430}
2431
2432// ARM's ABI for Neon vector types specifies that they should be mangled as
2433// if they are structs (to match ARM's initial implementation). The
2434// vector type must be one of the special types predefined by ARM.
2435void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2436 QualType EltType = T->getElementType();
2437 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002438 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2440 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002441 case BuiltinType::SChar:
2442 case BuiltinType::UChar:
2443 EltName = "poly8_t";
2444 break;
2445 case BuiltinType::Short:
2446 case BuiltinType::UShort:
2447 EltName = "poly16_t";
2448 break;
2449 case BuiltinType::ULongLong:
2450 EltName = "poly64_t";
2451 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002452 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2453 }
2454 } else {
2455 switch (cast<BuiltinType>(EltType)->getKind()) {
2456 case BuiltinType::SChar: EltName = "int8_t"; break;
2457 case BuiltinType::UChar: EltName = "uint8_t"; break;
2458 case BuiltinType::Short: EltName = "int16_t"; break;
2459 case BuiltinType::UShort: EltName = "uint16_t"; break;
2460 case BuiltinType::Int: EltName = "int32_t"; break;
2461 case BuiltinType::UInt: EltName = "uint32_t"; break;
2462 case BuiltinType::LongLong: EltName = "int64_t"; break;
2463 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002464 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002465 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002466 case BuiltinType::Half: EltName = "float16_t";break;
2467 default:
2468 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002469 }
2470 }
Craig Topper36250ad2014-05-12 05:36:57 +00002471 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002472 unsigned BitSize = (T->getNumElements() *
2473 getASTContext().getTypeSize(EltType));
2474 if (BitSize == 64)
2475 BaseName = "__simd64_";
2476 else {
2477 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2478 BaseName = "__simd128_";
2479 }
2480 Out << strlen(BaseName) + strlen(EltName);
2481 Out << BaseName << EltName;
2482}
2483
Tim Northover2fe823a2013-08-01 09:23:19 +00002484static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2485 switch (EltType->getKind()) {
2486 case BuiltinType::SChar:
2487 return "Int8";
2488 case BuiltinType::Short:
2489 return "Int16";
2490 case BuiltinType::Int:
2491 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002492 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002493 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002494 return "Int64";
2495 case BuiltinType::UChar:
2496 return "Uint8";
2497 case BuiltinType::UShort:
2498 return "Uint16";
2499 case BuiltinType::UInt:
2500 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002501 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002502 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002503 return "Uint64";
2504 case BuiltinType::Half:
2505 return "Float16";
2506 case BuiltinType::Float:
2507 return "Float32";
2508 case BuiltinType::Double:
2509 return "Float64";
2510 default:
2511 llvm_unreachable("Unexpected vector element base type");
2512 }
2513}
2514
2515// AArch64's ABI for Neon vector types specifies that they should be mangled as
2516// the equivalent internal name. The vector type must be one of the special
2517// types predefined by ARM.
2518void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2519 QualType EltType = T->getElementType();
2520 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2521 unsigned BitSize =
2522 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002523 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002524
2525 assert((BitSize == 64 || BitSize == 128) &&
2526 "Neon vector type not 64 or 128 bits");
2527
Tim Northover2fe823a2013-08-01 09:23:19 +00002528 StringRef EltName;
2529 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2530 switch (cast<BuiltinType>(EltType)->getKind()) {
2531 case BuiltinType::UChar:
2532 EltName = "Poly8";
2533 break;
2534 case BuiltinType::UShort:
2535 EltName = "Poly16";
2536 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002537 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00002538 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002539 EltName = "Poly64";
2540 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002541 default:
2542 llvm_unreachable("unexpected Neon polynomial vector element type");
2543 }
2544 } else
2545 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2546
2547 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00002548 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00002549 Out << TypeName.length() << TypeName;
2550}
2551
Guy Benyei11169dd2012-12-18 14:30:41 +00002552// GNU extension: vector types
2553// <type> ::= <vector-type>
2554// <vector-type> ::= Dv <positive dimension number> _
2555// <extended element type>
2556// ::= Dv [<dimension expression>] _ <element type>
2557// <extended element type> ::= <element type>
2558// ::= p # AltiVec vector pixel
2559// ::= b # Altivec vector bool
2560void CXXNameMangler::mangleType(const VectorType *T) {
2561 if ((T->getVectorKind() == VectorType::NeonVector ||
2562 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002563 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00002564 llvm::Triple::ArchType Arch =
2565 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00002566 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00002567 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00002568 mangleAArch64NeonVectorType(T);
2569 else
2570 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00002571 return;
2572 }
2573 Out << "Dv" << T->getNumElements() << '_';
2574 if (T->getVectorKind() == VectorType::AltiVecPixel)
2575 Out << 'p';
2576 else if (T->getVectorKind() == VectorType::AltiVecBool)
2577 Out << 'b';
2578 else
2579 mangleType(T->getElementType());
2580}
2581void CXXNameMangler::mangleType(const ExtVectorType *T) {
2582 mangleType(static_cast<const VectorType*>(T));
2583}
2584void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2585 Out << "Dv";
2586 mangleExpression(T->getSizeExpr());
2587 Out << '_';
2588 mangleType(T->getElementType());
2589}
2590
2591void CXXNameMangler::mangleType(const PackExpansionType *T) {
2592 // <type> ::= Dp <type> # pack expansion (C++0x)
2593 Out << "Dp";
2594 mangleType(T->getPattern());
2595}
2596
2597void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2598 mangleSourceName(T->getDecl()->getIdentifier());
2599}
2600
2601void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002602 // Treat __kindof as a vendor extended type qualifier.
2603 if (T->isKindOfType())
2604 Out << "U8__kindof";
2605
Eli Friedman5f508952013-06-18 22:41:37 +00002606 if (!T->qual_empty()) {
2607 // Mangle protocol qualifiers.
2608 SmallString<64> QualStr;
2609 llvm::raw_svector_ostream QualOS(QualStr);
2610 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00002611 for (const auto *I : T->quals()) {
2612 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00002613 QualOS << name.size() << name;
2614 }
Eli Friedman5f508952013-06-18 22:41:37 +00002615 Out << 'U' << QualStr.size() << QualStr;
2616 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002617
Guy Benyei11169dd2012-12-18 14:30:41 +00002618 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00002619
2620 if (T->isSpecialized()) {
2621 // Mangle type arguments as I <type>+ E
2622 Out << 'I';
2623 for (auto typeArg : T->getTypeArgs())
2624 mangleType(typeArg);
2625 Out << 'E';
2626 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002627}
2628
2629void CXXNameMangler::mangleType(const BlockPointerType *T) {
2630 Out << "U13block_pointer";
2631 mangleType(T->getPointeeType());
2632}
2633
2634void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2635 // Mangle injected class name types as if the user had written the
2636 // specialization out fully. It may not actually be possible to see
2637 // this mangling, though.
2638 mangleType(T->getInjectedSpecializationType());
2639}
2640
2641void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2642 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2643 mangleName(TD, T->getArgs(), T->getNumArgs());
2644 } else {
2645 if (mangleSubstitution(QualType(T, 0)))
2646 return;
2647
2648 mangleTemplatePrefix(T->getTemplateName());
2649
2650 // FIXME: GCC does not appear to mangle the template arguments when
2651 // the template in question is a dependent template name. Should we
2652 // emulate that badness?
2653 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2654 addSubstitution(QualType(T, 0));
2655 }
2656}
2657
2658void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00002659 // Proposal by cxx-abi-dev, 2014-03-26
2660 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2661 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002662 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00002663 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002664 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00002665 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002666 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00002667 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002668 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00002669 switch (T->getKeyword()) {
2670 case ETK_Typename:
2671 break;
2672 case ETK_Struct:
2673 case ETK_Class:
2674 case ETK_Interface:
2675 Out << "Ts";
2676 break;
2677 case ETK_Union:
2678 Out << "Tu";
2679 break;
2680 case ETK_Enum:
2681 Out << "Te";
2682 break;
2683 default:
2684 llvm_unreachable("unexpected keyword for dependent type name");
2685 }
David Majnemer2e159fb2014-04-15 05:51:25 +00002686 // Typename types are always nested
2687 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00002688 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00002689 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00002690 Out << 'E';
2691}
2692
2693void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2694 // Dependently-scoped template types are nested if they have a prefix.
2695 Out << 'N';
2696
2697 // TODO: avoid making this TemplateName.
2698 TemplateName Prefix =
2699 getASTContext().getDependentTemplateName(T->getQualifier(),
2700 T->getIdentifier());
2701 mangleTemplatePrefix(Prefix);
2702
2703 // FIXME: GCC does not appear to mangle the template arguments when
2704 // the template in question is a dependent template name. Should we
2705 // emulate that badness?
2706 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2707 Out << 'E';
2708}
2709
2710void CXXNameMangler::mangleType(const TypeOfType *T) {
2711 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2712 // "extension with parameters" mangling.
2713 Out << "u6typeof";
2714}
2715
2716void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2717 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2718 // "extension with parameters" mangling.
2719 Out << "u6typeof";
2720}
2721
2722void CXXNameMangler::mangleType(const DecltypeType *T) {
2723 Expr *E = T->getUnderlyingExpr();
2724
2725 // type ::= Dt <expression> E # decltype of an id-expression
2726 // # or class member access
2727 // ::= DT <expression> E # decltype of an expression
2728
2729 // This purports to be an exhaustive list of id-expressions and
2730 // class member accesses. Note that we do not ignore parentheses;
2731 // parentheses change the semantics of decltype for these
2732 // expressions (and cause the mangler to use the other form).
2733 if (isa<DeclRefExpr>(E) ||
2734 isa<MemberExpr>(E) ||
2735 isa<UnresolvedLookupExpr>(E) ||
2736 isa<DependentScopeDeclRefExpr>(E) ||
2737 isa<CXXDependentScopeMemberExpr>(E) ||
2738 isa<UnresolvedMemberExpr>(E))
2739 Out << "Dt";
2740 else
2741 Out << "DT";
2742 mangleExpression(E);
2743 Out << 'E';
2744}
2745
2746void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2747 // If this is dependent, we need to record that. If not, we simply
2748 // mangle it as the underlying type since they are equivalent.
2749 if (T->isDependentType()) {
2750 Out << 'U';
2751
2752 switch (T->getUTTKind()) {
2753 case UnaryTransformType::EnumUnderlyingType:
2754 Out << "3eut";
2755 break;
2756 }
2757 }
2758
David Majnemer140065a2016-06-08 00:34:15 +00002759 mangleType(T->getBaseType());
Guy Benyei11169dd2012-12-18 14:30:41 +00002760}
2761
2762void CXXNameMangler::mangleType(const AutoType *T) {
2763 QualType D = T->getDeducedType();
2764 // <builtin-type> ::= Da # dependent auto
Richard Smithe301ba22015-11-11 02:02:15 +00002765 if (D.isNull()) {
2766 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2767 "shouldn't need to mangle __auto_type!");
Richard Smith74aeef52013-04-26 16:15:35 +00002768 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Richard Smithe301ba22015-11-11 02:02:15 +00002769 } else
Guy Benyei11169dd2012-12-18 14:30:41 +00002770 mangleType(D);
2771}
2772
2773void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00002774 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00002775 // (Until there's a standardized mangling...)
2776 Out << "U7_Atomic";
2777 mangleType(T->getValueType());
2778}
2779
Xiuli Pan9c14e282016-01-09 12:53:17 +00002780void CXXNameMangler::mangleType(const PipeType *T) {
2781 // Pipe type mangling rules are described in SPIR 2.0 specification
2782 // A.1 Data types and A.3 Summary of changes
2783 // <type> ::= 8ocl_pipe
2784 Out << "8ocl_pipe";
2785}
2786
Guy Benyei11169dd2012-12-18 14:30:41 +00002787void CXXNameMangler::mangleIntegerLiteral(QualType T,
2788 const llvm::APSInt &Value) {
2789 // <expr-primary> ::= L <type> <value number> E # integer literal
2790 Out << 'L';
2791
2792 mangleType(T);
2793 if (T->isBooleanType()) {
2794 // Boolean values are encoded as 0/1.
2795 Out << (Value.getBoolValue() ? '1' : '0');
2796 } else {
2797 mangleNumber(Value);
2798 }
2799 Out << 'E';
2800
2801}
2802
David Majnemer1dabfdc2015-02-14 13:23:54 +00002803void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2804 // Ignore member expressions involving anonymous unions.
2805 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2806 if (!RT->getDecl()->isAnonymousStructOrUnion())
2807 break;
2808 const auto *ME = dyn_cast<MemberExpr>(Base);
2809 if (!ME)
2810 break;
2811 Base = ME->getBase();
2812 IsArrow = ME->isArrow();
2813 }
2814
2815 if (Base->isImplicitCXXThis()) {
2816 // Note: GCC mangles member expressions to the implicit 'this' as
2817 // *this., whereas we represent them as this->. The Itanium C++ ABI
2818 // does not specify anything here, so we follow GCC.
2819 Out << "dtdefpT";
2820 } else {
2821 Out << (IsArrow ? "pt" : "dt");
2822 mangleExpression(Base);
2823 }
2824}
2825
Guy Benyei11169dd2012-12-18 14:30:41 +00002826/// Mangles a member expression.
2827void CXXNameMangler::mangleMemberExpr(const Expr *base,
2828 bool isArrow,
2829 NestedNameSpecifier *qualifier,
2830 NamedDecl *firstQualifierLookup,
2831 DeclarationName member,
2832 unsigned arity) {
2833 // <expression> ::= dt <expression> <unresolved-name>
2834 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00002835 if (base)
2836 mangleMemberExprBase(base, isArrow);
David Majnemerb8014dd2015-02-19 02:16:16 +00002837 mangleUnresolvedName(qualifier, member, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002838}
2839
2840/// Look at the callee of the given call expression and determine if
2841/// it's a parenthesized id-expression which would have triggered ADL
2842/// otherwise.
2843static bool isParenthesizedADLCallee(const CallExpr *call) {
2844 const Expr *callee = call->getCallee();
2845 const Expr *fn = callee->IgnoreParens();
2846
2847 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2848 // too, but for those to appear in the callee, it would have to be
2849 // parenthesized.
2850 if (callee == fn) return false;
2851
2852 // Must be an unresolved lookup.
2853 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2854 if (!lookup) return false;
2855
2856 assert(!lookup->requiresADL());
2857
2858 // Must be an unqualified lookup.
2859 if (lookup->getQualifier()) return false;
2860
2861 // Must not have found a class member. Note that if one is a class
2862 // member, they're all class members.
2863 if (lookup->getNumDecls() > 0 &&
2864 (*lookup->decls_begin())->isCXXClassMember())
2865 return false;
2866
2867 // Otherwise, ADL would have been triggered.
2868 return true;
2869}
2870
David Majnemer9c775c72014-09-23 04:27:55 +00002871void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2872 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2873 Out << CastEncoding;
2874 mangleType(ECE->getType());
2875 mangleExpression(ECE->getSubExpr());
2876}
2877
Richard Smith520449d2015-02-05 06:15:50 +00002878void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2879 if (auto *Syntactic = InitList->getSyntacticForm())
2880 InitList = Syntactic;
2881 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2882 mangleExpression(InitList->getInit(i));
2883}
2884
Guy Benyei11169dd2012-12-18 14:30:41 +00002885void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2886 // <expression> ::= <unary operator-name> <expression>
2887 // ::= <binary operator-name> <expression> <expression>
2888 // ::= <trinary operator-name> <expression> <expression> <expression>
2889 // ::= cv <type> expression # conversion with one argument
2890 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00002891 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2892 // ::= sc <type> <expression> # static_cast<type> (expression)
2893 // ::= cc <type> <expression> # const_cast<type> (expression)
2894 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00002895 // ::= st <type> # sizeof (a type)
2896 // ::= at <type> # alignof (a type)
2897 // ::= <template-param>
2898 // ::= <function-param>
2899 // ::= sr <type> <unqualified-name> # dependent name
2900 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2901 // ::= ds <expression> <expression> # expr.*expr
2902 // ::= sZ <template-param> # size of a parameter pack
2903 // ::= sZ <function-param> # size of a function parameter pack
2904 // ::= <expr-primary>
2905 // <expr-primary> ::= L <type> <value number> E # integer literal
2906 // ::= L <type <value float> E # floating literal
2907 // ::= L <mangled-name> E # external name
2908 // ::= fpT # 'this' expression
2909 QualType ImplicitlyConvertedToType;
2910
2911recurse:
2912 switch (E->getStmtClass()) {
2913 case Expr::NoStmtClass:
2914#define ABSTRACT_STMT(Type)
2915#define EXPR(Type, Base)
2916#define STMT(Type, Base) \
2917 case Expr::Type##Class:
2918#include "clang/AST/StmtNodes.inc"
2919 // fallthrough
2920
2921 // These all can only appear in local or variable-initialization
2922 // contexts and so should never appear in a mangling.
2923 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002924 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002925 case Expr::ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002926 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002927 case Expr::ParenListExprClass:
2928 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00002929 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00002930 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002931 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00002932 case Expr::OMPArraySectionExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00002933 case Expr::CXXInheritedCtorInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 llvm_unreachable("unexpected statement kind");
2935
2936 // FIXME: invent manglings for all these.
2937 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 case Expr::ChooseExprClass:
2939 case Expr::CompoundLiteralExprClass:
Richard Smithed1cb882015-03-11 00:12:17 +00002940 case Expr::DesignatedInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002941 case Expr::ExtVectorElementExprClass:
2942 case Expr::GenericSelectionExprClass:
2943 case Expr::ObjCEncodeExprClass:
2944 case Expr::ObjCIsaExprClass:
2945 case Expr::ObjCIvarRefExprClass:
2946 case Expr::ObjCMessageExprClass:
2947 case Expr::ObjCPropertyRefExprClass:
2948 case Expr::ObjCProtocolExprClass:
2949 case Expr::ObjCSelectorExprClass:
2950 case Expr::ObjCStringLiteralClass:
2951 case Expr::ObjCBoxedExprClass:
2952 case Expr::ObjCArrayLiteralClass:
2953 case Expr::ObjCDictionaryLiteralClass:
2954 case Expr::ObjCSubscriptRefExprClass:
2955 case Expr::ObjCIndirectCopyRestoreExprClass:
2956 case Expr::OffsetOfExprClass:
2957 case Expr::PredefinedExprClass:
2958 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002959 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002960 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002961 case Expr::TypeTraitExprClass:
2962 case Expr::ArrayTypeTraitExprClass:
2963 case Expr::ExpressionTraitExprClass:
2964 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002965 case Expr::CUDAKernelCallExprClass:
2966 case Expr::AsTypeExprClass:
2967 case Expr::PseudoObjectExprClass:
2968 case Expr::AtomicExprClass:
2969 {
2970 // As bad as this diagnostic is, it's better than crashing.
2971 DiagnosticsEngine &Diags = Context.getDiags();
2972 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2973 "cannot yet mangle expression type %0");
2974 Diags.Report(E->getExprLoc(), DiagID)
2975 << E->getStmtClassName() << E->getSourceRange();
2976 break;
2977 }
2978
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00002979 case Expr::CXXUuidofExprClass: {
2980 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2981 if (UE->isTypeOperand()) {
2982 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2983 Out << "u8__uuidoft";
2984 mangleType(UuidT);
2985 } else {
2986 Expr *UuidExp = UE->getExprOperand();
2987 Out << "u8__uuidofz";
2988 mangleExpression(UuidExp, Arity);
2989 }
2990 break;
2991 }
2992
Guy Benyei11169dd2012-12-18 14:30:41 +00002993 // Even gcc-4.5 doesn't mangle this.
2994 case Expr::BinaryConditionalOperatorClass: {
2995 DiagnosticsEngine &Diags = Context.getDiags();
2996 unsigned DiagID =
2997 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2998 "?: operator with omitted middle operand cannot be mangled");
2999 Diags.Report(E->getExprLoc(), DiagID)
3000 << E->getStmtClassName() << E->getSourceRange();
3001 break;
3002 }
3003
3004 // These are used for internal purposes and cannot be meaningfully mangled.
3005 case Expr::OpaqueValueExprClass:
3006 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3007
3008 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003009 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00003010 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00003011 Out << "E";
3012 break;
3013 }
3014
3015 case Expr::CXXDefaultArgExprClass:
3016 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3017 break;
3018
Richard Smith852c9db2013-04-20 22:23:05 +00003019 case Expr::CXXDefaultInitExprClass:
3020 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3021 break;
3022
Richard Smithcc1b96d2013-06-12 22:31:48 +00003023 case Expr::CXXStdInitializerListExprClass:
3024 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3025 break;
3026
Guy Benyei11169dd2012-12-18 14:30:41 +00003027 case Expr::SubstNonTypeTemplateParmExprClass:
3028 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3029 Arity);
3030 break;
3031
3032 case Expr::UserDefinedLiteralClass:
3033 // We follow g++'s approach of mangling a UDL as a call to the literal
3034 // operator.
3035 case Expr::CXXMemberCallExprClass: // fallthrough
3036 case Expr::CallExprClass: {
3037 const CallExpr *CE = cast<CallExpr>(E);
3038
3039 // <expression> ::= cp <simple-id> <expression>* E
3040 // We use this mangling only when the call would use ADL except
3041 // for being parenthesized. Per discussion with David
3042 // Vandervoorde, 2011.04.25.
3043 if (isParenthesizedADLCallee(CE)) {
3044 Out << "cp";
3045 // The callee here is a parenthesized UnresolvedLookupExpr with
3046 // no qualifier and should always get mangled as a <simple-id>
3047 // anyway.
3048
3049 // <expression> ::= cl <expression>* E
3050 } else {
3051 Out << "cl";
3052 }
3053
David Majnemer67a8ec62015-02-19 21:41:48 +00003054 unsigned CallArity = CE->getNumArgs();
3055 for (const Expr *Arg : CE->arguments())
3056 if (isa<PackExpansionExpr>(Arg))
3057 CallArity = UnknownArity;
3058
3059 mangleExpression(CE->getCallee(), CallArity);
3060 for (const Expr *Arg : CE->arguments())
3061 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003062 Out << 'E';
3063 break;
3064 }
3065
3066 case Expr::CXXNewExprClass: {
3067 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3068 if (New->isGlobalNew()) Out << "gs";
3069 Out << (New->isArray() ? "na" : "nw");
3070 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3071 E = New->placement_arg_end(); I != E; ++I)
3072 mangleExpression(*I);
3073 Out << '_';
3074 mangleType(New->getAllocatedType());
3075 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3077 Out << "il";
3078 else
3079 Out << "pi";
3080 const Expr *Init = New->getInitializer();
3081 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3082 // Directly inline the initializers.
3083 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3084 E = CCE->arg_end();
3085 I != E; ++I)
3086 mangleExpression(*I);
3087 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3088 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3089 mangleExpression(PLE->getExpr(i));
3090 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3091 isa<InitListExpr>(Init)) {
3092 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003093 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003094 } else
3095 mangleExpression(Init);
3096 }
3097 Out << 'E';
3098 break;
3099 }
3100
David Majnemer1dabfdc2015-02-14 13:23:54 +00003101 case Expr::CXXPseudoDestructorExprClass: {
3102 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3103 if (const Expr *Base = PDE->getBase())
3104 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003105 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3106 QualType ScopeType;
3107 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3108 if (Qualifier) {
3109 mangleUnresolvedPrefix(Qualifier,
3110 /*Recursive=*/true);
3111 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3112 Out << 'E';
3113 } else {
3114 Out << "sr";
3115 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3116 Out << 'E';
3117 }
3118 } else if (Qualifier) {
3119 mangleUnresolvedPrefix(Qualifier);
3120 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003121 // <base-unresolved-name> ::= dn <destructor-name>
3122 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003123 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003124 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003125 break;
3126 }
3127
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 case Expr::MemberExprClass: {
3129 const MemberExpr *ME = cast<MemberExpr>(E);
3130 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003131 ME->getQualifier(), nullptr,
3132 ME->getMemberDecl()->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003133 break;
3134 }
3135
3136 case Expr::UnresolvedMemberExprClass: {
3137 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003138 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3139 ME->isArrow(), ME->getQualifier(), nullptr,
3140 ME->getMemberName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003141 if (ME->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003142 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003143 break;
3144 }
3145
3146 case Expr::CXXDependentScopeMemberExprClass: {
3147 const CXXDependentScopeMemberExpr *ME
3148 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003149 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3150 ME->isArrow(), ME->getQualifier(),
3151 ME->getFirstQualifierFoundInScope(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003152 ME->getMember(), Arity);
3153 if (ME->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003154 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003155 break;
3156 }
3157
3158 case Expr::UnresolvedLookupExprClass: {
3159 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00003160 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003161
3162 // All the <unresolved-name> productions end in a
3163 // base-unresolved-name, where <template-args> are just tacked
3164 // onto the end.
3165 if (ULE->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003166 mangleTemplateArgs(ULE->getTemplateArgs(), ULE->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003167 break;
3168 }
3169
3170 case Expr::CXXUnresolvedConstructExprClass: {
3171 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3172 unsigned N = CE->arg_size();
3173
3174 Out << "cv";
3175 mangleType(CE->getType());
3176 if (N != 1) Out << '_';
3177 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3178 if (N != 1) Out << 'E';
3179 break;
3180 }
3181
Guy Benyei11169dd2012-12-18 14:30:41 +00003182 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003183 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003184 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003185 assert(
3186 CE->getNumArgs() >= 1 &&
3187 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3188 "implicit CXXConstructExpr must have one argument");
3189 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3190 }
3191 Out << "il";
3192 for (auto *E : CE->arguments())
3193 mangleExpression(E);
3194 Out << "E";
3195 break;
3196 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003197
Richard Smith520449d2015-02-05 06:15:50 +00003198 case Expr::CXXTemporaryObjectExprClass: {
3199 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3200 unsigned N = CE->getNumArgs();
3201 bool List = CE->isListInitialization();
3202
3203 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 Out << "tl";
3205 else
3206 Out << "cv";
3207 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003208 if (!List && N != 1)
3209 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003210 if (CE->isStdInitListInitialization()) {
3211 // We implicitly created a std::initializer_list<T> for the first argument
3212 // of a constructor of type U in an expression of the form U{a, b, c}.
3213 // Strip all the semantic gunk off the initializer list.
3214 auto *SILE =
3215 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3216 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3217 mangleInitListElements(ILE);
3218 } else {
3219 for (auto *E : CE->arguments())
3220 mangleExpression(E);
3221 }
Richard Smith520449d2015-02-05 06:15:50 +00003222 if (List || N != 1)
3223 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003224 break;
3225 }
3226
3227 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003228 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003229 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003230 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003231 break;
3232
3233 case Expr::CXXNoexceptExprClass:
3234 Out << "nx";
3235 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3236 break;
3237
3238 case Expr::UnaryExprOrTypeTraitExprClass: {
3239 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3240
3241 if (!SAE->isInstantiationDependent()) {
3242 // Itanium C++ ABI:
3243 // If the operand of a sizeof or alignof operator is not
3244 // instantiation-dependent it is encoded as an integer literal
3245 // reflecting the result of the operator.
3246 //
3247 // If the result of the operator is implicitly converted to a known
3248 // integer type, that type is used for the literal; otherwise, the type
3249 // of std::size_t or std::ptrdiff_t is used.
3250 QualType T = (ImplicitlyConvertedToType.isNull() ||
3251 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3252 : ImplicitlyConvertedToType;
3253 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3254 mangleIntegerLiteral(T, V);
3255 break;
3256 }
3257
3258 switch(SAE->getKind()) {
3259 case UETT_SizeOf:
3260 Out << 's';
3261 break;
3262 case UETT_AlignOf:
3263 Out << 'a';
3264 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003265 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003266 DiagnosticsEngine &Diags = Context.getDiags();
3267 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3268 "cannot yet mangle vec_step expression");
3269 Diags.Report(DiagID);
3270 return;
3271 }
Alexey Bataev00396512015-07-02 03:40:19 +00003272 case UETT_OpenMPRequiredSimdAlign:
3273 DiagnosticsEngine &Diags = Context.getDiags();
3274 unsigned DiagID = Diags.getCustomDiagID(
3275 DiagnosticsEngine::Error,
3276 "cannot yet mangle __builtin_omp_required_simd_align expression");
3277 Diags.Report(DiagID);
3278 return;
3279 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 if (SAE->isArgumentType()) {
3281 Out << 't';
3282 mangleType(SAE->getArgumentType());
3283 } else {
3284 Out << 'z';
3285 mangleExpression(SAE->getArgumentExpr());
3286 }
3287 break;
3288 }
3289
3290 case Expr::CXXThrowExprClass: {
3291 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003292 // <expression> ::= tw <expression> # throw expression
3293 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 if (TE->getSubExpr()) {
3295 Out << "tw";
3296 mangleExpression(TE->getSubExpr());
3297 } else {
3298 Out << "tr";
3299 }
3300 break;
3301 }
3302
3303 case Expr::CXXTypeidExprClass: {
3304 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003305 // <expression> ::= ti <type> # typeid (type)
3306 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003307 if (TIE->isTypeOperand()) {
3308 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003309 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003310 } else {
3311 Out << "te";
3312 mangleExpression(TIE->getExprOperand());
3313 }
3314 break;
3315 }
3316
3317 case Expr::CXXDeleteExprClass: {
3318 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003319 // <expression> ::= [gs] dl <expression> # [::] delete expr
3320 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003321 if (DE->isGlobalDelete()) Out << "gs";
3322 Out << (DE->isArrayForm() ? "da" : "dl");
3323 mangleExpression(DE->getArgument());
3324 break;
3325 }
3326
3327 case Expr::UnaryOperatorClass: {
3328 const UnaryOperator *UO = cast<UnaryOperator>(E);
3329 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3330 /*Arity=*/1);
3331 mangleExpression(UO->getSubExpr());
3332 break;
3333 }
3334
3335 case Expr::ArraySubscriptExprClass: {
3336 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3337
3338 // Array subscript is treated as a syntactically weird form of
3339 // binary operator.
3340 Out << "ix";
3341 mangleExpression(AE->getLHS());
3342 mangleExpression(AE->getRHS());
3343 break;
3344 }
3345
3346 case Expr::CompoundAssignOperatorClass: // fallthrough
3347 case Expr::BinaryOperatorClass: {
3348 const BinaryOperator *BO = cast<BinaryOperator>(E);
3349 if (BO->getOpcode() == BO_PtrMemD)
3350 Out << "ds";
3351 else
3352 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3353 /*Arity=*/2);
3354 mangleExpression(BO->getLHS());
3355 mangleExpression(BO->getRHS());
3356 break;
3357 }
3358
3359 case Expr::ConditionalOperatorClass: {
3360 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3361 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3362 mangleExpression(CO->getCond());
3363 mangleExpression(CO->getLHS(), Arity);
3364 mangleExpression(CO->getRHS(), Arity);
3365 break;
3366 }
3367
3368 case Expr::ImplicitCastExprClass: {
3369 ImplicitlyConvertedToType = E->getType();
3370 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3371 goto recurse;
3372 }
3373
3374 case Expr::ObjCBridgedCastExprClass: {
3375 // Mangle ownership casts as a vendor extended operator __bridge,
3376 // __bridge_transfer, or __bridge_retain.
3377 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3378 Out << "v1U" << Kind.size() << Kind;
3379 }
3380 // Fall through to mangle the cast itself.
3381
3382 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003383 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003384 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003385
Richard Smith520449d2015-02-05 06:15:50 +00003386 case Expr::CXXFunctionalCastExprClass: {
3387 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3388 // FIXME: Add isImplicit to CXXConstructExpr.
3389 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3390 if (CCE->getParenOrBraceRange().isInvalid())
3391 Sub = CCE->getArg(0)->IgnoreImplicit();
3392 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3393 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3394 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3395 Out << "tl";
3396 mangleType(E->getType());
3397 mangleInitListElements(IL);
3398 Out << "E";
3399 } else {
3400 mangleCastExpression(E, "cv");
3401 }
3402 break;
3403 }
3404
David Majnemer9c775c72014-09-23 04:27:55 +00003405 case Expr::CXXStaticCastExprClass:
3406 mangleCastExpression(E, "sc");
3407 break;
3408 case Expr::CXXDynamicCastExprClass:
3409 mangleCastExpression(E, "dc");
3410 break;
3411 case Expr::CXXReinterpretCastExprClass:
3412 mangleCastExpression(E, "rc");
3413 break;
3414 case Expr::CXXConstCastExprClass:
3415 mangleCastExpression(E, "cc");
3416 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003417
3418 case Expr::CXXOperatorCallExprClass: {
3419 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3420 unsigned NumArgs = CE->getNumArgs();
3421 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3422 // Mangle the arguments.
3423 for (unsigned i = 0; i != NumArgs; ++i)
3424 mangleExpression(CE->getArg(i));
3425 break;
3426 }
3427
3428 case Expr::ParenExprClass:
3429 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3430 break;
3431
3432 case Expr::DeclRefExprClass: {
3433 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3434
3435 switch (D->getKind()) {
3436 default:
3437 // <expr-primary> ::= L <mangled-name> E # external name
3438 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003439 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003440 Out << 'E';
3441 break;
3442
3443 case Decl::ParmVar:
3444 mangleFunctionParam(cast<ParmVarDecl>(D));
3445 break;
3446
3447 case Decl::EnumConstant: {
3448 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3449 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3450 break;
3451 }
3452
3453 case Decl::NonTypeTemplateParm: {
3454 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3455 mangleTemplateParameter(PD->getIndex());
3456 break;
3457 }
3458
3459 }
3460
3461 break;
3462 }
3463
3464 case Expr::SubstNonTypeTemplateParmPackExprClass:
3465 // FIXME: not clear how to mangle this!
3466 // template <unsigned N...> class A {
3467 // template <class U...> void foo(U (&x)[N]...);
3468 // };
3469 Out << "_SUBSTPACK_";
3470 break;
3471
3472 case Expr::FunctionParmPackExprClass: {
3473 // FIXME: not clear how to mangle this!
3474 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3475 Out << "v110_SUBSTPACK";
3476 mangleFunctionParam(FPPE->getParameterPack());
3477 break;
3478 }
3479
3480 case Expr::DependentScopeDeclRefExprClass: {
3481 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00003482 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003483
3484 // All the <unresolved-name> productions end in a
3485 // base-unresolved-name, where <template-args> are just tacked
3486 // onto the end.
3487 if (DRE->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003488 mangleTemplateArgs(DRE->getTemplateArgs(), DRE->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003489 break;
3490 }
3491
3492 case Expr::CXXBindTemporaryExprClass:
3493 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3494 break;
3495
3496 case Expr::ExprWithCleanupsClass:
3497 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3498 break;
3499
3500 case Expr::FloatingLiteralClass: {
3501 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3502 Out << 'L';
3503 mangleType(FL->getType());
3504 mangleFloat(FL->getValue());
3505 Out << 'E';
3506 break;
3507 }
3508
3509 case Expr::CharacterLiteralClass:
3510 Out << 'L';
3511 mangleType(E->getType());
3512 Out << cast<CharacterLiteral>(E)->getValue();
3513 Out << 'E';
3514 break;
3515
3516 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3517 case Expr::ObjCBoolLiteralExprClass:
3518 Out << "Lb";
3519 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3520 Out << 'E';
3521 break;
3522
3523 case Expr::CXXBoolLiteralExprClass:
3524 Out << "Lb";
3525 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3526 Out << 'E';
3527 break;
3528
3529 case Expr::IntegerLiteralClass: {
3530 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3531 if (E->getType()->isSignedIntegerType())
3532 Value.setIsSigned(true);
3533 mangleIntegerLiteral(E->getType(), Value);
3534 break;
3535 }
3536
3537 case Expr::ImaginaryLiteralClass: {
3538 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3539 // Mangle as if a complex literal.
3540 // Proposal from David Vandevoorde, 2010.06.30.
3541 Out << 'L';
3542 mangleType(E->getType());
3543 if (const FloatingLiteral *Imag =
3544 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3545 // Mangle a floating-point zero of the appropriate type.
3546 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3547 Out << '_';
3548 mangleFloat(Imag->getValue());
3549 } else {
3550 Out << "0_";
3551 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3552 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3553 Value.setIsSigned(true);
3554 mangleNumber(Value);
3555 }
3556 Out << 'E';
3557 break;
3558 }
3559
3560 case Expr::StringLiteralClass: {
3561 // Revised proposal from David Vandervoorde, 2010.07.15.
3562 Out << 'L';
3563 assert(isa<ConstantArrayType>(E->getType()));
3564 mangleType(E->getType());
3565 Out << 'E';
3566 break;
3567 }
3568
3569 case Expr::GNUNullExprClass:
3570 // FIXME: should this really be mangled the same as nullptr?
3571 // fallthrough
3572
3573 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003574 Out << "LDnE";
3575 break;
3576 }
3577
3578 case Expr::PackExpansionExprClass:
3579 Out << "sp";
3580 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3581 break;
3582
3583 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00003584 auto *SPE = cast<SizeOfPackExpr>(E);
3585 if (SPE->isPartiallySubstituted()) {
3586 Out << "sP";
3587 for (const auto &A : SPE->getPartialArguments())
3588 mangleTemplateArg(A);
3589 Out << "E";
3590 break;
3591 }
3592
Guy Benyei11169dd2012-12-18 14:30:41 +00003593 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00003594 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00003595 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3596 mangleTemplateParameter(TTP->getIndex());
3597 else if (const NonTypeTemplateParmDecl *NTTP
3598 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3599 mangleTemplateParameter(NTTP->getIndex());
3600 else if (const TemplateTemplateParmDecl *TempTP
3601 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3602 mangleTemplateParameter(TempTP->getIndex());
3603 else
3604 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3605 break;
3606 }
Richard Smith0f0af192014-11-08 05:07:16 +00003607
Guy Benyei11169dd2012-12-18 14:30:41 +00003608 case Expr::MaterializeTemporaryExprClass: {
3609 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3610 break;
3611 }
Richard Smith0f0af192014-11-08 05:07:16 +00003612
3613 case Expr::CXXFoldExprClass: {
3614 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00003615 if (FE->isLeftFold())
3616 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00003617 else
Richard Smith8e6923b2014-11-10 19:44:15 +00003618 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00003619
3620 if (FE->getOperator() == BO_PtrMemD)
3621 Out << "ds";
3622 else
3623 mangleOperatorName(
3624 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3625 /*Arity=*/2);
3626
3627 if (FE->getLHS())
3628 mangleExpression(FE->getLHS());
3629 if (FE->getRHS())
3630 mangleExpression(FE->getRHS());
3631 break;
3632 }
3633
Guy Benyei11169dd2012-12-18 14:30:41 +00003634 case Expr::CXXThisExprClass:
3635 Out << "fpT";
3636 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00003637
3638 case Expr::CoawaitExprClass:
3639 // FIXME: Propose a non-vendor mangling.
3640 Out << "v18co_await";
3641 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3642 break;
3643
3644 case Expr::CoyieldExprClass:
3645 // FIXME: Propose a non-vendor mangling.
3646 Out << "v18co_yield";
3647 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3648 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003649 }
3650}
3651
3652/// Mangle an expression which refers to a parameter variable.
3653///
3654/// <expression> ::= <function-param>
3655/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3656/// <function-param> ::= fp <top-level CV-qualifiers>
3657/// <parameter-2 non-negative number> _ # L == 0, I > 0
3658/// <function-param> ::= fL <L-1 non-negative number>
3659/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3660/// <function-param> ::= fL <L-1 non-negative number>
3661/// p <top-level CV-qualifiers>
3662/// <I-1 non-negative number> _ # L > 0, I > 0
3663///
3664/// L is the nesting depth of the parameter, defined as 1 if the
3665/// parameter comes from the innermost function prototype scope
3666/// enclosing the current context, 2 if from the next enclosing
3667/// function prototype scope, and so on, with one special case: if
3668/// we've processed the full parameter clause for the innermost
3669/// function type, then L is one less. This definition conveniently
3670/// makes it irrelevant whether a function's result type was written
3671/// trailing or leading, but is otherwise overly complicated; the
3672/// numbering was first designed without considering references to
3673/// parameter in locations other than return types, and then the
3674/// mangling had to be generalized without changing the existing
3675/// manglings.
3676///
3677/// I is the zero-based index of the parameter within its parameter
3678/// declaration clause. Note that the original ABI document describes
3679/// this using 1-based ordinals.
3680void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3681 unsigned parmDepth = parm->getFunctionScopeDepth();
3682 unsigned parmIndex = parm->getFunctionScopeIndex();
3683
3684 // Compute 'L'.
3685 // parmDepth does not include the declaring function prototype.
3686 // FunctionTypeDepth does account for that.
3687 assert(parmDepth < FunctionTypeDepth.getDepth());
3688 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3689 if (FunctionTypeDepth.isInResultType())
3690 nestingDepth--;
3691
3692 if (nestingDepth == 0) {
3693 Out << "fp";
3694 } else {
3695 Out << "fL" << (nestingDepth - 1) << 'p';
3696 }
3697
3698 // Top-level qualifiers. We don't have to worry about arrays here,
3699 // because parameters declared as arrays should already have been
3700 // transformed to have pointer type. FIXME: apparently these don't
3701 // get mangled if used as an rvalue of a known non-class type?
3702 assert(!parm->getType()->isArrayType()
3703 && "parameter's type is still an array type?");
3704 mangleQualifiers(parm->getType().getQualifiers());
3705
3706 // Parameter index.
3707 if (parmIndex != 0) {
3708 Out << (parmIndex - 1);
3709 }
3710 Out << '_';
3711}
3712
Richard Smith5179eb72016-06-28 19:03:57 +00003713void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
3714 const CXXRecordDecl *InheritedFrom) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003715 // <ctor-dtor-name> ::= C1 # complete object constructor
3716 // ::= C2 # base object constructor
Richard Smith5179eb72016-06-28 19:03:57 +00003717 // ::= CI1 <type> # complete inheriting constructor
3718 // ::= CI2 <type> # base inheriting constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00003719 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003720 // In addition, C5 is a comdat name with C1 and C2 in it.
Richard Smith5179eb72016-06-28 19:03:57 +00003721 Out << 'C';
3722 if (InheritedFrom)
3723 Out << 'I';
Guy Benyei11169dd2012-12-18 14:30:41 +00003724 switch (T) {
3725 case Ctor_Complete:
Richard Smith5179eb72016-06-28 19:03:57 +00003726 Out << '1';
Guy Benyei11169dd2012-12-18 14:30:41 +00003727 break;
3728 case Ctor_Base:
Richard Smith5179eb72016-06-28 19:03:57 +00003729 Out << '2';
Guy Benyei11169dd2012-12-18 14:30:41 +00003730 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003731 case Ctor_Comdat:
Richard Smith5179eb72016-06-28 19:03:57 +00003732 Out << '5';
Guy Benyei11169dd2012-12-18 14:30:41 +00003733 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00003734 case Ctor_DefaultClosure:
3735 case Ctor_CopyingClosure:
3736 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00003737 }
Richard Smith5179eb72016-06-28 19:03:57 +00003738 if (InheritedFrom)
3739 mangleName(InheritedFrom);
Guy Benyei11169dd2012-12-18 14:30:41 +00003740}
3741
3742void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3743 // <ctor-dtor-name> ::= D0 # deleting destructor
3744 // ::= D1 # complete object destructor
3745 // ::= D2 # base object destructor
3746 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003747 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003748 switch (T) {
3749 case Dtor_Deleting:
3750 Out << "D0";
3751 break;
3752 case Dtor_Complete:
3753 Out << "D1";
3754 break;
3755 case Dtor_Base:
3756 Out << "D2";
3757 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003758 case Dtor_Comdat:
3759 Out << "D5";
3760 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003761 }
3762}
3763
James Y Knight04ec5bf2015-12-24 02:59:37 +00003764void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
3765 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003766 // <template-args> ::= I <template-arg>+ E
3767 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00003768 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3769 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00003770 Out << 'E';
3771}
3772
3773void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3774 // <template-args> ::= I <template-arg>+ E
3775 Out << 'I';
3776 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3777 mangleTemplateArg(AL[i]);
3778 Out << 'E';
3779}
3780
3781void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3782 unsigned NumTemplateArgs) {
3783 // <template-args> ::= I <template-arg>+ E
3784 Out << 'I';
3785 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3786 mangleTemplateArg(TemplateArgs[i]);
3787 Out << 'E';
3788}
3789
3790void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3791 // <template-arg> ::= <type> # type or template
3792 // ::= X <expression> E # expression
3793 // ::= <expr-primary> # simple expressions
3794 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00003795 if (!A.isInstantiationDependent() || A.isDependent())
3796 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3797
3798 switch (A.getKind()) {
3799 case TemplateArgument::Null:
3800 llvm_unreachable("Cannot mangle NULL template argument");
3801
3802 case TemplateArgument::Type:
3803 mangleType(A.getAsType());
3804 break;
3805 case TemplateArgument::Template:
3806 // This is mangled as <type>.
3807 mangleType(A.getAsTemplate());
3808 break;
3809 case TemplateArgument::TemplateExpansion:
3810 // <type> ::= Dp <type> # pack expansion (C++0x)
3811 Out << "Dp";
3812 mangleType(A.getAsTemplateOrTemplatePattern());
3813 break;
3814 case TemplateArgument::Expression: {
3815 // It's possible to end up with a DeclRefExpr here in certain
3816 // dependent cases, in which case we should mangle as a
3817 // declaration.
3818 const Expr *E = A.getAsExpr()->IgnoreParens();
3819 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3820 const ValueDecl *D = DRE->getDecl();
3821 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00003822 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003823 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003824 Out << 'E';
3825 break;
3826 }
3827 }
3828
3829 Out << 'X';
3830 mangleExpression(E);
3831 Out << 'E';
3832 break;
3833 }
3834 case TemplateArgument::Integral:
3835 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3836 break;
3837 case TemplateArgument::Declaration: {
3838 // <expr-primary> ::= L <mangled-name> E # external name
3839 // Clang produces AST's where pointer-to-member-function expressions
3840 // and pointer-to-function expressions are represented as a declaration not
3841 // an expression. We compensate for it here to produce the correct mangling.
3842 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00003843 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003844 if (compensateMangling) {
3845 Out << 'X';
3846 mangleOperatorName(OO_Amp, 1);
3847 }
3848
3849 Out << 'L';
3850 // References to external entities use the mangled name; if the name would
Nico Weberfb420782016-05-25 14:15:08 +00003851 // not normally be mangled then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00003852 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003853 Out << 'E';
3854
3855 if (compensateMangling)
3856 Out << 'E';
3857
3858 break;
3859 }
3860 case TemplateArgument::NullPtr: {
3861 // <expr-primary> ::= L <type> 0 E
3862 Out << 'L';
3863 mangleType(A.getNullPtrType());
3864 Out << "0E";
3865 break;
3866 }
3867 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00003868 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00003869 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00003870 for (const auto &P : A.pack_elements())
3871 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00003872 Out << 'E';
3873 }
3874 }
3875}
3876
3877void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3878 // <template-param> ::= T_ # first template parameter
3879 // ::= T <parameter-2 non-negative number> _
3880 if (Index == 0)
3881 Out << "T_";
3882 else
3883 Out << 'T' << (Index - 1) << '_';
3884}
3885
David Majnemer3b3bdb52014-05-06 22:49:16 +00003886void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3887 if (SeqID == 1)
3888 Out << '0';
3889 else if (SeqID > 1) {
3890 SeqID--;
3891
3892 // <seq-id> is encoded in base-36, using digits and upper case letters.
3893 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00003894 MutableArrayRef<char> BufferRef(Buffer);
3895 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00003896
3897 for (; SeqID != 0; SeqID /= 36) {
3898 unsigned C = SeqID % 36;
3899 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3900 }
3901
3902 Out.write(I.base(), I - BufferRef.rbegin());
3903 }
3904 Out << '_';
3905}
3906
Guy Benyei11169dd2012-12-18 14:30:41 +00003907void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3908 bool result = mangleSubstitution(tname);
3909 assert(result && "no existing substitution for template name");
3910 (void) result;
3911}
3912
3913// <substitution> ::= S <seq-id> _
3914// ::= S_
3915bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3916 // Try one of the standard substitutions first.
3917 if (mangleStandardSubstitution(ND))
3918 return true;
3919
3920 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3921 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3922}
3923
Justin Bognere8d762e2015-05-22 06:48:13 +00003924/// Determine whether the given type has any qualifiers that are relevant for
3925/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00003926static bool hasMangledSubstitutionQualifiers(QualType T) {
3927 Qualifiers Qs = T.getQualifiers();
3928 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3929}
3930
3931bool CXXNameMangler::mangleSubstitution(QualType T) {
3932 if (!hasMangledSubstitutionQualifiers(T)) {
3933 if (const RecordType *RT = T->getAs<RecordType>())
3934 return mangleSubstitution(RT->getDecl());
3935 }
3936
3937 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3938
3939 return mangleSubstitution(TypePtr);
3940}
3941
3942bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3943 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3944 return mangleSubstitution(TD);
3945
3946 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3947 return mangleSubstitution(
3948 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3949}
3950
3951bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3952 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3953 if (I == Substitutions.end())
3954 return false;
3955
3956 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00003957 Out << 'S';
3958 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00003959
3960 return true;
3961}
3962
3963static bool isCharType(QualType T) {
3964 if (T.isNull())
3965 return false;
3966
3967 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3968 T->isSpecificBuiltinType(BuiltinType::Char_U);
3969}
3970
Justin Bognere8d762e2015-05-22 06:48:13 +00003971/// Returns whether a given type is a template specialization of a given name
3972/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00003973static bool isCharSpecialization(QualType T, const char *Name) {
3974 if (T.isNull())
3975 return false;
3976
3977 const RecordType *RT = T->getAs<RecordType>();
3978 if (!RT)
3979 return false;
3980
3981 const ClassTemplateSpecializationDecl *SD =
3982 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3983 if (!SD)
3984 return false;
3985
3986 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3987 return false;
3988
3989 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3990 if (TemplateArgs.size() != 1)
3991 return false;
3992
3993 if (!isCharType(TemplateArgs[0].getAsType()))
3994 return false;
3995
3996 return SD->getIdentifier()->getName() == Name;
3997}
3998
3999template <std::size_t StrLen>
4000static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4001 const char (&Str)[StrLen]) {
4002 if (!SD->getIdentifier()->isStr(Str))
4003 return false;
4004
4005 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4006 if (TemplateArgs.size() != 2)
4007 return false;
4008
4009 if (!isCharType(TemplateArgs[0].getAsType()))
4010 return false;
4011
4012 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4013 return false;
4014
4015 return true;
4016}
4017
4018bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4019 // <substitution> ::= St # ::std::
4020 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4021 if (isStd(NS)) {
4022 Out << "St";
4023 return true;
4024 }
4025 }
4026
4027 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4028 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4029 return false;
4030
4031 // <substitution> ::= Sa # ::std::allocator
4032 if (TD->getIdentifier()->isStr("allocator")) {
4033 Out << "Sa";
4034 return true;
4035 }
4036
4037 // <<substitution> ::= Sb # ::std::basic_string
4038 if (TD->getIdentifier()->isStr("basic_string")) {
4039 Out << "Sb";
4040 return true;
4041 }
4042 }
4043
4044 if (const ClassTemplateSpecializationDecl *SD =
4045 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4046 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4047 return false;
4048
4049 // <substitution> ::= Ss # ::std::basic_string<char,
4050 // ::std::char_traits<char>,
4051 // ::std::allocator<char> >
4052 if (SD->getIdentifier()->isStr("basic_string")) {
4053 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4054
4055 if (TemplateArgs.size() != 3)
4056 return false;
4057
4058 if (!isCharType(TemplateArgs[0].getAsType()))
4059 return false;
4060
4061 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4062 return false;
4063
4064 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4065 return false;
4066
4067 Out << "Ss";
4068 return true;
4069 }
4070
4071 // <substitution> ::= Si # ::std::basic_istream<char,
4072 // ::std::char_traits<char> >
4073 if (isStreamCharSpecialization(SD, "basic_istream")) {
4074 Out << "Si";
4075 return true;
4076 }
4077
4078 // <substitution> ::= So # ::std::basic_ostream<char,
4079 // ::std::char_traits<char> >
4080 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4081 Out << "So";
4082 return true;
4083 }
4084
4085 // <substitution> ::= Sd # ::std::basic_iostream<char,
4086 // ::std::char_traits<char> >
4087 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4088 Out << "Sd";
4089 return true;
4090 }
4091 }
4092 return false;
4093}
4094
4095void CXXNameMangler::addSubstitution(QualType T) {
4096 if (!hasMangledSubstitutionQualifiers(T)) {
4097 if (const RecordType *RT = T->getAs<RecordType>()) {
4098 addSubstitution(RT->getDecl());
4099 return;
4100 }
4101 }
4102
4103 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4104 addSubstitution(TypePtr);
4105}
4106
4107void CXXNameMangler::addSubstitution(TemplateName Template) {
4108 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4109 return addSubstitution(TD);
4110
4111 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4112 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4113}
4114
4115void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4116 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4117 Substitutions[Ptr] = SeqID++;
4118}
4119
4120//
4121
Justin Bognere8d762e2015-05-22 06:48:13 +00004122/// Mangles the name of the declaration D and emits that name to the given
4123/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004124///
4125/// If the declaration D requires a mangled name, this routine will emit that
4126/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4127/// and this routine will return false. In this case, the caller should just
4128/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4129/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004130void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4131 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004132 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4133 "Invalid mangleName() call, argument is not a variable or function!");
4134 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4135 "Invalid mangleName() call on 'structor decl!");
4136
4137 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4138 getASTContext().getSourceManager(),
4139 "Mangling declaration");
4140
4141 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004142 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004143}
4144
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004145void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4146 CXXCtorType Type,
4147 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004148 CXXNameMangler Mangler(*this, Out, D, Type);
4149 Mangler.mangle(D);
4150}
4151
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004152void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4153 CXXDtorType Type,
4154 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004155 CXXNameMangler Mangler(*this, Out, D, Type);
4156 Mangler.mangle(D);
4157}
4158
Rafael Espindola1e4df922014-09-16 15:18:21 +00004159void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4160 raw_ostream &Out) {
4161 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4162 Mangler.mangle(D);
4163}
4164
4165void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4166 raw_ostream &Out) {
4167 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4168 Mangler.mangle(D);
4169}
4170
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004171void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4172 const ThunkInfo &Thunk,
4173 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004174 // <special-name> ::= T <call-offset> <base encoding>
4175 // # base is the nominal target function of thunk
4176 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4177 // # base is the nominal target function of thunk
4178 // # first call-offset is 'this' adjustment
4179 // # second call-offset is result adjustment
4180
4181 assert(!isa<CXXDestructorDecl>(MD) &&
4182 "Use mangleCXXDtor for destructor decls!");
4183 CXXNameMangler Mangler(*this, Out);
4184 Mangler.getStream() << "_ZT";
4185 if (!Thunk.Return.isEmpty())
4186 Mangler.getStream() << 'c';
4187
4188 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004189 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4190 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4191
Guy Benyei11169dd2012-12-18 14:30:41 +00004192 // Mangle the return pointer adjustment if there is one.
4193 if (!Thunk.Return.isEmpty())
4194 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004195 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4196
Guy Benyei11169dd2012-12-18 14:30:41 +00004197 Mangler.mangleFunctionEncoding(MD);
4198}
4199
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004200void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4201 const CXXDestructorDecl *DD, CXXDtorType Type,
4202 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004203 // <special-name> ::= T <call-offset> <base encoding>
4204 // # base is the nominal target function of thunk
4205 CXXNameMangler Mangler(*this, Out, DD, Type);
4206 Mangler.getStream() << "_ZT";
4207
4208 // Mangle the 'this' pointer adjustment.
4209 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004210 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004211
4212 Mangler.mangleFunctionEncoding(DD);
4213}
4214
Justin Bognere8d762e2015-05-22 06:48:13 +00004215/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004216void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4217 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004218 // <special-name> ::= GV <object name> # Guard variable for one-time
4219 // # initialization
4220 CXXNameMangler Mangler(*this, Out);
4221 Mangler.getStream() << "_ZGV";
4222 Mangler.mangleName(D);
4223}
4224
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004225void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4226 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004227 // These symbols are internal in the Itanium ABI, so the names don't matter.
4228 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4229 // avoid duplicate symbols.
4230 Out << "__cxx_global_var_init";
4231}
4232
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004233void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4234 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004235 // Prefix the mangling of D with __dtor_.
4236 CXXNameMangler Mangler(*this, Out);
4237 Mangler.getStream() << "__dtor_";
4238 if (shouldMangleDeclName(D))
4239 Mangler.mangle(D);
4240 else
4241 Mangler.getStream() << D->getName();
4242}
4243
Reid Kleckner1d59f992015-01-22 01:36:17 +00004244void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4245 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4246 CXXNameMangler Mangler(*this, Out);
4247 Mangler.getStream() << "__filt_";
4248 if (shouldMangleDeclName(EnclosingDecl))
4249 Mangler.mangle(EnclosingDecl);
4250 else
4251 Mangler.getStream() << EnclosingDecl->getName();
4252}
4253
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004254void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4255 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4256 CXXNameMangler Mangler(*this, Out);
4257 Mangler.getStream() << "__fin_";
4258 if (shouldMangleDeclName(EnclosingDecl))
4259 Mangler.mangle(EnclosingDecl);
4260 else
4261 Mangler.getStream() << EnclosingDecl->getName();
4262}
4263
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004264void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4265 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004266 // <special-name> ::= TH <object name>
4267 CXXNameMangler Mangler(*this, Out);
4268 Mangler.getStream() << "_ZTH";
4269 Mangler.mangleName(D);
4270}
4271
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004272void
4273ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4274 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004275 // <special-name> ::= TW <object name>
4276 CXXNameMangler Mangler(*this, Out);
4277 Mangler.getStream() << "_ZTW";
4278 Mangler.mangleName(D);
4279}
4280
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004281void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004282 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004283 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004284 // We match the GCC mangling here.
4285 // <special-name> ::= GR <object name>
4286 CXXNameMangler Mangler(*this, Out);
4287 Mangler.getStream() << "_ZGR";
4288 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004289 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004290 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004291}
4292
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004293void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4294 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004295 // <special-name> ::= TV <type> # virtual table
4296 CXXNameMangler Mangler(*this, Out);
4297 Mangler.getStream() << "_ZTV";
4298 Mangler.mangleNameOrStandardSubstitution(RD);
4299}
4300
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004301void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4302 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 // <special-name> ::= TT <type> # VTT structure
4304 CXXNameMangler Mangler(*this, Out);
4305 Mangler.getStream() << "_ZTT";
4306 Mangler.mangleNameOrStandardSubstitution(RD);
4307}
4308
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004309void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4310 int64_t Offset,
4311 const CXXRecordDecl *Type,
4312 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004313 // <special-name> ::= TC <type> <offset number> _ <base type>
4314 CXXNameMangler Mangler(*this, Out);
4315 Mangler.getStream() << "_ZTC";
4316 Mangler.mangleNameOrStandardSubstitution(RD);
4317 Mangler.getStream() << Offset;
4318 Mangler.getStream() << '_';
4319 Mangler.mangleNameOrStandardSubstitution(Type);
4320}
4321
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004322void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004323 // <special-name> ::= TI <type> # typeinfo structure
4324 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4325 CXXNameMangler Mangler(*this, Out);
4326 Mangler.getStream() << "_ZTI";
4327 Mangler.mangleType(Ty);
4328}
4329
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004330void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4331 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004332 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4333 CXXNameMangler Mangler(*this, Out);
4334 Mangler.getStream() << "_ZTS";
4335 Mangler.mangleType(Ty);
4336}
4337
Reid Klecknercc99e262013-11-19 23:23:00 +00004338void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4339 mangleCXXRTTIName(Ty, Out);
4340}
4341
David Majnemer58e5bee2014-03-24 21:43:36 +00004342void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4343 llvm_unreachable("Can't mangle string literals");
4344}
4345
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004346ItaniumMangleContext *
4347ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4348 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004349}