blob: 5510f96596f5cce91f721d51a97addc8d45dbf15 [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
1104void
Reid Kleckner52518862013-03-20 01:40:23 +00001105MicrosoftCXXNameMangler::mangleTemplateArgs(const TemplateDecl *TD,
1106 const TemplateArgumentList &TemplateArgs) {
Reid Kleckner96f8f932014-02-05 17:27:08 +00001107 // <template-args> ::= <template-arg>+ @
Guy Benyei11169dd2012-12-18 14:30:41 +00001108 unsigned NumTemplateArgs = TemplateArgs.size();
1109 for (unsigned i = 0; i < NumTemplateArgs; ++i) {
Reid Kleckner52518862013-03-20 01:40:23 +00001110 const TemplateArgument &TA = TemplateArgs[i];
David Majnemer08177c52013-08-27 08:21:25 +00001111 mangleTemplateArg(TD, TA);
Guy Benyei11169dd2012-12-18 14:30:41 +00001112 }
1113 Out << '@';
1114}
1115
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001116void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
David Majnemer08177c52013-08-27 08:21:25 +00001117 const TemplateArgument &TA) {
Reid Kleckner96f8f932014-02-05 17:27:08 +00001118 // <template-arg> ::= <type>
1119 // ::= <integer-literal>
1120 // ::= <member-data-pointer>
1121 // ::= <member-function-pointer>
1122 // ::= $E? <name> <type-encoding>
1123 // ::= $1? <name> <type-encoding>
1124 // ::= $0A@
1125 // ::= <template-args>
1126
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001127 switch (TA.getKind()) {
1128 case TemplateArgument::Null:
1129 llvm_unreachable("Can't mangle null template arguments!");
David Majnemer08177c52013-08-27 08:21:25 +00001130 case TemplateArgument::TemplateExpansion:
1131 llvm_unreachable("Can't mangle template expansion arguments!");
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001132 case TemplateArgument::Type: {
1133 QualType T = TA.getAsType();
1134 mangleType(T, SourceRange(), QMM_Escape);
1135 break;
1136 }
David Majnemere8fdc062013-08-13 01:25:35 +00001137 case TemplateArgument::Declaration: {
1138 const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
David Majnemer1e378e42014-02-06 12:46:52 +00001139 if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
Reid Klecknere253b092014-02-08 01:15:37 +00001140 mangleMemberDataPointer(
1141 cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
1142 cast<ValueDecl>(ND));
Reid Kleckner09b47d12014-02-05 18:59:38 +00001143 } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
Nick Lewycky1f529662014-02-05 23:53:29 +00001144 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Reid Kleckner09b47d12014-02-05 18:59:38 +00001145 if (MD && MD->isInstance())
Reid Klecknere253b092014-02-08 01:15:37 +00001146 mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
Reid Kleckner09b47d12014-02-05 18:59:38 +00001147 else
Nick Lewycky1f529662014-02-05 23:53:29 +00001148 mangle(FD, "$1?");
Reid Kleckner09b47d12014-02-05 18:59:38 +00001149 } else {
Reid Kleckner96f8f932014-02-05 17:27:08 +00001150 mangle(ND, TA.isDeclForReferenceParam() ? "$E?" : "$1?");
Reid Kleckner09b47d12014-02-05 18:59:38 +00001151 }
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001152 break;
David Majnemere8fdc062013-08-13 01:25:35 +00001153 }
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001154 case TemplateArgument::Integral:
1155 mangleIntegerLiteral(TA.getAsIntegral(),
1156 TA.getIntegralType()->isBooleanType());
1157 break;
Reid Kleckner96f8f932014-02-05 17:27:08 +00001158 case TemplateArgument::NullPtr: {
1159 QualType T = TA.getNullPtrType();
1160 if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
David Majnemer763584d2014-02-06 10:59:19 +00001161 const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
Reid Kleckner96f8f932014-02-05 17:27:08 +00001162 if (MPT->isMemberFunctionPointerType())
1163 mangleMemberFunctionPointer(RD, 0);
1164 else
1165 mangleMemberDataPointer(RD, 0);
1166 } else {
1167 Out << "$0A@";
1168 }
David Majnemerae465ef2013-08-05 21:33:59 +00001169 break;
Reid Kleckner96f8f932014-02-05 17:27:08 +00001170 }
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001171 case TemplateArgument::Expression:
1172 mangleExpression(TA.getAsExpr());
1173 break;
1174 case TemplateArgument::Pack:
1175 // Unlike Itanium, there is no character code to indicate an argument pack.
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001176 for (TemplateArgument::pack_iterator I = TA.pack_begin(), E = TA.pack_end();
1177 I != E; ++I)
David Majnemer08177c52013-08-27 08:21:25 +00001178 mangleTemplateArg(TD, *I);
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001179 break;
1180 case TemplateArgument::Template:
David Majnemer0db0ca42013-08-05 22:26:46 +00001181 mangleType(cast<TagDecl>(
1182 TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl()));
1183 break;
Reid Klecknerf0ae35b2013-07-02 18:10:07 +00001184 }
1185}
1186
Guy Benyei11169dd2012-12-18 14:30:41 +00001187void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1188 bool IsMember) {
1189 // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1190 // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1191 // 'I' means __restrict (32/64-bit).
1192 // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1193 // keyword!
1194 // <base-cvr-qualifiers> ::= A # near
1195 // ::= B # near const
1196 // ::= C # near volatile
1197 // ::= D # near const volatile
1198 // ::= E # far (16-bit)
1199 // ::= F # far const (16-bit)
1200 // ::= G # far volatile (16-bit)
1201 // ::= H # far const volatile (16-bit)
1202 // ::= I # huge (16-bit)
1203 // ::= J # huge const (16-bit)
1204 // ::= K # huge volatile (16-bit)
1205 // ::= L # huge const volatile (16-bit)
1206 // ::= M <basis> # based
1207 // ::= N <basis> # based const
1208 // ::= O <basis> # based volatile
1209 // ::= P <basis> # based const volatile
1210 // ::= Q # near member
1211 // ::= R # near const member
1212 // ::= S # near volatile member
1213 // ::= T # near const volatile member
1214 // ::= U # far member (16-bit)
1215 // ::= V # far const member (16-bit)
1216 // ::= W # far volatile member (16-bit)
1217 // ::= X # far const volatile member (16-bit)
1218 // ::= Y # huge member (16-bit)
1219 // ::= Z # huge const member (16-bit)
1220 // ::= 0 # huge volatile member (16-bit)
1221 // ::= 1 # huge const volatile member (16-bit)
1222 // ::= 2 <basis> # based member
1223 // ::= 3 <basis> # based const member
1224 // ::= 4 <basis> # based volatile member
1225 // ::= 5 <basis> # based const volatile member
1226 // ::= 6 # near function (pointers only)
1227 // ::= 7 # far function (pointers only)
1228 // ::= 8 # near method (pointers only)
1229 // ::= 9 # far method (pointers only)
1230 // ::= _A <basis> # based function (pointers only)
1231 // ::= _B <basis> # based function (far?) (pointers only)
1232 // ::= _C <basis> # based method (pointers only)
1233 // ::= _D <basis> # based method (far?) (pointers only)
1234 // ::= _E # block (Clang)
1235 // <basis> ::= 0 # __based(void)
1236 // ::= 1 # __based(segment)?
1237 // ::= 2 <name> # __based(name)
1238 // ::= 3 # ?
1239 // ::= 4 # ?
1240 // ::= 5 # not really based
1241 bool HasConst = Quals.hasConst(),
1242 HasVolatile = Quals.hasVolatile();
David Majnemer89594f32013-08-05 22:43:06 +00001243
Guy Benyei11169dd2012-12-18 14:30:41 +00001244 if (!IsMember) {
1245 if (HasConst && HasVolatile) {
1246 Out << 'D';
1247 } else if (HasVolatile) {
1248 Out << 'C';
1249 } else if (HasConst) {
1250 Out << 'B';
1251 } else {
1252 Out << 'A';
1253 }
1254 } else {
1255 if (HasConst && HasVolatile) {
1256 Out << 'T';
1257 } else if (HasVolatile) {
1258 Out << 'S';
1259 } else if (HasConst) {
1260 Out << 'R';
1261 } else {
1262 Out << 'Q';
1263 }
1264 }
1265
1266 // FIXME: For now, just drop all extension qualifiers on the floor.
1267}
1268
David Majnemer8eec58f2014-02-18 14:20:10 +00001269void
1270MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1271 const Type *PointeeType) {
1272 bool HasRestrict = Quals.hasRestrict();
1273 if (PointersAre64Bit && (!PointeeType || !PointeeType->isFunctionType()))
1274 Out << 'E';
1275
1276 if (HasRestrict)
1277 Out << 'I';
1278}
1279
1280void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1281 // <pointer-cv-qualifiers> ::= P # no qualifiers
1282 // ::= Q # const
1283 // ::= R # volatile
1284 // ::= S # const volatile
Guy Benyei11169dd2012-12-18 14:30:41 +00001285 bool HasConst = Quals.hasConst(),
David Majnemer8eec58f2014-02-18 14:20:10 +00001286 HasVolatile = Quals.hasVolatile();
David Majnemer0b6bf8a2014-02-18 12:58:35 +00001287
Guy Benyei11169dd2012-12-18 14:30:41 +00001288 if (HasConst && HasVolatile) {
1289 Out << 'S';
1290 } else if (HasVolatile) {
1291 Out << 'R';
1292 } else if (HasConst) {
1293 Out << 'Q';
1294 } else {
1295 Out << 'P';
1296 }
1297}
1298
1299void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1300 SourceRange Range) {
Reid Kleckner18da98e2013-06-24 19:21:52 +00001301 // MSVC will backreference two canonically equivalent types that have slightly
1302 // different manglings when mangled alone.
David Majnemer5a1b2042013-09-11 04:44:30 +00001303
1304 // Decayed types do not match up with non-decayed versions of the same type.
1305 //
1306 // e.g.
1307 // void (*x)(void) will not form a backreference with void x(void)
1308 void *TypePtr;
1309 if (const DecayedType *DT = T->getAs<DecayedType>()) {
1310 TypePtr = DT->getOriginalType().getCanonicalType().getAsOpaquePtr();
1311 // If the original parameter was textually written as an array,
1312 // instead treat the decayed parameter like it's const.
1313 //
1314 // e.g.
1315 // int [] -> int * const
1316 if (DT->getOriginalType()->isArrayType())
1317 T = T.withConst();
1318 } else
1319 TypePtr = T.getCanonicalType().getAsOpaquePtr();
1320
Guy Benyei11169dd2012-12-18 14:30:41 +00001321 ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1322
1323 if (Found == TypeBackReferences.end()) {
1324 size_t OutSizeBefore = Out.GetNumBytesInBuffer();
1325
David Majnemer5a1b2042013-09-11 04:44:30 +00001326 mangleType(T, Range, QMM_Drop);
Guy Benyei11169dd2012-12-18 14:30:41 +00001327
1328 // See if it's worth creating a back reference.
1329 // Only types longer than 1 character are considered
1330 // and only 10 back references slots are available:
1331 bool LongerThanOneChar = (Out.GetNumBytesInBuffer() - OutSizeBefore > 1);
1332 if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1333 size_t Size = TypeBackReferences.size();
1334 TypeBackReferences[TypePtr] = Size;
1335 }
1336 } else {
1337 Out << Found->second;
1338 }
1339}
1340
1341void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
Peter Collingbourne2816c022013-04-25 04:25:40 +00001342 QualifierMangleMode QMM) {
Reid Kleckner18da98e2013-06-24 19:21:52 +00001343 // Don't use the canonical types. MSVC includes things like 'const' on
1344 // pointer arguments to function pointers that canonicalization strips away.
1345 T = T.getDesugaredType(getASTContext());
Guy Benyei11169dd2012-12-18 14:30:41 +00001346 Qualifiers Quals = T.getLocalQualifiers();
Reid Kleckner18da98e2013-06-24 19:21:52 +00001347 if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1348 // If there were any Quals, getAsArrayType() pushed them onto the array
1349 // element type.
Peter Collingbourne2816c022013-04-25 04:25:40 +00001350 if (QMM == QMM_Mangle)
1351 Out << 'A';
1352 else if (QMM == QMM_Escape || QMM == QMM_Result)
1353 Out << "$$B";
Reid Kleckner18da98e2013-06-24 19:21:52 +00001354 mangleArrayType(AT);
Peter Collingbourne2816c022013-04-25 04:25:40 +00001355 return;
1356 }
1357
1358 bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1359 T->isBlockPointerType();
1360
1361 switch (QMM) {
1362 case QMM_Drop:
1363 break;
1364 case QMM_Mangle:
1365 if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1366 Out << '6';
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +00001367 mangleFunctionType(FT);
Peter Collingbourne2816c022013-04-25 04:25:40 +00001368 return;
1369 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001370 mangleQualifiers(Quals, false);
Peter Collingbourne2816c022013-04-25 04:25:40 +00001371 break;
1372 case QMM_Escape:
1373 if (!IsPointer && Quals) {
1374 Out << "$$C";
1375 mangleQualifiers(Quals, false);
1376 }
1377 break;
1378 case QMM_Result:
1379 if ((!IsPointer && Quals) || isa<TagType>(T)) {
1380 Out << '?';
1381 mangleQualifiers(Quals, false);
1382 }
1383 break;
Guy Benyei11169dd2012-12-18 14:30:41 +00001384 }
1385
Peter Collingbourne2816c022013-04-25 04:25:40 +00001386 // We have to mangle these now, while we still have enough information.
David Majnemer8eec58f2014-02-18 14:20:10 +00001387 if (IsPointer) {
1388 manglePointerCVQualifiers(Quals);
1389 manglePointerExtQualifiers(Quals, T->getPointeeType().getTypePtr());
1390 }
Peter Collingbourne2816c022013-04-25 04:25:40 +00001391 const Type *ty = T.getTypePtr();
Guy Benyei11169dd2012-12-18 14:30:41 +00001392
1393 switch (ty->getTypeClass()) {
1394#define ABSTRACT_TYPE(CLASS, PARENT)
1395#define NON_CANONICAL_TYPE(CLASS, PARENT) \
1396 case Type::CLASS: \
1397 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1398 return;
1399#define TYPE(CLASS, PARENT) \
1400 case Type::CLASS: \
1401 mangleType(cast<CLASS##Type>(ty), Range); \
1402 break;
1403#include "clang/AST/TypeNodes.def"
1404#undef ABSTRACT_TYPE
1405#undef NON_CANONICAL_TYPE
1406#undef TYPE
1407 }
1408}
1409
1410void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T,
1411 SourceRange Range) {
1412 // <type> ::= <builtin-type>
1413 // <builtin-type> ::= X # void
1414 // ::= C # signed char
1415 // ::= D # char
1416 // ::= E # unsigned char
1417 // ::= F # short
1418 // ::= G # unsigned short (or wchar_t if it's not a builtin)
1419 // ::= H # int
1420 // ::= I # unsigned int
1421 // ::= J # long
1422 // ::= K # unsigned long
1423 // L # <none>
1424 // ::= M # float
1425 // ::= N # double
1426 // ::= O # long double (__float80 is mangled differently)
1427 // ::= _J # long long, __int64
1428 // ::= _K # unsigned long long, __int64
1429 // ::= _L # __int128
1430 // ::= _M # unsigned __int128
1431 // ::= _N # bool
1432 // _O # <array in parameter>
1433 // ::= _T # __float80 (Intel)
1434 // ::= _W # wchar_t
1435 // ::= _Z # __float80 (Digital Mars)
1436 switch (T->getKind()) {
1437 case BuiltinType::Void: Out << 'X'; break;
1438 case BuiltinType::SChar: Out << 'C'; break;
1439 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
1440 case BuiltinType::UChar: Out << 'E'; break;
1441 case BuiltinType::Short: Out << 'F'; break;
1442 case BuiltinType::UShort: Out << 'G'; break;
1443 case BuiltinType::Int: Out << 'H'; break;
1444 case BuiltinType::UInt: Out << 'I'; break;
1445 case BuiltinType::Long: Out << 'J'; break;
1446 case BuiltinType::ULong: Out << 'K'; break;
1447 case BuiltinType::Float: Out << 'M'; break;
1448 case BuiltinType::Double: Out << 'N'; break;
1449 // TODO: Determine size and mangle accordingly
1450 case BuiltinType::LongDouble: Out << 'O'; break;
1451 case BuiltinType::LongLong: Out << "_J"; break;
1452 case BuiltinType::ULongLong: Out << "_K"; break;
1453 case BuiltinType::Int128: Out << "_L"; break;
1454 case BuiltinType::UInt128: Out << "_M"; break;
1455 case BuiltinType::Bool: Out << "_N"; break;
1456 case BuiltinType::WChar_S:
1457 case BuiltinType::WChar_U: Out << "_W"; break;
1458
1459#define BUILTIN_TYPE(Id, SingletonId)
1460#define PLACEHOLDER_TYPE(Id, SingletonId) \
1461 case BuiltinType::Id:
1462#include "clang/AST/BuiltinTypes.def"
1463 case BuiltinType::Dependent:
1464 llvm_unreachable("placeholder types shouldn't get to name mangling");
1465
1466 case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
1467 case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
1468 case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
Guy Benyeid8a08ea2012-12-18 14:38:23 +00001469
1470 case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
1471 case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
1472 case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
1473 case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
1474 case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
1475 case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
Guy Benyei61054192013-02-07 10:55:47 +00001476 case BuiltinType::OCLSampler: Out << "PAUocl_sampler@@"; break;
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00001477 case BuiltinType::OCLEvent: Out << "PAUocl_event@@"; break;
David Majnemerb4119f72013-12-13 01:06:04 +00001478
Guy Benyei11169dd2012-12-18 14:30:41 +00001479 case BuiltinType::NullPtr: Out << "$$T"; break;
1480
1481 case BuiltinType::Char16:
1482 case BuiltinType::Char32:
1483 case BuiltinType::Half: {
1484 DiagnosticsEngine &Diags = Context.getDiags();
1485 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1486 "cannot mangle this built-in %0 type yet");
1487 Diags.Report(Range.getBegin(), DiagID)
1488 << T->getName(Context.getASTContext().getPrintingPolicy())
1489 << Range;
1490 break;
1491 }
1492 }
1493}
1494
1495// <type> ::= <function-type>
1496void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T,
1497 SourceRange) {
1498 // Structors only appear in decls, so at this point we know it's not a
1499 // structor type.
1500 // FIXME: This may not be lambda-friendly.
1501 Out << "$$A6";
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +00001502 mangleFunctionType(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00001503}
1504void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1505 SourceRange) {
1506 llvm_unreachable("Can't mangle K&R function prototypes");
1507}
1508
Peter Collingbourne2816c022013-04-25 04:25:40 +00001509void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1510 const FunctionDecl *D,
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +00001511 bool ForceInstMethod) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001512 // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1513 // <return-type> <argument-list> <throw-spec>
1514 const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1515
Reid Kleckner18da98e2013-06-24 19:21:52 +00001516 SourceRange Range;
1517 if (D) Range = D->getSourceRange();
1518
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +00001519 bool IsStructor = false, IsInstMethod = ForceInstMethod;
1520 if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1521 if (MD->isInstance())
1522 IsInstMethod = true;
1523 if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
1524 IsStructor = true;
1525 }
1526
Guy Benyei11169dd2012-12-18 14:30:41 +00001527 // If this is a C++ instance method, mangle the CVR qualifiers for the
1528 // this pointer.
David Majnemer6dda7bb2013-08-15 08:13:23 +00001529 if (IsInstMethod) {
David Majnemer8eec58f2014-02-18 14:20:10 +00001530 Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
1531 manglePointerExtQualifiers(Quals, 0);
1532 mangleQualifiers(Quals, false);
David Majnemer6dda7bb2013-08-15 08:13:23 +00001533 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001534
Reid Klecknerc5cc3382013-09-25 22:28:52 +00001535 mangleCallingConvention(T);
Guy Benyei11169dd2012-12-18 14:30:41 +00001536
1537 // <return-type> ::= <type>
1538 // ::= @ # structors (they have no declared return type)
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001539 if (IsStructor) {
1540 if (isa<CXXDestructorDecl>(D) && D == Structor &&
1541 StructorType == Dtor_Deleting) {
1542 // The scalar deleting destructor takes an extra int argument.
1543 // However, the FunctionType generated has 0 arguments.
1544 // FIXME: This is a temporary hack.
1545 // Maybe should fix the FunctionType creation instead?
Timur Iskhodzhanovf46993e2013-08-26 10:32:04 +00001546 Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001547 return;
1548 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001549 Out << '@';
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00001550 } else {
Alp Toker314cc812014-01-25 16:55:45 +00001551 QualType ResultType = Proto->getReturnType();
David Majnemer6dda7bb2013-08-15 08:13:23 +00001552 if (ResultType->isVoidType())
1553 ResultType = ResultType.getUnqualifiedType();
1554 mangleType(ResultType, Range, QMM_Result);
Guy Benyei11169dd2012-12-18 14:30:41 +00001555 }
1556
1557 // <argument-list> ::= X # void
1558 // ::= <type>+ @
1559 // ::= <type>* Z # varargs
Alp Toker9cacbab2014-01-20 20:26:09 +00001560 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001561 Out << 'X';
1562 } else {
Reid Kleckner18da98e2013-06-24 19:21:52 +00001563 // Happens for function pointer type arguments for example.
Aaron Ballman40bd0aa2014-03-17 15:23:01 +00001564 for (const auto &Arg : Proto->param_types())
1565 mangleArgumentType(Arg, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00001566 // <builtin-type> ::= Z # ellipsis
1567 if (Proto->isVariadic())
1568 Out << 'Z';
1569 else
1570 Out << '@';
1571 }
1572
1573 mangleThrowSpecification(Proto);
1574}
1575
1576void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
Reid Kleckner369f3162013-05-14 20:30:42 +00001577 // <function-class> ::= <member-function> E? # E designates a 64-bit 'this'
1578 // # pointer. in 64-bit mode *all*
1579 // # 'this' pointers are 64-bit.
1580 // ::= <global-function>
1581 // <member-function> ::= A # private: near
1582 // ::= B # private: far
1583 // ::= C # private: static near
1584 // ::= D # private: static far
1585 // ::= E # private: virtual near
1586 // ::= F # private: virtual far
Reid Kleckner369f3162013-05-14 20:30:42 +00001587 // ::= I # protected: near
1588 // ::= J # protected: far
1589 // ::= K # protected: static near
1590 // ::= L # protected: static far
1591 // ::= M # protected: virtual near
1592 // ::= N # protected: virtual far
Reid Kleckner369f3162013-05-14 20:30:42 +00001593 // ::= Q # public: near
1594 // ::= R # public: far
1595 // ::= S # public: static near
1596 // ::= T # public: static far
1597 // ::= U # public: virtual near
1598 // ::= V # public: virtual far
Reid Kleckner369f3162013-05-14 20:30:42 +00001599 // <global-function> ::= Y # global near
1600 // ::= Z # global far
Guy Benyei11169dd2012-12-18 14:30:41 +00001601 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1602 switch (MD->getAccess()) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00001603 case AS_none:
1604 llvm_unreachable("Unsupported access specifier");
Guy Benyei11169dd2012-12-18 14:30:41 +00001605 case AS_private:
1606 if (MD->isStatic())
1607 Out << 'C';
1608 else if (MD->isVirtual())
1609 Out << 'E';
1610 else
1611 Out << 'A';
1612 break;
1613 case AS_protected:
1614 if (MD->isStatic())
1615 Out << 'K';
1616 else if (MD->isVirtual())
1617 Out << 'M';
1618 else
1619 Out << 'I';
1620 break;
1621 case AS_public:
1622 if (MD->isStatic())
1623 Out << 'S';
1624 else if (MD->isVirtual())
1625 Out << 'U';
1626 else
1627 Out << 'Q';
1628 }
1629 } else
1630 Out << 'Y';
1631}
Reid Klecknerc5cc3382013-09-25 22:28:52 +00001632void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001633 // <calling-convention> ::= A # __cdecl
1634 // ::= B # __export __cdecl
1635 // ::= C # __pascal
1636 // ::= D # __export __pascal
1637 // ::= E # __thiscall
1638 // ::= F # __export __thiscall
1639 // ::= G # __stdcall
1640 // ::= H # __export __stdcall
1641 // ::= I # __fastcall
1642 // ::= J # __export __fastcall
1643 // The 'export' calling conventions are from a bygone era
1644 // (*cough*Win16*cough*) when functions were declared for export with
1645 // that keyword. (It didn't actually export them, it just made them so
1646 // that they could be in a DLL and somebody from another module could call
1647 // them.)
1648 CallingConv CC = T->getCallConv();
Guy Benyei11169dd2012-12-18 14:30:41 +00001649 switch (CC) {
1650 default:
1651 llvm_unreachable("Unsupported CC for mangling");
Charles Davisb5a214e2013-08-30 04:39:01 +00001652 case CC_X86_64Win64:
1653 case CC_X86_64SysV:
Guy Benyei11169dd2012-12-18 14:30:41 +00001654 case CC_C: Out << 'A'; break;
1655 case CC_X86Pascal: Out << 'C'; break;
1656 case CC_X86ThisCall: Out << 'E'; break;
1657 case CC_X86StdCall: Out << 'G'; break;
1658 case CC_X86FastCall: Out << 'I'; break;
1659 }
1660}
1661void MicrosoftCXXNameMangler::mangleThrowSpecification(
1662 const FunctionProtoType *FT) {
1663 // <throw-spec> ::= Z # throw(...) (default)
1664 // ::= @ # throw() or __declspec/__attribute__((nothrow))
1665 // ::= <type>+
1666 // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1667 // all actually mangled as 'Z'. (They're ignored because their associated
1668 // functionality isn't implemented, and probably never will be.)
1669 Out << 'Z';
1670}
1671
1672void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
1673 SourceRange Range) {
1674 // Probably should be mangled as a template instantiation; need to see what
1675 // VC does first.
1676 DiagnosticsEngine &Diags = Context.getDiags();
1677 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1678 "cannot mangle this unresolved dependent type yet");
1679 Diags.Report(Range.getBegin(), DiagID)
1680 << Range;
1681}
1682
1683// <type> ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1684// <union-type> ::= T <name>
1685// <struct-type> ::= U <name>
1686// <class-type> ::= V <name>
David Majnemer048f90c2013-12-09 04:28:34 +00001687// <enum-type> ::= W4 <name>
Guy Benyei11169dd2012-12-18 14:30:41 +00001688void MicrosoftCXXNameMangler::mangleType(const EnumType *T, SourceRange) {
David Majnemer0db0ca42013-08-05 22:26:46 +00001689 mangleType(cast<TagType>(T)->getDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001690}
1691void MicrosoftCXXNameMangler::mangleType(const RecordType *T, SourceRange) {
David Majnemer0db0ca42013-08-05 22:26:46 +00001692 mangleType(cast<TagType>(T)->getDecl());
Guy Benyei11169dd2012-12-18 14:30:41 +00001693}
David Majnemer0db0ca42013-08-05 22:26:46 +00001694void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
1695 switch (TD->getTagKind()) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001696 case TTK_Union:
1697 Out << 'T';
1698 break;
1699 case TTK_Struct:
1700 case TTK_Interface:
1701 Out << 'U';
1702 break;
1703 case TTK_Class:
1704 Out << 'V';
1705 break;
1706 case TTK_Enum:
David Majnemer048f90c2013-12-09 04:28:34 +00001707 Out << "W4";
Guy Benyei11169dd2012-12-18 14:30:41 +00001708 break;
1709 }
David Majnemer0db0ca42013-08-05 22:26:46 +00001710 mangleName(TD);
Guy Benyei11169dd2012-12-18 14:30:41 +00001711}
1712
1713// <type> ::= <array-type>
1714// <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1715// [Y <dimension-count> <dimension>+]
Reid Kleckner369f3162013-05-14 20:30:42 +00001716// <element-type> # as global, E is never required
Guy Benyei11169dd2012-12-18 14:30:41 +00001717// It's supposed to be the other way around, but for some strange reason, it
1718// isn't. Today this behavior is retained for the sole purpose of backwards
1719// compatibility.
David Majnemer5a1b2042013-09-11 04:44:30 +00001720void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
Guy Benyei11169dd2012-12-18 14:30:41 +00001721 // This isn't a recursive mangling, so now we have to do it all in this
1722 // one call.
David Majnemer8eec58f2014-02-18 14:20:10 +00001723 manglePointerCVQualifiers(T->getElementType().getQualifiers());
Peter Collingbourne2816c022013-04-25 04:25:40 +00001724 mangleType(T->getElementType(), SourceRange());
Guy Benyei11169dd2012-12-18 14:30:41 +00001725}
1726void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *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 VariableArrayType *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 DependentSizedArrayType *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}
1738void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
1739 SourceRange) {
Peter Collingbourne2816c022013-04-25 04:25:40 +00001740 llvm_unreachable("Should have been special cased");
Guy Benyei11169dd2012-12-18 14:30:41 +00001741}
Reid Kleckner18da98e2013-06-24 19:21:52 +00001742void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
Peter Collingbourne2816c022013-04-25 04:25:40 +00001743 QualType ElementTy(T, 0);
Guy Benyei11169dd2012-12-18 14:30:41 +00001744 SmallVector<llvm::APInt, 3> Dimensions;
1745 for (;;) {
1746 if (const ConstantArrayType *CAT =
1747 getASTContext().getAsConstantArrayType(ElementTy)) {
1748 Dimensions.push_back(CAT->getSize());
1749 ElementTy = CAT->getElementType();
1750 } else if (ElementTy->isVariableArrayType()) {
1751 const VariableArrayType *VAT =
1752 getASTContext().getAsVariableArrayType(ElementTy);
1753 DiagnosticsEngine &Diags = Context.getDiags();
1754 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1755 "cannot mangle this variable-length array yet");
1756 Diags.Report(VAT->getSizeExpr()->getExprLoc(), DiagID)
1757 << VAT->getBracketsRange();
1758 return;
1759 } else if (ElementTy->isDependentSizedArrayType()) {
1760 // The dependent expression has to be folded into a constant (TODO).
1761 const DependentSizedArrayType *DSAT =
1762 getASTContext().getAsDependentSizedArrayType(ElementTy);
1763 DiagnosticsEngine &Diags = Context.getDiags();
1764 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1765 "cannot mangle this dependent-length array yet");
1766 Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
1767 << DSAT->getBracketsRange();
1768 return;
Peter Collingbourne2816c022013-04-25 04:25:40 +00001769 } else if (const IncompleteArrayType *IAT =
1770 getASTContext().getAsIncompleteArrayType(ElementTy)) {
1771 Dimensions.push_back(llvm::APInt(32, 0));
1772 ElementTy = IAT->getElementType();
1773 }
Guy Benyei11169dd2012-12-18 14:30:41 +00001774 else break;
1775 }
Peter Collingbourne2816c022013-04-25 04:25:40 +00001776 Out << 'Y';
1777 // <dimension-count> ::= <number> # number of extra dimensions
1778 mangleNumber(Dimensions.size());
1779 for (unsigned Dim = 0; Dim < Dimensions.size(); ++Dim)
1780 mangleNumber(Dimensions[Dim].getLimitedValue());
Reid Kleckner18da98e2013-06-24 19:21:52 +00001781 mangleType(ElementTy, SourceRange(), QMM_Escape);
Guy Benyei11169dd2012-12-18 14:30:41 +00001782}
1783
1784// <type> ::= <pointer-to-member-type>
1785// <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1786// <class name> <type>
1787void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
1788 SourceRange Range) {
1789 QualType PointeeType = T->getPointeeType();
1790 if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
1791 Out << '8';
1792 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +00001793 mangleFunctionType(FPT, 0, true);
Guy Benyei11169dd2012-12-18 14:30:41 +00001794 } else {
1795 mangleQualifiers(PointeeType.getQualifiers(), true);
1796 mangleName(T->getClass()->castAs<RecordType>()->getDecl());
Peter Collingbourne2816c022013-04-25 04:25:40 +00001797 mangleType(PointeeType, Range, QMM_Drop);
Guy Benyei11169dd2012-12-18 14:30:41 +00001798 }
1799}
1800
1801void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
1802 SourceRange Range) {
1803 DiagnosticsEngine &Diags = Context.getDiags();
1804 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1805 "cannot mangle this template type parameter type yet");
1806 Diags.Report(Range.getBegin(), DiagID)
1807 << Range;
1808}
1809
1810void MicrosoftCXXNameMangler::mangleType(
1811 const SubstTemplateTypeParmPackType *T,
1812 SourceRange Range) {
1813 DiagnosticsEngine &Diags = Context.getDiags();
1814 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1815 "cannot mangle this substituted parameter pack yet");
1816 Diags.Report(Range.getBegin(), DiagID)
1817 << Range;
1818}
1819
1820// <type> ::= <pointer-type>
Reid Kleckner369f3162013-05-14 20:30:42 +00001821// <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
Alp Tokerd4733632013-12-05 04:47:09 +00001822// # the E is required for 64-bit non-static pointers
Guy Benyei11169dd2012-12-18 14:30:41 +00001823void MicrosoftCXXNameMangler::mangleType(const PointerType *T,
1824 SourceRange Range) {
1825 QualType PointeeTy = T->getPointeeType();
Peter Collingbourne2816c022013-04-25 04:25:40 +00001826 mangleType(PointeeTy, Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00001827}
1828void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
1829 SourceRange Range) {
1830 // Object pointers never have qualifiers.
1831 Out << 'A';
David Majnemer8eec58f2014-02-18 14:20:10 +00001832 manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
Guy Benyei11169dd2012-12-18 14:30:41 +00001833 mangleType(T->getPointeeType(), Range);
1834}
1835
1836// <type> ::= <reference-type>
Reid Kleckner369f3162013-05-14 20:30:42 +00001837// <reference-type> ::= A E? <cvr-qualifiers> <type>
Alp Tokerd4733632013-12-05 04:47:09 +00001838// # the E is required for 64-bit non-static lvalue references
Guy Benyei11169dd2012-12-18 14:30:41 +00001839void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
1840 SourceRange Range) {
1841 Out << 'A';
David Majnemer8eec58f2014-02-18 14:20:10 +00001842 manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
Peter Collingbourne2816c022013-04-25 04:25:40 +00001843 mangleType(T->getPointeeType(), Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00001844}
1845
1846// <type> ::= <r-value-reference-type>
Reid Kleckner369f3162013-05-14 20:30:42 +00001847// <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
Alp Tokerd4733632013-12-05 04:47:09 +00001848// # the E is required for 64-bit non-static rvalue references
Guy Benyei11169dd2012-12-18 14:30:41 +00001849void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
1850 SourceRange Range) {
1851 Out << "$$Q";
David Majnemer8eec58f2014-02-18 14:20:10 +00001852 manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
Peter Collingbourne2816c022013-04-25 04:25:40 +00001853 mangleType(T->getPointeeType(), Range);
Guy Benyei11169dd2012-12-18 14:30:41 +00001854}
1855
1856void MicrosoftCXXNameMangler::mangleType(const ComplexType *T,
1857 SourceRange Range) {
1858 DiagnosticsEngine &Diags = Context.getDiags();
1859 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1860 "cannot mangle this complex number type yet");
1861 Diags.Report(Range.getBegin(), DiagID)
1862 << Range;
1863}
1864
1865void MicrosoftCXXNameMangler::mangleType(const VectorType *T,
1866 SourceRange Range) {
Reid Klecknere7e64d82013-03-26 16:56:59 +00001867 const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
1868 assert(ET && "vectors with non-builtin elements are unsupported");
1869 uint64_t Width = getASTContext().getTypeSize(T);
1870 // Pattern match exactly the typedefs in our intrinsic headers. Anything that
1871 // doesn't match the Intel types uses a custom mangling below.
1872 bool IntelVector = true;
1873 if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
1874 Out << "T__m64";
1875 } else if (Width == 128 || Width == 256) {
1876 if (ET->getKind() == BuiltinType::Float)
1877 Out << "T__m" << Width;
1878 else if (ET->getKind() == BuiltinType::LongLong)
1879 Out << "T__m" << Width << 'i';
1880 else if (ET->getKind() == BuiltinType::Double)
1881 Out << "U__m" << Width << 'd';
1882 else
1883 IntelVector = false;
1884 } else {
1885 IntelVector = false;
1886 }
1887
1888 if (!IntelVector) {
1889 // The MS ABI doesn't have a special mangling for vector types, so we define
1890 // our own mangling to handle uses of __vector_size__ on user-specified
1891 // types, and for extensions like __v4sf.
1892 Out << "T__clang_vec" << T->getNumElements() << '_';
1893 mangleType(ET, Range);
1894 }
1895
1896 Out << "@@";
Guy Benyei11169dd2012-12-18 14:30:41 +00001897}
Reid Klecknere7e64d82013-03-26 16:56:59 +00001898
Guy Benyei11169dd2012-12-18 14:30:41 +00001899void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
1900 SourceRange Range) {
1901 DiagnosticsEngine &Diags = Context.getDiags();
1902 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1903 "cannot mangle this extended vector type yet");
1904 Diags.Report(Range.getBegin(), DiagID)
1905 << Range;
1906}
1907void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
1908 SourceRange Range) {
1909 DiagnosticsEngine &Diags = Context.getDiags();
1910 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1911 "cannot mangle this dependent-sized extended vector type yet");
1912 Diags.Report(Range.getBegin(), DiagID)
1913 << Range;
1914}
1915
1916void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T,
1917 SourceRange) {
1918 // ObjC interfaces have structs underlying them.
1919 Out << 'U';
1920 mangleName(T->getDecl());
1921}
1922
1923void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
1924 SourceRange Range) {
1925 // We don't allow overloading by different protocol qualification,
1926 // so mangling them isn't necessary.
1927 mangleType(T->getBaseType(), Range);
1928}
1929
1930void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
1931 SourceRange Range) {
1932 Out << "_E";
1933
1934 QualType pointee = T->getPointeeType();
Timur Iskhodzhanov555a7722013-10-04 11:25:05 +00001935 mangleFunctionType(pointee->castAs<FunctionProtoType>());
Guy Benyei11169dd2012-12-18 14:30:41 +00001936}
1937
David Majnemerf0a84f22013-08-16 08:29:13 +00001938void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
1939 SourceRange) {
1940 llvm_unreachable("Cannot mangle injected class name type.");
Guy Benyei11169dd2012-12-18 14:30:41 +00001941}
1942
1943void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
1944 SourceRange Range) {
1945 DiagnosticsEngine &Diags = Context.getDiags();
1946 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1947 "cannot mangle this template specialization type yet");
1948 Diags.Report(Range.getBegin(), DiagID)
1949 << Range;
1950}
1951
1952void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T,
1953 SourceRange Range) {
1954 DiagnosticsEngine &Diags = Context.getDiags();
1955 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1956 "cannot mangle this dependent name type yet");
1957 Diags.Report(Range.getBegin(), DiagID)
1958 << Range;
1959}
1960
1961void MicrosoftCXXNameMangler::mangleType(
1962 const DependentTemplateSpecializationType *T,
1963 SourceRange Range) {
1964 DiagnosticsEngine &Diags = Context.getDiags();
1965 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1966 "cannot mangle this dependent template specialization type yet");
1967 Diags.Report(Range.getBegin(), DiagID)
1968 << Range;
1969}
1970
1971void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T,
1972 SourceRange Range) {
1973 DiagnosticsEngine &Diags = Context.getDiags();
1974 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1975 "cannot mangle this pack expansion yet");
1976 Diags.Report(Range.getBegin(), DiagID)
1977 << Range;
1978}
1979
1980void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T,
1981 SourceRange Range) {
1982 DiagnosticsEngine &Diags = Context.getDiags();
1983 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1984 "cannot mangle this typeof(type) yet");
1985 Diags.Report(Range.getBegin(), DiagID)
1986 << Range;
1987}
1988
1989void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T,
1990 SourceRange Range) {
1991 DiagnosticsEngine &Diags = Context.getDiags();
1992 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1993 "cannot mangle this typeof(expression) yet");
1994 Diags.Report(Range.getBegin(), DiagID)
1995 << Range;
1996}
1997
1998void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T,
1999 SourceRange Range) {
2000 DiagnosticsEngine &Diags = Context.getDiags();
2001 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2002 "cannot mangle this decltype() yet");
2003 Diags.Report(Range.getBegin(), DiagID)
2004 << Range;
2005}
2006
2007void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2008 SourceRange Range) {
2009 DiagnosticsEngine &Diags = Context.getDiags();
2010 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2011 "cannot mangle this unary transform type yet");
2012 Diags.Report(Range.getBegin(), DiagID)
2013 << Range;
2014}
2015
2016void MicrosoftCXXNameMangler::mangleType(const AutoType *T, SourceRange Range) {
David Majnemerb9a5f2d2014-01-21 20:33:36 +00002017 assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2018
Guy Benyei11169dd2012-12-18 14:30:41 +00002019 DiagnosticsEngine &Diags = Context.getDiags();
2020 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2021 "cannot mangle this 'auto' type yet");
2022 Diags.Report(Range.getBegin(), DiagID)
2023 << Range;
2024}
2025
2026void MicrosoftCXXNameMangler::mangleType(const AtomicType *T,
2027 SourceRange Range) {
2028 DiagnosticsEngine &Diags = Context.getDiags();
2029 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2030 "cannot mangle this C11 atomic type yet");
2031 Diags.Report(Range.getBegin(), DiagID)
2032 << Range;
2033}
2034
Rafael Espindola002667c2013-10-16 01:40:34 +00002035void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2036 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002037 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2038 "Invalid mangleName() call, argument is not a variable or function!");
2039 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2040 "Invalid mangleName() call on 'structor decl!");
2041
2042 PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2043 getASTContext().getSourceManager(),
2044 "Mangling declaration");
2045
2046 MicrosoftCXXNameMangler Mangler(*this, Out);
2047 return Mangler.mangle(D);
2048}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002049
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002050// <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2051// <virtual-adjustment>
2052// <no-adjustment> ::= A # private near
2053// ::= B # private far
2054// ::= I # protected near
2055// ::= J # protected far
2056// ::= Q # public near
2057// ::= R # public far
2058// <static-adjustment> ::= G <static-offset> # private near
2059// ::= H <static-offset> # private far
2060// ::= O <static-offset> # protected near
2061// ::= P <static-offset> # protected far
2062// ::= W <static-offset> # public near
2063// ::= X <static-offset> # public far
2064// <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2065// ::= $1 <virtual-shift> <static-offset> # private far
2066// ::= $2 <virtual-shift> <static-offset> # protected near
2067// ::= $3 <virtual-shift> <static-offset> # protected far
2068// ::= $4 <virtual-shift> <static-offset> # public near
2069// ::= $5 <virtual-shift> <static-offset> # public far
2070// <virtual-shift> ::= <vtordisp-shift> | <vtordispex-shift>
2071// <vtordisp-shift> ::= <offset-to-vtordisp>
2072// <vtordispex-shift> ::= <offset-to-vbptr> <vbase-offset-offset>
2073// <offset-to-vtordisp>
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002074static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2075 const ThisAdjustment &Adjustment,
2076 MicrosoftCXXNameMangler &Mangler,
2077 raw_ostream &Out) {
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002078 if (!Adjustment.Virtual.isEmpty()) {
2079 Out << '$';
2080 char AccessSpec;
2081 switch (MD->getAccess()) {
2082 case AS_none:
2083 llvm_unreachable("Unsupported access specifier");
2084 case AS_private:
2085 AccessSpec = '0';
2086 break;
2087 case AS_protected:
2088 AccessSpec = '2';
2089 break;
2090 case AS_public:
2091 AccessSpec = '4';
2092 }
2093 if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2094 Out << 'R' << AccessSpec;
David Majnemer2a816452013-12-09 10:44:32 +00002095 Mangler.mangleNumber(
2096 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2097 Mangler.mangleNumber(
2098 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2099 Mangler.mangleNumber(
2100 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2101 Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002102 } else {
2103 Out << AccessSpec;
David Majnemer2a816452013-12-09 10:44:32 +00002104 Mangler.mangleNumber(
2105 static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2106 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
Timur Iskhodzhanov053142a2013-11-06 06:24:31 +00002107 }
2108 } else if (Adjustment.NonVirtual != 0) {
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002109 switch (MD->getAccess()) {
2110 case AS_none:
2111 llvm_unreachable("Unsupported access specifier");
2112 case AS_private:
2113 Out << 'G';
2114 break;
2115 case AS_protected:
2116 Out << 'O';
2117 break;
2118 case AS_public:
2119 Out << 'W';
2120 }
David Majnemer2a816452013-12-09 10:44:32 +00002121 Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002122 } else {
2123 switch (MD->getAccess()) {
2124 case AS_none:
2125 llvm_unreachable("Unsupported access specifier");
2126 case AS_private:
2127 Out << 'A';
2128 break;
2129 case AS_protected:
2130 Out << 'I';
2131 break;
2132 case AS_public:
2133 Out << 'Q';
2134 }
2135 }
2136}
2137
Reid Kleckner96f8f932014-02-05 17:27:08 +00002138void
2139MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2140 raw_ostream &Out) {
2141 MicrosoftVTableContext *VTContext =
2142 cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2143 const MicrosoftVTableContext::MethodVFTableLocation &ML =
2144 VTContext->getMethodVFTableLocation(GlobalDecl(MD));
Hans Wennborg88497d62013-11-15 17:24:45 +00002145
2146 MicrosoftCXXNameMangler Mangler(*this, Out);
Reid Kleckner96f8f932014-02-05 17:27:08 +00002147 Mangler.getStream() << "\01?";
2148 Mangler.mangleVirtualMemPtrThunk(MD, ML);
Hans Wennborg88497d62013-11-15 17:24:45 +00002149}
2150
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002151void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2152 const ThunkInfo &Thunk,
2153 raw_ostream &Out) {
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002154 MicrosoftCXXNameMangler Mangler(*this, Out);
2155 Out << "\01?";
2156 Mangler.mangleName(MD);
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002157 mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
2158 if (!Thunk.Return.isEmpty())
2159 assert(Thunk.Method != 0 && "Thunk info should hold the overridee decl");
2160
2161 const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2162 Mangler.mangleFunctionType(
2163 DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
Guy Benyei11169dd2012-12-18 14:30:41 +00002164}
Timur Iskhodzhanovdf7e7fb2013-07-30 09:46:19 +00002165
Timur Iskhodzhanovad9d3b82013-10-09 09:23:58 +00002166void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2167 const CXXDestructorDecl *DD, CXXDtorType Type,
2168 const ThisAdjustment &Adjustment, raw_ostream &Out) {
2169 // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2170 // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2171 // mangling manually until we support both deleting dtor types.
2172 assert(Type == Dtor_Deleting);
2173 MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
2174 Out << "\01??_E";
2175 Mangler.mangleName(DD->getParent());
2176 mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
2177 Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
Guy Benyei11169dd2012-12-18 14:30:41 +00002178}
Reid Kleckner7810af02013-06-19 15:20:38 +00002179
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002180void MicrosoftMangleContextImpl::mangleCXXVFTable(
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002181 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2182 raw_ostream &Out) {
Reid Kleckner7810af02013-06-19 15:20:38 +00002183 // <mangled-name> ::= ?_7 <class-name> <storage-class>
2184 // <cvr-qualifiers> [<name>] @
Guy Benyei11169dd2012-12-18 14:30:41 +00002185 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
Reid Kleckner7810af02013-06-19 15:20:38 +00002186 // is always '6' for vftables.
Guy Benyei11169dd2012-12-18 14:30:41 +00002187 MicrosoftCXXNameMangler Mangler(*this, Out);
2188 Mangler.getStream() << "\01??_7";
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +00002189 Mangler.mangleName(Derived);
2190 Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2191 for (ArrayRef<const CXXRecordDecl *>::iterator I = BasePath.begin(),
2192 E = BasePath.end();
2193 I != E; ++I) {
2194 Mangler.mangleName(*I);
2195 }
Guy Benyei11169dd2012-12-18 14:30:41 +00002196 Mangler.getStream() << '@';
2197}
Reid Kleckner7810af02013-06-19 15:20:38 +00002198
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002199void MicrosoftMangleContextImpl::mangleCXXVBTable(
Reid Kleckner7810af02013-06-19 15:20:38 +00002200 const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2201 raw_ostream &Out) {
2202 // <mangled-name> ::= ?_8 <class-name> <storage-class>
2203 // <cvr-qualifiers> [<name>] @
2204 // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2205 // is always '7' for vbtables.
2206 MicrosoftCXXNameMangler Mangler(*this, Out);
2207 Mangler.getStream() << "\01??_8";
2208 Mangler.mangleName(Derived);
2209 Mangler.getStream() << "7B"; // '7' for vbtable, 'B' for const.
2210 for (ArrayRef<const CXXRecordDecl *>::iterator I = BasePath.begin(),
2211 E = BasePath.end();
2212 I != E; ++I) {
2213 Mangler.mangleName(*I);
2214 }
2215 Mangler.getStream() << '@';
2216}
2217
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002218void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002219 // FIXME: Give a location...
2220 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2221 "cannot mangle RTTI descriptors for type %0 yet");
2222 getDiags().Report(DiagID)
2223 << T.getBaseTypeIdentifier();
2224}
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002225
2226void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T, raw_ostream &) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002227 // FIXME: Give a location...
2228 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2229 "cannot mangle the name of type %0 into RTTI descriptors yet");
2230 getDiags().Report(DiagID)
2231 << T.getBaseTypeIdentifier();
2232}
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002233
Reid Klecknercc99e262013-11-19 23:23:00 +00002234void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
2235 // This is just a made up unique string for the purposes of tbaa. undname
2236 // does *not* know how to demangle it.
2237 MicrosoftCXXNameMangler Mangler(*this, Out);
2238 Mangler.getStream() << '?';
2239 Mangler.mangleType(T, SourceRange());
2240}
2241
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002242void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
2243 CXXCtorType Type,
2244 raw_ostream &Out) {
Guy Benyei11169dd2012-12-18 14:30:41 +00002245 MicrosoftCXXNameMangler mangler(*this, Out);
2246 mangler.mangle(D);
2247}
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002248
2249void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
2250 CXXDtorType Type,
2251 raw_ostream &Out) {
Timur Iskhodzhanovee6bc532013-02-13 08:37:51 +00002252 MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
Guy Benyei11169dd2012-12-18 14:30:41 +00002253 mangler.mangle(D);
2254}
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002255
2256void MicrosoftMangleContextImpl::mangleReferenceTemporary(const VarDecl *VD,
David Majnemer210e6bfa12013-12-13 00:39:38 +00002257 raw_ostream &) {
2258 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2259 "cannot mangle this reference temporary yet");
2260 getDiags().Report(VD->getLocation(), DiagID);
Guy Benyei11169dd2012-12-18 14:30:41 +00002261}
2262
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002263void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
2264 raw_ostream &Out) {
David Majnemer25e1a5e2013-12-13 00:52:45 +00002265 // TODO: This is not correct, especially with respect to MSVC2013. MSVC2013
2266 // utilizes thread local variables to implement thread safe, re-entrant
2267 // initialization for statics. They no longer differentiate between an
2268 // externally visible and non-externally visible static with respect to
2269 // mangling, they all get $TSS <number>.
2270 //
2271 // N.B. This means that they can get more than 32 static variable guards in a
2272 // scope. It also means that they broke compatibility with their own ABI.
2273
David Majnemer2206bf52014-03-05 08:57:59 +00002274 // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
Reid Klecknerd8110b62013-09-10 20:14:30 +00002275 // ::= ?$S <guard-num> @ <postfix> @4IA
2276
2277 // The first mangling is what MSVC uses to guard static locals in inline
2278 // functions. It uses a different mangling in external functions to support
2279 // guarding more than 32 variables. MSVC rejects inline functions with more
2280 // than 32 static locals. We don't fully implement the second mangling
2281 // because those guards are not externally visible, and instead use LLVM's
2282 // default renaming when creating a new guard variable.
2283 MicrosoftCXXNameMangler Mangler(*this, Out);
2284
2285 bool Visible = VD->isExternallyVisible();
2286 // <operator-name> ::= ?_B # local static guard
2287 Mangler.getStream() << (Visible ? "\01??_B" : "\01?$S1@");
David Majnemer34b49892014-03-06 19:57:36 +00002288 unsigned ScopeDepth = 0;
2289 if (Visible && !getNextDiscriminator(VD, ScopeDepth))
2290 // If we do not have a discriminator and are emitting a guard variable for
2291 // use at global scope, then mangling the nested name will not be enough to
2292 // remove ambiguities.
2293 Mangler.mangle(VD, "");
2294 else
2295 Mangler.mangleNestedName(VD);
David Majnemer2206bf52014-03-05 08:57:59 +00002296 Mangler.getStream() << (Visible ? "@5" : "@4IA");
David Majnemer34b49892014-03-06 19:57:36 +00002297 if (ScopeDepth)
David Majnemer2206bf52014-03-05 08:57:59 +00002298 Mangler.mangleNumber(ScopeDepth);
Reid Klecknerd8110b62013-09-10 20:14:30 +00002299}
2300
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002301void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
2302 raw_ostream &Out,
2303 char CharCode) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00002304 MicrosoftCXXNameMangler Mangler(*this, Out);
2305 Mangler.getStream() << "\01??__" << CharCode;
2306 Mangler.mangleName(D);
David Majnemerf55feec2014-03-06 19:10:27 +00002307 if (D->isStaticDataMember()) {
2308 Mangler.mangleVariableEncoding(D);
2309 Mangler.getStream() << '@';
2310 }
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00002311 // This is the function class mangling. These stubs are global, non-variadic,
2312 // cdecl functions that return void and take no args.
2313 Mangler.getStream() << "YAXXZ";
2314}
2315
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002316void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
2317 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00002318 // <initializer-name> ::= ?__E <name> YAXXZ
2319 mangleInitFiniStub(D, Out, 'E');
2320}
2321
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002322void
2323MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
2324 raw_ostream &Out) {
Reid Kleckner1ece9fc2013-09-10 20:43:12 +00002325 // <destructor-name> ::= ?__F <name> YAXXZ
2326 mangleInitFiniStub(D, Out, 'F');
Reid Klecknerd8110b62013-09-10 20:14:30 +00002327}
2328
David Majnemer58e5bee2014-03-24 21:43:36 +00002329void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
2330 raw_ostream &Out) {
2331 // <char-type> ::= 0 # char
2332 // ::= 1 # wchar_t
2333 // ::= ??? # char16_t/char32_t will need a mangling too...
2334 //
2335 // <literal-length> ::= <non-negative integer> # the length of the literal
2336 //
2337 // <encoded-crc> ::= <hex digit>+ @ # crc of the literal including
2338 // # null-terminator
2339 //
2340 // <encoded-string> ::= <simple character> # uninteresting character
2341 // ::= '?$' <hex digit> <hex digit> # these two nibbles
2342 // # encode the byte for the
2343 // # character
2344 // ::= '?' [a-z] # \xe1 - \xfa
2345 // ::= '?' [A-Z] # \xc1 - \xda
2346 // ::= '?' [0-9] # [,/\:. \n\t'-]
2347 //
2348 // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
2349 // <encoded-string> '@'
2350 MicrosoftCXXNameMangler Mangler(*this, Out);
2351 Mangler.getStream() << "\01??_C@_";
2352
2353 // <char-type>: The "kind" of string literal is encoded into the mangled name.
2354 // TODO: This needs to be updated when MSVC gains support for unicode
2355 // literals.
2356 if (SL->isAscii())
2357 Mangler.getStream() << '0';
2358 else if (SL->isWide())
2359 Mangler.getStream() << '1';
2360 else
2361 llvm_unreachable("unexpected string literal kind!");
2362
2363 // <literal-length>: The next part of the mangled name consists of the length
2364 // of the string.
2365 // The StringLiteral does not consider the NUL terminator byte(s) but the
2366 // mangling does.
2367 // N.B. The length is in terms of bytes, not characters.
2368 Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
2369
2370 // We will use the "Rocksoft^tm Model CRC Algorithm" to describe the
2371 // properties of our CRC:
2372 // Width : 32
2373 // Poly : 04C11DB7
2374 // Init : FFFFFFFF
2375 // RefIn : True
2376 // RefOut : True
2377 // XorOut : 00000000
2378 // Check : 340BC6D9
2379 uint32_t CRC = 0xFFFFFFFFU;
2380
2381 auto UpdateCRC = [&CRC](char Byte) {
2382 for (unsigned i = 0; i < 8; ++i) {
2383 bool Bit = CRC & 0x80000000U;
2384 if (Byte & (1U << i))
2385 Bit = !Bit;
2386 CRC <<= 1;
2387 if (Bit)
2388 CRC ^= 0x04C11DB7U;
2389 }
2390 };
2391
2392 // CRC all the bytes of the StringLiteral.
2393 for (char Byte : SL->getBytes())
2394 UpdateCRC(Byte);
2395
2396 // The NUL terminator byte(s) were not present earlier,
2397 // we need to manually process those bytes into the CRC.
2398 for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2399 ++NullTerminator)
2400 UpdateCRC('\x00');
2401
2402 // The literature refers to the process of reversing the bits in the final CRC
2403 // output as "reflection".
2404 CRC = llvm::reverseBits(CRC);
2405
2406 // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
2407 // scheme.
2408 Mangler.mangleNumber(CRC);
2409
2410 // <encoded-crc>: The mangled name also contains the first 32 _characters_
2411 // (including null-terminator bytes) of the StringLiteral.
2412 // Each character is encoded by splitting them into bytes and then encoding
2413 // the constituent bytes.
2414 auto MangleByte = [&Mangler](char Byte) {
2415 // There are five different manglings for characters:
2416 // - [a-zA-Z0-9_$]: A one-to-one mapping.
2417 // - ?[a-z]: The range from \xe1 to \xfa.
2418 // - ?[A-Z]: The range from \xc1 to \xda.
2419 // - ?[0-9]: The set of [,/\:. \n\t'-].
2420 // - ?$XX: A fallback which maps nibbles.
2421 if ((Byte >= 'a' && Byte <= 'z') || (Byte >= 'A' && Byte <= 'Z') ||
2422 (Byte >= '0' && Byte <= '9') || Byte == '_' || Byte == '$') {
2423 Mangler.getStream() << Byte;
David Majnemer0dc714a2014-03-30 06:34:26 +00002424 } else if ((Byte >= '\xe1' && Byte <= '\xfa') ||
2425 (Byte >= '\xc1' && Byte <= '\xda')) {
David Majnemer58e5bee2014-03-24 21:43:36 +00002426 Mangler.getStream() << '?' << static_cast<char>('A' + (Byte - '\xc1'));
2427 } else {
2428 switch (Byte) {
2429 case ',':
2430 Mangler.getStream() << "?0";
2431 break;
2432 case '/':
2433 Mangler.getStream() << "?1";
2434 break;
2435 case '\\':
2436 Mangler.getStream() << "?2";
2437 break;
2438 case ':':
2439 Mangler.getStream() << "?3";
2440 break;
2441 case '.':
2442 Mangler.getStream() << "?4";
2443 break;
2444 case ' ':
2445 Mangler.getStream() << "?5";
2446 break;
2447 case '\n':
2448 Mangler.getStream() << "?6";
2449 break;
2450 case '\t':
2451 Mangler.getStream() << "?7";
2452 break;
2453 case '\'':
2454 Mangler.getStream() << "?8";
2455 break;
2456 case '-':
2457 Mangler.getStream() << "?9";
2458 break;
2459 default:
2460 Mangler.getStream() << "?$";
2461 Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
2462 Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
2463 break;
2464 }
2465 }
2466 };
2467
2468 auto MangleChar = [&Mangler, &MangleByte, &SL](uint32_t CodeUnit) {
2469 if (SL->getCharByteWidth() == 1) {
2470 MangleByte(static_cast<char>(CodeUnit));
2471 } else if (SL->getCharByteWidth() == 2) {
2472 MangleByte(static_cast<char>((CodeUnit >> 16) & 0xff));
2473 MangleByte(static_cast<char>(CodeUnit & 0xff));
2474 } else {
2475 llvm_unreachable("unsupported CharByteWidth");
2476 }
2477 };
2478
2479 // Enforce our 32 character max.
2480 unsigned NumCharsToMangle = std::min(32U, SL->getLength());
2481 for (unsigned i = 0; i < NumCharsToMangle; ++i)
2482 MangleChar(SL->getCodeUnit(i));
2483
2484 // Encode the NUL terminator if there is room.
2485 if (NumCharsToMangle < 32)
2486 MangleChar(0);
2487
2488 Mangler.getStream() << '@';
2489}
2490
Timur Iskhodzhanov67455222013-10-03 06:26:13 +00002491MicrosoftMangleContext *
2492MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
2493 return new MicrosoftMangleContextImpl(Context, Diags);
Guy Benyei11169dd2012-12-18 14:30:41 +00002494}