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