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