Coverage Report

Created: 2021-01-23 06:44

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