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