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