Coverage Report

Created: 2022-01-25 06:29

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