blob: 1d8a311c6145c7b9f57b29d4c50013662f661aad [file] [log] [blame]
Guy Benyei7f92f2d2012-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//
14// http://www.codesourcery.com/public/cxx-abi/abi.html
15//
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"
24#include "clang/AST/ExprCXX.h"
25#include "clang/AST/ExprObjC.h"
26#include "clang/AST/TypeLoc.h"
27#include "clang/Basic/ABI.h"
28#include "clang/Basic/SourceManager.h"
29#include "clang/Basic/TargetInfo.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/Support/ErrorHandling.h"
32#include "llvm/Support/raw_ostream.h"
33
34#define MANGLE_CHECKER 0
35
36#if MANGLE_CHECKER
37#include <cxxabi.h>
38#endif
39
40using namespace clang;
41
42namespace {
43
44/// \brief Retrieve the declaration context that should be used when mangling
45/// the given declaration.
46static const DeclContext *getEffectiveDeclContext(const Decl *D) {
47 // The ABI assumes that lambda closure types that occur within
48 // default arguments live in the context of the function. However, due to
49 // the way in which Clang parses and creates function declarations, this is
50 // not the case: the lambda closure type ends up living in the context
51 // where the function itself resides, because the function declaration itself
52 // had not yet been created. Fix the context here.
53 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
54 if (RD->isLambda())
55 if (ParmVarDecl *ContextParam
56 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
57 return ContextParam->getDeclContext();
58 }
Eli Friedmane79c9872013-07-10 01:33:19 +000059
60 // Perform the same check for block literals.
61 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
62 if (ParmVarDecl *ContextParam
63 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
64 return ContextParam->getDeclContext();
65 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +000066
Eli Friedman84431882013-07-02 17:52:28 +000067 const DeclContext *DC = D->getDeclContext();
68 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
69 return getEffectiveDeclContext(CD);
70
71 return DC;
Guy Benyei7f92f2d2012-12-18 14:30:41 +000072}
73
74static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
75 return getEffectiveDeclContext(cast<Decl>(DC));
76}
Eli Friedman84431882013-07-02 17:52:28 +000077
78static bool isLocalContainerContext(const DeclContext *DC) {
79 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
80}
81
Eli Friedman1847c712013-07-05 20:27:40 +000082static const RecordDecl *GetLocalClassDecl(const Decl *D) {
Eli Friedman1cf7c3f2013-07-02 02:01:18 +000083 const DeclContext *DC = getEffectiveDeclContext(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +000084 while (!DC->isNamespace() && !DC->isTranslationUnit()) {
Eli Friedman84431882013-07-02 17:52:28 +000085 if (isLocalContainerContext(DC))
Eli Friedman1847c712013-07-05 20:27:40 +000086 return dyn_cast<RecordDecl>(D);
Eli Friedman1cf7c3f2013-07-02 02:01:18 +000087 D = cast<Decl>(DC);
88 DC = getEffectiveDeclContext(D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +000089 }
90 return 0;
91}
92
93static const FunctionDecl *getStructor(const FunctionDecl *fn) {
94 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
95 return ftd->getTemplatedDecl();
96
97 return fn;
98}
99
100static const NamedDecl *getStructor(const NamedDecl *decl) {
101 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
102 return (fn ? getStructor(fn) : decl);
103}
104
105static const unsigned UnknownArity = ~0U;
106
107class ItaniumMangleContext : public MangleContext {
108 llvm::DenseMap<const TagDecl *, uint64_t> AnonStructIds;
Eli Friedman5e867c82013-07-10 00:30:46 +0000109 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
110 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000111 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
112
113public:
114 explicit ItaniumMangleContext(ASTContext &Context,
115 DiagnosticsEngine &Diags)
116 : MangleContext(Context, Diags) { }
117
118 uint64_t getAnonymousStructId(const TagDecl *TD) {
119 std::pair<llvm::DenseMap<const TagDecl *,
120 uint64_t>::iterator, bool> Result =
121 AnonStructIds.insert(std::make_pair(TD, AnonStructIds.size()));
122 return Result.first->second;
123 }
124
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000125 /// @name Mangler Entry Points
126 /// @{
127
128 bool shouldMangleDeclName(const NamedDecl *D);
129 void mangleName(const NamedDecl *D, raw_ostream &);
130 void mangleThunk(const CXXMethodDecl *MD,
131 const ThunkInfo &Thunk,
132 raw_ostream &);
133 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
134 const ThisAdjustment &ThisAdjustment,
135 raw_ostream &);
136 void mangleReferenceTemporary(const VarDecl *D,
137 raw_ostream &);
138 void mangleCXXVTable(const CXXRecordDecl *RD,
139 raw_ostream &);
140 void mangleCXXVTT(const CXXRecordDecl *RD,
141 raw_ostream &);
Reid Kleckner90633022013-06-19 15:20:38 +0000142 void mangleCXXVBTable(const CXXRecordDecl *Derived,
143 ArrayRef<const CXXRecordDecl *> BasePath,
144 raw_ostream &Out);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000145 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
146 const CXXRecordDecl *Type,
147 raw_ostream &);
148 void mangleCXXRTTI(QualType T, raw_ostream &);
149 void mangleCXXRTTIName(QualType T, raw_ostream &);
150 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
151 raw_ostream &);
152 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
153 raw_ostream &);
154
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000155 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &);
156 void mangleDynamicAtExitDestructor(const VarDecl *D, raw_ostream &Out);
Richard Smithb80a16e2013-04-19 16:42:07 +0000157 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &);
158 void mangleItaniumThreadLocalWrapper(const VarDecl *D, raw_ostream &);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000159
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000160 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
Eli Friedman5e867c82013-07-10 00:30:46 +0000161 // Lambda closure types are already numbered.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000162 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(ND))
Eli Friedman5e867c82013-07-10 00:30:46 +0000163 if (RD->isLambda())
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000164 return false;
Eli Friedman5e867c82013-07-10 00:30:46 +0000165
166 // Anonymous tags are already numbered.
167 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
168 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
169 return false;
170 }
171
172 // Use the canonical number for externally visible decls.
173 if (ND->isExternallyVisible()) {
174 unsigned discriminator = getASTContext().getManglingNumber(ND);
175 if (discriminator == 1)
176 return false;
177 disc = discriminator - 2;
178 return true;
179 }
180
181 // Make up a reasonable number for internal decls.
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000182 unsigned &discriminator = Uniquifier[ND];
Eli Friedman5e867c82013-07-10 00:30:46 +0000183 if (!discriminator) {
184 const DeclContext *DC = getEffectiveDeclContext(ND);
185 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
186 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000187 if (discriminator == 1)
188 return false;
189 disc = discriminator-2;
190 return true;
191 }
192 /// @}
193};
194
195/// CXXNameMangler - Manage the mangling of a single name.
196class CXXNameMangler {
197 ItaniumMangleContext &Context;
198 raw_ostream &Out;
199
200 /// The "structor" is the top-level declaration being mangled, if
201 /// that's not a template specialization; otherwise it's the pattern
202 /// for that specialization.
203 const NamedDecl *Structor;
204 unsigned StructorType;
205
206 /// SeqID - The next subsitution sequence number.
207 unsigned SeqID;
208
209 class FunctionTypeDepthState {
210 unsigned Bits;
211
212 enum { InResultTypeMask = 1 };
213
214 public:
215 FunctionTypeDepthState() : Bits(0) {}
216
217 /// The number of function types we're inside.
218 unsigned getDepth() const {
219 return Bits >> 1;
220 }
221
222 /// True if we're in the return type of the innermost function type.
223 bool isInResultType() const {
224 return Bits & InResultTypeMask;
225 }
226
227 FunctionTypeDepthState push() {
228 FunctionTypeDepthState tmp = *this;
229 Bits = (Bits & ~InResultTypeMask) + 2;
230 return tmp;
231 }
232
233 void enterResultType() {
234 Bits |= InResultTypeMask;
235 }
236
237 void leaveResultType() {
238 Bits &= ~InResultTypeMask;
239 }
240
241 void pop(FunctionTypeDepthState saved) {
242 assert(getDepth() == saved.getDepth() + 1);
243 Bits = saved.Bits;
244 }
245
246 } FunctionTypeDepth;
247
248 llvm::DenseMap<uintptr_t, unsigned> Substitutions;
249
250 ASTContext &getASTContext() const { return Context.getASTContext(); }
251
252public:
253 CXXNameMangler(ItaniumMangleContext &C, raw_ostream &Out_,
254 const NamedDecl *D = 0)
255 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0),
256 SeqID(0) {
257 // These can't be mangled without a ctor type or dtor type.
258 assert(!D || (!isa<CXXDestructorDecl>(D) &&
259 !isa<CXXConstructorDecl>(D)));
260 }
261 CXXNameMangler(ItaniumMangleContext &C, raw_ostream &Out_,
262 const CXXConstructorDecl *D, CXXCtorType Type)
263 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
264 SeqID(0) { }
265 CXXNameMangler(ItaniumMangleContext &C, raw_ostream &Out_,
266 const CXXDestructorDecl *D, CXXDtorType Type)
267 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
268 SeqID(0) { }
269
270#if MANGLE_CHECKER
271 ~CXXNameMangler() {
272 if (Out.str()[0] == '\01')
273 return;
274
275 int status = 0;
276 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
277 assert(status == 0 && "Could not demangle mangled name!");
278 free(result);
279 }
280#endif
281 raw_ostream &getStream() { return Out; }
282
283 void mangle(const NamedDecl *D, StringRef Prefix = "_Z");
284 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
285 void mangleNumber(const llvm::APSInt &I);
286 void mangleNumber(int64_t Number);
287 void mangleFloat(const llvm::APFloat &F);
288 void mangleFunctionEncoding(const FunctionDecl *FD);
289 void mangleName(const NamedDecl *ND);
290 void mangleType(QualType T);
291 void mangleNameOrStandardSubstitution(const NamedDecl *ND);
292
293private:
294 bool mangleSubstitution(const NamedDecl *ND);
295 bool mangleSubstitution(QualType T);
296 bool mangleSubstitution(TemplateName Template);
297 bool mangleSubstitution(uintptr_t Ptr);
298
299 void mangleExistingSubstitution(QualType type);
300 void mangleExistingSubstitution(TemplateName name);
301
302 bool mangleStandardSubstitution(const NamedDecl *ND);
303
304 void addSubstitution(const NamedDecl *ND) {
305 ND = cast<NamedDecl>(ND->getCanonicalDecl());
306
307 addSubstitution(reinterpret_cast<uintptr_t>(ND));
308 }
309 void addSubstitution(QualType T);
310 void addSubstitution(TemplateName Template);
311 void addSubstitution(uintptr_t Ptr);
312
313 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
314 NamedDecl *firstQualifierLookup,
315 bool recursive = false);
316 void mangleUnresolvedName(NestedNameSpecifier *qualifier,
317 NamedDecl *firstQualifierLookup,
318 DeclarationName name,
319 unsigned KnownArity = UnknownArity);
320
321 void mangleName(const TemplateDecl *TD,
322 const TemplateArgument *TemplateArgs,
323 unsigned NumTemplateArgs);
324 void mangleUnqualifiedName(const NamedDecl *ND) {
325 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity);
326 }
327 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
328 unsigned KnownArity);
329 void mangleUnscopedName(const NamedDecl *ND);
330 void mangleUnscopedTemplateName(const TemplateDecl *ND);
331 void mangleUnscopedTemplateName(TemplateName);
332 void mangleSourceName(const IdentifierInfo *II);
Eli Friedman84431882013-07-02 17:52:28 +0000333 void mangleLocalName(const Decl *D);
334 void mangleBlockForPrefix(const BlockDecl *Block);
335 void mangleUnqualifiedBlock(const BlockDecl *Block);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000336 void mangleLambda(const CXXRecordDecl *Lambda);
337 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
338 bool NoFunction=false);
339 void mangleNestedName(const TemplateDecl *TD,
340 const TemplateArgument *TemplateArgs,
341 unsigned NumTemplateArgs);
342 void manglePrefix(NestedNameSpecifier *qualifier);
343 void manglePrefix(const DeclContext *DC, bool NoFunction=false);
344 void manglePrefix(QualType type);
Eli Friedman88922102013-07-05 18:41:30 +0000345 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000346 void mangleTemplatePrefix(TemplateName Template);
347 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
348 void mangleQualifiers(Qualifiers Quals);
349 void mangleRefQualifier(RefQualifierKind RefQualifier);
350
351 void mangleObjCMethodName(const ObjCMethodDecl *MD);
352
353 // Declare manglers for every type class.
354#define ABSTRACT_TYPE(CLASS, PARENT)
355#define NON_CANONICAL_TYPE(CLASS, PARENT)
356#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
357#include "clang/AST/TypeNodes.def"
358
359 void mangleType(const TagType*);
360 void mangleType(TemplateName);
361 void mangleBareFunctionType(const FunctionType *T,
362 bool MangleReturnType);
363 void mangleNeonVectorType(const VectorType *T);
Tim Northoverb793f0d2013-08-01 09:23:19 +0000364 void mangleAArch64NeonVectorType(const VectorType *T);
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000365
366 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
367 void mangleMemberExpr(const Expr *base, bool isArrow,
368 NestedNameSpecifier *qualifier,
369 NamedDecl *firstQualifierLookup,
370 DeclarationName name,
371 unsigned knownArity);
372 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
373 void mangleCXXCtorType(CXXCtorType T);
374 void mangleCXXDtorType(CXXDtorType T);
375
376 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs);
377 void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
378 unsigned NumTemplateArgs);
379 void mangleTemplateArgs(const TemplateArgumentList &AL);
380 void mangleTemplateArg(TemplateArgument A);
381
382 void mangleTemplateParameter(unsigned Index);
383
384 void mangleFunctionParam(const ParmVarDecl *parm);
385};
386
387}
388
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000389bool ItaniumMangleContext::shouldMangleDeclName(const NamedDecl *D) {
390 // In C, functions with no attributes never need to be mangled. Fastpath them.
391 if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
392 return false;
393
394 // Any decl can be declared with __asm("foo") on it, and this takes precedence
395 // over all other naming in the .o file.
396 if (D->hasAttr<AsmLabelAttr>())
397 return true;
398
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000399 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000400 if (FD) {
401 LanguageLinkage L = FD->getLanguageLinkage();
402 // Overloadable functions need mangling.
403 if (FD->hasAttr<OverloadableAttr>())
404 return true;
405
Rafael Espindola83dece52013-02-14 15:38:59 +0000406 // "main" is not mangled.
407 if (FD->isMain())
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000408 return false;
409
410 // C++ functions and those whose names are not a simple identifier need
411 // mangling.
412 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
413 return true;
Rafael Espindola747836e2013-02-14 03:31:26 +0000414
Rafael Espindola83dece52013-02-14 15:38:59 +0000415 // C functions are not mangled.
416 if (L == CLanguageLinkage)
417 return false;
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000418 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000419
420 // Otherwise, no mangling is done outside C++ mode.
421 if (!getASTContext().getLangOpts().CPlusPlus)
422 return false;
423
Rafael Espindolad2fdd422013-02-14 01:47:04 +0000424 const VarDecl *VD = dyn_cast<VarDecl>(D);
425 if (VD) {
426 // C variables are not mangled.
427 if (VD->isExternC())
428 return false;
429
430 // Variables at global scope with non-internal linkage are not mangled
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000431 const DeclContext *DC = getEffectiveDeclContext(D);
432 // Check for extern variable declared locally.
433 if (DC->isFunctionOrMethod() && D->hasLinkage())
434 while (!DC->isNamespace() && !DC->isTranslationUnit())
435 DC = getEffectiveParentContext(DC);
Larisse Voufoef4579c2013-08-06 01:03:05 +0000436 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
437 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000438 return false;
439 }
440
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000441 return true;
442}
443
444void CXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
445 // Any decl can be declared with __asm("foo") on it, and this takes precedence
446 // over all other naming in the .o file.
447 if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
448 // If we have an asm name, then we use it as the mangling.
449
450 // Adding the prefix can cause problems when one file has a "foo" and
451 // another has a "\01foo". That is known to happen on ELF with the
452 // tricks normally used for producing aliases (PR9177). Fortunately the
453 // llvm mangler on ELF is a nop, so we can just avoid adding the \01
454 // marker. We also avoid adding the marker if this is an alias for an
455 // LLVM intrinsic.
456 StringRef UserLabelPrefix =
457 getASTContext().getTargetInfo().getUserLabelPrefix();
458 if (!UserLabelPrefix.empty() && !ALA->getLabel().startswith("llvm."))
459 Out << '\01'; // LLVM IR Marker for __asm("foo")
460
461 Out << ALA->getLabel();
462 return;
463 }
464
465 // <mangled-name> ::= _Z <encoding>
466 // ::= <data name>
467 // ::= <special-name>
468 Out << Prefix;
469 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
470 mangleFunctionEncoding(FD);
471 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
472 mangleName(VD);
473 else
474 mangleName(cast<FieldDecl>(D));
475}
476
477void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
478 // <encoding> ::= <function name> <bare-function-type>
479 mangleName(FD);
480
481 // Don't mangle in the type if this isn't a decl we should typically mangle.
482 if (!Context.shouldMangleDeclName(FD))
483 return;
484
485 // Whether the mangling of a function type includes the return type depends on
486 // the context and the nature of the function. The rules for deciding whether
487 // the return type is included are:
488 //
489 // 1. Template functions (names or types) have return types encoded, with
490 // the exceptions listed below.
491 // 2. Function types not appearing as part of a function name mangling,
492 // e.g. parameters, pointer types, etc., have return type encoded, with the
493 // exceptions listed below.
494 // 3. Non-template function names do not have return types encoded.
495 //
496 // The exceptions mentioned in (1) and (2) above, for which the return type is
497 // never included, are
498 // 1. Constructors.
499 // 2. Destructors.
500 // 3. Conversion operator functions, e.g. operator int.
501 bool MangleReturnType = false;
502 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
503 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
504 isa<CXXConversionDecl>(FD)))
505 MangleReturnType = true;
506
507 // Mangle the type of the primary template.
508 FD = PrimaryTemplate->getTemplatedDecl();
509 }
510
511 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(),
512 MangleReturnType);
513}
514
515static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
516 while (isa<LinkageSpecDecl>(DC)) {
517 DC = getEffectiveParentContext(DC);
518 }
519
520 return DC;
521}
522
523/// isStd - Return whether a given namespace is the 'std' namespace.
524static bool isStd(const NamespaceDecl *NS) {
525 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
526 ->isTranslationUnit())
527 return false;
528
529 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
530 return II && II->isStr("std");
531}
532
533// isStdNamespace - Return whether a given decl context is a toplevel 'std'
534// namespace.
535static bool isStdNamespace(const DeclContext *DC) {
536 if (!DC->isNamespace())
537 return false;
538
539 return isStd(cast<NamespaceDecl>(DC));
540}
541
542static const TemplateDecl *
543isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
544 // Check if we have a function template.
545 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
546 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
547 TemplateArgs = FD->getTemplateSpecializationArgs();
548 return TD;
549 }
550 }
551
552 // Check if we have a class template.
553 if (const ClassTemplateSpecializationDecl *Spec =
554 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
555 TemplateArgs = &Spec->getTemplateArgs();
556 return Spec->getSpecializedTemplate();
557 }
558
Larisse Voufoef4579c2013-08-06 01:03:05 +0000559 // Check if we have a variable template.
560 if (const VarTemplateSpecializationDecl *Spec =
561 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
562 TemplateArgs = &Spec->getTemplateArgs();
563 return Spec->getSpecializedTemplate();
564 }
565
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000566 return 0;
567}
568
569static bool isLambda(const NamedDecl *ND) {
570 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
571 if (!Record)
572 return false;
573
574 return Record->isLambda();
575}
576
577void CXXNameMangler::mangleName(const NamedDecl *ND) {
578 // <name> ::= <nested-name>
579 // ::= <unscoped-name>
580 // ::= <unscoped-template-name> <template-args>
581 // ::= <local-name>
582 //
583 const DeclContext *DC = getEffectiveDeclContext(ND);
584
585 // If this is an extern variable declared locally, the relevant DeclContext
586 // is that of the containing namespace, or the translation unit.
587 // FIXME: This is a hack; extern variables declared locally should have
588 // a proper semantic declaration context!
Eli Friedman84431882013-07-02 17:52:28 +0000589 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000590 while (!DC->isNamespace() && !DC->isTranslationUnit())
591 DC = getEffectiveParentContext(DC);
592 else if (GetLocalClassDecl(ND)) {
593 mangleLocalName(ND);
594 return;
595 }
596
597 DC = IgnoreLinkageSpecDecls(DC);
598
599 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
600 // Check if we have a template.
601 const TemplateArgumentList *TemplateArgs = 0;
602 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
603 mangleUnscopedTemplateName(TD);
604 mangleTemplateArgs(*TemplateArgs);
605 return;
606 }
607
608 mangleUnscopedName(ND);
609 return;
610 }
611
Eli Friedman84431882013-07-02 17:52:28 +0000612 if (isLocalContainerContext(DC)) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000613 mangleLocalName(ND);
614 return;
615 }
616
617 mangleNestedName(ND, DC);
618}
619void CXXNameMangler::mangleName(const TemplateDecl *TD,
620 const TemplateArgument *TemplateArgs,
621 unsigned NumTemplateArgs) {
622 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
623
624 if (DC->isTranslationUnit() || isStdNamespace(DC)) {
625 mangleUnscopedTemplateName(TD);
626 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
627 } else {
628 mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
629 }
630}
631
632void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) {
633 // <unscoped-name> ::= <unqualified-name>
634 // ::= St <unqualified-name> # ::std::
635
636 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
637 Out << "St";
638
639 mangleUnqualifiedName(ND);
640}
641
642void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) {
643 // <unscoped-template-name> ::= <unscoped-name>
644 // ::= <substitution>
645 if (mangleSubstitution(ND))
646 return;
647
648 // <template-template-param> ::= <template-param>
649 if (const TemplateTemplateParmDecl *TTP
650 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
651 mangleTemplateParameter(TTP->getIndex());
652 return;
653 }
654
655 mangleUnscopedName(ND->getTemplatedDecl());
656 addSubstitution(ND);
657}
658
659void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) {
660 // <unscoped-template-name> ::= <unscoped-name>
661 // ::= <substitution>
662 if (TemplateDecl *TD = Template.getAsTemplateDecl())
663 return mangleUnscopedTemplateName(TD);
664
665 if (mangleSubstitution(Template))
666 return;
667
668 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
669 assert(Dependent && "Not a dependent template name?");
670 if (const IdentifierInfo *Id = Dependent->getIdentifier())
671 mangleSourceName(Id);
672 else
673 mangleOperatorName(Dependent->getOperator(), UnknownArity);
674
675 addSubstitution(Template);
676}
677
678void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
679 // ABI:
680 // Floating-point literals are encoded using a fixed-length
681 // lowercase hexadecimal string corresponding to the internal
682 // representation (IEEE on Itanium), high-order bytes first,
683 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
684 // on Itanium.
685 // The 'without leading zeroes' thing seems to be an editorial
686 // mistake; see the discussion on cxx-abi-dev beginning on
687 // 2012-01-16.
688
689 // Our requirements here are just barely weird enough to justify
690 // using a custom algorithm instead of post-processing APInt::toString().
691
692 llvm::APInt valueBits = f.bitcastToAPInt();
693 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
694 assert(numCharacters != 0);
695
696 // Allocate a buffer of the right number of characters.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000697 SmallVector<char, 20> buffer;
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000698 buffer.set_size(numCharacters);
699
700 // Fill the buffer left-to-right.
701 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
702 // The bit-index of the next hex digit.
703 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
704
705 // Project out 4 bits starting at 'digitIndex'.
706 llvm::integerPart hexDigit
707 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
708 hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
709 hexDigit &= 0xF;
710
711 // Map that over to a lowercase hex digit.
712 static const char charForHex[16] = {
713 '0', '1', '2', '3', '4', '5', '6', '7',
714 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
715 };
716 buffer[stringIndex] = charForHex[hexDigit];
717 }
718
719 Out.write(buffer.data(), numCharacters);
720}
721
722void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
723 if (Value.isSigned() && Value.isNegative()) {
724 Out << 'n';
725 Value.abs().print(Out, /*signed*/ false);
726 } else {
727 Value.print(Out, /*signed*/ false);
728 }
729}
730
731void CXXNameMangler::mangleNumber(int64_t Number) {
732 // <number> ::= [n] <non-negative decimal integer>
733 if (Number < 0) {
734 Out << 'n';
735 Number = -Number;
736 }
737
738 Out << Number;
739}
740
741void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
742 // <call-offset> ::= h <nv-offset> _
743 // ::= v <v-offset> _
744 // <nv-offset> ::= <offset number> # non-virtual base override
745 // <v-offset> ::= <offset number> _ <virtual offset number>
746 // # virtual base override, with vcall offset
747 if (!Virtual) {
748 Out << 'h';
749 mangleNumber(NonVirtual);
750 Out << '_';
751 return;
752 }
753
754 Out << 'v';
755 mangleNumber(NonVirtual);
756 Out << '_';
757 mangleNumber(Virtual);
758 Out << '_';
759}
760
761void CXXNameMangler::manglePrefix(QualType type) {
762 if (const TemplateSpecializationType *TST =
763 type->getAs<TemplateSpecializationType>()) {
764 if (!mangleSubstitution(QualType(TST, 0))) {
765 mangleTemplatePrefix(TST->getTemplateName());
766
767 // FIXME: GCC does not appear to mangle the template arguments when
768 // the template in question is a dependent template name. Should we
769 // emulate that badness?
770 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
771 addSubstitution(QualType(TST, 0));
772 }
773 } else if (const DependentTemplateSpecializationType *DTST
774 = type->getAs<DependentTemplateSpecializationType>()) {
775 TemplateName Template
776 = getASTContext().getDependentTemplateName(DTST->getQualifier(),
777 DTST->getIdentifier());
778 mangleTemplatePrefix(Template);
779
780 // FIXME: GCC does not appear to mangle the template arguments when
781 // the template in question is a dependent template name. Should we
782 // emulate that badness?
783 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
784 } else {
785 // We use the QualType mangle type variant here because it handles
786 // substitutions.
787 mangleType(type);
788 }
789}
790
791/// Mangle everything prior to the base-unresolved-name in an unresolved-name.
792///
793/// \param firstQualifierLookup - the entity found by unqualified lookup
794/// for the first name in the qualifier, if this is for a member expression
795/// \param recursive - true if this is being called recursively,
796/// i.e. if there is more prefix "to the right".
797void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
798 NamedDecl *firstQualifierLookup,
799 bool recursive) {
800
801 // x, ::x
802 // <unresolved-name> ::= [gs] <base-unresolved-name>
803
804 // T::x / decltype(p)::x
805 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
806
807 // T::N::x /decltype(p)::N::x
808 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
809 // <base-unresolved-name>
810
811 // A::x, N::y, A<T>::z; "gs" means leading "::"
812 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
813 // <base-unresolved-name>
814
815 switch (qualifier->getKind()) {
816 case NestedNameSpecifier::Global:
817 Out << "gs";
818
819 // We want an 'sr' unless this is the entire NNS.
820 if (recursive)
821 Out << "sr";
822
823 // We never want an 'E' here.
824 return;
825
826 case NestedNameSpecifier::Namespace:
827 if (qualifier->getPrefix())
828 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
829 /*recursive*/ true);
830 else
831 Out << "sr";
832 mangleSourceName(qualifier->getAsNamespace()->getIdentifier());
833 break;
834 case NestedNameSpecifier::NamespaceAlias:
835 if (qualifier->getPrefix())
836 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
837 /*recursive*/ true);
838 else
839 Out << "sr";
840 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier());
841 break;
842
843 case NestedNameSpecifier::TypeSpec:
844 case NestedNameSpecifier::TypeSpecWithTemplate: {
845 const Type *type = qualifier->getAsType();
846
847 // We only want to use an unresolved-type encoding if this is one of:
848 // - a decltype
849 // - a template type parameter
850 // - a template template parameter with arguments
851 // In all of these cases, we should have no prefix.
852 if (qualifier->getPrefix()) {
853 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
854 /*recursive*/ true);
855 } else {
856 // Otherwise, all the cases want this.
857 Out << "sr";
858 }
859
860 // Only certain other types are valid as prefixes; enumerate them.
861 switch (type->getTypeClass()) {
862 case Type::Builtin:
863 case Type::Complex:
Reid Kleckner12df2462013-06-24 17:51:48 +0000864 case Type::Decayed:
Guy Benyei7f92f2d2012-12-18 14:30:41 +0000865 case Type::Pointer:
866 case Type::BlockPointer:
867 case Type::LValueReference:
868 case Type::RValueReference:
869 case Type::MemberPointer:
870 case Type::ConstantArray:
871 case Type::IncompleteArray:
872 case Type::VariableArray:
873 case Type::DependentSizedArray:
874 case Type::DependentSizedExtVector:
875 case Type::Vector:
876 case Type::ExtVector:
877 case Type::FunctionProto:
878 case Type::FunctionNoProto:
879 case Type::Enum:
880 case Type::Paren:
881 case Type::Elaborated:
882 case Type::Attributed:
883 case Type::Auto:
884 case Type::PackExpansion:
885 case Type::ObjCObject:
886 case Type::ObjCInterface:
887 case Type::ObjCObjectPointer:
888 case Type::Atomic:
889 llvm_unreachable("type is illegal as a nested name specifier");
890
891 case Type::SubstTemplateTypeParmPack:
892 // FIXME: not clear how to mangle this!
893 // template <class T...> class A {
894 // template <class U...> void foo(decltype(T::foo(U())) x...);
895 // };
896 Out << "_SUBSTPACK_";
897 break;
898
899 // <unresolved-type> ::= <template-param>
900 // ::= <decltype>
901 // ::= <template-template-param> <template-args>
902 // (this last is not official yet)
903 case Type::TypeOfExpr:
904 case Type::TypeOf:
905 case Type::Decltype:
906 case Type::TemplateTypeParm:
907 case Type::UnaryTransform:
908 case Type::SubstTemplateTypeParm:
909 unresolvedType:
910 assert(!qualifier->getPrefix());
911
912 // We only get here recursively if we're followed by identifiers.
913 if (recursive) Out << 'N';
914
915 // This seems to do everything we want. It's not really
916 // sanctioned for a substituted template parameter, though.
917 mangleType(QualType(type, 0));
918
919 // We never want to print 'E' directly after an unresolved-type,
920 // so we return directly.
921 return;
922
923 case Type::Typedef:
924 mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier());
925 break;
926
927 case Type::UnresolvedUsing:
928 mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl()
929 ->getIdentifier());
930 break;
931
932 case Type::Record:
933 mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier());
934 break;
935
936 case Type::TemplateSpecialization: {
937 const TemplateSpecializationType *tst
938 = cast<TemplateSpecializationType>(type);
939 TemplateName name = tst->getTemplateName();
940 switch (name.getKind()) {
941 case TemplateName::Template:
942 case TemplateName::QualifiedTemplate: {
943 TemplateDecl *temp = name.getAsTemplateDecl();
944
945 // If the base is a template template parameter, this is an
946 // unresolved type.
947 assert(temp && "no template for template specialization type");
948 if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType;
949
950 mangleSourceName(temp->getIdentifier());
951 break;
952 }
953
954 case TemplateName::OverloadedTemplate:
955 case TemplateName::DependentTemplate:
956 llvm_unreachable("invalid base for a template specialization type");
957
958 case TemplateName::SubstTemplateTemplateParm: {
959 SubstTemplateTemplateParmStorage *subst
960 = name.getAsSubstTemplateTemplateParm();
961 mangleExistingSubstitution(subst->getReplacement());
962 break;
963 }
964
965 case TemplateName::SubstTemplateTemplateParmPack: {
966 // FIXME: not clear how to mangle this!
967 // template <template <class U> class T...> class A {
968 // template <class U...> void foo(decltype(T<U>::foo) x...);
969 // };
970 Out << "_SUBSTPACK_";
971 break;
972 }
973 }
974
975 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
976 break;
977 }
978
979 case Type::InjectedClassName:
980 mangleSourceName(cast<InjectedClassNameType>(type)->getDecl()
981 ->getIdentifier());
982 break;
983
984 case Type::DependentName:
985 mangleSourceName(cast<DependentNameType>(type)->getIdentifier());
986 break;
987
988 case Type::DependentTemplateSpecialization: {
989 const DependentTemplateSpecializationType *tst
990 = cast<DependentTemplateSpecializationType>(type);
991 mangleSourceName(tst->getIdentifier());
992 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs());
993 break;
994 }
995 }
996 break;
997 }
998
999 case NestedNameSpecifier::Identifier:
1000 // Member expressions can have these without prefixes.
1001 if (qualifier->getPrefix()) {
1002 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup,
1003 /*recursive*/ true);
1004 } else if (firstQualifierLookup) {
1005
1006 // Try to make a proper qualifier out of the lookup result, and
1007 // then just recurse on that.
1008 NestedNameSpecifier *newQualifier;
1009 if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) {
1010 QualType type = getASTContext().getTypeDeclType(typeDecl);
1011
1012 // Pretend we had a different nested name specifier.
1013 newQualifier = NestedNameSpecifier::Create(getASTContext(),
1014 /*prefix*/ 0,
1015 /*template*/ false,
1016 type.getTypePtr());
1017 } else if (NamespaceDecl *nspace =
1018 dyn_cast<NamespaceDecl>(firstQualifierLookup)) {
1019 newQualifier = NestedNameSpecifier::Create(getASTContext(),
1020 /*prefix*/ 0,
1021 nspace);
1022 } else if (NamespaceAliasDecl *alias =
1023 dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) {
1024 newQualifier = NestedNameSpecifier::Create(getASTContext(),
1025 /*prefix*/ 0,
1026 alias);
1027 } else {
1028 // No sensible mangling to do here.
1029 newQualifier = 0;
1030 }
1031
1032 if (newQualifier)
1033 return mangleUnresolvedPrefix(newQualifier, /*lookup*/ 0, recursive);
1034
1035 } else {
1036 Out << "sr";
1037 }
1038
1039 mangleSourceName(qualifier->getAsIdentifier());
1040 break;
1041 }
1042
1043 // If this was the innermost part of the NNS, and we fell out to
1044 // here, append an 'E'.
1045 if (!recursive)
1046 Out << 'E';
1047}
1048
1049/// Mangle an unresolved-name, which is generally used for names which
1050/// weren't resolved to specific entities.
1051void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
1052 NamedDecl *firstQualifierLookup,
1053 DeclarationName name,
1054 unsigned knownArity) {
1055 if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup);
1056 mangleUnqualifiedName(0, name, knownArity);
1057}
1058
1059static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) {
1060 assert(RD->isAnonymousStructOrUnion() &&
1061 "Expected anonymous struct or union!");
1062
1063 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1064 I != E; ++I) {
1065 if (I->getIdentifier())
1066 return *I;
1067
1068 if (const RecordType *RT = I->getType()->getAs<RecordType>())
1069 if (const FieldDecl *NamedDataMember =
1070 FindFirstNamedDataMember(RT->getDecl()))
1071 return NamedDataMember;
1072 }
1073
1074 // We didn't find a named data member.
1075 return 0;
1076}
1077
1078void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1079 DeclarationName Name,
1080 unsigned KnownArity) {
1081 // <unqualified-name> ::= <operator-name>
1082 // ::= <ctor-dtor-name>
1083 // ::= <source-name>
1084 switch (Name.getNameKind()) {
1085 case DeclarationName::Identifier: {
1086 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1087 // We must avoid conflicts between internally- and externally-
1088 // linked variable and function declaration names in the same TU:
1089 // void test() { extern void foo(); }
1090 // static void foo();
1091 // This naming convention is the same as that followed by GCC,
1092 // though it shouldn't actually matter.
Rafael Espindola181e3ec2013-05-13 00:12:11 +00001093 if (ND && ND->getFormalLinkage() == InternalLinkage &&
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001094 getEffectiveDeclContext(ND)->isFileContext())
1095 Out << 'L';
1096
1097 mangleSourceName(II);
1098 break;
1099 }
1100
1101 // Otherwise, an anonymous entity. We must have a declaration.
1102 assert(ND && "mangling empty name without declaration");
1103
1104 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1105 if (NS->isAnonymousNamespace()) {
1106 // This is how gcc mangles these names.
1107 Out << "12_GLOBAL__N_1";
1108 break;
1109 }
1110 }
1111
1112 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1113 // We must have an anonymous union or struct declaration.
1114 const RecordDecl *RD =
1115 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
1116
1117 // Itanium C++ ABI 5.1.2:
1118 //
1119 // For the purposes of mangling, the name of an anonymous union is
1120 // considered to be the name of the first named data member found by a
1121 // pre-order, depth-first, declaration-order walk of the data members of
1122 // the anonymous union. If there is no such data member (i.e., if all of
1123 // the data members in the union are unnamed), then there is no way for
1124 // a program to refer to the anonymous union, and there is therefore no
1125 // need to mangle its name.
1126 const FieldDecl *FD = FindFirstNamedDataMember(RD);
1127
1128 // It's actually possible for various reasons for us to get here
1129 // with an empty anonymous struct / union. Fortunately, it
1130 // doesn't really matter what name we generate.
1131 if (!FD) break;
1132 assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1133
1134 mangleSourceName(FD->getIdentifier());
1135 break;
1136 }
John McCall0baaabb2013-04-10 06:08:21 +00001137
1138 // Class extensions have no name as a category, and it's possible
1139 // for them to be the semantic parent of certain declarations
1140 // (primarily, tag decls defined within declarations). Such
1141 // declarations will always have internal linkage, so the name
1142 // doesn't really matter, but we shouldn't crash on them. For
1143 // safety, just handle all ObjC containers here.
1144 if (isa<ObjCContainerDecl>(ND))
1145 break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001146
1147 // We must have an anonymous struct.
1148 const TagDecl *TD = cast<TagDecl>(ND);
1149 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1150 assert(TD->getDeclContext() == D->getDeclContext() &&
1151 "Typedef should not be in another decl context!");
1152 assert(D->getDeclName().getAsIdentifierInfo() &&
1153 "Typedef was not named!");
1154 mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1155 break;
1156 }
1157
1158 // <unnamed-type-name> ::= <closure-type-name>
1159 //
1160 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1161 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'.
1162 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1163 if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1164 mangleLambda(Record);
1165 break;
1166 }
1167 }
1168
Eli Friedman5e867c82013-07-10 00:30:46 +00001169 if (TD->isExternallyVisible()) {
1170 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001171 Out << "Ut";
Eli Friedman5e867c82013-07-10 00:30:46 +00001172 if (UnnamedMangle > 1)
1173 Out << llvm::utostr(UnnamedMangle - 2);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001174 Out << '_';
1175 break;
1176 }
1177
1178 // Get a unique id for the anonymous struct.
1179 uint64_t AnonStructId = Context.getAnonymousStructId(TD);
1180
1181 // Mangle it as a source name in the form
1182 // [n] $_<id>
1183 // where n is the length of the string.
1184 SmallString<8> Str;
1185 Str += "$_";
1186 Str += llvm::utostr(AnonStructId);
1187
1188 Out << Str.size();
1189 Out << Str.str();
1190 break;
1191 }
1192
1193 case DeclarationName::ObjCZeroArgSelector:
1194 case DeclarationName::ObjCOneArgSelector:
1195 case DeclarationName::ObjCMultiArgSelector:
1196 llvm_unreachable("Can't mangle Objective-C selector names here!");
1197
1198 case DeclarationName::CXXConstructorName:
1199 if (ND == Structor)
1200 // If the named decl is the C++ constructor we're mangling, use the type
1201 // we were given.
1202 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType));
1203 else
1204 // Otherwise, use the complete constructor name. This is relevant if a
1205 // class with a constructor is declared within a constructor.
1206 mangleCXXCtorType(Ctor_Complete);
1207 break;
1208
1209 case DeclarationName::CXXDestructorName:
1210 if (ND == Structor)
1211 // If the named decl is the C++ destructor we're mangling, use the type we
1212 // were given.
1213 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1214 else
1215 // Otherwise, use the complete destructor name. This is relevant if a
1216 // class with a destructor is declared within a destructor.
1217 mangleCXXDtorType(Dtor_Complete);
1218 break;
1219
1220 case DeclarationName::CXXConversionFunctionName:
1221 // <operator-name> ::= cv <type> # (cast)
1222 Out << "cv";
1223 mangleType(Name.getCXXNameType());
1224 break;
1225
1226 case DeclarationName::CXXOperatorName: {
1227 unsigned Arity;
1228 if (ND) {
1229 Arity = cast<FunctionDecl>(ND)->getNumParams();
1230
1231 // If we have a C++ member function, we need to include the 'this' pointer.
1232 // FIXME: This does not make sense for operators that are static, but their
1233 // names stay the same regardless of the arity (operator new for instance).
1234 if (isa<CXXMethodDecl>(ND))
1235 Arity++;
1236 } else
1237 Arity = KnownArity;
1238
1239 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1240 break;
1241 }
1242
1243 case DeclarationName::CXXLiteralOperatorName:
1244 // FIXME: This mangling is not yet official.
1245 Out << "li";
1246 mangleSourceName(Name.getCXXLiteralIdentifier());
1247 break;
1248
1249 case DeclarationName::CXXUsingDirective:
1250 llvm_unreachable("Can't mangle a using directive name!");
1251 }
1252}
1253
1254void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1255 // <source-name> ::= <positive length number> <identifier>
1256 // <number> ::= [n] <non-negative decimal integer>
1257 // <identifier> ::= <unqualified source code identifier>
1258 Out << II->getLength() << II->getName();
1259}
1260
1261void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1262 const DeclContext *DC,
1263 bool NoFunction) {
1264 // <nested-name>
1265 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1266 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
1267 // <template-args> E
1268
1269 Out << 'N';
1270 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1271 mangleQualifiers(Qualifiers::fromCVRMask(Method->getTypeQualifiers()));
1272 mangleRefQualifier(Method->getRefQualifier());
1273 }
1274
1275 // Check if we have a template.
1276 const TemplateArgumentList *TemplateArgs = 0;
1277 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Eli Friedman88922102013-07-05 18:41:30 +00001278 mangleTemplatePrefix(TD, NoFunction);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001279 mangleTemplateArgs(*TemplateArgs);
1280 }
1281 else {
1282 manglePrefix(DC, NoFunction);
1283 mangleUnqualifiedName(ND);
1284 }
1285
1286 Out << 'E';
1287}
1288void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1289 const TemplateArgument *TemplateArgs,
1290 unsigned NumTemplateArgs) {
1291 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1292
1293 Out << 'N';
1294
1295 mangleTemplatePrefix(TD);
1296 mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1297
1298 Out << 'E';
1299}
1300
Eli Friedman84431882013-07-02 17:52:28 +00001301void CXXNameMangler::mangleLocalName(const Decl *D) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001302 // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1303 // := Z <function encoding> E s [<discriminator>]
1304 // <local-name> := Z <function encoding> E d [ <parameter number> ]
1305 // _ <entity name>
1306 // <discriminator> := _ <non-negative number>
Eli Friedman84431882013-07-02 17:52:28 +00001307 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
Eli Friedman1847c712013-07-05 20:27:40 +00001308 const RecordDecl *RD = GetLocalClassDecl(D);
Eli Friedman84431882013-07-02 17:52:28 +00001309 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001310
1311 Out << 'Z';
1312
Eli Friedman1cf7c3f2013-07-02 02:01:18 +00001313 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1314 mangleObjCMethodName(MD);
1315 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
Eli Friedman84431882013-07-02 17:52:28 +00001316 mangleBlockForPrefix(BD);
Eli Friedman1cf7c3f2013-07-02 02:01:18 +00001317 else
1318 mangleFunctionEncoding(cast<FunctionDecl>(DC));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001319
Eli Friedman1cf7c3f2013-07-02 02:01:18 +00001320 Out << 'E';
1321
1322 if (RD) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001323 // The parameter number is omitted for the last parameter, 0 for the
1324 // second-to-last parameter, 1 for the third-to-last parameter, etc. The
1325 // <entity name> will of course contain a <closure-type-name>: Its
1326 // numbering will be local to the particular argument in which it appears
1327 // -- other default arguments do not affect its encoding.
Eli Friedman1847c712013-07-05 20:27:40 +00001328 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1329 if (CXXRD->isLambda()) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001330 if (const ParmVarDecl *Parm
Eli Friedman1847c712013-07-05 20:27:40 +00001331 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001332 if (const FunctionDecl *Func
1333 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1334 Out << 'd';
1335 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1336 if (Num > 1)
1337 mangleNumber(Num - 2);
1338 Out << '_';
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001339 }
1340 }
1341 }
1342
1343 // Mangle the name relative to the closest enclosing function.
Eli Friedman84431882013-07-02 17:52:28 +00001344 // equality ok because RD derived from ND above
1345 if (D == RD) {
1346 mangleUnqualifiedName(RD);
1347 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1348 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1349 mangleUnqualifiedBlock(BD);
1350 } else {
1351 const NamedDecl *ND = cast<NamedDecl>(D);
Eli Friedman1cf7c3f2013-07-02 02:01:18 +00001352 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/);
Eli Friedman84431882013-07-02 17:52:28 +00001353 }
Eli Friedmane79c9872013-07-10 01:33:19 +00001354 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1355 // Mangle a block in a default parameter; see above explanation for
1356 // lambdas.
1357 if (const ParmVarDecl *Parm
1358 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1359 if (const FunctionDecl *Func
1360 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1361 Out << 'd';
1362 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1363 if (Num > 1)
1364 mangleNumber(Num - 2);
1365 Out << '_';
1366 }
1367 }
1368
1369 mangleUnqualifiedBlock(BD);
Eli Friedman5e867c82013-07-10 00:30:46 +00001370 } else {
Eli Friedmane79c9872013-07-10 01:33:19 +00001371 mangleUnqualifiedName(cast<NamedDecl>(D));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001372 }
Eli Friedmane79c9872013-07-10 01:33:19 +00001373
Eli Friedman5e867c82013-07-10 00:30:46 +00001374 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1375 unsigned disc;
1376 if (Context.getNextDiscriminator(ND, disc)) {
1377 if (disc < 10)
1378 Out << '_' << disc;
1379 else
1380 Out << "__" << disc << '_';
1381 }
1382 }
Eli Friedman84431882013-07-02 17:52:28 +00001383}
1384
1385void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1386 if (GetLocalClassDecl(Block)) {
1387 mangleLocalName(Block);
1388 return;
1389 }
1390 const DeclContext *DC = getEffectiveDeclContext(Block);
1391 if (isLocalContainerContext(DC)) {
1392 mangleLocalName(Block);
1393 return;
1394 }
1395 manglePrefix(getEffectiveDeclContext(Block));
1396 mangleUnqualifiedBlock(Block);
1397}
1398
1399void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1400 if (Decl *Context = Block->getBlockManglingContextDecl()) {
1401 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1402 Context->getDeclContext()->isRecord()) {
1403 if (const IdentifierInfo *Name
1404 = cast<NamedDecl>(Context)->getIdentifier()) {
1405 mangleSourceName(Name);
1406 Out << 'M';
1407 }
1408 }
1409 }
1410
1411 // If we have a block mangling number, use it.
1412 unsigned Number = Block->getBlockManglingNumber();
1413 // Otherwise, just make up a number. It doesn't matter what it is because
1414 // the symbol in question isn't externally visible.
1415 if (!Number)
1416 Number = Context.getBlockId(Block, false);
1417 Out << "Ub";
1418 if (Number > 1)
1419 Out << Number - 2;
1420 Out << '_';
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001421}
1422
1423void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1424 // If the context of a closure type is an initializer for a class member
1425 // (static or nonstatic), it is encoded in a qualified name with a final
1426 // <prefix> of the form:
1427 //
1428 // <data-member-prefix> := <member source-name> M
1429 //
1430 // Technically, the data-member-prefix is part of the <prefix>. However,
1431 // since a closure type will always be mangled with a prefix, it's easier
1432 // to emit that last part of the prefix here.
1433 if (Decl *Context = Lambda->getLambdaContextDecl()) {
1434 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1435 Context->getDeclContext()->isRecord()) {
1436 if (const IdentifierInfo *Name
1437 = cast<NamedDecl>(Context)->getIdentifier()) {
1438 mangleSourceName(Name);
1439 Out << 'M';
1440 }
1441 }
1442 }
1443
1444 Out << "Ul";
1445 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1446 getAs<FunctionProtoType>();
1447 mangleBareFunctionType(Proto, /*MangleReturnType=*/false);
1448 Out << "E";
1449
1450 // The number is omitted for the first closure type with a given
1451 // <lambda-sig> in a given context; it is n-2 for the nth closure type
1452 // (in lexical order) with that same <lambda-sig> and context.
1453 //
1454 // The AST keeps track of the number for us.
1455 unsigned Number = Lambda->getLambdaManglingNumber();
1456 assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1457 if (Number > 1)
1458 mangleNumber(Number - 2);
1459 Out << '_';
1460}
1461
1462void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1463 switch (qualifier->getKind()) {
1464 case NestedNameSpecifier::Global:
1465 // nothing
1466 return;
1467
1468 case NestedNameSpecifier::Namespace:
1469 mangleName(qualifier->getAsNamespace());
1470 return;
1471
1472 case NestedNameSpecifier::NamespaceAlias:
1473 mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1474 return;
1475
1476 case NestedNameSpecifier::TypeSpec:
1477 case NestedNameSpecifier::TypeSpecWithTemplate:
1478 manglePrefix(QualType(qualifier->getAsType(), 0));
1479 return;
1480
1481 case NestedNameSpecifier::Identifier:
1482 // Member expressions can have these without prefixes, but that
1483 // should end up in mangleUnresolvedPrefix instead.
1484 assert(qualifier->getPrefix());
1485 manglePrefix(qualifier->getPrefix());
1486
1487 mangleSourceName(qualifier->getAsIdentifier());
1488 return;
1489 }
1490
1491 llvm_unreachable("unexpected nested name specifier");
1492}
1493
1494void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1495 // <prefix> ::= <prefix> <unqualified-name>
1496 // ::= <template-prefix> <template-args>
1497 // ::= <template-param>
1498 // ::= # empty
1499 // ::= <substitution>
1500
1501 DC = IgnoreLinkageSpecDecls(DC);
1502
1503 if (DC->isTranslationUnit())
1504 return;
1505
Eli Friedman84431882013-07-02 17:52:28 +00001506 if (NoFunction && isLocalContainerContext(DC))
1507 return;
Eli Friedman07369dd2013-07-01 20:22:57 +00001508
Eli Friedman84431882013-07-02 17:52:28 +00001509 assert(!isLocalContainerContext(DC));
1510
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001511 const NamedDecl *ND = cast<NamedDecl>(DC);
1512 if (mangleSubstitution(ND))
1513 return;
1514
1515 // Check if we have a template.
1516 const TemplateArgumentList *TemplateArgs = 0;
1517 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1518 mangleTemplatePrefix(TD);
1519 mangleTemplateArgs(*TemplateArgs);
Eli Friedman84431882013-07-02 17:52:28 +00001520 } else {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001521 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1522 mangleUnqualifiedName(ND);
1523 }
1524
1525 addSubstitution(ND);
1526}
1527
1528void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1529 // <template-prefix> ::= <prefix> <template unqualified-name>
1530 // ::= <template-param>
1531 // ::= <substitution>
1532 if (TemplateDecl *TD = Template.getAsTemplateDecl())
1533 return mangleTemplatePrefix(TD);
1534
1535 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1536 manglePrefix(Qualified->getQualifier());
1537
1538 if (OverloadedTemplateStorage *Overloaded
1539 = Template.getAsOverloadedTemplate()) {
1540 mangleUnqualifiedName(0, (*Overloaded->begin())->getDeclName(),
1541 UnknownArity);
1542 return;
1543 }
1544
1545 DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1546 assert(Dependent && "Unknown template name kind?");
1547 manglePrefix(Dependent->getQualifier());
1548 mangleUnscopedTemplateName(Template);
1549}
1550
Eli Friedman88922102013-07-05 18:41:30 +00001551void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1552 bool NoFunction) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001553 // <template-prefix> ::= <prefix> <template unqualified-name>
1554 // ::= <template-param>
1555 // ::= <substitution>
1556 // <template-template-param> ::= <template-param>
1557 // <substitution>
1558
1559 if (mangleSubstitution(ND))
1560 return;
1561
1562 // <template-template-param> ::= <template-param>
1563 if (const TemplateTemplateParmDecl *TTP
1564 = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1565 mangleTemplateParameter(TTP->getIndex());
1566 return;
1567 }
1568
Eli Friedman88922102013-07-05 18:41:30 +00001569 manglePrefix(getEffectiveDeclContext(ND), NoFunction);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001570 mangleUnqualifiedName(ND->getTemplatedDecl());
1571 addSubstitution(ND);
1572}
1573
1574/// Mangles a template name under the production <type>. Required for
1575/// template template arguments.
1576/// <type> ::= <class-enum-type>
1577/// ::= <template-param>
1578/// ::= <substitution>
1579void CXXNameMangler::mangleType(TemplateName TN) {
1580 if (mangleSubstitution(TN))
1581 return;
1582
1583 TemplateDecl *TD = 0;
1584
1585 switch (TN.getKind()) {
1586 case TemplateName::QualifiedTemplate:
1587 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1588 goto HaveDecl;
1589
1590 case TemplateName::Template:
1591 TD = TN.getAsTemplateDecl();
1592 goto HaveDecl;
1593
1594 HaveDecl:
1595 if (isa<TemplateTemplateParmDecl>(TD))
1596 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1597 else
1598 mangleName(TD);
1599 break;
1600
1601 case TemplateName::OverloadedTemplate:
1602 llvm_unreachable("can't mangle an overloaded template name as a <type>");
1603
1604 case TemplateName::DependentTemplate: {
1605 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1606 assert(Dependent->isIdentifier());
1607
1608 // <class-enum-type> ::= <name>
1609 // <name> ::= <nested-name>
1610 mangleUnresolvedPrefix(Dependent->getQualifier(), 0);
1611 mangleSourceName(Dependent->getIdentifier());
1612 break;
1613 }
1614
1615 case TemplateName::SubstTemplateTemplateParm: {
1616 // Substituted template parameters are mangled as the substituted
1617 // template. This will check for the substitution twice, which is
1618 // fine, but we have to return early so that we don't try to *add*
1619 // the substitution twice.
1620 SubstTemplateTemplateParmStorage *subst
1621 = TN.getAsSubstTemplateTemplateParm();
1622 mangleType(subst->getReplacement());
1623 return;
1624 }
1625
1626 case TemplateName::SubstTemplateTemplateParmPack: {
1627 // FIXME: not clear how to mangle this!
1628 // template <template <class> class T...> class A {
1629 // template <template <class> class U...> void foo(B<T,U> x...);
1630 // };
1631 Out << "_SUBSTPACK_";
1632 break;
1633 }
1634 }
1635
1636 addSubstitution(TN);
1637}
1638
1639void
1640CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1641 switch (OO) {
1642 // <operator-name> ::= nw # new
1643 case OO_New: Out << "nw"; break;
1644 // ::= na # new[]
1645 case OO_Array_New: Out << "na"; break;
1646 // ::= dl # delete
1647 case OO_Delete: Out << "dl"; break;
1648 // ::= da # delete[]
1649 case OO_Array_Delete: Out << "da"; break;
1650 // ::= ps # + (unary)
1651 // ::= pl # + (binary or unknown)
1652 case OO_Plus:
1653 Out << (Arity == 1? "ps" : "pl"); break;
1654 // ::= ng # - (unary)
1655 // ::= mi # - (binary or unknown)
1656 case OO_Minus:
1657 Out << (Arity == 1? "ng" : "mi"); break;
1658 // ::= ad # & (unary)
1659 // ::= an # & (binary or unknown)
1660 case OO_Amp:
1661 Out << (Arity == 1? "ad" : "an"); break;
1662 // ::= de # * (unary)
1663 // ::= ml # * (binary or unknown)
1664 case OO_Star:
1665 // Use binary when unknown.
1666 Out << (Arity == 1? "de" : "ml"); break;
1667 // ::= co # ~
1668 case OO_Tilde: Out << "co"; break;
1669 // ::= dv # /
1670 case OO_Slash: Out << "dv"; break;
1671 // ::= rm # %
1672 case OO_Percent: Out << "rm"; break;
1673 // ::= or # |
1674 case OO_Pipe: Out << "or"; break;
1675 // ::= eo # ^
1676 case OO_Caret: Out << "eo"; break;
1677 // ::= aS # =
1678 case OO_Equal: Out << "aS"; break;
1679 // ::= pL # +=
1680 case OO_PlusEqual: Out << "pL"; break;
1681 // ::= mI # -=
1682 case OO_MinusEqual: Out << "mI"; break;
1683 // ::= mL # *=
1684 case OO_StarEqual: Out << "mL"; break;
1685 // ::= dV # /=
1686 case OO_SlashEqual: Out << "dV"; break;
1687 // ::= rM # %=
1688 case OO_PercentEqual: Out << "rM"; break;
1689 // ::= aN # &=
1690 case OO_AmpEqual: Out << "aN"; break;
1691 // ::= oR # |=
1692 case OO_PipeEqual: Out << "oR"; break;
1693 // ::= eO # ^=
1694 case OO_CaretEqual: Out << "eO"; break;
1695 // ::= ls # <<
1696 case OO_LessLess: Out << "ls"; break;
1697 // ::= rs # >>
1698 case OO_GreaterGreater: Out << "rs"; break;
1699 // ::= lS # <<=
1700 case OO_LessLessEqual: Out << "lS"; break;
1701 // ::= rS # >>=
1702 case OO_GreaterGreaterEqual: Out << "rS"; break;
1703 // ::= eq # ==
1704 case OO_EqualEqual: Out << "eq"; break;
1705 // ::= ne # !=
1706 case OO_ExclaimEqual: Out << "ne"; break;
1707 // ::= lt # <
1708 case OO_Less: Out << "lt"; break;
1709 // ::= gt # >
1710 case OO_Greater: Out << "gt"; break;
1711 // ::= le # <=
1712 case OO_LessEqual: Out << "le"; break;
1713 // ::= ge # >=
1714 case OO_GreaterEqual: Out << "ge"; break;
1715 // ::= nt # !
1716 case OO_Exclaim: Out << "nt"; break;
1717 // ::= aa # &&
1718 case OO_AmpAmp: Out << "aa"; break;
1719 // ::= oo # ||
1720 case OO_PipePipe: Out << "oo"; break;
1721 // ::= pp # ++
1722 case OO_PlusPlus: Out << "pp"; break;
1723 // ::= mm # --
1724 case OO_MinusMinus: Out << "mm"; break;
1725 // ::= cm # ,
1726 case OO_Comma: Out << "cm"; break;
1727 // ::= pm # ->*
1728 case OO_ArrowStar: Out << "pm"; break;
1729 // ::= pt # ->
1730 case OO_Arrow: Out << "pt"; break;
1731 // ::= cl # ()
1732 case OO_Call: Out << "cl"; break;
1733 // ::= ix # []
1734 case OO_Subscript: Out << "ix"; break;
1735
1736 // ::= qu # ?
1737 // The conditional operator can't be overloaded, but we still handle it when
1738 // mangling expressions.
1739 case OO_Conditional: Out << "qu"; break;
1740
1741 case OO_None:
1742 case NUM_OVERLOADED_OPERATORS:
1743 llvm_unreachable("Not an overloaded operator");
1744 }
1745}
1746
1747void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
1748 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
1749 if (Quals.hasRestrict())
1750 Out << 'r';
1751 if (Quals.hasVolatile())
1752 Out << 'V';
1753 if (Quals.hasConst())
1754 Out << 'K';
1755
1756 if (Quals.hasAddressSpace()) {
1757 // Extension:
1758 //
1759 // <type> ::= U <address-space-number>
1760 //
1761 // where <address-space-number> is a source name consisting of 'AS'
1762 // followed by the address space <number>.
1763 SmallString<64> ASString;
Tanya Lattnerf21107b2013-02-08 01:07:32 +00001764 ASString = "AS" + llvm::utostr_32(
1765 Context.getASTContext().getTargetAddressSpace(Quals.getAddressSpace()));
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001766 Out << 'U' << ASString.size() << ASString;
1767 }
1768
1769 StringRef LifetimeName;
1770 switch (Quals.getObjCLifetime()) {
1771 // Objective-C ARC Extension:
1772 //
1773 // <type> ::= U "__strong"
1774 // <type> ::= U "__weak"
1775 // <type> ::= U "__autoreleasing"
1776 case Qualifiers::OCL_None:
1777 break;
1778
1779 case Qualifiers::OCL_Weak:
1780 LifetimeName = "__weak";
1781 break;
1782
1783 case Qualifiers::OCL_Strong:
1784 LifetimeName = "__strong";
1785 break;
1786
1787 case Qualifiers::OCL_Autoreleasing:
1788 LifetimeName = "__autoreleasing";
1789 break;
1790
1791 case Qualifiers::OCL_ExplicitNone:
1792 // The __unsafe_unretained qualifier is *not* mangled, so that
1793 // __unsafe_unretained types in ARC produce the same manglings as the
1794 // equivalent (but, naturally, unqualified) types in non-ARC, providing
1795 // better ABI compatibility.
1796 //
1797 // It's safe to do this because unqualified 'id' won't show up
1798 // in any type signatures that need to be mangled.
1799 break;
1800 }
1801 if (!LifetimeName.empty())
1802 Out << 'U' << LifetimeName.size() << LifetimeName;
1803}
1804
1805void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1806 // <ref-qualifier> ::= R # lvalue reference
1807 // ::= O # rvalue-reference
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001808 switch (RefQualifier) {
1809 case RQ_None:
1810 break;
1811
1812 case RQ_LValue:
1813 Out << 'R';
1814 break;
1815
1816 case RQ_RValue:
1817 Out << 'O';
1818 break;
1819 }
1820}
1821
1822void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1823 Context.mangleObjCMethodName(MD, Out);
1824}
1825
1826void CXXNameMangler::mangleType(QualType T) {
1827 // If our type is instantiation-dependent but not dependent, we mangle
1828 // it as it was written in the source, removing any top-level sugar.
1829 // Otherwise, use the canonical type.
1830 //
1831 // FIXME: This is an approximation of the instantiation-dependent name
1832 // mangling rules, since we should really be using the type as written and
1833 // augmented via semantic analysis (i.e., with implicit conversions and
1834 // default template arguments) for any instantiation-dependent type.
1835 // Unfortunately, that requires several changes to our AST:
1836 // - Instantiation-dependent TemplateSpecializationTypes will need to be
1837 // uniqued, so that we can handle substitutions properly
1838 // - Default template arguments will need to be represented in the
1839 // TemplateSpecializationType, since they need to be mangled even though
1840 // they aren't written.
1841 // - Conversions on non-type template arguments need to be expressed, since
1842 // they can affect the mangling of sizeof/alignof.
1843 if (!T->isInstantiationDependentType() || T->isDependentType())
1844 T = T.getCanonicalType();
1845 else {
1846 // Desugar any types that are purely sugar.
1847 do {
1848 // Don't desugar through template specialization types that aren't
1849 // type aliases. We need to mangle the template arguments as written.
1850 if (const TemplateSpecializationType *TST
1851 = dyn_cast<TemplateSpecializationType>(T))
1852 if (!TST->isTypeAlias())
1853 break;
1854
1855 QualType Desugared
1856 = T.getSingleStepDesugaredType(Context.getASTContext());
1857 if (Desugared == T)
1858 break;
1859
1860 T = Desugared;
1861 } while (true);
1862 }
1863 SplitQualType split = T.split();
1864 Qualifiers quals = split.Quals;
1865 const Type *ty = split.Ty;
1866
1867 bool isSubstitutable = quals || !isa<BuiltinType>(T);
1868 if (isSubstitutable && mangleSubstitution(T))
1869 return;
1870
1871 // If we're mangling a qualified array type, push the qualifiers to
1872 // the element type.
1873 if (quals && isa<ArrayType>(T)) {
1874 ty = Context.getASTContext().getAsArrayType(T);
1875 quals = Qualifiers();
1876
1877 // Note that we don't update T: we want to add the
1878 // substitution at the original type.
1879 }
1880
1881 if (quals) {
1882 mangleQualifiers(quals);
1883 // Recurse: even if the qualified type isn't yet substitutable,
1884 // the unqualified type might be.
1885 mangleType(QualType(ty, 0));
1886 } else {
1887 switch (ty->getTypeClass()) {
1888#define ABSTRACT_TYPE(CLASS, PARENT)
1889#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1890 case Type::CLASS: \
1891 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1892 return;
1893#define TYPE(CLASS, PARENT) \
1894 case Type::CLASS: \
1895 mangleType(static_cast<const CLASS##Type*>(ty)); \
1896 break;
1897#include "clang/AST/TypeNodes.def"
1898 }
1899 }
1900
1901 // Add the substitution.
1902 if (isSubstitutable)
1903 addSubstitution(T);
1904}
1905
1906void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
1907 if (!mangleStandardSubstitution(ND))
1908 mangleName(ND);
1909}
1910
1911void CXXNameMangler::mangleType(const BuiltinType *T) {
1912 // <type> ::= <builtin-type>
1913 // <builtin-type> ::= v # void
1914 // ::= w # wchar_t
1915 // ::= b # bool
1916 // ::= c # char
1917 // ::= a # signed char
1918 // ::= h # unsigned char
1919 // ::= s # short
1920 // ::= t # unsigned short
1921 // ::= i # int
1922 // ::= j # unsigned int
1923 // ::= l # long
1924 // ::= m # unsigned long
1925 // ::= x # long long, __int64
1926 // ::= y # unsigned long long, __int64
1927 // ::= n # __int128
1928 // UNSUPPORTED: ::= o # unsigned __int128
1929 // ::= f # float
1930 // ::= d # double
1931 // ::= e # long double, __float80
1932 // UNSUPPORTED: ::= g # __float128
1933 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
1934 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
1935 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
1936 // ::= Dh # IEEE 754r half-precision floating point (16 bits)
1937 // ::= Di # char32_t
1938 // ::= Ds # char16_t
1939 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
1940 // ::= u <source-name> # vendor extended type
1941 switch (T->getKind()) {
1942 case BuiltinType::Void: Out << 'v'; break;
1943 case BuiltinType::Bool: Out << 'b'; break;
1944 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break;
1945 case BuiltinType::UChar: Out << 'h'; break;
1946 case BuiltinType::UShort: Out << 't'; break;
1947 case BuiltinType::UInt: Out << 'j'; break;
1948 case BuiltinType::ULong: Out << 'm'; break;
1949 case BuiltinType::ULongLong: Out << 'y'; break;
1950 case BuiltinType::UInt128: Out << 'o'; break;
1951 case BuiltinType::SChar: Out << 'a'; break;
1952 case BuiltinType::WChar_S:
1953 case BuiltinType::WChar_U: Out << 'w'; break;
1954 case BuiltinType::Char16: Out << "Ds"; break;
1955 case BuiltinType::Char32: Out << "Di"; break;
1956 case BuiltinType::Short: Out << 's'; break;
1957 case BuiltinType::Int: Out << 'i'; break;
1958 case BuiltinType::Long: Out << 'l'; break;
1959 case BuiltinType::LongLong: Out << 'x'; break;
1960 case BuiltinType::Int128: Out << 'n'; break;
1961 case BuiltinType::Half: Out << "Dh"; break;
1962 case BuiltinType::Float: Out << 'f'; break;
1963 case BuiltinType::Double: Out << 'd'; break;
1964 case BuiltinType::LongDouble: Out << 'e'; break;
1965 case BuiltinType::NullPtr: Out << "Dn"; break;
1966
1967#define BUILTIN_TYPE(Id, SingletonId)
1968#define PLACEHOLDER_TYPE(Id, SingletonId) \
1969 case BuiltinType::Id:
1970#include "clang/AST/BuiltinTypes.def"
1971 case BuiltinType::Dependent:
1972 llvm_unreachable("mangling a placeholder type");
1973 case BuiltinType::ObjCId: Out << "11objc_object"; break;
1974 case BuiltinType::ObjCClass: Out << "10objc_class"; break;
1975 case BuiltinType::ObjCSel: Out << "13objc_selector"; break;
Guy Benyeib13621d2012-12-18 14:38:23 +00001976 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break;
1977 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break;
1978 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break;
1979 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break;
1980 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break;
1981 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break;
Guy Benyei21f18c42013-02-07 10:55:47 +00001982 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break;
Guy Benyeie6b9d802013-01-20 12:31:11 +00001983 case BuiltinType::OCLEvent: Out << "9ocl_event"; break;
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001984 }
1985}
1986
1987// <type> ::= <function-type>
1988// <function-type> ::= [<CV-qualifiers>] F [Y]
1989// <bare-function-type> [<ref-qualifier>] E
Guy Benyei7f92f2d2012-12-18 14:30:41 +00001990void CXXNameMangler::mangleType(const FunctionProtoType *T) {
1991 // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
1992 // e.g. "const" in "int (A::*)() const".
1993 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
1994
1995 Out << 'F';
1996
1997 // FIXME: We don't have enough information in the AST to produce the 'Y'
1998 // encoding for extern "C" function types.
1999 mangleBareFunctionType(T, /*MangleReturnType=*/true);
2000
2001 // Mangle the ref-qualifier, if present.
2002 mangleRefQualifier(T->getRefQualifier());
2003
2004 Out << 'E';
2005}
2006void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2007 llvm_unreachable("Can't mangle K&R function prototypes");
2008}
2009void CXXNameMangler::mangleBareFunctionType(const FunctionType *T,
2010 bool MangleReturnType) {
2011 // We should never be mangling something without a prototype.
2012 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
2013
2014 // Record that we're in a function type. See mangleFunctionParam
2015 // for details on what we're trying to achieve here.
2016 FunctionTypeDepthState saved = FunctionTypeDepth.push();
2017
2018 // <bare-function-type> ::= <signature type>+
2019 if (MangleReturnType) {
2020 FunctionTypeDepth.enterResultType();
2021 mangleType(Proto->getResultType());
2022 FunctionTypeDepth.leaveResultType();
2023 }
2024
2025 if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
2026 // <builtin-type> ::= v # void
2027 Out << 'v';
2028
2029 FunctionTypeDepth.pop(saved);
2030 return;
2031 }
2032
2033 for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
2034 ArgEnd = Proto->arg_type_end();
2035 Arg != ArgEnd; ++Arg)
2036 mangleType(Context.getASTContext().getSignatureParameterType(*Arg));
2037
2038 FunctionTypeDepth.pop(saved);
2039
2040 // <builtin-type> ::= z # ellipsis
2041 if (Proto->isVariadic())
2042 Out << 'z';
2043}
2044
2045// <type> ::= <class-enum-type>
2046// <class-enum-type> ::= <name>
2047void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2048 mangleName(T->getDecl());
2049}
2050
2051// <type> ::= <class-enum-type>
2052// <class-enum-type> ::= <name>
2053void CXXNameMangler::mangleType(const EnumType *T) {
2054 mangleType(static_cast<const TagType*>(T));
2055}
2056void CXXNameMangler::mangleType(const RecordType *T) {
2057 mangleType(static_cast<const TagType*>(T));
2058}
2059void CXXNameMangler::mangleType(const TagType *T) {
2060 mangleName(T->getDecl());
2061}
2062
2063// <type> ::= <array-type>
2064// <array-type> ::= A <positive dimension number> _ <element type>
2065// ::= A [<dimension expression>] _ <element type>
2066void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2067 Out << 'A' << T->getSize() << '_';
2068 mangleType(T->getElementType());
2069}
2070void CXXNameMangler::mangleType(const VariableArrayType *T) {
2071 Out << 'A';
2072 // decayed vla types (size 0) will just be skipped.
2073 if (T->getSizeExpr())
2074 mangleExpression(T->getSizeExpr());
2075 Out << '_';
2076 mangleType(T->getElementType());
2077}
2078void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2079 Out << 'A';
2080 mangleExpression(T->getSizeExpr());
2081 Out << '_';
2082 mangleType(T->getElementType());
2083}
2084void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2085 Out << "A_";
2086 mangleType(T->getElementType());
2087}
2088
2089// <type> ::= <pointer-to-member-type>
2090// <pointer-to-member-type> ::= M <class type> <member type>
2091void CXXNameMangler::mangleType(const MemberPointerType *T) {
2092 Out << 'M';
2093 mangleType(QualType(T->getClass(), 0));
2094 QualType PointeeType = T->getPointeeType();
2095 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2096 mangleType(FPT);
2097
2098 // Itanium C++ ABI 5.1.8:
2099 //
2100 // The type of a non-static member function is considered to be different,
2101 // for the purposes of substitution, from the type of a namespace-scope or
2102 // static member function whose type appears similar. The types of two
2103 // non-static member functions are considered to be different, for the
2104 // purposes of substitution, if the functions are members of different
2105 // classes. In other words, for the purposes of substitution, the class of
2106 // which the function is a member is considered part of the type of
2107 // function.
2108
2109 // Given that we already substitute member function pointers as a
2110 // whole, the net effect of this rule is just to unconditionally
2111 // suppress substitution on the function type in a member pointer.
2112 // We increment the SeqID here to emulate adding an entry to the
2113 // substitution table.
2114 ++SeqID;
2115 } else
2116 mangleType(PointeeType);
2117}
2118
2119// <type> ::= <template-param>
2120void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2121 mangleTemplateParameter(T->getIndex());
2122}
2123
2124// <type> ::= <template-param>
2125void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2126 // FIXME: not clear how to mangle this!
2127 // template <class T...> class A {
2128 // template <class U...> void foo(T(*)(U) x...);
2129 // };
2130 Out << "_SUBSTPACK_";
2131}
2132
2133// <type> ::= P <type> # pointer-to
2134void CXXNameMangler::mangleType(const PointerType *T) {
2135 Out << 'P';
2136 mangleType(T->getPointeeType());
2137}
2138void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2139 Out << 'P';
2140 mangleType(T->getPointeeType());
2141}
2142
2143// <type> ::= R <type> # reference-to
2144void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2145 Out << 'R';
2146 mangleType(T->getPointeeType());
2147}
2148
2149// <type> ::= O <type> # rvalue reference-to (C++0x)
2150void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2151 Out << 'O';
2152 mangleType(T->getPointeeType());
2153}
2154
2155// <type> ::= C <type> # complex pair (C 2000)
2156void CXXNameMangler::mangleType(const ComplexType *T) {
2157 Out << 'C';
2158 mangleType(T->getElementType());
2159}
2160
2161// ARM's ABI for Neon vector types specifies that they should be mangled as
2162// if they are structs (to match ARM's initial implementation). The
2163// vector type must be one of the special types predefined by ARM.
2164void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2165 QualType EltType = T->getElementType();
2166 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2167 const char *EltName = 0;
2168 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2169 switch (cast<BuiltinType>(EltType)->getKind()) {
2170 case BuiltinType::SChar: EltName = "poly8_t"; break;
2171 case BuiltinType::Short: EltName = "poly16_t"; break;
2172 default: llvm_unreachable("unexpected Neon polynomial vector element type");
2173 }
2174 } else {
2175 switch (cast<BuiltinType>(EltType)->getKind()) {
2176 case BuiltinType::SChar: EltName = "int8_t"; break;
2177 case BuiltinType::UChar: EltName = "uint8_t"; break;
2178 case BuiltinType::Short: EltName = "int16_t"; break;
2179 case BuiltinType::UShort: EltName = "uint16_t"; break;
2180 case BuiltinType::Int: EltName = "int32_t"; break;
2181 case BuiltinType::UInt: EltName = "uint32_t"; break;
2182 case BuiltinType::LongLong: EltName = "int64_t"; break;
2183 case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2184 case BuiltinType::Float: EltName = "float32_t"; break;
Tim Northoverb793f0d2013-08-01 09:23:19 +00002185 case BuiltinType::Half: EltName = "float16_t";break;
2186 default:
2187 llvm_unreachable("unexpected Neon vector element type");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002188 }
2189 }
2190 const char *BaseName = 0;
2191 unsigned BitSize = (T->getNumElements() *
2192 getASTContext().getTypeSize(EltType));
2193 if (BitSize == 64)
2194 BaseName = "__simd64_";
2195 else {
2196 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2197 BaseName = "__simd128_";
2198 }
2199 Out << strlen(BaseName) + strlen(EltName);
2200 Out << BaseName << EltName;
2201}
2202
Tim Northoverb793f0d2013-08-01 09:23:19 +00002203static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2204 switch (EltType->getKind()) {
2205 case BuiltinType::SChar:
2206 return "Int8";
2207 case BuiltinType::Short:
2208 return "Int16";
2209 case BuiltinType::Int:
2210 return "Int32";
2211 case BuiltinType::LongLong:
2212 return "Int64";
2213 case BuiltinType::UChar:
2214 return "Uint8";
2215 case BuiltinType::UShort:
2216 return "Uint16";
2217 case BuiltinType::UInt:
2218 return "Uint32";
2219 case BuiltinType::ULongLong:
2220 return "Uint64";
2221 case BuiltinType::Half:
2222 return "Float16";
2223 case BuiltinType::Float:
2224 return "Float32";
2225 case BuiltinType::Double:
2226 return "Float64";
2227 default:
2228 llvm_unreachable("Unexpected vector element base type");
2229 }
2230}
2231
2232// AArch64's ABI for Neon vector types specifies that they should be mangled as
2233// the equivalent internal name. The vector type must be one of the special
2234// types predefined by ARM.
2235void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2236 QualType EltType = T->getElementType();
2237 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2238 unsigned BitSize =
2239 (T->getNumElements() * getASTContext().getTypeSize(EltType));
Daniel Jasper800de7e2013-08-01 10:30:11 +00002240 (void)BitSize; // Silence warning.
Tim Northoverb793f0d2013-08-01 09:23:19 +00002241
2242 assert((BitSize == 64 || BitSize == 128) &&
2243 "Neon vector type not 64 or 128 bits");
2244
2245 assert(getASTContext().getTypeSize(EltType) != BitSize &&
2246 "Vector of 1 element not permitted");
2247
2248 StringRef EltName;
2249 if (T->getVectorKind() == VectorType::NeonPolyVector) {
2250 switch (cast<BuiltinType>(EltType)->getKind()) {
2251 case BuiltinType::UChar:
2252 EltName = "Poly8";
2253 break;
2254 case BuiltinType::UShort:
2255 EltName = "Poly16";
2256 break;
2257 default:
2258 llvm_unreachable("unexpected Neon polynomial vector element type");
2259 }
2260 } else
2261 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2262
2263 std::string TypeName =
2264 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str();
2265 Out << TypeName.length() << TypeName;
2266}
2267
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002268// GNU extension: vector types
2269// <type> ::= <vector-type>
2270// <vector-type> ::= Dv <positive dimension number> _
2271// <extended element type>
2272// ::= Dv [<dimension expression>] _ <element type>
2273// <extended element type> ::= <element type>
2274// ::= p # AltiVec vector pixel
2275// ::= b # Altivec vector bool
2276void CXXNameMangler::mangleType(const VectorType *T) {
2277 if ((T->getVectorKind() == VectorType::NeonVector ||
2278 T->getVectorKind() == VectorType::NeonPolyVector)) {
Tim Northoverb793f0d2013-08-01 09:23:19 +00002279 if (getASTContext().getTargetInfo().getTriple().getArch() ==
2280 llvm::Triple::aarch64)
2281 mangleAArch64NeonVectorType(T);
2282 else
2283 mangleNeonVectorType(T);
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002284 return;
2285 }
2286 Out << "Dv" << T->getNumElements() << '_';
2287 if (T->getVectorKind() == VectorType::AltiVecPixel)
2288 Out << 'p';
2289 else if (T->getVectorKind() == VectorType::AltiVecBool)
2290 Out << 'b';
2291 else
2292 mangleType(T->getElementType());
2293}
2294void CXXNameMangler::mangleType(const ExtVectorType *T) {
2295 mangleType(static_cast<const VectorType*>(T));
2296}
2297void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2298 Out << "Dv";
2299 mangleExpression(T->getSizeExpr());
2300 Out << '_';
2301 mangleType(T->getElementType());
2302}
2303
2304void CXXNameMangler::mangleType(const PackExpansionType *T) {
2305 // <type> ::= Dp <type> # pack expansion (C++0x)
2306 Out << "Dp";
2307 mangleType(T->getPattern());
2308}
2309
2310void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2311 mangleSourceName(T->getDecl()->getIdentifier());
2312}
2313
2314void CXXNameMangler::mangleType(const ObjCObjectType *T) {
Eli Friedman06017002013-06-18 22:41:37 +00002315 if (!T->qual_empty()) {
2316 // Mangle protocol qualifiers.
2317 SmallString<64> QualStr;
2318 llvm::raw_svector_ostream QualOS(QualStr);
2319 QualOS << "objcproto";
2320 ObjCObjectType::qual_iterator i = T->qual_begin(), e = T->qual_end();
2321 for ( ; i != e; ++i) {
2322 StringRef name = (*i)->getName();
2323 QualOS << name.size() << name;
2324 }
2325 QualOS.flush();
2326 Out << 'U' << QualStr.size() << QualStr;
2327 }
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002328 mangleType(T->getBaseType());
2329}
2330
2331void CXXNameMangler::mangleType(const BlockPointerType *T) {
2332 Out << "U13block_pointer";
2333 mangleType(T->getPointeeType());
2334}
2335
2336void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2337 // Mangle injected class name types as if the user had written the
2338 // specialization out fully. It may not actually be possible to see
2339 // this mangling, though.
2340 mangleType(T->getInjectedSpecializationType());
2341}
2342
2343void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2344 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2345 mangleName(TD, T->getArgs(), T->getNumArgs());
2346 } else {
2347 if (mangleSubstitution(QualType(T, 0)))
2348 return;
2349
2350 mangleTemplatePrefix(T->getTemplateName());
2351
2352 // FIXME: GCC does not appear to mangle the template arguments when
2353 // the template in question is a dependent template name. Should we
2354 // emulate that badness?
2355 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2356 addSubstitution(QualType(T, 0));
2357 }
2358}
2359
2360void CXXNameMangler::mangleType(const DependentNameType *T) {
2361 // Typename types are always nested
2362 Out << 'N';
2363 manglePrefix(T->getQualifier());
2364 mangleSourceName(T->getIdentifier());
2365 Out << 'E';
2366}
2367
2368void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2369 // Dependently-scoped template types are nested if they have a prefix.
2370 Out << 'N';
2371
2372 // TODO: avoid making this TemplateName.
2373 TemplateName Prefix =
2374 getASTContext().getDependentTemplateName(T->getQualifier(),
2375 T->getIdentifier());
2376 mangleTemplatePrefix(Prefix);
2377
2378 // FIXME: GCC does not appear to mangle the template arguments when
2379 // the template in question is a dependent template name. Should we
2380 // emulate that badness?
2381 mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2382 Out << 'E';
2383}
2384
2385void CXXNameMangler::mangleType(const TypeOfType *T) {
2386 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2387 // "extension with parameters" mangling.
2388 Out << "u6typeof";
2389}
2390
2391void CXXNameMangler::mangleType(const TypeOfExprType *T) {
2392 // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2393 // "extension with parameters" mangling.
2394 Out << "u6typeof";
2395}
2396
2397void CXXNameMangler::mangleType(const DecltypeType *T) {
2398 Expr *E = T->getUnderlyingExpr();
2399
2400 // type ::= Dt <expression> E # decltype of an id-expression
2401 // # or class member access
2402 // ::= DT <expression> E # decltype of an expression
2403
2404 // This purports to be an exhaustive list of id-expressions and
2405 // class member accesses. Note that we do not ignore parentheses;
2406 // parentheses change the semantics of decltype for these
2407 // expressions (and cause the mangler to use the other form).
2408 if (isa<DeclRefExpr>(E) ||
2409 isa<MemberExpr>(E) ||
2410 isa<UnresolvedLookupExpr>(E) ||
2411 isa<DependentScopeDeclRefExpr>(E) ||
2412 isa<CXXDependentScopeMemberExpr>(E) ||
2413 isa<UnresolvedMemberExpr>(E))
2414 Out << "Dt";
2415 else
2416 Out << "DT";
2417 mangleExpression(E);
2418 Out << 'E';
2419}
2420
2421void CXXNameMangler::mangleType(const UnaryTransformType *T) {
2422 // If this is dependent, we need to record that. If not, we simply
2423 // mangle it as the underlying type since they are equivalent.
2424 if (T->isDependentType()) {
2425 Out << 'U';
2426
2427 switch (T->getUTTKind()) {
2428 case UnaryTransformType::EnumUnderlyingType:
2429 Out << "3eut";
2430 break;
2431 }
2432 }
2433
2434 mangleType(T->getUnderlyingType());
2435}
2436
2437void CXXNameMangler::mangleType(const AutoType *T) {
2438 QualType D = T->getDeducedType();
2439 // <builtin-type> ::= Da # dependent auto
2440 if (D.isNull())
Richard Smitha2c36462013-04-26 16:15:35 +00002441 Out << (T->isDecltypeAuto() ? "Dc" : "Da");
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002442 else
2443 mangleType(D);
2444}
2445
2446void CXXNameMangler::mangleType(const AtomicType *T) {
2447 // <type> ::= U <source-name> <type> # vendor extended type qualifier
2448 // (Until there's a standardized mangling...)
2449 Out << "U7_Atomic";
2450 mangleType(T->getValueType());
2451}
2452
2453void CXXNameMangler::mangleIntegerLiteral(QualType T,
2454 const llvm::APSInt &Value) {
2455 // <expr-primary> ::= L <type> <value number> E # integer literal
2456 Out << 'L';
2457
2458 mangleType(T);
2459 if (T->isBooleanType()) {
2460 // Boolean values are encoded as 0/1.
2461 Out << (Value.getBoolValue() ? '1' : '0');
2462 } else {
2463 mangleNumber(Value);
2464 }
2465 Out << 'E';
2466
2467}
2468
2469/// Mangles a member expression.
2470void CXXNameMangler::mangleMemberExpr(const Expr *base,
2471 bool isArrow,
2472 NestedNameSpecifier *qualifier,
2473 NamedDecl *firstQualifierLookup,
2474 DeclarationName member,
2475 unsigned arity) {
2476 // <expression> ::= dt <expression> <unresolved-name>
2477 // ::= pt <expression> <unresolved-name>
2478 if (base) {
2479 if (base->isImplicitCXXThis()) {
2480 // Note: GCC mangles member expressions to the implicit 'this' as
2481 // *this., whereas we represent them as this->. The Itanium C++ ABI
2482 // does not specify anything here, so we follow GCC.
2483 Out << "dtdefpT";
2484 } else {
2485 Out << (isArrow ? "pt" : "dt");
2486 mangleExpression(base);
2487 }
2488 }
2489 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity);
2490}
2491
2492/// Look at the callee of the given call expression and determine if
2493/// it's a parenthesized id-expression which would have triggered ADL
2494/// otherwise.
2495static bool isParenthesizedADLCallee(const CallExpr *call) {
2496 const Expr *callee = call->getCallee();
2497 const Expr *fn = callee->IgnoreParens();
2498
2499 // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
2500 // too, but for those to appear in the callee, it would have to be
2501 // parenthesized.
2502 if (callee == fn) return false;
2503
2504 // Must be an unresolved lookup.
2505 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
2506 if (!lookup) return false;
2507
2508 assert(!lookup->requiresADL());
2509
2510 // Must be an unqualified lookup.
2511 if (lookup->getQualifier()) return false;
2512
2513 // Must not have found a class member. Note that if one is a class
2514 // member, they're all class members.
2515 if (lookup->getNumDecls() > 0 &&
2516 (*lookup->decls_begin())->isCXXClassMember())
2517 return false;
2518
2519 // Otherwise, ADL would have been triggered.
2520 return true;
2521}
2522
2523void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
2524 // <expression> ::= <unary operator-name> <expression>
2525 // ::= <binary operator-name> <expression> <expression>
2526 // ::= <trinary operator-name> <expression> <expression> <expression>
2527 // ::= cv <type> expression # conversion with one argument
2528 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
2529 // ::= st <type> # sizeof (a type)
2530 // ::= at <type> # alignof (a type)
2531 // ::= <template-param>
2532 // ::= <function-param>
2533 // ::= sr <type> <unqualified-name> # dependent name
2534 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
2535 // ::= ds <expression> <expression> # expr.*expr
2536 // ::= sZ <template-param> # size of a parameter pack
2537 // ::= sZ <function-param> # size of a function parameter pack
2538 // ::= <expr-primary>
2539 // <expr-primary> ::= L <type> <value number> E # integer literal
2540 // ::= L <type <value float> E # floating literal
2541 // ::= L <mangled-name> E # external name
2542 // ::= fpT # 'this' expression
2543 QualType ImplicitlyConvertedToType;
2544
2545recurse:
2546 switch (E->getStmtClass()) {
2547 case Expr::NoStmtClass:
2548#define ABSTRACT_STMT(Type)
2549#define EXPR(Type, Base)
2550#define STMT(Type, Base) \
2551 case Expr::Type##Class:
2552#include "clang/AST/StmtNodes.inc"
2553 // fallthrough
2554
2555 // These all can only appear in local or variable-initialization
2556 // contexts and so should never appear in a mangling.
2557 case Expr::AddrLabelExprClass:
2558 case Expr::DesignatedInitExprClass:
2559 case Expr::ImplicitValueInitExprClass:
2560 case Expr::ParenListExprClass:
2561 case Expr::LambdaExprClass:
John McCall76da55d2013-04-16 07:28:30 +00002562 case Expr::MSPropertyRefExprClass:
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002563 llvm_unreachable("unexpected statement kind");
2564
2565 // FIXME: invent manglings for all these.
2566 case Expr::BlockExprClass:
2567 case Expr::CXXPseudoDestructorExprClass:
2568 case Expr::ChooseExprClass:
2569 case Expr::CompoundLiteralExprClass:
2570 case Expr::ExtVectorElementExprClass:
2571 case Expr::GenericSelectionExprClass:
2572 case Expr::ObjCEncodeExprClass:
2573 case Expr::ObjCIsaExprClass:
2574 case Expr::ObjCIvarRefExprClass:
2575 case Expr::ObjCMessageExprClass:
2576 case Expr::ObjCPropertyRefExprClass:
2577 case Expr::ObjCProtocolExprClass:
2578 case Expr::ObjCSelectorExprClass:
2579 case Expr::ObjCStringLiteralClass:
2580 case Expr::ObjCBoxedExprClass:
2581 case Expr::ObjCArrayLiteralClass:
2582 case Expr::ObjCDictionaryLiteralClass:
2583 case Expr::ObjCSubscriptRefExprClass:
2584 case Expr::ObjCIndirectCopyRestoreExprClass:
2585 case Expr::OffsetOfExprClass:
2586 case Expr::PredefinedExprClass:
2587 case Expr::ShuffleVectorExprClass:
2588 case Expr::StmtExprClass:
2589 case Expr::UnaryTypeTraitExprClass:
2590 case Expr::BinaryTypeTraitExprClass:
2591 case Expr::TypeTraitExprClass:
2592 case Expr::ArrayTypeTraitExprClass:
2593 case Expr::ExpressionTraitExprClass:
2594 case Expr::VAArgExprClass:
2595 case Expr::CXXUuidofExprClass:
2596 case Expr::CUDAKernelCallExprClass:
2597 case Expr::AsTypeExprClass:
2598 case Expr::PseudoObjectExprClass:
2599 case Expr::AtomicExprClass:
2600 {
2601 // As bad as this diagnostic is, it's better than crashing.
2602 DiagnosticsEngine &Diags = Context.getDiags();
2603 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2604 "cannot yet mangle expression type %0");
2605 Diags.Report(E->getExprLoc(), DiagID)
2606 << E->getStmtClassName() << E->getSourceRange();
2607 break;
2608 }
2609
2610 // Even gcc-4.5 doesn't mangle this.
2611 case Expr::BinaryConditionalOperatorClass: {
2612 DiagnosticsEngine &Diags = Context.getDiags();
2613 unsigned DiagID =
2614 Diags.getCustomDiagID(DiagnosticsEngine::Error,
2615 "?: operator with omitted middle operand cannot be mangled");
2616 Diags.Report(E->getExprLoc(), DiagID)
2617 << E->getStmtClassName() << E->getSourceRange();
2618 break;
2619 }
2620
2621 // These are used for internal purposes and cannot be meaningfully mangled.
2622 case Expr::OpaqueValueExprClass:
2623 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
2624
2625 case Expr::InitListExprClass: {
2626 // Proposal by Jason Merrill, 2012-01-03
2627 Out << "il";
2628 const InitListExpr *InitList = cast<InitListExpr>(E);
2629 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2630 mangleExpression(InitList->getInit(i));
2631 Out << "E";
2632 break;
2633 }
2634
2635 case Expr::CXXDefaultArgExprClass:
2636 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
2637 break;
2638
Richard Smithc3bf52c2013-04-20 22:23:05 +00002639 case Expr::CXXDefaultInitExprClass:
2640 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
2641 break;
2642
Richard Smith7c3e6152013-06-12 22:31:48 +00002643 case Expr::CXXStdInitializerListExprClass:
2644 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
2645 break;
2646
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002647 case Expr::SubstNonTypeTemplateParmExprClass:
2648 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
2649 Arity);
2650 break;
2651
2652 case Expr::UserDefinedLiteralClass:
2653 // We follow g++'s approach of mangling a UDL as a call to the literal
2654 // operator.
2655 case Expr::CXXMemberCallExprClass: // fallthrough
2656 case Expr::CallExprClass: {
2657 const CallExpr *CE = cast<CallExpr>(E);
2658
2659 // <expression> ::= cp <simple-id> <expression>* E
2660 // We use this mangling only when the call would use ADL except
2661 // for being parenthesized. Per discussion with David
2662 // Vandervoorde, 2011.04.25.
2663 if (isParenthesizedADLCallee(CE)) {
2664 Out << "cp";
2665 // The callee here is a parenthesized UnresolvedLookupExpr with
2666 // no qualifier and should always get mangled as a <simple-id>
2667 // anyway.
2668
2669 // <expression> ::= cl <expression>* E
2670 } else {
2671 Out << "cl";
2672 }
2673
2674 mangleExpression(CE->getCallee(), CE->getNumArgs());
2675 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I)
2676 mangleExpression(CE->getArg(I));
2677 Out << 'E';
2678 break;
2679 }
2680
2681 case Expr::CXXNewExprClass: {
2682 const CXXNewExpr *New = cast<CXXNewExpr>(E);
2683 if (New->isGlobalNew()) Out << "gs";
2684 Out << (New->isArray() ? "na" : "nw");
2685 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
2686 E = New->placement_arg_end(); I != E; ++I)
2687 mangleExpression(*I);
2688 Out << '_';
2689 mangleType(New->getAllocatedType());
2690 if (New->hasInitializer()) {
2691 // Proposal by Jason Merrill, 2012-01-03
2692 if (New->getInitializationStyle() == CXXNewExpr::ListInit)
2693 Out << "il";
2694 else
2695 Out << "pi";
2696 const Expr *Init = New->getInitializer();
2697 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
2698 // Directly inline the initializers.
2699 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
2700 E = CCE->arg_end();
2701 I != E; ++I)
2702 mangleExpression(*I);
2703 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
2704 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
2705 mangleExpression(PLE->getExpr(i));
2706 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
2707 isa<InitListExpr>(Init)) {
2708 // Only take InitListExprs apart for list-initialization.
2709 const InitListExpr *InitList = cast<InitListExpr>(Init);
2710 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
2711 mangleExpression(InitList->getInit(i));
2712 } else
2713 mangleExpression(Init);
2714 }
2715 Out << 'E';
2716 break;
2717 }
2718
2719 case Expr::MemberExprClass: {
2720 const MemberExpr *ME = cast<MemberExpr>(E);
2721 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2722 ME->getQualifier(), 0, ME->getMemberDecl()->getDeclName(),
2723 Arity);
2724 break;
2725 }
2726
2727 case Expr::UnresolvedMemberExprClass: {
2728 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
2729 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2730 ME->getQualifier(), 0, ME->getMemberName(),
2731 Arity);
2732 if (ME->hasExplicitTemplateArgs())
2733 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2734 break;
2735 }
2736
2737 case Expr::CXXDependentScopeMemberExprClass: {
2738 const CXXDependentScopeMemberExpr *ME
2739 = cast<CXXDependentScopeMemberExpr>(E);
2740 mangleMemberExpr(ME->getBase(), ME->isArrow(),
2741 ME->getQualifier(), ME->getFirstQualifierFoundInScope(),
2742 ME->getMember(), Arity);
2743 if (ME->hasExplicitTemplateArgs())
2744 mangleTemplateArgs(ME->getExplicitTemplateArgs());
2745 break;
2746 }
2747
2748 case Expr::UnresolvedLookupExprClass: {
2749 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
2750 mangleUnresolvedName(ULE->getQualifier(), 0, ULE->getName(), Arity);
2751
2752 // All the <unresolved-name> productions end in a
2753 // base-unresolved-name, where <template-args> are just tacked
2754 // onto the end.
2755 if (ULE->hasExplicitTemplateArgs())
2756 mangleTemplateArgs(ULE->getExplicitTemplateArgs());
2757 break;
2758 }
2759
2760 case Expr::CXXUnresolvedConstructExprClass: {
2761 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
2762 unsigned N = CE->arg_size();
2763
2764 Out << "cv";
2765 mangleType(CE->getType());
2766 if (N != 1) Out << '_';
2767 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2768 if (N != 1) Out << 'E';
2769 break;
2770 }
2771
2772 case Expr::CXXTemporaryObjectExprClass:
2773 case Expr::CXXConstructExprClass: {
2774 const CXXConstructExpr *CE = cast<CXXConstructExpr>(E);
2775 unsigned N = CE->getNumArgs();
2776
2777 // Proposal by Jason Merrill, 2012-01-03
2778 if (CE->isListInitialization())
2779 Out << "tl";
2780 else
2781 Out << "cv";
2782 mangleType(CE->getType());
2783 if (N != 1) Out << '_';
2784 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
2785 if (N != 1) Out << 'E';
2786 break;
2787 }
2788
2789 case Expr::CXXScalarValueInitExprClass:
2790 Out <<"cv";
2791 mangleType(E->getType());
2792 Out <<"_E";
2793 break;
2794
2795 case Expr::CXXNoexceptExprClass:
2796 Out << "nx";
2797 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
2798 break;
2799
2800 case Expr::UnaryExprOrTypeTraitExprClass: {
2801 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
2802
2803 if (!SAE->isInstantiationDependent()) {
2804 // Itanium C++ ABI:
2805 // If the operand of a sizeof or alignof operator is not
2806 // instantiation-dependent it is encoded as an integer literal
2807 // reflecting the result of the operator.
2808 //
2809 // If the result of the operator is implicitly converted to a known
2810 // integer type, that type is used for the literal; otherwise, the type
2811 // of std::size_t or std::ptrdiff_t is used.
2812 QualType T = (ImplicitlyConvertedToType.isNull() ||
2813 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
2814 : ImplicitlyConvertedToType;
2815 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
2816 mangleIntegerLiteral(T, V);
2817 break;
2818 }
2819
2820 switch(SAE->getKind()) {
2821 case UETT_SizeOf:
2822 Out << 's';
2823 break;
2824 case UETT_AlignOf:
2825 Out << 'a';
2826 break;
2827 case UETT_VecStep:
2828 DiagnosticsEngine &Diags = Context.getDiags();
2829 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2830 "cannot yet mangle vec_step expression");
2831 Diags.Report(DiagID);
2832 return;
2833 }
2834 if (SAE->isArgumentType()) {
2835 Out << 't';
2836 mangleType(SAE->getArgumentType());
2837 } else {
2838 Out << 'z';
2839 mangleExpression(SAE->getArgumentExpr());
2840 }
2841 break;
2842 }
2843
2844 case Expr::CXXThrowExprClass: {
2845 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
Richard Smithec1f9052013-08-27 01:03:46 +00002846 // <expression> ::= tw <expression> # throw expression
2847 // ::= tr # rethrow
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002848 if (TE->getSubExpr()) {
2849 Out << "tw";
2850 mangleExpression(TE->getSubExpr());
2851 } else {
2852 Out << "tr";
2853 }
2854 break;
2855 }
2856
2857 case Expr::CXXTypeidExprClass: {
2858 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
Richard Smithec1f9052013-08-27 01:03:46 +00002859 // <expression> ::= ti <type> # typeid (type)
2860 // ::= te <expression> # typeid (expression)
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002861 if (TIE->isTypeOperand()) {
2862 Out << "ti";
2863 mangleType(TIE->getTypeOperand());
2864 } else {
2865 Out << "te";
2866 mangleExpression(TIE->getExprOperand());
2867 }
2868 break;
2869 }
2870
2871 case Expr::CXXDeleteExprClass: {
2872 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
Richard Smithec1f9052013-08-27 01:03:46 +00002873 // <expression> ::= [gs] dl <expression> # [::] delete expr
2874 // ::= [gs] da <expression> # [::] delete [] expr
Guy Benyei7f92f2d2012-12-18 14:30:41 +00002875 if (DE->isGlobalDelete()) Out << "gs";
2876 Out << (DE->isArrayForm() ? "da" : "dl");
2877 mangleExpression(DE->getArgument());
2878 break;
2879 }
2880
2881 case Expr::UnaryOperatorClass: {
2882 const UnaryOperator *UO = cast<UnaryOperator>(E);
2883 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
2884 /*Arity=*/1);
2885 mangleExpression(UO->getSubExpr());
2886 break;
2887 }
2888
2889 case Expr::ArraySubscriptExprClass: {
2890 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
2891
2892 // Array subscript is treated as a syntactically weird form of
2893 // binary operator.
2894 Out << "ix";
2895 mangleExpression(AE->getLHS());
2896 mangleExpression(AE->getRHS());
2897 break;
2898 }
2899
2900 case Expr::CompoundAssignOperatorClass: // fallthrough
2901 case Expr::BinaryOperatorClass: {
2902 const BinaryOperator *BO = cast<BinaryOperator>(E);
2903 if (BO->getOpcode() == BO_PtrMemD)
2904 Out << "ds";
2905 else
2906 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
2907 /*Arity=*/2);
2908 mangleExpression(BO->getLHS());
2909 mangleExpression(BO->getRHS());
2910 break;
2911 }
2912
2913 case Expr::ConditionalOperatorClass: {
2914 const ConditionalOperator *CO = cast<ConditionalOperator>(E);
2915 mangleOperatorName(OO_Conditional, /*Arity=*/3);
2916 mangleExpression(CO->getCond());
2917 mangleExpression(CO->getLHS(), Arity);
2918 mangleExpression(CO->getRHS(), Arity);
2919 break;
2920 }
2921
2922 case Expr::ImplicitCastExprClass: {
2923 ImplicitlyConvertedToType = E->getType();
2924 E = cast<ImplicitCastExpr>(E)->getSubExpr();
2925 goto recurse;
2926 }
2927
2928 case Expr::ObjCBridgedCastExprClass: {
2929 // Mangle ownership casts as a vendor extended operator __bridge,
2930 // __bridge_transfer, or __bridge_retain.
2931 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
2932 Out << "v1U" << Kind.size() << Kind;
2933 }
2934 // Fall through to mangle the cast itself.
2935
2936 case Expr::CStyleCastExprClass:
2937 case Expr::CXXStaticCastExprClass:
2938 case Expr::CXXDynamicCastExprClass:
2939 case Expr::CXXReinterpretCastExprClass:
2940 case Expr::CXXConstCastExprClass:
2941 case Expr::CXXFunctionalCastExprClass: {
2942 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
2943 Out << "cv";
2944 mangleType(ECE->getType());
2945 mangleExpression(ECE->getSubExpr());
2946 break;
2947 }
2948
2949 case Expr::CXXOperatorCallExprClass: {
2950 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
2951 unsigned NumArgs = CE->getNumArgs();
2952 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
2953 // Mangle the arguments.
2954 for (unsigned i = 0; i != NumArgs; ++i)
2955 mangleExpression(CE->getArg(i));
2956 break;
2957 }
2958
2959 case Expr::ParenExprClass:
2960 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
2961 break;
2962
2963 case Expr::DeclRefExprClass: {
2964 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
2965
2966 switch (D->getKind()) {
2967 default:
2968 // <expr-primary> ::= L <mangled-name> E # external name
2969 Out << 'L';
2970 mangle(D, "_Z");
2971 Out << 'E';
2972 break;
2973
2974 case Decl::ParmVar:
2975 mangleFunctionParam(cast<ParmVarDecl>(D));
2976 break;
2977
2978 case Decl::EnumConstant: {
2979 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
2980 mangleIntegerLiteral(ED->getType(), ED->getInitVal());
2981 break;
2982 }
2983
2984 case Decl::NonTypeTemplateParm: {
2985 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
2986 mangleTemplateParameter(PD->getIndex());
2987 break;
2988 }
2989
2990 }
2991
2992 break;
2993 }
2994
2995 case Expr::SubstNonTypeTemplateParmPackExprClass:
2996 // FIXME: not clear how to mangle this!
2997 // template <unsigned N...> class A {
2998 // template <class U...> void foo(U (&x)[N]...);
2999 // };
3000 Out << "_SUBSTPACK_";
3001 break;
3002
3003 case Expr::FunctionParmPackExprClass: {
3004 // FIXME: not clear how to mangle this!
3005 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3006 Out << "v110_SUBSTPACK";
3007 mangleFunctionParam(FPPE->getParameterPack());
3008 break;
3009 }
3010
3011 case Expr::DependentScopeDeclRefExprClass: {
3012 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
3013 mangleUnresolvedName(DRE->getQualifier(), 0, DRE->getDeclName(), Arity);
3014
3015 // All the <unresolved-name> productions end in a
3016 // base-unresolved-name, where <template-args> are just tacked
3017 // onto the end.
3018 if (DRE->hasExplicitTemplateArgs())
3019 mangleTemplateArgs(DRE->getExplicitTemplateArgs());
3020 break;
3021 }
3022
3023 case Expr::CXXBindTemporaryExprClass:
3024 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3025 break;
3026
3027 case Expr::ExprWithCleanupsClass:
3028 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3029 break;
3030
3031 case Expr::FloatingLiteralClass: {
3032 const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3033 Out << 'L';
3034 mangleType(FL->getType());
3035 mangleFloat(FL->getValue());
3036 Out << 'E';
3037 break;
3038 }
3039
3040 case Expr::CharacterLiteralClass:
3041 Out << 'L';
3042 mangleType(E->getType());
3043 Out << cast<CharacterLiteral>(E)->getValue();
3044 Out << 'E';
3045 break;
3046
3047 // FIXME. __objc_yes/__objc_no are mangled same as true/false
3048 case Expr::ObjCBoolLiteralExprClass:
3049 Out << "Lb";
3050 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3051 Out << 'E';
3052 break;
3053
3054 case Expr::CXXBoolLiteralExprClass:
3055 Out << "Lb";
3056 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3057 Out << 'E';
3058 break;
3059
3060 case Expr::IntegerLiteralClass: {
3061 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3062 if (E->getType()->isSignedIntegerType())
3063 Value.setIsSigned(true);
3064 mangleIntegerLiteral(E->getType(), Value);
3065 break;
3066 }
3067
3068 case Expr::ImaginaryLiteralClass: {
3069 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3070 // Mangle as if a complex literal.
3071 // Proposal from David Vandevoorde, 2010.06.30.
3072 Out << 'L';
3073 mangleType(E->getType());
3074 if (const FloatingLiteral *Imag =
3075 dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3076 // Mangle a floating-point zero of the appropriate type.
3077 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3078 Out << '_';
3079 mangleFloat(Imag->getValue());
3080 } else {
3081 Out << "0_";
3082 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3083 if (IE->getSubExpr()->getType()->isSignedIntegerType())
3084 Value.setIsSigned(true);
3085 mangleNumber(Value);
3086 }
3087 Out << 'E';
3088 break;
3089 }
3090
3091 case Expr::StringLiteralClass: {
3092 // Revised proposal from David Vandervoorde, 2010.07.15.
3093 Out << 'L';
3094 assert(isa<ConstantArrayType>(E->getType()));
3095 mangleType(E->getType());
3096 Out << 'E';
3097 break;
3098 }
3099
3100 case Expr::GNUNullExprClass:
3101 // FIXME: should this really be mangled the same as nullptr?
3102 // fallthrough
3103
3104 case Expr::CXXNullPtrLiteralExprClass: {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003105 Out << "LDnE";
3106 break;
3107 }
3108
3109 case Expr::PackExpansionExprClass:
3110 Out << "sp";
3111 mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3112 break;
3113
3114 case Expr::SizeOfPackExprClass: {
3115 Out << "sZ";
3116 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack();
3117 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3118 mangleTemplateParameter(TTP->getIndex());
3119 else if (const NonTypeTemplateParmDecl *NTTP
3120 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3121 mangleTemplateParameter(NTTP->getIndex());
3122 else if (const TemplateTemplateParmDecl *TempTP
3123 = dyn_cast<TemplateTemplateParmDecl>(Pack))
3124 mangleTemplateParameter(TempTP->getIndex());
3125 else
3126 mangleFunctionParam(cast<ParmVarDecl>(Pack));
3127 break;
3128 }
3129
3130 case Expr::MaterializeTemporaryExprClass: {
3131 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3132 break;
3133 }
3134
3135 case Expr::CXXThisExprClass:
3136 Out << "fpT";
3137 break;
3138 }
3139}
3140
3141/// Mangle an expression which refers to a parameter variable.
3142///
3143/// <expression> ::= <function-param>
3144/// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
3145/// <function-param> ::= fp <top-level CV-qualifiers>
3146/// <parameter-2 non-negative number> _ # L == 0, I > 0
3147/// <function-param> ::= fL <L-1 non-negative number>
3148/// p <top-level CV-qualifiers> _ # L > 0, I == 0
3149/// <function-param> ::= fL <L-1 non-negative number>
3150/// p <top-level CV-qualifiers>
3151/// <I-1 non-negative number> _ # L > 0, I > 0
3152///
3153/// L is the nesting depth of the parameter, defined as 1 if the
3154/// parameter comes from the innermost function prototype scope
3155/// enclosing the current context, 2 if from the next enclosing
3156/// function prototype scope, and so on, with one special case: if
3157/// we've processed the full parameter clause for the innermost
3158/// function type, then L is one less. This definition conveniently
3159/// makes it irrelevant whether a function's result type was written
3160/// trailing or leading, but is otherwise overly complicated; the
3161/// numbering was first designed without considering references to
3162/// parameter in locations other than return types, and then the
3163/// mangling had to be generalized without changing the existing
3164/// manglings.
3165///
3166/// I is the zero-based index of the parameter within its parameter
3167/// declaration clause. Note that the original ABI document describes
3168/// this using 1-based ordinals.
3169void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3170 unsigned parmDepth = parm->getFunctionScopeDepth();
3171 unsigned parmIndex = parm->getFunctionScopeIndex();
3172
3173 // Compute 'L'.
3174 // parmDepth does not include the declaring function prototype.
3175 // FunctionTypeDepth does account for that.
3176 assert(parmDepth < FunctionTypeDepth.getDepth());
3177 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3178 if (FunctionTypeDepth.isInResultType())
3179 nestingDepth--;
3180
3181 if (nestingDepth == 0) {
3182 Out << "fp";
3183 } else {
3184 Out << "fL" << (nestingDepth - 1) << 'p';
3185 }
3186
3187 // Top-level qualifiers. We don't have to worry about arrays here,
3188 // because parameters declared as arrays should already have been
3189 // transformed to have pointer type. FIXME: apparently these don't
3190 // get mangled if used as an rvalue of a known non-class type?
3191 assert(!parm->getType()->isArrayType()
3192 && "parameter's type is still an array type?");
3193 mangleQualifiers(parm->getType().getQualifiers());
3194
3195 // Parameter index.
3196 if (parmIndex != 0) {
3197 Out << (parmIndex - 1);
3198 }
3199 Out << '_';
3200}
3201
3202void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) {
3203 // <ctor-dtor-name> ::= C1 # complete object constructor
3204 // ::= C2 # base object constructor
3205 // ::= C3 # complete object allocating constructor
3206 //
3207 switch (T) {
3208 case Ctor_Complete:
3209 Out << "C1";
3210 break;
3211 case Ctor_Base:
3212 Out << "C2";
3213 break;
3214 case Ctor_CompleteAllocating:
3215 Out << "C3";
3216 break;
3217 }
3218}
3219
3220void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
3221 // <ctor-dtor-name> ::= D0 # deleting destructor
3222 // ::= D1 # complete object destructor
3223 // ::= D2 # base object destructor
3224 //
3225 switch (T) {
3226 case Dtor_Deleting:
3227 Out << "D0";
3228 break;
3229 case Dtor_Complete:
3230 Out << "D1";
3231 break;
3232 case Dtor_Base:
3233 Out << "D2";
3234 break;
3235 }
3236}
3237
3238void CXXNameMangler::mangleTemplateArgs(
3239 const ASTTemplateArgumentListInfo &TemplateArgs) {
3240 // <template-args> ::= I <template-arg>+ E
3241 Out << 'I';
3242 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i)
3243 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument());
3244 Out << 'E';
3245}
3246
3247void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
3248 // <template-args> ::= I <template-arg>+ E
3249 Out << 'I';
3250 for (unsigned i = 0, e = AL.size(); i != e; ++i)
3251 mangleTemplateArg(AL[i]);
3252 Out << 'E';
3253}
3254
3255void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
3256 unsigned NumTemplateArgs) {
3257 // <template-args> ::= I <template-arg>+ E
3258 Out << 'I';
3259 for (unsigned i = 0; i != NumTemplateArgs; ++i)
3260 mangleTemplateArg(TemplateArgs[i]);
3261 Out << 'E';
3262}
3263
3264void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
3265 // <template-arg> ::= <type> # type or template
3266 // ::= X <expression> E # expression
3267 // ::= <expr-primary> # simple expressions
3268 // ::= J <template-arg>* E # argument pack
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003269 if (!A.isInstantiationDependent() || A.isDependent())
3270 A = Context.getASTContext().getCanonicalTemplateArgument(A);
3271
3272 switch (A.getKind()) {
3273 case TemplateArgument::Null:
3274 llvm_unreachable("Cannot mangle NULL template argument");
3275
3276 case TemplateArgument::Type:
3277 mangleType(A.getAsType());
3278 break;
3279 case TemplateArgument::Template:
3280 // This is mangled as <type>.
3281 mangleType(A.getAsTemplate());
3282 break;
3283 case TemplateArgument::TemplateExpansion:
3284 // <type> ::= Dp <type> # pack expansion (C++0x)
3285 Out << "Dp";
3286 mangleType(A.getAsTemplateOrTemplatePattern());
3287 break;
3288 case TemplateArgument::Expression: {
3289 // It's possible to end up with a DeclRefExpr here in certain
3290 // dependent cases, in which case we should mangle as a
3291 // declaration.
3292 const Expr *E = A.getAsExpr()->IgnoreParens();
3293 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
3294 const ValueDecl *D = DRE->getDecl();
3295 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
3296 Out << "L";
3297 mangle(D, "_Z");
3298 Out << 'E';
3299 break;
3300 }
3301 }
3302
3303 Out << 'X';
3304 mangleExpression(E);
3305 Out << 'E';
3306 break;
3307 }
3308 case TemplateArgument::Integral:
3309 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
3310 break;
3311 case TemplateArgument::Declaration: {
3312 // <expr-primary> ::= L <mangled-name> E # external name
3313 // Clang produces AST's where pointer-to-member-function expressions
3314 // and pointer-to-function expressions are represented as a declaration not
3315 // an expression. We compensate for it here to produce the correct mangling.
3316 ValueDecl *D = A.getAsDecl();
3317 bool compensateMangling = !A.isDeclForReferenceParam();
3318 if (compensateMangling) {
3319 Out << 'X';
3320 mangleOperatorName(OO_Amp, 1);
3321 }
3322
3323 Out << 'L';
3324 // References to external entities use the mangled name; if the name would
3325 // not normally be manged then mangle it as unqualified.
3326 //
3327 // FIXME: The ABI specifies that external names here should have _Z, but
3328 // gcc leaves this off.
3329 if (compensateMangling)
3330 mangle(D, "_Z");
3331 else
3332 mangle(D, "Z");
3333 Out << 'E';
3334
3335 if (compensateMangling)
3336 Out << 'E';
3337
3338 break;
3339 }
3340 case TemplateArgument::NullPtr: {
3341 // <expr-primary> ::= L <type> 0 E
3342 Out << 'L';
3343 mangleType(A.getNullPtrType());
3344 Out << "0E";
3345 break;
3346 }
3347 case TemplateArgument::Pack: {
Richard Smithec1f9052013-08-27 01:03:46 +00003348 // <template-arg> ::= J <template-arg>* E
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003349 Out << 'J';
Richard Smithec1f9052013-08-27 01:03:46 +00003350 for (TemplateArgument::pack_iterator PA = A.pack_begin(),
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003351 PAEnd = A.pack_end();
3352 PA != PAEnd; ++PA)
3353 mangleTemplateArg(*PA);
3354 Out << 'E';
3355 }
3356 }
3357}
3358
3359void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
3360 // <template-param> ::= T_ # first template parameter
3361 // ::= T <parameter-2 non-negative number> _
3362 if (Index == 0)
3363 Out << "T_";
3364 else
3365 Out << 'T' << (Index - 1) << '_';
3366}
3367
3368void CXXNameMangler::mangleExistingSubstitution(QualType type) {
3369 bool result = mangleSubstitution(type);
3370 assert(result && "no existing substitution for type");
3371 (void) result;
3372}
3373
3374void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
3375 bool result = mangleSubstitution(tname);
3376 assert(result && "no existing substitution for template name");
3377 (void) result;
3378}
3379
3380// <substitution> ::= S <seq-id> _
3381// ::= S_
3382bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
3383 // Try one of the standard substitutions first.
3384 if (mangleStandardSubstitution(ND))
3385 return true;
3386
3387 ND = cast<NamedDecl>(ND->getCanonicalDecl());
3388 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
3389}
3390
3391/// \brief Determine whether the given type has any qualifiers that are
3392/// relevant for substitutions.
3393static bool hasMangledSubstitutionQualifiers(QualType T) {
3394 Qualifiers Qs = T.getQualifiers();
3395 return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
3396}
3397
3398bool CXXNameMangler::mangleSubstitution(QualType T) {
3399 if (!hasMangledSubstitutionQualifiers(T)) {
3400 if (const RecordType *RT = T->getAs<RecordType>())
3401 return mangleSubstitution(RT->getDecl());
3402 }
3403
3404 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3405
3406 return mangleSubstitution(TypePtr);
3407}
3408
3409bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
3410 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3411 return mangleSubstitution(TD);
3412
3413 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3414 return mangleSubstitution(
3415 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3416}
3417
3418bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
3419 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
3420 if (I == Substitutions.end())
3421 return false;
3422
3423 unsigned SeqID = I->second;
3424 if (SeqID == 0)
3425 Out << "S_";
3426 else {
3427 SeqID--;
3428
3429 // <seq-id> is encoded in base-36, using digits and upper case letters.
3430 char Buffer[10];
3431 char *BufferPtr = llvm::array_endof(Buffer);
3432
3433 if (SeqID == 0) *--BufferPtr = '0';
3434
3435 while (SeqID) {
3436 assert(BufferPtr > Buffer && "Buffer overflow!");
3437
3438 char c = static_cast<char>(SeqID % 36);
3439
3440 *--BufferPtr = (c < 10 ? '0' + c : 'A' + c - 10);
3441 SeqID /= 36;
3442 }
3443
3444 Out << 'S'
3445 << StringRef(BufferPtr, llvm::array_endof(Buffer)-BufferPtr)
3446 << '_';
3447 }
3448
3449 return true;
3450}
3451
3452static bool isCharType(QualType T) {
3453 if (T.isNull())
3454 return false;
3455
3456 return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
3457 T->isSpecificBuiltinType(BuiltinType::Char_U);
3458}
3459
3460/// isCharSpecialization - Returns whether a given type is a template
3461/// specialization of a given name with a single argument of type char.
3462static bool isCharSpecialization(QualType T, const char *Name) {
3463 if (T.isNull())
3464 return false;
3465
3466 const RecordType *RT = T->getAs<RecordType>();
3467 if (!RT)
3468 return false;
3469
3470 const ClassTemplateSpecializationDecl *SD =
3471 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
3472 if (!SD)
3473 return false;
3474
3475 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3476 return false;
3477
3478 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3479 if (TemplateArgs.size() != 1)
3480 return false;
3481
3482 if (!isCharType(TemplateArgs[0].getAsType()))
3483 return false;
3484
3485 return SD->getIdentifier()->getName() == Name;
3486}
3487
3488template <std::size_t StrLen>
3489static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
3490 const char (&Str)[StrLen]) {
3491 if (!SD->getIdentifier()->isStr(Str))
3492 return false;
3493
3494 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3495 if (TemplateArgs.size() != 2)
3496 return false;
3497
3498 if (!isCharType(TemplateArgs[0].getAsType()))
3499 return false;
3500
3501 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3502 return false;
3503
3504 return true;
3505}
3506
3507bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
3508 // <substitution> ::= St # ::std::
3509 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
3510 if (isStd(NS)) {
3511 Out << "St";
3512 return true;
3513 }
3514 }
3515
3516 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
3517 if (!isStdNamespace(getEffectiveDeclContext(TD)))
3518 return false;
3519
3520 // <substitution> ::= Sa # ::std::allocator
3521 if (TD->getIdentifier()->isStr("allocator")) {
3522 Out << "Sa";
3523 return true;
3524 }
3525
3526 // <<substitution> ::= Sb # ::std::basic_string
3527 if (TD->getIdentifier()->isStr("basic_string")) {
3528 Out << "Sb";
3529 return true;
3530 }
3531 }
3532
3533 if (const ClassTemplateSpecializationDecl *SD =
3534 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
3535 if (!isStdNamespace(getEffectiveDeclContext(SD)))
3536 return false;
3537
3538 // <substitution> ::= Ss # ::std::basic_string<char,
3539 // ::std::char_traits<char>,
3540 // ::std::allocator<char> >
3541 if (SD->getIdentifier()->isStr("basic_string")) {
3542 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
3543
3544 if (TemplateArgs.size() != 3)
3545 return false;
3546
3547 if (!isCharType(TemplateArgs[0].getAsType()))
3548 return false;
3549
3550 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
3551 return false;
3552
3553 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
3554 return false;
3555
3556 Out << "Ss";
3557 return true;
3558 }
3559
3560 // <substitution> ::= Si # ::std::basic_istream<char,
3561 // ::std::char_traits<char> >
3562 if (isStreamCharSpecialization(SD, "basic_istream")) {
3563 Out << "Si";
3564 return true;
3565 }
3566
3567 // <substitution> ::= So # ::std::basic_ostream<char,
3568 // ::std::char_traits<char> >
3569 if (isStreamCharSpecialization(SD, "basic_ostream")) {
3570 Out << "So";
3571 return true;
3572 }
3573
3574 // <substitution> ::= Sd # ::std::basic_iostream<char,
3575 // ::std::char_traits<char> >
3576 if (isStreamCharSpecialization(SD, "basic_iostream")) {
3577 Out << "Sd";
3578 return true;
3579 }
3580 }
3581 return false;
3582}
3583
3584void CXXNameMangler::addSubstitution(QualType T) {
3585 if (!hasMangledSubstitutionQualifiers(T)) {
3586 if (const RecordType *RT = T->getAs<RecordType>()) {
3587 addSubstitution(RT->getDecl());
3588 return;
3589 }
3590 }
3591
3592 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
3593 addSubstitution(TypePtr);
3594}
3595
3596void CXXNameMangler::addSubstitution(TemplateName Template) {
3597 if (TemplateDecl *TD = Template.getAsTemplateDecl())
3598 return addSubstitution(TD);
3599
3600 Template = Context.getASTContext().getCanonicalTemplateName(Template);
3601 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
3602}
3603
3604void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
3605 assert(!Substitutions.count(Ptr) && "Substitution already exists!");
3606 Substitutions[Ptr] = SeqID++;
3607}
3608
3609//
3610
3611/// \brief Mangles the name of the declaration D and emits that name to the
3612/// given output stream.
3613///
3614/// If the declaration D requires a mangled name, this routine will emit that
3615/// mangled name to \p os and return true. Otherwise, \p os will be unchanged
3616/// and this routine will return false. In this case, the caller should just
3617/// emit the identifier of the declaration (\c D->getIdentifier()) as its
3618/// name.
3619void ItaniumMangleContext::mangleName(const NamedDecl *D,
3620 raw_ostream &Out) {
3621 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
3622 "Invalid mangleName() call, argument is not a variable or function!");
3623 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
3624 "Invalid mangleName() call on 'structor decl!");
3625
3626 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3627 getASTContext().getSourceManager(),
3628 "Mangling declaration");
3629
3630 CXXNameMangler Mangler(*this, Out, D);
3631 return Mangler.mangle(D);
3632}
3633
3634void ItaniumMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
3635 CXXCtorType Type,
3636 raw_ostream &Out) {
3637 CXXNameMangler Mangler(*this, Out, D, Type);
3638 Mangler.mangle(D);
3639}
3640
3641void ItaniumMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
3642 CXXDtorType Type,
3643 raw_ostream &Out) {
3644 CXXNameMangler Mangler(*this, Out, D, Type);
3645 Mangler.mangle(D);
3646}
3647
3648void ItaniumMangleContext::mangleThunk(const CXXMethodDecl *MD,
3649 const ThunkInfo &Thunk,
3650 raw_ostream &Out) {
3651 // <special-name> ::= T <call-offset> <base encoding>
3652 // # base is the nominal target function of thunk
3653 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
3654 // # base is the nominal target function of thunk
3655 // # first call-offset is 'this' adjustment
3656 // # second call-offset is result adjustment
3657
3658 assert(!isa<CXXDestructorDecl>(MD) &&
3659 "Use mangleCXXDtor for destructor decls!");
3660 CXXNameMangler Mangler(*this, Out);
3661 Mangler.getStream() << "_ZT";
3662 if (!Thunk.Return.isEmpty())
3663 Mangler.getStream() << 'c';
3664
3665 // Mangle the 'this' pointer adjustment.
3666 Mangler.mangleCallOffset(Thunk.This.NonVirtual, Thunk.This.VCallOffsetOffset);
3667
3668 // Mangle the return pointer adjustment if there is one.
3669 if (!Thunk.Return.isEmpty())
3670 Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
3671 Thunk.Return.VBaseOffsetOffset);
3672
3673 Mangler.mangleFunctionEncoding(MD);
3674}
3675
3676void
3677ItaniumMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
3678 CXXDtorType Type,
3679 const ThisAdjustment &ThisAdjustment,
3680 raw_ostream &Out) {
3681 // <special-name> ::= T <call-offset> <base encoding>
3682 // # base is the nominal target function of thunk
3683 CXXNameMangler Mangler(*this, Out, DD, Type);
3684 Mangler.getStream() << "_ZT";
3685
3686 // Mangle the 'this' pointer adjustment.
3687 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
3688 ThisAdjustment.VCallOffsetOffset);
3689
3690 Mangler.mangleFunctionEncoding(DD);
3691}
3692
3693/// mangleGuardVariable - Returns the mangled name for a guard variable
3694/// for the passed in VarDecl.
Reid Kleckner942f9fe2013-09-10 20:14:30 +00003695void ItaniumMangleContext::mangleStaticGuardVariable(const VarDecl *D,
3696 raw_ostream &Out) {
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003697 // <special-name> ::= GV <object name> # Guard variable for one-time
3698 // # initialization
3699 CXXNameMangler Mangler(*this, Out);
3700 Mangler.getStream() << "_ZGV";
3701 Mangler.mangleName(D);
3702}
3703
Reid Kleckner942f9fe2013-09-10 20:14:30 +00003704void ItaniumMangleContext::mangleDynamicAtExitDestructor(const VarDecl *D,
3705 raw_ostream &Out) {
3706 // Prefix the mangling of D with __dtor_.
3707 CXXNameMangler Mangler(*this, Out);
3708 Mangler.getStream() << "__dtor_";
3709 if (shouldMangleDeclName(D))
3710 Mangler.mangle(D);
3711 else
3712 Mangler.getStream() << D->getName();
3713}
3714
Richard Smithb80a16e2013-04-19 16:42:07 +00003715void ItaniumMangleContext::mangleItaniumThreadLocalInit(const VarDecl *D,
3716 raw_ostream &Out) {
3717 // <special-name> ::= TH <object name>
3718 CXXNameMangler Mangler(*this, Out);
3719 Mangler.getStream() << "_ZTH";
3720 Mangler.mangleName(D);
3721}
3722
3723void ItaniumMangleContext::mangleItaniumThreadLocalWrapper(const VarDecl *D,
3724 raw_ostream &Out) {
3725 // <special-name> ::= TW <object name>
3726 CXXNameMangler Mangler(*this, Out);
3727 Mangler.getStream() << "_ZTW";
3728 Mangler.mangleName(D);
3729}
3730
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003731void ItaniumMangleContext::mangleReferenceTemporary(const VarDecl *D,
3732 raw_ostream &Out) {
3733 // We match the GCC mangling here.
3734 // <special-name> ::= GR <object name>
3735 CXXNameMangler Mangler(*this, Out);
3736 Mangler.getStream() << "_ZGR";
3737 Mangler.mangleName(D);
3738}
3739
3740void ItaniumMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
3741 raw_ostream &Out) {
3742 // <special-name> ::= TV <type> # virtual table
3743 CXXNameMangler Mangler(*this, Out);
3744 Mangler.getStream() << "_ZTV";
3745 Mangler.mangleNameOrStandardSubstitution(RD);
3746}
3747
3748void ItaniumMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
3749 raw_ostream &Out) {
3750 // <special-name> ::= TT <type> # VTT structure
3751 CXXNameMangler Mangler(*this, Out);
3752 Mangler.getStream() << "_ZTT";
3753 Mangler.mangleNameOrStandardSubstitution(RD);
3754}
3755
Reid Kleckner90633022013-06-19 15:20:38 +00003756void
3757ItaniumMangleContext::mangleCXXVBTable(const CXXRecordDecl *Derived,
3758 ArrayRef<const CXXRecordDecl *> BasePath,
3759 raw_ostream &Out) {
3760 llvm_unreachable("The Itanium C++ ABI does not have virtual base tables!");
3761}
3762
Guy Benyei7f92f2d2012-12-18 14:30:41 +00003763void ItaniumMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
3764 int64_t Offset,
3765 const CXXRecordDecl *Type,
3766 raw_ostream &Out) {
3767 // <special-name> ::= TC <type> <offset number> _ <base type>
3768 CXXNameMangler Mangler(*this, Out);
3769 Mangler.getStream() << "_ZTC";
3770 Mangler.mangleNameOrStandardSubstitution(RD);
3771 Mangler.getStream() << Offset;
3772 Mangler.getStream() << '_';
3773 Mangler.mangleNameOrStandardSubstitution(Type);
3774}
3775
3776void ItaniumMangleContext::mangleCXXRTTI(QualType Ty,
3777 raw_ostream &Out) {
3778 // <special-name> ::= TI <type> # typeinfo structure
3779 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
3780 CXXNameMangler Mangler(*this, Out);
3781 Mangler.getStream() << "_ZTI";
3782 Mangler.mangleType(Ty);
3783}
3784
3785void ItaniumMangleContext::mangleCXXRTTIName(QualType Ty,
3786 raw_ostream &Out) {
3787 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
3788 CXXNameMangler Mangler(*this, Out);
3789 Mangler.getStream() << "_ZTS";
3790 Mangler.mangleType(Ty);
3791}
3792
3793MangleContext *clang::createItaniumMangleContext(ASTContext &Context,
3794 DiagnosticsEngine &Diags) {
3795 return new ItaniumMangleContext(Context, Diags);
3796}