1 //===--- 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"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/CharUnits.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/Expr.h"
24 #include "clang/AST/ExprCXX.h"
25 #include "clang/AST/VTableBuilder.h"
26 #include "clang/Basic/ABI.h"
27 #include "clang/Basic/DiagnosticOptions.h"
28 #include "clang/Basic/TargetInfo.h"
29 #include "llvm/ADT/StringExtras.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/Support/MathExtras.h"
32 
33 using namespace clang;
34 
35 namespace {
36 
37 /// \brief Retrieve the declaration context that should be used when mangling
38 /// the given declaration.
39 static 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 
67 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
68   return getEffectiveDeclContext(cast<Decl>(DC));
69 }
70 
71 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
72   if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
73     return ftd->getTemplatedDecl();
74 
75   return fn;
76 }
77 
78 static bool isLambda(const NamedDecl *ND) {
79   const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
80   if (!Record)
81     return false;
82 
83   return Record->isLambda();
84 }
85 
86 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
87 /// Microsoft Visual C++ ABI.
88 class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
89   typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
90   llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
91   llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
92   llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
93 
94 public:
95   MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags)
96       : MicrosoftMangleContext(Context, Diags) {}
97   bool shouldMangleCXXName(const NamedDecl *D) override;
98   bool shouldMangleStringLiteral(const StringLiteral *SL) override;
99   void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
100   void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
101                                 raw_ostream &) override;
102   void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
103                    raw_ostream &) override;
104   void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
105                           const ThisAdjustment &ThisAdjustment,
106                           raw_ostream &) override;
107   void mangleCXXVFTable(const CXXRecordDecl *Derived,
108                         ArrayRef<const CXXRecordDecl *> BasePath,
109                         raw_ostream &Out) override;
110   void mangleCXXVBTable(const CXXRecordDecl *Derived,
111                         ArrayRef<const CXXRecordDecl *> BasePath,
112                         raw_ostream &Out) override;
113   void mangleCXXRTTI(QualType T, raw_ostream &) override;
114   void mangleCXXRTTIName(QualType T, raw_ostream &) override;
115   void mangleTypeName(QualType T, raw_ostream &) override;
116   void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
117                      raw_ostream &) override;
118   void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
119                      raw_ostream &) override;
120   void mangleReferenceTemporary(const VarDecl *, raw_ostream &) override;
121   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
122   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
123   void mangleDynamicAtExitDestructor(const VarDecl *D,
124                                      raw_ostream &Out) override;
125   void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
126   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
127     // Lambda closure types are already numbered.
128     if (isLambda(ND))
129       return false;
130 
131     const DeclContext *DC = getEffectiveDeclContext(ND);
132     if (!DC->isFunctionOrMethod())
133       return false;
134 
135     // Use the canonical number for externally visible decls.
136     if (ND->isExternallyVisible()) {
137       disc = getASTContext().getManglingNumber(ND);
138       return true;
139     }
140 
141     // Anonymous tags are already numbered.
142     if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
143       if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
144         return false;
145     }
146 
147     // Make up a reasonable number for internal decls.
148     unsigned &discriminator = Uniquifier[ND];
149     if (!discriminator)
150       discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
151     disc = discriminator;
152     return true;
153   }
154 
155   unsigned getLambdaId(const CXXRecordDecl *RD) {
156     assert(RD->isLambda() && "RD must be a lambda!");
157     assert(!RD->isExternallyVisible() && "RD must not be visible!");
158     assert(RD->getLambdaManglingNumber() == 0 &&
159            "RD must not have a mangling number!");
160     std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
161         Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
162     return Result.first->second;
163   }
164 
165 private:
166   void mangleInitFiniStub(const VarDecl *D, raw_ostream &Out, char CharCode);
167 };
168 
169 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
170 /// Microsoft Visual C++ ABI.
171 class MicrosoftCXXNameMangler {
172   MicrosoftMangleContextImpl &Context;
173   raw_ostream &Out;
174 
175   /// The "structor" is the top-level declaration being mangled, if
176   /// that's not a template specialization; otherwise it's the pattern
177   /// for that specialization.
178   const NamedDecl *Structor;
179   unsigned StructorType;
180 
181   typedef llvm::StringMap<unsigned> BackRefMap;
182   BackRefMap NameBackReferences;
183   bool UseNameBackReferences;
184 
185   typedef llvm::DenseMap<void *, unsigned> ArgBackRefMap;
186   ArgBackRefMap TypeBackReferences;
187 
188   ASTContext &getASTContext() const { return Context.getASTContext(); }
189 
190   // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
191   // this check into mangleQualifiers().
192   const bool PointersAre64Bit;
193 
194 public:
195   enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
196 
197   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
198       : Context(C), Out(Out_), 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_), Structor(getStructor(D)), StructorType(Type),
206         UseNameBackReferences(true),
207         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
208                          64) {}
209 
210   raw_ostream &getStream() const { return Out; }
211 
212   void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
213   void mangleName(const NamedDecl *ND);
214   void mangleFunctionEncoding(const FunctionDecl *FD);
215   void mangleVariableEncoding(const VarDecl *VD);
216   void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
217   void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
218                                    const CXXMethodDecl *MD);
219   void mangleVirtualMemPtrThunk(
220       const CXXMethodDecl *MD,
221       const MicrosoftVTableContext::MethodVFTableLocation &ML);
222   void mangleNumber(int64_t Number);
223   void mangleType(QualType T, SourceRange Range,
224                   QualifierMangleMode QMM = QMM_Mangle);
225   void mangleFunctionType(const FunctionType *T, const FunctionDecl *D = 0,
226                           bool ForceInstMethod = false);
227   void mangleNestedName(const NamedDecl *ND);
228 
229 private:
230   void disableBackReferences() { UseNameBackReferences = false; }
231   void mangleUnqualifiedName(const NamedDecl *ND) {
232     mangleUnqualifiedName(ND, ND->getDeclName());
233   }
234   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
235   void mangleSourceName(StringRef Name);
236   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
237   void mangleCXXDtorType(CXXDtorType T);
238   void mangleQualifiers(Qualifiers Quals, bool IsMember);
239   void mangleRefQualifier(RefQualifierKind RefQualifier);
240   void manglePointerCVQualifiers(Qualifiers Quals);
241   void manglePointerExtQualifiers(Qualifiers Quals, const Type *PointeeType);
242 
243   void mangleUnscopedTemplateName(const TemplateDecl *ND);
244   void
245   mangleTemplateInstantiationName(const TemplateDecl *TD,
246                                   const TemplateArgumentList &TemplateArgs);
247   void mangleObjCMethodName(const ObjCMethodDecl *MD);
248 
249   void mangleArgumentType(QualType T, SourceRange Range);
250 
251   // Declare manglers for every type class.
252 #define ABSTRACT_TYPE(CLASS, PARENT)
253 #define NON_CANONICAL_TYPE(CLASS, PARENT)
254 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
255                                             SourceRange Range);
256 #include "clang/AST/TypeNodes.def"
257 #undef ABSTRACT_TYPE
258 #undef NON_CANONICAL_TYPE
259 #undef TYPE
260 
261   void mangleType(const TagDecl *TD);
262   void mangleDecayedArrayType(const ArrayType *T);
263   void mangleArrayType(const ArrayType *T);
264   void mangleFunctionClass(const FunctionDecl *FD);
265   void mangleCallingConvention(const FunctionType *T);
266   void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
267   void mangleExpression(const Expr *E);
268   void mangleThrowSpecification(const FunctionProtoType *T);
269 
270   void mangleTemplateArgs(const TemplateDecl *TD,
271                           const TemplateArgumentList &TemplateArgs);
272   void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA);
273 };
274 }
275 
276 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
277   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
278     LanguageLinkage L = FD->getLanguageLinkage();
279     // Overloadable functions need mangling.
280     if (FD->hasAttr<OverloadableAttr>())
281       return true;
282 
283     // The ABI expects that we would never mangle "typical" user-defined entry
284     // points regardless of visibility or freestanding-ness.
285     //
286     // N.B. This is distinct from asking about "main".  "main" has a lot of
287     // special rules associated with it in the standard while these
288     // user-defined entry points are outside of the purview of the standard.
289     // For example, there can be only one definition for "main" in a standards
290     // compliant program; however nothing forbids the existence of wmain and
291     // WinMain in the same translation unit.
292     if (FD->isMSVCRTEntryPoint())
293       return false;
294 
295     // C++ functions and those whose names are not a simple identifier need
296     // mangling.
297     if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
298       return true;
299 
300     // C functions are not mangled.
301     if (L == CLanguageLinkage)
302       return false;
303   }
304 
305   // Otherwise, no mangling is done outside C++ mode.
306   if (!getASTContext().getLangOpts().CPlusPlus)
307     return false;
308 
309   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
310     // C variables are not mangled.
311     if (VD->isExternC())
312       return false;
313 
314     // Variables at global scope with non-internal linkage are not mangled.
315     const DeclContext *DC = getEffectiveDeclContext(D);
316     // Check for extern variable declared locally.
317     if (DC->isFunctionOrMethod() && D->hasLinkage())
318       while (!DC->isNamespace() && !DC->isTranslationUnit())
319         DC = getEffectiveParentContext(DC);
320 
321     if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
322         !isa<VarTemplateSpecializationDecl>(D))
323       return false;
324   }
325 
326   return true;
327 }
328 
329 bool
330 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
331   return SL->isAscii() || SL->isWide();
332   // TODO: This needs to be updated when MSVC gains support for Unicode
333   // literals.
334 }
335 
336 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, 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 
343   // <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(
355         DiagnosticsEngine::Error, "cannot mangle this declaration yet");
356     Diags.Report(D->getLocation(), DiagID) << D->getSourceRange();
357   }
358 }
359 
360 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
361   // <type-encoding> ::= <function-class> <function-type>
362 
363   // Since MSVC operates on the type as written and not the canonical type, it
364   // actually matters which decl we have here.  MSVC appears to choose the
365   // first, since it is most likely to be the declaration in a header file.
366   FD = FD->getFirstDecl();
367 
368   // We should never ever see a FunctionNoProtoType at this point.
369   // We don't even know how to mangle their types anyway :).
370   const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
371 
372   // extern "C" functions can hold entities that must be mangled.
373   // As it stands, these functions still need to get expressed in the full
374   // external name.  They have their class and type omitted, replaced with '9'.
375   if (Context.shouldMangleDeclName(FD)) {
376     // First, the function class.
377     mangleFunctionClass(FD);
378 
379     mangleFunctionType(FT, FD);
380   } else
381     Out << '9';
382 }
383 
384 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
385   // <type-encoding> ::= <storage-class> <variable-type>
386   // <storage-class> ::= 0  # private static member
387   //                 ::= 1  # protected static member
388   //                 ::= 2  # public static member
389   //                 ::= 3  # global
390   //                 ::= 4  # static local
391 
392   // The first character in the encoding (after the name) is the storage class.
393   if (VD->isStaticDataMember()) {
394     // If it's a static member, it also encodes the access level.
395     switch (VD->getAccess()) {
396       default:
397       case AS_private: Out << '0'; break;
398       case AS_protected: Out << '1'; break;
399       case AS_public: Out << '2'; break;
400     }
401   }
402   else if (!VD->isStaticLocal())
403     Out << '3';
404   else
405     Out << '4';
406   // Now mangle the type.
407   // <variable-type> ::= <type> <cvr-qualifiers>
408   //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
409   // Pointers and references are odd. The type of 'int * const foo;' gets
410   // mangled as 'QAHA' instead of 'PAHB', for example.
411   TypeLoc TL = VD->getTypeSourceInfo()->getTypeLoc();
412   QualType Ty = VD->getType();
413   if (Ty->isPointerType() || Ty->isReferenceType() ||
414       Ty->isMemberPointerType()) {
415     mangleType(Ty, TL.getSourceRange(), QMM_Drop);
416     manglePointerExtQualifiers(
417         Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), 0);
418     if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
419       mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
420       // Member pointers are suffixed with a back reference to the member
421       // pointer's class name.
422       mangleName(MPT->getClass()->getAsCXXRecordDecl());
423     } else
424       mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
425   } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
426     // Global arrays are funny, too.
427     mangleDecayedArrayType(AT);
428     if (AT->getElementType()->isArrayType())
429       Out << 'A';
430     else
431       mangleQualifiers(Ty.getQualifiers(), false);
432   } else {
433     mangleType(Ty, TL.getSourceRange(), QMM_Drop);
434     mangleQualifiers(Ty.getLocalQualifiers(), false);
435   }
436 }
437 
438 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
439                                                       const ValueDecl *VD) {
440   // <member-data-pointer> ::= <integer-literal>
441   //                       ::= $F <number> <number>
442   //                       ::= $G <number> <number> <number>
443 
444   int64_t FieldOffset;
445   int64_t VBTableOffset;
446   MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
447   if (VD) {
448     FieldOffset = getASTContext().getFieldOffset(VD);
449     assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
450            "cannot take address of bitfield");
451     FieldOffset /= getASTContext().getCharWidth();
452 
453     VBTableOffset = 0;
454   } else {
455     FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
456 
457     VBTableOffset = -1;
458   }
459 
460   char Code = '\0';
461   switch (IM) {
462   case MSInheritanceAttr::Keyword_single_inheritance:      Code = '0'; break;
463   case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = '0'; break;
464   case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'F'; break;
465   case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
466   }
467 
468   Out << '$' << Code;
469 
470   mangleNumber(FieldOffset);
471 
472   // The C++ standard doesn't allow base-to-derived member pointer conversions
473   // in template parameter contexts, so the vbptr offset of data member pointers
474   // is always zero.
475   if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
476     mangleNumber(0);
477   if (MSInheritanceAttr::hasVBTableOffsetField(IM))
478     mangleNumber(VBTableOffset);
479 }
480 
481 void
482 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
483                                                      const CXXMethodDecl *MD) {
484   // <member-function-pointer> ::= $1? <name>
485   //                           ::= $H? <name> <number>
486   //                           ::= $I? <name> <number> <number>
487   //                           ::= $J? <name> <number> <number> <number>
488   //                           ::= $0A@
489 
490   MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
491 
492   // The null member function pointer is $0A@ in function templates and crashes
493   // MSVC when used in class templates, so we don't know what they really look
494   // like.
495   if (!MD) {
496     Out << "$0A@";
497     return;
498   }
499 
500   char Code = '\0';
501   switch (IM) {
502   case MSInheritanceAttr::Keyword_single_inheritance:      Code = '1'; break;
503   case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = 'H'; break;
504   case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'I'; break;
505   case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
506   }
507 
508   Out << '$' << Code << '?';
509 
510   // If non-virtual, mangle the name.  If virtual, mangle as a virtual memptr
511   // thunk.
512   uint64_t NVOffset = 0;
513   uint64_t VBTableOffset = 0;
514   uint64_t VBPtrOffset = 0;
515   if (MD->isVirtual()) {
516     MicrosoftVTableContext *VTContext =
517         cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
518     const MicrosoftVTableContext::MethodVFTableLocation &ML =
519         VTContext->getMethodVFTableLocation(GlobalDecl(MD));
520     mangleVirtualMemPtrThunk(MD, ML);
521     NVOffset = ML.VFPtrOffset.getQuantity();
522     VBTableOffset = ML.VBTableIndex * 4;
523     if (ML.VBase) {
524       const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
525       VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
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(VBPtrOffset);
536   if (MSInheritanceAttr::hasVBTableOffsetField(IM))
537     mangleNumber(VBTableOffset);
538 }
539 
540 void 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 
556 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
557   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
558 
559   // Always start with the unqualified name.
560   mangleUnqualifiedName(ND);
561 
562   mangleNestedName(ND);
563 
564   // Terminate the whole name with an '@'.
565   Out << '@';
566 }
567 
568 void 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>
574 
575   uint64_t Value = static_cast<uint64_t>(Number);
576   if (Number < 0) {
577     Value = -Value;
578     Out << '?';
579   }
580 
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());
595     Out << '@';
596   }
597 }
598 
599 static const TemplateDecl *
600 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
601   // Check if we have a function template.
602   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
603     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
604       TemplateArgs = FD->getTemplateSpecializationArgs();
605       return TD;
606     }
607   }
608 
609   // Check if we have a class template.
610   if (const ClassTemplateSpecializationDecl *Spec =
611           dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
612     TemplateArgs = &Spec->getTemplateArgs();
613     return Spec->getSpecializedTemplate();
614   }
615 
616   // 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 
623   return 0;
624 }
625 
626 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
627                                                     DeclarationName Name) {
628   //  <unqualified-name> ::= <operator-name>
629   //                     ::= <ctor-dtor-name>
630   //                     ::= <source-name>
631   //                     ::= <template-name>
632 
633   // Check if we have a template.
634   const TemplateArgumentList *TemplateArgs = 0;
635   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
636     // Function templates aren't considered for name back referencing.  This
637     // makes sense since function templates aren't likely to occur multiple
638     // times in a symbol.
639     // FIXME: Test alias template mangling with MSVC 2013.
640     if (!isa<ClassTemplateDecl>(TD)) {
641       mangleTemplateInstantiationName(TD, *TemplateArgs);
642       return;
643     }
644 
645     // Here comes the tricky thing: if we need to mangle something like
646     //   void foo(A::X<Y>, B::X<Y>),
647     // the X<Y> part is aliased. However, if you need to mangle
648     //   void foo(A::X<A::Y>, A::X<B::Y>),
649     // the A::X<> part is not aliased.
650     // That said, from the mangler's perspective we have a structure like this:
651     //   namespace[s] -> type[ -> template-parameters]
652     // but from the Clang perspective we have
653     //   type [ -> template-parameters]
654     //      \-> namespace[s]
655     // What we do is we create a new mangler, mangle the same type (without
656     // a namespace suffix) using the extra mangler with back references
657     // disabled (to avoid infinite recursion) and then use the mangled type
658     // name as a key to check the mangling of different types for aliasing.
659 
660     std::string BackReferenceKey;
661     BackRefMap::iterator Found;
662     if (UseNameBackReferences) {
663       llvm::raw_string_ostream Stream(BackReferenceKey);
664       MicrosoftCXXNameMangler Extra(Context, Stream);
665       Extra.disableBackReferences();
666       Extra.mangleUnqualifiedName(ND, Name);
667       Stream.flush();
668 
669       Found = NameBackReferences.find(BackReferenceKey);
670     }
671     if (!UseNameBackReferences || Found == NameBackReferences.end()) {
672       mangleTemplateInstantiationName(TD, *TemplateArgs);
673       if (UseNameBackReferences && NameBackReferences.size() < 10) {
674         size_t Size = NameBackReferences.size();
675         NameBackReferences[BackReferenceKey] = Size;
676       }
677     } else {
678       Out << Found->second;
679     }
680     return;
681   }
682 
683   switch (Name.getNameKind()) {
684     case DeclarationName::Identifier: {
685       if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
686         mangleSourceName(II->getName());
687         break;
688       }
689 
690       // Otherwise, an anonymous entity.  We must have a declaration.
691       assert(ND && "mangling empty name without declaration");
692 
693       if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
694         if (NS->isAnonymousNamespace()) {
695           Out << "?A@";
696           break;
697         }
698       }
699 
700       if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
701         // We must have an anonymous union or struct declaration.
702         const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
703         assert(RD && "expected variable decl to have a record type");
704         // Anonymous types with no tag or typedef get the name of their
705         // declarator mangled in.  If they have no declarator, number them with
706         // a $S prefix.
707         llvm::SmallString<64> Name("$S");
708         // Get a unique id for the anonymous struct.
709         Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
710         mangleSourceName(Name.str());
711         break;
712       }
713 
714       // We must have an anonymous struct.
715       const TagDecl *TD = cast<TagDecl>(ND);
716       if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
717         assert(TD->getDeclContext() == D->getDeclContext() &&
718                "Typedef should not be in another decl context!");
719         assert(D->getDeclName().getAsIdentifierInfo() &&
720                "Typedef was not named!");
721         mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
722         break;
723       }
724 
725       if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
726         if (Record->isLambda()) {
727           llvm::SmallString<10> Name("<lambda_");
728           unsigned LambdaId;
729           if (Record->getLambdaManglingNumber())
730             LambdaId = Record->getLambdaManglingNumber();
731           else
732             LambdaId = Context.getLambdaId(Record);
733 
734           Name += llvm::utostr(LambdaId);
735           Name += ">";
736 
737           mangleSourceName(Name);
738           break;
739         }
740       }
741 
742       llvm::SmallString<64> Name("<unnamed-type-");
743       if (TD->hasDeclaratorForAnonDecl()) {
744         // Anonymous types with no tag or typedef get the name of their
745         // declarator mangled in if they have one.
746         Name += TD->getDeclaratorForAnonDecl()->getName();
747       } else {
748         // Otherwise, number the types using a $S prefix.
749         Name += "$S";
750         Name += llvm::utostr(Context.getAnonymousStructId(TD));
751       }
752       Name += ">";
753       mangleSourceName(Name.str());
754       break;
755     }
756 
757     case DeclarationName::ObjCZeroArgSelector:
758     case DeclarationName::ObjCOneArgSelector:
759     case DeclarationName::ObjCMultiArgSelector:
760       llvm_unreachable("Can't mangle Objective-C selector names here!");
761 
762     case DeclarationName::CXXConstructorName:
763       if (ND == Structor) {
764         assert(StructorType == Ctor_Complete &&
765                "Should never be asked to mangle a ctor other than complete");
766       }
767       Out << "?0";
768       break;
769 
770     case DeclarationName::CXXDestructorName:
771       if (ND == Structor)
772         // If the named decl is the C++ destructor we're mangling,
773         // use the type we were given.
774         mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
775       else
776         // Otherwise, use the base destructor name. This is relevant if a
777         // class with a destructor is declared within a destructor.
778         mangleCXXDtorType(Dtor_Base);
779       break;
780 
781     case DeclarationName::CXXConversionFunctionName:
782       // <operator-name> ::= ?B # (cast)
783       // The target type is encoded as the return type.
784       Out << "?B";
785       break;
786 
787     case DeclarationName::CXXOperatorName:
788       mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
789       break;
790 
791     case DeclarationName::CXXLiteralOperatorName: {
792       // FIXME: Was this added in VS2010? Does MS even know how to mangle this?
793       DiagnosticsEngine Diags = Context.getDiags();
794       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
795         "cannot mangle this literal operator yet");
796       Diags.Report(ND->getLocation(), DiagID);
797       break;
798     }
799 
800     case DeclarationName::CXXUsingDirective:
801       llvm_unreachable("Can't mangle a using directive name!");
802   }
803 }
804 
805 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
806   // <postfix> ::= <unqualified-name> [<postfix>]
807   //           ::= <substitution> [<postfix>]
808   if (isLambda(ND))
809     return;
810 
811   const DeclContext *DC = ND->getDeclContext();
812 
813   while (!DC->isTranslationUnit()) {
814     if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
815       unsigned Disc;
816       if (Context.getNextDiscriminator(ND, Disc)) {
817         Out << '?';
818         mangleNumber(Disc);
819         Out << '?';
820       }
821     }
822 
823     if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
824       DiagnosticsEngine Diags = Context.getDiags();
825       unsigned DiagID =
826           Diags.getCustomDiagID(DiagnosticsEngine::Error,
827                                 "cannot mangle a local inside this block yet");
828       Diags.Report(BD->getLocation(), DiagID);
829 
830       // FIXME: This is completely, utterly, wrong; see ItaniumMangle
831       // for how this should be done.
832       Out << "__block_invoke" << Context.getBlockId(BD, false);
833       Out << '@';
834       continue;
835     } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
836       mangleObjCMethodName(Method);
837     } else if (isa<NamedDecl>(DC)) {
838       ND = cast<NamedDecl>(DC);
839       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
840         mangle(FD, "?");
841         break;
842       } else
843         mangleUnqualifiedName(ND);
844     }
845     DC = DC->getParent();
846   }
847 }
848 
849 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
850   // Microsoft uses the names on the case labels for these dtor variants.  Clang
851   // uses the Itanium terminology internally.  Everything in this ABI delegates
852   // towards the base dtor.
853   switch (T) {
854   // <operator-name> ::= ?1  # destructor
855   case Dtor_Base: Out << "?1"; return;
856   // <operator-name> ::= ?_D # vbase destructor
857   case Dtor_Complete: Out << "?_D"; return;
858   // <operator-name> ::= ?_G # scalar deleting destructor
859   case Dtor_Deleting: Out << "?_G"; return;
860   // <operator-name> ::= ?_E # vector deleting destructor
861   // FIXME: Add a vector deleting dtor type.  It goes in the vtable, so we need
862   // it.
863   }
864   llvm_unreachable("Unsupported dtor type?");
865 }
866 
867 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
868                                                  SourceLocation Loc) {
869   switch (OO) {
870   //                     ?0 # constructor
871   //                     ?1 # destructor
872   // <operator-name> ::= ?2 # new
873   case OO_New: Out << "?2"; break;
874   // <operator-name> ::= ?3 # delete
875   case OO_Delete: Out << "?3"; break;
876   // <operator-name> ::= ?4 # =
877   case OO_Equal: Out << "?4"; break;
878   // <operator-name> ::= ?5 # >>
879   case OO_GreaterGreater: Out << "?5"; break;
880   // <operator-name> ::= ?6 # <<
881   case OO_LessLess: Out << "?6"; break;
882   // <operator-name> ::= ?7 # !
883   case OO_Exclaim: Out << "?7"; break;
884   // <operator-name> ::= ?8 # ==
885   case OO_EqualEqual: Out << "?8"; break;
886   // <operator-name> ::= ?9 # !=
887   case OO_ExclaimEqual: Out << "?9"; break;
888   // <operator-name> ::= ?A # []
889   case OO_Subscript: Out << "?A"; break;
890   //                     ?B # conversion
891   // <operator-name> ::= ?C # ->
892   case OO_Arrow: Out << "?C"; break;
893   // <operator-name> ::= ?D # *
894   case OO_Star: Out << "?D"; break;
895   // <operator-name> ::= ?E # ++
896   case OO_PlusPlus: Out << "?E"; break;
897   // <operator-name> ::= ?F # --
898   case OO_MinusMinus: Out << "?F"; break;
899   // <operator-name> ::= ?G # -
900   case OO_Minus: Out << "?G"; break;
901   // <operator-name> ::= ?H # +
902   case OO_Plus: Out << "?H"; break;
903   // <operator-name> ::= ?I # &
904   case OO_Amp: Out << "?I"; break;
905   // <operator-name> ::= ?J # ->*
906   case OO_ArrowStar: Out << "?J"; break;
907   // <operator-name> ::= ?K # /
908   case OO_Slash: Out << "?K"; break;
909   // <operator-name> ::= ?L # %
910   case OO_Percent: Out << "?L"; break;
911   // <operator-name> ::= ?M # <
912   case OO_Less: Out << "?M"; break;
913   // <operator-name> ::= ?N # <=
914   case OO_LessEqual: Out << "?N"; break;
915   // <operator-name> ::= ?O # >
916   case OO_Greater: Out << "?O"; break;
917   // <operator-name> ::= ?P # >=
918   case OO_GreaterEqual: Out << "?P"; break;
919   // <operator-name> ::= ?Q # ,
920   case OO_Comma: Out << "?Q"; break;
921   // <operator-name> ::= ?R # ()
922   case OO_Call: Out << "?R"; break;
923   // <operator-name> ::= ?S # ~
924   case OO_Tilde: Out << "?S"; break;
925   // <operator-name> ::= ?T # ^
926   case OO_Caret: Out << "?T"; break;
927   // <operator-name> ::= ?U # |
928   case OO_Pipe: Out << "?U"; break;
929   // <operator-name> ::= ?V # &&
930   case OO_AmpAmp: Out << "?V"; break;
931   // <operator-name> ::= ?W # ||
932   case OO_PipePipe: Out << "?W"; break;
933   // <operator-name> ::= ?X # *=
934   case OO_StarEqual: Out << "?X"; break;
935   // <operator-name> ::= ?Y # +=
936   case OO_PlusEqual: Out << "?Y"; break;
937   // <operator-name> ::= ?Z # -=
938   case OO_MinusEqual: Out << "?Z"; break;
939   // <operator-name> ::= ?_0 # /=
940   case OO_SlashEqual: Out << "?_0"; break;
941   // <operator-name> ::= ?_1 # %=
942   case OO_PercentEqual: Out << "?_1"; break;
943   // <operator-name> ::= ?_2 # >>=
944   case OO_GreaterGreaterEqual: Out << "?_2"; break;
945   // <operator-name> ::= ?_3 # <<=
946   case OO_LessLessEqual: Out << "?_3"; break;
947   // <operator-name> ::= ?_4 # &=
948   case OO_AmpEqual: Out << "?_4"; break;
949   // <operator-name> ::= ?_5 # |=
950   case OO_PipeEqual: Out << "?_5"; break;
951   // <operator-name> ::= ?_6 # ^=
952   case OO_CaretEqual: Out << "?_6"; break;
953   //                     ?_7 # vftable
954   //                     ?_8 # vbtable
955   //                     ?_9 # vcall
956   //                     ?_A # typeof
957   //                     ?_B # local static guard
958   //                     ?_C # string
959   //                     ?_D # vbase destructor
960   //                     ?_E # vector deleting destructor
961   //                     ?_F # default constructor closure
962   //                     ?_G # scalar deleting destructor
963   //                     ?_H # vector constructor iterator
964   //                     ?_I # vector destructor iterator
965   //                     ?_J # vector vbase constructor iterator
966   //                     ?_K # virtual displacement map
967   //                     ?_L # eh vector constructor iterator
968   //                     ?_M # eh vector destructor iterator
969   //                     ?_N # eh vector vbase constructor iterator
970   //                     ?_O # copy constructor closure
971   //                     ?_P<name> # udt returning <name>
972   //                     ?_Q # <unknown>
973   //                     ?_R0 # RTTI Type Descriptor
974   //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
975   //                     ?_R2 # RTTI Base Class Array
976   //                     ?_R3 # RTTI Class Hierarchy Descriptor
977   //                     ?_R4 # RTTI Complete Object Locator
978   //                     ?_S # local vftable
979   //                     ?_T # local vftable constructor closure
980   // <operator-name> ::= ?_U # new[]
981   case OO_Array_New: Out << "?_U"; break;
982   // <operator-name> ::= ?_V # delete[]
983   case OO_Array_Delete: Out << "?_V"; break;
984 
985   case OO_Conditional: {
986     DiagnosticsEngine &Diags = Context.getDiags();
987     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
988       "cannot mangle this conditional operator yet");
989     Diags.Report(Loc, DiagID);
990     break;
991   }
992 
993   case OO_None:
994   case NUM_OVERLOADED_OPERATORS:
995     llvm_unreachable("Not an overloaded operator");
996   }
997 }
998 
999 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1000   // <source name> ::= <identifier> @
1001   BackRefMap::iterator Found;
1002   if (UseNameBackReferences)
1003     Found = NameBackReferences.find(Name);
1004   if (!UseNameBackReferences || Found == NameBackReferences.end()) {
1005     Out << Name << '@';
1006     if (UseNameBackReferences && NameBackReferences.size() < 10) {
1007       size_t Size = NameBackReferences.size();
1008       NameBackReferences[Name] = Size;
1009     }
1010   } else {
1011     Out << Found->second;
1012   }
1013 }
1014 
1015 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1016   Context.mangleObjCMethodName(MD, Out);
1017 }
1018 
1019 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1020     const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1021   // <template-name> ::= <unscoped-template-name> <template-args>
1022   //                 ::= <substitution>
1023   // Always start with the unqualified name.
1024 
1025   // Templates have their own context for back references.
1026   ArgBackRefMap OuterArgsContext;
1027   BackRefMap OuterTemplateContext;
1028   NameBackReferences.swap(OuterTemplateContext);
1029   TypeBackReferences.swap(OuterArgsContext);
1030 
1031   mangleUnscopedTemplateName(TD);
1032   mangleTemplateArgs(TD, TemplateArgs);
1033 
1034   // Restore the previous back reference contexts.
1035   NameBackReferences.swap(OuterTemplateContext);
1036   TypeBackReferences.swap(OuterArgsContext);
1037 }
1038 
1039 void
1040 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1041   // <unscoped-template-name> ::= ?$ <unqualified-name>
1042   Out << "?$";
1043   mangleUnqualifiedName(TD);
1044 }
1045 
1046 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1047                                                    bool IsBoolean) {
1048   // <integer-literal> ::= $0 <number>
1049   Out << "$0";
1050   // Make sure booleans are encoded as 0/1.
1051   if (IsBoolean && Value.getBoolValue())
1052     mangleNumber(1);
1053   else
1054     mangleNumber(Value.getSExtValue());
1055 }
1056 
1057 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1058   // See if this is a constant expression.
1059   llvm::APSInt Value;
1060   if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1061     mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1062     return;
1063   }
1064 
1065   const CXXUuidofExpr *UE = 0;
1066   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1067     if (UO->getOpcode() == UO_AddrOf)
1068       UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1069   } else
1070     UE = dyn_cast<CXXUuidofExpr>(E);
1071 
1072   if (UE) {
1073     // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1074     // const __s_GUID _GUID_{lower case UUID with underscores}
1075     StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
1076     std::string Name = "_GUID_" + Uuid.lower();
1077     std::replace(Name.begin(), Name.end(), '-', '_');
1078 
1079     // If we had to peek through an address-of operator, treat this like we are
1080     // dealing with a pointer type.  Otherwise, treat it like a const reference.
1081     //
1082     // N.B. This matches up with the handling of TemplateArgument::Declaration
1083     // in mangleTemplateArg
1084     if (UE == E)
1085       Out << "$E?";
1086     else
1087       Out << "$1?";
1088     Out << Name << "@@3U__s_GUID@@B";
1089     return;
1090   }
1091 
1092   // As bad as this diagnostic is, it's better than crashing.
1093   DiagnosticsEngine &Diags = Context.getDiags();
1094   unsigned DiagID = Diags.getCustomDiagID(
1095       DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1096   Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1097                                         << E->getSourceRange();
1098 }
1099 
1100 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1101     const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1102   // <template-args> ::= <template-arg>+ @
1103   for (const TemplateArgument &TA : TemplateArgs.asArray())
1104     mangleTemplateArg(TD, TA);
1105   Out << '@';
1106 }
1107 
1108 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1109                                                 const TemplateArgument &TA) {
1110   // <template-arg> ::= <type>
1111   //                ::= <integer-literal>
1112   //                ::= <member-data-pointer>
1113   //                ::= <member-function-pointer>
1114   //                ::= $E? <name> <type-encoding>
1115   //                ::= $1? <name> <type-encoding>
1116   //                ::= $0A@
1117   //                ::= <template-args>
1118 
1119   switch (TA.getKind()) {
1120   case TemplateArgument::Null:
1121     llvm_unreachable("Can't mangle null template arguments!");
1122   case TemplateArgument::TemplateExpansion:
1123     llvm_unreachable("Can't mangle template expansion arguments!");
1124   case TemplateArgument::Type: {
1125     QualType T = TA.getAsType();
1126     mangleType(T, SourceRange(), QMM_Escape);
1127     break;
1128   }
1129   case TemplateArgument::Declaration: {
1130     const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
1131     if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1132       mangleMemberDataPointer(
1133           cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
1134           cast<ValueDecl>(ND));
1135     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1136       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1137       if (MD && MD->isInstance())
1138         mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
1139       else
1140         mangle(FD, "$1?");
1141     } else {
1142       mangle(ND, TA.isDeclForReferenceParam() ? "$E?" : "$1?");
1143     }
1144     break;
1145   }
1146   case TemplateArgument::Integral:
1147     mangleIntegerLiteral(TA.getAsIntegral(),
1148                          TA.getIntegralType()->isBooleanType());
1149     break;
1150   case TemplateArgument::NullPtr: {
1151     QualType T = TA.getNullPtrType();
1152     if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1153       const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1154       if (MPT->isMemberFunctionPointerType())
1155         mangleMemberFunctionPointer(RD, 0);
1156       else
1157         mangleMemberDataPointer(RD, 0);
1158     } else {
1159       Out << "$0A@";
1160     }
1161     break;
1162   }
1163   case TemplateArgument::Expression:
1164     mangleExpression(TA.getAsExpr());
1165     break;
1166   case TemplateArgument::Pack:
1167     // Unlike Itanium, there is no character code to indicate an argument pack.
1168     for (const TemplateArgument &PA : TA.getPackAsArray())
1169       mangleTemplateArg(TD, PA);
1170     break;
1171   case TemplateArgument::Template:
1172     mangleType(cast<TagDecl>(
1173         TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl()));
1174     break;
1175   }
1176 }
1177 
1178 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1179                                                bool IsMember) {
1180   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1181   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1182   // 'I' means __restrict (32/64-bit).
1183   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1184   // keyword!
1185   // <base-cvr-qualifiers> ::= A  # near
1186   //                       ::= B  # near const
1187   //                       ::= C  # near volatile
1188   //                       ::= D  # near const volatile
1189   //                       ::= E  # far (16-bit)
1190   //                       ::= F  # far const (16-bit)
1191   //                       ::= G  # far volatile (16-bit)
1192   //                       ::= H  # far const volatile (16-bit)
1193   //                       ::= I  # huge (16-bit)
1194   //                       ::= J  # huge const (16-bit)
1195   //                       ::= K  # huge volatile (16-bit)
1196   //                       ::= L  # huge const volatile (16-bit)
1197   //                       ::= M <basis> # based
1198   //                       ::= N <basis> # based const
1199   //                       ::= O <basis> # based volatile
1200   //                       ::= P <basis> # based const volatile
1201   //                       ::= Q  # near member
1202   //                       ::= R  # near const member
1203   //                       ::= S  # near volatile member
1204   //                       ::= T  # near const volatile member
1205   //                       ::= U  # far member (16-bit)
1206   //                       ::= V  # far const member (16-bit)
1207   //                       ::= W  # far volatile member (16-bit)
1208   //                       ::= X  # far const volatile member (16-bit)
1209   //                       ::= Y  # huge member (16-bit)
1210   //                       ::= Z  # huge const member (16-bit)
1211   //                       ::= 0  # huge volatile member (16-bit)
1212   //                       ::= 1  # huge const volatile member (16-bit)
1213   //                       ::= 2 <basis> # based member
1214   //                       ::= 3 <basis> # based const member
1215   //                       ::= 4 <basis> # based volatile member
1216   //                       ::= 5 <basis> # based const volatile member
1217   //                       ::= 6  # near function (pointers only)
1218   //                       ::= 7  # far function (pointers only)
1219   //                       ::= 8  # near method (pointers only)
1220   //                       ::= 9  # far method (pointers only)
1221   //                       ::= _A <basis> # based function (pointers only)
1222   //                       ::= _B <basis> # based function (far?) (pointers only)
1223   //                       ::= _C <basis> # based method (pointers only)
1224   //                       ::= _D <basis> # based method (far?) (pointers only)
1225   //                       ::= _E # block (Clang)
1226   // <basis> ::= 0 # __based(void)
1227   //         ::= 1 # __based(segment)?
1228   //         ::= 2 <name> # __based(name)
1229   //         ::= 3 # ?
1230   //         ::= 4 # ?
1231   //         ::= 5 # not really based
1232   bool HasConst = Quals.hasConst(),
1233        HasVolatile = Quals.hasVolatile();
1234 
1235   if (!IsMember) {
1236     if (HasConst && HasVolatile) {
1237       Out << 'D';
1238     } else if (HasVolatile) {
1239       Out << 'C';
1240     } else if (HasConst) {
1241       Out << 'B';
1242     } else {
1243       Out << 'A';
1244     }
1245   } else {
1246     if (HasConst && HasVolatile) {
1247       Out << 'T';
1248     } else if (HasVolatile) {
1249       Out << 'S';
1250     } else if (HasConst) {
1251       Out << 'R';
1252     } else {
1253       Out << 'Q';
1254     }
1255   }
1256 
1257   // FIXME: For now, just drop all extension qualifiers on the floor.
1258 }
1259 
1260 void
1261 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1262   // <ref-qualifier> ::= G                # lvalue reference
1263   //                 ::= H                # rvalue-reference
1264   switch (RefQualifier) {
1265   case RQ_None:
1266     break;
1267 
1268   case RQ_LValue:
1269     Out << 'G';
1270     break;
1271 
1272   case RQ_RValue:
1273     Out << 'H';
1274     break;
1275   }
1276 }
1277 
1278 void
1279 MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1280                                                     const Type *PointeeType) {
1281   bool HasRestrict = Quals.hasRestrict();
1282   if (PointersAre64Bit && (!PointeeType || !PointeeType->isFunctionType()))
1283     Out << 'E';
1284 
1285   if (HasRestrict)
1286     Out << 'I';
1287 }
1288 
1289 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1290   // <pointer-cv-qualifiers> ::= P  # no qualifiers
1291   //                         ::= Q  # const
1292   //                         ::= R  # volatile
1293   //                         ::= S  # const volatile
1294   bool HasConst = Quals.hasConst(),
1295        HasVolatile = Quals.hasVolatile();
1296 
1297   if (HasConst && HasVolatile) {
1298     Out << 'S';
1299   } else if (HasVolatile) {
1300     Out << 'R';
1301   } else if (HasConst) {
1302     Out << 'Q';
1303   } else {
1304     Out << 'P';
1305   }
1306 }
1307 
1308 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1309                                                  SourceRange Range) {
1310   // MSVC will backreference two canonically equivalent types that have slightly
1311   // different manglings when mangled alone.
1312 
1313   // Decayed types do not match up with non-decayed versions of the same type.
1314   //
1315   // e.g.
1316   // void (*x)(void) will not form a backreference with void x(void)
1317   void *TypePtr;
1318   if (const DecayedType *DT = T->getAs<DecayedType>()) {
1319     TypePtr = DT->getOriginalType().getCanonicalType().getAsOpaquePtr();
1320     // If the original parameter was textually written as an array,
1321     // instead treat the decayed parameter like it's const.
1322     //
1323     // e.g.
1324     // int [] -> int * const
1325     if (DT->getOriginalType()->isArrayType())
1326       T = T.withConst();
1327   } else
1328     TypePtr = T.getCanonicalType().getAsOpaquePtr();
1329 
1330   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1331 
1332   if (Found == TypeBackReferences.end()) {
1333     size_t OutSizeBefore = Out.GetNumBytesInBuffer();
1334 
1335     mangleType(T, Range, QMM_Drop);
1336 
1337     // See if it's worth creating a back reference.
1338     // Only types longer than 1 character are considered
1339     // and only 10 back references slots are available:
1340     bool LongerThanOneChar = (Out.GetNumBytesInBuffer() - OutSizeBefore > 1);
1341     if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1342       size_t Size = TypeBackReferences.size();
1343       TypeBackReferences[TypePtr] = Size;
1344     }
1345   } else {
1346     Out << Found->second;
1347   }
1348 }
1349 
1350 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1351                                          QualifierMangleMode QMM) {
1352   // Don't use the canonical types.  MSVC includes things like 'const' on
1353   // pointer arguments to function pointers that canonicalization strips away.
1354   T = T.getDesugaredType(getASTContext());
1355   Qualifiers Quals = T.getLocalQualifiers();
1356   if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1357     // If there were any Quals, getAsArrayType() pushed them onto the array
1358     // element type.
1359     if (QMM == QMM_Mangle)
1360       Out << 'A';
1361     else if (QMM == QMM_Escape || QMM == QMM_Result)
1362       Out << "$$B";
1363     mangleArrayType(AT);
1364     return;
1365   }
1366 
1367   bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1368                    T->isBlockPointerType();
1369 
1370   switch (QMM) {
1371   case QMM_Drop:
1372     break;
1373   case QMM_Mangle:
1374     if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1375       Out << '6';
1376       mangleFunctionType(FT);
1377       return;
1378     }
1379     mangleQualifiers(Quals, false);
1380     break;
1381   case QMM_Escape:
1382     if (!IsPointer && Quals) {
1383       Out << "$$C";
1384       mangleQualifiers(Quals, false);
1385     }
1386     break;
1387   case QMM_Result:
1388     if ((!IsPointer && Quals) || isa<TagType>(T)) {
1389       Out << '?';
1390       mangleQualifiers(Quals, false);
1391     }
1392     break;
1393   }
1394 
1395   // We have to mangle these now, while we still have enough information.
1396   if (IsPointer) {
1397     manglePointerCVQualifiers(Quals);
1398     manglePointerExtQualifiers(Quals, T->getPointeeType().getTypePtr());
1399   }
1400   const Type *ty = T.getTypePtr();
1401 
1402   switch (ty->getTypeClass()) {
1403 #define ABSTRACT_TYPE(CLASS, PARENT)
1404 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1405   case Type::CLASS: \
1406     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1407     return;
1408 #define TYPE(CLASS, PARENT) \
1409   case Type::CLASS: \
1410     mangleType(cast<CLASS##Type>(ty), Range); \
1411     break;
1412 #include "clang/AST/TypeNodes.def"
1413 #undef ABSTRACT_TYPE
1414 #undef NON_CANONICAL_TYPE
1415 #undef TYPE
1416   }
1417 }
1418 
1419 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T,
1420                                          SourceRange Range) {
1421   //  <type>         ::= <builtin-type>
1422   //  <builtin-type> ::= X  # void
1423   //                 ::= C  # signed char
1424   //                 ::= D  # char
1425   //                 ::= E  # unsigned char
1426   //                 ::= F  # short
1427   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1428   //                 ::= H  # int
1429   //                 ::= I  # unsigned int
1430   //                 ::= J  # long
1431   //                 ::= K  # unsigned long
1432   //                     L  # <none>
1433   //                 ::= M  # float
1434   //                 ::= N  # double
1435   //                 ::= O  # long double (__float80 is mangled differently)
1436   //                 ::= _J # long long, __int64
1437   //                 ::= _K # unsigned long long, __int64
1438   //                 ::= _L # __int128
1439   //                 ::= _M # unsigned __int128
1440   //                 ::= _N # bool
1441   //                     _O # <array in parameter>
1442   //                 ::= _T # __float80 (Intel)
1443   //                 ::= _W # wchar_t
1444   //                 ::= _Z # __float80 (Digital Mars)
1445   switch (T->getKind()) {
1446   case BuiltinType::Void: Out << 'X'; break;
1447   case BuiltinType::SChar: Out << 'C'; break;
1448   case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
1449   case BuiltinType::UChar: Out << 'E'; break;
1450   case BuiltinType::Short: Out << 'F'; break;
1451   case BuiltinType::UShort: Out << 'G'; break;
1452   case BuiltinType::Int: Out << 'H'; break;
1453   case BuiltinType::UInt: Out << 'I'; break;
1454   case BuiltinType::Long: Out << 'J'; break;
1455   case BuiltinType::ULong: Out << 'K'; break;
1456   case BuiltinType::Float: Out << 'M'; break;
1457   case BuiltinType::Double: Out << 'N'; break;
1458   // TODO: Determine size and mangle accordingly
1459   case BuiltinType::LongDouble: Out << 'O'; break;
1460   case BuiltinType::LongLong: Out << "_J"; break;
1461   case BuiltinType::ULongLong: Out << "_K"; break;
1462   case BuiltinType::Int128: Out << "_L"; break;
1463   case BuiltinType::UInt128: Out << "_M"; break;
1464   case BuiltinType::Bool: Out << "_N"; break;
1465   case BuiltinType::WChar_S:
1466   case BuiltinType::WChar_U: Out << "_W"; break;
1467 
1468 #define BUILTIN_TYPE(Id, SingletonId)
1469 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1470   case BuiltinType::Id:
1471 #include "clang/AST/BuiltinTypes.def"
1472   case BuiltinType::Dependent:
1473     llvm_unreachable("placeholder types shouldn't get to name mangling");
1474 
1475   case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
1476   case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
1477   case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
1478 
1479   case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
1480   case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
1481   case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
1482   case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
1483   case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
1484   case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
1485   case BuiltinType::OCLSampler: Out << "PAUocl_sampler@@"; break;
1486   case BuiltinType::OCLEvent: Out << "PAUocl_event@@"; break;
1487 
1488   case BuiltinType::NullPtr: Out << "$$T"; break;
1489 
1490   case BuiltinType::Char16:
1491   case BuiltinType::Char32:
1492   case BuiltinType::Half: {
1493     DiagnosticsEngine &Diags = Context.getDiags();
1494     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1495       "cannot mangle this built-in %0 type yet");
1496     Diags.Report(Range.getBegin(), DiagID)
1497       << T->getName(Context.getASTContext().getPrintingPolicy())
1498       << Range;
1499     break;
1500   }
1501   }
1502 }
1503 
1504 // <type>          ::= <function-type>
1505 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T,
1506                                          SourceRange) {
1507   // Structors only appear in decls, so at this point we know it's not a
1508   // structor type.
1509   // FIXME: This may not be lambda-friendly.
1510   Out << "$$A6";
1511   mangleFunctionType(T);
1512 }
1513 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1514                                          SourceRange) {
1515   llvm_unreachable("Can't mangle K&R function prototypes");
1516 }
1517 
1518 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1519                                                  const FunctionDecl *D,
1520                                                  bool ForceInstMethod) {
1521   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1522   //                     <return-type> <argument-list> <throw-spec>
1523   const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1524 
1525   SourceRange Range;
1526   if (D) Range = D->getSourceRange();
1527 
1528   bool IsStructor = false, IsInstMethod = ForceInstMethod;
1529   if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1530     if (MD->isInstance())
1531       IsInstMethod = true;
1532     if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
1533       IsStructor = true;
1534   }
1535 
1536   // If this is a C++ instance method, mangle the CVR qualifiers for the
1537   // this pointer.
1538   if (IsInstMethod) {
1539     Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
1540     manglePointerExtQualifiers(Quals, 0);
1541     mangleRefQualifier(Proto->getRefQualifier());
1542     mangleQualifiers(Quals, false);
1543   }
1544 
1545   mangleCallingConvention(T);
1546 
1547   // <return-type> ::= <type>
1548   //               ::= @ # structors (they have no declared return type)
1549   if (IsStructor) {
1550     if (isa<CXXDestructorDecl>(D) && D == Structor &&
1551         StructorType == Dtor_Deleting) {
1552       // The scalar deleting destructor takes an extra int argument.
1553       // However, the FunctionType generated has 0 arguments.
1554       // FIXME: This is a temporary hack.
1555       // Maybe should fix the FunctionType creation instead?
1556       Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
1557       return;
1558     }
1559     Out << '@';
1560   } else {
1561     QualType ResultType = Proto->getReturnType();
1562     if (const auto *AT =
1563             dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
1564       Out << '?';
1565       mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
1566       Out << '?';
1567       mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
1568       Out << '@';
1569     } else {
1570       if (ResultType->isVoidType())
1571         ResultType = ResultType.getUnqualifiedType();
1572       mangleType(ResultType, Range, QMM_Result);
1573     }
1574   }
1575 
1576   // <argument-list> ::= X # void
1577   //                 ::= <type>+ @
1578   //                 ::= <type>* Z # varargs
1579   if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
1580     Out << 'X';
1581   } else {
1582     // Happens for function pointer type arguments for example.
1583     for (const QualType Arg : Proto->param_types())
1584       mangleArgumentType(Arg, Range);
1585     // <builtin-type>      ::= Z  # ellipsis
1586     if (Proto->isVariadic())
1587       Out << 'Z';
1588     else
1589       Out << '@';
1590   }
1591 
1592   mangleThrowSpecification(Proto);
1593 }
1594 
1595 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1596   // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
1597   //                                            # pointer. in 64-bit mode *all*
1598   //                                            # 'this' pointers are 64-bit.
1599   //                   ::= <global-function>
1600   // <member-function> ::= A # private: near
1601   //                   ::= B # private: far
1602   //                   ::= C # private: static near
1603   //                   ::= D # private: static far
1604   //                   ::= E # private: virtual near
1605   //                   ::= F # private: virtual far
1606   //                   ::= I # protected: near
1607   //                   ::= J # protected: far
1608   //                   ::= K # protected: static near
1609   //                   ::= L # protected: static far
1610   //                   ::= M # protected: virtual near
1611   //                   ::= N # protected: virtual far
1612   //                   ::= Q # public: near
1613   //                   ::= R # public: far
1614   //                   ::= S # public: static near
1615   //                   ::= T # public: static far
1616   //                   ::= U # public: virtual near
1617   //                   ::= V # public: virtual far
1618   // <global-function> ::= Y # global near
1619   //                   ::= Z # global far
1620   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1621     switch (MD->getAccess()) {
1622       case AS_none:
1623         llvm_unreachable("Unsupported access specifier");
1624       case AS_private:
1625         if (MD->isStatic())
1626           Out << 'C';
1627         else if (MD->isVirtual())
1628           Out << 'E';
1629         else
1630           Out << 'A';
1631         break;
1632       case AS_protected:
1633         if (MD->isStatic())
1634           Out << 'K';
1635         else if (MD->isVirtual())
1636           Out << 'M';
1637         else
1638           Out << 'I';
1639         break;
1640       case AS_public:
1641         if (MD->isStatic())
1642           Out << 'S';
1643         else if (MD->isVirtual())
1644           Out << 'U';
1645         else
1646           Out << 'Q';
1647     }
1648   } else
1649     Out << 'Y';
1650 }
1651 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
1652   // <calling-convention> ::= A # __cdecl
1653   //                      ::= B # __export __cdecl
1654   //                      ::= C # __pascal
1655   //                      ::= D # __export __pascal
1656   //                      ::= E # __thiscall
1657   //                      ::= F # __export __thiscall
1658   //                      ::= G # __stdcall
1659   //                      ::= H # __export __stdcall
1660   //                      ::= I # __fastcall
1661   //                      ::= J # __export __fastcall
1662   // The 'export' calling conventions are from a bygone era
1663   // (*cough*Win16*cough*) when functions were declared for export with
1664   // that keyword. (It didn't actually export them, it just made them so
1665   // that they could be in a DLL and somebody from another module could call
1666   // them.)
1667   CallingConv CC = T->getCallConv();
1668   switch (CC) {
1669     default:
1670       llvm_unreachable("Unsupported CC for mangling");
1671     case CC_X86_64Win64:
1672     case CC_X86_64SysV:
1673     case CC_C: Out << 'A'; break;
1674     case CC_X86Pascal: Out << 'C'; break;
1675     case CC_X86ThisCall: Out << 'E'; break;
1676     case CC_X86StdCall: Out << 'G'; break;
1677     case CC_X86FastCall: Out << 'I'; break;
1678   }
1679 }
1680 void MicrosoftCXXNameMangler::mangleThrowSpecification(
1681                                                 const FunctionProtoType *FT) {
1682   // <throw-spec> ::= Z # throw(...) (default)
1683   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
1684   //              ::= <type>+
1685   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1686   // all actually mangled as 'Z'. (They're ignored because their associated
1687   // functionality isn't implemented, and probably never will be.)
1688   Out << 'Z';
1689 }
1690 
1691 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
1692                                          SourceRange Range) {
1693   // Probably should be mangled as a template instantiation; need to see what
1694   // VC does first.
1695   DiagnosticsEngine &Diags = Context.getDiags();
1696   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1697     "cannot mangle this unresolved dependent type yet");
1698   Diags.Report(Range.getBegin(), DiagID)
1699     << Range;
1700 }
1701 
1702 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1703 // <union-type>  ::= T <name>
1704 // <struct-type> ::= U <name>
1705 // <class-type>  ::= V <name>
1706 // <enum-type>   ::= W4 <name>
1707 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, SourceRange) {
1708   mangleType(cast<TagType>(T)->getDecl());
1709 }
1710 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, SourceRange) {
1711   mangleType(cast<TagType>(T)->getDecl());
1712 }
1713 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
1714   switch (TD->getTagKind()) {
1715     case TTK_Union:
1716       Out << 'T';
1717       break;
1718     case TTK_Struct:
1719     case TTK_Interface:
1720       Out << 'U';
1721       break;
1722     case TTK_Class:
1723       Out << 'V';
1724       break;
1725     case TTK_Enum:
1726       Out << "W4";
1727       break;
1728   }
1729   mangleName(TD);
1730 }
1731 
1732 // <type>       ::= <array-type>
1733 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1734 //                  [Y <dimension-count> <dimension>+]
1735 //                  <element-type> # as global, E is never required
1736 // It's supposed to be the other way around, but for some strange reason, it
1737 // isn't. Today this behavior is retained for the sole purpose of backwards
1738 // compatibility.
1739 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
1740   // This isn't a recursive mangling, so now we have to do it all in this
1741   // one call.
1742   manglePointerCVQualifiers(T->getElementType().getQualifiers());
1743   mangleType(T->getElementType(), SourceRange());
1744 }
1745 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T,
1746                                          SourceRange) {
1747   llvm_unreachable("Should have been special cased");
1748 }
1749 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T,
1750                                          SourceRange) {
1751   llvm_unreachable("Should have been special cased");
1752 }
1753 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
1754                                          SourceRange) {
1755   llvm_unreachable("Should have been special cased");
1756 }
1757 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
1758                                          SourceRange) {
1759   llvm_unreachable("Should have been special cased");
1760 }
1761 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
1762   QualType ElementTy(T, 0);
1763   SmallVector<llvm::APInt, 3> Dimensions;
1764   for (;;) {
1765     if (const ConstantArrayType *CAT =
1766             getASTContext().getAsConstantArrayType(ElementTy)) {
1767       Dimensions.push_back(CAT->getSize());
1768       ElementTy = CAT->getElementType();
1769     } else if (ElementTy->isVariableArrayType()) {
1770       const VariableArrayType *VAT =
1771         getASTContext().getAsVariableArrayType(ElementTy);
1772       DiagnosticsEngine &Diags = Context.getDiags();
1773       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1774         "cannot mangle this variable-length array yet");
1775       Diags.Report(VAT->getSizeExpr()->getExprLoc(), DiagID)
1776         << VAT->getBracketsRange();
1777       return;
1778     } else if (ElementTy->isDependentSizedArrayType()) {
1779       // The dependent expression has to be folded into a constant (TODO).
1780       const DependentSizedArrayType *DSAT =
1781         getASTContext().getAsDependentSizedArrayType(ElementTy);
1782       DiagnosticsEngine &Diags = Context.getDiags();
1783       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1784         "cannot mangle this dependent-length array yet");
1785       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
1786         << DSAT->getBracketsRange();
1787       return;
1788     } else if (const IncompleteArrayType *IAT =
1789                    getASTContext().getAsIncompleteArrayType(ElementTy)) {
1790       Dimensions.push_back(llvm::APInt(32, 0));
1791       ElementTy = IAT->getElementType();
1792     }
1793     else break;
1794   }
1795   Out << 'Y';
1796   // <dimension-count> ::= <number> # number of extra dimensions
1797   mangleNumber(Dimensions.size());
1798   for (const llvm::APInt &Dimension : Dimensions)
1799     mangleNumber(Dimension.getLimitedValue());
1800   mangleType(ElementTy, SourceRange(), QMM_Escape);
1801 }
1802 
1803 // <type>                   ::= <pointer-to-member-type>
1804 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1805 //                                                          <class name> <type>
1806 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
1807                                          SourceRange Range) {
1808   QualType PointeeType = T->getPointeeType();
1809   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
1810     Out << '8';
1811     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1812     mangleFunctionType(FPT, 0, true);
1813   } else {
1814     mangleQualifiers(PointeeType.getQualifiers(), true);
1815     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1816     mangleType(PointeeType, Range, QMM_Drop);
1817   }
1818 }
1819 
1820 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
1821                                          SourceRange Range) {
1822   DiagnosticsEngine &Diags = Context.getDiags();
1823   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1824     "cannot mangle this template type parameter type yet");
1825   Diags.Report(Range.getBegin(), DiagID)
1826     << Range;
1827 }
1828 
1829 void MicrosoftCXXNameMangler::mangleType(
1830                                        const SubstTemplateTypeParmPackType *T,
1831                                        SourceRange Range) {
1832   DiagnosticsEngine &Diags = Context.getDiags();
1833   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1834     "cannot mangle this substituted parameter pack yet");
1835   Diags.Report(Range.getBegin(), DiagID)
1836     << Range;
1837 }
1838 
1839 // <type> ::= <pointer-type>
1840 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
1841 //                       # the E is required for 64-bit non-static pointers
1842 void MicrosoftCXXNameMangler::mangleType(const PointerType *T,
1843                                          SourceRange Range) {
1844   QualType PointeeTy = T->getPointeeType();
1845   mangleType(PointeeTy, Range);
1846 }
1847 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
1848                                          SourceRange Range) {
1849   // Object pointers never have qualifiers.
1850   Out << 'A';
1851   manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
1852   mangleType(T->getPointeeType(), Range);
1853 }
1854 
1855 // <type> ::= <reference-type>
1856 // <reference-type> ::= A E? <cvr-qualifiers> <type>
1857 //                 # the E is required for 64-bit non-static lvalue references
1858 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
1859                                          SourceRange Range) {
1860   Out << 'A';
1861   manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
1862   mangleType(T->getPointeeType(), Range);
1863 }
1864 
1865 // <type> ::= <r-value-reference-type>
1866 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
1867 //                 # the E is required for 64-bit non-static rvalue references
1868 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
1869                                          SourceRange Range) {
1870   Out << "$$Q";
1871   manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
1872   mangleType(T->getPointeeType(), Range);
1873 }
1874 
1875 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T,
1876                                          SourceRange Range) {
1877   DiagnosticsEngine &Diags = Context.getDiags();
1878   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1879     "cannot mangle this complex number type yet");
1880   Diags.Report(Range.getBegin(), DiagID)
1881     << Range;
1882 }
1883 
1884 void MicrosoftCXXNameMangler::mangleType(const VectorType *T,
1885                                          SourceRange Range) {
1886   const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
1887   assert(ET && "vectors with non-builtin elements are unsupported");
1888   uint64_t Width = getASTContext().getTypeSize(T);
1889   // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
1890   // doesn't match the Intel types uses a custom mangling below.
1891   bool IntelVector = true;
1892   if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
1893     Out << "T__m64";
1894   } else if (Width == 128 || Width == 256) {
1895     if (ET->getKind() == BuiltinType::Float)
1896       Out << "T__m" << Width;
1897     else if (ET->getKind() == BuiltinType::LongLong)
1898       Out << "T__m" << Width << 'i';
1899     else if (ET->getKind() == BuiltinType::Double)
1900       Out << "U__m" << Width << 'd';
1901     else
1902       IntelVector = false;
1903   } else {
1904     IntelVector = false;
1905   }
1906 
1907   if (!IntelVector) {
1908     // The MS ABI doesn't have a special mangling for vector types, so we define
1909     // our own mangling to handle uses of __vector_size__ on user-specified
1910     // types, and for extensions like __v4sf.
1911     Out << "T__clang_vec" << T->getNumElements() << '_';
1912     mangleType(ET, Range);
1913   }
1914 
1915   Out << "@@";
1916 }
1917 
1918 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
1919                                          SourceRange Range) {
1920   DiagnosticsEngine &Diags = Context.getDiags();
1921   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1922     "cannot mangle this extended vector type yet");
1923   Diags.Report(Range.getBegin(), DiagID)
1924     << Range;
1925 }
1926 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
1927                                          SourceRange Range) {
1928   DiagnosticsEngine &Diags = Context.getDiags();
1929   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1930     "cannot mangle this dependent-sized extended vector type yet");
1931   Diags.Report(Range.getBegin(), DiagID)
1932     << Range;
1933 }
1934 
1935 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T,
1936                                          SourceRange) {
1937   // ObjC interfaces have structs underlying them.
1938   Out << 'U';
1939   mangleName(T->getDecl());
1940 }
1941 
1942 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
1943                                          SourceRange Range) {
1944   // We don't allow overloading by different protocol qualification,
1945   // so mangling them isn't necessary.
1946   mangleType(T->getBaseType(), Range);
1947 }
1948 
1949 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
1950                                          SourceRange Range) {
1951   Out << "_E";
1952 
1953   QualType pointee = T->getPointeeType();
1954   mangleFunctionType(pointee->castAs<FunctionProtoType>());
1955 }
1956 
1957 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
1958                                          SourceRange) {
1959   llvm_unreachable("Cannot mangle injected class name type.");
1960 }
1961 
1962 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
1963                                          SourceRange Range) {
1964   DiagnosticsEngine &Diags = Context.getDiags();
1965   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1966     "cannot mangle this template specialization type yet");
1967   Diags.Report(Range.getBegin(), DiagID)
1968     << Range;
1969 }
1970 
1971 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T,
1972                                          SourceRange Range) {
1973   DiagnosticsEngine &Diags = Context.getDiags();
1974   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1975     "cannot mangle this dependent name type yet");
1976   Diags.Report(Range.getBegin(), DiagID)
1977     << Range;
1978 }
1979 
1980 void MicrosoftCXXNameMangler::mangleType(
1981                                  const DependentTemplateSpecializationType *T,
1982                                  SourceRange Range) {
1983   DiagnosticsEngine &Diags = Context.getDiags();
1984   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1985     "cannot mangle this dependent template specialization type yet");
1986   Diags.Report(Range.getBegin(), DiagID)
1987     << Range;
1988 }
1989 
1990 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T,
1991                                          SourceRange Range) {
1992   DiagnosticsEngine &Diags = Context.getDiags();
1993   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1994     "cannot mangle this pack expansion yet");
1995   Diags.Report(Range.getBegin(), DiagID)
1996     << Range;
1997 }
1998 
1999 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T,
2000                                          SourceRange Range) {
2001   DiagnosticsEngine &Diags = Context.getDiags();
2002   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2003     "cannot mangle this typeof(type) yet");
2004   Diags.Report(Range.getBegin(), DiagID)
2005     << Range;
2006 }
2007 
2008 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T,
2009                                          SourceRange Range) {
2010   DiagnosticsEngine &Diags = Context.getDiags();
2011   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2012     "cannot mangle this typeof(expression) yet");
2013   Diags.Report(Range.getBegin(), DiagID)
2014     << Range;
2015 }
2016 
2017 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T,
2018                                          SourceRange Range) {
2019   DiagnosticsEngine &Diags = Context.getDiags();
2020   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2021     "cannot mangle this decltype() yet");
2022   Diags.Report(Range.getBegin(), DiagID)
2023     << Range;
2024 }
2025 
2026 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2027                                          SourceRange Range) {
2028   DiagnosticsEngine &Diags = Context.getDiags();
2029   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2030     "cannot mangle this unary transform type yet");
2031   Diags.Report(Range.getBegin(), DiagID)
2032     << Range;
2033 }
2034 
2035 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, SourceRange Range) {
2036   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2037 
2038   DiagnosticsEngine &Diags = Context.getDiags();
2039   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2040     "cannot mangle this 'auto' type yet");
2041   Diags.Report(Range.getBegin(), DiagID)
2042     << Range;
2043 }
2044 
2045 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T,
2046                                          SourceRange Range) {
2047   DiagnosticsEngine &Diags = Context.getDiags();
2048   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2049     "cannot mangle this C11 atomic type yet");
2050   Diags.Report(Range.getBegin(), DiagID)
2051     << Range;
2052 }
2053 
2054 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2055                                                raw_ostream &Out) {
2056   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2057          "Invalid mangleName() call, argument is not a variable or function!");
2058   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2059          "Invalid mangleName() call on 'structor decl!");
2060 
2061   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2062                                  getASTContext().getSourceManager(),
2063                                  "Mangling declaration");
2064 
2065   MicrosoftCXXNameMangler Mangler(*this, Out);
2066   return Mangler.mangle(D);
2067 }
2068 
2069 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2070 //                       <virtual-adjustment>
2071 // <no-adjustment>      ::= A # private near
2072 //                      ::= B # private far
2073 //                      ::= I # protected near
2074 //                      ::= J # protected far
2075 //                      ::= Q # public near
2076 //                      ::= R # public far
2077 // <static-adjustment>  ::= G <static-offset> # private near
2078 //                      ::= H <static-offset> # private far
2079 //                      ::= O <static-offset> # protected near
2080 //                      ::= P <static-offset> # protected far
2081 //                      ::= W <static-offset> # public near
2082 //                      ::= X <static-offset> # public far
2083 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2084 //                      ::= $1 <virtual-shift> <static-offset> # private far
2085 //                      ::= $2 <virtual-shift> <static-offset> # protected near
2086 //                      ::= $3 <virtual-shift> <static-offset> # protected far
2087 //                      ::= $4 <virtual-shift> <static-offset> # public near
2088 //                      ::= $5 <virtual-shift> <static-offset> # public far
2089 // <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
2090 // <vtordisp-shift>     ::= <offset-to-vtordisp>
2091 // <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
2092 //                          <offset-to-vtordisp>
2093 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2094                                       const ThisAdjustment &Adjustment,
2095                                       MicrosoftCXXNameMangler &Mangler,
2096                                       raw_ostream &Out) {
2097   if (!Adjustment.Virtual.isEmpty()) {
2098     Out << '$';
2099     char AccessSpec;
2100     switch (MD->getAccess()) {
2101     case AS_none:
2102       llvm_unreachable("Unsupported access specifier");
2103     case AS_private:
2104       AccessSpec = '0';
2105       break;
2106     case AS_protected:
2107       AccessSpec = '2';
2108       break;
2109     case AS_public:
2110       AccessSpec = '4';
2111     }
2112     if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2113       Out << 'R' << AccessSpec;
2114       Mangler.mangleNumber(
2115           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2116       Mangler.mangleNumber(
2117           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2118       Mangler.mangleNumber(
2119           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2120       Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2121     } else {
2122       Out << AccessSpec;
2123       Mangler.mangleNumber(
2124           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2125       Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2126     }
2127   } else if (Adjustment.NonVirtual != 0) {
2128     switch (MD->getAccess()) {
2129     case AS_none:
2130       llvm_unreachable("Unsupported access specifier");
2131     case AS_private:
2132       Out << 'G';
2133       break;
2134     case AS_protected:
2135       Out << 'O';
2136       break;
2137     case AS_public:
2138       Out << 'W';
2139     }
2140     Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2141   } else {
2142     switch (MD->getAccess()) {
2143     case AS_none:
2144       llvm_unreachable("Unsupported access specifier");
2145     case AS_private:
2146       Out << 'A';
2147       break;
2148     case AS_protected:
2149       Out << 'I';
2150       break;
2151     case AS_public:
2152       Out << 'Q';
2153     }
2154   }
2155 }
2156 
2157 void
2158 MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2159                                                      raw_ostream &Out) {
2160   MicrosoftVTableContext *VTContext =
2161       cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2162   const MicrosoftVTableContext::MethodVFTableLocation &ML =
2163       VTContext->getMethodVFTableLocation(GlobalDecl(MD));
2164 
2165   MicrosoftCXXNameMangler Mangler(*this, Out);
2166   Mangler.getStream() << "\01?";
2167   Mangler.mangleVirtualMemPtrThunk(MD, ML);
2168 }
2169 
2170 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2171                                              const ThunkInfo &Thunk,
2172                                              raw_ostream &Out) {
2173   MicrosoftCXXNameMangler Mangler(*this, Out);
2174   Out << "\01?";
2175   Mangler.mangleName(MD);
2176   mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
2177   if (!Thunk.Return.isEmpty())
2178     assert(Thunk.Method != 0 && "Thunk info should hold the overridee decl");
2179 
2180   const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2181   Mangler.mangleFunctionType(
2182       DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2183 }
2184 
2185 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2186     const CXXDestructorDecl *DD, CXXDtorType Type,
2187     const ThisAdjustment &Adjustment, raw_ostream &Out) {
2188   // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2189   // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2190   // mangling manually until we support both deleting dtor types.
2191   assert(Type == Dtor_Deleting);
2192   MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
2193   Out << "\01??_E";
2194   Mangler.mangleName(DD->getParent());
2195   mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
2196   Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2197 }
2198 
2199 void MicrosoftMangleContextImpl::mangleCXXVFTable(
2200     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2201     raw_ostream &Out) {
2202   // <mangled-name> ::= ?_7 <class-name> <storage-class>
2203   //                    <cvr-qualifiers> [<name>] @
2204   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2205   // is always '6' for vftables.
2206   MicrosoftCXXNameMangler Mangler(*this, Out);
2207   Mangler.getStream() << "\01??_7";
2208   Mangler.mangleName(Derived);
2209   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2210   for (const CXXRecordDecl *RD : BasePath)
2211     Mangler.mangleName(RD);
2212   Mangler.getStream() << '@';
2213 }
2214 
2215 void MicrosoftMangleContextImpl::mangleCXXVBTable(
2216     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2217     raw_ostream &Out) {
2218   // <mangled-name> ::= ?_8 <class-name> <storage-class>
2219   //                    <cvr-qualifiers> [<name>] @
2220   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2221   // is always '7' for vbtables.
2222   MicrosoftCXXNameMangler Mangler(*this, Out);
2223   Mangler.getStream() << "\01??_8";
2224   Mangler.mangleName(Derived);
2225   Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
2226   for (const CXXRecordDecl *RD : BasePath)
2227     Mangler.mangleName(RD);
2228   Mangler.getStream() << '@';
2229 }
2230 
2231 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &) {
2232   // FIXME: Give a location...
2233   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2234     "cannot mangle RTTI descriptors for type %0 yet");
2235   getDiags().Report(DiagID)
2236     << T.getBaseTypeIdentifier();
2237 }
2238 
2239 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T, raw_ostream &) {
2240   // FIXME: Give a location...
2241   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2242     "cannot mangle the name of type %0 into RTTI descriptors yet");
2243   getDiags().Report(DiagID)
2244     << T.getBaseTypeIdentifier();
2245 }
2246 
2247 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
2248   // This is just a made up unique string for the purposes of tbaa.  undname
2249   // does *not* know how to demangle it.
2250   MicrosoftCXXNameMangler Mangler(*this, Out);
2251   Mangler.getStream() << '?';
2252   Mangler.mangleType(T, SourceRange());
2253 }
2254 
2255 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
2256                                                CXXCtorType Type,
2257                                                raw_ostream &Out) {
2258   MicrosoftCXXNameMangler mangler(*this, Out);
2259   mangler.mangle(D);
2260 }
2261 
2262 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
2263                                                CXXDtorType Type,
2264                                                raw_ostream &Out) {
2265   MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2266   mangler.mangle(D);
2267 }
2268 
2269 void MicrosoftMangleContextImpl::mangleReferenceTemporary(const VarDecl *VD,
2270                                                           raw_ostream &) {
2271   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2272     "cannot mangle this reference temporary yet");
2273   getDiags().Report(VD->getLocation(), DiagID);
2274 }
2275 
2276 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
2277                                                            raw_ostream &Out) {
2278   // TODO: This is not correct, especially with respect to MSVC2013.  MSVC2013
2279   // utilizes thread local variables to implement thread safe, re-entrant
2280   // initialization for statics.  They no longer differentiate between an
2281   // externally visible and non-externally visible static with respect to
2282   // mangling, they all get $TSS <number>.
2283   //
2284   // N.B. This means that they can get more than 32 static variable guards in a
2285   // scope.  It also means that they broke compatibility with their own ABI.
2286 
2287   // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
2288   //              ::= ?$S <guard-num> @ <postfix> @4IA
2289 
2290   // The first mangling is what MSVC uses to guard static locals in inline
2291   // functions.  It uses a different mangling in external functions to support
2292   // guarding more than 32 variables.  MSVC rejects inline functions with more
2293   // than 32 static locals.  We don't fully implement the second mangling
2294   // because those guards are not externally visible, and instead use LLVM's
2295   // default renaming when creating a new guard variable.
2296   MicrosoftCXXNameMangler Mangler(*this, Out);
2297 
2298   bool Visible = VD->isExternallyVisible();
2299   // <operator-name> ::= ?_B # local static guard
2300   Mangler.getStream() << (Visible ? "\01??_B" : "\01?$S1@");
2301   unsigned ScopeDepth = 0;
2302   if (Visible && !getNextDiscriminator(VD, ScopeDepth))
2303     // If we do not have a discriminator and are emitting a guard variable for
2304     // use at global scope, then mangling the nested name will not be enough to
2305     // remove ambiguities.
2306     Mangler.mangle(VD, "");
2307   else
2308     Mangler.mangleNestedName(VD);
2309   Mangler.getStream() << (Visible ? "@5" : "@4IA");
2310   if (ScopeDepth)
2311     Mangler.mangleNumber(ScopeDepth);
2312 }
2313 
2314 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
2315                                                     raw_ostream &Out,
2316                                                     char CharCode) {
2317   MicrosoftCXXNameMangler Mangler(*this, Out);
2318   Mangler.getStream() << "\01??__" << CharCode;
2319   Mangler.mangleName(D);
2320   if (D->isStaticDataMember()) {
2321     Mangler.mangleVariableEncoding(D);
2322     Mangler.getStream() << '@';
2323   }
2324   // This is the function class mangling.  These stubs are global, non-variadic,
2325   // cdecl functions that return void and take no args.
2326   Mangler.getStream() << "YAXXZ";
2327 }
2328 
2329 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
2330                                                           raw_ostream &Out) {
2331   // <initializer-name> ::= ?__E <name> YAXXZ
2332   mangleInitFiniStub(D, Out, 'E');
2333 }
2334 
2335 void
2336 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
2337                                                           raw_ostream &Out) {
2338   // <destructor-name> ::= ?__F <name> YAXXZ
2339   mangleInitFiniStub(D, Out, 'F');
2340 }
2341 
2342 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
2343                                                      raw_ostream &Out) {
2344   // <char-type> ::= 0   # char
2345   //             ::= 1   # wchar_t
2346   //             ::= ??? # char16_t/char32_t will need a mangling too...
2347   //
2348   // <literal-length> ::= <non-negative integer>  # the length of the literal
2349   //
2350   // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
2351   //                                              # null-terminator
2352   //
2353   // <encoded-string> ::= <simple character>           # uninteresting character
2354   //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
2355   //                                                   # encode the byte for the
2356   //                                                   # character
2357   //                  ::= '?' [a-z]                    # \xe1 - \xfa
2358   //                  ::= '?' [A-Z]                    # \xc1 - \xda
2359   //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
2360   //
2361   // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
2362   //               <encoded-string> '@'
2363   MicrosoftCXXNameMangler Mangler(*this, Out);
2364   Mangler.getStream() << "\01??_C@_";
2365 
2366   // <char-type>: The "kind" of string literal is encoded into the mangled name.
2367   // TODO: This needs to be updated when MSVC gains support for unicode
2368   // literals.
2369   if (SL->isAscii())
2370     Mangler.getStream() << '0';
2371   else if (SL->isWide())
2372     Mangler.getStream() << '1';
2373   else
2374     llvm_unreachable("unexpected string literal kind!");
2375 
2376   // <literal-length>: The next part of the mangled name consists of the length
2377   // of the string.
2378   // The StringLiteral does not consider the NUL terminator byte(s) but the
2379   // mangling does.
2380   // N.B. The length is in terms of bytes, not characters.
2381   Mangler.mangleNumber(SL->getByteLength() + SL->getCharByteWidth());
2382 
2383   // We will use the "Rocksoft^tm Model CRC Algorithm" to describe the
2384   // properties of our CRC:
2385   //   Width  : 32
2386   //   Poly   : 04C11DB7
2387   //   Init   : FFFFFFFF
2388   //   RefIn  : True
2389   //   RefOut : True
2390   //   XorOut : 00000000
2391   //   Check  : 340BC6D9
2392   uint32_t CRC = 0xFFFFFFFFU;
2393 
2394   auto UpdateCRC = [&CRC](char Byte) {
2395     for (unsigned i = 0; i < 8; ++i) {
2396       bool Bit = CRC & 0x80000000U;
2397       if (Byte & (1U << i))
2398         Bit = !Bit;
2399       CRC <<= 1;
2400       if (Bit)
2401         CRC ^= 0x04C11DB7U;
2402     }
2403   };
2404 
2405   auto GetLittleEndianByte = [&Mangler, &SL](unsigned Index) {
2406     unsigned CharByteWidth = SL->getCharByteWidth();
2407     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2408     unsigned OffsetInCodeUnit = Index % CharByteWidth;
2409     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2410   };
2411 
2412   auto GetBigEndianByte = [&Mangler, &SL](unsigned Index) {
2413     unsigned CharByteWidth = SL->getCharByteWidth();
2414     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
2415     unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
2416     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
2417   };
2418 
2419   // CRC all the bytes of the StringLiteral.
2420   for (unsigned I = 0, E = SL->getByteLength(); I != E; ++I)
2421     UpdateCRC(GetLittleEndianByte(I));
2422 
2423   // The NUL terminator byte(s) were not present earlier,
2424   // we need to manually process those bytes into the CRC.
2425   for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2426        ++NullTerminator)
2427     UpdateCRC('\x00');
2428 
2429   // The literature refers to the process of reversing the bits in the final CRC
2430   // output as "reflection".
2431   CRC = llvm::reverseBits(CRC);
2432 
2433   // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
2434   // scheme.
2435   Mangler.mangleNumber(CRC);
2436 
2437   // <encoded-string>: The mangled name also contains the first 32 _characters_
2438   // (including null-terminator bytes) of the StringLiteral.
2439   // Each character is encoded by splitting them into bytes and then encoding
2440   // the constituent bytes.
2441   auto MangleByte = [&Mangler](char Byte) {
2442     // There are five different manglings for characters:
2443     // - [a-zA-Z0-9_$]: A one-to-one mapping.
2444     // - ?[a-z]: The range from \xe1 to \xfa.
2445     // - ?[A-Z]: The range from \xc1 to \xda.
2446     // - ?[0-9]: The set of [,/\:. \n\t'-].
2447     // - ?$XX: A fallback which maps nibbles.
2448     if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
2449       Mangler.getStream() << Byte;
2450     } else if (isLetter(Byte & 0x7f)) {
2451       Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
2452     } else {
2453       switch (Byte) {
2454         case ',':
2455           Mangler.getStream() << "?0";
2456           break;
2457         case '/':
2458           Mangler.getStream() << "?1";
2459           break;
2460         case '\\':
2461           Mangler.getStream() << "?2";
2462           break;
2463         case ':':
2464           Mangler.getStream() << "?3";
2465           break;
2466         case '.':
2467           Mangler.getStream() << "?4";
2468           break;
2469         case ' ':
2470           Mangler.getStream() << "?5";
2471           break;
2472         case '\n':
2473           Mangler.getStream() << "?6";
2474           break;
2475         case '\t':
2476           Mangler.getStream() << "?7";
2477           break;
2478         case '\'':
2479           Mangler.getStream() << "?8";
2480           break;
2481         case '-':
2482           Mangler.getStream() << "?9";
2483           break;
2484         default:
2485           Mangler.getStream() << "?$";
2486           Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
2487           Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
2488           break;
2489       }
2490     }
2491   };
2492 
2493   // Enforce our 32 character max.
2494   unsigned NumCharsToMangle = std::min(32U, SL->getLength());
2495   for (unsigned I = 0, E = NumCharsToMangle * SL->getCharByteWidth(); I != E;
2496        ++I)
2497     MangleByte(GetBigEndianByte(I));
2498 
2499   // Encode the NUL terminator if there is room.
2500   if (NumCharsToMangle < 32)
2501     for (unsigned NullTerminator = 0; NullTerminator < SL->getCharByteWidth();
2502          ++NullTerminator)
2503       MangleByte(0);
2504 
2505   Mangler.getStream() << '@';
2506 }
2507 
2508 MicrosoftMangleContext *
2509 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
2510   return new MicrosoftMangleContextImpl(Context, Diags);
2511 }
2512