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