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