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