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