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