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/DeclOpenMP.h"
23 #include "clang/AST/DeclTemplate.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/AST/ExprCXX.h"
26 #include "clang/AST/VTableBuilder.h"
27 #include "clang/Basic/ABI.h"
28 #include "clang/Basic/DiagnosticOptions.h"
29 #include "clang/Basic/TargetInfo.h"
30 #include "llvm/ADT/StringExtras.h"
31 #include "llvm/Support/JamCRC.h"
32 #include "llvm/Support/xxhash.h"
33 #include "llvm/Support/MD5.h"
34 #include "llvm/Support/MathExtras.h"
35 
36 using namespace clang;
37 
38 namespace {
39 
40 struct msvc_hashing_ostream : public llvm::raw_svector_ostream {
41   raw_ostream &OS;
42   llvm::SmallString<64> Buffer;
43 
44   msvc_hashing_ostream(raw_ostream &OS)
45       : llvm::raw_svector_ostream(Buffer), OS(OS) {}
46   ~msvc_hashing_ostream() override {
47     StringRef MangledName = str();
48     bool StartsWithEscape = MangledName.startswith("\01");
49     if (StartsWithEscape)
50       MangledName = MangledName.drop_front(1);
51     if (MangledName.size() <= 4096) {
52       OS << str();
53       return;
54     }
55 
56     llvm::MD5 Hasher;
57     llvm::MD5::MD5Result Hash;
58     Hasher.update(MangledName);
59     Hasher.final(Hash);
60 
61     SmallString<32> HexString;
62     llvm::MD5::stringifyResult(Hash, HexString);
63 
64     if (StartsWithEscape)
65       OS << '\01';
66     OS << "??@" << HexString << '@';
67   }
68 };
69 
70 static const DeclContext *
71 getLambdaDefaultArgumentDeclContext(const Decl *D) {
72   if (const auto *RD = dyn_cast<CXXRecordDecl>(D))
73     if (RD->isLambda())
74       if (const auto *Parm =
75               dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
76         return Parm->getDeclContext();
77   return nullptr;
78 }
79 
80 /// Retrieve the declaration context that should be used when mangling
81 /// the given declaration.
82 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
83   // The ABI assumes that lambda closure types that occur within
84   // default arguments live in the context of the function. However, due to
85   // the way in which Clang parses and creates function declarations, this is
86   // not the case: the lambda closure type ends up living in the context
87   // where the function itself resides, because the function declaration itself
88   // had not yet been created. Fix the context here.
89   if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(D))
90     return LDADC;
91 
92   // Perform the same check for block literals.
93   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
94     if (ParmVarDecl *ContextParam =
95             dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
96       return ContextParam->getDeclContext();
97   }
98 
99   const DeclContext *DC = D->getDeclContext();
100   if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
101     return getEffectiveDeclContext(cast<Decl>(DC));
102   }
103 
104   return DC->getRedeclContext();
105 }
106 
107 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
108   return getEffectiveDeclContext(cast<Decl>(DC));
109 }
110 
111 static const FunctionDecl *getStructor(const NamedDecl *ND) {
112   if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
113     return FTD->getTemplatedDecl()->getCanonicalDecl();
114 
115   const auto *FD = cast<FunctionDecl>(ND);
116   if (const auto *FTD = FD->getPrimaryTemplate())
117     return FTD->getTemplatedDecl()->getCanonicalDecl();
118 
119   return FD->getCanonicalDecl();
120 }
121 
122 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
123 /// Microsoft Visual C++ ABI.
124 class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
125   typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
126   llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
127   llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
128   llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
129   llvm::DenseMap<const NamedDecl *, unsigned> SEHFilterIds;
130   llvm::DenseMap<const NamedDecl *, unsigned> SEHFinallyIds;
131   SmallString<16> AnonymousNamespaceHash;
132 
133 public:
134   MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags);
135   bool shouldMangleCXXName(const NamedDecl *D) override;
136   bool shouldMangleStringLiteral(const StringLiteral *SL) override;
137   void mangleCXXName(const NamedDecl *D, raw_ostream &Out) override;
138   void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
139                                 const MethodVFTableLocation &ML,
140                                 raw_ostream &Out) override;
141   void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
142                    raw_ostream &) override;
143   void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
144                           const ThisAdjustment &ThisAdjustment,
145                           raw_ostream &) override;
146   void mangleCXXVFTable(const CXXRecordDecl *Derived,
147                         ArrayRef<const CXXRecordDecl *> BasePath,
148                         raw_ostream &Out) override;
149   void mangleCXXVBTable(const CXXRecordDecl *Derived,
150                         ArrayRef<const CXXRecordDecl *> BasePath,
151                         raw_ostream &Out) override;
152   void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
153                                        const CXXRecordDecl *DstRD,
154                                        raw_ostream &Out) override;
155   void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
156                           bool IsUnaligned, uint32_t NumEntries,
157                           raw_ostream &Out) override;
158   void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
159                                    raw_ostream &Out) override;
160   void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
161                               CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
162                               int32_t VBPtrOffset, uint32_t VBIndex,
163                               raw_ostream &Out) override;
164   void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
165   void mangleCXXRTTIName(QualType T, raw_ostream &Out) override;
166   void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
167                                         uint32_t NVOffset, int32_t VBPtrOffset,
168                                         uint32_t VBTableOffset, uint32_t Flags,
169                                         raw_ostream &Out) override;
170   void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
171                                    raw_ostream &Out) override;
172   void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
173                                              raw_ostream &Out) override;
174   void
175   mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
176                                      ArrayRef<const CXXRecordDecl *> BasePath,
177                                      raw_ostream &Out) override;
178   void mangleTypeName(QualType T, raw_ostream &) override;
179   void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
180                      raw_ostream &) override;
181   void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
182                      raw_ostream &) override;
183   void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
184                                 raw_ostream &) override;
185   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
186   void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
187                                            raw_ostream &Out) override;
188   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
189   void mangleDynamicAtExitDestructor(const VarDecl *D,
190                                      raw_ostream &Out) override;
191   void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
192                                  raw_ostream &Out) override;
193   void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
194                              raw_ostream &Out) override;
195   void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
196   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
197     const DeclContext *DC = getEffectiveDeclContext(ND);
198     if (!DC->isFunctionOrMethod())
199       return false;
200 
201     // Lambda closure types are already numbered, give out a phony number so
202     // that they demangle nicely.
203     if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
204       if (RD->isLambda()) {
205         disc = 1;
206         return true;
207       }
208     }
209 
210     // Use the canonical number for externally visible decls.
211     if (ND->isExternallyVisible()) {
212       disc = getASTContext().getManglingNumber(ND);
213       return true;
214     }
215 
216     // Anonymous tags are already numbered.
217     if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
218       if (!Tag->hasNameForLinkage() &&
219           !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) &&
220           !getASTContext().getTypedefNameForUnnamedTagDecl(Tag))
221         return false;
222     }
223 
224     // Make up a reasonable number for internal decls.
225     unsigned &discriminator = Uniquifier[ND];
226     if (!discriminator)
227       discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
228     disc = discriminator + 1;
229     return true;
230   }
231 
232   unsigned getLambdaId(const CXXRecordDecl *RD) {
233     assert(RD->isLambda() && "RD must be a lambda!");
234     assert(!RD->isExternallyVisible() && "RD must not be visible!");
235     assert(RD->getLambdaManglingNumber() == 0 &&
236            "RD must not have a mangling number!");
237     std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
238         Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
239     return Result.first->second;
240   }
241 
242   /// Return a character sequence that is (somewhat) unique to the TU suitable
243   /// for mangling anonymous namespaces.
244   StringRef getAnonymousNamespaceHash() const {
245     return AnonymousNamespaceHash;
246   }
247 
248 private:
249   void mangleInitFiniStub(const VarDecl *D, char CharCode, raw_ostream &Out);
250 };
251 
252 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
253 /// Microsoft Visual C++ ABI.
254 class MicrosoftCXXNameMangler {
255   MicrosoftMangleContextImpl &Context;
256   raw_ostream &Out;
257 
258   /// The "structor" is the top-level declaration being mangled, if
259   /// that's not a template specialization; otherwise it's the pattern
260   /// for that specialization.
261   const NamedDecl *Structor;
262   unsigned StructorType;
263 
264   typedef llvm::SmallVector<std::string, 10> BackRefVec;
265   BackRefVec NameBackReferences;
266 
267   typedef llvm::DenseMap<const void *, unsigned> ArgBackRefMap;
268   ArgBackRefMap TypeBackReferences;
269 
270   typedef std::set<int> PassObjectSizeArgsSet;
271   PassObjectSizeArgsSet PassObjectSizeArgs;
272 
273   ASTContext &getASTContext() const { return Context.getASTContext(); }
274 
275   // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
276   // this check into mangleQualifiers().
277   const bool PointersAre64Bit;
278 
279 public:
280   enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
281 
282   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
283       : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
284         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
285                          64) {}
286 
287   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
288                           const CXXConstructorDecl *D, CXXCtorType Type)
289       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
290         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
291                          64) {}
292 
293   MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
294                           const CXXDestructorDecl *D, CXXDtorType Type)
295       : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
296         PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
297                          64) {}
298 
299   raw_ostream &getStream() const { return Out; }
300 
301   void mangle(const NamedDecl *D, StringRef Prefix = "?");
302   void mangleName(const NamedDecl *ND);
303   void mangleFunctionEncoding(const FunctionDecl *FD, bool ShouldMangle);
304   void mangleVariableEncoding(const VarDecl *VD);
305   void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
306   void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
307                                    const CXXMethodDecl *MD);
308   void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
309                                 const MethodVFTableLocation &ML);
310   void mangleNumber(int64_t Number);
311   void mangleTagTypeKind(TagTypeKind TK);
312   void mangleArtificalTagType(TagTypeKind TK, StringRef UnqualifiedName,
313                               ArrayRef<StringRef> NestedNames = None);
314   void mangleType(QualType T, SourceRange Range,
315                   QualifierMangleMode QMM = QMM_Mangle);
316   void mangleFunctionType(const FunctionType *T,
317                           const FunctionDecl *D = nullptr,
318                           bool ForceThisQuals = false);
319   void mangleNestedName(const NamedDecl *ND);
320 
321 private:
322   bool isStructorDecl(const NamedDecl *ND) const {
323     return ND == Structor || getStructor(ND) == Structor;
324   }
325 
326   void mangleUnqualifiedName(const NamedDecl *ND) {
327     mangleUnqualifiedName(ND, ND->getDeclName());
328   }
329   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
330   void mangleSourceName(StringRef Name);
331   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
332   void mangleCXXDtorType(CXXDtorType T);
333   void mangleQualifiers(Qualifiers Quals, bool IsMember);
334   void mangleRefQualifier(RefQualifierKind RefQualifier);
335   void manglePointerCVQualifiers(Qualifiers Quals);
336   void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
337 
338   void mangleUnscopedTemplateName(const TemplateDecl *ND);
339   void
340   mangleTemplateInstantiationName(const TemplateDecl *TD,
341                                   const TemplateArgumentList &TemplateArgs);
342   void mangleObjCMethodName(const ObjCMethodDecl *MD);
343 
344   void mangleArgumentType(QualType T, SourceRange Range);
345   void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA);
346 
347   bool isArtificialTagType(QualType T) const;
348 
349   // Declare manglers for every type class.
350 #define ABSTRACT_TYPE(CLASS, PARENT)
351 #define NON_CANONICAL_TYPE(CLASS, PARENT)
352 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
353                                             Qualifiers Quals, \
354                                             SourceRange Range);
355 #include "clang/AST/TypeNodes.def"
356 #undef ABSTRACT_TYPE
357 #undef NON_CANONICAL_TYPE
358 #undef TYPE
359 
360   void mangleType(const TagDecl *TD);
361   void mangleDecayedArrayType(const ArrayType *T);
362   void mangleArrayType(const ArrayType *T);
363   void mangleFunctionClass(const FunctionDecl *FD);
364   void mangleCallingConvention(CallingConv CC);
365   void mangleCallingConvention(const FunctionType *T);
366   void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
367   void mangleExpression(const Expr *E);
368   void mangleThrowSpecification(const FunctionProtoType *T);
369 
370   void mangleTemplateArgs(const TemplateDecl *TD,
371                           const TemplateArgumentList &TemplateArgs);
372   void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
373                          const NamedDecl *Parm);
374 
375   void mangleObjCProtocol(const ObjCProtocolDecl *PD);
376   void mangleObjCLifetime(const QualType T, Qualifiers Quals,
377                           SourceRange Range);
378 };
379 }
380 
381 MicrosoftMangleContextImpl::MicrosoftMangleContextImpl(ASTContext &Context,
382                                                        DiagnosticsEngine &Diags)
383     : MicrosoftMangleContext(Context, Diags) {
384   // To mangle anonymous namespaces, hash the path to the main source file. The
385   // path should be whatever (probably relative) path was passed on the command
386   // line. The goal is for the compiler to produce the same output regardless of
387   // working directory, so use the uncanonicalized relative path.
388   //
389   // It's important to make the mangled names unique because, when CodeView
390   // debug info is in use, the debugger uses mangled type names to distinguish
391   // between otherwise identically named types in anonymous namespaces.
392   //
393   // These symbols are always internal, so there is no need for the hash to
394   // match what MSVC produces. For the same reason, clang is free to change the
395   // hash at any time without breaking compatibility with old versions of clang.
396   // The generated names are intended to look similar to what MSVC generates,
397   // which are something like "?A0x01234567@".
398   SourceManager &SM = Context.getSourceManager();
399   if (const FileEntry *FE = SM.getFileEntryForID(SM.getMainFileID())) {
400     // Truncate the hash so we get 8 characters of hexadecimal.
401     uint32_t TruncatedHash = uint32_t(xxHash64(FE->getName()));
402     AnonymousNamespaceHash = llvm::utohexstr(TruncatedHash);
403   } else {
404     // If we don't have a path to the main file, we'll just use 0.
405     AnonymousNamespaceHash = "0";
406   }
407 }
408 
409 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
410   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
411     LanguageLinkage L = FD->getLanguageLinkage();
412     // Overloadable functions need mangling.
413     if (FD->hasAttr<OverloadableAttr>())
414       return true;
415 
416     // The ABI expects that we would never mangle "typical" user-defined entry
417     // points regardless of visibility or freestanding-ness.
418     //
419     // N.B. This is distinct from asking about "main".  "main" has a lot of
420     // special rules associated with it in the standard while these
421     // user-defined entry points are outside of the purview of the standard.
422     // For example, there can be only one definition for "main" in a standards
423     // compliant program; however nothing forbids the existence of wmain and
424     // WinMain in the same translation unit.
425     if (FD->isMSVCRTEntryPoint())
426       return false;
427 
428     // C++ functions and those whose names are not a simple identifier need
429     // mangling.
430     if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
431       return true;
432 
433     // C functions are not mangled.
434     if (L == CLanguageLinkage)
435       return false;
436   }
437 
438   // Otherwise, no mangling is done outside C++ mode.
439   if (!getASTContext().getLangOpts().CPlusPlus)
440     return false;
441 
442   const VarDecl *VD = dyn_cast<VarDecl>(D);
443   if (VD && !isa<DecompositionDecl>(D)) {
444     // C variables are not mangled.
445     if (VD->isExternC())
446       return false;
447 
448     // Variables at global scope with non-internal linkage are not mangled.
449     const DeclContext *DC = getEffectiveDeclContext(D);
450     // Check for extern variable declared locally.
451     if (DC->isFunctionOrMethod() && D->hasLinkage())
452       while (!DC->isNamespace() && !DC->isTranslationUnit())
453         DC = getEffectiveParentContext(DC);
454 
455     if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
456         !isa<VarTemplateSpecializationDecl>(D) &&
457         D->getIdentifier() != nullptr)
458       return false;
459   }
460 
461   return true;
462 }
463 
464 bool
465 MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
466   return true;
467 }
468 
469 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) {
470   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
471   // Therefore it's really important that we don't decorate the
472   // name with leading underscores or leading/trailing at signs. So, by
473   // default, we emit an asm marker at the start so we get the name right.
474   // Callers can override this with a custom prefix.
475 
476   // <mangled-name> ::= ? <name> <type-encoding>
477   Out << Prefix;
478   mangleName(D);
479   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
480     mangleFunctionEncoding(FD, Context.shouldMangleDeclName(FD));
481   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
482     mangleVariableEncoding(VD);
483   else if (!isa<ObjCInterfaceDecl>(D))
484     llvm_unreachable("Tried to mangle unexpected NamedDecl!");
485 }
486 
487 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD,
488                                                      bool ShouldMangle) {
489   // <type-encoding> ::= <function-class> <function-type>
490 
491   // Since MSVC operates on the type as written and not the canonical type, it
492   // actually matters which decl we have here.  MSVC appears to choose the
493   // first, since it is most likely to be the declaration in a header file.
494   FD = FD->getFirstDecl();
495 
496   // We should never ever see a FunctionNoProtoType at this point.
497   // We don't even know how to mangle their types anyway :).
498   const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
499 
500   // extern "C" functions can hold entities that must be mangled.
501   // As it stands, these functions still need to get expressed in the full
502   // external name.  They have their class and type omitted, replaced with '9'.
503   if (ShouldMangle) {
504     // We would like to mangle all extern "C" functions using this additional
505     // component but this would break compatibility with MSVC's behavior.
506     // Instead, do this when we know that compatibility isn't important (in
507     // other words, when it is an overloaded extern "C" function).
508     if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
509       Out << "$$J0";
510 
511     mangleFunctionClass(FD);
512 
513     mangleFunctionType(FT, FD);
514   } else {
515     Out << '9';
516   }
517 }
518 
519 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
520   // <type-encoding> ::= <storage-class> <variable-type>
521   // <storage-class> ::= 0  # private static member
522   //                 ::= 1  # protected static member
523   //                 ::= 2  # public static member
524   //                 ::= 3  # global
525   //                 ::= 4  # static local
526 
527   // The first character in the encoding (after the name) is the storage class.
528   if (VD->isStaticDataMember()) {
529     // If it's a static member, it also encodes the access level.
530     switch (VD->getAccess()) {
531       default:
532       case AS_private: Out << '0'; break;
533       case AS_protected: Out << '1'; break;
534       case AS_public: Out << '2'; break;
535     }
536   }
537   else if (!VD->isStaticLocal())
538     Out << '3';
539   else
540     Out << '4';
541   // Now mangle the type.
542   // <variable-type> ::= <type> <cvr-qualifiers>
543   //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
544   // Pointers and references are odd. The type of 'int * const foo;' gets
545   // mangled as 'QAHA' instead of 'PAHB', for example.
546   SourceRange SR = VD->getSourceRange();
547   QualType Ty = VD->getType();
548   if (Ty->isPointerType() || Ty->isReferenceType() ||
549       Ty->isMemberPointerType()) {
550     mangleType(Ty, SR, QMM_Drop);
551     manglePointerExtQualifiers(
552         Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
553     if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
554       mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
555       // Member pointers are suffixed with a back reference to the member
556       // pointer's class name.
557       mangleName(MPT->getClass()->getAsCXXRecordDecl());
558     } else
559       mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
560   } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
561     // Global arrays are funny, too.
562     mangleDecayedArrayType(AT);
563     if (AT->getElementType()->isArrayType())
564       Out << 'A';
565     else
566       mangleQualifiers(Ty.getQualifiers(), false);
567   } else {
568     mangleType(Ty, SR, QMM_Drop);
569     mangleQualifiers(Ty.getQualifiers(), false);
570   }
571 }
572 
573 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
574                                                       const ValueDecl *VD) {
575   // <member-data-pointer> ::= <integer-literal>
576   //                       ::= $F <number> <number>
577   //                       ::= $G <number> <number> <number>
578 
579   int64_t FieldOffset;
580   int64_t VBTableOffset;
581   MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
582   if (VD) {
583     FieldOffset = getASTContext().getFieldOffset(VD);
584     assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
585            "cannot take address of bitfield");
586     FieldOffset /= getASTContext().getCharWidth();
587 
588     VBTableOffset = 0;
589 
590     if (IM == MSInheritanceAttr::Keyword_virtual_inheritance)
591       FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
592   } else {
593     FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
594 
595     VBTableOffset = -1;
596   }
597 
598   char Code = '\0';
599   switch (IM) {
600   case MSInheritanceAttr::Keyword_single_inheritance:      Code = '0'; break;
601   case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = '0'; break;
602   case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'F'; break;
603   case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
604   }
605 
606   Out << '$' << Code;
607 
608   mangleNumber(FieldOffset);
609 
610   // The C++ standard doesn't allow base-to-derived member pointer conversions
611   // in template parameter contexts, so the vbptr offset of data member pointers
612   // is always zero.
613   if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
614     mangleNumber(0);
615   if (MSInheritanceAttr::hasVBTableOffsetField(IM))
616     mangleNumber(VBTableOffset);
617 }
618 
619 void
620 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
621                                                      const CXXMethodDecl *MD) {
622   // <member-function-pointer> ::= $1? <name>
623   //                           ::= $H? <name> <number>
624   //                           ::= $I? <name> <number> <number>
625   //                           ::= $J? <name> <number> <number> <number>
626 
627   MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
628 
629   char Code = '\0';
630   switch (IM) {
631   case MSInheritanceAttr::Keyword_single_inheritance:      Code = '1'; break;
632   case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = 'H'; break;
633   case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'I'; break;
634   case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
635   }
636 
637   // If non-virtual, mangle the name.  If virtual, mangle as a virtual memptr
638   // thunk.
639   uint64_t NVOffset = 0;
640   uint64_t VBTableOffset = 0;
641   uint64_t VBPtrOffset = 0;
642   if (MD) {
643     Out << '$' << Code << '?';
644     if (MD->isVirtual()) {
645       MicrosoftVTableContext *VTContext =
646           cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
647       MethodVFTableLocation ML =
648           VTContext->getMethodVFTableLocation(GlobalDecl(MD));
649       mangleVirtualMemPtrThunk(MD, ML);
650       NVOffset = ML.VFPtrOffset.getQuantity();
651       VBTableOffset = ML.VBTableIndex * 4;
652       if (ML.VBase) {
653         const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
654         VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
655       }
656     } else {
657       mangleName(MD);
658       mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
659     }
660 
661     if (VBTableOffset == 0 &&
662         IM == MSInheritanceAttr::Keyword_virtual_inheritance)
663       NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
664   } else {
665     // Null single inheritance member functions are encoded as a simple nullptr.
666     if (IM == MSInheritanceAttr::Keyword_single_inheritance) {
667       Out << "$0A@";
668       return;
669     }
670     if (IM == MSInheritanceAttr::Keyword_unspecified_inheritance)
671       VBTableOffset = -1;
672     Out << '$' << Code;
673   }
674 
675   if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
676     mangleNumber(static_cast<uint32_t>(NVOffset));
677   if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
678     mangleNumber(VBPtrOffset);
679   if (MSInheritanceAttr::hasVBTableOffsetField(IM))
680     mangleNumber(VBTableOffset);
681 }
682 
683 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
684     const CXXMethodDecl *MD, const MethodVFTableLocation &ML) {
685   // Get the vftable offset.
686   CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
687       getASTContext().getTargetInfo().getPointerWidth(0));
688   uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
689 
690   Out << "?_9";
691   mangleName(MD->getParent());
692   Out << "$B";
693   mangleNumber(OffsetInVFTable);
694   Out << 'A';
695   mangleCallingConvention(MD->getType()->getAs<FunctionProtoType>());
696 }
697 
698 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
699   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
700 
701   // Always start with the unqualified name.
702   mangleUnqualifiedName(ND);
703 
704   mangleNestedName(ND);
705 
706   // Terminate the whole name with an '@'.
707   Out << '@';
708 }
709 
710 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
711   // <non-negative integer> ::= A@              # when Number == 0
712   //                        ::= <decimal digit> # when 1 <= Number <= 10
713   //                        ::= <hex digit>+ @  # when Number >= 10
714   //
715   // <number>               ::= [?] <non-negative integer>
716 
717   uint64_t Value = static_cast<uint64_t>(Number);
718   if (Number < 0) {
719     Value = -Value;
720     Out << '?';
721   }
722 
723   if (Value == 0)
724     Out << "A@";
725   else if (Value >= 1 && Value <= 10)
726     Out << (Value - 1);
727   else {
728     // Numbers that are not encoded as decimal digits are represented as nibbles
729     // in the range of ASCII characters 'A' to 'P'.
730     // The number 0x123450 would be encoded as 'BCDEFA'
731     char EncodedNumberBuffer[sizeof(uint64_t) * 2];
732     MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
733     MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
734     for (; Value != 0; Value >>= 4)
735       *I++ = 'A' + (Value & 0xf);
736     Out.write(I.base(), I - BufferRef.rbegin());
737     Out << '@';
738   }
739 }
740 
741 static const TemplateDecl *
742 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
743   // Check if we have a function template.
744   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
745     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
746       TemplateArgs = FD->getTemplateSpecializationArgs();
747       return TD;
748     }
749   }
750 
751   // Check if we have a class template.
752   if (const ClassTemplateSpecializationDecl *Spec =
753           dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
754     TemplateArgs = &Spec->getTemplateArgs();
755     return Spec->getSpecializedTemplate();
756   }
757 
758   // Check if we have a variable template.
759   if (const VarTemplateSpecializationDecl *Spec =
760           dyn_cast<VarTemplateSpecializationDecl>(ND)) {
761     TemplateArgs = &Spec->getTemplateArgs();
762     return Spec->getSpecializedTemplate();
763   }
764 
765   return nullptr;
766 }
767 
768 void MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
769                                                     DeclarationName Name) {
770   //  <unqualified-name> ::= <operator-name>
771   //                     ::= <ctor-dtor-name>
772   //                     ::= <source-name>
773   //                     ::= <template-name>
774 
775   // Check if we have a template.
776   const TemplateArgumentList *TemplateArgs = nullptr;
777   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
778     // Function templates aren't considered for name back referencing.  This
779     // makes sense since function templates aren't likely to occur multiple
780     // times in a symbol.
781     if (isa<FunctionTemplateDecl>(TD)) {
782       mangleTemplateInstantiationName(TD, *TemplateArgs);
783       Out << '@';
784       return;
785     }
786 
787     // Here comes the tricky thing: if we need to mangle something like
788     //   void foo(A::X<Y>, B::X<Y>),
789     // the X<Y> part is aliased. However, if you need to mangle
790     //   void foo(A::X<A::Y>, A::X<B::Y>),
791     // the A::X<> part is not aliased.
792     // That said, from the mangler's perspective we have a structure like this:
793     //   namespace[s] -> type[ -> template-parameters]
794     // but from the Clang perspective we have
795     //   type [ -> template-parameters]
796     //      \-> namespace[s]
797     // What we do is we create a new mangler, mangle the same type (without
798     // a namespace suffix) to a string using the extra mangler and then use
799     // the mangled type name as a key to check the mangling of different types
800     // for aliasing.
801 
802     llvm::SmallString<64> TemplateMangling;
803     llvm::raw_svector_ostream Stream(TemplateMangling);
804     MicrosoftCXXNameMangler Extra(Context, Stream);
805     Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
806 
807     mangleSourceName(TemplateMangling);
808     return;
809   }
810 
811   switch (Name.getNameKind()) {
812     case DeclarationName::Identifier: {
813       if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
814         mangleSourceName(II->getName());
815         break;
816       }
817 
818       // Otherwise, an anonymous entity.  We must have a declaration.
819       assert(ND && "mangling empty name without declaration");
820 
821       if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
822         if (NS->isAnonymousNamespace()) {
823           Out << "?A0x" << Context.getAnonymousNamespaceHash() << '@';
824           break;
825         }
826       }
827 
828       if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(ND)) {
829         // FIXME: Invented mangling for decomposition declarations:
830         //   [X,Y,Z]
831         // where X,Y,Z are the names of the bindings.
832         llvm::SmallString<128> Name("[");
833         for (auto *BD : DD->bindings()) {
834           if (Name.size() > 1)
835             Name += ',';
836           Name += BD->getDeclName().getAsIdentifierInfo()->getName();
837         }
838         Name += ']';
839         mangleSourceName(Name);
840         break;
841       }
842 
843       if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
844         // We must have an anonymous union or struct declaration.
845         const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
846         assert(RD && "expected variable decl to have a record type");
847         // Anonymous types with no tag or typedef get the name of their
848         // declarator mangled in.  If they have no declarator, number them with
849         // a $S prefix.
850         llvm::SmallString<64> Name("$S");
851         // Get a unique id for the anonymous struct.
852         Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
853         mangleSourceName(Name.str());
854         break;
855       }
856 
857       // We must have an anonymous struct.
858       const TagDecl *TD = cast<TagDecl>(ND);
859       if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
860         assert(TD->getDeclContext() == D->getDeclContext() &&
861                "Typedef should not be in another decl context!");
862         assert(D->getDeclName().getAsIdentifierInfo() &&
863                "Typedef was not named!");
864         mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
865         break;
866       }
867 
868       if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
869         if (Record->isLambda()) {
870           llvm::SmallString<10> Name("<lambda_");
871 
872           Decl *LambdaContextDecl = Record->getLambdaContextDecl();
873           unsigned LambdaManglingNumber = Record->getLambdaManglingNumber();
874           unsigned LambdaId;
875           const ParmVarDecl *Parm =
876               dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
877           const FunctionDecl *Func =
878               Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
879 
880           if (Func) {
881             unsigned DefaultArgNo =
882                 Func->getNumParams() - Parm->getFunctionScopeIndex();
883             Name += llvm::utostr(DefaultArgNo);
884             Name += "_";
885           }
886 
887           if (LambdaManglingNumber)
888             LambdaId = LambdaManglingNumber;
889           else
890             LambdaId = Context.getLambdaId(Record);
891 
892           Name += llvm::utostr(LambdaId);
893           Name += ">";
894 
895           mangleSourceName(Name);
896 
897           // If the context of a closure type is an initializer for a class
898           // member (static or nonstatic), it is encoded in a qualified name.
899           if (LambdaManglingNumber && LambdaContextDecl) {
900             if ((isa<VarDecl>(LambdaContextDecl) ||
901                  isa<FieldDecl>(LambdaContextDecl)) &&
902                 LambdaContextDecl->getDeclContext()->isRecord()) {
903               mangleUnqualifiedName(cast<NamedDecl>(LambdaContextDecl));
904             }
905           }
906           break;
907         }
908       }
909 
910       llvm::SmallString<64> Name;
911       if (DeclaratorDecl *DD =
912               Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) {
913         // Anonymous types without a name for linkage purposes have their
914         // declarator mangled in if they have one.
915         Name += "<unnamed-type-";
916         Name += DD->getName();
917       } else if (TypedefNameDecl *TND =
918                      Context.getASTContext().getTypedefNameForUnnamedTagDecl(
919                          TD)) {
920         // Anonymous types without a name for linkage purposes have their
921         // associate typedef mangled in if they have one.
922         Name += "<unnamed-type-";
923         Name += TND->getName();
924       } else if (isa<EnumDecl>(TD) &&
925                  cast<EnumDecl>(TD)->enumerator_begin() !=
926                      cast<EnumDecl>(TD)->enumerator_end()) {
927         // Anonymous non-empty enums mangle in the first enumerator.
928         auto *ED = cast<EnumDecl>(TD);
929         Name += "<unnamed-enum-";
930         Name += ED->enumerator_begin()->getName();
931       } else {
932         // Otherwise, number the types using a $S prefix.
933         Name += "<unnamed-type-$S";
934         Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1);
935       }
936       Name += ">";
937       mangleSourceName(Name.str());
938       break;
939     }
940 
941     case DeclarationName::ObjCZeroArgSelector:
942     case DeclarationName::ObjCOneArgSelector:
943     case DeclarationName::ObjCMultiArgSelector: {
944       // This is reachable only when constructing an outlined SEH finally
945       // block.  Nothing depends on this mangling and it's used only with
946       // functinos with internal linkage.
947       llvm::SmallString<64> Name;
948       mangleSourceName(Name.str());
949       break;
950     }
951 
952     case DeclarationName::CXXConstructorName:
953       if (isStructorDecl(ND)) {
954         if (StructorType == Ctor_CopyingClosure) {
955           Out << "?_O";
956           return;
957         }
958         if (StructorType == Ctor_DefaultClosure) {
959           Out << "?_F";
960           return;
961         }
962       }
963       Out << "?0";
964       return;
965 
966     case DeclarationName::CXXDestructorName:
967       if (isStructorDecl(ND))
968         // If the named decl is the C++ destructor we're mangling,
969         // use the type we were given.
970         mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
971       else
972         // Otherwise, use the base destructor name. This is relevant if a
973         // class with a destructor is declared within a destructor.
974         mangleCXXDtorType(Dtor_Base);
975       break;
976 
977     case DeclarationName::CXXConversionFunctionName:
978       // <operator-name> ::= ?B # (cast)
979       // The target type is encoded as the return type.
980       Out << "?B";
981       break;
982 
983     case DeclarationName::CXXOperatorName:
984       mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
985       break;
986 
987     case DeclarationName::CXXLiteralOperatorName: {
988       Out << "?__K";
989       mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
990       break;
991     }
992 
993     case DeclarationName::CXXDeductionGuideName:
994       llvm_unreachable("Can't mangle a deduction guide name!");
995 
996     case DeclarationName::CXXUsingDirective:
997       llvm_unreachable("Can't mangle a using directive name!");
998   }
999 }
1000 
1001 // <postfix> ::= <unqualified-name> [<postfix>]
1002 //           ::= <substitution> [<postfix>]
1003 void MicrosoftCXXNameMangler::mangleNestedName(const NamedDecl *ND) {
1004   const DeclContext *DC = getEffectiveDeclContext(ND);
1005   while (!DC->isTranslationUnit()) {
1006     if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
1007       unsigned Disc;
1008       if (Context.getNextDiscriminator(ND, Disc)) {
1009         Out << '?';
1010         mangleNumber(Disc);
1011         Out << '?';
1012       }
1013     }
1014 
1015     if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
1016       auto Discriminate =
1017           [](StringRef Name, const unsigned Discriminator,
1018              const unsigned ParameterDiscriminator) -> std::string {
1019         std::string Buffer;
1020         llvm::raw_string_ostream Stream(Buffer);
1021         Stream << Name;
1022         if (Discriminator)
1023           Stream << '_' << Discriminator;
1024         if (ParameterDiscriminator)
1025           Stream << '_' << ParameterDiscriminator;
1026         return Stream.str();
1027       };
1028 
1029       unsigned Discriminator = BD->getBlockManglingNumber();
1030       if (!Discriminator)
1031         Discriminator = Context.getBlockId(BD, /*Local=*/false);
1032 
1033       // Mangle the parameter position as a discriminator to deal with unnamed
1034       // parameters.  Rather than mangling the unqualified parameter name,
1035       // always use the position to give a uniform mangling.
1036       unsigned ParameterDiscriminator = 0;
1037       if (const auto *MC = BD->getBlockManglingContextDecl())
1038         if (const auto *P = dyn_cast<ParmVarDecl>(MC))
1039           if (const auto *F = dyn_cast<FunctionDecl>(P->getDeclContext()))
1040             ParameterDiscriminator =
1041                 F->getNumParams() - P->getFunctionScopeIndex();
1042 
1043       DC = getEffectiveDeclContext(BD);
1044 
1045       Out << '?';
1046       mangleSourceName(Discriminate("_block_invoke", Discriminator,
1047                                     ParameterDiscriminator));
1048       // If we have a block mangling context, encode that now.  This allows us
1049       // to discriminate between named static data initializers in the same
1050       // scope.  This is handled differently from parameters, which use
1051       // positions to discriminate between multiple instances.
1052       if (const auto *MC = BD->getBlockManglingContextDecl())
1053         if (!isa<ParmVarDecl>(MC))
1054           if (const auto *ND = dyn_cast<NamedDecl>(MC))
1055             mangleUnqualifiedName(ND);
1056       // MS ABI and Itanium manglings are in inverted scopes.  In the case of a
1057       // RecordDecl, mangle the entire scope hierarchy at this point rather than
1058       // just the unqualified name to get the ordering correct.
1059       if (const auto *RD = dyn_cast<RecordDecl>(DC))
1060         mangleName(RD);
1061       else
1062         Out << '@';
1063       // void __cdecl
1064       Out << "YAX";
1065       // struct __block_literal *
1066       Out << 'P';
1067       // __ptr64
1068       if (PointersAre64Bit)
1069         Out << 'E';
1070       Out << 'A';
1071       mangleArtificalTagType(TTK_Struct,
1072                              Discriminate("__block_literal", Discriminator,
1073                                           ParameterDiscriminator));
1074       Out << "@Z";
1075 
1076       // If the effective context was a Record, we have fully mangled the
1077       // qualified name and do not need to continue.
1078       if (isa<RecordDecl>(DC))
1079         break;
1080       continue;
1081     } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
1082       mangleObjCMethodName(Method);
1083     } else if (isa<NamedDecl>(DC)) {
1084       ND = cast<NamedDecl>(DC);
1085       if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1086         mangle(FD, "?");
1087         break;
1088       } else {
1089         mangleUnqualifiedName(ND);
1090         // Lambdas in default arguments conceptually belong to the function the
1091         // parameter corresponds to.
1092         if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(ND)) {
1093           DC = LDADC;
1094           continue;
1095         }
1096       }
1097     }
1098     DC = DC->getParent();
1099   }
1100 }
1101 
1102 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
1103   // Microsoft uses the names on the case labels for these dtor variants.  Clang
1104   // uses the Itanium terminology internally.  Everything in this ABI delegates
1105   // towards the base dtor.
1106   switch (T) {
1107   // <operator-name> ::= ?1  # destructor
1108   case Dtor_Base: Out << "?1"; return;
1109   // <operator-name> ::= ?_D # vbase destructor
1110   case Dtor_Complete: Out << "?_D"; return;
1111   // <operator-name> ::= ?_G # scalar deleting destructor
1112   case Dtor_Deleting: Out << "?_G"; return;
1113   // <operator-name> ::= ?_E # vector deleting destructor
1114   // FIXME: Add a vector deleting dtor type.  It goes in the vtable, so we need
1115   // it.
1116   case Dtor_Comdat:
1117     llvm_unreachable("not expecting a COMDAT");
1118   }
1119   llvm_unreachable("Unsupported dtor type?");
1120 }
1121 
1122 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
1123                                                  SourceLocation Loc) {
1124   switch (OO) {
1125   //                     ?0 # constructor
1126   //                     ?1 # destructor
1127   // <operator-name> ::= ?2 # new
1128   case OO_New: Out << "?2"; break;
1129   // <operator-name> ::= ?3 # delete
1130   case OO_Delete: Out << "?3"; break;
1131   // <operator-name> ::= ?4 # =
1132   case OO_Equal: Out << "?4"; break;
1133   // <operator-name> ::= ?5 # >>
1134   case OO_GreaterGreater: Out << "?5"; break;
1135   // <operator-name> ::= ?6 # <<
1136   case OO_LessLess: Out << "?6"; break;
1137   // <operator-name> ::= ?7 # !
1138   case OO_Exclaim: Out << "?7"; break;
1139   // <operator-name> ::= ?8 # ==
1140   case OO_EqualEqual: Out << "?8"; break;
1141   // <operator-name> ::= ?9 # !=
1142   case OO_ExclaimEqual: Out << "?9"; break;
1143   // <operator-name> ::= ?A # []
1144   case OO_Subscript: Out << "?A"; break;
1145   //                     ?B # conversion
1146   // <operator-name> ::= ?C # ->
1147   case OO_Arrow: Out << "?C"; break;
1148   // <operator-name> ::= ?D # *
1149   case OO_Star: Out << "?D"; break;
1150   // <operator-name> ::= ?E # ++
1151   case OO_PlusPlus: Out << "?E"; break;
1152   // <operator-name> ::= ?F # --
1153   case OO_MinusMinus: Out << "?F"; break;
1154   // <operator-name> ::= ?G # -
1155   case OO_Minus: Out << "?G"; break;
1156   // <operator-name> ::= ?H # +
1157   case OO_Plus: Out << "?H"; break;
1158   // <operator-name> ::= ?I # &
1159   case OO_Amp: Out << "?I"; break;
1160   // <operator-name> ::= ?J # ->*
1161   case OO_ArrowStar: Out << "?J"; break;
1162   // <operator-name> ::= ?K # /
1163   case OO_Slash: Out << "?K"; break;
1164   // <operator-name> ::= ?L # %
1165   case OO_Percent: Out << "?L"; break;
1166   // <operator-name> ::= ?M # <
1167   case OO_Less: Out << "?M"; break;
1168   // <operator-name> ::= ?N # <=
1169   case OO_LessEqual: Out << "?N"; break;
1170   // <operator-name> ::= ?O # >
1171   case OO_Greater: Out << "?O"; break;
1172   // <operator-name> ::= ?P # >=
1173   case OO_GreaterEqual: Out << "?P"; break;
1174   // <operator-name> ::= ?Q # ,
1175   case OO_Comma: Out << "?Q"; break;
1176   // <operator-name> ::= ?R # ()
1177   case OO_Call: Out << "?R"; break;
1178   // <operator-name> ::= ?S # ~
1179   case OO_Tilde: Out << "?S"; break;
1180   // <operator-name> ::= ?T # ^
1181   case OO_Caret: Out << "?T"; break;
1182   // <operator-name> ::= ?U # |
1183   case OO_Pipe: Out << "?U"; break;
1184   // <operator-name> ::= ?V # &&
1185   case OO_AmpAmp: Out << "?V"; break;
1186   // <operator-name> ::= ?W # ||
1187   case OO_PipePipe: Out << "?W"; break;
1188   // <operator-name> ::= ?X # *=
1189   case OO_StarEqual: Out << "?X"; break;
1190   // <operator-name> ::= ?Y # +=
1191   case OO_PlusEqual: Out << "?Y"; break;
1192   // <operator-name> ::= ?Z # -=
1193   case OO_MinusEqual: Out << "?Z"; break;
1194   // <operator-name> ::= ?_0 # /=
1195   case OO_SlashEqual: Out << "?_0"; break;
1196   // <operator-name> ::= ?_1 # %=
1197   case OO_PercentEqual: Out << "?_1"; break;
1198   // <operator-name> ::= ?_2 # >>=
1199   case OO_GreaterGreaterEqual: Out << "?_2"; break;
1200   // <operator-name> ::= ?_3 # <<=
1201   case OO_LessLessEqual: Out << "?_3"; break;
1202   // <operator-name> ::= ?_4 # &=
1203   case OO_AmpEqual: Out << "?_4"; break;
1204   // <operator-name> ::= ?_5 # |=
1205   case OO_PipeEqual: Out << "?_5"; break;
1206   // <operator-name> ::= ?_6 # ^=
1207   case OO_CaretEqual: Out << "?_6"; break;
1208   //                     ?_7 # vftable
1209   //                     ?_8 # vbtable
1210   //                     ?_9 # vcall
1211   //                     ?_A # typeof
1212   //                     ?_B # local static guard
1213   //                     ?_C # string
1214   //                     ?_D # vbase destructor
1215   //                     ?_E # vector deleting destructor
1216   //                     ?_F # default constructor closure
1217   //                     ?_G # scalar deleting destructor
1218   //                     ?_H # vector constructor iterator
1219   //                     ?_I # vector destructor iterator
1220   //                     ?_J # vector vbase constructor iterator
1221   //                     ?_K # virtual displacement map
1222   //                     ?_L # eh vector constructor iterator
1223   //                     ?_M # eh vector destructor iterator
1224   //                     ?_N # eh vector vbase constructor iterator
1225   //                     ?_O # copy constructor closure
1226   //                     ?_P<name> # udt returning <name>
1227   //                     ?_Q # <unknown>
1228   //                     ?_R0 # RTTI Type Descriptor
1229   //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1230   //                     ?_R2 # RTTI Base Class Array
1231   //                     ?_R3 # RTTI Class Hierarchy Descriptor
1232   //                     ?_R4 # RTTI Complete Object Locator
1233   //                     ?_S # local vftable
1234   //                     ?_T # local vftable constructor closure
1235   // <operator-name> ::= ?_U # new[]
1236   case OO_Array_New: Out << "?_U"; break;
1237   // <operator-name> ::= ?_V # delete[]
1238   case OO_Array_Delete: Out << "?_V"; break;
1239   // <operator-name> ::= ?__L # co_await
1240   case OO_Coawait: Out << "?__L"; break;
1241 
1242   case OO_Spaceship: {
1243     // FIXME: Once MS picks a mangling, use it.
1244     DiagnosticsEngine &Diags = Context.getDiags();
1245     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1246       "cannot mangle this three-way comparison operator yet");
1247     Diags.Report(Loc, DiagID);
1248     break;
1249   }
1250 
1251   case OO_Conditional: {
1252     DiagnosticsEngine &Diags = Context.getDiags();
1253     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1254       "cannot mangle this conditional operator yet");
1255     Diags.Report(Loc, DiagID);
1256     break;
1257   }
1258 
1259   case OO_None:
1260   case NUM_OVERLOADED_OPERATORS:
1261     llvm_unreachable("Not an overloaded operator");
1262   }
1263 }
1264 
1265 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1266   // <source name> ::= <identifier> @
1267   BackRefVec::iterator Found =
1268       std::find(NameBackReferences.begin(), NameBackReferences.end(), Name);
1269   if (Found == NameBackReferences.end()) {
1270     if (NameBackReferences.size() < 10)
1271       NameBackReferences.push_back(Name);
1272     Out << Name << '@';
1273   } else {
1274     Out << (Found - NameBackReferences.begin());
1275   }
1276 }
1277 
1278 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1279   Context.mangleObjCMethodName(MD, Out);
1280 }
1281 
1282 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1283     const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1284   // <template-name> ::= <unscoped-template-name> <template-args>
1285   //                 ::= <substitution>
1286   // Always start with the unqualified name.
1287 
1288   // Templates have their own context for back references.
1289   ArgBackRefMap OuterArgsContext;
1290   BackRefVec OuterTemplateContext;
1291   PassObjectSizeArgsSet OuterPassObjectSizeArgs;
1292   NameBackReferences.swap(OuterTemplateContext);
1293   TypeBackReferences.swap(OuterArgsContext);
1294   PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1295 
1296   mangleUnscopedTemplateName(TD);
1297   mangleTemplateArgs(TD, TemplateArgs);
1298 
1299   // Restore the previous back reference contexts.
1300   NameBackReferences.swap(OuterTemplateContext);
1301   TypeBackReferences.swap(OuterArgsContext);
1302   PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1303 }
1304 
1305 void
1306 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
1307   // <unscoped-template-name> ::= ?$ <unqualified-name>
1308   Out << "?$";
1309   mangleUnqualifiedName(TD);
1310 }
1311 
1312 void MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1313                                                    bool IsBoolean) {
1314   // <integer-literal> ::= $0 <number>
1315   Out << "$0";
1316   // Make sure booleans are encoded as 0/1.
1317   if (IsBoolean && Value.getBoolValue())
1318     mangleNumber(1);
1319   else if (Value.isSigned())
1320     mangleNumber(Value.getSExtValue());
1321   else
1322     mangleNumber(Value.getZExtValue());
1323 }
1324 
1325 void MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1326   // See if this is a constant expression.
1327   llvm::APSInt Value;
1328   if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1329     mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1330     return;
1331   }
1332 
1333   // Look through no-op casts like template parameter substitutions.
1334   E = E->IgnoreParenNoopCasts(Context.getASTContext());
1335 
1336   const CXXUuidofExpr *UE = nullptr;
1337   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1338     if (UO->getOpcode() == UO_AddrOf)
1339       UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1340   } else
1341     UE = dyn_cast<CXXUuidofExpr>(E);
1342 
1343   if (UE) {
1344     // If we had to peek through an address-of operator, treat this like we are
1345     // dealing with a pointer type.  Otherwise, treat it like a const reference.
1346     //
1347     // N.B. This matches up with the handling of TemplateArgument::Declaration
1348     // in mangleTemplateArg
1349     if (UE == E)
1350       Out << "$E?";
1351     else
1352       Out << "$1?";
1353 
1354     // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1355     // const __s_GUID _GUID_{lower case UUID with underscores}
1356     StringRef Uuid = UE->getUuidStr();
1357     std::string Name = "_GUID_" + Uuid.lower();
1358     std::replace(Name.begin(), Name.end(), '-', '_');
1359 
1360     mangleSourceName(Name);
1361     // Terminate the whole name with an '@'.
1362     Out << '@';
1363     // It's a global variable.
1364     Out << '3';
1365     // It's a struct called __s_GUID.
1366     mangleArtificalTagType(TTK_Struct, "__s_GUID");
1367     // It's const.
1368     Out << 'B';
1369     return;
1370   }
1371 
1372   // As bad as this diagnostic is, it's better than crashing.
1373   DiagnosticsEngine &Diags = Context.getDiags();
1374   unsigned DiagID = Diags.getCustomDiagID(
1375       DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1376   Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1377                                         << E->getSourceRange();
1378 }
1379 
1380 void MicrosoftCXXNameMangler::mangleTemplateArgs(
1381     const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1382   // <template-args> ::= <template-arg>+
1383   const TemplateParameterList *TPL = TD->getTemplateParameters();
1384   assert(TPL->size() == TemplateArgs.size() &&
1385          "size mismatch between args and parms!");
1386 
1387   for (size_t i = 0; i < TemplateArgs.size(); ++i) {
1388     const TemplateArgument &TA = TemplateArgs[i];
1389 
1390     // Separate consecutive packs by $$Z.
1391     if (i > 0 && TA.getKind() == TemplateArgument::Pack &&
1392         TemplateArgs[i - 1].getKind() == TemplateArgument::Pack)
1393       Out << "$$Z";
1394 
1395     mangleTemplateArg(TD, TA, TPL->getParam(i));
1396   }
1397 }
1398 
1399 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1400                                                 const TemplateArgument &TA,
1401                                                 const NamedDecl *Parm) {
1402   // <template-arg> ::= <type>
1403   //                ::= <integer-literal>
1404   //                ::= <member-data-pointer>
1405   //                ::= <member-function-pointer>
1406   //                ::= $E? <name> <type-encoding>
1407   //                ::= $1? <name> <type-encoding>
1408   //                ::= $0A@
1409   //                ::= <template-args>
1410 
1411   switch (TA.getKind()) {
1412   case TemplateArgument::Null:
1413     llvm_unreachable("Can't mangle null template arguments!");
1414   case TemplateArgument::TemplateExpansion:
1415     llvm_unreachable("Can't mangle template expansion arguments!");
1416   case TemplateArgument::Type: {
1417     QualType T = TA.getAsType();
1418     mangleType(T, SourceRange(), QMM_Escape);
1419     break;
1420   }
1421   case TemplateArgument::Declaration: {
1422     const NamedDecl *ND = TA.getAsDecl();
1423     if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1424       mangleMemberDataPointer(cast<CXXRecordDecl>(ND->getDeclContext())
1425                                   ->getMostRecentNonInjectedDecl(),
1426                               cast<ValueDecl>(ND));
1427     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1428       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1429       if (MD && MD->isInstance()) {
1430         mangleMemberFunctionPointer(
1431             MD->getParent()->getMostRecentNonInjectedDecl(), MD);
1432       } else {
1433         Out << "$1?";
1434         mangleName(FD);
1435         mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1436       }
1437     } else {
1438       mangle(ND, TA.getParamTypeForDecl()->isReferenceType() ? "$E?" : "$1?");
1439     }
1440     break;
1441   }
1442   case TemplateArgument::Integral:
1443     mangleIntegerLiteral(TA.getAsIntegral(),
1444                          TA.getIntegralType()->isBooleanType());
1445     break;
1446   case TemplateArgument::NullPtr: {
1447     QualType T = TA.getNullPtrType();
1448     if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1449       const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1450       if (MPT->isMemberFunctionPointerType() &&
1451           !isa<FunctionTemplateDecl>(TD)) {
1452         mangleMemberFunctionPointer(RD, nullptr);
1453         return;
1454       }
1455       if (MPT->isMemberDataPointer()) {
1456         if (!isa<FunctionTemplateDecl>(TD)) {
1457           mangleMemberDataPointer(RD, nullptr);
1458           return;
1459         }
1460         // nullptr data pointers are always represented with a single field
1461         // which is initialized with either 0 or -1.  Why -1?  Well, we need to
1462         // distinguish the case where the data member is at offset zero in the
1463         // record.
1464         // However, we are free to use 0 *if* we would use multiple fields for
1465         // non-nullptr member pointers.
1466         if (!RD->nullFieldOffsetIsZero()) {
1467           mangleIntegerLiteral(llvm::APSInt::get(-1), /*IsBoolean=*/false);
1468           return;
1469         }
1470       }
1471     }
1472     mangleIntegerLiteral(llvm::APSInt::getUnsigned(0), /*IsBoolean=*/false);
1473     break;
1474   }
1475   case TemplateArgument::Expression:
1476     mangleExpression(TA.getAsExpr());
1477     break;
1478   case TemplateArgument::Pack: {
1479     ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1480     if (TemplateArgs.empty()) {
1481       if (isa<TemplateTypeParmDecl>(Parm) ||
1482           isa<TemplateTemplateParmDecl>(Parm))
1483         // MSVC 2015 changed the mangling for empty expanded template packs,
1484         // use the old mangling for link compatibility for old versions.
1485         Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1486                     LangOptions::MSVC2015)
1487                     ? "$$V"
1488                     : "$$$V");
1489       else if (isa<NonTypeTemplateParmDecl>(Parm))
1490         Out << "$S";
1491       else
1492         llvm_unreachable("unexpected template parameter decl!");
1493     } else {
1494       for (const TemplateArgument &PA : TemplateArgs)
1495         mangleTemplateArg(TD, PA, Parm);
1496     }
1497     break;
1498   }
1499   case TemplateArgument::Template: {
1500     const NamedDecl *ND =
1501         TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1502     if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1503       mangleType(TD);
1504     } else if (isa<TypeAliasDecl>(ND)) {
1505       Out << "$$Y";
1506       mangleName(ND);
1507     } else {
1508       llvm_unreachable("unexpected template template NamedDecl!");
1509     }
1510     break;
1511   }
1512   }
1513 }
1514 
1515 void MicrosoftCXXNameMangler::mangleObjCProtocol(const ObjCProtocolDecl *PD) {
1516   llvm::SmallString<64> TemplateMangling;
1517   llvm::raw_svector_ostream Stream(TemplateMangling);
1518   MicrosoftCXXNameMangler Extra(Context, Stream);
1519 
1520   Stream << "?$";
1521   Extra.mangleSourceName("Protocol");
1522   Extra.mangleArtificalTagType(TTK_Struct, PD->getName());
1523 
1524   mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1525 }
1526 
1527 void MicrosoftCXXNameMangler::mangleObjCLifetime(const QualType Type,
1528                                                  Qualifiers Quals,
1529                                                  SourceRange Range) {
1530   llvm::SmallString<64> TemplateMangling;
1531   llvm::raw_svector_ostream Stream(TemplateMangling);
1532   MicrosoftCXXNameMangler Extra(Context, Stream);
1533 
1534   Stream << "?$";
1535   switch (Quals.getObjCLifetime()) {
1536   case Qualifiers::OCL_None:
1537   case Qualifiers::OCL_ExplicitNone:
1538     break;
1539   case Qualifiers::OCL_Autoreleasing:
1540     Extra.mangleSourceName("Autoreleasing");
1541     break;
1542   case Qualifiers::OCL_Strong:
1543     Extra.mangleSourceName("Strong");
1544     break;
1545   case Qualifiers::OCL_Weak:
1546     Extra.mangleSourceName("Weak");
1547     break;
1548   }
1549   Extra.manglePointerCVQualifiers(Quals);
1550   Extra.manglePointerExtQualifiers(Quals, Type);
1551   Extra.mangleType(Type, Range);
1552 
1553   mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__ObjC"});
1554 }
1555 
1556 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1557                                                bool IsMember) {
1558   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1559   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1560   // 'I' means __restrict (32/64-bit).
1561   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1562   // keyword!
1563   // <base-cvr-qualifiers> ::= A  # near
1564   //                       ::= B  # near const
1565   //                       ::= C  # near volatile
1566   //                       ::= D  # near const volatile
1567   //                       ::= E  # far (16-bit)
1568   //                       ::= F  # far const (16-bit)
1569   //                       ::= G  # far volatile (16-bit)
1570   //                       ::= H  # far const volatile (16-bit)
1571   //                       ::= I  # huge (16-bit)
1572   //                       ::= J  # huge const (16-bit)
1573   //                       ::= K  # huge volatile (16-bit)
1574   //                       ::= L  # huge const volatile (16-bit)
1575   //                       ::= M <basis> # based
1576   //                       ::= N <basis> # based const
1577   //                       ::= O <basis> # based volatile
1578   //                       ::= P <basis> # based const volatile
1579   //                       ::= Q  # near member
1580   //                       ::= R  # near const member
1581   //                       ::= S  # near volatile member
1582   //                       ::= T  # near const volatile member
1583   //                       ::= U  # far member (16-bit)
1584   //                       ::= V  # far const member (16-bit)
1585   //                       ::= W  # far volatile member (16-bit)
1586   //                       ::= X  # far const volatile member (16-bit)
1587   //                       ::= Y  # huge member (16-bit)
1588   //                       ::= Z  # huge const member (16-bit)
1589   //                       ::= 0  # huge volatile member (16-bit)
1590   //                       ::= 1  # huge const volatile member (16-bit)
1591   //                       ::= 2 <basis> # based member
1592   //                       ::= 3 <basis> # based const member
1593   //                       ::= 4 <basis> # based volatile member
1594   //                       ::= 5 <basis> # based const volatile member
1595   //                       ::= 6  # near function (pointers only)
1596   //                       ::= 7  # far function (pointers only)
1597   //                       ::= 8  # near method (pointers only)
1598   //                       ::= 9  # far method (pointers only)
1599   //                       ::= _A <basis> # based function (pointers only)
1600   //                       ::= _B <basis> # based function (far?) (pointers only)
1601   //                       ::= _C <basis> # based method (pointers only)
1602   //                       ::= _D <basis> # based method (far?) (pointers only)
1603   //                       ::= _E # block (Clang)
1604   // <basis> ::= 0 # __based(void)
1605   //         ::= 1 # __based(segment)?
1606   //         ::= 2 <name> # __based(name)
1607   //         ::= 3 # ?
1608   //         ::= 4 # ?
1609   //         ::= 5 # not really based
1610   bool HasConst = Quals.hasConst(),
1611        HasVolatile = Quals.hasVolatile();
1612 
1613   if (!IsMember) {
1614     if (HasConst && HasVolatile) {
1615       Out << 'D';
1616     } else if (HasVolatile) {
1617       Out << 'C';
1618     } else if (HasConst) {
1619       Out << 'B';
1620     } else {
1621       Out << 'A';
1622     }
1623   } else {
1624     if (HasConst && HasVolatile) {
1625       Out << 'T';
1626     } else if (HasVolatile) {
1627       Out << 'S';
1628     } else if (HasConst) {
1629       Out << 'R';
1630     } else {
1631       Out << 'Q';
1632     }
1633   }
1634 
1635   // FIXME: For now, just drop all extension qualifiers on the floor.
1636 }
1637 
1638 void
1639 MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
1640   // <ref-qualifier> ::= G                # lvalue reference
1641   //                 ::= H                # rvalue-reference
1642   switch (RefQualifier) {
1643   case RQ_None:
1644     break;
1645 
1646   case RQ_LValue:
1647     Out << 'G';
1648     break;
1649 
1650   case RQ_RValue:
1651     Out << 'H';
1652     break;
1653   }
1654 }
1655 
1656 void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1657                                                          QualType PointeeType) {
1658   if (PointersAre64Bit &&
1659       (PointeeType.isNull() || !PointeeType->isFunctionType()))
1660     Out << 'E';
1661 
1662   if (Quals.hasRestrict())
1663     Out << 'I';
1664 
1665   if (Quals.hasUnaligned() ||
1666       (!PointeeType.isNull() && PointeeType.getLocalQualifiers().hasUnaligned()))
1667     Out << 'F';
1668 }
1669 
1670 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1671   // <pointer-cv-qualifiers> ::= P  # no qualifiers
1672   //                         ::= Q  # const
1673   //                         ::= R  # volatile
1674   //                         ::= S  # const volatile
1675   bool HasConst = Quals.hasConst(),
1676        HasVolatile = Quals.hasVolatile();
1677 
1678   if (HasConst && HasVolatile) {
1679     Out << 'S';
1680   } else if (HasVolatile) {
1681     Out << 'R';
1682   } else if (HasConst) {
1683     Out << 'Q';
1684   } else {
1685     Out << 'P';
1686   }
1687 }
1688 
1689 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1690                                                  SourceRange Range) {
1691   // MSVC will backreference two canonically equivalent types that have slightly
1692   // different manglings when mangled alone.
1693 
1694   // Decayed types do not match up with non-decayed versions of the same type.
1695   //
1696   // e.g.
1697   // void (*x)(void) will not form a backreference with void x(void)
1698   void *TypePtr;
1699   if (const auto *DT = T->getAs<DecayedType>()) {
1700     QualType OriginalType = DT->getOriginalType();
1701     // All decayed ArrayTypes should be treated identically; as-if they were
1702     // a decayed IncompleteArrayType.
1703     if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
1704       OriginalType = getASTContext().getIncompleteArrayType(
1705           AT->getElementType(), AT->getSizeModifier(),
1706           AT->getIndexTypeCVRQualifiers());
1707 
1708     TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
1709     // If the original parameter was textually written as an array,
1710     // instead treat the decayed parameter like it's const.
1711     //
1712     // e.g.
1713     // int [] -> int * const
1714     if (OriginalType->isArrayType())
1715       T = T.withConst();
1716   } else {
1717     TypePtr = T.getCanonicalType().getAsOpaquePtr();
1718   }
1719 
1720   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1721 
1722   if (Found == TypeBackReferences.end()) {
1723     size_t OutSizeBefore = Out.tell();
1724 
1725     mangleType(T, Range, QMM_Drop);
1726 
1727     // See if it's worth creating a back reference.
1728     // Only types longer than 1 character are considered
1729     // and only 10 back references slots are available:
1730     bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
1731     if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1732       size_t Size = TypeBackReferences.size();
1733       TypeBackReferences[TypePtr] = Size;
1734     }
1735   } else {
1736     Out << Found->second;
1737   }
1738 }
1739 
1740 void MicrosoftCXXNameMangler::manglePassObjectSizeArg(
1741     const PassObjectSizeAttr *POSA) {
1742   int Type = POSA->getType();
1743 
1744   auto Iter = PassObjectSizeArgs.insert(Type).first;
1745   auto *TypePtr = (const void *)&*Iter;
1746   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1747 
1748   if (Found == TypeBackReferences.end()) {
1749     mangleArtificalTagType(TTK_Enum, "__pass_object_size" + llvm::utostr(Type),
1750                            {"__clang"});
1751 
1752     if (TypeBackReferences.size() < 10) {
1753       size_t Size = TypeBackReferences.size();
1754       TypeBackReferences[TypePtr] = Size;
1755     }
1756   } else {
1757     Out << Found->second;
1758   }
1759 }
1760 
1761 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1762                                          QualifierMangleMode QMM) {
1763   // Don't use the canonical types.  MSVC includes things like 'const' on
1764   // pointer arguments to function pointers that canonicalization strips away.
1765   T = T.getDesugaredType(getASTContext());
1766   Qualifiers Quals = T.getLocalQualifiers();
1767   if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1768     // If there were any Quals, getAsArrayType() pushed them onto the array
1769     // element type.
1770     if (QMM == QMM_Mangle)
1771       Out << 'A';
1772     else if (QMM == QMM_Escape || QMM == QMM_Result)
1773       Out << "$$B";
1774     mangleArrayType(AT);
1775     return;
1776   }
1777 
1778   bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1779                    T->isReferenceType() || T->isBlockPointerType();
1780 
1781   switch (QMM) {
1782   case QMM_Drop:
1783     if (Quals.hasObjCLifetime())
1784       Quals = Quals.withoutObjCLifetime();
1785     break;
1786   case QMM_Mangle:
1787     if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1788       Out << '6';
1789       mangleFunctionType(FT);
1790       return;
1791     }
1792     mangleQualifiers(Quals, false);
1793     break;
1794   case QMM_Escape:
1795     if (!IsPointer && Quals) {
1796       Out << "$$C";
1797       mangleQualifiers(Quals, false);
1798     }
1799     break;
1800   case QMM_Result:
1801     // Presence of __unaligned qualifier shouldn't affect mangling here.
1802     Quals.removeUnaligned();
1803     if (Quals.hasObjCLifetime())
1804       Quals = Quals.withoutObjCLifetime();
1805     if ((!IsPointer && Quals) || isa<TagType>(T) || isArtificialTagType(T)) {
1806       Out << '?';
1807       mangleQualifiers(Quals, false);
1808     }
1809     break;
1810   }
1811 
1812   const Type *ty = T.getTypePtr();
1813 
1814   switch (ty->getTypeClass()) {
1815 #define ABSTRACT_TYPE(CLASS, PARENT)
1816 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1817   case Type::CLASS: \
1818     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1819     return;
1820 #define TYPE(CLASS, PARENT) \
1821   case Type::CLASS: \
1822     mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1823     break;
1824 #include "clang/AST/TypeNodes.def"
1825 #undef ABSTRACT_TYPE
1826 #undef NON_CANONICAL_TYPE
1827 #undef TYPE
1828   }
1829 }
1830 
1831 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1832                                          SourceRange Range) {
1833   //  <type>         ::= <builtin-type>
1834   //  <builtin-type> ::= X  # void
1835   //                 ::= C  # signed char
1836   //                 ::= D  # char
1837   //                 ::= E  # unsigned char
1838   //                 ::= F  # short
1839   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1840   //                 ::= H  # int
1841   //                 ::= I  # unsigned int
1842   //                 ::= J  # long
1843   //                 ::= K  # unsigned long
1844   //                     L  # <none>
1845   //                 ::= M  # float
1846   //                 ::= N  # double
1847   //                 ::= O  # long double (__float80 is mangled differently)
1848   //                 ::= _J # long long, __int64
1849   //                 ::= _K # unsigned long long, __int64
1850   //                 ::= _L # __int128
1851   //                 ::= _M # unsigned __int128
1852   //                 ::= _N # bool
1853   //                     _O # <array in parameter>
1854   //                 ::= _T # __float80 (Intel)
1855   //                 ::= _S # char16_t
1856   //                 ::= _U # char32_t
1857   //                 ::= _W # wchar_t
1858   //                 ::= _Z # __float80 (Digital Mars)
1859   switch (T->getKind()) {
1860   case BuiltinType::Void:
1861     Out << 'X';
1862     break;
1863   case BuiltinType::SChar:
1864     Out << 'C';
1865     break;
1866   case BuiltinType::Char_U:
1867   case BuiltinType::Char_S:
1868     Out << 'D';
1869     break;
1870   case BuiltinType::UChar:
1871     Out << 'E';
1872     break;
1873   case BuiltinType::Short:
1874     Out << 'F';
1875     break;
1876   case BuiltinType::UShort:
1877     Out << 'G';
1878     break;
1879   case BuiltinType::Int:
1880     Out << 'H';
1881     break;
1882   case BuiltinType::UInt:
1883     Out << 'I';
1884     break;
1885   case BuiltinType::Long:
1886     Out << 'J';
1887     break;
1888   case BuiltinType::ULong:
1889     Out << 'K';
1890     break;
1891   case BuiltinType::Float:
1892     Out << 'M';
1893     break;
1894   case BuiltinType::Double:
1895     Out << 'N';
1896     break;
1897   // TODO: Determine size and mangle accordingly
1898   case BuiltinType::LongDouble:
1899     Out << 'O';
1900     break;
1901   case BuiltinType::LongLong:
1902     Out << "_J";
1903     break;
1904   case BuiltinType::ULongLong:
1905     Out << "_K";
1906     break;
1907   case BuiltinType::Int128:
1908     Out << "_L";
1909     break;
1910   case BuiltinType::UInt128:
1911     Out << "_M";
1912     break;
1913   case BuiltinType::Bool:
1914     Out << "_N";
1915     break;
1916   case BuiltinType::Char16:
1917     Out << "_S";
1918     break;
1919   case BuiltinType::Char32:
1920     Out << "_U";
1921     break;
1922   case BuiltinType::WChar_S:
1923   case BuiltinType::WChar_U:
1924     Out << "_W";
1925     break;
1926 
1927 #define BUILTIN_TYPE(Id, SingletonId)
1928 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1929   case BuiltinType::Id:
1930 #include "clang/AST/BuiltinTypes.def"
1931   case BuiltinType::Dependent:
1932     llvm_unreachable("placeholder types shouldn't get to name mangling");
1933 
1934   case BuiltinType::ObjCId:
1935     mangleArtificalTagType(TTK_Struct, ".objc_object");
1936     break;
1937   case BuiltinType::ObjCClass:
1938     mangleArtificalTagType(TTK_Struct, ".objc_class");
1939     break;
1940   case BuiltinType::ObjCSel:
1941     mangleArtificalTagType(TTK_Struct, ".objc_selector");
1942     break;
1943 
1944 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
1945   case BuiltinType::Id: \
1946     Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \
1947     break;
1948 #include "clang/Basic/OpenCLImageTypes.def"
1949   case BuiltinType::OCLSampler:
1950     Out << "PA";
1951     mangleArtificalTagType(TTK_Struct, "ocl_sampler");
1952     break;
1953   case BuiltinType::OCLEvent:
1954     Out << "PA";
1955     mangleArtificalTagType(TTK_Struct, "ocl_event");
1956     break;
1957   case BuiltinType::OCLClkEvent:
1958     Out << "PA";
1959     mangleArtificalTagType(TTK_Struct, "ocl_clkevent");
1960     break;
1961   case BuiltinType::OCLQueue:
1962     Out << "PA";
1963     mangleArtificalTagType(TTK_Struct, "ocl_queue");
1964     break;
1965   case BuiltinType::OCLReserveID:
1966     Out << "PA";
1967     mangleArtificalTagType(TTK_Struct, "ocl_reserveid");
1968     break;
1969 
1970   case BuiltinType::NullPtr:
1971     Out << "$$T";
1972     break;
1973 
1974   case BuiltinType::Float16:
1975     mangleArtificalTagType(TTK_Struct, "_Float16", {"__clang"});
1976     break;
1977 
1978   case BuiltinType::Half:
1979     mangleArtificalTagType(TTK_Struct, "_Half", {"__clang"});
1980     break;
1981 
1982   case BuiltinType::ShortAccum:
1983   case BuiltinType::Accum:
1984   case BuiltinType::LongAccum:
1985   case BuiltinType::UShortAccum:
1986   case BuiltinType::UAccum:
1987   case BuiltinType::ULongAccum:
1988   case BuiltinType::ShortFract:
1989   case BuiltinType::Fract:
1990   case BuiltinType::LongFract:
1991   case BuiltinType::UShortFract:
1992   case BuiltinType::UFract:
1993   case BuiltinType::ULongFract:
1994   case BuiltinType::SatShortAccum:
1995   case BuiltinType::SatAccum:
1996   case BuiltinType::SatLongAccum:
1997   case BuiltinType::SatUShortAccum:
1998   case BuiltinType::SatUAccum:
1999   case BuiltinType::SatULongAccum:
2000   case BuiltinType::SatShortFract:
2001   case BuiltinType::SatFract:
2002   case BuiltinType::SatLongFract:
2003   case BuiltinType::SatUShortFract:
2004   case BuiltinType::SatUFract:
2005   case BuiltinType::SatULongFract:
2006   case BuiltinType::Char8:
2007   case BuiltinType::Float128: {
2008     DiagnosticsEngine &Diags = Context.getDiags();
2009     unsigned DiagID = Diags.getCustomDiagID(
2010         DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
2011     Diags.Report(Range.getBegin(), DiagID)
2012         << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
2013     break;
2014   }
2015   }
2016 }
2017 
2018 // <type>          ::= <function-type>
2019 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
2020                                          SourceRange) {
2021   // Structors only appear in decls, so at this point we know it's not a
2022   // structor type.
2023   // FIXME: This may not be lambda-friendly.
2024   if (T->getTypeQuals() || T->getRefQualifier() != RQ_None) {
2025     Out << "$$A8@@";
2026     mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
2027   } else {
2028     Out << "$$A6";
2029     mangleFunctionType(T);
2030   }
2031 }
2032 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
2033                                          Qualifiers, SourceRange) {
2034   Out << "$$A6";
2035   mangleFunctionType(T);
2036 }
2037 
2038 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
2039                                                  const FunctionDecl *D,
2040                                                  bool ForceThisQuals) {
2041   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
2042   //                     <return-type> <argument-list> <throw-spec>
2043   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
2044 
2045   SourceRange Range;
2046   if (D) Range = D->getSourceRange();
2047 
2048   bool IsInLambda = false;
2049   bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
2050   CallingConv CC = T->getCallConv();
2051   if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
2052     if (MD->getParent()->isLambda())
2053       IsInLambda = true;
2054     if (MD->isInstance())
2055       HasThisQuals = true;
2056     if (isa<CXXDestructorDecl>(MD)) {
2057       IsStructor = true;
2058     } else if (isa<CXXConstructorDecl>(MD)) {
2059       IsStructor = true;
2060       IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
2061                        StructorType == Ctor_DefaultClosure) &&
2062                       isStructorDecl(MD);
2063       if (IsCtorClosure)
2064         CC = getASTContext().getDefaultCallingConvention(
2065             /*IsVariadic=*/false, /*IsCXXMethod=*/true);
2066     }
2067   }
2068 
2069   // If this is a C++ instance method, mangle the CVR qualifiers for the
2070   // this pointer.
2071   if (HasThisQuals) {
2072     Qualifiers Quals = Qualifiers::fromCVRUMask(Proto->getTypeQuals());
2073     manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
2074     mangleRefQualifier(Proto->getRefQualifier());
2075     mangleQualifiers(Quals, /*IsMember=*/false);
2076   }
2077 
2078   mangleCallingConvention(CC);
2079 
2080   // <return-type> ::= <type>
2081   //               ::= @ # structors (they have no declared return type)
2082   if (IsStructor) {
2083     if (isa<CXXDestructorDecl>(D) && isStructorDecl(D)) {
2084       // The scalar deleting destructor takes an extra int argument which is not
2085       // reflected in the AST.
2086       if (StructorType == Dtor_Deleting) {
2087         Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
2088         return;
2089       }
2090       // The vbase destructor returns void which is not reflected in the AST.
2091       if (StructorType == Dtor_Complete) {
2092         Out << "XXZ";
2093         return;
2094       }
2095     }
2096     if (IsCtorClosure) {
2097       // Default constructor closure and copy constructor closure both return
2098       // void.
2099       Out << 'X';
2100 
2101       if (StructorType == Ctor_DefaultClosure) {
2102         // Default constructor closure always has no arguments.
2103         Out << 'X';
2104       } else if (StructorType == Ctor_CopyingClosure) {
2105         // Copy constructor closure always takes an unqualified reference.
2106         mangleArgumentType(getASTContext().getLValueReferenceType(
2107                                Proto->getParamType(0)
2108                                    ->getAs<LValueReferenceType>()
2109                                    ->getPointeeType(),
2110                                /*SpelledAsLValue=*/true),
2111                            Range);
2112         Out << '@';
2113       } else {
2114         llvm_unreachable("unexpected constructor closure!");
2115       }
2116       Out << 'Z';
2117       return;
2118     }
2119     Out << '@';
2120   } else {
2121     QualType ResultType = T->getReturnType();
2122     if (const auto *AT =
2123             dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
2124       Out << '?';
2125       mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
2126       Out << '?';
2127       assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2128              "shouldn't need to mangle __auto_type!");
2129       mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
2130       Out << '@';
2131     } else if (IsInLambda) {
2132       Out << '@';
2133     } else {
2134       if (ResultType->isVoidType())
2135         ResultType = ResultType.getUnqualifiedType();
2136       mangleType(ResultType, Range, QMM_Result);
2137     }
2138   }
2139 
2140   // <argument-list> ::= X # void
2141   //                 ::= <type>+ @
2142   //                 ::= <type>* Z # varargs
2143   if (!Proto) {
2144     // Function types without prototypes can arise when mangling a function type
2145     // within an overloadable function in C. We mangle these as the absence of
2146     // any parameter types (not even an empty parameter list).
2147     Out << '@';
2148   } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2149     Out << 'X';
2150   } else {
2151     // Happens for function pointer type arguments for example.
2152     for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2153       mangleArgumentType(Proto->getParamType(I), Range);
2154       // Mangle each pass_object_size parameter as if it's a parameter of enum
2155       // type passed directly after the parameter with the pass_object_size
2156       // attribute. The aforementioned enum's name is __pass_object_size, and we
2157       // pretend it resides in a top-level namespace called __clang.
2158       //
2159       // FIXME: Is there a defined extension notation for the MS ABI, or is it
2160       // necessary to just cross our fingers and hope this type+namespace
2161       // combination doesn't conflict with anything?
2162       if (D)
2163         if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
2164           manglePassObjectSizeArg(P);
2165     }
2166     // <builtin-type>      ::= Z  # ellipsis
2167     if (Proto->isVariadic())
2168       Out << 'Z';
2169     else
2170       Out << '@';
2171   }
2172 
2173   mangleThrowSpecification(Proto);
2174 }
2175 
2176 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
2177   // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
2178   //                                            # pointer. in 64-bit mode *all*
2179   //                                            # 'this' pointers are 64-bit.
2180   //                   ::= <global-function>
2181   // <member-function> ::= A # private: near
2182   //                   ::= B # private: far
2183   //                   ::= C # private: static near
2184   //                   ::= D # private: static far
2185   //                   ::= E # private: virtual near
2186   //                   ::= F # private: virtual far
2187   //                   ::= I # protected: near
2188   //                   ::= J # protected: far
2189   //                   ::= K # protected: static near
2190   //                   ::= L # protected: static far
2191   //                   ::= M # protected: virtual near
2192   //                   ::= N # protected: virtual far
2193   //                   ::= Q # public: near
2194   //                   ::= R # public: far
2195   //                   ::= S # public: static near
2196   //                   ::= T # public: static far
2197   //                   ::= U # public: virtual near
2198   //                   ::= V # public: virtual far
2199   // <global-function> ::= Y # global near
2200   //                   ::= Z # global far
2201   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2202     bool IsVirtual = MD->isVirtual();
2203     // When mangling vbase destructor variants, ignore whether or not the
2204     // underlying destructor was defined to be virtual.
2205     if (isa<CXXDestructorDecl>(MD) && isStructorDecl(MD) &&
2206         StructorType == Dtor_Complete) {
2207       IsVirtual = false;
2208     }
2209     switch (MD->getAccess()) {
2210       case AS_none:
2211         llvm_unreachable("Unsupported access specifier");
2212       case AS_private:
2213         if (MD->isStatic())
2214           Out << 'C';
2215         else if (IsVirtual)
2216           Out << 'E';
2217         else
2218           Out << 'A';
2219         break;
2220       case AS_protected:
2221         if (MD->isStatic())
2222           Out << 'K';
2223         else if (IsVirtual)
2224           Out << 'M';
2225         else
2226           Out << 'I';
2227         break;
2228       case AS_public:
2229         if (MD->isStatic())
2230           Out << 'S';
2231         else if (IsVirtual)
2232           Out << 'U';
2233         else
2234           Out << 'Q';
2235     }
2236   } else {
2237     Out << 'Y';
2238   }
2239 }
2240 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
2241   // <calling-convention> ::= A # __cdecl
2242   //                      ::= B # __export __cdecl
2243   //                      ::= C # __pascal
2244   //                      ::= D # __export __pascal
2245   //                      ::= E # __thiscall
2246   //                      ::= F # __export __thiscall
2247   //                      ::= G # __stdcall
2248   //                      ::= H # __export __stdcall
2249   //                      ::= I # __fastcall
2250   //                      ::= J # __export __fastcall
2251   //                      ::= Q # __vectorcall
2252   //                      ::= w # __regcall
2253   // The 'export' calling conventions are from a bygone era
2254   // (*cough*Win16*cough*) when functions were declared for export with
2255   // that keyword. (It didn't actually export them, it just made them so
2256   // that they could be in a DLL and somebody from another module could call
2257   // them.)
2258 
2259   switch (CC) {
2260     default:
2261       llvm_unreachable("Unsupported CC for mangling");
2262     case CC_Win64:
2263     case CC_X86_64SysV:
2264     case CC_C: Out << 'A'; break;
2265     case CC_X86Pascal: Out << 'C'; break;
2266     case CC_X86ThisCall: Out << 'E'; break;
2267     case CC_X86StdCall: Out << 'G'; break;
2268     case CC_X86FastCall: Out << 'I'; break;
2269     case CC_X86VectorCall: Out << 'Q'; break;
2270     case CC_Swift: Out << 'S'; break;
2271     case CC_PreserveMost: Out << 'U'; break;
2272     case CC_X86RegCall: Out << 'w'; break;
2273   }
2274 }
2275 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2276   mangleCallingConvention(T->getCallConv());
2277 }
2278 void MicrosoftCXXNameMangler::mangleThrowSpecification(
2279                                                 const FunctionProtoType *FT) {
2280   // <throw-spec> ::= Z # throw(...) (default)
2281   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
2282   //              ::= <type>+
2283   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
2284   // all actually mangled as 'Z'. (They're ignored because their associated
2285   // functionality isn't implemented, and probably never will be.)
2286   Out << 'Z';
2287 }
2288 
2289 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2290                                          Qualifiers, SourceRange Range) {
2291   // Probably should be mangled as a template instantiation; need to see what
2292   // VC does first.
2293   DiagnosticsEngine &Diags = Context.getDiags();
2294   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2295     "cannot mangle this unresolved dependent type yet");
2296   Diags.Report(Range.getBegin(), DiagID)
2297     << Range;
2298 }
2299 
2300 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2301 // <union-type>  ::= T <name>
2302 // <struct-type> ::= U <name>
2303 // <class-type>  ::= V <name>
2304 // <enum-type>   ::= W4 <name>
2305 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2306   switch (TTK) {
2307     case TTK_Union:
2308       Out << 'T';
2309       break;
2310     case TTK_Struct:
2311     case TTK_Interface:
2312       Out << 'U';
2313       break;
2314     case TTK_Class:
2315       Out << 'V';
2316       break;
2317     case TTK_Enum:
2318       Out << "W4";
2319       break;
2320   }
2321 }
2322 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2323                                          SourceRange) {
2324   mangleType(cast<TagType>(T)->getDecl());
2325 }
2326 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2327                                          SourceRange) {
2328   mangleType(cast<TagType>(T)->getDecl());
2329 }
2330 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2331   mangleTagTypeKind(TD->getTagKind());
2332   mangleName(TD);
2333 }
2334 
2335 // If you add a call to this, consider updating isArtificialTagType() too.
2336 void MicrosoftCXXNameMangler::mangleArtificalTagType(
2337     TagTypeKind TK, StringRef UnqualifiedName,
2338     ArrayRef<StringRef> NestedNames) {
2339   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2340   mangleTagTypeKind(TK);
2341 
2342   // Always start with the unqualified name.
2343   mangleSourceName(UnqualifiedName);
2344 
2345   for (auto I = NestedNames.rbegin(), E = NestedNames.rend(); I != E; ++I)
2346     mangleSourceName(*I);
2347 
2348   // Terminate the whole name with an '@'.
2349   Out << '@';
2350 }
2351 
2352 // <type>       ::= <array-type>
2353 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2354 //                  [Y <dimension-count> <dimension>+]
2355 //                  <element-type> # as global, E is never required
2356 // It's supposed to be the other way around, but for some strange reason, it
2357 // isn't. Today this behavior is retained for the sole purpose of backwards
2358 // compatibility.
2359 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2360   // This isn't a recursive mangling, so now we have to do it all in this
2361   // one call.
2362   manglePointerCVQualifiers(T->getElementType().getQualifiers());
2363   mangleType(T->getElementType(), SourceRange());
2364 }
2365 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2366                                          SourceRange) {
2367   llvm_unreachable("Should have been special cased");
2368 }
2369 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2370                                          SourceRange) {
2371   llvm_unreachable("Should have been special cased");
2372 }
2373 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2374                                          Qualifiers, SourceRange) {
2375   llvm_unreachable("Should have been special cased");
2376 }
2377 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2378                                          Qualifiers, SourceRange) {
2379   llvm_unreachable("Should have been special cased");
2380 }
2381 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2382   QualType ElementTy(T, 0);
2383   SmallVector<llvm::APInt, 3> Dimensions;
2384   for (;;) {
2385     if (ElementTy->isConstantArrayType()) {
2386       const ConstantArrayType *CAT =
2387           getASTContext().getAsConstantArrayType(ElementTy);
2388       Dimensions.push_back(CAT->getSize());
2389       ElementTy = CAT->getElementType();
2390     } else if (ElementTy->isIncompleteArrayType()) {
2391       const IncompleteArrayType *IAT =
2392           getASTContext().getAsIncompleteArrayType(ElementTy);
2393       Dimensions.push_back(llvm::APInt(32, 0));
2394       ElementTy = IAT->getElementType();
2395     } else if (ElementTy->isVariableArrayType()) {
2396       const VariableArrayType *VAT =
2397         getASTContext().getAsVariableArrayType(ElementTy);
2398       Dimensions.push_back(llvm::APInt(32, 0));
2399       ElementTy = VAT->getElementType();
2400     } else if (ElementTy->isDependentSizedArrayType()) {
2401       // The dependent expression has to be folded into a constant (TODO).
2402       const DependentSizedArrayType *DSAT =
2403         getASTContext().getAsDependentSizedArrayType(ElementTy);
2404       DiagnosticsEngine &Diags = Context.getDiags();
2405       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2406         "cannot mangle this dependent-length array yet");
2407       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2408         << DSAT->getBracketsRange();
2409       return;
2410     } else {
2411       break;
2412     }
2413   }
2414   Out << 'Y';
2415   // <dimension-count> ::= <number> # number of extra dimensions
2416   mangleNumber(Dimensions.size());
2417   for (const llvm::APInt &Dimension : Dimensions)
2418     mangleNumber(Dimension.getLimitedValue());
2419   mangleType(ElementTy, SourceRange(), QMM_Escape);
2420 }
2421 
2422 // <type>                   ::= <pointer-to-member-type>
2423 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2424 //                                                          <class name> <type>
2425 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
2426                                          Qualifiers Quals, SourceRange Range) {
2427   QualType PointeeType = T->getPointeeType();
2428   manglePointerCVQualifiers(Quals);
2429   manglePointerExtQualifiers(Quals, PointeeType);
2430   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2431     Out << '8';
2432     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2433     mangleFunctionType(FPT, nullptr, true);
2434   } else {
2435     mangleQualifiers(PointeeType.getQualifiers(), true);
2436     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2437     mangleType(PointeeType, Range, QMM_Drop);
2438   }
2439 }
2440 
2441 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2442                                          Qualifiers, SourceRange Range) {
2443   DiagnosticsEngine &Diags = Context.getDiags();
2444   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2445     "cannot mangle this template type parameter type yet");
2446   Diags.Report(Range.getBegin(), DiagID)
2447     << Range;
2448 }
2449 
2450 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2451                                          Qualifiers, SourceRange Range) {
2452   DiagnosticsEngine &Diags = Context.getDiags();
2453   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2454     "cannot mangle this substituted parameter pack yet");
2455   Diags.Report(Range.getBegin(), DiagID)
2456     << Range;
2457 }
2458 
2459 // <type> ::= <pointer-type>
2460 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2461 //                       # the E is required for 64-bit non-static pointers
2462 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2463                                          SourceRange Range) {
2464   QualType PointeeType = T->getPointeeType();
2465   manglePointerCVQualifiers(Quals);
2466   manglePointerExtQualifiers(Quals, PointeeType);
2467   mangleType(PointeeType, Range);
2468 }
2469 
2470 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2471                                          Qualifiers Quals, SourceRange Range) {
2472   QualType PointeeType = T->getPointeeType();
2473   switch (Quals.getObjCLifetime()) {
2474   case Qualifiers::OCL_None:
2475   case Qualifiers::OCL_ExplicitNone:
2476     break;
2477   case Qualifiers::OCL_Autoreleasing:
2478   case Qualifiers::OCL_Strong:
2479   case Qualifiers::OCL_Weak:
2480     return mangleObjCLifetime(PointeeType, Quals, Range);
2481   }
2482   manglePointerCVQualifiers(Quals);
2483   manglePointerExtQualifiers(Quals, PointeeType);
2484   mangleType(PointeeType, Range);
2485 }
2486 
2487 // <type> ::= <reference-type>
2488 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2489 //                 # the E is required for 64-bit non-static lvalue references
2490 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2491                                          Qualifiers Quals, SourceRange Range) {
2492   QualType PointeeType = T->getPointeeType();
2493   assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2494   Out << 'A';
2495   manglePointerExtQualifiers(Quals, PointeeType);
2496   mangleType(PointeeType, Range);
2497 }
2498 
2499 // <type> ::= <r-value-reference-type>
2500 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2501 //                 # the E is required for 64-bit non-static rvalue references
2502 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2503                                          Qualifiers Quals, SourceRange Range) {
2504   QualType PointeeType = T->getPointeeType();
2505   assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2506   Out << "$$Q";
2507   manglePointerExtQualifiers(Quals, PointeeType);
2508   mangleType(PointeeType, Range);
2509 }
2510 
2511 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2512                                          SourceRange Range) {
2513   QualType ElementType = T->getElementType();
2514 
2515   llvm::SmallString<64> TemplateMangling;
2516   llvm::raw_svector_ostream Stream(TemplateMangling);
2517   MicrosoftCXXNameMangler Extra(Context, Stream);
2518   Stream << "?$";
2519   Extra.mangleSourceName("_Complex");
2520   Extra.mangleType(ElementType, Range, QMM_Escape);
2521 
2522   mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__clang"});
2523 }
2524 
2525 // Returns true for types that mangleArtificalTagType() gets called for with
2526 // TTK_Union, TTK_Struct, TTK_Class and where compatibility with MSVC's
2527 // mangling matters.
2528 // (It doesn't matter for Objective-C types and the like that cl.exe doesn't
2529 // support.)
2530 bool MicrosoftCXXNameMangler::isArtificialTagType(QualType T) const {
2531   const Type *ty = T.getTypePtr();
2532   switch (ty->getTypeClass()) {
2533   default:
2534     return false;
2535 
2536   case Type::Vector: {
2537     // For ABI compatibility only __m64, __m128(id), and __m256(id) matter,
2538     // but since mangleType(VectorType*) always calls mangleArtificalTagType()
2539     // just always return true (the other vector types are clang-only).
2540     return true;
2541   }
2542   }
2543 }
2544 
2545 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2546                                          SourceRange Range) {
2547   const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2548   assert(ET && "vectors with non-builtin elements are unsupported");
2549   uint64_t Width = getASTContext().getTypeSize(T);
2550   // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
2551   // doesn't match the Intel types uses a custom mangling below.
2552   size_t OutSizeBefore = Out.tell();
2553   llvm::Triple::ArchType AT =
2554       getASTContext().getTargetInfo().getTriple().getArch();
2555   if (AT == llvm::Triple::x86 || AT == llvm::Triple::x86_64) {
2556     if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2557       mangleArtificalTagType(TTK_Union, "__m64");
2558     } else if (Width >= 128) {
2559       if (ET->getKind() == BuiltinType::Float)
2560         mangleArtificalTagType(TTK_Union, "__m" + llvm::utostr(Width));
2561       else if (ET->getKind() == BuiltinType::LongLong)
2562         mangleArtificalTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
2563       else if (ET->getKind() == BuiltinType::Double)
2564         mangleArtificalTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
2565     }
2566   }
2567 
2568   bool IsBuiltin = Out.tell() != OutSizeBefore;
2569   if (!IsBuiltin) {
2570     // The MS ABI doesn't have a special mangling for vector types, so we define
2571     // our own mangling to handle uses of __vector_size__ on user-specified
2572     // types, and for extensions like __v4sf.
2573 
2574     llvm::SmallString<64> TemplateMangling;
2575     llvm::raw_svector_ostream Stream(TemplateMangling);
2576     MicrosoftCXXNameMangler Extra(Context, Stream);
2577     Stream << "?$";
2578     Extra.mangleSourceName("__vector");
2579     Extra.mangleType(QualType(ET, 0), Range, QMM_Escape);
2580     Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()),
2581                                /*IsBoolean=*/false);
2582 
2583     mangleArtificalTagType(TTK_Union, TemplateMangling, {"__clang"});
2584   }
2585 }
2586 
2587 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
2588                                          Qualifiers Quals, SourceRange Range) {
2589   mangleType(static_cast<const VectorType *>(T), Quals, Range);
2590 }
2591 
2592 void MicrosoftCXXNameMangler::mangleType(const DependentVectorType *T,
2593                                          Qualifiers, SourceRange Range) {
2594   DiagnosticsEngine &Diags = Context.getDiags();
2595   unsigned DiagID = Diags.getCustomDiagID(
2596       DiagnosticsEngine::Error,
2597       "cannot mangle this dependent-sized vector type yet");
2598   Diags.Report(Range.getBegin(), DiagID) << Range;
2599 }
2600 
2601 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2602                                          Qualifiers, SourceRange Range) {
2603   DiagnosticsEngine &Diags = Context.getDiags();
2604   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2605     "cannot mangle this dependent-sized extended vector type yet");
2606   Diags.Report(Range.getBegin(), DiagID)
2607     << Range;
2608 }
2609 
2610 void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T,
2611                                          Qualifiers, SourceRange Range) {
2612   DiagnosticsEngine &Diags = Context.getDiags();
2613   unsigned DiagID = Diags.getCustomDiagID(
2614       DiagnosticsEngine::Error,
2615       "cannot mangle this dependent address space type yet");
2616   Diags.Report(Range.getBegin(), DiagID) << Range;
2617 }
2618 
2619 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2620                                          SourceRange) {
2621   // ObjC interfaces are mangled as if they were structs with a name that is
2622   // not a valid C/C++ identifier
2623   mangleTagTypeKind(TTK_Struct);
2624   mangle(T->getDecl(), ".objc_cls_");
2625 }
2626 
2627 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T, Qualifiers,
2628                                          SourceRange Range) {
2629   if (T->qual_empty())
2630     return mangleType(T->getBaseType(), Range, QMM_Drop);
2631 
2632   ArgBackRefMap OuterArgsContext;
2633   BackRefVec OuterTemplateContext;
2634 
2635   TypeBackReferences.swap(OuterArgsContext);
2636   NameBackReferences.swap(OuterTemplateContext);
2637 
2638   mangleTagTypeKind(TTK_Struct);
2639 
2640   Out << "?$";
2641   if (T->isObjCId())
2642     mangleSourceName(".objc_object");
2643   else if (T->isObjCClass())
2644     mangleSourceName(".objc_class");
2645   else
2646     mangleSourceName((".objc_cls_" + T->getInterface()->getName()).str());
2647 
2648   for (const auto &Q : T->quals())
2649     mangleObjCProtocol(Q);
2650   Out << '@';
2651 
2652   Out << '@';
2653 
2654   TypeBackReferences.swap(OuterArgsContext);
2655   NameBackReferences.swap(OuterTemplateContext);
2656 }
2657 
2658 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2659                                          Qualifiers Quals, SourceRange Range) {
2660   QualType PointeeType = T->getPointeeType();
2661   manglePointerCVQualifiers(Quals);
2662   manglePointerExtQualifiers(Quals, PointeeType);
2663 
2664   Out << "_E";
2665 
2666   mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2667 }
2668 
2669 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2670                                          Qualifiers, SourceRange) {
2671   llvm_unreachable("Cannot mangle injected class name type.");
2672 }
2673 
2674 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2675                                          Qualifiers, SourceRange Range) {
2676   DiagnosticsEngine &Diags = Context.getDiags();
2677   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2678     "cannot mangle this template specialization type yet");
2679   Diags.Report(Range.getBegin(), DiagID)
2680     << Range;
2681 }
2682 
2683 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2684                                          SourceRange Range) {
2685   DiagnosticsEngine &Diags = Context.getDiags();
2686   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2687     "cannot mangle this dependent name type yet");
2688   Diags.Report(Range.getBegin(), DiagID)
2689     << Range;
2690 }
2691 
2692 void MicrosoftCXXNameMangler::mangleType(
2693     const DependentTemplateSpecializationType *T, Qualifiers,
2694     SourceRange Range) {
2695   DiagnosticsEngine &Diags = Context.getDiags();
2696   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2697     "cannot mangle this dependent template specialization type yet");
2698   Diags.Report(Range.getBegin(), DiagID)
2699     << Range;
2700 }
2701 
2702 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2703                                          SourceRange Range) {
2704   DiagnosticsEngine &Diags = Context.getDiags();
2705   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2706     "cannot mangle this pack expansion yet");
2707   Diags.Report(Range.getBegin(), DiagID)
2708     << Range;
2709 }
2710 
2711 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2712                                          SourceRange Range) {
2713   DiagnosticsEngine &Diags = Context.getDiags();
2714   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2715     "cannot mangle this typeof(type) yet");
2716   Diags.Report(Range.getBegin(), DiagID)
2717     << Range;
2718 }
2719 
2720 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2721                                          SourceRange Range) {
2722   DiagnosticsEngine &Diags = Context.getDiags();
2723   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2724     "cannot mangle this typeof(expression) yet");
2725   Diags.Report(Range.getBegin(), DiagID)
2726     << Range;
2727 }
2728 
2729 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2730                                          SourceRange Range) {
2731   DiagnosticsEngine &Diags = Context.getDiags();
2732   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2733     "cannot mangle this decltype() yet");
2734   Diags.Report(Range.getBegin(), DiagID)
2735     << Range;
2736 }
2737 
2738 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2739                                          Qualifiers, SourceRange Range) {
2740   DiagnosticsEngine &Diags = Context.getDiags();
2741   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2742     "cannot mangle this unary transform type yet");
2743   Diags.Report(Range.getBegin(), DiagID)
2744     << Range;
2745 }
2746 
2747 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2748                                          SourceRange Range) {
2749   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2750 
2751   DiagnosticsEngine &Diags = Context.getDiags();
2752   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2753     "cannot mangle this 'auto' type yet");
2754   Diags.Report(Range.getBegin(), DiagID)
2755     << Range;
2756 }
2757 
2758 void MicrosoftCXXNameMangler::mangleType(
2759     const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) {
2760   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2761 
2762   DiagnosticsEngine &Diags = Context.getDiags();
2763   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2764     "cannot mangle this deduced class template specialization type yet");
2765   Diags.Report(Range.getBegin(), DiagID)
2766     << Range;
2767 }
2768 
2769 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2770                                          SourceRange Range) {
2771   QualType ValueType = T->getValueType();
2772 
2773   llvm::SmallString<64> TemplateMangling;
2774   llvm::raw_svector_ostream Stream(TemplateMangling);
2775   MicrosoftCXXNameMangler Extra(Context, Stream);
2776   Stream << "?$";
2777   Extra.mangleSourceName("_Atomic");
2778   Extra.mangleType(ValueType, Range, QMM_Escape);
2779 
2780   mangleArtificalTagType(TTK_Struct, TemplateMangling, {"__clang"});
2781 }
2782 
2783 void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
2784                                          SourceRange Range) {
2785   DiagnosticsEngine &Diags = Context.getDiags();
2786   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2787     "cannot mangle this OpenCL pipe type yet");
2788   Diags.Report(Range.getBegin(), DiagID)
2789     << Range;
2790 }
2791 
2792 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
2793                                                raw_ostream &Out) {
2794   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
2795          "Invalid mangleName() call, argument is not a variable or function!");
2796   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
2797          "Invalid mangleName() call on 'structor decl!");
2798 
2799   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2800                                  getASTContext().getSourceManager(),
2801                                  "Mangling declaration");
2802 
2803   msvc_hashing_ostream MHO(Out);
2804   MicrosoftCXXNameMangler Mangler(*this, MHO);
2805   return Mangler.mangle(D);
2806 }
2807 
2808 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2809 //                       <virtual-adjustment>
2810 // <no-adjustment>      ::= A # private near
2811 //                      ::= B # private far
2812 //                      ::= I # protected near
2813 //                      ::= J # protected far
2814 //                      ::= Q # public near
2815 //                      ::= R # public far
2816 // <static-adjustment>  ::= G <static-offset> # private near
2817 //                      ::= H <static-offset> # private far
2818 //                      ::= O <static-offset> # protected near
2819 //                      ::= P <static-offset> # protected far
2820 //                      ::= W <static-offset> # public near
2821 //                      ::= X <static-offset> # public far
2822 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2823 //                      ::= $1 <virtual-shift> <static-offset> # private far
2824 //                      ::= $2 <virtual-shift> <static-offset> # protected near
2825 //                      ::= $3 <virtual-shift> <static-offset> # protected far
2826 //                      ::= $4 <virtual-shift> <static-offset> # public near
2827 //                      ::= $5 <virtual-shift> <static-offset> # public far
2828 // <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
2829 // <vtordisp-shift>     ::= <offset-to-vtordisp>
2830 // <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
2831 //                          <offset-to-vtordisp>
2832 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2833                                       const ThisAdjustment &Adjustment,
2834                                       MicrosoftCXXNameMangler &Mangler,
2835                                       raw_ostream &Out) {
2836   if (!Adjustment.Virtual.isEmpty()) {
2837     Out << '$';
2838     char AccessSpec;
2839     switch (MD->getAccess()) {
2840     case AS_none:
2841       llvm_unreachable("Unsupported access specifier");
2842     case AS_private:
2843       AccessSpec = '0';
2844       break;
2845     case AS_protected:
2846       AccessSpec = '2';
2847       break;
2848     case AS_public:
2849       AccessSpec = '4';
2850     }
2851     if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2852       Out << 'R' << AccessSpec;
2853       Mangler.mangleNumber(
2854           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2855       Mangler.mangleNumber(
2856           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2857       Mangler.mangleNumber(
2858           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2859       Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2860     } else {
2861       Out << AccessSpec;
2862       Mangler.mangleNumber(
2863           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2864       Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2865     }
2866   } else if (Adjustment.NonVirtual != 0) {
2867     switch (MD->getAccess()) {
2868     case AS_none:
2869       llvm_unreachable("Unsupported access specifier");
2870     case AS_private:
2871       Out << 'G';
2872       break;
2873     case AS_protected:
2874       Out << 'O';
2875       break;
2876     case AS_public:
2877       Out << 'W';
2878     }
2879     Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2880   } else {
2881     switch (MD->getAccess()) {
2882     case AS_none:
2883       llvm_unreachable("Unsupported access specifier");
2884     case AS_private:
2885       Out << 'A';
2886       break;
2887     case AS_protected:
2888       Out << 'I';
2889       break;
2890     case AS_public:
2891       Out << 'Q';
2892     }
2893   }
2894 }
2895 
2896 void MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(
2897     const CXXMethodDecl *MD, const MethodVFTableLocation &ML,
2898     raw_ostream &Out) {
2899   msvc_hashing_ostream MHO(Out);
2900   MicrosoftCXXNameMangler Mangler(*this, MHO);
2901   Mangler.getStream() << '?';
2902   Mangler.mangleVirtualMemPtrThunk(MD, ML);
2903 }
2904 
2905 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2906                                              const ThunkInfo &Thunk,
2907                                              raw_ostream &Out) {
2908   msvc_hashing_ostream MHO(Out);
2909   MicrosoftCXXNameMangler Mangler(*this, MHO);
2910   Mangler.getStream() << '?';
2911   Mangler.mangleName(MD);
2912   mangleThunkThisAdjustment(MD, Thunk.This, Mangler, MHO);
2913   if (!Thunk.Return.isEmpty())
2914     assert(Thunk.Method != nullptr &&
2915            "Thunk info should hold the overridee decl");
2916 
2917   const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2918   Mangler.mangleFunctionType(
2919       DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2920 }
2921 
2922 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2923     const CXXDestructorDecl *DD, CXXDtorType Type,
2924     const ThisAdjustment &Adjustment, raw_ostream &Out) {
2925   // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2926   // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2927   // mangling manually until we support both deleting dtor types.
2928   assert(Type == Dtor_Deleting);
2929   msvc_hashing_ostream MHO(Out);
2930   MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
2931   Mangler.getStream() << "??_E";
2932   Mangler.mangleName(DD->getParent());
2933   mangleThunkThisAdjustment(DD, Adjustment, Mangler, MHO);
2934   Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2935 }
2936 
2937 void MicrosoftMangleContextImpl::mangleCXXVFTable(
2938     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2939     raw_ostream &Out) {
2940   // <mangled-name> ::= ?_7 <class-name> <storage-class>
2941   //                    <cvr-qualifiers> [<name>] @
2942   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2943   // is always '6' for vftables.
2944   msvc_hashing_ostream MHO(Out);
2945   MicrosoftCXXNameMangler Mangler(*this, MHO);
2946   if (Derived->hasAttr<DLLImportAttr>())
2947     Mangler.getStream() << "??_S";
2948   else
2949     Mangler.getStream() << "??_7";
2950   Mangler.mangleName(Derived);
2951   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2952   for (const CXXRecordDecl *RD : BasePath)
2953     Mangler.mangleName(RD);
2954   Mangler.getStream() << '@';
2955 }
2956 
2957 void MicrosoftMangleContextImpl::mangleCXXVBTable(
2958     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2959     raw_ostream &Out) {
2960   // <mangled-name> ::= ?_8 <class-name> <storage-class>
2961   //                    <cvr-qualifiers> [<name>] @
2962   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2963   // is always '7' for vbtables.
2964   msvc_hashing_ostream MHO(Out);
2965   MicrosoftCXXNameMangler Mangler(*this, MHO);
2966   Mangler.getStream() << "??_8";
2967   Mangler.mangleName(Derived);
2968   Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
2969   for (const CXXRecordDecl *RD : BasePath)
2970     Mangler.mangleName(RD);
2971   Mangler.getStream() << '@';
2972 }
2973 
2974 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
2975   msvc_hashing_ostream MHO(Out);
2976   MicrosoftCXXNameMangler Mangler(*this, MHO);
2977   Mangler.getStream() << "??_R0";
2978   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2979   Mangler.getStream() << "@8";
2980 }
2981 
2982 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
2983                                                    raw_ostream &Out) {
2984   MicrosoftCXXNameMangler Mangler(*this, Out);
2985   Mangler.getStream() << '.';
2986   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
2987 }
2988 
2989 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
2990     const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
2991   msvc_hashing_ostream MHO(Out);
2992   MicrosoftCXXNameMangler Mangler(*this, MHO);
2993   Mangler.getStream() << "??_K";
2994   Mangler.mangleName(SrcRD);
2995   Mangler.getStream() << "$C";
2996   Mangler.mangleName(DstRD);
2997 }
2998 
2999 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst,
3000                                                     bool IsVolatile,
3001                                                     bool IsUnaligned,
3002                                                     uint32_t NumEntries,
3003                                                     raw_ostream &Out) {
3004   msvc_hashing_ostream MHO(Out);
3005   MicrosoftCXXNameMangler Mangler(*this, MHO);
3006   Mangler.getStream() << "_TI";
3007   if (IsConst)
3008     Mangler.getStream() << 'C';
3009   if (IsVolatile)
3010     Mangler.getStream() << 'V';
3011   if (IsUnaligned)
3012     Mangler.getStream() << 'U';
3013   Mangler.getStream() << NumEntries;
3014   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3015 }
3016 
3017 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
3018     QualType T, uint32_t NumEntries, raw_ostream &Out) {
3019   msvc_hashing_ostream MHO(Out);
3020   MicrosoftCXXNameMangler Mangler(*this, MHO);
3021   Mangler.getStream() << "_CTA";
3022   Mangler.getStream() << NumEntries;
3023   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3024 }
3025 
3026 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
3027     QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
3028     uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
3029     raw_ostream &Out) {
3030   MicrosoftCXXNameMangler Mangler(*this, Out);
3031   Mangler.getStream() << "_CT";
3032 
3033   llvm::SmallString<64> RTTIMangling;
3034   {
3035     llvm::raw_svector_ostream Stream(RTTIMangling);
3036     msvc_hashing_ostream MHO(Stream);
3037     mangleCXXRTTI(T, MHO);
3038   }
3039   Mangler.getStream() << RTTIMangling;
3040 
3041   // VS2015 CTP6 omits the copy-constructor in the mangled name.  This name is,
3042   // in fact, superfluous but I'm not sure the change was made consciously.
3043   llvm::SmallString<64> CopyCtorMangling;
3044   if (!getASTContext().getLangOpts().isCompatibleWithMSVC(
3045           LangOptions::MSVC2015) &&
3046       CD) {
3047     llvm::raw_svector_ostream Stream(CopyCtorMangling);
3048     msvc_hashing_ostream MHO(Stream);
3049     mangleCXXCtor(CD, CT, MHO);
3050   }
3051   Mangler.getStream() << CopyCtorMangling;
3052 
3053   Mangler.getStream() << Size;
3054   if (VBPtrOffset == -1) {
3055     if (NVOffset) {
3056       Mangler.getStream() << NVOffset;
3057     }
3058   } else {
3059     Mangler.getStream() << NVOffset;
3060     Mangler.getStream() << VBPtrOffset;
3061     Mangler.getStream() << VBIndex;
3062   }
3063 }
3064 
3065 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
3066     const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
3067     uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
3068   msvc_hashing_ostream MHO(Out);
3069   MicrosoftCXXNameMangler Mangler(*this, MHO);
3070   Mangler.getStream() << "??_R1";
3071   Mangler.mangleNumber(NVOffset);
3072   Mangler.mangleNumber(VBPtrOffset);
3073   Mangler.mangleNumber(VBTableOffset);
3074   Mangler.mangleNumber(Flags);
3075   Mangler.mangleName(Derived);
3076   Mangler.getStream() << "8";
3077 }
3078 
3079 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
3080     const CXXRecordDecl *Derived, raw_ostream &Out) {
3081   msvc_hashing_ostream MHO(Out);
3082   MicrosoftCXXNameMangler Mangler(*this, MHO);
3083   Mangler.getStream() << "??_R2";
3084   Mangler.mangleName(Derived);
3085   Mangler.getStream() << "8";
3086 }
3087 
3088 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
3089     const CXXRecordDecl *Derived, raw_ostream &Out) {
3090   msvc_hashing_ostream MHO(Out);
3091   MicrosoftCXXNameMangler Mangler(*this, MHO);
3092   Mangler.getStream() << "??_R3";
3093   Mangler.mangleName(Derived);
3094   Mangler.getStream() << "8";
3095 }
3096 
3097 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
3098     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3099     raw_ostream &Out) {
3100   // <mangled-name> ::= ?_R4 <class-name> <storage-class>
3101   //                    <cvr-qualifiers> [<name>] @
3102   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3103   // is always '6' for vftables.
3104   llvm::SmallString<64> VFTableMangling;
3105   llvm::raw_svector_ostream Stream(VFTableMangling);
3106   mangleCXXVFTable(Derived, BasePath, Stream);
3107 
3108   if (VFTableMangling.startswith("??@")) {
3109     assert(VFTableMangling.endswith("@"));
3110     Out << VFTableMangling << "??_R4@";
3111     return;
3112   }
3113 
3114   assert(VFTableMangling.startswith("??_7") ||
3115          VFTableMangling.startswith("??_S"));
3116 
3117   Out << "??_R4" << StringRef(VFTableMangling).drop_front(4);
3118 }
3119 
3120 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
3121     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3122   msvc_hashing_ostream MHO(Out);
3123   MicrosoftCXXNameMangler Mangler(*this, MHO);
3124   // The function body is in the same comdat as the function with the handler,
3125   // so the numbering here doesn't have to be the same across TUs.
3126   //
3127   // <mangled-name> ::= ?filt$ <filter-number> @0
3128   Mangler.getStream() << "?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
3129   Mangler.mangleName(EnclosingDecl);
3130 }
3131 
3132 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
3133     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3134   msvc_hashing_ostream MHO(Out);
3135   MicrosoftCXXNameMangler Mangler(*this, MHO);
3136   // The function body is in the same comdat as the function with the handler,
3137   // so the numbering here doesn't have to be the same across TUs.
3138   //
3139   // <mangled-name> ::= ?fin$ <filter-number> @0
3140   Mangler.getStream() << "?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
3141   Mangler.mangleName(EnclosingDecl);
3142 }
3143 
3144 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
3145   // This is just a made up unique string for the purposes of tbaa.  undname
3146   // does *not* know how to demangle it.
3147   MicrosoftCXXNameMangler Mangler(*this, Out);
3148   Mangler.getStream() << '?';
3149   Mangler.mangleType(T, SourceRange());
3150 }
3151 
3152 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
3153                                                CXXCtorType Type,
3154                                                raw_ostream &Out) {
3155   msvc_hashing_ostream MHO(Out);
3156   MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
3157   mangler.mangle(D);
3158 }
3159 
3160 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
3161                                                CXXDtorType Type,
3162                                                raw_ostream &Out) {
3163   msvc_hashing_ostream MHO(Out);
3164   MicrosoftCXXNameMangler mangler(*this, MHO, D, Type);
3165   mangler.mangle(D);
3166 }
3167 
3168 void MicrosoftMangleContextImpl::mangleReferenceTemporary(
3169     const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
3170   msvc_hashing_ostream MHO(Out);
3171   MicrosoftCXXNameMangler Mangler(*this, MHO);
3172 
3173   Mangler.getStream() << "?$RT" << ManglingNumber << '@';
3174   Mangler.mangle(VD, "");
3175 }
3176 
3177 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
3178     const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
3179   msvc_hashing_ostream MHO(Out);
3180   MicrosoftCXXNameMangler Mangler(*this, MHO);
3181 
3182   Mangler.getStream() << "?$TSS" << GuardNum << '@';
3183   Mangler.mangleNestedName(VD);
3184   Mangler.getStream() << "@4HA";
3185 }
3186 
3187 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
3188                                                            raw_ostream &Out) {
3189   // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
3190   //              ::= ?__J <postfix> @5 <scope-depth>
3191   //              ::= ?$S <guard-num> @ <postfix> @4IA
3192 
3193   // The first mangling is what MSVC uses to guard static locals in inline
3194   // functions.  It uses a different mangling in external functions to support
3195   // guarding more than 32 variables.  MSVC rejects inline functions with more
3196   // than 32 static locals.  We don't fully implement the second mangling
3197   // because those guards are not externally visible, and instead use LLVM's
3198   // default renaming when creating a new guard variable.
3199   msvc_hashing_ostream MHO(Out);
3200   MicrosoftCXXNameMangler Mangler(*this, MHO);
3201 
3202   bool Visible = VD->isExternallyVisible();
3203   if (Visible) {
3204     Mangler.getStream() << (VD->getTLSKind() ? "??__J" : "??_B");
3205   } else {
3206     Mangler.getStream() << "?$S1@";
3207   }
3208   unsigned ScopeDepth = 0;
3209   if (Visible && !getNextDiscriminator(VD, ScopeDepth))
3210     // If we do not have a discriminator and are emitting a guard variable for
3211     // use at global scope, then mangling the nested name will not be enough to
3212     // remove ambiguities.
3213     Mangler.mangle(VD, "");
3214   else
3215     Mangler.mangleNestedName(VD);
3216   Mangler.getStream() << (Visible ? "@5" : "@4IA");
3217   if (ScopeDepth)
3218     Mangler.mangleNumber(ScopeDepth);
3219 }
3220 
3221 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
3222                                                     char CharCode,
3223                                                     raw_ostream &Out) {
3224   msvc_hashing_ostream MHO(Out);
3225   MicrosoftCXXNameMangler Mangler(*this, MHO);
3226   Mangler.getStream() << "??__" << CharCode;
3227   if (D->isStaticDataMember()) {
3228     Mangler.getStream() << '?';
3229     Mangler.mangleName(D);
3230     Mangler.mangleVariableEncoding(D);
3231     Mangler.getStream() << "@@";
3232   } else {
3233     Mangler.mangleName(D);
3234   }
3235   // This is the function class mangling.  These stubs are global, non-variadic,
3236   // cdecl functions that return void and take no args.
3237   Mangler.getStream() << "YAXXZ";
3238 }
3239 
3240 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
3241                                                           raw_ostream &Out) {
3242   // <initializer-name> ::= ?__E <name> YAXXZ
3243   mangleInitFiniStub(D, 'E', Out);
3244 }
3245 
3246 void
3247 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3248                                                           raw_ostream &Out) {
3249   // <destructor-name> ::= ?__F <name> YAXXZ
3250   mangleInitFiniStub(D, 'F', Out);
3251 }
3252 
3253 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
3254                                                      raw_ostream &Out) {
3255   // <char-type> ::= 0   # char, char16_t, char32_t
3256   //                     # (little endian char data in mangling)
3257   //             ::= 1   # wchar_t (big endian char data in mangling)
3258   //
3259   // <literal-length> ::= <non-negative integer>  # the length of the literal
3260   //
3261   // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
3262   //                                              # trailing null bytes
3263   //
3264   // <encoded-string> ::= <simple character>           # uninteresting character
3265   //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
3266   //                                                   # encode the byte for the
3267   //                                                   # character
3268   //                  ::= '?' [a-z]                    # \xe1 - \xfa
3269   //                  ::= '?' [A-Z]                    # \xc1 - \xda
3270   //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
3271   //
3272   // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
3273   //               <encoded-string> '@'
3274   MicrosoftCXXNameMangler Mangler(*this, Out);
3275   Mangler.getStream() << "??_C@_";
3276 
3277   // The actual string length might be different from that of the string literal
3278   // in cases like:
3279   // char foo[3] = "foobar";
3280   // char bar[42] = "foobar";
3281   // Where it is truncated or zero-padded to fit the array. This is the length
3282   // used for mangling, and any trailing null-bytes also need to be mangled.
3283   unsigned StringLength = getASTContext()
3284                               .getAsConstantArrayType(SL->getType())
3285                               ->getSize()
3286                               .getZExtValue();
3287   unsigned StringByteLength = StringLength * SL->getCharByteWidth();
3288 
3289   // <char-type>: The "kind" of string literal is encoded into the mangled name.
3290   if (SL->isWide())
3291     Mangler.getStream() << '1';
3292   else
3293     Mangler.getStream() << '0';
3294 
3295   // <literal-length>: The next part of the mangled name consists of the length
3296   // of the string in bytes.
3297   Mangler.mangleNumber(StringByteLength);
3298 
3299   auto GetLittleEndianByte = [&SL](unsigned Index) {
3300     unsigned CharByteWidth = SL->getCharByteWidth();
3301     if (Index / CharByteWidth >= SL->getLength())
3302       return static_cast<char>(0);
3303     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3304     unsigned OffsetInCodeUnit = Index % CharByteWidth;
3305     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3306   };
3307 
3308   auto GetBigEndianByte = [&SL](unsigned Index) {
3309     unsigned CharByteWidth = SL->getCharByteWidth();
3310     if (Index / CharByteWidth >= SL->getLength())
3311       return static_cast<char>(0);
3312     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3313     unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
3314     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3315   };
3316 
3317   // CRC all the bytes of the StringLiteral.
3318   llvm::JamCRC JC;
3319   for (unsigned I = 0, E = StringByteLength; I != E; ++I)
3320     JC.update(GetLittleEndianByte(I));
3321 
3322   // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
3323   // scheme.
3324   Mangler.mangleNumber(JC.getCRC());
3325 
3326   // <encoded-string>: The mangled name also contains the first 32 bytes
3327   // (including null-terminator bytes) of the encoded StringLiteral.
3328   // Each character is encoded by splitting them into bytes and then encoding
3329   // the constituent bytes.
3330   auto MangleByte = [&Mangler](char Byte) {
3331     // There are five different manglings for characters:
3332     // - [a-zA-Z0-9_$]: A one-to-one mapping.
3333     // - ?[a-z]: The range from \xe1 to \xfa.
3334     // - ?[A-Z]: The range from \xc1 to \xda.
3335     // - ?[0-9]: The set of [,/\:. \n\t'-].
3336     // - ?$XX: A fallback which maps nibbles.
3337     if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
3338       Mangler.getStream() << Byte;
3339     } else if (isLetter(Byte & 0x7f)) {
3340       Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
3341     } else {
3342       const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
3343                                    ' ', '\n', '\t', '\'', '-'};
3344       const char *Pos =
3345           std::find(std::begin(SpecialChars), std::end(SpecialChars), Byte);
3346       if (Pos != std::end(SpecialChars)) {
3347         Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
3348       } else {
3349         Mangler.getStream() << "?$";
3350         Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
3351         Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
3352       }
3353     }
3354   };
3355 
3356   // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
3357   unsigned MaxBytesToMangle = SL->isWide() ? 64U : 32U;
3358   unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength);
3359   for (unsigned I = 0; I != NumBytesToMangle; ++I) {
3360     if (SL->isWide())
3361       MangleByte(GetBigEndianByte(I));
3362     else
3363       MangleByte(GetLittleEndianByte(I));
3364   }
3365 
3366   Mangler.getStream() << '@';
3367 }
3368 
3369 MicrosoftMangleContext *
3370 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
3371   return new MicrosoftMangleContextImpl(Context, Diags);
3372 }
3373