blob: 7ad464e1d912118bf685f144da2e6cb1762d3e01 [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
Eli Friedman95f50122013-07-02 17:52:28 +000082 return DC;
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
319 void mangleExistingSubstitution(QualType type);
320 void mangleExistingSubstitution(TemplateName name);
321
322 bool mangleStandardSubstitution(const NamedDecl *ND);
323
324 void addSubstitution(const NamedDecl *ND) {
325 ND = cast<NamedDecl>(ND->getCanonicalDecl());
326
327 addSubstitution(reinterpret_cast<uintptr_t>(ND));
328 }
329 void addSubstitution(QualType T);
330 void addSubstitution(TemplateName Template);
331 void addSubstitution(uintptr_t Ptr);
332
333 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000334 bool recursive = false);
335 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000336 DeclarationName name,
337 unsigned KnownArity = UnknownArity);
338
339 void mangleName(const TemplateDecl *TD,
340 const TemplateArgument *TemplateArgs,
341 unsigned NumTemplateArgs);
342 void mangleUnqualifiedName(const NamedDecl *ND) {
343 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
344 }
345 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
346 unsigned KnownArity);
347 void mangleUnscopedName(const NamedDecl *ND);
348 void mangleUnscopedTemplateName(const TemplateDecl *ND);
349 void mangleUnscopedTemplateName(TemplateName);
350 void mangleSourceName(const IdentifierInfo *II);
Eli Friedman95f50122013-07-02 17:52:28 +0000351 void mangleLocalName(const Decl *D);
352 void mangleBlockForPrefix(const BlockDecl *Block);
353 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000354 void mangleLambda(const CXXRecordDecl *Lambda);
355 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
356 bool NoFunction=false);
357 void mangleNestedName(const TemplateDecl *TD,
358 const TemplateArgument *TemplateArgs,
359 unsigned NumTemplateArgs);
360 void manglePrefix(NestedNameSpecifier *qualifier);
361 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
362 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000363 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000364 void mangleTemplatePrefix(TemplateName Template);
David Majnemerb8014dd2015-02-19 02:16:16 +0000365 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
366 StringRef Prefix = "");
David Majnemera88b3592015-02-18 02:28:01 +0000367 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000368 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
John McCall07daf722016-03-01 22:18:03 +0000369 void mangleVendorQualifier(StringRef qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +0000370 void mangleQualifiers(Qualifiers Quals);
371 void mangleRefQualifier(RefQualifierKind RefQualifier);
372
373 void mangleObjCMethodName(const ObjCMethodDecl *MD);
374
375 // Declare manglers for every type class.
376#define ABSTRACT_TYPE(CLASS, PARENT)
377#define NON_CANONICAL_TYPE(CLASS, PARENT)
378#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
379#include "clang/AST/TypeNodes.def"
380
381 void mangleType(const TagType*);
382 void mangleType(TemplateName);
John McCall07daf722016-03-01 22:18:03 +0000383 static StringRef getCallingConvQualifierName(CallingConv CC);
384 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
385 void mangleExtFunctionInfo(const FunctionType *T);
386 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000387 const FunctionDecl *FD = nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +0000388 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000389 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000390
391 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000392 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000393 void mangleMemberExpr(const Expr *base, bool isArrow,
394 NestedNameSpecifier *qualifier,
395 NamedDecl *firstQualifierLookup,
396 DeclarationName name,
397 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000398 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000399 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000400 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
401 void mangleCXXCtorType(CXXCtorType T);
402 void mangleCXXDtorType(CXXDtorType T);
403
James Y Knight04ec5bf2015-12-24 02:59:37 +0000404 void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
405 unsigned NumTemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000406 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
407 unsigned NumTemplateArgs);
408 void mangleTemplateArgs(const TemplateArgumentList &AL);
409 void mangleTemplateArg(TemplateArgument A);
410
411 void mangleTemplateParameter(unsigned Index);
412
413 void mangleFunctionParam(const ParmVarDecl *parm);
414};
415
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000416}
Guy Benyei11169dd2012-12-18 14:30:41 +0000417
Rafael Espindola002667c2013-10-16 01:40:34 +0000418bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000419 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000420 if (FD) {
421 LanguageLinkage L = FD->getLanguageLinkage();
422 // Overloadable functions need mangling.
423 if (FD->hasAttr<OverloadableAttr>())
424 return true;
425
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000426 // "main" is not mangled.
427 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000428 return false;
429
430 // C++ functions and those whose names are not a simple identifier need
431 // mangling.
432 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
433 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000434
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000435 // C functions are not mangled.
436 if (L == CLanguageLinkage)
437 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000438 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000439
440 // Otherwise, no mangling is done outside C++ mode.
441 if (!getASTContext().getLangOpts().CPlusPlus)
442 return false;
443
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000444 const VarDecl *VD = dyn_cast<VarDecl>(D);
445 if (VD) {
446 // C variables are not mangled.
447 if (VD->isExternC())
448 return false;
449
450 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000451 const DeclContext *DC = getEffectiveDeclContext(D);
452 // Check for extern variable declared locally.
453 if (DC->isFunctionOrMethod() && D->hasLinkage())
454 while (!DC->isNamespace() && !DC->isTranslationUnit())
455 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000456 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
457 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000458 return false;
459 }
460
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 return true;
462}
463
David Majnemer7ff7eb72015-02-18 07:47:09 +0000464void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000465 // <mangled-name> ::= _Z <encoding>
466 // ::= <data name>
467 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000468 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000469 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
470 mangleFunctionEncoding(FD);
471 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
472 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000473 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
474 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000475 else
476 mangleName(cast<FieldDecl>(D));
477}
478
479void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
480 // <encoding> ::= <function name> <bare-function-type>
481 mangleName(FD);
482
483 // Don't mangle in the type if this isn't a decl we should typically mangle.
484 if (!Context.shouldMangleDeclName(FD))
485 return;
486
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000487 if (FD->hasAttr<EnableIfAttr>()) {
488 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
489 Out << "Ua9enable_ifI";
490 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
491 // it here.
492 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
493 E = FD->getAttrs().rend();
494 I != E; ++I) {
495 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
496 if (!EIA)
497 continue;
498 Out << 'X';
499 mangleExpression(EIA->getCond());
500 Out << 'E';
501 }
502 Out << 'E';
503 FunctionTypeDepth.pop(Saved);
504 }
505
Guy Benyei11169dd2012-12-18 14:30:41 +0000506 // Whether the mangling of a function type includes the return type depends on
507 // the context and the nature of the function. The rules for deciding whether
508 // the return type is included are:
509 //
510 // 1. Template functions (names or types) have return types encoded, with
511 // the exceptions listed below.
512 // 2. Function types not appearing as part of a function name mangling,
513 // e.g. parameters, pointer types, etc., have return type encoded, with the
514 // exceptions listed below.
515 // 3. Non-template function names do not have return types encoded.
516 //
517 // The exceptions mentioned in (1) and (2) above, for which the return type is
518 // never included, are
519 // 1. Constructors.
520 // 2. Destructors.
521 // 3. Conversion operator functions, e.g. operator int.
522 bool MangleReturnType = false;
523 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
524 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
525 isa<CXXConversionDecl>(FD)))
526 MangleReturnType = true;
527
528 // Mangle the type of the primary template.
529 FD = PrimaryTemplate->getTemplatedDecl();
530 }
531
John McCall07daf722016-03-01 22:18:03 +0000532 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
George Burgess IV3e3bb95b2015-12-02 21:58:08 +0000533 MangleReturnType, FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000534}
535
536static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
537 while (isa<LinkageSpecDecl>(DC)) {
538 DC = getEffectiveParentContext(DC);
539 }
540
541 return DC;
542}
543
Justin Bognere8d762e2015-05-22 06:48:13 +0000544/// Return whether a given namespace is the 'std' namespace.
Guy Benyei11169dd2012-12-18 14:30:41 +0000545static bool isStd(const NamespaceDecl *NS) {
546 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
547 ->isTranslationUnit())
548 return false;
549
550 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
551 return II && II->isStr("std");
552}
553
554// isStdNamespace - Return whether a given decl context is a toplevel 'std'
555// namespace.
556static bool isStdNamespace(const DeclContext *DC) {
557 if (!DC->isNamespace())
558 return false;
559
560 return isStd(cast<NamespaceDecl>(DC));
561}
562
563static const TemplateDecl *
564isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
565 // Check if we have a function template.
566 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
567 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
568 TemplateArgs = FD->getTemplateSpecializationArgs();
569 return TD;
570 }
571 }
572
573 // Check if we have a class template.
574 if (const ClassTemplateSpecializationDecl *Spec =
575 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
576 TemplateArgs = &Spec->getTemplateArgs();
577 return Spec->getSpecializedTemplate();
578 }
579
Larisse Voufo39a1e502013-08-06 01:03:05 +0000580 // Check if we have a variable template.
581 if (const VarTemplateSpecializationDecl *Spec =
582 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
583 TemplateArgs = &Spec->getTemplateArgs();
584 return Spec->getSpecializedTemplate();
585 }
586
Craig Topper36250ad2014-05-12 05:36:57 +0000587 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000588}
589
Guy Benyei11169dd2012-12-18 14:30:41 +0000590void CXXNameMangler::mangleName(const NamedDecl *ND) {
591 // <name> ::= <nested-name>
592 // ::= <unscoped-name>
593 // ::= <unscoped-template-name> <template-args>
594 // ::= <local-name>
595 //
596 const DeclContext *DC = getEffectiveDeclContext(ND);
597
598 // If this is an extern variable declared locally, the relevant DeclContext
599 // is that of the containing namespace, or the translation unit.
600 // FIXME: This is a hack; extern variables declared locally should have
601 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000602 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000603 while (!DC->isNamespace() && !DC->isTranslationUnit())
604 DC = getEffectiveParentContext(DC);
605 else if (GetLocalClassDecl(ND)) {
606 mangleLocalName(ND);
607 return;
608 }
609
610 DC = IgnoreLinkageSpecDecls(DC);
611
612 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
613 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000614 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000615 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
616 mangleUnscopedTemplateName(TD);
617 mangleTemplateArgs(*TemplateArgs);
618 return;
619 }
620
621 mangleUnscopedName(ND);
622 return;
623 }
624
Eli Friedman95f50122013-07-02 17:52:28 +0000625 if (isLocalContainerContext(DC)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000626 mangleLocalName(ND);
627 return;
628 }
629
630 mangleNestedName(ND, DC);
631}
632void CXXNameMangler::mangleName(const TemplateDecl *TD,
633 const TemplateArgument *TemplateArgs,
634 unsigned NumTemplateArgs) {
635 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
636
637 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
638 mangleUnscopedTemplateName(TD);
639 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
640 } else {
641 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
642 }
643}
644
645void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
646 // <unscoped-name> ::= <unqualified-name>
647 // ::= St <unqualified-name> # ::std::
648
649 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
650 Out << "St";
651
652 mangleUnqualifiedName(ND);
653}
654
655void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
656 // <unscoped-template-name> ::= <unscoped-name>
657 // ::= <substitution>
658 if (mangleSubstitution(ND))
659 return;
660
661 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +0000662 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000663 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +0000664 else
665 mangleUnscopedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +0000666
Guy Benyei11169dd2012-12-18 14:30:41 +0000667 addSubstitution(ND);
668}
669
670void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
671 // <unscoped-template-name> ::= <unscoped-name>
672 // ::= <substitution>
673 if (TemplateDecl *TD = Template.getAsTemplateDecl())
674 return mangleUnscopedTemplateName(TD);
675
676 if (mangleSubstitution(Template))
677 return;
678
679 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
680 assert(Dependent && "Not a dependent template name?");
681 if (const IdentifierInfo *Id = Dependent->getIdentifier())
682 mangleSourceName(Id);
683 else
684 mangleOperatorName(Dependent->getOperator(), UnknownArity);
685
686 addSubstitution(Template);
687}
688
689void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
690 // ABI:
691 // Floating-point literals are encoded using a fixed-length
692 // lowercase hexadecimal string corresponding to the internal
693 // representation (IEEE on Itanium), high-order bytes first,
694 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
695 // on Itanium.
696 // The 'without leading zeroes' thing seems to be an editorial
697 // mistake; see the discussion on cxx-abi-dev beginning on
698 // 2012-01-16.
699
700 // Our requirements here are just barely weird enough to justify
701 // using a custom algorithm instead of post-processing APInt::toString().
702
703 llvm::APInt valueBits = f.bitcastToAPInt();
704 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
705 assert(numCharacters != 0);
706
707 // Allocate a buffer of the right number of characters.
Benjamin Kramerc9ba1bd2015-08-04 13:34:50 +0000708 SmallVector<char, 20> buffer(numCharacters);
Guy Benyei11169dd2012-12-18 14:30:41 +0000709
710 // Fill the buffer left-to-right.
711 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
712 // The bit-index of the next hex digit.
713 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
714
715 // Project out 4 bits starting at 'digitIndex'.
716 llvm::integerPart hexDigit
717 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
718 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
719 hexDigit &= 0xF;
720
721 // Map that over to a lowercase hex digit.
722 static const char charForHex[16] = {
723 '0', '1', '2', '3', '4', '5', '6', '7',
724 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
725 };
726 buffer[stringIndex] = charForHex[hexDigit];
727 }
728
729 Out.write(buffer.data(), numCharacters);
730}
731
732void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
733 if (Value.isSigned() && Value.isNegative()) {
734 Out << 'n';
735 Value.abs().print(Out, /*signed*/ false);
736 } else {
737 Value.print(Out, /*signed*/ false);
738 }
739}
740
741void CXXNameMangler::mangleNumber(int64_t Number) {
742 // <number> ::= [n] <non-negative decimal integer>
743 if (Number < 0) {
744 Out << 'n';
745 Number = -Number;
746 }
747
748 Out << Number;
749}
750
751void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
752 // <call-offset> ::= h <nv-offset> _
753 // ::= v <v-offset> _
754 // <nv-offset> ::= <offset number> # non-virtual base override
755 // <v-offset> ::= <offset number> _ <virtual offset number>
756 // # virtual base override, with vcall offset
757 if (!Virtual) {
758 Out << 'h';
759 mangleNumber(NonVirtual);
760 Out << '_';
761 return;
762 }
763
764 Out << 'v';
765 mangleNumber(NonVirtual);
766 Out << '_';
767 mangleNumber(Virtual);
768 Out << '_';
769}
770
771void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +0000772 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000773 if (!mangleSubstitution(QualType(TST, 0))) {
774 mangleTemplatePrefix(TST->getTemplateName());
775
776 // FIXME: GCC does not appear to mangle the template arguments when
777 // the template in question is a dependent template name. Should we
778 // emulate that badness?
779 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
780 addSubstitution(QualType(TST, 0));
781 }
David Majnemera88b3592015-02-18 02:28:01 +0000782 } else if (const auto *DTST =
783 type->getAs<DependentTemplateSpecializationType>()) {
784 if (!mangleSubstitution(QualType(DTST, 0))) {
785 TemplateName Template = getASTContext().getDependentTemplateName(
786 DTST->getQualifier(), DTST->getIdentifier());
787 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +0000788
David Majnemera88b3592015-02-18 02:28:01 +0000789 // FIXME: GCC does not appear to mangle the template arguments when
790 // the template in question is a dependent template name. Should we
791 // emulate that badness?
792 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
793 addSubstitution(QualType(DTST, 0));
794 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000795 } else {
796 // We use the QualType mangle type variant here because it handles
797 // substitutions.
798 mangleType(type);
799 }
800}
801
802/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
803///
Guy Benyei11169dd2012-12-18 14:30:41 +0000804/// \param recursive - true if this is being called recursively,
805/// i.e. if there is more prefix "to the right".
806void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000807 bool recursive) {
808
809 // x, ::x
810 // <unresolved-name> ::= [gs] <base-unresolved-name>
811
812 // T::x / decltype(p)::x
813 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
814
815 // T::N::x /decltype(p)::N::x
816 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
817 // <base-unresolved-name>
818
819 // A::x, N::y, A<T>::z; "gs" means leading "::"
820 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
821 // <base-unresolved-name>
822
823 switch (qualifier->getKind()) {
824 case NestedNameSpecifier::Global:
825 Out << "gs";
826
827 // We want an 'sr' unless this is the entire NNS.
828 if (recursive)
829 Out << "sr";
830
831 // We never want an 'E' here.
832 return;
833
Nikola Smiljanic67860242014-09-26 00:28:20 +0000834 case NestedNameSpecifier::Super:
835 llvm_unreachable("Can't mangle __super specifier");
836
Guy Benyei11169dd2012-12-18 14:30:41 +0000837 case NestedNameSpecifier::Namespace:
838 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000839 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000840 /*recursive*/ true);
841 else
842 Out << "sr";
843 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
844 break;
845 case NestedNameSpecifier::NamespaceAlias:
846 if (qualifier->getPrefix())
David Majnemerb8014dd2015-02-19 02:16:16 +0000847 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000848 /*recursive*/ true);
849 else
850 Out << "sr";
851 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
852 break;
853
854 case NestedNameSpecifier::TypeSpec:
855 case NestedNameSpecifier::TypeSpecWithTemplate: {
856 const Type *type = qualifier->getAsType();
857
858 // We only want to use an unresolved-type encoding if this is one of:
859 // - a decltype
860 // - a template type parameter
861 // - a template template parameter with arguments
862 // In all of these cases, we should have no prefix.
863 if (qualifier->getPrefix()) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000864 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000865 /*recursive*/ true);
866 } else {
867 // Otherwise, all the cases want this.
868 Out << "sr";
869 }
870
David Majnemerb8014dd2015-02-19 02:16:16 +0000871 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
Guy Benyei11169dd2012-12-18 14:30:41 +0000872 return;
873
Guy Benyei11169dd2012-12-18 14:30:41 +0000874 break;
875 }
876
877 case NestedNameSpecifier::Identifier:
878 // Member expressions can have these without prefixes.
David Majnemerb8014dd2015-02-19 02:16:16 +0000879 if (qualifier->getPrefix())
880 mangleUnresolvedPrefix(qualifier->getPrefix(),
Guy Benyei11169dd2012-12-18 14:30:41 +0000881 /*recursive*/ true);
David Majnemerb8014dd2015-02-19 02:16:16 +0000882 else
Guy Benyei11169dd2012-12-18 14:30:41 +0000883 Out << "sr";
Guy Benyei11169dd2012-12-18 14:30:41 +0000884
885 mangleSourceName(qualifier->getAsIdentifier());
886 break;
887 }
888
889 // If this was the innermost part of the NNS, and we fell out to
890 // here, append an 'E'.
891 if (!recursive)
892 Out << 'E';
893}
894
895/// Mangle an unresolved-name, which is generally used for names which
896/// weren't resolved to specific entities.
897void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
Guy Benyei11169dd2012-12-18 14:30:41 +0000898 DeclarationName name,
899 unsigned knownArity) {
David Majnemerb8014dd2015-02-19 02:16:16 +0000900 if (qualifier) mangleUnresolvedPrefix(qualifier);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000901 switch (name.getNameKind()) {
902 // <base-unresolved-name> ::= <simple-id>
903 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +0000904 mangleSourceName(name.getAsIdentifierInfo());
905 break;
906 // <base-unresolved-name> ::= dn <destructor-name>
907 case DeclarationName::CXXDestructorName:
908 Out << "dn";
David Majnemerb8014dd2015-02-19 02:16:16 +0000909 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +0000910 break;
911 // <base-unresolved-name> ::= on <operator-name>
912 case DeclarationName::CXXConversionFunctionName:
913 case DeclarationName::CXXLiteralOperatorName:
914 case DeclarationName::CXXOperatorName:
915 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +0000916 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000917 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +0000918 case DeclarationName::CXXConstructorName:
919 llvm_unreachable("Can't mangle a constructor name!");
920 case DeclarationName::CXXUsingDirective:
921 llvm_unreachable("Can't mangle a using directive name!");
922 case DeclarationName::ObjCMultiArgSelector:
923 case DeclarationName::ObjCOneArgSelector:
924 case DeclarationName::ObjCZeroArgSelector:
925 llvm_unreachable("Can't mangle Objective-C selector names here!");
926 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000927}
928
Guy Benyei11169dd2012-12-18 14:30:41 +0000929void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
930 DeclarationName Name,
931 unsigned KnownArity) {
David Majnemera88b3592015-02-18 02:28:01 +0000932 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +0000933 // <unqualified-name> ::= <operator-name>
934 // ::= <ctor-dtor-name>
935 // ::= <source-name>
936 switch (Name.getNameKind()) {
937 case DeclarationName::Identifier: {
938 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
939 // We must avoid conflicts between internally- and externally-
940 // linked variable and function declaration names in the same TU:
941 // void test() { extern void foo(); }
942 // static void foo();
943 // This naming convention is the same as that followed by GCC,
944 // though it shouldn't actually matter.
Rafael Espindola3ae00052013-05-13 00:12:11 +0000945 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei11169dd2012-12-18 14:30:41 +0000946 getEffectiveDeclContext(ND)->isFileContext())
947 Out << 'L';
948
949 mangleSourceName(II);
950 break;
951 }
952
953 // Otherwise, an anonymous entity. We must have a declaration.
954 assert(ND && "mangling empty name without declaration");
955
956 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
957 if (NS->isAnonymousNamespace()) {
958 // This is how gcc mangles these names.
959 Out << "12_GLOBAL__N_1";
960 break;
961 }
962 }
963
964 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
965 // We must have an anonymous union or struct declaration.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000966 const RecordDecl *RD =
Guy Benyei11169dd2012-12-18 14:30:41 +0000967 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000968
Guy Benyei11169dd2012-12-18 14:30:41 +0000969 // Itanium C++ ABI 5.1.2:
970 //
971 // For the purposes of mangling, the name of an anonymous union is
972 // considered to be the name of the first named data member found by a
973 // pre-order, depth-first, declaration-order walk of the data members of
974 // the anonymous union. If there is no such data member (i.e., if all of
975 // the data members in the union are unnamed), then there is no way for
976 // a program to refer to the anonymous union, and there is therefore no
977 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000978 assert(RD->isAnonymousStructOrUnion()
979 && "Expected anonymous struct or union!");
980 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +0000981
982 // It's actually possible for various reasons for us to get here
983 // with an empty anonymous struct / union. Fortunately, it
984 // doesn't really matter what name we generate.
985 if (!FD) break;
986 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000987
Guy Benyei11169dd2012-12-18 14:30:41 +0000988 mangleSourceName(FD->getIdentifier());
989 break;
990 }
John McCall924046f2013-04-10 06:08:21 +0000991
992 // Class extensions have no name as a category, and it's possible
993 // for them to be the semantic parent of certain declarations
994 // (primarily, tag decls defined within declarations). Such
995 // declarations will always have internal linkage, so the name
996 // doesn't really matter, but we shouldn't crash on them. For
997 // safety, just handle all ObjC containers here.
998 if (isa<ObjCContainerDecl>(ND))
999 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001000
1001 // We must have an anonymous struct.
1002 const TagDecl *TD = cast<TagDecl>(ND);
1003 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1004 assert(TD->getDeclContext() == D->getDeclContext() &&
1005 "Typedef should not be in another decl context!");
1006 assert(D->getDeclName().getAsIdentifierInfo() &&
1007 "Typedef was not named!");
1008 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1009 break;
1010 }
1011
1012 // <unnamed-type-name> ::= <closure-type-name>
1013 //
1014 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1015 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1016 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1017 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1018 mangleLambda(Record);
1019 break;
1020 }
1021 }
1022
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001023 if (TD->isExternallyVisible()) {
1024 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001025 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001026 if (UnnamedMangle > 1)
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00001027 Out << UnnamedMangle - 2;
Guy Benyei11169dd2012-12-18 14:30:41 +00001028 Out << '_';
1029 break;
1030 }
1031
1032 // Get a unique id for the anonymous struct.
David Majnemer2206bf52014-03-05 08:57:59 +00001033 unsigned AnonStructId = Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001034
1035 // Mangle it as a source name in the form
1036 // [n] $_<id>
1037 // where n is the length of the string.
1038 SmallString<8> Str;
1039 Str += "$_";
1040 Str += llvm::utostr(AnonStructId);
1041
1042 Out << Str.size();
Yaron Keren09fb7c62015-03-10 07:33:23 +00001043 Out << Str;
Guy Benyei11169dd2012-12-18 14:30:41 +00001044 break;
1045 }
1046
1047 case DeclarationName::ObjCZeroArgSelector:
1048 case DeclarationName::ObjCOneArgSelector:
1049 case DeclarationName::ObjCMultiArgSelector:
1050 llvm_unreachable("Can't mangle Objective-C selector names here!");
1051
1052 case DeclarationName::CXXConstructorName:
1053 if (ND == Structor)
1054 // If the named decl is the C++ constructor we're mangling, use the type
1055 // we were given.
1056 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1057 else
1058 // Otherwise, use the complete constructor name. This is relevant if a
1059 // class with a constructor is declared within a constructor.
1060 mangleCXXCtorType(Ctor_Complete);
1061 break;
1062
1063 case DeclarationName::CXXDestructorName:
1064 if (ND == Structor)
1065 // If the named decl is the C++ destructor we're mangling, use the type we
1066 // were given.
1067 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1068 else
1069 // Otherwise, use the complete destructor name. This is relevant if a
1070 // class with a destructor is declared within a destructor.
1071 mangleCXXDtorType(Dtor_Complete);
1072 break;
1073
David Majnemera88b3592015-02-18 02:28:01 +00001074 case DeclarationName::CXXOperatorName:
1075 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001076 Arity = cast<FunctionDecl>(ND)->getNumParams();
1077
David Majnemera88b3592015-02-18 02:28:01 +00001078 // If we have a member function, we need to include the 'this' pointer.
1079 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1080 if (!MD->isStatic())
1081 Arity++;
1082 }
1083 // FALLTHROUGH
1084 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001085 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001086 mangleOperatorName(Name, Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00001087 break;
1088
1089 case DeclarationName::CXXUsingDirective:
1090 llvm_unreachable("Can't mangle a using directive name!");
1091 }
1092}
1093
1094void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1095 // <source-name> ::= <positive length number> <identifier>
1096 // <number> ::= [n] <non-negative decimal integer>
1097 // <identifier> ::= <unqualified source code identifier>
1098 Out << II->getLength() << II->getName();
1099}
1100
1101void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1102 const DeclContext *DC,
1103 bool NoFunction) {
1104 // <nested-name>
1105 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1106 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1107 // <template-args> E
1108
1109 Out << 'N';
1110 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001111 Qualifiers MethodQuals =
1112 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1113 // We do not consider restrict a distinguishing attribute for overloading
1114 // purposes so we must not mangle it.
1115 MethodQuals.removeRestrict();
1116 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001117 mangleRefQualifier(Method->getRefQualifier());
1118 }
1119
1120 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001121 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001122 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001123 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001124 mangleTemplateArgs(*TemplateArgs);
1125 }
1126 else {
1127 manglePrefix(DC, NoFunction);
1128 mangleUnqualifiedName(ND);
1129 }
1130
1131 Out << 'E';
1132}
1133void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1134 const TemplateArgument *TemplateArgs,
1135 unsigned NumTemplateArgs) {
1136 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1137
1138 Out << 'N';
1139
1140 mangleTemplatePrefix(TD);
1141 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1142
1143 Out << 'E';
1144}
1145
Eli Friedman95f50122013-07-02 17:52:28 +00001146void CXXNameMangler::mangleLocalName(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001147 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1148 // := Z <function encoding> E s [<discriminator>]
1149 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1150 // _ <entity name>
1151 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001152 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001153 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001154 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001155
1156 Out << 'Z';
1157
Eli Friedman92821742013-07-02 02:01:18 +00001158 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1159 mangleObjCMethodName(MD);
1160 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
Eli Friedman95f50122013-07-02 17:52:28 +00001161 mangleBlockForPrefix(BD);
Eli Friedman92821742013-07-02 02:01:18 +00001162 else
1163 mangleFunctionEncoding(cast<FunctionDecl>(DC));
Guy Benyei11169dd2012-12-18 14:30:41 +00001164
Eli Friedman92821742013-07-02 02:01:18 +00001165 Out << 'E';
1166
1167 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001168 // The parameter number is omitted for the last parameter, 0 for the
1169 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1170 // <entity name> will of course contain a <closure-type-name>: Its
1171 // numbering will be local to the particular argument in which it appears
1172 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001173 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1174 if (CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001175 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001176 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001177 if (const FunctionDecl *Func
1178 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1179 Out << 'd';
1180 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1181 if (Num > 1)
1182 mangleNumber(Num - 2);
1183 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001184 }
1185 }
1186 }
1187
1188 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001189 // equality ok because RD derived from ND above
1190 if (D == RD) {
1191 mangleUnqualifiedName(RD);
1192 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1193 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1194 mangleUnqualifiedBlock(BD);
1195 } else {
1196 const NamedDecl *ND = cast<NamedDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +00001197 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001198 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001199 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1200 // Mangle a block in a default parameter; see above explanation for
1201 // lambdas.
1202 if (const ParmVarDecl *Parm
1203 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1204 if (const FunctionDecl *Func
1205 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1206 Out << 'd';
1207 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1208 if (Num > 1)
1209 mangleNumber(Num - 2);
1210 Out << '_';
1211 }
1212 }
1213
1214 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001215 } else {
Eli Friedman0cd23352013-07-10 01:33:19 +00001216 mangleUnqualifiedName(cast<NamedDecl>(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00001217 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001218
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001219 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1220 unsigned disc;
1221 if (Context.getNextDiscriminator(ND, disc)) {
1222 if (disc < 10)
1223 Out << '_' << disc;
1224 else
1225 Out << "__" << disc << '_';
1226 }
1227 }
Eli Friedman95f50122013-07-02 17:52:28 +00001228}
1229
1230void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1231 if (GetLocalClassDecl(Block)) {
1232 mangleLocalName(Block);
1233 return;
1234 }
1235 const DeclContext *DC = getEffectiveDeclContext(Block);
1236 if (isLocalContainerContext(DC)) {
1237 mangleLocalName(Block);
1238 return;
1239 }
1240 manglePrefix(getEffectiveDeclContext(Block));
1241 mangleUnqualifiedBlock(Block);
1242}
1243
1244void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1245 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1246 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1247 Context->getDeclContext()->isRecord()) {
1248 if (const IdentifierInfo *Name
1249 = cast<NamedDecl>(Context)->getIdentifier()) {
1250 mangleSourceName(Name);
1251 Out << 'M';
1252 }
1253 }
1254 }
1255
1256 // If we have a block mangling number, use it.
1257 unsigned Number = Block->getBlockManglingNumber();
1258 // Otherwise, just make up a number. It doesn't matter what it is because
1259 // the symbol in question isn't externally visible.
1260 if (!Number)
1261 Number = Context.getBlockId(Block, false);
1262 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001263 if (Number > 0)
1264 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001265 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001266}
1267
1268void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1269 // If the context of a closure type is an initializer for a class member
1270 // (static or nonstatic), it is encoded in a qualified name with a final
1271 // <prefix> of the form:
1272 //
1273 // <data-member-prefix> := <member source-name> M
1274 //
1275 // Technically, the data-member-prefix is part of the <prefix>. However,
1276 // since a closure type will always be mangled with a prefix, it's easier
1277 // to emit that last part of the prefix here.
1278 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1279 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1280 Context->getDeclContext()->isRecord()) {
1281 if (const IdentifierInfo *Name
1282 = cast<NamedDecl>(Context)->getIdentifier()) {
1283 mangleSourceName(Name);
1284 Out << 'M';
1285 }
1286 }
1287 }
1288
1289 Out << "Ul";
1290 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1291 getAs<FunctionProtoType>();
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001292 mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1293 Lambda->getLambdaStaticInvoker());
Guy Benyei11169dd2012-12-18 14:30:41 +00001294 Out << "E";
1295
1296 // The number is omitted for the first closure type with a given
1297 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1298 // (in lexical order) with that same <lambda-sig> and context.
1299 //
1300 // The AST keeps track of the number for us.
1301 unsigned Number = Lambda->getLambdaManglingNumber();
1302 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1303 if (Number > 1)
1304 mangleNumber(Number - 2);
1305 Out << '_';
1306}
1307
1308void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1309 switch (qualifier->getKind()) {
1310 case NestedNameSpecifier::Global:
1311 // nothing
1312 return;
1313
Nikola Smiljanic67860242014-09-26 00:28:20 +00001314 case NestedNameSpecifier::Super:
1315 llvm_unreachable("Can't mangle __super specifier");
1316
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 case NestedNameSpecifier::Namespace:
1318 mangleName(qualifier->getAsNamespace());
1319 return;
1320
1321 case NestedNameSpecifier::NamespaceAlias:
1322 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1323 return;
1324
1325 case NestedNameSpecifier::TypeSpec:
1326 case NestedNameSpecifier::TypeSpecWithTemplate:
1327 manglePrefix(QualType(qualifier->getAsType(), 0));
1328 return;
1329
1330 case NestedNameSpecifier::Identifier:
1331 // Member expressions can have these without prefixes, but that
1332 // should end up in mangleUnresolvedPrefix instead.
1333 assert(qualifier->getPrefix());
1334 manglePrefix(qualifier->getPrefix());
1335
1336 mangleSourceName(qualifier->getAsIdentifier());
1337 return;
1338 }
1339
1340 llvm_unreachable("unexpected nested name specifier");
1341}
1342
1343void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1344 // <prefix> ::= <prefix> <unqualified-name>
1345 // ::= <template-prefix> <template-args>
1346 // ::= <template-param>
1347 // ::= # empty
1348 // ::= <substitution>
1349
1350 DC = IgnoreLinkageSpecDecls(DC);
1351
1352 if (DC->isTranslationUnit())
1353 return;
1354
Eli Friedman95f50122013-07-02 17:52:28 +00001355 if (NoFunction && isLocalContainerContext(DC))
1356 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001357
Eli Friedman95f50122013-07-02 17:52:28 +00001358 assert(!isLocalContainerContext(DC));
1359
Guy Benyei11169dd2012-12-18 14:30:41 +00001360 const NamedDecl *ND = cast<NamedDecl>(DC);
1361 if (mangleSubstitution(ND))
1362 return;
1363
1364 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001365 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001366 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1367 mangleTemplatePrefix(TD);
1368 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001369 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001370 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1371 mangleUnqualifiedName(ND);
1372 }
1373
1374 addSubstitution(ND);
1375}
1376
1377void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1378 // <template-prefix> ::= <prefix> <template unqualified-name>
1379 // ::= <template-param>
1380 // ::= <substitution>
1381 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1382 return mangleTemplatePrefix(TD);
1383
1384 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1385 manglePrefix(Qualified->getQualifier());
1386
1387 if (OverloadedTemplateStorage *Overloaded
1388 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001389 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001390 UnknownArity);
1391 return;
1392 }
1393
1394 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1395 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001396 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1397 manglePrefix(Qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00001398 mangleUnscopedTemplateName(Template);
1399}
1400
Eli Friedman86af13f02013-07-05 18:41:30 +00001401void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1402 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001403 // <template-prefix> ::= <prefix> <template unqualified-name>
1404 // ::= <template-param>
1405 // ::= <substitution>
1406 // <template-template-param> ::= <template-param>
1407 // <substitution>
1408
1409 if (mangleSubstitution(ND))
1410 return;
1411
1412 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001413 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001414 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001415 } else {
1416 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1417 mangleUnqualifiedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001418 }
1419
Guy Benyei11169dd2012-12-18 14:30:41 +00001420 addSubstitution(ND);
1421}
1422
1423/// Mangles a template name under the production <type>. Required for
1424/// template template arguments.
1425/// <type> ::= <class-enum-type>
1426/// ::= <template-param>
1427/// ::= <substitution>
1428void CXXNameMangler::mangleType(TemplateName TN) {
1429 if (mangleSubstitution(TN))
1430 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001431
1432 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001433
1434 switch (TN.getKind()) {
1435 case TemplateName::QualifiedTemplate:
1436 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1437 goto HaveDecl;
1438
1439 case TemplateName::Template:
1440 TD = TN.getAsTemplateDecl();
1441 goto HaveDecl;
1442
1443 HaveDecl:
1444 if (isa<TemplateTemplateParmDecl>(TD))
1445 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1446 else
1447 mangleName(TD);
1448 break;
1449
1450 case TemplateName::OverloadedTemplate:
1451 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1452
1453 case TemplateName::DependentTemplate: {
1454 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1455 assert(Dependent->isIdentifier());
1456
1457 // <class-enum-type> ::= <name>
1458 // <name> ::= <nested-name>
David Majnemercb34c672015-02-19 05:51:14 +00001459 mangleUnresolvedPrefix(Dependent->getQualifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00001460 mangleSourceName(Dependent->getIdentifier());
1461 break;
1462 }
1463
1464 case TemplateName::SubstTemplateTemplateParm: {
1465 // Substituted template parameters are mangled as the substituted
1466 // template. This will check for the substitution twice, which is
1467 // fine, but we have to return early so that we don't try to *add*
1468 // the substitution twice.
1469 SubstTemplateTemplateParmStorage *subst
1470 = TN.getAsSubstTemplateTemplateParm();
1471 mangleType(subst->getReplacement());
1472 return;
1473 }
1474
1475 case TemplateName::SubstTemplateTemplateParmPack: {
1476 // FIXME: not clear how to mangle this!
1477 // template <template <class> class T...> class A {
1478 // template <template <class> class U...> void foo(B<T,U> x...);
1479 // };
1480 Out << "_SUBSTPACK_";
1481 break;
1482 }
1483 }
1484
1485 addSubstitution(TN);
1486}
1487
David Majnemerb8014dd2015-02-19 02:16:16 +00001488bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1489 StringRef Prefix) {
1490 // Only certain other types are valid as prefixes; enumerate them.
1491 switch (Ty->getTypeClass()) {
1492 case Type::Builtin:
1493 case Type::Complex:
1494 case Type::Adjusted:
1495 case Type::Decayed:
1496 case Type::Pointer:
1497 case Type::BlockPointer:
1498 case Type::LValueReference:
1499 case Type::RValueReference:
1500 case Type::MemberPointer:
1501 case Type::ConstantArray:
1502 case Type::IncompleteArray:
1503 case Type::VariableArray:
1504 case Type::DependentSizedArray:
1505 case Type::DependentSizedExtVector:
1506 case Type::Vector:
1507 case Type::ExtVector:
1508 case Type::FunctionProto:
1509 case Type::FunctionNoProto:
1510 case Type::Paren:
1511 case Type::Attributed:
1512 case Type::Auto:
1513 case Type::PackExpansion:
1514 case Type::ObjCObject:
1515 case Type::ObjCInterface:
1516 case Type::ObjCObjectPointer:
1517 case Type::Atomic:
Xiuli Pan9c14e282016-01-09 12:53:17 +00001518 case Type::Pipe:
David Majnemerb8014dd2015-02-19 02:16:16 +00001519 llvm_unreachable("type is illegal as a nested name specifier");
1520
1521 case Type::SubstTemplateTypeParmPack:
1522 // FIXME: not clear how to mangle this!
1523 // template <class T...> class A {
1524 // template <class U...> void foo(decltype(T::foo(U())) x...);
1525 // };
1526 Out << "_SUBSTPACK_";
1527 break;
1528
1529 // <unresolved-type> ::= <template-param>
1530 // ::= <decltype>
1531 // ::= <template-template-param> <template-args>
1532 // (this last is not official yet)
1533 case Type::TypeOfExpr:
1534 case Type::TypeOf:
1535 case Type::Decltype:
1536 case Type::TemplateTypeParm:
1537 case Type::UnaryTransform:
1538 case Type::SubstTemplateTypeParm:
1539 unresolvedType:
1540 // Some callers want a prefix before the mangled type.
1541 Out << Prefix;
1542
1543 // This seems to do everything we want. It's not really
1544 // sanctioned for a substituted template parameter, though.
1545 mangleType(Ty);
1546
1547 // We never want to print 'E' directly after an unresolved-type,
1548 // so we return directly.
1549 return true;
1550
1551 case Type::Typedef:
1552 mangleSourceName(cast<TypedefType>(Ty)->getDecl()->getIdentifier());
1553 break;
1554
1555 case Type::UnresolvedUsing:
1556 mangleSourceName(
1557 cast<UnresolvedUsingType>(Ty)->getDecl()->getIdentifier());
1558 break;
1559
1560 case Type::Enum:
1561 case Type::Record:
1562 mangleSourceName(cast<TagType>(Ty)->getDecl()->getIdentifier());
1563 break;
1564
1565 case Type::TemplateSpecialization: {
1566 const TemplateSpecializationType *TST =
1567 cast<TemplateSpecializationType>(Ty);
David Majnemera88b3592015-02-18 02:28:01 +00001568 TemplateName TN = TST->getTemplateName();
David Majnemerb8014dd2015-02-19 02:16:16 +00001569 switch (TN.getKind()) {
1570 case TemplateName::Template:
1571 case TemplateName::QualifiedTemplate: {
1572 TemplateDecl *TD = TN.getAsTemplateDecl();
1573
1574 // If the base is a template template parameter, this is an
1575 // unresolved type.
1576 assert(TD && "no template for template specialization type");
1577 if (isa<TemplateTemplateParmDecl>(TD))
1578 goto unresolvedType;
1579
1580 mangleSourceName(TD->getIdentifier());
1581 break;
David Majnemera88b3592015-02-18 02:28:01 +00001582 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001583
1584 case TemplateName::OverloadedTemplate:
1585 case TemplateName::DependentTemplate:
1586 llvm_unreachable("invalid base for a template specialization type");
1587
1588 case TemplateName::SubstTemplateTemplateParm: {
1589 SubstTemplateTemplateParmStorage *subst =
1590 TN.getAsSubstTemplateTemplateParm();
1591 mangleExistingSubstitution(subst->getReplacement());
1592 break;
1593 }
1594
1595 case TemplateName::SubstTemplateTemplateParmPack: {
1596 // FIXME: not clear how to mangle this!
1597 // template <template <class U> class T...> class A {
1598 // template <class U...> void foo(decltype(T<U>::foo) x...);
1599 // };
1600 Out << "_SUBSTPACK_";
1601 break;
1602 }
1603 }
1604
David Majnemera88b3592015-02-18 02:28:01 +00001605 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
David Majnemerb8014dd2015-02-19 02:16:16 +00001606 break;
David Majnemera88b3592015-02-18 02:28:01 +00001607 }
David Majnemerb8014dd2015-02-19 02:16:16 +00001608
1609 case Type::InjectedClassName:
1610 mangleSourceName(
1611 cast<InjectedClassNameType>(Ty)->getDecl()->getIdentifier());
1612 break;
1613
1614 case Type::DependentName:
1615 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1616 break;
1617
1618 case Type::DependentTemplateSpecialization: {
1619 const DependentTemplateSpecializationType *DTST =
1620 cast<DependentTemplateSpecializationType>(Ty);
1621 mangleSourceName(DTST->getIdentifier());
1622 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1623 break;
1624 }
1625
1626 case Type::Elaborated:
1627 return mangleUnresolvedTypeOrSimpleId(
1628 cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1629 }
1630
1631 return false;
David Majnemera88b3592015-02-18 02:28:01 +00001632}
1633
1634void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1635 switch (Name.getNameKind()) {
1636 case DeclarationName::CXXConstructorName:
1637 case DeclarationName::CXXDestructorName:
1638 case DeclarationName::CXXUsingDirective:
1639 case DeclarationName::Identifier:
1640 case DeclarationName::ObjCMultiArgSelector:
1641 case DeclarationName::ObjCOneArgSelector:
1642 case DeclarationName::ObjCZeroArgSelector:
1643 llvm_unreachable("Not an operator name");
1644
1645 case DeclarationName::CXXConversionFunctionName:
1646 // <operator-name> ::= cv <type> # (cast)
1647 Out << "cv";
1648 mangleType(Name.getCXXNameType());
1649 break;
1650
1651 case DeclarationName::CXXLiteralOperatorName:
1652 Out << "li";
1653 mangleSourceName(Name.getCXXLiteralIdentifier());
1654 return;
1655
1656 case DeclarationName::CXXOperatorName:
1657 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1658 break;
1659 }
1660}
1661
1662
1663
Guy Benyei11169dd2012-12-18 14:30:41 +00001664void
1665CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1666 switch (OO) {
1667 // <operator-name> ::= nw # new
1668 case OO_New: Out << "nw"; break;
1669 // ::= na # new[]
1670 case OO_Array_New: Out << "na"; break;
1671 // ::= dl # delete
1672 case OO_Delete: Out << "dl"; break;
1673 // ::= da # delete[]
1674 case OO_Array_Delete: Out << "da"; break;
1675 // ::= ps # + (unary)
1676 // ::= pl # + (binary or unknown)
1677 case OO_Plus:
1678 Out << (Arity == 1? "ps" : "pl"); break;
1679 // ::= ng # - (unary)
1680 // ::= mi # - (binary or unknown)
1681 case OO_Minus:
1682 Out << (Arity == 1? "ng" : "mi"); break;
1683 // ::= ad # & (unary)
1684 // ::= an # & (binary or unknown)
1685 case OO_Amp:
1686 Out << (Arity == 1? "ad" : "an"); break;
1687 // ::= de # * (unary)
1688 // ::= ml # * (binary or unknown)
1689 case OO_Star:
1690 // Use binary when unknown.
1691 Out << (Arity == 1? "de" : "ml"); break;
1692 // ::= co # ~
1693 case OO_Tilde: Out << "co"; break;
1694 // ::= dv # /
1695 case OO_Slash: Out << "dv"; break;
1696 // ::= rm # %
1697 case OO_Percent: Out << "rm"; break;
1698 // ::= or # |
1699 case OO_Pipe: Out << "or"; break;
1700 // ::= eo # ^
1701 case OO_Caret: Out << "eo"; break;
1702 // ::= aS # =
1703 case OO_Equal: Out << "aS"; break;
1704 // ::= pL # +=
1705 case OO_PlusEqual: Out << "pL"; break;
1706 // ::= mI # -=
1707 case OO_MinusEqual: Out << "mI"; break;
1708 // ::= mL # *=
1709 case OO_StarEqual: Out << "mL"; break;
1710 // ::= dV # /=
1711 case OO_SlashEqual: Out << "dV"; break;
1712 // ::= rM # %=
1713 case OO_PercentEqual: Out << "rM"; break;
1714 // ::= aN # &=
1715 case OO_AmpEqual: Out << "aN"; break;
1716 // ::= oR # |=
1717 case OO_PipeEqual: Out << "oR"; break;
1718 // ::= eO # ^=
1719 case OO_CaretEqual: Out << "eO"; break;
1720 // ::= ls # <<
1721 case OO_LessLess: Out << "ls"; break;
1722 // ::= rs # >>
1723 case OO_GreaterGreater: Out << "rs"; break;
1724 // ::= lS # <<=
1725 case OO_LessLessEqual: Out << "lS"; break;
1726 // ::= rS # >>=
1727 case OO_GreaterGreaterEqual: Out << "rS"; break;
1728 // ::= eq # ==
1729 case OO_EqualEqual: Out << "eq"; break;
1730 // ::= ne # !=
1731 case OO_ExclaimEqual: Out << "ne"; break;
1732 // ::= lt # <
1733 case OO_Less: Out << "lt"; break;
1734 // ::= gt # >
1735 case OO_Greater: Out << "gt"; break;
1736 // ::= le # <=
1737 case OO_LessEqual: Out << "le"; break;
1738 // ::= ge # >=
1739 case OO_GreaterEqual: Out << "ge"; break;
1740 // ::= nt # !
1741 case OO_Exclaim: Out << "nt"; break;
1742 // ::= aa # &&
1743 case OO_AmpAmp: Out << "aa"; break;
1744 // ::= oo # ||
1745 case OO_PipePipe: Out << "oo"; break;
1746 // ::= pp # ++
1747 case OO_PlusPlus: Out << "pp"; break;
1748 // ::= mm # --
1749 case OO_MinusMinus: Out << "mm"; break;
1750 // ::= cm # ,
1751 case OO_Comma: Out << "cm"; break;
1752 // ::= pm # ->*
1753 case OO_ArrowStar: Out << "pm"; break;
1754 // ::= pt # ->
1755 case OO_Arrow: Out << "pt"; break;
1756 // ::= cl # ()
1757 case OO_Call: Out << "cl"; break;
1758 // ::= ix # []
1759 case OO_Subscript: Out << "ix"; break;
1760
1761 // ::= qu # ?
1762 // The conditional operator can't be overloaded, but we still handle it when
1763 // mangling expressions.
1764 case OO_Conditional: Out << "qu"; break;
Richard Smith9be594e2015-10-22 05:12:22 +00001765 // Proposal on cxx-abi-dev, 2015-10-21.
1766 // ::= aw # co_await
1767 case OO_Coawait: Out << "aw"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001768
1769 case OO_None:
1770 case NUM_OVERLOADED_OPERATORS:
1771 llvm_unreachable("Not an overloaded operator");
1772 }
1773}
1774
1775void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
John McCall07daf722016-03-01 22:18:03 +00001776 // Vendor qualifiers come first.
Guy Benyei11169dd2012-12-18 14:30:41 +00001777
John McCall07daf722016-03-01 22:18:03 +00001778 // Address space qualifiers start with an ordinary letter.
Guy Benyei11169dd2012-12-18 14:30:41 +00001779 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00001780 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00001781 //
David Tweed31d09b02013-09-13 12:04:22 +00001782 // <type> ::= U <target-addrspace>
1783 // <type> ::= U <OpenCL-addrspace>
1784 // <type> ::= U <CUDA-addrspace>
1785
Guy Benyei11169dd2012-12-18 14:30:41 +00001786 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00001787 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00001788
1789 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1790 // <target-addrspace> ::= "AS" <address-space-number>
1791 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
Craig Topperf42e0312016-01-31 04:20:03 +00001792 ASString = "AS" + llvm::utostr(TargetAS);
David Tweed31d09b02013-09-13 12:04:22 +00001793 } else {
1794 switch (AS) {
1795 default: llvm_unreachable("Not a language specific address space");
1796 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1797 case LangAS::opencl_global: ASString = "CLglobal"; break;
1798 case LangAS::opencl_local: ASString = "CLlocal"; break;
1799 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1800 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1801 case LangAS::cuda_device: ASString = "CUdevice"; break;
1802 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1803 case LangAS::cuda_shared: ASString = "CUshared"; break;
1804 }
1805 }
John McCall07daf722016-03-01 22:18:03 +00001806 mangleVendorQualifier(ASString);
Guy Benyei11169dd2012-12-18 14:30:41 +00001807 }
John McCall07daf722016-03-01 22:18:03 +00001808
1809 // The ARC ownership qualifiers start with underscores.
Guy Benyei11169dd2012-12-18 14:30:41 +00001810 switch (Quals.getObjCLifetime()) {
1811 // Objective-C ARC Extension:
1812 //
1813 // <type> ::= U "__strong"
1814 // <type> ::= U "__weak"
1815 // <type> ::= U "__autoreleasing"
1816 case Qualifiers::OCL_None:
1817 break;
1818
1819 case Qualifiers::OCL_Weak:
John McCall07daf722016-03-01 22:18:03 +00001820 mangleVendorQualifier("__weak");
Guy Benyei11169dd2012-12-18 14:30:41 +00001821 break;
1822
1823 case Qualifiers::OCL_Strong:
John McCall07daf722016-03-01 22:18:03 +00001824 mangleVendorQualifier("__strong");
Guy Benyei11169dd2012-12-18 14:30:41 +00001825 break;
1826
1827 case Qualifiers::OCL_Autoreleasing:
John McCall07daf722016-03-01 22:18:03 +00001828 mangleVendorQualifier("__autoreleasing");
Guy Benyei11169dd2012-12-18 14:30:41 +00001829 break;
1830
1831 case Qualifiers::OCL_ExplicitNone:
1832 // The __unsafe_unretained qualifier is *not* mangled, so that
1833 // __unsafe_unretained types in ARC produce the same manglings as the
1834 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1835 // better ABI compatibility.
1836 //
1837 // It's safe to do this because unqualified 'id' won't show up
1838 // in any type signatures that need to be mangled.
1839 break;
1840 }
John McCall07daf722016-03-01 22:18:03 +00001841
1842 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1843 if (Quals.hasRestrict())
1844 Out << 'r';
1845 if (Quals.hasVolatile())
1846 Out << 'V';
1847 if (Quals.hasConst())
1848 Out << 'K';
1849}
1850
1851void CXXNameMangler::mangleVendorQualifier(StringRef name) {
1852 Out << 'U' << name.size() << name;
Guy Benyei11169dd2012-12-18 14:30:41 +00001853}
1854
1855void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1856 // <ref-qualifier> ::= R # lvalue reference
1857 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00001858 switch (RefQualifier) {
1859 case RQ_None:
1860 break;
1861
1862 case RQ_LValue:
1863 Out << 'R';
1864 break;
1865
1866 case RQ_RValue:
1867 Out << 'O';
1868 break;
1869 }
1870}
1871
1872void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1873 Context.mangleObjCMethodName(MD, Out);
1874}
1875
David Majnemereea02ee2014-11-28 22:22:46 +00001876static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1877 if (Quals)
1878 return true;
1879 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1880 return true;
1881 if (Ty->isOpenCLSpecificType())
1882 return true;
1883 if (Ty->isBuiltinType())
1884 return false;
1885
1886 return true;
1887}
1888
Guy Benyei11169dd2012-12-18 14:30:41 +00001889void CXXNameMangler::mangleType(QualType T) {
1890 // If our type is instantiation-dependent but not dependent, we mangle
1891 // it as it was written in the source, removing any top-level sugar.
1892 // Otherwise, use the canonical type.
1893 //
1894 // FIXME: This is an approximation of the instantiation-dependent name
1895 // mangling rules, since we should really be using the type as written and
1896 // augmented via semantic analysis (i.e., with implicit conversions and
1897 // default template arguments) for any instantiation-dependent type.
1898 // Unfortunately, that requires several changes to our AST:
1899 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1900 // uniqued, so that we can handle substitutions properly
1901 // - Default template arguments will need to be represented in the
1902 // TemplateSpecializationType, since they need to be mangled even though
1903 // they aren't written.
1904 // - Conversions on non-type template arguments need to be expressed, since
1905 // they can affect the mangling of sizeof/alignof.
1906 if (!T->isInstantiationDependentType() || T->isDependentType())
1907 T = T.getCanonicalType();
1908 else {
1909 // Desugar any types that are purely sugar.
1910 do {
1911 // Don't desugar through template specialization types that aren't
1912 // type aliases. We need to mangle the template arguments as written.
1913 if (const TemplateSpecializationType *TST
1914 = dyn_cast<TemplateSpecializationType>(T))
1915 if (!TST->isTypeAlias())
1916 break;
1917
1918 QualType Desugared
1919 = T.getSingleStepDesugaredType(Context.getASTContext());
1920 if (Desugared == T)
1921 break;
1922
1923 T = Desugared;
1924 } while (true);
1925 }
1926 SplitQualType split = T.split();
1927 Qualifiers quals = split.Quals;
1928 const Type *ty = split.Ty;
1929
David Majnemereea02ee2014-11-28 22:22:46 +00001930 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001931 if (isSubstitutable && mangleSubstitution(T))
1932 return;
1933
1934 // If we're mangling a qualified array type, push the qualifiers to
1935 // the element type.
1936 if (quals && isa<ArrayType>(T)) {
1937 ty = Context.getASTContext().getAsArrayType(T);
1938 quals = Qualifiers();
1939
1940 // Note that we don't update T: we want to add the
1941 // substitution at the original type.
1942 }
1943
1944 if (quals) {
1945 mangleQualifiers(quals);
1946 // Recurse: even if the qualified type isn't yet substitutable,
1947 // the unqualified type might be.
1948 mangleType(QualType(ty, 0));
1949 } else {
1950 switch (ty->getTypeClass()) {
1951#define ABSTRACT_TYPE(CLASS, PARENT)
1952#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1953 case Type::CLASS: \
1954 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1955 return;
1956#define TYPE(CLASS, PARENT) \
1957 case Type::CLASS: \
1958 mangleType(static_cast<const CLASS##Type*>(ty)); \
1959 break;
1960#include "clang/AST/TypeNodes.def"
1961 }
1962 }
1963
1964 // Add the substitution.
1965 if (isSubstitutable)
1966 addSubstitution(T);
1967}
1968
1969void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1970 if (!mangleStandardSubstitution(ND))
1971 mangleName(ND);
1972}
1973
1974void CXXNameMangler::mangleType(const BuiltinType *T) {
1975 // <type> ::= <builtin-type>
1976 // <builtin-type> ::= v # void
1977 // ::= w # wchar_t
1978 // ::= b # bool
1979 // ::= c # char
1980 // ::= a # signed char
1981 // ::= h # unsigned char
1982 // ::= s # short
1983 // ::= t # unsigned short
1984 // ::= i # int
1985 // ::= j # unsigned int
1986 // ::= l # long
1987 // ::= m # unsigned long
1988 // ::= x # long long, __int64
1989 // ::= y # unsigned long long, __int64
1990 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00001991 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00001992 // ::= f # float
1993 // ::= d # double
1994 // ::= e # long double, __float80
Nemanja Ivanovicd7d45bf2016-04-15 18:04:13 +00001995 // UNSUPPORTED: ::= g # __float128
Guy Benyei11169dd2012-12-18 14:30:41 +00001996 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1997 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1998 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1999 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2000 // ::= Di # char32_t
2001 // ::= Ds # char16_t
2002 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2003 // ::= u <source-name> # vendor extended type
Alexey Bader954ba212016-04-08 13:40:33 +00002004 std::string type_name;
Guy Benyei11169dd2012-12-18 14:30:41 +00002005 switch (T->getKind()) {
Alexey Baderbdf7c842015-09-15 12:18:29 +00002006 case BuiltinType::Void:
2007 Out << 'v';
2008 break;
2009 case BuiltinType::Bool:
2010 Out << 'b';
2011 break;
2012 case BuiltinType::Char_U:
2013 case BuiltinType::Char_S:
2014 Out << 'c';
2015 break;
2016 case BuiltinType::UChar:
2017 Out << 'h';
2018 break;
2019 case BuiltinType::UShort:
2020 Out << 't';
2021 break;
2022 case BuiltinType::UInt:
2023 Out << 'j';
2024 break;
2025 case BuiltinType::ULong:
2026 Out << 'm';
2027 break;
2028 case BuiltinType::ULongLong:
2029 Out << 'y';
2030 break;
2031 case BuiltinType::UInt128:
2032 Out << 'o';
2033 break;
2034 case BuiltinType::SChar:
2035 Out << 'a';
2036 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002037 case BuiltinType::WChar_S:
Alexey Baderbdf7c842015-09-15 12:18:29 +00002038 case BuiltinType::WChar_U:
2039 Out << 'w';
2040 break;
2041 case BuiltinType::Char16:
2042 Out << "Ds";
2043 break;
2044 case BuiltinType::Char32:
2045 Out << "Di";
2046 break;
2047 case BuiltinType::Short:
2048 Out << 's';
2049 break;
2050 case BuiltinType::Int:
2051 Out << 'i';
2052 break;
2053 case BuiltinType::Long:
2054 Out << 'l';
2055 break;
2056 case BuiltinType::LongLong:
2057 Out << 'x';
2058 break;
2059 case BuiltinType::Int128:
2060 Out << 'n';
2061 break;
2062 case BuiltinType::Half:
2063 Out << "Dh";
2064 break;
2065 case BuiltinType::Float:
2066 Out << 'f';
2067 break;
2068 case BuiltinType::Double:
2069 Out << 'd';
2070 break;
David Majnemer2617ea62015-06-09 18:05:33 +00002071 case BuiltinType::LongDouble:
2072 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2073 ? 'g'
2074 : 'e');
2075 break;
Alexey Baderbdf7c842015-09-15 12:18:29 +00002076 case BuiltinType::NullPtr:
2077 Out << "Dn";
2078 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002079
2080#define BUILTIN_TYPE(Id, SingletonId)
2081#define PLACEHOLDER_TYPE(Id, SingletonId) \
2082 case BuiltinType::Id:
2083#include "clang/AST/BuiltinTypes.def"
2084 case BuiltinType::Dependent:
2085 llvm_unreachable("mangling a placeholder type");
Alexey Baderbdf7c842015-09-15 12:18:29 +00002086 case BuiltinType::ObjCId:
2087 Out << "11objc_object";
2088 break;
2089 case BuiltinType::ObjCClass:
2090 Out << "10objc_class";
2091 break;
2092 case BuiltinType::ObjCSel:
2093 Out << "13objc_selector";
2094 break;
Alexey Bader954ba212016-04-08 13:40:33 +00002095#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2096 case BuiltinType::Id: \
2097 type_name = "ocl_" #ImgType "_" #Suffix; \
2098 Out << type_name.size() << type_name; \
Alexey Baderbdf7c842015-09-15 12:18:29 +00002099 break;
Alexey Baderb62f1442016-04-13 08:33:41 +00002100#include "clang/Basic/OpenCLImageTypes.def"
Alexey Baderbdf7c842015-09-15 12:18:29 +00002101 case BuiltinType::OCLSampler:
2102 Out << "11ocl_sampler";
2103 break;
2104 case BuiltinType::OCLEvent:
2105 Out << "9ocl_event";
2106 break;
Alexey Bader9c8453f2015-09-15 11:18:52 +00002107 case BuiltinType::OCLClkEvent:
2108 Out << "12ocl_clkevent";
2109 break;
2110 case BuiltinType::OCLQueue:
2111 Out << "9ocl_queue";
2112 break;
2113 case BuiltinType::OCLNDRange:
2114 Out << "11ocl_ndrange";
2115 break;
2116 case BuiltinType::OCLReserveID:
2117 Out << "13ocl_reserveid";
2118 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 }
2120}
2121
John McCall07daf722016-03-01 22:18:03 +00002122StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2123 switch (CC) {
2124 case CC_C:
2125 return "";
2126
2127 case CC_X86StdCall:
2128 case CC_X86FastCall:
2129 case CC_X86ThisCall:
2130 case CC_X86VectorCall:
2131 case CC_X86Pascal:
2132 case CC_X86_64Win64:
2133 case CC_X86_64SysV:
2134 case CC_AAPCS:
2135 case CC_AAPCS_VFP:
2136 case CC_IntelOclBicc:
2137 case CC_SpirFunction:
2138 case CC_SpirKernel:
Roman Levenstein35aa5ce2016-03-16 18:00:46 +00002139 case CC_PreserveMost:
2140 case CC_PreserveAll:
John McCall07daf722016-03-01 22:18:03 +00002141 // FIXME: we should be mangling all of the above.
2142 return "";
John McCall477f2bb2016-03-03 06:39:32 +00002143
2144 case CC_Swift:
2145 return "swiftcall";
John McCall07daf722016-03-01 22:18:03 +00002146 }
2147 llvm_unreachable("bad calling convention");
2148}
2149
2150void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2151 // Fast path.
2152 if (T->getExtInfo() == FunctionType::ExtInfo())
2153 return;
2154
2155 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2156 // This will get more complicated in the future if we mangle other
2157 // things here; but for now, since we mangle ns_returns_retained as
2158 // a qualifier on the result type, we can get away with this:
2159 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2160 if (!CCQualifier.empty())
2161 mangleVendorQualifier(CCQualifier);
2162
2163 // FIXME: regparm
2164 // FIXME: noreturn
2165}
2166
2167void
2168CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2169 // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2170
2171 // Note that these are *not* substitution candidates. Demanglers might
2172 // have trouble with this if the parameter type is fully substituted.
2173
John McCall477f2bb2016-03-03 06:39:32 +00002174 switch (PI.getABI()) {
2175 case ParameterABI::Ordinary:
2176 break;
2177
2178 // All of these start with "swift", so they come before "ns_consumed".
2179 case ParameterABI::SwiftContext:
2180 case ParameterABI::SwiftErrorResult:
2181 case ParameterABI::SwiftIndirectResult:
2182 mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2183 break;
2184 }
2185
John McCall07daf722016-03-01 22:18:03 +00002186 if (PI.isConsumed())
John McCall477f2bb2016-03-03 06:39:32 +00002187 mangleVendorQualifier("ns_consumed");
John McCall07daf722016-03-01 22:18:03 +00002188}
2189
Guy Benyei11169dd2012-12-18 14:30:41 +00002190// <type> ::= <function-type>
2191// <function-type> ::= [<CV-qualifiers>] F [Y]
2192// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002193void CXXNameMangler::mangleType(const FunctionProtoType *T) {
John McCall07daf722016-03-01 22:18:03 +00002194 mangleExtFunctionInfo(T);
2195
Guy Benyei11169dd2012-12-18 14:30:41 +00002196 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2197 // e.g. "const" in "int (A::*)() const".
2198 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2199
2200 Out << 'F';
2201
2202 // FIXME: We don't have enough information in the AST to produce the 'Y'
2203 // encoding for extern "C" function types.
2204 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2205
2206 // Mangle the ref-qualifier, if present.
2207 mangleRefQualifier(T->getRefQualifier());
2208
2209 Out << 'E';
2210}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002211
Guy Benyei11169dd2012-12-18 14:30:41 +00002212void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002213 // Function types without prototypes can arise when mangling a function type
2214 // within an overloadable function in C. We mangle these as the absence of any
2215 // parameter types (not even an empty parameter list).
2216 Out << 'F';
2217
2218 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2219
2220 FunctionTypeDepth.enterResultType();
2221 mangleType(T->getReturnType());
2222 FunctionTypeDepth.leaveResultType();
2223
2224 FunctionTypeDepth.pop(saved);
2225 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00002226}
Peter Collingbourneeeebc412015-08-07 23:25:47 +00002227
John McCall07daf722016-03-01 22:18:03 +00002228void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002229 bool MangleReturnType,
2230 const FunctionDecl *FD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002231 // Record that we're in a function type. See mangleFunctionParam
2232 // for details on what we're trying to achieve here.
2233 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2234
2235 // <bare-function-type> ::= <signature type>+
2236 if (MangleReturnType) {
2237 FunctionTypeDepth.enterResultType();
John McCall07daf722016-03-01 22:18:03 +00002238
2239 // Mangle ns_returns_retained as an order-sensitive qualifier here.
2240 if (Proto->getExtInfo().getProducesResult())
2241 mangleVendorQualifier("ns_returns_retained");
2242
2243 // Mangle the return type without any direct ARC ownership qualifiers.
2244 QualType ReturnTy = Proto->getReturnType();
2245 if (ReturnTy.getObjCLifetime()) {
2246 auto SplitReturnTy = ReturnTy.split();
2247 SplitReturnTy.Quals.removeObjCLifetime();
2248 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2249 }
2250 mangleType(ReturnTy);
2251
Guy Benyei11169dd2012-12-18 14:30:41 +00002252 FunctionTypeDepth.leaveResultType();
2253 }
2254
Alp Toker9cacbab2014-01-20 20:26:09 +00002255 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002256 // <builtin-type> ::= v # void
2257 Out << 'v';
2258
2259 FunctionTypeDepth.pop(saved);
2260 return;
2261 }
2262
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002263 assert(!FD || FD->getNumParams() == Proto->getNumParams());
2264 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
John McCall07daf722016-03-01 22:18:03 +00002265 // Mangle extended parameter info as order-sensitive qualifiers here.
2266 if (Proto->hasExtParameterInfos()) {
2267 mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2268 }
2269
2270 // Mangle the type.
2271 QualType ParamTy = Proto->getParamType(I);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00002272 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2273
2274 if (FD) {
2275 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2276 // Attr can only take 1 character, so we can hardcode the length below.
2277 assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2278 Out << "U17pass_object_size" << Attr->getType();
2279 }
2280 }
2281 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002282
2283 FunctionTypeDepth.pop(saved);
2284
2285 // <builtin-type> ::= z # ellipsis
2286 if (Proto->isVariadic())
2287 Out << 'z';
2288}
2289
2290// <type> ::= <class-enum-type>
2291// <class-enum-type> ::= <name>
2292void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2293 mangleName(T->getDecl());
2294}
2295
2296// <type> ::= <class-enum-type>
2297// <class-enum-type> ::= <name>
2298void CXXNameMangler::mangleType(const EnumType *T) {
2299 mangleType(static_cast<const TagType*>(T));
2300}
2301void CXXNameMangler::mangleType(const RecordType *T) {
2302 mangleType(static_cast<const TagType*>(T));
2303}
2304void CXXNameMangler::mangleType(const TagType *T) {
2305 mangleName(T->getDecl());
2306}
2307
2308// <type> ::= <array-type>
2309// <array-type> ::= A <positive dimension number> _ <element type>
2310// ::= A [<dimension expression>] _ <element type>
2311void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2312 Out << 'A' << T->getSize() << '_';
2313 mangleType(T->getElementType());
2314}
2315void CXXNameMangler::mangleType(const VariableArrayType *T) {
2316 Out << 'A';
2317 // decayed vla types (size 0) will just be skipped.
2318 if (T->getSizeExpr())
2319 mangleExpression(T->getSizeExpr());
2320 Out << '_';
2321 mangleType(T->getElementType());
2322}
2323void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2324 Out << 'A';
2325 mangleExpression(T->getSizeExpr());
2326 Out << '_';
2327 mangleType(T->getElementType());
2328}
2329void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2330 Out << "A_";
2331 mangleType(T->getElementType());
2332}
2333
2334// <type> ::= <pointer-to-member-type>
2335// <pointer-to-member-type> ::= M <class type> <member type>
2336void CXXNameMangler::mangleType(const MemberPointerType *T) {
2337 Out << 'M';
2338 mangleType(QualType(T->getClass(), 0));
2339 QualType PointeeType = T->getPointeeType();
2340 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2341 mangleType(FPT);
2342
2343 // Itanium C++ ABI 5.1.8:
2344 //
2345 // The type of a non-static member function is considered to be different,
2346 // for the purposes of substitution, from the type of a namespace-scope or
2347 // static member function whose type appears similar. The types of two
2348 // non-static member functions are considered to be different, for the
2349 // purposes of substitution, if the functions are members of different
2350 // classes. In other words, for the purposes of substitution, the class of
2351 // which the function is a member is considered part of the type of
2352 // function.
2353
2354 // Given that we already substitute member function pointers as a
2355 // whole, the net effect of this rule is just to unconditionally
2356 // suppress substitution on the function type in a member pointer.
2357 // We increment the SeqID here to emulate adding an entry to the
2358 // substitution table.
2359 ++SeqID;
2360 } else
2361 mangleType(PointeeType);
2362}
2363
2364// <type> ::= <template-param>
2365void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2366 mangleTemplateParameter(T->getIndex());
2367}
2368
2369// <type> ::= <template-param>
2370void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2371 // FIXME: not clear how to mangle this!
2372 // template <class T...> class A {
2373 // template <class U...> void foo(T(*)(U) x...);
2374 // };
2375 Out << "_SUBSTPACK_";
2376}
2377
2378// <type> ::= P <type> # pointer-to
2379void CXXNameMangler::mangleType(const PointerType *T) {
2380 Out << 'P';
2381 mangleType(T->getPointeeType());
2382}
2383void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2384 Out << 'P';
2385 mangleType(T->getPointeeType());
2386}
2387
2388// <type> ::= R <type> # reference-to
2389void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2390 Out << 'R';
2391 mangleType(T->getPointeeType());
2392}
2393
2394// <type> ::= O <type> # rvalue reference-to (C++0x)
2395void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2396 Out << 'O';
2397 mangleType(T->getPointeeType());
2398}
2399
2400// <type> ::= C <type> # complex pair (C 2000)
2401void CXXNameMangler::mangleType(const ComplexType *T) {
2402 Out << 'C';
2403 mangleType(T->getElementType());
2404}
2405
2406// ARM's ABI for Neon vector types specifies that they should be mangled as
2407// if they are structs (to match ARM's initial implementation). The
2408// vector type must be one of the special types predefined by ARM.
2409void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2410 QualType EltType = T->getElementType();
2411 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002412 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002413 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2414 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002415 case BuiltinType::SChar:
2416 case BuiltinType::UChar:
2417 EltName = "poly8_t";
2418 break;
2419 case BuiltinType::Short:
2420 case BuiltinType::UShort:
2421 EltName = "poly16_t";
2422 break;
2423 case BuiltinType::ULongLong:
2424 EltName = "poly64_t";
2425 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002426 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2427 }
2428 } else {
2429 switch (cast<BuiltinType>(EltType)->getKind()) {
2430 case BuiltinType::SChar: EltName = "int8_t"; break;
2431 case BuiltinType::UChar: EltName = "uint8_t"; break;
2432 case BuiltinType::Short: EltName = "int16_t"; break;
2433 case BuiltinType::UShort: EltName = "uint16_t"; break;
2434 case BuiltinType::Int: EltName = "int32_t"; break;
2435 case BuiltinType::UInt: EltName = "uint32_t"; break;
2436 case BuiltinType::LongLong: EltName = "int64_t"; break;
2437 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002438 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002439 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002440 case BuiltinType::Half: EltName = "float16_t";break;
2441 default:
2442 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002443 }
2444 }
Craig Topper36250ad2014-05-12 05:36:57 +00002445 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002446 unsigned BitSize = (T->getNumElements() *
2447 getASTContext().getTypeSize(EltType));
2448 if (BitSize == 64)
2449 BaseName = "__simd64_";
2450 else {
2451 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2452 BaseName = "__simd128_";
2453 }
2454 Out << strlen(BaseName) + strlen(EltName);
2455 Out << BaseName << EltName;
2456}
2457
Tim Northover2fe823a2013-08-01 09:23:19 +00002458static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2459 switch (EltType->getKind()) {
2460 case BuiltinType::SChar:
2461 return "Int8";
2462 case BuiltinType::Short:
2463 return "Int16";
2464 case BuiltinType::Int:
2465 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002466 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002467 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002468 return "Int64";
2469 case BuiltinType::UChar:
2470 return "Uint8";
2471 case BuiltinType::UShort:
2472 return "Uint16";
2473 case BuiltinType::UInt:
2474 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002475 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002476 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002477 return "Uint64";
2478 case BuiltinType::Half:
2479 return "Float16";
2480 case BuiltinType::Float:
2481 return "Float32";
2482 case BuiltinType::Double:
2483 return "Float64";
2484 default:
2485 llvm_unreachable("Unexpected vector element base type");
2486 }
2487}
2488
2489// AArch64's ABI for Neon vector types specifies that they should be mangled as
2490// the equivalent internal name. The vector type must be one of the special
2491// types predefined by ARM.
2492void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2493 QualType EltType = T->getElementType();
2494 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2495 unsigned BitSize =
2496 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002497 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002498
2499 assert((BitSize == 64 || BitSize == 128) &&
2500 "Neon vector type not 64 or 128 bits");
2501
Tim Northover2fe823a2013-08-01 09:23:19 +00002502 StringRef EltName;
2503 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2504 switch (cast<BuiltinType>(EltType)->getKind()) {
2505 case BuiltinType::UChar:
2506 EltName = "Poly8";
2507 break;
2508 case BuiltinType::UShort:
2509 EltName = "Poly16";
2510 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002511 case BuiltinType::ULong:
Kevin Qin78b86532015-05-14 08:18:05 +00002512 case BuiltinType::ULongLong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002513 EltName = "Poly64";
2514 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002515 default:
2516 llvm_unreachable("unexpected Neon polynomial vector element type");
2517 }
2518 } else
2519 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2520
2521 std::string TypeName =
Benjamin Kramerb42d9a52015-12-24 10:07:37 +00002522 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
Tim Northover2fe823a2013-08-01 09:23:19 +00002523 Out << TypeName.length() << TypeName;
2524}
2525
Guy Benyei11169dd2012-12-18 14:30:41 +00002526// GNU extension: vector types
2527// <type> ::= <vector-type>
2528// <vector-type> ::= Dv <positive dimension number> _
2529// <extended element type>
2530// ::= Dv [<dimension expression>] _ <element type>
2531// <extended element type> ::= <element type>
2532// ::= p # AltiVec vector pixel
2533// ::= b # Altivec vector bool
2534void CXXNameMangler::mangleType(const VectorType *T) {
2535 if ((T->getVectorKind() == VectorType::NeonVector ||
2536 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002537 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00002538 llvm::Triple::ArchType Arch =
2539 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00002540 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00002541 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00002542 mangleAArch64NeonVectorType(T);
2543 else
2544 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00002545 return;
2546 }
2547 Out << "Dv" << T->getNumElements() << '_';
2548 if (T->getVectorKind() == VectorType::AltiVecPixel)
2549 Out << 'p';
2550 else if (T->getVectorKind() == VectorType::AltiVecBool)
2551 Out << 'b';
2552 else
2553 mangleType(T->getElementType());
2554}
2555void CXXNameMangler::mangleType(const ExtVectorType *T) {
2556 mangleType(static_cast<const VectorType*>(T));
2557}
2558void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2559 Out << "Dv";
2560 mangleExpression(T->getSizeExpr());
2561 Out << '_';
2562 mangleType(T->getElementType());
2563}
2564
2565void CXXNameMangler::mangleType(const PackExpansionType *T) {
2566 // <type> ::= Dp <type> # pack expansion (C++0x)
2567 Out << "Dp";
2568 mangleType(T->getPattern());
2569}
2570
2571void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2572 mangleSourceName(T->getDecl()->getIdentifier());
2573}
2574
2575void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Douglas Gregorab209d82015-07-07 03:58:42 +00002576 // Treat __kindof as a vendor extended type qualifier.
2577 if (T->isKindOfType())
2578 Out << "U8__kindof";
2579
Eli Friedman5f508952013-06-18 22:41:37 +00002580 if (!T->qual_empty()) {
2581 // Mangle protocol qualifiers.
2582 SmallString<64> QualStr;
2583 llvm::raw_svector_ostream QualOS(QualStr);
2584 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00002585 for (const auto *I : T->quals()) {
2586 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00002587 QualOS << name.size() << name;
2588 }
Eli Friedman5f508952013-06-18 22:41:37 +00002589 Out << 'U' << QualStr.size() << QualStr;
2590 }
Douglas Gregorab209d82015-07-07 03:58:42 +00002591
Guy Benyei11169dd2012-12-18 14:30:41 +00002592 mangleType(T->getBaseType());
Douglas Gregorab209d82015-07-07 03:58:42 +00002593
2594 if (T->isSpecialized()) {
2595 // Mangle type arguments as I <type>+ E
2596 Out << 'I';
2597 for (auto typeArg : T->getTypeArgs())
2598 mangleType(typeArg);
2599 Out << 'E';
2600 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002601}
2602
2603void CXXNameMangler::mangleType(const BlockPointerType *T) {
2604 Out << "U13block_pointer";
2605 mangleType(T->getPointeeType());
2606}
2607
2608void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2609 // Mangle injected class name types as if the user had written the
2610 // specialization out fully. It may not actually be possible to see
2611 // this mangling, though.
2612 mangleType(T->getInjectedSpecializationType());
2613}
2614
2615void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2616 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2617 mangleName(TD, T->getArgs(), T->getNumArgs());
2618 } else {
2619 if (mangleSubstitution(QualType(T, 0)))
2620 return;
2621
2622 mangleTemplatePrefix(T->getTemplateName());
2623
2624 // FIXME: GCC does not appear to mangle the template arguments when
2625 // the template in question is a dependent template name. Should we
2626 // emulate that badness?
2627 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2628 addSubstitution(QualType(T, 0));
2629 }
2630}
2631
2632void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00002633 // Proposal by cxx-abi-dev, 2014-03-26
2634 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2635 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002636 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00002637 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002638 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00002639 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002640 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00002641 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002642 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00002643 switch (T->getKeyword()) {
2644 case ETK_Typename:
2645 break;
2646 case ETK_Struct:
2647 case ETK_Class:
2648 case ETK_Interface:
2649 Out << "Ts";
2650 break;
2651 case ETK_Union:
2652 Out << "Tu";
2653 break;
2654 case ETK_Enum:
2655 Out << "Te";
2656 break;
2657 default:
2658 llvm_unreachable("unexpected keyword for dependent type name");
2659 }
David Majnemer2e159fb2014-04-15 05:51:25 +00002660 // Typename types are always nested
2661 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00002662 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00002663 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00002664 Out << 'E';
2665}
2666
2667void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2668 // Dependently-scoped template types are nested if they have a prefix.
2669 Out << 'N';
2670
2671 // TODO: avoid making this TemplateName.
2672 TemplateName Prefix =
2673 getASTContext().getDependentTemplateName(T->getQualifier(),
2674 T->getIdentifier());
2675 mangleTemplatePrefix(Prefix);
2676
2677 // FIXME: GCC does not appear to mangle the template arguments when
2678 // the template in question is a dependent template name. Should we
2679 // emulate that badness?
2680 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2681 Out << 'E';
2682}
2683
2684void CXXNameMangler::mangleType(const TypeOfType *T) {
2685 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2686 // "extension with parameters" mangling.
2687 Out << "u6typeof";
2688}
2689
2690void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2691 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2692 // "extension with parameters" mangling.
2693 Out << "u6typeof";
2694}
2695
2696void CXXNameMangler::mangleType(const DecltypeType *T) {
2697 Expr *E = T->getUnderlyingExpr();
2698
2699 // type ::= Dt <expression> E # decltype of an id-expression
2700 // # or class member access
2701 // ::= DT <expression> E # decltype of an expression
2702
2703 // This purports to be an exhaustive list of id-expressions and
2704 // class member accesses. Note that we do not ignore parentheses;
2705 // parentheses change the semantics of decltype for these
2706 // expressions (and cause the mangler to use the other form).
2707 if (isa<DeclRefExpr>(E) ||
2708 isa<MemberExpr>(E) ||
2709 isa<UnresolvedLookupExpr>(E) ||
2710 isa<DependentScopeDeclRefExpr>(E) ||
2711 isa<CXXDependentScopeMemberExpr>(E) ||
2712 isa<UnresolvedMemberExpr>(E))
2713 Out << "Dt";
2714 else
2715 Out << "DT";
2716 mangleExpression(E);
2717 Out << 'E';
2718}
2719
2720void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2721 // If this is dependent, we need to record that. If not, we simply
2722 // mangle it as the underlying type since they are equivalent.
2723 if (T->isDependentType()) {
2724 Out << 'U';
2725
2726 switch (T->getUTTKind()) {
2727 case UnaryTransformType::EnumUnderlyingType:
2728 Out << "3eut";
2729 break;
2730 }
2731 }
2732
2733 mangleType(T->getUnderlyingType());
2734}
2735
2736void CXXNameMangler::mangleType(const AutoType *T) {
2737 QualType D = T->getDeducedType();
2738 // <builtin-type> ::= Da # dependent auto
Richard Smithe301ba22015-11-11 02:02:15 +00002739 if (D.isNull()) {
2740 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2741 "shouldn't need to mangle __auto_type!");
Richard Smith74aeef52013-04-26 16:15:35 +00002742 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Richard Smithe301ba22015-11-11 02:02:15 +00002743 } else
Guy Benyei11169dd2012-12-18 14:30:41 +00002744 mangleType(D);
2745}
2746
2747void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00002748 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00002749 // (Until there's a standardized mangling...)
2750 Out << "U7_Atomic";
2751 mangleType(T->getValueType());
2752}
2753
Xiuli Pan9c14e282016-01-09 12:53:17 +00002754void CXXNameMangler::mangleType(const PipeType *T) {
2755 // Pipe type mangling rules are described in SPIR 2.0 specification
2756 // A.1 Data types and A.3 Summary of changes
2757 // <type> ::= 8ocl_pipe
2758 Out << "8ocl_pipe";
2759}
2760
Guy Benyei11169dd2012-12-18 14:30:41 +00002761void CXXNameMangler::mangleIntegerLiteral(QualType T,
2762 const llvm::APSInt &Value) {
2763 // <expr-primary> ::= L <type> <value number> E # integer literal
2764 Out << 'L';
2765
2766 mangleType(T);
2767 if (T->isBooleanType()) {
2768 // Boolean values are encoded as 0/1.
2769 Out << (Value.getBoolValue() ? '1' : '0');
2770 } else {
2771 mangleNumber(Value);
2772 }
2773 Out << 'E';
2774
2775}
2776
David Majnemer1dabfdc2015-02-14 13:23:54 +00002777void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2778 // Ignore member expressions involving anonymous unions.
2779 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2780 if (!RT->getDecl()->isAnonymousStructOrUnion())
2781 break;
2782 const auto *ME = dyn_cast<MemberExpr>(Base);
2783 if (!ME)
2784 break;
2785 Base = ME->getBase();
2786 IsArrow = ME->isArrow();
2787 }
2788
2789 if (Base->isImplicitCXXThis()) {
2790 // Note: GCC mangles member expressions to the implicit 'this' as
2791 // *this., whereas we represent them as this->. The Itanium C++ ABI
2792 // does not specify anything here, so we follow GCC.
2793 Out << "dtdefpT";
2794 } else {
2795 Out << (IsArrow ? "pt" : "dt");
2796 mangleExpression(Base);
2797 }
2798}
2799
Guy Benyei11169dd2012-12-18 14:30:41 +00002800/// Mangles a member expression.
2801void CXXNameMangler::mangleMemberExpr(const Expr *base,
2802 bool isArrow,
2803 NestedNameSpecifier *qualifier,
2804 NamedDecl *firstQualifierLookup,
2805 DeclarationName member,
2806 unsigned arity) {
2807 // <expression> ::= dt <expression> <unresolved-name>
2808 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00002809 if (base)
2810 mangleMemberExprBase(base, isArrow);
David Majnemerb8014dd2015-02-19 02:16:16 +00002811 mangleUnresolvedName(qualifier, member, arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002812}
2813
2814/// Look at the callee of the given call expression and determine if
2815/// it's a parenthesized id-expression which would have triggered ADL
2816/// otherwise.
2817static bool isParenthesizedADLCallee(const CallExpr *call) {
2818 const Expr *callee = call->getCallee();
2819 const Expr *fn = callee->IgnoreParens();
2820
2821 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2822 // too, but for those to appear in the callee, it would have to be
2823 // parenthesized.
2824 if (callee == fn) return false;
2825
2826 // Must be an unresolved lookup.
2827 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2828 if (!lookup) return false;
2829
2830 assert(!lookup->requiresADL());
2831
2832 // Must be an unqualified lookup.
2833 if (lookup->getQualifier()) return false;
2834
2835 // Must not have found a class member. Note that if one is a class
2836 // member, they're all class members.
2837 if (lookup->getNumDecls() > 0 &&
2838 (*lookup->decls_begin())->isCXXClassMember())
2839 return false;
2840
2841 // Otherwise, ADL would have been triggered.
2842 return true;
2843}
2844
David Majnemer9c775c72014-09-23 04:27:55 +00002845void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2846 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2847 Out << CastEncoding;
2848 mangleType(ECE->getType());
2849 mangleExpression(ECE->getSubExpr());
2850}
2851
Richard Smith520449d2015-02-05 06:15:50 +00002852void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2853 if (auto *Syntactic = InitList->getSyntacticForm())
2854 InitList = Syntactic;
2855 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2856 mangleExpression(InitList->getInit(i));
2857}
2858
Guy Benyei11169dd2012-12-18 14:30:41 +00002859void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2860 // <expression> ::= <unary operator-name> <expression>
2861 // ::= <binary operator-name> <expression> <expression>
2862 // ::= <trinary operator-name> <expression> <expression> <expression>
2863 // ::= cv <type> expression # conversion with one argument
2864 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00002865 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2866 // ::= sc <type> <expression> # static_cast<type> (expression)
2867 // ::= cc <type> <expression> # const_cast<type> (expression)
2868 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00002869 // ::= st <type> # sizeof (a type)
2870 // ::= at <type> # alignof (a type)
2871 // ::= <template-param>
2872 // ::= <function-param>
2873 // ::= sr <type> <unqualified-name> # dependent name
2874 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2875 // ::= ds <expression> <expression> # expr.*expr
2876 // ::= sZ <template-param> # size of a parameter pack
2877 // ::= sZ <function-param> # size of a function parameter pack
2878 // ::= <expr-primary>
2879 // <expr-primary> ::= L <type> <value number> E # integer literal
2880 // ::= L <type <value float> E # floating literal
2881 // ::= L <mangled-name> E # external name
2882 // ::= fpT # 'this' expression
2883 QualType ImplicitlyConvertedToType;
2884
2885recurse:
2886 switch (E->getStmtClass()) {
2887 case Expr::NoStmtClass:
2888#define ABSTRACT_STMT(Type)
2889#define EXPR(Type, Base)
2890#define STMT(Type, Base) \
2891 case Expr::Type##Class:
2892#include "clang/AST/StmtNodes.inc"
2893 // fallthrough
2894
2895 // These all can only appear in local or variable-initialization
2896 // contexts and so should never appear in a mangling.
2897 case Expr::AddrLabelExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002898 case Expr::DesignatedInitUpdateExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002899 case Expr::ImplicitValueInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00002900 case Expr::NoInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002901 case Expr::ParenListExprClass:
2902 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00002903 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00002904 case Expr::MSPropertySubscriptExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002905 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Alexey Bataev1a3320e2015-08-25 14:24:04 +00002906 case Expr::OMPArraySectionExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002907 llvm_unreachable("unexpected statement kind");
2908
2909 // FIXME: invent manglings for all these.
2910 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 case Expr::ChooseExprClass:
2912 case Expr::CompoundLiteralExprClass:
Richard Smithed1cb882015-03-11 00:12:17 +00002913 case Expr::DesignatedInitExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002914 case Expr::ExtVectorElementExprClass:
2915 case Expr::GenericSelectionExprClass:
2916 case Expr::ObjCEncodeExprClass:
2917 case Expr::ObjCIsaExprClass:
2918 case Expr::ObjCIvarRefExprClass:
2919 case Expr::ObjCMessageExprClass:
2920 case Expr::ObjCPropertyRefExprClass:
2921 case Expr::ObjCProtocolExprClass:
2922 case Expr::ObjCSelectorExprClass:
2923 case Expr::ObjCStringLiteralClass:
2924 case Expr::ObjCBoxedExprClass:
2925 case Expr::ObjCArrayLiteralClass:
2926 case Expr::ObjCDictionaryLiteralClass:
2927 case Expr::ObjCSubscriptRefExprClass:
2928 case Expr::ObjCIndirectCopyRestoreExprClass:
2929 case Expr::OffsetOfExprClass:
2930 case Expr::PredefinedExprClass:
2931 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002932 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002933 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002934 case Expr::TypeTraitExprClass:
2935 case Expr::ArrayTypeTraitExprClass:
2936 case Expr::ExpressionTraitExprClass:
2937 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002938 case Expr::CUDAKernelCallExprClass:
2939 case Expr::AsTypeExprClass:
2940 case Expr::PseudoObjectExprClass:
2941 case Expr::AtomicExprClass:
2942 {
2943 // As bad as this diagnostic is, it's better than crashing.
2944 DiagnosticsEngine &Diags = Context.getDiags();
2945 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2946 "cannot yet mangle expression type %0");
2947 Diags.Report(E->getExprLoc(), DiagID)
2948 << E->getStmtClassName() << E->getSourceRange();
2949 break;
2950 }
2951
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00002952 case Expr::CXXUuidofExprClass: {
2953 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2954 if (UE->isTypeOperand()) {
2955 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2956 Out << "u8__uuidoft";
2957 mangleType(UuidT);
2958 } else {
2959 Expr *UuidExp = UE->getExprOperand();
2960 Out << "u8__uuidofz";
2961 mangleExpression(UuidExp, Arity);
2962 }
2963 break;
2964 }
2965
Guy Benyei11169dd2012-12-18 14:30:41 +00002966 // Even gcc-4.5 doesn't mangle this.
2967 case Expr::BinaryConditionalOperatorClass: {
2968 DiagnosticsEngine &Diags = Context.getDiags();
2969 unsigned DiagID =
2970 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2971 "?: operator with omitted middle operand cannot be mangled");
2972 Diags.Report(E->getExprLoc(), DiagID)
2973 << E->getStmtClassName() << E->getSourceRange();
2974 break;
2975 }
2976
2977 // These are used for internal purposes and cannot be meaningfully mangled.
2978 case Expr::OpaqueValueExprClass:
2979 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2980
2981 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00002982 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00002983 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00002984 Out << "E";
2985 break;
2986 }
2987
2988 case Expr::CXXDefaultArgExprClass:
2989 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2990 break;
2991
Richard Smith852c9db2013-04-20 22:23:05 +00002992 case Expr::CXXDefaultInitExprClass:
2993 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2994 break;
2995
Richard Smithcc1b96d2013-06-12 22:31:48 +00002996 case Expr::CXXStdInitializerListExprClass:
2997 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2998 break;
2999
Guy Benyei11169dd2012-12-18 14:30:41 +00003000 case Expr::SubstNonTypeTemplateParmExprClass:
3001 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3002 Arity);
3003 break;
3004
3005 case Expr::UserDefinedLiteralClass:
3006 // We follow g++'s approach of mangling a UDL as a call to the literal
3007 // operator.
3008 case Expr::CXXMemberCallExprClass: // fallthrough
3009 case Expr::CallExprClass: {
3010 const CallExpr *CE = cast<CallExpr>(E);
3011
3012 // <expression> ::= cp <simple-id> <expression>* E
3013 // We use this mangling only when the call would use ADL except
3014 // for being parenthesized. Per discussion with David
3015 // Vandervoorde, 2011.04.25.
3016 if (isParenthesizedADLCallee(CE)) {
3017 Out << "cp";
3018 // The callee here is a parenthesized UnresolvedLookupExpr with
3019 // no qualifier and should always get mangled as a <simple-id>
3020 // anyway.
3021
3022 // <expression> ::= cl <expression>* E
3023 } else {
3024 Out << "cl";
3025 }
3026
David Majnemer67a8ec62015-02-19 21:41:48 +00003027 unsigned CallArity = CE->getNumArgs();
3028 for (const Expr *Arg : CE->arguments())
3029 if (isa<PackExpansionExpr>(Arg))
3030 CallArity = UnknownArity;
3031
3032 mangleExpression(CE->getCallee(), CallArity);
3033 for (const Expr *Arg : CE->arguments())
3034 mangleExpression(Arg);
Guy Benyei11169dd2012-12-18 14:30:41 +00003035 Out << 'E';
3036 break;
3037 }
3038
3039 case Expr::CXXNewExprClass: {
3040 const CXXNewExpr *New = cast<CXXNewExpr>(E);
3041 if (New->isGlobalNew()) Out << "gs";
3042 Out << (New->isArray() ? "na" : "nw");
3043 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3044 E = New->placement_arg_end(); I != E; ++I)
3045 mangleExpression(*I);
3046 Out << '_';
3047 mangleType(New->getAllocatedType());
3048 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003049 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3050 Out << "il";
3051 else
3052 Out << "pi";
3053 const Expr *Init = New->getInitializer();
3054 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3055 // Directly inline the initializers.
3056 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3057 E = CCE->arg_end();
3058 I != E; ++I)
3059 mangleExpression(*I);
3060 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3061 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3062 mangleExpression(PLE->getExpr(i));
3063 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3064 isa<InitListExpr>(Init)) {
3065 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00003066 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00003067 } else
3068 mangleExpression(Init);
3069 }
3070 Out << 'E';
3071 break;
3072 }
3073
David Majnemer1dabfdc2015-02-14 13:23:54 +00003074 case Expr::CXXPseudoDestructorExprClass: {
3075 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3076 if (const Expr *Base = PDE->getBase())
3077 mangleMemberExprBase(Base, PDE->isArrow());
David Majnemerb8014dd2015-02-19 02:16:16 +00003078 NestedNameSpecifier *Qualifier = PDE->getQualifier();
3079 QualType ScopeType;
3080 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3081 if (Qualifier) {
3082 mangleUnresolvedPrefix(Qualifier,
3083 /*Recursive=*/true);
3084 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3085 Out << 'E';
3086 } else {
3087 Out << "sr";
3088 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3089 Out << 'E';
3090 }
3091 } else if (Qualifier) {
3092 mangleUnresolvedPrefix(Qualifier);
3093 }
David Majnemer1dabfdc2015-02-14 13:23:54 +00003094 // <base-unresolved-name> ::= dn <destructor-name>
3095 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00003096 QualType DestroyedType = PDE->getDestroyedType();
David Majnemerb8014dd2015-02-19 02:16:16 +00003097 mangleUnresolvedTypeOrSimpleId(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00003098 break;
3099 }
3100
Guy Benyei11169dd2012-12-18 14:30:41 +00003101 case Expr::MemberExprClass: {
3102 const MemberExpr *ME = cast<MemberExpr>(E);
3103 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00003104 ME->getQualifier(), nullptr,
3105 ME->getMemberDecl()->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003106 break;
3107 }
3108
3109 case Expr::UnresolvedMemberExprClass: {
3110 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003111 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3112 ME->isArrow(), ME->getQualifier(), nullptr,
3113 ME->getMemberName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003114 if (ME->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003115 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003116 break;
3117 }
3118
3119 case Expr::CXXDependentScopeMemberExprClass: {
3120 const CXXDependentScopeMemberExpr *ME
3121 = cast<CXXDependentScopeMemberExpr>(E);
Douglas Gregor3c523c42015-05-21 18:28:18 +00003122 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3123 ME->isArrow(), ME->getQualifier(),
3124 ME->getFirstQualifierFoundInScope(),
Guy Benyei11169dd2012-12-18 14:30:41 +00003125 ME->getMember(), Arity);
3126 if (ME->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003127 mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003128 break;
3129 }
3130
3131 case Expr::UnresolvedLookupExprClass: {
3132 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00003133 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003134
3135 // All the <unresolved-name> productions end in a
3136 // base-unresolved-name, where <template-args> are just tacked
3137 // onto the end.
3138 if (ULE->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003139 mangleTemplateArgs(ULE->getTemplateArgs(), ULE->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003140 break;
3141 }
3142
3143 case Expr::CXXUnresolvedConstructExprClass: {
3144 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3145 unsigned N = CE->arg_size();
3146
3147 Out << "cv";
3148 mangleType(CE->getType());
3149 if (N != 1) Out << '_';
3150 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3151 if (N != 1) Out << 'E';
3152 break;
3153 }
3154
Guy Benyei11169dd2012-12-18 14:30:41 +00003155 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00003156 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00003157 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00003158 assert(
3159 CE->getNumArgs() >= 1 &&
3160 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3161 "implicit CXXConstructExpr must have one argument");
3162 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3163 }
3164 Out << "il";
3165 for (auto *E : CE->arguments())
3166 mangleExpression(E);
3167 Out << "E";
3168 break;
3169 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003170
Richard Smith520449d2015-02-05 06:15:50 +00003171 case Expr::CXXTemporaryObjectExprClass: {
3172 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3173 unsigned N = CE->getNumArgs();
3174 bool List = CE->isListInitialization();
3175
3176 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00003177 Out << "tl";
3178 else
3179 Out << "cv";
3180 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003181 if (!List && N != 1)
3182 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00003183 if (CE->isStdInitListInitialization()) {
3184 // We implicitly created a std::initializer_list<T> for the first argument
3185 // of a constructor of type U in an expression of the form U{a, b, c}.
3186 // Strip all the semantic gunk off the initializer list.
3187 auto *SILE =
3188 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3189 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3190 mangleInitListElements(ILE);
3191 } else {
3192 for (auto *E : CE->arguments())
3193 mangleExpression(E);
3194 }
Richard Smith520449d2015-02-05 06:15:50 +00003195 if (List || N != 1)
3196 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003197 break;
3198 }
3199
3200 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003201 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003202 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003203 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003204 break;
3205
3206 case Expr::CXXNoexceptExprClass:
3207 Out << "nx";
3208 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3209 break;
3210
3211 case Expr::UnaryExprOrTypeTraitExprClass: {
3212 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3213
3214 if (!SAE->isInstantiationDependent()) {
3215 // Itanium C++ ABI:
3216 // If the operand of a sizeof or alignof operator is not
3217 // instantiation-dependent it is encoded as an integer literal
3218 // reflecting the result of the operator.
3219 //
3220 // If the result of the operator is implicitly converted to a known
3221 // integer type, that type is used for the literal; otherwise, the type
3222 // of std::size_t or std::ptrdiff_t is used.
3223 QualType T = (ImplicitlyConvertedToType.isNull() ||
3224 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3225 : ImplicitlyConvertedToType;
3226 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3227 mangleIntegerLiteral(T, V);
3228 break;
3229 }
3230
3231 switch(SAE->getKind()) {
3232 case UETT_SizeOf:
3233 Out << 's';
3234 break;
3235 case UETT_AlignOf:
3236 Out << 'a';
3237 break;
Alexey Bataev00396512015-07-02 03:40:19 +00003238 case UETT_VecStep: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003239 DiagnosticsEngine &Diags = Context.getDiags();
3240 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3241 "cannot yet mangle vec_step expression");
3242 Diags.Report(DiagID);
3243 return;
3244 }
Alexey Bataev00396512015-07-02 03:40:19 +00003245 case UETT_OpenMPRequiredSimdAlign:
3246 DiagnosticsEngine &Diags = Context.getDiags();
3247 unsigned DiagID = Diags.getCustomDiagID(
3248 DiagnosticsEngine::Error,
3249 "cannot yet mangle __builtin_omp_required_simd_align expression");
3250 Diags.Report(DiagID);
3251 return;
3252 }
Guy Benyei11169dd2012-12-18 14:30:41 +00003253 if (SAE->isArgumentType()) {
3254 Out << 't';
3255 mangleType(SAE->getArgumentType());
3256 } else {
3257 Out << 'z';
3258 mangleExpression(SAE->getArgumentExpr());
3259 }
3260 break;
3261 }
3262
3263 case Expr::CXXThrowExprClass: {
3264 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003265 // <expression> ::= tw <expression> # throw expression
3266 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003267 if (TE->getSubExpr()) {
3268 Out << "tw";
3269 mangleExpression(TE->getSubExpr());
3270 } else {
3271 Out << "tr";
3272 }
3273 break;
3274 }
3275
3276 case Expr::CXXTypeidExprClass: {
3277 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003278 // <expression> ::= ti <type> # typeid (type)
3279 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003280 if (TIE->isTypeOperand()) {
3281 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003282 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003283 } else {
3284 Out << "te";
3285 mangleExpression(TIE->getExprOperand());
3286 }
3287 break;
3288 }
3289
3290 case Expr::CXXDeleteExprClass: {
3291 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003292 // <expression> ::= [gs] dl <expression> # [::] delete expr
3293 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003294 if (DE->isGlobalDelete()) Out << "gs";
3295 Out << (DE->isArrayForm() ? "da" : "dl");
3296 mangleExpression(DE->getArgument());
3297 break;
3298 }
3299
3300 case Expr::UnaryOperatorClass: {
3301 const UnaryOperator *UO = cast<UnaryOperator>(E);
3302 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3303 /*Arity=*/1);
3304 mangleExpression(UO->getSubExpr());
3305 break;
3306 }
3307
3308 case Expr::ArraySubscriptExprClass: {
3309 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3310
3311 // Array subscript is treated as a syntactically weird form of
3312 // binary operator.
3313 Out << "ix";
3314 mangleExpression(AE->getLHS());
3315 mangleExpression(AE->getRHS());
3316 break;
3317 }
3318
3319 case Expr::CompoundAssignOperatorClass: // fallthrough
3320 case Expr::BinaryOperatorClass: {
3321 const BinaryOperator *BO = cast<BinaryOperator>(E);
3322 if (BO->getOpcode() == BO_PtrMemD)
3323 Out << "ds";
3324 else
3325 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3326 /*Arity=*/2);
3327 mangleExpression(BO->getLHS());
3328 mangleExpression(BO->getRHS());
3329 break;
3330 }
3331
3332 case Expr::ConditionalOperatorClass: {
3333 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3334 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3335 mangleExpression(CO->getCond());
3336 mangleExpression(CO->getLHS(), Arity);
3337 mangleExpression(CO->getRHS(), Arity);
3338 break;
3339 }
3340
3341 case Expr::ImplicitCastExprClass: {
3342 ImplicitlyConvertedToType = E->getType();
3343 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3344 goto recurse;
3345 }
3346
3347 case Expr::ObjCBridgedCastExprClass: {
3348 // Mangle ownership casts as a vendor extended operator __bridge,
3349 // __bridge_transfer, or __bridge_retain.
3350 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3351 Out << "v1U" << Kind.size() << Kind;
3352 }
3353 // Fall through to mangle the cast itself.
3354
3355 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003356 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003357 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003358
Richard Smith520449d2015-02-05 06:15:50 +00003359 case Expr::CXXFunctionalCastExprClass: {
3360 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3361 // FIXME: Add isImplicit to CXXConstructExpr.
3362 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3363 if (CCE->getParenOrBraceRange().isInvalid())
3364 Sub = CCE->getArg(0)->IgnoreImplicit();
3365 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3366 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3367 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3368 Out << "tl";
3369 mangleType(E->getType());
3370 mangleInitListElements(IL);
3371 Out << "E";
3372 } else {
3373 mangleCastExpression(E, "cv");
3374 }
3375 break;
3376 }
3377
David Majnemer9c775c72014-09-23 04:27:55 +00003378 case Expr::CXXStaticCastExprClass:
3379 mangleCastExpression(E, "sc");
3380 break;
3381 case Expr::CXXDynamicCastExprClass:
3382 mangleCastExpression(E, "dc");
3383 break;
3384 case Expr::CXXReinterpretCastExprClass:
3385 mangleCastExpression(E, "rc");
3386 break;
3387 case Expr::CXXConstCastExprClass:
3388 mangleCastExpression(E, "cc");
3389 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003390
3391 case Expr::CXXOperatorCallExprClass: {
3392 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3393 unsigned NumArgs = CE->getNumArgs();
3394 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3395 // Mangle the arguments.
3396 for (unsigned i = 0; i != NumArgs; ++i)
3397 mangleExpression(CE->getArg(i));
3398 break;
3399 }
3400
3401 case Expr::ParenExprClass:
3402 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3403 break;
3404
3405 case Expr::DeclRefExprClass: {
3406 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3407
3408 switch (D->getKind()) {
3409 default:
3410 // <expr-primary> ::= L <mangled-name> E # external name
3411 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003412 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003413 Out << 'E';
3414 break;
3415
3416 case Decl::ParmVar:
3417 mangleFunctionParam(cast<ParmVarDecl>(D));
3418 break;
3419
3420 case Decl::EnumConstant: {
3421 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3422 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3423 break;
3424 }
3425
3426 case Decl::NonTypeTemplateParm: {
3427 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3428 mangleTemplateParameter(PD->getIndex());
3429 break;
3430 }
3431
3432 }
3433
3434 break;
3435 }
3436
3437 case Expr::SubstNonTypeTemplateParmPackExprClass:
3438 // FIXME: not clear how to mangle this!
3439 // template <unsigned N...> class A {
3440 // template <class U...> void foo(U (&x)[N]...);
3441 // };
3442 Out << "_SUBSTPACK_";
3443 break;
3444
3445 case Expr::FunctionParmPackExprClass: {
3446 // FIXME: not clear how to mangle this!
3447 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3448 Out << "v110_SUBSTPACK";
3449 mangleFunctionParam(FPPE->getParameterPack());
3450 break;
3451 }
3452
3453 case Expr::DependentScopeDeclRefExprClass: {
3454 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
David Majnemerb8014dd2015-02-19 02:16:16 +00003455 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003456
3457 // All the <unresolved-name> productions end in a
3458 // base-unresolved-name, where <template-args> are just tacked
3459 // onto the end.
3460 if (DRE->hasExplicitTemplateArgs())
James Y Knight04ec5bf2015-12-24 02:59:37 +00003461 mangleTemplateArgs(DRE->getTemplateArgs(), DRE->getNumTemplateArgs());
Guy Benyei11169dd2012-12-18 14:30:41 +00003462 break;
3463 }
3464
3465 case Expr::CXXBindTemporaryExprClass:
3466 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3467 break;
3468
3469 case Expr::ExprWithCleanupsClass:
3470 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3471 break;
3472
3473 case Expr::FloatingLiteralClass: {
3474 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3475 Out << 'L';
3476 mangleType(FL->getType());
3477 mangleFloat(FL->getValue());
3478 Out << 'E';
3479 break;
3480 }
3481
3482 case Expr::CharacterLiteralClass:
3483 Out << 'L';
3484 mangleType(E->getType());
3485 Out << cast<CharacterLiteral>(E)->getValue();
3486 Out << 'E';
3487 break;
3488
3489 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3490 case Expr::ObjCBoolLiteralExprClass:
3491 Out << "Lb";
3492 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3493 Out << 'E';
3494 break;
3495
3496 case Expr::CXXBoolLiteralExprClass:
3497 Out << "Lb";
3498 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3499 Out << 'E';
3500 break;
3501
3502 case Expr::IntegerLiteralClass: {
3503 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3504 if (E->getType()->isSignedIntegerType())
3505 Value.setIsSigned(true);
3506 mangleIntegerLiteral(E->getType(), Value);
3507 break;
3508 }
3509
3510 case Expr::ImaginaryLiteralClass: {
3511 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3512 // Mangle as if a complex literal.
3513 // Proposal from David Vandevoorde, 2010.06.30.
3514 Out << 'L';
3515 mangleType(E->getType());
3516 if (const FloatingLiteral *Imag =
3517 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3518 // Mangle a floating-point zero of the appropriate type.
3519 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3520 Out << '_';
3521 mangleFloat(Imag->getValue());
3522 } else {
3523 Out << "0_";
3524 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3525 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3526 Value.setIsSigned(true);
3527 mangleNumber(Value);
3528 }
3529 Out << 'E';
3530 break;
3531 }
3532
3533 case Expr::StringLiteralClass: {
3534 // Revised proposal from David Vandervoorde, 2010.07.15.
3535 Out << 'L';
3536 assert(isa<ConstantArrayType>(E->getType()));
3537 mangleType(E->getType());
3538 Out << 'E';
3539 break;
3540 }
3541
3542 case Expr::GNUNullExprClass:
3543 // FIXME: should this really be mangled the same as nullptr?
3544 // fallthrough
3545
3546 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003547 Out << "LDnE";
3548 break;
3549 }
3550
3551 case Expr::PackExpansionExprClass:
3552 Out << "sp";
3553 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3554 break;
3555
3556 case Expr::SizeOfPackExprClass: {
Richard Smithd784e682015-09-23 21:41:42 +00003557 auto *SPE = cast<SizeOfPackExpr>(E);
3558 if (SPE->isPartiallySubstituted()) {
3559 Out << "sP";
3560 for (const auto &A : SPE->getPartialArguments())
3561 mangleTemplateArg(A);
3562 Out << "E";
3563 break;
3564 }
3565
Guy Benyei11169dd2012-12-18 14:30:41 +00003566 Out << "sZ";
Richard Smithd784e682015-09-23 21:41:42 +00003567 const NamedDecl *Pack = SPE->getPack();
Guy Benyei11169dd2012-12-18 14:30:41 +00003568 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3569 mangleTemplateParameter(TTP->getIndex());
3570 else if (const NonTypeTemplateParmDecl *NTTP
3571 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3572 mangleTemplateParameter(NTTP->getIndex());
3573 else if (const TemplateTemplateParmDecl *TempTP
3574 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3575 mangleTemplateParameter(TempTP->getIndex());
3576 else
3577 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3578 break;
3579 }
Richard Smith0f0af192014-11-08 05:07:16 +00003580
Guy Benyei11169dd2012-12-18 14:30:41 +00003581 case Expr::MaterializeTemporaryExprClass: {
3582 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3583 break;
3584 }
Richard Smith0f0af192014-11-08 05:07:16 +00003585
3586 case Expr::CXXFoldExprClass: {
3587 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00003588 if (FE->isLeftFold())
3589 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00003590 else
Richard Smith8e6923b2014-11-10 19:44:15 +00003591 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00003592
3593 if (FE->getOperator() == BO_PtrMemD)
3594 Out << "ds";
3595 else
3596 mangleOperatorName(
3597 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3598 /*Arity=*/2);
3599
3600 if (FE->getLHS())
3601 mangleExpression(FE->getLHS());
3602 if (FE->getRHS())
3603 mangleExpression(FE->getRHS());
3604 break;
3605 }
3606
Guy Benyei11169dd2012-12-18 14:30:41 +00003607 case Expr::CXXThisExprClass:
3608 Out << "fpT";
3609 break;
Richard Smith9f690bd2015-10-27 06:02:45 +00003610
3611 case Expr::CoawaitExprClass:
3612 // FIXME: Propose a non-vendor mangling.
3613 Out << "v18co_await";
3614 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3615 break;
3616
3617 case Expr::CoyieldExprClass:
3618 // FIXME: Propose a non-vendor mangling.
3619 Out << "v18co_yield";
3620 mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3621 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003622 }
3623}
3624
3625/// Mangle an expression which refers to a parameter variable.
3626///
3627/// <expression> ::= <function-param>
3628/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3629/// <function-param> ::= fp <top-level CV-qualifiers>
3630/// <parameter-2 non-negative number> _ # L == 0, I > 0
3631/// <function-param> ::= fL <L-1 non-negative number>
3632/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3633/// <function-param> ::= fL <L-1 non-negative number>
3634/// p <top-level CV-qualifiers>
3635/// <I-1 non-negative number> _ # L > 0, I > 0
3636///
3637/// L is the nesting depth of the parameter, defined as 1 if the
3638/// parameter comes from the innermost function prototype scope
3639/// enclosing the current context, 2 if from the next enclosing
3640/// function prototype scope, and so on, with one special case: if
3641/// we've processed the full parameter clause for the innermost
3642/// function type, then L is one less. This definition conveniently
3643/// makes it irrelevant whether a function's result type was written
3644/// trailing or leading, but is otherwise overly complicated; the
3645/// numbering was first designed without considering references to
3646/// parameter in locations other than return types, and then the
3647/// mangling had to be generalized without changing the existing
3648/// manglings.
3649///
3650/// I is the zero-based index of the parameter within its parameter
3651/// declaration clause. Note that the original ABI document describes
3652/// this using 1-based ordinals.
3653void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3654 unsigned parmDepth = parm->getFunctionScopeDepth();
3655 unsigned parmIndex = parm->getFunctionScopeIndex();
3656
3657 // Compute 'L'.
3658 // parmDepth does not include the declaring function prototype.
3659 // FunctionTypeDepth does account for that.
3660 assert(parmDepth < FunctionTypeDepth.getDepth());
3661 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3662 if (FunctionTypeDepth.isInResultType())
3663 nestingDepth--;
3664
3665 if (nestingDepth == 0) {
3666 Out << "fp";
3667 } else {
3668 Out << "fL" << (nestingDepth - 1) << 'p';
3669 }
3670
3671 // Top-level qualifiers. We don't have to worry about arrays here,
3672 // because parameters declared as arrays should already have been
3673 // transformed to have pointer type. FIXME: apparently these don't
3674 // get mangled if used as an rvalue of a known non-class type?
3675 assert(!parm->getType()->isArrayType()
3676 && "parameter's type is still an array type?");
3677 mangleQualifiers(parm->getType().getQualifiers());
3678
3679 // Parameter index.
3680 if (parmIndex != 0) {
3681 Out << (parmIndex - 1);
3682 }
3683 Out << '_';
3684}
3685
3686void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3687 // <ctor-dtor-name> ::= C1 # complete object constructor
3688 // ::= C2 # base object constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00003689 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003690 // In addition, C5 is a comdat name with C1 and C2 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003691 switch (T) {
3692 case Ctor_Complete:
3693 Out << "C1";
3694 break;
3695 case Ctor_Base:
3696 Out << "C2";
3697 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003698 case Ctor_Comdat:
3699 Out << "C5";
Guy Benyei11169dd2012-12-18 14:30:41 +00003700 break;
David Majnemerdfa6d202015-03-11 18:36:39 +00003701 case Ctor_DefaultClosure:
3702 case Ctor_CopyingClosure:
3703 llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
Guy Benyei11169dd2012-12-18 14:30:41 +00003704 }
3705}
3706
3707void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3708 // <ctor-dtor-name> ::= D0 # deleting destructor
3709 // ::= D1 # complete object destructor
3710 // ::= D2 # base object destructor
3711 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003712 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003713 switch (T) {
3714 case Dtor_Deleting:
3715 Out << "D0";
3716 break;
3717 case Dtor_Complete:
3718 Out << "D1";
3719 break;
3720 case Dtor_Base:
3721 Out << "D2";
3722 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003723 case Dtor_Comdat:
3724 Out << "D5";
3725 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003726 }
3727}
3728
James Y Knight04ec5bf2015-12-24 02:59:37 +00003729void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
3730 unsigned NumTemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003731 // <template-args> ::= I <template-arg>+ E
3732 Out << 'I';
James Y Knight04ec5bf2015-12-24 02:59:37 +00003733 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3734 mangleTemplateArg(TemplateArgs[i].getArgument());
Guy Benyei11169dd2012-12-18 14:30:41 +00003735 Out << 'E';
3736}
3737
3738void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3739 // <template-args> ::= I <template-arg>+ E
3740 Out << 'I';
3741 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3742 mangleTemplateArg(AL[i]);
3743 Out << 'E';
3744}
3745
3746void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3747 unsigned NumTemplateArgs) {
3748 // <template-args> ::= I <template-arg>+ E
3749 Out << 'I';
3750 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3751 mangleTemplateArg(TemplateArgs[i]);
3752 Out << 'E';
3753}
3754
3755void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3756 // <template-arg> ::= <type> # type or template
3757 // ::= X <expression> E # expression
3758 // ::= <expr-primary> # simple expressions
3759 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00003760 if (!A.isInstantiationDependent() || A.isDependent())
3761 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3762
3763 switch (A.getKind()) {
3764 case TemplateArgument::Null:
3765 llvm_unreachable("Cannot mangle NULL template argument");
3766
3767 case TemplateArgument::Type:
3768 mangleType(A.getAsType());
3769 break;
3770 case TemplateArgument::Template:
3771 // This is mangled as <type>.
3772 mangleType(A.getAsTemplate());
3773 break;
3774 case TemplateArgument::TemplateExpansion:
3775 // <type> ::= Dp <type> # pack expansion (C++0x)
3776 Out << "Dp";
3777 mangleType(A.getAsTemplateOrTemplatePattern());
3778 break;
3779 case TemplateArgument::Expression: {
3780 // It's possible to end up with a DeclRefExpr here in certain
3781 // dependent cases, in which case we should mangle as a
3782 // declaration.
3783 const Expr *E = A.getAsExpr()->IgnoreParens();
3784 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3785 const ValueDecl *D = DRE->getDecl();
3786 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
David Majnemera16d4702015-02-18 19:08:14 +00003787 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003788 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003789 Out << 'E';
3790 break;
3791 }
3792 }
3793
3794 Out << 'X';
3795 mangleExpression(E);
3796 Out << 'E';
3797 break;
3798 }
3799 case TemplateArgument::Integral:
3800 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3801 break;
3802 case TemplateArgument::Declaration: {
3803 // <expr-primary> ::= L <mangled-name> E # external name
3804 // Clang produces AST's where pointer-to-member-function expressions
3805 // and pointer-to-function expressions are represented as a declaration not
3806 // an expression. We compensate for it here to produce the correct mangling.
3807 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00003808 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003809 if (compensateMangling) {
3810 Out << 'X';
3811 mangleOperatorName(OO_Amp, 1);
3812 }
3813
3814 Out << 'L';
3815 // References to external entities use the mangled name; if the name would
3816 // not normally be manged then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00003817 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003818 Out << 'E';
3819
3820 if (compensateMangling)
3821 Out << 'E';
3822
3823 break;
3824 }
3825 case TemplateArgument::NullPtr: {
3826 // <expr-primary> ::= L <type> 0 E
3827 Out << 'L';
3828 mangleType(A.getNullPtrType());
3829 Out << "0E";
3830 break;
3831 }
3832 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00003833 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00003834 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00003835 for (const auto &P : A.pack_elements())
3836 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00003837 Out << 'E';
3838 }
3839 }
3840}
3841
3842void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3843 // <template-param> ::= T_ # first template parameter
3844 // ::= T <parameter-2 non-negative number> _
3845 if (Index == 0)
3846 Out << "T_";
3847 else
3848 Out << 'T' << (Index - 1) << '_';
3849}
3850
David Majnemer3b3bdb52014-05-06 22:49:16 +00003851void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3852 if (SeqID == 1)
3853 Out << '0';
3854 else if (SeqID > 1) {
3855 SeqID--;
3856
3857 // <seq-id> is encoded in base-36, using digits and upper case letters.
3858 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00003859 MutableArrayRef<char> BufferRef(Buffer);
3860 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00003861
3862 for (; SeqID != 0; SeqID /= 36) {
3863 unsigned C = SeqID % 36;
3864 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3865 }
3866
3867 Out.write(I.base(), I - BufferRef.rbegin());
3868 }
3869 Out << '_';
3870}
3871
Guy Benyei11169dd2012-12-18 14:30:41 +00003872void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3873 bool result = mangleSubstitution(type);
3874 assert(result && "no existing substitution for type");
3875 (void) result;
3876}
3877
3878void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3879 bool result = mangleSubstitution(tname);
3880 assert(result && "no existing substitution for template name");
3881 (void) result;
3882}
3883
3884// <substitution> ::= S <seq-id> _
3885// ::= S_
3886bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3887 // Try one of the standard substitutions first.
3888 if (mangleStandardSubstitution(ND))
3889 return true;
3890
3891 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3892 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3893}
3894
Justin Bognere8d762e2015-05-22 06:48:13 +00003895/// Determine whether the given type has any qualifiers that are relevant for
3896/// substitutions.
Guy Benyei11169dd2012-12-18 14:30:41 +00003897static bool hasMangledSubstitutionQualifiers(QualType T) {
3898 Qualifiers Qs = T.getQualifiers();
3899 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3900}
3901
3902bool CXXNameMangler::mangleSubstitution(QualType T) {
3903 if (!hasMangledSubstitutionQualifiers(T)) {
3904 if (const RecordType *RT = T->getAs<RecordType>())
3905 return mangleSubstitution(RT->getDecl());
3906 }
3907
3908 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3909
3910 return mangleSubstitution(TypePtr);
3911}
3912
3913bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3914 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3915 return mangleSubstitution(TD);
3916
3917 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3918 return mangleSubstitution(
3919 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3920}
3921
3922bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3923 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3924 if (I == Substitutions.end())
3925 return false;
3926
3927 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00003928 Out << 'S';
3929 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00003930
3931 return true;
3932}
3933
3934static bool isCharType(QualType T) {
3935 if (T.isNull())
3936 return false;
3937
3938 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3939 T->isSpecificBuiltinType(BuiltinType::Char_U);
3940}
3941
Justin Bognere8d762e2015-05-22 06:48:13 +00003942/// Returns whether a given type is a template specialization of a given name
3943/// with a single argument of type char.
Guy Benyei11169dd2012-12-18 14:30:41 +00003944static bool isCharSpecialization(QualType T, const char *Name) {
3945 if (T.isNull())
3946 return false;
3947
3948 const RecordType *RT = T->getAs<RecordType>();
3949 if (!RT)
3950 return false;
3951
3952 const ClassTemplateSpecializationDecl *SD =
3953 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3954 if (!SD)
3955 return false;
3956
3957 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3958 return false;
3959
3960 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3961 if (TemplateArgs.size() != 1)
3962 return false;
3963
3964 if (!isCharType(TemplateArgs[0].getAsType()))
3965 return false;
3966
3967 return SD->getIdentifier()->getName() == Name;
3968}
3969
3970template <std::size_t StrLen>
3971static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3972 const char (&Str)[StrLen]) {
3973 if (!SD->getIdentifier()->isStr(Str))
3974 return false;
3975
3976 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3977 if (TemplateArgs.size() != 2)
3978 return false;
3979
3980 if (!isCharType(TemplateArgs[0].getAsType()))
3981 return false;
3982
3983 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3984 return false;
3985
3986 return true;
3987}
3988
3989bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3990 // <substitution> ::= St # ::std::
3991 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3992 if (isStd(NS)) {
3993 Out << "St";
3994 return true;
3995 }
3996 }
3997
3998 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3999 if (!isStdNamespace(getEffectiveDeclContext(TD)))
4000 return false;
4001
4002 // <substitution> ::= Sa # ::std::allocator
4003 if (TD->getIdentifier()->isStr("allocator")) {
4004 Out << "Sa";
4005 return true;
4006 }
4007
4008 // <<substitution> ::= Sb # ::std::basic_string
4009 if (TD->getIdentifier()->isStr("basic_string")) {
4010 Out << "Sb";
4011 return true;
4012 }
4013 }
4014
4015 if (const ClassTemplateSpecializationDecl *SD =
4016 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4017 if (!isStdNamespace(getEffectiveDeclContext(SD)))
4018 return false;
4019
4020 // <substitution> ::= Ss # ::std::basic_string<char,
4021 // ::std::char_traits<char>,
4022 // ::std::allocator<char> >
4023 if (SD->getIdentifier()->isStr("basic_string")) {
4024 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4025
4026 if (TemplateArgs.size() != 3)
4027 return false;
4028
4029 if (!isCharType(TemplateArgs[0].getAsType()))
4030 return false;
4031
4032 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4033 return false;
4034
4035 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4036 return false;
4037
4038 Out << "Ss";
4039 return true;
4040 }
4041
4042 // <substitution> ::= Si # ::std::basic_istream<char,
4043 // ::std::char_traits<char> >
4044 if (isStreamCharSpecialization(SD, "basic_istream")) {
4045 Out << "Si";
4046 return true;
4047 }
4048
4049 // <substitution> ::= So # ::std::basic_ostream<char,
4050 // ::std::char_traits<char> >
4051 if (isStreamCharSpecialization(SD, "basic_ostream")) {
4052 Out << "So";
4053 return true;
4054 }
4055
4056 // <substitution> ::= Sd # ::std::basic_iostream<char,
4057 // ::std::char_traits<char> >
4058 if (isStreamCharSpecialization(SD, "basic_iostream")) {
4059 Out << "Sd";
4060 return true;
4061 }
4062 }
4063 return false;
4064}
4065
4066void CXXNameMangler::addSubstitution(QualType T) {
4067 if (!hasMangledSubstitutionQualifiers(T)) {
4068 if (const RecordType *RT = T->getAs<RecordType>()) {
4069 addSubstitution(RT->getDecl());
4070 return;
4071 }
4072 }
4073
4074 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4075 addSubstitution(TypePtr);
4076}
4077
4078void CXXNameMangler::addSubstitution(TemplateName Template) {
4079 if (TemplateDecl *TD = Template.getAsTemplateDecl())
4080 return addSubstitution(TD);
4081
4082 Template = Context.getASTContext().getCanonicalTemplateName(Template);
4083 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4084}
4085
4086void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4087 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4088 Substitutions[Ptr] = SeqID++;
4089}
4090
4091//
4092
Justin Bognere8d762e2015-05-22 06:48:13 +00004093/// Mangles the name of the declaration D and emits that name to the given
4094/// output stream.
Guy Benyei11169dd2012-12-18 14:30:41 +00004095///
4096/// If the declaration D requires a mangled name, this routine will emit that
4097/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4098/// and this routine will return false. In this case, the caller should just
4099/// emit the identifier of the declaration (\c D->getIdentifier()) as its
4100/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00004101void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4102 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004103 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4104 "Invalid mangleName() call, argument is not a variable or function!");
4105 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4106 "Invalid mangleName() call on 'structor decl!");
4107
4108 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4109 getASTContext().getSourceManager(),
4110 "Mangling declaration");
4111
4112 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004113 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00004114}
4115
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004116void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4117 CXXCtorType Type,
4118 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004119 CXXNameMangler Mangler(*this, Out, D, Type);
4120 Mangler.mangle(D);
4121}
4122
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004123void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4124 CXXDtorType Type,
4125 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004126 CXXNameMangler Mangler(*this, Out, D, Type);
4127 Mangler.mangle(D);
4128}
4129
Rafael Espindola1e4df922014-09-16 15:18:21 +00004130void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4131 raw_ostream &Out) {
4132 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4133 Mangler.mangle(D);
4134}
4135
4136void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4137 raw_ostream &Out) {
4138 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4139 Mangler.mangle(D);
4140}
4141
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004142void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4143 const ThunkInfo &Thunk,
4144 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004145 // <special-name> ::= T <call-offset> <base encoding>
4146 // # base is the nominal target function of thunk
4147 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4148 // # base is the nominal target function of thunk
4149 // # first call-offset is 'this' adjustment
4150 // # second call-offset is result adjustment
4151
4152 assert(!isa<CXXDestructorDecl>(MD) &&
4153 "Use mangleCXXDtor for destructor decls!");
4154 CXXNameMangler Mangler(*this, Out);
4155 Mangler.getStream() << "_ZT";
4156 if (!Thunk.Return.isEmpty())
4157 Mangler.getStream() << 'c';
4158
4159 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004160 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4161 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4162
Guy Benyei11169dd2012-12-18 14:30:41 +00004163 // Mangle the return pointer adjustment if there is one.
4164 if (!Thunk.Return.isEmpty())
4165 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00004166 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4167
Guy Benyei11169dd2012-12-18 14:30:41 +00004168 Mangler.mangleFunctionEncoding(MD);
4169}
4170
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004171void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4172 const CXXDestructorDecl *DD, CXXDtorType Type,
4173 const ThisAdjustment &ThisAdjustment, 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 CXXNameMangler Mangler(*this, Out, DD, Type);
4177 Mangler.getStream() << "_ZT";
4178
4179 // Mangle the 'this' pointer adjustment.
4180 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00004181 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00004182
4183 Mangler.mangleFunctionEncoding(DD);
4184}
4185
Justin Bognere8d762e2015-05-22 06:48:13 +00004186/// Returns the mangled name for a guard variable for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004187void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4188 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004189 // <special-name> ::= GV <object name> # Guard variable for one-time
4190 // # initialization
4191 CXXNameMangler Mangler(*this, Out);
4192 Mangler.getStream() << "_ZGV";
4193 Mangler.mangleName(D);
4194}
4195
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004196void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4197 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00004198 // These symbols are internal in the Itanium ABI, so the names don't matter.
4199 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4200 // avoid duplicate symbols.
4201 Out << "__cxx_global_var_init";
4202}
4203
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004204void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4205 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00004206 // Prefix the mangling of D with __dtor_.
4207 CXXNameMangler Mangler(*this, Out);
4208 Mangler.getStream() << "__dtor_";
4209 if (shouldMangleDeclName(D))
4210 Mangler.mangle(D);
4211 else
4212 Mangler.getStream() << D->getName();
4213}
4214
Reid Kleckner1d59f992015-01-22 01:36:17 +00004215void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4216 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4217 CXXNameMangler Mangler(*this, Out);
4218 Mangler.getStream() << "__filt_";
4219 if (shouldMangleDeclName(EnclosingDecl))
4220 Mangler.mangle(EnclosingDecl);
4221 else
4222 Mangler.getStream() << EnclosingDecl->getName();
4223}
4224
Reid Klecknerebaf28d2015-04-14 20:59:00 +00004225void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4226 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4227 CXXNameMangler Mangler(*this, Out);
4228 Mangler.getStream() << "__fin_";
4229 if (shouldMangleDeclName(EnclosingDecl))
4230 Mangler.mangle(EnclosingDecl);
4231 else
4232 Mangler.getStream() << EnclosingDecl->getName();
4233}
4234
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004235void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4236 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004237 // <special-name> ::= TH <object name>
4238 CXXNameMangler Mangler(*this, Out);
4239 Mangler.getStream() << "_ZTH";
4240 Mangler.mangleName(D);
4241}
4242
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004243void
4244ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4245 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004246 // <special-name> ::= TW <object name>
4247 CXXNameMangler Mangler(*this, Out);
4248 Mangler.getStream() << "_ZTW";
4249 Mangler.mangleName(D);
4250}
4251
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004252void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004253 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004254 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004255 // We match the GCC mangling here.
4256 // <special-name> ::= GR <object name>
4257 CXXNameMangler Mangler(*this, Out);
4258 Mangler.getStream() << "_ZGR";
4259 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004260 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004261 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004262}
4263
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004264void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4265 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004266 // <special-name> ::= TV <type> # virtual table
4267 CXXNameMangler Mangler(*this, Out);
4268 Mangler.getStream() << "_ZTV";
4269 Mangler.mangleNameOrStandardSubstitution(RD);
4270}
4271
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004272void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4273 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004274 // <special-name> ::= TT <type> # VTT structure
4275 CXXNameMangler Mangler(*this, Out);
4276 Mangler.getStream() << "_ZTT";
4277 Mangler.mangleNameOrStandardSubstitution(RD);
4278}
4279
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004280void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4281 int64_t Offset,
4282 const CXXRecordDecl *Type,
4283 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004284 // <special-name> ::= TC <type> <offset number> _ <base type>
4285 CXXNameMangler Mangler(*this, Out);
4286 Mangler.getStream() << "_ZTC";
4287 Mangler.mangleNameOrStandardSubstitution(RD);
4288 Mangler.getStream() << Offset;
4289 Mangler.getStream() << '_';
4290 Mangler.mangleNameOrStandardSubstitution(Type);
4291}
4292
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004293void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004294 // <special-name> ::= TI <type> # typeinfo structure
4295 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4296 CXXNameMangler Mangler(*this, Out);
4297 Mangler.getStream() << "_ZTI";
4298 Mangler.mangleType(Ty);
4299}
4300
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004301void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4302 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004303 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4304 CXXNameMangler Mangler(*this, Out);
4305 Mangler.getStream() << "_ZTS";
4306 Mangler.mangleType(Ty);
4307}
4308
Reid Klecknercc99e262013-11-19 23:23:00 +00004309void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4310 mangleCXXRTTIName(Ty, Out);
4311}
4312
David Majnemer58e5bee2014-03-24 21:43:36 +00004313void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4314 llvm_unreachable("Can't mangle string literals");
4315}
4316
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004317ItaniumMangleContext *
4318ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4319 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004320}