blob: 01f9ffc5be5a0542a187350597e151fa5f583b69 [file] [log] [blame]
Guy Benyei11169dd2012-12-18 14:30:41 +00001//===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
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// This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Mangle.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/Attr.h"
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +000017#include "clang/AST/CXXInheritance.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000018#include "clang/AST/CharUnits.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000019#include "clang/AST/Decl.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/DeclTemplate.h"
David Majnemer58e5bee2014-03-24 21:43:36 +000023#include "clang/AST/Expr.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000024#include "clang/AST/ExprCXX.h"
Reid Kleckner96f8f932014-02-05 17:27:08 +000025#include "clang/AST/VTableBuilder.h"
Guy Benyei11169dd2012-12-18 14:30:41 +000026#include "clang/Basic/ABI.h"
27#include "clang/Basic/DiagnosticOptions.h"
Reid Kleckner369f3162013-05-14 20:30:42 +000028#include "clang/Basic/TargetInfo.h"
David Majnemer2206bf52014-03-05 08:57:59 +000029#include "llvm/ADT/StringExtras.h"
Reid Kleckner7dafb232013-05-22 17:16:39 +000030#include "llvm/ADT/StringMap.h"
David Majnemer58e5bee2014-03-24 21:43:36 +000031#include "llvm/Support/MathExtras.h"
David Majnemer3843a052014-03-23 17:47:16 +000032
Guy Benyei11169dd2012-12-18 14:30:41 +000033using namespace clang;
34
35namespace {
36
David Majnemerd5a42b82013-09-13 09:03:14 +000037/// \brief Retrieve the declaration context that should be used when mangling
38/// the given declaration.
39static const DeclContext *getEffectiveDeclContext(const Decl *D) {
40 // The ABI assumes that lambda closure types that occur within
41 // default arguments live in the context of the function. However, due to
42 // the way in which Clang parses and creates function declarations, this is
43 // not the case: the lambda closure type ends up living in the context
44 // where the function itself resides, because the function declaration itself
45 // had not yet been created. Fix the context here.
46 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
47 if (RD->isLambda())
48 if (ParmVarDecl *ContextParam =
49 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
50 return ContextParam->getDeclContext();
51 }
52
53 // Perform the same check for block literals.
54 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
55 if (ParmVarDecl *ContextParam =
56 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
57 return ContextParam->getDeclContext();
58 }
59
60 const DeclContext *DC = D->getDeclContext();
61 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
62 return getEffectiveDeclContext(CD);
63
64 return DC;
65}
66
67static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
68 return getEffectiveDeclContext(cast<Decl>(DC));
69}
70
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +000071static const FunctionDecl *getStructor(const FunctionDecl *fn) {
72 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
73 return ftd->getTemplatedDecl();
74
75 return fn;
76}
77
David Majnemer2206bf52014-03-05 08:57:59 +000078static bool isLambda(const NamedDecl *ND) {
79 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
80 if (!Record)
81 return false;
Guy Benyei11169dd2012-12-18 14:30:41 +000082
David Majnemer2206bf52014-03-05 08:57:59 +000083 return Record->isLambda();
84}
Guy Benyei11169dd2012-12-18 14:30:41 +000085
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000086/// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
Guy Benyei11169dd2012-12-18 14:30:41 +000087/// Microsoft Visual C++ ABI.
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000088class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
David Majnemer2206bf52014-03-05 08:57:59 +000089 typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
90 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
91 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
David Majnemerf017ec32014-03-05 10:35:06 +000092 llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
David Majnemer2206bf52014-03-05 08:57:59 +000093
Guy Benyei11169dd2012-12-18 14:30:41 +000094public:
Timur Iskhodzhanov67455222013-10-03 06:26:13 +000095 MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags)
96 : MicrosoftMangleContext(Context, Diags) {}
Craig Toppercbce6e92014-03-11 06:22:39 +000097 bool shouldMangleCXXName(const NamedDecl *D) override;
David Majnemer58e5bee2014-03-24 21:43:36 +000098 bool shouldMangleStringLiteral(const StringLiteral *SL) override;
Craig Toppercbce6e92014-03-11 06:22:39 +000099 void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
100 void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD, raw_ostream &) override;
101 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
102 raw_ostream &) override;
103 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
104 const ThisAdjustment &ThisAdjustment,
105 raw_ostream &) override;
106 void mangleCXXVFTable(const CXXRecordDecl *Derived,
107 ArrayRef<const CXXRecordDecl *> BasePath,
108 raw_ostream &Out) override;
109 void mangleCXXVBTable(const CXXRecordDecl *Derived,
110 ArrayRef<const CXXRecordDecl *> BasePath,
111 raw_ostream &Out) override;
112 void mangleCXXRTTI(QualType T, raw_ostream &) override;
113 void mangleCXXRTTIName(QualType T, raw_ostream &) override;
114 void mangleTypeName(QualType T, raw_ostream &) override;
115 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
116 raw_ostream &) override;
117 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
118 raw_ostream &) override;
119 void mangleReferenceTemporary(const VarDecl *, raw_ostream &) override;
120 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
121 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
122 void mangleDynamicAtExitDestructor(const VarDecl *D,
123 raw_ostream &Out) override;
David Majnemer58e5bee2014-03-24 21:43:36 +0000124 void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
David Majnemer2206bf52014-03-05 08:57:59 +0000125 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
126 // Lambda closure types are already numbered.
127 if (isLambda(ND))
128 return false;
129
130 const DeclContext *DC = getEffectiveDeclContext(ND);
131 if (!DC->isFunctionOrMethod())
132 return false;
133
134 // Use the canonical number for externally visible decls.
135 if (ND->isExternallyVisible()) {
136 disc = getASTContext().getManglingNumber(ND);
137 return true;
138 }
139
140 // Anonymous tags are already numbered.
141 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
142 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
143 return false;
144 }
145
146 // Make up a reasonable number for internal decls.
147 unsigned &discriminator = Uniquifier[ND];
148 if (!discriminator)
149 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
150 disc = discriminator;
151 return true;
152 }
Reid Kleckner1ece9fc2013-09-10 20:43:12 +0000153
David Majnemerf017ec32014-03-05 10:35:06 +0000154 unsigned getLambdaId(const CXXRecordDecl *RD) {
155 assert(RD->isLambda() && "RD must be a lambda!");
156 assert(!RD->isExternallyVisible() && "RD must not be visible!");
157 assert(RD->getLambdaManglingNumber() == 0 &&
158 "RD must not have a mangling number!");
159 std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
160 Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
161 return Result.first->second;
162 }
163
Reid Kleckner1ece9fc2013-09-10 20:43:12 +0000164private:
165 void mangleInitFiniStub(const VarDecl *D, raw_ostream &Out, char CharCode);
Guy Benyei11169dd2012-12-18 14:30:41 +0000166};
167
David Majnemer2206bf52014-03-05 08:57:59 +0000168/// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
169/// Microsoft Visual C++ ABI.
170class MicrosoftCXXNameMangler {
171 MicrosoftMangleContextImpl &Context;
172 raw_ostream &Out;
173
174 /// The "structor" is the top-level declaration being mangled, if
175 /// that's not a template specialization; otherwise it's the pattern
176 /// for that specialization.
177 const NamedDecl *Structor;
178 unsigned StructorType;
179
180 typedef llvm::StringMap<unsigned> BackRefMap;
181 BackRefMap NameBackReferences;
182 bool UseNameBackReferences;
183
184 typedef llvm::DenseMap<void*, unsigned> ArgBackRefMap;
185 ArgBackRefMap TypeBackReferences;
186
187 ASTContext &getASTContext() const { return Context.getASTContext(); }
188
189 // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
190 // this check into mangleQualifiers().
191 const bool PointersAre64Bit;
192
193public:
194 enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
195
196 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
197 : Context(C), Out(Out_),
198 Structor(0), StructorType(-1),
199 UseNameBackReferences(true),
200 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
201 64) { }
202
203 MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
204 const CXXDestructorDecl *D, CXXDtorType Type)
205 : Context(C), Out(Out_),
206 Structor(getStructor(D)), StructorType(Type),
207 UseNameBackReferences(true),
208 PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
209 64) { }
210
211 raw_ostream &getStream() const { return Out; }
212
213 void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
214 void mangleName(const NamedDecl *ND);
David Majnemer2206bf52014-03-05 08:57:59 +0000215 void mangleFunctionEncoding(const FunctionDecl *FD);
216 void mangleVariableEncoding(const VarDecl *VD);
217 void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
218 void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
219 const CXXMethodDecl *MD);
220 void mangleVirtualMemPtrThunk(
221 const CXXMethodDecl *MD,
222 const MicrosoftVTableContext::MethodVFTableLocation &ML);
223 void mangleNumber(int64_t Number);
224 void mangleType(QualType T, SourceRange Range,
225 QualifierMangleMode QMM = QMM_Mangle);
226 void mangleFunctionType(const FunctionType *T, const FunctionDecl *D = 0,
227 bool ForceInstMethod = false);
228 void mangleNestedName(const NamedDecl *ND);
229
230private:
231 void disableBackReferences() { UseNameBackReferences = false; }
232 void mangleUnqualifiedName(const NamedDecl *ND) {
233 mangleUnqualifiedName(ND, ND->getDeclName());
234 }
235 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
236 void mangleSourceName(StringRef Name);
237 void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
238 void mangleCXXDtorType(CXXDtorType T);
239 void mangleQualifiers(Qualifiers Quals, bool IsMember);
240 void manglePointerCVQualifiers(Qualifiers Quals);
241 void manglePointerExtQualifiers(Qualifiers Quals, const Type *PointeeType);
242
243 void mangleUnscopedTemplateName(const TemplateDecl *ND);
244 void mangleTemplateInstantiationName(const TemplateDecl *TD,
245 const TemplateArgumentList &TemplateArgs);
246 void mangleObjCMethodName(const ObjCMethodDecl *MD);
247
248 void mangleArgumentType(QualType T, SourceRange Range);
249
250 // Declare manglers for every type class.
251#define ABSTRACT_TYPE(CLASS, PARENT)
252#define NON_CANONICAL_TYPE(CLASS, PARENT)
253#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
254 SourceRange Range);
255#include "clang/AST/TypeNodes.def"
256#undef ABSTRACT_TYPE
257#undef NON_CANONICAL_TYPE
258#undef TYPE
259
260 void mangleType(const TagDecl *TD);
261 void mangleDecayedArrayType(const ArrayType *T);
262 void mangleArrayType(const ArrayType *T);
263 void mangleFunctionClass(const FunctionDecl *FD);
264 void mangleCallingConvention(const FunctionType *T);
265 void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
266 void mangleExpression(const Expr *E);
267 void mangleThrowSpecification(const FunctionProtoType *T);
268
269 void mangleTemplateArgs(const TemplateDecl *TD,
270 const TemplateArgumentList &TemplateArgs);
271 void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA);
272};
Guy Benyei11169dd2012-12-18 14:30:41 +0000273}
274
Rafael Espindola002667c2013-10-16 01:40:34 +0000275bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
David Majnemerd5a42b82013-09-13 09:03:14 +0000276 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
277 LanguageLinkage L = FD->getLanguageLinkage();
278 // Overloadable functions need mangling.
279 if (FD->hasAttr<OverloadableAttr>())
280 return true;
281
David Majnemerc729b0b2013-09-16 22:44:20 +0000282 // The ABI expects that we would never mangle "typical" user-defined entry
283 // points regardless of visibility or freestanding-ness.
284 //
285 // N.B. This is distinct from asking about "main". "main" has a lot of
286 // special rules associated with it in the standard while these
287 // user-defined entry points are outside of the purview of the standard.
288 // For example, there can be only one definition for "main" in a standards
289 // compliant program; however nothing forbids the existence of wmain and
290 // WinMain in the same translation unit.
291 if (FD->isMSVCRTEntryPoint())
David Majnemerd5a42b82013-09-13 09:03:14 +0000292 return false;
293
294 // C++ functions and those whose names are not a simple identifier need
295 // mangling.
296 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
297 return true;
298
299 // C functions are not mangled.
300 if (L == CLanguageLinkage)
301 return false;
302 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000303
304 // Otherwise, no mangling is done outside C++ mode.
305 if (!getASTContext().getLangOpts().CPlusPlus)
306 return false;
307
David Majnemerd5a42b82013-09-13 09:03:14 +0000308 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
309 // C variables are not mangled.
310 if (VD->isExternC())
311 return false;
312
313 // Variables at global scope with non-internal linkage are not mangled.
314 const DeclContext *DC = getEffectiveDeclContext(D);
315 // Check for extern variable declared locally.
316 if (DC->isFunctionOrMethod() && D->hasLinkage())
317 while (!DC->isNamespace() && !DC->isTranslationUnit())
318 DC = getEffectiveParentContext(DC);
319
320 if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
321 !isa<VarTemplateSpecializationDecl>(D))
Guy Benyei11169dd2012-12-18 14:30:41 +0000322 return false;
323 }
324
Guy Benyei11169dd2012-12-18 14:30:41 +0000325 return true;
326}
327
David Majnemer58e5bee2014-03-24 21:43:36 +0000328bool
329MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
330 return SL->isAscii() || SL->isWide();
331 // TODO: This needs to be updated when MSVC gains support for Unicode
332 // literals.
333}
334
Guy Benyei11169dd2012-12-18 14:30:41 +0000335void MicrosoftCXXNameMangler::mangle(const NamedDecl *D,
336 StringRef Prefix) {
337 // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
338 // Therefore it's really important that we don't decorate the
339 // name with leading underscores or leading/trailing at signs. So, by
340 // default, we emit an asm marker at the start so we get the name right.
341 // Callers can override this with a custom prefix.
342
Guy Benyei11169dd2012-12-18 14:30:41 +0000343 // <mangled-name> ::= ? <name> <type-encoding>
344 Out << Prefix;
345 mangleName(D);
346 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
347 mangleFunctionEncoding(FD);
348 else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
349 mangleVariableEncoding(VD);
350 else {
351 // TODO: Fields? Can MSVC even mangle them?
352 // Issue a diagnostic for now.
353 DiagnosticsEngine &Diags = Context.getDiags();
354 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
355 "cannot mangle this declaration yet");
356 Diags.Report(D->getLocation(), DiagID)
357 << D->getSourceRange();
358 }
359}
360
361void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
362 // <type-encoding> ::= <function-class> <function-type>
363
Reid Kleckner18da98e2013-06-24 19:21:52 +0000364 // Since MSVC operates on the type as written and not the canonical type, it
365 // actually matters which decl we have here. MSVC appears to choose the
366 // first, since it is most likely to be the declaration in a header file.
Rafael Espindola8db352d2013-10-17 15:37:26 +0000367 FD = FD->getFirstDecl();
Reid Kleckner18da98e2013-06-24 19:21:52 +0000368
Guy Benyei11169dd2012-12-18 14:30:41 +0000369 // We should never ever see a FunctionNoProtoType at this point.
370 // We don't even know how to mangle their types anyway :).
Reid Kleckner9a7f3e62013-10-08 00:58:57 +0000371 const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
Guy Benyei11169dd2012-12-18 14:30:41 +0000372
David Majnemerd5a42b82013-09-13 09:03:14 +0000373 // extern "C" functions can hold entities that must be mangled.
374 // As it stands, these functions still need to get expressed in the full
375 // external name. They have their class and type omitted, replaced with '9'.
376 if (Context.shouldMangleDeclName(FD)) {
377 // First, the function class.
378 mangleFunctionClass(FD);
Guy Benyei11169dd2012-12-18 14:30:41 +0000379
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +0000380 mangleFunctionType(FT, FD);
David Majnemerd5a42b82013-09-13 09:03:14 +0000381 } else
382 Out << '9';
Guy Benyei11169dd2012-12-18 14:30:41 +0000383}
384
385void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
386 // <type-encoding> ::= <storage-class> <variable-type>
387 // <storage-class> ::= 0 # private static member
388 // ::= 1 # protected static member
389 // ::= 2 # public static member
390 // ::= 3 # global
391 // ::= 4 # static local
David Majnemerb4119f72013-12-13 01:06:04 +0000392
Guy Benyei11169dd2012-12-18 14:30:41 +0000393 // The first character in the encoding (after the name) is the storage class.
394 if (VD->isStaticDataMember()) {
395 // If it's a static member, it also encodes the access level.
396 switch (VD->getAccess()) {
397 default:
398 case AS_private: Out << '0'; break;
399 case AS_protected: Out << '1'; break;
400 case AS_public: Out << '2'; break;
401 }
402 }
403 else if (!VD->isStaticLocal())
404 Out << '3';
405 else
406 Out << '4';
407 // Now mangle the type.
408 // <variable-type> ::= <type> <cvr-qualifiers>
409 // ::= <type> <pointee-cvr-qualifiers> # pointers, references
410 // Pointers and references are odd. The type of 'int * const foo;' gets
411 // mangled as 'QAHA' instead of 'PAHB', for example.
412 TypeLoc TL = VD->getTypeSourceInfo()->getTypeLoc();
David Majnemerb9a5f2d2014-01-21 20:33:36 +0000413 QualType Ty = VD->getType();
David Majnemer6dda7bb2013-08-15 08:13:23 +0000414 if (Ty->isPointerType() || Ty->isReferenceType() ||
415 Ty->isMemberPointerType()) {
David Majnemera2724ae2013-08-09 05:56:24 +0000416 mangleType(Ty, TL.getSourceRange(), QMM_Drop);
David Majnemer8eec58f2014-02-18 14:20:10 +0000417 manglePointerExtQualifiers(
418 Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), 0);
David Majnemer6dda7bb2013-08-15 08:13:23 +0000419 if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
420 mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
421 // Member pointers are suffixed with a back reference to the member
422 // pointer's class name.
423 mangleName(MPT->getClass()->getAsCXXRecordDecl());
424 } else
425 mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
David Majnemera2724ae2013-08-09 05:56:24 +0000426 } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000427 // Global arrays are funny, too.
David Majnemer5a1b2042013-09-11 04:44:30 +0000428 mangleDecayedArrayType(AT);
Peter Collingbourne2816c022013-04-25 04:25:40 +0000429 if (AT->getElementType()->isArrayType())
430 Out << 'A';
431 else
432 mangleQualifiers(Ty.getQualifiers(), false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000433 } else {
Peter Collingbourne2816c022013-04-25 04:25:40 +0000434 mangleType(Ty, TL.getSourceRange(), QMM_Drop);
David Majnemer6dda7bb2013-08-15 08:13:23 +0000435 mangleQualifiers(Ty.getLocalQualifiers(), false);
Guy Benyei11169dd2012-12-18 14:30:41 +0000436 }
437}
438
Reid Kleckner96f8f932014-02-05 17:27:08 +0000439void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
David Majnemer1e378e42014-02-06 12:46:52 +0000440 const ValueDecl *VD) {
Reid Kleckner96f8f932014-02-05 17:27:08 +0000441 // <member-data-pointer> ::= <integer-literal>
442 // ::= $F <number> <number>
443 // ::= $G <number> <number> <number>
444
David Majnemer763584d2014-02-06 10:59:19 +0000445 int64_t FieldOffset;
446 int64_t VBTableOffset;
Reid Kleckner96f8f932014-02-05 17:27:08 +0000447 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
David Majnemer1e378e42014-02-06 12:46:52 +0000448 if (VD) {
449 FieldOffset = getASTContext().getFieldOffset(VD);
David Majnemer763584d2014-02-06 10:59:19 +0000450 assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
Reid Kleckner96f8f932014-02-05 17:27:08 +0000451 "cannot take address of bitfield");
David Majnemer763584d2014-02-06 10:59:19 +0000452 FieldOffset /= getASTContext().getCharWidth();
453
454 VBTableOffset = 0;
455 } else {
456 FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
457
458 VBTableOffset = -1;
Reid Kleckner96f8f932014-02-05 17:27:08 +0000459 }
460
David Majnemer763584d2014-02-06 10:59:19 +0000461 char Code = '\0';
Reid Kleckner96f8f932014-02-05 17:27:08 +0000462 switch (IM) {
David Majnemer763584d2014-02-06 10:59:19 +0000463 case MSInheritanceAttr::Keyword_single_inheritance: Code = '0'; break;
464 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = '0'; break;
465 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'F'; break;
466 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
Reid Kleckner96f8f932014-02-05 17:27:08 +0000467 }
468
David Majnemer763584d2014-02-06 10:59:19 +0000469 Out << '$' << Code;
Reid Kleckner96f8f932014-02-05 17:27:08 +0000470
David Majnemer763584d2014-02-06 10:59:19 +0000471 mangleNumber(FieldOffset);
472
473 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
Reid Kleckner96f8f932014-02-05 17:27:08 +0000474 mangleNumber(0);
David Majnemer763584d2014-02-06 10:59:19 +0000475 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
476 mangleNumber(VBTableOffset);
Reid Kleckner96f8f932014-02-05 17:27:08 +0000477}
478
479void
480MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
481 const CXXMethodDecl *MD) {
482 // <member-function-pointer> ::= $1? <name>
483 // ::= $H? <name> <number>
484 // ::= $I? <name> <number> <number>
485 // ::= $J? <name> <number> <number> <number>
486 // ::= $0A@
487
488 MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
489
490 // The null member function pointer is $0A@ in function templates and crashes
491 // MSVC when used in class templates, so we don't know what they really look
492 // like.
493 if (!MD) {
494 Out << "$0A@";
495 return;
496 }
497
498 char Code = '\0';
499 switch (IM) {
500 case MSInheritanceAttr::Keyword_single_inheritance: Code = '1'; break;
501 case MSInheritanceAttr::Keyword_multiple_inheritance: Code = 'H'; break;
502 case MSInheritanceAttr::Keyword_virtual_inheritance: Code = 'I'; break;
503 case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
504 }
505
506 Out << '$' << Code << '?';
507
508 // If non-virtual, mangle the name. If virtual, mangle as a virtual memptr
509 // thunk.
510 uint64_t NVOffset = 0;
511 uint64_t VBTableOffset = 0;
David Majnemer763584d2014-02-06 10:59:19 +0000512 if (MD->isVirtual()) {
Reid Kleckner96f8f932014-02-05 17:27:08 +0000513 MicrosoftVTableContext *VTContext =
514 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
515 const MicrosoftVTableContext::MethodVFTableLocation &ML =
516 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
517 mangleVirtualMemPtrThunk(MD, ML);
518 NVOffset = ML.VFPtrOffset.getQuantity();
519 VBTableOffset = ML.VBTableIndex * 4;
520 if (ML.VBase) {
521 DiagnosticsEngine &Diags = Context.getDiags();
522 unsigned DiagID = Diags.getCustomDiagID(
523 DiagnosticsEngine::Error,
524 "cannot mangle pointers to member functions from virtual bases");
525 Diags.Report(MD->getLocation(), DiagID);
526 }
527 } else {
528 mangleName(MD);
529 mangleFunctionEncoding(MD);
530 }
531
532 if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
533 mangleNumber(NVOffset);
534 if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
535 mangleNumber(0);
536 if (MSInheritanceAttr::hasVBTableOffsetField(IM))
537 mangleNumber(VBTableOffset);
538}
539
540void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
541 const CXXMethodDecl *MD,
542 const MicrosoftVTableContext::MethodVFTableLocation &ML) {
543 // Get the vftable offset.
544 CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
545 getASTContext().getTargetInfo().getPointerWidth(0));
546 uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
547
548 Out << "?_9";
549 mangleName(MD->getParent());
550 Out << "$B";
551 mangleNumber(OffsetInVFTable);
552 Out << 'A';
553 Out << (PointersAre64Bit ? 'A' : 'E');
554}
555
Guy Benyei11169dd2012-12-18 14:30:41 +0000556void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
557 // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
Guy Benyei11169dd2012-12-18 14:30:41 +0000558
559 // Always start with the unqualified name.
David Majnemerb4119f72013-12-13 01:06:04 +0000560 mangleUnqualifiedName(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +0000561
David Majnemer2206bf52014-03-05 08:57:59 +0000562 mangleNestedName(ND);
Guy Benyei11169dd2012-12-18 14:30:41 +0000563
564 // Terminate the whole name with an '@'.
565 Out << '@';
566}
567
David Majnemer2a816452013-12-09 10:44:32 +0000568void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
569 // <non-negative integer> ::= A@ # when Number == 0
570 // ::= <decimal digit> # when 1 <= Number <= 10
571 // ::= <hex digit>+ @ # when Number >= 10
572 //
573 // <number> ::= [?] <non-negative integer>
Guy Benyei11169dd2012-12-18 14:30:41 +0000574
David Majnemer2a816452013-12-09 10:44:32 +0000575 uint64_t Value = static_cast<uint64_t>(Number);
576 if (Number < 0) {
577 Value = -Value;
Guy Benyei11169dd2012-12-18 14:30:41 +0000578 Out << '?';
Guy Benyei11169dd2012-12-18 14:30:41 +0000579 }
David Majnemer2a816452013-12-09 10:44:32 +0000580
581 if (Value == 0)
582 Out << "A@";
583 else if (Value >= 1 && Value <= 10)
584 Out << (Value - 1);
585 else {
586 // Numbers that are not encoded as decimal digits are represented as nibbles
587 // in the range of ASCII characters 'A' to 'P'.
588 // The number 0x123450 would be encoded as 'BCDEFA'
589 char EncodedNumberBuffer[sizeof(uint64_t) * 2];
590 llvm::MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
591 llvm::MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
592 for (; Value != 0; Value >>= 4)
593 *I++ = 'A' + (Value & 0xf);
594 Out.write(I.base(), I - BufferRef.rbegin());
Guy Benyei11169dd2012-12-18 14:30:41 +0000595 Out << '@';
596 }
597}
598
599static const TemplateDecl *
Reid Kleckner52518862013-03-20 01:40:23 +0000600isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000601 // Check if we have a function template.
602 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
603 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
Reid Kleckner52518862013-03-20 01:40:23 +0000604 TemplateArgs = FD->getTemplateSpecializationArgs();
Guy Benyei11169dd2012-12-18 14:30:41 +0000605 return TD;
606 }
607 }
608
609 // Check if we have a class template.
610 if (const ClassTemplateSpecializationDecl *Spec =
Reid Kleckner52518862013-03-20 01:40:23 +0000611 dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
612 TemplateArgs = &Spec->getTemplateArgs();
Guy Benyei11169dd2012-12-18 14:30:41 +0000613 return Spec->getSpecializedTemplate();
614 }
615
David Majnemer8f774532014-03-04 05:38:05 +0000616 // Check if we have a variable template.
617 if (const VarTemplateSpecializationDecl *Spec =
618 dyn_cast<VarTemplateSpecializationDecl>(ND)) {
619 TemplateArgs = &Spec->getTemplateArgs();
620 return Spec->getSpecializedTemplate();
621 }
622
Guy Benyei11169dd2012-12-18 14:30:41 +0000623 return 0;
624}
625
626void
627MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
628 DeclarationName Name) {
629 // <unqualified-name> ::= <operator-name>
630 // ::= <ctor-dtor-name>
631 // ::= <source-name>
632 // ::= <template-name>
Reid Kleckner52518862013-03-20 01:40:23 +0000633
Guy Benyei11169dd2012-12-18 14:30:41 +0000634 // Check if we have a template.
Reid Kleckner52518862013-03-20 01:40:23 +0000635 const TemplateArgumentList *TemplateArgs = 0;
Guy Benyei11169dd2012-12-18 14:30:41 +0000636 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
Reid Klecknerc16c4472013-07-13 00:43:39 +0000637 // Function templates aren't considered for name back referencing. This
638 // makes sense since function templates aren't likely to occur multiple
639 // times in a symbol.
640 // FIXME: Test alias template mangling with MSVC 2013.
641 if (!isa<ClassTemplateDecl>(TD)) {
642 mangleTemplateInstantiationName(TD, *TemplateArgs);
643 return;
644 }
645
Guy Benyei11169dd2012-12-18 14:30:41 +0000646 // Here comes the tricky thing: if we need to mangle something like
647 // void foo(A::X<Y>, B::X<Y>),
648 // the X<Y> part is aliased. However, if you need to mangle
649 // void foo(A::X<A::Y>, A::X<B::Y>),
650 // the A::X<> part is not aliased.
651 // That said, from the mangler's perspective we have a structure like this:
652 // namespace[s] -> type[ -> template-parameters]
653 // but from the Clang perspective we have
654 // type [ -> template-parameters]
655 // \-> namespace[s]
656 // What we do is we create a new mangler, mangle the same type (without
657 // a namespace suffix) using the extra mangler with back references
658 // disabled (to avoid infinite recursion) and then use the mangled type
659 // name as a key to check the mangling of different types for aliasing.
660
661 std::string BackReferenceKey;
662 BackRefMap::iterator Found;
663 if (UseNameBackReferences) {
664 llvm::raw_string_ostream Stream(BackReferenceKey);
665 MicrosoftCXXNameMangler Extra(Context, Stream);
666 Extra.disableBackReferences();
667 Extra.mangleUnqualifiedName(ND, Name);
668 Stream.flush();
669
670 Found = NameBackReferences.find(BackReferenceKey);
671 }
672 if (!UseNameBackReferences || Found == NameBackReferences.end()) {
Reid Kleckner52518862013-03-20 01:40:23 +0000673 mangleTemplateInstantiationName(TD, *TemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +0000674 if (UseNameBackReferences && NameBackReferences.size() < 10) {
675 size_t Size = NameBackReferences.size();
676 NameBackReferences[BackReferenceKey] = Size;
677 }
678 } else {
679 Out << Found->second;
680 }
681 return;
682 }
683
684 switch (Name.getNameKind()) {
685 case DeclarationName::Identifier: {
686 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
David Majnemer956bc112013-11-25 17:50:19 +0000687 mangleSourceName(II->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +0000688 break;
689 }
David Majnemerb4119f72013-12-13 01:06:04 +0000690
Guy Benyei11169dd2012-12-18 14:30:41 +0000691 // Otherwise, an anonymous entity. We must have a declaration.
692 assert(ND && "mangling empty name without declaration");
David Majnemerb4119f72013-12-13 01:06:04 +0000693
Guy Benyei11169dd2012-12-18 14:30:41 +0000694 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
695 if (NS->isAnonymousNamespace()) {
696 Out << "?A@";
697 break;
698 }
699 }
David Majnemerb4119f72013-12-13 01:06:04 +0000700
David Majnemer2206bf52014-03-05 08:57:59 +0000701 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
702 // We must have an anonymous union or struct declaration.
703 const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
704 assert(RD && "expected variable decl to have a record type");
705 // Anonymous types with no tag or typedef get the name of their
706 // declarator mangled in. If they have no declarator, number them with
707 // a $S prefix.
708 llvm::SmallString<64> Name("$S");
709 // Get a unique id for the anonymous struct.
710 Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
711 mangleSourceName(Name.str());
712 break;
713 }
714
Guy Benyei11169dd2012-12-18 14:30:41 +0000715 // We must have an anonymous struct.
716 const TagDecl *TD = cast<TagDecl>(ND);
717 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
718 assert(TD->getDeclContext() == D->getDeclContext() &&
719 "Typedef should not be in another decl context!");
720 assert(D->getDeclName().getAsIdentifierInfo() &&
721 "Typedef was not named!");
David Majnemer956bc112013-11-25 17:50:19 +0000722 mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
Guy Benyei11169dd2012-12-18 14:30:41 +0000723 break;
724 }
725
David Majnemerf017ec32014-03-05 10:35:06 +0000726 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
727 if (Record->isLambda()) {
728 llvm::SmallString<10> Name("<lambda_");
729 unsigned LambdaId;
730 if (Record->getLambdaManglingNumber())
731 LambdaId = Record->getLambdaManglingNumber();
732 else
733 LambdaId = Context.getLambdaId(Record);
734
735 Name += llvm::utostr(LambdaId);
736 Name += ">";
737
738 mangleSourceName(Name);
739 break;
740 }
741 }
742
David Majnemer2206bf52014-03-05 08:57:59 +0000743 llvm::SmallString<64> Name("<unnamed-type-");
David Majnemer956bc112013-11-25 17:50:19 +0000744 if (TD->hasDeclaratorForAnonDecl()) {
David Majnemer50ce8352013-09-17 23:57:10 +0000745 // Anonymous types with no tag or typedef get the name of their
David Majnemer2206bf52014-03-05 08:57:59 +0000746 // declarator mangled in if they have one.
David Majnemer956bc112013-11-25 17:50:19 +0000747 Name += TD->getDeclaratorForAnonDecl()->getName();
David Majnemer956bc112013-11-25 17:50:19 +0000748 } else {
David Majnemer2206bf52014-03-05 08:57:59 +0000749 // Otherwise, number the types using a $S prefix.
750 Name += "$S";
David Majnemerf017ec32014-03-05 10:35:06 +0000751 Name += llvm::utostr(Context.getAnonymousStructId(TD));
David Majnemer956bc112013-11-25 17:50:19 +0000752 }
David Majnemer2206bf52014-03-05 08:57:59 +0000753 Name += ">";
754 mangleSourceName(Name.str());
Guy Benyei11169dd2012-12-18 14:30:41 +0000755 break;
756 }
David Majnemerb4119f72013-12-13 01:06:04 +0000757
Guy Benyei11169dd2012-12-18 14:30:41 +0000758 case DeclarationName::ObjCZeroArgSelector:
759 case DeclarationName::ObjCOneArgSelector:
760 case DeclarationName::ObjCMultiArgSelector:
761 llvm_unreachable("Can't mangle Objective-C selector names here!");
David Majnemerb4119f72013-12-13 01:06:04 +0000762
Guy Benyei11169dd2012-12-18 14:30:41 +0000763 case DeclarationName::CXXConstructorName:
Timur Iskhodzhanov57cbe5c2013-02-27 13:46:31 +0000764 if (ND == Structor) {
765 assert(StructorType == Ctor_Complete &&
766 "Should never be asked to mangle a ctor other than complete");
767 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000768 Out << "?0";
769 break;
David Majnemerb4119f72013-12-13 01:06:04 +0000770
Guy Benyei11169dd2012-12-18 14:30:41 +0000771 case DeclarationName::CXXDestructorName:
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000772 if (ND == Structor)
773 // If the named decl is the C++ destructor we're mangling,
774 // use the type we were given.
775 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
776 else
Reid Klecknere7de47e2013-07-22 13:51:44 +0000777 // Otherwise, use the base destructor name. This is relevant if a
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000778 // class with a destructor is declared within a destructor.
Reid Klecknere7de47e2013-07-22 13:51:44 +0000779 mangleCXXDtorType(Dtor_Base);
Guy Benyei11169dd2012-12-18 14:30:41 +0000780 break;
David Majnemerb4119f72013-12-13 01:06:04 +0000781
Guy Benyei11169dd2012-12-18 14:30:41 +0000782 case DeclarationName::CXXConversionFunctionName:
783 // <operator-name> ::= ?B # (cast)
784 // The target type is encoded as the return type.
785 Out << "?B";
786 break;
David Majnemerb4119f72013-12-13 01:06:04 +0000787
Guy Benyei11169dd2012-12-18 14:30:41 +0000788 case DeclarationName::CXXOperatorName:
789 mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
790 break;
David Majnemerb4119f72013-12-13 01:06:04 +0000791
Guy Benyei11169dd2012-12-18 14:30:41 +0000792 case DeclarationName::CXXLiteralOperatorName: {
793 // FIXME: Was this added in VS2010? Does MS even know how to mangle this?
794 DiagnosticsEngine Diags = Context.getDiags();
795 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
796 "cannot mangle this literal operator yet");
797 Diags.Report(ND->getLocation(), DiagID);
798 break;
799 }
David Majnemerb4119f72013-12-13 01:06:04 +0000800
Guy Benyei11169dd2012-12-18 14:30:41 +0000801 case DeclarationName::CXXUsingDirective:
802 llvm_unreachable("Can't mangle a using directive name!");
803 }
804}
805
David Majnemer2206bf52014-03-05 08:57:59 +0000806void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
Guy Benyei11169dd2012-12-18 14:30:41 +0000807 // <postfix> ::= <unqualified-name> [<postfix>]
808 // ::= <substitution> [<postfix>]
David Majnemerf017ec32014-03-05 10:35:06 +0000809 if (isLambda(ND))
810 return;
811
David Majnemer2206bf52014-03-05 08:57:59 +0000812 const DeclContext *DC = ND->getDeclContext();
Guy Benyei11169dd2012-12-18 14:30:41 +0000813
David Majnemer2206bf52014-03-05 08:57:59 +0000814 while (!DC->isTranslationUnit()) {
815 if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
816 unsigned Disc;
817 if (Context.getNextDiscriminator(ND, Disc)) {
818 Out << '?';
819 mangleNumber(Disc);
820 Out << '?';
821 }
822 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000823
David Majnemer2206bf52014-03-05 08:57:59 +0000824 if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
825 DiagnosticsEngine Diags = Context.getDiags();
826 unsigned DiagID =
827 Diags.getCustomDiagID(DiagnosticsEngine::Error,
828 "cannot mangle a local inside this block yet");
829 Diags.Report(BD->getLocation(), DiagID);
830
831 // FIXME: This is completely, utterly, wrong; see ItaniumMangle
832 // for how this should be done.
833 Out << "__block_invoke" << Context.getBlockId(BD, false);
834 Out << '@';
835 continue;
836 } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
837 mangleObjCMethodName(Method);
838 } else if (isa<NamedDecl>(DC)) {
839 ND = cast<NamedDecl>(DC);
840 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
841 mangle(FD, "?");
842 break;
843 } else
844 mangleUnqualifiedName(ND);
845 }
Guy Benyei11169dd2012-12-18 14:30:41 +0000846 DC = DC->getParent();
Guy Benyei11169dd2012-12-18 14:30:41 +0000847 }
848}
849
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000850void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000851 // Microsoft uses the names on the case labels for these dtor variants. Clang
852 // uses the Itanium terminology internally. Everything in this ABI delegates
853 // towards the base dtor.
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000854 switch (T) {
Reid Klecknere7de47e2013-07-22 13:51:44 +0000855 // <operator-name> ::= ?1 # destructor
856 case Dtor_Base: Out << "?1"; return;
857 // <operator-name> ::= ?_D # vbase destructor
858 case Dtor_Complete: Out << "?_D"; return;
859 // <operator-name> ::= ?_G # scalar deleting destructor
860 case Dtor_Deleting: Out << "?_G"; return;
861 // <operator-name> ::= ?_E # vector deleting destructor
862 // FIXME: Add a vector deleting dtor type. It goes in the vtable, so we need
863 // it.
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +0000864 }
865 llvm_unreachable("Unsupported dtor type?");
866}
867
Guy Benyei11169dd2012-12-18 14:30:41 +0000868void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
869 SourceLocation Loc) {
870 switch (OO) {
871 // ?0 # constructor
872 // ?1 # destructor
873 // <operator-name> ::= ?2 # new
874 case OO_New: Out << "?2"; break;
875 // <operator-name> ::= ?3 # delete
876 case OO_Delete: Out << "?3"; break;
877 // <operator-name> ::= ?4 # =
878 case OO_Equal: Out << "?4"; break;
879 // <operator-name> ::= ?5 # >>
880 case OO_GreaterGreater: Out << "?5"; break;
881 // <operator-name> ::= ?6 # <<
882 case OO_LessLess: Out << "?6"; break;
883 // <operator-name> ::= ?7 # !
884 case OO_Exclaim: Out << "?7"; break;
885 // <operator-name> ::= ?8 # ==
886 case OO_EqualEqual: Out << "?8"; break;
887 // <operator-name> ::= ?9 # !=
888 case OO_ExclaimEqual: Out << "?9"; break;
889 // <operator-name> ::= ?A # []
890 case OO_Subscript: Out << "?A"; break;
891 // ?B # conversion
892 // <operator-name> ::= ?C # ->
893 case OO_Arrow: Out << "?C"; break;
894 // <operator-name> ::= ?D # *
895 case OO_Star: Out << "?D"; break;
896 // <operator-name> ::= ?E # ++
897 case OO_PlusPlus: Out << "?E"; break;
898 // <operator-name> ::= ?F # --
899 case OO_MinusMinus: Out << "?F"; break;
900 // <operator-name> ::= ?G # -
901 case OO_Minus: Out << "?G"; break;
902 // <operator-name> ::= ?H # +
903 case OO_Plus: Out << "?H"; break;
904 // <operator-name> ::= ?I # &
905 case OO_Amp: Out << "?I"; break;
906 // <operator-name> ::= ?J # ->*
907 case OO_ArrowStar: Out << "?J"; break;
908 // <operator-name> ::= ?K # /
909 case OO_Slash: Out << "?K"; break;
910 // <operator-name> ::= ?L # %
911 case OO_Percent: Out << "?L"; break;
912 // <operator-name> ::= ?M # <
913 case OO_Less: Out << "?M"; break;
914 // <operator-name> ::= ?N # <=
915 case OO_LessEqual: Out << "?N"; break;
916 // <operator-name> ::= ?O # >
917 case OO_Greater: Out << "?O"; break;
918 // <operator-name> ::= ?P # >=
919 case OO_GreaterEqual: Out << "?P"; break;
920 // <operator-name> ::= ?Q # ,
921 case OO_Comma: Out << "?Q"; break;
922 // <operator-name> ::= ?R # ()
923 case OO_Call: Out << "?R"; break;
924 // <operator-name> ::= ?S # ~
925 case OO_Tilde: Out << "?S"; break;
926 // <operator-name> ::= ?T # ^
927 case OO_Caret: Out << "?T"; break;
928 // <operator-name> ::= ?U # |
929 case OO_Pipe: Out << "?U"; break;
930 // <operator-name> ::= ?V # &&
931 case OO_AmpAmp: Out << "?V"; break;
932 // <operator-name> ::= ?W # ||
933 case OO_PipePipe: Out << "?W"; break;
934 // <operator-name> ::= ?X # *=
935 case OO_StarEqual: Out << "?X"; break;
936 // <operator-name> ::= ?Y # +=
937 case OO_PlusEqual: Out << "?Y"; break;
938 // <operator-name> ::= ?Z # -=
939 case OO_MinusEqual: Out << "?Z"; break;
940 // <operator-name> ::= ?_0 # /=
941 case OO_SlashEqual: Out << "?_0"; break;
942 // <operator-name> ::= ?_1 # %=
943 case OO_PercentEqual: Out << "?_1"; break;
944 // <operator-name> ::= ?_2 # >>=
945 case OO_GreaterGreaterEqual: Out << "?_2"; break;
946 // <operator-name> ::= ?_3 # <<=
947 case OO_LessLessEqual: Out << "?_3"; break;
948 // <operator-name> ::= ?_4 # &=
949 case OO_AmpEqual: Out << "?_4"; break;
950 // <operator-name> ::= ?_5 # |=
951 case OO_PipeEqual: Out << "?_5"; break;
952 // <operator-name> ::= ?_6 # ^=
953 case OO_CaretEqual: Out << "?_6"; break;
954 // ?_7 # vftable
955 // ?_8 # vbtable
956 // ?_9 # vcall
957 // ?_A # typeof
958 // ?_B # local static guard
959 // ?_C # string
960 // ?_D # vbase destructor
961 // ?_E # vector deleting destructor
962 // ?_F # default constructor closure
963 // ?_G # scalar deleting destructor
964 // ?_H # vector constructor iterator
965 // ?_I # vector destructor iterator
966 // ?_J # vector vbase constructor iterator
967 // ?_K # virtual displacement map
968 // ?_L # eh vector constructor iterator
969 // ?_M # eh vector destructor iterator
970 // ?_N # eh vector vbase constructor iterator
971 // ?_O # copy constructor closure
972 // ?_P<name> # udt returning <name>
973 // ?_Q # <unknown>
974 // ?_R0 # RTTI Type Descriptor
975 // ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
976 // ?_R2 # RTTI Base Class Array
977 // ?_R3 # RTTI Class Hierarchy Descriptor
978 // ?_R4 # RTTI Complete Object Locator
979 // ?_S # local vftable
980 // ?_T # local vftable constructor closure
981 // <operator-name> ::= ?_U # new[]
982 case OO_Array_New: Out << "?_U"; break;
983 // <operator-name> ::= ?_V # delete[]
984 case OO_Array_Delete: Out << "?_V"; break;
David Majnemerb4119f72013-12-13 01:06:04 +0000985
Guy Benyei11169dd2012-12-18 14:30:41 +0000986 case OO_Conditional: {
987 DiagnosticsEngine &Diags = Context.getDiags();
988 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
989 "cannot mangle this conditional operator yet");
990 Diags.Report(Loc, DiagID);
991 break;
992 }
David Majnemerb4119f72013-12-13 01:06:04 +0000993
Guy Benyei11169dd2012-12-18 14:30:41 +0000994 case OO_None:
995 case NUM_OVERLOADED_OPERATORS:
996 llvm_unreachable("Not an overloaded operator");
997 }
998}
999
David Majnemer956bc112013-11-25 17:50:19 +00001000void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001001 // <source name> ::= <identifier> @
Guy Benyei11169dd2012-12-18 14:30:41 +00001002 BackRefMap::iterator Found;
1003 if (UseNameBackReferences)
David Majnemer956bc112013-11-25 17:50:19 +00001004 Found = NameBackReferences.find(Name);
Guy Benyei11169dd2012-12-18 14:30:41 +00001005 if (!UseNameBackReferences || Found == NameBackReferences.end()) {
David Majnemer956bc112013-11-25 17:50:19 +00001006 Out << Name << '@';
Guy Benyei11169dd2012-12-18 14:30:41 +00001007 if (UseNameBackReferences && NameBackReferences.size() < 10) {
1008 size_t Size = NameBackReferences.size();
David Majnemer956bc112013-11-25 17:50:19 +00001009 NameBackReferences[Name] = Size;
Guy Benyei11169dd2012-12-18 14:30:41 +00001010 }
1011 } else {
1012 Out << Found->second;
1013 }
1014}
1015
1016void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1017 Context.mangleObjCMethodName(MD, Out);
1018}
1019
Guy Benyei11169dd2012-12-18 14:30:41 +00001020void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1021 const TemplateDecl *TD,
Reid Kleckner52518862013-03-20 01:40:23 +00001022 const TemplateArgumentList &TemplateArgs) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001023 // <template-name> ::= <unscoped-template-name> <template-args>
1024 // ::= <substitution>
1025 // Always start with the unqualified name.
1026
1027 // Templates have their own context for back references.
1028 ArgBackRefMap OuterArgsContext;
1029 BackRefMap OuterTemplateContext;
1030 NameBackReferences.swap(OuterTemplateContext);
1031 TypeBackReferences.swap(OuterArgsContext);
1032
1033 mangleUnscopedTemplateName(TD);
Reid Kleckner52518862013-03-20 01:40:23 +00001034 mangleTemplateArgs(TD, TemplateArgs);
Guy Benyei11169dd2012-12-18 14:30:41 +00001035
1036 // Restore the previous back reference contexts.
1037 NameBackReferences.swap(OuterTemplateContext);
1038 TypeBackReferences.swap(OuterArgsContext);
1039}
1040
1041void
1042MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1043 // <unscoped-template-name> ::= ?$ <unqualified-name>
1044 Out << "?$";
1045 mangleUnqualifiedName(TD);
1046}
1047
1048void
1049MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1050 bool IsBoolean) {
1051 // <integer-literal> ::= $0 <number>
1052 Out << "$0";
1053 // Make sure booleans are encoded as 0/1.
1054 if (IsBoolean && Value.getBoolValue())
1055 mangleNumber(1);
1056 else
David Majnemer2a816452013-12-09 10:44:32 +00001057 mangleNumber(Value.getSExtValue());
Guy Benyei11169dd2012-12-18 14:30:41 +00001058}
1059
1060void
1061MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1062 // See if this is a constant expression.
1063 llvm::APSInt Value;
1064 if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1065 mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1066 return;
1067 }
1068
David Majnemer8eaab6f2013-08-13 06:32:20 +00001069 const CXXUuidofExpr *UE = 0;
1070 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1071 if (UO->getOpcode() == UO_AddrOf)
1072 UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1073 } else
1074 UE = dyn_cast<CXXUuidofExpr>(E);
1075
1076 if (UE) {
1077 // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1078 // const __s_GUID _GUID_{lower case UUID with underscores}
1079 StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
1080 std::string Name = "_GUID_" + Uuid.lower();
1081 std::replace(Name.begin(), Name.end(), '-', '_');
1082
David Majnemere9cab2f2013-08-13 09:17:25 +00001083 // If we had to peek through an address-of operator, treat this like we are
David Majnemer8eaab6f2013-08-13 06:32:20 +00001084 // dealing with a pointer type. Otherwise, treat it like a const reference.
1085 //
1086 // N.B. This matches up with the handling of TemplateArgument::Declaration
1087 // in mangleTemplateArg
1088 if (UE == E)
1089 Out << "$E?";
1090 else
1091 Out << "$1?";
1092 Out << Name << "@@3U__s_GUID@@B";
1093 return;
1094 }
1095
Guy Benyei11169dd2012-12-18 14:30:41 +00001096 // As bad as this diagnostic is, it's better than crashing.
1097 DiagnosticsEngine &Diags = Context.getDiags();
1098 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1099 "cannot yet mangle expression type %0");
1100 Diags.Report(E->getExprLoc(), DiagID)
1101 << E->getStmtClassName() << E->getSourceRange();
1102}
1103
David Majnemer8265dec2014-03-30 16:30:54 +00001104void MicrosoftCXXNameMangler::mangleTemplateArgs(
1105 const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
Reid Kleckner96f8f932014-02-05 17:27:08 +00001106 // <template-args> ::= <template-arg>+ @
David Majnemer8265dec2014-03-30 16:30:54 +00001107 for (const TemplateArgument &TA : TemplateArgs.asArray())
David Majnemer08177c52013-08-27 08:21:25 +00001108 mangleTemplateArg(TD, TA);
Guy Benyei11169dd2012-12-18 14:30:41 +00001109 Out << '@';
1110}
1111
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001112void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
David Majnemer08177c52013-08-27 08:21:25 +00001113 const TemplateArgument &TA) {
Reid Kleckner96f8f932014-02-05 17:27:08 +00001114 // <template-arg> ::= <type>
1115 // ::= <integer-literal>
1116 // ::= <member-data-pointer>
1117 // ::= <member-function-pointer>
1118 // ::= $E? <name> <type-encoding>
1119 // ::= $1? <name> <type-encoding>
1120 // ::= $0A@
1121 // ::= <template-args>
1122
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001123 switch (TA.getKind()) {
1124 case TemplateArgument::Null:
1125 llvm_unreachable("Can't mangle null template arguments!");
David Majnemer08177c52013-08-27 08:21:25 +00001126 case TemplateArgument::TemplateExpansion:
1127 llvm_unreachable("Can't mangle template expansion arguments!");
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001128 case TemplateArgument::Type: {
1129 QualType T = TA.getAsType();
1130 mangleType(T, SourceRange(), QMM_Escape);
1131 break;
1132 }
David Majnemere8fdc062013-08-13 01:25:35 +00001133 case TemplateArgument::Declaration: {
1134 const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
David Majnemer1e378e42014-02-06 12:46:52 +00001135 if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
Reid Klecknere253b092014-02-08 01:15:37 +00001136 mangleMemberDataPointer(
1137 cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
1138 cast<ValueDecl>(ND));
Reid Kleckner09b47d12014-02-05 18:59:38 +00001139 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Nick Lewycky1f529662014-02-05 23:53:29 +00001140 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Reid Kleckner09b47d12014-02-05 18:59:38 +00001141 if (MD && MD->isInstance())
Reid Klecknere253b092014-02-08 01:15:37 +00001142 mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
Reid Kleckner09b47d12014-02-05 18:59:38 +00001143 else
Nick Lewycky1f529662014-02-05 23:53:29 +00001144 mangle(FD, "$1?");
Reid Kleckner09b47d12014-02-05 18:59:38 +00001145 } else {
Reid Kleckner96f8f932014-02-05 17:27:08 +00001146 mangle(ND, TA.isDeclForReferenceParam() ? "$E?" : "$1?");
Reid Kleckner09b47d12014-02-05 18:59:38 +00001147 }
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001148 break;
David Majnemere8fdc062013-08-13 01:25:35 +00001149 }
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001150 case TemplateArgument::Integral:
1151 mangleIntegerLiteral(TA.getAsIntegral(),
1152 TA.getIntegralType()->isBooleanType());
1153 break;
Reid Kleckner96f8f932014-02-05 17:27:08 +00001154 case TemplateArgument::NullPtr: {
1155 QualType T = TA.getNullPtrType();
1156 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
David Majnemer763584d2014-02-06 10:59:19 +00001157 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
Reid Kleckner96f8f932014-02-05 17:27:08 +00001158 if (MPT->isMemberFunctionPointerType())
1159 mangleMemberFunctionPointer(RD, 0);
1160 else
1161 mangleMemberDataPointer(RD, 0);
1162 } else {
1163 Out << "$0A@";
1164 }
David Majnemerae465ef2013-08-05 21:33:59 +00001165 break;
Reid Kleckner96f8f932014-02-05 17:27:08 +00001166 }
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001167 case TemplateArgument::Expression:
1168 mangleExpression(TA.getAsExpr());
1169 break;
1170 case TemplateArgument::Pack:
1171 // Unlike Itanium, there is no character code to indicate an argument pack.
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001172 for (TemplateArgument::pack_iterator I = TA.pack_begin(), E = TA.pack_end();
1173 I != E; ++I)
David Majnemer08177c52013-08-27 08:21:25 +00001174 mangleTemplateArg(TD, *I);
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001175 break;
1176 case TemplateArgument::Template:
David Majnemer0db0ca42013-08-05 22:26:46 +00001177 mangleType(cast<TagDecl>(
1178 TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl()));
1179 break;
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001180 }
1181}
1182
Guy Benyei11169dd2012-12-18 14:30:41 +00001183void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1184 bool IsMember) {
1185 // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1186 // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1187 // 'I' means __restrict (32/64-bit).
1188 // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1189 // keyword!
1190 // <base-cvr-qualifiers> ::= A # near
1191 // ::= B # near const
1192 // ::= C # near volatile
1193 // ::= D # near const volatile
1194 // ::= E # far (16-bit)
1195 // ::= F # far const (16-bit)
1196 // ::= G # far volatile (16-bit)
1197 // ::= H # far const volatile (16-bit)
1198 // ::= I # huge (16-bit)
1199 // ::= J # huge const (16-bit)
1200 // ::= K # huge volatile (16-bit)
1201 // ::= L # huge const volatile (16-bit)
1202 // ::= M <basis> # based
1203 // ::= N <basis> # based const
1204 // ::= O <basis> # based volatile
1205 // ::= P <basis> # based const volatile
1206 // ::= Q # near member
1207 // ::= R # near const member
1208 // ::= S # near volatile member
1209 // ::= T # near const volatile member
1210 // ::= U # far member (16-bit)
1211 // ::= V # far const member (16-bit)
1212 // ::= W # far volatile member (16-bit)
1213 // ::= X # far const volatile member (16-bit)
1214 // ::= Y # huge member (16-bit)
1215 // ::= Z # huge const member (16-bit)
1216 // ::= 0 # huge volatile member (16-bit)
1217 // ::= 1 # huge const volatile member (16-bit)
1218 // ::= 2 <basis> # based member
1219 // ::= 3 <basis> # based const member
1220 // ::= 4 <basis> # based volatile member
1221 // ::= 5 <basis> # based const volatile member
1222 // ::= 6 # near function (pointers only)
1223 // ::= 7 # far function (pointers only)
1224 // ::= 8 # near method (pointers only)
1225 // ::= 9 # far method (pointers only)
1226 // ::= _A <basis> # based function (pointers only)
1227 // ::= _B <basis> # based function (far?) (pointers only)
1228 // ::= _C <basis> # based method (pointers only)
1229 // ::= _D <basis> # based method (far?) (pointers only)
1230 // ::= _E # block (Clang)
1231 // <basis> ::= 0 # __based(void)
1232 // ::= 1 # __based(segment)?
1233 // ::= 2 <name> # __based(name)
1234 // ::= 3 # ?
1235 // ::= 4 # ?
1236 // ::= 5 # not really based
1237 bool HasConst = Quals.hasConst(),
1238 HasVolatile = Quals.hasVolatile();
David Majnemer89594f32013-08-05 22:43:06 +00001239
Guy Benyei11169dd2012-12-18 14:30:41 +00001240 if (!IsMember) {
1241 if (HasConst && HasVolatile) {
1242 Out << 'D';
1243 } else if (HasVolatile) {
1244 Out << 'C';
1245 } else if (HasConst) {
1246 Out << 'B';
1247 } else {
1248 Out << 'A';
1249 }
1250 } else {
1251 if (HasConst && HasVolatile) {
1252 Out << 'T';
1253 } else if (HasVolatile) {
1254 Out << 'S';
1255 } else if (HasConst) {
1256 Out << 'R';
1257 } else {
1258 Out << 'Q';
1259 }
1260 }
1261
1262 // FIXME: For now, just drop all extension qualifiers on the floor.
1263}
1264
David Majnemer8eec58f2014-02-18 14:20:10 +00001265void
1266MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1267 const Type *PointeeType) {
1268 bool HasRestrict = Quals.hasRestrict();
1269 if (PointersAre64Bit && (!PointeeType || !PointeeType->isFunctionType()))
1270 Out << 'E';
1271
1272 if (HasRestrict)
1273 Out << 'I';
1274}
1275
1276void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1277 // <pointer-cv-qualifiers> ::= P # no qualifiers
1278 // ::= Q # const
1279 // ::= R # volatile
1280 // ::= S # const volatile
Guy Benyei11169dd2012-12-18 14:30:41 +00001281 bool HasConst = Quals.hasConst(),
David Majnemer8eec58f2014-02-18 14:20:10 +00001282 HasVolatile = Quals.hasVolatile();
David Majnemer0b6bf8a2014-02-18 12:58:35 +00001283
Guy Benyei11169dd2012-12-18 14:30:41 +00001284 if (HasConst && HasVolatile) {
1285 Out << 'S';
1286 } else if (HasVolatile) {
1287 Out << 'R';
1288 } else if (HasConst) {
1289 Out << 'Q';
1290 } else {
1291 Out << 'P';
1292 }
1293}
1294
1295void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1296 SourceRange Range) {
Reid Kleckner18da98e2013-06-24 19:21:52 +00001297 // MSVC will backreference two canonically equivalent types that have slightly
1298 // different manglings when mangled alone.
David Majnemer5a1b2042013-09-11 04:44:30 +00001299
1300 // Decayed types do not match up with non-decayed versions of the same type.
1301 //
1302 // e.g.
1303 // void (*x)(void) will not form a backreference with void x(void)
1304 void *TypePtr;
1305 if (const DecayedType *DT = T->getAs<DecayedType>()) {
1306 TypePtr = DT->getOriginalType().getCanonicalType().getAsOpaquePtr();
1307 // If the original parameter was textually written as an array,
1308 // instead treat the decayed parameter like it's const.
1309 //
1310 // e.g.
1311 // int [] -> int * const
1312 if (DT->getOriginalType()->isArrayType())
1313 T = T.withConst();
1314 } else
1315 TypePtr = T.getCanonicalType().getAsOpaquePtr();
1316
Guy Benyei11169dd2012-12-18 14:30:41 +00001317 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1318
1319 if (Found == TypeBackReferences.end()) {
1320 size_t OutSizeBefore = Out.GetNumBytesInBuffer();
1321
David Majnemer5a1b2042013-09-11 04:44:30 +00001322 mangleType(T, Range, QMM_Drop);
Guy Benyei11169dd2012-12-18 14:30:41 +00001323
1324 // See if it's worth creating a back reference.
1325 // Only types longer than 1 character are considered
1326 // and only 10 back references slots are available:
1327 bool LongerThanOneChar = (Out.GetNumBytesInBuffer() - OutSizeBefore > 1);
1328 if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1329 size_t Size = TypeBackReferences.size();
1330 TypeBackReferences[TypePtr] = Size;
1331 }
1332 } else {
1333 Out << Found->second;
1334 }
1335}
1336
1337void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
Peter Collingbourne2816c022013-04-25 04:25:40 +00001338 QualifierMangleMode QMM) {
Reid Kleckner18da98e2013-06-24 19:21:52 +00001339 // Don't use the canonical types. MSVC includes things like 'const' on
1340 // pointer arguments to function pointers that canonicalization strips away.
1341 T = T.getDesugaredType(getASTContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001342 Qualifiers Quals = T.getLocalQualifiers();
Reid Kleckner18da98e2013-06-24 19:21:52 +00001343 if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1344 // If there were any Quals, getAsArrayType() pushed them onto the array
1345 // element type.
Peter Collingbourne2816c022013-04-25 04:25:40 +00001346 if (QMM == QMM_Mangle)
1347 Out << 'A';
1348 else if (QMM == QMM_Escape || QMM == QMM_Result)
1349 Out << "$$B";
Reid Kleckner18da98e2013-06-24 19:21:52 +00001350 mangleArrayType(AT);
Peter Collingbourne2816c022013-04-25 04:25:40 +00001351 return;
1352 }
1353
1354 bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1355 T->isBlockPointerType();
1356
1357 switch (QMM) {
1358 case QMM_Drop:
1359 break;
1360 case QMM_Mangle:
1361 if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1362 Out << '6';
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +00001363 mangleFunctionType(FT);
Peter Collingbourne2816c022013-04-25 04:25:40 +00001364 return;
1365 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001366 mangleQualifiers(Quals, false);
Peter Collingbourne2816c022013-04-25 04:25:40 +00001367 break;
1368 case QMM_Escape:
1369 if (!IsPointer && Quals) {
1370 Out << "$$C";
1371 mangleQualifiers(Quals, false);
1372 }
1373 break;
1374 case QMM_Result:
1375 if ((!IsPointer && Quals) || isa<TagType>(T)) {
1376 Out << '?';
1377 mangleQualifiers(Quals, false);
1378 }
1379 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001380 }
1381
Peter Collingbourne2816c022013-04-25 04:25:40 +00001382 // We have to mangle these now, while we still have enough information.
David Majnemer8eec58f2014-02-18 14:20:10 +00001383 if (IsPointer) {
1384 manglePointerCVQualifiers(Quals);
1385 manglePointerExtQualifiers(Quals, T->getPointeeType().getTypePtr());
1386 }
Peter Collingbourne2816c022013-04-25 04:25:40 +00001387 const Type *ty = T.getTypePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001388
1389 switch (ty->getTypeClass()) {
1390#define ABSTRACT_TYPE(CLASS, PARENT)
1391#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1392 case Type::CLASS: \
1393 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1394 return;
1395#define TYPE(CLASS, PARENT) \
1396 case Type::CLASS: \
1397 mangleType(cast<CLASS##Type>(ty), Range); \
1398 break;
1399#include "clang/AST/TypeNodes.def"
1400#undef ABSTRACT_TYPE
1401#undef NON_CANONICAL_TYPE
1402#undef TYPE
1403 }
1404}
1405
1406void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T,
1407 SourceRange Range) {
1408 // <type> ::= <builtin-type>
1409 // <builtin-type> ::= X # void
1410 // ::= C # signed char
1411 // ::= D # char
1412 // ::= E # unsigned char
1413 // ::= F # short
1414 // ::= G # unsigned short (or wchar_t if it's not a builtin)
1415 // ::= H # int
1416 // ::= I # unsigned int
1417 // ::= J # long
1418 // ::= K # unsigned long
1419 // L # <none>
1420 // ::= M # float
1421 // ::= N # double
1422 // ::= O # long double (__float80 is mangled differently)
1423 // ::= _J # long long, __int64
1424 // ::= _K # unsigned long long, __int64
1425 // ::= _L # __int128
1426 // ::= _M # unsigned __int128
1427 // ::= _N # bool
1428 // _O # <array in parameter>
1429 // ::= _T # __float80 (Intel)
1430 // ::= _W # wchar_t
1431 // ::= _Z # __float80 (Digital Mars)
1432 switch (T->getKind()) {
1433 case BuiltinType::Void: Out << 'X'; break;
1434 case BuiltinType::SChar: Out << 'C'; break;
1435 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
1436 case BuiltinType::UChar: Out << 'E'; break;
1437 case BuiltinType::Short: Out << 'F'; break;
1438 case BuiltinType::UShort: Out << 'G'; break;
1439 case BuiltinType::Int: Out << 'H'; break;
1440 case BuiltinType::UInt: Out << 'I'; break;
1441 case BuiltinType::Long: Out << 'J'; break;
1442 case BuiltinType::ULong: Out << 'K'; break;
1443 case BuiltinType::Float: Out << 'M'; break;
1444 case BuiltinType::Double: Out << 'N'; break;
1445 // TODO: Determine size and mangle accordingly
1446 case BuiltinType::LongDouble: Out << 'O'; break;
1447 case BuiltinType::LongLong: Out << "_J"; break;
1448 case BuiltinType::ULongLong: Out << "_K"; break;
1449 case BuiltinType::Int128: Out << "_L"; break;
1450 case BuiltinType::UInt128: Out << "_M"; break;
1451 case BuiltinType::Bool: Out << "_N"; break;
1452 case BuiltinType::WChar_S:
1453 case BuiltinType::WChar_U: Out << "_W"; break;
1454
1455#define BUILTIN_TYPE(Id, SingletonId)
1456#define PLACEHOLDER_TYPE(Id, SingletonId) \
1457 case BuiltinType::Id:
1458#include "clang/AST/BuiltinTypes.def"
1459 case BuiltinType::Dependent:
1460 llvm_unreachable("placeholder types shouldn't get to name mangling");
1461
1462 case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
1463 case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
1464 case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001465
1466 case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
1467 case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
1468 case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
1469 case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
1470 case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
1471 case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
Guy Benyei61054192013-02-07 10:55:47 +00001472 case BuiltinType::OCLSampler: Out << "PAUocl_sampler@@"; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001473 case BuiltinType::OCLEvent: Out << "PAUocl_event@@"; break;
David Majnemerb4119f72013-12-13 01:06:04 +00001474
Guy Benyei11169dd2012-12-18 14:30:41 +00001475 case BuiltinType::NullPtr: Out << "$$T"; break;
1476
1477 case BuiltinType::Char16:
1478 case BuiltinType::Char32:
1479 case BuiltinType::Half: {
1480 DiagnosticsEngine &Diags = Context.getDiags();
1481 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1482 "cannot mangle this built-in %0 type yet");
1483 Diags.Report(Range.getBegin(), DiagID)
1484 << T->getName(Context.getASTContext().getPrintingPolicy())
1485 << Range;
1486 break;
1487 }
1488 }
1489}
1490
1491// <type> ::= <function-type>
1492void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T,
1493 SourceRange) {
1494 // Structors only appear in decls, so at this point we know it's not a
1495 // structor type.
1496 // FIXME: This may not be lambda-friendly.
1497 Out << "$$A6";
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +00001498 mangleFunctionType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00001499}
1500void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1501 SourceRange) {
1502 llvm_unreachable("Can't mangle K&R function prototypes");
1503}
1504
Peter Collingbourne2816c022013-04-25 04:25:40 +00001505void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1506 const FunctionDecl *D,
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +00001507 bool ForceInstMethod) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001508 // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1509 // <return-type> <argument-list> <throw-spec>
1510 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1511
Reid Kleckner18da98e2013-06-24 19:21:52 +00001512 SourceRange Range;
1513 if (D) Range = D->getSourceRange();
1514
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +00001515 bool IsStructor = false, IsInstMethod = ForceInstMethod;
1516 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1517 if (MD->isInstance())
1518 IsInstMethod = true;
1519 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
1520 IsStructor = true;
1521 }
1522
Guy Benyei11169dd2012-12-18 14:30:41 +00001523 // If this is a C++ instance method, mangle the CVR qualifiers for the
1524 // this pointer.
David Majnemer6dda7bb2013-08-15 08:13:23 +00001525 if (IsInstMethod) {
David Majnemer8eec58f2014-02-18 14:20:10 +00001526 Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
1527 manglePointerExtQualifiers(Quals, 0);
1528 mangleQualifiers(Quals, false);
David Majnemer6dda7bb2013-08-15 08:13:23 +00001529 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001530
Reid Klecknerc5cc3382013-09-25 22:28:52 +00001531 mangleCallingConvention(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00001532
1533 // <return-type> ::= <type>
1534 // ::= @ # structors (they have no declared return type)
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001535 if (IsStructor) {
1536 if (isa<CXXDestructorDecl>(D) && D == Structor &&
1537 StructorType == Dtor_Deleting) {
1538 // The scalar deleting destructor takes an extra int argument.
1539 // However, the FunctionType generated has 0 arguments.
1540 // FIXME: This is a temporary hack.
1541 // Maybe should fix the FunctionType creation instead?
Timur Iskhodzhanovf46993e2013-08-26 10:32:04 +00001542 Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001543 return;
1544 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001545 Out << '@';
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001546 } else {
Alp Toker314cc812014-01-25 16:55:45 +00001547 QualType ResultType = Proto->getReturnType();
David Majnemer6dda7bb2013-08-15 08:13:23 +00001548 if (ResultType->isVoidType())
1549 ResultType = ResultType.getUnqualifiedType();
1550 mangleType(ResultType, Range, QMM_Result);
Guy Benyei11169dd2012-12-18 14:30:41 +00001551 }
1552
1553 // <argument-list> ::= X # void
1554 // ::= <type>+ @
1555 // ::= <type>* Z # varargs
Alp Toker9cacbab2014-01-20 20:26:09 +00001556 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001557 Out << 'X';
1558 } else {
Reid Kleckner18da98e2013-06-24 19:21:52 +00001559 // Happens for function pointer type arguments for example.
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00001560 for (const auto &Arg : Proto->param_types())
1561 mangleArgumentType(Arg, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00001562 // <builtin-type> ::= Z # ellipsis
1563 if (Proto->isVariadic())
1564 Out << 'Z';
1565 else
1566 Out << '@';
1567 }
1568
1569 mangleThrowSpecification(Proto);
1570}
1571
1572void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
Reid Kleckner369f3162013-05-14 20:30:42 +00001573 // <function-class> ::= <member-function> E? # E designates a 64-bit 'this'
1574 // # pointer. in 64-bit mode *all*
1575 // # 'this' pointers are 64-bit.
1576 // ::= <global-function>
1577 // <member-function> ::= A # private: near
1578 // ::= B # private: far
1579 // ::= C # private: static near
1580 // ::= D # private: static far
1581 // ::= E # private: virtual near
1582 // ::= F # private: virtual far
Reid Kleckner369f3162013-05-14 20:30:42 +00001583 // ::= I # protected: near
1584 // ::= J # protected: far
1585 // ::= K # protected: static near
1586 // ::= L # protected: static far
1587 // ::= M # protected: virtual near
1588 // ::= N # protected: virtual far
Reid Kleckner369f3162013-05-14 20:30:42 +00001589 // ::= Q # public: near
1590 // ::= R # public: far
1591 // ::= S # public: static near
1592 // ::= T # public: static far
1593 // ::= U # public: virtual near
1594 // ::= V # public: virtual far
Reid Kleckner369f3162013-05-14 20:30:42 +00001595 // <global-function> ::= Y # global near
1596 // ::= Z # global far
Guy Benyei11169dd2012-12-18 14:30:41 +00001597 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1598 switch (MD->getAccess()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00001599 case AS_none:
1600 llvm_unreachable("Unsupported access specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 case AS_private:
1602 if (MD->isStatic())
1603 Out << 'C';
1604 else if (MD->isVirtual())
1605 Out << 'E';
1606 else
1607 Out << 'A';
1608 break;
1609 case AS_protected:
1610 if (MD->isStatic())
1611 Out << 'K';
1612 else if (MD->isVirtual())
1613 Out << 'M';
1614 else
1615 Out << 'I';
1616 break;
1617 case AS_public:
1618 if (MD->isStatic())
1619 Out << 'S';
1620 else if (MD->isVirtual())
1621 Out << 'U';
1622 else
1623 Out << 'Q';
1624 }
1625 } else
1626 Out << 'Y';
1627}
Reid Klecknerc5cc3382013-09-25 22:28:52 +00001628void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001629 // <calling-convention> ::= A # __cdecl
1630 // ::= B # __export __cdecl
1631 // ::= C # __pascal
1632 // ::= D # __export __pascal
1633 // ::= E # __thiscall
1634 // ::= F # __export __thiscall
1635 // ::= G # __stdcall
1636 // ::= H # __export __stdcall
1637 // ::= I # __fastcall
1638 // ::= J # __export __fastcall
1639 // The 'export' calling conventions are from a bygone era
1640 // (*cough*Win16*cough*) when functions were declared for export with
1641 // that keyword. (It didn't actually export them, it just made them so
1642 // that they could be in a DLL and somebody from another module could call
1643 // them.)
1644 CallingConv CC = T->getCallConv();
Guy Benyei11169dd2012-12-18 14:30:41 +00001645 switch (CC) {
1646 default:
1647 llvm_unreachable("Unsupported CC for mangling");
Charles Davisb5a214e2013-08-30 04:39:01 +00001648 case CC_X86_64Win64:
1649 case CC_X86_64SysV:
Guy Benyei11169dd2012-12-18 14:30:41 +00001650 case CC_C: Out << 'A'; break;
1651 case CC_X86Pascal: Out << 'C'; break;
1652 case CC_X86ThisCall: Out << 'E'; break;
1653 case CC_X86StdCall: Out << 'G'; break;
1654 case CC_X86FastCall: Out << 'I'; break;
1655 }
1656}
1657void MicrosoftCXXNameMangler::mangleThrowSpecification(
1658 const FunctionProtoType *FT) {
1659 // <throw-spec> ::= Z # throw(...) (default)
1660 // ::= @ # throw() or __declspec/__attribute__((nothrow))
1661 // ::= <type>+
1662 // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1663 // all actually mangled as 'Z'. (They're ignored because their associated
1664 // functionality isn't implemented, and probably never will be.)
1665 Out << 'Z';
1666}
1667
1668void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
1669 SourceRange Range) {
1670 // Probably should be mangled as a template instantiation; need to see what
1671 // VC does first.
1672 DiagnosticsEngine &Diags = Context.getDiags();
1673 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1674 "cannot mangle this unresolved dependent type yet");
1675 Diags.Report(Range.getBegin(), DiagID)
1676 << Range;
1677}
1678
1679// <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1680// <union-type> ::= T <name>
1681// <struct-type> ::= U <name>
1682// <class-type> ::= V <name>
David Majnemer048f90c2013-12-09 04:28:34 +00001683// <enum-type> ::= W4 <name>
Guy Benyei11169dd2012-12-18 14:30:41 +00001684void MicrosoftCXXNameMangler::mangleType(const EnumType *T, SourceRange) {
David Majnemer0db0ca42013-08-05 22:26:46 +00001685 mangleType(cast<TagType>(T)->getDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001686}
1687void MicrosoftCXXNameMangler::mangleType(const RecordType *T, SourceRange) {
David Majnemer0db0ca42013-08-05 22:26:46 +00001688 mangleType(cast<TagType>(T)->getDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001689}
David Majnemer0db0ca42013-08-05 22:26:46 +00001690void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
1691 switch (TD->getTagKind()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001692 case TTK_Union:
1693 Out << 'T';
1694 break;
1695 case TTK_Struct:
1696 case TTK_Interface:
1697 Out << 'U';
1698 break;
1699 case TTK_Class:
1700 Out << 'V';
1701 break;
1702 case TTK_Enum:
David Majnemer048f90c2013-12-09 04:28:34 +00001703 Out << "W4";
Guy Benyei11169dd2012-12-18 14:30:41 +00001704 break;
1705 }
David Majnemer0db0ca42013-08-05 22:26:46 +00001706 mangleName(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001707}
1708
1709// <type> ::= <array-type>
1710// <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1711// [Y <dimension-count> <dimension>+]
Reid Kleckner369f3162013-05-14 20:30:42 +00001712// <element-type> # as global, E is never required
Guy Benyei11169dd2012-12-18 14:30:41 +00001713// It's supposed to be the other way around, but for some strange reason, it
1714// isn't. Today this behavior is retained for the sole purpose of backwards
1715// compatibility.
David Majnemer5a1b2042013-09-11 04:44:30 +00001716void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001717 // This isn't a recursive mangling, so now we have to do it all in this
1718 // one call.
David Majnemer8eec58f2014-02-18 14:20:10 +00001719 manglePointerCVQualifiers(T->getElementType().getQualifiers());
Peter Collingbourne2816c022013-04-25 04:25:40 +00001720 mangleType(T->getElementType(), SourceRange());
Guy Benyei11169dd2012-12-18 14:30:41 +00001721}
1722void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T,
1723 SourceRange) {
Peter Collingbourne2816c022013-04-25 04:25:40 +00001724 llvm_unreachable("Should have been special cased");
Guy Benyei11169dd2012-12-18 14:30:41 +00001725}
1726void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T,
1727 SourceRange) {
Peter Collingbourne2816c022013-04-25 04:25:40 +00001728 llvm_unreachable("Should have been special cased");
Guy Benyei11169dd2012-12-18 14:30:41 +00001729}
1730void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
1731 SourceRange) {
Peter Collingbourne2816c022013-04-25 04:25:40 +00001732 llvm_unreachable("Should have been special cased");
Guy Benyei11169dd2012-12-18 14:30:41 +00001733}
1734void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
1735 SourceRange) {
Peter Collingbourne2816c022013-04-25 04:25:40 +00001736 llvm_unreachable("Should have been special cased");
Guy Benyei11169dd2012-12-18 14:30:41 +00001737}
Reid Kleckner18da98e2013-06-24 19:21:52 +00001738void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
Peter Collingbourne2816c022013-04-25 04:25:40 +00001739 QualType ElementTy(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00001740 SmallVector<llvm::APInt, 3> Dimensions;
1741 for (;;) {
1742 if (const ConstantArrayType *CAT =
1743 getASTContext().getAsConstantArrayType(ElementTy)) {
1744 Dimensions.push_back(CAT->getSize());
1745 ElementTy = CAT->getElementType();
1746 } else if (ElementTy->isVariableArrayType()) {
1747 const VariableArrayType *VAT =
1748 getASTContext().getAsVariableArrayType(ElementTy);
1749 DiagnosticsEngine &Diags = Context.getDiags();
1750 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1751 "cannot mangle this variable-length array yet");
1752 Diags.Report(VAT->getSizeExpr()->getExprLoc(), DiagID)
1753 << VAT->getBracketsRange();
1754 return;
1755 } else if (ElementTy->isDependentSizedArrayType()) {
1756 // The dependent expression has to be folded into a constant (TODO).
1757 const DependentSizedArrayType *DSAT =
1758 getASTContext().getAsDependentSizedArrayType(ElementTy);
1759 DiagnosticsEngine &Diags = Context.getDiags();
1760 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1761 "cannot mangle this dependent-length array yet");
1762 Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
1763 << DSAT->getBracketsRange();
1764 return;
Peter Collingbourne2816c022013-04-25 04:25:40 +00001765 } else if (const IncompleteArrayType *IAT =
1766 getASTContext().getAsIncompleteArrayType(ElementTy)) {
1767 Dimensions.push_back(llvm::APInt(32, 0));
1768 ElementTy = IAT->getElementType();
1769 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001770 else break;
1771 }
Peter Collingbourne2816c022013-04-25 04:25:40 +00001772 Out << 'Y';
1773 // <dimension-count> ::= <number> # number of extra dimensions
1774 mangleNumber(Dimensions.size());
1775 for (unsigned Dim = 0; Dim < Dimensions.size(); ++Dim)
1776 mangleNumber(Dimensions[Dim].getLimitedValue());
Reid Kleckner18da98e2013-06-24 19:21:52 +00001777 mangleType(ElementTy, SourceRange(), QMM_Escape);
Guy Benyei11169dd2012-12-18 14:30:41 +00001778}
1779
1780// <type> ::= <pointer-to-member-type>
1781// <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1782// <class name> <type>
1783void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
1784 SourceRange Range) {
1785 QualType PointeeType = T->getPointeeType();
1786 if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
1787 Out << '8';
1788 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +00001789 mangleFunctionType(FPT, 0, true);
Guy Benyei11169dd2012-12-18 14:30:41 +00001790 } else {
1791 mangleQualifiers(PointeeType.getQualifiers(), true);
1792 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
Peter Collingbourne2816c022013-04-25 04:25:40 +00001793 mangleType(PointeeType, Range, QMM_Drop);
Guy Benyei11169dd2012-12-18 14:30:41 +00001794 }
1795}
1796
1797void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
1798 SourceRange Range) {
1799 DiagnosticsEngine &Diags = Context.getDiags();
1800 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1801 "cannot mangle this template type parameter type yet");
1802 Diags.Report(Range.getBegin(), DiagID)
1803 << Range;
1804}
1805
1806void MicrosoftCXXNameMangler::mangleType(
1807 const SubstTemplateTypeParmPackType *T,
1808 SourceRange Range) {
1809 DiagnosticsEngine &Diags = Context.getDiags();
1810 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1811 "cannot mangle this substituted parameter pack yet");
1812 Diags.Report(Range.getBegin(), DiagID)
1813 << Range;
1814}
1815
1816// <type> ::= <pointer-type>
Reid Kleckner369f3162013-05-14 20:30:42 +00001817// <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
Alp Tokerd4733632013-12-05 04:47:09 +00001818// # the E is required for 64-bit non-static pointers
Guy Benyei11169dd2012-12-18 14:30:41 +00001819void MicrosoftCXXNameMangler::mangleType(const PointerType *T,
1820 SourceRange Range) {
1821 QualType PointeeTy = T->getPointeeType();
Peter Collingbourne2816c022013-04-25 04:25:40 +00001822 mangleType(PointeeTy, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00001823}
1824void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
1825 SourceRange Range) {
1826 // Object pointers never have qualifiers.
1827 Out << 'A';
David Majnemer8eec58f2014-02-18 14:20:10 +00001828 manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001829 mangleType(T->getPointeeType(), Range);
1830}
1831
1832// <type> ::= <reference-type>
Reid Kleckner369f3162013-05-14 20:30:42 +00001833// <reference-type> ::= A E? <cvr-qualifiers> <type>
Alp Tokerd4733632013-12-05 04:47:09 +00001834// # the E is required for 64-bit non-static lvalue references
Guy Benyei11169dd2012-12-18 14:30:41 +00001835void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
1836 SourceRange Range) {
1837 Out << 'A';
David Majnemer8eec58f2014-02-18 14:20:10 +00001838 manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
Peter Collingbourne2816c022013-04-25 04:25:40 +00001839 mangleType(T->getPointeeType(), Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00001840}
1841
1842// <type> ::= <r-value-reference-type>
Reid Kleckner369f3162013-05-14 20:30:42 +00001843// <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
Alp Tokerd4733632013-12-05 04:47:09 +00001844// # the E is required for 64-bit non-static rvalue references
Guy Benyei11169dd2012-12-18 14:30:41 +00001845void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
1846 SourceRange Range) {
1847 Out << "$$Q";
David Majnemer8eec58f2014-02-18 14:20:10 +00001848 manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
Peter Collingbourne2816c022013-04-25 04:25:40 +00001849 mangleType(T->getPointeeType(), Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00001850}
1851
1852void MicrosoftCXXNameMangler::mangleType(const ComplexType *T,
1853 SourceRange Range) {
1854 DiagnosticsEngine &Diags = Context.getDiags();
1855 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1856 "cannot mangle this complex number type yet");
1857 Diags.Report(Range.getBegin(), DiagID)
1858 << Range;
1859}
1860
1861void MicrosoftCXXNameMangler::mangleType(const VectorType *T,
1862 SourceRange Range) {
Reid Klecknere7e64d82013-03-26 16:56:59 +00001863 const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
1864 assert(ET && "vectors with non-builtin elements are unsupported");
1865 uint64_t Width = getASTContext().getTypeSize(T);
1866 // Pattern match exactly the typedefs in our intrinsic headers. Anything that
1867 // doesn't match the Intel types uses a custom mangling below.
1868 bool IntelVector = true;
1869 if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
1870 Out << "T__m64";
1871 } else if (Width == 128 || Width == 256) {
1872 if (ET->getKind() == BuiltinType::Float)
1873 Out << "T__m" << Width;
1874 else if (ET->getKind() == BuiltinType::LongLong)
1875 Out << "T__m" << Width << 'i';
1876 else if (ET->getKind() == BuiltinType::Double)
1877 Out << "U__m" << Width << 'd';
1878 else
1879 IntelVector = false;
1880 } else {
1881 IntelVector = false;
1882 }
1883
1884 if (!IntelVector) {
1885 // The MS ABI doesn't have a special mangling for vector types, so we define
1886 // our own mangling to handle uses of __vector_size__ on user-specified
1887 // types, and for extensions like __v4sf.
1888 Out << "T__clang_vec" << T->getNumElements() << '_';
1889 mangleType(ET, Range);
1890 }
1891
1892 Out << "@@";
Guy Benyei11169dd2012-12-18 14:30:41 +00001893}
Reid Klecknere7e64d82013-03-26 16:56:59 +00001894
Guy Benyei11169dd2012-12-18 14:30:41 +00001895void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
1896 SourceRange Range) {
1897 DiagnosticsEngine &Diags = Context.getDiags();
1898 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1899 "cannot mangle this extended vector type yet");
1900 Diags.Report(Range.getBegin(), DiagID)
1901 << Range;
1902}
1903void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
1904 SourceRange Range) {
1905 DiagnosticsEngine &Diags = Context.getDiags();
1906 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1907 "cannot mangle this dependent-sized extended vector type yet");
1908 Diags.Report(Range.getBegin(), DiagID)
1909 << Range;
1910}
1911
1912void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T,
1913 SourceRange) {
1914 // ObjC interfaces have structs underlying them.
1915 Out << 'U';
1916 mangleName(T->getDecl());
1917}
1918
1919void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
1920 SourceRange Range) {
1921 // We don't allow overloading by different protocol qualification,
1922 // so mangling them isn't necessary.
1923 mangleType(T->getBaseType(), Range);
1924}
1925
1926void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
1927 SourceRange Range) {
1928 Out << "_E";
1929
1930 QualType pointee = T->getPointeeType();
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +00001931 mangleFunctionType(pointee->castAs<FunctionProtoType>());
Guy Benyei11169dd2012-12-18 14:30:41 +00001932}
1933
David Majnemerf0a84f22013-08-16 08:29:13 +00001934void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
1935 SourceRange) {
1936 llvm_unreachable("Cannot mangle injected class name type.");
Guy Benyei11169dd2012-12-18 14:30:41 +00001937}
1938
1939void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
1940 SourceRange Range) {
1941 DiagnosticsEngine &Diags = Context.getDiags();
1942 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1943 "cannot mangle this template specialization type yet");
1944 Diags.Report(Range.getBegin(), DiagID)
1945 << Range;
1946}
1947
1948void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T,
1949 SourceRange Range) {
1950 DiagnosticsEngine &Diags = Context.getDiags();
1951 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1952 "cannot mangle this dependent name type yet");
1953 Diags.Report(Range.getBegin(), DiagID)
1954 << Range;
1955}
1956
1957void MicrosoftCXXNameMangler::mangleType(
1958 const DependentTemplateSpecializationType *T,
1959 SourceRange Range) {
1960 DiagnosticsEngine &Diags = Context.getDiags();
1961 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1962 "cannot mangle this dependent template specialization type yet");
1963 Diags.Report(Range.getBegin(), DiagID)
1964 << Range;
1965}
1966
1967void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T,
1968 SourceRange Range) {
1969 DiagnosticsEngine &Diags = Context.getDiags();
1970 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1971 "cannot mangle this pack expansion yet");
1972 Diags.Report(Range.getBegin(), DiagID)
1973 << Range;
1974}
1975
1976void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T,
1977 SourceRange Range) {
1978 DiagnosticsEngine &Diags = Context.getDiags();
1979 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1980 "cannot mangle this typeof(type) yet");
1981 Diags.Report(Range.getBegin(), DiagID)
1982 << Range;
1983}
1984
1985void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T,
1986 SourceRange Range) {
1987 DiagnosticsEngine &Diags = Context.getDiags();
1988 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1989 "cannot mangle this typeof(expression) yet");
1990 Diags.Report(Range.getBegin(), DiagID)
1991 << Range;
1992}
1993
1994void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T,
1995 SourceRange Range) {
1996 DiagnosticsEngine &Diags = Context.getDiags();
1997 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1998 "cannot mangle this decltype() yet");
1999 Diags.Report(Range.getBegin(), DiagID)
2000 << Range;
2001}
2002
2003void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2004 SourceRange Range) {
2005 DiagnosticsEngine &Diags = Context.getDiags();
2006 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2007 "cannot mangle this unary transform type yet");
2008 Diags.Report(Range.getBegin(), DiagID)
2009 << Range;
2010}
2011
2012void MicrosoftCXXNameMangler::mangleType(const AutoType *T, SourceRange Range) {
David Majnemerb9a5f2d2014-01-21 20:33:36 +00002013 assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2014
Guy Benyei11169dd2012-12-18 14:30:41 +00002015 DiagnosticsEngine &Diags = Context.getDiags();
2016 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2017 "cannot mangle this 'auto' type yet");
2018 Diags.Report(Range.getBegin(), DiagID)
2019 << Range;
2020}
2021
2022void MicrosoftCXXNameMangler::mangleType(const AtomicType *T,
2023 SourceRange Range) {
2024 DiagnosticsEngine &Diags = Context.getDiags();
2025 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2026 "cannot mangle this C11 atomic type yet");
2027 Diags.Report(Range.getBegin(), DiagID)
2028 << Range;
2029}
2030
Rafael Espindola002667c2013-10-16 01:40:34 +00002031void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2032 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002033 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2034 "Invalid mangleName() call, argument is not a variable or function!");
2035 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2036 "Invalid mangleName() call on 'structor decl!");
2037
2038 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2039 getASTContext().getSourceManager(),
2040 "Mangling declaration");
2041
2042 MicrosoftCXXNameMangler Mangler(*this, Out);
2043 return Mangler.mangle(D);
2044}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002045
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002046// <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2047// <virtual-adjustment>
2048// <no-adjustment> ::= A # private near
2049// ::= B # private far
2050// ::= I # protected near
2051// ::= J # protected far
2052// ::= Q # public near
2053// ::= R # public far
2054// <static-adjustment> ::= G <static-offset> # private near
2055// ::= H <static-offset> # private far
2056// ::= O <static-offset> # protected near
2057// ::= P <static-offset> # protected far
2058// ::= W <static-offset> # public near
2059// ::= X <static-offset> # public far
2060// <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2061// ::= $1 <virtual-shift> <static-offset> # private far
2062// ::= $2 <virtual-shift> <static-offset> # protected near
2063// ::= $3 <virtual-shift> <static-offset> # protected far
2064// ::= $4 <virtual-shift> <static-offset> # public near
2065// ::= $5 <virtual-shift> <static-offset> # public far
2066// <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift>
2067// <vtordisp-shift> ::= <offset-to-vtordisp>
2068// <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset>
2069// <offset-to-vtordisp>
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002070static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2071 const ThisAdjustment &Adjustment,
2072 MicrosoftCXXNameMangler &Mangler,
2073 raw_ostream &Out) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002074 if (!Adjustment.Virtual.isEmpty()) {
2075 Out << '$';
2076 char AccessSpec;
2077 switch (MD->getAccess()) {
2078 case AS_none:
2079 llvm_unreachable("Unsupported access specifier");
2080 case AS_private:
2081 AccessSpec = '0';
2082 break;
2083 case AS_protected:
2084 AccessSpec = '2';
2085 break;
2086 case AS_public:
2087 AccessSpec = '4';
2088 }
2089 if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2090 Out << 'R' << AccessSpec;
David Majnemer2a816452013-12-09 10:44:32 +00002091 Mangler.mangleNumber(
2092 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2093 Mangler.mangleNumber(
2094 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2095 Mangler.mangleNumber(
2096 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2097 Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002098 } else {
2099 Out << AccessSpec;
David Majnemer2a816452013-12-09 10:44:32 +00002100 Mangler.mangleNumber(
2101 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2102 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002103 }
2104 } else if (Adjustment.NonVirtual != 0) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002105 switch (MD->getAccess()) {
2106 case AS_none:
2107 llvm_unreachable("Unsupported access specifier");
2108 case AS_private:
2109 Out << 'G';
2110 break;
2111 case AS_protected:
2112 Out << 'O';
2113 break;
2114 case AS_public:
2115 Out << 'W';
2116 }
David Majnemer2a816452013-12-09 10:44:32 +00002117 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002118 } else {
2119 switch (MD->getAccess()) {
2120 case AS_none:
2121 llvm_unreachable("Unsupported access specifier");
2122 case AS_private:
2123 Out << 'A';
2124 break;
2125 case AS_protected:
2126 Out << 'I';
2127 break;
2128 case AS_public:
2129 Out << 'Q';
2130 }
2131 }
2132}
2133
Reid Kleckner96f8f932014-02-05 17:27:08 +00002134void
2135MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2136 raw_ostream &Out) {
2137 MicrosoftVTableContext *VTContext =
2138 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2139 const MicrosoftVTableContext::MethodVFTableLocation &ML =
2140 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
Hans Wennborg88497d62013-11-15 17:24:45 +00002141
2142 MicrosoftCXXNameMangler Mangler(*this, Out);
Reid Kleckner96f8f932014-02-05 17:27:08 +00002143 Mangler.getStream() << "\01?";
2144 Mangler.mangleVirtualMemPtrThunk(MD, ML);
Hans Wennborg88497d62013-11-15 17:24:45 +00002145}
2146
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002147void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2148 const ThunkInfo &Thunk,
2149 raw_ostream &Out) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002150 MicrosoftCXXNameMangler Mangler(*this, Out);
2151 Out << "\01?";
2152 Mangler.mangleName(MD);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002153 mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
2154 if (!Thunk.Return.isEmpty())
2155 assert(Thunk.Method != 0 && "Thunk info should hold the overridee decl");
2156
2157 const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2158 Mangler.mangleFunctionType(
2159 DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
Guy Benyei11169dd2012-12-18 14:30:41 +00002160}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002161
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002162void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2163 const CXXDestructorDecl *DD, CXXDtorType Type,
2164 const ThisAdjustment &Adjustment, raw_ostream &Out) {
2165 // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2166 // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2167 // mangling manually until we support both deleting dtor types.
2168 assert(Type == Dtor_Deleting);
2169 MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
2170 Out << "\01??_E";
2171 Mangler.mangleName(DD->getParent());
2172 mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
2173 Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
Guy Benyei11169dd2012-12-18 14:30:41 +00002174}
Reid Kleckner7810af02013-06-19 15:20:38 +00002175
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002176void MicrosoftMangleContextImpl::mangleCXXVFTable(
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002177 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2178 raw_ostream &Out) {
Reid Kleckner7810af02013-06-19 15:20:38 +00002179 // <mangled-name> ::= ?_7 <class-name> <storage-class>
2180 // <cvr-qualifiers> [<name>] @
Guy Benyei11169dd2012-12-18 14:30:41 +00002181 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
Reid Kleckner7810af02013-06-19 15:20:38 +00002182 // is always '6' for vftables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002183 MicrosoftCXXNameMangler Mangler(*this, Out);
2184 Mangler.getStream() << "\01??_7";
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002185 Mangler.mangleName(Derived);
2186 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2187 for (ArrayRef<const CXXRecordDecl *>::iterator I = BasePath.begin(),
2188 E = BasePath.end();
2189 I != E; ++I) {
2190 Mangler.mangleName(*I);
2191 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002192 Mangler.getStream() << '@';
2193}
Reid Kleckner7810af02013-06-19 15:20:38 +00002194
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002195void MicrosoftMangleContextImpl::mangleCXXVBTable(
Reid Kleckner7810af02013-06-19 15:20:38 +00002196 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2197 raw_ostream &Out) {
2198 // <mangled-name> ::= ?_8 <class-name> <storage-class>
2199 // <cvr-qualifiers> [<name>] @
2200 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2201 // is always '7' for vbtables.
2202 MicrosoftCXXNameMangler Mangler(*this, Out);
2203 Mangler.getStream() << "\01??_8";
2204 Mangler.mangleName(Derived);
2205 Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const.
2206 for (ArrayRef<const CXXRecordDecl *>::iterator I = BasePath.begin(),
2207 E = BasePath.end();
2208 I != E; ++I) {
2209 Mangler.mangleName(*I);
2210 }
2211 Mangler.getStream() << '@';
2212}
2213
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002214void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002215 // FIXME: Give a location...
2216 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2217 "cannot mangle RTTI descriptors for type %0 yet");
2218 getDiags().Report(DiagID)
2219 << T.getBaseTypeIdentifier();
2220}
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002221
2222void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T, raw_ostream &) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002223 // FIXME: Give a location...
2224 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2225 "cannot mangle the name of type %0 into RTTI descriptors yet");
2226 getDiags().Report(DiagID)
2227 << T.getBaseTypeIdentifier();
2228}
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002229
Reid Klecknercc99e262013-11-19 23:23:00 +00002230void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
2231 // This is just a made up unique string for the purposes of tbaa. undname
2232 // does *not* know how to demangle it.
2233 MicrosoftCXXNameMangler Mangler(*this, Out);
2234 Mangler.getStream() << '?';
2235 Mangler.mangleType(T, SourceRange());
2236}
2237
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002238void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
2239 CXXCtorType Type,
2240 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002241 MicrosoftCXXNameMangler mangler(*this, Out);
2242 mangler.mangle(D);
2243}
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002244
2245void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
2246 CXXDtorType Type,
2247 raw_ostream &Out) {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00002248 MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
Guy Benyei11169dd2012-12-18 14:30:41 +00002249 mangler.mangle(D);
2250}
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002251
2252void MicrosoftMangleContextImpl::mangleReferenceTemporary(const VarDecl *VD,
David Majnemer210e6bfa12013-12-13 00:39:38 +00002253 raw_ostream &) {
2254 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2255 "cannot mangle this reference temporary yet");
2256 getDiags().Report(VD->getLocation(), DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00002257}
2258
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002259void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
2260 raw_ostream &Out) {
David Majnemer25e1a5e2013-12-13 00:52:45 +00002261 // TODO: This is not correct, especially with respect to MSVC2013. MSVC2013
2262 // utilizes thread local variables to implement thread safe, re-entrant
2263 // initialization for statics. They no longer differentiate between an
2264 // externally visible and non-externally visible static with respect to
2265 // mangling, they all get $TSS <number>.
2266 //
2267 // N.B. This means that they can get more than 32 static variable guards in a
2268 // scope. It also means that they broke compatibility with their own ABI.
2269
David Majnemer2206bf52014-03-05 08:57:59 +00002270 // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
Reid Klecknerd8110b62013-09-10 20:14:30 +00002271 // ::= ?$S <guard-num> @ <postfix> @4IA
2272
2273 // The first mangling is what MSVC uses to guard static locals in inline
2274 // functions. It uses a different mangling in external functions to support
2275 // guarding more than 32 variables. MSVC rejects inline functions with more
2276 // than 32 static locals. We don't fully implement the second mangling
2277 // because those guards are not externally visible, and instead use LLVM's
2278 // default renaming when creating a new guard variable.
2279 MicrosoftCXXNameMangler Mangler(*this, Out);
2280
2281 bool Visible = VD->isExternallyVisible();
2282 // <operator-name> ::= ?_B # local static guard
2283 Mangler.getStream() << (Visible ? "\01??_B" : "\01?$S1@");
David Majnemer34b49892014-03-06 19:57:36 +00002284 unsigned ScopeDepth = 0;
2285 if (Visible && !getNextDiscriminator(VD, ScopeDepth))
2286 // If we do not have a discriminator and are emitting a guard variable for
2287 // use at global scope, then mangling the nested name will not be enough to
2288 // remove ambiguities.
2289 Mangler.mangle(VD, "");
2290 else
2291 Mangler.mangleNestedName(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00002292 Mangler.getStream() << (Visible ? "@5" : "@4IA");
David Majnemer34b49892014-03-06 19:57:36 +00002293 if (ScopeDepth)
David Majnemer2206bf52014-03-05 08:57:59 +00002294 Mangler.mangleNumber(ScopeDepth);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002295}
2296
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002297void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
2298 raw_ostream &Out,
2299 char CharCode) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00002300 MicrosoftCXXNameMangler Mangler(*this, Out);
2301 Mangler.getStream() << "\01??__" << CharCode;
2302 Mangler.mangleName(D);
David Majnemerf55feec2014-03-06 19:10:27 +00002303 if (D->isStaticDataMember()) {
2304 Mangler.mangleVariableEncoding(D);
2305 Mangler.getStream() << '@';
2306 }
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00002307 // This is the function class mangling. These stubs are global, non-variadic,
2308 // cdecl functions that return void and take no args.
2309 Mangler.getStream() << "YAXXZ";
2310}
2311
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002312void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
2313 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00002314 // <initializer-name> ::= ?__E <name> YAXXZ
2315 mangleInitFiniStub(D, Out, 'E');
2316}
2317
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002318void
2319MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
2320 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00002321 // <destructor-name> ::= ?__F <name> YAXXZ
2322 mangleInitFiniStub(D, Out, 'F');
Reid Klecknerd8110b62013-09-10 20:14:30 +00002323}
2324
David Majnemer58e5bee2014-03-24 21:43:36 +00002325void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
2326 raw_ostream &Out) {
2327 // <char-type> ::= 0 # char
2328 // ::= 1 # wchar_t
2329 // ::= ??? # char16_t/char32_t will need a mangling too...
2330 //
2331 // <literal-length> ::= <non-negative integer> # the length of the literal
2332 //
2333 // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including
2334 // # null-terminator
2335 //
2336 // <encoded-string> ::= <simple character> # uninteresting character
2337 // ::= '?$' <hex digit> <hex digit> # these two nibbles
2338 // # encode the byte for the
2339 // # character
2340 // ::= '?' [a-z] # \xe1 - \xfa
2341 // ::= '?' [A-Z] # \xc1 - \xda
2342 // ::= '?' [0-9] # [,/\:. \n\t'-]
2343 //
2344 // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
2345 // <encoded-string> '@'
2346 MicrosoftCXXNameMangler Mangler(*this, Out);
2347 Mangler.getStream() << "\01??_C@_";
2348
2349 // <char-type>: The "kind" of string literal is encoded into the mangled name.
2350 // TODO: This needs to be updated when MSVC gains support for unicode
2351 // literals.
2352 if (SL->isAscii())
2353 Mangler.getStream() << '0';
2354 else if (SL->isWide())
2355 Mangler.getStream() << '1';
2356 else
2357 llvm_unreachable("unexpected string literal kind!");
2358
2359 // <literal-length>: The next part of the mangled name consists of the length
2360 // of the string.
2361 // The StringLiteral does not consider the NUL terminator byte(s) but the
2362 // mangling does.
2363 // N.B. The length is in terms of bytes, not characters.
2364 Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
2365
2366 // We will use the "Rocksoft^tm Model CRC Algorithm" to describe the
2367 // properties of our CRC:
2368 // Width : 32
2369 // Poly : 04C11DB7
2370 // Init : FFFFFFFF
2371 // RefIn : True
2372 // RefOut : True
2373 // XorOut : 00000000
2374 // Check : 340BC6D9
2375 uint32_t CRC = 0xFFFFFFFFU;
2376
2377 auto UpdateCRC = [&CRC](char Byte) {
2378 for (unsigned i = 0; i < 8; ++i) {
2379 bool Bit = CRC & 0x80000000U;
2380 if (Byte & (1U << i))
2381 Bit = !Bit;
2382 CRC <<= 1;
2383 if (Bit)
2384 CRC ^= 0x04C11DB7U;
2385 }
2386 };
2387
2388 // CRC all the bytes of the StringLiteral.
2389 for (char Byte : SL->getBytes())
2390 UpdateCRC(Byte);
2391
2392 // The NUL terminator byte(s) were not present earlier,
2393 // we need to manually process those bytes into the CRC.
2394 for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2395 ++NullTerminator)
2396 UpdateCRC('\x00');
2397
2398 // The literature refers to the process of reversing the bits in the final CRC
2399 // output as "reflection".
2400 CRC = llvm::reverseBits(CRC);
2401
2402 // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
2403 // scheme.
2404 Mangler.mangleNumber(CRC);
2405
2406 // <encoded-crc>: The mangled name also contains the first 32 _characters_
2407 // (including null-terminator bytes) of the StringLiteral.
2408 // Each character is encoded by splitting them into bytes and then encoding
2409 // the constituent bytes.
2410 auto MangleByte = [&Mangler](char Byte) {
2411 // There are five different manglings for characters:
2412 // - [a-zA-Z0-9_$]: A one-to-one mapping.
2413 // - ?[a-z]: The range from \xe1 to \xfa.
2414 // - ?[A-Z]: The range from \xc1 to \xda.
2415 // - ?[0-9]: The set of [,/\:. \n\t'-].
2416 // - ?$XX: A fallback which maps nibbles.
2417 if ((Byte >= 'a' && Byte <= 'z') || (Byte >= 'A' && Byte <= 'Z') ||
2418 (Byte >= '0' && Byte <= '9') || Byte == '_' || Byte == '$') {
2419 Mangler.getStream() << Byte;
David Majnemer0dc714a2014-03-30 06:34:26 +00002420 } else if ((Byte >= '\xe1' && Byte <= '\xfa') ||
2421 (Byte >= '\xc1' && Byte <= '\xda')) {
David Majnemer58e5bee2014-03-24 21:43:36 +00002422 Mangler.getStream() << '?' << static_cast<char>('A' + (Byte - '\xc1'));
2423 } else {
2424 switch (Byte) {
2425 case ',':
2426 Mangler.getStream() << "?0";
2427 break;
2428 case '/':
2429 Mangler.getStream() << "?1";
2430 break;
2431 case '\\':
2432 Mangler.getStream() << "?2";
2433 break;
2434 case ':':
2435 Mangler.getStream() << "?3";
2436 break;
2437 case '.':
2438 Mangler.getStream() << "?4";
2439 break;
2440 case ' ':
2441 Mangler.getStream() << "?5";
2442 break;
2443 case '\n':
2444 Mangler.getStream() << "?6";
2445 break;
2446 case '\t':
2447 Mangler.getStream() << "?7";
2448 break;
2449 case '\'':
2450 Mangler.getStream() << "?8";
2451 break;
2452 case '-':
2453 Mangler.getStream() << "?9";
2454 break;
2455 default:
2456 Mangler.getStream() << "?$";
2457 Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
2458 Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
2459 break;
2460 }
2461 }
2462 };
2463
2464 auto MangleChar = [&Mangler, &MangleByte, &SL](uint32_t CodeUnit) {
2465 if (SL->getCharByteWidth() == 1) {
2466 MangleByte(static_cast<char>(CodeUnit));
2467 } else if (SL->getCharByteWidth() == 2) {
2468 MangleByte(static_cast<char>((CodeUnit >> 16) & 0xff));
2469 MangleByte(static_cast<char>(CodeUnit & 0xff));
2470 } else {
2471 llvm_unreachable("unsupported CharByteWidth");
2472 }
2473 };
2474
2475 // Enforce our 32 character max.
2476 unsigned NumCharsToMangle = std::min(32U, SL->getLength());
2477 for (unsigned i = 0; i < NumCharsToMangle; ++i)
2478 MangleChar(SL->getCodeUnit(i));
2479
2480 // Encode the NUL terminator if there is room.
2481 if (NumCharsToMangle < 32)
2482 MangleChar(0);
2483
2484 Mangler.getStream() << '@';
2485}
2486
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002487MicrosoftMangleContext *
2488MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
2489 return new MicrosoftMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00002490}