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