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