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