Bug Summary

File:src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/lib/AST/MicrosoftMangle.cpp
Warning:line 2765, column 7
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple amd64-unknown-openbsd7.0 -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name MicrosoftMangle.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -mrelocation-model static -mframe-pointer=all -relaxed-aliasing -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -fcoverage-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangAST/obj -resource-dir /usr/local/lib/clang/13.0.0 -I /usr/src/gnu/usr.bin/clang/libclangAST/obj/../include/clang/AST -I /usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/include -I /usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/llvm/include -I /usr/src/gnu/usr.bin/clang/libclangAST/../include -I /usr/src/gnu/usr.bin/clang/libclangAST/obj -I /usr/src/gnu/usr.bin/clang/libclangAST/obj/../include -D NDEBUG -D __STDC_LIMIT_MACROS -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D LLVM_PREFIX="/usr" -internal-isystem /usr/include/c++/v1 -internal-isystem /usr/local/lib/clang/13.0.0/include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/usr/src/gnu/usr.bin/clang/libclangAST/obj -ferror-limit 19 -fvisibility-inlines-hidden -fwrapv -stack-protector 2 -fno-rtti -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -fno-builtin-malloc -fno-builtin-calloc -fno-builtin-realloc -fno-builtin-valloc -fno-builtin-free -fno-builtin-strdup -fno-builtin-strndup -analyzer-output=html -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /home/ben/Projects/vmm/scan-build/2022-01-12-194120-40624-1 -x c++ /usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/lib/AST/MicrosoftMangle.cpp

/usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/lib/AST/MicrosoftMangle.cpp

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

/usr/src/gnu/usr.bin/clang/libclangAST/../../../llvm/clang/include/clang/Basic/LangOptions.h

1//===- LangOptions.h - C Language Family Language Options -------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9/// \file
10/// Defines the clang::LangOptions interface.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_BASIC_LANGOPTIONS_H
15#define LLVM_CLANG_BASIC_LANGOPTIONS_H
16
17#include "clang/Basic/CommentOptions.h"
18#include "clang/Basic/LLVM.h"
19#include "clang/Basic/LangStandard.h"
20#include "clang/Basic/ObjCRuntime.h"
21#include "clang/Basic/Sanitizers.h"
22#include "clang/Basic/TargetCXXABI.h"
23#include "clang/Basic/Visibility.h"
24#include "llvm/ADT/FloatingPointMode.h"
25#include "llvm/ADT/StringRef.h"
26#include "llvm/ADT/Triple.h"
27#include <string>
28#include <vector>
29
30namespace clang {
31
32/// Bitfields of LangOptions, split out from LangOptions in order to ensure that
33/// this large collection of bitfields is a trivial class type.
34class LangOptionsBase {
35 friend class CompilerInvocation;
36
37public:
38 // Define simple language options (with no accessors).
39#define LANGOPT(Name, Bits, Default, Description) unsigned Name : Bits;
40#define ENUM_LANGOPT(Name, Type, Bits, Default, Description)
41#include "clang/Basic/LangOptions.def"
42
43protected:
44 // Define language options of enumeration type. These are private, and will
45 // have accessors (below).
46#define LANGOPT(Name, Bits, Default, Description)
47#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
48 unsigned Name : Bits;
49#include "clang/Basic/LangOptions.def"
50};
51
52/// In the Microsoft ABI, this controls the placement of virtual displacement
53/// members used to implement virtual inheritance.
54enum class MSVtorDispMode { Never, ForVBaseOverride, ForVFTable };
55
56/// Keeps track of the various options that can be
57/// enabled, which controls the dialect of C or C++ that is accepted.
58class LangOptions : public LangOptionsBase {
59public:
60 using Visibility = clang::Visibility;
61 using RoundingMode = llvm::RoundingMode;
62
63 enum GCMode { NonGC, GCOnly, HybridGC };
64 enum StackProtectorMode { SSPOff, SSPOn, SSPStrong, SSPReq };
65
66 // Automatic variables live on the stack, and when trivial they're usually
67 // uninitialized because it's undefined behavior to use them without
68 // initializing them.
69 enum class TrivialAutoVarInitKind { Uninitialized, Zero, Pattern };
70
71 enum SignedOverflowBehaviorTy {
72 // Default C standard behavior.
73 SOB_Undefined,
74
75 // -fwrapv
76 SOB_Defined,
77
78 // -ftrapv
79 SOB_Trapping
80 };
81
82 // FIXME: Unify with TUKind.
83 enum CompilingModuleKind {
84 /// Not compiling a module interface at all.
85 CMK_None,
86
87 /// Compiling a module from a module map.
88 CMK_ModuleMap,
89
90 /// Compiling a module from a list of header files.
91 CMK_HeaderModule,
92
93 /// Compiling a C++ modules TS module interface unit.
94 CMK_ModuleInterface,
95 };
96
97 enum PragmaMSPointersToMembersKind {
98 PPTMK_BestCase,
99 PPTMK_FullGeneralitySingleInheritance,
100 PPTMK_FullGeneralityMultipleInheritance,
101 PPTMK_FullGeneralityVirtualInheritance
102 };
103
104 using MSVtorDispMode = clang::MSVtorDispMode;
105
106 enum DefaultCallingConvention {
107 DCC_None,
108 DCC_CDecl,
109 DCC_FastCall,
110 DCC_StdCall,
111 DCC_VectorCall,
112 DCC_RegCall
113 };
114
115 enum AddrSpaceMapMangling { ASMM_Target, ASMM_On, ASMM_Off };
116
117 // Corresponds to _MSC_VER
118 enum MSVCMajorVersion {
119 MSVC2010 = 1600,
120 MSVC2012 = 1700,
121 MSVC2013 = 1800,
122 MSVC2015 = 1900,
123 MSVC2017 = 1910,
124 MSVC2017_5 = 1912,
125 MSVC2017_7 = 1914,
126 MSVC2019 = 1920,
127 MSVC2019_8 = 1928,
128 };
129
130 enum SYCLMajorVersion {
131 SYCL_None,
132 SYCL_2017,
133 SYCL_2020,
134 // The "default" SYCL version to be used when none is specified on the
135 // frontend command line.
136 SYCL_Default = SYCL_2020
137 };
138
139 /// Clang versions with different platform ABI conformance.
140 enum class ClangABI {
141 /// Attempt to be ABI-compatible with code generated by Clang 3.8.x
142 /// (SVN r257626). This causes <1 x long long> to be passed in an
143 /// integer register instead of an SSE register on x64_64.
144 Ver3_8,
145
146 /// Attempt to be ABI-compatible with code generated by Clang 4.0.x
147 /// (SVN r291814). This causes move operations to be ignored when
148 /// determining whether a class type can be passed or returned directly.
149 Ver4,
150
151 /// Attempt to be ABI-compatible with code generated by Clang 6.0.x
152 /// (SVN r321711). This causes determination of whether a type is
153 /// standard-layout to ignore collisions between empty base classes
154 /// and between base classes and member subobjects, which affects
155 /// whether we reuse base class tail padding in some ABIs.
156 Ver6,
157
158 /// Attempt to be ABI-compatible with code generated by Clang 7.0.x
159 /// (SVN r338536). This causes alignof (C++) and _Alignof (C11) to be
160 /// compatible with __alignof (i.e., return the preferred alignment)
161 /// rather than returning the required alignment.
162 Ver7,
163
164 /// Attempt to be ABI-compatible with code generated by Clang 9.0.x
165 /// (SVN r351319). This causes vectors of __int128 to be passed in memory
166 /// instead of passing in multiple scalar registers on x86_64 on Linux and
167 /// NetBSD.
168 Ver9,
169
170 /// Attempt to be ABI-compatible with code generated by Clang 11.0.x
171 /// (git 2e10b7a39b93). This causes clang to pass unions with a 256-bit
172 /// vector member on the stack instead of using registers, to not properly
173 /// mangle substitutions for template names in some cases, and to mangle
174 /// declaration template arguments without a cast to the parameter type
175 /// even when that can lead to mangling collisions.
176 Ver11,
177
178 /// Attempt to be ABI-compatible with code generated by Clang 12.0.x
179 /// (git 8e464dd76bef). This causes clang to mangle lambdas within
180 /// global-scope inline variables incorrectly.
181 Ver12,
182
183 /// Conform to the underlying platform's C and C++ ABIs as closely
184 /// as we can.
185 Latest
186 };
187
188 enum class CoreFoundationABI {
189 /// No interoperability ABI has been specified
190 Unspecified,
191 /// CoreFoundation does not have any language interoperability
192 Standalone,
193 /// Interoperability with the ObjectiveC runtime
194 ObjectiveC,
195 /// Interoperability with the latest known version of the Swift runtime
196 Swift,
197 /// Interoperability with the Swift 5.0 runtime
198 Swift5_0,
199 /// Interoperability with the Swift 4.2 runtime
200 Swift4_2,
201 /// Interoperability with the Swift 4.1 runtime
202 Swift4_1,
203 };
204
205 enum FPModeKind {
206 // Disable the floating point pragma
207 FPM_Off,
208
209 // Enable the floating point pragma
210 FPM_On,
211
212 // Aggressively fuse FP ops (E.g. FMA) disregarding pragmas.
213 FPM_Fast,
214
215 // Aggressively fuse FP ops and honor pragmas.
216 FPM_FastHonorPragmas
217 };
218
219 /// Alias for RoundingMode::NearestTiesToEven.
220 static constexpr unsigned FPR_ToNearest =
221 static_cast<unsigned>(llvm::RoundingMode::NearestTiesToEven);
222
223 /// Possible floating point exception behavior.
224 enum FPExceptionModeKind {
225 /// Assume that floating-point exceptions are masked.
226 FPE_Ignore,
227 /// Transformations do not cause new exceptions but may hide some.
228 FPE_MayTrap,
229 /// Strictly preserve the floating-point exception semantics.
230 FPE_Strict
231 };
232
233 /// Possible exception handling behavior.
234 enum class ExceptionHandlingKind { None, SjLj, WinEH, DwarfCFI, Wasm };
235
236 enum class LaxVectorConversionKind {
237 /// Permit no implicit vector bitcasts.
238 None,
239 /// Permit vector bitcasts between integer vectors with different numbers
240 /// of elements but the same total bit-width.
241 Integer,
242 /// Permit vector bitcasts between all vectors with the same total
243 /// bit-width.
244 All,
245 };
246
247 enum class AltivecSrcCompatKind {
248 // All vector compares produce scalars except vector pixel and vector bool.
249 // The types vector pixel and vector bool return vector results.
250 Mixed,
251 // All vector compares produce vector results as in GCC.
252 GCC,
253 // All vector compares produce scalars as in XL.
254 XL,
255 // Default clang behaviour.
256 Default = Mixed,
257 };
258
259 enum class SignReturnAddressScopeKind {
260 /// No signing for any function.
261 None,
262 /// Sign the return address of functions that spill LR.
263 NonLeaf,
264 /// Sign the return address of all functions,
265 All
266 };
267
268 enum class SignReturnAddressKeyKind {
269 /// Return address signing uses APIA key.
270 AKey,
271 /// Return address signing uses APIB key.
272 BKey
273 };
274
275 enum class ThreadModelKind {
276 /// POSIX Threads.
277 POSIX,
278 /// Single Threaded Environment.
279 Single
280 };
281
282 enum class ExtendArgsKind {
283 /// Integer arguments are sign or zero extended to 32/64 bits
284 /// during default argument promotions.
285 ExtendTo32,
286 ExtendTo64
287 };
288
289public:
290 /// The used language standard.
291 LangStandard::Kind LangStd;
292
293 /// Set of enabled sanitizers.
294 SanitizerSet Sanitize;
295 /// Is at least one coverage instrumentation type enabled.
296 bool SanitizeCoverage = false;
297
298 /// Paths to files specifying which objects
299 /// (files, functions, variables) should not be instrumented.
300 std::vector<std::string> NoSanitizeFiles;
301
302 /// Paths to the XRay "always instrument" files specifying which
303 /// objects (files, functions, variables) should be imbued with the XRay
304 /// "always instrument" attribute.
305 /// WARNING: This is a deprecated field and will go away in the future.
306 std::vector<std::string> XRayAlwaysInstrumentFiles;
307
308 /// Paths to the XRay "never instrument" files specifying which
309 /// objects (files, functions, variables) should be imbued with the XRay
310 /// "never instrument" attribute.
311 /// WARNING: This is a deprecated field and will go away in the future.
312 std::vector<std::string> XRayNeverInstrumentFiles;
313
314 /// Paths to the XRay attribute list files, specifying which objects
315 /// (files, functions, variables) should be imbued with the appropriate XRay
316 /// attribute(s).
317 std::vector<std::string> XRayAttrListFiles;
318
319 /// Paths to special case list files specifying which entities
320 /// (files, functions) should or should not be instrumented.
321 std::vector<std::string> ProfileListFiles;
322
323 clang::ObjCRuntime ObjCRuntime;
324
325 CoreFoundationABI CFRuntime = CoreFoundationABI::Unspecified;
326
327 std::string ObjCConstantStringClass;
328
329 /// The name of the handler function to be called when -ftrapv is
330 /// specified.
331 ///
332 /// If none is specified, abort (GCC-compatible behaviour).
333 std::string OverflowHandler;
334
335 /// The module currently being compiled as specified by -fmodule-name.
336 std::string ModuleName;
337
338 /// The name of the current module, of which the main source file
339 /// is a part. If CompilingModule is set, we are compiling the interface
340 /// of this module, otherwise we are compiling an implementation file of
341 /// it. This starts as ModuleName in case -fmodule-name is provided and
342 /// changes during compilation to reflect the current module.
343 std::string CurrentModule;
344
345 /// The names of any features to enable in module 'requires' decls
346 /// in addition to the hard-coded list in Module.cpp and the target features.
347 ///
348 /// This list is sorted.
349 std::vector<std::string> ModuleFeatures;
350
351 /// Options for parsing comments.
352 CommentOptions CommentOpts;
353
354 /// A list of all -fno-builtin-* function names (e.g., memset).
355 std::vector<std::string> NoBuiltinFuncs;
356
357 /// A prefix map for __FILE__, __BASE_FILE__ and __builtin_FILE().
358 std::map<std::string, std::string, std::greater<std::string>> MacroPrefixMap;
359
360 /// Triples of the OpenMP targets that the host code codegen should
361 /// take into account in order to generate accurate offloading descriptors.
362 std::vector<llvm::Triple> OMPTargetTriples;
363
364 /// Name of the IR file that contains the result of the OpenMP target
365 /// host code generation.
366 std::string OMPHostIRFile;
367
368 /// The user provided compilation unit ID, if non-empty. This is used to
369 /// externalize static variables which is needed to support accessing static
370 /// device variables in host code for single source offloading languages
371 /// like CUDA/HIP.
372 std::string CUID;
373
374 /// C++ ABI to compile with, if specified by the frontend through -fc++-abi=.
375 /// This overrides the default ABI used by the target.
376 llvm::Optional<TargetCXXABI::Kind> CXXABI;
377
378 /// Indicates whether the front-end is explicitly told that the
379 /// input is a header file (i.e. -x c-header).
380 bool IsHeaderFile = false;
381
382 LangOptions();
383
384 // Define accessors/mutators for language options of enumeration type.
385#define LANGOPT(Name, Bits, Default, Description)
386#define ENUM_LANGOPT(Name, Type, Bits, Default, Description) \
387 Type get##Name() const { return static_cast<Type>(Name); } \
388 void set##Name(Type Value) { Name = static_cast<unsigned>(Value); }
389#include "clang/Basic/LangOptions.def"
390
391 /// Are we compiling a module interface (.cppm or module map)?
392 bool isCompilingModule() const {
393 return getCompilingModule() != CMK_None;
394 }
395
396 /// Do we need to track the owning module for a local declaration?
397 bool trackLocalOwningModule() const {
398 return isCompilingModule() || ModulesLocalVisibility;
399 }
400
401 bool isSignedOverflowDefined() const {
402 return getSignedOverflowBehavior() == SOB_Defined;
403 }
404
405 bool isSubscriptPointerArithmetic() const {
406 return ObjCRuntime.isSubscriptPointerArithmetic() &&
407 !ObjCSubscriptingLegacyRuntime;
408 }
409
410 bool isCompatibleWithMSVC(MSVCMajorVersion MajorVersion) const {
411 return MSCompatibilityVersion >= MajorVersion * 100000U;
17
Assuming the condition is true
18
Returning the value 1, which participates in a condition later
412 }
413
414 /// Reset all of the options that are not considered when building a
415 /// module.
416 void resetNonModularOptions();
417
418 /// Is this a libc/libm function that is no longer recognized as a
419 /// builtin because a -fno-builtin-* option has been specified?
420 bool isNoBuiltinFunc(StringRef Name) const;
421
422 /// True if any ObjC types may have non-trivial lifetime qualifiers.
423 bool allowsNonTrivialObjCLifetimeQualifiers() const {
424 return ObjCAutoRefCount || ObjCWeak;
425 }
426
427 bool assumeFunctionsAreConvergent() const {
428 return ConvergentFunctions;
429 }
430
431 /// Return the OpenCL C or C++ version as a VersionTuple.
432 VersionTuple getOpenCLVersionTuple() const;
433
434 /// Check if return address signing is enabled.
435 bool hasSignReturnAddress() const {
436 return getSignReturnAddressScope() != SignReturnAddressScopeKind::None;
437 }
438
439 /// Check if return address signing uses AKey.
440 bool isSignReturnAddressWithAKey() const {
441 return getSignReturnAddressKey() == SignReturnAddressKeyKind::AKey;
442 }
443
444 /// Check if leaf functions are also signed.
445 bool isSignReturnAddressScopeAll() const {
446 return getSignReturnAddressScope() == SignReturnAddressScopeKind::All;
447 }
448
449 bool hasSjLjExceptions() const {
450 return getExceptionHandling() == ExceptionHandlingKind::SjLj;
451 }
452
453 bool hasSEHExceptions() const {
454 return getExceptionHandling() == ExceptionHandlingKind::WinEH;
455 }
456
457 bool hasDWARFExceptions() const {
458 return getExceptionHandling() == ExceptionHandlingKind::DwarfCFI;
459 }
460
461 bool hasWasmExceptions() const {
462 return getExceptionHandling() == ExceptionHandlingKind::Wasm;
463 }
464
465 bool isSYCL() const { return SYCLIsDevice || SYCLIsHost; }
466
467 /// Remap path prefix according to -fmacro-prefix-path option.
468 void remapPathPrefix(SmallString<256> &Path) const;
469};
470
471/// Floating point control options
472class FPOptionsOverride;
473class FPOptions {
474public:
475 // We start by defining the layout.
476 using storage_type = uint16_t;
477
478 using RoundingMode = llvm::RoundingMode;
479
480 static constexpr unsigned StorageBitSize = 8 * sizeof(storage_type);
481
482 // Define a fake option named "First" so that we have a PREVIOUS even for the
483 // real first option.
484 static constexpr storage_type FirstShift = 0, FirstWidth = 0;
485#define OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
486 static constexpr storage_type NAME##Shift = \
487 PREVIOUS##Shift + PREVIOUS##Width; \
488 static constexpr storage_type NAME##Width = WIDTH; \
489 static constexpr storage_type NAME##Mask = ((1 << NAME##Width) - 1) \
490 << NAME##Shift;
491#include "clang/Basic/FPOptions.def"
492
493 static constexpr storage_type TotalWidth = 0
494#define OPTION(NAME, TYPE, WIDTH, PREVIOUS) +WIDTH
495#include "clang/Basic/FPOptions.def"
496 ;
497 static_assert(TotalWidth <= StorageBitSize, "Too short type for FPOptions");
498
499private:
500 storage_type Value;
501
502public:
503 FPOptions() : Value(0) {
504 setFPContractMode(LangOptions::FPM_Off);
505 setRoundingMode(static_cast<RoundingMode>(LangOptions::FPR_ToNearest));
506 setFPExceptionMode(LangOptions::FPE_Ignore);
507 }
508 explicit FPOptions(const LangOptions &LO) {
509 Value = 0;
510 // The language fp contract option FPM_FastHonorPragmas has the same effect
511 // as FPM_Fast in frontend. For simplicity, use FPM_Fast uniformly in
512 // frontend.
513 auto LangOptContractMode = LO.getDefaultFPContractMode();
514 if (LangOptContractMode == LangOptions::FPM_FastHonorPragmas)
515 LangOptContractMode = LangOptions::FPM_Fast;
516 setFPContractMode(LangOptContractMode);
517 setRoundingMode(LO.getFPRoundingMode());
518 setFPExceptionMode(LO.getFPExceptionMode());
519 setAllowFPReassociate(LO.AllowFPReassoc);
520 setNoHonorNaNs(LO.NoHonorNaNs);
521 setNoHonorInfs(LO.NoHonorInfs);
522 setNoSignedZero(LO.NoSignedZero);
523 setAllowReciprocal(LO.AllowRecip);
524 setAllowApproxFunc(LO.ApproxFunc);
525 if (getFPContractMode() == LangOptions::FPM_On &&
526 getRoundingMode() == llvm::RoundingMode::Dynamic &&
527 getFPExceptionMode() == LangOptions::FPE_Strict)
528 // If the FP settings are set to the "strict" model, then
529 // FENV access is set to true. (ffp-model=strict)
530 setAllowFEnvAccess(true);
531 else
532 setAllowFEnvAccess(LangOptions::FPM_Off);
533 }
534
535 bool allowFPContractWithinStatement() const {
536 return getFPContractMode() == LangOptions::FPM_On;
537 }
538 void setAllowFPContractWithinStatement() {
539 setFPContractMode(LangOptions::FPM_On);
540 }
541
542 bool allowFPContractAcrossStatement() const {
543 return getFPContractMode() == LangOptions::FPM_Fast;
544 }
545 void setAllowFPContractAcrossStatement() {
546 setFPContractMode(LangOptions::FPM_Fast);
547 }
548
549 bool isFPConstrained() const {
550 return getRoundingMode() != llvm::RoundingMode::NearestTiesToEven ||
551 getFPExceptionMode() != LangOptions::FPE_Ignore ||
552 getAllowFEnvAccess();
553 }
554
555 bool operator==(FPOptions other) const { return Value == other.Value; }
556
557 /// Return the default value of FPOptions that's used when trailing
558 /// storage isn't required.
559 static FPOptions defaultWithoutTrailingStorage(const LangOptions &LO);
560
561 storage_type getAsOpaqueInt() const { return Value; }
562 static FPOptions getFromOpaqueInt(storage_type Value) {
563 FPOptions Opts;
564 Opts.Value = Value;
565 return Opts;
566 }
567
568 // We can define most of the accessors automatically:
569#define OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
570 TYPE get##NAME() const { \
571 return static_cast<TYPE>((Value & NAME##Mask) >> NAME##Shift); \
572 } \
573 void set##NAME(TYPE value) { \
574 Value = (Value & ~NAME##Mask) | (storage_type(value) << NAME##Shift); \
575 }
576#include "clang/Basic/FPOptions.def"
577 LLVM_DUMP_METHOD__attribute__((noinline)) void dump();
578};
579
580/// Represents difference between two FPOptions values.
581///
582/// The effect of language constructs changing the set of floating point options
583/// is usually a change of some FP properties while leaving others intact. This
584/// class describes such changes by keeping information about what FP options
585/// are overridden.
586///
587/// The integral set of FP options, described by the class FPOptions, may be
588/// represented as a default FP option set, defined by language standard and
589/// command line options, with the overrides introduced by pragmas.
590///
591/// The is implemented as a value of the new FPOptions plus a mask showing which
592/// fields are actually set in it.
593class FPOptionsOverride {
594 FPOptions Options = FPOptions::getFromOpaqueInt(0);
595 FPOptions::storage_type OverrideMask = 0;
596
597public:
598 using RoundingMode = llvm::RoundingMode;
599
600 /// The type suitable for storing values of FPOptionsOverride. Must be twice
601 /// as wide as bit size of FPOption.
602 using storage_type = uint32_t;
603 static_assert(sizeof(storage_type) >= 2 * sizeof(FPOptions::storage_type),
604 "Too short type for FPOptionsOverride");
605
606 /// Bit mask selecting bits of OverrideMask in serialized representation of
607 /// FPOptionsOverride.
608 static constexpr storage_type OverrideMaskBits =
609 (static_cast<storage_type>(1) << FPOptions::StorageBitSize) - 1;
610
611 FPOptionsOverride() {}
612 FPOptionsOverride(const LangOptions &LO)
613 : Options(LO), OverrideMask(OverrideMaskBits) {}
614 FPOptionsOverride(FPOptions FPO)
615 : Options(FPO), OverrideMask(OverrideMaskBits) {}
616
617 bool requiresTrailingStorage() const { return OverrideMask != 0; }
618
619 void setAllowFPContractWithinStatement() {
620 setFPContractModeOverride(LangOptions::FPM_On);
621 }
622
623 void setAllowFPContractAcrossStatement() {
624 setFPContractModeOverride(LangOptions::FPM_Fast);
625 }
626
627 void setDisallowFPContract() {
628 setFPContractModeOverride(LangOptions::FPM_Off);
629 }
630
631 void setFPPreciseEnabled(bool Value) {
632 setAllowFPReassociateOverride(!Value);
633 setNoHonorNaNsOverride(!Value);
634 setNoHonorInfsOverride(!Value);
635 setNoSignedZeroOverride(!Value);
636 setAllowReciprocalOverride(!Value);
637 setAllowApproxFuncOverride(!Value);
638 if (Value)
639 /* Precise mode implies fp_contract=on and disables ffast-math */
640 setAllowFPContractWithinStatement();
641 else
642 /* Precise mode disabled sets fp_contract=fast and enables ffast-math */
643 setAllowFPContractAcrossStatement();
644 }
645
646 storage_type getAsOpaqueInt() const {
647 return (static_cast<storage_type>(Options.getAsOpaqueInt())
648 << FPOptions::StorageBitSize) |
649 OverrideMask;
650 }
651 static FPOptionsOverride getFromOpaqueInt(storage_type I) {
652 FPOptionsOverride Opts;
653 Opts.OverrideMask = I & OverrideMaskBits;
654 Opts.Options = FPOptions::getFromOpaqueInt(I >> FPOptions::StorageBitSize);
655 return Opts;
656 }
657
658 FPOptions applyOverrides(FPOptions Base) {
659 FPOptions Result =
660 FPOptions::getFromOpaqueInt((Base.getAsOpaqueInt() & ~OverrideMask) |
661 (Options.getAsOpaqueInt() & OverrideMask));
662 return Result;
663 }
664
665 FPOptions applyOverrides(const LangOptions &LO) {
666 return applyOverrides(FPOptions(LO));
667 }
668
669 bool operator==(FPOptionsOverride other) const {
670 return Options == other.Options && OverrideMask == other.OverrideMask;
671 }
672 bool operator!=(FPOptionsOverride other) const { return !(*this == other); }
673
674#define OPTION(NAME, TYPE, WIDTH, PREVIOUS) \
675 bool has##NAME##Override() const { \
676 return OverrideMask & FPOptions::NAME##Mask; \
677 } \
678 TYPE get##NAME##Override() const { \
679 assert(has##NAME##Override())((void)0); \
680 return Options.get##NAME(); \
681 } \
682 void clear##NAME##Override() { \
683 /* Clear the actual value so that we don't have spurious differences when \
684 * testing equality. */ \
685 Options.set##NAME(TYPE(0)); \
686 OverrideMask &= ~FPOptions::NAME##Mask; \
687 } \
688 void set##NAME##Override(TYPE value) { \
689 Options.set##NAME(value); \
690 OverrideMask |= FPOptions::NAME##Mask; \
691 }
692#include "clang/Basic/FPOptions.def"
693 LLVM_DUMP_METHOD__attribute__((noinline)) void dump();
694};
695
696/// Describes the kind of translation unit being processed.
697enum TranslationUnitKind {
698 /// The translation unit is a complete translation unit.
699 TU_Complete,
700
701 /// The translation unit is a prefix to a translation unit, and is
702 /// not complete.
703 TU_Prefix,
704
705 /// The translation unit is a module.
706 TU_Module,
707
708 /// The translation unit is a is a complete translation unit that we might
709 /// incrementally extend later.
710 TU_Incremental
711};
712
713} // namespace clang
714
715#endif // LLVM_CLANG_BASIC_LANGOPTIONS_H