Coverage Report

Created: 2024-01-17 10:31

/src/llvm-project/clang/lib/AST/MicrosoftMangle.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- MicrosoftMangle.cpp - Microsoft Visual C++ Name Mangling ---------===//
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
// This provides C++ name mangling targeting the Microsoft Visual C++ ABI.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/AST/ASTContext.h"
14
#include "clang/AST/Attr.h"
15
#include "clang/AST/CXXInheritance.h"
16
#include "clang/AST/CharUnits.h"
17
#include "clang/AST/Decl.h"
18
#include "clang/AST/DeclCXX.h"
19
#include "clang/AST/DeclObjC.h"
20
#include "clang/AST/DeclOpenMP.h"
21
#include "clang/AST/DeclTemplate.h"
22
#include "clang/AST/Expr.h"
23
#include "clang/AST/ExprCXX.h"
24
#include "clang/AST/GlobalDecl.h"
25
#include "clang/AST/Mangle.h"
26
#include "clang/AST/VTableBuilder.h"
27
#include "clang/Basic/ABI.h"
28
#include "clang/Basic/DiagnosticOptions.h"
29
#include "clang/Basic/FileManager.h"
30
#include "clang/Basic/SourceManager.h"
31
#include "clang/Basic/TargetInfo.h"
32
#include "llvm/ADT/SmallVector.h"
33
#include "llvm/ADT/StringExtras.h"
34
#include "llvm/Support/CRC.h"
35
#include "llvm/Support/MD5.h"
36
#include "llvm/Support/MathExtras.h"
37
#include "llvm/Support/StringSaver.h"
38
#include "llvm/Support/xxhash.h"
39
#include <functional>
40
#include <optional>
41
42
using namespace clang;
43
44
namespace {
45
46
// Get GlobalDecl of DeclContext of local entities.
47
0
static GlobalDecl getGlobalDeclAsDeclContext(const DeclContext *DC) {
48
0
  GlobalDecl GD;
49
0
  if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
50
0
    GD = GlobalDecl(CD, Ctor_Complete);
51
0
  else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
52
0
    GD = GlobalDecl(DD, Dtor_Complete);
53
0
  else
54
0
    GD = GlobalDecl(cast<FunctionDecl>(DC));
55
0
  return GD;
56
0
}
57
58
struct msvc_hashing_ostream : public llvm::raw_svector_ostream {
59
  raw_ostream &OS;
60
  llvm::SmallString<64> Buffer;
61
62
  msvc_hashing_ostream(raw_ostream &OS)
63
0
      : llvm::raw_svector_ostream(Buffer), OS(OS) {}
64
0
  ~msvc_hashing_ostream() override {
65
0
    StringRef MangledName = str();
66
0
    bool StartsWithEscape = MangledName.starts_with("\01");
67
0
    if (StartsWithEscape)
68
0
      MangledName = MangledName.drop_front(1);
69
0
    if (MangledName.size() < 4096) {
70
0
      OS << str();
71
0
      return;
72
0
    }
73
74
0
    llvm::MD5 Hasher;
75
0
    llvm::MD5::MD5Result Hash;
76
0
    Hasher.update(MangledName);
77
0
    Hasher.final(Hash);
78
79
0
    SmallString<32> HexString;
80
0
    llvm::MD5::stringifyResult(Hash, HexString);
81
82
0
    if (StartsWithEscape)
83
0
      OS << '\01';
84
0
    OS << "??@" << HexString << '@';
85
0
  }
86
};
87
88
static const DeclContext *
89
0
getLambdaDefaultArgumentDeclContext(const Decl *D) {
90
0
  if (const auto *RD = dyn_cast<CXXRecordDecl>(D))
91
0
    if (RD->isLambda())
92
0
      if (const auto *Parm =
93
0
              dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
94
0
        return Parm->getDeclContext();
95
0
  return nullptr;
96
0
}
97
98
/// Retrieve the declaration context that should be used when mangling
99
/// the given declaration.
100
0
static const DeclContext *getEffectiveDeclContext(const Decl *D) {
101
  // The ABI assumes that lambda closure types that occur within
102
  // default arguments live in the context of the function. However, due to
103
  // the way in which Clang parses and creates function declarations, this is
104
  // not the case: the lambda closure type ends up living in the context
105
  // where the function itself resides, because the function declaration itself
106
  // had not yet been created. Fix the context here.
107
0
  if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(D))
108
0
    return LDADC;
109
110
  // Perform the same check for block literals.
111
0
  if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
112
0
    if (ParmVarDecl *ContextParam =
113
0
            dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
114
0
      return ContextParam->getDeclContext();
115
0
  }
116
117
0
  const DeclContext *DC = D->getDeclContext();
118
0
  if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
119
0
      isa<OMPDeclareMapperDecl>(DC)) {
120
0
    return getEffectiveDeclContext(cast<Decl>(DC));
121
0
  }
122
123
0
  return DC->getRedeclContext();
124
0
}
125
126
0
static const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
127
0
  return getEffectiveDeclContext(cast<Decl>(DC));
128
0
}
129
130
0
static const FunctionDecl *getStructor(const NamedDecl *ND) {
131
0
  if (const auto *FTD = dyn_cast<FunctionTemplateDecl>(ND))
132
0
    return FTD->getTemplatedDecl()->getCanonicalDecl();
133
134
0
  const auto *FD = cast<FunctionDecl>(ND);
135
0
  if (const auto *FTD = FD->getPrimaryTemplate())
136
0
    return FTD->getTemplatedDecl()->getCanonicalDecl();
137
138
0
  return FD->getCanonicalDecl();
139
0
}
140
141
/// MicrosoftMangleContextImpl - Overrides the default MangleContext for the
142
/// Microsoft Visual C++ ABI.
143
class MicrosoftMangleContextImpl : public MicrosoftMangleContext {
144
  typedef std::pair<const DeclContext *, IdentifierInfo *> DiscriminatorKeyTy;
145
  llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
146
  llvm::DenseMap<const NamedDecl *, unsigned> Uniquifier;
147
  llvm::DenseMap<const CXXRecordDecl *, unsigned> LambdaIds;
148
  llvm::DenseMap<GlobalDecl, unsigned> SEHFilterIds;
149
  llvm::DenseMap<GlobalDecl, unsigned> SEHFinallyIds;
150
  SmallString<16> AnonymousNamespaceHash;
151
152
public:
153
  MicrosoftMangleContextImpl(ASTContext &Context, DiagnosticsEngine &Diags,
154
                             bool IsAux = false);
155
  bool shouldMangleCXXName(const NamedDecl *D) override;
156
  bool shouldMangleStringLiteral(const StringLiteral *SL) override;
157
  void mangleCXXName(GlobalDecl GD, raw_ostream &Out) override;
158
  void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
159
                                const MethodVFTableLocation &ML,
160
                                raw_ostream &Out) override;
161
  void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
162
                   raw_ostream &) override;
163
  void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
164
                          const ThisAdjustment &ThisAdjustment,
165
                          raw_ostream &) override;
166
  void mangleCXXVFTable(const CXXRecordDecl *Derived,
167
                        ArrayRef<const CXXRecordDecl *> BasePath,
168
                        raw_ostream &Out) override;
169
  void mangleCXXVBTable(const CXXRecordDecl *Derived,
170
                        ArrayRef<const CXXRecordDecl *> BasePath,
171
                        raw_ostream &Out) override;
172
  void mangleCXXVirtualDisplacementMap(const CXXRecordDecl *SrcRD,
173
                                       const CXXRecordDecl *DstRD,
174
                                       raw_ostream &Out) override;
175
  void mangleCXXThrowInfo(QualType T, bool IsConst, bool IsVolatile,
176
                          bool IsUnaligned, uint32_t NumEntries,
177
                          raw_ostream &Out) override;
178
  void mangleCXXCatchableTypeArray(QualType T, uint32_t NumEntries,
179
                                   raw_ostream &Out) override;
180
  void mangleCXXCatchableType(QualType T, const CXXConstructorDecl *CD,
181
                              CXXCtorType CT, uint32_t Size, uint32_t NVOffset,
182
                              int32_t VBPtrOffset, uint32_t VBIndex,
183
                              raw_ostream &Out) override;
184
  void mangleCXXRTTI(QualType T, raw_ostream &Out) override;
185
  void mangleCXXRTTIName(QualType T, raw_ostream &Out,
186
                         bool NormalizeIntegers) override;
187
  void mangleCXXRTTIBaseClassDescriptor(const CXXRecordDecl *Derived,
188
                                        uint32_t NVOffset, int32_t VBPtrOffset,
189
                                        uint32_t VBTableOffset, uint32_t Flags,
190
                                        raw_ostream &Out) override;
191
  void mangleCXXRTTIBaseClassArray(const CXXRecordDecl *Derived,
192
                                   raw_ostream &Out) override;
193
  void mangleCXXRTTIClassHierarchyDescriptor(const CXXRecordDecl *Derived,
194
                                             raw_ostream &Out) override;
195
  void
196
  mangleCXXRTTICompleteObjectLocator(const CXXRecordDecl *Derived,
197
                                     ArrayRef<const CXXRecordDecl *> BasePath,
198
                                     raw_ostream &Out) override;
199
  void mangleCanonicalTypeName(QualType T, raw_ostream &,
200
                               bool NormalizeIntegers) override;
201
  void mangleReferenceTemporary(const VarDecl *, unsigned ManglingNumber,
202
                                raw_ostream &) override;
203
  void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &Out) override;
204
  void mangleThreadSafeStaticGuardVariable(const VarDecl *D, unsigned GuardNum,
205
                                           raw_ostream &Out) override;
206
  void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
207
  void mangleDynamicAtExitDestructor(const VarDecl *D,
208
                                     raw_ostream &Out) override;
209
  void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,
210
                                 raw_ostream &Out) override;
211
  void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,
212
                             raw_ostream &Out) override;
213
  void mangleStringLiteral(const StringLiteral *SL, raw_ostream &Out) override;
214
0
  bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
215
0
    const DeclContext *DC = getEffectiveDeclContext(ND);
216
0
    if (!DC->isFunctionOrMethod())
217
0
      return false;
218
219
    // Lambda closure types are already numbered, give out a phony number so
220
    // that they demangle nicely.
221
0
    if (const auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
222
0
      if (RD->isLambda()) {
223
0
        disc = 1;
224
0
        return true;
225
0
      }
226
0
    }
227
228
    // Use the canonical number for externally visible decls.
229
0
    if (ND->isExternallyVisible()) {
230
0
      disc = getASTContext().getManglingNumber(ND, isAux());
231
0
      return true;
232
0
    }
233
234
    // Anonymous tags are already numbered.
235
0
    if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
236
0
      if (!Tag->hasNameForLinkage() &&
237
0
          !getASTContext().getDeclaratorForUnnamedTagDecl(Tag) &&
238
0
          !getASTContext().getTypedefNameForUnnamedTagDecl(Tag))
239
0
        return false;
240
0
    }
241
242
    // Make up a reasonable number for internal decls.
243
0
    unsigned &discriminator = Uniquifier[ND];
244
0
    if (!discriminator)
245
0
      discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
246
0
    disc = discriminator + 1;
247
0
    return true;
248
0
  }
249
250
0
  std::string getLambdaString(const CXXRecordDecl *Lambda) override {
251
0
    assert(Lambda->isLambda() && "RD must be a lambda!");
252
0
    std::string Name("<lambda_");
253
254
0
    Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
255
0
    unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
256
0
    unsigned LambdaId;
257
0
    const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
258
0
    const FunctionDecl *Func =
259
0
        Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
260
261
0
    if (Func) {
262
0
      unsigned DefaultArgNo =
263
0
          Func->getNumParams() - Parm->getFunctionScopeIndex();
264
0
      Name += llvm::utostr(DefaultArgNo);
265
0
      Name += "_";
266
0
    }
267
268
0
    if (LambdaManglingNumber)
269
0
      LambdaId = LambdaManglingNumber;
270
0
    else
271
0
      LambdaId = getLambdaIdForDebugInfo(Lambda);
272
273
0
    Name += llvm::utostr(LambdaId);
274
0
    Name += ">";
275
0
    return Name;
276
0
  }
277
278
0
  unsigned getLambdaId(const CXXRecordDecl *RD) {
279
0
    assert(RD->isLambda() && "RD must be a lambda!");
280
0
    assert(!RD->isExternallyVisible() && "RD must not be visible!");
281
0
    assert(RD->getLambdaManglingNumber() == 0 &&
282
0
           "RD must not have a mangling number!");
283
0
    std::pair<llvm::DenseMap<const CXXRecordDecl *, unsigned>::iterator, bool>
284
0
        Result = LambdaIds.insert(std::make_pair(RD, LambdaIds.size()));
285
0
    return Result.first->second;
286
0
  }
287
288
0
  unsigned getLambdaIdForDebugInfo(const CXXRecordDecl *RD) {
289
0
    assert(RD->isLambda() && "RD must be a lambda!");
290
0
    assert(!RD->isExternallyVisible() && "RD must not be visible!");
291
0
    assert(RD->getLambdaManglingNumber() == 0 &&
292
0
           "RD must not have a mangling number!");
293
    // The lambda should exist, but return 0 in case it doesn't.
294
0
    return LambdaIds.lookup(RD);
295
0
  }
296
297
  /// Return a character sequence that is (somewhat) unique to the TU suitable
298
  /// for mangling anonymous namespaces.
299
0
  StringRef getAnonymousNamespaceHash() const {
300
0
    return AnonymousNamespaceHash;
301
0
  }
302
303
private:
304
  void mangleInitFiniStub(const VarDecl *D, char CharCode, raw_ostream &Out);
305
};
306
307
/// MicrosoftCXXNameMangler - Manage the mangling of a single name for the
308
/// Microsoft Visual C++ ABI.
309
class MicrosoftCXXNameMangler {
310
  MicrosoftMangleContextImpl &Context;
311
  raw_ostream &Out;
312
313
  /// The "structor" is the top-level declaration being mangled, if
314
  /// that's not a template specialization; otherwise it's the pattern
315
  /// for that specialization.
316
  const NamedDecl *Structor;
317
  unsigned StructorType;
318
319
  typedef llvm::SmallVector<std::string, 10> BackRefVec;
320
  BackRefVec NameBackReferences;
321
322
  typedef llvm::DenseMap<const void *, unsigned> ArgBackRefMap;
323
  ArgBackRefMap FunArgBackReferences;
324
  ArgBackRefMap TemplateArgBackReferences;
325
326
  typedef llvm::DenseMap<const void *, StringRef> TemplateArgStringMap;
327
  TemplateArgStringMap TemplateArgStrings;
328
  llvm::BumpPtrAllocator TemplateArgStringStorageAlloc;
329
  llvm::StringSaver TemplateArgStringStorage;
330
331
  typedef std::set<std::pair<int, bool>> PassObjectSizeArgsSet;
332
  PassObjectSizeArgsSet PassObjectSizeArgs;
333
334
0
  ASTContext &getASTContext() const { return Context.getASTContext(); }
335
336
  const bool PointersAre64Bit;
337
338
public:
339
  enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
340
341
  MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_)
342
      : Context(C), Out(Out_), Structor(nullptr), StructorType(-1),
343
        TemplateArgStringStorage(TemplateArgStringStorageAlloc),
344
        PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(
345
0
                             LangAS::Default) == 64) {}
346
347
  MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
348
                          const CXXConstructorDecl *D, CXXCtorType Type)
349
      : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
350
        TemplateArgStringStorage(TemplateArgStringStorageAlloc),
351
        PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(
352
0
                             LangAS::Default) == 64) {}
353
354
  MicrosoftCXXNameMangler(MicrosoftMangleContextImpl &C, raw_ostream &Out_,
355
                          const CXXDestructorDecl *D, CXXDtorType Type)
356
      : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
357
        TemplateArgStringStorage(TemplateArgStringStorageAlloc),
358
        PointersAre64Bit(C.getASTContext().getTargetInfo().getPointerWidth(
359
0
                             LangAS::Default) == 64) {}
360
361
0
  raw_ostream &getStream() const { return Out; }
362
363
  void mangle(GlobalDecl GD, StringRef Prefix = "?");
364
  void mangleName(GlobalDecl GD);
365
  void mangleFunctionEncoding(GlobalDecl GD, bool ShouldMangle);
366
  void mangleVariableEncoding(const VarDecl *VD);
367
  void mangleMemberDataPointer(const CXXRecordDecl *RD, const ValueDecl *VD,
368
                               StringRef Prefix = "$");
369
  void mangleMemberDataPointerInClassNTTP(const CXXRecordDecl *,
370
                                          const ValueDecl *);
371
  void mangleMemberFunctionPointer(const CXXRecordDecl *RD,
372
                                   const CXXMethodDecl *MD,
373
                                   StringRef Prefix = "$");
374
  void mangleMemberFunctionPointerInClassNTTP(const CXXRecordDecl *RD,
375
                                              const CXXMethodDecl *MD);
376
  void mangleVirtualMemPtrThunk(const CXXMethodDecl *MD,
377
                                const MethodVFTableLocation &ML);
378
  void mangleNumber(int64_t Number);
379
  void mangleNumber(llvm::APSInt Number);
380
  void mangleFloat(llvm::APFloat Number);
381
  void mangleBits(llvm::APInt Number);
382
  void mangleTagTypeKind(TagTypeKind TK);
383
  void mangleArtificialTagType(TagTypeKind TK, StringRef UnqualifiedName,
384
                               ArrayRef<StringRef> NestedNames = std::nullopt);
385
  void mangleAddressSpaceType(QualType T, Qualifiers Quals, SourceRange Range);
386
  void mangleType(QualType T, SourceRange Range,
387
                  QualifierMangleMode QMM = QMM_Mangle);
388
  void mangleFunctionType(const FunctionType *T,
389
                          const FunctionDecl *D = nullptr,
390
                          bool ForceThisQuals = false,
391
                          bool MangleExceptionSpec = true);
392
  void mangleNestedName(GlobalDecl GD);
393
394
private:
395
0
  bool isStructorDecl(const NamedDecl *ND) const {
396
0
    return ND == Structor || getStructor(ND) == Structor;
397
0
  }
398
399
0
  bool is64BitPointer(Qualifiers Quals) const {
400
0
    LangAS AddrSpace = Quals.getAddressSpace();
401
0
    return AddrSpace == LangAS::ptr64 ||
402
0
           (PointersAre64Bit && !(AddrSpace == LangAS::ptr32_sptr ||
403
0
                                  AddrSpace == LangAS::ptr32_uptr));
404
0
  }
405
406
0
  void mangleUnqualifiedName(GlobalDecl GD) {
407
0
    mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName());
408
0
  }
409
  void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name);
410
  void mangleSourceName(StringRef Name);
411
  void mangleOperatorName(OverloadedOperatorKind OO, SourceLocation Loc);
412
  void mangleCXXDtorType(CXXDtorType T);
413
  void mangleQualifiers(Qualifiers Quals, bool IsMember);
414
  void mangleRefQualifier(RefQualifierKind RefQualifier);
415
  void manglePointerCVQualifiers(Qualifiers Quals);
416
  void manglePointerExtQualifiers(Qualifiers Quals, QualType PointeeType);
417
418
  void mangleUnscopedTemplateName(GlobalDecl GD);
419
  void
420
  mangleTemplateInstantiationName(GlobalDecl GD,
421
                                  const TemplateArgumentList &TemplateArgs);
422
  void mangleObjCMethodName(const ObjCMethodDecl *MD);
423
424
  void mangleFunctionArgumentType(QualType T, SourceRange Range);
425
  void manglePassObjectSizeArg(const PassObjectSizeAttr *POSA);
426
427
  bool isArtificialTagType(QualType T) const;
428
429
  // Declare manglers for every type class.
430
#define ABSTRACT_TYPE(CLASS, PARENT)
431
#define NON_CANONICAL_TYPE(CLASS, PARENT)
432
#define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T, \
433
                                            Qualifiers Quals, \
434
                                            SourceRange Range);
435
#include "clang/AST/TypeNodes.inc"
436
#undef ABSTRACT_TYPE
437
#undef NON_CANONICAL_TYPE
438
#undef TYPE
439
440
  void mangleType(const TagDecl *TD);
441
  void mangleDecayedArrayType(const ArrayType *T);
442
  void mangleArrayType(const ArrayType *T);
443
  void mangleFunctionClass(const FunctionDecl *FD);
444
  void mangleCallingConvention(CallingConv CC);
445
  void mangleCallingConvention(const FunctionType *T);
446
  void mangleIntegerLiteral(const llvm::APSInt &Number,
447
                            const NonTypeTemplateParmDecl *PD = nullptr,
448
                            QualType TemplateArgType = QualType());
449
  void mangleExpression(const Expr *E, const NonTypeTemplateParmDecl *PD);
450
  void mangleThrowSpecification(const FunctionProtoType *T);
451
452
  void mangleTemplateArgs(const TemplateDecl *TD,
453
                          const TemplateArgumentList &TemplateArgs);
454
  void mangleTemplateArg(const TemplateDecl *TD, const TemplateArgument &TA,
455
                         const NamedDecl *Parm);
456
  void mangleTemplateArgValue(QualType T, const APValue &V,
457
                              bool WithScalarType = false);
458
459
  void mangleObjCProtocol(const ObjCProtocolDecl *PD);
460
  void mangleObjCLifetime(const QualType T, Qualifiers Quals,
461
                          SourceRange Range);
462
  void mangleObjCKindOfType(const ObjCObjectType *T, Qualifiers Quals,
463
                            SourceRange Range);
464
};
465
}
466
467
MicrosoftMangleContextImpl::MicrosoftMangleContextImpl(ASTContext &Context,
468
                                                       DiagnosticsEngine &Diags,
469
                                                       bool IsAux)
470
0
    : MicrosoftMangleContext(Context, Diags, IsAux) {
471
  // To mangle anonymous namespaces, hash the path to the main source file. The
472
  // path should be whatever (probably relative) path was passed on the command
473
  // line. The goal is for the compiler to produce the same output regardless of
474
  // working directory, so use the uncanonicalized relative path.
475
  //
476
  // It's important to make the mangled names unique because, when CodeView
477
  // debug info is in use, the debugger uses mangled type names to distinguish
478
  // between otherwise identically named types in anonymous namespaces.
479
  //
480
  // These symbols are always internal, so there is no need for the hash to
481
  // match what MSVC produces. For the same reason, clang is free to change the
482
  // hash at any time without breaking compatibility with old versions of clang.
483
  // The generated names are intended to look similar to what MSVC generates,
484
  // which are something like "?A0x01234567@".
485
0
  SourceManager &SM = Context.getSourceManager();
486
0
  if (OptionalFileEntryRef FE = SM.getFileEntryRefForID(SM.getMainFileID())) {
487
    // Truncate the hash so we get 8 characters of hexadecimal.
488
0
    uint32_t TruncatedHash = uint32_t(xxh3_64bits(FE->getName()));
489
0
    AnonymousNamespaceHash = llvm::utohexstr(TruncatedHash);
490
0
  } else {
491
    // If we don't have a path to the main file, we'll just use 0.
492
0
    AnonymousNamespaceHash = "0";
493
0
  }
494
0
}
495
496
0
bool MicrosoftMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
497
0
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
498
0
    LanguageLinkage L = FD->getLanguageLinkage();
499
    // Overloadable functions need mangling.
500
0
    if (FD->hasAttr<OverloadableAttr>())
501
0
      return true;
502
503
    // The ABI expects that we would never mangle "typical" user-defined entry
504
    // points regardless of visibility or freestanding-ness.
505
    //
506
    // N.B. This is distinct from asking about "main".  "main" has a lot of
507
    // special rules associated with it in the standard while these
508
    // user-defined entry points are outside of the purview of the standard.
509
    // For example, there can be only one definition for "main" in a standards
510
    // compliant program; however nothing forbids the existence of wmain and
511
    // WinMain in the same translation unit.
512
0
    if (FD->isMSVCRTEntryPoint())
513
0
      return false;
514
515
    // C++ functions and those whose names are not a simple identifier need
516
    // mangling.
517
0
    if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
518
0
      return true;
519
520
    // C functions are not mangled.
521
0
    if (L == CLanguageLinkage)
522
0
      return false;
523
0
  }
524
525
  // Otherwise, no mangling is done outside C++ mode.
526
0
  if (!getASTContext().getLangOpts().CPlusPlus)
527
0
    return false;
528
529
0
  const VarDecl *VD = dyn_cast<VarDecl>(D);
530
0
  if (VD && !isa<DecompositionDecl>(D)) {
531
    // C variables are not mangled.
532
0
    if (VD->isExternC())
533
0
      return false;
534
535
    // Variables at global scope with internal linkage are not mangled.
536
0
    const DeclContext *DC = getEffectiveDeclContext(D);
537
    // Check for extern variable declared locally.
538
0
    if (DC->isFunctionOrMethod() && D->hasLinkage())
539
0
      while (!DC->isNamespace() && !DC->isTranslationUnit())
540
0
        DC = getEffectiveParentContext(DC);
541
542
0
    if (DC->isTranslationUnit() && D->getFormalLinkage() == Linkage::Internal &&
543
0
        !isa<VarTemplateSpecializationDecl>(D) && D->getIdentifier() != nullptr)
544
0
      return false;
545
0
  }
546
547
0
  return true;
548
0
}
549
550
bool
551
0
MicrosoftMangleContextImpl::shouldMangleStringLiteral(const StringLiteral *SL) {
552
0
  return true;
553
0
}
554
555
0
void MicrosoftCXXNameMangler::mangle(GlobalDecl GD, StringRef Prefix) {
556
0
  const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
557
  // MSVC doesn't mangle C++ names the same way it mangles extern "C" names.
558
  // Therefore it's really important that we don't decorate the
559
  // name with leading underscores or leading/trailing at signs. So, by
560
  // default, we emit an asm marker at the start so we get the name right.
561
  // Callers can override this with a custom prefix.
562
563
  // <mangled-name> ::= ? <name> <type-encoding>
564
0
  Out << Prefix;
565
0
  mangleName(GD);
566
0
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D))
567
0
    mangleFunctionEncoding(GD, Context.shouldMangleDeclName(FD));
568
0
  else if (const VarDecl *VD = dyn_cast<VarDecl>(D))
569
0
    mangleVariableEncoding(VD);
570
0
  else if (isa<MSGuidDecl>(D))
571
    // MSVC appears to mangle GUIDs as if they were variables of type
572
    // 'const struct __s_GUID'.
573
0
    Out << "3U__s_GUID@@B";
574
0
  else if (isa<TemplateParamObjectDecl>(D)) {
575
    // Template parameter objects don't get a <type-encoding>; their type is
576
    // specified as part of their value.
577
0
  } else
578
0
    llvm_unreachable("Tried to mangle unexpected NamedDecl!");
579
0
}
580
581
void MicrosoftCXXNameMangler::mangleFunctionEncoding(GlobalDecl GD,
582
0
                                                     bool ShouldMangle) {
583
0
  const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
584
  // <type-encoding> ::= <function-class> <function-type>
585
586
  // Since MSVC operates on the type as written and not the canonical type, it
587
  // actually matters which decl we have here.  MSVC appears to choose the
588
  // first, since it is most likely to be the declaration in a header file.
589
0
  FD = FD->getFirstDecl();
590
591
  // We should never ever see a FunctionNoProtoType at this point.
592
  // We don't even know how to mangle their types anyway :).
593
0
  const FunctionProtoType *FT = FD->getType()->castAs<FunctionProtoType>();
594
595
  // extern "C" functions can hold entities that must be mangled.
596
  // As it stands, these functions still need to get expressed in the full
597
  // external name.  They have their class and type omitted, replaced with '9'.
598
0
  if (ShouldMangle) {
599
    // We would like to mangle all extern "C" functions using this additional
600
    // component but this would break compatibility with MSVC's behavior.
601
    // Instead, do this when we know that compatibility isn't important (in
602
    // other words, when it is an overloaded extern "C" function).
603
0
    if (FD->isExternC() && FD->hasAttr<OverloadableAttr>())
604
0
      Out << "$$J0";
605
606
0
    mangleFunctionClass(FD);
607
608
0
    mangleFunctionType(FT, FD, false, false);
609
0
  } else {
610
0
    Out << '9';
611
0
  }
612
0
}
613
614
0
void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
615
  // <type-encoding> ::= <storage-class> <variable-type>
616
  // <storage-class> ::= 0  # private static member
617
  //                 ::= 1  # protected static member
618
  //                 ::= 2  # public static member
619
  //                 ::= 3  # global
620
  //                 ::= 4  # static local
621
622
  // The first character in the encoding (after the name) is the storage class.
623
0
  if (VD->isStaticDataMember()) {
624
    // If it's a static member, it also encodes the access level.
625
0
    switch (VD->getAccess()) {
626
0
      default:
627
0
      case AS_private: Out << '0'; break;
628
0
      case AS_protected: Out << '1'; break;
629
0
      case AS_public: Out << '2'; break;
630
0
    }
631
0
  }
632
0
  else if (!VD->isStaticLocal())
633
0
    Out << '3';
634
0
  else
635
0
    Out << '4';
636
  // Now mangle the type.
637
  // <variable-type> ::= <type> <cvr-qualifiers>
638
  //                 ::= <type> <pointee-cvr-qualifiers> # pointers, references
639
  // Pointers and references are odd. The type of 'int * const foo;' gets
640
  // mangled as 'QAHA' instead of 'PAHB', for example.
641
0
  SourceRange SR = VD->getSourceRange();
642
0
  QualType Ty = VD->getType();
643
0
  if (Ty->isPointerType() || Ty->isReferenceType() ||
644
0
      Ty->isMemberPointerType()) {
645
0
    mangleType(Ty, SR, QMM_Drop);
646
0
    manglePointerExtQualifiers(
647
0
        Ty.getDesugaredType(getASTContext()).getLocalQualifiers(), QualType());
648
0
    if (const MemberPointerType *MPT = Ty->getAs<MemberPointerType>()) {
649
0
      mangleQualifiers(MPT->getPointeeType().getQualifiers(), true);
650
      // Member pointers are suffixed with a back reference to the member
651
      // pointer's class name.
652
0
      mangleName(MPT->getClass()->getAsCXXRecordDecl());
653
0
    } else
654
0
      mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
655
0
  } else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
656
    // Global arrays are funny, too.
657
0
    mangleDecayedArrayType(AT);
658
0
    if (AT->getElementType()->isArrayType())
659
0
      Out << 'A';
660
0
    else
661
0
      mangleQualifiers(Ty.getQualifiers(), false);
662
0
  } else {
663
0
    mangleType(Ty, SR, QMM_Drop);
664
0
    mangleQualifiers(Ty.getQualifiers(), false);
665
0
  }
666
0
}
667
668
void MicrosoftCXXNameMangler::mangleMemberDataPointer(const CXXRecordDecl *RD,
669
                                                      const ValueDecl *VD,
670
0
                                                      StringRef Prefix) {
671
  // <member-data-pointer> ::= <integer-literal>
672
  //                       ::= $F <number> <number>
673
  //                       ::= $G <number> <number> <number>
674
675
0
  int64_t FieldOffset;
676
0
  int64_t VBTableOffset;
677
0
  MSInheritanceModel IM = RD->getMSInheritanceModel();
678
0
  if (VD) {
679
0
    FieldOffset = getASTContext().getFieldOffset(VD);
680
0
    assert(FieldOffset % getASTContext().getCharWidth() == 0 &&
681
0
           "cannot take address of bitfield");
682
0
    FieldOffset /= getASTContext().getCharWidth();
683
684
0
    VBTableOffset = 0;
685
686
0
    if (IM == MSInheritanceModel::Virtual)
687
0
      FieldOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
688
0
  } else {
689
0
    FieldOffset = RD->nullFieldOffsetIsZero() ? 0 : -1;
690
691
0
    VBTableOffset = -1;
692
0
  }
693
694
0
  char Code = '\0';
695
0
  switch (IM) {
696
0
  case MSInheritanceModel::Single:      Code = '0'; break;
697
0
  case MSInheritanceModel::Multiple:    Code = '0'; break;
698
0
  case MSInheritanceModel::Virtual:     Code = 'F'; break;
699
0
  case MSInheritanceModel::Unspecified: Code = 'G'; break;
700
0
  }
701
702
0
  Out << Prefix << Code;
703
704
0
  mangleNumber(FieldOffset);
705
706
  // The C++ standard doesn't allow base-to-derived member pointer conversions
707
  // in template parameter contexts, so the vbptr offset of data member pointers
708
  // is always zero.
709
0
  if (inheritanceModelHasVBPtrOffsetField(IM))
710
0
    mangleNumber(0);
711
0
  if (inheritanceModelHasVBTableOffsetField(IM))
712
0
    mangleNumber(VBTableOffset);
713
0
}
714
715
void MicrosoftCXXNameMangler::mangleMemberDataPointerInClassNTTP(
716
0
    const CXXRecordDecl *RD, const ValueDecl *VD) {
717
0
  MSInheritanceModel IM = RD->getMSInheritanceModel();
718
  // <nttp-class-member-data-pointer> ::= <member-data-pointer>
719
  //                                  ::= N
720
  //                                  ::= 8 <postfix> @ <unqualified-name> @
721
722
0
  if (IM != MSInheritanceModel::Single && IM != MSInheritanceModel::Multiple)
723
0
    return mangleMemberDataPointer(RD, VD, "");
724
725
0
  if (!VD) {
726
0
    Out << 'N';
727
0
    return;
728
0
  }
729
730
0
  Out << '8';
731
0
  mangleNestedName(VD);
732
0
  Out << '@';
733
0
  mangleUnqualifiedName(VD);
734
0
  Out << '@';
735
0
}
736
737
void
738
MicrosoftCXXNameMangler::mangleMemberFunctionPointer(const CXXRecordDecl *RD,
739
                                                     const CXXMethodDecl *MD,
740
0
                                                     StringRef Prefix) {
741
  // <member-function-pointer> ::= $1? <name>
742
  //                           ::= $H? <name> <number>
743
  //                           ::= $I? <name> <number> <number>
744
  //                           ::= $J? <name> <number> <number> <number>
745
746
0
  MSInheritanceModel IM = RD->getMSInheritanceModel();
747
748
0
  char Code = '\0';
749
0
  switch (IM) {
750
0
  case MSInheritanceModel::Single:      Code = '1'; break;
751
0
  case MSInheritanceModel::Multiple:    Code = 'H'; break;
752
0
  case MSInheritanceModel::Virtual:     Code = 'I'; break;
753
0
  case MSInheritanceModel::Unspecified: Code = 'J'; break;
754
0
  }
755
756
  // If non-virtual, mangle the name.  If virtual, mangle as a virtual memptr
757
  // thunk.
758
0
  uint64_t NVOffset = 0;
759
0
  uint64_t VBTableOffset = 0;
760
0
  uint64_t VBPtrOffset = 0;
761
0
  if (MD) {
762
0
    Out << Prefix << Code << '?';
763
0
    if (MD->isVirtual()) {
764
0
      MicrosoftVTableContext *VTContext =
765
0
          cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
766
0
      MethodVFTableLocation ML =
767
0
          VTContext->getMethodVFTableLocation(GlobalDecl(MD));
768
0
      mangleVirtualMemPtrThunk(MD, ML);
769
0
      NVOffset = ML.VFPtrOffset.getQuantity();
770
0
      VBTableOffset = ML.VBTableIndex * 4;
771
0
      if (ML.VBase) {
772
0
        const ASTRecordLayout &Layout = getASTContext().getASTRecordLayout(RD);
773
0
        VBPtrOffset = Layout.getVBPtrOffset().getQuantity();
774
0
      }
775
0
    } else {
776
0
      mangleName(MD);
777
0
      mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
778
0
    }
779
780
0
    if (VBTableOffset == 0 && IM == MSInheritanceModel::Virtual)
781
0
      NVOffset -= getASTContext().getOffsetOfBaseWithVBPtr(RD).getQuantity();
782
0
  } else {
783
    // Null single inheritance member functions are encoded as a simple nullptr.
784
0
    if (IM == MSInheritanceModel::Single) {
785
0
      Out << Prefix << "0A@";
786
0
      return;
787
0
    }
788
0
    if (IM == MSInheritanceModel::Unspecified)
789
0
      VBTableOffset = -1;
790
0
    Out << Prefix << Code;
791
0
  }
792
793
0
  if (inheritanceModelHasNVOffsetField(/*IsMemberFunction=*/true, IM))
794
0
    mangleNumber(static_cast<uint32_t>(NVOffset));
795
0
  if (inheritanceModelHasVBPtrOffsetField(IM))
796
0
    mangleNumber(VBPtrOffset);
797
0
  if (inheritanceModelHasVBTableOffsetField(IM))
798
0
    mangleNumber(VBTableOffset);
799
0
}
800
801
void MicrosoftCXXNameMangler::mangleMemberFunctionPointerInClassNTTP(
802
0
    const CXXRecordDecl *RD, const CXXMethodDecl *MD) {
803
  // <nttp-class-member-function-pointer> ::= <member-function-pointer>
804
  //                           ::= N
805
  //                           ::= E? <virtual-mem-ptr-thunk>
806
  //                           ::= E? <mangled-name> <type-encoding>
807
808
0
  if (!MD) {
809
0
    if (RD->getMSInheritanceModel() != MSInheritanceModel::Single)
810
0
      return mangleMemberFunctionPointer(RD, MD, "");
811
812
0
    Out << 'N';
813
0
    return;
814
0
  }
815
816
0
  Out << "E?";
817
0
  if (MD->isVirtual()) {
818
0
    MicrosoftVTableContext *VTContext =
819
0
        cast<MicrosoftVTableContext>(getASTContext().getVTableContext());
820
0
    MethodVFTableLocation ML =
821
0
        VTContext->getMethodVFTableLocation(GlobalDecl(MD));
822
0
    mangleVirtualMemPtrThunk(MD, ML);
823
0
  } else {
824
0
    mangleName(MD);
825
0
    mangleFunctionEncoding(MD, /*ShouldMangle=*/true);
826
0
  }
827
0
}
828
829
void MicrosoftCXXNameMangler::mangleVirtualMemPtrThunk(
830
0
    const CXXMethodDecl *MD, const MethodVFTableLocation &ML) {
831
  // Get the vftable offset.
832
0
  CharUnits PointerWidth = getASTContext().toCharUnitsFromBits(
833
0
      getASTContext().getTargetInfo().getPointerWidth(LangAS::Default));
834
0
  uint64_t OffsetInVFTable = ML.Index * PointerWidth.getQuantity();
835
836
0
  Out << "?_9";
837
0
  mangleName(MD->getParent());
838
0
  Out << "$B";
839
0
  mangleNumber(OffsetInVFTable);
840
0
  Out << 'A';
841
0
  mangleCallingConvention(MD->getType()->castAs<FunctionProtoType>());
842
0
}
843
844
0
void MicrosoftCXXNameMangler::mangleName(GlobalDecl GD) {
845
  // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
846
847
  // Always start with the unqualified name.
848
0
  mangleUnqualifiedName(GD);
849
850
0
  mangleNestedName(GD);
851
852
  // Terminate the whole name with an '@'.
853
0
  Out << '@';
854
0
}
855
856
0
void MicrosoftCXXNameMangler::mangleNumber(int64_t Number) {
857
0
  mangleNumber(llvm::APSInt(llvm::APInt(64, Number), /*IsUnsigned*/false));
858
0
}
859
860
0
void MicrosoftCXXNameMangler::mangleNumber(llvm::APSInt Number) {
861
  // MSVC never mangles any integer wider than 64 bits. In general it appears
862
  // to convert every integer to signed 64 bit before mangling (including
863
  // unsigned 64 bit values). Do the same, but preserve bits beyond the bottom
864
  // 64.
865
0
  unsigned Width = std::max(Number.getBitWidth(), 64U);
866
0
  llvm::APInt Value = Number.extend(Width);
867
868
  // <non-negative integer> ::= A@              # when Number == 0
869
  //                        ::= <decimal digit> # when 1 <= Number <= 10
870
  //                        ::= <hex digit>+ @  # when Number >= 10
871
  //
872
  // <number>               ::= [?] <non-negative integer>
873
874
0
  if (Value.isNegative()) {
875
0
    Value = -Value;
876
0
    Out << '?';
877
0
  }
878
0
  mangleBits(Value);
879
0
}
880
881
0
void MicrosoftCXXNameMangler::mangleFloat(llvm::APFloat Number) {
882
0
  using llvm::APFloat;
883
884
0
  switch (APFloat::SemanticsToEnum(Number.getSemantics())) {
885
0
  case APFloat::S_IEEEsingle: Out << 'A'; break;
886
0
  case APFloat::S_IEEEdouble: Out << 'B'; break;
887
888
  // The following are all Clang extensions. We try to pick manglings that are
889
  // unlikely to conflict with MSVC's scheme.
890
0
  case APFloat::S_IEEEhalf: Out << 'V'; break;
891
0
  case APFloat::S_BFloat: Out << 'W'; break;
892
0
  case APFloat::S_x87DoubleExtended: Out << 'X'; break;
893
0
  case APFloat::S_IEEEquad: Out << 'Y'; break;
894
0
  case APFloat::S_PPCDoubleDouble: Out << 'Z'; break;
895
0
  case APFloat::S_Float8E5M2:
896
0
  case APFloat::S_Float8E4M3FN:
897
0
  case APFloat::S_Float8E5M2FNUZ:
898
0
  case APFloat::S_Float8E4M3FNUZ:
899
0
  case APFloat::S_Float8E4M3B11FNUZ:
900
0
  case APFloat::S_FloatTF32:
901
0
    llvm_unreachable("Tried to mangle unexpected APFloat semantics");
902
0
  }
903
904
0
  mangleBits(Number.bitcastToAPInt());
905
0
}
906
907
0
void MicrosoftCXXNameMangler::mangleBits(llvm::APInt Value) {
908
0
  if (Value == 0)
909
0
    Out << "A@";
910
0
  else if (Value.uge(1) && Value.ule(10))
911
0
    Out << (Value - 1);
912
0
  else {
913
    // Numbers that are not encoded as decimal digits are represented as nibbles
914
    // in the range of ASCII characters 'A' to 'P'.
915
    // The number 0x123450 would be encoded as 'BCDEFA'
916
0
    llvm::SmallString<32> EncodedNumberBuffer;
917
0
    for (; Value != 0; Value.lshrInPlace(4))
918
0
      EncodedNumberBuffer.push_back('A' + (Value & 0xf).getZExtValue());
919
0
    std::reverse(EncodedNumberBuffer.begin(), EncodedNumberBuffer.end());
920
0
    Out.write(EncodedNumberBuffer.data(), EncodedNumberBuffer.size());
921
0
    Out << '@';
922
0
  }
923
0
}
924
925
static GlobalDecl isTemplate(GlobalDecl GD,
926
0
                             const TemplateArgumentList *&TemplateArgs) {
927
0
  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
928
  // Check if we have a function template.
929
0
  if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
930
0
    if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
931
0
      TemplateArgs = FD->getTemplateSpecializationArgs();
932
0
      return GD.getWithDecl(TD);
933
0
    }
934
0
  }
935
936
  // Check if we have a class template.
937
0
  if (const ClassTemplateSpecializationDecl *Spec =
938
0
          dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
939
0
    TemplateArgs = &Spec->getTemplateArgs();
940
0
    return GD.getWithDecl(Spec->getSpecializedTemplate());
941
0
  }
942
943
  // Check if we have a variable template.
944
0
  if (const VarTemplateSpecializationDecl *Spec =
945
0
          dyn_cast<VarTemplateSpecializationDecl>(ND)) {
946
0
    TemplateArgs = &Spec->getTemplateArgs();
947
0
    return GD.getWithDecl(Spec->getSpecializedTemplate());
948
0
  }
949
950
0
  return GlobalDecl();
951
0
}
952
953
void MicrosoftCXXNameMangler::mangleUnqualifiedName(GlobalDecl GD,
954
0
                                                    DeclarationName Name) {
955
0
  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
956
  //  <unqualified-name> ::= <operator-name>
957
  //                     ::= <ctor-dtor-name>
958
  //                     ::= <source-name>
959
  //                     ::= <template-name>
960
961
  // Check if we have a template.
962
0
  const TemplateArgumentList *TemplateArgs = nullptr;
963
0
  if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
964
    // Function templates aren't considered for name back referencing.  This
965
    // makes sense since function templates aren't likely to occur multiple
966
    // times in a symbol.
967
0
    if (isa<FunctionTemplateDecl>(TD.getDecl())) {
968
0
      mangleTemplateInstantiationName(TD, *TemplateArgs);
969
0
      Out << '@';
970
0
      return;
971
0
    }
972
973
    // Here comes the tricky thing: if we need to mangle something like
974
    //   void foo(A::X<Y>, B::X<Y>),
975
    // the X<Y> part is aliased. However, if you need to mangle
976
    //   void foo(A::X<A::Y>, A::X<B::Y>),
977
    // the A::X<> part is not aliased.
978
    // That is, from the mangler's perspective we have a structure like this:
979
    //   namespace[s] -> type[ -> template-parameters]
980
    // but from the Clang perspective we have
981
    //   type [ -> template-parameters]
982
    //      \-> namespace[s]
983
    // What we do is we create a new mangler, mangle the same type (without
984
    // a namespace suffix) to a string using the extra mangler and then use
985
    // the mangled type name as a key to check the mangling of different types
986
    // for aliasing.
987
988
    // It's important to key cache reads off ND, not TD -- the same TD can
989
    // be used with different TemplateArgs, but ND uniquely identifies
990
    // TD / TemplateArg pairs.
991
0
    ArgBackRefMap::iterator Found = TemplateArgBackReferences.find(ND);
992
0
    if (Found == TemplateArgBackReferences.end()) {
993
994
0
      TemplateArgStringMap::iterator Found = TemplateArgStrings.find(ND);
995
0
      if (Found == TemplateArgStrings.end()) {
996
        // Mangle full template name into temporary buffer.
997
0
        llvm::SmallString<64> TemplateMangling;
998
0
        llvm::raw_svector_ostream Stream(TemplateMangling);
999
0
        MicrosoftCXXNameMangler Extra(Context, Stream);
1000
0
        Extra.mangleTemplateInstantiationName(TD, *TemplateArgs);
1001
1002
        // Use the string backref vector to possibly get a back reference.
1003
0
        mangleSourceName(TemplateMangling);
1004
1005
        // Memoize back reference for this type if one exist, else memoize
1006
        // the mangling itself.
1007
0
        BackRefVec::iterator StringFound =
1008
0
            llvm::find(NameBackReferences, TemplateMangling);
1009
0
        if (StringFound != NameBackReferences.end()) {
1010
0
          TemplateArgBackReferences[ND] =
1011
0
              StringFound - NameBackReferences.begin();
1012
0
        } else {
1013
0
          TemplateArgStrings[ND] =
1014
0
              TemplateArgStringStorage.save(TemplateMangling.str());
1015
0
        }
1016
0
      } else {
1017
0
        Out << Found->second << '@'; // Outputs a StringRef.
1018
0
      }
1019
0
    } else {
1020
0
      Out << Found->second; // Outputs a back reference (an int).
1021
0
    }
1022
0
    return;
1023
0
  }
1024
1025
0
  switch (Name.getNameKind()) {
1026
0
    case DeclarationName::Identifier: {
1027
0
      if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) {
1028
0
        bool IsDeviceStub =
1029
0
            ND &&
1030
0
            ((isa<FunctionDecl>(ND) && ND->hasAttr<CUDAGlobalAttr>()) ||
1031
0
             (isa<FunctionTemplateDecl>(ND) &&
1032
0
              cast<FunctionTemplateDecl>(ND)
1033
0
                  ->getTemplatedDecl()
1034
0
                  ->hasAttr<CUDAGlobalAttr>())) &&
1035
0
            GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
1036
0
        if (IsDeviceStub)
1037
0
          mangleSourceName(
1038
0
              (llvm::Twine("__device_stub__") + II->getName()).str());
1039
0
        else
1040
0
          mangleSourceName(II->getName());
1041
0
        break;
1042
0
      }
1043
1044
      // Otherwise, an anonymous entity.  We must have a declaration.
1045
0
      assert(ND && "mangling empty name without declaration");
1046
1047
0
      if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
1048
0
        if (NS->isAnonymousNamespace()) {
1049
0
          Out << "?A0x" << Context.getAnonymousNamespaceHash() << '@';
1050
0
          break;
1051
0
        }
1052
0
      }
1053
1054
0
      if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(ND)) {
1055
        // Decomposition declarations are considered anonymous, and get
1056
        // numbered with a $S prefix.
1057
0
        llvm::SmallString<64> Name("$S");
1058
        // Get a unique id for the anonymous struct.
1059
0
        Name += llvm::utostr(Context.getAnonymousStructId(DD) + 1);
1060
0
        mangleSourceName(Name);
1061
0
        break;
1062
0
      }
1063
1064
0
      if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
1065
        // We must have an anonymous union or struct declaration.
1066
0
        const CXXRecordDecl *RD = VD->getType()->getAsCXXRecordDecl();
1067
0
        assert(RD && "expected variable decl to have a record type");
1068
        // Anonymous types with no tag or typedef get the name of their
1069
        // declarator mangled in.  If they have no declarator, number them with
1070
        // a $S prefix.
1071
0
        llvm::SmallString<64> Name("$S");
1072
        // Get a unique id for the anonymous struct.
1073
0
        Name += llvm::utostr(Context.getAnonymousStructId(RD) + 1);
1074
0
        mangleSourceName(Name.str());
1075
0
        break;
1076
0
      }
1077
1078
0
      if (const MSGuidDecl *GD = dyn_cast<MSGuidDecl>(ND)) {
1079
        // Mangle a GUID object as if it were a variable with the corresponding
1080
        // mangled name.
1081
0
        SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
1082
0
        llvm::raw_svector_ostream GUIDOS(GUID);
1083
0
        Context.mangleMSGuidDecl(GD, GUIDOS);
1084
0
        mangleSourceName(GUID);
1085
0
        break;
1086
0
      }
1087
1088
0
      if (const auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
1089
0
        Out << "?__N";
1090
0
        mangleTemplateArgValue(TPO->getType().getUnqualifiedType(),
1091
0
                               TPO->getValue());
1092
0
        break;
1093
0
      }
1094
1095
      // We must have an anonymous struct.
1096
0
      const TagDecl *TD = cast<TagDecl>(ND);
1097
0
      if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
1098
0
        assert(TD->getDeclContext() == D->getDeclContext() &&
1099
0
               "Typedef should not be in another decl context!");
1100
0
        assert(D->getDeclName().getAsIdentifierInfo() &&
1101
0
               "Typedef was not named!");
1102
0
        mangleSourceName(D->getDeclName().getAsIdentifierInfo()->getName());
1103
0
        break;
1104
0
      }
1105
1106
0
      if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
1107
0
        if (Record->isLambda()) {
1108
0
          llvm::SmallString<10> Name("<lambda_");
1109
1110
0
          Decl *LambdaContextDecl = Record->getLambdaContextDecl();
1111
0
          unsigned LambdaManglingNumber = Record->getLambdaManglingNumber();
1112
0
          unsigned LambdaId;
1113
0
          const ParmVarDecl *Parm =
1114
0
              dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
1115
0
          const FunctionDecl *Func =
1116
0
              Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
1117
1118
0
          if (Func) {
1119
0
            unsigned DefaultArgNo =
1120
0
                Func->getNumParams() - Parm->getFunctionScopeIndex();
1121
0
            Name += llvm::utostr(DefaultArgNo);
1122
0
            Name += "_";
1123
0
          }
1124
1125
0
          if (LambdaManglingNumber)
1126
0
            LambdaId = LambdaManglingNumber;
1127
0
          else
1128
0
            LambdaId = Context.getLambdaId(Record);
1129
1130
0
          Name += llvm::utostr(LambdaId);
1131
0
          Name += ">";
1132
1133
0
          mangleSourceName(Name);
1134
1135
          // If the context is a variable or a class member and not a parameter,
1136
          // it is encoded in a qualified name.
1137
0
          if (LambdaManglingNumber && LambdaContextDecl) {
1138
0
            if ((isa<VarDecl>(LambdaContextDecl) ||
1139
0
                 isa<FieldDecl>(LambdaContextDecl)) &&
1140
0
                !isa<ParmVarDecl>(LambdaContextDecl)) {
1141
0
              mangleUnqualifiedName(cast<NamedDecl>(LambdaContextDecl));
1142
0
            }
1143
0
          }
1144
0
          break;
1145
0
        }
1146
0
      }
1147
1148
0
      llvm::SmallString<64> Name;
1149
0
      if (DeclaratorDecl *DD =
1150
0
              Context.getASTContext().getDeclaratorForUnnamedTagDecl(TD)) {
1151
        // Anonymous types without a name for linkage purposes have their
1152
        // declarator mangled in if they have one.
1153
0
        Name += "<unnamed-type-";
1154
0
        Name += DD->getName();
1155
0
      } else if (TypedefNameDecl *TND =
1156
0
                     Context.getASTContext().getTypedefNameForUnnamedTagDecl(
1157
0
                         TD)) {
1158
        // Anonymous types without a name for linkage purposes have their
1159
        // associate typedef mangled in if they have one.
1160
0
        Name += "<unnamed-type-";
1161
0
        Name += TND->getName();
1162
0
      } else if (isa<EnumDecl>(TD) &&
1163
0
                 cast<EnumDecl>(TD)->enumerator_begin() !=
1164
0
                     cast<EnumDecl>(TD)->enumerator_end()) {
1165
        // Anonymous non-empty enums mangle in the first enumerator.
1166
0
        auto *ED = cast<EnumDecl>(TD);
1167
0
        Name += "<unnamed-enum-";
1168
0
        Name += ED->enumerator_begin()->getName();
1169
0
      } else {
1170
        // Otherwise, number the types using a $S prefix.
1171
0
        Name += "<unnamed-type-$S";
1172
0
        Name += llvm::utostr(Context.getAnonymousStructId(TD) + 1);
1173
0
      }
1174
0
      Name += ">";
1175
0
      mangleSourceName(Name.str());
1176
0
      break;
1177
0
    }
1178
1179
0
    case DeclarationName::ObjCZeroArgSelector:
1180
0
    case DeclarationName::ObjCOneArgSelector:
1181
0
    case DeclarationName::ObjCMultiArgSelector: {
1182
      // This is reachable only when constructing an outlined SEH finally
1183
      // block.  Nothing depends on this mangling and it's used only with
1184
      // functinos with internal linkage.
1185
0
      llvm::SmallString<64> Name;
1186
0
      mangleSourceName(Name.str());
1187
0
      break;
1188
0
    }
1189
1190
0
    case DeclarationName::CXXConstructorName:
1191
0
      if (isStructorDecl(ND)) {
1192
0
        if (StructorType == Ctor_CopyingClosure) {
1193
0
          Out << "?_O";
1194
0
          return;
1195
0
        }
1196
0
        if (StructorType == Ctor_DefaultClosure) {
1197
0
          Out << "?_F";
1198
0
          return;
1199
0
        }
1200
0
      }
1201
0
      Out << "?0";
1202
0
      return;
1203
1204
0
    case DeclarationName::CXXDestructorName:
1205
0
      if (isStructorDecl(ND))
1206
        // If the named decl is the C++ destructor we're mangling,
1207
        // use the type we were given.
1208
0
        mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
1209
0
      else
1210
        // Otherwise, use the base destructor name. This is relevant if a
1211
        // class with a destructor is declared within a destructor.
1212
0
        mangleCXXDtorType(Dtor_Base);
1213
0
      break;
1214
1215
0
    case DeclarationName::CXXConversionFunctionName:
1216
      // <operator-name> ::= ?B # (cast)
1217
      // The target type is encoded as the return type.
1218
0
      Out << "?B";
1219
0
      break;
1220
1221
0
    case DeclarationName::CXXOperatorName:
1222
0
      mangleOperatorName(Name.getCXXOverloadedOperator(), ND->getLocation());
1223
0
      break;
1224
1225
0
    case DeclarationName::CXXLiteralOperatorName: {
1226
0
      Out << "?__K";
1227
0
      mangleSourceName(Name.getCXXLiteralIdentifier()->getName());
1228
0
      break;
1229
0
    }
1230
1231
0
    case DeclarationName::CXXDeductionGuideName:
1232
0
      llvm_unreachable("Can't mangle a deduction guide name!");
1233
1234
0
    case DeclarationName::CXXUsingDirective:
1235
0
      llvm_unreachable("Can't mangle a using directive name!");
1236
0
  }
1237
0
}
1238
1239
// <postfix> ::= <unqualified-name> [<postfix>]
1240
//           ::= <substitution> [<postfix>]
1241
0
void MicrosoftCXXNameMangler::mangleNestedName(GlobalDecl GD) {
1242
0
  const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
1243
1244
0
  if (const auto *ID = dyn_cast<IndirectFieldDecl>(ND))
1245
0
    for (unsigned I = 1, IE = ID->getChainingSize(); I < IE; ++I)
1246
0
      mangleSourceName("<unnamed-tag>");
1247
1248
0
  const DeclContext *DC = getEffectiveDeclContext(ND);
1249
0
  while (!DC->isTranslationUnit()) {
1250
0
    if (isa<TagDecl>(ND) || isa<VarDecl>(ND)) {
1251
0
      unsigned Disc;
1252
0
      if (Context.getNextDiscriminator(ND, Disc)) {
1253
0
        Out << '?';
1254
0
        mangleNumber(Disc);
1255
0
        Out << '?';
1256
0
      }
1257
0
    }
1258
1259
0
    if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) {
1260
0
      auto Discriminate =
1261
0
          [](StringRef Name, const unsigned Discriminator,
1262
0
             const unsigned ParameterDiscriminator) -> std::string {
1263
0
        std::string Buffer;
1264
0
        llvm::raw_string_ostream Stream(Buffer);
1265
0
        Stream << Name;
1266
0
        if (Discriminator)
1267
0
          Stream << '_' << Discriminator;
1268
0
        if (ParameterDiscriminator)
1269
0
          Stream << '_' << ParameterDiscriminator;
1270
0
        return Stream.str();
1271
0
      };
1272
1273
0
      unsigned Discriminator = BD->getBlockManglingNumber();
1274
0
      if (!Discriminator)
1275
0
        Discriminator = Context.getBlockId(BD, /*Local=*/false);
1276
1277
      // Mangle the parameter position as a discriminator to deal with unnamed
1278
      // parameters.  Rather than mangling the unqualified parameter name,
1279
      // always use the position to give a uniform mangling.
1280
0
      unsigned ParameterDiscriminator = 0;
1281
0
      if (const auto *MC = BD->getBlockManglingContextDecl())
1282
0
        if (const auto *P = dyn_cast<ParmVarDecl>(MC))
1283
0
          if (const auto *F = dyn_cast<FunctionDecl>(P->getDeclContext()))
1284
0
            ParameterDiscriminator =
1285
0
                F->getNumParams() - P->getFunctionScopeIndex();
1286
1287
0
      DC = getEffectiveDeclContext(BD);
1288
1289
0
      Out << '?';
1290
0
      mangleSourceName(Discriminate("_block_invoke", Discriminator,
1291
0
                                    ParameterDiscriminator));
1292
      // If we have a block mangling context, encode that now.  This allows us
1293
      // to discriminate between named static data initializers in the same
1294
      // scope.  This is handled differently from parameters, which use
1295
      // positions to discriminate between multiple instances.
1296
0
      if (const auto *MC = BD->getBlockManglingContextDecl())
1297
0
        if (!isa<ParmVarDecl>(MC))
1298
0
          if (const auto *ND = dyn_cast<NamedDecl>(MC))
1299
0
            mangleUnqualifiedName(ND);
1300
      // MS ABI and Itanium manglings are in inverted scopes.  In the case of a
1301
      // RecordDecl, mangle the entire scope hierarchy at this point rather than
1302
      // just the unqualified name to get the ordering correct.
1303
0
      if (const auto *RD = dyn_cast<RecordDecl>(DC))
1304
0
        mangleName(RD);
1305
0
      else
1306
0
        Out << '@';
1307
      // void __cdecl
1308
0
      Out << "YAX";
1309
      // struct __block_literal *
1310
0
      Out << 'P';
1311
      // __ptr64
1312
0
      if (PointersAre64Bit)
1313
0
        Out << 'E';
1314
0
      Out << 'A';
1315
0
      mangleArtificialTagType(TagTypeKind::Struct,
1316
0
                              Discriminate("__block_literal", Discriminator,
1317
0
                                           ParameterDiscriminator));
1318
0
      Out << "@Z";
1319
1320
      // If the effective context was a Record, we have fully mangled the
1321
      // qualified name and do not need to continue.
1322
0
      if (isa<RecordDecl>(DC))
1323
0
        break;
1324
0
      continue;
1325
0
    } else if (const ObjCMethodDecl *Method = dyn_cast<ObjCMethodDecl>(DC)) {
1326
0
      mangleObjCMethodName(Method);
1327
0
    } else if (isa<NamedDecl>(DC)) {
1328
0
      ND = cast<NamedDecl>(DC);
1329
0
      if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1330
0
        mangle(getGlobalDeclAsDeclContext(FD), "?");
1331
0
        break;
1332
0
      } else {
1333
0
        mangleUnqualifiedName(ND);
1334
        // Lambdas in default arguments conceptually belong to the function the
1335
        // parameter corresponds to.
1336
0
        if (const auto *LDADC = getLambdaDefaultArgumentDeclContext(ND)) {
1337
0
          DC = LDADC;
1338
0
          continue;
1339
0
        }
1340
0
      }
1341
0
    }
1342
0
    DC = DC->getParent();
1343
0
  }
1344
0
}
1345
1346
0
void MicrosoftCXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
1347
  // Microsoft uses the names on the case labels for these dtor variants.  Clang
1348
  // uses the Itanium terminology internally.  Everything in this ABI delegates
1349
  // towards the base dtor.
1350
0
  switch (T) {
1351
  // <operator-name> ::= ?1  # destructor
1352
0
  case Dtor_Base: Out << "?1"; return;
1353
  // <operator-name> ::= ?_D # vbase destructor
1354
0
  case Dtor_Complete: Out << "?_D"; return;
1355
  // <operator-name> ::= ?_G # scalar deleting destructor
1356
0
  case Dtor_Deleting: Out << "?_G"; return;
1357
  // <operator-name> ::= ?_E # vector deleting destructor
1358
  // FIXME: Add a vector deleting dtor type.  It goes in the vtable, so we need
1359
  // it.
1360
0
  case Dtor_Comdat:
1361
0
    llvm_unreachable("not expecting a COMDAT");
1362
0
  }
1363
0
  llvm_unreachable("Unsupported dtor type?");
1364
0
}
1365
1366
void MicrosoftCXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO,
1367
0
                                                 SourceLocation Loc) {
1368
0
  switch (OO) {
1369
  //                     ?0 # constructor
1370
  //                     ?1 # destructor
1371
  // <operator-name> ::= ?2 # new
1372
0
  case OO_New: Out << "?2"; break;
1373
  // <operator-name> ::= ?3 # delete
1374
0
  case OO_Delete: Out << "?3"; break;
1375
  // <operator-name> ::= ?4 # =
1376
0
  case OO_Equal: Out << "?4"; break;
1377
  // <operator-name> ::= ?5 # >>
1378
0
  case OO_GreaterGreater: Out << "?5"; break;
1379
  // <operator-name> ::= ?6 # <<
1380
0
  case OO_LessLess: Out << "?6"; break;
1381
  // <operator-name> ::= ?7 # !
1382
0
  case OO_Exclaim: Out << "?7"; break;
1383
  // <operator-name> ::= ?8 # ==
1384
0
  case OO_EqualEqual: Out << "?8"; break;
1385
  // <operator-name> ::= ?9 # !=
1386
0
  case OO_ExclaimEqual: Out << "?9"; break;
1387
  // <operator-name> ::= ?A # []
1388
0
  case OO_Subscript: Out << "?A"; break;
1389
  //                     ?B # conversion
1390
  // <operator-name> ::= ?C # ->
1391
0
  case OO_Arrow: Out << "?C"; break;
1392
  // <operator-name> ::= ?D # *
1393
0
  case OO_Star: Out << "?D"; break;
1394
  // <operator-name> ::= ?E # ++
1395
0
  case OO_PlusPlus: Out << "?E"; break;
1396
  // <operator-name> ::= ?F # --
1397
0
  case OO_MinusMinus: Out << "?F"; break;
1398
  // <operator-name> ::= ?G # -
1399
0
  case OO_Minus: Out << "?G"; break;
1400
  // <operator-name> ::= ?H # +
1401
0
  case OO_Plus: Out << "?H"; break;
1402
  // <operator-name> ::= ?I # &
1403
0
  case OO_Amp: Out << "?I"; break;
1404
  // <operator-name> ::= ?J # ->*
1405
0
  case OO_ArrowStar: Out << "?J"; break;
1406
  // <operator-name> ::= ?K # /
1407
0
  case OO_Slash: Out << "?K"; break;
1408
  // <operator-name> ::= ?L # %
1409
0
  case OO_Percent: Out << "?L"; break;
1410
  // <operator-name> ::= ?M # <
1411
0
  case OO_Less: Out << "?M"; break;
1412
  // <operator-name> ::= ?N # <=
1413
0
  case OO_LessEqual: Out << "?N"; break;
1414
  // <operator-name> ::= ?O # >
1415
0
  case OO_Greater: Out << "?O"; break;
1416
  // <operator-name> ::= ?P # >=
1417
0
  case OO_GreaterEqual: Out << "?P"; break;
1418
  // <operator-name> ::= ?Q # ,
1419
0
  case OO_Comma: Out << "?Q"; break;
1420
  // <operator-name> ::= ?R # ()
1421
0
  case OO_Call: Out << "?R"; break;
1422
  // <operator-name> ::= ?S # ~
1423
0
  case OO_Tilde: Out << "?S"; break;
1424
  // <operator-name> ::= ?T # ^
1425
0
  case OO_Caret: Out << "?T"; break;
1426
  // <operator-name> ::= ?U # |
1427
0
  case OO_Pipe: Out << "?U"; break;
1428
  // <operator-name> ::= ?V # &&
1429
0
  case OO_AmpAmp: Out << "?V"; break;
1430
  // <operator-name> ::= ?W # ||
1431
0
  case OO_PipePipe: Out << "?W"; break;
1432
  // <operator-name> ::= ?X # *=
1433
0
  case OO_StarEqual: Out << "?X"; break;
1434
  // <operator-name> ::= ?Y # +=
1435
0
  case OO_PlusEqual: Out << "?Y"; break;
1436
  // <operator-name> ::= ?Z # -=
1437
0
  case OO_MinusEqual: Out << "?Z"; break;
1438
  // <operator-name> ::= ?_0 # /=
1439
0
  case OO_SlashEqual: Out << "?_0"; break;
1440
  // <operator-name> ::= ?_1 # %=
1441
0
  case OO_PercentEqual: Out << "?_1"; break;
1442
  // <operator-name> ::= ?_2 # >>=
1443
0
  case OO_GreaterGreaterEqual: Out << "?_2"; break;
1444
  // <operator-name> ::= ?_3 # <<=
1445
0
  case OO_LessLessEqual: Out << "?_3"; break;
1446
  // <operator-name> ::= ?_4 # &=
1447
0
  case OO_AmpEqual: Out << "?_4"; break;
1448
  // <operator-name> ::= ?_5 # |=
1449
0
  case OO_PipeEqual: Out << "?_5"; break;
1450
  // <operator-name> ::= ?_6 # ^=
1451
0
  case OO_CaretEqual: Out << "?_6"; break;
1452
  //                     ?_7 # vftable
1453
  //                     ?_8 # vbtable
1454
  //                     ?_9 # vcall
1455
  //                     ?_A # typeof
1456
  //                     ?_B # local static guard
1457
  //                     ?_C # string
1458
  //                     ?_D # vbase destructor
1459
  //                     ?_E # vector deleting destructor
1460
  //                     ?_F # default constructor closure
1461
  //                     ?_G # scalar deleting destructor
1462
  //                     ?_H # vector constructor iterator
1463
  //                     ?_I # vector destructor iterator
1464
  //                     ?_J # vector vbase constructor iterator
1465
  //                     ?_K # virtual displacement map
1466
  //                     ?_L # eh vector constructor iterator
1467
  //                     ?_M # eh vector destructor iterator
1468
  //                     ?_N # eh vector vbase constructor iterator
1469
  //                     ?_O # copy constructor closure
1470
  //                     ?_P<name> # udt returning <name>
1471
  //                     ?_Q # <unknown>
1472
  //                     ?_R0 # RTTI Type Descriptor
1473
  //                     ?_R1 # RTTI Base Class Descriptor at (a,b,c,d)
1474
  //                     ?_R2 # RTTI Base Class Array
1475
  //                     ?_R3 # RTTI Class Hierarchy Descriptor
1476
  //                     ?_R4 # RTTI Complete Object Locator
1477
  //                     ?_S # local vftable
1478
  //                     ?_T # local vftable constructor closure
1479
  // <operator-name> ::= ?_U # new[]
1480
0
  case OO_Array_New: Out << "?_U"; break;
1481
  // <operator-name> ::= ?_V # delete[]
1482
0
  case OO_Array_Delete: Out << "?_V"; break;
1483
  // <operator-name> ::= ?__L # co_await
1484
0
  case OO_Coawait: Out << "?__L"; break;
1485
  // <operator-name> ::= ?__M # <=>
1486
0
  case OO_Spaceship: Out << "?__M"; break;
1487
1488
0
  case OO_Conditional: {
1489
0
    DiagnosticsEngine &Diags = Context.getDiags();
1490
0
    unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
1491
0
      "cannot mangle this conditional operator yet");
1492
0
    Diags.Report(Loc, DiagID);
1493
0
    break;
1494
0
  }
1495
1496
0
  case OO_None:
1497
0
  case NUM_OVERLOADED_OPERATORS:
1498
0
    llvm_unreachable("Not an overloaded operator");
1499
0
  }
1500
0
}
1501
1502
0
void MicrosoftCXXNameMangler::mangleSourceName(StringRef Name) {
1503
  // <source name> ::= <identifier> @
1504
0
  BackRefVec::iterator Found = llvm::find(NameBackReferences, Name);
1505
0
  if (Found == NameBackReferences.end()) {
1506
0
    if (NameBackReferences.size() < 10)
1507
0
      NameBackReferences.push_back(std::string(Name));
1508
0
    Out << Name << '@';
1509
0
  } else {
1510
0
    Out << (Found - NameBackReferences.begin());
1511
0
  }
1512
0
}
1513
1514
0
void MicrosoftCXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
1515
0
  Context.mangleObjCMethodNameAsSourceName(MD, Out);
1516
0
}
1517
1518
void MicrosoftCXXNameMangler::mangleTemplateInstantiationName(
1519
0
    GlobalDecl GD, const TemplateArgumentList &TemplateArgs) {
1520
  // <template-name> ::= <unscoped-template-name> <template-args>
1521
  //                 ::= <substitution>
1522
  // Always start with the unqualified name.
1523
1524
  // Templates have their own context for back references.
1525
0
  ArgBackRefMap OuterFunArgsContext;
1526
0
  ArgBackRefMap OuterTemplateArgsContext;
1527
0
  BackRefVec OuterTemplateContext;
1528
0
  PassObjectSizeArgsSet OuterPassObjectSizeArgs;
1529
0
  NameBackReferences.swap(OuterTemplateContext);
1530
0
  FunArgBackReferences.swap(OuterFunArgsContext);
1531
0
  TemplateArgBackReferences.swap(OuterTemplateArgsContext);
1532
0
  PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1533
1534
0
  mangleUnscopedTemplateName(GD);
1535
0
  mangleTemplateArgs(cast<TemplateDecl>(GD.getDecl()), TemplateArgs);
1536
1537
  // Restore the previous back reference contexts.
1538
0
  NameBackReferences.swap(OuterTemplateContext);
1539
0
  FunArgBackReferences.swap(OuterFunArgsContext);
1540
0
  TemplateArgBackReferences.swap(OuterTemplateArgsContext);
1541
0
  PassObjectSizeArgs.swap(OuterPassObjectSizeArgs);
1542
0
}
1543
1544
0
void MicrosoftCXXNameMangler::mangleUnscopedTemplateName(GlobalDecl GD) {
1545
  // <unscoped-template-name> ::= ?$ <unqualified-name>
1546
0
  Out << "?$";
1547
0
  mangleUnqualifiedName(GD);
1548
0
}
1549
1550
void MicrosoftCXXNameMangler::mangleIntegerLiteral(
1551
    const llvm::APSInt &Value, const NonTypeTemplateParmDecl *PD,
1552
0
    QualType TemplateArgType) {
1553
  // <integer-literal> ::= $0 <number>
1554
0
  Out << "$";
1555
1556
  // Since MSVC 2019, add 'M[<type>]' after '$' for auto template parameter when
1557
  // argument is integer.
1558
0
  if (getASTContext().getLangOpts().isCompatibleWithMSVC(
1559
0
          LangOptions::MSVC2019) &&
1560
0
      PD && PD->getType()->getTypeClass() == Type::Auto &&
1561
0
      !TemplateArgType.isNull()) {
1562
0
    Out << "M";
1563
0
    mangleType(TemplateArgType, SourceRange(), QMM_Drop);
1564
0
  }
1565
1566
0
  Out << "0";
1567
1568
0
  mangleNumber(Value);
1569
0
}
1570
1571
void MicrosoftCXXNameMangler::mangleExpression(
1572
0
    const Expr *E, const NonTypeTemplateParmDecl *PD) {
1573
  // See if this is a constant expression.
1574
0
  if (std::optional<llvm::APSInt> Value =
1575
0
          E->getIntegerConstantExpr(Context.getASTContext())) {
1576
0
    mangleIntegerLiteral(*Value, PD, E->getType());
1577
0
    return;
1578
0
  }
1579
1580
  // As bad as this diagnostic is, it's better than crashing.
1581
0
  DiagnosticsEngine &Diags = Context.getDiags();
1582
0
  unsigned DiagID = Diags.getCustomDiagID(
1583
0
      DiagnosticsEngine::Error, "cannot yet mangle expression type %0");
1584
0
  Diags.Report(E->getExprLoc(), DiagID) << E->getStmtClassName()
1585
0
                                        << E->getSourceRange();
1586
0
}
1587
1588
void MicrosoftCXXNameMangler::mangleTemplateArgs(
1589
0
    const TemplateDecl *TD, const TemplateArgumentList &TemplateArgs) {
1590
  // <template-args> ::= <template-arg>+
1591
0
  const TemplateParameterList *TPL = TD->getTemplateParameters();
1592
0
  assert(TPL->size() == TemplateArgs.size() &&
1593
0
         "size mismatch between args and parms!");
1594
1595
0
  for (size_t i = 0; i < TemplateArgs.size(); ++i) {
1596
0
    const TemplateArgument &TA = TemplateArgs[i];
1597
1598
    // Separate consecutive packs by $$Z.
1599
0
    if (i > 0 && TA.getKind() == TemplateArgument::Pack &&
1600
0
        TemplateArgs[i - 1].getKind() == TemplateArgument::Pack)
1601
0
      Out << "$$Z";
1602
1603
0
    mangleTemplateArg(TD, TA, TPL->getParam(i));
1604
0
  }
1605
0
}
1606
1607
void MicrosoftCXXNameMangler::mangleTemplateArg(const TemplateDecl *TD,
1608
                                                const TemplateArgument &TA,
1609
0
                                                const NamedDecl *Parm) {
1610
  // <template-arg> ::= <type>
1611
  //                ::= <integer-literal>
1612
  //                ::= <member-data-pointer>
1613
  //                ::= <member-function-pointer>
1614
  //                ::= $ <constant-value>
1615
  //                ::= <template-args>
1616
  //
1617
  // <constant-value> ::= 0 <number>                   # integer
1618
  //                  ::= 1 <mangled-name>             # address of D
1619
  //                  ::= 2 <type> <typed-constant-value>* @ # struct
1620
  //                  ::= 3 <type> <constant-value>* @ # array
1621
  //                  ::= 4 ???                        # string
1622
  //                  ::= 5 <constant-value> @         # address of subobject
1623
  //                  ::= 6 <constant-value> <unqualified-name> @ # a.b
1624
  //                  ::= 7 <type> [<unqualified-name> <constant-value>] @
1625
  //                      # union, with or without an active member
1626
  //                  # pointer to member, symbolically
1627
  //                  ::= 8 <class> <unqualified-name> @
1628
  //                  ::= A <type> <non-negative integer>  # float
1629
  //                  ::= B <type> <non-negative integer>  # double
1630
  //                  # pointer to member, by component value
1631
  //                  ::= F <number> <number>
1632
  //                  ::= G <number> <number> <number>
1633
  //                  ::= H <mangled-name> <number>
1634
  //                  ::= I <mangled-name> <number> <number>
1635
  //                  ::= J <mangled-name> <number> <number> <number>
1636
  //
1637
  // <typed-constant-value> ::= [<type>] <constant-value>
1638
  //
1639
  // The <type> appears to be included in a <typed-constant-value> only in the
1640
  // '0', '1', '8', 'A', 'B', and 'E' cases.
1641
1642
0
  switch (TA.getKind()) {
1643
0
  case TemplateArgument::Null:
1644
0
    llvm_unreachable("Can't mangle null template arguments!");
1645
0
  case TemplateArgument::TemplateExpansion:
1646
0
    llvm_unreachable("Can't mangle template expansion arguments!");
1647
0
  case TemplateArgument::Type: {
1648
0
    QualType T = TA.getAsType();
1649
0
    mangleType(T, SourceRange(), QMM_Escape);
1650
0
    break;
1651
0
  }
1652
0
  case TemplateArgument::Declaration: {
1653
0
    const NamedDecl *ND = TA.getAsDecl();
1654
0
    if (isa<FieldDecl>(ND) || isa<IndirectFieldDecl>(ND)) {
1655
0
      mangleMemberDataPointer(cast<CXXRecordDecl>(ND->getDeclContext())
1656
0
                                  ->getMostRecentNonInjectedDecl(),
1657
0
                              cast<ValueDecl>(ND));
1658
0
    } else if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
1659
0
      const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
1660
0
      if (MD && MD->isInstance()) {
1661
0
        mangleMemberFunctionPointer(
1662
0
            MD->getParent()->getMostRecentNonInjectedDecl(), MD);
1663
0
      } else {
1664
0
        Out << "$1?";
1665
0
        mangleName(FD);
1666
0
        mangleFunctionEncoding(FD, /*ShouldMangle=*/true);
1667
0
      }
1668
0
    } else if (TA.getParamTypeForDecl()->isRecordType()) {
1669
0
      Out << "$";
1670
0
      auto *TPO = cast<TemplateParamObjectDecl>(ND);
1671
0
      mangleTemplateArgValue(TPO->getType().getUnqualifiedType(),
1672
0
                             TPO->getValue());
1673
0
    } else {
1674
0
      mangle(ND, "$1?");
1675
0
    }
1676
0
    break;
1677
0
  }
1678
0
  case TemplateArgument::Integral: {
1679
0
    QualType T = TA.getIntegralType();
1680
0
    mangleIntegerLiteral(TA.getAsIntegral(),
1681
0
                         cast<NonTypeTemplateParmDecl>(Parm), T);
1682
0
    break;
1683
0
  }
1684
0
  case TemplateArgument::NullPtr: {
1685
0
    QualType T = TA.getNullPtrType();
1686
0
    if (const MemberPointerType *MPT = T->getAs<MemberPointerType>()) {
1687
0
      const CXXRecordDecl *RD = MPT->getMostRecentCXXRecordDecl();
1688
0
      if (MPT->isMemberFunctionPointerType() &&
1689
0
          !isa<FunctionTemplateDecl>(TD)) {
1690
0
        mangleMemberFunctionPointer(RD, nullptr);
1691
0
        return;
1692
0
      }
1693
0
      if (MPT->isMemberDataPointer()) {
1694
0
        if (!isa<FunctionTemplateDecl>(TD)) {
1695
0
          mangleMemberDataPointer(RD, nullptr);
1696
0
          return;
1697
0
        }
1698
        // nullptr data pointers are always represented with a single field
1699
        // which is initialized with either 0 or -1.  Why -1?  Well, we need to
1700
        // distinguish the case where the data member is at offset zero in the
1701
        // record.
1702
        // However, we are free to use 0 *if* we would use multiple fields for
1703
        // non-nullptr member pointers.
1704
0
        if (!RD->nullFieldOffsetIsZero()) {
1705
0
          mangleIntegerLiteral(llvm::APSInt::get(-1),
1706
0
                               cast<NonTypeTemplateParmDecl>(Parm), T);
1707
0
          return;
1708
0
        }
1709
0
      }
1710
0
    }
1711
0
    mangleIntegerLiteral(llvm::APSInt::getUnsigned(0),
1712
0
                         cast<NonTypeTemplateParmDecl>(Parm), T);
1713
0
    break;
1714
0
  }
1715
0
  case TemplateArgument::Expression:
1716
0
    mangleExpression(TA.getAsExpr(), cast<NonTypeTemplateParmDecl>(Parm));
1717
0
    break;
1718
0
  case TemplateArgument::Pack: {
1719
0
    ArrayRef<TemplateArgument> TemplateArgs = TA.getPackAsArray();
1720
0
    if (TemplateArgs.empty()) {
1721
0
      if (isa<TemplateTypeParmDecl>(Parm) ||
1722
0
          isa<TemplateTemplateParmDecl>(Parm))
1723
        // MSVC 2015 changed the mangling for empty expanded template packs,
1724
        // use the old mangling for link compatibility for old versions.
1725
0
        Out << (Context.getASTContext().getLangOpts().isCompatibleWithMSVC(
1726
0
                    LangOptions::MSVC2015)
1727
0
                    ? "$$V"
1728
0
                    : "$$$V");
1729
0
      else if (isa<NonTypeTemplateParmDecl>(Parm))
1730
0
        Out << "$S";
1731
0
      else
1732
0
        llvm_unreachable("unexpected template parameter decl!");
1733
0
    } else {
1734
0
      for (const TemplateArgument &PA : TemplateArgs)
1735
0
        mangleTemplateArg(TD, PA, Parm);
1736
0
    }
1737
0
    break;
1738
0
  }
1739
0
  case TemplateArgument::Template: {
1740
0
    const NamedDecl *ND =
1741
0
        TA.getAsTemplate().getAsTemplateDecl()->getTemplatedDecl();
1742
0
    if (const auto *TD = dyn_cast<TagDecl>(ND)) {
1743
0
      mangleType(TD);
1744
0
    } else if (isa<TypeAliasDecl>(ND)) {
1745
0
      Out << "$$Y";
1746
0
      mangleName(ND);
1747
0
    } else {
1748
0
      llvm_unreachable("unexpected template template NamedDecl!");
1749
0
    }
1750
0
    break;
1751
0
  }
1752
0
  }
1753
0
}
1754
1755
void MicrosoftCXXNameMangler::mangleTemplateArgValue(QualType T,
1756
                                                     const APValue &V,
1757
0
                                                     bool WithScalarType) {
1758
0
  switch (V.getKind()) {
1759
0
  case APValue::None:
1760
0
  case APValue::Indeterminate:
1761
    // FIXME: MSVC doesn't allow this, so we can't be sure how it should be
1762
    // mangled.
1763
0
    if (WithScalarType)
1764
0
      mangleType(T, SourceRange(), QMM_Escape);
1765
0
    Out << '@';
1766
0
    return;
1767
1768
0
  case APValue::Int:
1769
0
    if (WithScalarType)
1770
0
      mangleType(T, SourceRange(), QMM_Escape);
1771
0
    Out << '0';
1772
0
    mangleNumber(V.getInt());
1773
0
    return;
1774
1775
0
  case APValue::Float:
1776
0
    if (WithScalarType)
1777
0
      mangleType(T, SourceRange(), QMM_Escape);
1778
0
    mangleFloat(V.getFloat());
1779
0
    return;
1780
1781
0
  case APValue::LValue: {
1782
0
    if (WithScalarType)
1783
0
      mangleType(T, SourceRange(), QMM_Escape);
1784
1785
    // We don't know how to mangle past-the-end pointers yet.
1786
0
    if (V.isLValueOnePastTheEnd())
1787
0
      break;
1788
1789
0
    APValue::LValueBase Base = V.getLValueBase();
1790
0
    if (!V.hasLValuePath() || V.getLValuePath().empty()) {
1791
      // Taking the address of a complete object has a special-case mangling.
1792
0
      if (Base.isNull()) {
1793
        // MSVC emits 0A@ for null pointers. Generalize this for arbitrary
1794
        // integers cast to pointers.
1795
        // FIXME: This mangles 0 cast to a pointer the same as a null pointer,
1796
        // even in cases where the two are different values.
1797
0
        Out << "0";
1798
0
        mangleNumber(V.getLValueOffset().getQuantity());
1799
0
      } else if (!V.hasLValuePath()) {
1800
        // FIXME: This can only happen as an extension. Invent a mangling.
1801
0
        break;
1802
0
      } else if (auto *VD = Base.dyn_cast<const ValueDecl*>()) {
1803
0
        Out << "E";
1804
0
        mangle(VD);
1805
0
      } else {
1806
0
        break;
1807
0
      }
1808
0
    } else {
1809
0
      if (T->isPointerType())
1810
0
        Out << "5";
1811
1812
0
      SmallVector<char, 2> EntryTypes;
1813
0
      SmallVector<std::function<void()>, 2> EntryManglers;
1814
0
      QualType ET = Base.getType();
1815
0
      for (APValue::LValuePathEntry E : V.getLValuePath()) {
1816
0
        if (auto *AT = ET->getAsArrayTypeUnsafe()) {
1817
0
          EntryTypes.push_back('C');
1818
0
          EntryManglers.push_back([this, I = E.getAsArrayIndex()] {
1819
0
            Out << '0';
1820
0
            mangleNumber(I);
1821
0
            Out << '@';
1822
0
          });
1823
0
          ET = AT->getElementType();
1824
0
          continue;
1825
0
        }
1826
1827
0
        const Decl *D = E.getAsBaseOrMember().getPointer();
1828
0
        if (auto *FD = dyn_cast<FieldDecl>(D)) {
1829
0
          ET = FD->getType();
1830
0
          if (const auto *RD = ET->getAsRecordDecl())
1831
0
            if (RD->isAnonymousStructOrUnion())
1832
0
              continue;
1833
0
        } else {
1834
0
          ET = getASTContext().getRecordType(cast<CXXRecordDecl>(D));
1835
          // Bug in MSVC: fully qualified name of base class should be used for
1836
          // mangling to prevent collisions e.g. on base classes with same names
1837
          // in different namespaces.
1838
0
        }
1839
1840
0
        EntryTypes.push_back('6');
1841
0
        EntryManglers.push_back([this, D] {
1842
0
          mangleUnqualifiedName(cast<NamedDecl>(D));
1843
0
          Out << '@';
1844
0
        });
1845
0
      }
1846
1847
0
      for (auto I = EntryTypes.rbegin(), E = EntryTypes.rend(); I != E; ++I)
1848
0
        Out << *I;
1849
1850
0
      auto *VD = Base.dyn_cast<const ValueDecl*>();
1851
0
      if (!VD)
1852
0
        break;
1853
0
      Out << "E";
1854
0
      mangle(VD);
1855
1856
0
      for (const std::function<void()> &Mangler : EntryManglers)
1857
0
        Mangler();
1858
0
      if (T->isPointerType())
1859
0
        Out << '@';
1860
0
    }
1861
1862
0
    return;
1863
0
  }
1864
1865
0
  case APValue::MemberPointer: {
1866
0
    if (WithScalarType)
1867
0
      mangleType(T, SourceRange(), QMM_Escape);
1868
1869
0
    const CXXRecordDecl *RD =
1870
0
        T->castAs<MemberPointerType>()->getMostRecentCXXRecordDecl();
1871
0
    const ValueDecl *D = V.getMemberPointerDecl();
1872
0
    if (T->isMemberDataPointerType())
1873
0
      mangleMemberDataPointerInClassNTTP(RD, D);
1874
0
    else
1875
0
      mangleMemberFunctionPointerInClassNTTP(RD,
1876
0
                                             cast_or_null<CXXMethodDecl>(D));
1877
0
    return;
1878
0
  }
1879
1880
0
  case APValue::Struct: {
1881
0
    Out << '2';
1882
0
    mangleType(T, SourceRange(), QMM_Escape);
1883
0
    const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
1884
0
    assert(RD && "unexpected type for record value");
1885
1886
0
    unsigned BaseIndex = 0;
1887
0
    for (const CXXBaseSpecifier &B : RD->bases())
1888
0
      mangleTemplateArgValue(B.getType(), V.getStructBase(BaseIndex++));
1889
0
    for (const FieldDecl *FD : RD->fields())
1890
0
      if (!FD->isUnnamedBitfield())
1891
0
        mangleTemplateArgValue(FD->getType(),
1892
0
                               V.getStructField(FD->getFieldIndex()),
1893
0
                               /*WithScalarType*/ true);
1894
0
    Out << '@';
1895
0
    return;
1896
0
  }
1897
1898
0
  case APValue::Union:
1899
0
    Out << '7';
1900
0
    mangleType(T, SourceRange(), QMM_Escape);
1901
0
    if (const FieldDecl *FD = V.getUnionField()) {
1902
0
      mangleUnqualifiedName(FD);
1903
0
      mangleTemplateArgValue(FD->getType(), V.getUnionValue());
1904
0
    }
1905
0
    Out << '@';
1906
0
    return;
1907
1908
0
  case APValue::ComplexInt:
1909
    // We mangle complex types as structs, so mangle the value as a struct too.
1910
0
    Out << '2';
1911
0
    mangleType(T, SourceRange(), QMM_Escape);
1912
0
    Out << '0';
1913
0
    mangleNumber(V.getComplexIntReal());
1914
0
    Out << '0';
1915
0
    mangleNumber(V.getComplexIntImag());
1916
0
    Out << '@';
1917
0
    return;
1918
1919
0
  case APValue::ComplexFloat:
1920
0
    Out << '2';
1921
0
    mangleType(T, SourceRange(), QMM_Escape);
1922
0
    mangleFloat(V.getComplexFloatReal());
1923
0
    mangleFloat(V.getComplexFloatImag());
1924
0
    Out << '@';
1925
0
    return;
1926
1927
0
  case APValue::Array: {
1928
0
    Out << '3';
1929
0
    QualType ElemT = getASTContext().getAsArrayType(T)->getElementType();
1930
0
    mangleType(ElemT, SourceRange(), QMM_Escape);
1931
0
    for (unsigned I = 0, N = V.getArraySize(); I != N; ++I) {
1932
0
      const APValue &ElemV = I < V.getArrayInitializedElts()
1933
0
                                 ? V.getArrayInitializedElt(I)
1934
0
                                 : V.getArrayFiller();
1935
0
      mangleTemplateArgValue(ElemT, ElemV);
1936
0
      Out << '@';
1937
0
    }
1938
0
    Out << '@';
1939
0
    return;
1940
0
  }
1941
1942
0
  case APValue::Vector: {
1943
    // __m128 is mangled as a struct containing an array. We follow this
1944
    // approach for all vector types.
1945
0
    Out << '2';
1946
0
    mangleType(T, SourceRange(), QMM_Escape);
1947
0
    Out << '3';
1948
0
    QualType ElemT = T->castAs<VectorType>()->getElementType();
1949
0
    mangleType(ElemT, SourceRange(), QMM_Escape);
1950
0
    for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I) {
1951
0
      const APValue &ElemV = V.getVectorElt(I);
1952
0
      mangleTemplateArgValue(ElemT, ElemV);
1953
0
      Out << '@';
1954
0
    }
1955
0
    Out << "@@";
1956
0
    return;
1957
0
  }
1958
1959
0
  case APValue::AddrLabelDiff:
1960
0
  case APValue::FixedPoint:
1961
0
    break;
1962
0
  }
1963
1964
0
  DiagnosticsEngine &Diags = Context.getDiags();
1965
0
  unsigned DiagID = Diags.getCustomDiagID(
1966
0
      DiagnosticsEngine::Error, "cannot mangle this template argument yet");
1967
0
  Diags.Report(DiagID);
1968
0
}
1969
1970
0
void MicrosoftCXXNameMangler::mangleObjCProtocol(const ObjCProtocolDecl *PD) {
1971
0
  llvm::SmallString<64> TemplateMangling;
1972
0
  llvm::raw_svector_ostream Stream(TemplateMangling);
1973
0
  MicrosoftCXXNameMangler Extra(Context, Stream);
1974
1975
0
  Stream << "?$";
1976
0
  Extra.mangleSourceName("Protocol");
1977
0
  Extra.mangleArtificialTagType(TagTypeKind::Struct, PD->getName());
1978
1979
0
  mangleArtificialTagType(TagTypeKind::Struct, TemplateMangling, {"__ObjC"});
1980
0
}
1981
1982
void MicrosoftCXXNameMangler::mangleObjCLifetime(const QualType Type,
1983
                                                 Qualifiers Quals,
1984
0
                                                 SourceRange Range) {
1985
0
  llvm::SmallString<64> TemplateMangling;
1986
0
  llvm::raw_svector_ostream Stream(TemplateMangling);
1987
0
  MicrosoftCXXNameMangler Extra(Context, Stream);
1988
1989
0
  Stream << "?$";
1990
0
  switch (Quals.getObjCLifetime()) {
1991
0
  case Qualifiers::OCL_None:
1992
0
  case Qualifiers::OCL_ExplicitNone:
1993
0
    break;
1994
0
  case Qualifiers::OCL_Autoreleasing:
1995
0
    Extra.mangleSourceName("Autoreleasing");
1996
0
    break;
1997
0
  case Qualifiers::OCL_Strong:
1998
0
    Extra.mangleSourceName("Strong");
1999
0
    break;
2000
0
  case Qualifiers::OCL_Weak:
2001
0
    Extra.mangleSourceName("Weak");
2002
0
    break;
2003
0
  }
2004
0
  Extra.manglePointerCVQualifiers(Quals);
2005
0
  Extra.manglePointerExtQualifiers(Quals, Type);
2006
0
  Extra.mangleType(Type, Range);
2007
2008
0
  mangleArtificialTagType(TagTypeKind::Struct, TemplateMangling, {"__ObjC"});
2009
0
}
2010
2011
void MicrosoftCXXNameMangler::mangleObjCKindOfType(const ObjCObjectType *T,
2012
                                                   Qualifiers Quals,
2013
0
                                                   SourceRange Range) {
2014
0
  llvm::SmallString<64> TemplateMangling;
2015
0
  llvm::raw_svector_ostream Stream(TemplateMangling);
2016
0
  MicrosoftCXXNameMangler Extra(Context, Stream);
2017
2018
0
  Stream << "?$";
2019
0
  Extra.mangleSourceName("KindOf");
2020
0
  Extra.mangleType(QualType(T, 0)
2021
0
                       .stripObjCKindOfType(getASTContext())
2022
0
                       ->castAs<ObjCObjectType>(),
2023
0
                   Quals, Range);
2024
2025
0
  mangleArtificialTagType(TagTypeKind::Struct, TemplateMangling, {"__ObjC"});
2026
0
}
2027
2028
void MicrosoftCXXNameMangler::mangleQualifiers(Qualifiers Quals,
2029
0
                                               bool IsMember) {
2030
  // <cvr-qualifiers> ::= [E] [F] [I] <base-cvr-qualifiers>
2031
  // 'E' means __ptr64 (32-bit only); 'F' means __unaligned (32/64-bit only);
2032
  // 'I' means __restrict (32/64-bit).
2033
  // Note that the MSVC __restrict keyword isn't the same as the C99 restrict
2034
  // keyword!
2035
  // <base-cvr-qualifiers> ::= A  # near
2036
  //                       ::= B  # near const
2037
  //                       ::= C  # near volatile
2038
  //                       ::= D  # near const volatile
2039
  //                       ::= E  # far (16-bit)
2040
  //                       ::= F  # far const (16-bit)
2041
  //                       ::= G  # far volatile (16-bit)
2042
  //                       ::= H  # far const volatile (16-bit)
2043
  //                       ::= I  # huge (16-bit)
2044
  //                       ::= J  # huge const (16-bit)
2045
  //                       ::= K  # huge volatile (16-bit)
2046
  //                       ::= L  # huge const volatile (16-bit)
2047
  //                       ::= M <basis> # based
2048
  //                       ::= N <basis> # based const
2049
  //                       ::= O <basis> # based volatile
2050
  //                       ::= P <basis> # based const volatile
2051
  //                       ::= Q  # near member
2052
  //                       ::= R  # near const member
2053
  //                       ::= S  # near volatile member
2054
  //                       ::= T  # near const volatile member
2055
  //                       ::= U  # far member (16-bit)
2056
  //                       ::= V  # far const member (16-bit)
2057
  //                       ::= W  # far volatile member (16-bit)
2058
  //                       ::= X  # far const volatile member (16-bit)
2059
  //                       ::= Y  # huge member (16-bit)
2060
  //                       ::= Z  # huge const member (16-bit)
2061
  //                       ::= 0  # huge volatile member (16-bit)
2062
  //                       ::= 1  # huge const volatile member (16-bit)
2063
  //                       ::= 2 <basis> # based member
2064
  //                       ::= 3 <basis> # based const member
2065
  //                       ::= 4 <basis> # based volatile member
2066
  //                       ::= 5 <basis> # based const volatile member
2067
  //                       ::= 6  # near function (pointers only)
2068
  //                       ::= 7  # far function (pointers only)
2069
  //                       ::= 8  # near method (pointers only)
2070
  //                       ::= 9  # far method (pointers only)
2071
  //                       ::= _A <basis> # based function (pointers only)
2072
  //                       ::= _B <basis> # based function (far?) (pointers only)
2073
  //                       ::= _C <basis> # based method (pointers only)
2074
  //                       ::= _D <basis> # based method (far?) (pointers only)
2075
  //                       ::= _E # block (Clang)
2076
  // <basis> ::= 0 # __based(void)
2077
  //         ::= 1 # __based(segment)?
2078
  //         ::= 2 <name> # __based(name)
2079
  //         ::= 3 # ?
2080
  //         ::= 4 # ?
2081
  //         ::= 5 # not really based
2082
0
  bool HasConst = Quals.hasConst(),
2083
0
       HasVolatile = Quals.hasVolatile();
2084
2085
0
  if (!IsMember) {
2086
0
    if (HasConst && HasVolatile) {
2087
0
      Out << 'D';
2088
0
    } else if (HasVolatile) {
2089
0
      Out << 'C';
2090
0
    } else if (HasConst) {
2091
0
      Out << 'B';
2092
0
    } else {
2093
0
      Out << 'A';
2094
0
    }
2095
0
  } else {
2096
0
    if (HasConst && HasVolatile) {
2097
0
      Out << 'T';
2098
0
    } else if (HasVolatile) {
2099
0
      Out << 'S';
2100
0
    } else if (HasConst) {
2101
0
      Out << 'R';
2102
0
    } else {
2103
0
      Out << 'Q';
2104
0
    }
2105
0
  }
2106
2107
  // FIXME: For now, just drop all extension qualifiers on the floor.
2108
0
}
2109
2110
void
2111
0
MicrosoftCXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
2112
  // <ref-qualifier> ::= G                # lvalue reference
2113
  //                 ::= H                # rvalue-reference
2114
0
  switch (RefQualifier) {
2115
0
  case RQ_None:
2116
0
    break;
2117
2118
0
  case RQ_LValue:
2119
0
    Out << 'G';
2120
0
    break;
2121
2122
0
  case RQ_RValue:
2123
0
    Out << 'H';
2124
0
    break;
2125
0
  }
2126
0
}
2127
2128
void MicrosoftCXXNameMangler::manglePointerExtQualifiers(Qualifiers Quals,
2129
0
                                                         QualType PointeeType) {
2130
  // Check if this is a default 64-bit pointer or has __ptr64 qualifier.
2131
0
  bool is64Bit = PointeeType.isNull() ? PointersAre64Bit :
2132
0
      is64BitPointer(PointeeType.getQualifiers());
2133
0
  if (is64Bit && (PointeeType.isNull() || !PointeeType->isFunctionType()))
2134
0
    Out << 'E';
2135
2136
0
  if (Quals.hasRestrict())
2137
0
    Out << 'I';
2138
2139
0
  if (Quals.hasUnaligned() ||
2140
0
      (!PointeeType.isNull() && PointeeType.getLocalQualifiers().hasUnaligned()))
2141
0
    Out << 'F';
2142
0
}
2143
2144
0
void MicrosoftCXXNameMangler::manglePointerCVQualifiers(Qualifiers Quals) {
2145
  // <pointer-cv-qualifiers> ::= P  # no qualifiers
2146
  //                         ::= Q  # const
2147
  //                         ::= R  # volatile
2148
  //                         ::= S  # const volatile
2149
0
  bool HasConst = Quals.hasConst(),
2150
0
       HasVolatile = Quals.hasVolatile();
2151
2152
0
  if (HasConst && HasVolatile) {
2153
0
    Out << 'S';
2154
0
  } else if (HasVolatile) {
2155
0
    Out << 'R';
2156
0
  } else if (HasConst) {
2157
0
    Out << 'Q';
2158
0
  } else {
2159
0
    Out << 'P';
2160
0
  }
2161
0
}
2162
2163
void MicrosoftCXXNameMangler::mangleFunctionArgumentType(QualType T,
2164
0
                                                         SourceRange Range) {
2165
  // MSVC will backreference two canonically equivalent types that have slightly
2166
  // different manglings when mangled alone.
2167
2168
  // Decayed types do not match up with non-decayed versions of the same type.
2169
  //
2170
  // e.g.
2171
  // void (*x)(void) will not form a backreference with void x(void)
2172
0
  void *TypePtr;
2173
0
  if (const auto *DT = T->getAs<DecayedType>()) {
2174
0
    QualType OriginalType = DT->getOriginalType();
2175
    // All decayed ArrayTypes should be treated identically; as-if they were
2176
    // a decayed IncompleteArrayType.
2177
0
    if (const auto *AT = getASTContext().getAsArrayType(OriginalType))
2178
0
      OriginalType = getASTContext().getIncompleteArrayType(
2179
0
          AT->getElementType(), AT->getSizeModifier(),
2180
0
          AT->getIndexTypeCVRQualifiers());
2181
2182
0
    TypePtr = OriginalType.getCanonicalType().getAsOpaquePtr();
2183
    // If the original parameter was textually written as an array,
2184
    // instead treat the decayed parameter like it's const.
2185
    //
2186
    // e.g.
2187
    // int [] -> int * const
2188
0
    if (OriginalType->isArrayType())
2189
0
      T = T.withConst();
2190
0
  } else {
2191
0
    TypePtr = T.getCanonicalType().getAsOpaquePtr();
2192
0
  }
2193
2194
0
  ArgBackRefMap::iterator Found = FunArgBackReferences.find(TypePtr);
2195
2196
0
  if (Found == FunArgBackReferences.end()) {
2197
0
    size_t OutSizeBefore = Out.tell();
2198
2199
0
    mangleType(T, Range, QMM_Drop);
2200
2201
    // See if it's worth creating a back reference.
2202
    // Only types longer than 1 character are considered
2203
    // and only 10 back references slots are available:
2204
0
    bool LongerThanOneChar = (Out.tell() - OutSizeBefore > 1);
2205
0
    if (LongerThanOneChar && FunArgBackReferences.size() < 10) {
2206
0
      size_t Size = FunArgBackReferences.size();
2207
0
      FunArgBackReferences[TypePtr] = Size;
2208
0
    }
2209
0
  } else {
2210
0
    Out << Found->second;
2211
0
  }
2212
0
}
2213
2214
void MicrosoftCXXNameMangler::manglePassObjectSizeArg(
2215
0
    const PassObjectSizeAttr *POSA) {
2216
0
  int Type = POSA->getType();
2217
0
  bool Dynamic = POSA->isDynamic();
2218
2219
0
  auto Iter = PassObjectSizeArgs.insert({Type, Dynamic}).first;
2220
0
  auto *TypePtr = (const void *)&*Iter;
2221
0
  ArgBackRefMap::iterator Found = FunArgBackReferences.find(TypePtr);
2222
2223
0
  if (Found == FunArgBackReferences.end()) {
2224
0
    std::string Name =
2225
0
        Dynamic ? "__pass_dynamic_object_size" : "__pass_object_size";
2226
0
    mangleArtificialTagType(TagTypeKind::Enum, Name + llvm::utostr(Type),
2227
0
                            {"__clang"});
2228
2229
0
    if (FunArgBackReferences.size() < 10) {
2230
0
      size_t Size = FunArgBackReferences.size();
2231
0
      FunArgBackReferences[TypePtr] = Size;
2232
0
    }
2233
0
  } else {
2234
0
    Out << Found->second;
2235
0
  }
2236
0
}
2237
2238
void MicrosoftCXXNameMangler::mangleAddressSpaceType(QualType T,
2239
                                                     Qualifiers Quals,
2240
0
                                                     SourceRange Range) {
2241
  // Address space is mangled as an unqualified templated type in the __clang
2242
  // namespace. The demangled version of this is:
2243
  // In the case of a language specific address space:
2244
  // __clang::struct _AS[language_addr_space]<Type>
2245
  // where:
2246
  //  <language_addr_space> ::= <OpenCL-addrspace> | <CUDA-addrspace>
2247
  //    <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
2248
  //                                "private"| "generic" | "device" | "host" ]
2249
  //    <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
2250
  //    Note that the above were chosen to match the Itanium mangling for this.
2251
  //
2252
  // In the case of a non-language specific address space:
2253
  //  __clang::struct _AS<TargetAS, Type>
2254
0
  assert(Quals.hasAddressSpace() && "Not valid without address space");
2255
0
  llvm::SmallString<32> ASMangling;
2256
0
  llvm::raw_svector_ostream Stream(ASMangling);
2257
0
  MicrosoftCXXNameMangler Extra(Context, Stream);
2258
0
  Stream << "?$";
2259
2260
0
  LangAS AS = Quals.getAddressSpace();
2261
0
  if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
2262
0
    unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
2263
0
    Extra.mangleSourceName("_AS");
2264
0
    Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(TargetAS));
2265
0
  } else {
2266
0
    switch (AS) {
2267
0
    default:
2268
0
      llvm_unreachable("Not a language specific address space");
2269
0
    case LangAS::opencl_global:
2270
0
      Extra.mangleSourceName("_ASCLglobal");
2271
0
      break;
2272
0
    case LangAS::opencl_global_device:
2273
0
      Extra.mangleSourceName("_ASCLdevice");
2274
0
      break;
2275
0
    case LangAS::opencl_global_host:
2276
0
      Extra.mangleSourceName("_ASCLhost");
2277
0
      break;
2278
0
    case LangAS::opencl_local:
2279
0
      Extra.mangleSourceName("_ASCLlocal");
2280
0
      break;
2281
0
    case LangAS::opencl_constant:
2282
0
      Extra.mangleSourceName("_ASCLconstant");
2283
0
      break;
2284
0
    case LangAS::opencl_private:
2285
0
      Extra.mangleSourceName("_ASCLprivate");
2286
0
      break;
2287
0
    case LangAS::opencl_generic:
2288
0
      Extra.mangleSourceName("_ASCLgeneric");
2289
0
      break;
2290
0
    case LangAS::cuda_device:
2291
0
      Extra.mangleSourceName("_ASCUdevice");
2292
0
      break;
2293
0
    case LangAS::cuda_constant:
2294
0
      Extra.mangleSourceName("_ASCUconstant");
2295
0
      break;
2296
0
    case LangAS::cuda_shared:
2297
0
      Extra.mangleSourceName("_ASCUshared");
2298
0
      break;
2299
0
    case LangAS::ptr32_sptr:
2300
0
    case LangAS::ptr32_uptr:
2301
0
    case LangAS::ptr64:
2302
0
      llvm_unreachable("don't mangle ptr address spaces with _AS");
2303
0
    }
2304
0
  }
2305
2306
0
  Extra.mangleType(T, Range, QMM_Escape);
2307
0
  mangleQualifiers(Qualifiers(), false);
2308
0
  mangleArtificialTagType(TagTypeKind::Struct, ASMangling, {"__clang"});
2309
0
}
2310
2311
void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
2312
0
                                         QualifierMangleMode QMM) {
2313
  // Don't use the canonical types.  MSVC includes things like 'const' on
2314
  // pointer arguments to function pointers that canonicalization strips away.
2315
0
  T = T.getDesugaredType(getASTContext());
2316
0
  Qualifiers Quals = T.getLocalQualifiers();
2317
2318
0
  if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
2319
    // If there were any Quals, getAsArrayType() pushed them onto the array
2320
    // element type.
2321
0
    if (QMM == QMM_Mangle)
2322
0
      Out << 'A';
2323
0
    else if (QMM == QMM_Escape || QMM == QMM_Result)
2324
0
      Out << "$$B";
2325
0
    mangleArrayType(AT);
2326
0
    return;
2327
0
  }
2328
2329
0
  bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
2330
0
                   T->isReferenceType() || T->isBlockPointerType();
2331
2332
0
  switch (QMM) {
2333
0
  case QMM_Drop:
2334
0
    if (Quals.hasObjCLifetime())
2335
0
      Quals = Quals.withoutObjCLifetime();
2336
0
    break;
2337
0
  case QMM_Mangle:
2338
0
    if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
2339
0
      Out << '6';
2340
0
      mangleFunctionType(FT);
2341
0
      return;
2342
0
    }
2343
0
    mangleQualifiers(Quals, false);
2344
0
    break;
2345
0
  case QMM_Escape:
2346
0
    if (!IsPointer && Quals) {
2347
0
      Out << "$$C";
2348
0
      mangleQualifiers(Quals, false);
2349
0
    }
2350
0
    break;
2351
0
  case QMM_Result:
2352
    // Presence of __unaligned qualifier shouldn't affect mangling here.
2353
0
    Quals.removeUnaligned();
2354
0
    if (Quals.hasObjCLifetime())
2355
0
      Quals = Quals.withoutObjCLifetime();
2356
0
    if ((!IsPointer && Quals) || isa<TagType>(T) || isArtificialTagType(T)) {
2357
0
      Out << '?';
2358
0
      mangleQualifiers(Quals, false);
2359
0
    }
2360
0
    break;
2361
0
  }
2362
2363
0
  const Type *ty = T.getTypePtr();
2364
2365
0
  switch (ty->getTypeClass()) {
2366
0
#define ABSTRACT_TYPE(CLASS, PARENT)
2367
0
#define NON_CANONICAL_TYPE(CLASS, PARENT) \
2368
0
  case Type::CLASS: \
2369
0
    llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
2370
0
    return;
2371
0
#define TYPE(CLASS, PARENT) \
2372
0
  case Type::CLASS: \
2373
0
    mangleType(cast<CLASS##Type>(ty), Quals, Range); \
2374
0
    break;
2375
0
#include "clang/AST/TypeNodes.inc"
2376
0
#undef ABSTRACT_TYPE
2377
0
#undef NON_CANONICAL_TYPE
2378
0
#undef TYPE
2379
0
  }
2380
0
}
2381
2382
void MicrosoftCXXNameMangler::mangleType(const BuiltinType *T, Qualifiers,
2383
0
                                         SourceRange Range) {
2384
  //  <type>         ::= <builtin-type>
2385
  //  <builtin-type> ::= X  # void
2386
  //                 ::= C  # signed char
2387
  //                 ::= D  # char
2388
  //                 ::= E  # unsigned char
2389
  //                 ::= F  # short
2390
  //                 ::= G  # unsigned short (or wchar_t if it's not a builtin)
2391
  //                 ::= H  # int
2392
  //                 ::= I  # unsigned int
2393
  //                 ::= J  # long
2394
  //                 ::= K  # unsigned long
2395
  //                     L  # <none>
2396
  //                 ::= M  # float
2397
  //                 ::= N  # double
2398
  //                 ::= O  # long double (__float80 is mangled differently)
2399
  //                 ::= _J # long long, __int64
2400
  //                 ::= _K # unsigned long long, __int64
2401
  //                 ::= _L # __int128
2402
  //                 ::= _M # unsigned __int128
2403
  //                 ::= _N # bool
2404
  //                     _O # <array in parameter>
2405
  //                 ::= _Q # char8_t
2406
  //                 ::= _S # char16_t
2407
  //                 ::= _T # __float80 (Intel)
2408
  //                 ::= _U # char32_t
2409
  //                 ::= _W # wchar_t
2410
  //                 ::= _Z # __float80 (Digital Mars)
2411
0
  switch (T->getKind()) {
2412
0
  case BuiltinType::Void:
2413
0
    Out << 'X';
2414
0
    break;
2415
0
  case BuiltinType::SChar:
2416
0
    Out << 'C';
2417
0
    break;
2418
0
  case BuiltinType::Char_U:
2419
0
  case BuiltinType::Char_S:
2420
0
    Out << 'D';
2421
0
    break;
2422
0
  case BuiltinType::UChar:
2423
0
    Out << 'E';
2424
0
    break;
2425
0
  case BuiltinType::Short:
2426
0
    Out << 'F';
2427
0
    break;
2428
0
  case BuiltinType::UShort:
2429
0
    Out << 'G';
2430
0
    break;
2431
0
  case BuiltinType::Int:
2432
0
    Out << 'H';
2433
0
    break;
2434
0
  case BuiltinType::UInt:
2435
0
    Out << 'I';
2436
0
    break;
2437
0
  case BuiltinType::Long:
2438
0
    Out << 'J';
2439
0
    break;
2440
0
  case BuiltinType::ULong:
2441
0
    Out << 'K';
2442
0
    break;
2443
0
  case BuiltinType::Float:
2444
0
    Out << 'M';
2445
0
    break;
2446
0
  case BuiltinType::Double:
2447
0
    Out << 'N';
2448
0
    break;
2449
  // TODO: Determine size and mangle accordingly
2450
0
  case BuiltinType::LongDouble:
2451
0
    Out << 'O';
2452
0
    break;
2453
0
  case BuiltinType::LongLong:
2454
0
    Out << "_J";
2455
0
    break;
2456
0
  case BuiltinType::ULongLong:
2457
0
    Out << "_K";
2458
0
    break;
2459
0
  case BuiltinType::Int128:
2460
0
    Out << "_L";
2461
0
    break;
2462
0
  case BuiltinType::UInt128:
2463
0
    Out << "_M";
2464
0
    break;
2465
0
  case BuiltinType::Bool:
2466
0
    Out << "_N";
2467
0
    break;
2468
0
  case BuiltinType::Char8:
2469
0
    Out << "_Q";
2470
0
    break;
2471
0
  case BuiltinType::Char16:
2472
0
    Out << "_S";
2473
0
    break;
2474
0
  case BuiltinType::Char32:
2475
0
    Out << "_U";
2476
0
    break;
2477
0
  case BuiltinType::WChar_S:
2478
0
  case BuiltinType::WChar_U:
2479
0
    Out << "_W";
2480
0
    break;
2481
2482
0
#define BUILTIN_TYPE(Id, SingletonId)
2483
0
#define PLACEHOLDER_TYPE(Id, SingletonId) \
2484
0
  case BuiltinType::Id:
2485
0
#include "clang/AST/BuiltinTypes.def"
2486
0
  case BuiltinType::Dependent:
2487
0
    llvm_unreachable("placeholder types shouldn't get to name mangling");
2488
2489
0
  case BuiltinType::ObjCId:
2490
0
    mangleArtificialTagType(TagTypeKind::Struct, "objc_object");
2491
0
    break;
2492
0
  case BuiltinType::ObjCClass:
2493
0
    mangleArtificialTagType(TagTypeKind::Struct, "objc_class");
2494
0
    break;
2495
0
  case BuiltinType::ObjCSel:
2496
0
    mangleArtificialTagType(TagTypeKind::Struct, "objc_selector");
2497
0
    break;
2498
2499
0
#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
2500
0
  case BuiltinType::Id: \
2501
0
    Out << "PAUocl_" #ImgType "_" #Suffix "@@"; \
2502
0
    break;
2503
0
#include "clang/Basic/OpenCLImageTypes.def"
2504
0
  case BuiltinType::OCLSampler:
2505
0
    Out << "PA";
2506
0
    mangleArtificialTagType(TagTypeKind::Struct, "ocl_sampler");
2507
0
    break;
2508
0
  case BuiltinType::OCLEvent:
2509
0
    Out << "PA";
2510
0
    mangleArtificialTagType(TagTypeKind::Struct, "ocl_event");
2511
0
    break;
2512
0
  case BuiltinType::OCLClkEvent:
2513
0
    Out << "PA";
2514
0
    mangleArtificialTagType(TagTypeKind::Struct, "ocl_clkevent");
2515
0
    break;
2516
0
  case BuiltinType::OCLQueue:
2517
0
    Out << "PA";
2518
0
    mangleArtificialTagType(TagTypeKind::Struct, "ocl_queue");
2519
0
    break;
2520
0
  case BuiltinType::OCLReserveID:
2521
0
    Out << "PA";
2522
0
    mangleArtificialTagType(TagTypeKind::Struct, "ocl_reserveid");
2523
0
    break;
2524
0
#define EXT_OPAQUE_TYPE(ExtType, Id, Ext)                                      \
2525
0
  case BuiltinType::Id:                                                        \
2526
0
    mangleArtificialTagType(TagTypeKind::Struct, "ocl_" #ExtType);             \
2527
0
    break;
2528
0
#include "clang/Basic/OpenCLExtensionTypes.def"
2529
2530
0
  case BuiltinType::NullPtr:
2531
0
    Out << "$$T";
2532
0
    break;
2533
2534
0
  case BuiltinType::Float16:
2535
0
    mangleArtificialTagType(TagTypeKind::Struct, "_Float16", {"__clang"});
2536
0
    break;
2537
2538
0
  case BuiltinType::Half:
2539
0
    if (!getASTContext().getLangOpts().HLSL)
2540
0
      mangleArtificialTagType(TagTypeKind::Struct, "_Half", {"__clang"});
2541
0
    else if (getASTContext().getLangOpts().NativeHalfType)
2542
0
      Out << "$f16@";
2543
0
    else
2544
0
      Out << "$halff@";
2545
0
    break;
2546
2547
0
  case BuiltinType::BFloat16:
2548
0
    mangleArtificialTagType(TagTypeKind::Struct, "__bf16", {"__clang"});
2549
0
    break;
2550
2551
0
#define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS)          \
2552
0
  case BuiltinType::Id:                                                        \
2553
0
    mangleArtificialTagType(TagTypeKind::Struct, MangledName);                 \
2554
0
    mangleArtificialTagType(TagTypeKind::Struct, MangledName, {"__clang"});    \
2555
0
    break;
2556
2557
0
#include "clang/Basic/WebAssemblyReferenceTypes.def"
2558
0
#define SVE_TYPE(Name, Id, SingletonId) \
2559
0
  case BuiltinType::Id:
2560
0
#include "clang/Basic/AArch64SVEACLETypes.def"
2561
0
#define PPC_VECTOR_TYPE(Name, Id, Size) \
2562
0
  case BuiltinType::Id:
2563
0
#include "clang/Basic/PPCTypes.def"
2564
0
#define RVV_TYPE(Name, Id, SingletonId) case BuiltinType::Id:
2565
0
#include "clang/Basic/RISCVVTypes.def"
2566
0
  case BuiltinType::ShortAccum:
2567
0
  case BuiltinType::Accum:
2568
0
  case BuiltinType::LongAccum:
2569
0
  case BuiltinType::UShortAccum:
2570
0
  case BuiltinType::UAccum:
2571
0
  case BuiltinType::ULongAccum:
2572
0
  case BuiltinType::ShortFract:
2573
0
  case BuiltinType::Fract:
2574
0
  case BuiltinType::LongFract:
2575
0
  case BuiltinType::UShortFract:
2576
0
  case BuiltinType::UFract:
2577
0
  case BuiltinType::ULongFract:
2578
0
  case BuiltinType::SatShortAccum:
2579
0
  case BuiltinType::SatAccum:
2580
0
  case BuiltinType::SatLongAccum:
2581
0
  case BuiltinType::SatUShortAccum:
2582
0
  case BuiltinType::SatUAccum:
2583
0
  case BuiltinType::SatULongAccum:
2584
0
  case BuiltinType::SatShortFract:
2585
0
  case BuiltinType::SatFract:
2586
0
  case BuiltinType::SatLongFract:
2587
0
  case BuiltinType::SatUShortFract:
2588
0
  case BuiltinType::SatUFract:
2589
0
  case BuiltinType::SatULongFract:
2590
0
  case BuiltinType::Ibm128:
2591
0
  case BuiltinType::Float128: {
2592
0
    DiagnosticsEngine &Diags = Context.getDiags();
2593
0
    unsigned DiagID = Diags.getCustomDiagID(
2594
0
        DiagnosticsEngine::Error, "cannot mangle this built-in %0 type yet");
2595
0
    Diags.Report(Range.getBegin(), DiagID)
2596
0
        << T->getName(Context.getASTContext().getPrintingPolicy()) << Range;
2597
0
    break;
2598
0
  }
2599
0
  }
2600
0
}
2601
2602
// <type>          ::= <function-type>
2603
void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T, Qualifiers,
2604
0
                                         SourceRange) {
2605
  // Structors only appear in decls, so at this point we know it's not a
2606
  // structor type.
2607
  // FIXME: This may not be lambda-friendly.
2608
0
  if (T->getMethodQuals() || T->getRefQualifier() != RQ_None) {
2609
0
    Out << "$$A8@@";
2610
0
    mangleFunctionType(T, /*D=*/nullptr, /*ForceThisQuals=*/true);
2611
0
  } else {
2612
0
    Out << "$$A6";
2613
0
    mangleFunctionType(T);
2614
0
  }
2615
0
}
2616
void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
2617
0
                                         Qualifiers, SourceRange) {
2618
0
  Out << "$$A6";
2619
0
  mangleFunctionType(T);
2620
0
}
2621
2622
void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
2623
                                                 const FunctionDecl *D,
2624
                                                 bool ForceThisQuals,
2625
0
                                                 bool MangleExceptionSpec) {
2626
  // <function-type> ::= <this-cvr-qualifiers> <calling-convention>
2627
  //                     <return-type> <argument-list> <throw-spec>
2628
0
  const FunctionProtoType *Proto = dyn_cast<FunctionProtoType>(T);
2629
2630
0
  SourceRange Range;
2631
0
  if (D) Range = D->getSourceRange();
2632
2633
0
  bool IsInLambda = false;
2634
0
  bool IsStructor = false, HasThisQuals = ForceThisQuals, IsCtorClosure = false;
2635
0
  CallingConv CC = T->getCallConv();
2636
0
  if (const CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(D)) {
2637
0
    if (MD->getParent()->isLambda())
2638
0
      IsInLambda = true;
2639
0
    if (MD->isImplicitObjectMemberFunction())
2640
0
      HasThisQuals = true;
2641
0
    if (isa<CXXDestructorDecl>(MD)) {
2642
0
      IsStructor = true;
2643
0
    } else if (isa<CXXConstructorDecl>(MD)) {
2644
0
      IsStructor = true;
2645
0
      IsCtorClosure = (StructorType == Ctor_CopyingClosure ||
2646
0
                       StructorType == Ctor_DefaultClosure) &&
2647
0
                      isStructorDecl(MD);
2648
0
      if (IsCtorClosure)
2649
0
        CC = getASTContext().getDefaultCallingConvention(
2650
0
            /*IsVariadic=*/false, /*IsCXXMethod=*/true);
2651
0
    }
2652
0
  }
2653
2654
  // If this is a C++ instance method, mangle the CVR qualifiers for the
2655
  // this pointer.
2656
0
  if (HasThisQuals) {
2657
0
    Qualifiers Quals = Proto->getMethodQuals();
2658
0
    manglePointerExtQualifiers(Quals, /*PointeeType=*/QualType());
2659
0
    mangleRefQualifier(Proto->getRefQualifier());
2660
0
    mangleQualifiers(Quals, /*IsMember=*/false);
2661
0
  }
2662
2663
0
  mangleCallingConvention(CC);
2664
2665
  // <return-type> ::= <type>
2666
  //               ::= @ # structors (they have no declared return type)
2667
0
  if (IsStructor) {
2668
0
    if (isa<CXXDestructorDecl>(D) && isStructorDecl(D)) {
2669
      // The scalar deleting destructor takes an extra int argument which is not
2670
      // reflected in the AST.
2671
0
      if (StructorType == Dtor_Deleting) {
2672
0
        Out << (PointersAre64Bit ? "PEAXI@Z" : "PAXI@Z");
2673
0
        return;
2674
0
      }
2675
      // The vbase destructor returns void which is not reflected in the AST.
2676
0
      if (StructorType == Dtor_Complete) {
2677
0
        Out << "XXZ";
2678
0
        return;
2679
0
      }
2680
0
    }
2681
0
    if (IsCtorClosure) {
2682
      // Default constructor closure and copy constructor closure both return
2683
      // void.
2684
0
      Out << 'X';
2685
2686
0
      if (StructorType == Ctor_DefaultClosure) {
2687
        // Default constructor closure always has no arguments.
2688
0
        Out << 'X';
2689
0
      } else if (StructorType == Ctor_CopyingClosure) {
2690
        // Copy constructor closure always takes an unqualified reference.
2691
0
        mangleFunctionArgumentType(getASTContext().getLValueReferenceType(
2692
0
                                       Proto->getParamType(0)
2693
0
                                           ->castAs<LValueReferenceType>()
2694
0
                                           ->getPointeeType(),
2695
0
                                       /*SpelledAsLValue=*/true),
2696
0
                                   Range);
2697
0
        Out << '@';
2698
0
      } else {
2699
0
        llvm_unreachable("unexpected constructor closure!");
2700
0
      }
2701
0
      Out << 'Z';
2702
0
      return;
2703
0
    }
2704
0
    Out << '@';
2705
0
  } else if (IsInLambda && D && isa<CXXConversionDecl>(D)) {
2706
    // The only lambda conversion operators are to function pointers, which
2707
    // can differ by their calling convention and are typically deduced.  So
2708
    // we make sure that this type gets mangled properly.
2709
0
    mangleType(T->getReturnType(), Range, QMM_Result);
2710
0
  } else {
2711
0
    QualType ResultType = T->getReturnType();
2712
0
    if (IsInLambda && isa<CXXConversionDecl>(D)) {
2713
      // The only lambda conversion operators are to function pointers, which
2714
      // can differ by their calling convention and are typically deduced.  So
2715
      // we make sure that this type gets mangled properly.
2716
0
      mangleType(ResultType, Range, QMM_Result);
2717
0
    } else if (const auto *AT = dyn_cast_or_null<AutoType>(
2718
0
                   ResultType->getContainedAutoType())) {
2719
0
      Out << '?';
2720
0
      mangleQualifiers(ResultType.getLocalQualifiers(), /*IsMember=*/false);
2721
0
      Out << '?';
2722
0
      assert(AT->getKeyword() != AutoTypeKeyword::GNUAutoType &&
2723
0
             "shouldn't need to mangle __auto_type!");
2724
0
      mangleSourceName(AT->isDecltypeAuto() ? "<decltype-auto>" : "<auto>");
2725
0
      Out << '@';
2726
0
    } else if (IsInLambda) {
2727
0
      Out << '@';
2728
0
    } else {
2729
0
      if (ResultType->isVoidType())
2730
0
        ResultType = ResultType.getUnqualifiedType();
2731
0
      mangleType(ResultType, Range, QMM_Result);
2732
0
    }
2733
0
  }
2734
2735
  // <argument-list> ::= X # void
2736
  //                 ::= <type>+ @
2737
  //                 ::= <type>* Z # varargs
2738
0
  if (!Proto) {
2739
    // Function types without prototypes can arise when mangling a function type
2740
    // within an overloadable function in C. We mangle these as the absence of
2741
    // any parameter types (not even an empty parameter list).
2742
0
    Out << '@';
2743
0
  } else if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
2744
0
    Out << 'X';
2745
0
  } else {
2746
    // Happens for function pointer type arguments for example.
2747
0
    for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
2748
      // Explicit object parameters are prefixed by "_V".
2749
0
      if (I == 0 && D && D->getParamDecl(I)->isExplicitObjectParameter())
2750
0
        Out << "_V";
2751
2752
0
      mangleFunctionArgumentType(Proto->getParamType(I), Range);
2753
      // Mangle each pass_object_size parameter as if it's a parameter of enum
2754
      // type passed directly after the parameter with the pass_object_size
2755
      // attribute. The aforementioned enum's name is __pass_object_size, and we
2756
      // pretend it resides in a top-level namespace called __clang.
2757
      //
2758
      // FIXME: Is there a defined extension notation for the MS ABI, or is it
2759
      // necessary to just cross our fingers and hope this type+namespace
2760
      // combination doesn't conflict with anything?
2761
0
      if (D)
2762
0
        if (const auto *P = D->getParamDecl(I)->getAttr<PassObjectSizeAttr>())
2763
0
          manglePassObjectSizeArg(P);
2764
0
    }
2765
    // <builtin-type>      ::= Z  # ellipsis
2766
0
    if (Proto->isVariadic())
2767
0
      Out << 'Z';
2768
0
    else
2769
0
      Out << '@';
2770
0
  }
2771
2772
0
  if (MangleExceptionSpec && getASTContext().getLangOpts().CPlusPlus17 &&
2773
0
      getASTContext().getLangOpts().isCompatibleWithMSVC(
2774
0
          LangOptions::MSVC2017_5))
2775
0
    mangleThrowSpecification(Proto);
2776
0
  else
2777
0
    Out << 'Z';
2778
0
}
2779
2780
0
void MicrosoftCXXNameMangler::mangleFunctionClass(const FunctionDecl *FD) {
2781
  // <function-class>  ::= <member-function> E? # E designates a 64-bit 'this'
2782
  //                                            # pointer. in 64-bit mode *all*
2783
  //                                            # 'this' pointers are 64-bit.
2784
  //                   ::= <global-function>
2785
  // <member-function> ::= A # private: near
2786
  //                   ::= B # private: far
2787
  //                   ::= C # private: static near
2788
  //                   ::= D # private: static far
2789
  //                   ::= E # private: virtual near
2790
  //                   ::= F # private: virtual far
2791
  //                   ::= I # protected: near
2792
  //                   ::= J # protected: far
2793
  //                   ::= K # protected: static near
2794
  //                   ::= L # protected: static far
2795
  //                   ::= M # protected: virtual near
2796
  //                   ::= N # protected: virtual far
2797
  //                   ::= Q # public: near
2798
  //                   ::= R # public: far
2799
  //                   ::= S # public: static near
2800
  //                   ::= T # public: static far
2801
  //                   ::= U # public: virtual near
2802
  //                   ::= V # public: virtual far
2803
  // <global-function> ::= Y # global near
2804
  //                   ::= Z # global far
2805
0
  if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD)) {
2806
0
    bool IsVirtual = MD->isVirtual();
2807
    // When mangling vbase destructor variants, ignore whether or not the
2808
    // underlying destructor was defined to be virtual.
2809
0
    if (isa<CXXDestructorDecl>(MD) && isStructorDecl(MD) &&
2810
0
        StructorType == Dtor_Complete) {
2811
0
      IsVirtual = false;
2812
0
    }
2813
0
    switch (MD->getAccess()) {
2814
0
      case AS_none:
2815
0
        llvm_unreachable("Unsupported access specifier");
2816
0
      case AS_private:
2817
0
        if (!MD->isImplicitObjectMemberFunction())
2818
0
          Out << 'C';
2819
0
        else if (IsVirtual)
2820
0
          Out << 'E';
2821
0
        else
2822
0
          Out << 'A';
2823
0
        break;
2824
0
      case AS_protected:
2825
0
        if (!MD->isImplicitObjectMemberFunction())
2826
0
          Out << 'K';
2827
0
        else if (IsVirtual)
2828
0
          Out << 'M';
2829
0
        else
2830
0
          Out << 'I';
2831
0
        break;
2832
0
      case AS_public:
2833
0
        if (!MD->isImplicitObjectMemberFunction())
2834
0
          Out << 'S';
2835
0
        else if (IsVirtual)
2836
0
          Out << 'U';
2837
0
        else
2838
0
          Out << 'Q';
2839
0
    }
2840
0
  } else {
2841
0
    Out << 'Y';
2842
0
  }
2843
0
}
2844
0
void MicrosoftCXXNameMangler::mangleCallingConvention(CallingConv CC) {
2845
  // <calling-convention> ::= A # __cdecl
2846
  //                      ::= B # __export __cdecl
2847
  //                      ::= C # __pascal
2848
  //                      ::= D # __export __pascal
2849
  //                      ::= E # __thiscall
2850
  //                      ::= F # __export __thiscall
2851
  //                      ::= G # __stdcall
2852
  //                      ::= H # __export __stdcall
2853
  //                      ::= I # __fastcall
2854
  //                      ::= J # __export __fastcall
2855
  //                      ::= Q # __vectorcall
2856
  //                      ::= S # __attribute__((__swiftcall__)) // Clang-only
2857
  //                      ::= T # __attribute__((__swiftasynccall__))
2858
  //                            // Clang-only
2859
  //                      ::= w # __regcall
2860
  //                      ::= x # __regcall4
2861
  // The 'export' calling conventions are from a bygone era
2862
  // (*cough*Win16*cough*) when functions were declared for export with
2863
  // that keyword. (It didn't actually export them, it just made them so
2864
  // that they could be in a DLL and somebody from another module could call
2865
  // them.)
2866
2867
0
  switch (CC) {
2868
0
    default:
2869
0
      llvm_unreachable("Unsupported CC for mangling");
2870
0
    case CC_Win64:
2871
0
    case CC_X86_64SysV:
2872
0
    case CC_C: Out << 'A'; break;
2873
0
    case CC_X86Pascal: Out << 'C'; break;
2874
0
    case CC_X86ThisCall: Out << 'E'; break;
2875
0
    case CC_X86StdCall: Out << 'G'; break;
2876
0
    case CC_X86FastCall: Out << 'I'; break;
2877
0
    case CC_X86VectorCall: Out << 'Q'; break;
2878
0
    case CC_Swift: Out << 'S'; break;
2879
0
    case CC_SwiftAsync: Out << 'W'; break;
2880
0
    case CC_PreserveMost: Out << 'U'; break;
2881
0
    case CC_X86RegCall:
2882
0
      if (getASTContext().getLangOpts().RegCall4)
2883
0
        Out << "x";
2884
0
      else
2885
0
        Out << "w";
2886
0
      break;
2887
0
  }
2888
0
}
2889
0
void MicrosoftCXXNameMangler::mangleCallingConvention(const FunctionType *T) {
2890
0
  mangleCallingConvention(T->getCallConv());
2891
0
}
2892
2893
void MicrosoftCXXNameMangler::mangleThrowSpecification(
2894
0
                                                const FunctionProtoType *FT) {
2895
  // <throw-spec> ::= Z # (default)
2896
  //              ::= _E # noexcept
2897
0
  if (FT->canThrow())
2898
0
    Out << 'Z';
2899
0
  else
2900
0
    Out << "_E";
2901
0
}
2902
2903
void MicrosoftCXXNameMangler::mangleType(const UnresolvedUsingType *T,
2904
0
                                         Qualifiers, SourceRange Range) {
2905
  // Probably should be mangled as a template instantiation; need to see what
2906
  // VC does first.
2907
0
  DiagnosticsEngine &Diags = Context.getDiags();
2908
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
2909
0
    "cannot mangle this unresolved dependent type yet");
2910
0
  Diags.Report(Range.getBegin(), DiagID)
2911
0
    << Range;
2912
0
}
2913
2914
// <type>        ::= <union-type> | <struct-type> | <class-type> | <enum-type>
2915
// <union-type>  ::= T <name>
2916
// <struct-type> ::= U <name>
2917
// <class-type>  ::= V <name>
2918
// <enum-type>   ::= W4 <name>
2919
0
void MicrosoftCXXNameMangler::mangleTagTypeKind(TagTypeKind TTK) {
2920
0
  switch (TTK) {
2921
0
  case TagTypeKind::Union:
2922
0
    Out << 'T';
2923
0
    break;
2924
0
  case TagTypeKind::Struct:
2925
0
  case TagTypeKind::Interface:
2926
0
    Out << 'U';
2927
0
    break;
2928
0
  case TagTypeKind::Class:
2929
0
    Out << 'V';
2930
0
    break;
2931
0
  case TagTypeKind::Enum:
2932
0
    Out << "W4";
2933
0
    break;
2934
0
  }
2935
0
}
2936
void MicrosoftCXXNameMangler::mangleType(const EnumType *T, Qualifiers,
2937
0
                                         SourceRange) {
2938
0
  mangleType(cast<TagType>(T)->getDecl());
2939
0
}
2940
void MicrosoftCXXNameMangler::mangleType(const RecordType *T, Qualifiers,
2941
0
                                         SourceRange) {
2942
0
  mangleType(cast<TagType>(T)->getDecl());
2943
0
}
2944
0
void MicrosoftCXXNameMangler::mangleType(const TagDecl *TD) {
2945
0
  mangleTagTypeKind(TD->getTagKind());
2946
0
  mangleName(TD);
2947
0
}
2948
2949
// If you add a call to this, consider updating isArtificialTagType() too.
2950
void MicrosoftCXXNameMangler::mangleArtificialTagType(
2951
    TagTypeKind TK, StringRef UnqualifiedName,
2952
0
    ArrayRef<StringRef> NestedNames) {
2953
  // <name> ::= <unscoped-name> {[<named-scope>]+ | [<nested-name>]}? @
2954
0
  mangleTagTypeKind(TK);
2955
2956
  // Always start with the unqualified name.
2957
0
  mangleSourceName(UnqualifiedName);
2958
2959
0
  for (StringRef N : llvm::reverse(NestedNames))
2960
0
    mangleSourceName(N);
2961
2962
  // Terminate the whole name with an '@'.
2963
0
  Out << '@';
2964
0
}
2965
2966
// <type>       ::= <array-type>
2967
// <array-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
2968
//                  [Y <dimension-count> <dimension>+]
2969
//                  <element-type> # as global, E is never required
2970
// It's supposed to be the other way around, but for some strange reason, it
2971
// isn't. Today this behavior is retained for the sole purpose of backwards
2972
// compatibility.
2973
0
void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T) {
2974
  // This isn't a recursive mangling, so now we have to do it all in this
2975
  // one call.
2976
0
  manglePointerCVQualifiers(T->getElementType().getQualifiers());
2977
0
  mangleType(T->getElementType(), SourceRange());
2978
0
}
2979
void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T, Qualifiers,
2980
0
                                         SourceRange) {
2981
0
  llvm_unreachable("Should have been special cased");
2982
0
}
2983
void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T, Qualifiers,
2984
0
                                         SourceRange) {
2985
0
  llvm_unreachable("Should have been special cased");
2986
0
}
2987
void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
2988
0
                                         Qualifiers, SourceRange) {
2989
0
  llvm_unreachable("Should have been special cased");
2990
0
}
2991
void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
2992
0
                                         Qualifiers, SourceRange) {
2993
0
  llvm_unreachable("Should have been special cased");
2994
0
}
2995
0
void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T) {
2996
0
  QualType ElementTy(T, 0);
2997
0
  SmallVector<llvm::APInt, 3> Dimensions;
2998
0
  for (;;) {
2999
0
    if (ElementTy->isConstantArrayType()) {
3000
0
      const ConstantArrayType *CAT =
3001
0
          getASTContext().getAsConstantArrayType(ElementTy);
3002
0
      Dimensions.push_back(CAT->getSize());
3003
0
      ElementTy = CAT->getElementType();
3004
0
    } else if (ElementTy->isIncompleteArrayType()) {
3005
0
      const IncompleteArrayType *IAT =
3006
0
          getASTContext().getAsIncompleteArrayType(ElementTy);
3007
0
      Dimensions.push_back(llvm::APInt(32, 0));
3008
0
      ElementTy = IAT->getElementType();
3009
0
    } else if (ElementTy->isVariableArrayType()) {
3010
0
      const VariableArrayType *VAT =
3011
0
        getASTContext().getAsVariableArrayType(ElementTy);
3012
0
      Dimensions.push_back(llvm::APInt(32, 0));
3013
0
      ElementTy = VAT->getElementType();
3014
0
    } else if (ElementTy->isDependentSizedArrayType()) {
3015
      // The dependent expression has to be folded into a constant (TODO).
3016
0
      const DependentSizedArrayType *DSAT =
3017
0
        getASTContext().getAsDependentSizedArrayType(ElementTy);
3018
0
      DiagnosticsEngine &Diags = Context.getDiags();
3019
0
      unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3020
0
        "cannot mangle this dependent-length array yet");
3021
0
      Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
3022
0
        << DSAT->getBracketsRange();
3023
0
      return;
3024
0
    } else {
3025
0
      break;
3026
0
    }
3027
0
  }
3028
0
  Out << 'Y';
3029
  // <dimension-count> ::= <number> # number of extra dimensions
3030
0
  mangleNumber(Dimensions.size());
3031
0
  for (const llvm::APInt &Dimension : Dimensions)
3032
0
    mangleNumber(Dimension.getLimitedValue());
3033
0
  mangleType(ElementTy, SourceRange(), QMM_Escape);
3034
0
}
3035
3036
// <type>                   ::= <pointer-to-member-type>
3037
// <pointer-to-member-type> ::= <pointer-cvr-qualifiers> <cvr-qualifiers>
3038
//                                                          <class name> <type>
3039
void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
3040
0
                                         Qualifiers Quals, SourceRange Range) {
3041
0
  QualType PointeeType = T->getPointeeType();
3042
0
  manglePointerCVQualifiers(Quals);
3043
0
  manglePointerExtQualifiers(Quals, PointeeType);
3044
0
  if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
3045
0
    Out << '8';
3046
0
    mangleName(T->getClass()->castAs<RecordType>()->getDecl());
3047
0
    mangleFunctionType(FPT, nullptr, true);
3048
0
  } else {
3049
0
    mangleQualifiers(PointeeType.getQualifiers(), true);
3050
0
    mangleName(T->getClass()->castAs<RecordType>()->getDecl());
3051
0
    mangleType(PointeeType, Range, QMM_Drop);
3052
0
  }
3053
0
}
3054
3055
void MicrosoftCXXNameMangler::mangleType(const TemplateTypeParmType *T,
3056
0
                                         Qualifiers, SourceRange Range) {
3057
0
  DiagnosticsEngine &Diags = Context.getDiags();
3058
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3059
0
    "cannot mangle this template type parameter type yet");
3060
0
  Diags.Report(Range.getBegin(), DiagID)
3061
0
    << Range;
3062
0
}
3063
3064
void MicrosoftCXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T,
3065
0
                                         Qualifiers, SourceRange Range) {
3066
0
  DiagnosticsEngine &Diags = Context.getDiags();
3067
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3068
0
    "cannot mangle this substituted parameter pack yet");
3069
0
  Diags.Report(Range.getBegin(), DiagID)
3070
0
    << Range;
3071
0
}
3072
3073
// <type> ::= <pointer-type>
3074
// <pointer-type> ::= E? <pointer-cvr-qualifiers> <cvr-qualifiers> <type>
3075
//                       # the E is required for 64-bit non-static pointers
3076
void MicrosoftCXXNameMangler::mangleType(const PointerType *T, Qualifiers Quals,
3077
0
                                         SourceRange Range) {
3078
0
  QualType PointeeType = T->getPointeeType();
3079
0
  manglePointerCVQualifiers(Quals);
3080
0
  manglePointerExtQualifiers(Quals, PointeeType);
3081
3082
  // For pointer size address spaces, go down the same type mangling path as
3083
  // non address space types.
3084
0
  LangAS AddrSpace = PointeeType.getQualifiers().getAddressSpace();
3085
0
  if (isPtrSizeAddressSpace(AddrSpace) || AddrSpace == LangAS::Default)
3086
0
    mangleType(PointeeType, Range);
3087
0
  else
3088
0
    mangleAddressSpaceType(PointeeType, PointeeType.getQualifiers(), Range);
3089
0
}
3090
3091
void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
3092
0
                                         Qualifiers Quals, SourceRange Range) {
3093
0
  QualType PointeeType = T->getPointeeType();
3094
0
  switch (Quals.getObjCLifetime()) {
3095
0
  case Qualifiers::OCL_None:
3096
0
  case Qualifiers::OCL_ExplicitNone:
3097
0
    break;
3098
0
  case Qualifiers::OCL_Autoreleasing:
3099
0
  case Qualifiers::OCL_Strong:
3100
0
  case Qualifiers::OCL_Weak:
3101
0
    return mangleObjCLifetime(PointeeType, Quals, Range);
3102
0
  }
3103
0
  manglePointerCVQualifiers(Quals);
3104
0
  manglePointerExtQualifiers(Quals, PointeeType);
3105
0
  mangleType(PointeeType, Range);
3106
0
}
3107
3108
// <type> ::= <reference-type>
3109
// <reference-type> ::= A E? <cvr-qualifiers> <type>
3110
//                 # the E is required for 64-bit non-static lvalue references
3111
void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
3112
0
                                         Qualifiers Quals, SourceRange Range) {
3113
0
  QualType PointeeType = T->getPointeeType();
3114
0
  assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
3115
0
  Out << 'A';
3116
0
  manglePointerExtQualifiers(Quals, PointeeType);
3117
0
  mangleType(PointeeType, Range);
3118
0
}
3119
3120
// <type> ::= <r-value-reference-type>
3121
// <r-value-reference-type> ::= $$Q E? <cvr-qualifiers> <type>
3122
//                 # the E is required for 64-bit non-static rvalue references
3123
void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
3124
0
                                         Qualifiers Quals, SourceRange Range) {
3125
0
  QualType PointeeType = T->getPointeeType();
3126
0
  assert(!Quals.hasConst() && !Quals.hasVolatile() && "unexpected qualifier!");
3127
0
  Out << "$$Q";
3128
0
  manglePointerExtQualifiers(Quals, PointeeType);
3129
0
  mangleType(PointeeType, Range);
3130
0
}
3131
3132
void MicrosoftCXXNameMangler::mangleType(const ComplexType *T, Qualifiers,
3133
0
                                         SourceRange Range) {
3134
0
  QualType ElementType = T->getElementType();
3135
3136
0
  llvm::SmallString<64> TemplateMangling;
3137
0
  llvm::raw_svector_ostream Stream(TemplateMangling);
3138
0
  MicrosoftCXXNameMangler Extra(Context, Stream);
3139
0
  Stream << "?$";
3140
0
  Extra.mangleSourceName("_Complex");
3141
0
  Extra.mangleType(ElementType, Range, QMM_Escape);
3142
3143
0
  mangleArtificialTagType(TagTypeKind::Struct, TemplateMangling, {"__clang"});
3144
0
}
3145
3146
// Returns true for types that mangleArtificialTagType() gets called for with
3147
// TagTypeKind Union, Struct, Class and where compatibility with MSVC's
3148
// mangling matters.
3149
// (It doesn't matter for Objective-C types and the like that cl.exe doesn't
3150
// support.)
3151
0
bool MicrosoftCXXNameMangler::isArtificialTagType(QualType T) const {
3152
0
  const Type *ty = T.getTypePtr();
3153
0
  switch (ty->getTypeClass()) {
3154
0
  default:
3155
0
    return false;
3156
3157
0
  case Type::Vector: {
3158
    // For ABI compatibility only __m64, __m128(id), and __m256(id) matter,
3159
    // but since mangleType(VectorType*) always calls mangleArtificialTagType()
3160
    // just always return true (the other vector types are clang-only).
3161
0
    return true;
3162
0
  }
3163
0
  }
3164
0
}
3165
3166
void MicrosoftCXXNameMangler::mangleType(const VectorType *T, Qualifiers Quals,
3167
0
                                         SourceRange Range) {
3168
0
  QualType EltTy = T->getElementType();
3169
0
  const BuiltinType *ET = EltTy->getAs<BuiltinType>();
3170
0
  const BitIntType *BitIntTy = EltTy->getAs<BitIntType>();
3171
0
  assert((ET || BitIntTy) &&
3172
0
         "vectors with non-builtin/_BitInt elements are unsupported");
3173
0
  uint64_t Width = getASTContext().getTypeSize(T);
3174
  // Pattern match exactly the typedefs in our intrinsic headers.  Anything that
3175
  // doesn't match the Intel types uses a custom mangling below.
3176
0
  size_t OutSizeBefore = Out.tell();
3177
0
  if (!isa<ExtVectorType>(T)) {
3178
0
    if (getASTContext().getTargetInfo().getTriple().isX86() && ET) {
3179
0
      if (Width == 64 && ET->getKind() == BuiltinType::LongLong) {
3180
0
        mangleArtificialTagType(TagTypeKind::Union, "__m64");
3181
0
      } else if (Width >= 128) {
3182
0
        if (ET->getKind() == BuiltinType::Float)
3183
0
          mangleArtificialTagType(TagTypeKind::Union,
3184
0
                                  "__m" + llvm::utostr(Width));
3185
0
        else if (ET->getKind() == BuiltinType::LongLong)
3186
0
          mangleArtificialTagType(TagTypeKind::Union,
3187
0
                                  "__m" + llvm::utostr(Width) + 'i');
3188
0
        else if (ET->getKind() == BuiltinType::Double)
3189
0
          mangleArtificialTagType(TagTypeKind::Struct,
3190
0
                                  "__m" + llvm::utostr(Width) + 'd');
3191
0
      }
3192
0
    }
3193
0
  }
3194
3195
0
  bool IsBuiltin = Out.tell() != OutSizeBefore;
3196
0
  if (!IsBuiltin) {
3197
    // The MS ABI doesn't have a special mangling for vector types, so we define
3198
    // our own mangling to handle uses of __vector_size__ on user-specified
3199
    // types, and for extensions like __v4sf.
3200
3201
0
    llvm::SmallString<64> TemplateMangling;
3202
0
    llvm::raw_svector_ostream Stream(TemplateMangling);
3203
0
    MicrosoftCXXNameMangler Extra(Context, Stream);
3204
0
    Stream << "?$";
3205
0
    Extra.mangleSourceName("__vector");
3206
0
    Extra.mangleType(QualType(ET ? static_cast<const Type *>(ET) : BitIntTy, 0),
3207
0
                     Range, QMM_Escape);
3208
0
    Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumElements()));
3209
3210
0
    mangleArtificialTagType(TagTypeKind::Union, TemplateMangling, {"__clang"});
3211
0
  }
3212
0
}
3213
3214
void MicrosoftCXXNameMangler::mangleType(const ExtVectorType *T,
3215
0
                                         Qualifiers Quals, SourceRange Range) {
3216
0
  mangleType(static_cast<const VectorType *>(T), Quals, Range);
3217
0
}
3218
3219
void MicrosoftCXXNameMangler::mangleType(const DependentVectorType *T,
3220
0
                                         Qualifiers, SourceRange Range) {
3221
0
  DiagnosticsEngine &Diags = Context.getDiags();
3222
0
  unsigned DiagID = Diags.getCustomDiagID(
3223
0
      DiagnosticsEngine::Error,
3224
0
      "cannot mangle this dependent-sized vector type yet");
3225
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3226
0
}
3227
3228
void MicrosoftCXXNameMangler::mangleType(const DependentSizedExtVectorType *T,
3229
0
                                         Qualifiers, SourceRange Range) {
3230
0
  DiagnosticsEngine &Diags = Context.getDiags();
3231
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3232
0
    "cannot mangle this dependent-sized extended vector type yet");
3233
0
  Diags.Report(Range.getBegin(), DiagID)
3234
0
    << Range;
3235
0
}
3236
3237
void MicrosoftCXXNameMangler::mangleType(const ConstantMatrixType *T,
3238
0
                                         Qualifiers quals, SourceRange Range) {
3239
0
  DiagnosticsEngine &Diags = Context.getDiags();
3240
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3241
0
                                          "Cannot mangle this matrix type yet");
3242
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3243
0
}
3244
3245
void MicrosoftCXXNameMangler::mangleType(const DependentSizedMatrixType *T,
3246
0
                                         Qualifiers quals, SourceRange Range) {
3247
0
  DiagnosticsEngine &Diags = Context.getDiags();
3248
0
  unsigned DiagID = Diags.getCustomDiagID(
3249
0
      DiagnosticsEngine::Error,
3250
0
      "Cannot mangle this dependent-sized matrix type yet");
3251
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3252
0
}
3253
3254
void MicrosoftCXXNameMangler::mangleType(const DependentAddressSpaceType *T,
3255
0
                                         Qualifiers, SourceRange Range) {
3256
0
  DiagnosticsEngine &Diags = Context.getDiags();
3257
0
  unsigned DiagID = Diags.getCustomDiagID(
3258
0
      DiagnosticsEngine::Error,
3259
0
      "cannot mangle this dependent address space type yet");
3260
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3261
0
}
3262
3263
void MicrosoftCXXNameMangler::mangleType(const ObjCInterfaceType *T, Qualifiers,
3264
0
                                         SourceRange) {
3265
  // ObjC interfaces have structs underlying them.
3266
0
  mangleTagTypeKind(TagTypeKind::Struct);
3267
0
  mangleName(T->getDecl());
3268
0
}
3269
3270
void MicrosoftCXXNameMangler::mangleType(const ObjCObjectType *T,
3271
0
                                         Qualifiers Quals, SourceRange Range) {
3272
0
  if (T->isKindOfType())
3273
0
    return mangleObjCKindOfType(T, Quals, Range);
3274
3275
0
  if (T->qual_empty() && !T->isSpecialized())
3276
0
    return mangleType(T->getBaseType(), Range, QMM_Drop);
3277
3278
0
  ArgBackRefMap OuterFunArgsContext;
3279
0
  ArgBackRefMap OuterTemplateArgsContext;
3280
0
  BackRefVec OuterTemplateContext;
3281
3282
0
  FunArgBackReferences.swap(OuterFunArgsContext);
3283
0
  TemplateArgBackReferences.swap(OuterTemplateArgsContext);
3284
0
  NameBackReferences.swap(OuterTemplateContext);
3285
3286
0
  mangleTagTypeKind(TagTypeKind::Struct);
3287
3288
0
  Out << "?$";
3289
0
  if (T->isObjCId())
3290
0
    mangleSourceName("objc_object");
3291
0
  else if (T->isObjCClass())
3292
0
    mangleSourceName("objc_class");
3293
0
  else
3294
0
    mangleSourceName(T->getInterface()->getName());
3295
3296
0
  for (const auto &Q : T->quals())
3297
0
    mangleObjCProtocol(Q);
3298
3299
0
  if (T->isSpecialized())
3300
0
    for (const auto &TA : T->getTypeArgs())
3301
0
      mangleType(TA, Range, QMM_Drop);
3302
3303
0
  Out << '@';
3304
3305
0
  Out << '@';
3306
3307
0
  FunArgBackReferences.swap(OuterFunArgsContext);
3308
0
  TemplateArgBackReferences.swap(OuterTemplateArgsContext);
3309
0
  NameBackReferences.swap(OuterTemplateContext);
3310
0
}
3311
3312
void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
3313
0
                                         Qualifiers Quals, SourceRange Range) {
3314
0
  QualType PointeeType = T->getPointeeType();
3315
0
  manglePointerCVQualifiers(Quals);
3316
0
  manglePointerExtQualifiers(Quals, PointeeType);
3317
3318
0
  Out << "_E";
3319
3320
0
  mangleFunctionType(PointeeType->castAs<FunctionProtoType>());
3321
0
}
3322
3323
void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *,
3324
0
                                         Qualifiers, SourceRange) {
3325
0
  llvm_unreachable("Cannot mangle injected class name type.");
3326
0
}
3327
3328
void MicrosoftCXXNameMangler::mangleType(const TemplateSpecializationType *T,
3329
0
                                         Qualifiers, SourceRange Range) {
3330
0
  DiagnosticsEngine &Diags = Context.getDiags();
3331
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3332
0
    "cannot mangle this template specialization type yet");
3333
0
  Diags.Report(Range.getBegin(), DiagID)
3334
0
    << Range;
3335
0
}
3336
3337
void MicrosoftCXXNameMangler::mangleType(const DependentNameType *T, Qualifiers,
3338
0
                                         SourceRange Range) {
3339
0
  DiagnosticsEngine &Diags = Context.getDiags();
3340
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3341
0
    "cannot mangle this dependent name type yet");
3342
0
  Diags.Report(Range.getBegin(), DiagID)
3343
0
    << Range;
3344
0
}
3345
3346
void MicrosoftCXXNameMangler::mangleType(
3347
    const DependentTemplateSpecializationType *T, Qualifiers,
3348
0
    SourceRange Range) {
3349
0
  DiagnosticsEngine &Diags = Context.getDiags();
3350
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3351
0
    "cannot mangle this dependent template specialization type yet");
3352
0
  Diags.Report(Range.getBegin(), DiagID)
3353
0
    << Range;
3354
0
}
3355
3356
void MicrosoftCXXNameMangler::mangleType(const PackExpansionType *T, Qualifiers,
3357
0
                                         SourceRange Range) {
3358
0
  DiagnosticsEngine &Diags = Context.getDiags();
3359
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3360
0
    "cannot mangle this pack expansion yet");
3361
0
  Diags.Report(Range.getBegin(), DiagID)
3362
0
    << Range;
3363
0
}
3364
3365
void MicrosoftCXXNameMangler::mangleType(const TypeOfType *T, Qualifiers,
3366
0
                                         SourceRange Range) {
3367
0
  DiagnosticsEngine &Diags = Context.getDiags();
3368
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3369
0
    "cannot mangle this typeof(type) yet");
3370
0
  Diags.Report(Range.getBegin(), DiagID)
3371
0
    << Range;
3372
0
}
3373
3374
void MicrosoftCXXNameMangler::mangleType(const TypeOfExprType *T, Qualifiers,
3375
0
                                         SourceRange Range) {
3376
0
  DiagnosticsEngine &Diags = Context.getDiags();
3377
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3378
0
    "cannot mangle this typeof(expression) yet");
3379
0
  Diags.Report(Range.getBegin(), DiagID)
3380
0
    << Range;
3381
0
}
3382
3383
void MicrosoftCXXNameMangler::mangleType(const DecltypeType *T, Qualifiers,
3384
0
                                         SourceRange Range) {
3385
0
  DiagnosticsEngine &Diags = Context.getDiags();
3386
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3387
0
    "cannot mangle this decltype() yet");
3388
0
  Diags.Report(Range.getBegin(), DiagID)
3389
0
    << Range;
3390
0
}
3391
3392
void MicrosoftCXXNameMangler::mangleType(const UnaryTransformType *T,
3393
0
                                         Qualifiers, SourceRange Range) {
3394
0
  DiagnosticsEngine &Diags = Context.getDiags();
3395
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3396
0
    "cannot mangle this unary transform type yet");
3397
0
  Diags.Report(Range.getBegin(), DiagID)
3398
0
    << Range;
3399
0
}
3400
3401
void MicrosoftCXXNameMangler::mangleType(const AutoType *T, Qualifiers,
3402
0
                                         SourceRange Range) {
3403
0
  assert(T->getDeducedType().isNull() && "expecting a dependent type!");
3404
3405
0
  DiagnosticsEngine &Diags = Context.getDiags();
3406
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3407
0
    "cannot mangle this 'auto' type yet");
3408
0
  Diags.Report(Range.getBegin(), DiagID)
3409
0
    << Range;
3410
0
}
3411
3412
void MicrosoftCXXNameMangler::mangleType(
3413
0
    const DeducedTemplateSpecializationType *T, Qualifiers, SourceRange Range) {
3414
0
  assert(T->getDeducedType().isNull() && "expecting a dependent type!");
3415
3416
0
  DiagnosticsEngine &Diags = Context.getDiags();
3417
0
  unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
3418
0
    "cannot mangle this deduced class template specialization type yet");
3419
0
  Diags.Report(Range.getBegin(), DiagID)
3420
0
    << Range;
3421
0
}
3422
3423
void MicrosoftCXXNameMangler::mangleType(const AtomicType *T, Qualifiers,
3424
0
                                         SourceRange Range) {
3425
0
  QualType ValueType = T->getValueType();
3426
3427
0
  llvm::SmallString<64> TemplateMangling;
3428
0
  llvm::raw_svector_ostream Stream(TemplateMangling);
3429
0
  MicrosoftCXXNameMangler Extra(Context, Stream);
3430
0
  Stream << "?$";
3431
0
  Extra.mangleSourceName("_Atomic");
3432
0
  Extra.mangleType(ValueType, Range, QMM_Escape);
3433
3434
0
  mangleArtificialTagType(TagTypeKind::Struct, TemplateMangling, {"__clang"});
3435
0
}
3436
3437
void MicrosoftCXXNameMangler::mangleType(const PipeType *T, Qualifiers,
3438
0
                                         SourceRange Range) {
3439
0
  QualType ElementType = T->getElementType();
3440
3441
0
  llvm::SmallString<64> TemplateMangling;
3442
0
  llvm::raw_svector_ostream Stream(TemplateMangling);
3443
0
  MicrosoftCXXNameMangler Extra(Context, Stream);
3444
0
  Stream << "?$";
3445
0
  Extra.mangleSourceName("ocl_pipe");
3446
0
  Extra.mangleType(ElementType, Range, QMM_Escape);
3447
0
  Extra.mangleIntegerLiteral(llvm::APSInt::get(T->isReadOnly()));
3448
3449
0
  mangleArtificialTagType(TagTypeKind::Struct, TemplateMangling, {"__clang"});
3450
0
}
3451
3452
void MicrosoftMangleContextImpl::mangleCXXName(GlobalDecl GD,
3453
0
                                               raw_ostream &Out) {
3454
0
  const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
3455
0
  PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
3456
0
                                 getASTContext().getSourceManager(),
3457
0
                                 "Mangling declaration");
3458
3459
0
  msvc_hashing_ostream MHO(Out);
3460
3461
0
  if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
3462
0
    auto Type = GD.getCtorType();
3463
0
    MicrosoftCXXNameMangler mangler(*this, MHO, CD, Type);
3464
0
    return mangler.mangle(GD);
3465
0
  }
3466
3467
0
  if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
3468
0
    auto Type = GD.getDtorType();
3469
0
    MicrosoftCXXNameMangler mangler(*this, MHO, DD, Type);
3470
0
    return mangler.mangle(GD);
3471
0
  }
3472
3473
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3474
0
  return Mangler.mangle(GD);
3475
0
}
3476
3477
void MicrosoftCXXNameMangler::mangleType(const BitIntType *T, Qualifiers,
3478
0
                                         SourceRange Range) {
3479
0
  llvm::SmallString<64> TemplateMangling;
3480
0
  llvm::raw_svector_ostream Stream(TemplateMangling);
3481
0
  MicrosoftCXXNameMangler Extra(Context, Stream);
3482
0
  Stream << "?$";
3483
0
  if (T->isUnsigned())
3484
0
    Extra.mangleSourceName("_UBitInt");
3485
0
  else
3486
0
    Extra.mangleSourceName("_BitInt");
3487
0
  Extra.mangleIntegerLiteral(llvm::APSInt::getUnsigned(T->getNumBits()));
3488
3489
0
  mangleArtificialTagType(TagTypeKind::Struct, TemplateMangling, {"__clang"});
3490
0
}
3491
3492
void MicrosoftCXXNameMangler::mangleType(const DependentBitIntType *T,
3493
0
                                         Qualifiers, SourceRange Range) {
3494
0
  DiagnosticsEngine &Diags = Context.getDiags();
3495
0
  unsigned DiagID = Diags.getCustomDiagID(
3496
0
      DiagnosticsEngine::Error, "cannot mangle this DependentBitInt type yet");
3497
0
  Diags.Report(Range.getBegin(), DiagID) << Range;
3498
0
}
3499
3500
// <this-adjustment> ::= <no-adjustment> | <static-adjustment> |
3501
//                       <virtual-adjustment>
3502
// <no-adjustment>      ::= A # private near
3503
//                      ::= B # private far
3504
//                      ::= I # protected near
3505
//                      ::= J # protected far
3506
//                      ::= Q # public near
3507
//                      ::= R # public far
3508
// <static-adjustment>  ::= G <static-offset> # private near
3509
//                      ::= H <static-offset> # private far
3510
//                      ::= O <static-offset> # protected near
3511
//                      ::= P <static-offset> # protected far
3512
//                      ::= W <static-offset> # public near
3513
//                      ::= X <static-offset> # public far
3514
// <virtual-adjustment> ::= $0 <virtual-shift> <static-offset> # private near
3515
//                      ::= $1 <virtual-shift> <static-offset> # private far
3516
//                      ::= $2 <virtual-shift> <static-offset> # protected near
3517
//                      ::= $3 <virtual-shift> <static-offset> # protected far
3518
//                      ::= $4 <virtual-shift> <static-offset> # public near
3519
//                      ::= $5 <virtual-shift> <static-offset> # public far
3520
// <virtual-shift>      ::= <vtordisp-shift> | <vtordispex-shift>
3521
// <vtordisp-shift>     ::= <offset-to-vtordisp>
3522
// <vtordispex-shift>   ::= <offset-to-vbptr> <vbase-offset-offset>
3523
//                          <offset-to-vtordisp>
3524
static void mangleThunkThisAdjustment(AccessSpecifier AS,
3525
                                      const ThisAdjustment &Adjustment,
3526
                                      MicrosoftCXXNameMangler &Mangler,
3527
0
                                      raw_ostream &Out) {
3528
0
  if (!Adjustment.Virtual.isEmpty()) {
3529
0
    Out << '$';
3530
0
    char AccessSpec;
3531
0
    switch (AS) {
3532
0
    case AS_none:
3533
0
      llvm_unreachable("Unsupported access specifier");
3534
0
    case AS_private:
3535
0
      AccessSpec = '0';
3536
0
      break;
3537
0
    case AS_protected:
3538
0
      AccessSpec = '2';
3539
0
      break;
3540
0
    case AS_public:
3541
0
      AccessSpec = '4';
3542
0
    }
3543
0
    if (Adjustment.Virtual.Microsoft.VBPtrOffset) {
3544
0
      Out << 'R' << AccessSpec;
3545
0
      Mangler.mangleNumber(
3546
0
          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBPtrOffset));
3547
0
      Mangler.mangleNumber(
3548
0
          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VBOffsetOffset));
3549
0
      Mangler.mangleNumber(
3550
0
          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
3551
0
      Mangler.mangleNumber(static_cast<uint32_t>(Adjustment.NonVirtual));
3552
0
    } else {
3553
0
      Out << AccessSpec;
3554
0
      Mangler.mangleNumber(
3555
0
          static_cast<uint32_t>(Adjustment.Virtual.Microsoft.VtordispOffset));
3556
0
      Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
3557
0
    }
3558
0
  } else if (Adjustment.NonVirtual != 0) {
3559
0
    switch (AS) {
3560
0
    case AS_none:
3561
0
      llvm_unreachable("Unsupported access specifier");
3562
0
    case AS_private:
3563
0
      Out << 'G';
3564
0
      break;
3565
0
    case AS_protected:
3566
0
      Out << 'O';
3567
0
      break;
3568
0
    case AS_public:
3569
0
      Out << 'W';
3570
0
    }
3571
0
    Mangler.mangleNumber(-static_cast<uint32_t>(Adjustment.NonVirtual));
3572
0
  } else {
3573
0
    switch (AS) {
3574
0
    case AS_none:
3575
0
      llvm_unreachable("Unsupported access specifier");
3576
0
    case AS_private:
3577
0
      Out << 'A';
3578
0
      break;
3579
0
    case AS_protected:
3580
0
      Out << 'I';
3581
0
      break;
3582
0
    case AS_public:
3583
0
      Out << 'Q';
3584
0
    }
3585
0
  }
3586
0
}
3587
3588
void MicrosoftMangleContextImpl::mangleVirtualMemPtrThunk(
3589
    const CXXMethodDecl *MD, const MethodVFTableLocation &ML,
3590
0
    raw_ostream &Out) {
3591
0
  msvc_hashing_ostream MHO(Out);
3592
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3593
0
  Mangler.getStream() << '?';
3594
0
  Mangler.mangleVirtualMemPtrThunk(MD, ML);
3595
0
}
3596
3597
void MicrosoftMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
3598
                                             const ThunkInfo &Thunk,
3599
0
                                             raw_ostream &Out) {
3600
0
  msvc_hashing_ostream MHO(Out);
3601
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3602
0
  Mangler.getStream() << '?';
3603
0
  Mangler.mangleName(MD);
3604
3605
  // Usually the thunk uses the access specifier of the new method, but if this
3606
  // is a covariant return thunk, then MSVC always uses the public access
3607
  // specifier, and we do the same.
3608
0
  AccessSpecifier AS = Thunk.Return.isEmpty() ? MD->getAccess() : AS_public;
3609
0
  mangleThunkThisAdjustment(AS, Thunk.This, Mangler, MHO);
3610
3611
0
  if (!Thunk.Return.isEmpty())
3612
0
    assert(Thunk.Method != nullptr &&
3613
0
           "Thunk info should hold the overridee decl");
3614
3615
0
  const CXXMethodDecl *DeclForFPT = Thunk.Method ? Thunk.Method : MD;
3616
0
  Mangler.mangleFunctionType(
3617
0
      DeclForFPT->getType()->castAs<FunctionProtoType>(), MD);
3618
0
}
3619
3620
void MicrosoftMangleContextImpl::mangleCXXDtorThunk(
3621
    const CXXDestructorDecl *DD, CXXDtorType Type,
3622
0
    const ThisAdjustment &Adjustment, raw_ostream &Out) {
3623
  // FIXME: Actually, the dtor thunk should be emitted for vector deleting
3624
  // dtors rather than scalar deleting dtors. Just use the vector deleting dtor
3625
  // mangling manually until we support both deleting dtor types.
3626
0
  assert(Type == Dtor_Deleting);
3627
0
  msvc_hashing_ostream MHO(Out);
3628
0
  MicrosoftCXXNameMangler Mangler(*this, MHO, DD, Type);
3629
0
  Mangler.getStream() << "??_E";
3630
0
  Mangler.mangleName(DD->getParent());
3631
0
  mangleThunkThisAdjustment(DD->getAccess(), Adjustment, Mangler, MHO);
3632
0
  Mangler.mangleFunctionType(DD->getType()->castAs<FunctionProtoType>(), DD);
3633
0
}
3634
3635
void MicrosoftMangleContextImpl::mangleCXXVFTable(
3636
    const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3637
0
    raw_ostream &Out) {
3638
  // <mangled-name> ::= ?_7 <class-name> <storage-class>
3639
  //                    <cvr-qualifiers> [<name>] @
3640
  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3641
  // is always '6' for vftables.
3642
0
  msvc_hashing_ostream MHO(Out);
3643
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3644
0
  if (Derived->hasAttr<DLLImportAttr>())
3645
0
    Mangler.getStream() << "??_S";
3646
0
  else
3647
0
    Mangler.getStream() << "??_7";
3648
0
  Mangler.mangleName(Derived);
3649
0
  Mangler.getStream() << "6B"; // '6' for vftable, 'B' for const.
3650
0
  for (const CXXRecordDecl *RD : BasePath)
3651
0
    Mangler.mangleName(RD);
3652
0
  Mangler.getStream() << '@';
3653
0
}
3654
3655
void MicrosoftMangleContextImpl::mangleCXXVBTable(
3656
    const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3657
0
    raw_ostream &Out) {
3658
  // <mangled-name> ::= ?_8 <class-name> <storage-class>
3659
  //                    <cvr-qualifiers> [<name>] @
3660
  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3661
  // is always '7' for vbtables.
3662
0
  msvc_hashing_ostream MHO(Out);
3663
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3664
0
  Mangler.getStream() << "??_8";
3665
0
  Mangler.mangleName(Derived);
3666
0
  Mangler.getStream() << "7B";  // '7' for vbtable, 'B' for const.
3667
0
  for (const CXXRecordDecl *RD : BasePath)
3668
0
    Mangler.mangleName(RD);
3669
0
  Mangler.getStream() << '@';
3670
0
}
3671
3672
0
void MicrosoftMangleContextImpl::mangleCXXRTTI(QualType T, raw_ostream &Out) {
3673
0
  msvc_hashing_ostream MHO(Out);
3674
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3675
0
  Mangler.getStream() << "??_R0";
3676
0
  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3677
0
  Mangler.getStream() << "@8";
3678
0
}
3679
3680
void MicrosoftMangleContextImpl::mangleCXXRTTIName(
3681
0
    QualType T, raw_ostream &Out, bool NormalizeIntegers = false) {
3682
0
  MicrosoftCXXNameMangler Mangler(*this, Out);
3683
0
  Mangler.getStream() << '.';
3684
0
  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3685
0
}
3686
3687
void MicrosoftMangleContextImpl::mangleCXXVirtualDisplacementMap(
3688
0
    const CXXRecordDecl *SrcRD, const CXXRecordDecl *DstRD, raw_ostream &Out) {
3689
0
  msvc_hashing_ostream MHO(Out);
3690
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3691
0
  Mangler.getStream() << "??_K";
3692
0
  Mangler.mangleName(SrcRD);
3693
0
  Mangler.getStream() << "$C";
3694
0
  Mangler.mangleName(DstRD);
3695
0
}
3696
3697
void MicrosoftMangleContextImpl::mangleCXXThrowInfo(QualType T, bool IsConst,
3698
                                                    bool IsVolatile,
3699
                                                    bool IsUnaligned,
3700
                                                    uint32_t NumEntries,
3701
0
                                                    raw_ostream &Out) {
3702
0
  msvc_hashing_ostream MHO(Out);
3703
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3704
0
  Mangler.getStream() << "_TI";
3705
0
  if (IsConst)
3706
0
    Mangler.getStream() << 'C';
3707
0
  if (IsVolatile)
3708
0
    Mangler.getStream() << 'V';
3709
0
  if (IsUnaligned)
3710
0
    Mangler.getStream() << 'U';
3711
0
  Mangler.getStream() << NumEntries;
3712
0
  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3713
0
}
3714
3715
void MicrosoftMangleContextImpl::mangleCXXCatchableTypeArray(
3716
0
    QualType T, uint32_t NumEntries, raw_ostream &Out) {
3717
0
  msvc_hashing_ostream MHO(Out);
3718
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3719
0
  Mangler.getStream() << "_CTA";
3720
0
  Mangler.getStream() << NumEntries;
3721
0
  Mangler.mangleType(T, SourceRange(), MicrosoftCXXNameMangler::QMM_Result);
3722
0
}
3723
3724
void MicrosoftMangleContextImpl::mangleCXXCatchableType(
3725
    QualType T, const CXXConstructorDecl *CD, CXXCtorType CT, uint32_t Size,
3726
    uint32_t NVOffset, int32_t VBPtrOffset, uint32_t VBIndex,
3727
0
    raw_ostream &Out) {
3728
0
  MicrosoftCXXNameMangler Mangler(*this, Out);
3729
0
  Mangler.getStream() << "_CT";
3730
3731
0
  llvm::SmallString<64> RTTIMangling;
3732
0
  {
3733
0
    llvm::raw_svector_ostream Stream(RTTIMangling);
3734
0
    msvc_hashing_ostream MHO(Stream);
3735
0
    mangleCXXRTTI(T, MHO);
3736
0
  }
3737
0
  Mangler.getStream() << RTTIMangling;
3738
3739
  // VS2015 and VS2017.1 omit the copy-constructor in the mangled name but
3740
  // both older and newer versions include it.
3741
  // FIXME: It is known that the Ctor is present in 2013, and in 2017.7
3742
  // (_MSC_VER 1914) and newer, and that it's omitted in 2015 and 2017.4
3743
  // (_MSC_VER 1911), but it's unknown when exactly it reappeared (1914?
3744
  // Or 1912, 1913 already?).
3745
0
  bool OmitCopyCtor = getASTContext().getLangOpts().isCompatibleWithMSVC(
3746
0
                          LangOptions::MSVC2015) &&
3747
0
                      !getASTContext().getLangOpts().isCompatibleWithMSVC(
3748
0
                          LangOptions::MSVC2017_7);
3749
0
  llvm::SmallString<64> CopyCtorMangling;
3750
0
  if (!OmitCopyCtor && CD) {
3751
0
    llvm::raw_svector_ostream Stream(CopyCtorMangling);
3752
0
    msvc_hashing_ostream MHO(Stream);
3753
0
    mangleCXXName(GlobalDecl(CD, CT), MHO);
3754
0
  }
3755
0
  Mangler.getStream() << CopyCtorMangling;
3756
3757
0
  Mangler.getStream() << Size;
3758
0
  if (VBPtrOffset == -1) {
3759
0
    if (NVOffset) {
3760
0
      Mangler.getStream() << NVOffset;
3761
0
    }
3762
0
  } else {
3763
0
    Mangler.getStream() << NVOffset;
3764
0
    Mangler.getStream() << VBPtrOffset;
3765
0
    Mangler.getStream() << VBIndex;
3766
0
  }
3767
0
}
3768
3769
void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassDescriptor(
3770
    const CXXRecordDecl *Derived, uint32_t NVOffset, int32_t VBPtrOffset,
3771
0
    uint32_t VBTableOffset, uint32_t Flags, raw_ostream &Out) {
3772
0
  msvc_hashing_ostream MHO(Out);
3773
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3774
0
  Mangler.getStream() << "??_R1";
3775
0
  Mangler.mangleNumber(NVOffset);
3776
0
  Mangler.mangleNumber(VBPtrOffset);
3777
0
  Mangler.mangleNumber(VBTableOffset);
3778
0
  Mangler.mangleNumber(Flags);
3779
0
  Mangler.mangleName(Derived);
3780
0
  Mangler.getStream() << "8";
3781
0
}
3782
3783
void MicrosoftMangleContextImpl::mangleCXXRTTIBaseClassArray(
3784
0
    const CXXRecordDecl *Derived, raw_ostream &Out) {
3785
0
  msvc_hashing_ostream MHO(Out);
3786
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3787
0
  Mangler.getStream() << "??_R2";
3788
0
  Mangler.mangleName(Derived);
3789
0
  Mangler.getStream() << "8";
3790
0
}
3791
3792
void MicrosoftMangleContextImpl::mangleCXXRTTIClassHierarchyDescriptor(
3793
0
    const CXXRecordDecl *Derived, raw_ostream &Out) {
3794
0
  msvc_hashing_ostream MHO(Out);
3795
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3796
0
  Mangler.getStream() << "??_R3";
3797
0
  Mangler.mangleName(Derived);
3798
0
  Mangler.getStream() << "8";
3799
0
}
3800
3801
void MicrosoftMangleContextImpl::mangleCXXRTTICompleteObjectLocator(
3802
    const CXXRecordDecl *Derived, ArrayRef<const CXXRecordDecl *> BasePath,
3803
0
    raw_ostream &Out) {
3804
  // <mangled-name> ::= ?_R4 <class-name> <storage-class>
3805
  //                    <cvr-qualifiers> [<name>] @
3806
  // NOTE: <cvr-qualifiers> here is always 'B' (const). <storage-class>
3807
  // is always '6' for vftables.
3808
0
  llvm::SmallString<64> VFTableMangling;
3809
0
  llvm::raw_svector_ostream Stream(VFTableMangling);
3810
0
  mangleCXXVFTable(Derived, BasePath, Stream);
3811
3812
0
  if (VFTableMangling.starts_with("??@")) {
3813
0
    assert(VFTableMangling.ends_with("@"));
3814
0
    Out << VFTableMangling << "??_R4@";
3815
0
    return;
3816
0
  }
3817
3818
0
  assert(VFTableMangling.starts_with("??_7") ||
3819
0
         VFTableMangling.starts_with("??_S"));
3820
3821
0
  Out << "??_R4" << VFTableMangling.str().drop_front(4);
3822
0
}
3823
3824
void MicrosoftMangleContextImpl::mangleSEHFilterExpression(
3825
0
    GlobalDecl EnclosingDecl, raw_ostream &Out) {
3826
0
  msvc_hashing_ostream MHO(Out);
3827
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3828
  // The function body is in the same comdat as the function with the handler,
3829
  // so the numbering here doesn't have to be the same across TUs.
3830
  //
3831
  // <mangled-name> ::= ?filt$ <filter-number> @0
3832
0
  Mangler.getStream() << "?filt$" << SEHFilterIds[EnclosingDecl]++ << "@0@";
3833
0
  Mangler.mangleName(EnclosingDecl);
3834
0
}
3835
3836
void MicrosoftMangleContextImpl::mangleSEHFinallyBlock(
3837
0
    GlobalDecl EnclosingDecl, raw_ostream &Out) {
3838
0
  msvc_hashing_ostream MHO(Out);
3839
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3840
  // The function body is in the same comdat as the function with the handler,
3841
  // so the numbering here doesn't have to be the same across TUs.
3842
  //
3843
  // <mangled-name> ::= ?fin$ <filter-number> @0
3844
0
  Mangler.getStream() << "?fin$" << SEHFinallyIds[EnclosingDecl]++ << "@0@";
3845
0
  Mangler.mangleName(EnclosingDecl);
3846
0
}
3847
3848
void MicrosoftMangleContextImpl::mangleCanonicalTypeName(
3849
0
    QualType T, raw_ostream &Out, bool NormalizeIntegers = false) {
3850
  // This is just a made up unique string for the purposes of tbaa.  undname
3851
  // does *not* know how to demangle it.
3852
0
  MicrosoftCXXNameMangler Mangler(*this, Out);
3853
0
  Mangler.getStream() << '?';
3854
0
  Mangler.mangleType(T.getCanonicalType(), SourceRange());
3855
0
}
3856
3857
void MicrosoftMangleContextImpl::mangleReferenceTemporary(
3858
0
    const VarDecl *VD, unsigned ManglingNumber, raw_ostream &Out) {
3859
0
  msvc_hashing_ostream MHO(Out);
3860
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3861
3862
0
  Mangler.getStream() << "?$RT" << ManglingNumber << '@';
3863
0
  Mangler.mangle(VD, "");
3864
0
}
3865
3866
void MicrosoftMangleContextImpl::mangleThreadSafeStaticGuardVariable(
3867
0
    const VarDecl *VD, unsigned GuardNum, raw_ostream &Out) {
3868
0
  msvc_hashing_ostream MHO(Out);
3869
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3870
3871
0
  Mangler.getStream() << "?$TSS" << GuardNum << '@';
3872
0
  Mangler.mangleNestedName(VD);
3873
0
  Mangler.getStream() << "@4HA";
3874
0
}
3875
3876
void MicrosoftMangleContextImpl::mangleStaticGuardVariable(const VarDecl *VD,
3877
0
                                                           raw_ostream &Out) {
3878
  // <guard-name> ::= ?_B <postfix> @5 <scope-depth>
3879
  //              ::= ?__J <postfix> @5 <scope-depth>
3880
  //              ::= ?$S <guard-num> @ <postfix> @4IA
3881
3882
  // The first mangling is what MSVC uses to guard static locals in inline
3883
  // functions.  It uses a different mangling in external functions to support
3884
  // guarding more than 32 variables.  MSVC rejects inline functions with more
3885
  // than 32 static locals.  We don't fully implement the second mangling
3886
  // because those guards are not externally visible, and instead use LLVM's
3887
  // default renaming when creating a new guard variable.
3888
0
  msvc_hashing_ostream MHO(Out);
3889
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3890
3891
0
  bool Visible = VD->isExternallyVisible();
3892
0
  if (Visible) {
3893
0
    Mangler.getStream() << (VD->getTLSKind() ? "??__J" : "??_B");
3894
0
  } else {
3895
0
    Mangler.getStream() << "?$S1@";
3896
0
  }
3897
0
  unsigned ScopeDepth = 0;
3898
0
  if (Visible && !getNextDiscriminator(VD, ScopeDepth))
3899
    // If we do not have a discriminator and are emitting a guard variable for
3900
    // use at global scope, then mangling the nested name will not be enough to
3901
    // remove ambiguities.
3902
0
    Mangler.mangle(VD, "");
3903
0
  else
3904
0
    Mangler.mangleNestedName(VD);
3905
0
  Mangler.getStream() << (Visible ? "@5" : "@4IA");
3906
0
  if (ScopeDepth)
3907
0
    Mangler.mangleNumber(ScopeDepth);
3908
0
}
3909
3910
void MicrosoftMangleContextImpl::mangleInitFiniStub(const VarDecl *D,
3911
                                                    char CharCode,
3912
0
                                                    raw_ostream &Out) {
3913
0
  msvc_hashing_ostream MHO(Out);
3914
0
  MicrosoftCXXNameMangler Mangler(*this, MHO);
3915
0
  Mangler.getStream() << "??__" << CharCode;
3916
0
  if (D->isStaticDataMember()) {
3917
0
    Mangler.getStream() << '?';
3918
0
    Mangler.mangleName(D);
3919
0
    Mangler.mangleVariableEncoding(D);
3920
0
    Mangler.getStream() << "@@";
3921
0
  } else {
3922
0
    Mangler.mangleName(D);
3923
0
  }
3924
  // This is the function class mangling.  These stubs are global, non-variadic,
3925
  // cdecl functions that return void and take no args.
3926
0
  Mangler.getStream() << "YAXXZ";
3927
0
}
3928
3929
void MicrosoftMangleContextImpl::mangleDynamicInitializer(const VarDecl *D,
3930
0
                                                          raw_ostream &Out) {
3931
  // <initializer-name> ::= ?__E <name> YAXXZ
3932
0
  mangleInitFiniStub(D, 'E', Out);
3933
0
}
3934
3935
void
3936
MicrosoftMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
3937
0
                                                          raw_ostream &Out) {
3938
  // <destructor-name> ::= ?__F <name> YAXXZ
3939
0
  mangleInitFiniStub(D, 'F', Out);
3940
0
}
3941
3942
void MicrosoftMangleContextImpl::mangleStringLiteral(const StringLiteral *SL,
3943
0
                                                     raw_ostream &Out) {
3944
  // <char-type> ::= 0   # char, char16_t, char32_t
3945
  //                     # (little endian char data in mangling)
3946
  //             ::= 1   # wchar_t (big endian char data in mangling)
3947
  //
3948
  // <literal-length> ::= <non-negative integer>  # the length of the literal
3949
  //
3950
  // <encoded-crc>    ::= <hex digit>+ @          # crc of the literal including
3951
  //                                              # trailing null bytes
3952
  //
3953
  // <encoded-string> ::= <simple character>           # uninteresting character
3954
  //                  ::= '?$' <hex digit> <hex digit> # these two nibbles
3955
  //                                                   # encode the byte for the
3956
  //                                                   # character
3957
  //                  ::= '?' [a-z]                    # \xe1 - \xfa
3958
  //                  ::= '?' [A-Z]                    # \xc1 - \xda
3959
  //                  ::= '?' [0-9]                    # [,/\:. \n\t'-]
3960
  //
3961
  // <literal> ::= '??_C@_' <char-type> <literal-length> <encoded-crc>
3962
  //               <encoded-string> '@'
3963
0
  MicrosoftCXXNameMangler Mangler(*this, Out);
3964
0
  Mangler.getStream() << "??_C@_";
3965
3966
  // The actual string length might be different from that of the string literal
3967
  // in cases like:
3968
  // char foo[3] = "foobar";
3969
  // char bar[42] = "foobar";
3970
  // Where it is truncated or zero-padded to fit the array. This is the length
3971
  // used for mangling, and any trailing null-bytes also need to be mangled.
3972
0
  unsigned StringLength = getASTContext()
3973
0
                              .getAsConstantArrayType(SL->getType())
3974
0
                              ->getSize()
3975
0
                              .getZExtValue();
3976
0
  unsigned StringByteLength = StringLength * SL->getCharByteWidth();
3977
3978
  // <char-type>: The "kind" of string literal is encoded into the mangled name.
3979
0
  if (SL->isWide())
3980
0
    Mangler.getStream() << '1';
3981
0
  else
3982
0
    Mangler.getStream() << '0';
3983
3984
  // <literal-length>: The next part of the mangled name consists of the length
3985
  // of the string in bytes.
3986
0
  Mangler.mangleNumber(StringByteLength);
3987
3988
0
  auto GetLittleEndianByte = [&SL](unsigned Index) {
3989
0
    unsigned CharByteWidth = SL->getCharByteWidth();
3990
0
    if (Index / CharByteWidth >= SL->getLength())
3991
0
      return static_cast<char>(0);
3992
0
    uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
3993
0
    unsigned OffsetInCodeUnit = Index % CharByteWidth;
3994
0
    return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
3995
0
  };
3996
3997
0
  auto GetBigEndianByte = [&SL](unsigned Index) {
3998
0
    unsigned CharByteWidth = SL->getCharByteWidth();
3999
0
    if (Index / CharByteWidth >= SL->getLength())
4000
0
      return static_cast<char>(0);
4001
0
    uint32_t CodeUnit = SL->getCodeUnit(Index / CharByteWidth);
4002
0
    unsigned OffsetInCodeUnit = (CharByteWidth - 1) - (Index % CharByteWidth);
4003
0
    return static_cast<char>((CodeUnit >> (8 * OffsetInCodeUnit)) & 0xff);
4004
0
  };
4005
4006
  // CRC all the bytes of the StringLiteral.
4007
0
  llvm::JamCRC JC;
4008
0
  for (unsigned I = 0, E = StringByteLength; I != E; ++I)
4009
0
    JC.update(GetLittleEndianByte(I));
4010
4011
  // <encoded-crc>: The CRC is encoded utilizing the standard number mangling
4012
  // scheme.
4013
0
  Mangler.mangleNumber(JC.getCRC());
4014
4015
  // <encoded-string>: The mangled name also contains the first 32 bytes
4016
  // (including null-terminator bytes) of the encoded StringLiteral.
4017
  // Each character is encoded by splitting them into bytes and then encoding
4018
  // the constituent bytes.
4019
0
  auto MangleByte = [&Mangler](char Byte) {
4020
    // There are five different manglings for characters:
4021
    // - [a-zA-Z0-9_$]: A one-to-one mapping.
4022
    // - ?[a-z]: The range from \xe1 to \xfa.
4023
    // - ?[A-Z]: The range from \xc1 to \xda.
4024
    // - ?[0-9]: The set of [,/\:. \n\t'-].
4025
    // - ?$XX: A fallback which maps nibbles.
4026
0
    if (isAsciiIdentifierContinue(Byte, /*AllowDollar=*/true)) {
4027
0
      Mangler.getStream() << Byte;
4028
0
    } else if (isLetter(Byte & 0x7f)) {
4029
0
      Mangler.getStream() << '?' << static_cast<char>(Byte & 0x7f);
4030
0
    } else {
4031
0
      const char SpecialChars[] = {',', '/',  '\\', ':',  '.',
4032
0
                                   ' ', '\n', '\t', '\'', '-'};
4033
0
      const char *Pos = llvm::find(SpecialChars, Byte);
4034
0
      if (Pos != std::end(SpecialChars)) {
4035
0
        Mangler.getStream() << '?' << (Pos - std::begin(SpecialChars));
4036
0
      } else {
4037
0
        Mangler.getStream() << "?$";
4038
0
        Mangler.getStream() << static_cast<char>('A' + ((Byte >> 4) & 0xf));
4039
0
        Mangler.getStream() << static_cast<char>('A' + (Byte & 0xf));
4040
0
      }
4041
0
    }
4042
0
  };
4043
4044
  // Enforce our 32 bytes max, except wchar_t which gets 32 chars instead.
4045
0
  unsigned MaxBytesToMangle = SL->isWide() ? 64U : 32U;
4046
0
  unsigned NumBytesToMangle = std::min(MaxBytesToMangle, StringByteLength);
4047
0
  for (unsigned I = 0; I != NumBytesToMangle; ++I) {
4048
0
    if (SL->isWide())
4049
0
      MangleByte(GetBigEndianByte(I));
4050
0
    else
4051
0
      MangleByte(GetLittleEndianByte(I));
4052
0
  }
4053
4054
0
  Mangler.getStream() << '@';
4055
0
}
4056
4057
MicrosoftMangleContext *MicrosoftMangleContext::create(ASTContext &Context,
4058
                                                       DiagnosticsEngine &Diags,
4059
0
                                                       bool IsAux) {
4060
0
  return new MicrosoftMangleContextImpl(Context, Diags, IsAux);
4061
0
}