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