MicrosoftMangle.cpp revision c0838d2acb498b0491908d3693514dfec5befe6f
1//===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/Mangle.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/CharUnits.h"
17#include "clang/AST/Decl.h"
18#include "clang/AST/DeclCXX.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/AST/DeclTemplate.h"
21#include "clang/AST/ExprCXX.h"
22#include "clang/Basic/ABI.h"
23
24using namespace clang;
25
26namespace {
27
28/// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
29/// Microsoft Visual C++ ABI.
30class MicrosoftCXXNameMangler {
31  MangleContext &Context;
32  raw_ostream &Out;
33
34  ASTContext &getASTContext() const { return Context.getASTContext(); }
35
36public:
37  MicrosoftCXXNameMangler(MangleContext &C, raw_ostream &Out_)
38  : Context(C), Out(Out_) { }
39
40  void mangle(const NamedDecl *D, StringRef Prefix = "?");
41  void mangleName(const NamedDecl *ND);
42  void mangleFunctionEncoding(const FunctionDecl *FD);
43  void mangleVariableEncoding(const VarDecl *VD);
44  void mangleNumber(int64_t Number);
45  void mangleNumber(const llvm::APSInt &Value);
46  void mangleType(QualType T);
47
48private:
49  void mangleUnqualifiedName(const NamedDecl *ND) {
50    mangleUnqualifiedName(ND, ND->getDeclName());
51  }
52  void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name);
53  void mangleSourceName(const IdentifierInfo *II);
54  void manglePostfix(const DeclContext *DC, bool NoFunction=false);
55  void mangleOperatorName(OverloadedOperatorKind OO);
56  void mangleQualifiers(Qualifiers Quals, bool IsMember);
57
58  void mangleUnscopedTemplateName(const TemplateDecl *ND);
59  void mangleTemplateInstantiationName(const TemplateDecl *TD,
60                                       const TemplateArgument *TemplateArgs,
61                                       unsigned NumTemplateArgs,
62                                       SourceLocation InstantiationLoc);
63  void mangleObjCMethodName(const ObjCMethodDecl *MD);
64
65  // Declare manglers for every type class.
66#define ABSTRACT_TYPE(CLASS, PARENT)
67#define NON_CANONICAL_TYPE(CLASS, PARENT)
68#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
69#include "clang/AST/TypeNodes.def"
70
71  void mangleType(const TagType*);
72  void mangleType(const FunctionType *T, const FunctionDecl *D,
73                  bool IsStructor, bool IsInstMethod);
74  void mangleType(const ArrayType *T, bool IsGlobal);
75  void mangleExtraDimensions(QualType T);
76  void mangleFunctionClass(const FunctionDecl *FD);
77  void mangleCallingConvention(const FunctionType *T, bool IsInstMethod = false);
78  void mangleIntegerLiteral(QualType T, const llvm::APSInt &Number);
79  void mangleThrowSpecification(const FunctionProtoType *T);
80
81  void mangleTemplateArgs(const TemplateArgument *TemplateArgs, unsigned NumTemplateArgs,
82                          SourceLocation InstantiationLoc);
83
84};
85
86/// MicrosoftMangleContext - Overrides the default MangleContext for the
87/// Microsoft Visual C++ ABI.
88class MicrosoftMangleContext : public MangleContext {
89public:
90  MicrosoftMangleContext(ASTContext &Context,
91                   DiagnosticsEngine &Diags) : MangleContext(Context, Diags) { }
92  virtual bool shouldMangleDeclName(const NamedDecl *D);
93  virtual void mangleName(const NamedDecl *D, raw_ostream &Out);
94  virtual void mangleThunk(const CXXMethodDecl *MD,
95                           const ThunkInfo &Thunk,
96                           raw_ostream &);
97  virtual void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
98                                  const ThisAdjustment &ThisAdjustment,
99                                  raw_ostream &);
100  virtual void mangleCXXVTable(const CXXRecordDecl *RD,
101                               raw_ostream &);
102  virtual void mangleCXXVTT(const CXXRecordDecl *RD,
103                            raw_ostream &);
104  virtual void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
105                                   const CXXRecordDecl *Type,
106                                   raw_ostream &);
107  virtual void mangleCXXRTTI(QualType T, raw_ostream &);
108  virtual void mangleCXXRTTIName(QualType T, raw_ostream &);
109  virtual void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
110                             raw_ostream &);
111  virtual void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
112                             raw_ostream &);
113  virtual void mangleReferenceTemporary(const clang::VarDecl *,
114                                        raw_ostream &);
115};
116
117}
118
119static bool isInCLinkageSpecification(const Decl *D) {
120  D = D->getCanonicalDecl();
121  for (const DeclContext *DC = D->getDeclContext();
122       !DC->isTranslationUnit(); DC = DC->getParent()) {
123    if (const LinkageSpecDecl *Linkage = dyn_cast<LinkageSpecDecl>(DC))
124      return Linkage->getLanguage() == LinkageSpecDecl::lang_c;
125  }
126
127  return false;
128}
129
130bool MicrosoftMangleContext::shouldMangleDeclName(const NamedDecl *D) {
131  // In C, functions with no attributes never need to be mangled. Fastpath them.
132  if (!getASTContext().getLangOpts().CPlusPlus && !D->hasAttrs())
133    return false;
134
135  // Any decl can be declared with __asm("foo") on it, and this takes precedence
136  // over all other naming in the .o file.
137  if (D->hasAttr<AsmLabelAttr>())
138    return true;
139
140  // Clang's "overloadable" attribute extension to C/C++ implies name mangling
141  // (always) as does passing a C++ member function and a function
142  // whose name is not a simple identifier.
143  const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
144  if (FD && (FD->hasAttr<OverloadableAttr>() || isa<CXXMethodDecl>(FD) ||
145             !FD->getDeclName().isIdentifier()))
146    return true;
147
148  // Otherwise, no mangling is done outside C++ mode.
149  if (!getASTContext().getLangOpts().CPlusPlus)
150    return false;
151
152  // Variables at global scope with internal linkage are not mangled.
153  if (!FD) {
154    const DeclContext *DC = D->getDeclContext();
155    if (DC->isTranslationUnit() && D->getLinkage() == InternalLinkage)
156      return false;
157  }
158
159  // C functions and "main" are not mangled.
160  if ((FD && FD->isMain()) || isInCLinkageSpecification(D))
161    return false;
162
163  return true;
164}
165
166void MicrosoftCXXNameMangler::mangle(const NamedDecl *D,
167                                     StringRef Prefix) {
168  // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
169  // Therefore it's really important that we don't decorate the
170  // name with leading underscores or leading/trailing at signs. So, emit a
171  // asm marker at the start so we get the name right.
172  Out << '\01';  // LLVM IR Marker for __asm("foo")
173
174  // Any decl can be declared with __asm("foo") on it, and this takes precedence
175  // over all other naming in the .o file.
176  if (const AsmLabelAttr *ALA = D->getAttr<AsmLabelAttr>()) {
177    // If we have an asm name, then we use it as the mangling.
178    Out << ALA->getLabel();
179    return;
180  }
181
182  // <mangled-name> ::= ? <name> <type-encoding>
183  Out << Prefix;
184  mangleName(D);
185  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
186    mangleFunctionEncoding(FD);
187  else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
188    mangleVariableEncoding(VD);
189  // TODO: Fields? Can MSVC even mangle them?
190}
191
192void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
193  // <type-encoding> ::= <function-class> <function-type>
194
195  // Don't mangle in the type if this isn't a decl we should typically mangle.
196  if (!Context.shouldMangleDeclName(FD))
197    return;
198
199  // We should never ever see a FunctionNoProtoType at this point.
200  // We don't even know how to mangle their types anyway :).
201  const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
202
203  bool InStructor = false, InInstMethod = false;
204  const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
205  if (MD) {
206    if (MD->isInstance())
207      InInstMethod = true;
208    if (isa<CXXConstructorDecl>(MD) || isa<CXXDestructorDecl>(MD))
209      InStructor = true;
210  }
211
212  // First, the function class.
213  mangleFunctionClass(FD);
214
215  mangleType(FT, FD, InStructor, InInstMethod);
216}
217
218void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
219  // <type-encoding> ::= <storage-class> <variable-type>
220  // <storage-class> ::= 0  # private static member
221  //                 ::= 1  # protected static member
222  //                 ::= 2  # public static member
223  //                 ::= 3  # global
224  //                 ::= 4  # static local
225
226  // The first character in the encoding (after the name) is the storage class.
227  if (VD->isStaticDataMember()) {
228    // If it's a static member, it also encodes the access level.
229    switch (VD->getAccess()) {
230      default:
231      case AS_private: Out << '0'; break;
232      case AS_protected: Out << '1'; break;
233      case AS_public: Out << '2'; break;
234    }
235  }
236  else if (!VD->isStaticLocal())
237    Out << '3';
238  else
239    Out << '4';
240  // Now mangle the type.
241  // <variable-type> ::= <type> <cvr-qualifiers>
242  //                 ::= <type> A # pointers, references, arrays
243  // Pointers and references are odd. The type of 'int * const foo;' gets
244  // mangled as 'QAHA' instead of 'PAHB', for example.
245  QualType Ty = VD->getType();
246  if (Ty->isPointerType() || Ty->isReferenceType()) {
247    mangleType(Ty);
248    Out << 'A';
249  } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
250    // Global arrays are funny, too.
251    mangleType(AT, true);
252    Out << 'A';
253  } else {
254    mangleType(Ty.getLocalUnqualifiedType());
255    mangleQualifiers(Ty.getLocalQualifiers(), false);
256  }
257}
258
259void MicrosoftCXXNameMangler::mangleName(const NamedDecl *ND) {
260  // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
261  const DeclContext *DC = ND->getDeclContext();
262
263  // Always start with the unqualified name.
264  mangleUnqualifiedName(ND);
265
266  // If this is an extern variable declared locally, the relevant DeclContext
267  // is that of the containing namespace, or the translation unit.
268  if (isa<FunctionDecl>(DC) && ND->hasLinkage())
269    while (!DC->isNamespace() && !DC->isTranslationUnit())
270      DC = DC->getParent();
271
272  manglePostfix(DC);
273
274  // Terminate the whole name with an '@'.
275  Out << '@';
276}
277
278void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
279  // <number> ::= [?] <decimal digit> # 1 <= Number <= 10
280  //          ::= [?] <hex digit>+ @ # 0 or > 9; A = 0, B = 1, etc...
281  //          ::= [?] @ # 0 (alternate mangling, not emitted by VC)
282  if (Number < 0) {
283    Out << '?';
284    Number = -Number;
285  }
286  // Oddly enough, there's a special shorter mangling for 0, but Microsoft chose not
287  // to use it. Instead, 0 gets mangled as "A@". Oh well...
288  if (Number >= 1 && Number <= 10)
289    Out << Number-1;
290  else {
291    // We have to build up the encoding in reverse order, so it will come
292    // out right when we write it out.
293    char Encoding[16];
294    char *EndPtr = Encoding+sizeof(Encoding);
295    char *CurPtr = EndPtr;
296    do {
297      *--CurPtr = 'A' + (Number % 16);
298      Number /= 16;
299    } while (Number);
300    Out.write(CurPtr, EndPtr-CurPtr);
301    Out << '@';
302  }
303}
304
305void MicrosoftCXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
306  if (Value.isSigned() && Value.isNegative()) {
307    Out << '?';
308    mangleNumber(llvm::APSInt(Value.abs()));
309    return;
310  }
311  llvm::APSInt Temp(Value);
312  if (Value.uge(1) && Value.ule(10)) {
313    --Temp;
314    Temp.print(Out, false);
315  } else {
316    // We have to build up the encoding in reverse order, so it will come
317    // out right when we write it out.
318    char Encoding[64];
319    char *EndPtr = Encoding+sizeof(Encoding);
320    char *CurPtr = EndPtr;
321    llvm::APSInt NibbleMask(Value.getBitWidth(), Value.isUnsigned());
322    NibbleMask = 0xf;
323    for (int i = 0, e = Value.getActiveBits() / 4; i != e; ++i) {
324      *--CurPtr = 'A' + Temp.And(NibbleMask).getLimitedValue(0xf);
325      Temp = Temp.lshr(4);
326    };
327    Out.write(CurPtr, EndPtr-CurPtr);
328    Out << '@';
329  }
330}
331
332static const TemplateDecl *
333isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
334  // Check if we have a function template.
335  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){
336    if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
337      TemplateArgs = FD->getTemplateSpecializationArgs();
338      return TD;
339    }
340  }
341
342  // Check if we have a class template.
343  if (const ClassTemplateSpecializationDecl *Spec =
344      dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
345    TemplateArgs = &Spec->getTemplateArgs();
346    return Spec->getSpecializedTemplate();
347  }
348
349  return 0;
350}
351
352void
353MicrosoftCXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
354                                               DeclarationName Name) {
355  //  <unqualified-name> ::= <operator-name>
356  //                     ::= <ctor-dtor-name>
357  //                     ::= <source-name>
358  //                     ::= <template-name>
359  const TemplateArgumentList *TemplateArgs;
360  // Check if we have a template.
361  if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
362    mangleTemplateInstantiationName(TD, TemplateArgs->data(), TemplateArgs->size(),
363                                    ND->getLocation());
364    return;
365  }
366
367  switch (Name.getNameKind()) {
368    case DeclarationName::Identifier: {
369      if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
370        mangleSourceName(II);
371        break;
372      }
373
374      // Otherwise, an anonymous entity.  We must have a declaration.
375      assert(ND && "mangling empty name without declaration");
376
377      if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
378        if (NS->isAnonymousNamespace()) {
379          Out << "?A";
380          break;
381        }
382      }
383
384      // We must have an anonymous struct.
385      const TagDecl *TD = cast<TagDecl>(ND);
386      if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
387        assert(TD->getDeclContext() == D->getDeclContext() &&
388               "Typedef should not be in another decl context!");
389        assert(D->getDeclName().getAsIdentifierInfo() &&
390               "Typedef was not named!");
391        mangleSourceName(D->getDeclName().getAsIdentifierInfo());
392        break;
393      }
394
395      // When VC encounters an anonymous type with no tag and no typedef,
396      // it literally emits '<unnamed-tag>'.
397      Out << "<unnamed-tag>";
398      break;
399    }
400
401    case DeclarationName::ObjCZeroArgSelector:
402    case DeclarationName::ObjCOneArgSelector:
403    case DeclarationName::ObjCMultiArgSelector:
404      llvm_unreachable("Can't mangle Objective-C selector names here!");
405
406    case DeclarationName::CXXConstructorName:
407      Out << "?0";
408      break;
409
410    case DeclarationName::CXXDestructorName:
411      Out << "?1";
412      break;
413
414    case DeclarationName::CXXConversionFunctionName:
415      // <operator-name> ::= ?B # (cast)
416      // The target type is encoded as the return type.
417      Out << "?B";
418      break;
419
420    case DeclarationName::CXXOperatorName:
421      mangleOperatorName(Name.getCXXOverloadedOperator());
422      break;
423
424    case DeclarationName::CXXLiteralOperatorName:
425      // FIXME: Was this added in VS2010? Does MS even know how to mangle this?
426      llvm_unreachable("Don't know how to mangle literal operators yet!");
427
428    case DeclarationName::CXXUsingDirective:
429      llvm_unreachable("Can't mangle a using directive name!");
430  }
431}
432
433void MicrosoftCXXNameMangler::manglePostfix(const DeclContext *DC,
434                                            bool NoFunction) {
435  // <postfix> ::= <unqualified-name> [<postfix>]
436  //           ::= <template-param>
437  //           ::= <substitution> [<postfix>]
438
439  if (!DC) return;
440
441  while (isa<LinkageSpecDecl>(DC))
442    DC = DC->getParent();
443
444  if (DC->isTranslationUnit())
445    return;
446
447  if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
448    Context.mangleBlock(BD, Out);
449    Out << '@';
450    return manglePostfix(DC->getParent(), NoFunction);
451  }
452
453  if (NoFunction && (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC)))
454    return;
455  else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC))
456    mangleObjCMethodName(Method);
457  else {
458    mangleUnqualifiedName(cast<NamedDecl>(DC));
459    manglePostfix(DC->getParent(), NoFunction);
460  }
461}
462
463void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO) {
464  switch (OO) {
465  //                     ?0 # constructor
466  //                     ?1 # destructor
467  // <operator-name> ::= ?2 # new
468  case OO_New: Out << "?2"; break;
469  // <operator-name> ::= ?3 # delete
470  case OO_Delete: Out << "?3"; break;
471  // <operator-name> ::= ?4 # =
472  case OO_Equal: Out << "?4"; break;
473  // <operator-name> ::= ?5 # >>
474  case OO_GreaterGreater: Out << "?5"; break;
475  // <operator-name> ::= ?6 # <<
476  case OO_LessLess: Out << "?6"; break;
477  // <operator-name> ::= ?7 # !
478  case OO_Exclaim: Out << "?7"; break;
479  // <operator-name> ::= ?8 # ==
480  case OO_EqualEqual: Out << "?8"; break;
481  // <operator-name> ::= ?9 # !=
482  case OO_ExclaimEqual: Out << "?9"; break;
483  // <operator-name> ::= ?A # []
484  case OO_Subscript: Out << "?A"; break;
485  //                     ?B # conversion
486  // <operator-name> ::= ?C # ->
487  case OO_Arrow: Out << "?C"; break;
488  // <operator-name> ::= ?D # *
489  case OO_Star: Out << "?D"; break;
490  // <operator-name> ::= ?E # ++
491  case OO_PlusPlus: Out << "?E"; break;
492  // <operator-name> ::= ?F # --
493  case OO_MinusMinus: Out << "?F"; break;
494  // <operator-name> ::= ?G # -
495  case OO_Minus: Out << "?G"; break;
496  // <operator-name> ::= ?H # +
497  case OO_Plus: Out << "?H"; break;
498  // <operator-name> ::= ?I # &
499  case OO_Amp: Out << "?I"; break;
500  // <operator-name> ::= ?J # ->*
501  case OO_ArrowStar: Out << "?J"; break;
502  // <operator-name> ::= ?K # /
503  case OO_Slash: Out << "?K"; break;
504  // <operator-name> ::= ?L # %
505  case OO_Percent: Out << "?L"; break;
506  // <operator-name> ::= ?M # <
507  case OO_Less: Out << "?M"; break;
508  // <operator-name> ::= ?N # <=
509  case OO_LessEqual: Out << "?N"; break;
510  // <operator-name> ::= ?O # >
511  case OO_Greater: Out << "?O"; break;
512  // <operator-name> ::= ?P # >=
513  case OO_GreaterEqual: Out << "?P"; break;
514  // <operator-name> ::= ?Q # ,
515  case OO_Comma: Out << "?Q"; break;
516  // <operator-name> ::= ?R # ()
517  case OO_Call: Out << "?R"; break;
518  // <operator-name> ::= ?S # ~
519  case OO_Tilde: Out << "?S"; break;
520  // <operator-name> ::= ?T # ^
521  case OO_Caret: Out << "?T"; break;
522  // <operator-name> ::= ?U # |
523  case OO_Pipe: Out << "?U"; break;
524  // <operator-name> ::= ?V # &&
525  case OO_AmpAmp: Out << "?V"; break;
526  // <operator-name> ::= ?W # ||
527  case OO_PipePipe: Out << "?W"; break;
528  // <operator-name> ::= ?X # *=
529  case OO_StarEqual: Out << "?X"; break;
530  // <operator-name> ::= ?Y # +=
531  case OO_PlusEqual: Out << "?Y"; break;
532  // <operator-name> ::= ?Z # -=
533  case OO_MinusEqual: Out << "?Z"; break;
534  // <operator-name> ::= ?_0 # /=
535  case OO_SlashEqual: Out << "?_0"; break;
536  // <operator-name> ::= ?_1 # %=
537  case OO_PercentEqual: Out << "?_1"; break;
538  // <operator-name> ::= ?_2 # >>=
539  case OO_GreaterGreaterEqual: Out << "?_2"; break;
540  // <operator-name> ::= ?_3 # <<=
541  case OO_LessLessEqual: Out << "?_3"; break;
542  // <operator-name> ::= ?_4 # &=
543  case OO_AmpEqual: Out << "?_4"; break;
544  // <operator-name> ::= ?_5 # |=
545  case OO_PipeEqual: Out << "?_5"; break;
546  // <operator-name> ::= ?_6 # ^=
547  case OO_CaretEqual: Out << "?_6"; break;
548  //                     ?_7 # vftable
549  //                     ?_8 # vbtable
550  //                     ?_9 # vcall
551  //                     ?_A # typeof
552  //                     ?_B # local static guard
553  //                     ?_C # string
554  //                     ?_D # vbase destructor
555  //                     ?_E # vector deleting destructor
556  //                     ?_F # default constructor closure
557  //                     ?_G # scalar deleting destructor
558  //                     ?_H # vector constructor iterator
559  //                     ?_I # vector destructor iterator
560  //                     ?_J # vector vbase constructor iterator
561  //                     ?_K # virtual displacement map
562  //                     ?_L # eh vector constructor iterator
563  //                     ?_M # eh vector destructor iterator
564  //                     ?_N # eh vector vbase constructor iterator
565  //                     ?_O # copy constructor closure
566  //                     ?_P<name> # udt returning <name>
567  //                     ?_Q # <unknown>
568  //                     ?_R0 # RTTI Type Descriptor
569  //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
570  //                     ?_R2 # RTTI Base Class Array
571  //                     ?_R3 # RTTI Class Hierarchy Descriptor
572  //                     ?_R4 # RTTI Complete Object Locator
573  //                     ?_S # local vftable
574  //                     ?_T # local vftable constructor closure
575  // <operator-name> ::= ?_U # new[]
576  case OO_Array_New: Out << "?_U"; break;
577  // <operator-name> ::= ?_V # delete[]
578  case OO_Array_Delete: Out << "?_V"; break;
579
580  case OO_Conditional:
581    llvm_unreachable("Don't know how to mangle ?:");
582
583  case OO_None:
584  case NUM_OVERLOADED_OPERATORS:
585    llvm_unreachable("Not an overloaded operator");
586  }
587}
588
589void MicrosoftCXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
590  // <source name> ::= <identifier> @
591  Out << II->getName() << '@';
592}
593
594void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(const TemplateDecl *TD,
595                                                     const TemplateArgument *TemplateArgs,
596                                                              unsigned NumTemplateArgs,
597                                                        SourceLocation InstantiationLoc) {
598  // <template-name> ::= <unscoped-template-name> <template-args>
599  //                 ::= <substitution>
600  // Always start with the unqualified name.
601  mangleUnscopedTemplateName(TD);
602  mangleTemplateArgs(TemplateArgs, NumTemplateArgs, InstantiationLoc);
603}
604
605void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
606  Context.mangleObjCMethodName(MD, Out);
607}
608
609void
610MicrosoftCXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *TD) {
611  // <unscoped-template-name> ::= ?$ <unqualified-name>
612  Out << "?$";
613  mangleUnqualifiedName(TD);
614}
615
616void
617MicrosoftCXXNameMangler::mangleIntegerLiteral(QualType T, const llvm::APSInt &Value) {
618  // <integer-literal> ::= $0 <number>
619  Out << "$0";
620  // Make sure booleans are encoded as 0/1.
621  if (T->isBooleanType())
622    Out << (Value.getBoolValue() ? "0" : "A@");
623  else
624    mangleNumber(Value);
625}
626
627void
628MicrosoftCXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
629                                            unsigned NumTemplateArgs,
630                                            SourceLocation InstantiationLoc) {
631  // <template-args> ::= {<type> | <integer-literal>}+ @
632  for (unsigned int i = 0; i < NumTemplateArgs; ++i) {
633    const TemplateArgument &TA = TemplateArgs[i];
634    switch (TA.getKind()) {
635  	case TemplateArgument::Null:
636  		llvm_unreachable("Can't mangle null template arguments!");
637    case TemplateArgument::Type:
638      mangleType(TA.getAsType());
639      break;
640    case TemplateArgument::Integral:
641      mangleIntegerLiteral(TA.getIntegralType(), TA.getAsIntegral());
642      break;
643    default: {
644    	// Issue a diagnostic.
645    	DiagnosticsEngine &Diags = Context.getDiags();
646    	unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
647    		"cannot yet mangle this %select{null|type|pointer/reference|integral|template|"
648    		"template pack expansion|expression|parameter pack}0 template argument");
649    	Diags.Report(InstantiationLoc, DiagID)
650    		<< TA.getKind();
651    }
652    }
653  }
654  Out << '@';
655}
656
657void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
658                                               bool IsMember) {
659  // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
660  // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
661  // 'I' means __restrict (32/64-bit).
662  // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
663  // keyword!
664  // <base-cvr-qualifiers> ::= A  # near
665  //                       ::= B  # near const
666  //                       ::= C  # near volatile
667  //                       ::= D  # near const volatile
668  //                       ::= E  # far (16-bit)
669  //                       ::= F  # far const (16-bit)
670  //                       ::= G  # far volatile (16-bit)
671  //                       ::= H  # far const volatile (16-bit)
672  //                       ::= I  # huge (16-bit)
673  //                       ::= J  # huge const (16-bit)
674  //                       ::= K  # huge volatile (16-bit)
675  //                       ::= L  # huge const volatile (16-bit)
676  //                       ::= M <basis> # based
677  //                       ::= N <basis> # based const
678  //                       ::= O <basis> # based volatile
679  //                       ::= P <basis> # based const volatile
680  //                       ::= Q  # near member
681  //                       ::= R  # near const member
682  //                       ::= S  # near volatile member
683  //                       ::= T  # near const volatile member
684  //                       ::= U  # far member (16-bit)
685  //                       ::= V  # far const member (16-bit)
686  //                       ::= W  # far volatile member (16-bit)
687  //                       ::= X  # far const volatile member (16-bit)
688  //                       ::= Y  # huge member (16-bit)
689  //                       ::= Z  # huge const member (16-bit)
690  //                       ::= 0  # huge volatile member (16-bit)
691  //                       ::= 1  # huge const volatile member (16-bit)
692  //                       ::= 2 <basis> # based member
693  //                       ::= 3 <basis> # based const member
694  //                       ::= 4 <basis> # based volatile member
695  //                       ::= 5 <basis> # based const volatile member
696  //                       ::= 6  # near function (pointers only)
697  //                       ::= 7  # far function (pointers only)
698  //                       ::= 8  # near method (pointers only)
699  //                       ::= 9  # far method (pointers only)
700  //                       ::= _A <basis> # based function (pointers only)
701  //                       ::= _B <basis> # based function (far?) (pointers only)
702  //                       ::= _C <basis> # based method (pointers only)
703  //                       ::= _D <basis> # based method (far?) (pointers only)
704  //                       ::= _E # block (Clang)
705  // <basis> ::= 0 # __based(void)
706  //         ::= 1 # __based(segment)?
707  //         ::= 2 <name> # __based(name)
708  //         ::= 3 # ?
709  //         ::= 4 # ?
710  //         ::= 5 # not really based
711  if (!IsMember) {
712    if (!Quals.hasVolatile()) {
713      if (!Quals.hasConst())
714        Out << 'A';
715      else
716        Out << 'B';
717    } else {
718      if (!Quals.hasConst())
719        Out << 'C';
720      else
721        Out << 'D';
722    }
723  } else {
724    if (!Quals.hasVolatile()) {
725      if (!Quals.hasConst())
726        Out << 'Q';
727      else
728        Out << 'R';
729    } else {
730      if (!Quals.hasConst())
731        Out << 'S';
732      else
733        Out << 'T';
734    }
735  }
736
737  // FIXME: For now, just drop all extension qualifiers on the floor.
738}
739
740void MicrosoftCXXNameMangler::mangleType(QualType T) {
741  // Only operate on the canonical type!
742  T = getASTContext().getCanonicalType(T);
743
744  Qualifiers Quals = T.getLocalQualifiers();
745  if (Quals) {
746    // We have to mangle these now, while we still have enough information.
747    // <pointer-cvr-qualifiers> ::= P  # pointer
748    //                          ::= Q  # const pointer
749    //                          ::= R  # volatile pointer
750    //                          ::= S  # const volatile pointer
751    if (T->isAnyPointerType() || T->isMemberPointerType() ||
752        T->isBlockPointerType()) {
753      if (!Quals.hasVolatile())
754        Out << 'Q';
755      else {
756        if (!Quals.hasConst())
757          Out << 'R';
758        else
759          Out << 'S';
760      }
761    } else
762      // Just emit qualifiers like normal.
763      // NB: When we mangle a pointer/reference type, and the pointee
764      // type has no qualifiers, the lack of qualifier gets mangled
765      // in there.
766      mangleQualifiers(Quals, false);
767  } else if (T->isAnyPointerType() || T->isMemberPointerType() ||
768             T->isBlockPointerType()) {
769    Out << 'P';
770  }
771  switch (T->getTypeClass()) {
772#define ABSTRACT_TYPE(CLASS, PARENT)
773#define NON_CANONICAL_TYPE(CLASS, PARENT) \
774case Type::CLASS: \
775llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
776return;
777#define TYPE(CLASS, PARENT) \
778case Type::CLASS: \
779mangleType(static_cast<const CLASS##Type*>(T.getTypePtr())); \
780break;
781#include "clang/AST/TypeNodes.def"
782  }
783}
784
785void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T) {
786  //  <type>         ::= <builtin-type>
787  //  <builtin-type> ::= X  # void
788  //                 ::= C  # signed char
789  //                 ::= D  # char
790  //                 ::= E  # unsigned char
791  //                 ::= F  # short
792  //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
793  //                 ::= H  # int
794  //                 ::= I  # unsigned int
795  //                 ::= J  # long
796  //                 ::= K  # unsigned long
797  //                     L  # <none>
798  //                 ::= M  # float
799  //                 ::= N  # double
800  //                 ::= O  # long double (__float80 is mangled differently)
801  //                 ::= _J # long long, __int64
802  //                 ::= _K # unsigned long long, __int64
803  //                 ::= _L # __int128
804  //                 ::= _M # unsigned __int128
805  //                 ::= _N # bool
806  //                     _O # <array in parameter>
807  //                 ::= _T # __float80 (Intel)
808  //                 ::= _W # wchar_t
809  //                 ::= _Z # __float80 (Digital Mars)
810  switch (T->getKind()) {
811  case BuiltinType::Void: Out << 'X'; break;
812  case BuiltinType::SChar: Out << 'C'; break;
813  case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'D'; break;
814  case BuiltinType::UChar: Out << 'E'; break;
815  case BuiltinType::Short: Out << 'F'; break;
816  case BuiltinType::UShort: Out << 'G'; break;
817  case BuiltinType::Int: Out << 'H'; break;
818  case BuiltinType::UInt: Out << 'I'; break;
819  case BuiltinType::Long: Out << 'J'; break;
820  case BuiltinType::ULong: Out << 'K'; break;
821  case BuiltinType::Float: Out << 'M'; break;
822  case BuiltinType::Double: Out << 'N'; break;
823  // TODO: Determine size and mangle accordingly
824  case BuiltinType::LongDouble: Out << 'O'; break;
825  case BuiltinType::LongLong: Out << "_J"; break;
826  case BuiltinType::ULongLong: Out << "_K"; break;
827  case BuiltinType::Int128: Out << "_L"; break;
828  case BuiltinType::UInt128: Out << "_M"; break;
829  case BuiltinType::Bool: Out << "_N"; break;
830  case BuiltinType::WChar_S:
831  case BuiltinType::WChar_U: Out << "_W"; break;
832
833#define BUILTIN_TYPE(Id, SingletonId)
834#define PLACEHOLDER_TYPE(Id, SingletonId) \
835  case BuiltinType::Id:
836#include "clang/AST/BuiltinTypes.def"
837  case BuiltinType::Dependent:
838    llvm_unreachable("placeholder types shouldn't get to name mangling");
839
840  case BuiltinType::ObjCId: Out << "PAUobjc_object@@"; break;
841  case BuiltinType::ObjCClass: Out << "PAUobjc_class@@"; break;
842  case BuiltinType::ObjCSel: Out << "PAUobjc_selector@@"; break;
843
844  case BuiltinType::Char16:
845  case BuiltinType::Char32:
846  case BuiltinType::Half:
847  case BuiltinType::NullPtr:
848    assert(0 && "Don't know how to mangle this type yet");
849  }
850}
851
852// <type>          ::= <function-type>
853void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T) {
854  // Structors only appear in decls, so at this point we know it's not a
855  // structor type.
856  // I'll probably have mangleType(MemberPointerType) call the mangleType()
857  // method directly.
858  mangleType(T, NULL, false, false);
859}
860void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T) {
861  llvm_unreachable("Can't mangle K&R function prototypes");
862}
863
864void MicrosoftCXXNameMangler::mangleType(const FunctionType *T,
865                                         const FunctionDecl *D,
866                                         bool IsStructor,
867                                         bool IsInstMethod) {
868  // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
869  //                     <return-type> <argument-list> <throw-spec>
870  const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
871
872  // If this is a C++ instance method, mangle the CVR qualifiers for the
873  // this pointer.
874  if (IsInstMethod)
875    mangleQualifiers(Qualifiers::fromCVRMask(Proto->getTypeQuals()), false);
876
877  mangleCallingConvention(T, IsInstMethod);
878
879  // <return-type> ::= <type>
880  //               ::= @ # structors (they have no declared return type)
881  if (IsStructor)
882    Out << '@';
883  else
884    mangleType(Proto->getResultType());
885
886  // <argument-list> ::= X # void
887  //                 ::= <type>+ @
888  //                 ::= <type>* Z # varargs
889  if (Proto->getNumArgs() == 0 && !Proto->isVariadic()) {
890    Out << 'X';
891  } else {
892    if (D) {
893      // If we got a decl, use the type-as-written to make sure arrays
894      // get mangled right.  Note that we can't rely on the TSI
895      // existing if (for example) the parameter was synthesized.
896      for (FunctionDecl::param_const_iterator Parm = D->param_begin(),
897             ParmEnd = D->param_end(); Parm != ParmEnd; ++Parm) {
898        if (TypeSourceInfo *typeAsWritten = (*Parm)->getTypeSourceInfo())
899          mangleType(typeAsWritten->getType());
900        else
901          mangleType((*Parm)->getType());
902      }
903    } else {
904      for (FunctionProtoType::arg_type_iterator Arg = Proto->arg_type_begin(),
905           ArgEnd = Proto->arg_type_end();
906           Arg != ArgEnd; ++Arg)
907        mangleType(*Arg);
908    }
909    // <builtin-type>      ::= Z  # ellipsis
910    if (Proto->isVariadic())
911      Out << 'Z';
912    else
913      Out << '@';
914  }
915
916  mangleThrowSpecification(Proto);
917}
918
919void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
920  // <function-class> ::= A # private: near
921  //                  ::= B # private: far
922  //                  ::= C # private: static near
923  //                  ::= D # private: static far
924  //                  ::= E # private: virtual near
925  //                  ::= F # private: virtual far
926  //                  ::= G # private: thunk near
927  //                  ::= H # private: thunk far
928  //                  ::= I # protected: near
929  //                  ::= J # protected: far
930  //                  ::= K # protected: static near
931  //                  ::= L # protected: static far
932  //                  ::= M # protected: virtual near
933  //                  ::= N # protected: virtual far
934  //                  ::= O # protected: thunk near
935  //                  ::= P # protected: thunk far
936  //                  ::= Q # public: near
937  //                  ::= R # public: far
938  //                  ::= S # public: static near
939  //                  ::= T # public: static far
940  //                  ::= U # public: virtual near
941  //                  ::= V # public: virtual far
942  //                  ::= W # public: thunk near
943  //                  ::= X # public: thunk far
944  //                  ::= Y # global near
945  //                  ::= Z # global far
946  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
947    switch (MD->getAccess()) {
948      default:
949      case AS_private:
950        if (MD->isStatic())
951          Out << 'C';
952        else if (MD->isVirtual())
953          Out << 'E';
954        else
955          Out << 'A';
956        break;
957      case AS_protected:
958        if (MD->isStatic())
959          Out << 'K';
960        else if (MD->isVirtual())
961          Out << 'M';
962        else
963          Out << 'I';
964        break;
965      case AS_public:
966        if (MD->isStatic())
967          Out << 'S';
968        else if (MD->isVirtual())
969          Out << 'U';
970        else
971          Out << 'Q';
972    }
973  } else
974    Out << 'Y';
975}
976void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T,
977                                                      bool IsInstMethod) {
978  // <calling-convention> ::= A # __cdecl
979  //                      ::= B # __export __cdecl
980  //                      ::= C # __pascal
981  //                      ::= D # __export __pascal
982  //                      ::= E # __thiscall
983  //                      ::= F # __export __thiscall
984  //                      ::= G # __stdcall
985  //                      ::= H # __export __stdcall
986  //                      ::= I # __fastcall
987  //                      ::= J # __export __fastcall
988  // The 'export' calling conventions are from a bygone era
989  // (*cough*Win16*cough*) when functions were declared for export with
990  // that keyword. (It didn't actually export them, it just made them so
991  // that they could be in a DLL and somebody from another module could call
992  // them.)
993  CallingConv CC = T->getCallConv();
994  if (CC == CC_Default)
995    CC = IsInstMethod ? getASTContext().getDefaultMethodCallConv() : CC_C;
996  switch (CC) {
997    default:
998      llvm_unreachable("Unsupported CC for mangling");
999    case CC_Default:
1000    case CC_C: Out << 'A'; break;
1001    case CC_X86Pascal: Out << 'C'; break;
1002    case CC_X86ThisCall: Out << 'E'; break;
1003    case CC_X86StdCall: Out << 'G'; break;
1004    case CC_X86FastCall: Out << 'I'; break;
1005  }
1006}
1007void MicrosoftCXXNameMangler::mangleThrowSpecification(
1008                                                const FunctionProtoType *FT) {
1009  // <throw-spec> ::= Z # throw(...) (default)
1010  //              ::= @ # throw() or __declspec/__attribute__((nothrow))
1011  //              ::= <type>+
1012  // NOTE: Since the Microsoft compiler ignores throw specifications, they are
1013  // all actually mangled as 'Z'. (They're ignored because their associated
1014  // functionality isn't implemented, and probably never will be.)
1015  Out << 'Z';
1016}
1017
1018void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T) {
1019  llvm_unreachable("Don't know how to mangle UnresolvedUsingTypes yet!");
1020}
1021
1022// <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
1023// <union-type>  ::= T <name>
1024// <struct-type> ::= U <name>
1025// <class-type>  ::= V <name>
1026// <enum-type>   ::= W <size> <name>
1027void MicrosoftCXXNameMangler::mangleType(const EnumType *T) {
1028  mangleType(static_cast<const TagType*>(T));
1029}
1030void MicrosoftCXXNameMangler::mangleType(const RecordType *T) {
1031  mangleType(static_cast<const TagType*>(T));
1032}
1033void MicrosoftCXXNameMangler::mangleType(const TagType *T) {
1034  switch (T->getDecl()->getTagKind()) {
1035    case TTK_Union:
1036      Out << 'T';
1037      break;
1038    case TTK_Struct:
1039      Out << 'U';
1040      break;
1041    case TTK_Class:
1042      Out << 'V';
1043      break;
1044    case TTK_Enum:
1045      Out << 'W';
1046      Out << getASTContext().getTypeSizeInChars(
1047                cast<EnumDecl>(T->getDecl())->getIntegerType()).getQuantity();
1048      break;
1049  }
1050  mangleName(T->getDecl());
1051}
1052
1053// <type>       ::= <array-type>
1054// <array-type> ::= P <cvr-qualifiers> [Y <dimension-count> <dimension>+]
1055//                                                  <element-type> # as global
1056//              ::= Q <cvr-qualifiers> [Y <dimension-count> <dimension>+]
1057//                                                  <element-type> # as param
1058// It's supposed to be the other way around, but for some strange reason, it
1059// isn't. Today this behavior is retained for the sole purpose of backwards
1060// compatibility.
1061void MicrosoftCXXNameMangler::mangleType(const ArrayType *T, bool IsGlobal) {
1062  // This isn't a recursive mangling, so now we have to do it all in this
1063  // one call.
1064  if (IsGlobal)
1065    Out << 'P';
1066  else
1067    Out << 'Q';
1068  mangleExtraDimensions(T->getElementType());
1069}
1070void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T) {
1071  mangleType(static_cast<const ArrayType *>(T), false);
1072}
1073void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T) {
1074  mangleType(static_cast<const ArrayType *>(T), false);
1075}
1076void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T) {
1077  mangleType(static_cast<const ArrayType *>(T), false);
1078}
1079void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T) {
1080  mangleType(static_cast<const ArrayType *>(T), false);
1081}
1082void MicrosoftCXXNameMangler::mangleExtraDimensions(QualType ElementTy) {
1083  SmallVector<llvm::APInt, 3> Dimensions;
1084  for (;;) {
1085    if (const ConstantArrayType *CAT =
1086          getASTContext().getAsConstantArrayType(ElementTy)) {
1087      Dimensions.push_back(CAT->getSize());
1088      ElementTy = CAT->getElementType();
1089    } else if (ElementTy->isVariableArrayType()) {
1090      llvm_unreachable("Don't know how to mangle VLAs!");
1091    } else if (ElementTy->isDependentSizedArrayType()) {
1092      // The dependent expression has to be folded into a constant (TODO).
1093      llvm_unreachable("Don't know how to mangle dependent-sized arrays!");
1094    } else if (ElementTy->isIncompleteArrayType()) continue;
1095    else break;
1096  }
1097  mangleQualifiers(ElementTy.getQualifiers(), false);
1098  // If there are any additional dimensions, mangle them now.
1099  if (Dimensions.size() > 0) {
1100    Out << 'Y';
1101    // <dimension-count> ::= <number> # number of extra dimensions
1102    mangleNumber(Dimensions.size());
1103    for (unsigned Dim = 0; Dim < Dimensions.size(); ++Dim) {
1104      mangleNumber(Dimensions[Dim].getLimitedValue());
1105    }
1106  }
1107  mangleType(ElementTy.getLocalUnqualifiedType());
1108}
1109
1110// <type>                   ::= <pointer-to-member-type>
1111// <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
1112//                                                          <class name> <type>
1113void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T) {
1114  QualType PointeeType = T->getPointeeType();
1115  if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
1116    Out << '8';
1117    mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1118    mangleType(FPT, NULL, false, true);
1119  } else {
1120    mangleQualifiers(PointeeType.getQualifiers(), true);
1121    mangleName(T->getClass()->castAs<RecordType>()->getDecl());
1122    mangleType(PointeeType.getLocalUnqualifiedType());
1123  }
1124}
1125
1126void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T) {
1127  llvm_unreachable("Don't know how to mangle TemplateTypeParmTypes yet!");
1128}
1129
1130void MicrosoftCXXNameMangler::mangleType(
1131                                       const SubstTemplateTypeParmPackType *T) {
1132  llvm_unreachable(
1133         "Don't know how to mangle SubstTemplateTypeParmPackTypes yet!");
1134}
1135
1136// <type> ::= <pointer-type>
1137// <pointer-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
1138void MicrosoftCXXNameMangler::mangleType(const PointerType *T) {
1139  QualType PointeeTy = T->getPointeeType();
1140  if (PointeeTy->isArrayType()) {
1141    // Pointers to arrays are mangled like arrays.
1142    mangleExtraDimensions(PointeeTy);
1143  } else if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
1144    // Function pointers are special.
1145    Out << '6';
1146    mangleType(FT, NULL, false, false);
1147  } else {
1148    if (!PointeeTy.hasQualifiers())
1149      // Lack of qualifiers is mangled as 'A'.
1150      Out << 'A';
1151    mangleType(PointeeTy);
1152  }
1153}
1154void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
1155  // Object pointers never have qualifiers.
1156  Out << 'A';
1157  mangleType(T->getPointeeType());
1158}
1159
1160// <type> ::= <reference-type>
1161// <reference-type> ::= A <cvr-qualifiers> <type>
1162void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T) {
1163  Out << 'A';
1164  QualType PointeeTy = T->getPointeeType();
1165  if (!PointeeTy.hasQualifiers())
1166    // Lack of qualifiers is mangled as 'A'.
1167    Out << 'A';
1168  mangleType(PointeeTy);
1169}
1170
1171void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T) {
1172  llvm_unreachable("Don't know how to mangle RValueReferenceTypes yet!");
1173}
1174
1175void MicrosoftCXXNameMangler::mangleType(const ComplexType *T) {
1176  llvm_unreachable("Don't know how to mangle ComplexTypes yet!");
1177}
1178
1179void MicrosoftCXXNameMangler::mangleType(const VectorType *T) {
1180  llvm_unreachable("Don't know how to mangle VectorTypes yet!");
1181}
1182void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T) {
1183  llvm_unreachable("Don't know how to mangle ExtVectorTypes yet!");
1184}
1185void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
1186  llvm_unreachable(
1187                  "Don't know how to mangle DependentSizedExtVectorTypes yet!");
1188}
1189
1190void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T) {
1191  // ObjC interfaces have structs underlying them.
1192  Out << 'U';
1193  mangleName(T->getDecl());
1194}
1195
1196void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T) {
1197  // We don't allow overloading by different protocol qualification,
1198  // so mangling them isn't necessary.
1199  mangleType(T->getBaseType());
1200}
1201
1202void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T) {
1203  Out << "_E";
1204  mangleType(T->getPointeeType());
1205}
1206
1207void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *T) {
1208  llvm_unreachable("Don't know how to mangle InjectedClassNameTypes yet!");
1209}
1210
1211void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T) {
1212  llvm_unreachable("Don't know how to mangle TemplateSpecializationTypes yet!");
1213}
1214
1215void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T) {
1216  llvm_unreachable("Don't know how to mangle DependentNameTypes yet!");
1217}
1218
1219void MicrosoftCXXNameMangler::mangleType(
1220                                 const DependentTemplateSpecializationType *T) {
1221  llvm_unreachable(
1222         "Don't know how to mangle DependentTemplateSpecializationTypes yet!");
1223}
1224
1225void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T) {
1226  llvm_unreachable("Don't know how to mangle PackExpansionTypes yet!");
1227}
1228
1229void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T) {
1230  llvm_unreachable("Don't know how to mangle TypeOfTypes yet!");
1231}
1232
1233void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T) {
1234  llvm_unreachable("Don't know how to mangle TypeOfExprTypes yet!");
1235}
1236
1237void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T) {
1238  llvm_unreachable("Don't know how to mangle DecltypeTypes yet!");
1239}
1240
1241void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T) {
1242  llvm_unreachable("Don't know how to mangle UnaryTransformationTypes yet!");
1243}
1244
1245void MicrosoftCXXNameMangler::mangleType(const AutoType *T) {
1246  llvm_unreachable("Don't know how to mangle AutoTypes yet!");
1247}
1248
1249void MicrosoftCXXNameMangler::mangleType(const AtomicType *T) {
1250  llvm_unreachable("Don't know how to mangle AtomicTypes yet!");
1251}
1252
1253void MicrosoftMangleContext::mangleName(const NamedDecl *D,
1254                                        raw_ostream &Out) {
1255  assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
1256         "Invalid mangleName() call, argument is not a variable or function!");
1257  assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
1258         "Invalid mangleName() call on 'structor decl!");
1259
1260  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
1261                                 getASTContext().getSourceManager(),
1262                                 "Mangling declaration");
1263
1264  MicrosoftCXXNameMangler Mangler(*this, Out);
1265  return Mangler.mangle(D);
1266}
1267void MicrosoftMangleContext::mangleThunk(const CXXMethodDecl *MD,
1268                                         const ThunkInfo &Thunk,
1269                                         raw_ostream &) {
1270  llvm_unreachable("Can't yet mangle thunks!");
1271}
1272void MicrosoftMangleContext::mangleCXXDtorThunk(const CXXDestructorDecl *DD,
1273                                                CXXDtorType Type,
1274                                                const ThisAdjustment &,
1275                                                raw_ostream &) {
1276  llvm_unreachable("Can't yet mangle destructor thunks!");
1277}
1278void MicrosoftMangleContext::mangleCXXVTable(const CXXRecordDecl *RD,
1279                                             raw_ostream &) {
1280  llvm_unreachable("Can't yet mangle virtual tables!");
1281}
1282void MicrosoftMangleContext::mangleCXXVTT(const CXXRecordDecl *RD,
1283                                          raw_ostream &) {
1284  llvm_unreachable("The MS C++ ABI does not have virtual table tables!");
1285}
1286void MicrosoftMangleContext::mangleCXXCtorVTable(const CXXRecordDecl *RD,
1287                                                 int64_t Offset,
1288                                                 const CXXRecordDecl *Type,
1289                                                 raw_ostream &) {
1290  llvm_unreachable("The MS C++ ABI does not have constructor vtables!");
1291}
1292void MicrosoftMangleContext::mangleCXXRTTI(QualType T,
1293                                           raw_ostream &) {
1294  llvm_unreachable("Can't yet mangle RTTI!");
1295}
1296void MicrosoftMangleContext::mangleCXXRTTIName(QualType T,
1297                                               raw_ostream &) {
1298  llvm_unreachable("Can't yet mangle RTTI names!");
1299}
1300void MicrosoftMangleContext::mangleCXXCtor(const CXXConstructorDecl *D,
1301                                           CXXCtorType Type,
1302                                           raw_ostream & Out) {
1303  MicrosoftCXXNameMangler mangler(*this, Out);
1304  mangler.mangle(D);
1305}
1306void MicrosoftMangleContext::mangleCXXDtor(const CXXDestructorDecl *D,
1307                                           CXXDtorType Type,
1308                                           raw_ostream & Out) {
1309  MicrosoftCXXNameMangler mangler(*this, Out);
1310  mangler.mangle(D);
1311}
1312void MicrosoftMangleContext::mangleReferenceTemporary(const clang::VarDecl *,
1313                                                      raw_ostream &) {
1314  llvm_unreachable("Can't yet mangle reference temporaries!");
1315}
1316
1317MangleContext *clang::createMicrosoftMangleContext(ASTContext &Context,
1318                                                   DiagnosticsEngine &Diags) {
1319  return new MicrosoftMangleContext(Context, Diags);
1320}
1321