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/ExprCXX.h"
24 #include "clang/AST/VTableBuilder.h"
25 #include "clang/Basic/ABI.h"
26 #include "clang/Basic/DiagnosticOptions.h"
27 #include "clang/Basic/TargetInfo.h"
28 #include "llvm/ADT/StringMap.h"
29 
30 using namespace clang;
31 
32 namespace {
33 
34 /// \brief Retrieve the declaration context that should be used when mangling
35 /// the given declaration.
36 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
37   // The ABI assumes that lambda closure types that occur within
38   // default arguments live in the context of the function. However, due to
39   // the way in which Clang parses and creates function declarations, this is
40   // not the case: the lambda closure type ends up living in the context
41   // where the function itself resides, because the function declaration itself
42   // had not yet been created. Fix the context here.
43   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
44     if (RD->isLambda())
45       if (ParmVarDecl *ContextParam =
46               dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
47         return ContextParam->getDeclContext();
48   }
49 
50   // Perform the same check for block literals.
51   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
52     if (ParmVarDecl *ContextParam =
53             dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
54       return ContextParam->getDeclContext();
55   }
56 
57   const DeclContext *DC = D->getDeclContext();
58   if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC))
59     return getEffectiveDeclContext(CD);
60 
61   return DC;
62 }
63 
64 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
65   return getEffectiveDeclContext(cast<Decl>(DC));
66 }
67 
68 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
69   if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
70     return ftd->getTemplatedDecl();
71 
72   return fn;
73 }
74 
75 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
76 /// Microsoft Visual C++ ABI.
77 class MicrosoftCXXNameMangler {
78   MangleContext &Context;
79   raw_ostream &Out;
80 
81   /// The "structor" is the top-level declaration being mangled, if
82   /// that's not a template specialization; otherwise it's the pattern
83   /// for that specialization.
84   const NamedDecl *Structor;
85   unsigned StructorType;
86 
87   typedef llvm::StringMap<unsigned> BackRefMap;
88   BackRefMap NameBackReferences;
89   bool UseNameBackReferences;
90 
91   typedef llvm::DenseMap<void*, unsigned> ArgBackRefMap;
92   ArgBackRefMap TypeBackReferences;
93 
94   ASTContext &getASTContext() const { return Context.getASTContext(); }
95 
96   // FIXME: If we add support for __ptr32/64 qualifiers, then we should push
97   // this check into mangleQualifiers().
98   const bool PointersAre64Bit;
99 
100 public:
101   enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
102 
103   MicrosoftCXXNameMangler(MangleContext &C, raw_ostream &Out_)
104     : Context(C), Out(Out_),
105       Structor(0), StructorType(-1),
106       UseNameBackReferences(true),
107       PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
108                        64) { }
109 
110   MicrosoftCXXNameMangler(MangleContext &C, raw_ostream &Out_,
111                           const CXXDestructorDecl *D, CXXDtorType Type)
112     : Context(C), Out(Out_),
113       Structor(getStructor(D)), StructorType(Type),
114       UseNameBackReferences(true),
115       PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(0) ==
116                        64) { }
117 
118   raw_ostream &getStream() const { return Out; }
119 
120   void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
121   void mangleName(const NamedDecl *ND);
122   void mangleDeclaration(const NamedDecl *ND);
123   void mangleFunctionEncoding(const FunctionDecl *FD);
124   void mangleVariableEncoding(const VarDecl *VD);
125   void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD);
126   void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
127                                    const CXXMethodDecl *MD);
128   void mangleVirtualMemPtrThunk(
129       const CXXMethodDecl *MD,
130       const MicrosoftVTableContext::MethodVFTableLocation &ML);
131   void mangleNumber(int64_t Number);
132   void mangleType(QualType T, SourceRange Range,
133                   QualifierMangleMode QMM = QMM_Mangle);
134   void mangleFunctionType(const FunctionType *T, const FunctionDecl *D = 0,
135                           bool ForceInstMethod = false);
136   void manglePostfix(const DeclContext *DC, bool NoFunction = false);
137 
138 private:
139   void disableBackReferences() { UseNameBackReferences = false; }
140   void mangleUnqualifiedName(const NamedDecl *ND) {
141     mangleUnqualifiedName(ND, ND->getDeclName());
142   }
143   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
144   void mangleSourceName(StringRef Name);
145   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
146   void mangleCXXDtorType(CXXDtorType T);
147   void mangleQualifiers(Qualifiers Quals, bool IsMember);
148   void manglePointerCVQualifiers(Qualifiers Quals);
149   void manglePointerExtQualifiers(Qualifiers Quals, const Type *PointeeType);
150 
151   void mangleUnscopedTemplateName(const TemplateDecl *ND);
152   void mangleTemplateInstantiationName(const TemplateDecl *TD,
153                                       const TemplateArgumentList &TemplateArgs);
154   void mangleObjCMethodName(const ObjCMethodDecl *MD);
155   void mangleLocalName(const FunctionDecl *FD);
156 
157   void mangleArgumentType(QualType T, SourceRange Range);
158 
159   // Declare manglers for every type class.
160 #define ABSTRACT_TYPE(CLASS, PARENT)
161 #define NON_CANONICAL_TYPE(CLASS, PARENT)
162 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
163                                             SourceRange Range);
164 #include "clang/AST/TypeNodes.def"
165 #undef ABSTRACT_TYPE
166 #undef NON_CANONICAL_TYPE
167 #undef TYPE
168 
169   void mangleType(const TagDecl *TD);
170   void mangleDecayedArrayType(const ArrayType *T);
171   void mangleArrayType(const ArrayType *T);
172   void mangleFunctionClass(const FunctionDecl *FD);
173   void mangleCallingConvention(const FunctionType *T);
174   void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
175   void mangleExpression(const Expr *E);
176   void mangleThrowSpecification(const FunctionProtoType *T);
177 
178   void mangleTemplateArgs(const TemplateDecl *TD,
179                           const TemplateArgumentList &TemplateArgs);
180   void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA);
181 };
182 
183 /// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
184 /// Microsoft Visual C++ ABI.
185 class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
186 public:
187   MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags)
188       : MicrosoftMangleContext(Context, Diags) {}
189   virtual bool shouldMangleCXXName(const NamedDecl *D);
190   virtual void mangleCXXName(const NamedDecl *D, raw_ostream &Out);
191   virtual void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
192                                         raw_ostream &);
193   virtual void mangleThunk(const CXXMethodDecl *MD,
194                            const ThunkInfo &Thunk,
195                            raw_ostream &);
196   virtual void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
197                                   const ThisAdjustment &ThisAdjustment,
198                                   raw_ostream &);
199   virtual void mangleCXXVFTable(const CXXRecordDecl *Derived,
200                                 ArrayRef<const CXXRecordDecl *> BasePath,
201                                 raw_ostream &Out);
202   virtual void mangleCXXVBTable(const CXXRecordDecl *Derived,
203                                 ArrayRef<const CXXRecordDecl *> BasePath,
204                                 raw_ostream &Out);
205   virtual void mangleCXXRTTI(QualType T, raw_ostream &);
206   virtual void mangleCXXRTTIName(QualType T, raw_ostream &);
207   virtual void mangleTypeName(QualType T, raw_ostream &);
208   virtual void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
209                              raw_ostream &);
210   virtual void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
211                              raw_ostream &);
212   virtual void mangleReferenceTemporary(const VarDecl *, raw_ostream &);
213   virtual void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out);
214   virtual void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out);
215   virtual void mangleDynamicAtExitDestructor(const VarDecl *D,
216                                              raw_ostream &Out);
217 
218 private:
219   void mangleInitFiniStub(const VarDecl *D, raw_ostream &Out, char CharCode);
220 };
221 
222 }
223 
224 bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
225   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
226     LanguageLinkage L = FD->getLanguageLinkage();
227     // Overloadable functions need mangling.
228     if (FD->hasAttr<OverloadableAttr>())
229       return true;
230 
231     // The ABI expects that we would never mangle "typical" user-defined entry
232     // points regardless of visibility or freestanding-ness.
233     //
234     // N.B. This is distinct from asking about "main".  "main" has a lot of
235     // special rules associated with it in the standard while these
236     // user-defined entry points are outside of the purview of the standard.
237     // For example, there can be only one definition for "main" in a standards
238     // compliant program; however nothing forbids the existence of wmain and
239     // WinMain in the same translation unit.
240     if (FD->isMSVCRTEntryPoint())
241       return false;
242 
243     // C++ functions and those whose names are not a simple identifier need
244     // mangling.
245     if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
246       return true;
247 
248     // C functions are not mangled.
249     if (L == CLanguageLinkage)
250       return false;
251   }
252 
253   // Otherwise, no mangling is done outside C++ mode.
254   if (!getASTContext().getLangOpts().CPlusPlus)
255     return false;
256 
257   if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
258     // C variables are not mangled.
259     if (VD->isExternC())
260       return false;
261 
262     // Variables at global scope with non-internal linkage are not mangled.
263     const DeclContext *DC = getEffectiveDeclContext(D);
264     // Check for extern variable declared locally.
265     if (DC->isFunctionOrMethod() && D->hasLinkage())
266       while (!DC->isNamespace() && !DC->isTranslationUnit())
267         DC = getEffectiveParentContext(DC);
268 
269     if (DC->isTranslationUnit() && D->getFormalLinkage() == InternalLinkage &&
270         !isa<VarTemplateSpecializationDecl>(D))
271       return false;
272   }
273 
274   return true;
275 }
276 
277 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D,
278                                      StringRef Prefix) {
279   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
280   // Therefore it's really important that we don't decorate the
281   // name with leading underscores or leading/trailing at signs. So, by
282   // default, we emit an asm marker at the start so we get the name right.
283   // Callers can override this with a custom prefix.
284 
285   // <mangled-name> ::= ? <name> <type-encoding>
286   Out << Prefix;
287   mangleName(D);
288   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
289     mangleFunctionEncoding(FD);
290   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
291     mangleVariableEncoding(VD);
292   else {
293     // TODO: Fields? Can MSVC even mangle them?
294     // Issue a diagnostic for now.
295     DiagnosticsEngine &Diags = Context.getDiags();
296     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
297       "cannot mangle this declaration yet");
298     Diags.Report(D->getLocation(), DiagID)
299       << D->getSourceRange();
300   }
301 }
302 
303 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
304   // <type-encoding> ::= <function-class> <function-type>
305 
306   // Since MSVC operates on the type as written and not the canonical type, it
307   // actually matters which decl we have here.  MSVC appears to choose the
308   // first, since it is most likely to be the declaration in a header file.
309   FD = FD->getFirstDecl();
310 
311   // We should never ever see a FunctionNoProtoType at this point.
312   // We don't even know how to mangle their types anyway :).
313   const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
314 
315   // extern "C" functions can hold entities that must be mangled.
316   // As it stands, these functions still need to get expressed in the full
317   // external name.  They have their class and type omitted, replaced with '9'.
318   if (Context.shouldMangleDeclName(FD)) {
319     // First, the function class.
320     mangleFunctionClass(FD);
321 
322     mangleFunctionType(FT, FD);
323   } else
324     Out << '9';
325 }
326 
327 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
328   // <type-encoding> ::= <storage-class> <variable-type>
329   // <storage-class> ::= 0  # private static member
330   //                 ::= 1  # protected static member
331   //                 ::= 2  # public static member
332   //                 ::= 3  # global
333   //                 ::= 4  # static local
334 
335   // The first character in the encoding (after the name) is the storage class.
336   if (VD->isStaticDataMember()) {
337     // If it's a static member, it also encodes the access level.
338     switch (VD->getAccess()) {
339       default:
340       case AS_private: Out << '0'; break;
341       case AS_protected: Out << '1'; break;
342       case AS_public: Out << '2'; break;
343     }
344   }
345   else if (!VD->isStaticLocal())
346     Out << '3';
347   else
348     Out << '4';
349   // Now mangle the type.
350   // <variable-type> ::= <type> <cvr-qualifiers>
351   //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
352   // Pointers and references are odd. The type of 'int * const foo;' gets
353   // mangled as 'QAHA' instead of 'PAHB', for example.
354   TypeLoc TL = VD->getTypeSourceInfo()->getTypeLoc();
355   QualType Ty = VD->getType();
356   if (Ty->isPointerType() || Ty->isReferenceType() ||
357       Ty->isMemberPointerType()) {
358     mangleType(Ty, TL.getSourceRange(), QMM_Drop);
359     manglePointerExtQualifiers(
360         Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), 0);
361     if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
362       mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
363       // Member pointers are suffixed with a back reference to the member
364       // pointer's class name.
365       mangleName(MPT->getClass()->getAsCXXRecordDecl());
366     } else
367       mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
368   } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
369     // Global arrays are funny, too.
370     mangleDecayedArrayType(AT);
371     if (AT->getElementType()->isArrayType())
372       Out << 'A';
373     else
374       mangleQualifiers(Ty.getQualifiers(), false);
375   } else {
376     mangleType(Ty, TL.getSourceRange(), QMM_Drop);
377     mangleQualifiers(Ty.getLocalQualifiers(), false);
378   }
379 }
380 
381 void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
382                                                       const ValueDecl *VD) {
383   // <member-data-pointer> ::= <integer-literal>
384   //                       ::= $F <number> <number>
385   //                       ::= $G <number> <number> <number>
386 
387   int64_t FieldOffset;
388   int64_t VBTableOffset;
389   MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
390   if (VD) {
391     FieldOffset = getASTContext().getFieldOffset(VD);
392     assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
393            "cannot take address of bitfield");
394     FieldOffset /= getASTContext().getCharWidth();
395 
396     VBTableOffset = 0;
397   } else {
398     FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
399 
400     VBTableOffset = -1;
401   }
402 
403   char Code = '\0';
404   switch (IM) {
405   case MSInheritanceAttr::Keyword_single_inheritance:      Code = '0'; break;
406   case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = '0'; break;
407   case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'F'; break;
408   case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'G'; break;
409   }
410 
411   Out << '$' << Code;
412 
413   mangleNumber(FieldOffset);
414 
415   if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
416     mangleNumber(0);
417   if (MSInheritanceAttr::hasVBTableOffsetField(IM))
418     mangleNumber(VBTableOffset);
419 }
420 
421 void
422 MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
423                                                      const CXXMethodDecl *MD) {
424   // <member-function-pointer> ::= $1? <name>
425   //                           ::= $H? <name> <number>
426   //                           ::= $I? <name> <number> <number>
427   //                           ::= $J? <name> <number> <number> <number>
428   //                           ::= $0A@
429 
430   MSInheritanceAttr::Spelling IM = RD->getMSInheritanceModel();
431 
432   // The null member function pointer is $0A@ in function templates and crashes
433   // MSVC when used in class templates, so we don't know what they really look
434   // like.
435   if (!MD) {
436     Out << "$0A@";
437     return;
438   }
439 
440   char Code = '\0';
441   switch (IM) {
442   case MSInheritanceAttr::Keyword_single_inheritance:      Code = '1'; break;
443   case MSInheritanceAttr::Keyword_multiple_inheritance:    Code = 'H'; break;
444   case MSInheritanceAttr::Keyword_virtual_inheritance:     Code = 'I'; break;
445   case MSInheritanceAttr::Keyword_unspecified_inheritance: Code = 'J'; break;
446   }
447 
448   Out << '$' << Code << '?';
449 
450   // If non-virtual, mangle the name.  If virtual, mangle as a virtual memptr
451   // thunk.
452   uint64_t NVOffset = 0;
453   uint64_t VBTableOffset = 0;
454   if (MD->isVirtual()) {
455     MicrosoftVTableContext *VTContext =
456         cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
457     const MicrosoftVTableContext::MethodVFTableLocation &ML =
458         VTContext->getMethodVFTableLocation(GlobalDecl(MD));
459     mangleVirtualMemPtrThunk(MD, ML);
460     NVOffset = ML.VFPtrOffset.getQuantity();
461     VBTableOffset = ML.VBTableIndex * 4;
462     if (ML.VBase) {
463       DiagnosticsEngine &Diags = Context.getDiags();
464       unsigned DiagID = Diags.getCustomDiagID(
465           DiagnosticsEngine::Error,
466           "cannot mangle pointers to member functions from virtual bases");
467       Diags.Report(MD->getLocation(), DiagID);
468     }
469   } else {
470     mangleName(MD);
471     mangleFunctionEncoding(MD);
472   }
473 
474   if (MSInheritanceAttr::hasNVOffsetField(/*IsMemberFunction=*/true, IM))
475     mangleNumber(NVOffset);
476   if (MSInheritanceAttr::hasVBPtrOffsetField(IM))
477     mangleNumber(0);
478   if (MSInheritanceAttr::hasVBTableOffsetField(IM))
479     mangleNumber(VBTableOffset);
480 }
481 
482 void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
483     const CXXMethodDecl *MD,
484     const MicrosoftVTableContext::MethodVFTableLocation &ML) {
485   // Get the vftable offset.
486   CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
487       getASTContext().getTargetInfo().getPointerWidth(0));
488   uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
489 
490   Out << "?_9";
491   mangleName(MD->getParent());
492   Out << "$B";
493   mangleNumber(OffsetInVFTable);
494   Out << 'A';
495   Out << (PointersAre64Bit ? 'A' : 'E');
496 }
497 
498 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
499   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
500   const DeclContext *DC = ND->getDeclContext();
501 
502   // Always start with the unqualified name.
503   mangleUnqualifiedName(ND);
504 
505   // If this is an extern variable declared locally, the relevant DeclContext
506   // is that of the containing namespace, or the translation unit.
507   if (isa<FunctionDecl>(DC) && ND->hasLinkage())
508     while (!DC->isNamespace() && !DC->isTranslationUnit())
509       DC = DC->getParent();
510 
511   manglePostfix(DC);
512 
513   // Terminate the whole name with an '@'.
514   Out << '@';
515 }
516 
517 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
518   // <non-negative integer> ::= A@              # when Number == 0
519   //                        ::= <decimal digit> # when 1 <= Number <= 10
520   //                        ::= <hex digit>+ @  # when Number >= 10
521   //
522   // <number>               ::= [?] <non-negative integer>
523 
524   uint64_t Value = static_cast<uint64_t>(Number);
525   if (Number < 0) {
526     Value = -Value;
527     Out << '?';
528   }
529 
530   if (Value == 0)
531     Out << "A@";
532   else if (Value >= 1 && Value <= 10)
533     Out << (Value - 1);
534   else {
535     // Numbers that are not encoded as decimal digits are represented as nibbles
536     // in the range of ASCII characters 'A' to 'P'.
537     // The number 0x123450 would be encoded as 'BCDEFA'
538     char EncodedNumberBuffer[sizeof(uint64_t) * 2];
539     llvm::MutableArrayRef<char> BufferRef(EncodedNumberBuffer);
540     llvm::MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
541     for (; Value != 0; Value >>= 4)
542       *I++ = 'A' + (Value & 0xf);
543     Out.write(I.base(), I - BufferRef.rbegin());
544     Out << '@';
545   }
546 }
547 
548 static const TemplateDecl *
549 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
550   // Check if we have a function template.
551   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
552     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
553       TemplateArgs = FD->getTemplateSpecializationArgs();
554       return TD;
555     }
556   }
557 
558   // Check if we have a class template.
559   if (const ClassTemplateSpecializationDecl *Spec =
560         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
561     TemplateArgs = &Spec->getTemplateArgs();
562     return Spec->getSpecializedTemplate();
563   }
564 
565   // Check if we have a variable template.
566   if (const VarTemplateSpecializationDecl *Spec =
567           dyn_cast<VarTemplateSpecializationDecl>(ND)) {
568     TemplateArgs = &Spec->getTemplateArgs();
569     return Spec->getSpecializedTemplate();
570   }
571 
572   return 0;
573 }
574 
575 void
576 MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
577                                                DeclarationName Name) {
578   //  <unqualified-name> ::= <operator-name>
579   //                     ::= <ctor-dtor-name>
580   //                     ::= <source-name>
581   //                     ::= <template-name>
582 
583   // Check if we have a template.
584   const TemplateArgumentList *TemplateArgs = 0;
585   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
586     // Function templates aren't considered for name back referencing.  This
587     // makes sense since function templates aren't likely to occur multiple
588     // times in a symbol.
589     // FIXME: Test alias template mangling with MSVC 2013.
590     if (!isa<ClassTemplateDecl>(TD)) {
591       mangleTemplateInstantiationName(TD, *TemplateArgs);
592       return;
593     }
594 
595     // Here comes the tricky thing: if we need to mangle something like
596     //   void foo(A::X<Y>, B::X<Y>),
597     // the X<Y> part is aliased. However, if you need to mangle
598     //   void foo(A::X<A::Y>, A::X<B::Y>),
599     // the A::X<> part is not aliased.
600     // That said, from the mangler's perspective we have a structure like this:
601     //   namespace[s] -> type[ -> template-parameters]
602     // but from the Clang perspective we have
603     //   type [ -> template-parameters]
604     //      \-> namespace[s]
605     // What we do is we create a new mangler, mangle the same type (without
606     // a namespace suffix) using the extra mangler with back references
607     // disabled (to avoid infinite recursion) and then use the mangled type
608     // name as a key to check the mangling of different types for aliasing.
609 
610     std::string BackReferenceKey;
611     BackRefMap::iterator Found;
612     if (UseNameBackReferences) {
613       llvm::raw_string_ostream Stream(BackReferenceKey);
614       MicrosoftCXXNameMangler Extra(Context, Stream);
615       Extra.disableBackReferences();
616       Extra.mangleUnqualifiedName(ND, Name);
617       Stream.flush();
618 
619       Found = NameBackReferences.find(BackReferenceKey);
620     }
621     if (!UseNameBackReferences || Found == NameBackReferences.end()) {
622       mangleTemplateInstantiationName(TD, *TemplateArgs);
623       if (UseNameBackReferences && NameBackReferences.size() < 10) {
624         size_t Size = NameBackReferences.size();
625         NameBackReferences[BackReferenceKey] = Size;
626       }
627     } else {
628       Out << Found->second;
629     }
630     return;
631   }
632 
633   switch (Name.getNameKind()) {
634     case DeclarationName::Identifier: {
635       if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
636         mangleSourceName(II->getName());
637         break;
638       }
639 
640       // Otherwise, an anonymous entity.  We must have a declaration.
641       assert(ND && "mangling empty name without declaration");
642 
643       if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
644         if (NS->isAnonymousNamespace()) {
645           Out << "?A@";
646           break;
647         }
648       }
649 
650       // We must have an anonymous struct.
651       const TagDecl *TD = cast<TagDecl>(ND);
652       if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
653         assert(TD->getDeclContext() == D->getDeclContext() &&
654                "Typedef should not be in another decl context!");
655         assert(D->getDeclName().getAsIdentifierInfo() &&
656                "Typedef was not named!");
657         mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
658         break;
659       }
660 
661       if (TD->hasDeclaratorForAnonDecl()) {
662         // Anonymous types with no tag or typedef get the name of their
663         // declarator mangled in.
664         llvm::SmallString<64> Name("<unnamed-type-");
665         Name += TD->getDeclaratorForAnonDecl()->getName();
666         Name += ">";
667         mangleSourceName(Name.str());
668       } else {
669         // Anonymous types with no tag, no typedef, or declarator get
670         // '<unnamed-tag>'.
671         mangleSourceName("<unnamed-tag>");
672       }
673       break;
674     }
675 
676     case DeclarationName::ObjCZeroArgSelector:
677     case DeclarationName::ObjCOneArgSelector:
678     case DeclarationName::ObjCMultiArgSelector:
679       llvm_unreachable("Can't mangle Objective-C selector names here!");
680 
681     case DeclarationName::CXXConstructorName:
682       if (ND == Structor) {
683         assert(StructorType == Ctor_Complete &&
684                "Should never be asked to mangle a ctor other than complete");
685       }
686       Out << "?0";
687       break;
688 
689     case DeclarationName::CXXDestructorName:
690       if (ND == Structor)
691         // If the named decl is the C++ destructor we're mangling,
692         // use the type we were given.
693         mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
694       else
695         // Otherwise, use the base destructor name. This is relevant if a
696         // class with a destructor is declared within a destructor.
697         mangleCXXDtorType(Dtor_Base);
698       break;
699 
700     case DeclarationName::CXXConversionFunctionName:
701       // <operator-name> ::= ?B # (cast)
702       // The target type is encoded as the return type.
703       Out << "?B";
704       break;
705 
706     case DeclarationName::CXXOperatorName:
707       mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
708       break;
709 
710     case DeclarationName::CXXLiteralOperatorName: {
711       // FIXME: Was this added in VS2010? Does MS even know how to mangle this?
712       DiagnosticsEngine Diags = Context.getDiags();
713       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
714         "cannot mangle this literal operator yet");
715       Diags.Report(ND->getLocation(), DiagID);
716       break;
717     }
718 
719     case DeclarationName::CXXUsingDirective:
720       llvm_unreachable("Can't mangle a using directive name!");
721   }
722 }
723 
724 void MicrosoftCXXNameMangler::manglePostfix(const DeclContext *DC,
725                                             bool NoFunction) {
726   // <postfix> ::= <unqualified-name> [<postfix>]
727   //           ::= <substitution> [<postfix>]
728 
729   if (!DC) return;
730 
731   while (isa<LinkageSpecDecl>(DC))
732     DC = DC->getParent();
733 
734   if (DC->isTranslationUnit())
735     return;
736 
737   if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
738     DiagnosticsEngine Diags = Context.getDiags();
739     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
740       "cannot mangle a local inside this block yet");
741     Diags.Report(BD->getLocation(), DiagID);
742 
743     // FIXME: This is completely, utterly, wrong; see ItaniumMangle
744     // for how this should be done.
745     Out << "__block_invoke" << Context.getBlockId(BD, false);
746     Out << '@';
747     return manglePostfix(DC->getParent(), NoFunction);
748   } else if (isa<CapturedDecl>(DC)) {
749     // Skip CapturedDecl context.
750     manglePostfix(DC->getParent(), NoFunction);
751     return;
752   }
753 
754   if (NoFunction && (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)))
755     return;
756   else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC))
757     mangleObjCMethodName(Method);
758   else if (const FunctionDecl *Func = dyn_cast<FunctionDecl>(DC))
759     mangleLocalName(Func);
760   else {
761     mangleUnqualifiedName(cast<NamedDecl>(DC));
762     manglePostfix(DC->getParent(), NoFunction);
763   }
764 }
765 
766 void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
767   // Microsoft uses the names on the case labels for these dtor variants.  Clang
768   // uses the Itanium terminology internally.  Everything in this ABI delegates
769   // towards the base dtor.
770   switch (T) {
771   // <operator-name> ::= ?1  # destructor
772   case Dtor_Base: Out << "?1"; return;
773   // <operator-name> ::= ?_D # vbase destructor
774   case Dtor_Complete: Out << "?_D"; return;
775   // <operator-name> ::= ?_G # scalar deleting destructor
776   case Dtor_Deleting: Out << "?_G"; return;
777   // <operator-name> ::= ?_E # vector deleting destructor
778   // FIXME: Add a vector deleting dtor type.  It goes in the vtable, so we need
779   // it.
780   }
781   llvm_unreachable("Unsupported dtor type?");
782 }
783 
784 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
785                                                  SourceLocation Loc) {
786   switch (OO) {
787   //                     ?0 # constructor
788   //                     ?1 # destructor
789   // <operator-name> ::= ?2 # new
790   case OO_New: Out << "?2"; break;
791   // <operator-name> ::= ?3 # delete
792   case OO_Delete: Out << "?3"; break;
793   // <operator-name> ::= ?4 # =
794   case OO_Equal: Out << "?4"; break;
795   // <operator-name> ::= ?5 # >>
796   case OO_GreaterGreater: Out << "?5"; break;
797   // <operator-name> ::= ?6 # <<
798   case OO_LessLess: Out << "?6"; break;
799   // <operator-name> ::= ?7 # !
800   case OO_Exclaim: Out << "?7"; break;
801   // <operator-name> ::= ?8 # ==
802   case OO_EqualEqual: Out << "?8"; break;
803   // <operator-name> ::= ?9 # !=
804   case OO_ExclaimEqual: Out << "?9"; break;
805   // <operator-name> ::= ?A # []
806   case OO_Subscript: Out << "?A"; break;
807   //                     ?B # conversion
808   // <operator-name> ::= ?C # ->
809   case OO_Arrow: Out << "?C"; break;
810   // <operator-name> ::= ?D # *
811   case OO_Star: Out << "?D"; break;
812   // <operator-name> ::= ?E # ++
813   case OO_PlusPlus: Out << "?E"; break;
814   // <operator-name> ::= ?F # --
815   case OO_MinusMinus: Out << "?F"; break;
816   // <operator-name> ::= ?G # -
817   case OO_Minus: Out << "?G"; break;
818   // <operator-name> ::= ?H # +
819   case OO_Plus: Out << "?H"; break;
820   // <operator-name> ::= ?I # &
821   case OO_Amp: Out << "?I"; break;
822   // <operator-name> ::= ?J # ->*
823   case OO_ArrowStar: Out << "?J"; break;
824   // <operator-name> ::= ?K # /
825   case OO_Slash: Out << "?K"; break;
826   // <operator-name> ::= ?L # %
827   case OO_Percent: Out << "?L"; break;
828   // <operator-name> ::= ?M # <
829   case OO_Less: Out << "?M"; break;
830   // <operator-name> ::= ?N # <=
831   case OO_LessEqual: Out << "?N"; break;
832   // <operator-name> ::= ?O # >
833   case OO_Greater: Out << "?O"; break;
834   // <operator-name> ::= ?P # >=
835   case OO_GreaterEqual: Out << "?P"; break;
836   // <operator-name> ::= ?Q # ,
837   case OO_Comma: Out << "?Q"; break;
838   // <operator-name> ::= ?R # ()
839   case OO_Call: Out << "?R"; break;
840   // <operator-name> ::= ?S # ~
841   case OO_Tilde: Out << "?S"; break;
842   // <operator-name> ::= ?T # ^
843   case OO_Caret: Out << "?T"; break;
844   // <operator-name> ::= ?U # |
845   case OO_Pipe: Out << "?U"; break;
846   // <operator-name> ::= ?V # &&
847   case OO_AmpAmp: Out << "?V"; break;
848   // <operator-name> ::= ?W # ||
849   case OO_PipePipe: Out << "?W"; break;
850   // <operator-name> ::= ?X # *=
851   case OO_StarEqual: Out << "?X"; break;
852   // <operator-name> ::= ?Y # +=
853   case OO_PlusEqual: Out << "?Y"; break;
854   // <operator-name> ::= ?Z # -=
855   case OO_MinusEqual: Out << "?Z"; break;
856   // <operator-name> ::= ?_0 # /=
857   case OO_SlashEqual: Out << "?_0"; break;
858   // <operator-name> ::= ?_1 # %=
859   case OO_PercentEqual: Out << "?_1"; break;
860   // <operator-name> ::= ?_2 # >>=
861   case OO_GreaterGreaterEqual: Out << "?_2"; break;
862   // <operator-name> ::= ?_3 # <<=
863   case OO_LessLessEqual: Out << "?_3"; break;
864   // <operator-name> ::= ?_4 # &=
865   case OO_AmpEqual: Out << "?_4"; break;
866   // <operator-name> ::= ?_5 # |=
867   case OO_PipeEqual: Out << "?_5"; break;
868   // <operator-name> ::= ?_6 # ^=
869   case OO_CaretEqual: Out << "?_6"; break;
870   //                     ?_7 # vftable
871   //                     ?_8 # vbtable
872   //                     ?_9 # vcall
873   //                     ?_A # typeof
874   //                     ?_B # local static guard
875   //                     ?_C # string
876   //                     ?_D # vbase destructor
877   //                     ?_E # vector deleting destructor
878   //                     ?_F # default constructor closure
879   //                     ?_G # scalar deleting destructor
880   //                     ?_H # vector constructor iterator
881   //                     ?_I # vector destructor iterator
882   //                     ?_J # vector vbase constructor iterator
883   //                     ?_K # virtual displacement map
884   //                     ?_L # eh vector constructor iterator
885   //                     ?_M # eh vector destructor iterator
886   //                     ?_N # eh vector vbase constructor iterator
887   //                     ?_O # copy constructor closure
888   //                     ?_P<name> # udt returning <name>
889   //                     ?_Q # <unknown>
890   //                     ?_R0 # RTTI Type Descriptor
891   //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
892   //                     ?_R2 # RTTI Base Class Array
893   //                     ?_R3 # RTTI Class Hierarchy Descriptor
894   //                     ?_R4 # RTTI Complete Object Locator
895   //                     ?_S # local vftable
896   //                     ?_T # local vftable constructor closure
897   // <operator-name> ::= ?_U # new[]
898   case OO_Array_New: Out << "?_U"; break;
899   // <operator-name> ::= ?_V # delete[]
900   case OO_Array_Delete: Out << "?_V"; break;
901 
902   case OO_Conditional: {
903     DiagnosticsEngine &Diags = Context.getDiags();
904     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
905       "cannot mangle this conditional operator yet");
906     Diags.Report(Loc, DiagID);
907     break;
908   }
909 
910   case OO_None:
911   case NUM_OVERLOADED_OPERATORS:
912     llvm_unreachable("Not an overloaded operator");
913   }
914 }
915 
916 void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
917   // <source name> ::= <identifier> @
918   BackRefMap::iterator Found;
919   if (UseNameBackReferences)
920     Found = NameBackReferences.find(Name);
921   if (!UseNameBackReferences || Found == NameBackReferences.end()) {
922     Out << Name << '@';
923     if (UseNameBackReferences && NameBackReferences.size() < 10) {
924       size_t Size = NameBackReferences.size();
925       NameBackReferences[Name] = Size;
926     }
927   } else {
928     Out << Found->second;
929   }
930 }
931 
932 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
933   Context.mangleObjCMethodName(MD, Out);
934 }
935 
936 // Find out how many function decls live above this one and return an integer
937 // suitable for use as the number in a numbered anonymous scope.
938 // TODO: Memoize.
939 static unsigned getLocalNestingLevel(const FunctionDecl *FD) {
940   const DeclContext *DC = FD->getParent();
941   int level = 1;
942 
943   while (DC && !DC->isTranslationUnit()) {
944     if (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)) level++;
945     DC = DC->getParent();
946   }
947 
948   return 2*level;
949 }
950 
951 void MicrosoftCXXNameMangler::mangleLocalName(const FunctionDecl *FD) {
952   // <nested-name> ::= <numbered-anonymous-scope> ? <mangled-name>
953   // <numbered-anonymous-scope> ::= ? <number>
954   // Even though the name is rendered in reverse order (e.g.
955   // A::B::C is rendered as C@B@A), VC numbers the scopes from outermost to
956   // innermost. So a method bar in class C local to function foo gets mangled
957   // as something like:
958   // ?bar@C@?1??foo@@YAXXZ@QAEXXZ
959   // This is more apparent when you have a type nested inside a method of a
960   // type nested inside a function. A method baz in class D local to method
961   // bar of class C local to function foo gets mangled as:
962   // ?baz@D@?3??bar@C@?1??foo@@YAXXZ@QAEXXZ@QAEXXZ
963   // This scheme is general enough to support GCC-style nested
964   // functions. You could have a method baz of class C inside a function bar
965   // inside a function foo, like so:
966   // ?baz@C@?3??bar@?1??foo@@YAXXZ@YAXXZ@QAEXXZ
967   unsigned NestLevel = getLocalNestingLevel(FD);
968   Out << '?';
969   mangleNumber(NestLevel);
970   Out << '?';
971   mangle(FD, "?");
972 }
973 
974 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
975                                                          const TemplateDecl *TD,
976                      const TemplateArgumentList &TemplateArgs) {
977   // <template-name> ::= <unscoped-template-name> <template-args>
978   //                 ::= <substitution>
979   // Always start with the unqualified name.
980 
981   // Templates have their own context for back references.
982   ArgBackRefMap OuterArgsContext;
983   BackRefMap OuterTemplateContext;
984   NameBackReferences.swap(OuterTemplateContext);
985   TypeBackReferences.swap(OuterArgsContext);
986 
987   mangleUnscopedTemplateName(TD);
988   mangleTemplateArgs(TD, TemplateArgs);
989 
990   // Restore the previous back reference contexts.
991   NameBackReferences.swap(OuterTemplateContext);
992   TypeBackReferences.swap(OuterArgsContext);
993 }
994 
995 void
996 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
997   // <unscoped-template-name> ::= ?$ <unqualified-name>
998   Out << "?$";
999   mangleUnqualifiedName(TD);
1000 }
1001 
1002 void
1003 MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
1004                                               bool IsBoolean) {
1005   // <integer-literal> ::= $0 <number>
1006   Out << "$0";
1007   // Make sure booleans are encoded as 0/1.
1008   if (IsBoolean && Value.getBoolValue())
1009     mangleNumber(1);
1010   else
1011     mangleNumber(Value.getSExtValue());
1012 }
1013 
1014 void
1015 MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
1016   // See if this is a constant expression.
1017   llvm::APSInt Value;
1018   if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
1019     mangleIntegerLiteral(Value, E->getType()->isBooleanType());
1020     return;
1021   }
1022 
1023   const CXXUuidofExpr *UE = 0;
1024   if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) {
1025     if (UO->getOpcode() == UO_AddrOf)
1026       UE = dyn_cast<CXXUuidofExpr>(UO->getSubExpr());
1027   } else
1028     UE = dyn_cast<CXXUuidofExpr>(E);
1029 
1030   if (UE) {
1031     // This CXXUuidofExpr is mangled as-if it were actually a VarDecl from
1032     // const __s_GUID _GUID_{lower case UUID with underscores}
1033     StringRef Uuid = UE->getUuidAsStringRef(Context.getASTContext());
1034     std::string Name = "_GUID_" + Uuid.lower();
1035     std::replace(Name.begin(), Name.end(), '-', '_');
1036 
1037     // If we had to peek through an address-of operator, treat this like we are
1038     // dealing with a pointer type.  Otherwise, treat it like a const reference.
1039     //
1040     // N.B. This matches up with the handling of TemplateArgument::Declaration
1041     // in mangleTemplateArg
1042     if (UE == E)
1043       Out << "$E?";
1044     else
1045       Out << "$1?";
1046     Out << Name << "@@3U__s_GUID@@B";
1047     return;
1048   }
1049 
1050   // As bad as this diagnostic is, it's better than crashing.
1051   DiagnosticsEngine &Diags = Context.getDiags();
1052   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1053                                    "cannot yet mangle expression type %0");
1054   Diags.Report(E->getExprLoc(), DiagID)
1055     << E->getStmtClassName() << E->getSourceRange();
1056 }
1057 
1058 void
1059 MicrosoftCXXNameMangler::mangleTemplateArgs(const TemplateDecl *TD,
1060                                      const TemplateArgumentList &TemplateArgs) {
1061   // <template-args> ::= <template-arg>+ @
1062   unsigned NumTemplateArgs = TemplateArgs.size();
1063   for (unsigned i = 0; i < NumTemplateArgs; ++i) {
1064     const TemplateArgument &TA = TemplateArgs[i];
1065     mangleTemplateArg(TD, TA);
1066   }
1067   Out << '@';
1068 }
1069 
1070 void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1071                                                 const TemplateArgument &TA) {
1072   // <template-arg> ::= <type>
1073   //                ::= <integer-literal>
1074   //                ::= <member-data-pointer>
1075   //                ::= <member-function-pointer>
1076   //                ::= $E? <name> <type-encoding>
1077   //                ::= $1? <name> <type-encoding>
1078   //                ::= $0A@
1079   //                ::= <template-args>
1080 
1081   switch (TA.getKind()) {
1082   case TemplateArgument::Null:
1083     llvm_unreachable("Can't mangle null template arguments!");
1084   case TemplateArgument::TemplateExpansion:
1085     llvm_unreachable("Can't mangle template expansion arguments!");
1086   case TemplateArgument::Type: {
1087     QualType T = TA.getAsType();
1088     mangleType(T, SourceRange(), QMM_Escape);
1089     break;
1090   }
1091   case TemplateArgument::Declaration: {
1092     const NamedDecl *ND = cast<NamedDecl>(TA.getAsDecl());
1093     if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1094       mangleMemberDataPointer(
1095           cast<CXXRecordDecl>(ND->getDeclContext())->getMostRecentDecl(),
1096           cast<ValueDecl>(ND));
1097     } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1098       const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1099       if (MD && MD->isInstance())
1100         mangleMemberFunctionPointer(MD->getParent()->getMostRecentDecl(), MD);
1101       else
1102         mangle(FD, "$1?");
1103     } else {
1104       mangle(ND, TA.isDeclForReferenceParam() ? "$E?" : "$1?");
1105     }
1106     break;
1107   }
1108   case TemplateArgument::Integral:
1109     mangleIntegerLiteral(TA.getAsIntegral(),
1110                          TA.getIntegralType()->isBooleanType());
1111     break;
1112   case TemplateArgument::NullPtr: {
1113     QualType T = TA.getNullPtrType();
1114     if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1115       const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1116       if (MPT->isMemberFunctionPointerType())
1117         mangleMemberFunctionPointer(RD, 0);
1118       else
1119         mangleMemberDataPointer(RD, 0);
1120     } else {
1121       Out << "$0A@";
1122     }
1123     break;
1124   }
1125   case TemplateArgument::Expression:
1126     mangleExpression(TA.getAsExpr());
1127     break;
1128   case TemplateArgument::Pack:
1129     // Unlike Itanium, there is no character code to indicate an argument pack.
1130     for (TemplateArgument::pack_iterator I = TA.pack_begin(), E = TA.pack_end();
1131          I != E; ++I)
1132       mangleTemplateArg(TD, *I);
1133     break;
1134   case TemplateArgument::Template:
1135     mangleType(cast<TagDecl>(
1136         TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl()));
1137     break;
1138   }
1139 }
1140 
1141 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
1142                                                bool IsMember) {
1143   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
1144   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
1145   // 'I' means __restrict (32/64-bit).
1146   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
1147   // keyword!
1148   // <base-cvr-qualifiers> ::= A  # near
1149   //                       ::= B  # near const
1150   //                       ::= C  # near volatile
1151   //                       ::= D  # near const volatile
1152   //                       ::= E  # far (16-bit)
1153   //                       ::= F  # far const (16-bit)
1154   //                       ::= G  # far volatile (16-bit)
1155   //                       ::= H  # far const volatile (16-bit)
1156   //                       ::= I  # huge (16-bit)
1157   //                       ::= J  # huge const (16-bit)
1158   //                       ::= K  # huge volatile (16-bit)
1159   //                       ::= L  # huge const volatile (16-bit)
1160   //                       ::= M <basis> # based
1161   //                       ::= N <basis> # based const
1162   //                       ::= O <basis> # based volatile
1163   //                       ::= P <basis> # based const volatile
1164   //                       ::= Q  # near member
1165   //                       ::= R  # near const member
1166   //                       ::= S  # near volatile member
1167   //                       ::= T  # near const volatile member
1168   //                       ::= U  # far member (16-bit)
1169   //                       ::= V  # far const member (16-bit)
1170   //                       ::= W  # far volatile member (16-bit)
1171   //                       ::= X  # far const volatile member (16-bit)
1172   //                       ::= Y  # huge member (16-bit)
1173   //                       ::= Z  # huge const member (16-bit)
1174   //                       ::= 0  # huge volatile member (16-bit)
1175   //                       ::= 1  # huge const volatile member (16-bit)
1176   //                       ::= 2 <basis> # based member
1177   //                       ::= 3 <basis> # based const member
1178   //                       ::= 4 <basis> # based volatile member
1179   //                       ::= 5 <basis> # based const volatile member
1180   //                       ::= 6  # near function (pointers only)
1181   //                       ::= 7  # far function (pointers only)
1182   //                       ::= 8  # near method (pointers only)
1183   //                       ::= 9  # far method (pointers only)
1184   //                       ::= _A <basis> # based function (pointers only)
1185   //                       ::= _B <basis> # based function (far?) (pointers only)
1186   //                       ::= _C <basis> # based method (pointers only)
1187   //                       ::= _D <basis> # based method (far?) (pointers only)
1188   //                       ::= _E # block (Clang)
1189   // <basis> ::= 0 # __based(void)
1190   //         ::= 1 # __based(segment)?
1191   //         ::= 2 <name> # __based(name)
1192   //         ::= 3 # ?
1193   //         ::= 4 # ?
1194   //         ::= 5 # not really based
1195   bool HasConst = Quals.hasConst(),
1196        HasVolatile = Quals.hasVolatile();
1197 
1198   if (!IsMember) {
1199     if (HasConst && HasVolatile) {
1200       Out << 'D';
1201     } else if (HasVolatile) {
1202       Out << 'C';
1203     } else if (HasConst) {
1204       Out << 'B';
1205     } else {
1206       Out << 'A';
1207     }
1208   } else {
1209     if (HasConst && HasVolatile) {
1210       Out << 'T';
1211     } else if (HasVolatile) {
1212       Out << 'S';
1213     } else if (HasConst) {
1214       Out << 'R';
1215     } else {
1216       Out << 'Q';
1217     }
1218   }
1219 
1220   // FIXME: For now, just drop all extension qualifiers on the floor.
1221 }
1222 
1223 void
1224 MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
1225                                                     const Type *PointeeType) {
1226   bool HasRestrict = Quals.hasRestrict();
1227   if (PointersAre64Bit && (!PointeeType || !PointeeType->isFunctionType()))
1228     Out << 'E';
1229 
1230   if (HasRestrict)
1231     Out << 'I';
1232 }
1233 
1234 void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
1235   // <pointer-cv-qualifiers> ::= P  # no qualifiers
1236   //                         ::= Q  # const
1237   //                         ::= R  # volatile
1238   //                         ::= S  # const volatile
1239   bool HasConst = Quals.hasConst(),
1240        HasVolatile = Quals.hasVolatile();
1241 
1242   if (HasConst && HasVolatile) {
1243     Out << 'S';
1244   } else if (HasVolatile) {
1245     Out << 'R';
1246   } else if (HasConst) {
1247     Out << 'Q';
1248   } else {
1249     Out << 'P';
1250   }
1251 }
1252 
1253 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
1254                                                  SourceRange Range) {
1255   // MSVC will backreference two canonically equivalent types that have slightly
1256   // different manglings when mangled alone.
1257 
1258   // Decayed types do not match up with non-decayed versions of the same type.
1259   //
1260   // e.g.
1261   // void (*x)(void) will not form a backreference with void x(void)
1262   void *TypePtr;
1263   if (const DecayedType *DT = T->getAs<DecayedType>()) {
1264     TypePtr = DT->getOriginalType().getCanonicalType().getAsOpaquePtr();
1265     // If the original parameter was textually written as an array,
1266     // instead treat the decayed parameter like it's const.
1267     //
1268     // e.g.
1269     // int [] -> int * const
1270     if (DT->getOriginalType()->isArrayType())
1271       T = T.withConst();
1272   } else
1273     TypePtr = T.getCanonicalType().getAsOpaquePtr();
1274 
1275   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
1276 
1277   if (Found == TypeBackReferences.end()) {
1278     size_t OutSizeBefore = Out.GetNumBytesInBuffer();
1279 
1280     mangleType(T, Range, QMM_Drop);
1281 
1282     // See if it's worth creating a back reference.
1283     // Only types longer than 1 character are considered
1284     // and only 10 back references slots are available:
1285     bool LongerThanOneChar = (Out.GetNumBytesInBuffer() - OutSizeBefore > 1);
1286     if (LongerThanOneChar && TypeBackReferences.size() < 10) {
1287       size_t Size = TypeBackReferences.size();
1288       TypeBackReferences[TypePtr] = Size;
1289     }
1290   } else {
1291     Out << Found->second;
1292   }
1293 }
1294 
1295 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
1296                                          QualifierMangleMode QMM) {
1297   // Don't use the canonical types.  MSVC includes things like 'const' on
1298   // pointer arguments to function pointers that canonicalization strips away.
1299   T = T.getDesugaredType(getASTContext());
1300   Qualifiers Quals = T.getLocalQualifiers();
1301   if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
1302     // If there were any Quals, getAsArrayType() pushed them onto the array
1303     // element type.
1304     if (QMM == QMM_Mangle)
1305       Out << 'A';
1306     else if (QMM == QMM_Escape || QMM == QMM_Result)
1307       Out << "$$B";
1308     mangleArrayType(AT);
1309     return;
1310   }
1311 
1312   bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
1313                    T->isBlockPointerType();
1314 
1315   switch (QMM) {
1316   case QMM_Drop:
1317     break;
1318   case QMM_Mangle:
1319     if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
1320       Out << '6';
1321       mangleFunctionType(FT);
1322       return;
1323     }
1324     mangleQualifiers(Quals, false);
1325     break;
1326   case QMM_Escape:
1327     if (!IsPointer && Quals) {
1328       Out << "$$C";
1329       mangleQualifiers(Quals, false);
1330     }
1331     break;
1332   case QMM_Result:
1333     if ((!IsPointer && Quals) || isa<TagType>(T)) {
1334       Out << '?';
1335       mangleQualifiers(Quals, false);
1336     }
1337     break;
1338   }
1339 
1340   // We have to mangle these now, while we still have enough information.
1341   if (IsPointer) {
1342     manglePointerCVQualifiers(Quals);
1343     manglePointerExtQualifiers(Quals, T->getPointeeType().getTypePtr());
1344   }
1345   const Type *ty = T.getTypePtr();
1346 
1347   switch (ty->getTypeClass()) {
1348 #define ABSTRACT_TYPE(CLASS, PARENT)
1349 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
1350   case Type::CLASS: \
1351     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
1352     return;
1353 #define TYPE(CLASS, PARENT) \
1354   case Type::CLASS: \
1355     mangleType(cast<CLASS##Type>(ty), Range); \
1356     break;
1357 #include "clang/AST/TypeNodes.def"
1358 #undef ABSTRACT_TYPE
1359 #undef NON_CANONICAL_TYPE
1360 #undef TYPE
1361   }
1362 }
1363 
1364 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T,
1365                                          SourceRange Range) {
1366   //  <type>         ::= <builtin-type>
1367   //  <builtin-type> ::= X  # void
1368   //                 ::= C  # signed char
1369   //                 ::= D  # char
1370   //                 ::= E  # unsigned char
1371   //                 ::= F  # short
1372   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1373   //                 ::= H  # int
1374   //                 ::= I  # unsigned int
1375   //                 ::= J  # long
1376   //                 ::= K  # unsigned long
1377   //                     L  # <none>
1378   //                 ::= M  # float
1379   //                 ::= N  # double
1380   //                 ::= O  # long double (__float80 is mangled differently)
1381   //                 ::= _J # long long, __int64
1382   //                 ::= _K # unsigned long long, __int64
1383   //                 ::= _L # __int128
1384   //                 ::= _M # unsigned __int128
1385   //                 ::= _N # bool
1386   //                     _O # <array in parameter>
1387   //                 ::= _T # __float80 (Intel)
1388   //                 ::= _W # wchar_t
1389   //                 ::= _Z # __float80 (Digital Mars)
1390   switch (T->getKind()) {
1391   case BuiltinType::Void: Out << 'X'; break;
1392   case BuiltinType::SChar: Out << 'C'; break;
1393   case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
1394   case BuiltinType::UChar: Out << 'E'; break;
1395   case BuiltinType::Short: Out << 'F'; break;
1396   case BuiltinType::UShort: Out << 'G'; break;
1397   case BuiltinType::Int: Out << 'H'; break;
1398   case BuiltinType::UInt: Out << 'I'; break;
1399   case BuiltinType::Long: Out << 'J'; break;
1400   case BuiltinType::ULong: Out << 'K'; break;
1401   case BuiltinType::Float: Out << 'M'; break;
1402   case BuiltinType::Double: Out << 'N'; break;
1403   // TODO: Determine size and mangle accordingly
1404   case BuiltinType::LongDouble: Out << 'O'; break;
1405   case BuiltinType::LongLong: Out << "_J"; break;
1406   case BuiltinType::ULongLong: Out << "_K"; break;
1407   case BuiltinType::Int128: Out << "_L"; break;
1408   case BuiltinType::UInt128: Out << "_M"; break;
1409   case BuiltinType::Bool: Out << "_N"; break;
1410   case BuiltinType::WChar_S:
1411   case BuiltinType::WChar_U: Out << "_W"; break;
1412 
1413 #define BUILTIN_TYPE(Id, SingletonId)
1414 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1415   case BuiltinType::Id:
1416 #include "clang/AST/BuiltinTypes.def"
1417   case BuiltinType::Dependent:
1418     llvm_unreachable("placeholder types shouldn't get to name mangling");
1419 
1420   case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
1421   case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
1422   case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
1423 
1424   case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
1425   case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
1426   case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
1427   case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
1428   case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
1429   case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
1430   case BuiltinType::OCLSampler: Out << "PAUocl_sampler@@"; break;
1431   case BuiltinType::OCLEvent: Out << "PAUocl_event@@"; break;
1432 
1433   case BuiltinType::NullPtr: Out << "$$T"; break;
1434 
1435   case BuiltinType::Char16:
1436   case BuiltinType::Char32:
1437   case BuiltinType::Half: {
1438     DiagnosticsEngine &Diags = Context.getDiags();
1439     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1440       "cannot mangle this built-in %0 type yet");
1441     Diags.Report(Range.getBegin(), DiagID)
1442       << T->getName(Context.getASTContext().getPrintingPolicy())
1443       << Range;
1444     break;
1445   }
1446   }
1447 }
1448 
1449 // <type>          ::= <function-type>
1450 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T,
1451                                          SourceRange) {
1452   // Structors only appear in decls, so at this point we know it's not a
1453   // structor type.
1454   // FIXME: This may not be lambda-friendly.
1455   Out << "$$A6";
1456   mangleFunctionType(T);
1457 }
1458 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1459                                          SourceRange) {
1460   llvm_unreachable("Can't mangle K&R function prototypes");
1461 }
1462 
1463 void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
1464                                                  const FunctionDecl *D,
1465                                                  bool ForceInstMethod) {
1466   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1467   //                     <return-type> <argument-list> <throw-spec>
1468   const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1469 
1470   SourceRange Range;
1471   if (D) Range = D->getSourceRange();
1472 
1473   bool IsStructor = false, IsInstMethod = ForceInstMethod;
1474   if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
1475     if (MD->isInstance())
1476       IsInstMethod = true;
1477     if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
1478       IsStructor = true;
1479   }
1480 
1481   // If this is a C++ instance method, mangle the CVR qualifiers for the
1482   // this pointer.
1483   if (IsInstMethod) {
1484     Qualifiers Quals = Qualifiers::fromCVRMask(Proto->getTypeQuals());
1485     manglePointerExtQualifiers(Quals, 0);
1486     mangleQualifiers(Quals, false);
1487   }
1488 
1489   mangleCallingConvention(T);
1490 
1491   // <return-type> ::= <type>
1492   //               ::= @ # structors (they have no declared return type)
1493   if (IsStructor) {
1494     if (isa<CXXDestructorDecl>(D) && D == Structor &&
1495         StructorType == Dtor_Deleting) {
1496       // The scalar deleting destructor takes an extra int argument.
1497       // However, the FunctionType generated has 0 arguments.
1498       // FIXME: This is a temporary hack.
1499       // Maybe should fix the FunctionType creation instead?
1500       Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
1501       return;
1502     }
1503     Out << '@';
1504   } else {
1505     QualType ResultType = Proto->getReturnType();
1506     if (ResultType->isVoidType())
1507       ResultType = ResultType.getUnqualifiedType();
1508     mangleType(ResultType, Range, QMM_Result);
1509   }
1510 
1511   // <argument-list> ::= X # void
1512   //                 ::= <type>+ @
1513   //                 ::= <type>* Z # varargs
1514   if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
1515     Out << 'X';
1516   } else {
1517     // Happens for function pointer type arguments for example.
1518     for (FunctionProtoType::param_type_iterator
1519              Arg = Proto->param_type_begin(),
1520              ArgEnd = Proto->param_type_end();
1521          Arg != ArgEnd; ++Arg)
1522       mangleArgumentType(*Arg, Range);
1523     // <builtin-type>      ::= Z  # ellipsis
1524     if (Proto->isVariadic())
1525       Out << 'Z';
1526     else
1527       Out << '@';
1528   }
1529 
1530   mangleThrowSpecification(Proto);
1531 }
1532 
1533 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1534   // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
1535   //                                            # pointer. in 64-bit mode *all*
1536   //                                            # 'this' pointers are 64-bit.
1537   //                   ::= <global-function>
1538   // <member-function> ::= A # private: near
1539   //                   ::= B # private: far
1540   //                   ::= C # private: static near
1541   //                   ::= D # private: static far
1542   //                   ::= E # private: virtual near
1543   //                   ::= F # private: virtual far
1544   //                   ::= I # protected: near
1545   //                   ::= J # protected: far
1546   //                   ::= K # protected: static near
1547   //                   ::= L # protected: static far
1548   //                   ::= M # protected: virtual near
1549   //                   ::= N # protected: virtual far
1550   //                   ::= Q # public: near
1551   //                   ::= R # public: far
1552   //                   ::= S # public: static near
1553   //                   ::= T # public: static far
1554   //                   ::= U # public: virtual near
1555   //                   ::= V # public: virtual far
1556   // <global-function> ::= Y # global near
1557   //                   ::= Z # global far
1558   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1559     switch (MD->getAccess()) {
1560       case AS_none:
1561         llvm_unreachable("Unsupported access specifier");
1562       case AS_private:
1563         if (MD->isStatic())
1564           Out << 'C';
1565         else if (MD->isVirtual())
1566           Out << 'E';
1567         else
1568           Out << 'A';
1569         break;
1570       case AS_protected:
1571         if (MD->isStatic())
1572           Out << 'K';
1573         else if (MD->isVirtual())
1574           Out << 'M';
1575         else
1576           Out << 'I';
1577         break;
1578       case AS_public:
1579         if (MD->isStatic())
1580           Out << 'S';
1581         else if (MD->isVirtual())
1582           Out << 'U';
1583         else
1584           Out << 'Q';
1585     }
1586   } else
1587     Out << 'Y';
1588 }
1589 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
1590   // <calling-convention> ::= A # __cdecl
1591   //                      ::= B # __export __cdecl
1592   //                      ::= C # __pascal
1593   //                      ::= D # __export __pascal
1594   //                      ::= E # __thiscall
1595   //                      ::= F # __export __thiscall
1596   //                      ::= G # __stdcall
1597   //                      ::= H # __export __stdcall
1598   //                      ::= I # __fastcall
1599   //                      ::= J # __export __fastcall
1600   // The 'export' calling conventions are from a bygone era
1601   // (*cough*Win16*cough*) when functions were declared for export with
1602   // that keyword. (It didn't actually export them, it just made them so
1603   // that they could be in a DLL and somebody from another module could call
1604   // them.)
1605   CallingConv CC = T->getCallConv();
1606   switch (CC) {
1607     default:
1608       llvm_unreachable("Unsupported CC for mangling");
1609     case CC_X86_64Win64:
1610     case CC_X86_64SysV:
1611     case CC_C: Out << 'A'; break;
1612     case CC_X86Pascal: Out << 'C'; break;
1613     case CC_X86ThisCall: Out << 'E'; break;
1614     case CC_X86StdCall: Out << 'G'; break;
1615     case CC_X86FastCall: Out << 'I'; break;
1616   }
1617 }
1618 void MicrosoftCXXNameMangler::mangleThrowSpecification(
1619                                                 const FunctionProtoType *FT) {
1620   // <throw-spec> ::= Z # throw(...) (default)
1621   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
1622   //              ::= <type>+
1623   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1624   // all actually mangled as 'Z'. (They're ignored because their associated
1625   // functionality isn't implemented, and probably never will be.)
1626   Out << 'Z';
1627 }
1628 
1629 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
1630                                          SourceRange Range) {
1631   // Probably should be mangled as a template instantiation; need to see what
1632   // VC does first.
1633   DiagnosticsEngine &Diags = Context.getDiags();
1634   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1635     "cannot mangle this unresolved dependent type yet");
1636   Diags.Report(Range.getBegin(), DiagID)
1637     << Range;
1638 }
1639 
1640 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1641 // <union-type>  ::= T <name>
1642 // <struct-type> ::= U <name>
1643 // <class-type>  ::= V <name>
1644 // <enum-type>   ::= W4 <name>
1645 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, SourceRange) {
1646   mangleType(cast<TagType>(T)->getDecl());
1647 }
1648 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, SourceRange) {
1649   mangleType(cast<TagType>(T)->getDecl());
1650 }
1651 void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
1652   switch (TD->getTagKind()) {
1653     case TTK_Union:
1654       Out << 'T';
1655       break;
1656     case TTK_Struct:
1657     case TTK_Interface:
1658       Out << 'U';
1659       break;
1660     case TTK_Class:
1661       Out << 'V';
1662       break;
1663     case TTK_Enum:
1664       Out << "W4";
1665       break;
1666   }
1667   mangleName(TD);
1668 }
1669 
1670 // <type>       ::= <array-type>
1671 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1672 //                  [Y <dimension-count> <dimension>+]
1673 //                  <element-type> # as global, E is never required
1674 // It's supposed to be the other way around, but for some strange reason, it
1675 // isn't. Today this behavior is retained for the sole purpose of backwards
1676 // compatibility.
1677 void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
1678   // This isn't a recursive mangling, so now we have to do it all in this
1679   // one call.
1680   manglePointerCVQualifiers(T->getElementType().getQualifiers());
1681   mangleType(T->getElementType(), SourceRange());
1682 }
1683 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T,
1684                                          SourceRange) {
1685   llvm_unreachable("Should have been special cased");
1686 }
1687 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T,
1688                                          SourceRange) {
1689   llvm_unreachable("Should have been special cased");
1690 }
1691 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
1692                                          SourceRange) {
1693   llvm_unreachable("Should have been special cased");
1694 }
1695 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
1696                                          SourceRange) {
1697   llvm_unreachable("Should have been special cased");
1698 }
1699 void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
1700   QualType ElementTy(T, 0);
1701   SmallVector<llvm::APInt, 3> Dimensions;
1702   for (;;) {
1703     if (const ConstantArrayType *CAT =
1704           getASTContext().getAsConstantArrayType(ElementTy)) {
1705       Dimensions.push_back(CAT->getSize());
1706       ElementTy = CAT->getElementType();
1707     } else if (ElementTy->isVariableArrayType()) {
1708       const VariableArrayType *VAT =
1709         getASTContext().getAsVariableArrayType(ElementTy);
1710       DiagnosticsEngine &Diags = Context.getDiags();
1711       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1712         "cannot mangle this variable-length array yet");
1713       Diags.Report(VAT->getSizeExpr()->getExprLoc(), DiagID)
1714         << VAT->getBracketsRange();
1715       return;
1716     } else if (ElementTy->isDependentSizedArrayType()) {
1717       // The dependent expression has to be folded into a constant (TODO).
1718       const DependentSizedArrayType *DSAT =
1719         getASTContext().getAsDependentSizedArrayType(ElementTy);
1720       DiagnosticsEngine &Diags = Context.getDiags();
1721       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1722         "cannot mangle this dependent-length array yet");
1723       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
1724         << DSAT->getBracketsRange();
1725       return;
1726     } else if (const IncompleteArrayType *IAT =
1727           getASTContext().getAsIncompleteArrayType(ElementTy)) {
1728       Dimensions.push_back(llvm::APInt(32, 0));
1729       ElementTy = IAT->getElementType();
1730     }
1731     else break;
1732   }
1733   Out << 'Y';
1734   // <dimension-count> ::= <number> # number of extra dimensions
1735   mangleNumber(Dimensions.size());
1736   for (unsigned Dim = 0; Dim < Dimensions.size(); ++Dim)
1737     mangleNumber(Dimensions[Dim].getLimitedValue());
1738   mangleType(ElementTy, SourceRange(), QMM_Escape);
1739 }
1740 
1741 // <type>                   ::= <pointer-to-member-type>
1742 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1743 //                                                          <class name> <type>
1744 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
1745                                          SourceRange Range) {
1746   QualType PointeeType = T->getPointeeType();
1747   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
1748     Out << '8';
1749     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1750     mangleFunctionType(FPT, 0, true);
1751   } else {
1752     mangleQualifiers(PointeeType.getQualifiers(), true);
1753     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1754     mangleType(PointeeType, Range, QMM_Drop);
1755   }
1756 }
1757 
1758 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
1759                                          SourceRange Range) {
1760   DiagnosticsEngine &Diags = Context.getDiags();
1761   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1762     "cannot mangle this template type parameter type yet");
1763   Diags.Report(Range.getBegin(), DiagID)
1764     << Range;
1765 }
1766 
1767 void MicrosoftCXXNameMangler::mangleType(
1768                                        const SubstTemplateTypeParmPackType *T,
1769                                        SourceRange Range) {
1770   DiagnosticsEngine &Diags = Context.getDiags();
1771   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1772     "cannot mangle this substituted parameter pack yet");
1773   Diags.Report(Range.getBegin(), DiagID)
1774     << Range;
1775 }
1776 
1777 // <type> ::= <pointer-type>
1778 // <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
1779 //                       # the E is required for 64-bit non-static pointers
1780 void MicrosoftCXXNameMangler::mangleType(const PointerType *T,
1781                                          SourceRange Range) {
1782   QualType PointeeTy = T->getPointeeType();
1783   mangleType(PointeeTy, Range);
1784 }
1785 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
1786                                          SourceRange Range) {
1787   // Object pointers never have qualifiers.
1788   Out << 'A';
1789   manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
1790   mangleType(T->getPointeeType(), Range);
1791 }
1792 
1793 // <type> ::= <reference-type>
1794 // <reference-type> ::= A E? <cvr-qualifiers> <type>
1795 //                 # the E is required for 64-bit non-static lvalue references
1796 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
1797                                          SourceRange Range) {
1798   Out << 'A';
1799   manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
1800   mangleType(T->getPointeeType(), Range);
1801 }
1802 
1803 // <type> ::= <r-value-reference-type>
1804 // <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
1805 //                 # the E is required for 64-bit non-static rvalue references
1806 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
1807                                          SourceRange Range) {
1808   Out << "$$Q";
1809   manglePointerExtQualifiers(Qualifiers(), T->getPointeeType().getTypePtr());
1810   mangleType(T->getPointeeType(), Range);
1811 }
1812 
1813 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T,
1814                                          SourceRange Range) {
1815   DiagnosticsEngine &Diags = Context.getDiags();
1816   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1817     "cannot mangle this complex number type yet");
1818   Diags.Report(Range.getBegin(), DiagID)
1819     << Range;
1820 }
1821 
1822 void MicrosoftCXXNameMangler::mangleType(const VectorType *T,
1823                                          SourceRange Range) {
1824   const BuiltinType *ET = T->getElementType()->getAs<BuiltinType>();
1825   assert(ET && "vectors with non-builtin elements are unsupported");
1826   uint64_t Width = getASTContext().getTypeSize(T);
1827   // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
1828   // doesn't match the Intel types uses a custom mangling below.
1829   bool IntelVector = true;
1830   if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
1831     Out << "T__m64";
1832   } else if (Width == 128 || Width == 256) {
1833     if (ET->getKind() == BuiltinType::Float)
1834       Out << "T__m" << Width;
1835     else if (ET->getKind() == BuiltinType::LongLong)
1836       Out << "T__m" << Width << 'i';
1837     else if (ET->getKind() == BuiltinType::Double)
1838       Out << "U__m" << Width << 'd';
1839     else
1840       IntelVector = false;
1841   } else {
1842     IntelVector = false;
1843   }
1844 
1845   if (!IntelVector) {
1846     // The MS ABI doesn't have a special mangling for vector types, so we define
1847     // our own mangling to handle uses of __vector_size__ on user-specified
1848     // types, and for extensions like __v4sf.
1849     Out << "T__clang_vec" << T->getNumElements() << '_';
1850     mangleType(ET, Range);
1851   }
1852 
1853   Out << "@@";
1854 }
1855 
1856 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
1857                                          SourceRange Range) {
1858   DiagnosticsEngine &Diags = Context.getDiags();
1859   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1860     "cannot mangle this extended vector type yet");
1861   Diags.Report(Range.getBegin(), DiagID)
1862     << Range;
1863 }
1864 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
1865                                          SourceRange Range) {
1866   DiagnosticsEngine &Diags = Context.getDiags();
1867   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1868     "cannot mangle this dependent-sized extended vector type yet");
1869   Diags.Report(Range.getBegin(), DiagID)
1870     << Range;
1871 }
1872 
1873 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T,
1874                                          SourceRange) {
1875   // ObjC interfaces have structs underlying them.
1876   Out << 'U';
1877   mangleName(T->getDecl());
1878 }
1879 
1880 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
1881                                          SourceRange Range) {
1882   // We don't allow overloading by different protocol qualification,
1883   // so mangling them isn't necessary.
1884   mangleType(T->getBaseType(), Range);
1885 }
1886 
1887 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
1888                                          SourceRange Range) {
1889   Out << "_E";
1890 
1891   QualType pointee = T->getPointeeType();
1892   mangleFunctionType(pointee->castAs<FunctionProtoType>());
1893 }
1894 
1895 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
1896                                          SourceRange) {
1897   llvm_unreachable("Cannot mangle injected class name type.");
1898 }
1899 
1900 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
1901                                          SourceRange Range) {
1902   DiagnosticsEngine &Diags = Context.getDiags();
1903   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1904     "cannot mangle this template specialization type yet");
1905   Diags.Report(Range.getBegin(), DiagID)
1906     << Range;
1907 }
1908 
1909 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T,
1910                                          SourceRange Range) {
1911   DiagnosticsEngine &Diags = Context.getDiags();
1912   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1913     "cannot mangle this dependent name type yet");
1914   Diags.Report(Range.getBegin(), DiagID)
1915     << Range;
1916 }
1917 
1918 void MicrosoftCXXNameMangler::mangleType(
1919                                  const DependentTemplateSpecializationType *T,
1920                                  SourceRange Range) {
1921   DiagnosticsEngine &Diags = Context.getDiags();
1922   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1923     "cannot mangle this dependent template specialization type yet");
1924   Diags.Report(Range.getBegin(), DiagID)
1925     << Range;
1926 }
1927 
1928 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T,
1929                                          SourceRange Range) {
1930   DiagnosticsEngine &Diags = Context.getDiags();
1931   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1932     "cannot mangle this pack expansion yet");
1933   Diags.Report(Range.getBegin(), DiagID)
1934     << Range;
1935 }
1936 
1937 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T,
1938                                          SourceRange Range) {
1939   DiagnosticsEngine &Diags = Context.getDiags();
1940   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1941     "cannot mangle this typeof(type) yet");
1942   Diags.Report(Range.getBegin(), DiagID)
1943     << Range;
1944 }
1945 
1946 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T,
1947                                          SourceRange Range) {
1948   DiagnosticsEngine &Diags = Context.getDiags();
1949   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1950     "cannot mangle this typeof(expression) yet");
1951   Diags.Report(Range.getBegin(), DiagID)
1952     << Range;
1953 }
1954 
1955 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T,
1956                                          SourceRange Range) {
1957   DiagnosticsEngine &Diags = Context.getDiags();
1958   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1959     "cannot mangle this decltype() yet");
1960   Diags.Report(Range.getBegin(), DiagID)
1961     << Range;
1962 }
1963 
1964 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
1965                                          SourceRange Range) {
1966   DiagnosticsEngine &Diags = Context.getDiags();
1967   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1968     "cannot mangle this unary transform type yet");
1969   Diags.Report(Range.getBegin(), DiagID)
1970     << Range;
1971 }
1972 
1973 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, SourceRange Range) {
1974   assert(T->getDeducedType().isNull() && "expecting a dependent type!");
1975 
1976   DiagnosticsEngine &Diags = Context.getDiags();
1977   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1978     "cannot mangle this 'auto' type yet");
1979   Diags.Report(Range.getBegin(), DiagID)
1980     << Range;
1981 }
1982 
1983 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T,
1984                                          SourceRange Range) {
1985   DiagnosticsEngine &Diags = Context.getDiags();
1986   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1987     "cannot mangle this C11 atomic type yet");
1988   Diags.Report(Range.getBegin(), DiagID)
1989     << Range;
1990 }
1991 
1992 void MicrosoftMangleContextImpl::mangleCXXName(const NamedDecl *D,
1993                                                raw_ostream &Out) {
1994   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
1995          "Invalid mangleName() call, argument is not a variable or function!");
1996   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
1997          "Invalid mangleName() call on 'structor decl!");
1998 
1999   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
2000                                  getASTContext().getSourceManager(),
2001                                  "Mangling declaration");
2002 
2003   MicrosoftCXXNameMangler Mangler(*this, Out);
2004   return Mangler.mangle(D);
2005 }
2006 
2007 // <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
2008 //                       <virtual-adjustment>
2009 // <no-adjustment>      ::= A # private near
2010 //                      ::= B # private far
2011 //                      ::= I # protected near
2012 //                      ::= J # protected far
2013 //                      ::= Q # public near
2014 //                      ::= R # public far
2015 // <static-adjustment>  ::= G <static-offset> # private near
2016 //                      ::= H <static-offset> # private far
2017 //                      ::= O <static-offset> # protected near
2018 //                      ::= P <static-offset> # protected far
2019 //                      ::= W <static-offset> # public near
2020 //                      ::= X <static-offset> # public far
2021 // <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
2022 //                      ::= $1 <virtual-shift> <static-offset> # private far
2023 //                      ::= $2 <virtual-shift> <static-offset> # protected near
2024 //                      ::= $3 <virtual-shift> <static-offset> # protected far
2025 //                      ::= $4 <virtual-shift> <static-offset> # public near
2026 //                      ::= $5 <virtual-shift> <static-offset> # public far
2027 // <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
2028 // <vtordisp-shift>     ::= <offset-to-vtordisp>
2029 // <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
2030 //                          <offset-to-vtordisp>
2031 static void mangleThunkThisAdjustment(const CXXMethodDecl *MD,
2032                                       const ThisAdjustment &Adjustment,
2033                                       MicrosoftCXXNameMangler &Mangler,
2034                                       raw_ostream &Out) {
2035   if (!Adjustment.Virtual.isEmpty()) {
2036     Out << '$';
2037     char AccessSpec;
2038     switch (MD->getAccess()) {
2039     case AS_none:
2040       llvm_unreachable("Unsupported access specifier");
2041     case AS_private:
2042       AccessSpec = '0';
2043       break;
2044     case AS_protected:
2045       AccessSpec = '2';
2046       break;
2047     case AS_public:
2048       AccessSpec = '4';
2049     }
2050     if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
2051       Out << 'R' << AccessSpec;
2052       Mangler.mangleNumber(
2053           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
2054       Mangler.mangleNumber(
2055           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
2056       Mangler.mangleNumber(
2057           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2058       Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
2059     } else {
2060       Out << AccessSpec;
2061       Mangler.mangleNumber(
2062           static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
2063       Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2064     }
2065   } else if (Adjustment.NonVirtual != 0) {
2066     switch (MD->getAccess()) {
2067     case AS_none:
2068       llvm_unreachable("Unsupported access specifier");
2069     case AS_private:
2070       Out << 'G';
2071       break;
2072     case AS_protected:
2073       Out << 'O';
2074       break;
2075     case AS_public:
2076       Out << 'W';
2077     }
2078     Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
2079   } else {
2080     switch (MD->getAccess()) {
2081     case AS_none:
2082       llvm_unreachable("Unsupported access specifier");
2083     case AS_private:
2084       Out << 'A';
2085       break;
2086     case AS_protected:
2087       Out << 'I';
2088       break;
2089     case AS_public:
2090       Out << 'Q';
2091     }
2092   }
2093 }
2094 
2095 void
2096 MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
2097                                                      raw_ostream &Out) {
2098   MicrosoftVTableContext *VTContext =
2099       cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
2100   const MicrosoftVTableContext::MethodVFTableLocation &ML =
2101       VTContext->getMethodVFTableLocation(GlobalDecl(MD));
2102 
2103   MicrosoftCXXNameMangler Mangler(*this, Out);
2104   Mangler.getStream() << "\01?";
2105   Mangler.mangleVirtualMemPtrThunk(MD, ML);
2106 }
2107 
2108 void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
2109                                              const ThunkInfo &Thunk,
2110                                              raw_ostream &Out) {
2111   MicrosoftCXXNameMangler Mangler(*this, Out);
2112   Out << "\01?";
2113   Mangler.mangleName(MD);
2114   mangleThunkThisAdjustment(MD, Thunk.This, Mangler, Out);
2115   if (!Thunk.Return.isEmpty())
2116     assert(Thunk.Method != 0 && "Thunk info should hold the overridee decl");
2117 
2118   const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
2119   Mangler.mangleFunctionType(
2120       DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
2121 }
2122 
2123 void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
2124     const CXXDestructorDecl *DD, CXXDtorType Type,
2125     const ThisAdjustment &Adjustment, raw_ostream &Out) {
2126   // FIXME: Actually, the dtor thunk should be emitted for vector deleting
2127   // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
2128   // mangling manually until we support both deleting dtor types.
2129   assert(Type == Dtor_Deleting);
2130   MicrosoftCXXNameMangler Mangler(*this, Out, DD, Type);
2131   Out << "\01??_E";
2132   Mangler.mangleName(DD->getParent());
2133   mangleThunkThisAdjustment(DD, Adjustment, Mangler, Out);
2134   Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
2135 }
2136 
2137 void MicrosoftMangleContextImpl::mangleCXXVFTable(
2138     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2139     raw_ostream &Out) {
2140   // <mangled-name> ::= ?_7 <class-name> <storage-class>
2141   //                    <cvr-qualifiers> [<name>] @
2142   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2143   // is always '6' for vftables.
2144   MicrosoftCXXNameMangler Mangler(*this, Out);
2145   Mangler.getStream() << "\01??_7";
2146   Mangler.mangleName(Derived);
2147   Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
2148   for (ArrayRef<const CXXRecordDecl *>::iterator I = BasePath.begin(),
2149                                                  E = BasePath.end();
2150        I != E; ++I) {
2151     Mangler.mangleName(*I);
2152   }
2153   Mangler.getStream() << '@';
2154 }
2155 
2156 void MicrosoftMangleContextImpl::mangleCXXVBTable(
2157     const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
2158     raw_ostream &Out) {
2159   // <mangled-name> ::= ?_8 <class-name> <storage-class>
2160   //                    <cvr-qualifiers> [<name>] @
2161   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
2162   // is always '7' for vbtables.
2163   MicrosoftCXXNameMangler Mangler(*this, Out);
2164   Mangler.getStream() << "\01??_8";
2165   Mangler.mangleName(Derived);
2166   Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
2167   for (ArrayRef<const CXXRecordDecl *>::iterator I = BasePath.begin(),
2168                                                  E = BasePath.end();
2169        I != E; ++I) {
2170     Mangler.mangleName(*I);
2171   }
2172   Mangler.getStream() << '@';
2173 }
2174 
2175 void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &) {
2176   // FIXME: Give a location...
2177   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2178     "cannot mangle RTTI descriptors for type %0 yet");
2179   getDiags().Report(DiagID)
2180     << T.getBaseTypeIdentifier();
2181 }
2182 
2183 void MicrosoftMangleContextImpl::mangleCXXRTTIName(QualType T, raw_ostream &) {
2184   // FIXME: Give a location...
2185   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2186     "cannot mangle the name of type %0 into RTTI descriptors yet");
2187   getDiags().Report(DiagID)
2188     << T.getBaseTypeIdentifier();
2189 }
2190 
2191 void MicrosoftMangleContextImpl::mangleTypeName(QualType T, raw_ostream &Out) {
2192   // This is just a made up unique string for the purposes of tbaa.  undname
2193   // does *not* know how to demangle it.
2194   MicrosoftCXXNameMangler Mangler(*this, Out);
2195   Mangler.getStream() << '?';
2196   Mangler.mangleType(T, SourceRange());
2197 }
2198 
2199 void MicrosoftMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
2200                                                CXXCtorType Type,
2201                                                raw_ostream &Out) {
2202   MicrosoftCXXNameMangler mangler(*this, Out);
2203   mangler.mangle(D);
2204 }
2205 
2206 void MicrosoftMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
2207                                                CXXDtorType Type,
2208                                                raw_ostream &Out) {
2209   MicrosoftCXXNameMangler mangler(*this, Out, D, Type);
2210   mangler.mangle(D);
2211 }
2212 
2213 void MicrosoftMangleContextImpl::mangleReferenceTemporary(const VarDecl *VD,
2214                                                           raw_ostream &) {
2215   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
2216     "cannot mangle this reference temporary yet");
2217   getDiags().Report(VD->getLocation(), DiagID);
2218 }
2219 
2220 void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
2221                                                            raw_ostream &Out) {
2222   // TODO: This is not correct, especially with respect to MSVC2013.  MSVC2013
2223   // utilizes thread local variables to implement thread safe, re-entrant
2224   // initialization for statics.  They no longer differentiate between an
2225   // externally visible and non-externally visible static with respect to
2226   // mangling, they all get $TSS <number>.
2227   //
2228   // N.B. This means that they can get more than 32 static variable guards in a
2229   // scope.  It also means that they broke compatibility with their own ABI.
2230 
2231   // <guard-name> ::= ?_B <postfix> @51
2232   //              ::= ?$S <guard-num> @ <postfix> @4IA
2233 
2234   // The first mangling is what MSVC uses to guard static locals in inline
2235   // functions.  It uses a different mangling in external functions to support
2236   // guarding more than 32 variables.  MSVC rejects inline functions with more
2237   // than 32 static locals.  We don't fully implement the second mangling
2238   // because those guards are not externally visible, and instead use LLVM's
2239   // default renaming when creating a new guard variable.
2240   MicrosoftCXXNameMangler Mangler(*this, Out);
2241 
2242   bool Visible = VD->isExternallyVisible();
2243   // <operator-name> ::= ?_B # local static guard
2244   Mangler.getStream() << (Visible ? "\01??_B" : "\01?$S1@");
2245   Mangler.manglePostfix(VD->getDeclContext());
2246   Mangler.getStream() << (Visible ? "@51" : "@4IA");
2247 }
2248 
2249 void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
2250                                                     raw_ostream &Out,
2251                                                     char CharCode) {
2252   MicrosoftCXXNameMangler Mangler(*this, Out);
2253   Mangler.getStream() << "\01??__" << CharCode;
2254   Mangler.mangleName(D);
2255   // This is the function class mangling.  These stubs are global, non-variadic,
2256   // cdecl functions that return void and take no args.
2257   Mangler.getStream() << "YAXXZ";
2258 }
2259 
2260 void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
2261                                                           raw_ostream &Out) {
2262   // <initializer-name> ::= ?__E <name> YAXXZ
2263   mangleInitFiniStub(D, Out, 'E');
2264 }
2265 
2266 void
2267 MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
2268                                                           raw_ostream &Out) {
2269   // <destructor-name> ::= ?__F <name> YAXXZ
2270   mangleInitFiniStub(D, Out, 'F');
2271 }
2272 
2273 MicrosoftMangleContext *
2274 MicrosoftMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
2275   return new MicrosoftMangleContextImpl(Context, Diags);
2276 }
2277