]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/AST/MicrosoftMangle.cpp
MFC r244628:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / lib / AST / MicrosoftMangle.cpp
1 //===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/AST/Mangle.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/CharUnits.h"
17 #include "clang/AST/Decl.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/ExprCXX.h"
22 #include "clang/Basic/ABI.h"
23 #include "clang/Basic/DiagnosticOptions.h"
24
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(QualType T, const llvm::APSInt &Number);
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   BackRefMap TemplateContext;
746   NameBackReferences.swap(TemplateContext);
747
748   mangleUnscopedTemplateName(TD);
749   mangleTemplateArgs(TemplateArgs);
750
751   NameBackReferences.swap(TemplateContext);
752 }
753
754 void
755 MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
756   // <unscoped-template-name> ::= ?$ <unqualified-name>
757   Out << "?$";
758   mangleUnqualifiedName(TD);
759 }
760
761 void
762 MicrosoftCXXNameMangler::mangleIntegerLiteral(QualType T,
763                                               const llvm::APSInt &Value) {
764   // <integer-literal> ::= $0 <number>
765   Out << "$0";
766   // Make sure booleans are encoded as 0/1.
767   if (T->isBooleanType())
768     Out << (Value.getBoolValue() ? "0" : "A@");
769   else
770     mangleNumber(Value);
771 }
772
773 void
774 MicrosoftCXXNameMangler::mangleExpression(const Expr *E) {
775   // See if this is a constant expression.
776   llvm::APSInt Value;
777   if (E->isIntegerConstantExpr(Value, Context.getASTContext())) {
778     mangleIntegerLiteral(E->getType(), Value);
779     return;
780   }
781
782   // As bad as this diagnostic is, it's better than crashing.
783   DiagnosticsEngine &Diags = Context.getDiags();
784   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
785                                    "cannot yet mangle expression type %0");
786   Diags.Report(E->getExprLoc(), DiagID)
787     << E->getStmtClassName() << E->getSourceRange();
788 }
789
790 void
791 MicrosoftCXXNameMangler::mangleTemplateArgs(
792                      const SmallVectorImpl<TemplateArgumentLoc> &TemplateArgs) {
793   // <template-args> ::= {<type> | <integer-literal>}+ @
794   unsigned NumTemplateArgs = TemplateArgs.size();
795   for (unsigned i = 0; i < NumTemplateArgs; ++i) {
796     const TemplateArgumentLoc &TAL = TemplateArgs[i];
797     const TemplateArgument &TA = TAL.getArgument();
798     switch (TA.getKind()) {
799     case TemplateArgument::Null:
800       llvm_unreachable("Can't mangle null template arguments!");
801     case TemplateArgument::Type:
802       mangleType(TA.getAsType(), TAL.getSourceRange());
803       break;
804     case TemplateArgument::Integral:
805       mangleIntegerLiteral(TA.getIntegralType(), TA.getAsIntegral());
806       break;
807     case TemplateArgument::Expression:
808       mangleExpression(TA.getAsExpr());
809       break;
810     case TemplateArgument::Template:
811     case TemplateArgument::TemplateExpansion:
812     case TemplateArgument::Declaration:
813     case TemplateArgument::NullPtr:
814     case TemplateArgument::Pack: {
815       // Issue a diagnostic.
816       DiagnosticsEngine &Diags = Context.getDiags();
817       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
818         "cannot mangle this %select{ERROR|ERROR|pointer/reference|nullptr|"
819         "integral|template|template pack expansion|ERROR|parameter pack}0 "
820         "template argument yet");
821       Diags.Report(TAL.getLocation(), DiagID)
822         << TA.getKind()
823         << TAL.getSourceRange();
824     }
825     }
826   }
827   Out << '@';
828 }
829
830 void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
831                                                bool IsMember) {
832   // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
833   // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
834   // 'I' means __restrict (32/64-bit).
835   // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
836   // keyword!
837   // <base-cvr-qualifiers> ::= A  # near
838   //                       ::= B  # near const
839   //                       ::= C  # near volatile
840   //                       ::= D  # near const volatile
841   //                       ::= E  # far (16-bit)
842   //                       ::= F  # far const (16-bit)
843   //                       ::= G  # far volatile (16-bit)
844   //                       ::= H  # far const volatile (16-bit)
845   //                       ::= I  # huge (16-bit)
846   //                       ::= J  # huge const (16-bit)
847   //                       ::= K  # huge volatile (16-bit)
848   //                       ::= L  # huge const volatile (16-bit)
849   //                       ::= M <basis> # based
850   //                       ::= N <basis> # based const
851   //                       ::= O <basis> # based volatile
852   //                       ::= P <basis> # based const volatile
853   //                       ::= Q  # near member
854   //                       ::= R  # near const member
855   //                       ::= S  # near volatile member
856   //                       ::= T  # near const volatile member
857   //                       ::= U  # far member (16-bit)
858   //                       ::= V  # far const member (16-bit)
859   //                       ::= W  # far volatile member (16-bit)
860   //                       ::= X  # far const volatile member (16-bit)
861   //                       ::= Y  # huge member (16-bit)
862   //                       ::= Z  # huge const member (16-bit)
863   //                       ::= 0  # huge volatile member (16-bit)
864   //                       ::= 1  # huge const volatile member (16-bit)
865   //                       ::= 2 <basis> # based member
866   //                       ::= 3 <basis> # based const member
867   //                       ::= 4 <basis> # based volatile member
868   //                       ::= 5 <basis> # based const volatile member
869   //                       ::= 6  # near function (pointers only)
870   //                       ::= 7  # far function (pointers only)
871   //                       ::= 8  # near method (pointers only)
872   //                       ::= 9  # far method (pointers only)
873   //                       ::= _A <basis> # based function (pointers only)
874   //                       ::= _B <basis> # based function (far?) (pointers only)
875   //                       ::= _C <basis> # based method (pointers only)
876   //                       ::= _D <basis> # based method (far?) (pointers only)
877   //                       ::= _E # block (Clang)
878   // <basis> ::= 0 # __based(void)
879   //         ::= 1 # __based(segment)?
880   //         ::= 2 <name> # __based(name)
881   //         ::= 3 # ?
882   //         ::= 4 # ?
883   //         ::= 5 # not really based
884   bool HasConst = Quals.hasConst(),
885        HasVolatile = Quals.hasVolatile();
886   if (!IsMember) {
887     if (HasConst && HasVolatile) {
888       Out << 'D';
889     } else if (HasVolatile) {
890       Out << 'C';
891     } else if (HasConst) {
892       Out << 'B';
893     } else {
894       Out << 'A';
895     }
896   } else {
897     if (HasConst && HasVolatile) {
898       Out << 'T';
899     } else if (HasVolatile) {
900       Out << 'S';
901     } else if (HasConst) {
902       Out << 'R';
903     } else {
904       Out << 'Q';
905     }
906   }
907
908   // FIXME: For now, just drop all extension qualifiers on the floor.
909 }
910
911 void MicrosoftCXXNameMangler::manglePointerQualifiers(Qualifiers Quals) {
912   // <pointer-cvr-qualifiers> ::= P  # no qualifiers
913   //                          ::= Q  # const
914   //                          ::= R  # volatile
915   //                          ::= S  # const volatile
916   bool HasConst = Quals.hasConst(),
917        HasVolatile = Quals.hasVolatile();
918   if (HasConst && HasVolatile) {
919     Out << 'S';
920   } else if (HasVolatile) {
921     Out << 'R';
922   } else if (HasConst) {
923     Out << 'Q';
924   } else {
925     Out << 'P';
926   }
927 }
928
929 void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
930                                                  SourceRange Range) {
931   void *TypePtr = getASTContext().getCanonicalType(T).getAsOpaquePtr();
932   ArgBackRefMap::iterator Found = TypeBackReferences.find(TypePtr);
933
934   if (Found == TypeBackReferences.end()) {
935     size_t OutSizeBefore = Out.GetNumBytesInBuffer();
936
937     mangleType(T, Range, false);
938
939     // See if it's worth creating a back reference.
940     // Only types longer than 1 character are considered
941     // and only 10 back references slots are available:
942     bool LongerThanOneChar = (Out.GetNumBytesInBuffer() - OutSizeBefore > 1);
943     if (LongerThanOneChar && TypeBackReferences.size() < 10) {
944       size_t Size = TypeBackReferences.size();
945       TypeBackReferences[TypePtr] = Size;
946     }
947   } else {
948     Out << Found->second;
949   }
950 }
951
952 void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
953                                          bool MangleQualifiers) {
954   // Only operate on the canonical type!
955   T = getASTContext().getCanonicalType(T);
956
957   Qualifiers Quals = T.getLocalQualifiers();
958   // We have to mangle these now, while we still have enough information.
959   if (T->isAnyPointerType() || T->isMemberPointerType() ||
960       T->isBlockPointerType()) {
961     manglePointerQualifiers(Quals);
962   } else if (Quals && MangleQualifiers) {
963     mangleQualifiers(Quals, false);
964   }
965
966   SplitQualType split = T.split();
967   const Type *ty = split.Ty;
968
969   // If we're mangling a qualified array type, push the qualifiers to
970   // the element type.
971   if (split.Quals && isa<ArrayType>(T)) {
972     ty = Context.getASTContext().getAsArrayType(T);
973   }
974
975   switch (ty->getTypeClass()) {
976 #define ABSTRACT_TYPE(CLASS, PARENT)
977 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
978   case Type::CLASS: \
979     llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
980     return;
981 #define TYPE(CLASS, PARENT) \
982   case Type::CLASS: \
983     mangleType(cast<CLASS##Type>(ty), Range); \
984     break;
985 #include "clang/AST/TypeNodes.def"
986 #undef ABSTRACT_TYPE
987 #undef NON_CANONICAL_TYPE
988 #undef TYPE
989   }
990 }
991
992 void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T,
993                                          SourceRange Range) {
994   //  <type>         ::= <builtin-type>
995   //  <builtin-type> ::= X  # void
996   //                 ::= C  # signed char
997   //                 ::= D  # char
998   //                 ::= E  # unsigned char
999   //                 ::= F  # short
1000   //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
1001   //                 ::= H  # int
1002   //                 ::= I  # unsigned int
1003   //                 ::= J  # long
1004   //                 ::= K  # unsigned long
1005   //                     L  # <none>
1006   //                 ::= M  # float
1007   //                 ::= N  # double
1008   //                 ::= O  # long double (__float80 is mangled differently)
1009   //                 ::= _J # long long, __int64
1010   //                 ::= _K # unsigned long long, __int64
1011   //                 ::= _L # __int128
1012   //                 ::= _M # unsigned __int128
1013   //                 ::= _N # bool
1014   //                     _O # <array in parameter>
1015   //                 ::= _T # __float80 (Intel)
1016   //                 ::= _W # wchar_t
1017   //                 ::= _Z # __float80 (Digital Mars)
1018   switch (T->getKind()) {
1019   case BuiltinType::Void: Out << 'X'; break;
1020   case BuiltinType::SChar: Out << 'C'; break;
1021   case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
1022   case BuiltinType::UChar: Out << 'E'; break;
1023   case BuiltinType::Short: Out << 'F'; break;
1024   case BuiltinType::UShort: Out << 'G'; break;
1025   case BuiltinType::Int: Out << 'H'; break;
1026   case BuiltinType::UInt: Out << 'I'; break;
1027   case BuiltinType::Long: Out << 'J'; break;
1028   case BuiltinType::ULong: Out << 'K'; break;
1029   case BuiltinType::Float: Out << 'M'; break;
1030   case BuiltinType::Double: Out << 'N'; break;
1031   // TODO: Determine size and mangle accordingly
1032   case BuiltinType::LongDouble: Out << 'O'; break;
1033   case BuiltinType::LongLong: Out << "_J"; break;
1034   case BuiltinType::ULongLong: Out << "_K"; break;
1035   case BuiltinType::Int128: Out << "_L"; break;
1036   case BuiltinType::UInt128: Out << "_M"; break;
1037   case BuiltinType::Bool: Out << "_N"; break;
1038   case BuiltinType::WChar_S:
1039   case BuiltinType::WChar_U: Out << "_W"; break;
1040
1041 #define BUILTIN_TYPE(Id, SingletonId)
1042 #define PLACEHOLDER_TYPE(Id, SingletonId) \
1043   case BuiltinType::Id:
1044 #include "clang/AST/BuiltinTypes.def"
1045   case BuiltinType::Dependent:
1046     llvm_unreachable("placeholder types shouldn't get to name mangling");
1047
1048   case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
1049   case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
1050   case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
1051  
1052   case BuiltinType::NullPtr: Out << "$$T"; break;
1053
1054   case BuiltinType::Char16:
1055   case BuiltinType::Char32:
1056   case BuiltinType::Half: {
1057     DiagnosticsEngine &Diags = Context.getDiags();
1058     unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1059       "cannot mangle this built-in %0 type yet");
1060     Diags.Report(Range.getBegin(), DiagID)
1061       << T->getName(Context.getASTContext().getPrintingPolicy())
1062       << Range;
1063     break;
1064   }
1065   }
1066 }
1067
1068 // <type>          ::= <function-type>
1069 void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T,
1070                                          SourceRange) {
1071   // Structors only appear in decls, so at this point we know it's not a
1072   // structor type.
1073   // FIXME: This may not be lambda-friendly.
1074   Out << "$$A6";
1075   mangleType(T, NULL, false, false);
1076 }
1077 void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
1078                                          SourceRange) {
1079   llvm_unreachable("Can't mangle K&R function prototypes");
1080 }
1081
1082 void MicrosoftCXXNameMangler::mangleType(const FunctionType *T,
1083                                          const FunctionDecl *D,
1084                                          bool IsStructor,
1085                                          bool IsInstMethod) {
1086   // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
1087   //                     <return-type> <argument-list> <throw-spec>
1088   const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
1089
1090   // If this is a C++ instance method, mangle the CVR qualifiers for the
1091   // this pointer.
1092   if (IsInstMethod)
1093     mangleQualifiers(Qualifiers::fromCVRMask(Proto->getTypeQuals()), false);
1094
1095   mangleCallingConvention(T, IsInstMethod);
1096
1097   // <return-type> ::= <type>
1098   //               ::= @ # structors (they have no declared return type)
1099   if (IsStructor)
1100     Out << '@';
1101   else {
1102     QualType Result = Proto->getResultType();
1103     const Type* RT = Result.getTypePtr();
1104     if (!RT->isAnyPointerType() && !RT->isReferenceType()) {
1105       if (Result.hasQualifiers() || !RT->isBuiltinType())
1106         Out << '?';
1107       if (!RT->isBuiltinType() && !Result.hasQualifiers()) {
1108         // Lack of qualifiers for user types is mangled as 'A'.
1109         Out << 'A';
1110       }
1111     }
1112
1113     // FIXME: Get the source range for the result type. Or, better yet,
1114     // implement the unimplemented stuff so we don't need accurate source
1115     // location info anymore :).
1116     mangleType(Result, SourceRange());
1117   }
1118
1119   // <argument-list> ::= X # void
1120   //                 ::= <type>+ @
1121   //                 ::= <type>* Z # varargs
1122   if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
1123     Out << 'X';
1124   } else {
1125     if (D) {
1126       // If we got a decl, use the type-as-written to make sure arrays
1127       // get mangled right.  Note that we can't rely on the TSI
1128       // existing if (for example) the parameter was synthesized.
1129       for (FunctionDecl::param_const_iterator Parm = D->param_begin(),
1130              ParmEnd = D->param_end(); Parm != ParmEnd; ++Parm) {
1131         TypeSourceInfo *TSI = (*Parm)->getTypeSourceInfo();
1132         QualType Type = TSI ? TSI->getType() : (*Parm)->getType();
1133         mangleArgumentType(Type, (*Parm)->getSourceRange());
1134       }
1135     } else {
1136       // Happens for function pointer type arguments for example.
1137       for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
1138            ArgEnd = Proto->arg_type_end();
1139            Arg != ArgEnd; ++Arg)
1140         mangleArgumentType(*Arg, SourceRange());
1141     }
1142     // <builtin-type>      ::= Z  # ellipsis
1143     if (Proto->isVariadic())
1144       Out << 'Z';
1145     else
1146       Out << '@';
1147   }
1148
1149   mangleThrowSpecification(Proto);
1150 }
1151
1152 void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
1153   // <function-class> ::= A # private: near
1154   //                  ::= B # private: far
1155   //                  ::= C # private: static near
1156   //                  ::= D # private: static far
1157   //                  ::= E # private: virtual near
1158   //                  ::= F # private: virtual far
1159   //                  ::= G # private: thunk near
1160   //                  ::= H # private: thunk far
1161   //                  ::= I # protected: near
1162   //                  ::= J # protected: far
1163   //                  ::= K # protected: static near
1164   //                  ::= L # protected: static far
1165   //                  ::= M # protected: virtual near
1166   //                  ::= N # protected: virtual far
1167   //                  ::= O # protected: thunk near
1168   //                  ::= P # protected: thunk far
1169   //                  ::= Q # public: near
1170   //                  ::= R # public: far
1171   //                  ::= S # public: static near
1172   //                  ::= T # public: static far
1173   //                  ::= U # public: virtual near
1174   //                  ::= V # public: virtual far
1175   //                  ::= W # public: thunk near
1176   //                  ::= X # public: thunk far
1177   //                  ::= Y # global near
1178   //                  ::= Z # global far
1179   if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
1180     switch (MD->getAccess()) {
1181       default:
1182       case AS_private:
1183         if (MD->isStatic())
1184           Out << 'C';
1185         else if (MD->isVirtual())
1186           Out << 'E';
1187         else
1188           Out << 'A';
1189         break;
1190       case AS_protected:
1191         if (MD->isStatic())
1192           Out << 'K';
1193         else if (MD->isVirtual())
1194           Out << 'M';
1195         else
1196           Out << 'I';
1197         break;
1198       case AS_public:
1199         if (MD->isStatic())
1200           Out << 'S';
1201         else if (MD->isVirtual())
1202           Out << 'U';
1203         else
1204           Out << 'Q';
1205     }
1206   } else
1207     Out << 'Y';
1208 }
1209 void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T,
1210                                                       bool IsInstMethod) {
1211   // <calling-convention> ::= A # __cdecl
1212   //                      ::= B # __export __cdecl
1213   //                      ::= C # __pascal
1214   //                      ::= D # __export __pascal
1215   //                      ::= E # __thiscall
1216   //                      ::= F # __export __thiscall
1217   //                      ::= G # __stdcall
1218   //                      ::= H # __export __stdcall
1219   //                      ::= I # __fastcall
1220   //                      ::= J # __export __fastcall
1221   // The 'export' calling conventions are from a bygone era
1222   // (*cough*Win16*cough*) when functions were declared for export with
1223   // that keyword. (It didn't actually export them, it just made them so
1224   // that they could be in a DLL and somebody from another module could call
1225   // them.)
1226   CallingConv CC = T->getCallConv();
1227   if (CC == CC_Default) {
1228     if (IsInstMethod) {
1229       const FunctionProtoType *FPT =
1230         T->getCanonicalTypeUnqualified().castAs<FunctionProtoType>();
1231       bool isVariadic = FPT->isVariadic();
1232       CC = getASTContext().getDefaultCXXMethodCallConv(isVariadic);
1233     } else {
1234       CC = CC_C;
1235     }
1236   }
1237   switch (CC) {
1238     default:
1239       llvm_unreachable("Unsupported CC for mangling");
1240     case CC_Default:
1241     case CC_C: Out << 'A'; break;
1242     case CC_X86Pascal: Out << 'C'; break;
1243     case CC_X86ThisCall: Out << 'E'; break;
1244     case CC_X86StdCall: Out << 'G'; break;
1245     case CC_X86FastCall: Out << 'I'; break;
1246   }
1247 }
1248 void MicrosoftCXXNameMangler::mangleThrowSpecification(
1249                                                 const FunctionProtoType *FT) {
1250   // <throw-spec> ::= Z # throw(...) (default)
1251   //              ::= @ # throw() or __declspec/__attribute__((nothrow))
1252   //              ::= <type>+
1253   // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1254   // all actually mangled as 'Z'. (They're ignored because their associated
1255   // functionality isn't implemented, and probably never will be.)
1256   Out << 'Z';
1257 }
1258
1259 void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
1260                                          SourceRange Range) {
1261   // Probably should be mangled as a template instantiation; need to see what
1262   // VC does first.
1263   DiagnosticsEngine &Diags = Context.getDiags();
1264   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1265     "cannot mangle this unresolved dependent type yet");
1266   Diags.Report(Range.getBegin(), DiagID)
1267     << Range;
1268 }
1269
1270 // <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1271 // <union-type>  ::= T <name>
1272 // <struct-type> ::= U <name>
1273 // <class-type>  ::= V <name>
1274 // <enum-type>   ::= W <size> <name>
1275 void MicrosoftCXXNameMangler::mangleType(const EnumType *T, SourceRange) {
1276   mangleType(cast<TagType>(T));
1277 }
1278 void MicrosoftCXXNameMangler::mangleType(const RecordType *T, SourceRange) {
1279   mangleType(cast<TagType>(T));
1280 }
1281 void MicrosoftCXXNameMangler::mangleType(const TagType *T) {
1282   switch (T->getDecl()->getTagKind()) {
1283     case TTK_Union:
1284       Out << 'T';
1285       break;
1286     case TTK_Struct:
1287     case TTK_Interface:
1288       Out << 'U';
1289       break;
1290     case TTK_Class:
1291       Out << 'V';
1292       break;
1293     case TTK_Enum:
1294       Out << 'W';
1295       Out << getASTContext().getTypeSizeInChars(
1296                 cast<EnumDecl>(T->getDecl())->getIntegerType()).getQuantity();
1297       break;
1298   }
1299   mangleName(T->getDecl());
1300 }
1301
1302 // <type>       ::= <array-type>
1303 // <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1304 //                  [Y <dimension-count> <dimension>+]
1305 //                  <element-type> # as global
1306 //              ::= Q <cvr-qualifiers> [Y <dimension-count> <dimension>+]
1307 //                  <element-type> # as param
1308 // It's supposed to be the other way around, but for some strange reason, it
1309 // isn't. Today this behavior is retained for the sole purpose of backwards
1310 // compatibility.
1311 void MicrosoftCXXNameMangler::mangleType(const ArrayType *T, bool IsGlobal) {
1312   // This isn't a recursive mangling, so now we have to do it all in this
1313   // one call.
1314   if (IsGlobal) {
1315     manglePointerQualifiers(T->getElementType().getQualifiers());
1316   } else {
1317     Out << 'Q';
1318   }
1319   mangleExtraDimensions(T->getElementType());
1320 }
1321 void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T,
1322                                          SourceRange) {
1323   mangleType(cast<ArrayType>(T), false);
1324 }
1325 void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T,
1326                                          SourceRange) {
1327   mangleType(cast<ArrayType>(T), false);
1328 }
1329 void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
1330                                          SourceRange) {
1331   mangleType(cast<ArrayType>(T), false);
1332 }
1333 void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
1334                                          SourceRange) {
1335   mangleType(cast<ArrayType>(T), false);
1336 }
1337 void MicrosoftCXXNameMangler::mangleExtraDimensions(QualType ElementTy) {
1338   SmallVector<llvm::APInt, 3> Dimensions;
1339   for (;;) {
1340     if (const ConstantArrayType *CAT =
1341           getASTContext().getAsConstantArrayType(ElementTy)) {
1342       Dimensions.push_back(CAT->getSize());
1343       ElementTy = CAT->getElementType();
1344     } else if (ElementTy->isVariableArrayType()) {
1345       const VariableArrayType *VAT =
1346         getASTContext().getAsVariableArrayType(ElementTy);
1347       DiagnosticsEngine &Diags = Context.getDiags();
1348       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1349         "cannot mangle this variable-length array yet");
1350       Diags.Report(VAT->getSizeExpr()->getExprLoc(), DiagID)
1351         << VAT->getBracketsRange();
1352       return;
1353     } else if (ElementTy->isDependentSizedArrayType()) {
1354       // The dependent expression has to be folded into a constant (TODO).
1355       const DependentSizedArrayType *DSAT =
1356         getASTContext().getAsDependentSizedArrayType(ElementTy);
1357       DiagnosticsEngine &Diags = Context.getDiags();
1358       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1359         "cannot mangle this dependent-length array yet");
1360       Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
1361         << DSAT->getBracketsRange();
1362       return;
1363     } else if (ElementTy->isIncompleteArrayType()) continue;
1364     else break;
1365   }
1366   mangleQualifiers(ElementTy.getQualifiers(), false);
1367   // If there are any additional dimensions, mangle them now.
1368   if (Dimensions.size() > 0) {
1369     Out << 'Y';
1370     // <dimension-count> ::= <number> # number of extra dimensions
1371     mangleNumber(Dimensions.size());
1372     for (unsigned Dim = 0; Dim < Dimensions.size(); ++Dim) {
1373       mangleNumber(Dimensions[Dim].getLimitedValue());
1374     }
1375   }
1376   mangleType(ElementTy.getLocalUnqualifiedType(), SourceRange());
1377 }
1378
1379 // <type>                   ::= <pointer-to-member-type>
1380 // <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1381 //                                                          <class name> <type>
1382 void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
1383                                          SourceRange Range) {
1384   QualType PointeeType = T->getPointeeType();
1385   if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
1386     Out << '8';
1387     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1388     mangleType(FPT, NULL, false, true);
1389   } else {
1390     mangleQualifiers(PointeeType.getQualifiers(), true);
1391     mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1392     mangleType(PointeeType.getLocalUnqualifiedType(), Range);
1393   }
1394 }
1395
1396 void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
1397                                          SourceRange Range) {
1398   DiagnosticsEngine &Diags = Context.getDiags();
1399   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1400     "cannot mangle this template type parameter type yet");
1401   Diags.Report(Range.getBegin(), DiagID)
1402     << Range;
1403 }
1404
1405 void MicrosoftCXXNameMangler::mangleType(
1406                                        const SubstTemplateTypeParmPackType *T,
1407                                        SourceRange Range) {
1408   DiagnosticsEngine &Diags = Context.getDiags();
1409   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1410     "cannot mangle this substituted parameter pack yet");
1411   Diags.Report(Range.getBegin(), DiagID)
1412     << Range;
1413 }
1414
1415 // <type> ::= <pointer-type>
1416 // <pointer-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
1417 void MicrosoftCXXNameMangler::mangleType(const PointerType *T,
1418                                          SourceRange Range) {
1419   QualType PointeeTy = T->getPointeeType();
1420   if (PointeeTy->isArrayType()) {
1421     // Pointers to arrays are mangled like arrays.
1422     mangleExtraDimensions(PointeeTy);
1423   } else if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
1424     // Function pointers are special.
1425     Out << '6';
1426     mangleType(FT, NULL, false, false);
1427   } else {
1428     mangleQualifiers(PointeeTy.getQualifiers(), false);
1429     mangleType(PointeeTy, Range, false);
1430   }
1431 }
1432 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
1433                                          SourceRange Range) {
1434   // Object pointers never have qualifiers.
1435   Out << 'A';
1436   mangleType(T->getPointeeType(), Range);
1437 }
1438
1439 // <type> ::= <reference-type>
1440 // <reference-type> ::= A <cvr-qualifiers> <type>
1441 void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
1442                                          SourceRange Range) {
1443   Out << 'A';
1444   QualType PointeeTy = T->getPointeeType();
1445   if (!PointeeTy.hasQualifiers())
1446     // Lack of qualifiers is mangled as 'A'.
1447     Out << 'A';
1448   mangleType(PointeeTy, Range);
1449 }
1450
1451 // <type> ::= <r-value-reference-type>
1452 // <r-value-reference-type> ::= $$Q <cvr-qualifiers> <type>
1453 void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
1454                                          SourceRange Range) {
1455   Out << "$$Q";
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 void MicrosoftCXXNameMangler::mangleType(const ComplexType *T,
1464                                          SourceRange Range) {
1465   DiagnosticsEngine &Diags = Context.getDiags();
1466   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1467     "cannot mangle this complex number type yet");
1468   Diags.Report(Range.getBegin(), DiagID)
1469     << Range;
1470 }
1471
1472 void MicrosoftCXXNameMangler::mangleType(const VectorType *T,
1473                                          SourceRange Range) {
1474   DiagnosticsEngine &Diags = Context.getDiags();
1475   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1476     "cannot mangle this vector type yet");
1477   Diags.Report(Range.getBegin(), DiagID)
1478     << Range;
1479 }
1480 void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
1481                                          SourceRange Range) {
1482   DiagnosticsEngine &Diags = Context.getDiags();
1483   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1484     "cannot mangle this extended vector type yet");
1485   Diags.Report(Range.getBegin(), DiagID)
1486     << Range;
1487 }
1488 void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
1489                                          SourceRange Range) {
1490   DiagnosticsEngine &Diags = Context.getDiags();
1491   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1492     "cannot mangle this dependent-sized extended vector type yet");
1493   Diags.Report(Range.getBegin(), DiagID)
1494     << Range;
1495 }
1496
1497 void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T,
1498                                          SourceRange) {
1499   // ObjC interfaces have structs underlying them.
1500   Out << 'U';
1501   mangleName(T->getDecl());
1502 }
1503
1504 void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
1505                                          SourceRange Range) {
1506   // We don't allow overloading by different protocol qualification,
1507   // so mangling them isn't necessary.
1508   mangleType(T->getBaseType(), Range);
1509 }
1510
1511 void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
1512                                          SourceRange Range) {
1513   Out << "_E";
1514
1515   QualType pointee = T->getPointeeType();
1516   mangleType(pointee->castAs<FunctionProtoType>(), NULL, false, false);
1517 }
1518
1519 void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *T,
1520                                          SourceRange Range) {
1521   DiagnosticsEngine &Diags = Context.getDiags();
1522   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1523     "cannot mangle this injected class name type yet");
1524   Diags.Report(Range.getBegin(), DiagID)
1525     << Range;
1526 }
1527
1528 void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
1529                                          SourceRange Range) {
1530   DiagnosticsEngine &Diags = Context.getDiags();
1531   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1532     "cannot mangle this template specialization type yet");
1533   Diags.Report(Range.getBegin(), DiagID)
1534     << Range;
1535 }
1536
1537 void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T,
1538                                          SourceRange Range) {
1539   DiagnosticsEngine &Diags = Context.getDiags();
1540   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1541     "cannot mangle this dependent name type yet");
1542   Diags.Report(Range.getBegin(), DiagID)
1543     << Range;
1544 }
1545
1546 void MicrosoftCXXNameMangler::mangleType(
1547                                  const DependentTemplateSpecializationType *T,
1548                                  SourceRange Range) {
1549   DiagnosticsEngine &Diags = Context.getDiags();
1550   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1551     "cannot mangle this dependent template specialization type yet");
1552   Diags.Report(Range.getBegin(), DiagID)
1553     << Range;
1554 }
1555
1556 void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T,
1557                                          SourceRange Range) {
1558   DiagnosticsEngine &Diags = Context.getDiags();
1559   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1560     "cannot mangle this pack expansion yet");
1561   Diags.Report(Range.getBegin(), DiagID)
1562     << Range;
1563 }
1564
1565 void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T,
1566                                          SourceRange Range) {
1567   DiagnosticsEngine &Diags = Context.getDiags();
1568   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1569     "cannot mangle this typeof(type) yet");
1570   Diags.Report(Range.getBegin(), DiagID)
1571     << Range;
1572 }
1573
1574 void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T,
1575                                          SourceRange Range) {
1576   DiagnosticsEngine &Diags = Context.getDiags();
1577   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1578     "cannot mangle this typeof(expression) yet");
1579   Diags.Report(Range.getBegin(), DiagID)
1580     << Range;
1581 }
1582
1583 void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T,
1584                                          SourceRange Range) {
1585   DiagnosticsEngine &Diags = Context.getDiags();
1586   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1587     "cannot mangle this decltype() yet");
1588   Diags.Report(Range.getBegin(), DiagID)
1589     << Range;
1590 }
1591
1592 void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
1593                                          SourceRange Range) {
1594   DiagnosticsEngine &Diags = Context.getDiags();
1595   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1596     "cannot mangle this unary transform type yet");
1597   Diags.Report(Range.getBegin(), DiagID)
1598     << Range;
1599 }
1600
1601 void MicrosoftCXXNameMangler::mangleType(const AutoType *T, SourceRange Range) {
1602   DiagnosticsEngine &Diags = Context.getDiags();
1603   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1604     "cannot mangle this 'auto' type yet");
1605   Diags.Report(Range.getBegin(), DiagID)
1606     << Range;
1607 }
1608
1609 void MicrosoftCXXNameMangler::mangleType(const AtomicType *T,
1610                                          SourceRange Range) {
1611   DiagnosticsEngine &Diags = Context.getDiags();
1612   unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1613     "cannot mangle this C11 atomic type yet");
1614   Diags.Report(Range.getBegin(), DiagID)
1615     << Range;
1616 }
1617
1618 void MicrosoftMangleContext::mangleName(const NamedDecl *D,
1619                                         raw_ostream &Out) {
1620   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
1621          "Invalid mangleName() call, argument is not a variable or function!");
1622   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
1623          "Invalid mangleName() call on 'structor decl!");
1624
1625   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
1626                                  getASTContext().getSourceManager(),
1627                                  "Mangling declaration");
1628
1629   MicrosoftCXXNameMangler Mangler(*this, Out);
1630   return Mangler.mangle(D);
1631 }
1632 void MicrosoftMangleContext::mangleThunk(const CXXMethodDecl *MD,
1633                                          const ThunkInfo &Thunk,
1634                                          raw_ostream &) {
1635   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1636     "cannot mangle thunk for this method yet");
1637   getDiags().Report(MD->getLocation(), DiagID);
1638 }
1639 void MicrosoftMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
1640                                                 CXXDtorType Type,
1641                                                 const ThisAdjustment &,
1642                                                 raw_ostream &) {
1643   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1644     "cannot mangle thunk for this destructor yet");
1645   getDiags().Report(DD->getLocation(), DiagID);
1646 }
1647 void MicrosoftMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
1648                                              raw_ostream &Out) {
1649   // <mangled-name> ::= ? <operator-name> <class-name> <storage-class>
1650   //                      <cvr-qualifiers> [<name>] @
1651   // <operator-name> ::= _7 # vftable
1652   //                 ::= _8 # vbtable
1653   // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
1654   // is always '6' for vftables and '7' for vbtables. (The difference is
1655   // beyond me.)
1656   // TODO: vbtables.
1657   MicrosoftCXXNameMangler Mangler(*this, Out);
1658   Mangler.getStream() << "\01??_7";
1659   Mangler.mangleName(RD);
1660   Mangler.getStream() << "6B";
1661   // TODO: If the class has more than one vtable, mangle in the class it came
1662   // from.
1663   Mangler.getStream() << '@';
1664 }
1665 void MicrosoftMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
1666                                           raw_ostream &) {
1667   llvm_unreachable("The MS C++ ABI does not have virtual table tables!");
1668 }
1669 void MicrosoftMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
1670                                                  int64_t Offset,
1671                                                  const CXXRecordDecl *Type,
1672                                                  raw_ostream &) {
1673   llvm_unreachable("The MS C++ ABI does not have constructor vtables!");
1674 }
1675 void MicrosoftMangleContext::mangleCXXRTTI(QualType T,
1676                                            raw_ostream &) {
1677   // FIXME: Give a location...
1678   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1679     "cannot mangle RTTI descriptors for type %0 yet");
1680   getDiags().Report(DiagID)
1681     << T.getBaseTypeIdentifier();
1682 }
1683 void MicrosoftMangleContext::mangleCXXRTTIName(QualType T,
1684                                                raw_ostream &) {
1685   // FIXME: Give a location...
1686   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1687     "cannot mangle the name of type %0 into RTTI descriptors yet");
1688   getDiags().Report(DiagID)
1689     << T.getBaseTypeIdentifier();
1690 }
1691 void MicrosoftMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
1692                                            CXXCtorType Type,
1693                                            raw_ostream & Out) {
1694   MicrosoftCXXNameMangler mangler(*this, Out);
1695   mangler.mangle(D);
1696 }
1697 void MicrosoftMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
1698                                            CXXDtorType Type,
1699                                            raw_ostream & Out) {
1700   MicrosoftCXXNameMangler mangler(*this, Out);
1701   mangler.mangle(D);
1702 }
1703 void MicrosoftMangleContext::mangleReferenceTemporary(const clang::VarDecl *VD,
1704                                                       raw_ostream &) {
1705   unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
1706     "cannot mangle this reference temporary yet");
1707   getDiags().Report(VD->getLocation(), DiagID);
1708 }
1709
1710 MangleContext *clang::createMicrosoftMangleContext(ASTContext &Context,
1711                                                    DiagnosticsEngine &Diags) {
1712   return new MicrosoftMangleContext(Context, Diags);
1713 }