blob: b97a2e6d5718d02bcf0e3a8b5d26a726ede1028a [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"
23#include "clang/AST/DeclTemplate.h"
David Majnemer58e5bee2014-03-24 21:43:36 +000024#include "clang/AST/Expr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000025#include "clang/AST/ExprCXX.h"
26#include "clang/AST/ExprObjC.h"
27#include "clang/AST/TypeLoc.h"
28#include "clang/Basic/ABI.h"
29#include "clang/Basic/SourceManager.h"
30#include "clang/Basic/TargetInfo.h"
31#include "llvm/ADT/StringExtras.h"
32#include "llvm/Support/ErrorHandling.h"
33#include "llvm/Support/raw_ostream.h"
34
35#define MANGLE_CHECKER 0
36
37#if MANGLE_CHECKER
38#include <cxxabi.h>
39#endif
40
41using namespace clang;
42
43namespace {
44
45/// \brief Retrieve the declaration context that should be used when mangling
46/// the given declaration.
47static const DeclContext *getEffectiveDeclContext(const Decl *D) {
48 // The ABI assumes that lambda closure types that occur within
49 // default arguments live in the context of the function. However, due to
50 // the way in which Clang parses and creates function declarations, this is
51 // not the case: the lambda closure type ends up living in the context
52 // where the function itself resides, because the function declaration itself
53 // had not yet been created. Fix the context here.
54 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
55 if (RD->isLambda())
56 if (ParmVarDecl *ContextParam
57 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
58 return ContextParam->getDeclContext();
59 }
Eli Friedman0cd23352013-07-10 01:33:19 +000060
61 // Perform the same check for block literals.
62 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
63 if (ParmVarDecl *ContextParam
64 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
65 return ContextParam->getDeclContext();
66 }
Guy Benyei11169dd2012-12-18 14:30:41 +000067
Eli Friedman95f50122013-07-02 17:52:28 +000068 const DeclContext *DC = D->getDeclContext();
69 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
70 return getEffectiveDeclContext(CD);
71
David Majnemerf8c02e62015-02-18 19:08:11 +000072 if (const auto *VD = dyn_cast<VarDecl>(D))
73 if (VD->isExternC())
74 return VD->getASTContext().getTranslationUnitDecl();
75
76 if (const auto *FD = dyn_cast<FunctionDecl>(D))
77 if (FD->isExternC())
78 return FD->getASTContext().getTranslationUnitDecl();
79
Eli Friedman95f50122013-07-02 17:52:28 +000080 return DC;
Guy Benyei11169dd2012-12-18 14:30:41 +000081}
82
83static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
84 return getEffectiveDeclContext(cast<Decl>(DC));
85}
Eli Friedman95f50122013-07-02 17:52:28 +000086
87static bool isLocalContainerContext(const DeclContext *DC) {
88 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
89}
90
Eli Friedmaneecc09a2013-07-05 20:27:40 +000091static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman92821742013-07-02 02:01:18 +000092 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000093 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman95f50122013-07-02 17:52:28 +000094 if (isLocalContainerContext(DC))
Eli Friedmaneecc09a2013-07-05 20:27:40 +000095 return dyn_cast<RecordDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +000096 D = cast<Decl>(DC);
97 DC = getEffectiveDeclContext(D);
Guy Benyei11169dd2012-12-18 14:30:41 +000098 }
Craig Topper36250ad2014-05-12 05:36:57 +000099 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000100}
101
102static const FunctionDecl *getStructor(const FunctionDecl *fn) {
103 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
104 return ftd->getTemplatedDecl();
105
106 return fn;
107}
108
109static const NamedDecl *getStructor(const NamedDecl *decl) {
110 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
111 return (fn ? getStructor(fn) : decl);
112}
David Majnemer2206bf52014-03-05 08:57:59 +0000113
114static bool isLambda(const NamedDecl *ND) {
115 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
116 if (!Record)
117 return false;
118
119 return Record->isLambda();
120}
121
Guy Benyei11169dd2012-12-18 14:30:41 +0000122static const unsigned UnknownArity = ~0U;
123
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000124class ItaniumMangleContextImpl : public ItaniumMangleContext {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000125 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
126 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei11169dd2012-12-18 14:30:41 +0000127 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
Evgeny Astigeevich665027d2014-12-12 16:17:46 +0000128
Guy Benyei11169dd2012-12-18 14:30:41 +0000129public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000130 explicit ItaniumMangleContextImpl(ASTContext &Context,
131 DiagnosticsEngine &Diags)
132 : ItaniumMangleContext(Context, Diags) {}
Guy Benyei11169dd2012-12-18 14:30:41 +0000133
Guy Benyei11169dd2012-12-18 14:30:41 +0000134 /// @name Mangler Entry Points
135 /// @{
136
Craig Toppercbce6e92014-03-11 06:22:39 +0000137 bool shouldMangleCXXName(const NamedDecl *D) override;
David Majnemer58e5bee2014-03-24 21:43:36 +0000138 bool shouldMangleStringLiteral(const StringLiteral *) override {
139 return false;
140 }
Craig Toppercbce6e92014-03-11 06:22:39 +0000141 void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
142 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
143 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000144 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
145 const ThisAdjustment &ThisAdjustment,
Craig Toppercbce6e92014-03-11 06:22:39 +0000146 raw_ostream &) override;
David Majnemerdaff3702014-05-01 17:50:17 +0000147 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
148 raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000149 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
150 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000151 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
Craig Toppercbce6e92014-03-11 06:22:39 +0000152 const CXXRecordDecl *Type, raw_ostream &) override;
153 void mangleCXXRTTI(QualType T, raw_ostream &) override;
154 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
155 void mangleTypeName(QualType T, raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000156 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000157 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000158 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
Craig Toppercbce6e92014-03-11 06:22:39 +0000159 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000160
Rafael Espindola1e4df922014-09-16 15:18:21 +0000161 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
162 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000163 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
164 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
165 void mangleDynamicAtExitDestructor(const VarDecl *D,
166 raw_ostream &Out) override;
Reid Kleckner1d59f992015-01-22 01:36:17 +0000167 void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
168 raw_ostream &Out) override;
Craig Toppercbce6e92014-03-11 06:22:39 +0000169 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
170 void mangleItaniumThreadLocalWrapper(const VarDecl *D,
171 raw_ostream &) override;
Guy Benyei11169dd2012-12-18 14:30:41 +0000172
David Majnemer58e5bee2014-03-24 21:43:36 +0000173 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
174
Guy Benyei11169dd2012-12-18 14:30:41 +0000175 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000176 // Lambda closure types are already numbered.
David Majnemer2206bf52014-03-05 08:57:59 +0000177 if (isLambda(ND))
178 return false;
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000179
180 // Anonymous tags are already numbered.
181 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
182 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
183 return false;
184 }
185
186 // Use the canonical number for externally visible decls.
187 if (ND->isExternallyVisible()) {
188 unsigned discriminator = getASTContext().getManglingNumber(ND);
189 if (discriminator == 1)
190 return false;
191 disc = discriminator - 2;
192 return true;
193 }
194
195 // Make up a reasonable number for internal decls.
Guy Benyei11169dd2012-12-18 14:30:41 +0000196 unsigned &discriminator = Uniquifier[ND];
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000197 if (!discriminator) {
198 const DeclContext *DC = getEffectiveDeclContext(ND);
199 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
200 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000201 if (discriminator == 1)
202 return false;
203 disc = discriminator-2;
204 return true;
205 }
206 /// @}
207};
208
209/// CXXNameMangler - Manage the mangling of a single name.
210class CXXNameMangler {
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000211 ItaniumMangleContextImpl &Context;
Guy Benyei11169dd2012-12-18 14:30:41 +0000212 raw_ostream &Out;
213
214 /// The "structor" is the top-level declaration being mangled, if
215 /// that's not a template specialization; otherwise it's the pattern
216 /// for that specialization.
217 const NamedDecl *Structor;
218 unsigned StructorType;
219
220 /// SeqID - The next subsitution sequence number.
221 unsigned SeqID;
222
223 class FunctionTypeDepthState {
224 unsigned Bits;
225
226 enum { InResultTypeMask = 1 };
227
228 public:
229 FunctionTypeDepthState() : Bits(0) {}
230
231 /// The number of function types we're inside.
232 unsigned getDepth() const {
233 return Bits >> 1;
234 }
235
236 /// True if we're in the return type of the innermost function type.
237 bool isInResultType() const {
238 return Bits & InResultTypeMask;
239 }
240
241 FunctionTypeDepthState push() {
242 FunctionTypeDepthState tmp = *this;
243 Bits = (Bits & ~InResultTypeMask) + 2;
244 return tmp;
245 }
246
247 void enterResultType() {
248 Bits |= InResultTypeMask;
249 }
250
251 void leaveResultType() {
252 Bits &= ~InResultTypeMask;
253 }
254
255 void pop(FunctionTypeDepthState saved) {
256 assert(getDepth() == saved.getDepth() + 1);
257 Bits = saved.Bits;
258 }
259
260 } FunctionTypeDepth;
261
262 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
263
264 ASTContext &getASTContext() const { return Context.getASTContext(); }
265
266public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000267 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Craig Topper36250ad2014-05-12 05:36:57 +0000268 const NamedDecl *D = nullptr)
Guy Benyei11169dd2012-12-18 14:30:41 +0000269 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
270 SeqID(0) {
271 // These can't be mangled without a ctor type or dtor type.
272 assert(!D || (!isa<CXXDestructorDecl>(D) &&
273 !isa<CXXConstructorDecl>(D)));
274 }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000275 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000276 const CXXConstructorDecl *D, CXXCtorType Type)
277 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
278 SeqID(0) { }
Timur Iskhodzhanov67455222013-10-03 06:26:13 +0000279 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
Guy Benyei11169dd2012-12-18 14:30:41 +0000280 const CXXDestructorDecl *D, CXXDtorType Type)
281 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
282 SeqID(0) { }
283
284#if MANGLE_CHECKER
285 ~CXXNameMangler() {
286 if (Out.str()[0] == '\01')
287 return;
288
289 int status = 0;
290 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
291 assert(status == 0 && "Could not demangle mangled name!");
292 free(result);
293 }
294#endif
295 raw_ostream &getStream() { return Out; }
296
David Majnemer7ff7eb72015-02-18 07:47:09 +0000297 void mangle(const NamedDecl *D);
Guy Benyei11169dd2012-12-18 14:30:41 +0000298 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
299 void mangleNumber(const llvm::APSInt &I);
300 void mangleNumber(int64_t Number);
301 void mangleFloat(const llvm::APFloat &F);
302 void mangleFunctionEncoding(const FunctionDecl *FD);
David Majnemer3b3bdb52014-05-06 22:49:16 +0000303 void mangleSeqID(unsigned SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +0000304 void mangleName(const NamedDecl *ND);
305 void mangleType(QualType T);
306 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
307
308private:
David Majnemer3b3bdb52014-05-06 22:49:16 +0000309
Guy Benyei11169dd2012-12-18 14:30:41 +0000310 bool mangleSubstitution(const NamedDecl *ND);
311 bool mangleSubstitution(QualType T);
312 bool mangleSubstitution(TemplateName Template);
313 bool mangleSubstitution(uintptr_t Ptr);
314
315 void mangleExistingSubstitution(QualType type);
316 void mangleExistingSubstitution(TemplateName name);
317
318 bool mangleStandardSubstitution(const NamedDecl *ND);
319
320 void addSubstitution(const NamedDecl *ND) {
321 ND = cast<NamedDecl>(ND->getCanonicalDecl());
322
323 addSubstitution(reinterpret_cast<uintptr_t>(ND));
324 }
325 void addSubstitution(QualType T);
326 void addSubstitution(TemplateName Template);
327 void addSubstitution(uintptr_t Ptr);
328
329 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
330 NamedDecl *firstQualifierLookup,
331 bool recursive = false);
332 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
333 NamedDecl *firstQualifierLookup,
334 DeclarationName name,
335 unsigned KnownArity = UnknownArity);
336
337 void mangleName(const TemplateDecl *TD,
338 const TemplateArgument *TemplateArgs,
339 unsigned NumTemplateArgs);
340 void mangleUnqualifiedName(const NamedDecl *ND) {
341 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
342 }
343 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
344 unsigned KnownArity);
345 void mangleUnscopedName(const NamedDecl *ND);
346 void mangleUnscopedTemplateName(const TemplateDecl *ND);
347 void mangleUnscopedTemplateName(TemplateName);
348 void mangleSourceName(const IdentifierInfo *II);
Eli Friedman95f50122013-07-02 17:52:28 +0000349 void mangleLocalName(const Decl *D);
350 void mangleBlockForPrefix(const BlockDecl *Block);
351 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei11169dd2012-12-18 14:30:41 +0000352 void mangleLambda(const CXXRecordDecl *Lambda);
353 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
354 bool NoFunction=false);
355 void mangleNestedName(const TemplateDecl *TD,
356 const TemplateArgument *TemplateArgs,
357 unsigned NumTemplateArgs);
358 void manglePrefix(NestedNameSpecifier *qualifier);
359 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
360 void manglePrefix(QualType type);
Eli Friedman86af13f02013-07-05 18:41:30 +0000361 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000362 void mangleTemplatePrefix(TemplateName Template);
David Majnemera88b3592015-02-18 02:28:01 +0000363 void mangleDestructorName(QualType DestroyedType);
364 void mangleOperatorName(DeclarationName Name, unsigned Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +0000365 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
366 void mangleQualifiers(Qualifiers Quals);
367 void mangleRefQualifier(RefQualifierKind RefQualifier);
368
369 void mangleObjCMethodName(const ObjCMethodDecl *MD);
370
371 // Declare manglers for every type class.
372#define ABSTRACT_TYPE(CLASS, PARENT)
373#define NON_CANONICAL_TYPE(CLASS, PARENT)
374#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
375#include "clang/AST/TypeNodes.def"
376
377 void mangleType(const TagType*);
378 void mangleType(TemplateName);
379 void mangleBareFunctionType(const FunctionType *T,
380 bool MangleReturnType);
381 void mangleNeonVectorType(const VectorType *T);
Tim Northover2fe823a2013-08-01 09:23:19 +0000382 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei11169dd2012-12-18 14:30:41 +0000383
384 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
David Majnemer1dabfdc2015-02-14 13:23:54 +0000385 void mangleMemberExprBase(const Expr *base, bool isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +0000386 void mangleMemberExpr(const Expr *base, bool isArrow,
387 NestedNameSpecifier *qualifier,
388 NamedDecl *firstQualifierLookup,
389 DeclarationName name,
390 unsigned knownArity);
David Majnemer9c775c72014-09-23 04:27:55 +0000391 void mangleCastExpression(const Expr *E, StringRef CastEncoding);
Richard Smith520449d2015-02-05 06:15:50 +0000392 void mangleInitListElements(const InitListExpr *InitList);
Guy Benyei11169dd2012-12-18 14:30:41 +0000393 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
394 void mangleCXXCtorType(CXXCtorType T);
395 void mangleCXXDtorType(CXXDtorType T);
396
397 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
398 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
399 unsigned NumTemplateArgs);
400 void mangleTemplateArgs(const TemplateArgumentList &AL);
401 void mangleTemplateArg(TemplateArgument A);
402
403 void mangleTemplateParameter(unsigned Index);
404
405 void mangleFunctionParam(const ParmVarDecl *parm);
406};
407
408}
409
Rafael Espindola002667c2013-10-16 01:40:34 +0000410bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000411 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000412 if (FD) {
413 LanguageLinkage L = FD->getLanguageLinkage();
414 // Overloadable functions need mangling.
415 if (FD->hasAttr<OverloadableAttr>())
416 return true;
417
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000418 // "main" is not mangled.
419 if (FD->isMain())
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000420 return false;
421
422 // C++ functions and those whose names are not a simple identifier need
423 // mangling.
424 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
425 return true;
Rafael Espindola46d2b6b2013-02-14 03:31:26 +0000426
Rafael Espindola3e0e33d2013-02-14 15:38:59 +0000427 // C functions are not mangled.
428 if (L == CLanguageLinkage)
429 return false;
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000430 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000431
432 // Otherwise, no mangling is done outside C++ mode.
433 if (!getASTContext().getLangOpts().CPlusPlus)
434 return false;
435
Rafael Espindola5bda63f2013-02-14 01:47:04 +0000436 const VarDecl *VD = dyn_cast<VarDecl>(D);
437 if (VD) {
438 // C variables are not mangled.
439 if (VD->isExternC())
440 return false;
441
442 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei11169dd2012-12-18 14:30:41 +0000443 const DeclContext *DC = getEffectiveDeclContext(D);
444 // Check for extern variable declared locally.
445 if (DC->isFunctionOrMethod() && D->hasLinkage())
446 while (!DC->isNamespace() && !DC->isTranslationUnit())
447 DC = getEffectiveParentContext(DC);
Larisse Voufo39a1e502013-08-06 01:03:05 +0000448 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
449 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000450 return false;
451 }
452
Guy Benyei11169dd2012-12-18 14:30:41 +0000453 return true;
454}
455
David Majnemer7ff7eb72015-02-18 07:47:09 +0000456void CXXNameMangler::mangle(const NamedDecl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000457 // <mangled-name> ::= _Z <encoding>
458 // ::= <data name>
459 // ::= <special-name>
David Majnemer7ff7eb72015-02-18 07:47:09 +0000460 Out << "_Z";
Guy Benyei11169dd2012-12-18 14:30:41 +0000461 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
462 mangleFunctionEncoding(FD);
463 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
464 mangleName(VD);
David Majnemer0eb8bbd2013-10-23 20:52:43 +0000465 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
466 mangleName(IFD->getAnonField());
Guy Benyei11169dd2012-12-18 14:30:41 +0000467 else
468 mangleName(cast<FieldDecl>(D));
469}
470
471void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
472 // <encoding> ::= <function name> <bare-function-type>
473 mangleName(FD);
474
475 // Don't mangle in the type if this isn't a decl we should typically mangle.
476 if (!Context.shouldMangleDeclName(FD))
477 return;
478
Nick Lewycky0c2986f2014-04-26 00:14:00 +0000479 if (FD->hasAttr<EnableIfAttr>()) {
480 FunctionTypeDepthState Saved = FunctionTypeDepth.push();
481 Out << "Ua9enable_ifI";
482 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
483 // it here.
484 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
485 E = FD->getAttrs().rend();
486 I != E; ++I) {
487 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
488 if (!EIA)
489 continue;
490 Out << 'X';
491 mangleExpression(EIA->getCond());
492 Out << 'E';
493 }
494 Out << 'E';
495 FunctionTypeDepth.pop(Saved);
496 }
497
Guy Benyei11169dd2012-12-18 14:30:41 +0000498 // Whether the mangling of a function type includes the return type depends on
499 // the context and the nature of the function. The rules for deciding whether
500 // the return type is included are:
501 //
502 // 1. Template functions (names or types) have return types encoded, with
503 // the exceptions listed below.
504 // 2. Function types not appearing as part of a function name mangling,
505 // e.g. parameters, pointer types, etc., have return type encoded, with the
506 // exceptions listed below.
507 // 3. Non-template function names do not have return types encoded.
508 //
509 // The exceptions mentioned in (1) and (2) above, for which the return type is
510 // never included, are
511 // 1. Constructors.
512 // 2. Destructors.
513 // 3. Conversion operator functions, e.g. operator int.
514 bool MangleReturnType = false;
515 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
516 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
517 isa<CXXConversionDecl>(FD)))
518 MangleReturnType = true;
519
520 // Mangle the type of the primary template.
521 FD = PrimaryTemplate->getTemplatedDecl();
522 }
523
524 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
525 MangleReturnType);
526}
527
528static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
529 while (isa<LinkageSpecDecl>(DC)) {
530 DC = getEffectiveParentContext(DC);
531 }
532
533 return DC;
534}
535
536/// isStd - Return whether a given namespace is the 'std' namespace.
537static bool isStd(const NamespaceDecl *NS) {
538 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
539 ->isTranslationUnit())
540 return false;
541
542 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
543 return II && II->isStr("std");
544}
545
546// isStdNamespace - Return whether a given decl context is a toplevel 'std'
547// namespace.
548static bool isStdNamespace(const DeclContext *DC) {
549 if (!DC->isNamespace())
550 return false;
551
552 return isStd(cast<NamespaceDecl>(DC));
553}
554
555static const TemplateDecl *
556isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
557 // Check if we have a function template.
558 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
559 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
560 TemplateArgs = FD->getTemplateSpecializationArgs();
561 return TD;
562 }
563 }
564
565 // Check if we have a class template.
566 if (const ClassTemplateSpecializationDecl *Spec =
567 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
568 TemplateArgs = &Spec->getTemplateArgs();
569 return Spec->getSpecializedTemplate();
570 }
571
Larisse Voufo39a1e502013-08-06 01:03:05 +0000572 // Check if we have a variable template.
573 if (const VarTemplateSpecializationDecl *Spec =
574 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
575 TemplateArgs = &Spec->getTemplateArgs();
576 return Spec->getSpecializedTemplate();
577 }
578
Craig Topper36250ad2014-05-12 05:36:57 +0000579 return nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000580}
581
Guy Benyei11169dd2012-12-18 14:30:41 +0000582void CXXNameMangler::mangleName(const NamedDecl *ND) {
583 // <name> ::= <nested-name>
584 // ::= <unscoped-name>
585 // ::= <unscoped-template-name> <template-args>
586 // ::= <local-name>
587 //
588 const DeclContext *DC = getEffectiveDeclContext(ND);
589
590 // If this is an extern variable declared locally, the relevant DeclContext
591 // is that of the containing namespace, or the translation unit.
592 // FIXME: This is a hack; extern variables declared locally should have
593 // a proper semantic declaration context!
Eli Friedman95f50122013-07-02 17:52:28 +0000594 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000595 while (!DC->isNamespace() && !DC->isTranslationUnit())
596 DC = getEffectiveParentContext(DC);
597 else if (GetLocalClassDecl(ND)) {
598 mangleLocalName(ND);
599 return;
600 }
601
602 DC = IgnoreLinkageSpecDecls(DC);
603
604 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
605 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +0000606 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +0000607 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
608 mangleUnscopedTemplateName(TD);
609 mangleTemplateArgs(*TemplateArgs);
610 return;
611 }
612
613 mangleUnscopedName(ND);
614 return;
615 }
616
Eli Friedman95f50122013-07-02 17:52:28 +0000617 if (isLocalContainerContext(DC)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000618 mangleLocalName(ND);
619 return;
620 }
621
622 mangleNestedName(ND, DC);
623}
624void CXXNameMangler::mangleName(const TemplateDecl *TD,
625 const TemplateArgument *TemplateArgs,
626 unsigned NumTemplateArgs) {
627 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
628
629 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
630 mangleUnscopedTemplateName(TD);
631 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
632 } else {
633 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
634 }
635}
636
637void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
638 // <unscoped-name> ::= <unqualified-name>
639 // ::= St <unqualified-name> # ::std::
640
641 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
642 Out << "St";
643
644 mangleUnqualifiedName(ND);
645}
646
647void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
648 // <unscoped-template-name> ::= <unscoped-name>
649 // ::= <substitution>
650 if (mangleSubstitution(ND))
651 return;
652
653 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +0000654 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND))
Guy Benyei11169dd2012-12-18 14:30:41 +0000655 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +0000656 else
657 mangleUnscopedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +0000658
Guy Benyei11169dd2012-12-18 14:30:41 +0000659 addSubstitution(ND);
660}
661
662void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
663 // <unscoped-template-name> ::= <unscoped-name>
664 // ::= <substitution>
665 if (TemplateDecl *TD = Template.getAsTemplateDecl())
666 return mangleUnscopedTemplateName(TD);
667
668 if (mangleSubstitution(Template))
669 return;
670
671 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
672 assert(Dependent && "Not a dependent template name?");
673 if (const IdentifierInfo *Id = Dependent->getIdentifier())
674 mangleSourceName(Id);
675 else
676 mangleOperatorName(Dependent->getOperator(), UnknownArity);
677
678 addSubstitution(Template);
679}
680
681void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
682 // ABI:
683 // Floating-point literals are encoded using a fixed-length
684 // lowercase hexadecimal string corresponding to the internal
685 // representation (IEEE on Itanium), high-order bytes first,
686 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
687 // on Itanium.
688 // The 'without leading zeroes' thing seems to be an editorial
689 // mistake; see the discussion on cxx-abi-dev beginning on
690 // 2012-01-16.
691
692 // Our requirements here are just barely weird enough to justify
693 // using a custom algorithm instead of post-processing APInt::toString().
694
695 llvm::APInt valueBits = f.bitcastToAPInt();
696 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
697 assert(numCharacters != 0);
698
699 // Allocate a buffer of the right number of characters.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000700 SmallVector<char, 20> buffer;
Guy Benyei11169dd2012-12-18 14:30:41 +0000701 buffer.set_size(numCharacters);
702
703 // Fill the buffer left-to-right.
704 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
705 // The bit-index of the next hex digit.
706 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
707
708 // Project out 4 bits starting at 'digitIndex'.
709 llvm::integerPart hexDigit
710 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
711 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
712 hexDigit &= 0xF;
713
714 // Map that over to a lowercase hex digit.
715 static const char charForHex[16] = {
716 '0', '1', '2', '3', '4', '5', '6', '7',
717 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
718 };
719 buffer[stringIndex] = charForHex[hexDigit];
720 }
721
722 Out.write(buffer.data(), numCharacters);
723}
724
725void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
726 if (Value.isSigned() && Value.isNegative()) {
727 Out << 'n';
728 Value.abs().print(Out, /*signed*/ false);
729 } else {
730 Value.print(Out, /*signed*/ false);
731 }
732}
733
734void CXXNameMangler::mangleNumber(int64_t Number) {
735 // <number> ::= [n] <non-negative decimal integer>
736 if (Number < 0) {
737 Out << 'n';
738 Number = -Number;
739 }
740
741 Out << Number;
742}
743
744void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
745 // <call-offset> ::= h <nv-offset> _
746 // ::= v <v-offset> _
747 // <nv-offset> ::= <offset number> # non-virtual base override
748 // <v-offset> ::= <offset number> _ <virtual offset number>
749 // # virtual base override, with vcall offset
750 if (!Virtual) {
751 Out << 'h';
752 mangleNumber(NonVirtual);
753 Out << '_';
754 return;
755 }
756
757 Out << 'v';
758 mangleNumber(NonVirtual);
759 Out << '_';
760 mangleNumber(Virtual);
761 Out << '_';
762}
763
764void CXXNameMangler::manglePrefix(QualType type) {
David Majnemera88b3592015-02-18 02:28:01 +0000765 if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000766 if (!mangleSubstitution(QualType(TST, 0))) {
767 mangleTemplatePrefix(TST->getTemplateName());
768
769 // FIXME: GCC does not appear to mangle the template arguments when
770 // the template in question is a dependent template name. Should we
771 // emulate that badness?
772 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
773 addSubstitution(QualType(TST, 0));
774 }
David Majnemera88b3592015-02-18 02:28:01 +0000775 } else if (const auto *DTST =
776 type->getAs<DependentTemplateSpecializationType>()) {
777 if (!mangleSubstitution(QualType(DTST, 0))) {
778 TemplateName Template = getASTContext().getDependentTemplateName(
779 DTST->getQualifier(), DTST->getIdentifier());
780 mangleTemplatePrefix(Template);
Guy Benyei11169dd2012-12-18 14:30:41 +0000781
David Majnemera88b3592015-02-18 02:28:01 +0000782 // FIXME: GCC does not appear to mangle the template arguments when
783 // the template in question is a dependent template name. Should we
784 // emulate that badness?
785 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
786 addSubstitution(QualType(DTST, 0));
787 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000788 } else {
789 // We use the QualType mangle type variant here because it handles
790 // substitutions.
791 mangleType(type);
792 }
793}
794
795/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
796///
797/// \param firstQualifierLookup - the entity found by unqualified lookup
798/// for the first name in the qualifier, if this is for a member expression
799/// \param recursive - true if this is being called recursively,
800/// i.e. if there is more prefix "to the right".
801void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
802 NamedDecl *firstQualifierLookup,
803 bool recursive) {
804
805 // x, ::x
806 // <unresolved-name> ::= [gs] <base-unresolved-name>
807
808 // T::x / decltype(p)::x
809 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
810
811 // T::N::x /decltype(p)::N::x
812 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
813 // <base-unresolved-name>
814
815 // A::x, N::y, A<T>::z; "gs" means leading "::"
816 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
817 // <base-unresolved-name>
818
819 switch (qualifier->getKind()) {
820 case NestedNameSpecifier::Global:
821 Out << "gs";
822
823 // We want an 'sr' unless this is the entire NNS.
824 if (recursive)
825 Out << "sr";
826
827 // We never want an 'E' here.
828 return;
829
Nikola Smiljanic67860242014-09-26 00:28:20 +0000830 case NestedNameSpecifier::Super:
831 llvm_unreachable("Can't mangle __super specifier");
832
Guy Benyei11169dd2012-12-18 14:30:41 +0000833 case NestedNameSpecifier::Namespace:
834 if (qualifier->getPrefix())
835 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
836 /*recursive*/ true);
837 else
838 Out << "sr";
839 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
840 break;
841 case NestedNameSpecifier::NamespaceAlias:
842 if (qualifier->getPrefix())
843 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
844 /*recursive*/ true);
845 else
846 Out << "sr";
847 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
848 break;
849
850 case NestedNameSpecifier::TypeSpec:
851 case NestedNameSpecifier::TypeSpecWithTemplate: {
852 const Type *type = qualifier->getAsType();
853
854 // We only want to use an unresolved-type encoding if this is one of:
855 // - a decltype
856 // - a template type parameter
857 // - a template template parameter with arguments
858 // In all of these cases, we should have no prefix.
859 if (qualifier->getPrefix()) {
860 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
861 /*recursive*/ true);
862 } else {
863 // Otherwise, all the cases want this.
864 Out << "sr";
865 }
866
867 // Only certain other types are valid as prefixes; enumerate them.
868 switch (type->getTypeClass()) {
869 case Type::Builtin:
870 case Type::Complex:
Reid Kleckner0503a872013-12-05 01:23:43 +0000871 case Type::Adjusted:
Reid Kleckner8a365022013-06-24 17:51:48 +0000872 case Type::Decayed:
Guy Benyei11169dd2012-12-18 14:30:41 +0000873 case Type::Pointer:
874 case Type::BlockPointer:
875 case Type::LValueReference:
876 case Type::RValueReference:
877 case Type::MemberPointer:
878 case Type::ConstantArray:
879 case Type::IncompleteArray:
880 case Type::VariableArray:
881 case Type::DependentSizedArray:
882 case Type::DependentSizedExtVector:
883 case Type::Vector:
884 case Type::ExtVector:
885 case Type::FunctionProto:
886 case Type::FunctionNoProto:
887 case Type::Enum:
888 case Type::Paren:
889 case Type::Elaborated:
890 case Type::Attributed:
891 case Type::Auto:
892 case Type::PackExpansion:
893 case Type::ObjCObject:
894 case Type::ObjCInterface:
895 case Type::ObjCObjectPointer:
896 case Type::Atomic:
897 llvm_unreachable("type is illegal as a nested name specifier");
898
899 case Type::SubstTemplateTypeParmPack:
900 // FIXME: not clear how to mangle this!
901 // template <class T...> class A {
902 // template <class U...> void foo(decltype(T::foo(U())) x...);
903 // };
904 Out << "_SUBSTPACK_";
905 break;
906
907 // <unresolved-type> ::= <template-param>
908 // ::= <decltype>
909 // ::= <template-template-param> <template-args>
910 // (this last is not official yet)
911 case Type::TypeOfExpr:
912 case Type::TypeOf:
913 case Type::Decltype:
914 case Type::TemplateTypeParm:
915 case Type::UnaryTransform:
916 case Type::SubstTemplateTypeParm:
917 unresolvedType:
918 assert(!qualifier->getPrefix());
919
920 // We only get here recursively if we're followed by identifiers.
921 if (recursive) Out << 'N';
922
923 // This seems to do everything we want. It's not really
924 // sanctioned for a substituted template parameter, though.
925 mangleType(QualType(type, 0));
926
927 // We never want to print 'E' directly after an unresolved-type,
928 // so we return directly.
929 return;
930
931 case Type::Typedef:
932 mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
933 break;
934
935 case Type::UnresolvedUsing:
936 mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
937 ->getIdentifier());
938 break;
939
940 case Type::Record:
941 mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
942 break;
943
944 case Type::TemplateSpecialization: {
945 const TemplateSpecializationType *tst
946 = cast<TemplateSpecializationType>(type);
947 TemplateName name = tst->getTemplateName();
948 switch (name.getKind()) {
949 case TemplateName::Template:
950 case TemplateName::QualifiedTemplate: {
951 TemplateDecl *temp = name.getAsTemplateDecl();
952
953 // If the base is a template template parameter, this is an
954 // unresolved type.
955 assert(temp && "no template for template specialization type");
956 if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
957
958 mangleSourceName(temp->getIdentifier());
959 break;
960 }
961
962 case TemplateName::OverloadedTemplate:
963 case TemplateName::DependentTemplate:
964 llvm_unreachable("invalid base for a template specialization type");
965
966 case TemplateName::SubstTemplateTemplateParm: {
967 SubstTemplateTemplateParmStorage *subst
968 = name.getAsSubstTemplateTemplateParm();
969 mangleExistingSubstitution(subst->getReplacement());
970 break;
971 }
972
973 case TemplateName::SubstTemplateTemplateParmPack: {
974 // FIXME: not clear how to mangle this!
975 // template <template <class U> class T...> class A {
976 // template <class U...> void foo(decltype(T<U>::foo) x...);
977 // };
978 Out << "_SUBSTPACK_";
979 break;
980 }
981 }
982
983 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
984 break;
985 }
986
987 case Type::InjectedClassName:
988 mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
989 ->getIdentifier());
990 break;
991
992 case Type::DependentName:
993 mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
994 break;
995
996 case Type::DependentTemplateSpecialization: {
997 const DependentTemplateSpecializationType *tst
998 = cast<DependentTemplateSpecializationType>(type);
999 mangleSourceName(tst->getIdentifier());
1000 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
1001 break;
1002 }
1003 }
1004 break;
1005 }
1006
1007 case NestedNameSpecifier::Identifier:
1008 // Member expressions can have these without prefixes.
1009 if (qualifier->getPrefix()) {
1010 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
1011 /*recursive*/ true);
1012 } else if (firstQualifierLookup) {
1013
1014 // Try to make a proper qualifier out of the lookup result, and
1015 // then just recurse on that.
1016 NestedNameSpecifier *newQualifier;
1017 if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
1018 QualType type = getASTContext().getTypeDeclType(typeDecl);
1019
1020 // Pretend we had a different nested name specifier.
1021 newQualifier = NestedNameSpecifier::Create(getASTContext(),
Craig Topper36250ad2014-05-12 05:36:57 +00001022 /*prefix*/ nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 /*template*/ false,
1024 type.getTypePtr());
1025 } else if (NamespaceDecl *nspace =
1026 dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
1027 newQualifier = NestedNameSpecifier::Create(getASTContext(),
Craig Topper36250ad2014-05-12 05:36:57 +00001028 /*prefix*/ nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +00001029 nspace);
1030 } else if (NamespaceAliasDecl *alias =
1031 dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
1032 newQualifier = NestedNameSpecifier::Create(getASTContext(),
Craig Topper36250ad2014-05-12 05:36:57 +00001033 /*prefix*/ nullptr,
Guy Benyei11169dd2012-12-18 14:30:41 +00001034 alias);
1035 } else {
1036 // No sensible mangling to do here.
Craig Topper36250ad2014-05-12 05:36:57 +00001037 newQualifier = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001038 }
1039
1040 if (newQualifier)
Craig Topper36250ad2014-05-12 05:36:57 +00001041 return mangleUnresolvedPrefix(newQualifier, /*lookup*/ nullptr,
1042 recursive);
Guy Benyei11169dd2012-12-18 14:30:41 +00001043
1044 } else {
1045 Out << "sr";
1046 }
1047
1048 mangleSourceName(qualifier->getAsIdentifier());
1049 break;
1050 }
1051
1052 // If this was the innermost part of the NNS, and we fell out to
1053 // here, append an 'E'.
1054 if (!recursive)
1055 Out << 'E';
1056}
1057
1058/// Mangle an unresolved-name, which is generally used for names which
1059/// weren't resolved to specific entities.
1060void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
1061 NamedDecl *firstQualifierLookup,
1062 DeclarationName name,
1063 unsigned knownArity) {
1064 if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001065 switch (name.getNameKind()) {
1066 // <base-unresolved-name> ::= <simple-id>
1067 case DeclarationName::Identifier:
David Majnemera88b3592015-02-18 02:28:01 +00001068 mangleSourceName(name.getAsIdentifierInfo());
1069 break;
1070 // <base-unresolved-name> ::= dn <destructor-name>
1071 case DeclarationName::CXXDestructorName:
1072 Out << "dn";
1073 mangleDestructorName(name.getCXXNameType());
David Majnemer1dabfdc2015-02-14 13:23:54 +00001074 break;
1075 // <base-unresolved-name> ::= on <operator-name>
1076 case DeclarationName::CXXConversionFunctionName:
1077 case DeclarationName::CXXLiteralOperatorName:
1078 case DeclarationName::CXXOperatorName:
1079 Out << "on";
David Majnemera88b3592015-02-18 02:28:01 +00001080 mangleOperatorName(name, knownArity);
David Majnemer1dabfdc2015-02-14 13:23:54 +00001081 break;
David Majnemer1dabfdc2015-02-14 13:23:54 +00001082 case DeclarationName::CXXConstructorName:
1083 llvm_unreachable("Can't mangle a constructor name!");
1084 case DeclarationName::CXXUsingDirective:
1085 llvm_unreachable("Can't mangle a using directive name!");
1086 case DeclarationName::ObjCMultiArgSelector:
1087 case DeclarationName::ObjCOneArgSelector:
1088 case DeclarationName::ObjCZeroArgSelector:
1089 llvm_unreachable("Can't mangle Objective-C selector names here!");
1090 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001091}
1092
Guy Benyei11169dd2012-12-18 14:30:41 +00001093void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1094 DeclarationName Name,
1095 unsigned KnownArity) {
David Majnemera88b3592015-02-18 02:28:01 +00001096 unsigned Arity = KnownArity;
Guy Benyei11169dd2012-12-18 14:30:41 +00001097 // <unqualified-name> ::= <operator-name>
1098 // ::= <ctor-dtor-name>
1099 // ::= <source-name>
1100 switch (Name.getNameKind()) {
1101 case DeclarationName::Identifier: {
1102 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1103 // We must avoid conflicts between internally- and externally-
1104 // linked variable and function declaration names in the same TU:
1105 // void test() { extern void foo(); }
1106 // static void foo();
1107 // This naming convention is the same as that followed by GCC,
1108 // though it shouldn't actually matter.
Rafael Espindola3ae00052013-05-13 00:12:11 +00001109 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei11169dd2012-12-18 14:30:41 +00001110 getEffectiveDeclContext(ND)->isFileContext())
1111 Out << 'L';
1112
1113 mangleSourceName(II);
1114 break;
1115 }
1116
1117 // Otherwise, an anonymous entity. We must have a declaration.
1118 assert(ND && "mangling empty name without declaration");
1119
1120 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1121 if (NS->isAnonymousNamespace()) {
1122 // This is how gcc mangles these names.
1123 Out << "12_GLOBAL__N_1";
1124 break;
1125 }
1126 }
1127
1128 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1129 // We must have an anonymous union or struct declaration.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001130 const RecordDecl *RD =
Guy Benyei11169dd2012-12-18 14:30:41 +00001131 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001132
Guy Benyei11169dd2012-12-18 14:30:41 +00001133 // Itanium C++ ABI 5.1.2:
1134 //
1135 // For the purposes of mangling, the name of an anonymous union is
1136 // considered to be the name of the first named data member found by a
1137 // pre-order, depth-first, declaration-order walk of the data members of
1138 // the anonymous union. If there is no such data member (i.e., if all of
1139 // the data members in the union are unnamed), then there is no way for
1140 // a program to refer to the anonymous union, and there is therefore no
1141 // need to mangle its name.
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001142 assert(RD->isAnonymousStructOrUnion()
1143 && "Expected anonymous struct or union!");
1144 const FieldDecl *FD = RD->findFirstNamedDataMember();
Guy Benyei11169dd2012-12-18 14:30:41 +00001145
1146 // It's actually possible for various reasons for us to get here
1147 // with an empty anonymous struct / union. Fortunately, it
1148 // doesn't really matter what name we generate.
1149 if (!FD) break;
1150 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00001151
Guy Benyei11169dd2012-12-18 14:30:41 +00001152 mangleSourceName(FD->getIdentifier());
1153 break;
1154 }
John McCall924046f2013-04-10 06:08:21 +00001155
1156 // Class extensions have no name as a category, and it's possible
1157 // for them to be the semantic parent of certain declarations
1158 // (primarily, tag decls defined within declarations). Such
1159 // declarations will always have internal linkage, so the name
1160 // doesn't really matter, but we shouldn't crash on them. For
1161 // safety, just handle all ObjC containers here.
1162 if (isa<ObjCContainerDecl>(ND))
1163 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001164
1165 // We must have an anonymous struct.
1166 const TagDecl *TD = cast<TagDecl>(ND);
1167 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1168 assert(TD->getDeclContext() == D->getDeclContext() &&
1169 "Typedef should not be in another decl context!");
1170 assert(D->getDeclName().getAsIdentifierInfo() &&
1171 "Typedef was not named!");
1172 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1173 break;
1174 }
1175
1176 // <unnamed-type-name> ::= <closure-type-name>
1177 //
1178 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1179 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1180 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1181 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1182 mangleLambda(Record);
1183 break;
1184 }
1185 }
1186
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001187 if (TD->isExternallyVisible()) {
1188 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001189 Out << "Ut";
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001190 if (UnnamedMangle > 1)
1191 Out << llvm::utostr(UnnamedMangle - 2);
Guy Benyei11169dd2012-12-18 14:30:41 +00001192 Out << '_';
1193 break;
1194 }
1195
1196 // Get a unique id for the anonymous struct.
David Majnemer2206bf52014-03-05 08:57:59 +00001197 unsigned AnonStructId = Context.getAnonymousStructId(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001198
1199 // Mangle it as a source name in the form
1200 // [n] $_<id>
1201 // where n is the length of the string.
1202 SmallString<8> Str;
1203 Str += "$_";
1204 Str += llvm::utostr(AnonStructId);
1205
1206 Out << Str.size();
1207 Out << Str.str();
1208 break;
1209 }
1210
1211 case DeclarationName::ObjCZeroArgSelector:
1212 case DeclarationName::ObjCOneArgSelector:
1213 case DeclarationName::ObjCMultiArgSelector:
1214 llvm_unreachable("Can't mangle Objective-C selector names here!");
1215
1216 case DeclarationName::CXXConstructorName:
1217 if (ND == Structor)
1218 // If the named decl is the C++ constructor we're mangling, use the type
1219 // we were given.
1220 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1221 else
1222 // Otherwise, use the complete constructor name. This is relevant if a
1223 // class with a constructor is declared within a constructor.
1224 mangleCXXCtorType(Ctor_Complete);
1225 break;
1226
1227 case DeclarationName::CXXDestructorName:
1228 if (ND == Structor)
1229 // If the named decl is the C++ destructor we're mangling, use the type we
1230 // were given.
1231 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1232 else
1233 // Otherwise, use the complete destructor name. This is relevant if a
1234 // class with a destructor is declared within a destructor.
1235 mangleCXXDtorType(Dtor_Complete);
1236 break;
1237
David Majnemera88b3592015-02-18 02:28:01 +00001238 case DeclarationName::CXXOperatorName:
1239 if (ND && Arity == UnknownArity) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001240 Arity = cast<FunctionDecl>(ND)->getNumParams();
1241
David Majnemera88b3592015-02-18 02:28:01 +00001242 // If we have a member function, we need to include the 'this' pointer.
1243 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1244 if (!MD->isStatic())
1245 Arity++;
1246 }
1247 // FALLTHROUGH
1248 case DeclarationName::CXXConversionFunctionName:
Guy Benyei11169dd2012-12-18 14:30:41 +00001249 case DeclarationName::CXXLiteralOperatorName:
David Majnemera88b3592015-02-18 02:28:01 +00001250 mangleOperatorName(Name, Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00001251 break;
1252
1253 case DeclarationName::CXXUsingDirective:
1254 llvm_unreachable("Can't mangle a using directive name!");
1255 }
1256}
1257
1258void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1259 // <source-name> ::= <positive length number> <identifier>
1260 // <number> ::= [n] <non-negative decimal integer>
1261 // <identifier> ::= <unqualified source code identifier>
1262 Out << II->getLength() << II->getName();
1263}
1264
1265void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1266 const DeclContext *DC,
1267 bool NoFunction) {
1268 // <nested-name>
1269 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1270 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1271 // <template-args> E
1272
1273 Out << 'N';
1274 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
David Majnemer42350df2013-11-03 23:51:28 +00001275 Qualifiers MethodQuals =
1276 Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1277 // We do not consider restrict a distinguishing attribute for overloading
1278 // purposes so we must not mangle it.
1279 MethodQuals.removeRestrict();
1280 mangleQualifiers(MethodQuals);
Guy Benyei11169dd2012-12-18 14:30:41 +00001281 mangleRefQualifier(Method->getRefQualifier());
1282 }
1283
1284 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001285 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001286 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman86af13f02013-07-05 18:41:30 +00001287 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei11169dd2012-12-18 14:30:41 +00001288 mangleTemplateArgs(*TemplateArgs);
1289 }
1290 else {
1291 manglePrefix(DC, NoFunction);
1292 mangleUnqualifiedName(ND);
1293 }
1294
1295 Out << 'E';
1296}
1297void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1298 const TemplateArgument *TemplateArgs,
1299 unsigned NumTemplateArgs) {
1300 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1301
1302 Out << 'N';
1303
1304 mangleTemplatePrefix(TD);
1305 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1306
1307 Out << 'E';
1308}
1309
Eli Friedman95f50122013-07-02 17:52:28 +00001310void CXXNameMangler::mangleLocalName(const Decl *D) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001311 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1312 // := Z <function encoding> E s [<discriminator>]
1313 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1314 // _ <entity name>
1315 // <discriminator> := _ <non-negative number>
Eli Friedman95f50122013-07-02 17:52:28 +00001316 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001317 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman95f50122013-07-02 17:52:28 +00001318 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei11169dd2012-12-18 14:30:41 +00001319
1320 Out << 'Z';
1321
Eli Friedman92821742013-07-02 02:01:18 +00001322 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1323 mangleObjCMethodName(MD);
1324 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
Eli Friedman95f50122013-07-02 17:52:28 +00001325 mangleBlockForPrefix(BD);
Eli Friedman92821742013-07-02 02:01:18 +00001326 else
1327 mangleFunctionEncoding(cast<FunctionDecl>(DC));
Guy Benyei11169dd2012-12-18 14:30:41 +00001328
Eli Friedman92821742013-07-02 02:01:18 +00001329 Out << 'E';
1330
1331 if (RD) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001332 // The parameter number is omitted for the last parameter, 0 for the
1333 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1334 // <entity name> will of course contain a <closure-type-name>: Its
1335 // numbering will be local to the particular argument in which it appears
1336 // -- other default arguments do not affect its encoding.
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001337 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1338 if (CXXRD->isLambda()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001339 if (const ParmVarDecl *Parm
Eli Friedmaneecc09a2013-07-05 20:27:40 +00001340 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001341 if (const FunctionDecl *Func
1342 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1343 Out << 'd';
1344 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1345 if (Num > 1)
1346 mangleNumber(Num - 2);
1347 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001348 }
1349 }
1350 }
1351
1352 // Mangle the name relative to the closest enclosing function.
Eli Friedman95f50122013-07-02 17:52:28 +00001353 // equality ok because RD derived from ND above
1354 if (D == RD) {
1355 mangleUnqualifiedName(RD);
1356 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1357 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1358 mangleUnqualifiedBlock(BD);
1359 } else {
1360 const NamedDecl *ND = cast<NamedDecl>(D);
Eli Friedman92821742013-07-02 02:01:18 +00001361 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
Eli Friedman95f50122013-07-02 17:52:28 +00001362 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001363 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1364 // Mangle a block in a default parameter; see above explanation for
1365 // lambdas.
1366 if (const ParmVarDecl *Parm
1367 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1368 if (const FunctionDecl *Func
1369 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1370 Out << 'd';
1371 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1372 if (Num > 1)
1373 mangleNumber(Num - 2);
1374 Out << '_';
1375 }
1376 }
1377
1378 mangleUnqualifiedBlock(BD);
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001379 } else {
Eli Friedman0cd23352013-07-10 01:33:19 +00001380 mangleUnqualifiedName(cast<NamedDecl>(D));
Guy Benyei11169dd2012-12-18 14:30:41 +00001381 }
Eli Friedman0cd23352013-07-10 01:33:19 +00001382
Eli Friedman3b7d46c2013-07-10 00:30:46 +00001383 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1384 unsigned disc;
1385 if (Context.getNextDiscriminator(ND, disc)) {
1386 if (disc < 10)
1387 Out << '_' << disc;
1388 else
1389 Out << "__" << disc << '_';
1390 }
1391 }
Eli Friedman95f50122013-07-02 17:52:28 +00001392}
1393
1394void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1395 if (GetLocalClassDecl(Block)) {
1396 mangleLocalName(Block);
1397 return;
1398 }
1399 const DeclContext *DC = getEffectiveDeclContext(Block);
1400 if (isLocalContainerContext(DC)) {
1401 mangleLocalName(Block);
1402 return;
1403 }
1404 manglePrefix(getEffectiveDeclContext(Block));
1405 mangleUnqualifiedBlock(Block);
1406}
1407
1408void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1409 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1410 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1411 Context->getDeclContext()->isRecord()) {
1412 if (const IdentifierInfo *Name
1413 = cast<NamedDecl>(Context)->getIdentifier()) {
1414 mangleSourceName(Name);
1415 Out << 'M';
1416 }
1417 }
1418 }
1419
1420 // If we have a block mangling number, use it.
1421 unsigned Number = Block->getBlockManglingNumber();
1422 // Otherwise, just make up a number. It doesn't matter what it is because
1423 // the symbol in question isn't externally visible.
1424 if (!Number)
1425 Number = Context.getBlockId(Block, false);
1426 Out << "Ub";
David Majnemer11d24272014-08-04 06:16:50 +00001427 if (Number > 0)
1428 Out << Number - 1;
Eli Friedman95f50122013-07-02 17:52:28 +00001429 Out << '_';
Guy Benyei11169dd2012-12-18 14:30:41 +00001430}
1431
1432void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1433 // If the context of a closure type is an initializer for a class member
1434 // (static or nonstatic), it is encoded in a qualified name with a final
1435 // <prefix> of the form:
1436 //
1437 // <data-member-prefix> := <member source-name> M
1438 //
1439 // Technically, the data-member-prefix is part of the <prefix>. However,
1440 // since a closure type will always be mangled with a prefix, it's easier
1441 // to emit that last part of the prefix here.
1442 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1443 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1444 Context->getDeclContext()->isRecord()) {
1445 if (const IdentifierInfo *Name
1446 = cast<NamedDecl>(Context)->getIdentifier()) {
1447 mangleSourceName(Name);
1448 Out << 'M';
1449 }
1450 }
1451 }
1452
1453 Out << "Ul";
1454 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1455 getAs<FunctionProtoType>();
1456 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1457 Out << "E";
1458
1459 // The number is omitted for the first closure type with a given
1460 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1461 // (in lexical order) with that same <lambda-sig> and context.
1462 //
1463 // The AST keeps track of the number for us.
1464 unsigned Number = Lambda->getLambdaManglingNumber();
1465 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1466 if (Number > 1)
1467 mangleNumber(Number - 2);
1468 Out << '_';
1469}
1470
1471void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1472 switch (qualifier->getKind()) {
1473 case NestedNameSpecifier::Global:
1474 // nothing
1475 return;
1476
Nikola Smiljanic67860242014-09-26 00:28:20 +00001477 case NestedNameSpecifier::Super:
1478 llvm_unreachable("Can't mangle __super specifier");
1479
Guy Benyei11169dd2012-12-18 14:30:41 +00001480 case NestedNameSpecifier::Namespace:
1481 mangleName(qualifier->getAsNamespace());
1482 return;
1483
1484 case NestedNameSpecifier::NamespaceAlias:
1485 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1486 return;
1487
1488 case NestedNameSpecifier::TypeSpec:
1489 case NestedNameSpecifier::TypeSpecWithTemplate:
1490 manglePrefix(QualType(qualifier->getAsType(), 0));
1491 return;
1492
1493 case NestedNameSpecifier::Identifier:
1494 // Member expressions can have these without prefixes, but that
1495 // should end up in mangleUnresolvedPrefix instead.
1496 assert(qualifier->getPrefix());
1497 manglePrefix(qualifier->getPrefix());
1498
1499 mangleSourceName(qualifier->getAsIdentifier());
1500 return;
1501 }
1502
1503 llvm_unreachable("unexpected nested name specifier");
1504}
1505
1506void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1507 // <prefix> ::= <prefix> <unqualified-name>
1508 // ::= <template-prefix> <template-args>
1509 // ::= <template-param>
1510 // ::= # empty
1511 // ::= <substitution>
1512
1513 DC = IgnoreLinkageSpecDecls(DC);
1514
1515 if (DC->isTranslationUnit())
1516 return;
1517
Eli Friedman95f50122013-07-02 17:52:28 +00001518 if (NoFunction && isLocalContainerContext(DC))
1519 return;
Eli Friedman7e346a82013-07-01 20:22:57 +00001520
Eli Friedman95f50122013-07-02 17:52:28 +00001521 assert(!isLocalContainerContext(DC));
1522
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 const NamedDecl *ND = cast<NamedDecl>(DC);
1524 if (mangleSubstitution(ND))
1525 return;
1526
1527 // Check if we have a template.
Craig Topper36250ad2014-05-12 05:36:57 +00001528 const TemplateArgumentList *TemplateArgs = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001529 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1530 mangleTemplatePrefix(TD);
1531 mangleTemplateArgs(*TemplateArgs);
Eli Friedman95f50122013-07-02 17:52:28 +00001532 } else {
Guy Benyei11169dd2012-12-18 14:30:41 +00001533 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1534 mangleUnqualifiedName(ND);
1535 }
1536
1537 addSubstitution(ND);
1538}
1539
1540void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1541 // <template-prefix> ::= <prefix> <template unqualified-name>
1542 // ::= <template-param>
1543 // ::= <substitution>
1544 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1545 return mangleTemplatePrefix(TD);
1546
1547 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1548 manglePrefix(Qualified->getQualifier());
1549
1550 if (OverloadedTemplateStorage *Overloaded
1551 = Template.getAsOverloadedTemplate()) {
Craig Topper36250ad2014-05-12 05:36:57 +00001552 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00001553 UnknownArity);
1554 return;
1555 }
1556
1557 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1558 assert(Dependent && "Unknown template name kind?");
David Majnemer1dabfdc2015-02-14 13:23:54 +00001559 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1560 manglePrefix(Qualifier);
Guy Benyei11169dd2012-12-18 14:30:41 +00001561 mangleUnscopedTemplateName(Template);
1562}
1563
Eli Friedman86af13f02013-07-05 18:41:30 +00001564void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1565 bool NoFunction) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001566 // <template-prefix> ::= <prefix> <template unqualified-name>
1567 // ::= <template-param>
1568 // ::= <substitution>
1569 // <template-template-param> ::= <template-param>
1570 // <substitution>
1571
1572 if (mangleSubstitution(ND))
1573 return;
1574
1575 // <template-template-param> ::= <template-param>
David Majnemer90a3b192014-10-24 20:22:57 +00001576 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001577 mangleTemplateParameter(TTP->getIndex());
David Majnemer90a3b192014-10-24 20:22:57 +00001578 } else {
1579 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1580 mangleUnqualifiedName(ND->getTemplatedDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001581 }
1582
Guy Benyei11169dd2012-12-18 14:30:41 +00001583 addSubstitution(ND);
1584}
1585
1586/// Mangles a template name under the production <type>. Required for
1587/// template template arguments.
1588/// <type> ::= <class-enum-type>
1589/// ::= <template-param>
1590/// ::= <substitution>
1591void CXXNameMangler::mangleType(TemplateName TN) {
1592 if (mangleSubstitution(TN))
1593 return;
Craig Topper36250ad2014-05-12 05:36:57 +00001594
1595 TemplateDecl *TD = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00001596
1597 switch (TN.getKind()) {
1598 case TemplateName::QualifiedTemplate:
1599 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1600 goto HaveDecl;
1601
1602 case TemplateName::Template:
1603 TD = TN.getAsTemplateDecl();
1604 goto HaveDecl;
1605
1606 HaveDecl:
1607 if (isa<TemplateTemplateParmDecl>(TD))
1608 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1609 else
1610 mangleName(TD);
1611 break;
1612
1613 case TemplateName::OverloadedTemplate:
1614 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1615
1616 case TemplateName::DependentTemplate: {
1617 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1618 assert(Dependent->isIdentifier());
1619
1620 // <class-enum-type> ::= <name>
1621 // <name> ::= <nested-name>
Craig Topper36250ad2014-05-12 05:36:57 +00001622 mangleUnresolvedPrefix(Dependent->getQualifier(), nullptr);
Guy Benyei11169dd2012-12-18 14:30:41 +00001623 mangleSourceName(Dependent->getIdentifier());
1624 break;
1625 }
1626
1627 case TemplateName::SubstTemplateTemplateParm: {
1628 // Substituted template parameters are mangled as the substituted
1629 // template. This will check for the substitution twice, which is
1630 // fine, but we have to return early so that we don't try to *add*
1631 // the substitution twice.
1632 SubstTemplateTemplateParmStorage *subst
1633 = TN.getAsSubstTemplateTemplateParm();
1634 mangleType(subst->getReplacement());
1635 return;
1636 }
1637
1638 case TemplateName::SubstTemplateTemplateParmPack: {
1639 // FIXME: not clear how to mangle this!
1640 // template <template <class> class T...> class A {
1641 // template <template <class> class U...> void foo(B<T,U> x...);
1642 // };
1643 Out << "_SUBSTPACK_";
1644 break;
1645 }
1646 }
1647
1648 addSubstitution(TN);
1649}
1650
David Majnemera88b3592015-02-18 02:28:01 +00001651void CXXNameMangler::mangleDestructorName(QualType DestroyedType) {
1652 // <destructor-name> ::= <unresolved-type>
1653 // ::= <simple-id>
1654 if (const auto *TST = DestroyedType->getAs<TemplateSpecializationType>()) {
1655 TemplateName TN = TST->getTemplateName();
1656 const auto *TD = TN.getAsTemplateDecl();
1657 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD)) {
1658 // Proposed to cxx-abi-dev on 2015-02-17.
1659 mangleTemplateParameter(TTP->getIndex());
1660 } else {
1661 mangleUnscopedName(TD->getTemplatedDecl());
1662 }
1663 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1664 } else if (const auto *DTST =
1665 DestroyedType->getAs<DependentTemplateSpecializationType>()) {
1666 const IdentifierInfo *II = DTST->getIdentifier();
1667 mangleSourceName(II);
1668 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1669 } else {
1670 // We use the QualType mangle type variant here because it handles
1671 // substitutions.
1672 mangleType(DestroyedType);
1673 }
1674}
1675
1676void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1677 switch (Name.getNameKind()) {
1678 case DeclarationName::CXXConstructorName:
1679 case DeclarationName::CXXDestructorName:
1680 case DeclarationName::CXXUsingDirective:
1681 case DeclarationName::Identifier:
1682 case DeclarationName::ObjCMultiArgSelector:
1683 case DeclarationName::ObjCOneArgSelector:
1684 case DeclarationName::ObjCZeroArgSelector:
1685 llvm_unreachable("Not an operator name");
1686
1687 case DeclarationName::CXXConversionFunctionName:
1688 // <operator-name> ::= cv <type> # (cast)
1689 Out << "cv";
1690 mangleType(Name.getCXXNameType());
1691 break;
1692
1693 case DeclarationName::CXXLiteralOperatorName:
1694 Out << "li";
1695 mangleSourceName(Name.getCXXLiteralIdentifier());
1696 return;
1697
1698 case DeclarationName::CXXOperatorName:
1699 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1700 break;
1701 }
1702}
1703
1704
1705
Guy Benyei11169dd2012-12-18 14:30:41 +00001706void
1707CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1708 switch (OO) {
1709 // <operator-name> ::= nw # new
1710 case OO_New: Out << "nw"; break;
1711 // ::= na # new[]
1712 case OO_Array_New: Out << "na"; break;
1713 // ::= dl # delete
1714 case OO_Delete: Out << "dl"; break;
1715 // ::= da # delete[]
1716 case OO_Array_Delete: Out << "da"; break;
1717 // ::= ps # + (unary)
1718 // ::= pl # + (binary or unknown)
1719 case OO_Plus:
1720 Out << (Arity == 1? "ps" : "pl"); break;
1721 // ::= ng # - (unary)
1722 // ::= mi # - (binary or unknown)
1723 case OO_Minus:
1724 Out << (Arity == 1? "ng" : "mi"); break;
1725 // ::= ad # & (unary)
1726 // ::= an # & (binary or unknown)
1727 case OO_Amp:
1728 Out << (Arity == 1? "ad" : "an"); break;
1729 // ::= de # * (unary)
1730 // ::= ml # * (binary or unknown)
1731 case OO_Star:
1732 // Use binary when unknown.
1733 Out << (Arity == 1? "de" : "ml"); break;
1734 // ::= co # ~
1735 case OO_Tilde: Out << "co"; break;
1736 // ::= dv # /
1737 case OO_Slash: Out << "dv"; break;
1738 // ::= rm # %
1739 case OO_Percent: Out << "rm"; break;
1740 // ::= or # |
1741 case OO_Pipe: Out << "or"; break;
1742 // ::= eo # ^
1743 case OO_Caret: Out << "eo"; break;
1744 // ::= aS # =
1745 case OO_Equal: Out << "aS"; break;
1746 // ::= pL # +=
1747 case OO_PlusEqual: Out << "pL"; break;
1748 // ::= mI # -=
1749 case OO_MinusEqual: Out << "mI"; break;
1750 // ::= mL # *=
1751 case OO_StarEqual: Out << "mL"; break;
1752 // ::= dV # /=
1753 case OO_SlashEqual: Out << "dV"; break;
1754 // ::= rM # %=
1755 case OO_PercentEqual: Out << "rM"; break;
1756 // ::= aN # &=
1757 case OO_AmpEqual: Out << "aN"; break;
1758 // ::= oR # |=
1759 case OO_PipeEqual: Out << "oR"; break;
1760 // ::= eO # ^=
1761 case OO_CaretEqual: Out << "eO"; break;
1762 // ::= ls # <<
1763 case OO_LessLess: Out << "ls"; break;
1764 // ::= rs # >>
1765 case OO_GreaterGreater: Out << "rs"; break;
1766 // ::= lS # <<=
1767 case OO_LessLessEqual: Out << "lS"; break;
1768 // ::= rS # >>=
1769 case OO_GreaterGreaterEqual: Out << "rS"; break;
1770 // ::= eq # ==
1771 case OO_EqualEqual: Out << "eq"; break;
1772 // ::= ne # !=
1773 case OO_ExclaimEqual: Out << "ne"; break;
1774 // ::= lt # <
1775 case OO_Less: Out << "lt"; break;
1776 // ::= gt # >
1777 case OO_Greater: Out << "gt"; break;
1778 // ::= le # <=
1779 case OO_LessEqual: Out << "le"; break;
1780 // ::= ge # >=
1781 case OO_GreaterEqual: Out << "ge"; break;
1782 // ::= nt # !
1783 case OO_Exclaim: Out << "nt"; break;
1784 // ::= aa # &&
1785 case OO_AmpAmp: Out << "aa"; break;
1786 // ::= oo # ||
1787 case OO_PipePipe: Out << "oo"; break;
1788 // ::= pp # ++
1789 case OO_PlusPlus: Out << "pp"; break;
1790 // ::= mm # --
1791 case OO_MinusMinus: Out << "mm"; break;
1792 // ::= cm # ,
1793 case OO_Comma: Out << "cm"; break;
1794 // ::= pm # ->*
1795 case OO_ArrowStar: Out << "pm"; break;
1796 // ::= pt # ->
1797 case OO_Arrow: Out << "pt"; break;
1798 // ::= cl # ()
1799 case OO_Call: Out << "cl"; break;
1800 // ::= ix # []
1801 case OO_Subscript: Out << "ix"; break;
1802
1803 // ::= qu # ?
1804 // The conditional operator can't be overloaded, but we still handle it when
1805 // mangling expressions.
1806 case OO_Conditional: Out << "qu"; break;
1807
1808 case OO_None:
1809 case NUM_OVERLOADED_OPERATORS:
1810 llvm_unreachable("Not an overloaded operator");
1811 }
1812}
1813
1814void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1815 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1816 if (Quals.hasRestrict())
1817 Out << 'r';
1818 if (Quals.hasVolatile())
1819 Out << 'V';
1820 if (Quals.hasConst())
1821 Out << 'K';
1822
1823 if (Quals.hasAddressSpace()) {
David Tweed31d09b02013-09-13 12:04:22 +00001824 // Address space extension:
Guy Benyei11169dd2012-12-18 14:30:41 +00001825 //
David Tweed31d09b02013-09-13 12:04:22 +00001826 // <type> ::= U <target-addrspace>
1827 // <type> ::= U <OpenCL-addrspace>
1828 // <type> ::= U <CUDA-addrspace>
1829
Guy Benyei11169dd2012-12-18 14:30:41 +00001830 SmallString<64> ASString;
David Tweed31d09b02013-09-13 12:04:22 +00001831 unsigned AS = Quals.getAddressSpace();
David Tweed31d09b02013-09-13 12:04:22 +00001832
1833 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
1834 // <target-addrspace> ::= "AS" <address-space-number>
1835 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
1836 ASString = "AS" + llvm::utostr_32(TargetAS);
1837 } else {
1838 switch (AS) {
1839 default: llvm_unreachable("Not a language specific address space");
1840 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
1841 case LangAS::opencl_global: ASString = "CLglobal"; break;
1842 case LangAS::opencl_local: ASString = "CLlocal"; break;
1843 case LangAS::opencl_constant: ASString = "CLconstant"; break;
1844 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
1845 case LangAS::cuda_device: ASString = "CUdevice"; break;
1846 case LangAS::cuda_constant: ASString = "CUconstant"; break;
1847 case LangAS::cuda_shared: ASString = "CUshared"; break;
1848 }
1849 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001850 Out << 'U' << ASString.size() << ASString;
1851 }
1852
1853 StringRef LifetimeName;
1854 switch (Quals.getObjCLifetime()) {
1855 // Objective-C ARC Extension:
1856 //
1857 // <type> ::= U "__strong"
1858 // <type> ::= U "__weak"
1859 // <type> ::= U "__autoreleasing"
1860 case Qualifiers::OCL_None:
1861 break;
1862
1863 case Qualifiers::OCL_Weak:
1864 LifetimeName = "__weak";
1865 break;
1866
1867 case Qualifiers::OCL_Strong:
1868 LifetimeName = "__strong";
1869 break;
1870
1871 case Qualifiers::OCL_Autoreleasing:
1872 LifetimeName = "__autoreleasing";
1873 break;
1874
1875 case Qualifiers::OCL_ExplicitNone:
1876 // The __unsafe_unretained qualifier is *not* mangled, so that
1877 // __unsafe_unretained types in ARC produce the same manglings as the
1878 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1879 // better ABI compatibility.
1880 //
1881 // It's safe to do this because unqualified 'id' won't show up
1882 // in any type signatures that need to be mangled.
1883 break;
1884 }
1885 if (!LifetimeName.empty())
1886 Out << 'U' << LifetimeName.size() << LifetimeName;
1887}
1888
1889void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1890 // <ref-qualifier> ::= R # lvalue reference
1891 // ::= O # rvalue-reference
Guy Benyei11169dd2012-12-18 14:30:41 +00001892 switch (RefQualifier) {
1893 case RQ_None:
1894 break;
1895
1896 case RQ_LValue:
1897 Out << 'R';
1898 break;
1899
1900 case RQ_RValue:
1901 Out << 'O';
1902 break;
1903 }
1904}
1905
1906void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1907 Context.mangleObjCMethodName(MD, Out);
1908}
1909
David Majnemereea02ee2014-11-28 22:22:46 +00001910static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
1911 if (Quals)
1912 return true;
1913 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
1914 return true;
1915 if (Ty->isOpenCLSpecificType())
1916 return true;
1917 if (Ty->isBuiltinType())
1918 return false;
1919
1920 return true;
1921}
1922
Guy Benyei11169dd2012-12-18 14:30:41 +00001923void CXXNameMangler::mangleType(QualType T) {
1924 // If our type is instantiation-dependent but not dependent, we mangle
1925 // it as it was written in the source, removing any top-level sugar.
1926 // Otherwise, use the canonical type.
1927 //
1928 // FIXME: This is an approximation of the instantiation-dependent name
1929 // mangling rules, since we should really be using the type as written and
1930 // augmented via semantic analysis (i.e., with implicit conversions and
1931 // default template arguments) for any instantiation-dependent type.
1932 // Unfortunately, that requires several changes to our AST:
1933 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1934 // uniqued, so that we can handle substitutions properly
1935 // - Default template arguments will need to be represented in the
1936 // TemplateSpecializationType, since they need to be mangled even though
1937 // they aren't written.
1938 // - Conversions on non-type template arguments need to be expressed, since
1939 // they can affect the mangling of sizeof/alignof.
1940 if (!T->isInstantiationDependentType() || T->isDependentType())
1941 T = T.getCanonicalType();
1942 else {
1943 // Desugar any types that are purely sugar.
1944 do {
1945 // Don't desugar through template specialization types that aren't
1946 // type aliases. We need to mangle the template arguments as written.
1947 if (const TemplateSpecializationType *TST
1948 = dyn_cast<TemplateSpecializationType>(T))
1949 if (!TST->isTypeAlias())
1950 break;
1951
1952 QualType Desugared
1953 = T.getSingleStepDesugaredType(Context.getASTContext());
1954 if (Desugared == T)
1955 break;
1956
1957 T = Desugared;
1958 } while (true);
1959 }
1960 SplitQualType split = T.split();
1961 Qualifiers quals = split.Quals;
1962 const Type *ty = split.Ty;
1963
David Majnemereea02ee2014-11-28 22:22:46 +00001964 bool isSubstitutable = isTypeSubstitutable(quals, ty);
Guy Benyei11169dd2012-12-18 14:30:41 +00001965 if (isSubstitutable && mangleSubstitution(T))
1966 return;
1967
1968 // If we're mangling a qualified array type, push the qualifiers to
1969 // the element type.
1970 if (quals && isa<ArrayType>(T)) {
1971 ty = Context.getASTContext().getAsArrayType(T);
1972 quals = Qualifiers();
1973
1974 // Note that we don't update T: we want to add the
1975 // substitution at the original type.
1976 }
1977
1978 if (quals) {
1979 mangleQualifiers(quals);
1980 // Recurse: even if the qualified type isn't yet substitutable,
1981 // the unqualified type might be.
1982 mangleType(QualType(ty, 0));
1983 } else {
1984 switch (ty->getTypeClass()) {
1985#define ABSTRACT_TYPE(CLASS, PARENT)
1986#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1987 case Type::CLASS: \
1988 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1989 return;
1990#define TYPE(CLASS, PARENT) \
1991 case Type::CLASS: \
1992 mangleType(static_cast<const CLASS##Type*>(ty)); \
1993 break;
1994#include "clang/AST/TypeNodes.def"
1995 }
1996 }
1997
1998 // Add the substitution.
1999 if (isSubstitutable)
2000 addSubstitution(T);
2001}
2002
2003void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2004 if (!mangleStandardSubstitution(ND))
2005 mangleName(ND);
2006}
2007
2008void CXXNameMangler::mangleType(const BuiltinType *T) {
2009 // <type> ::= <builtin-type>
2010 // <builtin-type> ::= v # void
2011 // ::= w # wchar_t
2012 // ::= b # bool
2013 // ::= c # char
2014 // ::= a # signed char
2015 // ::= h # unsigned char
2016 // ::= s # short
2017 // ::= t # unsigned short
2018 // ::= i # int
2019 // ::= j # unsigned int
2020 // ::= l # long
2021 // ::= m # unsigned long
2022 // ::= x # long long, __int64
2023 // ::= y # unsigned long long, __int64
2024 // ::= n # __int128
Ekaterina Romanova91b655b2013-11-21 22:25:24 +00002025 // ::= o # unsigned __int128
Guy Benyei11169dd2012-12-18 14:30:41 +00002026 // ::= f # float
2027 // ::= d # double
2028 // ::= e # long double, __float80
2029 // UNSUPPORTED: ::= g # __float128
2030 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
2031 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
2032 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
2033 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
2034 // ::= Di # char32_t
2035 // ::= Ds # char16_t
2036 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2037 // ::= u <source-name> # vendor extended type
2038 switch (T->getKind()) {
2039 case BuiltinType::Void: Out << 'v'; break;
2040 case BuiltinType::Bool: Out << 'b'; break;
2041 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
2042 case BuiltinType::UChar: Out << 'h'; break;
2043 case BuiltinType::UShort: Out << 't'; break;
2044 case BuiltinType::UInt: Out << 'j'; break;
2045 case BuiltinType::ULong: Out << 'm'; break;
2046 case BuiltinType::ULongLong: Out << 'y'; break;
2047 case BuiltinType::UInt128: Out << 'o'; break;
2048 case BuiltinType::SChar: Out << 'a'; break;
2049 case BuiltinType::WChar_S:
2050 case BuiltinType::WChar_U: Out << 'w'; break;
2051 case BuiltinType::Char16: Out << "Ds"; break;
2052 case BuiltinType::Char32: Out << "Di"; break;
2053 case BuiltinType::Short: Out << 's'; break;
2054 case BuiltinType::Int: Out << 'i'; break;
2055 case BuiltinType::Long: Out << 'l'; break;
2056 case BuiltinType::LongLong: Out << 'x'; break;
2057 case BuiltinType::Int128: Out << 'n'; break;
2058 case BuiltinType::Half: Out << "Dh"; break;
2059 case BuiltinType::Float: Out << 'f'; break;
2060 case BuiltinType::Double: Out << 'd'; break;
2061 case BuiltinType::LongDouble: Out << 'e'; break;
2062 case BuiltinType::NullPtr: Out << "Dn"; break;
2063
2064#define BUILTIN_TYPE(Id, SingletonId)
2065#define PLACEHOLDER_TYPE(Id, SingletonId) \
2066 case BuiltinType::Id:
2067#include "clang/AST/BuiltinTypes.def"
2068 case BuiltinType::Dependent:
2069 llvm_unreachable("mangling a placeholder type");
2070 case BuiltinType::ObjCId: Out << "11objc_object"; break;
2071 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
2072 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00002073 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
2074 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
2075 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
2076 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
2077 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
2078 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
Guy Benyei61054192013-02-07 10:55:47 +00002079 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00002080 case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002081 }
2082}
2083
2084// <type> ::= <function-type>
2085// <function-type> ::= [<CV-qualifiers>] F [Y]
2086// <bare-function-type> [<ref-qualifier>] E
Guy Benyei11169dd2012-12-18 14:30:41 +00002087void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2088 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
2089 // e.g. "const" in "int (A::*)() const".
2090 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2091
2092 Out << 'F';
2093
2094 // FIXME: We don't have enough information in the AST to produce the 'Y'
2095 // encoding for extern "C" function types.
2096 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2097
2098 // Mangle the ref-qualifier, if present.
2099 mangleRefQualifier(T->getRefQualifier());
2100
2101 Out << 'E';
2102}
2103void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2104 llvm_unreachable("Can't mangle K&R function prototypes");
2105}
2106void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
2107 bool MangleReturnType) {
2108 // We should never be mangling something without a prototype.
2109 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2110
2111 // Record that we're in a function type. See mangleFunctionParam
2112 // for details on what we're trying to achieve here.
2113 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2114
2115 // <bare-function-type> ::= <signature type>+
2116 if (MangleReturnType) {
2117 FunctionTypeDepth.enterResultType();
Alp Toker314cc812014-01-25 16:55:45 +00002118 mangleType(Proto->getReturnType());
Guy Benyei11169dd2012-12-18 14:30:41 +00002119 FunctionTypeDepth.leaveResultType();
2120 }
2121
Alp Toker9cacbab2014-01-20 20:26:09 +00002122 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002123 // <builtin-type> ::= v # void
2124 Out << 'v';
2125
2126 FunctionTypeDepth.pop(saved);
2127 return;
2128 }
2129
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00002130 for (const auto &Arg : Proto->param_types())
2131 mangleType(Context.getASTContext().getSignatureParameterType(Arg));
Guy Benyei11169dd2012-12-18 14:30:41 +00002132
2133 FunctionTypeDepth.pop(saved);
2134
2135 // <builtin-type> ::= z # ellipsis
2136 if (Proto->isVariadic())
2137 Out << 'z';
2138}
2139
2140// <type> ::= <class-enum-type>
2141// <class-enum-type> ::= <name>
2142void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2143 mangleName(T->getDecl());
2144}
2145
2146// <type> ::= <class-enum-type>
2147// <class-enum-type> ::= <name>
2148void CXXNameMangler::mangleType(const EnumType *T) {
2149 mangleType(static_cast<const TagType*>(T));
2150}
2151void CXXNameMangler::mangleType(const RecordType *T) {
2152 mangleType(static_cast<const TagType*>(T));
2153}
2154void CXXNameMangler::mangleType(const TagType *T) {
2155 mangleName(T->getDecl());
2156}
2157
2158// <type> ::= <array-type>
2159// <array-type> ::= A <positive dimension number> _ <element type>
2160// ::= A [<dimension expression>] _ <element type>
2161void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2162 Out << 'A' << T->getSize() << '_';
2163 mangleType(T->getElementType());
2164}
2165void CXXNameMangler::mangleType(const VariableArrayType *T) {
2166 Out << 'A';
2167 // decayed vla types (size 0) will just be skipped.
2168 if (T->getSizeExpr())
2169 mangleExpression(T->getSizeExpr());
2170 Out << '_';
2171 mangleType(T->getElementType());
2172}
2173void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2174 Out << 'A';
2175 mangleExpression(T->getSizeExpr());
2176 Out << '_';
2177 mangleType(T->getElementType());
2178}
2179void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2180 Out << "A_";
2181 mangleType(T->getElementType());
2182}
2183
2184// <type> ::= <pointer-to-member-type>
2185// <pointer-to-member-type> ::= M <class type> <member type>
2186void CXXNameMangler::mangleType(const MemberPointerType *T) {
2187 Out << 'M';
2188 mangleType(QualType(T->getClass(), 0));
2189 QualType PointeeType = T->getPointeeType();
2190 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2191 mangleType(FPT);
2192
2193 // Itanium C++ ABI 5.1.8:
2194 //
2195 // The type of a non-static member function is considered to be different,
2196 // for the purposes of substitution, from the type of a namespace-scope or
2197 // static member function whose type appears similar. The types of two
2198 // non-static member functions are considered to be different, for the
2199 // purposes of substitution, if the functions are members of different
2200 // classes. In other words, for the purposes of substitution, the class of
2201 // which the function is a member is considered part of the type of
2202 // function.
2203
2204 // Given that we already substitute member function pointers as a
2205 // whole, the net effect of this rule is just to unconditionally
2206 // suppress substitution on the function type in a member pointer.
2207 // We increment the SeqID here to emulate adding an entry to the
2208 // substitution table.
2209 ++SeqID;
2210 } else
2211 mangleType(PointeeType);
2212}
2213
2214// <type> ::= <template-param>
2215void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2216 mangleTemplateParameter(T->getIndex());
2217}
2218
2219// <type> ::= <template-param>
2220void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2221 // FIXME: not clear how to mangle this!
2222 // template <class T...> class A {
2223 // template <class U...> void foo(T(*)(U) x...);
2224 // };
2225 Out << "_SUBSTPACK_";
2226}
2227
2228// <type> ::= P <type> # pointer-to
2229void CXXNameMangler::mangleType(const PointerType *T) {
2230 Out << 'P';
2231 mangleType(T->getPointeeType());
2232}
2233void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2234 Out << 'P';
2235 mangleType(T->getPointeeType());
2236}
2237
2238// <type> ::= R <type> # reference-to
2239void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2240 Out << 'R';
2241 mangleType(T->getPointeeType());
2242}
2243
2244// <type> ::= O <type> # rvalue reference-to (C++0x)
2245void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2246 Out << 'O';
2247 mangleType(T->getPointeeType());
2248}
2249
2250// <type> ::= C <type> # complex pair (C 2000)
2251void CXXNameMangler::mangleType(const ComplexType *T) {
2252 Out << 'C';
2253 mangleType(T->getElementType());
2254}
2255
2256// ARM's ABI for Neon vector types specifies that they should be mangled as
2257// if they are structs (to match ARM's initial implementation). The
2258// vector type must be one of the special types predefined by ARM.
2259void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2260 QualType EltType = T->getElementType();
2261 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
Craig Topper36250ad2014-05-12 05:36:57 +00002262 const char *EltName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002263 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2264 switch (cast<BuiltinType>(EltType)->getKind()) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002265 case BuiltinType::SChar:
2266 case BuiltinType::UChar:
2267 EltName = "poly8_t";
2268 break;
2269 case BuiltinType::Short:
2270 case BuiltinType::UShort:
2271 EltName = "poly16_t";
2272 break;
2273 case BuiltinType::ULongLong:
2274 EltName = "poly64_t";
2275 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002276 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2277 }
2278 } else {
2279 switch (cast<BuiltinType>(EltType)->getKind()) {
2280 case BuiltinType::SChar: EltName = "int8_t"; break;
2281 case BuiltinType::UChar: EltName = "uint8_t"; break;
2282 case BuiltinType::Short: EltName = "int16_t"; break;
2283 case BuiltinType::UShort: EltName = "uint16_t"; break;
2284 case BuiltinType::Int: EltName = "int32_t"; break;
2285 case BuiltinType::UInt: EltName = "uint32_t"; break;
2286 case BuiltinType::LongLong: EltName = "int64_t"; break;
2287 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
Tim Northovera2ee4332014-03-29 15:09:45 +00002288 case BuiltinType::Double: EltName = "float64_t"; break;
Guy Benyei11169dd2012-12-18 14:30:41 +00002289 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002290 case BuiltinType::Half: EltName = "float16_t";break;
2291 default:
2292 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei11169dd2012-12-18 14:30:41 +00002293 }
2294 }
Craig Topper36250ad2014-05-12 05:36:57 +00002295 const char *BaseName = nullptr;
Guy Benyei11169dd2012-12-18 14:30:41 +00002296 unsigned BitSize = (T->getNumElements() *
2297 getASTContext().getTypeSize(EltType));
2298 if (BitSize == 64)
2299 BaseName = "__simd64_";
2300 else {
2301 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2302 BaseName = "__simd128_";
2303 }
2304 Out << strlen(BaseName) + strlen(EltName);
2305 Out << BaseName << EltName;
2306}
2307
Tim Northover2fe823a2013-08-01 09:23:19 +00002308static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2309 switch (EltType->getKind()) {
2310 case BuiltinType::SChar:
2311 return "Int8";
2312 case BuiltinType::Short:
2313 return "Int16";
2314 case BuiltinType::Int:
2315 return "Int32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002316 case BuiltinType::Long:
Tim Northovera2ee4332014-03-29 15:09:45 +00002317 case BuiltinType::LongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002318 return "Int64";
2319 case BuiltinType::UChar:
2320 return "Uint8";
2321 case BuiltinType::UShort:
2322 return "Uint16";
2323 case BuiltinType::UInt:
2324 return "Uint32";
Kevin Qinad64f6d2014-02-24 02:45:03 +00002325 case BuiltinType::ULong:
Tim Northovera2ee4332014-03-29 15:09:45 +00002326 case BuiltinType::ULongLong:
Tim Northover2fe823a2013-08-01 09:23:19 +00002327 return "Uint64";
2328 case BuiltinType::Half:
2329 return "Float16";
2330 case BuiltinType::Float:
2331 return "Float32";
2332 case BuiltinType::Double:
2333 return "Float64";
2334 default:
2335 llvm_unreachable("Unexpected vector element base type");
2336 }
2337}
2338
2339// AArch64's ABI for Neon vector types specifies that they should be mangled as
2340// the equivalent internal name. The vector type must be one of the special
2341// types predefined by ARM.
2342void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2343 QualType EltType = T->getElementType();
2344 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2345 unsigned BitSize =
2346 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper8698af42013-08-01 10:30:11 +00002347 (void)BitSize; // Silence warning.
Tim Northover2fe823a2013-08-01 09:23:19 +00002348
2349 assert((BitSize == 64 || BitSize == 128) &&
2350 "Neon vector type not 64 or 128 bits");
2351
Tim Northover2fe823a2013-08-01 09:23:19 +00002352 StringRef EltName;
2353 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2354 switch (cast<BuiltinType>(EltType)->getKind()) {
2355 case BuiltinType::UChar:
2356 EltName = "Poly8";
2357 break;
2358 case BuiltinType::UShort:
2359 EltName = "Poly16";
2360 break;
Kevin Qinad64f6d2014-02-24 02:45:03 +00002361 case BuiltinType::ULong:
Hao Liu90ee2f12013-11-17 09:14:46 +00002362 EltName = "Poly64";
2363 break;
Tim Northover2fe823a2013-08-01 09:23:19 +00002364 default:
2365 llvm_unreachable("unexpected Neon polynomial vector element type");
2366 }
2367 } else
2368 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2369
2370 std::string TypeName =
2371 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
2372 Out << TypeName.length() << TypeName;
2373}
2374
Guy Benyei11169dd2012-12-18 14:30:41 +00002375// GNU extension: vector types
2376// <type> ::= <vector-type>
2377// <vector-type> ::= Dv <positive dimension number> _
2378// <extended element type>
2379// ::= Dv [<dimension expression>] _ <element type>
2380// <extended element type> ::= <element type>
2381// ::= p # AltiVec vector pixel
2382// ::= b # Altivec vector bool
2383void CXXNameMangler::mangleType(const VectorType *T) {
2384 if ((T->getVectorKind() == VectorType::NeonVector ||
2385 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northovera2ee4332014-03-29 15:09:45 +00002386 llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
Christian Pirker9b019ae2014-02-25 13:51:00 +00002387 llvm::Triple::ArchType Arch =
2388 getASTContext().getTargetInfo().getTriple().getArch();
Tim Northover25e8a672014-05-24 12:51:25 +00002389 if ((Arch == llvm::Triple::aarch64 ||
Tim Northover40956e62014-07-23 12:32:58 +00002390 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
Tim Northover2fe823a2013-08-01 09:23:19 +00002391 mangleAArch64NeonVectorType(T);
2392 else
2393 mangleNeonVectorType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00002394 return;
2395 }
2396 Out << "Dv" << T->getNumElements() << '_';
2397 if (T->getVectorKind() == VectorType::AltiVecPixel)
2398 Out << 'p';
2399 else if (T->getVectorKind() == VectorType::AltiVecBool)
2400 Out << 'b';
2401 else
2402 mangleType(T->getElementType());
2403}
2404void CXXNameMangler::mangleType(const ExtVectorType *T) {
2405 mangleType(static_cast<const VectorType*>(T));
2406}
2407void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2408 Out << "Dv";
2409 mangleExpression(T->getSizeExpr());
2410 Out << '_';
2411 mangleType(T->getElementType());
2412}
2413
2414void CXXNameMangler::mangleType(const PackExpansionType *T) {
2415 // <type> ::= Dp <type> # pack expansion (C++0x)
2416 Out << "Dp";
2417 mangleType(T->getPattern());
2418}
2419
2420void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2421 mangleSourceName(T->getDecl()->getIdentifier());
2422}
2423
2424void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Eli Friedman5f508952013-06-18 22:41:37 +00002425 if (!T->qual_empty()) {
2426 // Mangle protocol qualifiers.
2427 SmallString<64> QualStr;
2428 llvm::raw_svector_ostream QualOS(QualStr);
2429 QualOS << "objcproto";
Aaron Ballman1683f7b2014-03-17 15:55:30 +00002430 for (const auto *I : T->quals()) {
2431 StringRef name = I->getName();
Eli Friedman5f508952013-06-18 22:41:37 +00002432 QualOS << name.size() << name;
2433 }
2434 QualOS.flush();
2435 Out << 'U' << QualStr.size() << QualStr;
2436 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002437 mangleType(T->getBaseType());
2438}
2439
2440void CXXNameMangler::mangleType(const BlockPointerType *T) {
2441 Out << "U13block_pointer";
2442 mangleType(T->getPointeeType());
2443}
2444
2445void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2446 // Mangle injected class name types as if the user had written the
2447 // specialization out fully. It may not actually be possible to see
2448 // this mangling, though.
2449 mangleType(T->getInjectedSpecializationType());
2450}
2451
2452void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2453 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2454 mangleName(TD, T->getArgs(), T->getNumArgs());
2455 } else {
2456 if (mangleSubstitution(QualType(T, 0)))
2457 return;
2458
2459 mangleTemplatePrefix(T->getTemplateName());
2460
2461 // FIXME: GCC does not appear to mangle the template arguments when
2462 // the template in question is a dependent template name. Should we
2463 // emulate that badness?
2464 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2465 addSubstitution(QualType(T, 0));
2466 }
2467}
2468
2469void CXXNameMangler::mangleType(const DependentNameType *T) {
David Majnemer64e40c52014-04-10 00:49:24 +00002470 // Proposal by cxx-abi-dev, 2014-03-26
2471 // <class-enum-type> ::= <name> # non-dependent or dependent type name or
2472 // # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002473 // # 'typename'
David Majnemer64e40c52014-04-10 00:49:24 +00002474 // ::= Ts <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002475 // # 'struct' or 'class'
David Majnemer64e40c52014-04-10 00:49:24 +00002476 // ::= Tu <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002477 // # 'union'
David Majnemer64e40c52014-04-10 00:49:24 +00002478 // ::= Te <name> # dependent elaborated type specifier using
David Majnemer61182a82014-04-10 00:59:44 +00002479 // # 'enum'
David Majnemer64e40c52014-04-10 00:49:24 +00002480 switch (T->getKeyword()) {
2481 case ETK_Typename:
2482 break;
2483 case ETK_Struct:
2484 case ETK_Class:
2485 case ETK_Interface:
2486 Out << "Ts";
2487 break;
2488 case ETK_Union:
2489 Out << "Tu";
2490 break;
2491 case ETK_Enum:
2492 Out << "Te";
2493 break;
2494 default:
2495 llvm_unreachable("unexpected keyword for dependent type name");
2496 }
David Majnemer2e159fb2014-04-15 05:51:25 +00002497 // Typename types are always nested
2498 Out << 'N';
Guy Benyei11169dd2012-12-18 14:30:41 +00002499 manglePrefix(T->getQualifier());
David Majnemer64e40c52014-04-10 00:49:24 +00002500 mangleSourceName(T->getIdentifier());
Guy Benyei11169dd2012-12-18 14:30:41 +00002501 Out << 'E';
2502}
2503
2504void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2505 // Dependently-scoped template types are nested if they have a prefix.
2506 Out << 'N';
2507
2508 // TODO: avoid making this TemplateName.
2509 TemplateName Prefix =
2510 getASTContext().getDependentTemplateName(T->getQualifier(),
2511 T->getIdentifier());
2512 mangleTemplatePrefix(Prefix);
2513
2514 // FIXME: GCC does not appear to mangle the template arguments when
2515 // the template in question is a dependent template name. Should we
2516 // emulate that badness?
2517 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2518 Out << 'E';
2519}
2520
2521void CXXNameMangler::mangleType(const TypeOfType *T) {
2522 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2523 // "extension with parameters" mangling.
2524 Out << "u6typeof";
2525}
2526
2527void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2528 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2529 // "extension with parameters" mangling.
2530 Out << "u6typeof";
2531}
2532
2533void CXXNameMangler::mangleType(const DecltypeType *T) {
2534 Expr *E = T->getUnderlyingExpr();
2535
2536 // type ::= Dt <expression> E # decltype of an id-expression
2537 // # or class member access
2538 // ::= DT <expression> E # decltype of an expression
2539
2540 // This purports to be an exhaustive list of id-expressions and
2541 // class member accesses. Note that we do not ignore parentheses;
2542 // parentheses change the semantics of decltype for these
2543 // expressions (and cause the mangler to use the other form).
2544 if (isa<DeclRefExpr>(E) ||
2545 isa<MemberExpr>(E) ||
2546 isa<UnresolvedLookupExpr>(E) ||
2547 isa<DependentScopeDeclRefExpr>(E) ||
2548 isa<CXXDependentScopeMemberExpr>(E) ||
2549 isa<UnresolvedMemberExpr>(E))
2550 Out << "Dt";
2551 else
2552 Out << "DT";
2553 mangleExpression(E);
2554 Out << 'E';
2555}
2556
2557void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2558 // If this is dependent, we need to record that. If not, we simply
2559 // mangle it as the underlying type since they are equivalent.
2560 if (T->isDependentType()) {
2561 Out << 'U';
2562
2563 switch (T->getUTTKind()) {
2564 case UnaryTransformType::EnumUnderlyingType:
2565 Out << "3eut";
2566 break;
2567 }
2568 }
2569
2570 mangleType(T->getUnderlyingType());
2571}
2572
2573void CXXNameMangler::mangleType(const AutoType *T) {
2574 QualType D = T->getDeducedType();
2575 // <builtin-type> ::= Da # dependent auto
2576 if (D.isNull())
Richard Smith74aeef52013-04-26 16:15:35 +00002577 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei11169dd2012-12-18 14:30:41 +00002578 else
2579 mangleType(D);
2580}
2581
2582void CXXNameMangler::mangleType(const AtomicType *T) {
Nick Lewycky206cc2d2014-03-09 17:09:28 +00002583 // <type> ::= U <source-name> <type> # vendor extended type qualifier
Guy Benyei11169dd2012-12-18 14:30:41 +00002584 // (Until there's a standardized mangling...)
2585 Out << "U7_Atomic";
2586 mangleType(T->getValueType());
2587}
2588
2589void CXXNameMangler::mangleIntegerLiteral(QualType T,
2590 const llvm::APSInt &Value) {
2591 // <expr-primary> ::= L <type> <value number> E # integer literal
2592 Out << 'L';
2593
2594 mangleType(T);
2595 if (T->isBooleanType()) {
2596 // Boolean values are encoded as 0/1.
2597 Out << (Value.getBoolValue() ? '1' : '0');
2598 } else {
2599 mangleNumber(Value);
2600 }
2601 Out << 'E';
2602
2603}
2604
David Majnemer1dabfdc2015-02-14 13:23:54 +00002605void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
2606 // Ignore member expressions involving anonymous unions.
2607 while (const auto *RT = Base->getType()->getAs<RecordType>()) {
2608 if (!RT->getDecl()->isAnonymousStructOrUnion())
2609 break;
2610 const auto *ME = dyn_cast<MemberExpr>(Base);
2611 if (!ME)
2612 break;
2613 Base = ME->getBase();
2614 IsArrow = ME->isArrow();
2615 }
2616
2617 if (Base->isImplicitCXXThis()) {
2618 // Note: GCC mangles member expressions to the implicit 'this' as
2619 // *this., whereas we represent them as this->. The Itanium C++ ABI
2620 // does not specify anything here, so we follow GCC.
2621 Out << "dtdefpT";
2622 } else {
2623 Out << (IsArrow ? "pt" : "dt");
2624 mangleExpression(Base);
2625 }
2626}
2627
Guy Benyei11169dd2012-12-18 14:30:41 +00002628/// Mangles a member expression.
2629void CXXNameMangler::mangleMemberExpr(const Expr *base,
2630 bool isArrow,
2631 NestedNameSpecifier *qualifier,
2632 NamedDecl *firstQualifierLookup,
2633 DeclarationName member,
2634 unsigned arity) {
2635 // <expression> ::= dt <expression> <unresolved-name>
2636 // ::= pt <expression> <unresolved-name>
David Majnemer1dabfdc2015-02-14 13:23:54 +00002637 if (base)
2638 mangleMemberExprBase(base, isArrow);
Guy Benyei11169dd2012-12-18 14:30:41 +00002639 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
2640}
2641
2642/// Look at the callee of the given call expression and determine if
2643/// it's a parenthesized id-expression which would have triggered ADL
2644/// otherwise.
2645static bool isParenthesizedADLCallee(const CallExpr *call) {
2646 const Expr *callee = call->getCallee();
2647 const Expr *fn = callee->IgnoreParens();
2648
2649 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2650 // too, but for those to appear in the callee, it would have to be
2651 // parenthesized.
2652 if (callee == fn) return false;
2653
2654 // Must be an unresolved lookup.
2655 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2656 if (!lookup) return false;
2657
2658 assert(!lookup->requiresADL());
2659
2660 // Must be an unqualified lookup.
2661 if (lookup->getQualifier()) return false;
2662
2663 // Must not have found a class member. Note that if one is a class
2664 // member, they're all class members.
2665 if (lookup->getNumDecls() > 0 &&
2666 (*lookup->decls_begin())->isCXXClassMember())
2667 return false;
2668
2669 // Otherwise, ADL would have been triggered.
2670 return true;
2671}
2672
David Majnemer9c775c72014-09-23 04:27:55 +00002673void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
2674 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2675 Out << CastEncoding;
2676 mangleType(ECE->getType());
2677 mangleExpression(ECE->getSubExpr());
2678}
2679
Richard Smith520449d2015-02-05 06:15:50 +00002680void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
2681 if (auto *Syntactic = InitList->getSyntacticForm())
2682 InitList = Syntactic;
2683 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2684 mangleExpression(InitList->getInit(i));
2685}
2686
Guy Benyei11169dd2012-12-18 14:30:41 +00002687void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2688 // <expression> ::= <unary operator-name> <expression>
2689 // ::= <binary operator-name> <expression> <expression>
2690 // ::= <trinary operator-name> <expression> <expression> <expression>
2691 // ::= cv <type> expression # conversion with one argument
2692 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
David Majnemer9c775c72014-09-23 04:27:55 +00002693 // ::= dc <type> <expression> # dynamic_cast<type> (expression)
2694 // ::= sc <type> <expression> # static_cast<type> (expression)
2695 // ::= cc <type> <expression> # const_cast<type> (expression)
2696 // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00002697 // ::= st <type> # sizeof (a type)
2698 // ::= at <type> # alignof (a type)
2699 // ::= <template-param>
2700 // ::= <function-param>
2701 // ::= sr <type> <unqualified-name> # dependent name
2702 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2703 // ::= ds <expression> <expression> # expr.*expr
2704 // ::= sZ <template-param> # size of a parameter pack
2705 // ::= sZ <function-param> # size of a function parameter pack
2706 // ::= <expr-primary>
2707 // <expr-primary> ::= L <type> <value number> E # integer literal
2708 // ::= L <type <value float> E # floating literal
2709 // ::= L <mangled-name> E # external name
2710 // ::= fpT # 'this' expression
2711 QualType ImplicitlyConvertedToType;
2712
2713recurse:
2714 switch (E->getStmtClass()) {
2715 case Expr::NoStmtClass:
2716#define ABSTRACT_STMT(Type)
2717#define EXPR(Type, Base)
2718#define STMT(Type, Base) \
2719 case Expr::Type##Class:
2720#include "clang/AST/StmtNodes.inc"
2721 // fallthrough
2722
2723 // These all can only appear in local or variable-initialization
2724 // contexts and so should never appear in a mangling.
2725 case Expr::AddrLabelExprClass:
2726 case Expr::DesignatedInitExprClass:
2727 case Expr::ImplicitValueInitExprClass:
2728 case Expr::ParenListExprClass:
2729 case Expr::LambdaExprClass:
John McCall5e77d762013-04-16 07:28:30 +00002730 case Expr::MSPropertyRefExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00002731 case Expr::TypoExprClass: // This should no longer exist in the AST by now.
Guy Benyei11169dd2012-12-18 14:30:41 +00002732 llvm_unreachable("unexpected statement kind");
2733
2734 // FIXME: invent manglings for all these.
2735 case Expr::BlockExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002736 case Expr::ChooseExprClass:
2737 case Expr::CompoundLiteralExprClass:
2738 case Expr::ExtVectorElementExprClass:
2739 case Expr::GenericSelectionExprClass:
2740 case Expr::ObjCEncodeExprClass:
2741 case Expr::ObjCIsaExprClass:
2742 case Expr::ObjCIvarRefExprClass:
2743 case Expr::ObjCMessageExprClass:
2744 case Expr::ObjCPropertyRefExprClass:
2745 case Expr::ObjCProtocolExprClass:
2746 case Expr::ObjCSelectorExprClass:
2747 case Expr::ObjCStringLiteralClass:
2748 case Expr::ObjCBoxedExprClass:
2749 case Expr::ObjCArrayLiteralClass:
2750 case Expr::ObjCDictionaryLiteralClass:
2751 case Expr::ObjCSubscriptRefExprClass:
2752 case Expr::ObjCIndirectCopyRestoreExprClass:
2753 case Expr::OffsetOfExprClass:
2754 case Expr::PredefinedExprClass:
2755 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00002756 case Expr::ConvertVectorExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002757 case Expr::StmtExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002758 case Expr::TypeTraitExprClass:
2759 case Expr::ArrayTypeTraitExprClass:
2760 case Expr::ExpressionTraitExprClass:
2761 case Expr::VAArgExprClass:
Guy Benyei11169dd2012-12-18 14:30:41 +00002762 case Expr::CUDAKernelCallExprClass:
2763 case Expr::AsTypeExprClass:
2764 case Expr::PseudoObjectExprClass:
2765 case Expr::AtomicExprClass:
2766 {
2767 // As bad as this diagnostic is, it's better than crashing.
2768 DiagnosticsEngine &Diags = Context.getDiags();
2769 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2770 "cannot yet mangle expression type %0");
2771 Diags.Report(E->getExprLoc(), DiagID)
2772 << E->getStmtClassName() << E->getSourceRange();
2773 break;
2774 }
2775
Fariborz Jahanian945a08d2014-09-24 16:28:40 +00002776 case Expr::CXXUuidofExprClass: {
2777 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
2778 if (UE->isTypeOperand()) {
2779 QualType UuidT = UE->getTypeOperand(Context.getASTContext());
2780 Out << "u8__uuidoft";
2781 mangleType(UuidT);
2782 } else {
2783 Expr *UuidExp = UE->getExprOperand();
2784 Out << "u8__uuidofz";
2785 mangleExpression(UuidExp, Arity);
2786 }
2787 break;
2788 }
2789
Guy Benyei11169dd2012-12-18 14:30:41 +00002790 // Even gcc-4.5 doesn't mangle this.
2791 case Expr::BinaryConditionalOperatorClass: {
2792 DiagnosticsEngine &Diags = Context.getDiags();
2793 unsigned DiagID =
2794 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2795 "?: operator with omitted middle operand cannot be mangled");
2796 Diags.Report(E->getExprLoc(), DiagID)
2797 << E->getStmtClassName() << E->getSourceRange();
2798 break;
2799 }
2800
2801 // These are used for internal purposes and cannot be meaningfully mangled.
2802 case Expr::OpaqueValueExprClass:
2803 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2804
2805 case Expr::InitListExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00002806 Out << "il";
Richard Smith520449d2015-02-05 06:15:50 +00002807 mangleInitListElements(cast<InitListExpr>(E));
Guy Benyei11169dd2012-12-18 14:30:41 +00002808 Out << "E";
2809 break;
2810 }
2811
2812 case Expr::CXXDefaultArgExprClass:
2813 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2814 break;
2815
Richard Smith852c9db2013-04-20 22:23:05 +00002816 case Expr::CXXDefaultInitExprClass:
2817 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2818 break;
2819
Richard Smithcc1b96d2013-06-12 22:31:48 +00002820 case Expr::CXXStdInitializerListExprClass:
2821 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2822 break;
2823
Guy Benyei11169dd2012-12-18 14:30:41 +00002824 case Expr::SubstNonTypeTemplateParmExprClass:
2825 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2826 Arity);
2827 break;
2828
2829 case Expr::UserDefinedLiteralClass:
2830 // We follow g++'s approach of mangling a UDL as a call to the literal
2831 // operator.
2832 case Expr::CXXMemberCallExprClass: // fallthrough
2833 case Expr::CallExprClass: {
2834 const CallExpr *CE = cast<CallExpr>(E);
2835
2836 // <expression> ::= cp <simple-id> <expression>* E
2837 // We use this mangling only when the call would use ADL except
2838 // for being parenthesized. Per discussion with David
2839 // Vandervoorde, 2011.04.25.
2840 if (isParenthesizedADLCallee(CE)) {
2841 Out << "cp";
2842 // The callee here is a parenthesized UnresolvedLookupExpr with
2843 // no qualifier and should always get mangled as a <simple-id>
2844 // anyway.
2845
2846 // <expression> ::= cl <expression>* E
2847 } else {
2848 Out << "cl";
2849 }
2850
2851 mangleExpression(CE->getCallee(), CE->getNumArgs());
2852 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2853 mangleExpression(CE->getArg(I));
2854 Out << 'E';
2855 break;
2856 }
2857
2858 case Expr::CXXNewExprClass: {
2859 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2860 if (New->isGlobalNew()) Out << "gs";
2861 Out << (New->isArray() ? "na" : "nw");
2862 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2863 E = New->placement_arg_end(); I != E; ++I)
2864 mangleExpression(*I);
2865 Out << '_';
2866 mangleType(New->getAllocatedType());
2867 if (New->hasInitializer()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002868 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2869 Out << "il";
2870 else
2871 Out << "pi";
2872 const Expr *Init = New->getInitializer();
2873 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2874 // Directly inline the initializers.
2875 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2876 E = CCE->arg_end();
2877 I != E; ++I)
2878 mangleExpression(*I);
2879 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2880 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2881 mangleExpression(PLE->getExpr(i));
2882 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2883 isa<InitListExpr>(Init)) {
2884 // Only take InitListExprs apart for list-initialization.
Richard Smith520449d2015-02-05 06:15:50 +00002885 mangleInitListElements(cast<InitListExpr>(Init));
Guy Benyei11169dd2012-12-18 14:30:41 +00002886 } else
2887 mangleExpression(Init);
2888 }
2889 Out << 'E';
2890 break;
2891 }
2892
David Majnemer1dabfdc2015-02-14 13:23:54 +00002893 case Expr::CXXPseudoDestructorExprClass: {
2894 const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
2895 if (const Expr *Base = PDE->getBase())
2896 mangleMemberExprBase(Base, PDE->isArrow());
2897 if (NestedNameSpecifier *Qualifier = PDE->getQualifier())
2898 mangleUnresolvedPrefix(Qualifier, /*FirstQualifierLookup=*/nullptr);
2899 // <base-unresolved-name> ::= dn <destructor-name>
2900 Out << "dn";
David Majnemera88b3592015-02-18 02:28:01 +00002901 QualType DestroyedType = PDE->getDestroyedType();
2902 mangleDestructorName(DestroyedType);
David Majnemer1dabfdc2015-02-14 13:23:54 +00002903 break;
2904 }
2905
Guy Benyei11169dd2012-12-18 14:30:41 +00002906 case Expr::MemberExprClass: {
2907 const MemberExpr *ME = cast<MemberExpr>(E);
2908 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00002909 ME->getQualifier(), nullptr,
2910 ME->getMemberDecl()->getDeclName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002911 break;
2912 }
2913
2914 case Expr::UnresolvedMemberExprClass: {
2915 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2916 mangleMemberExpr(ME->getBase(), ME->isArrow(),
Craig Topper36250ad2014-05-12 05:36:57 +00002917 ME->getQualifier(), nullptr, ME->getMemberName(),
Guy Benyei11169dd2012-12-18 14:30:41 +00002918 Arity);
2919 if (ME->hasExplicitTemplateArgs())
2920 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2921 break;
2922 }
2923
2924 case Expr::CXXDependentScopeMemberExprClass: {
2925 const CXXDependentScopeMemberExpr *ME
2926 = cast<CXXDependentScopeMemberExpr>(E);
2927 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2928 ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2929 ME->getMember(), Arity);
2930 if (ME->hasExplicitTemplateArgs())
2931 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2932 break;
2933 }
2934
2935 case Expr::UnresolvedLookupExprClass: {
2936 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
Craig Topper36250ad2014-05-12 05:36:57 +00002937 mangleUnresolvedName(ULE->getQualifier(), nullptr, ULE->getName(), Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00002938
2939 // All the <unresolved-name> productions end in a
2940 // base-unresolved-name, where <template-args> are just tacked
2941 // onto the end.
2942 if (ULE->hasExplicitTemplateArgs())
2943 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2944 break;
2945 }
2946
2947 case Expr::CXXUnresolvedConstructExprClass: {
2948 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2949 unsigned N = CE->arg_size();
2950
2951 Out << "cv";
2952 mangleType(CE->getType());
2953 if (N != 1) Out << '_';
2954 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2955 if (N != 1) Out << 'E';
2956 break;
2957 }
2958
Guy Benyei11169dd2012-12-18 14:30:41 +00002959 case Expr::CXXConstructExprClass: {
Richard Smith520449d2015-02-05 06:15:50 +00002960 const auto *CE = cast<CXXConstructExpr>(E);
Richard Smithed83ebd2015-02-05 07:02:11 +00002961 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
Richard Smith520449d2015-02-05 06:15:50 +00002962 assert(
2963 CE->getNumArgs() >= 1 &&
2964 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
2965 "implicit CXXConstructExpr must have one argument");
2966 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
2967 }
2968 Out << "il";
2969 for (auto *E : CE->arguments())
2970 mangleExpression(E);
2971 Out << "E";
2972 break;
2973 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002974
Richard Smith520449d2015-02-05 06:15:50 +00002975 case Expr::CXXTemporaryObjectExprClass: {
2976 const auto *CE = cast<CXXTemporaryObjectExpr>(E);
2977 unsigned N = CE->getNumArgs();
2978 bool List = CE->isListInitialization();
2979
2980 if (List)
Guy Benyei11169dd2012-12-18 14:30:41 +00002981 Out << "tl";
2982 else
2983 Out << "cv";
2984 mangleType(CE->getType());
Richard Smith520449d2015-02-05 06:15:50 +00002985 if (!List && N != 1)
2986 Out << '_';
Richard Smithed83ebd2015-02-05 07:02:11 +00002987 if (CE->isStdInitListInitialization()) {
2988 // We implicitly created a std::initializer_list<T> for the first argument
2989 // of a constructor of type U in an expression of the form U{a, b, c}.
2990 // Strip all the semantic gunk off the initializer list.
2991 auto *SILE =
2992 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
2993 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
2994 mangleInitListElements(ILE);
2995 } else {
2996 for (auto *E : CE->arguments())
2997 mangleExpression(E);
2998 }
Richard Smith520449d2015-02-05 06:15:50 +00002999 if (List || N != 1)
3000 Out << 'E';
Guy Benyei11169dd2012-12-18 14:30:41 +00003001 break;
3002 }
3003
3004 case Expr::CXXScalarValueInitExprClass:
Richard Smith520449d2015-02-05 06:15:50 +00003005 Out << "cv";
Guy Benyei11169dd2012-12-18 14:30:41 +00003006 mangleType(E->getType());
Richard Smith520449d2015-02-05 06:15:50 +00003007 Out << "_E";
Guy Benyei11169dd2012-12-18 14:30:41 +00003008 break;
3009
3010 case Expr::CXXNoexceptExprClass:
3011 Out << "nx";
3012 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3013 break;
3014
3015 case Expr::UnaryExprOrTypeTraitExprClass: {
3016 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3017
3018 if (!SAE->isInstantiationDependent()) {
3019 // Itanium C++ ABI:
3020 // If the operand of a sizeof or alignof operator is not
3021 // instantiation-dependent it is encoded as an integer literal
3022 // reflecting the result of the operator.
3023 //
3024 // If the result of the operator is implicitly converted to a known
3025 // integer type, that type is used for the literal; otherwise, the type
3026 // of std::size_t or std::ptrdiff_t is used.
3027 QualType T = (ImplicitlyConvertedToType.isNull() ||
3028 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3029 : ImplicitlyConvertedToType;
3030 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3031 mangleIntegerLiteral(T, V);
3032 break;
3033 }
3034
3035 switch(SAE->getKind()) {
3036 case UETT_SizeOf:
3037 Out << 's';
3038 break;
3039 case UETT_AlignOf:
3040 Out << 'a';
3041 break;
3042 case UETT_VecStep:
3043 DiagnosticsEngine &Diags = Context.getDiags();
3044 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3045 "cannot yet mangle vec_step expression");
3046 Diags.Report(DiagID);
3047 return;
3048 }
3049 if (SAE->isArgumentType()) {
3050 Out << 't';
3051 mangleType(SAE->getArgumentType());
3052 } else {
3053 Out << 'z';
3054 mangleExpression(SAE->getArgumentExpr());
3055 }
3056 break;
3057 }
3058
3059 case Expr::CXXThrowExprClass: {
3060 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003061 // <expression> ::= tw <expression> # throw expression
3062 // ::= tr # rethrow
Guy Benyei11169dd2012-12-18 14:30:41 +00003063 if (TE->getSubExpr()) {
3064 Out << "tw";
3065 mangleExpression(TE->getSubExpr());
3066 } else {
3067 Out << "tr";
3068 }
3069 break;
3070 }
3071
3072 case Expr::CXXTypeidExprClass: {
3073 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003074 // <expression> ::= ti <type> # typeid (type)
3075 // ::= te <expression> # typeid (expression)
Guy Benyei11169dd2012-12-18 14:30:41 +00003076 if (TIE->isTypeOperand()) {
3077 Out << "ti";
David Majnemer143c55e2013-09-27 07:04:31 +00003078 mangleType(TIE->getTypeOperand(Context.getASTContext()));
Guy Benyei11169dd2012-12-18 14:30:41 +00003079 } else {
3080 Out << "te";
3081 mangleExpression(TIE->getExprOperand());
3082 }
3083 break;
3084 }
3085
3086 case Expr::CXXDeleteExprClass: {
3087 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smitheb0133c2013-08-27 01:03:46 +00003088 // <expression> ::= [gs] dl <expression> # [::] delete expr
3089 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei11169dd2012-12-18 14:30:41 +00003090 if (DE->isGlobalDelete()) Out << "gs";
3091 Out << (DE->isArrayForm() ? "da" : "dl");
3092 mangleExpression(DE->getArgument());
3093 break;
3094 }
3095
3096 case Expr::UnaryOperatorClass: {
3097 const UnaryOperator *UO = cast<UnaryOperator>(E);
3098 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3099 /*Arity=*/1);
3100 mangleExpression(UO->getSubExpr());
3101 break;
3102 }
3103
3104 case Expr::ArraySubscriptExprClass: {
3105 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3106
3107 // Array subscript is treated as a syntactically weird form of
3108 // binary operator.
3109 Out << "ix";
3110 mangleExpression(AE->getLHS());
3111 mangleExpression(AE->getRHS());
3112 break;
3113 }
3114
3115 case Expr::CompoundAssignOperatorClass: // fallthrough
3116 case Expr::BinaryOperatorClass: {
3117 const BinaryOperator *BO = cast<BinaryOperator>(E);
3118 if (BO->getOpcode() == BO_PtrMemD)
3119 Out << "ds";
3120 else
3121 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3122 /*Arity=*/2);
3123 mangleExpression(BO->getLHS());
3124 mangleExpression(BO->getRHS());
3125 break;
3126 }
3127
3128 case Expr::ConditionalOperatorClass: {
3129 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3130 mangleOperatorName(OO_Conditional, /*Arity=*/3);
3131 mangleExpression(CO->getCond());
3132 mangleExpression(CO->getLHS(), Arity);
3133 mangleExpression(CO->getRHS(), Arity);
3134 break;
3135 }
3136
3137 case Expr::ImplicitCastExprClass: {
3138 ImplicitlyConvertedToType = E->getType();
3139 E = cast<ImplicitCastExpr>(E)->getSubExpr();
3140 goto recurse;
3141 }
3142
3143 case Expr::ObjCBridgedCastExprClass: {
3144 // Mangle ownership casts as a vendor extended operator __bridge,
3145 // __bridge_transfer, or __bridge_retain.
3146 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3147 Out << "v1U" << Kind.size() << Kind;
3148 }
3149 // Fall through to mangle the cast itself.
3150
3151 case Expr::CStyleCastExprClass:
David Majnemer9c775c72014-09-23 04:27:55 +00003152 mangleCastExpression(E, "cv");
Guy Benyei11169dd2012-12-18 14:30:41 +00003153 break;
David Majnemer9c775c72014-09-23 04:27:55 +00003154
Richard Smith520449d2015-02-05 06:15:50 +00003155 case Expr::CXXFunctionalCastExprClass: {
3156 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3157 // FIXME: Add isImplicit to CXXConstructExpr.
3158 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3159 if (CCE->getParenOrBraceRange().isInvalid())
3160 Sub = CCE->getArg(0)->IgnoreImplicit();
3161 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3162 Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3163 if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3164 Out << "tl";
3165 mangleType(E->getType());
3166 mangleInitListElements(IL);
3167 Out << "E";
3168 } else {
3169 mangleCastExpression(E, "cv");
3170 }
3171 break;
3172 }
3173
David Majnemer9c775c72014-09-23 04:27:55 +00003174 case Expr::CXXStaticCastExprClass:
3175 mangleCastExpression(E, "sc");
3176 break;
3177 case Expr::CXXDynamicCastExprClass:
3178 mangleCastExpression(E, "dc");
3179 break;
3180 case Expr::CXXReinterpretCastExprClass:
3181 mangleCastExpression(E, "rc");
3182 break;
3183 case Expr::CXXConstCastExprClass:
3184 mangleCastExpression(E, "cc");
3185 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003186
3187 case Expr::CXXOperatorCallExprClass: {
3188 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3189 unsigned NumArgs = CE->getNumArgs();
3190 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3191 // Mangle the arguments.
3192 for (unsigned i = 0; i != NumArgs; ++i)
3193 mangleExpression(CE->getArg(i));
3194 break;
3195 }
3196
3197 case Expr::ParenExprClass:
3198 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3199 break;
3200
3201 case Expr::DeclRefExprClass: {
3202 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3203
3204 switch (D->getKind()) {
3205 default:
3206 // <expr-primary> ::= L <mangled-name> E # external name
3207 Out << 'L';
David Majnemer7ff7eb72015-02-18 07:47:09 +00003208 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003209 Out << 'E';
3210 break;
3211
3212 case Decl::ParmVar:
3213 mangleFunctionParam(cast<ParmVarDecl>(D));
3214 break;
3215
3216 case Decl::EnumConstant: {
3217 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3218 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3219 break;
3220 }
3221
3222 case Decl::NonTypeTemplateParm: {
3223 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3224 mangleTemplateParameter(PD->getIndex());
3225 break;
3226 }
3227
3228 }
3229
3230 break;
3231 }
3232
3233 case Expr::SubstNonTypeTemplateParmPackExprClass:
3234 // FIXME: not clear how to mangle this!
3235 // template <unsigned N...> class A {
3236 // template <class U...> void foo(U (&x)[N]...);
3237 // };
3238 Out << "_SUBSTPACK_";
3239 break;
3240
3241 case Expr::FunctionParmPackExprClass: {
3242 // FIXME: not clear how to mangle this!
3243 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3244 Out << "v110_SUBSTPACK";
3245 mangleFunctionParam(FPPE->getParameterPack());
3246 break;
3247 }
3248
3249 case Expr::DependentScopeDeclRefExprClass: {
3250 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
Craig Topper36250ad2014-05-12 05:36:57 +00003251 mangleUnresolvedName(DRE->getQualifier(), nullptr, DRE->getDeclName(),
3252 Arity);
Guy Benyei11169dd2012-12-18 14:30:41 +00003253
3254 // All the <unresolved-name> productions end in a
3255 // base-unresolved-name, where <template-args> are just tacked
3256 // onto the end.
3257 if (DRE->hasExplicitTemplateArgs())
3258 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
3259 break;
3260 }
3261
3262 case Expr::CXXBindTemporaryExprClass:
3263 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3264 break;
3265
3266 case Expr::ExprWithCleanupsClass:
3267 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3268 break;
3269
3270 case Expr::FloatingLiteralClass: {
3271 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3272 Out << 'L';
3273 mangleType(FL->getType());
3274 mangleFloat(FL->getValue());
3275 Out << 'E';
3276 break;
3277 }
3278
3279 case Expr::CharacterLiteralClass:
3280 Out << 'L';
3281 mangleType(E->getType());
3282 Out << cast<CharacterLiteral>(E)->getValue();
3283 Out << 'E';
3284 break;
3285
3286 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3287 case Expr::ObjCBoolLiteralExprClass:
3288 Out << "Lb";
3289 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3290 Out << 'E';
3291 break;
3292
3293 case Expr::CXXBoolLiteralExprClass:
3294 Out << "Lb";
3295 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3296 Out << 'E';
3297 break;
3298
3299 case Expr::IntegerLiteralClass: {
3300 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3301 if (E->getType()->isSignedIntegerType())
3302 Value.setIsSigned(true);
3303 mangleIntegerLiteral(E->getType(), Value);
3304 break;
3305 }
3306
3307 case Expr::ImaginaryLiteralClass: {
3308 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3309 // Mangle as if a complex literal.
3310 // Proposal from David Vandevoorde, 2010.06.30.
3311 Out << 'L';
3312 mangleType(E->getType());
3313 if (const FloatingLiteral *Imag =
3314 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3315 // Mangle a floating-point zero of the appropriate type.
3316 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3317 Out << '_';
3318 mangleFloat(Imag->getValue());
3319 } else {
3320 Out << "0_";
3321 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3322 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3323 Value.setIsSigned(true);
3324 mangleNumber(Value);
3325 }
3326 Out << 'E';
3327 break;
3328 }
3329
3330 case Expr::StringLiteralClass: {
3331 // Revised proposal from David Vandervoorde, 2010.07.15.
3332 Out << 'L';
3333 assert(isa<ConstantArrayType>(E->getType()));
3334 mangleType(E->getType());
3335 Out << 'E';
3336 break;
3337 }
3338
3339 case Expr::GNUNullExprClass:
3340 // FIXME: should this really be mangled the same as nullptr?
3341 // fallthrough
3342
3343 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei11169dd2012-12-18 14:30:41 +00003344 Out << "LDnE";
3345 break;
3346 }
3347
3348 case Expr::PackExpansionExprClass:
3349 Out << "sp";
3350 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3351 break;
3352
3353 case Expr::SizeOfPackExprClass: {
3354 Out << "sZ";
3355 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
3356 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3357 mangleTemplateParameter(TTP->getIndex());
3358 else if (const NonTypeTemplateParmDecl *NTTP
3359 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3360 mangleTemplateParameter(NTTP->getIndex());
3361 else if (const TemplateTemplateParmDecl *TempTP
3362 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3363 mangleTemplateParameter(TempTP->getIndex());
3364 else
3365 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3366 break;
3367 }
Richard Smith0f0af192014-11-08 05:07:16 +00003368
Guy Benyei11169dd2012-12-18 14:30:41 +00003369 case Expr::MaterializeTemporaryExprClass: {
3370 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3371 break;
3372 }
Richard Smith0f0af192014-11-08 05:07:16 +00003373
3374 case Expr::CXXFoldExprClass: {
3375 auto *FE = cast<CXXFoldExpr>(E);
Richard Smith8e6923b2014-11-10 19:44:15 +00003376 if (FE->isLeftFold())
3377 Out << (FE->getInit() ? "fL" : "fl");
Richard Smith0f0af192014-11-08 05:07:16 +00003378 else
Richard Smith8e6923b2014-11-10 19:44:15 +00003379 Out << (FE->getInit() ? "fR" : "fr");
Richard Smith0f0af192014-11-08 05:07:16 +00003380
3381 if (FE->getOperator() == BO_PtrMemD)
3382 Out << "ds";
3383 else
3384 mangleOperatorName(
3385 BinaryOperator::getOverloadedOperator(FE->getOperator()),
3386 /*Arity=*/2);
3387
3388 if (FE->getLHS())
3389 mangleExpression(FE->getLHS());
3390 if (FE->getRHS())
3391 mangleExpression(FE->getRHS());
3392 break;
3393 }
3394
Guy Benyei11169dd2012-12-18 14:30:41 +00003395 case Expr::CXXThisExprClass:
3396 Out << "fpT";
3397 break;
3398 }
3399}
3400
3401/// Mangle an expression which refers to a parameter variable.
3402///
3403/// <expression> ::= <function-param>
3404/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3405/// <function-param> ::= fp <top-level CV-qualifiers>
3406/// <parameter-2 non-negative number> _ # L == 0, I > 0
3407/// <function-param> ::= fL <L-1 non-negative number>
3408/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3409/// <function-param> ::= fL <L-1 non-negative number>
3410/// p <top-level CV-qualifiers>
3411/// <I-1 non-negative number> _ # L > 0, I > 0
3412///
3413/// L is the nesting depth of the parameter, defined as 1 if the
3414/// parameter comes from the innermost function prototype scope
3415/// enclosing the current context, 2 if from the next enclosing
3416/// function prototype scope, and so on, with one special case: if
3417/// we've processed the full parameter clause for the innermost
3418/// function type, then L is one less. This definition conveniently
3419/// makes it irrelevant whether a function's result type was written
3420/// trailing or leading, but is otherwise overly complicated; the
3421/// numbering was first designed without considering references to
3422/// parameter in locations other than return types, and then the
3423/// mangling had to be generalized without changing the existing
3424/// manglings.
3425///
3426/// I is the zero-based index of the parameter within its parameter
3427/// declaration clause. Note that the original ABI document describes
3428/// this using 1-based ordinals.
3429void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3430 unsigned parmDepth = parm->getFunctionScopeDepth();
3431 unsigned parmIndex = parm->getFunctionScopeIndex();
3432
3433 // Compute 'L'.
3434 // parmDepth does not include the declaring function prototype.
3435 // FunctionTypeDepth does account for that.
3436 assert(parmDepth < FunctionTypeDepth.getDepth());
3437 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3438 if (FunctionTypeDepth.isInResultType())
3439 nestingDepth--;
3440
3441 if (nestingDepth == 0) {
3442 Out << "fp";
3443 } else {
3444 Out << "fL" << (nestingDepth - 1) << 'p';
3445 }
3446
3447 // Top-level qualifiers. We don't have to worry about arrays here,
3448 // because parameters declared as arrays should already have been
3449 // transformed to have pointer type. FIXME: apparently these don't
3450 // get mangled if used as an rvalue of a known non-class type?
3451 assert(!parm->getType()->isArrayType()
3452 && "parameter's type is still an array type?");
3453 mangleQualifiers(parm->getType().getQualifiers());
3454
3455 // Parameter index.
3456 if (parmIndex != 0) {
3457 Out << (parmIndex - 1);
3458 }
3459 Out << '_';
3460}
3461
3462void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3463 // <ctor-dtor-name> ::= C1 # complete object constructor
3464 // ::= C2 # base object constructor
Guy Benyei11169dd2012-12-18 14:30:41 +00003465 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003466 // In addition, C5 is a comdat name with C1 and C2 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003467 switch (T) {
3468 case Ctor_Complete:
3469 Out << "C1";
3470 break;
3471 case Ctor_Base:
3472 Out << "C2";
3473 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003474 case Ctor_Comdat:
3475 Out << "C5";
Guy Benyei11169dd2012-12-18 14:30:41 +00003476 break;
3477 }
3478}
3479
3480void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3481 // <ctor-dtor-name> ::= D0 # deleting destructor
3482 // ::= D1 # complete object destructor
3483 // ::= D2 # base object destructor
3484 //
Rafael Espindola1e4df922014-09-16 15:18:21 +00003485 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
Guy Benyei11169dd2012-12-18 14:30:41 +00003486 switch (T) {
3487 case Dtor_Deleting:
3488 Out << "D0";
3489 break;
3490 case Dtor_Complete:
3491 Out << "D1";
3492 break;
3493 case Dtor_Base:
3494 Out << "D2";
3495 break;
Rafael Espindola1e4df922014-09-16 15:18:21 +00003496 case Dtor_Comdat:
3497 Out << "D5";
3498 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00003499 }
3500}
3501
3502void CXXNameMangler::mangleTemplateArgs(
3503 const ASTTemplateArgumentListInfo &TemplateArgs) {
3504 // <template-args> ::= I <template-arg>+ E
3505 Out << 'I';
3506 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3507 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3508 Out << 'E';
3509}
3510
3511void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3512 // <template-args> ::= I <template-arg>+ E
3513 Out << 'I';
3514 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3515 mangleTemplateArg(AL[i]);
3516 Out << 'E';
3517}
3518
3519void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3520 unsigned NumTemplateArgs) {
3521 // <template-args> ::= I <template-arg>+ E
3522 Out << 'I';
3523 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3524 mangleTemplateArg(TemplateArgs[i]);
3525 Out << 'E';
3526}
3527
3528void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3529 // <template-arg> ::= <type> # type or template
3530 // ::= X <expression> E # expression
3531 // ::= <expr-primary> # simple expressions
3532 // ::= J <template-arg>* E # argument pack
Guy Benyei11169dd2012-12-18 14:30:41 +00003533 if (!A.isInstantiationDependent() || A.isDependent())
3534 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3535
3536 switch (A.getKind()) {
3537 case TemplateArgument::Null:
3538 llvm_unreachable("Cannot mangle NULL template argument");
3539
3540 case TemplateArgument::Type:
3541 mangleType(A.getAsType());
3542 break;
3543 case TemplateArgument::Template:
3544 // This is mangled as <type>.
3545 mangleType(A.getAsTemplate());
3546 break;
3547 case TemplateArgument::TemplateExpansion:
3548 // <type> ::= Dp <type> # pack expansion (C++0x)
3549 Out << "Dp";
3550 mangleType(A.getAsTemplateOrTemplatePattern());
3551 break;
3552 case TemplateArgument::Expression: {
3553 // It's possible to end up with a DeclRefExpr here in certain
3554 // dependent cases, in which case we should mangle as a
3555 // declaration.
3556 const Expr *E = A.getAsExpr()->IgnoreParens();
3557 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3558 const ValueDecl *D = DRE->getDecl();
3559 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3560 Out << "L";
David Majnemer7ff7eb72015-02-18 07:47:09 +00003561 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003562 Out << 'E';
3563 break;
3564 }
3565 }
3566
3567 Out << 'X';
3568 mangleExpression(E);
3569 Out << 'E';
3570 break;
3571 }
3572 case TemplateArgument::Integral:
3573 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3574 break;
3575 case TemplateArgument::Declaration: {
3576 // <expr-primary> ::= L <mangled-name> E # external name
3577 // Clang produces AST's where pointer-to-member-function expressions
3578 // and pointer-to-function expressions are represented as a declaration not
3579 // an expression. We compensate for it here to produce the correct mangling.
3580 ValueDecl *D = A.getAsDecl();
David Blaikie952a9b12014-10-17 18:00:12 +00003581 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
Guy Benyei11169dd2012-12-18 14:30:41 +00003582 if (compensateMangling) {
3583 Out << 'X';
3584 mangleOperatorName(OO_Amp, 1);
3585 }
3586
3587 Out << 'L';
3588 // References to external entities use the mangled name; if the name would
3589 // not normally be manged then mangle it as unqualified.
David Majnemer7ff7eb72015-02-18 07:47:09 +00003590 mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003591 Out << 'E';
3592
3593 if (compensateMangling)
3594 Out << 'E';
3595
3596 break;
3597 }
3598 case TemplateArgument::NullPtr: {
3599 // <expr-primary> ::= L <type> 0 E
3600 Out << 'L';
3601 mangleType(A.getNullPtrType());
3602 Out << "0E";
3603 break;
3604 }
3605 case TemplateArgument::Pack: {
Richard Smitheb0133c2013-08-27 01:03:46 +00003606 // <template-arg> ::= J <template-arg>* E
Guy Benyei11169dd2012-12-18 14:30:41 +00003607 Out << 'J';
Aaron Ballman2a89e852014-07-15 21:32:31 +00003608 for (const auto &P : A.pack_elements())
3609 mangleTemplateArg(P);
Guy Benyei11169dd2012-12-18 14:30:41 +00003610 Out << 'E';
3611 }
3612 }
3613}
3614
3615void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3616 // <template-param> ::= T_ # first template parameter
3617 // ::= T <parameter-2 non-negative number> _
3618 if (Index == 0)
3619 Out << "T_";
3620 else
3621 Out << 'T' << (Index - 1) << '_';
3622}
3623
David Majnemer3b3bdb52014-05-06 22:49:16 +00003624void CXXNameMangler::mangleSeqID(unsigned SeqID) {
3625 if (SeqID == 1)
3626 Out << '0';
3627 else if (SeqID > 1) {
3628 SeqID--;
3629
3630 // <seq-id> is encoded in base-36, using digits and upper case letters.
3631 char Buffer[7]; // log(2**32) / log(36) ~= 7
Craig Toppere3d2ecbe2014-06-28 23:22:33 +00003632 MutableArrayRef<char> BufferRef(Buffer);
3633 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
David Majnemer3b3bdb52014-05-06 22:49:16 +00003634
3635 for (; SeqID != 0; SeqID /= 36) {
3636 unsigned C = SeqID % 36;
3637 *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
3638 }
3639
3640 Out.write(I.base(), I - BufferRef.rbegin());
3641 }
3642 Out << '_';
3643}
3644
Guy Benyei11169dd2012-12-18 14:30:41 +00003645void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3646 bool result = mangleSubstitution(type);
3647 assert(result && "no existing substitution for type");
3648 (void) result;
3649}
3650
3651void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3652 bool result = mangleSubstitution(tname);
3653 assert(result && "no existing substitution for template name");
3654 (void) result;
3655}
3656
3657// <substitution> ::= S <seq-id> _
3658// ::= S_
3659bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3660 // Try one of the standard substitutions first.
3661 if (mangleStandardSubstitution(ND))
3662 return true;
3663
3664 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3665 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3666}
3667
3668/// \brief Determine whether the given type has any qualifiers that are
3669/// relevant for substitutions.
3670static bool hasMangledSubstitutionQualifiers(QualType T) {
3671 Qualifiers Qs = T.getQualifiers();
3672 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3673}
3674
3675bool CXXNameMangler::mangleSubstitution(QualType T) {
3676 if (!hasMangledSubstitutionQualifiers(T)) {
3677 if (const RecordType *RT = T->getAs<RecordType>())
3678 return mangleSubstitution(RT->getDecl());
3679 }
3680
3681 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3682
3683 return mangleSubstitution(TypePtr);
3684}
3685
3686bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3687 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3688 return mangleSubstitution(TD);
3689
3690 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3691 return mangleSubstitution(
3692 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3693}
3694
3695bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3696 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3697 if (I == Substitutions.end())
3698 return false;
3699
3700 unsigned SeqID = I->second;
David Majnemer3b3bdb52014-05-06 22:49:16 +00003701 Out << 'S';
3702 mangleSeqID(SeqID);
Guy Benyei11169dd2012-12-18 14:30:41 +00003703
3704 return true;
3705}
3706
3707static bool isCharType(QualType T) {
3708 if (T.isNull())
3709 return false;
3710
3711 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3712 T->isSpecificBuiltinType(BuiltinType::Char_U);
3713}
3714
3715/// isCharSpecialization - Returns whether a given type is a template
3716/// specialization of a given name with a single argument of type char.
3717static bool isCharSpecialization(QualType T, const char *Name) {
3718 if (T.isNull())
3719 return false;
3720
3721 const RecordType *RT = T->getAs<RecordType>();
3722 if (!RT)
3723 return false;
3724
3725 const ClassTemplateSpecializationDecl *SD =
3726 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3727 if (!SD)
3728 return false;
3729
3730 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3731 return false;
3732
3733 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3734 if (TemplateArgs.size() != 1)
3735 return false;
3736
3737 if (!isCharType(TemplateArgs[0].getAsType()))
3738 return false;
3739
3740 return SD->getIdentifier()->getName() == Name;
3741}
3742
3743template <std::size_t StrLen>
3744static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3745 const char (&Str)[StrLen]) {
3746 if (!SD->getIdentifier()->isStr(Str))
3747 return false;
3748
3749 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3750 if (TemplateArgs.size() != 2)
3751 return false;
3752
3753 if (!isCharType(TemplateArgs[0].getAsType()))
3754 return false;
3755
3756 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3757 return false;
3758
3759 return true;
3760}
3761
3762bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3763 // <substitution> ::= St # ::std::
3764 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3765 if (isStd(NS)) {
3766 Out << "St";
3767 return true;
3768 }
3769 }
3770
3771 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3772 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3773 return false;
3774
3775 // <substitution> ::= Sa # ::std::allocator
3776 if (TD->getIdentifier()->isStr("allocator")) {
3777 Out << "Sa";
3778 return true;
3779 }
3780
3781 // <<substitution> ::= Sb # ::std::basic_string
3782 if (TD->getIdentifier()->isStr("basic_string")) {
3783 Out << "Sb";
3784 return true;
3785 }
3786 }
3787
3788 if (const ClassTemplateSpecializationDecl *SD =
3789 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3790 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3791 return false;
3792
3793 // <substitution> ::= Ss # ::std::basic_string<char,
3794 // ::std::char_traits<char>,
3795 // ::std::allocator<char> >
3796 if (SD->getIdentifier()->isStr("basic_string")) {
3797 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3798
3799 if (TemplateArgs.size() != 3)
3800 return false;
3801
3802 if (!isCharType(TemplateArgs[0].getAsType()))
3803 return false;
3804
3805 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3806 return false;
3807
3808 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3809 return false;
3810
3811 Out << "Ss";
3812 return true;
3813 }
3814
3815 // <substitution> ::= Si # ::std::basic_istream<char,
3816 // ::std::char_traits<char> >
3817 if (isStreamCharSpecialization(SD, "basic_istream")) {
3818 Out << "Si";
3819 return true;
3820 }
3821
3822 // <substitution> ::= So # ::std::basic_ostream<char,
3823 // ::std::char_traits<char> >
3824 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3825 Out << "So";
3826 return true;
3827 }
3828
3829 // <substitution> ::= Sd # ::std::basic_iostream<char,
3830 // ::std::char_traits<char> >
3831 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3832 Out << "Sd";
3833 return true;
3834 }
3835 }
3836 return false;
3837}
3838
3839void CXXNameMangler::addSubstitution(QualType T) {
3840 if (!hasMangledSubstitutionQualifiers(T)) {
3841 if (const RecordType *RT = T->getAs<RecordType>()) {
3842 addSubstitution(RT->getDecl());
3843 return;
3844 }
3845 }
3846
3847 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3848 addSubstitution(TypePtr);
3849}
3850
3851void CXXNameMangler::addSubstitution(TemplateName Template) {
3852 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3853 return addSubstitution(TD);
3854
3855 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3856 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3857}
3858
3859void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3860 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3861 Substitutions[Ptr] = SeqID++;
3862}
3863
3864//
3865
3866/// \brief Mangles the name of the declaration D and emits that name to the
3867/// given output stream.
3868///
3869/// If the declaration D requires a mangled name, this routine will emit that
3870/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3871/// and this routine will return false. In this case, the caller should just
3872/// emit the identifier of the declaration (\c D->getIdentifier()) as its
3873/// name.
Rafael Espindola002667c2013-10-16 01:40:34 +00003874void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
3875 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003876 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3877 "Invalid mangleName() call, argument is not a variable or function!");
3878 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3879 "Invalid mangleName() call on 'structor decl!");
3880
3881 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3882 getASTContext().getSourceManager(),
3883 "Mangling declaration");
3884
3885 CXXNameMangler Mangler(*this, Out, D);
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00003886 Mangler.mangle(D);
Guy Benyei11169dd2012-12-18 14:30:41 +00003887}
3888
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003889void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3890 CXXCtorType Type,
3891 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003892 CXXNameMangler Mangler(*this, Out, D, Type);
3893 Mangler.mangle(D);
3894}
3895
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003896void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3897 CXXDtorType Type,
3898 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003899 CXXNameMangler Mangler(*this, Out, D, Type);
3900 Mangler.mangle(D);
3901}
3902
Rafael Espindola1e4df922014-09-16 15:18:21 +00003903void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
3904 raw_ostream &Out) {
3905 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
3906 Mangler.mangle(D);
3907}
3908
3909void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
3910 raw_ostream &Out) {
3911 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
3912 Mangler.mangle(D);
3913}
3914
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003915void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3916 const ThunkInfo &Thunk,
3917 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003918 // <special-name> ::= T <call-offset> <base encoding>
3919 // # base is the nominal target function of thunk
3920 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3921 // # base is the nominal target function of thunk
3922 // # first call-offset is 'this' adjustment
3923 // # second call-offset is result adjustment
3924
3925 assert(!isa<CXXDestructorDecl>(MD) &&
3926 "Use mangleCXXDtor for destructor decls!");
3927 CXXNameMangler Mangler(*this, Out);
3928 Mangler.getStream() << "_ZT";
3929 if (!Thunk.Return.isEmpty())
3930 Mangler.getStream() << 'c';
3931
3932 // Mangle the 'this' pointer adjustment.
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003933 Mangler.mangleCallOffset(Thunk.This.NonVirtual,
3934 Thunk.This.Virtual.Itanium.VCallOffsetOffset);
3935
Guy Benyei11169dd2012-12-18 14:30:41 +00003936 // Mangle the return pointer adjustment if there is one.
3937 if (!Thunk.Return.isEmpty())
3938 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
Timur Iskhodzhanov02014322013-10-30 11:55:43 +00003939 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
3940
Guy Benyei11169dd2012-12-18 14:30:41 +00003941 Mangler.mangleFunctionEncoding(MD);
3942}
3943
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003944void ItaniumMangleContextImpl::mangleCXXDtorThunk(
3945 const CXXDestructorDecl *DD, CXXDtorType Type,
3946 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003947 // <special-name> ::= T <call-offset> <base encoding>
3948 // # base is the nominal target function of thunk
3949 CXXNameMangler Mangler(*this, Out, DD, Type);
3950 Mangler.getStream() << "_ZT";
3951
3952 // Mangle the 'this' pointer adjustment.
3953 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00003954 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
Guy Benyei11169dd2012-12-18 14:30:41 +00003955
3956 Mangler.mangleFunctionEncoding(DD);
3957}
3958
3959/// mangleGuardVariable - Returns the mangled name for a guard variable
3960/// for the passed in VarDecl.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003961void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
3962 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00003963 // <special-name> ::= GV <object name> # Guard variable for one-time
3964 // # initialization
3965 CXXNameMangler Mangler(*this, Out);
3966 Mangler.getStream() << "_ZGV";
3967 Mangler.mangleName(D);
3968}
3969
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003970void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
3971 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00003972 // These symbols are internal in the Itanium ABI, so the names don't matter.
3973 // Clang has traditionally used this symbol and allowed LLVM to adjust it to
3974 // avoid duplicate symbols.
3975 Out << "__cxx_global_var_init";
3976}
3977
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003978void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3979 raw_ostream &Out) {
Reid Klecknerd8110b62013-09-10 20:14:30 +00003980 // Prefix the mangling of D with __dtor_.
3981 CXXNameMangler Mangler(*this, Out);
3982 Mangler.getStream() << "__dtor_";
3983 if (shouldMangleDeclName(D))
3984 Mangler.mangle(D);
3985 else
3986 Mangler.getStream() << D->getName();
3987}
3988
Reid Kleckner1d59f992015-01-22 01:36:17 +00003989void ItaniumMangleContextImpl::mangleSEHFilterExpression(
3990 const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3991 CXXNameMangler Mangler(*this, Out);
3992 Mangler.getStream() << "__filt_";
3993 if (shouldMangleDeclName(EnclosingDecl))
3994 Mangler.mangle(EnclosingDecl);
3995 else
3996 Mangler.getStream() << EnclosingDecl->getName();
3997}
3998
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00003999void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4000 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004001 // <special-name> ::= TH <object name>
4002 CXXNameMangler Mangler(*this, Out);
4003 Mangler.getStream() << "_ZTH";
4004 Mangler.mangleName(D);
4005}
4006
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004007void
4008ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4009 raw_ostream &Out) {
Richard Smith2fd1d7a2013-04-19 16:42:07 +00004010 // <special-name> ::= TW <object name>
4011 CXXNameMangler Mangler(*this, Out);
4012 Mangler.getStream() << "_ZTW";
4013 Mangler.mangleName(D);
4014}
4015
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004016void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
David Majnemerdaff3702014-05-01 17:50:17 +00004017 unsigned ManglingNumber,
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004018 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004019 // We match the GCC mangling here.
4020 // <special-name> ::= GR <object name>
4021 CXXNameMangler Mangler(*this, Out);
4022 Mangler.getStream() << "_ZGR";
4023 Mangler.mangleName(D);
David Majnemerdaff3702014-05-01 17:50:17 +00004024 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
David Majnemer3b3bdb52014-05-06 22:49:16 +00004025 Mangler.mangleSeqID(ManglingNumber - 1);
Guy Benyei11169dd2012-12-18 14:30:41 +00004026}
4027
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004028void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4029 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004030 // <special-name> ::= TV <type> # virtual table
4031 CXXNameMangler Mangler(*this, Out);
4032 Mangler.getStream() << "_ZTV";
4033 Mangler.mangleNameOrStandardSubstitution(RD);
4034}
4035
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004036void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4037 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004038 // <special-name> ::= TT <type> # VTT structure
4039 CXXNameMangler Mangler(*this, Out);
4040 Mangler.getStream() << "_ZTT";
4041 Mangler.mangleNameOrStandardSubstitution(RD);
4042}
4043
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004044void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4045 int64_t Offset,
4046 const CXXRecordDecl *Type,
4047 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004048 // <special-name> ::= TC <type> <offset number> _ <base type>
4049 CXXNameMangler Mangler(*this, Out);
4050 Mangler.getStream() << "_ZTC";
4051 Mangler.mangleNameOrStandardSubstitution(RD);
4052 Mangler.getStream() << Offset;
4053 Mangler.getStream() << '_';
4054 Mangler.mangleNameOrStandardSubstitution(Type);
4055}
4056
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004057void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004058 // <special-name> ::= TI <type> # typeinfo structure
4059 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4060 CXXNameMangler Mangler(*this, Out);
4061 Mangler.getStream() << "_ZTI";
4062 Mangler.mangleType(Ty);
4063}
4064
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004065void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4066 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00004067 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
4068 CXXNameMangler Mangler(*this, Out);
4069 Mangler.getStream() << "_ZTS";
4070 Mangler.mangleType(Ty);
4071}
4072
Reid Klecknercc99e262013-11-19 23:23:00 +00004073void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4074 mangleCXXRTTIName(Ty, Out);
4075}
4076
David Majnemer58e5bee2014-03-24 21:43:36 +00004077void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4078 llvm_unreachable("Can't mangle string literals");
4079}
4080
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00004081ItaniumMangleContext *
4082ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4083 return new ItaniumMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00004084}
Evgeny Astigeevich665027d2014-12-12 16:17:46 +00004085