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