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