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