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