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