Coverage Report

Created: 2022-01-18 06:27

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