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