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