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 is a variable or a class member and not a parameter,
951           // it is encoded in a qualified name.
952           if (LambdaManglingNumber && LambdaContextDecl) {
953             if ((isa<VarDecl>(LambdaContextDecl) ||
954                  isa<FieldDecl>(LambdaContextDecl)) &&
955                 !isa<ParmVarDecl>(LambdaContextDecl)) {
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   if (Optional<llvm::APSInt> Value =
1376           E->getIntegerConstantExpr(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" | "device" | "host" ]
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_global_device:
1827       Extra.mangleSourceName("_ASCLdevice");
1828       break;
1829     case LangAS::opencl_global_host:
1830       Extra.mangleSourceName("_ASCLhost");
1831       break;
1832     case LangAS::opencl_local:
1833       Extra.mangleSourceName("_ASCLlocal");
1834       break;
1835     case LangAS::opencl_constant:
1836       Extra.mangleSourceName("_ASCLconstant");
1837       break;
1838     case LangAS::opencl_private:
1839       Extra.mangleSourceName("_ASCLprivate");
1840       break;
1841     case LangAS::opencl_generic:
1842       Extra.mangleSourceName("_ASCLgeneric");
1843       break;
1844     case LangAS::cuda_device:
1845       Extra.mangleSourceName("_ASCUdevice");
1846       break;
1847     case LangAS::cuda_constant:
1848       Extra.mangleSourceName("_ASCUconstant");
1849       break;
1850     case LangAS::cuda_shared:
1851       Extra.mangleSourceName("_ASCUshared");
1852       break;
1853     case LangAS::ptr32_sptr:
1854     case LangAS::ptr32_uptr:
1855     case LangAS::ptr64:
1856       llvm_unreachable("don't mangle ptr address spaces with _AS");
1857     }
1858   }
1859 
1860   Extra.mangleType(T, Range, QMM_Escape);
1861   mangleQualifiers(Qualifiers(), false);
1862   mangleArtificialTagType(TTK_Struct, ASMangling, {"__clang"});
1863 }
1864 
1865 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1866                                          QualifierMangleMode QMM) {
1867   // Don't use the canonical types.  MSVC includes things like 'const' on
1868   // pointer arguments to function pointers that canonicalization strips away.
1869   T = T.getDesugaredType(getASTContext());
1870   Qualifiers Quals = T.getLocalQualifiers();
1871 
1872   if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1873     // If there were any Quals, getAsArrayType() pushed them onto the array
1874     // element type.
1875     if (QMM == QMM_Mangle)
1876       Out << 'A';
1877     else if (QMM == QMM_Escape || QMM == QMM_Result)
1878       Out << "$$B";
1879     mangleArrayType(AT);
1880     return;
1881   }
1882 
1883   bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1884                    T->isReferenceType() || T->isBlockPointerType();
1885 
1886   switch (QMM) {
1887   case QMM_Drop:
1888     if (Quals.hasObjCLifetime())
1889       Quals = Quals.withoutObjCLifetime();
1890     break;
1891   case QMM_Mangle:
1892     if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1893       Out << '6';
1894       mangleFunctionType(FT);
1895       return;
1896     }
1897     mangleQualifiers(Quals, false);
1898     break;
1899   case QMM_Escape:
1900     if (!IsPointer && Quals) {
1901       Out << "$$C";
1902       mangleQualifiers(Quals, false);
1903     }
1904     break;
1905   case QMM_Result:
1906     // Presence of __unaligned qualifier shouldn't affect mangling here.
1907     Quals.removeUnaligned();
1908     if (Quals.hasObjCLifetime())
1909       Quals = Quals.withoutObjCLifetime();
1910     if ((!IsPointer && Quals) || isa<TagType>(T) || isArtificialTagType(T)) {
1911       Out << '?';
1912       mangleQualifiers(Quals, false);
1913     }
1914     break;
1915   }
1916 
1917   const Type *ty = T.getTypePtr();
1918 
1919   switch (ty->getTypeClass()) {
1920 #define ABSTRACT_TYPE(CLASS, PARENT)
1921 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1922   case Type::CLASS: \
1923     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1924     return;
1925 #define TYPE(CLASS, PARENT) \
1926   case Type::CLASS: \
1927     mangleType(cast<CLASS##Type>(ty), Quals, Range); \
1928     break;
1929 #include "clang/AST/TypeNodes.inc"
1930 #undef ABSTRACT_TYPE
1931 #undef NON_CANONICAL_TYPE
1932 #undef TYPE
1933   }
1934 }
1935 
1936 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
1937                                          SourceRange Range) {
1938   //  <type>         ::= <builtin-type>
1939   //  <builtin-type> ::= X  # void
1940   //                 ::= C  # signed char
1941   //                 ::= D  # char
1942   //                 ::= E  # unsigned char
1943   //                 ::= F  # short
1944   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1945   //                 ::= H  # int
1946   //                 ::= I  # unsigned int
1947   //                 ::= J  # long
1948   //                 ::= K  # unsigned long
1949   //                     L  # <none>
1950   //                 ::= M  # float
1951   //                 ::= N  # double
1952   //                 ::= O  # long double (__float80 is mangled differently)
1953   //                 ::= _J # long long, __int64
1954   //                 ::= _K # unsigned long long, __int64
1955   //                 ::= _L # __int128
1956   //                 ::= _M # unsigned __int128
1957   //                 ::= _N # bool
1958   //                     _O # <array in parameter>
1959   //                 ::= _Q # char8_t
1960   //                 ::= _S # char16_t
1961   //                 ::= _T # __float80 (Intel)
1962   //                 ::= _U # char32_t
1963   //                 ::= _W # wchar_t
1964   //                 ::= _Z # __float80 (Digital Mars)
1965   switch (T->getKind()) {
1966   case BuiltinType::Void:
1967     Out << 'X';
1968     break;
1969   case BuiltinType::SChar:
1970     Out << 'C';
1971     break;
1972   case BuiltinType::Char_U:
1973   case BuiltinType::Char_S:
1974     Out << 'D';
1975     break;
1976   case BuiltinType::UChar:
1977     Out << 'E';
1978     break;
1979   case BuiltinType::Short:
1980     Out << 'F';
1981     break;
1982   case BuiltinType::UShort:
1983     Out << 'G';
1984     break;
1985   case BuiltinType::Int:
1986     Out << 'H';
1987     break;
1988   case BuiltinType::UInt:
1989     Out << 'I';
1990     break;
1991   case BuiltinType::Long:
1992     Out << 'J';
1993     break;
1994   case BuiltinType::ULong:
1995     Out << 'K';
1996     break;
1997   case BuiltinType::Float:
1998     Out << 'M';
1999     break;
2000   case BuiltinType::Double:
2001     Out << 'N';
2002     break;
2003   // TODO: Determine size and mangle accordingly
2004   case BuiltinType::LongDouble:
2005     Out << 'O';
2006     break;
2007   case BuiltinType::LongLong:
2008     Out << "_J";
2009     break;
2010   case BuiltinType::ULongLong:
2011     Out << "_K";
2012     break;
2013   case BuiltinType::Int128:
2014     Out << "_L";
2015     break;
2016   case BuiltinType::UInt128:
2017     Out << "_M";
2018     break;
2019   case BuiltinType::Bool:
2020     Out << "_N";
2021     break;
2022   case BuiltinType::Char8:
2023     Out << "_Q";
2024     break;
2025   case BuiltinType::Char16:
2026     Out << "_S";
2027     break;
2028   case BuiltinType::Char32:
2029     Out << "_U";
2030     break;
2031   case BuiltinType::WChar_S:
2032   case BuiltinType::WChar_U:
2033     Out << "_W";
2034     break;
2035 
2036 #define BUILTIN_TYPE(Id, SingletonId)
2037 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2038   case BuiltinType::Id:
2039 #include "clang/AST/BuiltinTypes.def"
2040   case BuiltinType::Dependent:
2041     llvm_unreachable("placeholder types shouldn't get to name mangling");
2042 
2043   case BuiltinType::ObjCId:
2044     mangleArtificialTagType(TTK_Struct, "objc_object");
2045     break;
2046   case BuiltinType::ObjCClass:
2047     mangleArtificialTagType(TTK_Struct, "objc_class");
2048     break;
2049   case BuiltinType::ObjCSel:
2050     mangleArtificialTagType(TTK_Struct, "objc_selector");
2051     break;
2052 
2053 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2054   case BuiltinType::Id: \
2055     Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \
2056     break;
2057 #include "clang/Basic/OpenCLImageTypes.def"
2058   case BuiltinType::OCLSampler:
2059     Out << "PA";
2060     mangleArtificialTagType(TTK_Struct, "ocl_sampler");
2061     break;
2062   case BuiltinType::OCLEvent:
2063     Out << "PA";
2064     mangleArtificialTagType(TTK_Struct, "ocl_event");
2065     break;
2066   case BuiltinType::OCLClkEvent:
2067     Out << "PA";
2068     mangleArtificialTagType(TTK_Struct, "ocl_clkevent");
2069     break;
2070   case BuiltinType::OCLQueue:
2071     Out << "PA";
2072     mangleArtificialTagType(TTK_Struct, "ocl_queue");
2073     break;
2074   case BuiltinType::OCLReserveID:
2075     Out << "PA";
2076     mangleArtificialTagType(TTK_Struct, "ocl_reserveid");
2077     break;
2078 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
2079   case BuiltinType::Id: \
2080     mangleArtificialTagType(TTK_Struct, "ocl_" #ExtType); \
2081     break;
2082 #include "clang/Basic/OpenCLExtensionTypes.def"
2083 
2084   case BuiltinType::NullPtr:
2085     Out << "$$T";
2086     break;
2087 
2088   case BuiltinType::Float16:
2089     mangleArtificialTagType(TTK_Struct, "_Float16", {"__clang"});
2090     break;
2091 
2092   case BuiltinType::Half:
2093     mangleArtificialTagType(TTK_Struct, "_Half", {"__clang"});
2094     break;
2095 
2096 #define SVE_TYPE(Name, Id, SingletonId) \
2097   case BuiltinType::Id:
2098 #include "clang/Basic/AArch64SVEACLETypes.def"
2099   case BuiltinType::ShortAccum:
2100   case BuiltinType::Accum:
2101   case BuiltinType::LongAccum:
2102   case BuiltinType::UShortAccum:
2103   case BuiltinType::UAccum:
2104   case BuiltinType::ULongAccum:
2105   case BuiltinType::ShortFract:
2106   case BuiltinType::Fract:
2107   case BuiltinType::LongFract:
2108   case BuiltinType::UShortFract:
2109   case BuiltinType::UFract:
2110   case BuiltinType::ULongFract:
2111   case BuiltinType::SatShortAccum:
2112   case BuiltinType::SatAccum:
2113   case BuiltinType::SatLongAccum:
2114   case BuiltinType::SatUShortAccum:
2115   case BuiltinType::SatUAccum:
2116   case BuiltinType::SatULongAccum:
2117   case BuiltinType::SatShortFract:
2118   case BuiltinType::SatFract:
2119   case BuiltinType::SatLongFract:
2120   case BuiltinType::SatUShortFract:
2121   case BuiltinType::SatUFract:
2122   case BuiltinType::SatULongFract:
2123   case BuiltinType::BFloat16:
2124   case BuiltinType::Float128: {
2125     DiagnosticsEngine &Diags = Context.getDiags();
2126     unsigned DiagID = Diags.getCustomDiagID(
2127         DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
2128     Diags.Report(Range.getBegin(), DiagID)
2129         << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
2130     break;
2131   }
2132   }
2133 }
2134 
2135 // <type>          ::= <function-type>
2136 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
2137                                          SourceRange) {
2138   // Structors only appear in decls, so at this point we know it's not a
2139   // structor type.
2140   // FIXME: This may not be lambda-friendly.
2141   if (T->getMethodQuals() || T->getRefQualifier() != RQ_None) {
2142     Out << "$$A8@@";
2143     mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
2144   } else {
2145     Out << "$$A6";
2146     mangleFunctionType(T);
2147   }
2148 }
2149 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
2150                                          Qualifiers, SourceRange) {
2151   Out << "$$A6";
2152   mangleFunctionType(T);
2153 }
2154 
2155 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
2156                                                  const FunctionDecl *D,
2157                                                  bool ForceThisQuals,
2158                                                  bool MangleExceptionSpec) {
2159   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
2160   //                     <return-type> <argument-list> <throw-spec>
2161   const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
2162 
2163   SourceRange Range;
2164   if (D) Range = D->getSourceRange();
2165 
2166   bool IsInLambda = false;
2167   bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
2168   CallingConv CC = T->getCallConv();
2169   if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
2170     if (MD->getParent()->isLambda())
2171       IsInLambda = true;
2172     if (MD->isInstance())
2173       HasThisQuals = true;
2174     if (isa<CXXDestructorDecl>(MD)) {
2175       IsStructor = true;
2176     } else if (isa<CXXConstructorDecl>(MD)) {
2177       IsStructor = true;
2178       IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
2179                        StructorType == Ctor_DefaultClosure) &&
2180                       isStructorDecl(MD);
2181       if (IsCtorClosure)
2182         CC = getASTContext().getDefaultCallingConvention(
2183             /*IsVariadic=*/false, /*IsCXXMethod=*/true);
2184     }
2185   }
2186 
2187   // If this is a C++ instance method, mangle the CVR qualifiers for the
2188   // this pointer.
2189   if (HasThisQuals) {
2190     Qualifiers Quals = Proto->getMethodQuals();
2191     manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
2192     mangleRefQualifier(Proto->getRefQualifier());
2193     mangleQualifiers(Quals, /*IsMember=*/false);
2194   }
2195 
2196   mangleCallingConvention(CC);
2197 
2198   // <return-type> ::= <type>
2199   //               ::= @ # structors (they have no declared return type)
2200   if (IsStructor) {
2201     if (isa<CXXDestructorDecl>(D) && isStructorDecl(D)) {
2202       // The scalar deleting destructor takes an extra int argument which is not
2203       // reflected in the AST.
2204       if (StructorType == Dtor_Deleting) {
2205         Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
2206         return;
2207       }
2208       // The vbase destructor returns void which is not reflected in the AST.
2209       if (StructorType == Dtor_Complete) {
2210         Out << "XXZ";
2211         return;
2212       }
2213     }
2214     if (IsCtorClosure) {
2215       // Default constructor closure and copy constructor closure both return
2216       // void.
2217       Out << 'X';
2218 
2219       if (StructorType == Ctor_DefaultClosure) {
2220         // Default constructor closure always has no arguments.
2221         Out << 'X';
2222       } else if (StructorType == Ctor_CopyingClosure) {
2223         // Copy constructor closure always takes an unqualified reference.
2224         mangleFunctionArgumentType(getASTContext().getLValueReferenceType(
2225                                        Proto->getParamType(0)
2226                                            ->getAs<LValueReferenceType>()
2227                                            ->getPointeeType(),
2228                                        /*SpelledAsLValue=*/true),
2229                                    Range);
2230         Out << '@';
2231       } else {
2232         llvm_unreachable("unexpected constructor closure!");
2233       }
2234       Out << 'Z';
2235       return;
2236     }
2237     Out << '@';
2238   } else {
2239     QualType ResultType = T->getReturnType();
2240     if (const auto *AT =
2241             dyn_cast_or_null<AutoType>(ResultType->getContainedAutoType())) {
2242       Out << '?';
2243       mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
2244       Out << '?';
2245       assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2246              "shouldn't need to mangle __auto_type!");
2247       mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
2248       Out << '@';
2249     } else if (IsInLambda) {
2250       Out << '@';
2251     } else {
2252       if (ResultType->isVoidType())
2253         ResultType = ResultType.getUnqualifiedType();
2254       mangleType(ResultType, Range, QMM_Result);
2255     }
2256   }
2257 
2258   // <argument-list> ::= X # void
2259   //                 ::= <type>+ @
2260   //                 ::= <type>* Z # varargs
2261   if (!Proto) {
2262     // Function types without prototypes can arise when mangling a function type
2263     // within an overloadable function in C. We mangle these as the absence of
2264     // any parameter types (not even an empty parameter list).
2265     Out << '@';
2266   } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2267     Out << 'X';
2268   } else {
2269     // Happens for function pointer type arguments for example.
2270     for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2271       mangleFunctionArgumentType(Proto->getParamType(I), Range);
2272       // Mangle each pass_object_size parameter as if it's a parameter of enum
2273       // type passed directly after the parameter with the pass_object_size
2274       // attribute. The aforementioned enum's name is __pass_object_size, and we
2275       // pretend it resides in a top-level namespace called __clang.
2276       //
2277       // FIXME: Is there a defined extension notation for the MS ABI, or is it
2278       // necessary to just cross our fingers and hope this type+namespace
2279       // combination doesn't conflict with anything?
2280       if (D)
2281         if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
2282           manglePassObjectSizeArg(P);
2283     }
2284     // <builtin-type>      ::= Z  # ellipsis
2285     if (Proto->isVariadic())
2286       Out << 'Z';
2287     else
2288       Out << '@';
2289   }
2290 
2291   if (MangleExceptionSpec && getASTContext().getLangOpts().CPlusPlus17 &&
2292       getASTContext().getLangOpts().isCompatibleWithMSVC(
2293           LangOptions::MSVC2017_5))
2294     mangleThrowSpecification(Proto);
2295   else
2296     Out << 'Z';
2297 }
2298 
2299 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
2300   // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
2301   //                                            # pointer. in 64-bit mode *all*
2302   //                                            # 'this' pointers are 64-bit.
2303   //                   ::= <global-function>
2304   // <member-function> ::= A # private: near
2305   //                   ::= B # private: far
2306   //                   ::= C # private: static near
2307   //                   ::= D # private: static far
2308   //                   ::= E # private: virtual near
2309   //                   ::= F # private: virtual far
2310   //                   ::= I # protected: near
2311   //                   ::= J # protected: far
2312   //                   ::= K # protected: static near
2313   //                   ::= L # protected: static far
2314   //                   ::= M # protected: virtual near
2315   //                   ::= N # protected: virtual far
2316   //                   ::= Q # public: near
2317   //                   ::= R # public: far
2318   //                   ::= S # public: static near
2319   //                   ::= T # public: static far
2320   //                   ::= U # public: virtual near
2321   //                   ::= V # public: virtual far
2322   // <global-function> ::= Y # global near
2323   //                   ::= Z # global far
2324   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2325     bool IsVirtual = MD->isVirtual();
2326     // When mangling vbase destructor variants, ignore whether or not the
2327     // underlying destructor was defined to be virtual.
2328     if (isa<CXXDestructorDecl>(MD) && isStructorDecl(MD) &&
2329         StructorType == Dtor_Complete) {
2330       IsVirtual = false;
2331     }
2332     switch (MD->getAccess()) {
2333       case AS_none:
2334         llvm_unreachable("Unsupported access specifier");
2335       case AS_private:
2336         if (MD->isStatic())
2337           Out << 'C';
2338         else if (IsVirtual)
2339           Out << 'E';
2340         else
2341           Out << 'A';
2342         break;
2343       case AS_protected:
2344         if (MD->isStatic())
2345           Out << 'K';
2346         else if (IsVirtual)
2347           Out << 'M';
2348         else
2349           Out << 'I';
2350         break;
2351       case AS_public:
2352         if (MD->isStatic())
2353           Out << 'S';
2354         else if (IsVirtual)
2355           Out << 'U';
2356         else
2357           Out << 'Q';
2358     }
2359   } else {
2360     Out << 'Y';
2361   }
2362 }
2363 void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
2364   // <calling-convention> ::= A # __cdecl
2365   //                      ::= B # __export __cdecl
2366   //                      ::= C # __pascal
2367   //                      ::= D # __export __pascal
2368   //                      ::= E # __thiscall
2369   //                      ::= F # __export __thiscall
2370   //                      ::= G # __stdcall
2371   //                      ::= H # __export __stdcall
2372   //                      ::= I # __fastcall
2373   //                      ::= J # __export __fastcall
2374   //                      ::= Q # __vectorcall
2375   //                      ::= w # __regcall
2376   // The 'export' calling conventions are from a bygone era
2377   // (*cough*Win16*cough*) when functions were declared for export with
2378   // that keyword. (It didn't actually export them, it just made them so
2379   // that they could be in a DLL and somebody from another module could call
2380   // them.)
2381 
2382   switch (CC) {
2383     default:
2384       llvm_unreachable("Unsupported CC for mangling");
2385     case CC_Win64:
2386     case CC_X86_64SysV:
2387     case CC_C: Out << 'A'; break;
2388     case CC_X86Pascal: Out << 'C'; break;
2389     case CC_X86ThisCall: Out << 'E'; break;
2390     case CC_X86StdCall: Out << 'G'; break;
2391     case CC_X86FastCall: Out << 'I'; break;
2392     case CC_X86VectorCall: Out << 'Q'; break;
2393     case CC_Swift: Out << 'S'; break;
2394     case CC_PreserveMost: Out << 'U'; break;
2395     case CC_X86RegCall: Out << 'w'; break;
2396   }
2397 }
2398 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2399   mangleCallingConvention(T->getCallConv());
2400 }
2401 
2402 void MicrosoftCXXNameMangler::mangleThrowSpecification(
2403                                                 const FunctionProtoType *FT) {
2404   // <throw-spec> ::= Z # (default)
2405   //              ::= _E # noexcept
2406   if (FT->canThrow())
2407     Out << 'Z';
2408   else
2409     Out << "_E";
2410 }
2411 
2412 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2413                                          Qualifiers, SourceRange Range) {
2414   // Probably should be mangled as a template instantiation; need to see what
2415   // VC does first.
2416   DiagnosticsEngine &Diags = Context.getDiags();
2417   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2418     "cannot mangle this unresolved dependent type yet");
2419   Diags.Report(Range.getBegin(), DiagID)
2420     << Range;
2421 }
2422 
2423 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2424 // <union-type>  ::= T <name>
2425 // <struct-type> ::= U <name>
2426 // <class-type>  ::= V <name>
2427 // <enum-type>   ::= W4 <name>
2428 void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2429   switch (TTK) {
2430     case TTK_Union:
2431       Out << 'T';
2432       break;
2433     case TTK_Struct:
2434     case TTK_Interface:
2435       Out << 'U';
2436       break;
2437     case TTK_Class:
2438       Out << 'V';
2439       break;
2440     case TTK_Enum:
2441       Out << "W4";
2442       break;
2443   }
2444 }
2445 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2446                                          SourceRange) {
2447   mangleType(cast<TagType>(T)->getDecl());
2448 }
2449 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2450                                          SourceRange) {
2451   mangleType(cast<TagType>(T)->getDecl());
2452 }
2453 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2454   mangleTagTypeKind(TD->getTagKind());
2455   mangleName(TD);
2456 }
2457 
2458 // If you add a call to this, consider updating isArtificialTagType() too.
2459 void MicrosoftCXXNameMangler::mangleArtificialTagType(
2460     TagTypeKind TK, StringRef UnqualifiedName,
2461     ArrayRef<StringRef> NestedNames) {
2462   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2463   mangleTagTypeKind(TK);
2464 
2465   // Always start with the unqualified name.
2466   mangleSourceName(UnqualifiedName);
2467 
2468   for (auto I = NestedNames.rbegin(), E = NestedNames.rend(); I != E; ++I)
2469     mangleSourceName(*I);
2470 
2471   // Terminate the whole name with an '@'.
2472   Out << '@';
2473 }
2474 
2475 // <type>       ::= <array-type>
2476 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2477 //                  [Y <dimension-count> <dimension>+]
2478 //                  <element-type> # as global, E is never required
2479 // It's supposed to be the other way around, but for some strange reason, it
2480 // isn't. Today this behavior is retained for the sole purpose of backwards
2481 // compatibility.
2482 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2483   // This isn't a recursive mangling, so now we have to do it all in this
2484   // one call.
2485   manglePointerCVQualifiers(T->getElementType().getQualifiers());
2486   mangleType(T->getElementType(), SourceRange());
2487 }
2488 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2489                                          SourceRange) {
2490   llvm_unreachable("Should have been special cased");
2491 }
2492 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2493                                          SourceRange) {
2494   llvm_unreachable("Should have been special cased");
2495 }
2496 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2497                                          Qualifiers, SourceRange) {
2498   llvm_unreachable("Should have been special cased");
2499 }
2500 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2501                                          Qualifiers, SourceRange) {
2502   llvm_unreachable("Should have been special cased");
2503 }
2504 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2505   QualType ElementTy(T, 0);
2506   SmallVector<llvm::APInt, 3> Dimensions;
2507   for (;;) {
2508     if (ElementTy->isConstantArrayType()) {
2509       const ConstantArrayType *CAT =
2510           getASTContext().getAsConstantArrayType(ElementTy);
2511       Dimensions.push_back(CAT->getSize());
2512       ElementTy = CAT->getElementType();
2513     } else if (ElementTy->isIncompleteArrayType()) {
2514       const IncompleteArrayType *IAT =
2515           getASTContext().getAsIncompleteArrayType(ElementTy);
2516       Dimensions.push_back(llvm::APInt(32, 0));
2517       ElementTy = IAT->getElementType();
2518     } else if (ElementTy->isVariableArrayType()) {
2519       const VariableArrayType *VAT =
2520         getASTContext().getAsVariableArrayType(ElementTy);
2521       Dimensions.push_back(llvm::APInt(32, 0));
2522       ElementTy = VAT->getElementType();
2523     } else if (ElementTy->isDependentSizedArrayType()) {
2524       // The dependent expression has to be folded into a constant (TODO).
2525       const DependentSizedArrayType *DSAT =
2526         getASTContext().getAsDependentSizedArrayType(ElementTy);
2527       DiagnosticsEngine &Diags = Context.getDiags();
2528       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2529         "cannot mangle this dependent-length array yet");
2530       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
2531         << DSAT->getBracketsRange();
2532       return;
2533     } else {
2534       break;
2535     }
2536   }
2537   Out << 'Y';
2538   // <dimension-count> ::= <number> # number of extra dimensions
2539   mangleNumber(Dimensions.size());
2540   for (const llvm::APInt &Dimension : Dimensions)
2541     mangleNumber(Dimension.getLimitedValue());
2542   mangleType(ElementTy, SourceRange(), QMM_Escape);
2543 }
2544 
2545 // <type>                   ::= <pointer-to-member-type>
2546 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2547 //                                                          <class name> <type>
2548 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
2549                                          Qualifiers Quals, SourceRange Range) {
2550   QualType PointeeType = T->getPointeeType();
2551   manglePointerCVQualifiers(Quals);
2552   manglePointerExtQualifiers(Quals, PointeeType);
2553   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
2554     Out << '8';
2555     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2556     mangleFunctionType(FPT, nullptr, true);
2557   } else {
2558     mangleQualifiers(PointeeType.getQualifiers(), true);
2559     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
2560     mangleType(PointeeType, Range, QMM_Drop);
2561   }
2562 }
2563 
2564 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
2565                                          Qualifiers, SourceRange Range) {
2566   DiagnosticsEngine &Diags = Context.getDiags();
2567   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2568     "cannot mangle this template type parameter type yet");
2569   Diags.Report(Range.getBegin(), DiagID)
2570     << Range;
2571 }
2572 
2573 void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
2574                                          Qualifiers, SourceRange Range) {
2575   DiagnosticsEngine &Diags = Context.getDiags();
2576   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2577     "cannot mangle this substituted parameter pack yet");
2578   Diags.Report(Range.getBegin(), DiagID)
2579     << Range;
2580 }
2581 
2582 // <type> ::= <pointer-type>
2583 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
2584 //                       # the E is required for 64-bit non-static pointers
2585 void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
2586                                          SourceRange Range) {
2587   QualType PointeeType = T->getPointeeType();
2588   manglePointerCVQualifiers(Quals);
2589   manglePointerExtQualifiers(Quals, PointeeType);
2590 
2591   // For pointer size address spaces, go down the same type mangling path as
2592   // non address space types.
2593   LangAS AddrSpace = PointeeType.getQualifiers().getAddressSpace();
2594   if (isPtrSizeAddressSpace(AddrSpace) || AddrSpace == LangAS::Default)
2595     mangleType(PointeeType, Range);
2596   else
2597     mangleAddressSpaceType(PointeeType, PointeeType.getQualifiers(), Range);
2598 }
2599 
2600 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
2601                                          Qualifiers Quals, SourceRange Range) {
2602   QualType PointeeType = T->getPointeeType();
2603   switch (Quals.getObjCLifetime()) {
2604   case Qualifiers::OCL_None:
2605   case Qualifiers::OCL_ExplicitNone:
2606     break;
2607   case Qualifiers::OCL_Autoreleasing:
2608   case Qualifiers::OCL_Strong:
2609   case Qualifiers::OCL_Weak:
2610     return mangleObjCLifetime(PointeeType, Quals, Range);
2611   }
2612   manglePointerCVQualifiers(Quals);
2613   manglePointerExtQualifiers(Quals, PointeeType);
2614   mangleType(PointeeType, Range);
2615 }
2616 
2617 // <type> ::= <reference-type>
2618 // <reference-type> ::= A E? <cvr-qualifiers> <type>
2619 //                 # the E is required for 64-bit non-static lvalue references
2620 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
2621                                          Qualifiers Quals, SourceRange Range) {
2622   QualType PointeeType = T->getPointeeType();
2623   assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2624   Out << 'A';
2625   manglePointerExtQualifiers(Quals, PointeeType);
2626   mangleType(PointeeType, Range);
2627 }
2628 
2629 // <type> ::= <r-value-reference-type>
2630 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
2631 //                 # the E is required for 64-bit non-static rvalue references
2632 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
2633                                          Qualifiers Quals, SourceRange Range) {
2634   QualType PointeeType = T->getPointeeType();
2635   assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
2636   Out << "$$Q";
2637   manglePointerExtQualifiers(Quals, PointeeType);
2638   mangleType(PointeeType, Range);
2639 }
2640 
2641 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
2642                                          SourceRange Range) {
2643   QualType ElementType = T->getElementType();
2644 
2645   llvm::SmallString<64> TemplateMangling;
2646   llvm::raw_svector_ostream Stream(TemplateMangling);
2647   MicrosoftCXXNameMangler Extra(Context, Stream);
2648   Stream << "?$";
2649   Extra.mangleSourceName("_Complex");
2650   Extra.mangleType(ElementType, Range, QMM_Escape);
2651 
2652   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
2653 }
2654 
2655 // Returns true for types that mangleArtificialTagType() gets called for with
2656 // TTK_Union, TTK_Struct, TTK_Class and where compatibility with MSVC's
2657 // mangling matters.
2658 // (It doesn't matter for Objective-C types and the like that cl.exe doesn't
2659 // support.)
2660 bool MicrosoftCXXNameMangler::isArtificialTagType(QualType T) const {
2661   const Type *ty = T.getTypePtr();
2662   switch (ty->getTypeClass()) {
2663   default:
2664     return false;
2665 
2666   case Type::Vector: {
2667     // For ABI compatibility only __m64, __m128(id), and __m256(id) matter,
2668     // but since mangleType(VectorType*) always calls mangleArtificialTagType()
2669     // just always return true (the other vector types are clang-only).
2670     return true;
2671   }
2672   }
2673 }
2674 
2675 void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
2676                                          SourceRange Range) {
2677   const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
2678   assert(ET && "vectors with non-builtin elements are unsupported");
2679   uint64_t Width = getASTContext().getTypeSize(T);
2680   // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
2681   // doesn't match the Intel types uses a custom mangling below.
2682   size_t OutSizeBefore = Out.tell();
2683   if (!isa<ExtVectorType>(T)) {
2684     if (getASTContext().getTargetInfo().getTriple().isX86()) {
2685       if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
2686         mangleArtificialTagType(TTK_Union, "__m64");
2687       } else if (Width >= 128) {
2688         if (ET->getKind() == BuiltinType::Float)
2689           mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width));
2690         else if (ET->getKind() == BuiltinType::LongLong)
2691           mangleArtificialTagType(TTK_Union, "__m" + llvm::utostr(Width) + 'i');
2692         else if (ET->getKind() == BuiltinType::Double)
2693           mangleArtificialTagType(TTK_Struct, "__m" + llvm::utostr(Width) + 'd');
2694       }
2695     }
2696   }
2697 
2698   bool IsBuiltin = Out.tell() != OutSizeBefore;
2699   if (!IsBuiltin) {
2700     // The MS ABI doesn't have a special mangling for vector types, so we define
2701     // our own mangling to handle uses of __vector_size__ on user-specified
2702     // types, and for extensions like __v4sf.
2703 
2704     llvm::SmallString<64> TemplateMangling;
2705     llvm::raw_svector_ostream Stream(TemplateMangling);
2706     MicrosoftCXXNameMangler Extra(Context, Stream);
2707     Stream << "?$";
2708     Extra.mangleSourceName("__vector");
2709     Extra.mangleType(QualType(ET, 0), Range, QMM_Escape);
2710     Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()),
2711                                /*IsBoolean=*/false);
2712 
2713     mangleArtificialTagType(TTK_Union, TemplateMangling, {"__clang"});
2714   }
2715 }
2716 
2717 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
2718                                          Qualifiers Quals, SourceRange Range) {
2719   mangleType(static_cast<const VectorType *>(T), Quals, Range);
2720 }
2721 
2722 void MicrosoftCXXNameMangler::mangleType(const DependentVectorType *T,
2723                                          Qualifiers, SourceRange Range) {
2724   DiagnosticsEngine &Diags = Context.getDiags();
2725   unsigned DiagID = Diags.getCustomDiagID(
2726       DiagnosticsEngine::Error,
2727       "cannot mangle this dependent-sized vector type yet");
2728   Diags.Report(Range.getBegin(), DiagID) << Range;
2729 }
2730 
2731 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
2732                                          Qualifiers, SourceRange Range) {
2733   DiagnosticsEngine &Diags = Context.getDiags();
2734   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2735     "cannot mangle this dependent-sized extended vector type yet");
2736   Diags.Report(Range.getBegin(), DiagID)
2737     << Range;
2738 }
2739 
2740 void MicrosoftCXXNameMangler::mangleType(const ConstantMatrixType *T,
2741                                          Qualifiers quals, SourceRange Range) {
2742   DiagnosticsEngine &Diags = Context.getDiags();
2743   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2744                                           "Cannot mangle this matrix type yet");
2745   Diags.Report(Range.getBegin(), DiagID) << Range;
2746 }
2747 
2748 void MicrosoftCXXNameMangler::mangleType(const DependentSizedMatrixType *T,
2749                                          Qualifiers quals, SourceRange Range) {
2750   DiagnosticsEngine &Diags = Context.getDiags();
2751   unsigned DiagID = Diags.getCustomDiagID(
2752       DiagnosticsEngine::Error,
2753       "Cannot mangle this dependent-sized matrix type yet");
2754   Diags.Report(Range.getBegin(), DiagID) << Range;
2755 }
2756 
2757 void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T,
2758                                          Qualifiers, SourceRange Range) {
2759   DiagnosticsEngine &Diags = Context.getDiags();
2760   unsigned DiagID = Diags.getCustomDiagID(
2761       DiagnosticsEngine::Error,
2762       "cannot mangle this dependent address space type yet");
2763   Diags.Report(Range.getBegin(), DiagID) << Range;
2764 }
2765 
2766 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
2767                                          SourceRange) {
2768   // ObjC interfaces have structs underlying them.
2769   mangleTagTypeKind(TTK_Struct);
2770   mangleName(T->getDecl());
2771 }
2772 
2773 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
2774                                          Qualifiers Quals, SourceRange Range) {
2775   if (T->isKindOfType())
2776     return mangleObjCKindOfType(T, Quals, Range);
2777 
2778   if (T->qual_empty() && !T->isSpecialized())
2779     return mangleType(T->getBaseType(), Range, QMM_Drop);
2780 
2781   ArgBackRefMap OuterFunArgsContext;
2782   ArgBackRefMap OuterTemplateArgsContext;
2783   BackRefVec OuterTemplateContext;
2784 
2785   FunArgBackReferences.swap(OuterFunArgsContext);
2786   TemplateArgBackReferences.swap(OuterTemplateArgsContext);
2787   NameBackReferences.swap(OuterTemplateContext);
2788 
2789   mangleTagTypeKind(TTK_Struct);
2790 
2791   Out << "?$";
2792   if (T->isObjCId())
2793     mangleSourceName("objc_object");
2794   else if (T->isObjCClass())
2795     mangleSourceName("objc_class");
2796   else
2797     mangleSourceName(T->getInterface()->getName());
2798 
2799   for (const auto &Q : T->quals())
2800     mangleObjCProtocol(Q);
2801 
2802   if (T->isSpecialized())
2803     for (const auto &TA : T->getTypeArgs())
2804       mangleType(TA, Range, QMM_Drop);
2805 
2806   Out << '@';
2807 
2808   Out << '@';
2809 
2810   FunArgBackReferences.swap(OuterFunArgsContext);
2811   TemplateArgBackReferences.swap(OuterTemplateArgsContext);
2812   NameBackReferences.swap(OuterTemplateContext);
2813 }
2814 
2815 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
2816                                          Qualifiers Quals, SourceRange Range) {
2817   QualType PointeeType = T->getPointeeType();
2818   manglePointerCVQualifiers(Quals);
2819   manglePointerExtQualifiers(Quals, PointeeType);
2820 
2821   Out << "_E";
2822 
2823   mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
2824 }
2825 
2826 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
2827                                          Qualifiers, SourceRange) {
2828   llvm_unreachable("Cannot mangle injected class name type.");
2829 }
2830 
2831 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
2832                                          Qualifiers, SourceRange Range) {
2833   DiagnosticsEngine &Diags = Context.getDiags();
2834   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2835     "cannot mangle this template specialization type yet");
2836   Diags.Report(Range.getBegin(), DiagID)
2837     << Range;
2838 }
2839 
2840 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
2841                                          SourceRange Range) {
2842   DiagnosticsEngine &Diags = Context.getDiags();
2843   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2844     "cannot mangle this dependent name type yet");
2845   Diags.Report(Range.getBegin(), DiagID)
2846     << Range;
2847 }
2848 
2849 void MicrosoftCXXNameMangler::mangleType(
2850     const DependentTemplateSpecializationType *T, Qualifiers,
2851     SourceRange Range) {
2852   DiagnosticsEngine &Diags = Context.getDiags();
2853   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2854     "cannot mangle this dependent template specialization type yet");
2855   Diags.Report(Range.getBegin(), DiagID)
2856     << Range;
2857 }
2858 
2859 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
2860                                          SourceRange Range) {
2861   DiagnosticsEngine &Diags = Context.getDiags();
2862   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2863     "cannot mangle this pack expansion yet");
2864   Diags.Report(Range.getBegin(), DiagID)
2865     << Range;
2866 }
2867 
2868 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
2869                                          SourceRange Range) {
2870   DiagnosticsEngine &Diags = Context.getDiags();
2871   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2872     "cannot mangle this typeof(type) yet");
2873   Diags.Report(Range.getBegin(), DiagID)
2874     << Range;
2875 }
2876 
2877 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
2878                                          SourceRange Range) {
2879   DiagnosticsEngine &Diags = Context.getDiags();
2880   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2881     "cannot mangle this typeof(expression) yet");
2882   Diags.Report(Range.getBegin(), DiagID)
2883     << Range;
2884 }
2885 
2886 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
2887                                          SourceRange Range) {
2888   DiagnosticsEngine &Diags = Context.getDiags();
2889   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2890     "cannot mangle this decltype() yet");
2891   Diags.Report(Range.getBegin(), DiagID)
2892     << Range;
2893 }
2894 
2895 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
2896                                          Qualifiers, SourceRange Range) {
2897   DiagnosticsEngine &Diags = Context.getDiags();
2898   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2899     "cannot mangle this unary transform type yet");
2900   Diags.Report(Range.getBegin(), DiagID)
2901     << Range;
2902 }
2903 
2904 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
2905                                          SourceRange Range) {
2906   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2907 
2908   DiagnosticsEngine &Diags = Context.getDiags();
2909   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2910     "cannot mangle this 'auto' type yet");
2911   Diags.Report(Range.getBegin(), DiagID)
2912     << Range;
2913 }
2914 
2915 void MicrosoftCXXNameMangler::mangleType(
2916     const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) {
2917   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
2918 
2919   DiagnosticsEngine &Diags = Context.getDiags();
2920   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2921     "cannot mangle this deduced class template specialization type yet");
2922   Diags.Report(Range.getBegin(), DiagID)
2923     << Range;
2924 }
2925 
2926 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
2927                                          SourceRange Range) {
2928   QualType ValueType = T->getValueType();
2929 
2930   llvm::SmallString<64> TemplateMangling;
2931   llvm::raw_svector_ostream Stream(TemplateMangling);
2932   MicrosoftCXXNameMangler Extra(Context, Stream);
2933   Stream << "?$";
2934   Extra.mangleSourceName("_Atomic");
2935   Extra.mangleType(ValueType, Range, QMM_Escape);
2936 
2937   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
2938 }
2939 
2940 void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
2941                                          SourceRange Range) {
2942   QualType ElementType = T->getElementType();
2943 
2944   llvm::SmallString<64> TemplateMangling;
2945   llvm::raw_svector_ostream Stream(TemplateMangling);
2946   MicrosoftCXXNameMangler Extra(Context, Stream);
2947   Stream << "?$";
2948   Extra.mangleSourceName("ocl_pipe");
2949   Extra.mangleType(ElementType, Range, QMM_Escape);
2950   Extra.mangleIntegerLiteral(llvm::APSInt::get(T->isReadOnly()), true);
2951 
2952   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
2953 }
2954 
2955 void MicrosoftMangleContextImpl::mangleCXXName(GlobalDecl GD,
2956                                                raw_ostream &Out) {
2957   const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
2958   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2959                                  getASTContext().getSourceManager(),
2960                                  "Mangling declaration");
2961 
2962   msvc_hashing_ostream MHO(Out);
2963 
2964   if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
2965     auto Type = GD.getCtorType();
2966     MicrosoftCXXNameMangler mangler(*this, MHO, CD, Type);
2967     return mangler.mangle(D);
2968   }
2969 
2970   if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
2971     auto Type = GD.getDtorType();
2972     MicrosoftCXXNameMangler mangler(*this, MHO, DD, Type);
2973     return mangler.mangle(D);
2974   }
2975 
2976   MicrosoftCXXNameMangler Mangler(*this, MHO);
2977   return Mangler.mangle(D);
2978 }
2979 
2980 void MicrosoftCXXNameMangler::mangleType(const ExtIntType *T, Qualifiers,
2981                                          SourceRange Range) {
2982   llvm::SmallString<64> TemplateMangling;
2983   llvm::raw_svector_ostream Stream(TemplateMangling);
2984   MicrosoftCXXNameMangler Extra(Context, Stream);
2985   Stream << "?$";
2986   if (T->isUnsigned())
2987     Extra.mangleSourceName("_UExtInt");
2988   else
2989     Extra.mangleSourceName("_ExtInt");
2990   Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumBits()),
2991                              /*IsBoolean=*/false);
2992 
2993   mangleArtificialTagType(TTK_Struct, TemplateMangling, {"__clang"});
2994 }
2995 
2996 void MicrosoftCXXNameMangler::mangleType(const DependentExtIntType *T,
2997                                          Qualifiers, SourceRange Range) {
2998   DiagnosticsEngine &Diags = Context.getDiags();
2999   unsigned DiagID = Diags.getCustomDiagID(
3000       DiagnosticsEngine::Error, "cannot mangle this DependentExtInt type yet");
3001   Diags.Report(Range.getBegin(), DiagID) << Range;
3002 }
3003 
3004 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
3005 //                       <virtual-adjustment>
3006 // <no-adjustment>      ::= A # private near
3007 //                      ::= B # private far
3008 //                      ::= I # protected near
3009 //                      ::= J # protected far
3010 //                      ::= Q # public near
3011 //                      ::= R # public far
3012 // <static-adjustment>  ::= G <static-offset> # private near
3013 //                      ::= H <static-offset> # private far
3014 //                      ::= O <static-offset> # protected near
3015 //                      ::= P <static-offset> # protected far
3016 //                      ::= W <static-offset> # public near
3017 //                      ::= X <static-offset> # public far
3018 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
3019 //                      ::= $1 <virtual-shift> <static-offset> # private far
3020 //                      ::= $2 <virtual-shift> <static-offset> # protected near
3021 //                      ::= $3 <virtual-shift> <static-offset> # protected far
3022 //                      ::= $4 <virtual-shift> <static-offset> # public near
3023 //                      ::= $5 <virtual-shift> <static-offset> # public far
3024 // <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
3025 // <vtordisp-shift>     ::= <offset-to-vtordisp>
3026 // <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
3027 //                          <offset-to-vtordisp>
3028 static void mangleThunkThisAdjustment(AccessSpecifier AS,
3029                                       const ThisAdjustment &Adjustment,
3030                                       MicrosoftCXXNameMangler &Mangler,
3031                                       raw_ostream &Out) {
3032   if (!Adjustment.Virtual.isEmpty()) {
3033     Out << '$';
3034     char AccessSpec;
3035     switch (AS) {
3036     case AS_none:
3037       llvm_unreachable("Unsupported access specifier");
3038     case AS_private:
3039       AccessSpec = '0';
3040       break;
3041     case AS_protected:
3042       AccessSpec = '2';
3043       break;
3044     case AS_public:
3045       AccessSpec = '4';
3046     }
3047     if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
3048       Out << 'R' << AccessSpec;
3049       Mangler.mangleNumber(
3050           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
3051       Mangler.mangleNumber(
3052           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
3053       Mangler.mangleNumber(
3054           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
3055       Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
3056     } else {
3057       Out << AccessSpec;
3058       Mangler.mangleNumber(
3059           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
3060       Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
3061     }
3062   } else if (Adjustment.NonVirtual != 0) {
3063     switch (AS) {
3064     case AS_none:
3065       llvm_unreachable("Unsupported access specifier");
3066     case AS_private:
3067       Out << 'G';
3068       break;
3069     case AS_protected:
3070       Out << 'O';
3071       break;
3072     case AS_public:
3073       Out << 'W';
3074     }
3075     Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
3076   } else {
3077     switch (AS) {
3078     case AS_none:
3079       llvm_unreachable("Unsupported access specifier");
3080     case AS_private:
3081       Out << 'A';
3082       break;
3083     case AS_protected:
3084       Out << 'I';
3085       break;
3086     case AS_public:
3087       Out << 'Q';
3088     }
3089   }
3090 }
3091 
3092 void MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(
3093     const CXXMethodDecl *MD, const MethodVFTableLocation &ML,
3094     raw_ostream &Out) {
3095   msvc_hashing_ostream MHO(Out);
3096   MicrosoftCXXNameMangler Mangler(*this, MHO);
3097   Mangler.getStream() << '?';
3098   Mangler.mangleVirtualMemPtrThunk(MD, ML);
3099 }
3100 
3101 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3102                                              const ThunkInfo &Thunk,
3103                                              raw_ostream &Out) {
3104   msvc_hashing_ostream MHO(Out);
3105   MicrosoftCXXNameMangler Mangler(*this, MHO);
3106   Mangler.getStream() << '?';
3107   Mangler.mangleName(MD);
3108 
3109   // Usually the thunk uses the access specifier of the new method, but if this
3110   // is a covariant return thunk, then MSVC always uses the public access
3111   // specifier, and we do the same.
3112   AccessSpecifier AS = Thunk.Return.isEmpty() ? MD->getAccess() : AS_public;
3113   mangleThunkThisAdjustment(AS, Thunk.This, Mangler, MHO);
3114 
3115   if (!Thunk.Return.isEmpty())
3116     assert(Thunk.Method != nullptr &&
3117            "Thunk info should hold the overridee decl");
3118 
3119   const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
3120   Mangler.mangleFunctionType(
3121       DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
3122 }
3123 
3124 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
3125     const CXXDestructorDecl *DD, CXXDtorType Type,
3126     const ThisAdjustment &Adjustment, raw_ostream &Out) {
3127   // FIXME: Actually, the dtor thunk should be emitted for vector deleting
3128   // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
3129   // mangling manually until we support both deleting dtor types.
3130   assert(Type == Dtor_Deleting);
3131   msvc_hashing_ostream MHO(Out);
3132   MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
3133   Mangler.getStream() << "??_E";
3134   Mangler.mangleName(DD->getParent());
3135   mangleThunkThisAdjustment(DD->getAccess(), Adjustment, Mangler, MHO);
3136   Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
3137 }
3138 
3139 void MicrosoftMangleContextImpl::mangleCXXVFTable(
3140     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3141     raw_ostream &Out) {
3142   // <mangled-name> ::= ?_7 <class-name> <storage-class>
3143   //                    <cvr-qualifiers> [<name>] @
3144   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3145   // is always '6' for vftables.
3146   msvc_hashing_ostream MHO(Out);
3147   MicrosoftCXXNameMangler Mangler(*this, MHO);
3148   if (Derived->hasAttr<DLLImportAttr>())
3149     Mangler.getStream() << "??_S";
3150   else
3151     Mangler.getStream() << "??_7";
3152   Mangler.mangleName(Derived);
3153   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
3154   for (const CXXRecordDecl *RD : BasePath)
3155     Mangler.mangleName(RD);
3156   Mangler.getStream() << '@';
3157 }
3158 
3159 void MicrosoftMangleContextImpl::mangleCXXVBTable(
3160     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3161     raw_ostream &Out) {
3162   // <mangled-name> ::= ?_8 <class-name> <storage-class>
3163   //                    <cvr-qualifiers> [<name>] @
3164   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3165   // is always '7' for vbtables.
3166   msvc_hashing_ostream MHO(Out);
3167   MicrosoftCXXNameMangler Mangler(*this, MHO);
3168   Mangler.getStream() << "??_8";
3169   Mangler.mangleName(Derived);
3170   Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
3171   for (const CXXRecordDecl *RD : BasePath)
3172     Mangler.mangleName(RD);
3173   Mangler.getStream() << '@';
3174 }
3175 
3176 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
3177   msvc_hashing_ostream MHO(Out);
3178   MicrosoftCXXNameMangler Mangler(*this, MHO);
3179   Mangler.getStream() << "??_R0";
3180   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3181   Mangler.getStream() << "@8";
3182 }
3183 
3184 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T,
3185                                                    raw_ostream &Out) {
3186   MicrosoftCXXNameMangler Mangler(*this, Out);
3187   Mangler.getStream() << '.';
3188   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3189 }
3190 
3191 void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
3192     const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
3193   msvc_hashing_ostream MHO(Out);
3194   MicrosoftCXXNameMangler Mangler(*this, MHO);
3195   Mangler.getStream() << "??_K";
3196   Mangler.mangleName(SrcRD);
3197   Mangler.getStream() << "$C";
3198   Mangler.mangleName(DstRD);
3199 }
3200 
3201 void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst,
3202                                                     bool IsVolatile,
3203                                                     bool IsUnaligned,
3204                                                     uint32_t NumEntries,
3205                                                     raw_ostream &Out) {
3206   msvc_hashing_ostream MHO(Out);
3207   MicrosoftCXXNameMangler Mangler(*this, MHO);
3208   Mangler.getStream() << "_TI";
3209   if (IsConst)
3210     Mangler.getStream() << 'C';
3211   if (IsVolatile)
3212     Mangler.getStream() << 'V';
3213   if (IsUnaligned)
3214     Mangler.getStream() << 'U';
3215   Mangler.getStream() << NumEntries;
3216   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3217 }
3218 
3219 void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
3220     QualType T, uint32_t NumEntries, raw_ostream &Out) {
3221   msvc_hashing_ostream MHO(Out);
3222   MicrosoftCXXNameMangler Mangler(*this, MHO);
3223   Mangler.getStream() << "_CTA";
3224   Mangler.getStream() << NumEntries;
3225   Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3226 }
3227 
3228 void MicrosoftMangleContextImpl::mangleCXXCatchableType(
3229     QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
3230     uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
3231     raw_ostream &Out) {
3232   MicrosoftCXXNameMangler Mangler(*this, Out);
3233   Mangler.getStream() << "_CT";
3234 
3235   llvm::SmallString<64> RTTIMangling;
3236   {
3237     llvm::raw_svector_ostream Stream(RTTIMangling);
3238     msvc_hashing_ostream MHO(Stream);
3239     mangleCXXRTTI(T, MHO);
3240   }
3241   Mangler.getStream() << RTTIMangling;
3242 
3243   // VS2015 and VS2017.1 omit the copy-constructor in the mangled name but
3244   // both older and newer versions include it.
3245   // FIXME: It is known that the Ctor is present in 2013, and in 2017.7
3246   // (_MSC_VER 1914) and newer, and that it's omitted in 2015 and 2017.4
3247   // (_MSC_VER 1911), but it's unknown when exactly it reappeared (1914?
3248   // Or 1912, 1913 aleady?).
3249   bool OmitCopyCtor = getASTContext().getLangOpts().isCompatibleWithMSVC(
3250                           LangOptions::MSVC2015) &&
3251                       !getASTContext().getLangOpts().isCompatibleWithMSVC(
3252                           LangOptions::MSVC2017_7);
3253   llvm::SmallString<64> CopyCtorMangling;
3254   if (!OmitCopyCtor && CD) {
3255     llvm::raw_svector_ostream Stream(CopyCtorMangling);
3256     msvc_hashing_ostream MHO(Stream);
3257     mangleCXXName(GlobalDecl(CD, CT), MHO);
3258   }
3259   Mangler.getStream() << CopyCtorMangling;
3260 
3261   Mangler.getStream() << Size;
3262   if (VBPtrOffset == -1) {
3263     if (NVOffset) {
3264       Mangler.getStream() << NVOffset;
3265     }
3266   } else {
3267     Mangler.getStream() << NVOffset;
3268     Mangler.getStream() << VBPtrOffset;
3269     Mangler.getStream() << VBIndex;
3270   }
3271 }
3272 
3273 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
3274     const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
3275     uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
3276   msvc_hashing_ostream MHO(Out);
3277   MicrosoftCXXNameMangler Mangler(*this, MHO);
3278   Mangler.getStream() << "??_R1";
3279   Mangler.mangleNumber(NVOffset);
3280   Mangler.mangleNumber(VBPtrOffset);
3281   Mangler.mangleNumber(VBTableOffset);
3282   Mangler.mangleNumber(Flags);
3283   Mangler.mangleName(Derived);
3284   Mangler.getStream() << "8";
3285 }
3286 
3287 void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
3288     const CXXRecordDecl *Derived, raw_ostream &Out) {
3289   msvc_hashing_ostream MHO(Out);
3290   MicrosoftCXXNameMangler Mangler(*this, MHO);
3291   Mangler.getStream() << "??_R2";
3292   Mangler.mangleName(Derived);
3293   Mangler.getStream() << "8";
3294 }
3295 
3296 void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
3297     const CXXRecordDecl *Derived, raw_ostream &Out) {
3298   msvc_hashing_ostream MHO(Out);
3299   MicrosoftCXXNameMangler Mangler(*this, MHO);
3300   Mangler.getStream() << "??_R3";
3301   Mangler.mangleName(Derived);
3302   Mangler.getStream() << "8";
3303 }
3304 
3305 void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
3306     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3307     raw_ostream &Out) {
3308   // <mangled-name> ::= ?_R4 <class-name> <storage-class>
3309   //                    <cvr-qualifiers> [<name>] @
3310   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3311   // is always '6' for vftables.
3312   llvm::SmallString<64> VFTableMangling;
3313   llvm::raw_svector_ostream Stream(VFTableMangling);
3314   mangleCXXVFTable(Derived, BasePath, Stream);
3315 
3316   if (VFTableMangling.startswith("??@")) {
3317     assert(VFTableMangling.endswith("@"));
3318     Out << VFTableMangling << "??_R4@";
3319     return;
3320   }
3321 
3322   assert(VFTableMangling.startswith("??_7") ||
3323          VFTableMangling.startswith("??_S"));
3324 
3325   Out << "??_R4" << StringRef(VFTableMangling).drop_front(4);
3326 }
3327 
3328 void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
3329     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3330   msvc_hashing_ostream MHO(Out);
3331   MicrosoftCXXNameMangler Mangler(*this, MHO);
3332   // The function body is in the same comdat as the function with the handler,
3333   // so the numbering here doesn't have to be the same across TUs.
3334   //
3335   // <mangled-name> ::= ?filt$ <filter-number> @0
3336   Mangler.getStream() << "?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
3337   Mangler.mangleName(EnclosingDecl);
3338 }
3339 
3340 void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
3341     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
3342   msvc_hashing_ostream MHO(Out);
3343   MicrosoftCXXNameMangler Mangler(*this, MHO);
3344   // The function body is in the same comdat as the function with the handler,
3345   // so the numbering here doesn't have to be the same across TUs.
3346   //
3347   // <mangled-name> ::= ?fin$ <filter-number> @0
3348   Mangler.getStream() << "?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
3349   Mangler.mangleName(EnclosingDecl);
3350 }
3351 
3352 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
3353   // This is just a made up unique string for the purposes of tbaa.  undname
3354   // does *not* know how to demangle it.
3355   MicrosoftCXXNameMangler Mangler(*this, Out);
3356   Mangler.getStream() << '?';
3357   Mangler.mangleType(T, SourceRange());
3358 }
3359 
3360 void MicrosoftMangleContextImpl::mangleReferenceTemporary(
3361     const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
3362   msvc_hashing_ostream MHO(Out);
3363   MicrosoftCXXNameMangler Mangler(*this, MHO);
3364 
3365   Mangler.getStream() << "?$RT" << ManglingNumber << '@';
3366   Mangler.mangle(VD, "");
3367 }
3368 
3369 void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
3370     const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
3371   msvc_hashing_ostream MHO(Out);
3372   MicrosoftCXXNameMangler Mangler(*this, MHO);
3373 
3374   Mangler.getStream() << "?$TSS" << GuardNum << '@';
3375   Mangler.mangleNestedName(VD);
3376   Mangler.getStream() << "@4HA";
3377 }
3378 
3379 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
3380                                                            raw_ostream &Out) {
3381   // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
3382   //              ::= ?__J <postfix> @5 <scope-depth>
3383   //              ::= ?$S <guard-num> @ <postfix> @4IA
3384 
3385   // The first mangling is what MSVC uses to guard static locals in inline
3386   // functions.  It uses a different mangling in external functions to support
3387   // guarding more than 32 variables.  MSVC rejects inline functions with more
3388   // than 32 static locals.  We don't fully implement the second mangling
3389   // because those guards are not externally visible, and instead use LLVM's
3390   // default renaming when creating a new guard variable.
3391   msvc_hashing_ostream MHO(Out);
3392   MicrosoftCXXNameMangler Mangler(*this, MHO);
3393 
3394   bool Visible = VD->isExternallyVisible();
3395   if (Visible) {
3396     Mangler.getStream() << (VD->getTLSKind() ? "??__J" : "??_B");
3397   } else {
3398     Mangler.getStream() << "?$S1@";
3399   }
3400   unsigned ScopeDepth = 0;
3401   if (Visible && !getNextDiscriminator(VD, ScopeDepth))
3402     // If we do not have a discriminator and are emitting a guard variable for
3403     // use at global scope, then mangling the nested name will not be enough to
3404     // remove ambiguities.
3405     Mangler.mangle(VD, "");
3406   else
3407     Mangler.mangleNestedName(VD);
3408   Mangler.getStream() << (Visible ? "@5" : "@4IA");
3409   if (ScopeDepth)
3410     Mangler.mangleNumber(ScopeDepth);
3411 }
3412 
3413 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
3414                                                     char CharCode,
3415                                                     raw_ostream &Out) {
3416   msvc_hashing_ostream MHO(Out);
3417   MicrosoftCXXNameMangler Mangler(*this, MHO);
3418   Mangler.getStream() << "??__" << CharCode;
3419   if (D->isStaticDataMember()) {
3420     Mangler.getStream() << '?';
3421     Mangler.mangleName(D);
3422     Mangler.mangleVariableEncoding(D);
3423     Mangler.getStream() << "@@";
3424   } else {
3425     Mangler.mangleName(D);
3426   }
3427   // This is the function class mangling.  These stubs are global, non-variadic,
3428   // cdecl functions that return void and take no args.
3429   Mangler.getStream() << "YAXXZ";
3430 }
3431 
3432 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
3433                                                           raw_ostream &Out) {
3434   // <initializer-name> ::= ?__E <name> YAXXZ
3435   mangleInitFiniStub(D, 'E', Out);
3436 }
3437 
3438 void
3439 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3440                                                           raw_ostream &Out) {
3441   // <destructor-name> ::= ?__F <name> YAXXZ
3442   mangleInitFiniStub(D, 'F', Out);
3443 }
3444 
3445 void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
3446                                                      raw_ostream &Out) {
3447   // <char-type> ::= 0   # char, char16_t, char32_t
3448   //                     # (little endian char data in mangling)
3449   //             ::= 1   # wchar_t (big endian char data in mangling)
3450   //
3451   // <literal-length> ::= <non-negative integer>  # the length of the literal
3452   //
3453   // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
3454   //                                              # trailing null bytes
3455   //
3456   // <encoded-string> ::= <simple character>           # uninteresting character
3457   //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
3458   //                                                   # encode the byte for the
3459   //                                                   # character
3460   //                  ::= '?' [a-z]                    # \xe1 - \xfa
3461   //                  ::= '?' [A-Z]                    # \xc1 - \xda
3462   //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
3463   //
3464   // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
3465   //               <encoded-string> '@'
3466   MicrosoftCXXNameMangler Mangler(*this, Out);
3467   Mangler.getStream() << "??_C@_";
3468 
3469   // The actual string length might be different from that of the string literal
3470   // in cases like:
3471   // char foo[3] = "foobar";
3472   // char bar[42] = "foobar";
3473   // Where it is truncated or zero-padded to fit the array. This is the length
3474   // used for mangling, and any trailing null-bytes also need to be mangled.
3475   unsigned StringLength = getASTContext()
3476                               .getAsConstantArrayType(SL->getType())
3477                               ->getSize()
3478                               .getZExtValue();
3479   unsigned StringByteLength = StringLength * SL->getCharByteWidth();
3480 
3481   // <char-type>: The "kind" of string literal is encoded into the mangled name.
3482   if (SL->isWide())
3483     Mangler.getStream() << '1';
3484   else
3485     Mangler.getStream() << '0';
3486 
3487   // <literal-length>: The next part of the mangled name consists of the length
3488   // of the string in bytes.
3489   Mangler.mangleNumber(StringByteLength);
3490 
3491   auto GetLittleEndianByte = [&SL](unsigned Index) {
3492     unsigned CharByteWidth = SL->getCharByteWidth();
3493     if (Index / CharByteWidth >= SL->getLength())
3494       return static_cast<char>(0);
3495     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3496     unsigned OffsetInCodeUnit = Index % CharByteWidth;
3497     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3498   };
3499 
3500   auto GetBigEndianByte = [&SL](unsigned Index) {
3501     unsigned CharByteWidth = SL->getCharByteWidth();
3502     if (Index / CharByteWidth >= SL->getLength())
3503       return static_cast<char>(0);
3504     uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3505     unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
3506     return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3507   };
3508 
3509   // CRC all the bytes of the StringLiteral.
3510   llvm::JamCRC JC;
3511   for (unsigned I = 0, E = StringByteLength; I != E; ++I)
3512     JC.update(GetLittleEndianByte(I));
3513 
3514   // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
3515   // scheme.
3516   Mangler.mangleNumber(JC.getCRC());
3517 
3518   // <encoded-string>: The mangled name also contains the first 32 bytes
3519   // (including null-terminator bytes) of the encoded StringLiteral.
3520   // Each character is encoded by splitting them into bytes and then encoding
3521   // the constituent bytes.
3522   auto MangleByte = [&Mangler](char Byte) {
3523     // There are five different manglings for characters:
3524     // - [a-zA-Z0-9_$]: A one-to-one mapping.
3525     // - ?[a-z]: The range from \xe1 to \xfa.
3526     // - ?[A-Z]: The range from \xc1 to \xda.
3527     // - ?[0-9]: The set of [,/\:. \n\t'-].
3528     // - ?$XX: A fallback which maps nibbles.
3529     if (isIdentifierBody(Byte, /*AllowDollar=*/true)) {
3530       Mangler.getStream() << Byte;
3531     } else if (isLetter(Byte & 0x7f)) {
3532       Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
3533     } else {
3534       const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
3535                                    ' ', '\n', '\t', '\'', '-'};
3536       const char *Pos = llvm::find(SpecialChars, Byte);
3537       if (Pos != std::end(SpecialChars)) {
3538         Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
3539       } else {
3540         Mangler.getStream() << "?$";
3541         Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
3542         Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
3543       }
3544     }
3545   };
3546 
3547   // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
3548   unsigned MaxBytesToMangle = SL->isWide() ? 64U : 32U;
3549   unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength);
3550   for (unsigned I = 0; I != NumBytesToMangle; ++I) {
3551     if (SL->isWide())
3552       MangleByte(GetBigEndianByte(I));
3553     else
3554       MangleByte(GetLittleEndianByte(I));
3555   }
3556 
3557   Mangler.getStream() << '@';
3558 }
3559 
3560 MicrosoftMangleContext *
3561 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
3562   return new MicrosoftMangleContextImpl(Context, Diags);
3563 }
3564