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