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