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