]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/AST/ItaniumMangle.cpp
MFV r313759: license change for a few headers (4 clause BSD to 3 clause BSD).
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / AST / ItaniumMangle.cpp
1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===//
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 // Implements C++ name mangling according to the Itanium C++ ABI,
11 // which is used in GCC 3.2 and newer (and many compilers that are
12 // ABI-compatible with GCC):
13 //
14 //   http://mentorembedded.github.io/cxx-abi/abi.html#mangling
15 //
16 //===----------------------------------------------------------------------===//
17 #include "clang/AST/Mangle.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Attr.h"
20 #include "clang/AST/Decl.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclObjC.h"
23 #include "clang/AST/DeclOpenMP.h"
24 #include "clang/AST/DeclTemplate.h"
25 #include "clang/AST/Expr.h"
26 #include "clang/AST/ExprCXX.h"
27 #include "clang/AST/ExprObjC.h"
28 #include "clang/AST/TypeLoc.h"
29 #include "clang/Basic/ABI.h"
30 #include "clang/Basic/SourceManager.h"
31 #include "clang/Basic/TargetInfo.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/raw_ostream.h"
35
36 #define MANGLE_CHECKER 0
37
38 #if MANGLE_CHECKER
39 #include <cxxabi.h>
40 #endif
41
42 using namespace clang;
43
44 namespace {
45
46 /// Retrieve the declaration context that should be used when mangling the given
47 /// declaration.
48 static const DeclContext *getEffectiveDeclContext(const Decl *D) {
49   // The ABI assumes that lambda closure types that occur within 
50   // default arguments live in the context of the function. However, due to
51   // the way in which Clang parses and creates function declarations, this is
52   // not the case: the lambda closure type ends up living in the context 
53   // where the function itself resides, because the function declaration itself
54   // had not yet been created. Fix the context here.
55   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
56     if (RD->isLambda())
57       if (ParmVarDecl *ContextParam
58             = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
59         return ContextParam->getDeclContext();
60   }
61
62   // Perform the same check for block literals.
63   if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
64     if (ParmVarDecl *ContextParam
65           = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
66       return ContextParam->getDeclContext();
67   }
68   
69   const DeclContext *DC = D->getDeclContext();
70   if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC)) {
71     return getEffectiveDeclContext(cast<Decl>(DC));
72   }
73
74   if (const auto *VD = dyn_cast<VarDecl>(D))
75     if (VD->isExternC())
76       return VD->getASTContext().getTranslationUnitDecl();
77
78   if (const auto *FD = dyn_cast<FunctionDecl>(D))
79     if (FD->isExternC())
80       return FD->getASTContext().getTranslationUnitDecl();
81
82   return DC->getRedeclContext();
83 }
84
85 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
86   return getEffectiveDeclContext(cast<Decl>(DC));
87 }
88
89 static bool isLocalContainerContext(const DeclContext *DC) {
90   return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
91 }
92
93 static const RecordDecl *GetLocalClassDecl(const Decl *D) {
94   const DeclContext *DC = getEffectiveDeclContext(D);
95   while (!DC->isNamespace() && !DC->isTranslationUnit()) {
96     if (isLocalContainerContext(DC))
97       return dyn_cast<RecordDecl>(D);
98     D = cast<Decl>(DC);
99     DC = getEffectiveDeclContext(D);
100   }
101   return nullptr;
102 }
103
104 static const FunctionDecl *getStructor(const FunctionDecl *fn) {
105   if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
106     return ftd->getTemplatedDecl();
107
108   return fn;
109 }
110
111 static const NamedDecl *getStructor(const NamedDecl *decl) {
112   const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
113   return (fn ? getStructor(fn) : decl);
114 }
115
116 static bool isLambda(const NamedDecl *ND) {
117   const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
118   if (!Record)
119     return false;
120
121   return Record->isLambda();
122 }
123
124 static const unsigned UnknownArity = ~0U;
125
126 class ItaniumMangleContextImpl : public ItaniumMangleContext {
127   typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
128   llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
129   llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
130
131 public:
132   explicit ItaniumMangleContextImpl(ASTContext &Context,
133                                     DiagnosticsEngine &Diags)
134       : ItaniumMangleContext(Context, Diags) {}
135
136   /// @name Mangler Entry Points
137   /// @{
138
139   bool shouldMangleCXXName(const NamedDecl *D) override;
140   bool shouldMangleStringLiteral(const StringLiteral *) override {
141     return false;
142   }
143   void mangleCXXName(const NamedDecl *D, raw_ostream &) override;
144   void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
145                    raw_ostream &) override;
146   void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
147                           const ThisAdjustment &ThisAdjustment,
148                           raw_ostream &) override;
149   void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
150                                 raw_ostream &) override;
151   void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
152   void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
153   void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
154                            const CXXRecordDecl *Type, raw_ostream &) override;
155   void mangleCXXRTTI(QualType T, raw_ostream &) override;
156   void mangleCXXRTTIName(QualType T, raw_ostream &) override;
157   void mangleTypeName(QualType T, raw_ostream &) override;
158   void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type,
159                      raw_ostream &) override;
160   void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type,
161                      raw_ostream &) override;
162
163   void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
164   void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
165   void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
166   void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
167   void mangleDynamicAtExitDestructor(const VarDecl *D,
168                                      raw_ostream &Out) override;
169   void mangleSEHFilterExpression(const NamedDecl *EnclosingDecl,
170                                  raw_ostream &Out) override;
171   void mangleSEHFinallyBlock(const NamedDecl *EnclosingDecl,
172                              raw_ostream &Out) override;
173   void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
174   void mangleItaniumThreadLocalWrapper(const VarDecl *D,
175                                        raw_ostream &) override;
176
177   void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
178
179   bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
180     // Lambda closure types are already numbered.
181     if (isLambda(ND))
182       return false;
183
184     // Anonymous tags are already numbered.
185     if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
186       if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
187         return false;
188     }
189
190     // Use the canonical number for externally visible decls.
191     if (ND->isExternallyVisible()) {
192       unsigned discriminator = getASTContext().getManglingNumber(ND);
193       if (discriminator == 1)
194         return false;
195       disc = discriminator - 2;
196       return true;
197     }
198
199     // Make up a reasonable number for internal decls.
200     unsigned &discriminator = Uniquifier[ND];
201     if (!discriminator) {
202       const DeclContext *DC = getEffectiveDeclContext(ND);
203       discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
204     }
205     if (discriminator == 1)
206       return false;
207     disc = discriminator-2;
208     return true;
209   }
210   /// @}
211 };
212
213 /// Manage the mangling of a single name.
214 class CXXNameMangler {
215   ItaniumMangleContextImpl &Context;
216   raw_ostream &Out;
217   bool NullOut = false;
218   /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated.
219   /// This mode is used when mangler creates another mangler recursively to
220   /// calculate ABI tags for the function return value or the variable type.
221   /// Also it is required to avoid infinite recursion in some cases.
222   bool DisableDerivedAbiTags = false;
223
224   /// The "structor" is the top-level declaration being mangled, if
225   /// that's not a template specialization; otherwise it's the pattern
226   /// for that specialization.
227   const NamedDecl *Structor;
228   unsigned StructorType;
229
230   /// The next substitution sequence number.
231   unsigned SeqID;
232
233   class FunctionTypeDepthState {
234     unsigned Bits;
235
236     enum { InResultTypeMask = 1 };
237
238   public:
239     FunctionTypeDepthState() : Bits(0) {}
240
241     /// The number of function types we're inside.
242     unsigned getDepth() const {
243       return Bits >> 1;
244     }
245
246     /// True if we're in the return type of the innermost function type.
247     bool isInResultType() const {
248       return Bits & InResultTypeMask;
249     }
250
251     FunctionTypeDepthState push() {
252       FunctionTypeDepthState tmp = *this;
253       Bits = (Bits & ~InResultTypeMask) + 2;
254       return tmp;
255     }
256
257     void enterResultType() {
258       Bits |= InResultTypeMask;
259     }
260
261     void leaveResultType() {
262       Bits &= ~InResultTypeMask;
263     }
264
265     void pop(FunctionTypeDepthState saved) {
266       assert(getDepth() == saved.getDepth() + 1);
267       Bits = saved.Bits;
268     }
269
270   } FunctionTypeDepth;
271
272   // abi_tag is a gcc attribute, taking one or more strings called "tags".
273   // The goal is to annotate against which version of a library an object was
274   // built and to be able to provide backwards compatibility ("dual abi").
275   // For more information see docs/ItaniumMangleAbiTags.rst.
276   typedef SmallVector<StringRef, 4> AbiTagList;
277
278   // State to gather all implicit and explicit tags used in a mangled name.
279   // Must always have an instance of this while emitting any name to keep
280   // track.
281   class AbiTagState final {
282   public:
283     explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) {
284       Parent = LinkHead;
285       LinkHead = this;
286     }
287
288     // No copy, no move.
289     AbiTagState(const AbiTagState &) = delete;
290     AbiTagState &operator=(const AbiTagState &) = delete;
291
292     ~AbiTagState() { pop(); }
293
294     void write(raw_ostream &Out, const NamedDecl *ND,
295                const AbiTagList *AdditionalAbiTags) {
296       ND = cast<NamedDecl>(ND->getCanonicalDecl());
297       if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) {
298         assert(
299             !AdditionalAbiTags &&
300             "only function and variables need a list of additional abi tags");
301         if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) {
302           if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) {
303             UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
304                                AbiTag->tags().end());
305           }
306           // Don't emit abi tags for namespaces.
307           return;
308         }
309       }
310
311       AbiTagList TagList;
312       if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) {
313         UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(),
314                            AbiTag->tags().end());
315         TagList.insert(TagList.end(), AbiTag->tags().begin(),
316                        AbiTag->tags().end());
317       }
318
319       if (AdditionalAbiTags) {
320         UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(),
321                            AdditionalAbiTags->end());
322         TagList.insert(TagList.end(), AdditionalAbiTags->begin(),
323                        AdditionalAbiTags->end());
324       }
325
326       std::sort(TagList.begin(), TagList.end());
327       TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end());
328
329       writeSortedUniqueAbiTags(Out, TagList);
330     }
331
332     const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; }
333     void setUsedAbiTags(const AbiTagList &AbiTags) {
334       UsedAbiTags = AbiTags;
335     }
336
337     const AbiTagList &getEmittedAbiTags() const {
338       return EmittedAbiTags;
339     }
340
341     const AbiTagList &getSortedUniqueUsedAbiTags() {
342       std::sort(UsedAbiTags.begin(), UsedAbiTags.end());
343       UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()),
344                         UsedAbiTags.end());
345       return UsedAbiTags;
346     }
347
348   private:
349     //! All abi tags used implicitly or explicitly.
350     AbiTagList UsedAbiTags;
351     //! All explicit abi tags (i.e. not from namespace).
352     AbiTagList EmittedAbiTags;
353
354     AbiTagState *&LinkHead;
355     AbiTagState *Parent = nullptr;
356
357     void pop() {
358       assert(LinkHead == this &&
359              "abi tag link head must point to us on destruction");
360       if (Parent) {
361         Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(),
362                                    UsedAbiTags.begin(), UsedAbiTags.end());
363         Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(),
364                                       EmittedAbiTags.begin(),
365                                       EmittedAbiTags.end());
366       }
367       LinkHead = Parent;
368     }
369
370     void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) {
371       for (const auto &Tag : AbiTags) {
372         EmittedAbiTags.push_back(Tag);
373         Out << "B";
374         Out << Tag.size();
375         Out << Tag;
376       }
377     }
378   };
379
380   AbiTagState *AbiTags = nullptr;
381   AbiTagState AbiTagsRoot;
382
383   llvm::DenseMap<uintptr_t, unsigned> Substitutions;
384
385   ASTContext &getASTContext() const { return Context.getASTContext(); }
386
387 public:
388   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
389                  const NamedDecl *D = nullptr, bool NullOut_ = false)
390     : Context(C), Out(Out_), NullOut(NullOut_),  Structor(getStructor(D)),
391       StructorType(0), SeqID(0), AbiTagsRoot(AbiTags) {
392     // These can't be mangled without a ctor type or dtor type.
393     assert(!D || (!isa<CXXDestructorDecl>(D) &&
394                   !isa<CXXConstructorDecl>(D)));
395   }
396   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
397                  const CXXConstructorDecl *D, CXXCtorType Type)
398     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
399       SeqID(0), AbiTagsRoot(AbiTags) { }
400   CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
401                  const CXXDestructorDecl *D, CXXDtorType Type)
402     : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
403       SeqID(0), AbiTagsRoot(AbiTags) { }
404
405   CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
406       : Context(Outer.Context), Out(Out_), NullOut(false),
407         Structor(Outer.Structor), StructorType(Outer.StructorType),
408         SeqID(Outer.SeqID), AbiTagsRoot(AbiTags) {}
409
410   CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
411       : Context(Outer.Context), Out(Out_), NullOut(true),
412         Structor(Outer.Structor), StructorType(Outer.StructorType),
413         SeqID(Outer.SeqID), AbiTagsRoot(AbiTags) {}
414
415 #if MANGLE_CHECKER
416   ~CXXNameMangler() {
417     if (Out.str()[0] == '\01')
418       return;
419
420     int status = 0;
421     char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status);
422     assert(status == 0 && "Could not demangle mangled name!");
423     free(result);
424   }
425 #endif
426   raw_ostream &getStream() { return Out; }
427
428   void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
429   static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
430
431   void mangle(const NamedDecl *D);
432   void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
433   void mangleNumber(const llvm::APSInt &I);
434   void mangleNumber(int64_t Number);
435   void mangleFloat(const llvm::APFloat &F);
436   void mangleFunctionEncoding(const FunctionDecl *FD);
437   void mangleSeqID(unsigned SeqID);
438   void mangleName(const NamedDecl *ND);
439   void mangleType(QualType T);
440   void mangleNameOrStandardSubstitution(const NamedDecl *ND);
441   
442 private:
443
444   bool mangleSubstitution(const NamedDecl *ND);
445   bool mangleSubstitution(QualType T);
446   bool mangleSubstitution(TemplateName Template);
447   bool mangleSubstitution(uintptr_t Ptr);
448
449   void mangleExistingSubstitution(TemplateName name);
450
451   bool mangleStandardSubstitution(const NamedDecl *ND);
452
453   void addSubstitution(const NamedDecl *ND) {
454     ND = cast<NamedDecl>(ND->getCanonicalDecl());
455
456     addSubstitution(reinterpret_cast<uintptr_t>(ND));
457   }
458   void addSubstitution(QualType T);
459   void addSubstitution(TemplateName Template);
460   void addSubstitution(uintptr_t Ptr);
461
462   void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
463                               bool recursive = false);
464   void mangleUnresolvedName(NestedNameSpecifier *qualifier,
465                             DeclarationName name,
466                             unsigned KnownArity = UnknownArity);
467
468   void mangleFunctionEncodingBareType(const FunctionDecl *FD);
469
470   void mangleNameWithAbiTags(const NamedDecl *ND,
471                              const AbiTagList *AdditionalAbiTags);
472   void mangleTemplateName(const TemplateDecl *TD,
473                           const TemplateArgument *TemplateArgs,
474                           unsigned NumTemplateArgs);
475   void mangleUnqualifiedName(const NamedDecl *ND,
476                              const AbiTagList *AdditionalAbiTags) {
477     mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity,
478                           AdditionalAbiTags);
479   }
480   void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name,
481                              unsigned KnownArity,
482                              const AbiTagList *AdditionalAbiTags);
483   void mangleUnscopedName(const NamedDecl *ND,
484                           const AbiTagList *AdditionalAbiTags);
485   void mangleUnscopedTemplateName(const TemplateDecl *ND,
486                                   const AbiTagList *AdditionalAbiTags);
487   void mangleUnscopedTemplateName(TemplateName,
488                                   const AbiTagList *AdditionalAbiTags);
489   void mangleSourceName(const IdentifierInfo *II);
490   void mangleSourceNameWithAbiTags(
491       const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
492   void mangleLocalName(const Decl *D,
493                        const AbiTagList *AdditionalAbiTags);
494   void mangleBlockForPrefix(const BlockDecl *Block);
495   void mangleUnqualifiedBlock(const BlockDecl *Block);
496   void mangleLambda(const CXXRecordDecl *Lambda);
497   void mangleNestedName(const NamedDecl *ND, const DeclContext *DC,
498                         const AbiTagList *AdditionalAbiTags,
499                         bool NoFunction=false);
500   void mangleNestedName(const TemplateDecl *TD,
501                         const TemplateArgument *TemplateArgs,
502                         unsigned NumTemplateArgs);
503   void manglePrefix(NestedNameSpecifier *qualifier);
504   void manglePrefix(const DeclContext *DC, bool NoFunction=false);
505   void manglePrefix(QualType type);
506   void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false);
507   void mangleTemplatePrefix(TemplateName Template);
508   bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
509                                       StringRef Prefix = "");
510   void mangleOperatorName(DeclarationName Name, unsigned Arity);
511   void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
512   void mangleVendorQualifier(StringRef qualifier);
513   void mangleQualifiers(Qualifiers Quals);
514   void mangleRefQualifier(RefQualifierKind RefQualifier);
515
516   void mangleObjCMethodName(const ObjCMethodDecl *MD);
517
518   // Declare manglers for every type class.
519 #define ABSTRACT_TYPE(CLASS, PARENT)
520 #define NON_CANONICAL_TYPE(CLASS, PARENT)
521 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
522 #include "clang/AST/TypeNodes.def"
523
524   void mangleType(const TagType*);
525   void mangleType(TemplateName);
526   static StringRef getCallingConvQualifierName(CallingConv CC);
527   void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
528   void mangleExtFunctionInfo(const FunctionType *T);
529   void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
530                               const FunctionDecl *FD = nullptr);
531   void mangleNeonVectorType(const VectorType *T);
532   void mangleAArch64NeonVectorType(const VectorType *T);
533
534   void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
535   void mangleMemberExprBase(const Expr *base, bool isArrow);
536   void mangleMemberExpr(const Expr *base, bool isArrow,
537                         NestedNameSpecifier *qualifier,
538                         NamedDecl *firstQualifierLookup,
539                         DeclarationName name,
540                         unsigned knownArity);
541   void mangleCastExpression(const Expr *E, StringRef CastEncoding);
542   void mangleInitListElements(const InitListExpr *InitList);
543   void mangleExpression(const Expr *E, unsigned Arity = UnknownArity);
544   void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
545   void mangleCXXDtorType(CXXDtorType T);
546
547   void mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
548                           unsigned NumTemplateArgs);
549   void mangleTemplateArgs(const TemplateArgument *TemplateArgs,
550                           unsigned NumTemplateArgs);
551   void mangleTemplateArgs(const TemplateArgumentList &AL);
552   void mangleTemplateArg(TemplateArgument A);
553
554   void mangleTemplateParameter(unsigned Index);
555
556   void mangleFunctionParam(const ParmVarDecl *parm);
557
558   void writeAbiTags(const NamedDecl *ND,
559                     const AbiTagList *AdditionalAbiTags);
560
561   // Returns sorted unique list of ABI tags.
562   AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
563   // Returns sorted unique list of ABI tags.
564   AbiTagList makeVariableTypeTags(const VarDecl *VD);
565 };
566
567 }
568
569 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
570   const FunctionDecl *FD = dyn_cast<FunctionDecl>(D);
571   if (FD) {
572     LanguageLinkage L = FD->getLanguageLinkage();
573     // Overloadable functions need mangling.
574     if (FD->hasAttr<OverloadableAttr>())
575       return true;
576
577     // "main" is not mangled.
578     if (FD->isMain())
579       return false;
580
581     // C++ functions and those whose names are not a simple identifier need
582     // mangling.
583     if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
584       return true;
585
586     // C functions are not mangled.
587     if (L == CLanguageLinkage)
588       return false;
589   }
590
591   // Otherwise, no mangling is done outside C++ mode.
592   if (!getASTContext().getLangOpts().CPlusPlus)
593     return false;
594
595   const VarDecl *VD = dyn_cast<VarDecl>(D);
596   if (VD) {
597     // C variables are not mangled.
598     if (VD->isExternC())
599       return false;
600
601     // Variables at global scope with non-internal linkage are not mangled
602     const DeclContext *DC = getEffectiveDeclContext(D);
603     // Check for extern variable declared locally.
604     if (DC->isFunctionOrMethod() && D->hasLinkage())
605       while (!DC->isNamespace() && !DC->isTranslationUnit())
606         DC = getEffectiveParentContext(DC);
607     if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
608         !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
609         !isa<VarTemplateSpecializationDecl>(D))
610       return false;
611   }
612
613   return true;
614 }
615
616 void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
617                                   const AbiTagList *AdditionalAbiTags) {
618   assert(AbiTags && "require AbiTagState");
619   AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
620 }
621
622 void CXXNameMangler::mangleSourceNameWithAbiTags(
623     const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
624   mangleSourceName(ND->getIdentifier());
625   writeAbiTags(ND, AdditionalAbiTags);
626 }
627
628 void CXXNameMangler::mangle(const NamedDecl *D) {
629   // <mangled-name> ::= _Z <encoding>
630   //            ::= <data name>
631   //            ::= <special-name>
632   Out << "_Z";
633   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
634     mangleFunctionEncoding(FD);
635   else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
636     mangleName(VD);
637   else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D))
638     mangleName(IFD->getAnonField());
639   else
640     mangleName(cast<FieldDecl>(D));
641 }
642
643 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
644   // <encoding> ::= <function name> <bare-function-type>
645
646   // Don't mangle in the type if this isn't a decl we should typically mangle.
647   if (!Context.shouldMangleDeclName(FD)) {
648     mangleName(FD);
649     return;
650   }
651
652   AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
653   if (ReturnTypeAbiTags.empty()) {
654     // There are no tags for return type, the simplest case.
655     mangleName(FD);
656     mangleFunctionEncodingBareType(FD);
657     return;
658   }
659
660   // Mangle function name and encoding to temporary buffer.
661   // We have to output name and encoding to the same mangler to get the same
662   // substitution as it will be in final mangling.
663   SmallString<256> FunctionEncodingBuf;
664   llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
665   CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
666   // Output name of the function.
667   FunctionEncodingMangler.disableDerivedAbiTags();
668   FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
669
670   // Remember length of the function name in the buffer.
671   size_t EncodingPositionStart = FunctionEncodingStream.str().size();
672   FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
673
674   // Get tags from return type that are not present in function name or
675   // encoding.
676   const AbiTagList &UsedAbiTags =
677       FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
678   AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
679   AdditionalAbiTags.erase(
680       std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
681                           UsedAbiTags.begin(), UsedAbiTags.end(),
682                           AdditionalAbiTags.begin()),
683       AdditionalAbiTags.end());
684
685   // Output name with implicit tags and function encoding from temporary buffer.
686   mangleNameWithAbiTags(FD, &AdditionalAbiTags);
687   Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
688 }
689
690 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
691   if (FD->hasAttr<EnableIfAttr>()) {
692     FunctionTypeDepthState Saved = FunctionTypeDepth.push();
693     Out << "Ua9enable_ifI";
694     // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use
695     // it here.
696     for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(),
697                                          E = FD->getAttrs().rend();
698          I != E; ++I) {
699       EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
700       if (!EIA)
701         continue;
702       Out << 'X';
703       mangleExpression(EIA->getCond());
704       Out << 'E';
705     }
706     Out << 'E';
707     FunctionTypeDepth.pop(Saved);
708   }
709
710   // When mangling an inheriting constructor, the bare function type used is
711   // that of the inherited constructor.
712   if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
713     if (auto Inherited = CD->getInheritedConstructor())
714       FD = Inherited.getConstructor();
715
716   // Whether the mangling of a function type includes the return type depends on
717   // the context and the nature of the function. The rules for deciding whether
718   // the return type is included are:
719   //
720   //   1. Template functions (names or types) have return types encoded, with
721   //   the exceptions listed below.
722   //   2. Function types not appearing as part of a function name mangling,
723   //   e.g. parameters, pointer types, etc., have return type encoded, with the
724   //   exceptions listed below.
725   //   3. Non-template function names do not have return types encoded.
726   //
727   // The exceptions mentioned in (1) and (2) above, for which the return type is
728   // never included, are
729   //   1. Constructors.
730   //   2. Destructors.
731   //   3. Conversion operator functions, e.g. operator int.
732   bool MangleReturnType = false;
733   if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
734     if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
735           isa<CXXConversionDecl>(FD)))
736       MangleReturnType = true;
737
738     // Mangle the type of the primary template.
739     FD = PrimaryTemplate->getTemplatedDecl();
740   }
741
742   mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
743                          MangleReturnType, FD);
744 }
745
746 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) {
747   while (isa<LinkageSpecDecl>(DC)) {
748     DC = getEffectiveParentContext(DC);
749   }
750
751   return DC;
752 }
753
754 /// Return whether a given namespace is the 'std' namespace.
755 static bool isStd(const NamespaceDecl *NS) {
756   if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS))
757                                 ->isTranslationUnit())
758     return false;
759   
760   const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
761   return II && II->isStr("std");
762 }
763
764 // isStdNamespace - Return whether a given decl context is a toplevel 'std'
765 // namespace.
766 static bool isStdNamespace(const DeclContext *DC) {
767   if (!DC->isNamespace())
768     return false;
769
770   return isStd(cast<NamespaceDecl>(DC));
771 }
772
773 static const TemplateDecl *
774 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) {
775   // Check if we have a function template.
776   if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
777     if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
778       TemplateArgs = FD->getTemplateSpecializationArgs();
779       return TD;
780     }
781   }
782
783   // Check if we have a class template.
784   if (const ClassTemplateSpecializationDecl *Spec =
785         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
786     TemplateArgs = &Spec->getTemplateArgs();
787     return Spec->getSpecializedTemplate();
788   }
789
790   // Check if we have a variable template.
791   if (const VarTemplateSpecializationDecl *Spec =
792           dyn_cast<VarTemplateSpecializationDecl>(ND)) {
793     TemplateArgs = &Spec->getTemplateArgs();
794     return Spec->getSpecializedTemplate();
795   }
796
797   return nullptr;
798 }
799
800 void CXXNameMangler::mangleName(const NamedDecl *ND) {
801   if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
802     // Variables should have implicit tags from its type.
803     AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
804     if (VariableTypeAbiTags.empty()) {
805       // Simple case no variable type tags.
806       mangleNameWithAbiTags(VD, nullptr);
807       return;
808     }
809
810     // Mangle variable name to null stream to collect tags.
811     llvm::raw_null_ostream NullOutStream;
812     CXXNameMangler VariableNameMangler(*this, NullOutStream);
813     VariableNameMangler.disableDerivedAbiTags();
814     VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
815
816     // Get tags from variable type that are not present in its name.
817     const AbiTagList &UsedAbiTags =
818         VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
819     AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
820     AdditionalAbiTags.erase(
821         std::set_difference(VariableTypeAbiTags.begin(),
822                             VariableTypeAbiTags.end(), UsedAbiTags.begin(),
823                             UsedAbiTags.end(), AdditionalAbiTags.begin()),
824         AdditionalAbiTags.end());
825
826     // Output name with implicit tags.
827     mangleNameWithAbiTags(VD, &AdditionalAbiTags);
828   } else {
829     mangleNameWithAbiTags(ND, nullptr);
830   }
831 }
832
833 void CXXNameMangler::mangleNameWithAbiTags(const NamedDecl *ND,
834                                            const AbiTagList *AdditionalAbiTags) {
835   //  <name> ::= <nested-name>
836   //         ::= <unscoped-name>
837   //         ::= <unscoped-template-name> <template-args>
838   //         ::= <local-name>
839   //
840   const DeclContext *DC = getEffectiveDeclContext(ND);
841
842   // If this is an extern variable declared locally, the relevant DeclContext
843   // is that of the containing namespace, or the translation unit.
844   // FIXME: This is a hack; extern variables declared locally should have
845   // a proper semantic declaration context!
846   if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
847     while (!DC->isNamespace() && !DC->isTranslationUnit())
848       DC = getEffectiveParentContext(DC);
849   else if (GetLocalClassDecl(ND)) {
850     mangleLocalName(ND, AdditionalAbiTags);
851     return;
852   }
853
854   DC = IgnoreLinkageSpecDecls(DC);
855
856   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
857     // Check if we have a template.
858     const TemplateArgumentList *TemplateArgs = nullptr;
859     if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
860       mangleUnscopedTemplateName(TD, AdditionalAbiTags);
861       mangleTemplateArgs(*TemplateArgs);
862       return;
863     }
864
865     mangleUnscopedName(ND, AdditionalAbiTags);
866     return;
867   }
868
869   if (isLocalContainerContext(DC)) {
870     mangleLocalName(ND, AdditionalAbiTags);
871     return;
872   }
873
874   mangleNestedName(ND, DC, AdditionalAbiTags);
875 }
876
877 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
878                                         const TemplateArgument *TemplateArgs,
879                                         unsigned NumTemplateArgs) {
880   const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD));
881
882   if (DC->isTranslationUnit() || isStdNamespace(DC)) {
883     mangleUnscopedTemplateName(TD, nullptr);
884     mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
885   } else {
886     mangleNestedName(TD, TemplateArgs, NumTemplateArgs);
887   }
888 }
889
890 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND,
891                                         const AbiTagList *AdditionalAbiTags) {
892   //  <unscoped-name> ::= <unqualified-name>
893   //                  ::= St <unqualified-name>   # ::std::
894
895   if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND))))
896     Out << "St";
897
898   mangleUnqualifiedName(ND, AdditionalAbiTags);
899 }
900
901 void CXXNameMangler::mangleUnscopedTemplateName(
902     const TemplateDecl *ND, const AbiTagList *AdditionalAbiTags) {
903   //     <unscoped-template-name> ::= <unscoped-name>
904   //                              ::= <substitution>
905   if (mangleSubstitution(ND))
906     return;
907
908   // <template-template-param> ::= <template-param>
909   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
910     assert(!AdditionalAbiTags &&
911            "template template param cannot have abi tags");
912     mangleTemplateParameter(TTP->getIndex());
913   } else if (isa<BuiltinTemplateDecl>(ND)) {
914     mangleUnscopedName(ND, AdditionalAbiTags);
915   } else {
916     mangleUnscopedName(ND->getTemplatedDecl(), AdditionalAbiTags);
917   }
918
919   addSubstitution(ND);
920 }
921
922 void CXXNameMangler::mangleUnscopedTemplateName(
923     TemplateName Template, const AbiTagList *AdditionalAbiTags) {
924   //     <unscoped-template-name> ::= <unscoped-name>
925   //                              ::= <substitution>
926   if (TemplateDecl *TD = Template.getAsTemplateDecl())
927     return mangleUnscopedTemplateName(TD, AdditionalAbiTags);
928   
929   if (mangleSubstitution(Template))
930     return;
931
932   assert(!AdditionalAbiTags &&
933          "dependent template name cannot have abi tags");
934
935   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
936   assert(Dependent && "Not a dependent template name?");
937   if (const IdentifierInfo *Id = Dependent->getIdentifier())
938     mangleSourceName(Id);
939   else
940     mangleOperatorName(Dependent->getOperator(), UnknownArity);
941
942   addSubstitution(Template);
943 }
944
945 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
946   // ABI:
947   //   Floating-point literals are encoded using a fixed-length
948   //   lowercase hexadecimal string corresponding to the internal
949   //   representation (IEEE on Itanium), high-order bytes first,
950   //   without leading zeroes. For example: "Lf bf800000 E" is -1.0f
951   //   on Itanium.
952   // The 'without leading zeroes' thing seems to be an editorial
953   // mistake; see the discussion on cxx-abi-dev beginning on
954   // 2012-01-16.
955
956   // Our requirements here are just barely weird enough to justify
957   // using a custom algorithm instead of post-processing APInt::toString().
958
959   llvm::APInt valueBits = f.bitcastToAPInt();
960   unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
961   assert(numCharacters != 0);
962
963   // Allocate a buffer of the right number of characters.
964   SmallVector<char, 20> buffer(numCharacters);
965
966   // Fill the buffer left-to-right.
967   for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
968     // The bit-index of the next hex digit.
969     unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
970
971     // Project out 4 bits starting at 'digitIndex'.
972     llvm::integerPart hexDigit
973       = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth];
974     hexDigit >>= (digitBitIndex % llvm::integerPartWidth);
975     hexDigit &= 0xF;
976
977     // Map that over to a lowercase hex digit.
978     static const char charForHex[16] = {
979       '0', '1', '2', '3', '4', '5', '6', '7',
980       '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
981     };
982     buffer[stringIndex] = charForHex[hexDigit];
983   }
984
985   Out.write(buffer.data(), numCharacters);
986 }
987
988 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
989   if (Value.isSigned() && Value.isNegative()) {
990     Out << 'n';
991     Value.abs().print(Out, /*signed*/ false);
992   } else {
993     Value.print(Out, /*signed*/ false);
994   }
995 }
996
997 void CXXNameMangler::mangleNumber(int64_t Number) {
998   //  <number> ::= [n] <non-negative decimal integer>
999   if (Number < 0) {
1000     Out << 'n';
1001     Number = -Number;
1002   }
1003
1004   Out << Number;
1005 }
1006
1007 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
1008   //  <call-offset>  ::= h <nv-offset> _
1009   //                 ::= v <v-offset> _
1010   //  <nv-offset>    ::= <offset number>        # non-virtual base override
1011   //  <v-offset>     ::= <offset number> _ <virtual offset number>
1012   //                      # virtual base override, with vcall offset
1013   if (!Virtual) {
1014     Out << 'h';
1015     mangleNumber(NonVirtual);
1016     Out << '_';
1017     return;
1018   }
1019
1020   Out << 'v';
1021   mangleNumber(NonVirtual);
1022   Out << '_';
1023   mangleNumber(Virtual);
1024   Out << '_';
1025 }
1026
1027 void CXXNameMangler::manglePrefix(QualType type) {
1028   if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
1029     if (!mangleSubstitution(QualType(TST, 0))) {
1030       mangleTemplatePrefix(TST->getTemplateName());
1031         
1032       // FIXME: GCC does not appear to mangle the template arguments when
1033       // the template in question is a dependent template name. Should we
1034       // emulate that badness?
1035       mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1036       addSubstitution(QualType(TST, 0));
1037     }
1038   } else if (const auto *DTST =
1039                  type->getAs<DependentTemplateSpecializationType>()) {
1040     if (!mangleSubstitution(QualType(DTST, 0))) {
1041       TemplateName Template = getASTContext().getDependentTemplateName(
1042           DTST->getQualifier(), DTST->getIdentifier());
1043       mangleTemplatePrefix(Template);
1044
1045       // FIXME: GCC does not appear to mangle the template arguments when
1046       // the template in question is a dependent template name. Should we
1047       // emulate that badness?
1048       mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1049       addSubstitution(QualType(DTST, 0));
1050     }
1051   } else {
1052     // We use the QualType mangle type variant here because it handles
1053     // substitutions.
1054     mangleType(type);
1055   }
1056 }
1057
1058 /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
1059 ///
1060 /// \param recursive - true if this is being called recursively,
1061 ///   i.e. if there is more prefix "to the right".
1062 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
1063                                             bool recursive) {
1064
1065   // x, ::x
1066   // <unresolved-name> ::= [gs] <base-unresolved-name>
1067
1068   // T::x / decltype(p)::x
1069   // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
1070
1071   // T::N::x /decltype(p)::N::x
1072   // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
1073   //                       <base-unresolved-name>
1074
1075   // A::x, N::y, A<T>::z; "gs" means leading "::"
1076   // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
1077   //                       <base-unresolved-name>
1078
1079   switch (qualifier->getKind()) {
1080   case NestedNameSpecifier::Global:
1081     Out << "gs";
1082
1083     // We want an 'sr' unless this is the entire NNS.
1084     if (recursive)
1085       Out << "sr";
1086
1087     // We never want an 'E' here.
1088     return;
1089
1090   case NestedNameSpecifier::Super:
1091     llvm_unreachable("Can't mangle __super specifier");
1092
1093   case NestedNameSpecifier::Namespace:
1094     if (qualifier->getPrefix())
1095       mangleUnresolvedPrefix(qualifier->getPrefix(),
1096                              /*recursive*/ true);
1097     else
1098       Out << "sr";
1099     mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
1100     break;
1101   case NestedNameSpecifier::NamespaceAlias:
1102     if (qualifier->getPrefix())
1103       mangleUnresolvedPrefix(qualifier->getPrefix(),
1104                              /*recursive*/ true);
1105     else
1106       Out << "sr";
1107     mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
1108     break;
1109
1110   case NestedNameSpecifier::TypeSpec:
1111   case NestedNameSpecifier::TypeSpecWithTemplate: {
1112     const Type *type = qualifier->getAsType();
1113
1114     // We only want to use an unresolved-type encoding if this is one of:
1115     //   - a decltype
1116     //   - a template type parameter
1117     //   - a template template parameter with arguments
1118     // In all of these cases, we should have no prefix.
1119     if (qualifier->getPrefix()) {
1120       mangleUnresolvedPrefix(qualifier->getPrefix(),
1121                              /*recursive*/ true);
1122     } else {
1123       // Otherwise, all the cases want this.
1124       Out << "sr";
1125     }
1126
1127     if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
1128       return;
1129
1130     break;
1131   }
1132
1133   case NestedNameSpecifier::Identifier:
1134     // Member expressions can have these without prefixes.
1135     if (qualifier->getPrefix())
1136       mangleUnresolvedPrefix(qualifier->getPrefix(),
1137                              /*recursive*/ true);
1138     else
1139       Out << "sr";
1140
1141     mangleSourceName(qualifier->getAsIdentifier());
1142     // An Identifier has no type information, so we can't emit abi tags for it.
1143     break;
1144   }
1145
1146   // If this was the innermost part of the NNS, and we fell out to
1147   // here, append an 'E'.
1148   if (!recursive)
1149     Out << 'E';
1150 }
1151
1152 /// Mangle an unresolved-name, which is generally used for names which
1153 /// weren't resolved to specific entities.
1154 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier,
1155                                           DeclarationName name,
1156                                           unsigned knownArity) {
1157   if (qualifier) mangleUnresolvedPrefix(qualifier);
1158   switch (name.getNameKind()) {
1159     // <base-unresolved-name> ::= <simple-id>
1160     case DeclarationName::Identifier:
1161       mangleSourceName(name.getAsIdentifierInfo());
1162       break;
1163     // <base-unresolved-name> ::= dn <destructor-name>
1164     case DeclarationName::CXXDestructorName:
1165       Out << "dn";
1166       mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
1167       break;
1168     // <base-unresolved-name> ::= on <operator-name>
1169     case DeclarationName::CXXConversionFunctionName:
1170     case DeclarationName::CXXLiteralOperatorName:
1171     case DeclarationName::CXXOperatorName:
1172       Out << "on";
1173       mangleOperatorName(name, knownArity);
1174       break;
1175     case DeclarationName::CXXConstructorName:
1176       llvm_unreachable("Can't mangle a constructor name!");
1177     case DeclarationName::CXXUsingDirective:
1178       llvm_unreachable("Can't mangle a using directive name!");
1179     case DeclarationName::ObjCMultiArgSelector:
1180     case DeclarationName::ObjCOneArgSelector:
1181     case DeclarationName::ObjCZeroArgSelector:
1182       llvm_unreachable("Can't mangle Objective-C selector names here!");
1183   }
1184 }
1185
1186 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
1187                                            DeclarationName Name,
1188                                            unsigned KnownArity,
1189                                            const AbiTagList *AdditionalAbiTags) {
1190   unsigned Arity = KnownArity;
1191   //  <unqualified-name> ::= <operator-name>
1192   //                     ::= <ctor-dtor-name>
1193   //                     ::= <source-name>
1194   switch (Name.getNameKind()) {
1195   case DeclarationName::Identifier: {
1196     if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1197       // We must avoid conflicts between internally- and externally-
1198       // linked variable and function declaration names in the same TU:
1199       //   void test() { extern void foo(); }
1200       //   static void foo();
1201       // This naming convention is the same as that followed by GCC,
1202       // though it shouldn't actually matter.
1203       if (ND && ND->getFormalLinkage() == InternalLinkage &&
1204           getEffectiveDeclContext(ND)->isFileContext())
1205         Out << 'L';
1206
1207       mangleSourceName(II);
1208       writeAbiTags(ND, AdditionalAbiTags);
1209       break;
1210     }
1211
1212     // Otherwise, an anonymous entity.  We must have a declaration.
1213     assert(ND && "mangling empty name without declaration");
1214
1215     if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1216       if (NS->isAnonymousNamespace()) {
1217         // This is how gcc mangles these names.
1218         Out << "12_GLOBAL__N_1";
1219         break;
1220       }
1221     }
1222
1223     if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1224       // We must have an anonymous union or struct declaration.
1225       const RecordDecl *RD =
1226         cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl());
1227
1228       // Itanium C++ ABI 5.1.2:
1229       //
1230       //   For the purposes of mangling, the name of an anonymous union is
1231       //   considered to be the name of the first named data member found by a
1232       //   pre-order, depth-first, declaration-order walk of the data members of
1233       //   the anonymous union. If there is no such data member (i.e., if all of
1234       //   the data members in the union are unnamed), then there is no way for
1235       //   a program to refer to the anonymous union, and there is therefore no
1236       //   need to mangle its name.
1237       assert(RD->isAnonymousStructOrUnion()
1238              && "Expected anonymous struct or union!");
1239       const FieldDecl *FD = RD->findFirstNamedDataMember();
1240
1241       // It's actually possible for various reasons for us to get here
1242       // with an empty anonymous struct / union.  Fortunately, it
1243       // doesn't really matter what name we generate.
1244       if (!FD) break;
1245       assert(FD->getIdentifier() && "Data member name isn't an identifier!");
1246
1247       mangleSourceName(FD->getIdentifier());
1248       // Not emitting abi tags: internal name anyway.
1249       break;
1250     }
1251
1252     // Class extensions have no name as a category, and it's possible
1253     // for them to be the semantic parent of certain declarations
1254     // (primarily, tag decls defined within declarations).  Such
1255     // declarations will always have internal linkage, so the name
1256     // doesn't really matter, but we shouldn't crash on them.  For
1257     // safety, just handle all ObjC containers here.
1258     if (isa<ObjCContainerDecl>(ND))
1259       break;
1260     
1261     // We must have an anonymous struct.
1262     const TagDecl *TD = cast<TagDecl>(ND);
1263     if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1264       assert(TD->getDeclContext() == D->getDeclContext() &&
1265              "Typedef should not be in another decl context!");
1266       assert(D->getDeclName().getAsIdentifierInfo() &&
1267              "Typedef was not named!");
1268       mangleSourceName(D->getDeclName().getAsIdentifierInfo());
1269       assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
1270       // Explicit abi tags are still possible; take from underlying type, not
1271       // from typedef.
1272       writeAbiTags(TD, nullptr);
1273       break;
1274     }
1275
1276     // <unnamed-type-name> ::= <closure-type-name>
1277     // 
1278     // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
1279     // <lambda-sig> ::= <parameter-type>+   # Parameter types or 'v' for 'void'.
1280     if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1281       if (Record->isLambda() && Record->getLambdaManglingNumber()) {
1282         assert(!AdditionalAbiTags &&
1283                "Lambda type cannot have additional abi tags");
1284         mangleLambda(Record);
1285         break;
1286       }
1287     }
1288
1289     if (TD->isExternallyVisible()) {
1290       unsigned UnnamedMangle = getASTContext().getManglingNumber(TD);
1291       Out << "Ut";
1292       if (UnnamedMangle > 1)
1293         Out << UnnamedMangle - 2;
1294       Out << '_';
1295       writeAbiTags(TD, AdditionalAbiTags);
1296       break;
1297     }
1298
1299     // Get a unique id for the anonymous struct. If it is not a real output
1300     // ID doesn't matter so use fake one.
1301     unsigned AnonStructId = NullOut ? 0 : Context.getAnonymousStructId(TD);
1302
1303     // Mangle it as a source name in the form
1304     // [n] $_<id>
1305     // where n is the length of the string.
1306     SmallString<8> Str;
1307     Str += "$_";
1308     Str += llvm::utostr(AnonStructId);
1309
1310     Out << Str.size();
1311     Out << Str;
1312     break;
1313   }
1314
1315   case DeclarationName::ObjCZeroArgSelector:
1316   case DeclarationName::ObjCOneArgSelector:
1317   case DeclarationName::ObjCMultiArgSelector:
1318     llvm_unreachable("Can't mangle Objective-C selector names here!");
1319
1320   case DeclarationName::CXXConstructorName: {
1321     const CXXRecordDecl *InheritedFrom = nullptr;
1322     const TemplateArgumentList *InheritedTemplateArgs = nullptr;
1323     if (auto Inherited =
1324             cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
1325       InheritedFrom = Inherited.getConstructor()->getParent();
1326       InheritedTemplateArgs =
1327           Inherited.getConstructor()->getTemplateSpecializationArgs();
1328     }
1329
1330     if (ND == Structor)
1331       // If the named decl is the C++ constructor we're mangling, use the type
1332       // we were given.
1333       mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
1334     else
1335       // Otherwise, use the complete constructor name. This is relevant if a
1336       // class with a constructor is declared within a constructor.
1337       mangleCXXCtorType(Ctor_Complete, InheritedFrom);
1338
1339     // FIXME: The template arguments are part of the enclosing prefix or
1340     // nested-name, but it's more convenient to mangle them here.
1341     if (InheritedTemplateArgs)
1342       mangleTemplateArgs(*InheritedTemplateArgs);
1343
1344     writeAbiTags(ND, AdditionalAbiTags);
1345     break;
1346   }
1347
1348   case DeclarationName::CXXDestructorName:
1349     if (ND == Structor)
1350       // If the named decl is the C++ destructor we're mangling, use the type we
1351       // were given.
1352       mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1353     else
1354       // Otherwise, use the complete destructor name. This is relevant if a
1355       // class with a destructor is declared within a destructor.
1356       mangleCXXDtorType(Dtor_Complete);
1357     writeAbiTags(ND, AdditionalAbiTags);
1358     break;
1359
1360   case DeclarationName::CXXOperatorName:
1361     if (ND && Arity == UnknownArity) {
1362       Arity = cast<FunctionDecl>(ND)->getNumParams();
1363
1364       // If we have a member function, we need to include the 'this' pointer.
1365       if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
1366         if (!MD->isStatic())
1367           Arity++;
1368     }
1369   // FALLTHROUGH
1370   case DeclarationName::CXXConversionFunctionName:
1371   case DeclarationName::CXXLiteralOperatorName:
1372     mangleOperatorName(Name, Arity);
1373     writeAbiTags(ND, AdditionalAbiTags);
1374     break;
1375
1376   case DeclarationName::CXXUsingDirective:
1377     llvm_unreachable("Can't mangle a using directive name!");
1378   }
1379 }
1380
1381 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
1382   // <source-name> ::= <positive length number> <identifier>
1383   // <number> ::= [n] <non-negative decimal integer>
1384   // <identifier> ::= <unqualified source code identifier>
1385   Out << II->getLength() << II->getName();
1386 }
1387
1388 void CXXNameMangler::mangleNestedName(const NamedDecl *ND,
1389                                       const DeclContext *DC,
1390                                       const AbiTagList *AdditionalAbiTags,
1391                                       bool NoFunction) {
1392   // <nested-name> 
1393   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
1394   //   ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> 
1395   //       <template-args> E
1396
1397   Out << 'N';
1398   if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
1399     Qualifiers MethodQuals =
1400         Qualifiers::fromCVRMask(Method->getTypeQualifiers());
1401     // We do not consider restrict a distinguishing attribute for overloading
1402     // purposes so we must not mangle it.
1403     MethodQuals.removeRestrict();
1404     mangleQualifiers(MethodQuals);
1405     mangleRefQualifier(Method->getRefQualifier());
1406   }
1407   
1408   // Check if we have a template.
1409   const TemplateArgumentList *TemplateArgs = nullptr;
1410   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1411     mangleTemplatePrefix(TD, NoFunction);
1412     mangleTemplateArgs(*TemplateArgs);
1413   }
1414   else {
1415     manglePrefix(DC, NoFunction);
1416     mangleUnqualifiedName(ND, AdditionalAbiTags);
1417   }
1418
1419   Out << 'E';
1420 }
1421 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
1422                                       const TemplateArgument *TemplateArgs,
1423                                       unsigned NumTemplateArgs) {
1424   // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
1425
1426   Out << 'N';
1427
1428   mangleTemplatePrefix(TD);
1429   mangleTemplateArgs(TemplateArgs, NumTemplateArgs);
1430
1431   Out << 'E';
1432 }
1433
1434 void CXXNameMangler::mangleLocalName(const Decl *D,
1435                                      const AbiTagList *AdditionalAbiTags) {
1436   // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
1437   //              := Z <function encoding> E s [<discriminator>]
1438   // <local-name> := Z <function encoding> E d [ <parameter number> ] 
1439   //                 _ <entity name>
1440   // <discriminator> := _ <non-negative number>
1441   assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
1442   const RecordDecl *RD = GetLocalClassDecl(D);
1443   const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D);
1444
1445   Out << 'Z';
1446
1447   {
1448     AbiTagState LocalAbiTags(AbiTags);
1449
1450     if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
1451       mangleObjCMethodName(MD);
1452     else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
1453       mangleBlockForPrefix(BD);
1454     else
1455       mangleFunctionEncoding(cast<FunctionDecl>(DC));
1456
1457     // Implicit ABI tags (from namespace) are not available in the following
1458     // entity; reset to actually emitted tags, which are available.
1459     LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
1460   }
1461
1462   Out << 'E';
1463
1464   // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
1465   // be a bug that is fixed in trunk.
1466
1467   if (RD) {
1468     // The parameter number is omitted for the last parameter, 0 for the 
1469     // second-to-last parameter, 1 for the third-to-last parameter, etc. The 
1470     // <entity name> will of course contain a <closure-type-name>: Its 
1471     // numbering will be local to the particular argument in which it appears
1472     // -- other default arguments do not affect its encoding.
1473     const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1474     if (CXXRD->isLambda()) {
1475       if (const ParmVarDecl *Parm
1476               = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
1477         if (const FunctionDecl *Func
1478               = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1479           Out << 'd';
1480           unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1481           if (Num > 1)
1482             mangleNumber(Num - 2);
1483           Out << '_';
1484         }
1485       }
1486     }
1487     
1488     // Mangle the name relative to the closest enclosing function.
1489     // equality ok because RD derived from ND above
1490     if (D == RD)  {
1491       mangleUnqualifiedName(RD, AdditionalAbiTags);
1492     } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1493       manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/);
1494       assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1495       mangleUnqualifiedBlock(BD);
1496     } else {
1497       const NamedDecl *ND = cast<NamedDecl>(D);
1498       mangleNestedName(ND, getEffectiveDeclContext(ND), AdditionalAbiTags,
1499                        true /*NoFunction*/);
1500     }
1501   } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
1502     // Mangle a block in a default parameter; see above explanation for
1503     // lambdas.
1504     if (const ParmVarDecl *Parm
1505             = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
1506       if (const FunctionDecl *Func
1507             = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
1508         Out << 'd';
1509         unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
1510         if (Num > 1)
1511           mangleNumber(Num - 2);
1512         Out << '_';
1513       }
1514     }
1515
1516     assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
1517     mangleUnqualifiedBlock(BD);
1518   } else {
1519     mangleUnqualifiedName(cast<NamedDecl>(D), AdditionalAbiTags);
1520   }
1521
1522   if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
1523     unsigned disc;
1524     if (Context.getNextDiscriminator(ND, disc)) {
1525       if (disc < 10)
1526         Out << '_' << disc;
1527       else
1528         Out << "__" << disc << '_';
1529     }
1530   }
1531 }
1532
1533 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
1534   if (GetLocalClassDecl(Block)) {
1535     mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1536     return;
1537   }
1538   const DeclContext *DC = getEffectiveDeclContext(Block);
1539   if (isLocalContainerContext(DC)) {
1540     mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
1541     return;
1542   }
1543   manglePrefix(getEffectiveDeclContext(Block));
1544   mangleUnqualifiedBlock(Block);
1545 }
1546
1547 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
1548   if (Decl *Context = Block->getBlockManglingContextDecl()) {
1549     if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1550         Context->getDeclContext()->isRecord()) {
1551       const auto *ND = cast<NamedDecl>(Context);
1552       if (ND->getIdentifier()) {
1553         mangleSourceNameWithAbiTags(ND);
1554         Out << 'M';
1555       }
1556     }
1557   }
1558
1559   // If we have a block mangling number, use it.
1560   unsigned Number = Block->getBlockManglingNumber();
1561   // Otherwise, just make up a number. It doesn't matter what it is because
1562   // the symbol in question isn't externally visible.
1563   if (!Number)
1564     Number = Context.getBlockId(Block, false);
1565   Out << "Ub";
1566   if (Number > 0)
1567     Out << Number - 1;
1568   Out << '_';
1569 }
1570
1571 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
1572   // If the context of a closure type is an initializer for a class member 
1573   // (static or nonstatic), it is encoded in a qualified name with a final 
1574   // <prefix> of the form:
1575   //
1576   //   <data-member-prefix> := <member source-name> M
1577   //
1578   // Technically, the data-member-prefix is part of the <prefix>. However,
1579   // since a closure type will always be mangled with a prefix, it's easier
1580   // to emit that last part of the prefix here.
1581   if (Decl *Context = Lambda->getLambdaContextDecl()) {
1582     if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
1583         Context->getDeclContext()->isRecord()) {
1584       if (const IdentifierInfo *Name
1585             = cast<NamedDecl>(Context)->getIdentifier()) {
1586         mangleSourceName(Name);
1587         Out << 'M';
1588       }
1589     }
1590   }
1591
1592   Out << "Ul";
1593   const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()->
1594                                    getAs<FunctionProtoType>();
1595   mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
1596                          Lambda->getLambdaStaticInvoker());
1597   Out << "E";
1598   
1599   // The number is omitted for the first closure type with a given 
1600   // <lambda-sig> in a given context; it is n-2 for the nth closure type 
1601   // (in lexical order) with that same <lambda-sig> and context.
1602   //
1603   // The AST keeps track of the number for us.
1604   unsigned Number = Lambda->getLambdaManglingNumber();
1605   assert(Number > 0 && "Lambda should be mangled as an unnamed class");
1606   if (Number > 1)
1607     mangleNumber(Number - 2);
1608   Out << '_';  
1609 }
1610
1611 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
1612   switch (qualifier->getKind()) {
1613   case NestedNameSpecifier::Global:
1614     // nothing
1615     return;
1616
1617   case NestedNameSpecifier::Super:
1618     llvm_unreachable("Can't mangle __super specifier");
1619
1620   case NestedNameSpecifier::Namespace:
1621     mangleName(qualifier->getAsNamespace());
1622     return;
1623
1624   case NestedNameSpecifier::NamespaceAlias:
1625     mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
1626     return;
1627
1628   case NestedNameSpecifier::TypeSpec:
1629   case NestedNameSpecifier::TypeSpecWithTemplate:
1630     manglePrefix(QualType(qualifier->getAsType(), 0));
1631     return;
1632
1633   case NestedNameSpecifier::Identifier:
1634     // Member expressions can have these without prefixes, but that
1635     // should end up in mangleUnresolvedPrefix instead.
1636     assert(qualifier->getPrefix());
1637     manglePrefix(qualifier->getPrefix());
1638
1639     mangleSourceName(qualifier->getAsIdentifier());
1640     return;
1641   }
1642
1643   llvm_unreachable("unexpected nested name specifier");
1644 }
1645
1646 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
1647   //  <prefix> ::= <prefix> <unqualified-name>
1648   //           ::= <template-prefix> <template-args>
1649   //           ::= <template-param>
1650   //           ::= # empty
1651   //           ::= <substitution>
1652
1653   DC = IgnoreLinkageSpecDecls(DC);
1654
1655   if (DC->isTranslationUnit())
1656     return;
1657
1658   if (NoFunction && isLocalContainerContext(DC))
1659     return;
1660
1661   assert(!isLocalContainerContext(DC));
1662
1663   const NamedDecl *ND = cast<NamedDecl>(DC);  
1664   if (mangleSubstitution(ND))
1665     return;
1666   
1667   // Check if we have a template.
1668   const TemplateArgumentList *TemplateArgs = nullptr;
1669   if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) {
1670     mangleTemplatePrefix(TD);
1671     mangleTemplateArgs(*TemplateArgs);
1672   } else {
1673     manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1674     mangleUnqualifiedName(ND, nullptr);
1675   }
1676
1677   addSubstitution(ND);
1678 }
1679
1680 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
1681   // <template-prefix> ::= <prefix> <template unqualified-name>
1682   //                   ::= <template-param>
1683   //                   ::= <substitution>
1684   if (TemplateDecl *TD = Template.getAsTemplateDecl())
1685     return mangleTemplatePrefix(TD);
1686
1687   if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName())
1688     manglePrefix(Qualified->getQualifier());
1689
1690   if (OverloadedTemplateStorage *Overloaded
1691                                       = Template.getAsOverloadedTemplate()) {
1692     mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(),
1693                           UnknownArity, nullptr);
1694     return;
1695   }
1696
1697   DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
1698   assert(Dependent && "Unknown template name kind?");
1699   if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
1700     manglePrefix(Qualifier);
1701   mangleUnscopedTemplateName(Template, /* AdditionalAbiTags */ nullptr);
1702 }
1703
1704 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND,
1705                                           bool NoFunction) {
1706   // <template-prefix> ::= <prefix> <template unqualified-name>
1707   //                   ::= <template-param>
1708   //                   ::= <substitution>
1709   // <template-template-param> ::= <template-param>
1710   //                               <substitution>
1711
1712   if (mangleSubstitution(ND))
1713     return;
1714
1715   // <template-template-param> ::= <template-param>
1716   if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
1717     mangleTemplateParameter(TTP->getIndex());
1718   } else {
1719     manglePrefix(getEffectiveDeclContext(ND), NoFunction);
1720     if (isa<BuiltinTemplateDecl>(ND))
1721       mangleUnqualifiedName(ND, nullptr);
1722     else
1723       mangleUnqualifiedName(ND->getTemplatedDecl(), nullptr);
1724   }
1725
1726   addSubstitution(ND);
1727 }
1728
1729 /// Mangles a template name under the production <type>.  Required for
1730 /// template template arguments.
1731 ///   <type> ::= <class-enum-type>
1732 ///          ::= <template-param>
1733 ///          ::= <substitution>
1734 void CXXNameMangler::mangleType(TemplateName TN) {
1735   if (mangleSubstitution(TN))
1736     return;
1737
1738   TemplateDecl *TD = nullptr;
1739
1740   switch (TN.getKind()) {
1741   case TemplateName::QualifiedTemplate:
1742     TD = TN.getAsQualifiedTemplateName()->getTemplateDecl();
1743     goto HaveDecl;
1744
1745   case TemplateName::Template:
1746     TD = TN.getAsTemplateDecl();
1747     goto HaveDecl;
1748
1749   HaveDecl:
1750     if (isa<TemplateTemplateParmDecl>(TD))
1751       mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex());
1752     else
1753       mangleName(TD);
1754     break;
1755
1756   case TemplateName::OverloadedTemplate:
1757     llvm_unreachable("can't mangle an overloaded template name as a <type>");
1758
1759   case TemplateName::DependentTemplate: {
1760     const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
1761     assert(Dependent->isIdentifier());
1762
1763     // <class-enum-type> ::= <name>
1764     // <name> ::= <nested-name>
1765     mangleUnresolvedPrefix(Dependent->getQualifier());
1766     mangleSourceName(Dependent->getIdentifier());
1767     break;
1768   }
1769
1770   case TemplateName::SubstTemplateTemplateParm: {
1771     // Substituted template parameters are mangled as the substituted
1772     // template.  This will check for the substitution twice, which is
1773     // fine, but we have to return early so that we don't try to *add*
1774     // the substitution twice.
1775     SubstTemplateTemplateParmStorage *subst
1776       = TN.getAsSubstTemplateTemplateParm();
1777     mangleType(subst->getReplacement());
1778     return;
1779   }
1780
1781   case TemplateName::SubstTemplateTemplateParmPack: {
1782     // FIXME: not clear how to mangle this!
1783     // template <template <class> class T...> class A {
1784     //   template <template <class> class U...> void foo(B<T,U> x...);
1785     // };
1786     Out << "_SUBSTPACK_";
1787     break;
1788   }
1789   }
1790
1791   addSubstitution(TN);
1792 }
1793
1794 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
1795                                                     StringRef Prefix) {
1796   // Only certain other types are valid as prefixes;  enumerate them.
1797   switch (Ty->getTypeClass()) {
1798   case Type::Builtin:
1799   case Type::Complex:
1800   case Type::Adjusted:
1801   case Type::Decayed:
1802   case Type::Pointer:
1803   case Type::BlockPointer:
1804   case Type::LValueReference:
1805   case Type::RValueReference:
1806   case Type::MemberPointer:
1807   case Type::ConstantArray:
1808   case Type::IncompleteArray:
1809   case Type::VariableArray:
1810   case Type::DependentSizedArray:
1811   case Type::DependentSizedExtVector:
1812   case Type::Vector:
1813   case Type::ExtVector:
1814   case Type::FunctionProto:
1815   case Type::FunctionNoProto:
1816   case Type::Paren:
1817   case Type::Attributed:
1818   case Type::Auto:
1819   case Type::PackExpansion:
1820   case Type::ObjCObject:
1821   case Type::ObjCInterface:
1822   case Type::ObjCObjectPointer:
1823   case Type::Atomic:
1824   case Type::Pipe:
1825     llvm_unreachable("type is illegal as a nested name specifier");
1826
1827   case Type::SubstTemplateTypeParmPack:
1828     // FIXME: not clear how to mangle this!
1829     // template <class T...> class A {
1830     //   template <class U...> void foo(decltype(T::foo(U())) x...);
1831     // };
1832     Out << "_SUBSTPACK_";
1833     break;
1834
1835   // <unresolved-type> ::= <template-param>
1836   //                   ::= <decltype>
1837   //                   ::= <template-template-param> <template-args>
1838   // (this last is not official yet)
1839   case Type::TypeOfExpr:
1840   case Type::TypeOf:
1841   case Type::Decltype:
1842   case Type::TemplateTypeParm:
1843   case Type::UnaryTransform:
1844   case Type::SubstTemplateTypeParm:
1845   unresolvedType:
1846     // Some callers want a prefix before the mangled type.
1847     Out << Prefix;
1848
1849     // This seems to do everything we want.  It's not really
1850     // sanctioned for a substituted template parameter, though.
1851     mangleType(Ty);
1852
1853     // We never want to print 'E' directly after an unresolved-type,
1854     // so we return directly.
1855     return true;
1856
1857   case Type::Typedef:
1858     mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
1859     break;
1860
1861   case Type::UnresolvedUsing:
1862     mangleSourceNameWithAbiTags(
1863         cast<UnresolvedUsingType>(Ty)->getDecl());
1864     break;
1865
1866   case Type::Enum:
1867   case Type::Record:
1868     mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
1869     break;
1870
1871   case Type::TemplateSpecialization: {
1872     const TemplateSpecializationType *TST =
1873         cast<TemplateSpecializationType>(Ty);
1874     TemplateName TN = TST->getTemplateName();
1875     switch (TN.getKind()) {
1876     case TemplateName::Template:
1877     case TemplateName::QualifiedTemplate: {
1878       TemplateDecl *TD = TN.getAsTemplateDecl();
1879
1880       // If the base is a template template parameter, this is an
1881       // unresolved type.
1882       assert(TD && "no template for template specialization type");
1883       if (isa<TemplateTemplateParmDecl>(TD))
1884         goto unresolvedType;
1885
1886       mangleSourceNameWithAbiTags(TD);
1887       break;
1888     }
1889
1890     case TemplateName::OverloadedTemplate:
1891     case TemplateName::DependentTemplate:
1892       llvm_unreachable("invalid base for a template specialization type");
1893
1894     case TemplateName::SubstTemplateTemplateParm: {
1895       SubstTemplateTemplateParmStorage *subst =
1896           TN.getAsSubstTemplateTemplateParm();
1897       mangleExistingSubstitution(subst->getReplacement());
1898       break;
1899     }
1900
1901     case TemplateName::SubstTemplateTemplateParmPack: {
1902       // FIXME: not clear how to mangle this!
1903       // template <template <class U> class T...> class A {
1904       //   template <class U...> void foo(decltype(T<U>::foo) x...);
1905       // };
1906       Out << "_SUBSTPACK_";
1907       break;
1908     }
1909     }
1910
1911     mangleTemplateArgs(TST->getArgs(), TST->getNumArgs());
1912     break;
1913   }
1914
1915   case Type::InjectedClassName:
1916     mangleSourceNameWithAbiTags(
1917         cast<InjectedClassNameType>(Ty)->getDecl());
1918     break;
1919
1920   case Type::DependentName:
1921     mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
1922     break;
1923
1924   case Type::DependentTemplateSpecialization: {
1925     const DependentTemplateSpecializationType *DTST =
1926         cast<DependentTemplateSpecializationType>(Ty);
1927     mangleSourceName(DTST->getIdentifier());
1928     mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs());
1929     break;
1930   }
1931
1932   case Type::Elaborated:
1933     return mangleUnresolvedTypeOrSimpleId(
1934         cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
1935   }
1936
1937   return false;
1938 }
1939
1940 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
1941   switch (Name.getNameKind()) {
1942   case DeclarationName::CXXConstructorName:
1943   case DeclarationName::CXXDestructorName:
1944   case DeclarationName::CXXUsingDirective:
1945   case DeclarationName::Identifier:
1946   case DeclarationName::ObjCMultiArgSelector:
1947   case DeclarationName::ObjCOneArgSelector:
1948   case DeclarationName::ObjCZeroArgSelector:
1949     llvm_unreachable("Not an operator name");
1950
1951   case DeclarationName::CXXConversionFunctionName:
1952     // <operator-name> ::= cv <type>    # (cast)
1953     Out << "cv";
1954     mangleType(Name.getCXXNameType());
1955     break;
1956
1957   case DeclarationName::CXXLiteralOperatorName:
1958     Out << "li";
1959     mangleSourceName(Name.getCXXLiteralIdentifier());
1960     return;
1961
1962   case DeclarationName::CXXOperatorName:
1963     mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
1964     break;
1965   }
1966 }
1967
1968 void
1969 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
1970   switch (OO) {
1971   // <operator-name> ::= nw     # new
1972   case OO_New: Out << "nw"; break;
1973   //              ::= na        # new[]
1974   case OO_Array_New: Out << "na"; break;
1975   //              ::= dl        # delete
1976   case OO_Delete: Out << "dl"; break;
1977   //              ::= da        # delete[]
1978   case OO_Array_Delete: Out << "da"; break;
1979   //              ::= ps        # + (unary)
1980   //              ::= pl        # + (binary or unknown)
1981   case OO_Plus:
1982     Out << (Arity == 1? "ps" : "pl"); break;
1983   //              ::= ng        # - (unary)
1984   //              ::= mi        # - (binary or unknown)
1985   case OO_Minus:
1986     Out << (Arity == 1? "ng" : "mi"); break;
1987   //              ::= ad        # & (unary)
1988   //              ::= an        # & (binary or unknown)
1989   case OO_Amp:
1990     Out << (Arity == 1? "ad" : "an"); break;
1991   //              ::= de        # * (unary)
1992   //              ::= ml        # * (binary or unknown)
1993   case OO_Star:
1994     // Use binary when unknown.
1995     Out << (Arity == 1? "de" : "ml"); break;
1996   //              ::= co        # ~
1997   case OO_Tilde: Out << "co"; break;
1998   //              ::= dv        # /
1999   case OO_Slash: Out << "dv"; break;
2000   //              ::= rm        # %
2001   case OO_Percent: Out << "rm"; break;
2002   //              ::= or        # |
2003   case OO_Pipe: Out << "or"; break;
2004   //              ::= eo        # ^
2005   case OO_Caret: Out << "eo"; break;
2006   //              ::= aS        # =
2007   case OO_Equal: Out << "aS"; break;
2008   //              ::= pL        # +=
2009   case OO_PlusEqual: Out << "pL"; break;
2010   //              ::= mI        # -=
2011   case OO_MinusEqual: Out << "mI"; break;
2012   //              ::= mL        # *=
2013   case OO_StarEqual: Out << "mL"; break;
2014   //              ::= dV        # /=
2015   case OO_SlashEqual: Out << "dV"; break;
2016   //              ::= rM        # %=
2017   case OO_PercentEqual: Out << "rM"; break;
2018   //              ::= aN        # &=
2019   case OO_AmpEqual: Out << "aN"; break;
2020   //              ::= oR        # |=
2021   case OO_PipeEqual: Out << "oR"; break;
2022   //              ::= eO        # ^=
2023   case OO_CaretEqual: Out << "eO"; break;
2024   //              ::= ls        # <<
2025   case OO_LessLess: Out << "ls"; break;
2026   //              ::= rs        # >>
2027   case OO_GreaterGreater: Out << "rs"; break;
2028   //              ::= lS        # <<=
2029   case OO_LessLessEqual: Out << "lS"; break;
2030   //              ::= rS        # >>=
2031   case OO_GreaterGreaterEqual: Out << "rS"; break;
2032   //              ::= eq        # ==
2033   case OO_EqualEqual: Out << "eq"; break;
2034   //              ::= ne        # !=
2035   case OO_ExclaimEqual: Out << "ne"; break;
2036   //              ::= lt        # <
2037   case OO_Less: Out << "lt"; break;
2038   //              ::= gt        # >
2039   case OO_Greater: Out << "gt"; break;
2040   //              ::= le        # <=
2041   case OO_LessEqual: Out << "le"; break;
2042   //              ::= ge        # >=
2043   case OO_GreaterEqual: Out << "ge"; break;
2044   //              ::= nt        # !
2045   case OO_Exclaim: Out << "nt"; break;
2046   //              ::= aa        # &&
2047   case OO_AmpAmp: Out << "aa"; break;
2048   //              ::= oo        # ||
2049   case OO_PipePipe: Out << "oo"; break;
2050   //              ::= pp        # ++
2051   case OO_PlusPlus: Out << "pp"; break;
2052   //              ::= mm        # --
2053   case OO_MinusMinus: Out << "mm"; break;
2054   //              ::= cm        # ,
2055   case OO_Comma: Out << "cm"; break;
2056   //              ::= pm        # ->*
2057   case OO_ArrowStar: Out << "pm"; break;
2058   //              ::= pt        # ->
2059   case OO_Arrow: Out << "pt"; break;
2060   //              ::= cl        # ()
2061   case OO_Call: Out << "cl"; break;
2062   //              ::= ix        # []
2063   case OO_Subscript: Out << "ix"; break;
2064
2065   //              ::= qu        # ?
2066   // The conditional operator can't be overloaded, but we still handle it when
2067   // mangling expressions.
2068   case OO_Conditional: Out << "qu"; break;
2069   // Proposal on cxx-abi-dev, 2015-10-21.
2070   //              ::= aw        # co_await
2071   case OO_Coawait: Out << "aw"; break;
2072
2073   case OO_None:
2074   case NUM_OVERLOADED_OPERATORS:
2075     llvm_unreachable("Not an overloaded operator");
2076   }
2077 }
2078
2079 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) {
2080   // Vendor qualifiers come first.
2081
2082   // Address space qualifiers start with an ordinary letter.
2083   if (Quals.hasAddressSpace()) {
2084     // Address space extension:
2085     //
2086     //   <type> ::= U <target-addrspace>
2087     //   <type> ::= U <OpenCL-addrspace>
2088     //   <type> ::= U <CUDA-addrspace>
2089
2090     SmallString<64> ASString;
2091     unsigned AS = Quals.getAddressSpace();
2092
2093     if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2094       //  <target-addrspace> ::= "AS" <address-space-number>
2095       unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2096       ASString = "AS" + llvm::utostr(TargetAS);
2097     } else {
2098       switch (AS) {
2099       default: llvm_unreachable("Not a language specific address space");
2100       //  <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ]
2101       case LangAS::opencl_global:   ASString = "CLglobal";   break;
2102       case LangAS::opencl_local:    ASString = "CLlocal";    break;
2103       case LangAS::opencl_constant: ASString = "CLconstant"; break;
2104       //  <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2105       case LangAS::cuda_device:     ASString = "CUdevice";   break;
2106       case LangAS::cuda_constant:   ASString = "CUconstant"; break;
2107       case LangAS::cuda_shared:     ASString = "CUshared";   break;
2108       }
2109     }
2110     mangleVendorQualifier(ASString);
2111   }
2112
2113   // The ARC ownership qualifiers start with underscores.
2114   switch (Quals.getObjCLifetime()) {
2115   // Objective-C ARC Extension:
2116   //
2117   //   <type> ::= U "__strong"
2118   //   <type> ::= U "__weak"
2119   //   <type> ::= U "__autoreleasing"
2120   case Qualifiers::OCL_None:
2121     break;
2122     
2123   case Qualifiers::OCL_Weak:
2124     mangleVendorQualifier("__weak");
2125     break;
2126     
2127   case Qualifiers::OCL_Strong:
2128     mangleVendorQualifier("__strong");
2129     break;
2130     
2131   case Qualifiers::OCL_Autoreleasing:
2132     mangleVendorQualifier("__autoreleasing");
2133     break;
2134     
2135   case Qualifiers::OCL_ExplicitNone:
2136     // The __unsafe_unretained qualifier is *not* mangled, so that
2137     // __unsafe_unretained types in ARC produce the same manglings as the
2138     // equivalent (but, naturally, unqualified) types in non-ARC, providing
2139     // better ABI compatibility.
2140     //
2141     // It's safe to do this because unqualified 'id' won't show up
2142     // in any type signatures that need to be mangled.
2143     break;
2144   }
2145
2146   // <CV-qualifiers> ::= [r] [V] [K]    # restrict (C99), volatile, const
2147   if (Quals.hasRestrict())
2148     Out << 'r';
2149   if (Quals.hasVolatile())
2150     Out << 'V';
2151   if (Quals.hasConst())
2152     Out << 'K';
2153 }
2154
2155 void CXXNameMangler::mangleVendorQualifier(StringRef name) {
2156   Out << 'U' << name.size() << name;
2157 }
2158
2159 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2160   // <ref-qualifier> ::= R                # lvalue reference
2161   //                 ::= O                # rvalue-reference
2162   switch (RefQualifier) {
2163   case RQ_None:
2164     break;
2165       
2166   case RQ_LValue:
2167     Out << 'R';
2168     break;
2169       
2170   case RQ_RValue:
2171     Out << 'O';
2172     break;
2173   }
2174 }
2175
2176 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
2177   Context.mangleObjCMethodName(MD, Out);
2178 }
2179
2180 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) {
2181   if (Quals)
2182     return true;
2183   if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
2184     return true;
2185   if (Ty->isOpenCLSpecificType())
2186     return true;
2187   if (Ty->isBuiltinType())
2188     return false;
2189
2190   return true;
2191 }
2192
2193 void CXXNameMangler::mangleType(QualType T) {
2194   // If our type is instantiation-dependent but not dependent, we mangle
2195   // it as it was written in the source, removing any top-level sugar. 
2196   // Otherwise, use the canonical type.
2197   //
2198   // FIXME: This is an approximation of the instantiation-dependent name 
2199   // mangling rules, since we should really be using the type as written and
2200   // augmented via semantic analysis (i.e., with implicit conversions and
2201   // default template arguments) for any instantiation-dependent type. 
2202   // Unfortunately, that requires several changes to our AST:
2203   //   - Instantiation-dependent TemplateSpecializationTypes will need to be 
2204   //     uniqued, so that we can handle substitutions properly
2205   //   - Default template arguments will need to be represented in the
2206   //     TemplateSpecializationType, since they need to be mangled even though
2207   //     they aren't written.
2208   //   - Conversions on non-type template arguments need to be expressed, since
2209   //     they can affect the mangling of sizeof/alignof.
2210   if (!T->isInstantiationDependentType() || T->isDependentType())
2211     T = T.getCanonicalType();
2212   else {
2213     // Desugar any types that are purely sugar.
2214     do {
2215       // Don't desugar through template specialization types that aren't
2216       // type aliases. We need to mangle the template arguments as written.
2217       if (const TemplateSpecializationType *TST 
2218                                       = dyn_cast<TemplateSpecializationType>(T))
2219         if (!TST->isTypeAlias())
2220           break;
2221
2222       QualType Desugared 
2223         = T.getSingleStepDesugaredType(Context.getASTContext());
2224       if (Desugared == T)
2225         break;
2226       
2227       T = Desugared;
2228     } while (true);
2229   }
2230   SplitQualType split = T.split();
2231   Qualifiers quals = split.Quals;
2232   const Type *ty = split.Ty;
2233
2234   bool isSubstitutable = isTypeSubstitutable(quals, ty);
2235   if (isSubstitutable && mangleSubstitution(T))
2236     return;
2237
2238   // If we're mangling a qualified array type, push the qualifiers to
2239   // the element type.
2240   if (quals && isa<ArrayType>(T)) {
2241     ty = Context.getASTContext().getAsArrayType(T);
2242     quals = Qualifiers();
2243
2244     // Note that we don't update T: we want to add the
2245     // substitution at the original type.
2246   }
2247
2248   if (quals) {
2249     mangleQualifiers(quals);
2250     // Recurse:  even if the qualified type isn't yet substitutable,
2251     // the unqualified type might be.
2252     mangleType(QualType(ty, 0));
2253   } else {
2254     switch (ty->getTypeClass()) {
2255 #define ABSTRACT_TYPE(CLASS, PARENT)
2256 #define NON_CANONICAL_TYPE(CLASS, PARENT) \
2257     case Type::CLASS: \
2258       llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2259       return;
2260 #define TYPE(CLASS, PARENT) \
2261     case Type::CLASS: \
2262       mangleType(static_cast<const CLASS##Type*>(ty)); \
2263       break;
2264 #include "clang/AST/TypeNodes.def"
2265     }
2266   }
2267
2268   // Add the substitution.
2269   if (isSubstitutable)
2270     addSubstitution(T);
2271 }
2272
2273 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
2274   if (!mangleStandardSubstitution(ND))
2275     mangleName(ND);
2276 }
2277
2278 void CXXNameMangler::mangleType(const BuiltinType *T) {
2279   //  <type>         ::= <builtin-type>
2280   //  <builtin-type> ::= v  # void
2281   //                 ::= w  # wchar_t
2282   //                 ::= b  # bool
2283   //                 ::= c  # char
2284   //                 ::= a  # signed char
2285   //                 ::= h  # unsigned char
2286   //                 ::= s  # short
2287   //                 ::= t  # unsigned short
2288   //                 ::= i  # int
2289   //                 ::= j  # unsigned int
2290   //                 ::= l  # long
2291   //                 ::= m  # unsigned long
2292   //                 ::= x  # long long, __int64
2293   //                 ::= y  # unsigned long long, __int64
2294   //                 ::= n  # __int128
2295   //                 ::= o  # unsigned __int128
2296   //                 ::= f  # float
2297   //                 ::= d  # double
2298   //                 ::= e  # long double, __float80
2299   //                 ::= g  # __float128
2300   // UNSUPPORTED:    ::= Dd # IEEE 754r decimal floating point (64 bits)
2301   // UNSUPPORTED:    ::= De # IEEE 754r decimal floating point (128 bits)
2302   // UNSUPPORTED:    ::= Df # IEEE 754r decimal floating point (32 bits)
2303   //                 ::= Dh # IEEE 754r half-precision floating point (16 bits)
2304   //                 ::= Di # char32_t
2305   //                 ::= Ds # char16_t
2306   //                 ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
2307   //                 ::= u <source-name>    # vendor extended type
2308   std::string type_name;
2309   switch (T->getKind()) {
2310   case BuiltinType::Void:
2311     Out << 'v';
2312     break;
2313   case BuiltinType::Bool:
2314     Out << 'b';
2315     break;
2316   case BuiltinType::Char_U:
2317   case BuiltinType::Char_S:
2318     Out << 'c';
2319     break;
2320   case BuiltinType::UChar:
2321     Out << 'h';
2322     break;
2323   case BuiltinType::UShort:
2324     Out << 't';
2325     break;
2326   case BuiltinType::UInt:
2327     Out << 'j';
2328     break;
2329   case BuiltinType::ULong:
2330     Out << 'm';
2331     break;
2332   case BuiltinType::ULongLong:
2333     Out << 'y';
2334     break;
2335   case BuiltinType::UInt128:
2336     Out << 'o';
2337     break;
2338   case BuiltinType::SChar:
2339     Out << 'a';
2340     break;
2341   case BuiltinType::WChar_S:
2342   case BuiltinType::WChar_U:
2343     Out << 'w';
2344     break;
2345   case BuiltinType::Char16:
2346     Out << "Ds";
2347     break;
2348   case BuiltinType::Char32:
2349     Out << "Di";
2350     break;
2351   case BuiltinType::Short:
2352     Out << 's';
2353     break;
2354   case BuiltinType::Int:
2355     Out << 'i';
2356     break;
2357   case BuiltinType::Long:
2358     Out << 'l';
2359     break;
2360   case BuiltinType::LongLong:
2361     Out << 'x';
2362     break;
2363   case BuiltinType::Int128:
2364     Out << 'n';
2365     break;
2366   case BuiltinType::Half:
2367     Out << "Dh";
2368     break;
2369   case BuiltinType::Float:
2370     Out << 'f';
2371     break;
2372   case BuiltinType::Double:
2373     Out << 'd';
2374     break;
2375   case BuiltinType::LongDouble:
2376     Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble()
2377                 ? 'g'
2378                 : 'e');
2379     break;
2380   case BuiltinType::Float128:
2381     if (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble())
2382       Out << "U10__float128"; // Match the GCC mangling
2383     else
2384       Out << 'g';
2385     break;
2386   case BuiltinType::NullPtr:
2387     Out << "Dn";
2388     break;
2389
2390 #define BUILTIN_TYPE(Id, SingletonId)
2391 #define PLACEHOLDER_TYPE(Id, SingletonId) \
2392   case BuiltinType::Id:
2393 #include "clang/AST/BuiltinTypes.def"
2394   case BuiltinType::Dependent:
2395     if (!NullOut)
2396       llvm_unreachable("mangling a placeholder type");
2397     break;
2398   case BuiltinType::ObjCId:
2399     Out << "11objc_object";
2400     break;
2401   case BuiltinType::ObjCClass:
2402     Out << "10objc_class";
2403     break;
2404   case BuiltinType::ObjCSel:
2405     Out << "13objc_selector";
2406     break;
2407 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2408   case BuiltinType::Id: \
2409     type_name = "ocl_" #ImgType "_" #Suffix; \
2410     Out << type_name.size() << type_name; \
2411     break;
2412 #include "clang/Basic/OpenCLImageTypes.def"
2413   case BuiltinType::OCLSampler:
2414     Out << "11ocl_sampler";
2415     break;
2416   case BuiltinType::OCLEvent:
2417     Out << "9ocl_event";
2418     break;
2419   case BuiltinType::OCLClkEvent:
2420     Out << "12ocl_clkevent";
2421     break;
2422   case BuiltinType::OCLQueue:
2423     Out << "9ocl_queue";
2424     break;
2425   case BuiltinType::OCLNDRange:
2426     Out << "11ocl_ndrange";
2427     break;
2428   case BuiltinType::OCLReserveID:
2429     Out << "13ocl_reserveid";
2430     break;
2431   }
2432 }
2433
2434 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
2435   switch (CC) {
2436   case CC_C:
2437     return "";
2438
2439   case CC_X86StdCall:
2440   case CC_X86FastCall:
2441   case CC_X86ThisCall:
2442   case CC_X86VectorCall:
2443   case CC_X86Pascal:
2444   case CC_X86_64Win64:
2445   case CC_X86_64SysV:
2446   case CC_AAPCS:
2447   case CC_AAPCS_VFP:
2448   case CC_IntelOclBicc:
2449   case CC_SpirFunction:
2450   case CC_OpenCLKernel:
2451   case CC_PreserveMost:
2452   case CC_PreserveAll:
2453     // FIXME: we should be mangling all of the above.
2454     return "";
2455
2456   case CC_Swift:
2457     return "swiftcall";
2458   }
2459   llvm_unreachable("bad calling convention");
2460 }
2461
2462 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
2463   // Fast path.
2464   if (T->getExtInfo() == FunctionType::ExtInfo())
2465     return;
2466
2467   // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2468   // This will get more complicated in the future if we mangle other
2469   // things here; but for now, since we mangle ns_returns_retained as
2470   // a qualifier on the result type, we can get away with this:
2471   StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
2472   if (!CCQualifier.empty())
2473     mangleVendorQualifier(CCQualifier);
2474
2475   // FIXME: regparm
2476   // FIXME: noreturn
2477 }
2478
2479 void
2480 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
2481   // Vendor-specific qualifiers are emitted in reverse alphabetical order.
2482
2483   // Note that these are *not* substitution candidates.  Demanglers might
2484   // have trouble with this if the parameter type is fully substituted.
2485
2486   switch (PI.getABI()) {
2487   case ParameterABI::Ordinary:
2488     break;
2489
2490   // All of these start with "swift", so they come before "ns_consumed".
2491   case ParameterABI::SwiftContext:
2492   case ParameterABI::SwiftErrorResult:
2493   case ParameterABI::SwiftIndirectResult:
2494     mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
2495     break;
2496   }
2497
2498   if (PI.isConsumed())
2499     mangleVendorQualifier("ns_consumed");
2500 }
2501
2502 // <type>          ::= <function-type>
2503 // <function-type> ::= [<CV-qualifiers>] F [Y]
2504 //                      <bare-function-type> [<ref-qualifier>] E
2505 void CXXNameMangler::mangleType(const FunctionProtoType *T) {
2506   mangleExtFunctionInfo(T);
2507
2508   // Mangle CV-qualifiers, if present.  These are 'this' qualifiers,
2509   // e.g. "const" in "int (A::*)() const".
2510   mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals()));
2511
2512   Out << 'F';
2513
2514   // FIXME: We don't have enough information in the AST to produce the 'Y'
2515   // encoding for extern "C" function types.
2516   mangleBareFunctionType(T, /*MangleReturnType=*/true);
2517
2518   // Mangle the ref-qualifier, if present.
2519   mangleRefQualifier(T->getRefQualifier());
2520
2521   Out << 'E';
2522 }
2523
2524 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
2525   // Function types without prototypes can arise when mangling a function type
2526   // within an overloadable function in C. We mangle these as the absence of any
2527   // parameter types (not even an empty parameter list).
2528   Out << 'F';
2529
2530   FunctionTypeDepthState saved = FunctionTypeDepth.push();
2531
2532   FunctionTypeDepth.enterResultType();
2533   mangleType(T->getReturnType());
2534   FunctionTypeDepth.leaveResultType();
2535
2536   FunctionTypeDepth.pop(saved);
2537   Out << 'E';
2538 }
2539
2540 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
2541                                             bool MangleReturnType,
2542                                             const FunctionDecl *FD) {
2543   // Record that we're in a function type.  See mangleFunctionParam
2544   // for details on what we're trying to achieve here.
2545   FunctionTypeDepthState saved = FunctionTypeDepth.push();
2546
2547   // <bare-function-type> ::= <signature type>+
2548   if (MangleReturnType) {
2549     FunctionTypeDepth.enterResultType();
2550
2551     // Mangle ns_returns_retained as an order-sensitive qualifier here.
2552     if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
2553       mangleVendorQualifier("ns_returns_retained");
2554
2555     // Mangle the return type without any direct ARC ownership qualifiers.
2556     QualType ReturnTy = Proto->getReturnType();
2557     if (ReturnTy.getObjCLifetime()) {
2558       auto SplitReturnTy = ReturnTy.split();
2559       SplitReturnTy.Quals.removeObjCLifetime();
2560       ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
2561     }
2562     mangleType(ReturnTy);
2563
2564     FunctionTypeDepth.leaveResultType();
2565   }
2566
2567   if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2568     //   <builtin-type> ::= v   # void
2569     Out << 'v';
2570
2571     FunctionTypeDepth.pop(saved);
2572     return;
2573   }
2574
2575   assert(!FD || FD->getNumParams() == Proto->getNumParams());
2576   for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2577     // Mangle extended parameter info as order-sensitive qualifiers here.
2578     if (Proto->hasExtParameterInfos() && FD == nullptr) {
2579       mangleExtParameterInfo(Proto->getExtParameterInfo(I));
2580     }
2581
2582     // Mangle the type.
2583     QualType ParamTy = Proto->getParamType(I);
2584     mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
2585
2586     if (FD) {
2587       if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
2588         // Attr can only take 1 character, so we can hardcode the length below.
2589         assert(Attr->getType() <= 9 && Attr->getType() >= 0);
2590         Out << "U17pass_object_size" << Attr->getType();
2591       }
2592     }
2593   }
2594
2595   FunctionTypeDepth.pop(saved);
2596
2597   // <builtin-type>      ::= z  # ellipsis
2598   if (Proto->isVariadic())
2599     Out << 'z';
2600 }
2601
2602 // <type>            ::= <class-enum-type>
2603 // <class-enum-type> ::= <name>
2604 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
2605   mangleName(T->getDecl());
2606 }
2607
2608 // <type>            ::= <class-enum-type>
2609 // <class-enum-type> ::= <name>
2610 void CXXNameMangler::mangleType(const EnumType *T) {
2611   mangleType(static_cast<const TagType*>(T));
2612 }
2613 void CXXNameMangler::mangleType(const RecordType *T) {
2614   mangleType(static_cast<const TagType*>(T));
2615 }
2616 void CXXNameMangler::mangleType(const TagType *T) {
2617   mangleName(T->getDecl());
2618 }
2619
2620 // <type>       ::= <array-type>
2621 // <array-type> ::= A <positive dimension number> _ <element type>
2622 //              ::= A [<dimension expression>] _ <element type>
2623 void CXXNameMangler::mangleType(const ConstantArrayType *T) {
2624   Out << 'A' << T->getSize() << '_';
2625   mangleType(T->getElementType());
2626 }
2627 void CXXNameMangler::mangleType(const VariableArrayType *T) {
2628   Out << 'A';
2629   // decayed vla types (size 0) will just be skipped.
2630   if (T->getSizeExpr())
2631     mangleExpression(T->getSizeExpr());
2632   Out << '_';
2633   mangleType(T->getElementType());
2634 }
2635 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
2636   Out << 'A';
2637   mangleExpression(T->getSizeExpr());
2638   Out << '_';
2639   mangleType(T->getElementType());
2640 }
2641 void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
2642   Out << "A_";
2643   mangleType(T->getElementType());
2644 }
2645
2646 // <type>                   ::= <pointer-to-member-type>
2647 // <pointer-to-member-type> ::= M <class type> <member type>
2648 void CXXNameMangler::mangleType(const MemberPointerType *T) {
2649   Out << 'M';
2650   mangleType(QualType(T->getClass(), 0));
2651   QualType PointeeType = T->getPointeeType();
2652   if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
2653     mangleType(FPT);
2654     
2655     // Itanium C++ ABI 5.1.8:
2656     //
2657     //   The type of a non-static member function is considered to be different,
2658     //   for the purposes of substitution, from the type of a namespace-scope or
2659     //   static member function whose type appears similar. The types of two
2660     //   non-static member functions are considered to be different, for the
2661     //   purposes of substitution, if the functions are members of different
2662     //   classes. In other words, for the purposes of substitution, the class of 
2663     //   which the function is a member is considered part of the type of 
2664     //   function.
2665
2666     // Given that we already substitute member function pointers as a
2667     // whole, the net effect of this rule is just to unconditionally
2668     // suppress substitution on the function type in a member pointer.
2669     // We increment the SeqID here to emulate adding an entry to the
2670     // substitution table.
2671     ++SeqID;
2672   } else
2673     mangleType(PointeeType);
2674 }
2675
2676 // <type>           ::= <template-param>
2677 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
2678   mangleTemplateParameter(T->getIndex());
2679 }
2680
2681 // <type>           ::= <template-param>
2682 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
2683   // FIXME: not clear how to mangle this!
2684   // template <class T...> class A {
2685   //   template <class U...> void foo(T(*)(U) x...);
2686   // };
2687   Out << "_SUBSTPACK_";
2688 }
2689
2690 // <type> ::= P <type>   # pointer-to
2691 void CXXNameMangler::mangleType(const PointerType *T) {
2692   Out << 'P';
2693   mangleType(T->getPointeeType());
2694 }
2695 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
2696   Out << 'P';
2697   mangleType(T->getPointeeType());
2698 }
2699
2700 // <type> ::= R <type>   # reference-to
2701 void CXXNameMangler::mangleType(const LValueReferenceType *T) {
2702   Out << 'R';
2703   mangleType(T->getPointeeType());
2704 }
2705
2706 // <type> ::= O <type>   # rvalue reference-to (C++0x)
2707 void CXXNameMangler::mangleType(const RValueReferenceType *T) {
2708   Out << 'O';
2709   mangleType(T->getPointeeType());
2710 }
2711
2712 // <type> ::= C <type>   # complex pair (C 2000)
2713 void CXXNameMangler::mangleType(const ComplexType *T) {
2714   Out << 'C';
2715   mangleType(T->getElementType());
2716 }
2717
2718 // ARM's ABI for Neon vector types specifies that they should be mangled as
2719 // if they are structs (to match ARM's initial implementation).  The
2720 // vector type must be one of the special types predefined by ARM.
2721 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
2722   QualType EltType = T->getElementType();
2723   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2724   const char *EltName = nullptr;
2725   if (T->getVectorKind() == VectorType::NeonPolyVector) {
2726     switch (cast<BuiltinType>(EltType)->getKind()) {
2727     case BuiltinType::SChar:
2728     case BuiltinType::UChar:
2729       EltName = "poly8_t";
2730       break;
2731     case BuiltinType::Short:
2732     case BuiltinType::UShort:
2733       EltName = "poly16_t";
2734       break;
2735     case BuiltinType::ULongLong:
2736       EltName = "poly64_t";
2737       break;
2738     default: llvm_unreachable("unexpected Neon polynomial vector element type");
2739     }
2740   } else {
2741     switch (cast<BuiltinType>(EltType)->getKind()) {
2742     case BuiltinType::SChar:     EltName = "int8_t"; break;
2743     case BuiltinType::UChar:     EltName = "uint8_t"; break;
2744     case BuiltinType::Short:     EltName = "int16_t"; break;
2745     case BuiltinType::UShort:    EltName = "uint16_t"; break;
2746     case BuiltinType::Int:       EltName = "int32_t"; break;
2747     case BuiltinType::UInt:      EltName = "uint32_t"; break;
2748     case BuiltinType::LongLong:  EltName = "int64_t"; break;
2749     case BuiltinType::ULongLong: EltName = "uint64_t"; break;
2750     case BuiltinType::Double:    EltName = "float64_t"; break;
2751     case BuiltinType::Float:     EltName = "float32_t"; break;
2752     case BuiltinType::Half:      EltName = "float16_t";break;
2753     default:
2754       llvm_unreachable("unexpected Neon vector element type");
2755     }
2756   }
2757   const char *BaseName = nullptr;
2758   unsigned BitSize = (T->getNumElements() *
2759                       getASTContext().getTypeSize(EltType));
2760   if (BitSize == 64)
2761     BaseName = "__simd64_";
2762   else {
2763     assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
2764     BaseName = "__simd128_";
2765   }
2766   Out << strlen(BaseName) + strlen(EltName);
2767   Out << BaseName << EltName;
2768 }
2769
2770 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
2771   switch (EltType->getKind()) {
2772   case BuiltinType::SChar:
2773     return "Int8";
2774   case BuiltinType::Short:
2775     return "Int16";
2776   case BuiltinType::Int:
2777     return "Int32";
2778   case BuiltinType::Long:
2779   case BuiltinType::LongLong:
2780     return "Int64";
2781   case BuiltinType::UChar:
2782     return "Uint8";
2783   case BuiltinType::UShort:
2784     return "Uint16";
2785   case BuiltinType::UInt:
2786     return "Uint32";
2787   case BuiltinType::ULong:
2788   case BuiltinType::ULongLong:
2789     return "Uint64";
2790   case BuiltinType::Half:
2791     return "Float16";
2792   case BuiltinType::Float:
2793     return "Float32";
2794   case BuiltinType::Double:
2795     return "Float64";
2796   default:
2797     llvm_unreachable("Unexpected vector element base type");
2798   }
2799 }
2800
2801 // AArch64's ABI for Neon vector types specifies that they should be mangled as
2802 // the equivalent internal name. The vector type must be one of the special
2803 // types predefined by ARM.
2804 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
2805   QualType EltType = T->getElementType();
2806   assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
2807   unsigned BitSize =
2808       (T->getNumElements() * getASTContext().getTypeSize(EltType));
2809   (void)BitSize; // Silence warning.
2810
2811   assert((BitSize == 64 || BitSize == 128) &&
2812          "Neon vector type not 64 or 128 bits");
2813
2814   StringRef EltName;
2815   if (T->getVectorKind() == VectorType::NeonPolyVector) {
2816     switch (cast<BuiltinType>(EltType)->getKind()) {
2817     case BuiltinType::UChar:
2818       EltName = "Poly8";
2819       break;
2820     case BuiltinType::UShort:
2821       EltName = "Poly16";
2822       break;
2823     case BuiltinType::ULong:
2824     case BuiltinType::ULongLong:
2825       EltName = "Poly64";
2826       break;
2827     default:
2828       llvm_unreachable("unexpected Neon polynomial vector element type");
2829     }
2830   } else
2831     EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
2832
2833   std::string TypeName =
2834       ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
2835   Out << TypeName.length() << TypeName;
2836 }
2837
2838 // GNU extension: vector types
2839 // <type>                  ::= <vector-type>
2840 // <vector-type>           ::= Dv <positive dimension number> _
2841 //                                    <extended element type>
2842 //                         ::= Dv [<dimension expression>] _ <element type>
2843 // <extended element type> ::= <element type>
2844 //                         ::= p # AltiVec vector pixel
2845 //                         ::= b # Altivec vector bool
2846 void CXXNameMangler::mangleType(const VectorType *T) {
2847   if ((T->getVectorKind() == VectorType::NeonVector ||
2848        T->getVectorKind() == VectorType::NeonPolyVector)) {
2849     llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
2850     llvm::Triple::ArchType Arch =
2851         getASTContext().getTargetInfo().getTriple().getArch();
2852     if ((Arch == llvm::Triple::aarch64 ||
2853          Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
2854       mangleAArch64NeonVectorType(T);
2855     else
2856       mangleNeonVectorType(T);
2857     return;
2858   }
2859   Out << "Dv" << T->getNumElements() << '_';
2860   if (T->getVectorKind() == VectorType::AltiVecPixel)
2861     Out << 'p';
2862   else if (T->getVectorKind() == VectorType::AltiVecBool)
2863     Out << 'b';
2864   else
2865     mangleType(T->getElementType());
2866 }
2867 void CXXNameMangler::mangleType(const ExtVectorType *T) {
2868   mangleType(static_cast<const VectorType*>(T));
2869 }
2870 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
2871   Out << "Dv";
2872   mangleExpression(T->getSizeExpr());
2873   Out << '_';
2874   mangleType(T->getElementType());
2875 }
2876
2877 void CXXNameMangler::mangleType(const PackExpansionType *T) {
2878   // <type>  ::= Dp <type>          # pack expansion (C++0x)
2879   Out << "Dp";
2880   mangleType(T->getPattern());
2881 }
2882
2883 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
2884   mangleSourceName(T->getDecl()->getIdentifier());
2885 }
2886
2887 void CXXNameMangler::mangleType(const ObjCObjectType *T) {
2888   // Treat __kindof as a vendor extended type qualifier.
2889   if (T->isKindOfType())
2890     Out << "U8__kindof";
2891
2892   if (!T->qual_empty()) {
2893     // Mangle protocol qualifiers.
2894     SmallString<64> QualStr;
2895     llvm::raw_svector_ostream QualOS(QualStr);
2896     QualOS << "objcproto";
2897     for (const auto *I : T->quals()) {
2898       StringRef name = I->getName();
2899       QualOS << name.size() << name;
2900     }
2901     Out << 'U' << QualStr.size() << QualStr;
2902   }
2903
2904   mangleType(T->getBaseType());
2905
2906   if (T->isSpecialized()) {
2907     // Mangle type arguments as I <type>+ E
2908     Out << 'I';
2909     for (auto typeArg : T->getTypeArgs())
2910       mangleType(typeArg);
2911     Out << 'E';
2912   }
2913 }
2914
2915 void CXXNameMangler::mangleType(const BlockPointerType *T) {
2916   Out << "U13block_pointer";
2917   mangleType(T->getPointeeType());
2918 }
2919
2920 void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
2921   // Mangle injected class name types as if the user had written the
2922   // specialization out fully.  It may not actually be possible to see
2923   // this mangling, though.
2924   mangleType(T->getInjectedSpecializationType());
2925 }
2926
2927 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
2928   if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
2929     mangleTemplateName(TD, T->getArgs(), T->getNumArgs());
2930   } else {
2931     if (mangleSubstitution(QualType(T, 0)))
2932       return;
2933     
2934     mangleTemplatePrefix(T->getTemplateName());
2935     
2936     // FIXME: GCC does not appear to mangle the template arguments when
2937     // the template in question is a dependent template name. Should we
2938     // emulate that badness?
2939     mangleTemplateArgs(T->getArgs(), T->getNumArgs());
2940     addSubstitution(QualType(T, 0));
2941   }
2942 }
2943
2944 void CXXNameMangler::mangleType(const DependentNameType *T) {
2945   // Proposal by cxx-abi-dev, 2014-03-26
2946   // <class-enum-type> ::= <name>    # non-dependent or dependent type name or
2947   //                                 # dependent elaborated type specifier using
2948   //                                 # 'typename'
2949   //                   ::= Ts <name> # dependent elaborated type specifier using
2950   //                                 # 'struct' or 'class'
2951   //                   ::= Tu <name> # dependent elaborated type specifier using
2952   //                                 # 'union'
2953   //                   ::= Te <name> # dependent elaborated type specifier using
2954   //                                 # 'enum'
2955   switch (T->getKeyword()) {
2956     case ETK_Typename:
2957       break;
2958     case ETK_Struct:
2959     case ETK_Class:
2960     case ETK_Interface:
2961       Out << "Ts";
2962       break;
2963     case ETK_Union:
2964       Out << "Tu";
2965       break;
2966     case ETK_Enum:
2967       Out << "Te";
2968       break;
2969     default:
2970       llvm_unreachable("unexpected keyword for dependent type name");
2971   }
2972   // Typename types are always nested
2973   Out << 'N';
2974   manglePrefix(T->getQualifier());
2975   mangleSourceName(T->getIdentifier());
2976   Out << 'E';
2977 }
2978
2979 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
2980   // Dependently-scoped template types are nested if they have a prefix.
2981   Out << 'N';
2982
2983   // TODO: avoid making this TemplateName.
2984   TemplateName Prefix =
2985     getASTContext().getDependentTemplateName(T->getQualifier(),
2986                                              T->getIdentifier());
2987   mangleTemplatePrefix(Prefix);
2988
2989   // FIXME: GCC does not appear to mangle the template arguments when
2990   // the template in question is a dependent template name. Should we
2991   // emulate that badness?
2992   mangleTemplateArgs(T->getArgs(), T->getNumArgs());    
2993   Out << 'E';
2994 }
2995
2996 void CXXNameMangler::mangleType(const TypeOfType *T) {
2997   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
2998   // "extension with parameters" mangling.
2999   Out << "u6typeof";
3000 }
3001
3002 void CXXNameMangler::mangleType(const TypeOfExprType *T) {
3003   // FIXME: this is pretty unsatisfactory, but there isn't an obvious
3004   // "extension with parameters" mangling.
3005   Out << "u6typeof";
3006 }
3007
3008 void CXXNameMangler::mangleType(const DecltypeType *T) {
3009   Expr *E = T->getUnderlyingExpr();
3010
3011   // type ::= Dt <expression> E  # decltype of an id-expression
3012   //                             #   or class member access
3013   //      ::= DT <expression> E  # decltype of an expression
3014
3015   // This purports to be an exhaustive list of id-expressions and
3016   // class member accesses.  Note that we do not ignore parentheses;
3017   // parentheses change the semantics of decltype for these
3018   // expressions (and cause the mangler to use the other form).
3019   if (isa<DeclRefExpr>(E) ||
3020       isa<MemberExpr>(E) ||
3021       isa<UnresolvedLookupExpr>(E) ||
3022       isa<DependentScopeDeclRefExpr>(E) ||
3023       isa<CXXDependentScopeMemberExpr>(E) ||
3024       isa<UnresolvedMemberExpr>(E))
3025     Out << "Dt";
3026   else
3027     Out << "DT";
3028   mangleExpression(E);
3029   Out << 'E';
3030 }
3031
3032 void CXXNameMangler::mangleType(const UnaryTransformType *T) {
3033   // If this is dependent, we need to record that. If not, we simply
3034   // mangle it as the underlying type since they are equivalent.
3035   if (T->isDependentType()) {
3036     Out << 'U';
3037     
3038     switch (T->getUTTKind()) {
3039       case UnaryTransformType::EnumUnderlyingType:
3040         Out << "3eut";
3041         break;
3042     }
3043   }
3044
3045   mangleType(T->getBaseType());
3046 }
3047
3048 void CXXNameMangler::mangleType(const AutoType *T) {
3049   QualType D = T->getDeducedType();
3050   // <builtin-type> ::= Da  # dependent auto
3051   if (D.isNull()) {
3052     assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
3053            "shouldn't need to mangle __auto_type!");
3054     Out << (T->isDecltypeAuto() ? "Dc" : "Da");
3055   } else
3056     mangleType(D);
3057 }
3058
3059 void CXXNameMangler::mangleType(const AtomicType *T) {
3060   // <type> ::= U <source-name> <type>  # vendor extended type qualifier
3061   // (Until there's a standardized mangling...)
3062   Out << "U7_Atomic";
3063   mangleType(T->getValueType());
3064 }
3065
3066 void CXXNameMangler::mangleType(const PipeType *T) {
3067   // Pipe type mangling rules are described in SPIR 2.0 specification
3068   // A.1 Data types and A.3 Summary of changes
3069   // <type> ::= 8ocl_pipe
3070   Out << "8ocl_pipe";
3071 }
3072
3073 void CXXNameMangler::mangleIntegerLiteral(QualType T,
3074                                           const llvm::APSInt &Value) {
3075   //  <expr-primary> ::= L <type> <value number> E # integer literal
3076   Out << 'L';
3077
3078   mangleType(T);
3079   if (T->isBooleanType()) {
3080     // Boolean values are encoded as 0/1.
3081     Out << (Value.getBoolValue() ? '1' : '0');
3082   } else {
3083     mangleNumber(Value);
3084   }
3085   Out << 'E';
3086
3087 }
3088
3089 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
3090   // Ignore member expressions involving anonymous unions.
3091   while (const auto *RT = Base->getType()->getAs<RecordType>()) {
3092     if (!RT->getDecl()->isAnonymousStructOrUnion())
3093       break;
3094     const auto *ME = dyn_cast<MemberExpr>(Base);
3095     if (!ME)
3096       break;
3097     Base = ME->getBase();
3098     IsArrow = ME->isArrow();
3099   }
3100
3101   if (Base->isImplicitCXXThis()) {
3102     // Note: GCC mangles member expressions to the implicit 'this' as
3103     // *this., whereas we represent them as this->. The Itanium C++ ABI
3104     // does not specify anything here, so we follow GCC.
3105     Out << "dtdefpT";
3106   } else {
3107     Out << (IsArrow ? "pt" : "dt");
3108     mangleExpression(Base);
3109   }
3110 }
3111
3112 /// Mangles a member expression.
3113 void CXXNameMangler::mangleMemberExpr(const Expr *base,
3114                                       bool isArrow,
3115                                       NestedNameSpecifier *qualifier,
3116                                       NamedDecl *firstQualifierLookup,
3117                                       DeclarationName member,
3118                                       unsigned arity) {
3119   // <expression> ::= dt <expression> <unresolved-name>
3120   //              ::= pt <expression> <unresolved-name>
3121   if (base)
3122     mangleMemberExprBase(base, isArrow);
3123   mangleUnresolvedName(qualifier, member, arity);
3124 }
3125
3126 /// Look at the callee of the given call expression and determine if
3127 /// it's a parenthesized id-expression which would have triggered ADL
3128 /// otherwise.
3129 static bool isParenthesizedADLCallee(const CallExpr *call) {
3130   const Expr *callee = call->getCallee();
3131   const Expr *fn = callee->IgnoreParens();
3132
3133   // Must be parenthesized.  IgnoreParens() skips __extension__ nodes,
3134   // too, but for those to appear in the callee, it would have to be
3135   // parenthesized.
3136   if (callee == fn) return false;
3137
3138   // Must be an unresolved lookup.
3139   const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
3140   if (!lookup) return false;
3141
3142   assert(!lookup->requiresADL());
3143
3144   // Must be an unqualified lookup.
3145   if (lookup->getQualifier()) return false;
3146
3147   // Must not have found a class member.  Note that if one is a class
3148   // member, they're all class members.
3149   if (lookup->getNumDecls() > 0 &&
3150       (*lookup->decls_begin())->isCXXClassMember())
3151     return false;
3152
3153   // Otherwise, ADL would have been triggered.
3154   return true;
3155 }
3156
3157 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
3158   const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
3159   Out << CastEncoding;
3160   mangleType(ECE->getType());
3161   mangleExpression(ECE->getSubExpr());
3162 }
3163
3164 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
3165   if (auto *Syntactic = InitList->getSyntacticForm())
3166     InitList = Syntactic;
3167   for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
3168     mangleExpression(InitList->getInit(i));
3169 }
3170
3171 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) {
3172   // <expression> ::= <unary operator-name> <expression>
3173   //              ::= <binary operator-name> <expression> <expression>
3174   //              ::= <trinary operator-name> <expression> <expression> <expression>
3175   //              ::= cv <type> expression           # conversion with one argument
3176   //              ::= cv <type> _ <expression>* E # conversion with a different number of arguments
3177   //              ::= dc <type> <expression>         # dynamic_cast<type> (expression)
3178   //              ::= sc <type> <expression>         # static_cast<type> (expression)
3179   //              ::= cc <type> <expression>         # const_cast<type> (expression)
3180   //              ::= rc <type> <expression>         # reinterpret_cast<type> (expression)
3181   //              ::= st <type>                      # sizeof (a type)
3182   //              ::= at <type>                      # alignof (a type)
3183   //              ::= <template-param>
3184   //              ::= <function-param>
3185   //              ::= sr <type> <unqualified-name>                   # dependent name
3186   //              ::= sr <type> <unqualified-name> <template-args>   # dependent template-id
3187   //              ::= ds <expression> <expression>                   # expr.*expr
3188   //              ::= sZ <template-param>                            # size of a parameter pack
3189   //              ::= sZ <function-param>    # size of a function parameter pack
3190   //              ::= <expr-primary>
3191   // <expr-primary> ::= L <type> <value number> E    # integer literal
3192   //                ::= L <type <value float> E      # floating literal
3193   //                ::= L <mangled-name> E           # external name
3194   //                ::= fpT                          # 'this' expression
3195   QualType ImplicitlyConvertedToType;
3196   
3197 recurse:
3198   switch (E->getStmtClass()) {
3199   case Expr::NoStmtClass:
3200 #define ABSTRACT_STMT(Type)
3201 #define EXPR(Type, Base)
3202 #define STMT(Type, Base) \
3203   case Expr::Type##Class:
3204 #include "clang/AST/StmtNodes.inc"
3205     // fallthrough
3206
3207   // These all can only appear in local or variable-initialization
3208   // contexts and so should never appear in a mangling.
3209   case Expr::AddrLabelExprClass:
3210   case Expr::DesignatedInitUpdateExprClass:
3211   case Expr::ImplicitValueInitExprClass:
3212   case Expr::NoInitExprClass:
3213   case Expr::ParenListExprClass:
3214   case Expr::LambdaExprClass:
3215   case Expr::MSPropertyRefExprClass:
3216   case Expr::MSPropertySubscriptExprClass:
3217   case Expr::TypoExprClass:  // This should no longer exist in the AST by now.
3218   case Expr::OMPArraySectionExprClass:
3219   case Expr::CXXInheritedCtorInitExprClass:
3220     llvm_unreachable("unexpected statement kind");
3221
3222   // FIXME: invent manglings for all these.
3223   case Expr::BlockExprClass:
3224   case Expr::ChooseExprClass:
3225   case Expr::CompoundLiteralExprClass:
3226   case Expr::DesignatedInitExprClass:
3227   case Expr::ExtVectorElementExprClass:
3228   case Expr::GenericSelectionExprClass:
3229   case Expr::ObjCEncodeExprClass:
3230   case Expr::ObjCIsaExprClass:
3231   case Expr::ObjCIvarRefExprClass:
3232   case Expr::ObjCMessageExprClass:
3233   case Expr::ObjCPropertyRefExprClass:
3234   case Expr::ObjCProtocolExprClass:
3235   case Expr::ObjCSelectorExprClass:
3236   case Expr::ObjCStringLiteralClass:
3237   case Expr::ObjCBoxedExprClass:
3238   case Expr::ObjCArrayLiteralClass:
3239   case Expr::ObjCDictionaryLiteralClass:
3240   case Expr::ObjCSubscriptRefExprClass:
3241   case Expr::ObjCIndirectCopyRestoreExprClass:
3242   case Expr::ObjCAvailabilityCheckExprClass:
3243   case Expr::OffsetOfExprClass:
3244   case Expr::PredefinedExprClass:
3245   case Expr::ShuffleVectorExprClass:
3246   case Expr::ConvertVectorExprClass:
3247   case Expr::StmtExprClass:
3248   case Expr::TypeTraitExprClass:
3249   case Expr::ArrayTypeTraitExprClass:
3250   case Expr::ExpressionTraitExprClass:
3251   case Expr::VAArgExprClass:
3252   case Expr::CUDAKernelCallExprClass:
3253   case Expr::AsTypeExprClass:
3254   case Expr::PseudoObjectExprClass:
3255   case Expr::AtomicExprClass:
3256   {
3257     if (!NullOut) {
3258       // As bad as this diagnostic is, it's better than crashing.
3259       DiagnosticsEngine &Diags = Context.getDiags();
3260       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3261                                        "cannot yet mangle expression type %0");
3262       Diags.Report(E->getExprLoc(), DiagID)
3263         << E->getStmtClassName() << E->getSourceRange();
3264     }
3265     break;
3266   }
3267
3268   case Expr::CXXUuidofExprClass: {
3269     const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
3270     if (UE->isTypeOperand()) {
3271       QualType UuidT = UE->getTypeOperand(Context.getASTContext());
3272       Out << "u8__uuidoft";
3273       mangleType(UuidT);
3274     } else {
3275       Expr *UuidExp = UE->getExprOperand();
3276       Out << "u8__uuidofz";
3277       mangleExpression(UuidExp, Arity);
3278     }
3279     break;
3280   }
3281
3282   // Even gcc-4.5 doesn't mangle this.
3283   case Expr::BinaryConditionalOperatorClass: {
3284     DiagnosticsEngine &Diags = Context.getDiags();
3285     unsigned DiagID =
3286       Diags.getCustomDiagID(DiagnosticsEngine::Error,
3287                 "?: operator with omitted middle operand cannot be mangled");
3288     Diags.Report(E->getExprLoc(), DiagID)
3289       << E->getStmtClassName() << E->getSourceRange();
3290     break;
3291   }
3292
3293   // These are used for internal purposes and cannot be meaningfully mangled.
3294   case Expr::OpaqueValueExprClass:
3295     llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
3296
3297   case Expr::InitListExprClass: {
3298     Out << "il";
3299     mangleInitListElements(cast<InitListExpr>(E));
3300     Out << "E";
3301     break;
3302   }
3303
3304   case Expr::CXXDefaultArgExprClass:
3305     mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
3306     break;
3307
3308   case Expr::CXXDefaultInitExprClass:
3309     mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
3310     break;
3311
3312   case Expr::CXXStdInitializerListExprClass:
3313     mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity);
3314     break;
3315
3316   case Expr::SubstNonTypeTemplateParmExprClass:
3317     mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
3318                      Arity);
3319     break;
3320
3321   case Expr::UserDefinedLiteralClass:
3322     // We follow g++'s approach of mangling a UDL as a call to the literal
3323     // operator.
3324   case Expr::CXXMemberCallExprClass: // fallthrough
3325   case Expr::CallExprClass: {
3326     const CallExpr *CE = cast<CallExpr>(E);
3327
3328     // <expression> ::= cp <simple-id> <expression>* E
3329     // We use this mangling only when the call would use ADL except
3330     // for being parenthesized.  Per discussion with David
3331     // Vandervoorde, 2011.04.25.
3332     if (isParenthesizedADLCallee(CE)) {
3333       Out << "cp";
3334       // The callee here is a parenthesized UnresolvedLookupExpr with
3335       // no qualifier and should always get mangled as a <simple-id>
3336       // anyway.
3337
3338     // <expression> ::= cl <expression>* E
3339     } else {
3340       Out << "cl";
3341     }
3342
3343     unsigned CallArity = CE->getNumArgs();
3344     for (const Expr *Arg : CE->arguments())
3345       if (isa<PackExpansionExpr>(Arg))
3346         CallArity = UnknownArity;
3347
3348     mangleExpression(CE->getCallee(), CallArity);
3349     for (const Expr *Arg : CE->arguments())
3350       mangleExpression(Arg);
3351     Out << 'E';
3352     break;
3353   }
3354
3355   case Expr::CXXNewExprClass: {
3356     const CXXNewExpr *New = cast<CXXNewExpr>(E);
3357     if (New->isGlobalNew()) Out << "gs";
3358     Out << (New->isArray() ? "na" : "nw");
3359     for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
3360            E = New->placement_arg_end(); I != E; ++I)
3361       mangleExpression(*I);
3362     Out << '_';
3363     mangleType(New->getAllocatedType());
3364     if (New->hasInitializer()) {
3365       if (New->getInitializationStyle() == CXXNewExpr::ListInit)
3366         Out << "il";
3367       else
3368         Out << "pi";
3369       const Expr *Init = New->getInitializer();
3370       if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
3371         // Directly inline the initializers.
3372         for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
3373                                                   E = CCE->arg_end();
3374              I != E; ++I)
3375           mangleExpression(*I);
3376       } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
3377         for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
3378           mangleExpression(PLE->getExpr(i));
3379       } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
3380                  isa<InitListExpr>(Init)) {
3381         // Only take InitListExprs apart for list-initialization.
3382         mangleInitListElements(cast<InitListExpr>(Init));
3383       } else
3384         mangleExpression(Init);
3385     }
3386     Out << 'E';
3387     break;
3388   }
3389
3390   case Expr::CXXPseudoDestructorExprClass: {
3391     const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
3392     if (const Expr *Base = PDE->getBase())
3393       mangleMemberExprBase(Base, PDE->isArrow());
3394     NestedNameSpecifier *Qualifier = PDE->getQualifier();
3395     QualType ScopeType;
3396     if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
3397       if (Qualifier) {
3398         mangleUnresolvedPrefix(Qualifier,
3399                                /*Recursive=*/true);
3400         mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
3401         Out << 'E';
3402       } else {
3403         Out << "sr";
3404         if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
3405           Out << 'E';
3406       }
3407     } else if (Qualifier) {
3408       mangleUnresolvedPrefix(Qualifier);
3409     }
3410     // <base-unresolved-name> ::= dn <destructor-name>
3411     Out << "dn";
3412     QualType DestroyedType = PDE->getDestroyedType();
3413     mangleUnresolvedTypeOrSimpleId(DestroyedType);
3414     break;
3415   }
3416
3417   case Expr::MemberExprClass: {
3418     const MemberExpr *ME = cast<MemberExpr>(E);
3419     mangleMemberExpr(ME->getBase(), ME->isArrow(),
3420                      ME->getQualifier(), nullptr,
3421                      ME->getMemberDecl()->getDeclName(), Arity);
3422     break;
3423   }
3424
3425   case Expr::UnresolvedMemberExprClass: {
3426     const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
3427     mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3428                      ME->isArrow(), ME->getQualifier(), nullptr,
3429                      ME->getMemberName(), Arity);
3430     if (ME->hasExplicitTemplateArgs())
3431       mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
3432     break;
3433   }
3434
3435   case Expr::CXXDependentScopeMemberExprClass: {
3436     const CXXDependentScopeMemberExpr *ME
3437       = cast<CXXDependentScopeMemberExpr>(E);
3438     mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
3439                      ME->isArrow(), ME->getQualifier(),
3440                      ME->getFirstQualifierFoundInScope(),
3441                      ME->getMember(), Arity);
3442     if (ME->hasExplicitTemplateArgs())
3443       mangleTemplateArgs(ME->getTemplateArgs(), ME->getNumTemplateArgs());
3444     break;
3445   }
3446
3447   case Expr::UnresolvedLookupExprClass: {
3448     const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
3449     mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity);
3450
3451     // All the <unresolved-name> productions end in a
3452     // base-unresolved-name, where <template-args> are just tacked
3453     // onto the end.
3454     if (ULE->hasExplicitTemplateArgs())
3455       mangleTemplateArgs(ULE->getTemplateArgs(), ULE->getNumTemplateArgs());
3456     break;
3457   }
3458
3459   case Expr::CXXUnresolvedConstructExprClass: {
3460     const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
3461     unsigned N = CE->arg_size();
3462
3463     Out << "cv";
3464     mangleType(CE->getType());
3465     if (N != 1) Out << '_';
3466     for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
3467     if (N != 1) Out << 'E';
3468     break;
3469   }
3470
3471   case Expr::CXXConstructExprClass: {
3472     const auto *CE = cast<CXXConstructExpr>(E);
3473     if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
3474       assert(
3475           CE->getNumArgs() >= 1 &&
3476           (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
3477           "implicit CXXConstructExpr must have one argument");
3478       return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0));
3479     }
3480     Out << "il";
3481     for (auto *E : CE->arguments())
3482       mangleExpression(E);
3483     Out << "E";
3484     break;
3485   }
3486
3487   case Expr::CXXTemporaryObjectExprClass: {
3488     const auto *CE = cast<CXXTemporaryObjectExpr>(E);
3489     unsigned N = CE->getNumArgs();
3490     bool List = CE->isListInitialization();
3491
3492     if (List)
3493       Out << "tl";
3494     else
3495       Out << "cv";
3496     mangleType(CE->getType());
3497     if (!List && N != 1)
3498       Out << '_';
3499     if (CE->isStdInitListInitialization()) {
3500       // We implicitly created a std::initializer_list<T> for the first argument
3501       // of a constructor of type U in an expression of the form U{a, b, c}.
3502       // Strip all the semantic gunk off the initializer list.
3503       auto *SILE =
3504           cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
3505       auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
3506       mangleInitListElements(ILE);
3507     } else {
3508       for (auto *E : CE->arguments())
3509         mangleExpression(E);
3510     }
3511     if (List || N != 1)
3512       Out << 'E';
3513     break;
3514   }
3515
3516   case Expr::CXXScalarValueInitExprClass:
3517     Out << "cv";
3518     mangleType(E->getType());
3519     Out << "_E";
3520     break;
3521
3522   case Expr::CXXNoexceptExprClass:
3523     Out << "nx";
3524     mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
3525     break;
3526
3527   case Expr::UnaryExprOrTypeTraitExprClass: {
3528     const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
3529     
3530     if (!SAE->isInstantiationDependent()) {
3531       // Itanium C++ ABI:
3532       //   If the operand of a sizeof or alignof operator is not 
3533       //   instantiation-dependent it is encoded as an integer literal 
3534       //   reflecting the result of the operator.
3535       //
3536       //   If the result of the operator is implicitly converted to a known 
3537       //   integer type, that type is used for the literal; otherwise, the type 
3538       //   of std::size_t or std::ptrdiff_t is used.
3539       QualType T = (ImplicitlyConvertedToType.isNull() || 
3540                     !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
3541                                                     : ImplicitlyConvertedToType;
3542       llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
3543       mangleIntegerLiteral(T, V);
3544       break;
3545     }
3546     
3547     switch(SAE->getKind()) {
3548     case UETT_SizeOf:
3549       Out << 's';
3550       break;
3551     case UETT_AlignOf:
3552       Out << 'a';
3553       break;
3554     case UETT_VecStep: {
3555       DiagnosticsEngine &Diags = Context.getDiags();
3556       unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3557                                      "cannot yet mangle vec_step expression");
3558       Diags.Report(DiagID);
3559       return;
3560     }
3561     case UETT_OpenMPRequiredSimdAlign:
3562       DiagnosticsEngine &Diags = Context.getDiags();
3563       unsigned DiagID = Diags.getCustomDiagID(
3564           DiagnosticsEngine::Error,
3565           "cannot yet mangle __builtin_omp_required_simd_align expression");
3566       Diags.Report(DiagID);
3567       return;
3568     }
3569     if (SAE->isArgumentType()) {
3570       Out << 't';
3571       mangleType(SAE->getArgumentType());
3572     } else {
3573       Out << 'z';
3574       mangleExpression(SAE->getArgumentExpr());
3575     }
3576     break;
3577   }
3578
3579   case Expr::CXXThrowExprClass: {
3580     const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
3581     //  <expression> ::= tw <expression>  # throw expression
3582     //               ::= tr               # rethrow
3583     if (TE->getSubExpr()) {
3584       Out << "tw";
3585       mangleExpression(TE->getSubExpr());
3586     } else {
3587       Out << "tr";
3588     }
3589     break;
3590   }
3591
3592   case Expr::CXXTypeidExprClass: {
3593     const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
3594     //  <expression> ::= ti <type>        # typeid (type)
3595     //               ::= te <expression>  # typeid (expression)
3596     if (TIE->isTypeOperand()) {
3597       Out << "ti";
3598       mangleType(TIE->getTypeOperand(Context.getASTContext()));
3599     } else {
3600       Out << "te";
3601       mangleExpression(TIE->getExprOperand());
3602     }
3603     break;
3604   }
3605
3606   case Expr::CXXDeleteExprClass: {
3607     const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
3608     //  <expression> ::= [gs] dl <expression>  # [::] delete expr
3609     //               ::= [gs] da <expression>  # [::] delete [] expr
3610     if (DE->isGlobalDelete()) Out << "gs";
3611     Out << (DE->isArrayForm() ? "da" : "dl");
3612     mangleExpression(DE->getArgument());
3613     break;
3614   }
3615
3616   case Expr::UnaryOperatorClass: {
3617     const UnaryOperator *UO = cast<UnaryOperator>(E);
3618     mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
3619                        /*Arity=*/1);
3620     mangleExpression(UO->getSubExpr());
3621     break;
3622   }
3623
3624   case Expr::ArraySubscriptExprClass: {
3625     const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
3626
3627     // Array subscript is treated as a syntactically weird form of
3628     // binary operator.
3629     Out << "ix";
3630     mangleExpression(AE->getLHS());
3631     mangleExpression(AE->getRHS());
3632     break;
3633   }
3634
3635   case Expr::CompoundAssignOperatorClass: // fallthrough
3636   case Expr::BinaryOperatorClass: {
3637     const BinaryOperator *BO = cast<BinaryOperator>(E);
3638     if (BO->getOpcode() == BO_PtrMemD)
3639       Out << "ds";
3640     else
3641       mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
3642                          /*Arity=*/2);
3643     mangleExpression(BO->getLHS());
3644     mangleExpression(BO->getRHS());
3645     break;
3646   }
3647
3648   case Expr::ConditionalOperatorClass: {
3649     const ConditionalOperator *CO = cast<ConditionalOperator>(E);
3650     mangleOperatorName(OO_Conditional, /*Arity=*/3);
3651     mangleExpression(CO->getCond());
3652     mangleExpression(CO->getLHS(), Arity);
3653     mangleExpression(CO->getRHS(), Arity);
3654     break;
3655   }
3656
3657   case Expr::ImplicitCastExprClass: {
3658     ImplicitlyConvertedToType = E->getType();
3659     E = cast<ImplicitCastExpr>(E)->getSubExpr();
3660     goto recurse;
3661   }
3662       
3663   case Expr::ObjCBridgedCastExprClass: {
3664     // Mangle ownership casts as a vendor extended operator __bridge, 
3665     // __bridge_transfer, or __bridge_retain.
3666     StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
3667     Out << "v1U" << Kind.size() << Kind;
3668   }
3669   // Fall through to mangle the cast itself.
3670       
3671   case Expr::CStyleCastExprClass:
3672     mangleCastExpression(E, "cv");
3673     break;
3674
3675   case Expr::CXXFunctionalCastExprClass: {
3676     auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
3677     // FIXME: Add isImplicit to CXXConstructExpr.
3678     if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
3679       if (CCE->getParenOrBraceRange().isInvalid())
3680         Sub = CCE->getArg(0)->IgnoreImplicit();
3681     if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
3682       Sub = StdInitList->getSubExpr()->IgnoreImplicit();
3683     if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
3684       Out << "tl";
3685       mangleType(E->getType());
3686       mangleInitListElements(IL);
3687       Out << "E";
3688     } else {
3689       mangleCastExpression(E, "cv");
3690     }
3691     break;
3692   }
3693
3694   case Expr::CXXStaticCastExprClass:
3695     mangleCastExpression(E, "sc");
3696     break;
3697   case Expr::CXXDynamicCastExprClass:
3698     mangleCastExpression(E, "dc");
3699     break;
3700   case Expr::CXXReinterpretCastExprClass:
3701     mangleCastExpression(E, "rc");
3702     break;
3703   case Expr::CXXConstCastExprClass:
3704     mangleCastExpression(E, "cc");
3705     break;
3706
3707   case Expr::CXXOperatorCallExprClass: {
3708     const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
3709     unsigned NumArgs = CE->getNumArgs();
3710     mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
3711     // Mangle the arguments.
3712     for (unsigned i = 0; i != NumArgs; ++i)
3713       mangleExpression(CE->getArg(i));
3714     break;
3715   }
3716
3717   case Expr::ParenExprClass:
3718     mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity);
3719     break;
3720
3721   case Expr::DeclRefExprClass: {
3722     const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
3723
3724     switch (D->getKind()) {
3725     default:
3726       //  <expr-primary> ::= L <mangled-name> E # external name
3727       Out << 'L';
3728       mangle(D);
3729       Out << 'E';
3730       break;
3731
3732     case Decl::ParmVar:
3733       mangleFunctionParam(cast<ParmVarDecl>(D));
3734       break;
3735
3736     case Decl::EnumConstant: {
3737       const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
3738       mangleIntegerLiteral(ED->getType(), ED->getInitVal());
3739       break;
3740     }
3741
3742     case Decl::NonTypeTemplateParm: {
3743       const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
3744       mangleTemplateParameter(PD->getIndex());
3745       break;
3746     }
3747
3748     }
3749
3750     break;
3751   }
3752
3753   case Expr::SubstNonTypeTemplateParmPackExprClass:
3754     // FIXME: not clear how to mangle this!
3755     // template <unsigned N...> class A {
3756     //   template <class U...> void foo(U (&x)[N]...);
3757     // };
3758     Out << "_SUBSTPACK_";
3759     break;
3760
3761   case Expr::FunctionParmPackExprClass: {
3762     // FIXME: not clear how to mangle this!
3763     const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
3764     Out << "v110_SUBSTPACK";
3765     mangleFunctionParam(FPPE->getParameterPack());
3766     break;
3767   }
3768
3769   case Expr::DependentScopeDeclRefExprClass: {
3770     const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
3771     mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity);
3772
3773     // All the <unresolved-name> productions end in a
3774     // base-unresolved-name, where <template-args> are just tacked
3775     // onto the end.
3776     if (DRE->hasExplicitTemplateArgs())
3777       mangleTemplateArgs(DRE->getTemplateArgs(), DRE->getNumTemplateArgs());
3778     break;
3779   }
3780
3781   case Expr::CXXBindTemporaryExprClass:
3782     mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr());
3783     break;
3784
3785   case Expr::ExprWithCleanupsClass:
3786     mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity);
3787     break;
3788
3789   case Expr::FloatingLiteralClass: {
3790     const FloatingLiteral *FL = cast<FloatingLiteral>(E);
3791     Out << 'L';
3792     mangleType(FL->getType());
3793     mangleFloat(FL->getValue());
3794     Out << 'E';
3795     break;
3796   }
3797
3798   case Expr::CharacterLiteralClass:
3799     Out << 'L';
3800     mangleType(E->getType());
3801     Out << cast<CharacterLiteral>(E)->getValue();
3802     Out << 'E';
3803     break;
3804
3805   // FIXME. __objc_yes/__objc_no are mangled same as true/false
3806   case Expr::ObjCBoolLiteralExprClass:
3807     Out << "Lb";
3808     Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3809     Out << 'E';
3810     break;
3811   
3812   case Expr::CXXBoolLiteralExprClass:
3813     Out << "Lb";
3814     Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
3815     Out << 'E';
3816     break;
3817
3818   case Expr::IntegerLiteralClass: {
3819     llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
3820     if (E->getType()->isSignedIntegerType())
3821       Value.setIsSigned(true);
3822     mangleIntegerLiteral(E->getType(), Value);
3823     break;
3824   }
3825
3826   case Expr::ImaginaryLiteralClass: {
3827     const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
3828     // Mangle as if a complex literal.
3829     // Proposal from David Vandevoorde, 2010.06.30.
3830     Out << 'L';
3831     mangleType(E->getType());
3832     if (const FloatingLiteral *Imag =
3833           dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
3834       // Mangle a floating-point zero of the appropriate type.
3835       mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
3836       Out << '_';
3837       mangleFloat(Imag->getValue());
3838     } else {
3839       Out << "0_";
3840       llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
3841       if (IE->getSubExpr()->getType()->isSignedIntegerType())
3842         Value.setIsSigned(true);
3843       mangleNumber(Value);
3844     }
3845     Out << 'E';
3846     break;
3847   }
3848
3849   case Expr::StringLiteralClass: {
3850     // Revised proposal from David Vandervoorde, 2010.07.15.
3851     Out << 'L';
3852     assert(isa<ConstantArrayType>(E->getType()));
3853     mangleType(E->getType());
3854     Out << 'E';
3855     break;
3856   }
3857
3858   case Expr::GNUNullExprClass:
3859     // FIXME: should this really be mangled the same as nullptr?
3860     // fallthrough
3861
3862   case Expr::CXXNullPtrLiteralExprClass: {
3863     Out << "LDnE";
3864     break;
3865   }
3866       
3867   case Expr::PackExpansionExprClass:
3868     Out << "sp";
3869     mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
3870     break;
3871       
3872   case Expr::SizeOfPackExprClass: {
3873     auto *SPE = cast<SizeOfPackExpr>(E);
3874     if (SPE->isPartiallySubstituted()) {
3875       Out << "sP";
3876       for (const auto &A : SPE->getPartialArguments())
3877         mangleTemplateArg(A);
3878       Out << "E";
3879       break;
3880     }
3881
3882     Out << "sZ";
3883     const NamedDecl *Pack = SPE->getPack();
3884     if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
3885       mangleTemplateParameter(TTP->getIndex());
3886     else if (const NonTypeTemplateParmDecl *NTTP
3887                 = dyn_cast<NonTypeTemplateParmDecl>(Pack))
3888       mangleTemplateParameter(NTTP->getIndex());
3889     else if (const TemplateTemplateParmDecl *TempTP
3890                                     = dyn_cast<TemplateTemplateParmDecl>(Pack))
3891       mangleTemplateParameter(TempTP->getIndex());
3892     else
3893       mangleFunctionParam(cast<ParmVarDecl>(Pack));
3894     break;
3895   }
3896
3897   case Expr::MaterializeTemporaryExprClass: {
3898     mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr());
3899     break;
3900   }
3901
3902   case Expr::CXXFoldExprClass: {
3903     auto *FE = cast<CXXFoldExpr>(E);
3904     if (FE->isLeftFold())
3905       Out << (FE->getInit() ? "fL" : "fl");
3906     else
3907       Out << (FE->getInit() ? "fR" : "fr");
3908
3909     if (FE->getOperator() == BO_PtrMemD)
3910       Out << "ds";
3911     else
3912       mangleOperatorName(
3913           BinaryOperator::getOverloadedOperator(FE->getOperator()),
3914           /*Arity=*/2);
3915
3916     if (FE->getLHS())
3917       mangleExpression(FE->getLHS());
3918     if (FE->getRHS())
3919       mangleExpression(FE->getRHS());
3920     break;
3921   }
3922
3923   case Expr::CXXThisExprClass:
3924     Out << "fpT";
3925     break;
3926
3927   case Expr::CoawaitExprClass:
3928     // FIXME: Propose a non-vendor mangling.
3929     Out << "v18co_await";
3930     mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3931     break;
3932
3933   case Expr::CoyieldExprClass:
3934     // FIXME: Propose a non-vendor mangling.
3935     Out << "v18co_yield";
3936     mangleExpression(cast<CoawaitExpr>(E)->getOperand());
3937     break;
3938   }
3939 }
3940
3941 /// Mangle an expression which refers to a parameter variable.
3942 ///
3943 /// <expression>     ::= <function-param>
3944 /// <function-param> ::= fp <top-level CV-qualifiers> _      # L == 0, I == 0
3945 /// <function-param> ::= fp <top-level CV-qualifiers>
3946 ///                      <parameter-2 non-negative number> _ # L == 0, I > 0
3947 /// <function-param> ::= fL <L-1 non-negative number>
3948 ///                      p <top-level CV-qualifiers> _       # L > 0, I == 0
3949 /// <function-param> ::= fL <L-1 non-negative number>
3950 ///                      p <top-level CV-qualifiers>
3951 ///                      <I-1 non-negative number> _         # L > 0, I > 0
3952 ///
3953 /// L is the nesting depth of the parameter, defined as 1 if the
3954 /// parameter comes from the innermost function prototype scope
3955 /// enclosing the current context, 2 if from the next enclosing
3956 /// function prototype scope, and so on, with one special case: if
3957 /// we've processed the full parameter clause for the innermost
3958 /// function type, then L is one less.  This definition conveniently
3959 /// makes it irrelevant whether a function's result type was written
3960 /// trailing or leading, but is otherwise overly complicated; the
3961 /// numbering was first designed without considering references to
3962 /// parameter in locations other than return types, and then the
3963 /// mangling had to be generalized without changing the existing
3964 /// manglings.
3965 ///
3966 /// I is the zero-based index of the parameter within its parameter
3967 /// declaration clause.  Note that the original ABI document describes
3968 /// this using 1-based ordinals.
3969 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
3970   unsigned parmDepth = parm->getFunctionScopeDepth();
3971   unsigned parmIndex = parm->getFunctionScopeIndex();
3972
3973   // Compute 'L'.
3974   // parmDepth does not include the declaring function prototype.
3975   // FunctionTypeDepth does account for that.
3976   assert(parmDepth < FunctionTypeDepth.getDepth());
3977   unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
3978   if (FunctionTypeDepth.isInResultType())
3979     nestingDepth--;
3980
3981   if (nestingDepth == 0) {
3982     Out << "fp";
3983   } else {
3984     Out << "fL" << (nestingDepth - 1) << 'p';
3985   }
3986
3987   // Top-level qualifiers.  We don't have to worry about arrays here,
3988   // because parameters declared as arrays should already have been
3989   // transformed to have pointer type. FIXME: apparently these don't
3990   // get mangled if used as an rvalue of a known non-class type?
3991   assert(!parm->getType()->isArrayType()
3992          && "parameter's type is still an array type?");
3993   mangleQualifiers(parm->getType().getQualifiers());
3994
3995   // Parameter index.
3996   if (parmIndex != 0) {
3997     Out << (parmIndex - 1);
3998   }
3999   Out << '_';
4000 }
4001
4002 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
4003                                        const CXXRecordDecl *InheritedFrom) {
4004   // <ctor-dtor-name> ::= C1  # complete object constructor
4005   //                  ::= C2  # base object constructor
4006   //                  ::= CI1 <type> # complete inheriting constructor
4007   //                  ::= CI2 <type> # base inheriting constructor
4008   //
4009   // In addition, C5 is a comdat name with C1 and C2 in it.
4010   Out << 'C';
4011   if (InheritedFrom)
4012     Out << 'I';
4013   switch (T) {
4014   case Ctor_Complete:
4015     Out << '1';
4016     break;
4017   case Ctor_Base:
4018     Out << '2';
4019     break;
4020   case Ctor_Comdat:
4021     Out << '5';
4022     break;
4023   case Ctor_DefaultClosure:
4024   case Ctor_CopyingClosure:
4025     llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
4026   }
4027   if (InheritedFrom)
4028     mangleName(InheritedFrom);
4029 }
4030
4031 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
4032   // <ctor-dtor-name> ::= D0  # deleting destructor
4033   //                  ::= D1  # complete object destructor
4034   //                  ::= D2  # base object destructor
4035   //
4036   // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
4037   switch (T) {
4038   case Dtor_Deleting:
4039     Out << "D0";
4040     break;
4041   case Dtor_Complete:
4042     Out << "D1";
4043     break;
4044   case Dtor_Base:
4045     Out << "D2";
4046     break;
4047   case Dtor_Comdat:
4048     Out << "D5";
4049     break;
4050   }
4051 }
4052
4053 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs,
4054                                         unsigned NumTemplateArgs) {
4055   // <template-args> ::= I <template-arg>+ E
4056   Out << 'I';
4057   for (unsigned i = 0; i != NumTemplateArgs; ++i)
4058     mangleTemplateArg(TemplateArgs[i].getArgument());
4059   Out << 'E';
4060 }
4061
4062 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) {
4063   // <template-args> ::= I <template-arg>+ E
4064   Out << 'I';
4065   for (unsigned i = 0, e = AL.size(); i != e; ++i)
4066     mangleTemplateArg(AL[i]);
4067   Out << 'E';
4068 }
4069
4070 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs,
4071                                         unsigned NumTemplateArgs) {
4072   // <template-args> ::= I <template-arg>+ E
4073   Out << 'I';
4074   for (unsigned i = 0; i != NumTemplateArgs; ++i)
4075     mangleTemplateArg(TemplateArgs[i]);
4076   Out << 'E';
4077 }
4078
4079 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) {
4080   // <template-arg> ::= <type>              # type or template
4081   //                ::= X <expression> E    # expression
4082   //                ::= <expr-primary>      # simple expressions
4083   //                ::= J <template-arg>* E # argument pack
4084   if (!A.isInstantiationDependent() || A.isDependent())
4085     A = Context.getASTContext().getCanonicalTemplateArgument(A);
4086   
4087   switch (A.getKind()) {
4088   case TemplateArgument::Null:
4089     llvm_unreachable("Cannot mangle NULL template argument");
4090       
4091   case TemplateArgument::Type:
4092     mangleType(A.getAsType());
4093     break;
4094   case TemplateArgument::Template:
4095     // This is mangled as <type>.
4096     mangleType(A.getAsTemplate());
4097     break;
4098   case TemplateArgument::TemplateExpansion:
4099     // <type>  ::= Dp <type>          # pack expansion (C++0x)
4100     Out << "Dp";
4101     mangleType(A.getAsTemplateOrTemplatePattern());
4102     break;
4103   case TemplateArgument::Expression: {
4104     // It's possible to end up with a DeclRefExpr here in certain
4105     // dependent cases, in which case we should mangle as a
4106     // declaration.
4107     const Expr *E = A.getAsExpr()->IgnoreParens();
4108     if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
4109       const ValueDecl *D = DRE->getDecl();
4110       if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
4111         Out << 'L';
4112         mangle(D);
4113         Out << 'E';
4114         break;
4115       }
4116     }
4117     
4118     Out << 'X';
4119     mangleExpression(E);
4120     Out << 'E';
4121     break;
4122   }
4123   case TemplateArgument::Integral:
4124     mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
4125     break;
4126   case TemplateArgument::Declaration: {
4127     //  <expr-primary> ::= L <mangled-name> E # external name
4128     // Clang produces AST's where pointer-to-member-function expressions
4129     // and pointer-to-function expressions are represented as a declaration not
4130     // an expression. We compensate for it here to produce the correct mangling.
4131     ValueDecl *D = A.getAsDecl();
4132     bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType();
4133     if (compensateMangling) {
4134       Out << 'X';
4135       mangleOperatorName(OO_Amp, 1);
4136     }
4137
4138     Out << 'L';
4139     // References to external entities use the mangled name; if the name would
4140     // not normally be mangled then mangle it as unqualified.
4141     mangle(D);
4142     Out << 'E';
4143
4144     if (compensateMangling)
4145       Out << 'E';
4146
4147     break;
4148   }
4149   case TemplateArgument::NullPtr: {
4150     //  <expr-primary> ::= L <type> 0 E
4151     Out << 'L';
4152     mangleType(A.getNullPtrType());
4153     Out << "0E";
4154     break;
4155   }
4156   case TemplateArgument::Pack: {
4157     //  <template-arg> ::= J <template-arg>* E
4158     Out << 'J';
4159     for (const auto &P : A.pack_elements())
4160       mangleTemplateArg(P);
4161     Out << 'E';
4162   }
4163   }
4164 }
4165
4166 void CXXNameMangler::mangleTemplateParameter(unsigned Index) {
4167   // <template-param> ::= T_    # first template parameter
4168   //                  ::= T <parameter-2 non-negative number> _
4169   if (Index == 0)
4170     Out << "T_";
4171   else
4172     Out << 'T' << (Index - 1) << '_';
4173 }
4174
4175 void CXXNameMangler::mangleSeqID(unsigned SeqID) {
4176   if (SeqID == 1)
4177     Out << '0';
4178   else if (SeqID > 1) {
4179     SeqID--;
4180
4181     // <seq-id> is encoded in base-36, using digits and upper case letters.
4182     char Buffer[7]; // log(2**32) / log(36) ~= 7
4183     MutableArrayRef<char> BufferRef(Buffer);
4184     MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
4185
4186     for (; SeqID != 0; SeqID /= 36) {
4187       unsigned C = SeqID % 36;
4188       *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
4189     }
4190
4191     Out.write(I.base(), I - BufferRef.rbegin());
4192   }
4193   Out << '_';
4194 }
4195
4196 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
4197   bool result = mangleSubstitution(tname);
4198   assert(result && "no existing substitution for template name");
4199   (void) result;
4200 }
4201
4202 // <substitution> ::= S <seq-id> _
4203 //                ::= S_
4204 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
4205   // Try one of the standard substitutions first.
4206   if (mangleStandardSubstitution(ND))
4207     return true;
4208
4209   ND = cast<NamedDecl>(ND->getCanonicalDecl());
4210   return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
4211 }
4212
4213 /// Determine whether the given type has any qualifiers that are relevant for
4214 /// substitutions.
4215 static bool hasMangledSubstitutionQualifiers(QualType T) {
4216   Qualifiers Qs = T.getQualifiers();
4217   return Qs.getCVRQualifiers() || Qs.hasAddressSpace();
4218 }
4219
4220 bool CXXNameMangler::mangleSubstitution(QualType T) {
4221   if (!hasMangledSubstitutionQualifiers(T)) {
4222     if (const RecordType *RT = T->getAs<RecordType>())
4223       return mangleSubstitution(RT->getDecl());
4224   }
4225
4226   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4227
4228   return mangleSubstitution(TypePtr);
4229 }
4230
4231 bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
4232   if (TemplateDecl *TD = Template.getAsTemplateDecl())
4233     return mangleSubstitution(TD);
4234   
4235   Template = Context.getASTContext().getCanonicalTemplateName(Template);
4236   return mangleSubstitution(
4237                       reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4238 }
4239
4240 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
4241   llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
4242   if (I == Substitutions.end())
4243     return false;
4244
4245   unsigned SeqID = I->second;
4246   Out << 'S';
4247   mangleSeqID(SeqID);
4248
4249   return true;
4250 }
4251
4252 static bool isCharType(QualType T) {
4253   if (T.isNull())
4254     return false;
4255
4256   return T->isSpecificBuiltinType(BuiltinType::Char_S) ||
4257     T->isSpecificBuiltinType(BuiltinType::Char_U);
4258 }
4259
4260 /// Returns whether a given type is a template specialization of a given name
4261 /// with a single argument of type char.
4262 static bool isCharSpecialization(QualType T, const char *Name) {
4263   if (T.isNull())
4264     return false;
4265
4266   const RecordType *RT = T->getAs<RecordType>();
4267   if (!RT)
4268     return false;
4269
4270   const ClassTemplateSpecializationDecl *SD =
4271     dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
4272   if (!SD)
4273     return false;
4274
4275   if (!isStdNamespace(getEffectiveDeclContext(SD)))
4276     return false;
4277
4278   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4279   if (TemplateArgs.size() != 1)
4280     return false;
4281
4282   if (!isCharType(TemplateArgs[0].getAsType()))
4283     return false;
4284
4285   return SD->getIdentifier()->getName() == Name;
4286 }
4287
4288 template <std::size_t StrLen>
4289 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD,
4290                                        const char (&Str)[StrLen]) {
4291   if (!SD->getIdentifier()->isStr(Str))
4292     return false;
4293
4294   const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4295   if (TemplateArgs.size() != 2)
4296     return false;
4297
4298   if (!isCharType(TemplateArgs[0].getAsType()))
4299     return false;
4300
4301   if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4302     return false;
4303
4304   return true;
4305 }
4306
4307 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
4308   // <substitution> ::= St # ::std::
4309   if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
4310     if (isStd(NS)) {
4311       Out << "St";
4312       return true;
4313     }
4314   }
4315
4316   if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
4317     if (!isStdNamespace(getEffectiveDeclContext(TD)))
4318       return false;
4319
4320     // <substitution> ::= Sa # ::std::allocator
4321     if (TD->getIdentifier()->isStr("allocator")) {
4322       Out << "Sa";
4323       return true;
4324     }
4325
4326     // <<substitution> ::= Sb # ::std::basic_string
4327     if (TD->getIdentifier()->isStr("basic_string")) {
4328       Out << "Sb";
4329       return true;
4330     }
4331   }
4332
4333   if (const ClassTemplateSpecializationDecl *SD =
4334         dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
4335     if (!isStdNamespace(getEffectiveDeclContext(SD)))
4336       return false;
4337
4338     //    <substitution> ::= Ss # ::std::basic_string<char,
4339     //                            ::std::char_traits<char>,
4340     //                            ::std::allocator<char> >
4341     if (SD->getIdentifier()->isStr("basic_string")) {
4342       const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
4343
4344       if (TemplateArgs.size() != 3)
4345         return false;
4346
4347       if (!isCharType(TemplateArgs[0].getAsType()))
4348         return false;
4349
4350       if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits"))
4351         return false;
4352
4353       if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator"))
4354         return false;
4355
4356       Out << "Ss";
4357       return true;
4358     }
4359
4360     //    <substitution> ::= Si # ::std::basic_istream<char,
4361     //                            ::std::char_traits<char> >
4362     if (isStreamCharSpecialization(SD, "basic_istream")) {
4363       Out << "Si";
4364       return true;
4365     }
4366
4367     //    <substitution> ::= So # ::std::basic_ostream<char,
4368     //                            ::std::char_traits<char> >
4369     if (isStreamCharSpecialization(SD, "basic_ostream")) {
4370       Out << "So";
4371       return true;
4372     }
4373
4374     //    <substitution> ::= Sd # ::std::basic_iostream<char,
4375     //                            ::std::char_traits<char> >
4376     if (isStreamCharSpecialization(SD, "basic_iostream")) {
4377       Out << "Sd";
4378       return true;
4379     }
4380   }
4381   return false;
4382 }
4383
4384 void CXXNameMangler::addSubstitution(QualType T) {
4385   if (!hasMangledSubstitutionQualifiers(T)) {
4386     if (const RecordType *RT = T->getAs<RecordType>()) {
4387       addSubstitution(RT->getDecl());
4388       return;
4389     }
4390   }
4391
4392   uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
4393   addSubstitution(TypePtr);
4394 }
4395
4396 void CXXNameMangler::addSubstitution(TemplateName Template) {
4397   if (TemplateDecl *TD = Template.getAsTemplateDecl())
4398     return addSubstitution(TD);
4399   
4400   Template = Context.getASTContext().getCanonicalTemplateName(Template);
4401   addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
4402 }
4403
4404 void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
4405   assert(!Substitutions.count(Ptr) && "Substitution already exists!");
4406   Substitutions[Ptr] = SeqID++;
4407 }
4408
4409 CXXNameMangler::AbiTagList
4410 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
4411   // When derived abi tags are disabled there is no need to make any list.
4412   if (DisableDerivedAbiTags)
4413     return AbiTagList();
4414
4415   llvm::raw_null_ostream NullOutStream;
4416   CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
4417   TrackReturnTypeTags.disableDerivedAbiTags();
4418
4419   const FunctionProtoType *Proto =
4420       cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
4421   TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
4422   TrackReturnTypeTags.mangleType(Proto->getReturnType());
4423   TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
4424
4425   return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4426 }
4427
4428 CXXNameMangler::AbiTagList
4429 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
4430   // When derived abi tags are disabled there is no need to make any list.
4431   if (DisableDerivedAbiTags)
4432     return AbiTagList();
4433
4434   llvm::raw_null_ostream NullOutStream;
4435   CXXNameMangler TrackVariableType(*this, NullOutStream);
4436   TrackVariableType.disableDerivedAbiTags();
4437
4438   TrackVariableType.mangleType(VD->getType());
4439
4440   return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
4441 }
4442
4443 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
4444                                        const VarDecl *VD) {
4445   llvm::raw_null_ostream NullOutStream;
4446   CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
4447   TrackAbiTags.mangle(VD);
4448   return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
4449 }
4450
4451 //
4452
4453 /// Mangles the name of the declaration D and emits that name to the given
4454 /// output stream.
4455 ///
4456 /// If the declaration D requires a mangled name, this routine will emit that
4457 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
4458 /// and this routine will return false. In this case, the caller should just
4459 /// emit the identifier of the declaration (\c D->getIdentifier()) as its
4460 /// name.
4461 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D,
4462                                              raw_ostream &Out) {
4463   assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) &&
4464           "Invalid mangleName() call, argument is not a variable or function!");
4465   assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) &&
4466          "Invalid mangleName() call on 'structor decl!");
4467
4468   PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
4469                                  getASTContext().getSourceManager(),
4470                                  "Mangling declaration");
4471
4472   CXXNameMangler Mangler(*this, Out, D);
4473   Mangler.mangle(D);
4474 }
4475
4476 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D,
4477                                              CXXCtorType Type,
4478                                              raw_ostream &Out) {
4479   CXXNameMangler Mangler(*this, Out, D, Type);
4480   Mangler.mangle(D);
4481 }
4482
4483 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D,
4484                                              CXXDtorType Type,
4485                                              raw_ostream &Out) {
4486   CXXNameMangler Mangler(*this, Out, D, Type);
4487   Mangler.mangle(D);
4488 }
4489
4490 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
4491                                                    raw_ostream &Out) {
4492   CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
4493   Mangler.mangle(D);
4494 }
4495
4496 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
4497                                                    raw_ostream &Out) {
4498   CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
4499   Mangler.mangle(D);
4500 }
4501
4502 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
4503                                            const ThunkInfo &Thunk,
4504                                            raw_ostream &Out) {
4505   //  <special-name> ::= T <call-offset> <base encoding>
4506   //                      # base is the nominal target function of thunk
4507   //  <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
4508   //                      # base is the nominal target function of thunk
4509   //                      # first call-offset is 'this' adjustment
4510   //                      # second call-offset is result adjustment
4511   
4512   assert(!isa<CXXDestructorDecl>(MD) &&
4513          "Use mangleCXXDtor for destructor decls!");
4514   CXXNameMangler Mangler(*this, Out);
4515   Mangler.getStream() << "_ZT";
4516   if (!Thunk.Return.isEmpty())
4517     Mangler.getStream() << 'c';
4518   
4519   // Mangle the 'this' pointer adjustment.
4520   Mangler.mangleCallOffset(Thunk.This.NonVirtual,
4521                            Thunk.This.Virtual.Itanium.VCallOffsetOffset);
4522
4523   // Mangle the return pointer adjustment if there is one.
4524   if (!Thunk.Return.isEmpty())
4525     Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
4526                              Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
4527
4528   Mangler.mangleFunctionEncoding(MD);
4529 }
4530
4531 void ItaniumMangleContextImpl::mangleCXXDtorThunk(
4532     const CXXDestructorDecl *DD, CXXDtorType Type,
4533     const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
4534   //  <special-name> ::= T <call-offset> <base encoding>
4535   //                      # base is the nominal target function of thunk
4536   CXXNameMangler Mangler(*this, Out, DD, Type);
4537   Mangler.getStream() << "_ZT";
4538
4539   // Mangle the 'this' pointer adjustment.
4540   Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 
4541                            ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
4542
4543   Mangler.mangleFunctionEncoding(DD);
4544 }
4545
4546 /// Returns the mangled name for a guard variable for the passed in VarDecl.
4547 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
4548                                                          raw_ostream &Out) {
4549   //  <special-name> ::= GV <object name>       # Guard variable for one-time
4550   //                                            # initialization
4551   CXXNameMangler Mangler(*this, Out);
4552   // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
4553   // be a bug that is fixed in trunk.
4554   Mangler.getStream() << "_ZGV";
4555   Mangler.mangleName(D);
4556 }
4557
4558 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
4559                                                         raw_ostream &Out) {
4560   // These symbols are internal in the Itanium ABI, so the names don't matter.
4561   // Clang has traditionally used this symbol and allowed LLVM to adjust it to
4562   // avoid duplicate symbols.
4563   Out << "__cxx_global_var_init";
4564 }
4565
4566 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
4567                                                              raw_ostream &Out) {
4568   // Prefix the mangling of D with __dtor_.
4569   CXXNameMangler Mangler(*this, Out);
4570   Mangler.getStream() << "__dtor_";
4571   if (shouldMangleDeclName(D))
4572     Mangler.mangle(D);
4573   else
4574     Mangler.getStream() << D->getName();
4575 }
4576
4577 void ItaniumMangleContextImpl::mangleSEHFilterExpression(
4578     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4579   CXXNameMangler Mangler(*this, Out);
4580   Mangler.getStream() << "__filt_";
4581   if (shouldMangleDeclName(EnclosingDecl))
4582     Mangler.mangle(EnclosingDecl);
4583   else
4584     Mangler.getStream() << EnclosingDecl->getName();
4585 }
4586
4587 void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
4588     const NamedDecl *EnclosingDecl, raw_ostream &Out) {
4589   CXXNameMangler Mangler(*this, Out);
4590   Mangler.getStream() << "__fin_";
4591   if (shouldMangleDeclName(EnclosingDecl))
4592     Mangler.mangle(EnclosingDecl);
4593   else
4594     Mangler.getStream() << EnclosingDecl->getName();
4595 }
4596
4597 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
4598                                                             raw_ostream &Out) {
4599   //  <special-name> ::= TH <object name>
4600   CXXNameMangler Mangler(*this, Out);
4601   Mangler.getStream() << "_ZTH";
4602   Mangler.mangleName(D);
4603 }
4604
4605 void
4606 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
4607                                                           raw_ostream &Out) {
4608   //  <special-name> ::= TW <object name>
4609   CXXNameMangler Mangler(*this, Out);
4610   Mangler.getStream() << "_ZTW";
4611   Mangler.mangleName(D);
4612 }
4613
4614 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
4615                                                         unsigned ManglingNumber,
4616                                                         raw_ostream &Out) {
4617   // We match the GCC mangling here.
4618   //  <special-name> ::= GR <object name>
4619   CXXNameMangler Mangler(*this, Out);
4620   Mangler.getStream() << "_ZGR";
4621   Mangler.mangleName(D);
4622   assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
4623   Mangler.mangleSeqID(ManglingNumber - 1);
4624 }
4625
4626 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
4627                                                raw_ostream &Out) {
4628   // <special-name> ::= TV <type>  # virtual table
4629   CXXNameMangler Mangler(*this, Out);
4630   Mangler.getStream() << "_ZTV";
4631   Mangler.mangleNameOrStandardSubstitution(RD);
4632 }
4633
4634 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
4635                                             raw_ostream &Out) {
4636   // <special-name> ::= TT <type>  # VTT structure
4637   CXXNameMangler Mangler(*this, Out);
4638   Mangler.getStream() << "_ZTT";
4639   Mangler.mangleNameOrStandardSubstitution(RD);
4640 }
4641
4642 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
4643                                                    int64_t Offset,
4644                                                    const CXXRecordDecl *Type,
4645                                                    raw_ostream &Out) {
4646   // <special-name> ::= TC <type> <offset number> _ <base type>
4647   CXXNameMangler Mangler(*this, Out);
4648   Mangler.getStream() << "_ZTC";
4649   Mangler.mangleNameOrStandardSubstitution(RD);
4650   Mangler.getStream() << Offset;
4651   Mangler.getStream() << '_';
4652   Mangler.mangleNameOrStandardSubstitution(Type);
4653 }
4654
4655 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
4656   // <special-name> ::= TI <type>  # typeinfo structure
4657   assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
4658   CXXNameMangler Mangler(*this, Out);
4659   Mangler.getStream() << "_ZTI";
4660   Mangler.mangleType(Ty);
4661 }
4662
4663 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
4664                                                  raw_ostream &Out) {
4665   // <special-name> ::= TS <type>  # typeinfo name (null terminated byte string)
4666   CXXNameMangler Mangler(*this, Out);
4667   Mangler.getStream() << "_ZTS";
4668   Mangler.mangleType(Ty);
4669 }
4670
4671 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
4672   mangleCXXRTTIName(Ty, Out);
4673 }
4674
4675 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
4676   llvm_unreachable("Can't mangle string literals");
4677 }
4678
4679 ItaniumMangleContext *
4680 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) {
4681   return new ItaniumMangleContextImpl(Context, Diags);
4682 }