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/CharUnits.h"
18 #include "clang/AST/Decl.h"
19 #include "clang/AST/DeclCXX.h"
20 #include "clang/AST/DeclObjC.h"
21 #include "clang/AST/DeclTemplate.h"
22 #include "clang/AST/ExprCXX.h"
23 #include "clang/Basic/ABI.h"
24 #include "clang/Basic/DiagnosticOptions.h"
25 #include <map>
26 
27 using namespace clang;
28 
29 namespace {
30 
31 /// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
32 /// Microsoft Visual C++ ABI.
33 class MicrosoftCXXNameMangler {
34   MangleContext &Context;
35   raw_ostream &Out;
36 
37   // FIXME: audit the performance of BackRefMap as it might do way too many
38   // copying of strings.
39   typedef std::map<std::string, unsigned> BackRefMap;
40   BackRefMap NameBackReferences;
41   bool UseNameBackReferences;
42 
43   typedef llvm::DenseMap<void*, unsigned> ArgBackRefMap;
44   ArgBackRefMap TypeBackReferences;
45 
46   ASTContext &getASTContext() const { return Context.getASTContext(); }
47 
48 public:
49   MicrosoftCXXNameMangler(MangleContext &C, raw_ostream &Out_)
50   : Context(C), Out(Out_), UseNameBackReferences(true) { }
51 
52   raw_ostream &getStream() const { return Out; }
53 
54   void mangle(const NamedDecl *D, StringRef Prefix = "\01?");
55   void mangleName(const NamedDecl *ND);
56   void mangleFunctionEncoding(const FunctionDecl *FD);
57   void mangleVariableEncoding(const VarDecl *VD);
58   void mangleNumber(int64_t Number);
59   void mangleNumber(const llvm::APSInt &Value);
60   void mangleType(QualType T, SourceRange Range, bool MangleQualifiers = true);
61 
62 private:
63   void disableBackReferences() { UseNameBackReferences = false; }
64   void mangleUnqualifiedName(const NamedDecl *ND) {
65     mangleUnqualifiedName(ND, ND->getDeclName());
66   }
67   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
68   void mangleSourceName(const IdentifierInfo *II);
69   void manglePostfix(const DeclContext *DC, bool NoFunction=false);
70   void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
71   void mangleQualifiers(Qualifiers Quals, bool IsMember);
72   void manglePointerQualifiers(Qualifiers Quals);
73 
74   void mangleUnscopedTemplateName(const TemplateDecl *ND);
75   void mangleTemplateInstantiationName(const TemplateDecl *TD,
76                       const SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs);
77   void mangleObjCMethodName(const ObjCMethodDecl *MD);
78   void mangleLocalName(const FunctionDecl *FD);
79 
80   void mangleArgumentType(QualType T, SourceRange Range);
81 
82   // Declare manglers for every type class.
83 #define ABSTRACT_TYPE(CLASS, PARENT)
84 #define NON_CANONICAL_TYPE(CLASS, PARENT)
85 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
86                                             SourceRange Range);
87 #include "clang/AST/TypeNodes.def"
88 #undef ABSTRACT_TYPE
89 #undef NON_CANONICAL_TYPE
90 #undef TYPE
91 
92   void mangleType(const TagType*);
93   void mangleType(const FunctionType *T, const FunctionDecl *D,
94                   bool IsStructor, bool IsInstMethod);
95   void mangleType(const ArrayType *T, bool IsGlobal);
96   void mangleExtraDimensions(QualType T);
97   void mangleFunctionClass(const FunctionDecl *FD);
98   void mangleCallingConvention(const FunctionType *T, bool IsInstMethod = false);
99   void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
100   void mangleExpression(const Expr *E);
101   void mangleThrowSpecification(const FunctionProtoType *T);
102 
103   void mangleTemplateArgs(
104                       const SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs);
105 
106 };
107 
108 /// MicrosoftMangleContext - Overrides the default MangleContext for the
109 /// Microsoft Visual C++ ABI.
110 class MicrosoftMangleContext : public MangleContext {
111 public:
112   MicrosoftMangleContext(ASTContext &Context,
113                    DiagnosticsEngine &Diags) : MangleContext(Context, Diags) { }
114   virtual bool shouldMangleDeclName(const NamedDecl *D);
115   virtual void mangleName(const NamedDecl *D, raw_ostream &Out);
116   virtual void mangleThunk(const CXXMethodDecl *MD,
117                            const ThunkInfo &Thunk,
118                            raw_ostream &);
119   virtual void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
120                                   const ThisAdjustment &ThisAdjustment,
121                                   raw_ostream &);
122   virtual void mangleCXXVTable(const CXXRecordDecl *RD,
123                                raw_ostream &);
124   virtual void mangleCXXVTT(const CXXRecordDecl *RD,
125                             raw_ostream &);
126   virtual void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
127                                    const CXXRecordDecl *Type,
128                                    raw_ostream &);
129   virtual void mangleCXXRTTI(QualType T, raw_ostream &);
130   virtual void mangleCXXRTTIName(QualType T, raw_ostream &);
131   virtual void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
132                              raw_ostream &);
133   virtual void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
134                              raw_ostream &);
135   virtual void mangleReferenceTemporary(const clang::VarDecl *,
136                                         raw_ostream &);
137 };
138 
139 }
140 
141 static bool isInCLinkageSpecification(const Decl *D) {
142   D = D->getCanonicalDecl();
143   for (const DeclContext *DC = D->getDeclContext();
144        !DC->isTranslationUnit(); DC = DC->getParent()) {
145     if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))
146       return Linkage->getLanguage() == LinkageSpecDecl::lang_c;
147   }
148 
149   return false;
150 }
151 
152 bool MicrosoftMangleContext::shouldMangleDeclName(const NamedDecl *D) {
153   // In C, functions with no attributes never need to be mangled. Fastpath them.
154   if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
155     return false;
156 
157   // Any decl can be declared with __asm("foo") on it, and this takes precedence
158   // over all other naming in the .o file.
159   if (D->hasAttr<AsmLabelAttr>())
160     return true;
161 
162   // Clang's "overloadable" attribute extension to C/C++ implies name mangling
163   // (always) as does passing a C++ member function and a function
164   // whose name is not a simple identifier.
165   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
166   if (FD && (FD->hasAttr<OverloadableAttr>() || isa<CXXMethodDecl>(FD) ||
167              !FD->getDeclName().isIdentifier()))
168     return true;
169 
170   // Otherwise, no mangling is done outside C++ mode.
171   if (!getASTContext().getLangOpts().CPlusPlus)
172     return false;
173 
174   // Variables at global scope with internal linkage are not mangled.
175   if (!FD) {
176     const DeclContext *DC = D->getDeclContext();
177     if (DC->isTranslationUnit() && D->getLinkage() == InternalLinkage)
178       return false;
179   }
180 
181   // C functions and "main" are not mangled.
182   if ((FD && FD->isMain()) || isInCLinkageSpecification(D))
183     return false;
184 
185   return true;
186 }
187 
188 void MicrosoftCXXNameMangler::mangle(const NamedDecl *D,
189                                      StringRef Prefix) {
190   // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
191   // Therefore it's really important that we don't decorate the
192   // name with leading underscores or leading/trailing at signs. So, by
193   // default, we emit an asm marker at the start so we get the name right.
194   // Callers can override this with a custom prefix.
195 
196   // Any decl can be declared with __asm("foo") on it, and this takes precedence
197   // over all other naming in the .o file.
198   if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
199     // If we have an asm name, then we use it as the mangling.
200     Out << '\01' << ALA->getLabel();
201     return;
202   }
203 
204   // <mangled-name> ::= ? <name> <type-encoding>
205   Out << Prefix;
206   mangleName(D);
207   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
208     mangleFunctionEncoding(FD);
209   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
210     mangleVariableEncoding(VD);
211   else {
212     // TODO: Fields? Can MSVC even mangle them?
213     // Issue a diagnostic for now.
214     DiagnosticsEngine &Diags = Context.getDiags();
215     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
216       "cannot mangle this declaration yet");
217     Diags.Report(D->getLocation(), DiagID)
218       << D->getSourceRange();
219   }
220 }
221 
222 void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
223   // <type-encoding> ::= <function-class> <function-type>
224 
225   // Don't mangle in the type if this isn't a decl we should typically mangle.
226   if (!Context.shouldMangleDeclName(FD))
227     return;
228 
229   // We should never ever see a FunctionNoProtoType at this point.
230   // We don't even know how to mangle their types anyway :).
231   const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
232 
233   bool InStructor = false, InInstMethod = false;
234   const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
235   if (MD) {
236     if (MD->isInstance())
237       InInstMethod = true;
238     if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
239       InStructor = true;
240   }
241 
242   // First, the function class.
243   mangleFunctionClass(FD);
244 
245   mangleType(FT, FD, InStructor, InInstMethod);
246 }
247 
248 void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
249   // <type-encoding> ::= <storage-class> <variable-type>
250   // <storage-class> ::= 0  # private static member
251   //                 ::= 1  # protected static member
252   //                 ::= 2  # public static member
253   //                 ::= 3  # global
254   //                 ::= 4  # static local
255 
256   // The first character in the encoding (after the name) is the storage class.
257   if (VD->isStaticDataMember()) {
258     // If it's a static member, it also encodes the access level.
259     switch (VD->getAccess()) {
260       default:
261       case AS_private: Out << '0'; break;
262       case AS_protected: Out << '1'; break;
263       case AS_public: Out << '2'; break;
264     }
265   }
266   else if (!VD->isStaticLocal())
267     Out << '3';
268   else
269     Out << '4';
270   // Now mangle the type.
271   // <variable-type> ::= <type> <cvr-qualifiers>
272   //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
273   // Pointers and references are odd. The type of 'int * const foo;' gets
274   // mangled as 'QAHA' instead of 'PAHB', for example.
275   TypeLoc TL = VD->getTypeSourceInfo()->getTypeLoc();
276   QualType Ty = TL.getType();
277   if (Ty->isPointerType() || Ty->isReferenceType()) {
278     mangleType(Ty, TL.getSourceRange());
279     mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
280   } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
281     // Global arrays are funny, too.
282     mangleType(AT, true);
283     mangleQualifiers(Ty.getQualifiers(), false);
284   } else {
285     mangleType(Ty.getLocalUnqualifiedType(), TL.getSourceRange());
286     mangleQualifiers(Ty.getLocalQualifiers(), false);
287   }
288 }
289 
290 void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
291   // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
292   const DeclContext *DC = ND->getDeclContext();
293 
294   // Always start with the unqualified name.
295   mangleUnqualifiedName(ND);
296 
297   // If this is an extern variable declared locally, the relevant DeclContext
298   // is that of the containing namespace, or the translation unit.
299   if (isa<FunctionDecl>(DC) && ND->hasLinkage())
300     while (!DC->isNamespace() && !DC->isTranslationUnit())
301       DC = DC->getParent();
302 
303   manglePostfix(DC);
304 
305   // Terminate the whole name with an '@'.
306   Out << '@';
307 }
308 
309 void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
310   llvm::APSInt APSNumber(/*BitWidth=*/64, /*isUnsigned=*/false);
311   APSNumber = Number;
312   mangleNumber(APSNumber);
313 }
314 
315 void MicrosoftCXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
316   // <number> ::= [?] <decimal digit> # 1 <= Number <= 10
317   //          ::= [?] <hex digit>+ @ # 0 or > 9; A = 0, B = 1, etc...
318   //          ::= [?] @ # 0 (alternate mangling, not emitted by VC)
319   if (Value.isSigned() && Value.isNegative()) {
320     Out << '?';
321     mangleNumber(llvm::APSInt(Value.abs()));
322     return;
323   }
324   llvm::APSInt Temp(Value);
325   // There's a special shorter mangling for 0, but Microsoft
326   // chose not to use it. Instead, 0 gets mangled as "A@". Oh well...
327   if (Value.uge(1) && Value.ule(10)) {
328     --Temp;
329     Temp.print(Out, false);
330   } else {
331     // We have to build up the encoding in reverse order, so it will come
332     // out right when we write it out.
333     char Encoding[64];
334     char *EndPtr = Encoding+sizeof(Encoding);
335     char *CurPtr = EndPtr;
336     llvm::APSInt NibbleMask(Value.getBitWidth(), Value.isUnsigned());
337     NibbleMask = 0xf;
338     do {
339       *--CurPtr = 'A' + Temp.And(NibbleMask).getLimitedValue(0xf);
340       Temp = Temp.lshr(4);
341     } while (Temp != 0);
342     Out.write(CurPtr, EndPtr-CurPtr);
343     Out << '@';
344   }
345 }
346 
347 static const TemplateDecl *
348 isTemplate(const NamedDecl *ND,
349            SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
350   // Check if we have a function template.
351   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
352     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
353       if (FD->getTemplateSpecializationArgsAsWritten()) {
354         const ASTTemplateArgumentListInfo *ArgList =
355           FD->getTemplateSpecializationArgsAsWritten();
356         TemplateArgs.append(ArgList->getTemplateArgs(),
357                             ArgList->getTemplateArgs() +
358                               ArgList->NumTemplateArgs);
359       } else {
360         const TemplateArgumentList *ArgList =
361           FD->getTemplateSpecializationArgs();
362         TemplateArgumentListInfo LI;
363         for (unsigned i = 0, e = ArgList->size(); i != e; ++i)
364           TemplateArgs.push_back(TemplateArgumentLoc(ArgList->get(i),
365                                                      FD->getTypeSourceInfo()));
366       }
367       return TD;
368     }
369   }
370 
371   // Check if we have a class template.
372   if (const ClassTemplateSpecializationDecl *Spec =
373       dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
374     TypeSourceInfo *TSI = Spec->getTypeAsWritten();
375     if (TSI) {
376       TemplateSpecializationTypeLoc TSTL =
377         cast<TemplateSpecializationTypeLoc>(TSI->getTypeLoc());
378       TemplateArgumentListInfo LI(TSTL.getLAngleLoc(), TSTL.getRAngleLoc());
379       for (unsigned i = 0, e = TSTL.getNumArgs(); i != e; ++i)
380         TemplateArgs.push_back(TSTL.getArgLoc(i));
381     } else {
382       TemplateArgumentListInfo LI;
383       const TemplateArgumentList &ArgList =
384         Spec->getTemplateArgs();
385       for (unsigned i = 0, e = ArgList.size(); i != e; ++i)
386         TemplateArgs.push_back(TemplateArgumentLoc(ArgList[i],
387                                                    TemplateArgumentLocInfo()));
388     }
389     return Spec->getSpecializedTemplate();
390   }
391 
392   return 0;
393 }
394 
395 void
396 MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
397                                                DeclarationName Name) {
398   //  <unqualified-name> ::= <operator-name>
399   //                     ::= <ctor-dtor-name>
400   //                     ::= <source-name>
401   //                     ::= <template-name>
402   SmallVector<TemplateArgumentLoc, 2> TemplateArgs;
403   // Check if we have a template.
404   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
405     // We have a template.
406     // Here comes the tricky thing: if we need to mangle something like
407     //   void foo(A::X<Y>, B::X<Y>),
408     // the X<Y> part is aliased. However, if you need to mangle
409     //   void foo(A::X<A::Y>, A::X<B::Y>),
410     // the A::X<> part is not aliased.
411     // That said, from the mangler's perspective we have a structure like this:
412     //   namespace[s] -> type[ -> template-parameters]
413     // but from the Clang perspective we have
414     //   type [ -> template-parameters]
415     //      \-> namespace[s]
416     // What we do is we create a new mangler, mangle the same type (without
417     // a namespace suffix) using the extra mangler with back references
418     // disabled (to avoid infinite recursion) and then use the mangled type
419     // name as a key to check the mangling of different types for aliasing.
420 
421     std::string BackReferenceKey;
422     BackRefMap::iterator Found;
423     if (UseNameBackReferences) {
424       llvm::raw_string_ostream Stream(BackReferenceKey);
425       MicrosoftCXXNameMangler Extra(Context, Stream);
426       Extra.disableBackReferences();
427       Extra.mangleUnqualifiedName(ND, Name);
428       Stream.flush();
429 
430       Found = NameBackReferences.find(BackReferenceKey);
431     }
432     if (!UseNameBackReferences || Found == NameBackReferences.end()) {
433       mangleTemplateInstantiationName(TD, TemplateArgs);
434       if (UseNameBackReferences && NameBackReferences.size() < 10) {
435         size_t Size = NameBackReferences.size();
436         NameBackReferences[BackReferenceKey] = Size;
437       }
438     } else {
439       Out << Found->second;
440     }
441     return;
442   }
443 
444   switch (Name.getNameKind()) {
445     case DeclarationName::Identifier: {
446       if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
447         mangleSourceName(II);
448         break;
449       }
450 
451       // Otherwise, an anonymous entity.  We must have a declaration.
452       assert(ND && "mangling empty name without declaration");
453 
454       if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
455         if (NS->isAnonymousNamespace()) {
456           Out << "?A@";
457           break;
458         }
459       }
460 
461       // We must have an anonymous struct.
462       const TagDecl *TD = cast<TagDecl>(ND);
463       if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
464         assert(TD->getDeclContext() == D->getDeclContext() &&
465                "Typedef should not be in another decl context!");
466         assert(D->getDeclName().getAsIdentifierInfo() &&
467                "Typedef was not named!");
468         mangleSourceName(D->getDeclName().getAsIdentifierInfo());
469         break;
470       }
471 
472       // When VC encounters an anonymous type with no tag and no typedef,
473       // it literally emits '<unnamed-tag>'.
474       Out << "<unnamed-tag>";
475       break;
476     }
477 
478     case DeclarationName::ObjCZeroArgSelector:
479     case DeclarationName::ObjCOneArgSelector:
480     case DeclarationName::ObjCMultiArgSelector:
481       llvm_unreachable("Can't mangle Objective-C selector names here!");
482 
483     case DeclarationName::CXXConstructorName:
484       Out << "?0";
485       break;
486 
487     case DeclarationName::CXXDestructorName:
488       Out << "?1";
489       break;
490 
491     case DeclarationName::CXXConversionFunctionName:
492       // <operator-name> ::= ?B # (cast)
493       // The target type is encoded as the return type.
494       Out << "?B";
495       break;
496 
497     case DeclarationName::CXXOperatorName:
498       mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
499       break;
500 
501     case DeclarationName::CXXLiteralOperatorName: {
502       // FIXME: Was this added in VS2010? Does MS even know how to mangle this?
503       DiagnosticsEngine Diags = Context.getDiags();
504       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
505         "cannot mangle this literal operator yet");
506       Diags.Report(ND->getLocation(), DiagID);
507       break;
508     }
509 
510     case DeclarationName::CXXUsingDirective:
511       llvm_unreachable("Can't mangle a using directive name!");
512   }
513 }
514 
515 void MicrosoftCXXNameMangler::manglePostfix(const DeclContext *DC,
516                                             bool NoFunction) {
517   // <postfix> ::= <unqualified-name> [<postfix>]
518   //           ::= <substitution> [<postfix>]
519 
520   if (!DC) return;
521 
522   while (isa<LinkageSpecDecl>(DC))
523     DC = DC->getParent();
524 
525   if (DC->isTranslationUnit())
526     return;
527 
528   if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
529     Context.mangleBlock(BD, Out);
530     Out << '@';
531     return manglePostfix(DC->getParent(), NoFunction);
532   }
533 
534   if (NoFunction && (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)))
535     return;
536   else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC))
537     mangleObjCMethodName(Method);
538   else if (const FunctionDecl *Func = dyn_cast<FunctionDecl>(DC))
539     mangleLocalName(Func);
540   else {
541     mangleUnqualifiedName(cast<NamedDecl>(DC));
542     manglePostfix(DC->getParent(), NoFunction);
543   }
544 }
545 
546 void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
547                                                  SourceLocation Loc) {
548   switch (OO) {
549   //                     ?0 # constructor
550   //                     ?1 # destructor
551   // <operator-name> ::= ?2 # new
552   case OO_New: Out << "?2"; break;
553   // <operator-name> ::= ?3 # delete
554   case OO_Delete: Out << "?3"; break;
555   // <operator-name> ::= ?4 # =
556   case OO_Equal: Out << "?4"; break;
557   // <operator-name> ::= ?5 # >>
558   case OO_GreaterGreater: Out << "?5"; break;
559   // <operator-name> ::= ?6 # <<
560   case OO_LessLess: Out << "?6"; break;
561   // <operator-name> ::= ?7 # !
562   case OO_Exclaim: Out << "?7"; break;
563   // <operator-name> ::= ?8 # ==
564   case OO_EqualEqual: Out << "?8"; break;
565   // <operator-name> ::= ?9 # !=
566   case OO_ExclaimEqual: Out << "?9"; break;
567   // <operator-name> ::= ?A # []
568   case OO_Subscript: Out << "?A"; break;
569   //                     ?B # conversion
570   // <operator-name> ::= ?C # ->
571   case OO_Arrow: Out << "?C"; break;
572   // <operator-name> ::= ?D # *
573   case OO_Star: Out << "?D"; break;
574   // <operator-name> ::= ?E # ++
575   case OO_PlusPlus: Out << "?E"; break;
576   // <operator-name> ::= ?F # --
577   case OO_MinusMinus: Out << "?F"; break;
578   // <operator-name> ::= ?G # -
579   case OO_Minus: Out << "?G"; break;
580   // <operator-name> ::= ?H # +
581   case OO_Plus: Out << "?H"; break;
582   // <operator-name> ::= ?I # &
583   case OO_Amp: Out << "?I"; break;
584   // <operator-name> ::= ?J # ->*
585   case OO_ArrowStar: Out << "?J"; break;
586   // <operator-name> ::= ?K # /
587   case OO_Slash: Out << "?K"; break;
588   // <operator-name> ::= ?L # %
589   case OO_Percent: Out << "?L"; break;
590   // <operator-name> ::= ?M # <
591   case OO_Less: Out << "?M"; break;
592   // <operator-name> ::= ?N # <=
593   case OO_LessEqual: Out << "?N"; break;
594   // <operator-name> ::= ?O # >
595   case OO_Greater: Out << "?O"; break;
596   // <operator-name> ::= ?P # >=
597   case OO_GreaterEqual: Out << "?P"; break;
598   // <operator-name> ::= ?Q # ,
599   case OO_Comma: Out << "?Q"; break;
600   // <operator-name> ::= ?R # ()
601   case OO_Call: Out << "?R"; break;
602   // <operator-name> ::= ?S # ~
603   case OO_Tilde: Out << "?S"; break;
604   // <operator-name> ::= ?T # ^
605   case OO_Caret: Out << "?T"; break;
606   // <operator-name> ::= ?U # |
607   case OO_Pipe: Out << "?U"; break;
608   // <operator-name> ::= ?V # &&
609   case OO_AmpAmp: Out << "?V"; break;
610   // <operator-name> ::= ?W # ||
611   case OO_PipePipe: Out << "?W"; break;
612   // <operator-name> ::= ?X # *=
613   case OO_StarEqual: Out << "?X"; break;
614   // <operator-name> ::= ?Y # +=
615   case OO_PlusEqual: Out << "?Y"; break;
616   // <operator-name> ::= ?Z # -=
617   case OO_MinusEqual: Out << "?Z"; break;
618   // <operator-name> ::= ?_0 # /=
619   case OO_SlashEqual: Out << "?_0"; break;
620   // <operator-name> ::= ?_1 # %=
621   case OO_PercentEqual: Out << "?_1"; break;
622   // <operator-name> ::= ?_2 # >>=
623   case OO_GreaterGreaterEqual: Out << "?_2"; break;
624   // <operator-name> ::= ?_3 # <<=
625   case OO_LessLessEqual: Out << "?_3"; break;
626   // <operator-name> ::= ?_4 # &=
627   case OO_AmpEqual: Out << "?_4"; break;
628   // <operator-name> ::= ?_5 # |=
629   case OO_PipeEqual: Out << "?_5"; break;
630   // <operator-name> ::= ?_6 # ^=
631   case OO_CaretEqual: Out << "?_6"; break;
632   //                     ?_7 # vftable
633   //                     ?_8 # vbtable
634   //                     ?_9 # vcall
635   //                     ?_A # typeof
636   //                     ?_B # local static guard
637   //                     ?_C # string
638   //                     ?_D # vbase destructor
639   //                     ?_E # vector deleting destructor
640   //                     ?_F # default constructor closure
641   //                     ?_G # scalar deleting destructor
642   //                     ?_H # vector constructor iterator
643   //                     ?_I # vector destructor iterator
644   //                     ?_J # vector vbase constructor iterator
645   //                     ?_K # virtual displacement map
646   //                     ?_L # eh vector constructor iterator
647   //                     ?_M # eh vector destructor iterator
648   //                     ?_N # eh vector vbase constructor iterator
649   //                     ?_O # copy constructor closure
650   //                     ?_P<name> # udt returning <name>
651   //                     ?_Q # <unknown>
652   //                     ?_R0 # RTTI Type Descriptor
653   //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
654   //                     ?_R2 # RTTI Base Class Array
655   //                     ?_R3 # RTTI Class Hierarchy Descriptor
656   //                     ?_R4 # RTTI Complete Object Locator
657   //                     ?_S # local vftable
658   //                     ?_T # local vftable constructor closure
659   // <operator-name> ::= ?_U # new[]
660   case OO_Array_New: Out << "?_U"; break;
661   // <operator-name> ::= ?_V # delete[]
662   case OO_Array_Delete: Out << "?_V"; break;
663 
664   case OO_Conditional: {
665     DiagnosticsEngine &Diags = Context.getDiags();
666     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
667       "cannot mangle this conditional operator yet");
668     Diags.Report(Loc, DiagID);
669     break;
670   }
671 
672   case OO_None:
673   case NUM_OVERLOADED_OPERATORS:
674     llvm_unreachable("Not an overloaded operator");
675   }
676 }
677 
678 void MicrosoftCXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
679   // <source name> ::= <identifier> @
680   std::string key = II->getNameStart();
681   BackRefMap::iterator Found;
682   if (UseNameBackReferences)
683     Found = NameBackReferences.find(key);
684   if (!UseNameBackReferences || Found == NameBackReferences.end()) {
685     Out << II->getName() << '@';
686     if (UseNameBackReferences && NameBackReferences.size() < 10) {
687       size_t Size = NameBackReferences.size();
688       NameBackReferences[key] = Size;
689     }
690   } else {
691     Out << Found->second;
692   }
693 }
694 
695 void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
696   Context.mangleObjCMethodName(MD, Out);
697 }
698 
699 // Find out how many function decls live above this one and return an integer
700 // suitable for use as the number in a numbered anonymous scope.
701 // TODO: Memoize.
702 static unsigned getLocalNestingLevel(const FunctionDecl *FD) {
703   const DeclContext *DC = FD->getParent();
704   int level = 1;
705 
706   while (DC && !DC->isTranslationUnit()) {
707     if (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)) level++;
708     DC = DC->getParent();
709   }
710 
711   return 2*level;
712 }
713 
714 void MicrosoftCXXNameMangler::mangleLocalName(const FunctionDecl *FD) {
715   // <nested-name> ::= <numbered-anonymous-scope> ? <mangled-name>
716   // <numbered-anonymous-scope> ::= ? <number>
717   // Even though the name is rendered in reverse order (e.g.
718   // A::B::C is rendered as C@B@A), VC numbers the scopes from outermost to
719   // innermost. So a method bar in class C local to function foo gets mangled
720   // as something like:
721   // ?bar@C@?1??foo@@YAXXZ@QAEXXZ
722   // This is more apparent when you have a type nested inside a method of a
723   // type nested inside a function. A method baz in class D local to method
724   // bar of class C local to function foo gets mangled as:
725   // ?baz@D@?3??bar@C@?1??foo@@YAXXZ@QAEXXZ@QAEXXZ
726   // This scheme is general enough to support GCC-style nested
727   // functions. You could have a method baz of class C inside a function bar
728   // inside a function foo, like so:
729   // ?baz@C@?3??bar@?1??foo@@YAXXZ@YAXXZ@QAEXXZ
730   int NestLevel = getLocalNestingLevel(FD);
731   Out << '?';
732   mangleNumber(NestLevel);
733   Out << '?';
734   mangle(FD, "?");
735 }
736 
737 void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
738                                                          const TemplateDecl *TD,
739                      const SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
740   // <template-name> ::= <unscoped-template-name> <template-args>
741   //                 ::= <substitution>
742   // Always start with the unqualified name.
743 
744   // Templates have their own context for back references.
745   ArgBackRefMap OuterArgsContext;
746   BackRefMap OuterTemplateContext;
747   NameBackReferences.swap(OuterTemplateContext);
748   TypeBackReferences.swap(OuterArgsContext);
749 
750   mangleUnscopedTemplateName(TD);
751   mangleTemplateArgs(TemplateArgs);
752 
753   // Restore the previous back reference contexts.
754   NameBackReferences.swap(OuterTemplateContext);
755   TypeBackReferences.swap(OuterArgsContext);
756 }
757 
758 void
759 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
760   // <unscoped-template-name> ::= ?$ <unqualified-name>
761   Out << "?$";
762   mangleUnqualifiedName(TD);
763 }
764 
765 void
766 MicrosoftCXXNameMangler::mangleIntegerLiteral(const llvm::APSInt &Value,
767                                               bool IsBoolean) {
768   // <integer-literal> ::= $0 <number>
769   Out << "$0";
770   // Make sure booleans are encoded as 0/1.
771   if (IsBoolean && Value.getBoolValue())
772     mangleNumber(1);
773   else
774     mangleNumber(Value);
775 }
776 
777 void
778 MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
779   // See if this is a constant expression.
780   llvm::APSInt Value;
781   if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
782     mangleIntegerLiteral(Value, E->getType()->isBooleanType());
783     return;
784   }
785 
786   // As bad as this diagnostic is, it's better than crashing.
787   DiagnosticsEngine &Diags = Context.getDiags();
788   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
789                                    "cannot yet mangle expression type %0");
790   Diags.Report(E->getExprLoc(), DiagID)
791     << E->getStmtClassName() << E->getSourceRange();
792 }
793 
794 void
795 MicrosoftCXXNameMangler::mangleTemplateArgs(
796                      const SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
797   // <template-args> ::= {<type> | <integer-literal>}+ @
798   unsigned NumTemplateArgs = TemplateArgs.size();
799   for (unsigned i = 0; i < NumTemplateArgs; ++i) {
800     const TemplateArgumentLoc &TAL = TemplateArgs[i];
801     const TemplateArgument &TA = TAL.getArgument();
802     switch (TA.getKind()) {
803     case TemplateArgument::Null:
804       llvm_unreachable("Can't mangle null template arguments!");
805     case TemplateArgument::Type:
806       mangleType(TA.getAsType(), TAL.getSourceRange());
807       break;
808     case TemplateArgument::Integral:
809       mangleIntegerLiteral(TA.getAsIntegral(),
810                            TA.getIntegralType()->isBooleanType());
811       break;
812     case TemplateArgument::Expression:
813       mangleExpression(TA.getAsExpr());
814       break;
815     case TemplateArgument::Template:
816     case TemplateArgument::TemplateExpansion:
817     case TemplateArgument::Declaration:
818     case TemplateArgument::NullPtr:
819     case TemplateArgument::Pack: {
820       // Issue a diagnostic.
821       DiagnosticsEngine &Diags = Context.getDiags();
822       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
823         "cannot mangle this %select{ERROR|ERROR|pointer/reference|nullptr|"
824         "integral|template|template pack expansion|ERROR|parameter pack}0 "
825         "template argument yet");
826       Diags.Report(TAL.getLocation(), DiagID)
827         << TA.getKind()
828         << TAL.getSourceRange();
829     }
830     }
831   }
832   Out << '@';
833 }
834 
835 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
836                                                bool IsMember) {
837   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
838   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
839   // 'I' means __restrict (32/64-bit).
840   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
841   // keyword!
842   // <base-cvr-qualifiers> ::= A  # near
843   //                       ::= B  # near const
844   //                       ::= C  # near volatile
845   //                       ::= D  # near const volatile
846   //                       ::= E  # far (16-bit)
847   //                       ::= F  # far const (16-bit)
848   //                       ::= G  # far volatile (16-bit)
849   //                       ::= H  # far const volatile (16-bit)
850   //                       ::= I  # huge (16-bit)
851   //                       ::= J  # huge const (16-bit)
852   //                       ::= K  # huge volatile (16-bit)
853   //                       ::= L  # huge const volatile (16-bit)
854   //                       ::= M <basis> # based
855   //                       ::= N <basis> # based const
856   //                       ::= O <basis> # based volatile
857   //                       ::= P <basis> # based const volatile
858   //                       ::= Q  # near member
859   //                       ::= R  # near const member
860   //                       ::= S  # near volatile member
861   //                       ::= T  # near const volatile member
862   //                       ::= U  # far member (16-bit)
863   //                       ::= V  # far const member (16-bit)
864   //                       ::= W  # far volatile member (16-bit)
865   //                       ::= X  # far const volatile member (16-bit)
866   //                       ::= Y  # huge member (16-bit)
867   //                       ::= Z  # huge const member (16-bit)
868   //                       ::= 0  # huge volatile member (16-bit)
869   //                       ::= 1  # huge const volatile member (16-bit)
870   //                       ::= 2 <basis> # based member
871   //                       ::= 3 <basis> # based const member
872   //                       ::= 4 <basis> # based volatile member
873   //                       ::= 5 <basis> # based const volatile member
874   //                       ::= 6  # near function (pointers only)
875   //                       ::= 7  # far function (pointers only)
876   //                       ::= 8  # near method (pointers only)
877   //                       ::= 9  # far method (pointers only)
878   //                       ::= _A <basis> # based function (pointers only)
879   //                       ::= _B <basis> # based function (far?) (pointers only)
880   //                       ::= _C <basis> # based method (pointers only)
881   //                       ::= _D <basis> # based method (far?) (pointers only)
882   //                       ::= _E # block (Clang)
883   // <basis> ::= 0 # __based(void)
884   //         ::= 1 # __based(segment)?
885   //         ::= 2 <name> # __based(name)
886   //         ::= 3 # ?
887   //         ::= 4 # ?
888   //         ::= 5 # not really based
889   bool HasConst = Quals.hasConst(),
890        HasVolatile = Quals.hasVolatile();
891   if (!IsMember) {
892     if (HasConst && HasVolatile) {
893       Out << 'D';
894     } else if (HasVolatile) {
895       Out << 'C';
896     } else if (HasConst) {
897       Out << 'B';
898     } else {
899       Out << 'A';
900     }
901   } else {
902     if (HasConst && HasVolatile) {
903       Out << 'T';
904     } else if (HasVolatile) {
905       Out << 'S';
906     } else if (HasConst) {
907       Out << 'R';
908     } else {
909       Out << 'Q';
910     }
911   }
912 
913   // FIXME: For now, just drop all extension qualifiers on the floor.
914 }
915 
916 void MicrosoftCXXNameMangler::manglePointerQualifiers(Qualifiers Quals) {
917   // <pointer-cvr-qualifiers> ::= P  # no qualifiers
918   //                          ::= Q  # const
919   //                          ::= R  # volatile
920   //                          ::= S  # const volatile
921   bool HasConst = Quals.hasConst(),
922        HasVolatile = Quals.hasVolatile();
923   if (HasConst && HasVolatile) {
924     Out << 'S';
925   } else if (HasVolatile) {
926     Out << 'R';
927   } else if (HasConst) {
928     Out << 'Q';
929   } else {
930     Out << 'P';
931   }
932 }
933 
934 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
935                                                  SourceRange Range) {
936   void *TypePtr = getASTContext().getCanonicalType(T).getAsOpaquePtr();
937   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
938 
939   if (Found == TypeBackReferences.end()) {
940     size_t OutSizeBefore = Out.GetNumBytesInBuffer();
941 
942     mangleType(T, Range, false);
943 
944     // See if it's worth creating a back reference.
945     // Only types longer than 1 character are considered
946     // and only 10 back references slots are available:
947     bool LongerThanOneChar = (Out.GetNumBytesInBuffer() - OutSizeBefore > 1);
948     if (LongerThanOneChar && TypeBackReferences.size() < 10) {
949       size_t Size = TypeBackReferences.size();
950       TypeBackReferences[TypePtr] = Size;
951     }
952   } else {
953     Out << Found->second;
954   }
955 }
956 
957 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
958                                          bool MangleQualifiers) {
959   // Only operate on the canonical type!
960   T = getASTContext().getCanonicalType(T);
961 
962   Qualifiers Quals = T.getLocalQualifiers();
963   // We have to mangle these now, while we still have enough information.
964   if (T->isAnyPointerType() || T->isMemberPointerType() ||
965       T->isBlockPointerType()) {
966     manglePointerQualifiers(Quals);
967   } else if (Quals && MangleQualifiers) {
968     mangleQualifiers(Quals, false);
969   }
970 
971   SplitQualType split = T.split();
972   const Type *ty = split.Ty;
973 
974   // If we're mangling a qualified array type, push the qualifiers to
975   // the element type.
976   if (split.Quals && isa<ArrayType>(T)) {
977     ty = Context.getASTContext().getAsArrayType(T);
978   }
979 
980   switch (ty->getTypeClass()) {
981 #define ABSTRACT_TYPE(CLASS, PARENT)
982 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
983   case Type::CLASS: \
984     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
985     return;
986 #define TYPE(CLASS, PARENT) \
987   case Type::CLASS: \
988     mangleType(cast<CLASS##Type>(ty), Range); \
989     break;
990 #include "clang/AST/TypeNodes.def"
991 #undef ABSTRACT_TYPE
992 #undef NON_CANONICAL_TYPE
993 #undef TYPE
994   }
995 }
996 
997 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T,
998                                          SourceRange Range) {
999   //  <type>         ::= <builtin-type>
1000   //  <builtin-type> ::= X  # void
1001   //                 ::= C  # signed char
1002   //                 ::= D  # char
1003   //                 ::= E  # unsigned char
1004   //                 ::= F  # short
1005   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1006   //                 ::= H  # int
1007   //                 ::= I  # unsigned int
1008   //                 ::= J  # long
1009   //                 ::= K  # unsigned long
1010   //                     L  # <none>
1011   //                 ::= M  # float
1012   //                 ::= N  # double
1013   //                 ::= O  # long double (__float80 is mangled differently)
1014   //                 ::= _J # long long, __int64
1015   //                 ::= _K # unsigned long long, __int64
1016   //                 ::= _L # __int128
1017   //                 ::= _M # unsigned __int128
1018   //                 ::= _N # bool
1019   //                     _O # <array in parameter>
1020   //                 ::= _T # __float80 (Intel)
1021   //                 ::= _W # wchar_t
1022   //                 ::= _Z # __float80 (Digital Mars)
1023   switch (T->getKind()) {
1024   case BuiltinType::Void: Out << 'X'; break;
1025   case BuiltinType::SChar: Out << 'C'; break;
1026   case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
1027   case BuiltinType::UChar: Out << 'E'; break;
1028   case BuiltinType::Short: Out << 'F'; break;
1029   case BuiltinType::UShort: Out << 'G'; break;
1030   case BuiltinType::Int: Out << 'H'; break;
1031   case BuiltinType::UInt: Out << 'I'; break;
1032   case BuiltinType::Long: Out << 'J'; break;
1033   case BuiltinType::ULong: Out << 'K'; break;
1034   case BuiltinType::Float: Out << 'M'; break;
1035   case BuiltinType::Double: Out << 'N'; break;
1036   // TODO: Determine size and mangle accordingly
1037   case BuiltinType::LongDouble: Out << 'O'; break;
1038   case BuiltinType::LongLong: Out << "_J"; break;
1039   case BuiltinType::ULongLong: Out << "_K"; break;
1040   case BuiltinType::Int128: Out << "_L"; break;
1041   case BuiltinType::UInt128: Out << "_M"; break;
1042   case BuiltinType::Bool: Out << "_N"; break;
1043   case BuiltinType::WChar_S:
1044   case BuiltinType::WChar_U: Out << "_W"; break;
1045 
1046 #define BUILTIN_TYPE(Id, SingletonId)
1047 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1048   case BuiltinType::Id:
1049 #include "clang/AST/BuiltinTypes.def"
1050   case BuiltinType::Dependent:
1051     llvm_unreachable("placeholder types shouldn't get to name mangling");
1052 
1053   case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
1054   case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
1055   case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
1056 
1057   case BuiltinType::OCLImage1d: Out << "PAUocl_image1d@@"; break;
1058   case BuiltinType::OCLImage1dArray: Out << "PAUocl_image1darray@@"; break;
1059   case BuiltinType::OCLImage1dBuffer: Out << "PAUocl_image1dbuffer@@"; break;
1060   case BuiltinType::OCLImage2d: Out << "PAUocl_image2d@@"; break;
1061   case BuiltinType::OCLImage2dArray: Out << "PAUocl_image2darray@@"; break;
1062   case BuiltinType::OCLImage3d: Out << "PAUocl_image3d@@"; break;
1063 
1064   case BuiltinType::NullPtr: Out << "$$T"; break;
1065 
1066   case BuiltinType::Char16:
1067   case BuiltinType::Char32:
1068   case BuiltinType::Half: {
1069     DiagnosticsEngine &Diags = Context.getDiags();
1070     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1071       "cannot mangle this built-in %0 type yet");
1072     Diags.Report(Range.getBegin(), DiagID)
1073       << T->getName(Context.getASTContext().getPrintingPolicy())
1074       << Range;
1075     break;
1076   }
1077   }
1078 }
1079 
1080 // <type>          ::= <function-type>
1081 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T,
1082                                          SourceRange) {
1083   // Structors only appear in decls, so at this point we know it's not a
1084   // structor type.
1085   // FIXME: This may not be lambda-friendly.
1086   Out << "$$A6";
1087   mangleType(T, NULL, false, false);
1088 }
1089 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1090                                          SourceRange) {
1091   llvm_unreachable("Can't mangle K&R function prototypes");
1092 }
1093 
1094 void MicrosoftCXXNameMangler::mangleType(const FunctionType *T,
1095                                          const FunctionDecl *D,
1096                                          bool IsStructor,
1097                                          bool IsInstMethod) {
1098   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1099   //                     <return-type> <argument-list> <throw-spec>
1100   const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1101 
1102   // If this is a C++ instance method, mangle the CVR qualifiers for the
1103   // this pointer.
1104   if (IsInstMethod)
1105     mangleQualifiers(Qualifiers::fromCVRMask(Proto->getTypeQuals()), false);
1106 
1107   mangleCallingConvention(T, IsInstMethod);
1108 
1109   // <return-type> ::= <type>
1110   //               ::= @ # structors (they have no declared return type)
1111   if (IsStructor)
1112     Out << '@';
1113   else {
1114     QualType Result = Proto->getResultType();
1115     const Type* RT = Result.getTypePtr();
1116     if (!RT->isAnyPointerType() && !RT->isReferenceType()) {
1117       if (Result.hasQualifiers() || !RT->isBuiltinType())
1118         Out << '?';
1119       if (!RT->isBuiltinType() && !Result.hasQualifiers()) {
1120         // Lack of qualifiers for user types is mangled as 'A'.
1121         Out << 'A';
1122       }
1123     }
1124 
1125     // FIXME: Get the source range for the result type. Or, better yet,
1126     // implement the unimplemented stuff so we don't need accurate source
1127     // location info anymore :).
1128     mangleType(Result, SourceRange());
1129   }
1130 
1131   // <argument-list> ::= X # void
1132   //                 ::= <type>+ @
1133   //                 ::= <type>* Z # varargs
1134   if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
1135     Out << 'X';
1136   } else {
1137     if (D) {
1138       // If we got a decl, use the type-as-written to make sure arrays
1139       // get mangled right.  Note that we can't rely on the TSI
1140       // existing if (for example) the parameter was synthesized.
1141       for (FunctionDecl::param_const_iterator Parm = D->param_begin(),
1142              ParmEnd = D->param_end(); Parm != ParmEnd; ++Parm) {
1143         TypeSourceInfo *TSI = (*Parm)->getTypeSourceInfo();
1144         QualType Type = TSI ? TSI->getType() : (*Parm)->getType();
1145         mangleArgumentType(Type, (*Parm)->getSourceRange());
1146       }
1147     } else {
1148       // Happens for function pointer type arguments for example.
1149       for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1150            ArgEnd = Proto->arg_type_end();
1151            Arg != ArgEnd; ++Arg)
1152         mangleArgumentType(*Arg, SourceRange());
1153     }
1154     // <builtin-type>      ::= Z  # ellipsis
1155     if (Proto->isVariadic())
1156       Out << 'Z';
1157     else
1158       Out << '@';
1159   }
1160 
1161   mangleThrowSpecification(Proto);
1162 }
1163 
1164 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1165   // <function-class> ::= A # private: near
1166   //                  ::= B # private: far
1167   //                  ::= C # private: static near
1168   //                  ::= D # private: static far
1169   //                  ::= E # private: virtual near
1170   //                  ::= F # private: virtual far
1171   //                  ::= G # private: thunk near
1172   //                  ::= H # private: thunk far
1173   //                  ::= I # protected: near
1174   //                  ::= J # protected: far
1175   //                  ::= K # protected: static near
1176   //                  ::= L # protected: static far
1177   //                  ::= M # protected: virtual near
1178   //                  ::= N # protected: virtual far
1179   //                  ::= O # protected: thunk near
1180   //                  ::= P # protected: thunk far
1181   //                  ::= Q # public: near
1182   //                  ::= R # public: far
1183   //                  ::= S # public: static near
1184   //                  ::= T # public: static far
1185   //                  ::= U # public: virtual near
1186   //                  ::= V # public: virtual far
1187   //                  ::= W # public: thunk near
1188   //                  ::= X # public: thunk far
1189   //                  ::= Y # global near
1190   //                  ::= Z # global far
1191   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1192     switch (MD->getAccess()) {
1193       default:
1194       case AS_private:
1195         if (MD->isStatic())
1196           Out << 'C';
1197         else if (MD->isVirtual())
1198           Out << 'E';
1199         else
1200           Out << 'A';
1201         break;
1202       case AS_protected:
1203         if (MD->isStatic())
1204           Out << 'K';
1205         else if (MD->isVirtual())
1206           Out << 'M';
1207         else
1208           Out << 'I';
1209         break;
1210       case AS_public:
1211         if (MD->isStatic())
1212           Out << 'S';
1213         else if (MD->isVirtual())
1214           Out << 'U';
1215         else
1216           Out << 'Q';
1217     }
1218   } else
1219     Out << 'Y';
1220 }
1221 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T,
1222                                                       bool IsInstMethod) {
1223   // <calling-convention> ::= A # __cdecl
1224   //                      ::= B # __export __cdecl
1225   //                      ::= C # __pascal
1226   //                      ::= D # __export __pascal
1227   //                      ::= E # __thiscall
1228   //                      ::= F # __export __thiscall
1229   //                      ::= G # __stdcall
1230   //                      ::= H # __export __stdcall
1231   //                      ::= I # __fastcall
1232   //                      ::= J # __export __fastcall
1233   // The 'export' calling conventions are from a bygone era
1234   // (*cough*Win16*cough*) when functions were declared for export with
1235   // that keyword. (It didn't actually export them, it just made them so
1236   // that they could be in a DLL and somebody from another module could call
1237   // them.)
1238   CallingConv CC = T->getCallConv();
1239   if (CC == CC_Default) {
1240     if (IsInstMethod) {
1241       const FunctionProtoType *FPT =
1242         T->getCanonicalTypeUnqualified().castAs<FunctionProtoType>();
1243       bool isVariadic = FPT->isVariadic();
1244       CC = getASTContext().getDefaultCXXMethodCallConv(isVariadic);
1245     } else {
1246       CC = CC_C;
1247     }
1248   }
1249   switch (CC) {
1250     default:
1251       llvm_unreachable("Unsupported CC for mangling");
1252     case CC_Default:
1253     case CC_C: Out << 'A'; break;
1254     case CC_X86Pascal: Out << 'C'; break;
1255     case CC_X86ThisCall: Out << 'E'; break;
1256     case CC_X86StdCall: Out << 'G'; break;
1257     case CC_X86FastCall: Out << 'I'; break;
1258   }
1259 }
1260 void MicrosoftCXXNameMangler::mangleThrowSpecification(
1261                                                 const FunctionProtoType *FT) {
1262   // <throw-spec> ::= Z # throw(...) (default)
1263   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
1264   //              ::= <type>+
1265   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1266   // all actually mangled as 'Z'. (They're ignored because their associated
1267   // functionality isn't implemented, and probably never will be.)
1268   Out << 'Z';
1269 }
1270 
1271 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
1272                                          SourceRange Range) {
1273   // Probably should be mangled as a template instantiation; need to see what
1274   // VC does first.
1275   DiagnosticsEngine &Diags = Context.getDiags();
1276   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1277     "cannot mangle this unresolved dependent type yet");
1278   Diags.Report(Range.getBegin(), DiagID)
1279     << Range;
1280 }
1281 
1282 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1283 // <union-type>  ::= T <name>
1284 // <struct-type> ::= U <name>
1285 // <class-type>  ::= V <name>
1286 // <enum-type>   ::= W <size> <name>
1287 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, SourceRange) {
1288   mangleType(cast<TagType>(T));
1289 }
1290 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, SourceRange) {
1291   mangleType(cast<TagType>(T));
1292 }
1293 void MicrosoftCXXNameMangler::mangleType(const TagType *T) {
1294   switch (T->getDecl()->getTagKind()) {
1295     case TTK_Union:
1296       Out << 'T';
1297       break;
1298     case TTK_Struct:
1299     case TTK_Interface:
1300       Out << 'U';
1301       break;
1302     case TTK_Class:
1303       Out << 'V';
1304       break;
1305     case TTK_Enum:
1306       Out << 'W';
1307       Out << getASTContext().getTypeSizeInChars(
1308                 cast<EnumDecl>(T->getDecl())->getIntegerType()).getQuantity();
1309       break;
1310   }
1311   mangleName(T->getDecl());
1312 }
1313 
1314 // <type>       ::= <array-type>
1315 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1316 //                  [Y <dimension-count> <dimension>+]
1317 //                  <element-type> # as global
1318 //              ::= Q <cvr-qualifiers> [Y <dimension-count> <dimension>+]
1319 //                  <element-type> # as param
1320 // It's supposed to be the other way around, but for some strange reason, it
1321 // isn't. Today this behavior is retained for the sole purpose of backwards
1322 // compatibility.
1323 void MicrosoftCXXNameMangler::mangleType(const ArrayType *T, bool IsGlobal) {
1324   // This isn't a recursive mangling, so now we have to do it all in this
1325   // one call.
1326   if (IsGlobal) {
1327     manglePointerQualifiers(T->getElementType().getQualifiers());
1328   } else {
1329     Out << 'Q';
1330   }
1331   mangleExtraDimensions(T->getElementType());
1332 }
1333 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T,
1334                                          SourceRange) {
1335   mangleType(cast<ArrayType>(T), false);
1336 }
1337 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T,
1338                                          SourceRange) {
1339   mangleType(cast<ArrayType>(T), false);
1340 }
1341 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
1342                                          SourceRange) {
1343   mangleType(cast<ArrayType>(T), false);
1344 }
1345 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
1346                                          SourceRange) {
1347   mangleType(cast<ArrayType>(T), false);
1348 }
1349 void MicrosoftCXXNameMangler::mangleExtraDimensions(QualType ElementTy) {
1350   SmallVector<llvm::APInt, 3> Dimensions;
1351   for (;;) {
1352     if (const ConstantArrayType *CAT =
1353           getASTContext().getAsConstantArrayType(ElementTy)) {
1354       Dimensions.push_back(CAT->getSize());
1355       ElementTy = CAT->getElementType();
1356     } else if (ElementTy->isVariableArrayType()) {
1357       const VariableArrayType *VAT =
1358         getASTContext().getAsVariableArrayType(ElementTy);
1359       DiagnosticsEngine &Diags = Context.getDiags();
1360       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1361         "cannot mangle this variable-length array yet");
1362       Diags.Report(VAT->getSizeExpr()->getExprLoc(), DiagID)
1363         << VAT->getBracketsRange();
1364       return;
1365     } else if (ElementTy->isDependentSizedArrayType()) {
1366       // The dependent expression has to be folded into a constant (TODO).
1367       const DependentSizedArrayType *DSAT =
1368         getASTContext().getAsDependentSizedArrayType(ElementTy);
1369       DiagnosticsEngine &Diags = Context.getDiags();
1370       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1371         "cannot mangle this dependent-length array yet");
1372       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
1373         << DSAT->getBracketsRange();
1374       return;
1375     } else if (ElementTy->isIncompleteArrayType()) continue;
1376     else break;
1377   }
1378   mangleQualifiers(ElementTy.getQualifiers(), false);
1379   // If there are any additional dimensions, mangle them now.
1380   if (Dimensions.size() > 0) {
1381     Out << 'Y';
1382     // <dimension-count> ::= <number> # number of extra dimensions
1383     mangleNumber(Dimensions.size());
1384     for (unsigned Dim = 0; Dim < Dimensions.size(); ++Dim) {
1385       mangleNumber(Dimensions[Dim].getLimitedValue());
1386     }
1387   }
1388   mangleType(ElementTy.getLocalUnqualifiedType(), SourceRange());
1389 }
1390 
1391 // <type>                   ::= <pointer-to-member-type>
1392 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1393 //                                                          <class name> <type>
1394 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
1395                                          SourceRange Range) {
1396   QualType PointeeType = T->getPointeeType();
1397   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
1398     Out << '8';
1399     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1400     mangleType(FPT, NULL, false, true);
1401   } else {
1402     mangleQualifiers(PointeeType.getQualifiers(), true);
1403     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1404     mangleType(PointeeType.getLocalUnqualifiedType(), Range);
1405   }
1406 }
1407 
1408 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
1409                                          SourceRange Range) {
1410   DiagnosticsEngine &Diags = Context.getDiags();
1411   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1412     "cannot mangle this template type parameter type yet");
1413   Diags.Report(Range.getBegin(), DiagID)
1414     << Range;
1415 }
1416 
1417 void MicrosoftCXXNameMangler::mangleType(
1418                                        const SubstTemplateTypeParmPackType *T,
1419                                        SourceRange Range) {
1420   DiagnosticsEngine &Diags = Context.getDiags();
1421   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1422     "cannot mangle this substituted parameter pack yet");
1423   Diags.Report(Range.getBegin(), DiagID)
1424     << Range;
1425 }
1426 
1427 // <type> ::= <pointer-type>
1428 // <pointer-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
1429 void MicrosoftCXXNameMangler::mangleType(const PointerType *T,
1430                                          SourceRange Range) {
1431   QualType PointeeTy = T->getPointeeType();
1432   if (PointeeTy->isArrayType()) {
1433     // Pointers to arrays are mangled like arrays.
1434     mangleExtraDimensions(PointeeTy);
1435   } else if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
1436     // Function pointers are special.
1437     Out << '6';
1438     mangleType(FT, NULL, false, false);
1439   } else {
1440     mangleQualifiers(PointeeTy.getQualifiers(), false);
1441     mangleType(PointeeTy, Range, false);
1442   }
1443 }
1444 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
1445                                          SourceRange Range) {
1446   // Object pointers never have qualifiers.
1447   Out << 'A';
1448   mangleType(T->getPointeeType(), Range);
1449 }
1450 
1451 // <type> ::= <reference-type>
1452 // <reference-type> ::= A <cvr-qualifiers> <type>
1453 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
1454                                          SourceRange Range) {
1455   Out << 'A';
1456   QualType PointeeTy = T->getPointeeType();
1457   if (!PointeeTy.hasQualifiers())
1458     // Lack of qualifiers is mangled as 'A'.
1459     Out << 'A';
1460   mangleType(PointeeTy, Range);
1461 }
1462 
1463 // <type> ::= <r-value-reference-type>
1464 // <r-value-reference-type> ::= $$Q <cvr-qualifiers> <type>
1465 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
1466                                          SourceRange Range) {
1467   Out << "$$Q";
1468   QualType PointeeTy = T->getPointeeType();
1469   if (!PointeeTy.hasQualifiers())
1470     // Lack of qualifiers is mangled as 'A'.
1471     Out << 'A';
1472   mangleType(PointeeTy, Range);
1473 }
1474 
1475 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T,
1476                                          SourceRange Range) {
1477   DiagnosticsEngine &Diags = Context.getDiags();
1478   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1479     "cannot mangle this complex number type yet");
1480   Diags.Report(Range.getBegin(), DiagID)
1481     << Range;
1482 }
1483 
1484 void MicrosoftCXXNameMangler::mangleType(const VectorType *T,
1485                                          SourceRange Range) {
1486   DiagnosticsEngine &Diags = Context.getDiags();
1487   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1488     "cannot mangle this vector type yet");
1489   Diags.Report(Range.getBegin(), DiagID)
1490     << Range;
1491 }
1492 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
1493                                          SourceRange Range) {
1494   DiagnosticsEngine &Diags = Context.getDiags();
1495   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1496     "cannot mangle this extended vector type yet");
1497   Diags.Report(Range.getBegin(), DiagID)
1498     << Range;
1499 }
1500 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
1501                                          SourceRange Range) {
1502   DiagnosticsEngine &Diags = Context.getDiags();
1503   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1504     "cannot mangle this dependent-sized extended vector type yet");
1505   Diags.Report(Range.getBegin(), DiagID)
1506     << Range;
1507 }
1508 
1509 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T,
1510                                          SourceRange) {
1511   // ObjC interfaces have structs underlying them.
1512   Out << 'U';
1513   mangleName(T->getDecl());
1514 }
1515 
1516 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
1517                                          SourceRange Range) {
1518   // We don't allow overloading by different protocol qualification,
1519   // so mangling them isn't necessary.
1520   mangleType(T->getBaseType(), Range);
1521 }
1522 
1523 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
1524                                          SourceRange Range) {
1525   Out << "_E";
1526 
1527   QualType pointee = T->getPointeeType();
1528   mangleType(pointee->castAs<FunctionProtoType>(), NULL, false, false);
1529 }
1530 
1531 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *T,
1532                                          SourceRange Range) {
1533   DiagnosticsEngine &Diags = Context.getDiags();
1534   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1535     "cannot mangle this injected class name type yet");
1536   Diags.Report(Range.getBegin(), DiagID)
1537     << Range;
1538 }
1539 
1540 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
1541                                          SourceRange Range) {
1542   DiagnosticsEngine &Diags = Context.getDiags();
1543   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1544     "cannot mangle this template specialization type yet");
1545   Diags.Report(Range.getBegin(), DiagID)
1546     << Range;
1547 }
1548 
1549 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T,
1550                                          SourceRange Range) {
1551   DiagnosticsEngine &Diags = Context.getDiags();
1552   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1553     "cannot mangle this dependent name type yet");
1554   Diags.Report(Range.getBegin(), DiagID)
1555     << Range;
1556 }
1557 
1558 void MicrosoftCXXNameMangler::mangleType(
1559                                  const DependentTemplateSpecializationType *T,
1560                                  SourceRange Range) {
1561   DiagnosticsEngine &Diags = Context.getDiags();
1562   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1563     "cannot mangle this dependent template specialization type yet");
1564   Diags.Report(Range.getBegin(), DiagID)
1565     << Range;
1566 }
1567 
1568 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T,
1569                                          SourceRange Range) {
1570   DiagnosticsEngine &Diags = Context.getDiags();
1571   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1572     "cannot mangle this pack expansion yet");
1573   Diags.Report(Range.getBegin(), DiagID)
1574     << Range;
1575 }
1576 
1577 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T,
1578                                          SourceRange Range) {
1579   DiagnosticsEngine &Diags = Context.getDiags();
1580   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1581     "cannot mangle this typeof(type) yet");
1582   Diags.Report(Range.getBegin(), DiagID)
1583     << Range;
1584 }
1585 
1586 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T,
1587                                          SourceRange Range) {
1588   DiagnosticsEngine &Diags = Context.getDiags();
1589   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1590     "cannot mangle this typeof(expression) yet");
1591   Diags.Report(Range.getBegin(), DiagID)
1592     << Range;
1593 }
1594 
1595 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T,
1596                                          SourceRange Range) {
1597   DiagnosticsEngine &Diags = Context.getDiags();
1598   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1599     "cannot mangle this decltype() yet");
1600   Diags.Report(Range.getBegin(), DiagID)
1601     << Range;
1602 }
1603 
1604 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
1605                                          SourceRange Range) {
1606   DiagnosticsEngine &Diags = Context.getDiags();
1607   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1608     "cannot mangle this unary transform type yet");
1609   Diags.Report(Range.getBegin(), DiagID)
1610     << Range;
1611 }
1612 
1613 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, SourceRange Range) {
1614   DiagnosticsEngine &Diags = Context.getDiags();
1615   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1616     "cannot mangle this 'auto' type yet");
1617   Diags.Report(Range.getBegin(), DiagID)
1618     << Range;
1619 }
1620 
1621 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T,
1622                                          SourceRange Range) {
1623   DiagnosticsEngine &Diags = Context.getDiags();
1624   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1625     "cannot mangle this C11 atomic type yet");
1626   Diags.Report(Range.getBegin(), DiagID)
1627     << Range;
1628 }
1629 
1630 void MicrosoftMangleContext::mangleName(const NamedDecl *D,
1631                                         raw_ostream &Out) {
1632   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
1633          "Invalid mangleName() call, argument is not a variable or function!");
1634   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
1635          "Invalid mangleName() call on 'structor decl!");
1636 
1637   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
1638                                  getASTContext().getSourceManager(),
1639                                  "Mangling declaration");
1640 
1641   MicrosoftCXXNameMangler Mangler(*this, Out);
1642   return Mangler.mangle(D);
1643 }
1644 void MicrosoftMangleContext::mangleThunk(const CXXMethodDecl *MD,
1645                                          const ThunkInfo &Thunk,
1646                                          raw_ostream &) {
1647   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1648     "cannot mangle thunk for this method yet");
1649   getDiags().Report(MD->getLocation(), DiagID);
1650 }
1651 void MicrosoftMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
1652                                                 CXXDtorType Type,
1653                                                 const ThisAdjustment &,
1654                                                 raw_ostream &) {
1655   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1656     "cannot mangle thunk for this destructor yet");
1657   getDiags().Report(DD->getLocation(), DiagID);
1658 }
1659 void MicrosoftMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
1660                                              raw_ostream &Out) {
1661   // <mangled-name> ::= ? <operator-name> <class-name> <storage-class>
1662   //                      <cvr-qualifiers> [<name>] @
1663   // <operator-name> ::= _7 # vftable
1664   //                 ::= _8 # vbtable
1665   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
1666   // is always '6' for vftables and '7' for vbtables. (The difference is
1667   // beyond me.)
1668   // TODO: vbtables.
1669   MicrosoftCXXNameMangler Mangler(*this, Out);
1670   Mangler.getStream() << "\01??_7";
1671   Mangler.mangleName(RD);
1672   Mangler.getStream() << "6B";
1673   // TODO: If the class has more than one vtable, mangle in the class it came
1674   // from.
1675   Mangler.getStream() << '@';
1676 }
1677 void MicrosoftMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
1678                                           raw_ostream &) {
1679   llvm_unreachable("The MS C++ ABI does not have virtual table tables!");
1680 }
1681 void MicrosoftMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
1682                                                  int64_t Offset,
1683                                                  const CXXRecordDecl *Type,
1684                                                  raw_ostream &) {
1685   llvm_unreachable("The MS C++ ABI does not have constructor vtables!");
1686 }
1687 void MicrosoftMangleContext::mangleCXXRTTI(QualType T,
1688                                            raw_ostream &) {
1689   // FIXME: Give a location...
1690   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1691     "cannot mangle RTTI descriptors for type %0 yet");
1692   getDiags().Report(DiagID)
1693     << T.getBaseTypeIdentifier();
1694 }
1695 void MicrosoftMangleContext::mangleCXXRTTIName(QualType T,
1696                                                raw_ostream &) {
1697   // FIXME: Give a location...
1698   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1699     "cannot mangle the name of type %0 into RTTI descriptors yet");
1700   getDiags().Report(DiagID)
1701     << T.getBaseTypeIdentifier();
1702 }
1703 void MicrosoftMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
1704                                            CXXCtorType Type,
1705                                            raw_ostream & Out) {
1706   MicrosoftCXXNameMangler mangler(*this, Out);
1707   mangler.mangle(D);
1708 }
1709 void MicrosoftMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
1710                                            CXXDtorType Type,
1711                                            raw_ostream & Out) {
1712   MicrosoftCXXNameMangler mangler(*this, Out);
1713   mangler.mangle(D);
1714 }
1715 void MicrosoftMangleContext::mangleReferenceTemporary(const clang::VarDecl *VD,
1716                                                       raw_ostream &) {
1717   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1718     "cannot mangle this reference temporary yet");
1719   getDiags().Report(VD->getLocation(), DiagID);
1720 }
1721 
1722 MangleContext *clang::createMicrosoftMangleContext(ASTContext &Context,
1723                                                    DiagnosticsEngine &Diags) {
1724   return new MicrosoftMangleContext(Context, Diags);
1725 }
1726