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