1 //===--- ItaniumMangle.cpp - Itanium C++ Name Mangling ----------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // Implements C++ name mangling according to the Itanium C++ ABI, 10 // which is used in GCC 3.2 and newer (and many compilers that are 11 // ABI-compatible with GCC): 12 // 13 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling 14 // 15 //===----------------------------------------------------------------------===// 16 17 #include "clang/AST/ASTContext.h" 18 #include "clang/AST/Attr.h" 19 #include "clang/AST/Decl.h" 20 #include "clang/AST/DeclCXX.h" 21 #include "clang/AST/DeclObjC.h" 22 #include "clang/AST/DeclOpenMP.h" 23 #include "clang/AST/DeclTemplate.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprConcepts.h" 27 #include "clang/AST/ExprObjC.h" 28 #include "clang/AST/Mangle.h" 29 #include "clang/AST/TypeLoc.h" 30 #include "clang/Basic/ABI.h" 31 #include "clang/Basic/DiagnosticAST.h" 32 #include "clang/Basic/Module.h" 33 #include "clang/Basic/SourceManager.h" 34 #include "clang/Basic/TargetInfo.h" 35 #include "clang/Basic/Thunk.h" 36 #include "llvm/ADT/StringExtras.h" 37 #include "llvm/Support/ErrorHandling.h" 38 #include "llvm/Support/raw_ostream.h" 39 #include "llvm/TargetParser/RISCVTargetParser.h" 40 #include <optional> 41 42 using namespace clang; 43 44 namespace { 45 46 static bool isLocalContainerContext(const DeclContext *DC) { 47 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC); 48 } 49 50 static const FunctionDecl *getStructor(const FunctionDecl *fn) { 51 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate()) 52 return ftd->getTemplatedDecl(); 53 54 return fn; 55 } 56 57 static const NamedDecl *getStructor(const NamedDecl *decl) { 58 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl); 59 return (fn ? getStructor(fn) : decl); 60 } 61 62 static bool isLambda(const NamedDecl *ND) { 63 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND); 64 if (!Record) 65 return false; 66 67 return Record->isLambda(); 68 } 69 70 static const unsigned UnknownArity = ~0U; 71 72 class ItaniumMangleContextImpl : public ItaniumMangleContext { 73 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy; 74 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator; 75 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier; 76 const DiscriminatorOverrideTy DiscriminatorOverride = nullptr; 77 NamespaceDecl *StdNamespace = nullptr; 78 79 bool NeedsUniqueInternalLinkageNames = false; 80 81 public: 82 explicit ItaniumMangleContextImpl( 83 ASTContext &Context, DiagnosticsEngine &Diags, 84 DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false) 85 : ItaniumMangleContext(Context, Diags, IsAux), 86 DiscriminatorOverride(DiscriminatorOverride) {} 87 88 /// @name Mangler Entry Points 89 /// @{ 90 91 bool shouldMangleCXXName(const NamedDecl *D) override; 92 bool shouldMangleStringLiteral(const StringLiteral *) override { 93 return false; 94 } 95 96 bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override; 97 void needsUniqueInternalLinkageNames() override { 98 NeedsUniqueInternalLinkageNames = true; 99 } 100 101 void mangleCXXName(GlobalDecl GD, raw_ostream &) override; 102 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, 103 raw_ostream &) override; 104 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type, 105 const ThisAdjustment &ThisAdjustment, 106 raw_ostream &) override; 107 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, 108 raw_ostream &) override; 109 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override; 110 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override; 111 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset, 112 const CXXRecordDecl *Type, raw_ostream &) override; 113 void mangleCXXRTTI(QualType T, raw_ostream &) override; 114 void mangleCXXRTTIName(QualType T, raw_ostream &, 115 bool NormalizeIntegers) override; 116 void mangleCanonicalTypeName(QualType T, raw_ostream &, 117 bool NormalizeIntegers) override; 118 119 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override; 120 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override; 121 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override; 122 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override; 123 void mangleDynamicAtExitDestructor(const VarDecl *D, 124 raw_ostream &Out) override; 125 void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override; 126 void mangleSEHFilterExpression(GlobalDecl EnclosingDecl, 127 raw_ostream &Out) override; 128 void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl, 129 raw_ostream &Out) override; 130 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override; 131 void mangleItaniumThreadLocalWrapper(const VarDecl *D, 132 raw_ostream &) override; 133 134 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override; 135 136 void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override; 137 138 void mangleModuleInitializer(const Module *Module, raw_ostream &) override; 139 140 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) { 141 // Lambda closure types are already numbered. 142 if (isLambda(ND)) 143 return false; 144 145 // Anonymous tags are already numbered. 146 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) { 147 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl()) 148 return false; 149 } 150 151 // Use the canonical number for externally visible decls. 152 if (ND->isExternallyVisible()) { 153 unsigned discriminator = getASTContext().getManglingNumber(ND, isAux()); 154 if (discriminator == 1) 155 return false; 156 disc = discriminator - 2; 157 return true; 158 } 159 160 // Make up a reasonable number for internal decls. 161 unsigned &discriminator = Uniquifier[ND]; 162 if (!discriminator) { 163 const DeclContext *DC = getEffectiveDeclContext(ND); 164 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())]; 165 } 166 if (discriminator == 1) 167 return false; 168 disc = discriminator-2; 169 return true; 170 } 171 172 std::string getLambdaString(const CXXRecordDecl *Lambda) override { 173 // This function matches the one in MicrosoftMangle, which returns 174 // the string that is used in lambda mangled names. 175 assert(Lambda->isLambda() && "RD must be a lambda!"); 176 std::string Name("<lambda"); 177 Decl *LambdaContextDecl = Lambda->getLambdaContextDecl(); 178 unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber(); 179 unsigned LambdaId; 180 const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl); 181 const FunctionDecl *Func = 182 Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr; 183 184 if (Func) { 185 unsigned DefaultArgNo = 186 Func->getNumParams() - Parm->getFunctionScopeIndex(); 187 Name += llvm::utostr(DefaultArgNo); 188 Name += "_"; 189 } 190 191 if (LambdaManglingNumber) 192 LambdaId = LambdaManglingNumber; 193 else 194 LambdaId = getAnonymousStructIdForDebugInfo(Lambda); 195 196 Name += llvm::utostr(LambdaId); 197 Name += '>'; 198 return Name; 199 } 200 201 DiscriminatorOverrideTy getDiscriminatorOverride() const override { 202 return DiscriminatorOverride; 203 } 204 205 NamespaceDecl *getStdNamespace(); 206 207 const DeclContext *getEffectiveDeclContext(const Decl *D); 208 const DeclContext *getEffectiveParentContext(const DeclContext *DC) { 209 return getEffectiveDeclContext(cast<Decl>(DC)); 210 } 211 212 bool isInternalLinkageDecl(const NamedDecl *ND); 213 214 /// @} 215 }; 216 217 /// Manage the mangling of a single name. 218 class CXXNameMangler { 219 ItaniumMangleContextImpl &Context; 220 raw_ostream &Out; 221 /// Normalize integer types for cross-language CFI support with other 222 /// languages that can't represent and encode C/C++ integer types. 223 bool NormalizeIntegers = false; 224 225 bool NullOut = false; 226 /// In the "DisableDerivedAbiTags" mode derived ABI tags are not calculated. 227 /// This mode is used when mangler creates another mangler recursively to 228 /// calculate ABI tags for the function return value or the variable type. 229 /// Also it is required to avoid infinite recursion in some cases. 230 bool DisableDerivedAbiTags = false; 231 232 /// The "structor" is the top-level declaration being mangled, if 233 /// that's not a template specialization; otherwise it's the pattern 234 /// for that specialization. 235 const NamedDecl *Structor; 236 unsigned StructorType = 0; 237 238 // An offset to add to all template parameter depths while mangling. Used 239 // when mangling a template parameter list to see if it matches a template 240 // template parameter exactly. 241 unsigned TemplateDepthOffset = 0; 242 243 /// The next substitution sequence number. 244 unsigned SeqID = 0; 245 246 class FunctionTypeDepthState { 247 unsigned Bits = 0; 248 249 enum { InResultTypeMask = 1 }; 250 251 public: 252 FunctionTypeDepthState() = default; 253 254 /// The number of function types we're inside. 255 unsigned getDepth() const { 256 return Bits >> 1; 257 } 258 259 /// True if we're in the return type of the innermost function type. 260 bool isInResultType() const { 261 return Bits & InResultTypeMask; 262 } 263 264 FunctionTypeDepthState push() { 265 FunctionTypeDepthState tmp = *this; 266 Bits = (Bits & ~InResultTypeMask) + 2; 267 return tmp; 268 } 269 270 void enterResultType() { 271 Bits |= InResultTypeMask; 272 } 273 274 void leaveResultType() { 275 Bits &= ~InResultTypeMask; 276 } 277 278 void pop(FunctionTypeDepthState saved) { 279 assert(getDepth() == saved.getDepth() + 1); 280 Bits = saved.Bits; 281 } 282 283 } FunctionTypeDepth; 284 285 // abi_tag is a gcc attribute, taking one or more strings called "tags". 286 // The goal is to annotate against which version of a library an object was 287 // built and to be able to provide backwards compatibility ("dual abi"). 288 // For more information see docs/ItaniumMangleAbiTags.rst. 289 typedef SmallVector<StringRef, 4> AbiTagList; 290 291 // State to gather all implicit and explicit tags used in a mangled name. 292 // Must always have an instance of this while emitting any name to keep 293 // track. 294 class AbiTagState final { 295 public: 296 explicit AbiTagState(AbiTagState *&Head) : LinkHead(Head) { 297 Parent = LinkHead; 298 LinkHead = this; 299 } 300 301 // No copy, no move. 302 AbiTagState(const AbiTagState &) = delete; 303 AbiTagState &operator=(const AbiTagState &) = delete; 304 305 ~AbiTagState() { pop(); } 306 307 void write(raw_ostream &Out, const NamedDecl *ND, 308 const AbiTagList *AdditionalAbiTags) { 309 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 310 if (!isa<FunctionDecl>(ND) && !isa<VarDecl>(ND)) { 311 assert( 312 !AdditionalAbiTags && 313 "only function and variables need a list of additional abi tags"); 314 if (const auto *NS = dyn_cast<NamespaceDecl>(ND)) { 315 if (const auto *AbiTag = NS->getAttr<AbiTagAttr>()) { 316 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(), 317 AbiTag->tags().end()); 318 } 319 // Don't emit abi tags for namespaces. 320 return; 321 } 322 } 323 324 AbiTagList TagList; 325 if (const auto *AbiTag = ND->getAttr<AbiTagAttr>()) { 326 UsedAbiTags.insert(UsedAbiTags.end(), AbiTag->tags().begin(), 327 AbiTag->tags().end()); 328 TagList.insert(TagList.end(), AbiTag->tags().begin(), 329 AbiTag->tags().end()); 330 } 331 332 if (AdditionalAbiTags) { 333 UsedAbiTags.insert(UsedAbiTags.end(), AdditionalAbiTags->begin(), 334 AdditionalAbiTags->end()); 335 TagList.insert(TagList.end(), AdditionalAbiTags->begin(), 336 AdditionalAbiTags->end()); 337 } 338 339 llvm::sort(TagList); 340 TagList.erase(std::unique(TagList.begin(), TagList.end()), TagList.end()); 341 342 writeSortedUniqueAbiTags(Out, TagList); 343 } 344 345 const AbiTagList &getUsedAbiTags() const { return UsedAbiTags; } 346 void setUsedAbiTags(const AbiTagList &AbiTags) { 347 UsedAbiTags = AbiTags; 348 } 349 350 const AbiTagList &getEmittedAbiTags() const { 351 return EmittedAbiTags; 352 } 353 354 const AbiTagList &getSortedUniqueUsedAbiTags() { 355 llvm::sort(UsedAbiTags); 356 UsedAbiTags.erase(std::unique(UsedAbiTags.begin(), UsedAbiTags.end()), 357 UsedAbiTags.end()); 358 return UsedAbiTags; 359 } 360 361 private: 362 //! All abi tags used implicitly or explicitly. 363 AbiTagList UsedAbiTags; 364 //! All explicit abi tags (i.e. not from namespace). 365 AbiTagList EmittedAbiTags; 366 367 AbiTagState *&LinkHead; 368 AbiTagState *Parent = nullptr; 369 370 void pop() { 371 assert(LinkHead == this && 372 "abi tag link head must point to us on destruction"); 373 if (Parent) { 374 Parent->UsedAbiTags.insert(Parent->UsedAbiTags.end(), 375 UsedAbiTags.begin(), UsedAbiTags.end()); 376 Parent->EmittedAbiTags.insert(Parent->EmittedAbiTags.end(), 377 EmittedAbiTags.begin(), 378 EmittedAbiTags.end()); 379 } 380 LinkHead = Parent; 381 } 382 383 void writeSortedUniqueAbiTags(raw_ostream &Out, const AbiTagList &AbiTags) { 384 for (const auto &Tag : AbiTags) { 385 EmittedAbiTags.push_back(Tag); 386 Out << "B"; 387 Out << Tag.size(); 388 Out << Tag; 389 } 390 } 391 }; 392 393 AbiTagState *AbiTags = nullptr; 394 AbiTagState AbiTagsRoot; 395 396 llvm::DenseMap<uintptr_t, unsigned> Substitutions; 397 llvm::DenseMap<StringRef, unsigned> ModuleSubstitutions; 398 399 ASTContext &getASTContext() const { return Context.getASTContext(); } 400 401 bool isCompatibleWith(LangOptions::ClangABI Ver) { 402 return Context.getASTContext().getLangOpts().getClangABICompat() <= Ver; 403 } 404 405 bool isStd(const NamespaceDecl *NS); 406 bool isStdNamespace(const DeclContext *DC); 407 408 const RecordDecl *GetLocalClassDecl(const Decl *D); 409 bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A); 410 bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD, 411 llvm::StringRef Name, bool HasAllocator); 412 413 public: 414 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, 415 const NamedDecl *D = nullptr, bool NullOut_ = false) 416 : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)), 417 AbiTagsRoot(AbiTags) { 418 // These can't be mangled without a ctor type or dtor type. 419 assert(!D || (!isa<CXXDestructorDecl>(D) && 420 !isa<CXXConstructorDecl>(D))); 421 } 422 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, 423 const CXXConstructorDecl *D, CXXCtorType Type) 424 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), 425 AbiTagsRoot(AbiTags) {} 426 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, 427 const CXXDestructorDecl *D, CXXDtorType Type) 428 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), 429 AbiTagsRoot(AbiTags) {} 430 431 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, 432 bool NormalizeIntegers_) 433 : Context(C), Out(Out_), NormalizeIntegers(NormalizeIntegers_), 434 NullOut(false), Structor(nullptr), AbiTagsRoot(AbiTags) {} 435 CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_) 436 : Context(Outer.Context), Out(Out_), Structor(Outer.Structor), 437 StructorType(Outer.StructorType), SeqID(Outer.SeqID), 438 FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags), 439 Substitutions(Outer.Substitutions), 440 ModuleSubstitutions(Outer.ModuleSubstitutions) {} 441 442 CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_) 443 : CXXNameMangler(Outer, (raw_ostream &)Out_) { 444 NullOut = true; 445 } 446 447 struct WithTemplateDepthOffset { unsigned Offset; }; 448 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out, 449 WithTemplateDepthOffset Offset) 450 : CXXNameMangler(C, Out) { 451 TemplateDepthOffset = Offset.Offset; 452 } 453 454 raw_ostream &getStream() { return Out; } 455 456 void disableDerivedAbiTags() { DisableDerivedAbiTags = true; } 457 static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD); 458 459 void mangle(GlobalDecl GD); 460 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual); 461 void mangleNumber(const llvm::APSInt &I); 462 void mangleNumber(int64_t Number); 463 void mangleFloat(const llvm::APFloat &F); 464 void mangleFunctionEncoding(GlobalDecl GD); 465 void mangleSeqID(unsigned SeqID); 466 void mangleName(GlobalDecl GD); 467 void mangleType(QualType T); 468 void mangleNameOrStandardSubstitution(const NamedDecl *ND); 469 void mangleLambdaSig(const CXXRecordDecl *Lambda); 470 void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false); 471 472 private: 473 474 bool mangleSubstitution(const NamedDecl *ND); 475 bool mangleSubstitution(NestedNameSpecifier *NNS); 476 bool mangleSubstitution(QualType T); 477 bool mangleSubstitution(TemplateName Template); 478 bool mangleSubstitution(uintptr_t Ptr); 479 480 void mangleExistingSubstitution(TemplateName name); 481 482 bool mangleStandardSubstitution(const NamedDecl *ND); 483 484 void addSubstitution(const NamedDecl *ND) { 485 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 486 487 addSubstitution(reinterpret_cast<uintptr_t>(ND)); 488 } 489 void addSubstitution(NestedNameSpecifier *NNS) { 490 NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS); 491 492 addSubstitution(reinterpret_cast<uintptr_t>(NNS)); 493 } 494 void addSubstitution(QualType T); 495 void addSubstitution(TemplateName Template); 496 void addSubstitution(uintptr_t Ptr); 497 // Destructive copy substitutions from other mangler. 498 void extendSubstitutions(CXXNameMangler* Other); 499 500 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier, 501 bool recursive = false); 502 void mangleUnresolvedName(NestedNameSpecifier *qualifier, 503 DeclarationName name, 504 const TemplateArgumentLoc *TemplateArgs, 505 unsigned NumTemplateArgs, 506 unsigned KnownArity = UnknownArity); 507 508 void mangleFunctionEncodingBareType(const FunctionDecl *FD); 509 510 void mangleNameWithAbiTags(GlobalDecl GD, 511 const AbiTagList *AdditionalAbiTags); 512 void mangleModuleName(const NamedDecl *ND); 513 void mangleTemplateName(const TemplateDecl *TD, 514 ArrayRef<TemplateArgument> Args); 515 void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC, 516 const AbiTagList *AdditionalAbiTags) { 517 mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC, 518 UnknownArity, AdditionalAbiTags); 519 } 520 void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name, 521 const DeclContext *DC, unsigned KnownArity, 522 const AbiTagList *AdditionalAbiTags); 523 void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC, 524 const AbiTagList *AdditionalAbiTags); 525 void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC, 526 const AbiTagList *AdditionalAbiTags); 527 void mangleSourceName(const IdentifierInfo *II); 528 void mangleRegCallName(const IdentifierInfo *II); 529 void mangleDeviceStubName(const IdentifierInfo *II); 530 void mangleSourceNameWithAbiTags( 531 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr); 532 void mangleLocalName(GlobalDecl GD, 533 const AbiTagList *AdditionalAbiTags); 534 void mangleBlockForPrefix(const BlockDecl *Block); 535 void mangleUnqualifiedBlock(const BlockDecl *Block); 536 void mangleTemplateParamDecl(const NamedDecl *Decl); 537 void mangleTemplateParameterList(const TemplateParameterList *Params); 538 void mangleTypeConstraint(const ConceptDecl *Concept, 539 ArrayRef<TemplateArgument> Arguments); 540 void mangleTypeConstraint(const TypeConstraint *Constraint); 541 void mangleRequiresClause(const Expr *RequiresClause); 542 void mangleLambda(const CXXRecordDecl *Lambda); 543 void mangleNestedName(GlobalDecl GD, const DeclContext *DC, 544 const AbiTagList *AdditionalAbiTags, 545 bool NoFunction=false); 546 void mangleNestedName(const TemplateDecl *TD, 547 ArrayRef<TemplateArgument> Args); 548 void mangleNestedNameWithClosurePrefix(GlobalDecl GD, 549 const NamedDecl *PrefixND, 550 const AbiTagList *AdditionalAbiTags); 551 void manglePrefix(NestedNameSpecifier *qualifier); 552 void manglePrefix(const DeclContext *DC, bool NoFunction=false); 553 void manglePrefix(QualType type); 554 void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false); 555 void mangleTemplatePrefix(TemplateName Template); 556 const NamedDecl *getClosurePrefix(const Decl *ND); 557 void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false); 558 bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType, 559 StringRef Prefix = ""); 560 void mangleOperatorName(DeclarationName Name, unsigned Arity); 561 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity); 562 void mangleVendorQualifier(StringRef qualifier); 563 void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr); 564 void mangleRefQualifier(RefQualifierKind RefQualifier); 565 566 void mangleObjCMethodName(const ObjCMethodDecl *MD); 567 568 // Declare manglers for every type class. 569 #define ABSTRACT_TYPE(CLASS, PARENT) 570 #define NON_CANONICAL_TYPE(CLASS, PARENT) 571 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T); 572 #include "clang/AST/TypeNodes.inc" 573 574 void mangleType(const TagType*); 575 void mangleType(TemplateName); 576 static StringRef getCallingConvQualifierName(CallingConv CC); 577 void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info); 578 void mangleExtFunctionInfo(const FunctionType *T); 579 void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType, 580 const FunctionDecl *FD = nullptr); 581 void mangleNeonVectorType(const VectorType *T); 582 void mangleNeonVectorType(const DependentVectorType *T); 583 void mangleAArch64NeonVectorType(const VectorType *T); 584 void mangleAArch64NeonVectorType(const DependentVectorType *T); 585 void mangleAArch64FixedSveVectorType(const VectorType *T); 586 void mangleAArch64FixedSveVectorType(const DependentVectorType *T); 587 void mangleRISCVFixedRVVVectorType(const VectorType *T); 588 void mangleRISCVFixedRVVVectorType(const DependentVectorType *T); 589 590 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value); 591 void mangleFloatLiteral(QualType T, const llvm::APFloat &V); 592 void mangleFixedPointLiteral(); 593 void mangleNullPointer(QualType T); 594 595 void mangleMemberExprBase(const Expr *base, bool isArrow); 596 void mangleMemberExpr(const Expr *base, bool isArrow, 597 NestedNameSpecifier *qualifier, 598 NamedDecl *firstQualifierLookup, 599 DeclarationName name, 600 const TemplateArgumentLoc *TemplateArgs, 601 unsigned NumTemplateArgs, 602 unsigned knownArity); 603 void mangleCastExpression(const Expr *E, StringRef CastEncoding); 604 void mangleInitListElements(const InitListExpr *InitList); 605 void mangleRequirement(SourceLocation RequiresExprLoc, 606 const concepts::Requirement *Req); 607 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity, 608 bool AsTemplateArg = false); 609 void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom); 610 void mangleCXXDtorType(CXXDtorType T); 611 612 struct TemplateArgManglingInfo; 613 void mangleTemplateArgs(TemplateName TN, 614 const TemplateArgumentLoc *TemplateArgs, 615 unsigned NumTemplateArgs); 616 void mangleTemplateArgs(TemplateName TN, ArrayRef<TemplateArgument> Args); 617 void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL); 618 void mangleTemplateArg(TemplateArgManglingInfo &Info, unsigned Index, 619 TemplateArgument A); 620 void mangleTemplateArg(TemplateArgument A, bool NeedExactType); 621 void mangleTemplateArgExpr(const Expr *E); 622 void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel, 623 bool NeedExactType = false); 624 625 void mangleTemplateParameter(unsigned Depth, unsigned Index); 626 627 void mangleFunctionParam(const ParmVarDecl *parm); 628 629 void writeAbiTags(const NamedDecl *ND, 630 const AbiTagList *AdditionalAbiTags); 631 632 // Returns sorted unique list of ABI tags. 633 AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD); 634 // Returns sorted unique list of ABI tags. 635 AbiTagList makeVariableTypeTags(const VarDecl *VD); 636 }; 637 638 } 639 640 NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() { 641 if (!StdNamespace) { 642 StdNamespace = NamespaceDecl::Create( 643 getASTContext(), getASTContext().getTranslationUnitDecl(), 644 /*Inline=*/false, SourceLocation(), SourceLocation(), 645 &getASTContext().Idents.get("std"), 646 /*PrevDecl=*/nullptr, /*Nested=*/false); 647 StdNamespace->setImplicit(); 648 } 649 return StdNamespace; 650 } 651 652 /// Retrieve the declaration context that should be used when mangling the given 653 /// declaration. 654 const DeclContext * 655 ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) { 656 // The ABI assumes that lambda closure types that occur within 657 // default arguments live in the context of the function. However, due to 658 // the way in which Clang parses and creates function declarations, this is 659 // not the case: the lambda closure type ends up living in the context 660 // where the function itself resides, because the function declaration itself 661 // had not yet been created. Fix the context here. 662 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 663 if (RD->isLambda()) 664 if (ParmVarDecl *ContextParam = 665 dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl())) 666 return ContextParam->getDeclContext(); 667 } 668 669 // Perform the same check for block literals. 670 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 671 if (ParmVarDecl *ContextParam = 672 dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) 673 return ContextParam->getDeclContext(); 674 } 675 676 // On ARM and AArch64, the va_list tag is always mangled as if in the std 677 // namespace. We do not represent va_list as actually being in the std 678 // namespace in C because this would result in incorrect debug info in C, 679 // among other things. It is important for both languages to have the same 680 // mangling in order for -fsanitize=cfi-icall to work. 681 if (D == getASTContext().getVaListTagDecl()) { 682 const llvm::Triple &T = getASTContext().getTargetInfo().getTriple(); 683 if (T.isARM() || T.isThumb() || T.isAArch64()) 684 return getStdNamespace(); 685 } 686 687 const DeclContext *DC = D->getDeclContext(); 688 if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) || 689 isa<OMPDeclareMapperDecl>(DC)) { 690 return getEffectiveDeclContext(cast<Decl>(DC)); 691 } 692 693 if (const auto *VD = dyn_cast<VarDecl>(D)) 694 if (VD->isExternC()) 695 return getASTContext().getTranslationUnitDecl(); 696 697 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 698 if (FD->isExternC()) 699 return getASTContext().getTranslationUnitDecl(); 700 // Member-like constrained friends are mangled as if they were members of 701 // the enclosing class. 702 if (FD->isMemberLikeConstrainedFriend() && 703 getASTContext().getLangOpts().getClangABICompat() > 704 LangOptions::ClangABI::Ver17) 705 return D->getLexicalDeclContext()->getRedeclContext(); 706 } 707 708 return DC->getRedeclContext(); 709 } 710 711 bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) { 712 if (ND && ND->getFormalLinkage() == Linkage::Internal && 713 !ND->isExternallyVisible() && 714 getEffectiveDeclContext(ND)->isFileContext() && 715 !ND->isInAnonymousNamespace()) 716 return true; 717 return false; 718 } 719 720 // Check if this Function Decl needs a unique internal linkage name. 721 bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl( 722 const NamedDecl *ND) { 723 if (!NeedsUniqueInternalLinkageNames || !ND) 724 return false; 725 726 const auto *FD = dyn_cast<FunctionDecl>(ND); 727 if (!FD) 728 return false; 729 730 // For C functions without prototypes, return false as their 731 // names should not be mangled. 732 if (!FD->getType()->getAs<FunctionProtoType>()) 733 return false; 734 735 if (isInternalLinkageDecl(ND)) 736 return true; 737 738 return false; 739 } 740 741 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) { 742 if (const auto *FD = dyn_cast<FunctionDecl>(D)) { 743 LanguageLinkage L = FD->getLanguageLinkage(); 744 // Overloadable functions need mangling. 745 if (FD->hasAttr<OverloadableAttr>()) 746 return true; 747 748 // "main" is not mangled. 749 if (FD->isMain()) 750 return false; 751 752 // The Windows ABI expects that we would never mangle "typical" 753 // user-defined entry points regardless of visibility or freestanding-ness. 754 // 755 // N.B. This is distinct from asking about "main". "main" has a lot of 756 // special rules associated with it in the standard while these 757 // user-defined entry points are outside of the purview of the standard. 758 // For example, there can be only one definition for "main" in a standards 759 // compliant program; however nothing forbids the existence of wmain and 760 // WinMain in the same translation unit. 761 if (FD->isMSVCRTEntryPoint()) 762 return false; 763 764 // C++ functions and those whose names are not a simple identifier need 765 // mangling. 766 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage) 767 return true; 768 769 // C functions are not mangled. 770 if (L == CLanguageLinkage) 771 return false; 772 } 773 774 // Otherwise, no mangling is done outside C++ mode. 775 if (!getASTContext().getLangOpts().CPlusPlus) 776 return false; 777 778 if (const auto *VD = dyn_cast<VarDecl>(D)) { 779 // Decompositions are mangled. 780 if (isa<DecompositionDecl>(VD)) 781 return true; 782 783 // C variables are not mangled. 784 if (VD->isExternC()) 785 return false; 786 787 // Variables at global scope are not mangled unless they have internal 788 // linkage or are specializations or are attached to a named module. 789 const DeclContext *DC = getEffectiveDeclContext(D); 790 // Check for extern variable declared locally. 791 if (DC->isFunctionOrMethod() && D->hasLinkage()) 792 while (!DC->isFileContext()) 793 DC = getEffectiveParentContext(DC); 794 if (DC->isTranslationUnit() && D->getFormalLinkage() != Linkage::Internal && 795 !CXXNameMangler::shouldHaveAbiTags(*this, VD) && 796 !isa<VarTemplateSpecializationDecl>(VD) && 797 !VD->getOwningModuleForLinkage()) 798 return false; 799 } 800 801 return true; 802 } 803 804 void CXXNameMangler::writeAbiTags(const NamedDecl *ND, 805 const AbiTagList *AdditionalAbiTags) { 806 assert(AbiTags && "require AbiTagState"); 807 AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags); 808 } 809 810 void CXXNameMangler::mangleSourceNameWithAbiTags( 811 const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) { 812 mangleSourceName(ND->getIdentifier()); 813 writeAbiTags(ND, AdditionalAbiTags); 814 } 815 816 void CXXNameMangler::mangle(GlobalDecl GD) { 817 // <mangled-name> ::= _Z <encoding> 818 // ::= <data name> 819 // ::= <special-name> 820 Out << "_Z"; 821 if (isa<FunctionDecl>(GD.getDecl())) 822 mangleFunctionEncoding(GD); 823 else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl, 824 BindingDecl>(GD.getDecl())) 825 mangleName(GD); 826 else if (const IndirectFieldDecl *IFD = 827 dyn_cast<IndirectFieldDecl>(GD.getDecl())) 828 mangleName(IFD->getAnonField()); 829 else 830 llvm_unreachable("unexpected kind of global decl"); 831 } 832 833 void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) { 834 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl()); 835 // <encoding> ::= <function name> <bare-function-type> 836 837 // Don't mangle in the type if this isn't a decl we should typically mangle. 838 if (!Context.shouldMangleDeclName(FD)) { 839 mangleName(GD); 840 return; 841 } 842 843 AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD); 844 if (ReturnTypeAbiTags.empty()) { 845 // There are no tags for return type, the simplest case. Enter the function 846 // parameter scope before mangling the name, because a template using 847 // constrained `auto` can have references to its parameters within its 848 // template argument list: 849 // 850 // template<typename T> void f(T x, C<decltype(x)> auto) 851 // ... is mangled as ... 852 // template<typename T, C<decltype(param 1)> U> void f(T, U) 853 FunctionTypeDepthState Saved = FunctionTypeDepth.push(); 854 mangleName(GD); 855 FunctionTypeDepth.pop(Saved); 856 mangleFunctionEncodingBareType(FD); 857 return; 858 } 859 860 // Mangle function name and encoding to temporary buffer. 861 // We have to output name and encoding to the same mangler to get the same 862 // substitution as it will be in final mangling. 863 SmallString<256> FunctionEncodingBuf; 864 llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf); 865 CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream); 866 // Output name of the function. 867 FunctionEncodingMangler.disableDerivedAbiTags(); 868 869 FunctionTypeDepthState Saved = FunctionTypeDepth.push(); 870 FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr); 871 FunctionTypeDepth.pop(Saved); 872 873 // Remember length of the function name in the buffer. 874 size_t EncodingPositionStart = FunctionEncodingStream.str().size(); 875 FunctionEncodingMangler.mangleFunctionEncodingBareType(FD); 876 877 // Get tags from return type that are not present in function name or 878 // encoding. 879 const AbiTagList &UsedAbiTags = 880 FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 881 AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size()); 882 AdditionalAbiTags.erase( 883 std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(), 884 UsedAbiTags.begin(), UsedAbiTags.end(), 885 AdditionalAbiTags.begin()), 886 AdditionalAbiTags.end()); 887 888 // Output name with implicit tags and function encoding from temporary buffer. 889 Saved = FunctionTypeDepth.push(); 890 mangleNameWithAbiTags(FD, &AdditionalAbiTags); 891 FunctionTypeDepth.pop(Saved); 892 Out << FunctionEncodingStream.str().substr(EncodingPositionStart); 893 894 // Function encoding could create new substitutions so we have to add 895 // temp mangled substitutions to main mangler. 896 extendSubstitutions(&FunctionEncodingMangler); 897 } 898 899 void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) { 900 if (FD->hasAttr<EnableIfAttr>()) { 901 FunctionTypeDepthState Saved = FunctionTypeDepth.push(); 902 Out << "Ua9enable_ifI"; 903 for (AttrVec::const_iterator I = FD->getAttrs().begin(), 904 E = FD->getAttrs().end(); 905 I != E; ++I) { 906 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I); 907 if (!EIA) 908 continue; 909 if (isCompatibleWith(LangOptions::ClangABI::Ver11)) { 910 // Prior to Clang 12, we hardcoded the X/E around enable-if's argument, 911 // even though <template-arg> should not include an X/E around 912 // <expr-primary>. 913 Out << 'X'; 914 mangleExpression(EIA->getCond()); 915 Out << 'E'; 916 } else { 917 mangleTemplateArgExpr(EIA->getCond()); 918 } 919 } 920 Out << 'E'; 921 FunctionTypeDepth.pop(Saved); 922 } 923 924 // When mangling an inheriting constructor, the bare function type used is 925 // that of the inherited constructor. 926 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) 927 if (auto Inherited = CD->getInheritedConstructor()) 928 FD = Inherited.getConstructor(); 929 930 // Whether the mangling of a function type includes the return type depends on 931 // the context and the nature of the function. The rules for deciding whether 932 // the return type is included are: 933 // 934 // 1. Template functions (names or types) have return types encoded, with 935 // the exceptions listed below. 936 // 2. Function types not appearing as part of a function name mangling, 937 // e.g. parameters, pointer types, etc., have return type encoded, with the 938 // exceptions listed below. 939 // 3. Non-template function names do not have return types encoded. 940 // 941 // The exceptions mentioned in (1) and (2) above, for which the return type is 942 // never included, are 943 // 1. Constructors. 944 // 2. Destructors. 945 // 3. Conversion operator functions, e.g. operator int. 946 bool MangleReturnType = false; 947 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) { 948 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) || 949 isa<CXXConversionDecl>(FD))) 950 MangleReturnType = true; 951 952 // Mangle the type of the primary template. 953 FD = PrimaryTemplate->getTemplatedDecl(); 954 } 955 956 mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(), 957 MangleReturnType, FD); 958 } 959 960 /// Return whether a given namespace is the 'std' namespace. 961 bool CXXNameMangler::isStd(const NamespaceDecl *NS) { 962 if (!Context.getEffectiveParentContext(NS)->isTranslationUnit()) 963 return false; 964 965 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier(); 966 return II && II->isStr("std"); 967 } 968 969 // isStdNamespace - Return whether a given decl context is a toplevel 'std' 970 // namespace. 971 bool CXXNameMangler::isStdNamespace(const DeclContext *DC) { 972 if (!DC->isNamespace()) 973 return false; 974 975 return isStd(cast<NamespaceDecl>(DC)); 976 } 977 978 static const GlobalDecl 979 isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) { 980 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 981 // Check if we have a function template. 982 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) { 983 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) { 984 TemplateArgs = FD->getTemplateSpecializationArgs(); 985 return GD.getWithDecl(TD); 986 } 987 } 988 989 // Check if we have a class template. 990 if (const ClassTemplateSpecializationDecl *Spec = 991 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 992 TemplateArgs = &Spec->getTemplateArgs(); 993 return GD.getWithDecl(Spec->getSpecializedTemplate()); 994 } 995 996 // Check if we have a variable template. 997 if (const VarTemplateSpecializationDecl *Spec = 998 dyn_cast<VarTemplateSpecializationDecl>(ND)) { 999 TemplateArgs = &Spec->getTemplateArgs(); 1000 return GD.getWithDecl(Spec->getSpecializedTemplate()); 1001 } 1002 1003 return GlobalDecl(); 1004 } 1005 1006 static TemplateName asTemplateName(GlobalDecl GD) { 1007 const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl()); 1008 return TemplateName(const_cast<TemplateDecl*>(TD)); 1009 } 1010 1011 void CXXNameMangler::mangleName(GlobalDecl GD) { 1012 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 1013 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 1014 // Variables should have implicit tags from its type. 1015 AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD); 1016 if (VariableTypeAbiTags.empty()) { 1017 // Simple case no variable type tags. 1018 mangleNameWithAbiTags(VD, nullptr); 1019 return; 1020 } 1021 1022 // Mangle variable name to null stream to collect tags. 1023 llvm::raw_null_ostream NullOutStream; 1024 CXXNameMangler VariableNameMangler(*this, NullOutStream); 1025 VariableNameMangler.disableDerivedAbiTags(); 1026 VariableNameMangler.mangleNameWithAbiTags(VD, nullptr); 1027 1028 // Get tags from variable type that are not present in its name. 1029 const AbiTagList &UsedAbiTags = 1030 VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 1031 AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size()); 1032 AdditionalAbiTags.erase( 1033 std::set_difference(VariableTypeAbiTags.begin(), 1034 VariableTypeAbiTags.end(), UsedAbiTags.begin(), 1035 UsedAbiTags.end(), AdditionalAbiTags.begin()), 1036 AdditionalAbiTags.end()); 1037 1038 // Output name with implicit tags. 1039 mangleNameWithAbiTags(VD, &AdditionalAbiTags); 1040 } else { 1041 mangleNameWithAbiTags(GD, nullptr); 1042 } 1043 } 1044 1045 const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) { 1046 const DeclContext *DC = Context.getEffectiveDeclContext(D); 1047 while (!DC->isNamespace() && !DC->isTranslationUnit()) { 1048 if (isLocalContainerContext(DC)) 1049 return dyn_cast<RecordDecl>(D); 1050 D = cast<Decl>(DC); 1051 DC = Context.getEffectiveDeclContext(D); 1052 } 1053 return nullptr; 1054 } 1055 1056 void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD, 1057 const AbiTagList *AdditionalAbiTags) { 1058 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 1059 // <name> ::= [<module-name>] <nested-name> 1060 // ::= [<module-name>] <unscoped-name> 1061 // ::= [<module-name>] <unscoped-template-name> <template-args> 1062 // ::= <local-name> 1063 // 1064 const DeclContext *DC = Context.getEffectiveDeclContext(ND); 1065 1066 // If this is an extern variable declared locally, the relevant DeclContext 1067 // is that of the containing namespace, or the translation unit. 1068 // FIXME: This is a hack; extern variables declared locally should have 1069 // a proper semantic declaration context! 1070 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND)) 1071 while (!DC->isNamespace() && !DC->isTranslationUnit()) 1072 DC = Context.getEffectiveParentContext(DC); 1073 else if (GetLocalClassDecl(ND)) { 1074 mangleLocalName(GD, AdditionalAbiTags); 1075 return; 1076 } 1077 1078 assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl"); 1079 1080 if (isLocalContainerContext(DC)) { 1081 mangleLocalName(GD, AdditionalAbiTags); 1082 return; 1083 } 1084 1085 // Closures can require a nested-name mangling even if they're semantically 1086 // in the global namespace. 1087 if (const NamedDecl *PrefixND = getClosurePrefix(ND)) { 1088 mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags); 1089 return; 1090 } 1091 1092 if (DC->isTranslationUnit() || isStdNamespace(DC)) { 1093 // Check if we have a template. 1094 const TemplateArgumentList *TemplateArgs = nullptr; 1095 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) { 1096 mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags); 1097 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); 1098 return; 1099 } 1100 1101 mangleUnscopedName(GD, DC, AdditionalAbiTags); 1102 return; 1103 } 1104 1105 mangleNestedName(GD, DC, AdditionalAbiTags); 1106 } 1107 1108 void CXXNameMangler::mangleModuleName(const NamedDecl *ND) { 1109 if (ND->isExternallyVisible()) 1110 if (Module *M = ND->getOwningModuleForLinkage()) 1111 mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName()); 1112 } 1113 1114 // <module-name> ::= <module-subname> 1115 // ::= <module-name> <module-subname> 1116 // ::= <substitution> 1117 // <module-subname> ::= W <source-name> 1118 // ::= W P <source-name> 1119 void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) { 1120 // <substitution> ::= S <seq-id> _ 1121 auto It = ModuleSubstitutions.find(Name); 1122 if (It != ModuleSubstitutions.end()) { 1123 Out << 'S'; 1124 mangleSeqID(It->second); 1125 return; 1126 } 1127 1128 // FIXME: Preserve hierarchy in module names rather than flattening 1129 // them to strings; use Module*s as substitution keys. 1130 auto Parts = Name.rsplit('.'); 1131 if (Parts.second.empty()) 1132 Parts.second = Parts.first; 1133 else { 1134 mangleModuleNamePrefix(Parts.first, IsPartition); 1135 IsPartition = false; 1136 } 1137 1138 Out << 'W'; 1139 if (IsPartition) 1140 Out << 'P'; 1141 Out << Parts.second.size() << Parts.second; 1142 ModuleSubstitutions.insert({Name, SeqID++}); 1143 } 1144 1145 void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD, 1146 ArrayRef<TemplateArgument> Args) { 1147 const DeclContext *DC = Context.getEffectiveDeclContext(TD); 1148 1149 if (DC->isTranslationUnit() || isStdNamespace(DC)) { 1150 mangleUnscopedTemplateName(TD, DC, nullptr); 1151 mangleTemplateArgs(asTemplateName(TD), Args); 1152 } else { 1153 mangleNestedName(TD, Args); 1154 } 1155 } 1156 1157 void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC, 1158 const AbiTagList *AdditionalAbiTags) { 1159 // <unscoped-name> ::= <unqualified-name> 1160 // ::= St <unqualified-name> # ::std:: 1161 1162 assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl"); 1163 if (isStdNamespace(DC)) 1164 Out << "St"; 1165 1166 mangleUnqualifiedName(GD, DC, AdditionalAbiTags); 1167 } 1168 1169 void CXXNameMangler::mangleUnscopedTemplateName( 1170 GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) { 1171 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl()); 1172 // <unscoped-template-name> ::= <unscoped-name> 1173 // ::= <substitution> 1174 if (mangleSubstitution(ND)) 1175 return; 1176 1177 // <template-template-param> ::= <template-param> 1178 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) { 1179 assert(!AdditionalAbiTags && 1180 "template template param cannot have abi tags"); 1181 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 1182 } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) { 1183 mangleUnscopedName(GD, DC, AdditionalAbiTags); 1184 } else { 1185 mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC, 1186 AdditionalAbiTags); 1187 } 1188 1189 addSubstitution(ND); 1190 } 1191 1192 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) { 1193 // ABI: 1194 // Floating-point literals are encoded using a fixed-length 1195 // lowercase hexadecimal string corresponding to the internal 1196 // representation (IEEE on Itanium), high-order bytes first, 1197 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f 1198 // on Itanium. 1199 // The 'without leading zeroes' thing seems to be an editorial 1200 // mistake; see the discussion on cxx-abi-dev beginning on 1201 // 2012-01-16. 1202 1203 // Our requirements here are just barely weird enough to justify 1204 // using a custom algorithm instead of post-processing APInt::toString(). 1205 1206 llvm::APInt valueBits = f.bitcastToAPInt(); 1207 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4; 1208 assert(numCharacters != 0); 1209 1210 // Allocate a buffer of the right number of characters. 1211 SmallVector<char, 20> buffer(numCharacters); 1212 1213 // Fill the buffer left-to-right. 1214 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) { 1215 // The bit-index of the next hex digit. 1216 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1); 1217 1218 // Project out 4 bits starting at 'digitIndex'. 1219 uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64]; 1220 hexDigit >>= (digitBitIndex % 64); 1221 hexDigit &= 0xF; 1222 1223 // Map that over to a lowercase hex digit. 1224 static const char charForHex[16] = { 1225 '0', '1', '2', '3', '4', '5', '6', '7', 1226 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 1227 }; 1228 buffer[stringIndex] = charForHex[hexDigit]; 1229 } 1230 1231 Out.write(buffer.data(), numCharacters); 1232 } 1233 1234 void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) { 1235 Out << 'L'; 1236 mangleType(T); 1237 mangleFloat(V); 1238 Out << 'E'; 1239 } 1240 1241 void CXXNameMangler::mangleFixedPointLiteral() { 1242 DiagnosticsEngine &Diags = Context.getDiags(); 1243 unsigned DiagID = Diags.getCustomDiagID( 1244 DiagnosticsEngine::Error, "cannot mangle fixed point literals yet"); 1245 Diags.Report(DiagID); 1246 } 1247 1248 void CXXNameMangler::mangleNullPointer(QualType T) { 1249 // <expr-primary> ::= L <type> 0 E 1250 Out << 'L'; 1251 mangleType(T); 1252 Out << "0E"; 1253 } 1254 1255 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) { 1256 if (Value.isSigned() && Value.isNegative()) { 1257 Out << 'n'; 1258 Value.abs().print(Out, /*signed*/ false); 1259 } else { 1260 Value.print(Out, /*signed*/ false); 1261 } 1262 } 1263 1264 void CXXNameMangler::mangleNumber(int64_t Number) { 1265 // <number> ::= [n] <non-negative decimal integer> 1266 if (Number < 0) { 1267 Out << 'n'; 1268 Number = -Number; 1269 } 1270 1271 Out << Number; 1272 } 1273 1274 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) { 1275 // <call-offset> ::= h <nv-offset> _ 1276 // ::= v <v-offset> _ 1277 // <nv-offset> ::= <offset number> # non-virtual base override 1278 // <v-offset> ::= <offset number> _ <virtual offset number> 1279 // # virtual base override, with vcall offset 1280 if (!Virtual) { 1281 Out << 'h'; 1282 mangleNumber(NonVirtual); 1283 Out << '_'; 1284 return; 1285 } 1286 1287 Out << 'v'; 1288 mangleNumber(NonVirtual); 1289 Out << '_'; 1290 mangleNumber(Virtual); 1291 Out << '_'; 1292 } 1293 1294 void CXXNameMangler::manglePrefix(QualType type) { 1295 if (const auto *TST = type->getAs<TemplateSpecializationType>()) { 1296 if (!mangleSubstitution(QualType(TST, 0))) { 1297 mangleTemplatePrefix(TST->getTemplateName()); 1298 1299 // FIXME: GCC does not appear to mangle the template arguments when 1300 // the template in question is a dependent template name. Should we 1301 // emulate that badness? 1302 mangleTemplateArgs(TST->getTemplateName(), TST->template_arguments()); 1303 addSubstitution(QualType(TST, 0)); 1304 } 1305 } else if (const auto *DTST = 1306 type->getAs<DependentTemplateSpecializationType>()) { 1307 if (!mangleSubstitution(QualType(DTST, 0))) { 1308 TemplateName Template = getASTContext().getDependentTemplateName( 1309 DTST->getQualifier(), DTST->getIdentifier()); 1310 mangleTemplatePrefix(Template); 1311 1312 // FIXME: GCC does not appear to mangle the template arguments when 1313 // the template in question is a dependent template name. Should we 1314 // emulate that badness? 1315 mangleTemplateArgs(Template, DTST->template_arguments()); 1316 addSubstitution(QualType(DTST, 0)); 1317 } 1318 } else { 1319 // We use the QualType mangle type variant here because it handles 1320 // substitutions. 1321 mangleType(type); 1322 } 1323 } 1324 1325 /// Mangle everything prior to the base-unresolved-name in an unresolved-name. 1326 /// 1327 /// \param recursive - true if this is being called recursively, 1328 /// i.e. if there is more prefix "to the right". 1329 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier, 1330 bool recursive) { 1331 1332 // x, ::x 1333 // <unresolved-name> ::= [gs] <base-unresolved-name> 1334 1335 // T::x / decltype(p)::x 1336 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name> 1337 1338 // T::N::x /decltype(p)::N::x 1339 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E 1340 // <base-unresolved-name> 1341 1342 // A::x, N::y, A<T>::z; "gs" means leading "::" 1343 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E 1344 // <base-unresolved-name> 1345 1346 switch (qualifier->getKind()) { 1347 case NestedNameSpecifier::Global: 1348 Out << "gs"; 1349 1350 // We want an 'sr' unless this is the entire NNS. 1351 if (recursive) 1352 Out << "sr"; 1353 1354 // We never want an 'E' here. 1355 return; 1356 1357 case NestedNameSpecifier::Super: 1358 llvm_unreachable("Can't mangle __super specifier"); 1359 1360 case NestedNameSpecifier::Namespace: 1361 if (qualifier->getPrefix()) 1362 mangleUnresolvedPrefix(qualifier->getPrefix(), 1363 /*recursive*/ true); 1364 else 1365 Out << "sr"; 1366 mangleSourceNameWithAbiTags(qualifier->getAsNamespace()); 1367 break; 1368 case NestedNameSpecifier::NamespaceAlias: 1369 if (qualifier->getPrefix()) 1370 mangleUnresolvedPrefix(qualifier->getPrefix(), 1371 /*recursive*/ true); 1372 else 1373 Out << "sr"; 1374 mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias()); 1375 break; 1376 1377 case NestedNameSpecifier::TypeSpec: 1378 case NestedNameSpecifier::TypeSpecWithTemplate: { 1379 const Type *type = qualifier->getAsType(); 1380 1381 // We only want to use an unresolved-type encoding if this is one of: 1382 // - a decltype 1383 // - a template type parameter 1384 // - a template template parameter with arguments 1385 // In all of these cases, we should have no prefix. 1386 if (qualifier->getPrefix()) { 1387 mangleUnresolvedPrefix(qualifier->getPrefix(), 1388 /*recursive*/ true); 1389 } else { 1390 // Otherwise, all the cases want this. 1391 Out << "sr"; 1392 } 1393 1394 if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : "")) 1395 return; 1396 1397 break; 1398 } 1399 1400 case NestedNameSpecifier::Identifier: 1401 // Member expressions can have these without prefixes. 1402 if (qualifier->getPrefix()) 1403 mangleUnresolvedPrefix(qualifier->getPrefix(), 1404 /*recursive*/ true); 1405 else 1406 Out << "sr"; 1407 1408 mangleSourceName(qualifier->getAsIdentifier()); 1409 // An Identifier has no type information, so we can't emit abi tags for it. 1410 break; 1411 } 1412 1413 // If this was the innermost part of the NNS, and we fell out to 1414 // here, append an 'E'. 1415 if (!recursive) 1416 Out << 'E'; 1417 } 1418 1419 /// Mangle an unresolved-name, which is generally used for names which 1420 /// weren't resolved to specific entities. 1421 void CXXNameMangler::mangleUnresolvedName( 1422 NestedNameSpecifier *qualifier, DeclarationName name, 1423 const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs, 1424 unsigned knownArity) { 1425 if (qualifier) mangleUnresolvedPrefix(qualifier); 1426 switch (name.getNameKind()) { 1427 // <base-unresolved-name> ::= <simple-id> 1428 case DeclarationName::Identifier: 1429 mangleSourceName(name.getAsIdentifierInfo()); 1430 break; 1431 // <base-unresolved-name> ::= dn <destructor-name> 1432 case DeclarationName::CXXDestructorName: 1433 Out << "dn"; 1434 mangleUnresolvedTypeOrSimpleId(name.getCXXNameType()); 1435 break; 1436 // <base-unresolved-name> ::= on <operator-name> 1437 case DeclarationName::CXXConversionFunctionName: 1438 case DeclarationName::CXXLiteralOperatorName: 1439 case DeclarationName::CXXOperatorName: 1440 Out << "on"; 1441 mangleOperatorName(name, knownArity); 1442 break; 1443 case DeclarationName::CXXConstructorName: 1444 llvm_unreachable("Can't mangle a constructor name!"); 1445 case DeclarationName::CXXUsingDirective: 1446 llvm_unreachable("Can't mangle a using directive name!"); 1447 case DeclarationName::CXXDeductionGuideName: 1448 llvm_unreachable("Can't mangle a deduction guide name!"); 1449 case DeclarationName::ObjCMultiArgSelector: 1450 case DeclarationName::ObjCOneArgSelector: 1451 case DeclarationName::ObjCZeroArgSelector: 1452 llvm_unreachable("Can't mangle Objective-C selector names here!"); 1453 } 1454 1455 // The <simple-id> and on <operator-name> productions end in an optional 1456 // <template-args>. 1457 if (TemplateArgs) 1458 mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs); 1459 } 1460 1461 void CXXNameMangler::mangleUnqualifiedName( 1462 GlobalDecl GD, DeclarationName Name, const DeclContext *DC, 1463 unsigned KnownArity, const AbiTagList *AdditionalAbiTags) { 1464 const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl()); 1465 // <unqualified-name> ::= [<module-name>] [F] <operator-name> 1466 // ::= <ctor-dtor-name> 1467 // ::= [<module-name>] [F] <source-name> 1468 // ::= [<module-name>] DC <source-name>* E 1469 1470 if (ND && DC && DC->isFileContext()) 1471 mangleModuleName(ND); 1472 1473 // A member-like constrained friend is mangled with a leading 'F'. 1474 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24. 1475 auto *FD = dyn_cast<FunctionDecl>(ND); 1476 auto *FTD = dyn_cast<FunctionTemplateDecl>(ND); 1477 if ((FD && FD->isMemberLikeConstrainedFriend()) || 1478 (FTD && FTD->getTemplatedDecl()->isMemberLikeConstrainedFriend())) { 1479 if (!isCompatibleWith(LangOptions::ClangABI::Ver17)) 1480 Out << 'F'; 1481 } 1482 1483 unsigned Arity = KnownArity; 1484 switch (Name.getNameKind()) { 1485 case DeclarationName::Identifier: { 1486 const IdentifierInfo *II = Name.getAsIdentifierInfo(); 1487 1488 // We mangle decomposition declarations as the names of their bindings. 1489 if (auto *DD = dyn_cast<DecompositionDecl>(ND)) { 1490 // FIXME: Non-standard mangling for decomposition declarations: 1491 // 1492 // <unqualified-name> ::= DC <source-name>* E 1493 // 1494 // Proposed on cxx-abi-dev on 2016-08-12 1495 Out << "DC"; 1496 for (auto *BD : DD->bindings()) 1497 mangleSourceName(BD->getDeclName().getAsIdentifierInfo()); 1498 Out << 'E'; 1499 writeAbiTags(ND, AdditionalAbiTags); 1500 break; 1501 } 1502 1503 if (auto *GD = dyn_cast<MSGuidDecl>(ND)) { 1504 // We follow MSVC in mangling GUID declarations as if they were variables 1505 // with a particular reserved name. Continue the pretense here. 1506 SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID; 1507 llvm::raw_svector_ostream GUIDOS(GUID); 1508 Context.mangleMSGuidDecl(GD, GUIDOS); 1509 Out << GUID.size() << GUID; 1510 break; 1511 } 1512 1513 if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) { 1514 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63. 1515 Out << "TA"; 1516 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(), 1517 TPO->getValue(), /*TopLevel=*/true); 1518 break; 1519 } 1520 1521 if (II) { 1522 // Match GCC's naming convention for internal linkage symbols, for 1523 // symbols that are not actually visible outside of this TU. GCC 1524 // distinguishes between internal and external linkage symbols in 1525 // its mangling, to support cases like this that were valid C++ prior 1526 // to DR426: 1527 // 1528 // void test() { extern void foo(); } 1529 // static void foo(); 1530 // 1531 // Don't bother with the L marker for names in anonymous namespaces; the 1532 // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better 1533 // matches GCC anyway, because GCC does not treat anonymous namespaces as 1534 // implying internal linkage. 1535 if (Context.isInternalLinkageDecl(ND)) 1536 Out << 'L'; 1537 1538 bool IsRegCall = FD && 1539 FD->getType()->castAs<FunctionType>()->getCallConv() == 1540 clang::CC_X86RegCall; 1541 bool IsDeviceStub = 1542 FD && FD->hasAttr<CUDAGlobalAttr>() && 1543 GD.getKernelReferenceKind() == KernelReferenceKind::Stub; 1544 if (IsDeviceStub) 1545 mangleDeviceStubName(II); 1546 else if (IsRegCall) 1547 mangleRegCallName(II); 1548 else 1549 mangleSourceName(II); 1550 1551 writeAbiTags(ND, AdditionalAbiTags); 1552 break; 1553 } 1554 1555 // Otherwise, an anonymous entity. We must have a declaration. 1556 assert(ND && "mangling empty name without declaration"); 1557 1558 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 1559 if (NS->isAnonymousNamespace()) { 1560 // This is how gcc mangles these names. 1561 Out << "12_GLOBAL__N_1"; 1562 break; 1563 } 1564 } 1565 1566 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 1567 // We must have an anonymous union or struct declaration. 1568 const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl(); 1569 1570 // Itanium C++ ABI 5.1.2: 1571 // 1572 // For the purposes of mangling, the name of an anonymous union is 1573 // considered to be the name of the first named data member found by a 1574 // pre-order, depth-first, declaration-order walk of the data members of 1575 // the anonymous union. If there is no such data member (i.e., if all of 1576 // the data members in the union are unnamed), then there is no way for 1577 // a program to refer to the anonymous union, and there is therefore no 1578 // need to mangle its name. 1579 assert(RD->isAnonymousStructOrUnion() 1580 && "Expected anonymous struct or union!"); 1581 const FieldDecl *FD = RD->findFirstNamedDataMember(); 1582 1583 // It's actually possible for various reasons for us to get here 1584 // with an empty anonymous struct / union. Fortunately, it 1585 // doesn't really matter what name we generate. 1586 if (!FD) break; 1587 assert(FD->getIdentifier() && "Data member name isn't an identifier!"); 1588 1589 mangleSourceName(FD->getIdentifier()); 1590 // Not emitting abi tags: internal name anyway. 1591 break; 1592 } 1593 1594 // Class extensions have no name as a category, and it's possible 1595 // for them to be the semantic parent of certain declarations 1596 // (primarily, tag decls defined within declarations). Such 1597 // declarations will always have internal linkage, so the name 1598 // doesn't really matter, but we shouldn't crash on them. For 1599 // safety, just handle all ObjC containers here. 1600 if (isa<ObjCContainerDecl>(ND)) 1601 break; 1602 1603 // We must have an anonymous struct. 1604 const TagDecl *TD = cast<TagDecl>(ND); 1605 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) { 1606 assert(TD->getDeclContext() == D->getDeclContext() && 1607 "Typedef should not be in another decl context!"); 1608 assert(D->getDeclName().getAsIdentifierInfo() && 1609 "Typedef was not named!"); 1610 mangleSourceName(D->getDeclName().getAsIdentifierInfo()); 1611 assert(!AdditionalAbiTags && "Type cannot have additional abi tags"); 1612 // Explicit abi tags are still possible; take from underlying type, not 1613 // from typedef. 1614 writeAbiTags(TD, nullptr); 1615 break; 1616 } 1617 1618 // <unnamed-type-name> ::= <closure-type-name> 1619 // 1620 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _ 1621 // <lambda-sig> ::= <template-param-decl>* <parameter-type>+ 1622 // # Parameter types or 'v' for 'void'. 1623 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) { 1624 std::optional<unsigned> DeviceNumber = 1625 Context.getDiscriminatorOverride()(Context.getASTContext(), Record); 1626 1627 // If we have a device-number via the discriminator, use that to mangle 1628 // the lambda, otherwise use the typical lambda-mangling-number. In either 1629 // case, a '0' should be mangled as a normal unnamed class instead of as a 1630 // lambda. 1631 if (Record->isLambda() && 1632 ((DeviceNumber && *DeviceNumber > 0) || 1633 (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) { 1634 assert(!AdditionalAbiTags && 1635 "Lambda type cannot have additional abi tags"); 1636 mangleLambda(Record); 1637 break; 1638 } 1639 } 1640 1641 if (TD->isExternallyVisible()) { 1642 unsigned UnnamedMangle = 1643 getASTContext().getManglingNumber(TD, Context.isAux()); 1644 Out << "Ut"; 1645 if (UnnamedMangle > 1) 1646 Out << UnnamedMangle - 2; 1647 Out << '_'; 1648 writeAbiTags(TD, AdditionalAbiTags); 1649 break; 1650 } 1651 1652 // Get a unique id for the anonymous struct. If it is not a real output 1653 // ID doesn't matter so use fake one. 1654 unsigned AnonStructId = 1655 NullOut ? 0 1656 : Context.getAnonymousStructId(TD, dyn_cast<FunctionDecl>(DC)); 1657 1658 // Mangle it as a source name in the form 1659 // [n] $_<id> 1660 // where n is the length of the string. 1661 SmallString<8> Str; 1662 Str += "$_"; 1663 Str += llvm::utostr(AnonStructId); 1664 1665 Out << Str.size(); 1666 Out << Str; 1667 break; 1668 } 1669 1670 case DeclarationName::ObjCZeroArgSelector: 1671 case DeclarationName::ObjCOneArgSelector: 1672 case DeclarationName::ObjCMultiArgSelector: 1673 llvm_unreachable("Can't mangle Objective-C selector names here!"); 1674 1675 case DeclarationName::CXXConstructorName: { 1676 const CXXRecordDecl *InheritedFrom = nullptr; 1677 TemplateName InheritedTemplateName; 1678 const TemplateArgumentList *InheritedTemplateArgs = nullptr; 1679 if (auto Inherited = 1680 cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) { 1681 InheritedFrom = Inherited.getConstructor()->getParent(); 1682 InheritedTemplateName = 1683 TemplateName(Inherited.getConstructor()->getPrimaryTemplate()); 1684 InheritedTemplateArgs = 1685 Inherited.getConstructor()->getTemplateSpecializationArgs(); 1686 } 1687 1688 if (ND == Structor) 1689 // If the named decl is the C++ constructor we're mangling, use the type 1690 // we were given. 1691 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom); 1692 else 1693 // Otherwise, use the complete constructor name. This is relevant if a 1694 // class with a constructor is declared within a constructor. 1695 mangleCXXCtorType(Ctor_Complete, InheritedFrom); 1696 1697 // FIXME: The template arguments are part of the enclosing prefix or 1698 // nested-name, but it's more convenient to mangle them here. 1699 if (InheritedTemplateArgs) 1700 mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs); 1701 1702 writeAbiTags(ND, AdditionalAbiTags); 1703 break; 1704 } 1705 1706 case DeclarationName::CXXDestructorName: 1707 if (ND == Structor) 1708 // If the named decl is the C++ destructor we're mangling, use the type we 1709 // were given. 1710 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType)); 1711 else 1712 // Otherwise, use the complete destructor name. This is relevant if a 1713 // class with a destructor is declared within a destructor. 1714 mangleCXXDtorType(Dtor_Complete); 1715 assert(ND); 1716 writeAbiTags(ND, AdditionalAbiTags); 1717 break; 1718 1719 case DeclarationName::CXXOperatorName: 1720 if (ND && Arity == UnknownArity) { 1721 Arity = cast<FunctionDecl>(ND)->getNumParams(); 1722 1723 // If we have a member function, we need to include the 'this' pointer. 1724 if (const auto *MD = dyn_cast<CXXMethodDecl>(ND)) 1725 if (MD->isImplicitObjectMemberFunction()) 1726 Arity++; 1727 } 1728 [[fallthrough]]; 1729 case DeclarationName::CXXConversionFunctionName: 1730 case DeclarationName::CXXLiteralOperatorName: 1731 mangleOperatorName(Name, Arity); 1732 writeAbiTags(ND, AdditionalAbiTags); 1733 break; 1734 1735 case DeclarationName::CXXDeductionGuideName: 1736 llvm_unreachable("Can't mangle a deduction guide name!"); 1737 1738 case DeclarationName::CXXUsingDirective: 1739 llvm_unreachable("Can't mangle a using directive name!"); 1740 } 1741 } 1742 1743 void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) { 1744 // <source-name> ::= <positive length number> __regcall3__ <identifier> 1745 // <number> ::= [n] <non-negative decimal integer> 1746 // <identifier> ::= <unqualified source code identifier> 1747 if (getASTContext().getLangOpts().RegCall4) 1748 Out << II->getLength() + sizeof("__regcall4__") - 1 << "__regcall4__" 1749 << II->getName(); 1750 else 1751 Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__" 1752 << II->getName(); 1753 } 1754 1755 void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) { 1756 // <source-name> ::= <positive length number> __device_stub__ <identifier> 1757 // <number> ::= [n] <non-negative decimal integer> 1758 // <identifier> ::= <unqualified source code identifier> 1759 Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__" 1760 << II->getName(); 1761 } 1762 1763 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) { 1764 // <source-name> ::= <positive length number> <identifier> 1765 // <number> ::= [n] <non-negative decimal integer> 1766 // <identifier> ::= <unqualified source code identifier> 1767 Out << II->getLength() << II->getName(); 1768 } 1769 1770 void CXXNameMangler::mangleNestedName(GlobalDecl GD, 1771 const DeclContext *DC, 1772 const AbiTagList *AdditionalAbiTags, 1773 bool NoFunction) { 1774 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl()); 1775 // <nested-name> 1776 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E 1777 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> 1778 // <template-args> E 1779 1780 Out << 'N'; 1781 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) { 1782 Qualifiers MethodQuals = Method->getMethodQualifiers(); 1783 // We do not consider restrict a distinguishing attribute for overloading 1784 // purposes so we must not mangle it. 1785 if (Method->isExplicitObjectMemberFunction()) 1786 Out << 'H'; 1787 MethodQuals.removeRestrict(); 1788 mangleQualifiers(MethodQuals); 1789 mangleRefQualifier(Method->getRefQualifier()); 1790 } 1791 1792 // Check if we have a template. 1793 const TemplateArgumentList *TemplateArgs = nullptr; 1794 if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) { 1795 mangleTemplatePrefix(TD, NoFunction); 1796 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); 1797 } else { 1798 manglePrefix(DC, NoFunction); 1799 mangleUnqualifiedName(GD, DC, AdditionalAbiTags); 1800 } 1801 1802 Out << 'E'; 1803 } 1804 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD, 1805 ArrayRef<TemplateArgument> Args) { 1806 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E 1807 1808 Out << 'N'; 1809 1810 mangleTemplatePrefix(TD); 1811 mangleTemplateArgs(asTemplateName(TD), Args); 1812 1813 Out << 'E'; 1814 } 1815 1816 void CXXNameMangler::mangleNestedNameWithClosurePrefix( 1817 GlobalDecl GD, const NamedDecl *PrefixND, 1818 const AbiTagList *AdditionalAbiTags) { 1819 // A <closure-prefix> represents a variable or field, not a regular 1820 // DeclContext, so needs special handling. In this case we're mangling a 1821 // limited form of <nested-name>: 1822 // 1823 // <nested-name> ::= N <closure-prefix> <closure-type-name> E 1824 1825 Out << 'N'; 1826 1827 mangleClosurePrefix(PrefixND); 1828 mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags); 1829 1830 Out << 'E'; 1831 } 1832 1833 static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) { 1834 GlobalDecl GD; 1835 // The Itanium spec says: 1836 // For entities in constructors and destructors, the mangling of the 1837 // complete object constructor or destructor is used as the base function 1838 // name, i.e. the C1 or D1 version. 1839 if (auto *CD = dyn_cast<CXXConstructorDecl>(DC)) 1840 GD = GlobalDecl(CD, Ctor_Complete); 1841 else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC)) 1842 GD = GlobalDecl(DD, Dtor_Complete); 1843 else 1844 GD = GlobalDecl(cast<FunctionDecl>(DC)); 1845 return GD; 1846 } 1847 1848 void CXXNameMangler::mangleLocalName(GlobalDecl GD, 1849 const AbiTagList *AdditionalAbiTags) { 1850 const Decl *D = GD.getDecl(); 1851 // <local-name> := Z <function encoding> E <entity name> [<discriminator>] 1852 // := Z <function encoding> E s [<discriminator>] 1853 // <local-name> := Z <function encoding> E d [ <parameter number> ] 1854 // _ <entity name> 1855 // <discriminator> := _ <non-negative number> 1856 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D)); 1857 const RecordDecl *RD = GetLocalClassDecl(D); 1858 const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D); 1859 1860 Out << 'Z'; 1861 1862 { 1863 AbiTagState LocalAbiTags(AbiTags); 1864 1865 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC)) 1866 mangleObjCMethodName(MD); 1867 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) 1868 mangleBlockForPrefix(BD); 1869 else 1870 mangleFunctionEncoding(getParentOfLocalEntity(DC)); 1871 1872 // Implicit ABI tags (from namespace) are not available in the following 1873 // entity; reset to actually emitted tags, which are available. 1874 LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags()); 1875 } 1876 1877 Out << 'E'; 1878 1879 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to 1880 // be a bug that is fixed in trunk. 1881 1882 if (RD) { 1883 // The parameter number is omitted for the last parameter, 0 for the 1884 // second-to-last parameter, 1 for the third-to-last parameter, etc. The 1885 // <entity name> will of course contain a <closure-type-name>: Its 1886 // numbering will be local to the particular argument in which it appears 1887 // -- other default arguments do not affect its encoding. 1888 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD); 1889 if (CXXRD && CXXRD->isLambda()) { 1890 if (const ParmVarDecl *Parm 1891 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) { 1892 if (const FunctionDecl *Func 1893 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) { 1894 Out << 'd'; 1895 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex(); 1896 if (Num > 1) 1897 mangleNumber(Num - 2); 1898 Out << '_'; 1899 } 1900 } 1901 } 1902 1903 // Mangle the name relative to the closest enclosing function. 1904 // equality ok because RD derived from ND above 1905 if (D == RD) { 1906 mangleUnqualifiedName(RD, DC, AdditionalAbiTags); 1907 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 1908 if (const NamedDecl *PrefixND = getClosurePrefix(BD)) 1909 mangleClosurePrefix(PrefixND, true /*NoFunction*/); 1910 else 1911 manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/); 1912 assert(!AdditionalAbiTags && "Block cannot have additional abi tags"); 1913 mangleUnqualifiedBlock(BD); 1914 } else { 1915 const NamedDecl *ND = cast<NamedDecl>(D); 1916 mangleNestedName(GD, Context.getEffectiveDeclContext(ND), 1917 AdditionalAbiTags, true /*NoFunction*/); 1918 } 1919 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 1920 // Mangle a block in a default parameter; see above explanation for 1921 // lambdas. 1922 if (const ParmVarDecl *Parm 1923 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) { 1924 if (const FunctionDecl *Func 1925 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) { 1926 Out << 'd'; 1927 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex(); 1928 if (Num > 1) 1929 mangleNumber(Num - 2); 1930 Out << '_'; 1931 } 1932 } 1933 1934 assert(!AdditionalAbiTags && "Block cannot have additional abi tags"); 1935 mangleUnqualifiedBlock(BD); 1936 } else { 1937 mangleUnqualifiedName(GD, DC, AdditionalAbiTags); 1938 } 1939 1940 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) { 1941 unsigned disc; 1942 if (Context.getNextDiscriminator(ND, disc)) { 1943 if (disc < 10) 1944 Out << '_' << disc; 1945 else 1946 Out << "__" << disc << '_'; 1947 } 1948 } 1949 } 1950 1951 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) { 1952 if (GetLocalClassDecl(Block)) { 1953 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr); 1954 return; 1955 } 1956 const DeclContext *DC = Context.getEffectiveDeclContext(Block); 1957 if (isLocalContainerContext(DC)) { 1958 mangleLocalName(Block, /* AdditionalAbiTags */ nullptr); 1959 return; 1960 } 1961 if (const NamedDecl *PrefixND = getClosurePrefix(Block)) 1962 mangleClosurePrefix(PrefixND); 1963 else 1964 manglePrefix(DC); 1965 mangleUnqualifiedBlock(Block); 1966 } 1967 1968 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) { 1969 // When trying to be ABI-compatibility with clang 12 and before, mangle a 1970 // <data-member-prefix> now, with no substitutions and no <template-args>. 1971 if (Decl *Context = Block->getBlockManglingContextDecl()) { 1972 if (isCompatibleWith(LangOptions::ClangABI::Ver12) && 1973 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) && 1974 Context->getDeclContext()->isRecord()) { 1975 const auto *ND = cast<NamedDecl>(Context); 1976 if (ND->getIdentifier()) { 1977 mangleSourceNameWithAbiTags(ND); 1978 Out << 'M'; 1979 } 1980 } 1981 } 1982 1983 // If we have a block mangling number, use it. 1984 unsigned Number = Block->getBlockManglingNumber(); 1985 // Otherwise, just make up a number. It doesn't matter what it is because 1986 // the symbol in question isn't externally visible. 1987 if (!Number) 1988 Number = Context.getBlockId(Block, false); 1989 else { 1990 // Stored mangling numbers are 1-based. 1991 --Number; 1992 } 1993 Out << "Ub"; 1994 if (Number > 0) 1995 Out << Number - 1; 1996 Out << '_'; 1997 } 1998 1999 // <template-param-decl> 2000 // ::= Ty # template type parameter 2001 // ::= Tk <concept name> [<template-args>] # constrained type parameter 2002 // ::= Tn <type> # template non-type parameter 2003 // ::= Tt <template-param-decl>* E [Q <requires-clause expr>] 2004 // # template template parameter 2005 // ::= Tp <template-param-decl> # template parameter pack 2006 void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) { 2007 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47. 2008 if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) { 2009 if (Ty->isParameterPack()) 2010 Out << "Tp"; 2011 const TypeConstraint *Constraint = Ty->getTypeConstraint(); 2012 if (Constraint && !isCompatibleWith(LangOptions::ClangABI::Ver17)) { 2013 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24. 2014 Out << "Tk"; 2015 mangleTypeConstraint(Constraint); 2016 } else { 2017 Out << "Ty"; 2018 } 2019 } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) { 2020 if (Tn->isExpandedParameterPack()) { 2021 for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) { 2022 Out << "Tn"; 2023 mangleType(Tn->getExpansionType(I)); 2024 } 2025 } else { 2026 QualType T = Tn->getType(); 2027 if (Tn->isParameterPack()) { 2028 Out << "Tp"; 2029 if (auto *PackExpansion = T->getAs<PackExpansionType>()) 2030 T = PackExpansion->getPattern(); 2031 } 2032 Out << "Tn"; 2033 mangleType(T); 2034 } 2035 } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) { 2036 if (Tt->isExpandedParameterPack()) { 2037 for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N; 2038 ++I) 2039 mangleTemplateParameterList(Tt->getExpansionTemplateParameters(I)); 2040 } else { 2041 if (Tt->isParameterPack()) 2042 Out << "Tp"; 2043 mangleTemplateParameterList(Tt->getTemplateParameters()); 2044 } 2045 } 2046 } 2047 2048 void CXXNameMangler::mangleTemplateParameterList( 2049 const TemplateParameterList *Params) { 2050 Out << "Tt"; 2051 for (auto *Param : *Params) 2052 mangleTemplateParamDecl(Param); 2053 mangleRequiresClause(Params->getRequiresClause()); 2054 Out << "E"; 2055 } 2056 2057 void CXXNameMangler::mangleTypeConstraint( 2058 const ConceptDecl *Concept, ArrayRef<TemplateArgument> Arguments) { 2059 const DeclContext *DC = Context.getEffectiveDeclContext(Concept); 2060 if (!Arguments.empty()) 2061 mangleTemplateName(Concept, Arguments); 2062 else if (DC->isTranslationUnit() || isStdNamespace(DC)) 2063 mangleUnscopedName(Concept, DC, nullptr); 2064 else 2065 mangleNestedName(Concept, DC, nullptr); 2066 } 2067 2068 void CXXNameMangler::mangleTypeConstraint(const TypeConstraint *Constraint) { 2069 llvm::SmallVector<TemplateArgument, 8> Args; 2070 if (Constraint->getTemplateArgsAsWritten()) { 2071 for (const TemplateArgumentLoc &ArgLoc : 2072 Constraint->getTemplateArgsAsWritten()->arguments()) 2073 Args.push_back(ArgLoc.getArgument()); 2074 } 2075 return mangleTypeConstraint(Constraint->getNamedConcept(), Args); 2076 } 2077 2078 void CXXNameMangler::mangleRequiresClause(const Expr *RequiresClause) { 2079 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24. 2080 if (RequiresClause && !isCompatibleWith(LangOptions::ClangABI::Ver17)) { 2081 Out << 'Q'; 2082 mangleExpression(RequiresClause); 2083 } 2084 } 2085 2086 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { 2087 // When trying to be ABI-compatibility with clang 12 and before, mangle a 2088 // <data-member-prefix> now, with no substitutions. 2089 if (Decl *Context = Lambda->getLambdaContextDecl()) { 2090 if (isCompatibleWith(LangOptions::ClangABI::Ver12) && 2091 (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) && 2092 !isa<ParmVarDecl>(Context)) { 2093 if (const IdentifierInfo *Name 2094 = cast<NamedDecl>(Context)->getIdentifier()) { 2095 mangleSourceName(Name); 2096 const TemplateArgumentList *TemplateArgs = nullptr; 2097 if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs)) 2098 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); 2099 Out << 'M'; 2100 } 2101 } 2102 } 2103 2104 Out << "Ul"; 2105 mangleLambdaSig(Lambda); 2106 Out << "E"; 2107 2108 // The number is omitted for the first closure type with a given 2109 // <lambda-sig> in a given context; it is n-2 for the nth closure type 2110 // (in lexical order) with that same <lambda-sig> and context. 2111 // 2112 // The AST keeps track of the number for us. 2113 // 2114 // In CUDA/HIP, to ensure the consistent lamba numbering between the device- 2115 // and host-side compilations, an extra device mangle context may be created 2116 // if the host-side CXX ABI has different numbering for lambda. In such case, 2117 // if the mangle context is that device-side one, use the device-side lambda 2118 // mangling number for this lambda. 2119 std::optional<unsigned> DeviceNumber = 2120 Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda); 2121 unsigned Number = 2122 DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber(); 2123 2124 assert(Number > 0 && "Lambda should be mangled as an unnamed class"); 2125 if (Number > 1) 2126 mangleNumber(Number - 2); 2127 Out << '_'; 2128 } 2129 2130 void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) { 2131 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/31. 2132 for (auto *D : Lambda->getLambdaExplicitTemplateParameters()) 2133 mangleTemplateParamDecl(D); 2134 2135 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24. 2136 if (auto *TPL = Lambda->getGenericLambdaTemplateParameterList()) 2137 mangleRequiresClause(TPL->getRequiresClause()); 2138 2139 auto *Proto = 2140 Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>(); 2141 mangleBareFunctionType(Proto, /*MangleReturnType=*/false, 2142 Lambda->getLambdaStaticInvoker()); 2143 } 2144 2145 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) { 2146 switch (qualifier->getKind()) { 2147 case NestedNameSpecifier::Global: 2148 // nothing 2149 return; 2150 2151 case NestedNameSpecifier::Super: 2152 llvm_unreachable("Can't mangle __super specifier"); 2153 2154 case NestedNameSpecifier::Namespace: 2155 mangleName(qualifier->getAsNamespace()); 2156 return; 2157 2158 case NestedNameSpecifier::NamespaceAlias: 2159 mangleName(qualifier->getAsNamespaceAlias()->getNamespace()); 2160 return; 2161 2162 case NestedNameSpecifier::TypeSpec: 2163 case NestedNameSpecifier::TypeSpecWithTemplate: 2164 manglePrefix(QualType(qualifier->getAsType(), 0)); 2165 return; 2166 2167 case NestedNameSpecifier::Identifier: 2168 // Clang 14 and before did not consider this substitutable. 2169 bool Clang14Compat = isCompatibleWith(LangOptions::ClangABI::Ver14); 2170 if (!Clang14Compat && mangleSubstitution(qualifier)) 2171 return; 2172 2173 // Member expressions can have these without prefixes, but that 2174 // should end up in mangleUnresolvedPrefix instead. 2175 assert(qualifier->getPrefix()); 2176 manglePrefix(qualifier->getPrefix()); 2177 2178 mangleSourceName(qualifier->getAsIdentifier()); 2179 2180 if (!Clang14Compat) 2181 addSubstitution(qualifier); 2182 return; 2183 } 2184 2185 llvm_unreachable("unexpected nested name specifier"); 2186 } 2187 2188 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) { 2189 // <prefix> ::= <prefix> <unqualified-name> 2190 // ::= <template-prefix> <template-args> 2191 // ::= <closure-prefix> 2192 // ::= <template-param> 2193 // ::= # empty 2194 // ::= <substitution> 2195 2196 assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl"); 2197 2198 if (DC->isTranslationUnit()) 2199 return; 2200 2201 if (NoFunction && isLocalContainerContext(DC)) 2202 return; 2203 2204 assert(!isLocalContainerContext(DC)); 2205 2206 const NamedDecl *ND = cast<NamedDecl>(DC); 2207 if (mangleSubstitution(ND)) 2208 return; 2209 2210 // Check if we have a template-prefix or a closure-prefix. 2211 const TemplateArgumentList *TemplateArgs = nullptr; 2212 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) { 2213 mangleTemplatePrefix(TD); 2214 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); 2215 } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) { 2216 mangleClosurePrefix(PrefixND, NoFunction); 2217 mangleUnqualifiedName(ND, nullptr, nullptr); 2218 } else { 2219 const DeclContext *DC = Context.getEffectiveDeclContext(ND); 2220 manglePrefix(DC, NoFunction); 2221 mangleUnqualifiedName(ND, DC, nullptr); 2222 } 2223 2224 addSubstitution(ND); 2225 } 2226 2227 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) { 2228 // <template-prefix> ::= <prefix> <template unqualified-name> 2229 // ::= <template-param> 2230 // ::= <substitution> 2231 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 2232 return mangleTemplatePrefix(TD); 2233 2234 DependentTemplateName *Dependent = Template.getAsDependentTemplateName(); 2235 assert(Dependent && "unexpected template name kind"); 2236 2237 // Clang 11 and before mangled the substitution for a dependent template name 2238 // after already having emitted (a substitution for) the prefix. 2239 bool Clang11Compat = isCompatibleWith(LangOptions::ClangABI::Ver11); 2240 if (!Clang11Compat && mangleSubstitution(Template)) 2241 return; 2242 2243 if (NestedNameSpecifier *Qualifier = Dependent->getQualifier()) 2244 manglePrefix(Qualifier); 2245 2246 if (Clang11Compat && mangleSubstitution(Template)) 2247 return; 2248 2249 if (const IdentifierInfo *Id = Dependent->getIdentifier()) 2250 mangleSourceName(Id); 2251 else 2252 mangleOperatorName(Dependent->getOperator(), UnknownArity); 2253 2254 addSubstitution(Template); 2255 } 2256 2257 void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD, 2258 bool NoFunction) { 2259 const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl()); 2260 // <template-prefix> ::= <prefix> <template unqualified-name> 2261 // ::= <template-param> 2262 // ::= <substitution> 2263 // <template-template-param> ::= <template-param> 2264 // <substitution> 2265 2266 if (mangleSubstitution(ND)) 2267 return; 2268 2269 // <template-template-param> ::= <template-param> 2270 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) { 2271 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 2272 } else { 2273 const DeclContext *DC = Context.getEffectiveDeclContext(ND); 2274 manglePrefix(DC, NoFunction); 2275 if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) 2276 mangleUnqualifiedName(GD, DC, nullptr); 2277 else 2278 mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC, 2279 nullptr); 2280 } 2281 2282 addSubstitution(ND); 2283 } 2284 2285 const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) { 2286 if (isCompatibleWith(LangOptions::ClangABI::Ver12)) 2287 return nullptr; 2288 2289 const NamedDecl *Context = nullptr; 2290 if (auto *Block = dyn_cast<BlockDecl>(ND)) { 2291 Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl()); 2292 } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) { 2293 if (RD->isLambda()) 2294 Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl()); 2295 } 2296 if (!Context) 2297 return nullptr; 2298 2299 // Only lambdas within the initializer of a non-local variable or non-static 2300 // data member get a <closure-prefix>. 2301 if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) || 2302 isa<FieldDecl>(Context)) 2303 return Context; 2304 2305 return nullptr; 2306 } 2307 2308 void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) { 2309 // <closure-prefix> ::= [ <prefix> ] <unqualified-name> M 2310 // ::= <template-prefix> <template-args> M 2311 if (mangleSubstitution(ND)) 2312 return; 2313 2314 const TemplateArgumentList *TemplateArgs = nullptr; 2315 if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) { 2316 mangleTemplatePrefix(TD, NoFunction); 2317 mangleTemplateArgs(asTemplateName(TD), *TemplateArgs); 2318 } else { 2319 const auto *DC = Context.getEffectiveDeclContext(ND); 2320 manglePrefix(DC, NoFunction); 2321 mangleUnqualifiedName(ND, DC, nullptr); 2322 } 2323 2324 Out << 'M'; 2325 2326 addSubstitution(ND); 2327 } 2328 2329 /// Mangles a template name under the production <type>. Required for 2330 /// template template arguments. 2331 /// <type> ::= <class-enum-type> 2332 /// ::= <template-param> 2333 /// ::= <substitution> 2334 void CXXNameMangler::mangleType(TemplateName TN) { 2335 if (mangleSubstitution(TN)) 2336 return; 2337 2338 TemplateDecl *TD = nullptr; 2339 2340 switch (TN.getKind()) { 2341 case TemplateName::QualifiedTemplate: 2342 case TemplateName::UsingTemplate: 2343 case TemplateName::Template: 2344 TD = TN.getAsTemplateDecl(); 2345 goto HaveDecl; 2346 2347 HaveDecl: 2348 if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD)) 2349 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 2350 else 2351 mangleName(TD); 2352 break; 2353 2354 case TemplateName::OverloadedTemplate: 2355 case TemplateName::AssumedTemplate: 2356 llvm_unreachable("can't mangle an overloaded template name as a <type>"); 2357 2358 case TemplateName::DependentTemplate: { 2359 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName(); 2360 assert(Dependent->isIdentifier()); 2361 2362 // <class-enum-type> ::= <name> 2363 // <name> ::= <nested-name> 2364 mangleUnresolvedPrefix(Dependent->getQualifier()); 2365 mangleSourceName(Dependent->getIdentifier()); 2366 break; 2367 } 2368 2369 case TemplateName::SubstTemplateTemplateParm: { 2370 // Substituted template parameters are mangled as the substituted 2371 // template. This will check for the substitution twice, which is 2372 // fine, but we have to return early so that we don't try to *add* 2373 // the substitution twice. 2374 SubstTemplateTemplateParmStorage *subst 2375 = TN.getAsSubstTemplateTemplateParm(); 2376 mangleType(subst->getReplacement()); 2377 return; 2378 } 2379 2380 case TemplateName::SubstTemplateTemplateParmPack: { 2381 // FIXME: not clear how to mangle this! 2382 // template <template <class> class T...> class A { 2383 // template <template <class> class U...> void foo(B<T,U> x...); 2384 // }; 2385 Out << "_SUBSTPACK_"; 2386 break; 2387 } 2388 } 2389 2390 addSubstitution(TN); 2391 } 2392 2393 bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty, 2394 StringRef Prefix) { 2395 // Only certain other types are valid as prefixes; enumerate them. 2396 switch (Ty->getTypeClass()) { 2397 case Type::Builtin: 2398 case Type::Complex: 2399 case Type::Adjusted: 2400 case Type::Decayed: 2401 case Type::Pointer: 2402 case Type::BlockPointer: 2403 case Type::LValueReference: 2404 case Type::RValueReference: 2405 case Type::MemberPointer: 2406 case Type::ConstantArray: 2407 case Type::IncompleteArray: 2408 case Type::VariableArray: 2409 case Type::DependentSizedArray: 2410 case Type::DependentAddressSpace: 2411 case Type::DependentVector: 2412 case Type::DependentSizedExtVector: 2413 case Type::Vector: 2414 case Type::ExtVector: 2415 case Type::ConstantMatrix: 2416 case Type::DependentSizedMatrix: 2417 case Type::FunctionProto: 2418 case Type::FunctionNoProto: 2419 case Type::Paren: 2420 case Type::Attributed: 2421 case Type::BTFTagAttributed: 2422 case Type::Auto: 2423 case Type::DeducedTemplateSpecialization: 2424 case Type::PackExpansion: 2425 case Type::ObjCObject: 2426 case Type::ObjCInterface: 2427 case Type::ObjCObjectPointer: 2428 case Type::ObjCTypeParam: 2429 case Type::Atomic: 2430 case Type::Pipe: 2431 case Type::MacroQualified: 2432 case Type::BitInt: 2433 case Type::DependentBitInt: 2434 llvm_unreachable("type is illegal as a nested name specifier"); 2435 2436 case Type::SubstTemplateTypeParmPack: 2437 // FIXME: not clear how to mangle this! 2438 // template <class T...> class A { 2439 // template <class U...> void foo(decltype(T::foo(U())) x...); 2440 // }; 2441 Out << "_SUBSTPACK_"; 2442 break; 2443 2444 // <unresolved-type> ::= <template-param> 2445 // ::= <decltype> 2446 // ::= <template-template-param> <template-args> 2447 // (this last is not official yet) 2448 case Type::TypeOfExpr: 2449 case Type::TypeOf: 2450 case Type::Decltype: 2451 case Type::TemplateTypeParm: 2452 case Type::UnaryTransform: 2453 case Type::SubstTemplateTypeParm: 2454 unresolvedType: 2455 // Some callers want a prefix before the mangled type. 2456 Out << Prefix; 2457 2458 // This seems to do everything we want. It's not really 2459 // sanctioned for a substituted template parameter, though. 2460 mangleType(Ty); 2461 2462 // We never want to print 'E' directly after an unresolved-type, 2463 // so we return directly. 2464 return true; 2465 2466 case Type::Typedef: 2467 mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl()); 2468 break; 2469 2470 case Type::UnresolvedUsing: 2471 mangleSourceNameWithAbiTags( 2472 cast<UnresolvedUsingType>(Ty)->getDecl()); 2473 break; 2474 2475 case Type::Enum: 2476 case Type::Record: 2477 mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl()); 2478 break; 2479 2480 case Type::TemplateSpecialization: { 2481 const TemplateSpecializationType *TST = 2482 cast<TemplateSpecializationType>(Ty); 2483 TemplateName TN = TST->getTemplateName(); 2484 switch (TN.getKind()) { 2485 case TemplateName::Template: 2486 case TemplateName::QualifiedTemplate: { 2487 TemplateDecl *TD = TN.getAsTemplateDecl(); 2488 2489 // If the base is a template template parameter, this is an 2490 // unresolved type. 2491 assert(TD && "no template for template specialization type"); 2492 if (isa<TemplateTemplateParmDecl>(TD)) 2493 goto unresolvedType; 2494 2495 mangleSourceNameWithAbiTags(TD); 2496 break; 2497 } 2498 2499 case TemplateName::OverloadedTemplate: 2500 case TemplateName::AssumedTemplate: 2501 case TemplateName::DependentTemplate: 2502 llvm_unreachable("invalid base for a template specialization type"); 2503 2504 case TemplateName::SubstTemplateTemplateParm: { 2505 SubstTemplateTemplateParmStorage *subst = 2506 TN.getAsSubstTemplateTemplateParm(); 2507 mangleExistingSubstitution(subst->getReplacement()); 2508 break; 2509 } 2510 2511 case TemplateName::SubstTemplateTemplateParmPack: { 2512 // FIXME: not clear how to mangle this! 2513 // template <template <class U> class T...> class A { 2514 // template <class U...> void foo(decltype(T<U>::foo) x...); 2515 // }; 2516 Out << "_SUBSTPACK_"; 2517 break; 2518 } 2519 case TemplateName::UsingTemplate: { 2520 TemplateDecl *TD = TN.getAsTemplateDecl(); 2521 assert(TD && !isa<TemplateTemplateParmDecl>(TD)); 2522 mangleSourceNameWithAbiTags(TD); 2523 break; 2524 } 2525 } 2526 2527 // Note: we don't pass in the template name here. We are mangling the 2528 // original source-level template arguments, so we shouldn't consider 2529 // conversions to the corresponding template parameter. 2530 // FIXME: Other compilers mangle partially-resolved template arguments in 2531 // unresolved-qualifier-levels. 2532 mangleTemplateArgs(TemplateName(), TST->template_arguments()); 2533 break; 2534 } 2535 2536 case Type::InjectedClassName: 2537 mangleSourceNameWithAbiTags( 2538 cast<InjectedClassNameType>(Ty)->getDecl()); 2539 break; 2540 2541 case Type::DependentName: 2542 mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier()); 2543 break; 2544 2545 case Type::DependentTemplateSpecialization: { 2546 const DependentTemplateSpecializationType *DTST = 2547 cast<DependentTemplateSpecializationType>(Ty); 2548 TemplateName Template = getASTContext().getDependentTemplateName( 2549 DTST->getQualifier(), DTST->getIdentifier()); 2550 mangleSourceName(DTST->getIdentifier()); 2551 mangleTemplateArgs(Template, DTST->template_arguments()); 2552 break; 2553 } 2554 2555 case Type::Using: 2556 return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(), 2557 Prefix); 2558 case Type::Elaborated: 2559 return mangleUnresolvedTypeOrSimpleId( 2560 cast<ElaboratedType>(Ty)->getNamedType(), Prefix); 2561 } 2562 2563 return false; 2564 } 2565 2566 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) { 2567 switch (Name.getNameKind()) { 2568 case DeclarationName::CXXConstructorName: 2569 case DeclarationName::CXXDestructorName: 2570 case DeclarationName::CXXDeductionGuideName: 2571 case DeclarationName::CXXUsingDirective: 2572 case DeclarationName::Identifier: 2573 case DeclarationName::ObjCMultiArgSelector: 2574 case DeclarationName::ObjCOneArgSelector: 2575 case DeclarationName::ObjCZeroArgSelector: 2576 llvm_unreachable("Not an operator name"); 2577 2578 case DeclarationName::CXXConversionFunctionName: 2579 // <operator-name> ::= cv <type> # (cast) 2580 Out << "cv"; 2581 mangleType(Name.getCXXNameType()); 2582 break; 2583 2584 case DeclarationName::CXXLiteralOperatorName: 2585 Out << "li"; 2586 mangleSourceName(Name.getCXXLiteralIdentifier()); 2587 return; 2588 2589 case DeclarationName::CXXOperatorName: 2590 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity); 2591 break; 2592 } 2593 } 2594 2595 void 2596 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) { 2597 switch (OO) { 2598 // <operator-name> ::= nw # new 2599 case OO_New: Out << "nw"; break; 2600 // ::= na # new[] 2601 case OO_Array_New: Out << "na"; break; 2602 // ::= dl # delete 2603 case OO_Delete: Out << "dl"; break; 2604 // ::= da # delete[] 2605 case OO_Array_Delete: Out << "da"; break; 2606 // ::= ps # + (unary) 2607 // ::= pl # + (binary or unknown) 2608 case OO_Plus: 2609 Out << (Arity == 1? "ps" : "pl"); break; 2610 // ::= ng # - (unary) 2611 // ::= mi # - (binary or unknown) 2612 case OO_Minus: 2613 Out << (Arity == 1? "ng" : "mi"); break; 2614 // ::= ad # & (unary) 2615 // ::= an # & (binary or unknown) 2616 case OO_Amp: 2617 Out << (Arity == 1? "ad" : "an"); break; 2618 // ::= de # * (unary) 2619 // ::= ml # * (binary or unknown) 2620 case OO_Star: 2621 // Use binary when unknown. 2622 Out << (Arity == 1? "de" : "ml"); break; 2623 // ::= co # ~ 2624 case OO_Tilde: Out << "co"; break; 2625 // ::= dv # / 2626 case OO_Slash: Out << "dv"; break; 2627 // ::= rm # % 2628 case OO_Percent: Out << "rm"; break; 2629 // ::= or # | 2630 case OO_Pipe: Out << "or"; break; 2631 // ::= eo # ^ 2632 case OO_Caret: Out << "eo"; break; 2633 // ::= aS # = 2634 case OO_Equal: Out << "aS"; break; 2635 // ::= pL # += 2636 case OO_PlusEqual: Out << "pL"; break; 2637 // ::= mI # -= 2638 case OO_MinusEqual: Out << "mI"; break; 2639 // ::= mL # *= 2640 case OO_StarEqual: Out << "mL"; break; 2641 // ::= dV # /= 2642 case OO_SlashEqual: Out << "dV"; break; 2643 // ::= rM # %= 2644 case OO_PercentEqual: Out << "rM"; break; 2645 // ::= aN # &= 2646 case OO_AmpEqual: Out << "aN"; break; 2647 // ::= oR # |= 2648 case OO_PipeEqual: Out << "oR"; break; 2649 // ::= eO # ^= 2650 case OO_CaretEqual: Out << "eO"; break; 2651 // ::= ls # << 2652 case OO_LessLess: Out << "ls"; break; 2653 // ::= rs # >> 2654 case OO_GreaterGreater: Out << "rs"; break; 2655 // ::= lS # <<= 2656 case OO_LessLessEqual: Out << "lS"; break; 2657 // ::= rS # >>= 2658 case OO_GreaterGreaterEqual: Out << "rS"; break; 2659 // ::= eq # == 2660 case OO_EqualEqual: Out << "eq"; break; 2661 // ::= ne # != 2662 case OO_ExclaimEqual: Out << "ne"; break; 2663 // ::= lt # < 2664 case OO_Less: Out << "lt"; break; 2665 // ::= gt # > 2666 case OO_Greater: Out << "gt"; break; 2667 // ::= le # <= 2668 case OO_LessEqual: Out << "le"; break; 2669 // ::= ge # >= 2670 case OO_GreaterEqual: Out << "ge"; break; 2671 // ::= nt # ! 2672 case OO_Exclaim: Out << "nt"; break; 2673 // ::= aa # && 2674 case OO_AmpAmp: Out << "aa"; break; 2675 // ::= oo # || 2676 case OO_PipePipe: Out << "oo"; break; 2677 // ::= pp # ++ 2678 case OO_PlusPlus: Out << "pp"; break; 2679 // ::= mm # -- 2680 case OO_MinusMinus: Out << "mm"; break; 2681 // ::= cm # , 2682 case OO_Comma: Out << "cm"; break; 2683 // ::= pm # ->* 2684 case OO_ArrowStar: Out << "pm"; break; 2685 // ::= pt # -> 2686 case OO_Arrow: Out << "pt"; break; 2687 // ::= cl # () 2688 case OO_Call: Out << "cl"; break; 2689 // ::= ix # [] 2690 case OO_Subscript: Out << "ix"; break; 2691 2692 // ::= qu # ? 2693 // The conditional operator can't be overloaded, but we still handle it when 2694 // mangling expressions. 2695 case OO_Conditional: Out << "qu"; break; 2696 // Proposal on cxx-abi-dev, 2015-10-21. 2697 // ::= aw # co_await 2698 case OO_Coawait: Out << "aw"; break; 2699 // Proposed in cxx-abi github issue 43. 2700 // ::= ss # <=> 2701 case OO_Spaceship: Out << "ss"; break; 2702 2703 case OO_None: 2704 case NUM_OVERLOADED_OPERATORS: 2705 llvm_unreachable("Not an overloaded operator"); 2706 } 2707 } 2708 2709 void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) { 2710 // Vendor qualifiers come first and if they are order-insensitive they must 2711 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5. 2712 2713 // <type> ::= U <addrspace-expr> 2714 if (DAST) { 2715 Out << "U2ASI"; 2716 mangleExpression(DAST->getAddrSpaceExpr()); 2717 Out << "E"; 2718 } 2719 2720 // Address space qualifiers start with an ordinary letter. 2721 if (Quals.hasAddressSpace()) { 2722 // Address space extension: 2723 // 2724 // <type> ::= U <target-addrspace> 2725 // <type> ::= U <OpenCL-addrspace> 2726 // <type> ::= U <CUDA-addrspace> 2727 2728 SmallString<64> ASString; 2729 LangAS AS = Quals.getAddressSpace(); 2730 2731 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) { 2732 // <target-addrspace> ::= "AS" <address-space-number> 2733 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS); 2734 if (TargetAS != 0 || 2735 Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0) 2736 ASString = "AS" + llvm::utostr(TargetAS); 2737 } else { 2738 switch (AS) { 2739 default: llvm_unreachable("Not a language specific address space"); 2740 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" | 2741 // "private"| "generic" | "device" | 2742 // "host" ] 2743 case LangAS::opencl_global: 2744 ASString = "CLglobal"; 2745 break; 2746 case LangAS::opencl_global_device: 2747 ASString = "CLdevice"; 2748 break; 2749 case LangAS::opencl_global_host: 2750 ASString = "CLhost"; 2751 break; 2752 case LangAS::opencl_local: 2753 ASString = "CLlocal"; 2754 break; 2755 case LangAS::opencl_constant: 2756 ASString = "CLconstant"; 2757 break; 2758 case LangAS::opencl_private: 2759 ASString = "CLprivate"; 2760 break; 2761 case LangAS::opencl_generic: 2762 ASString = "CLgeneric"; 2763 break; 2764 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" | 2765 // "device" | "host" ] 2766 case LangAS::sycl_global: 2767 ASString = "SYglobal"; 2768 break; 2769 case LangAS::sycl_global_device: 2770 ASString = "SYdevice"; 2771 break; 2772 case LangAS::sycl_global_host: 2773 ASString = "SYhost"; 2774 break; 2775 case LangAS::sycl_local: 2776 ASString = "SYlocal"; 2777 break; 2778 case LangAS::sycl_private: 2779 ASString = "SYprivate"; 2780 break; 2781 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ] 2782 case LangAS::cuda_device: 2783 ASString = "CUdevice"; 2784 break; 2785 case LangAS::cuda_constant: 2786 ASString = "CUconstant"; 2787 break; 2788 case LangAS::cuda_shared: 2789 ASString = "CUshared"; 2790 break; 2791 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ] 2792 case LangAS::ptr32_sptr: 2793 ASString = "ptr32_sptr"; 2794 break; 2795 case LangAS::ptr32_uptr: 2796 ASString = "ptr32_uptr"; 2797 break; 2798 case LangAS::ptr64: 2799 ASString = "ptr64"; 2800 break; 2801 } 2802 } 2803 if (!ASString.empty()) 2804 mangleVendorQualifier(ASString); 2805 } 2806 2807 // The ARC ownership qualifiers start with underscores. 2808 // Objective-C ARC Extension: 2809 // 2810 // <type> ::= U "__strong" 2811 // <type> ::= U "__weak" 2812 // <type> ::= U "__autoreleasing" 2813 // 2814 // Note: we emit __weak first to preserve the order as 2815 // required by the Itanium ABI. 2816 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak) 2817 mangleVendorQualifier("__weak"); 2818 2819 // __unaligned (from -fms-extensions) 2820 if (Quals.hasUnaligned()) 2821 mangleVendorQualifier("__unaligned"); 2822 2823 // Remaining ARC ownership qualifiers. 2824 switch (Quals.getObjCLifetime()) { 2825 case Qualifiers::OCL_None: 2826 break; 2827 2828 case Qualifiers::OCL_Weak: 2829 // Do nothing as we already handled this case above. 2830 break; 2831 2832 case Qualifiers::OCL_Strong: 2833 mangleVendorQualifier("__strong"); 2834 break; 2835 2836 case Qualifiers::OCL_Autoreleasing: 2837 mangleVendorQualifier("__autoreleasing"); 2838 break; 2839 2840 case Qualifiers::OCL_ExplicitNone: 2841 // The __unsafe_unretained qualifier is *not* mangled, so that 2842 // __unsafe_unretained types in ARC produce the same manglings as the 2843 // equivalent (but, naturally, unqualified) types in non-ARC, providing 2844 // better ABI compatibility. 2845 // 2846 // It's safe to do this because unqualified 'id' won't show up 2847 // in any type signatures that need to be mangled. 2848 break; 2849 } 2850 2851 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const 2852 if (Quals.hasRestrict()) 2853 Out << 'r'; 2854 if (Quals.hasVolatile()) 2855 Out << 'V'; 2856 if (Quals.hasConst()) 2857 Out << 'K'; 2858 } 2859 2860 void CXXNameMangler::mangleVendorQualifier(StringRef name) { 2861 Out << 'U' << name.size() << name; 2862 } 2863 2864 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) { 2865 // <ref-qualifier> ::= R # lvalue reference 2866 // ::= O # rvalue-reference 2867 switch (RefQualifier) { 2868 case RQ_None: 2869 break; 2870 2871 case RQ_LValue: 2872 Out << 'R'; 2873 break; 2874 2875 case RQ_RValue: 2876 Out << 'O'; 2877 break; 2878 } 2879 } 2880 2881 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) { 2882 Context.mangleObjCMethodNameAsSourceName(MD, Out); 2883 } 2884 2885 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty, 2886 ASTContext &Ctx) { 2887 if (Quals) 2888 return true; 2889 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel)) 2890 return true; 2891 if (Ty->isOpenCLSpecificType()) 2892 return true; 2893 // From Clang 18.0 we correctly treat SVE types as substitution candidates. 2894 if (Ty->isSVESizelessBuiltinType() && 2895 Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver17) 2896 return true; 2897 if (Ty->isBuiltinType()) 2898 return false; 2899 // Through to Clang 6.0, we accidentally treated undeduced auto types as 2900 // substitution candidates. 2901 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 && 2902 isa<AutoType>(Ty)) 2903 return false; 2904 // A placeholder type for class template deduction is substitutable with 2905 // its corresponding template name; this is handled specially when mangling 2906 // the type. 2907 if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>()) 2908 if (DeducedTST->getDeducedType().isNull()) 2909 return false; 2910 return true; 2911 } 2912 2913 void CXXNameMangler::mangleType(QualType T) { 2914 // If our type is instantiation-dependent but not dependent, we mangle 2915 // it as it was written in the source, removing any top-level sugar. 2916 // Otherwise, use the canonical type. 2917 // 2918 // FIXME: This is an approximation of the instantiation-dependent name 2919 // mangling rules, since we should really be using the type as written and 2920 // augmented via semantic analysis (i.e., with implicit conversions and 2921 // default template arguments) for any instantiation-dependent type. 2922 // Unfortunately, that requires several changes to our AST: 2923 // - Instantiation-dependent TemplateSpecializationTypes will need to be 2924 // uniqued, so that we can handle substitutions properly 2925 // - Default template arguments will need to be represented in the 2926 // TemplateSpecializationType, since they need to be mangled even though 2927 // they aren't written. 2928 // - Conversions on non-type template arguments need to be expressed, since 2929 // they can affect the mangling of sizeof/alignof. 2930 // 2931 // FIXME: This is wrong when mapping to the canonical type for a dependent 2932 // type discards instantiation-dependent portions of the type, such as for: 2933 // 2934 // template<typename T, int N> void f(T (&)[sizeof(N)]); 2935 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17) 2936 // 2937 // It's also wrong in the opposite direction when instantiation-dependent, 2938 // canonically-equivalent types differ in some irrelevant portion of inner 2939 // type sugar. In such cases, we fail to form correct substitutions, eg: 2940 // 2941 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*)); 2942 // 2943 // We should instead canonicalize the non-instantiation-dependent parts, 2944 // regardless of whether the type as a whole is dependent or instantiation 2945 // dependent. 2946 if (!T->isInstantiationDependentType() || T->isDependentType()) 2947 T = T.getCanonicalType(); 2948 else { 2949 // Desugar any types that are purely sugar. 2950 do { 2951 // Don't desugar through template specialization types that aren't 2952 // type aliases. We need to mangle the template arguments as written. 2953 if (const TemplateSpecializationType *TST 2954 = dyn_cast<TemplateSpecializationType>(T)) 2955 if (!TST->isTypeAlias()) 2956 break; 2957 2958 // FIXME: We presumably shouldn't strip off ElaboratedTypes with 2959 // instantation-dependent qualifiers. See 2960 // https://github.com/itanium-cxx-abi/cxx-abi/issues/114. 2961 2962 QualType Desugared 2963 = T.getSingleStepDesugaredType(Context.getASTContext()); 2964 if (Desugared == T) 2965 break; 2966 2967 T = Desugared; 2968 } while (true); 2969 } 2970 SplitQualType split = T.split(); 2971 Qualifiers quals = split.Quals; 2972 const Type *ty = split.Ty; 2973 2974 bool isSubstitutable = 2975 isTypeSubstitutable(quals, ty, Context.getASTContext()); 2976 if (isSubstitutable && mangleSubstitution(T)) 2977 return; 2978 2979 // If we're mangling a qualified array type, push the qualifiers to 2980 // the element type. 2981 if (quals && isa<ArrayType>(T)) { 2982 ty = Context.getASTContext().getAsArrayType(T); 2983 quals = Qualifiers(); 2984 2985 // Note that we don't update T: we want to add the 2986 // substitution at the original type. 2987 } 2988 2989 if (quals || ty->isDependentAddressSpaceType()) { 2990 if (const DependentAddressSpaceType *DAST = 2991 dyn_cast<DependentAddressSpaceType>(ty)) { 2992 SplitQualType splitDAST = DAST->getPointeeType().split(); 2993 mangleQualifiers(splitDAST.Quals, DAST); 2994 mangleType(QualType(splitDAST.Ty, 0)); 2995 } else { 2996 mangleQualifiers(quals); 2997 2998 // Recurse: even if the qualified type isn't yet substitutable, 2999 // the unqualified type might be. 3000 mangleType(QualType(ty, 0)); 3001 } 3002 } else { 3003 switch (ty->getTypeClass()) { 3004 #define ABSTRACT_TYPE(CLASS, PARENT) 3005 #define NON_CANONICAL_TYPE(CLASS, PARENT) \ 3006 case Type::CLASS: \ 3007 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \ 3008 return; 3009 #define TYPE(CLASS, PARENT) \ 3010 case Type::CLASS: \ 3011 mangleType(static_cast<const CLASS##Type*>(ty)); \ 3012 break; 3013 #include "clang/AST/TypeNodes.inc" 3014 } 3015 } 3016 3017 // Add the substitution. 3018 if (isSubstitutable) 3019 addSubstitution(T); 3020 } 3021 3022 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) { 3023 if (!mangleStandardSubstitution(ND)) 3024 mangleName(ND); 3025 } 3026 3027 void CXXNameMangler::mangleType(const BuiltinType *T) { 3028 // <type> ::= <builtin-type> 3029 // <builtin-type> ::= v # void 3030 // ::= w # wchar_t 3031 // ::= b # bool 3032 // ::= c # char 3033 // ::= a # signed char 3034 // ::= h # unsigned char 3035 // ::= s # short 3036 // ::= t # unsigned short 3037 // ::= i # int 3038 // ::= j # unsigned int 3039 // ::= l # long 3040 // ::= m # unsigned long 3041 // ::= x # long long, __int64 3042 // ::= y # unsigned long long, __int64 3043 // ::= n # __int128 3044 // ::= o # unsigned __int128 3045 // ::= f # float 3046 // ::= d # double 3047 // ::= e # long double, __float80 3048 // ::= g # __float128 3049 // ::= g # __ibm128 3050 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits) 3051 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits) 3052 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits) 3053 // ::= Dh # IEEE 754r half-precision floating point (16 bits) 3054 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits); 3055 // ::= Di # char32_t 3056 // ::= Ds # char16_t 3057 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr)) 3058 // ::= [DS] DA # N1169 fixed-point [_Sat] T _Accum 3059 // ::= [DS] DR # N1169 fixed-point [_Sat] T _Fract 3060 // ::= u <source-name> # vendor extended type 3061 // 3062 // <fixed-point-size> 3063 // ::= s # short 3064 // ::= t # unsigned short 3065 // ::= i # plain 3066 // ::= j # unsigned 3067 // ::= l # long 3068 // ::= m # unsigned long 3069 std::string type_name; 3070 // Normalize integer types as vendor extended types: 3071 // u<length>i<type size> 3072 // u<length>u<type size> 3073 if (NormalizeIntegers && T->isInteger()) { 3074 if (T->isSignedInteger()) { 3075 switch (getASTContext().getTypeSize(T)) { 3076 case 8: 3077 // Pick a representative for each integer size in the substitution 3078 // dictionary. (Its actual defined size is not relevant.) 3079 if (mangleSubstitution(BuiltinType::SChar)) 3080 break; 3081 Out << "u2i8"; 3082 addSubstitution(BuiltinType::SChar); 3083 break; 3084 case 16: 3085 if (mangleSubstitution(BuiltinType::Short)) 3086 break; 3087 Out << "u3i16"; 3088 addSubstitution(BuiltinType::Short); 3089 break; 3090 case 32: 3091 if (mangleSubstitution(BuiltinType::Int)) 3092 break; 3093 Out << "u3i32"; 3094 addSubstitution(BuiltinType::Int); 3095 break; 3096 case 64: 3097 if (mangleSubstitution(BuiltinType::Long)) 3098 break; 3099 Out << "u3i64"; 3100 addSubstitution(BuiltinType::Long); 3101 break; 3102 case 128: 3103 if (mangleSubstitution(BuiltinType::Int128)) 3104 break; 3105 Out << "u4i128"; 3106 addSubstitution(BuiltinType::Int128); 3107 break; 3108 default: 3109 llvm_unreachable("Unknown integer size for normalization"); 3110 } 3111 } else { 3112 switch (getASTContext().getTypeSize(T)) { 3113 case 8: 3114 if (mangleSubstitution(BuiltinType::UChar)) 3115 break; 3116 Out << "u2u8"; 3117 addSubstitution(BuiltinType::UChar); 3118 break; 3119 case 16: 3120 if (mangleSubstitution(BuiltinType::UShort)) 3121 break; 3122 Out << "u3u16"; 3123 addSubstitution(BuiltinType::UShort); 3124 break; 3125 case 32: 3126 if (mangleSubstitution(BuiltinType::UInt)) 3127 break; 3128 Out << "u3u32"; 3129 addSubstitution(BuiltinType::UInt); 3130 break; 3131 case 64: 3132 if (mangleSubstitution(BuiltinType::ULong)) 3133 break; 3134 Out << "u3u64"; 3135 addSubstitution(BuiltinType::ULong); 3136 break; 3137 case 128: 3138 if (mangleSubstitution(BuiltinType::UInt128)) 3139 break; 3140 Out << "u4u128"; 3141 addSubstitution(BuiltinType::UInt128); 3142 break; 3143 default: 3144 llvm_unreachable("Unknown integer size for normalization"); 3145 } 3146 } 3147 return; 3148 } 3149 switch (T->getKind()) { 3150 case BuiltinType::Void: 3151 Out << 'v'; 3152 break; 3153 case BuiltinType::Bool: 3154 Out << 'b'; 3155 break; 3156 case BuiltinType::Char_U: 3157 case BuiltinType::Char_S: 3158 Out << 'c'; 3159 break; 3160 case BuiltinType::UChar: 3161 Out << 'h'; 3162 break; 3163 case BuiltinType::UShort: 3164 Out << 't'; 3165 break; 3166 case BuiltinType::UInt: 3167 Out << 'j'; 3168 break; 3169 case BuiltinType::ULong: 3170 Out << 'm'; 3171 break; 3172 case BuiltinType::ULongLong: 3173 Out << 'y'; 3174 break; 3175 case BuiltinType::UInt128: 3176 Out << 'o'; 3177 break; 3178 case BuiltinType::SChar: 3179 Out << 'a'; 3180 break; 3181 case BuiltinType::WChar_S: 3182 case BuiltinType::WChar_U: 3183 Out << 'w'; 3184 break; 3185 case BuiltinType::Char8: 3186 Out << "Du"; 3187 break; 3188 case BuiltinType::Char16: 3189 Out << "Ds"; 3190 break; 3191 case BuiltinType::Char32: 3192 Out << "Di"; 3193 break; 3194 case BuiltinType::Short: 3195 Out << 's'; 3196 break; 3197 case BuiltinType::Int: 3198 Out << 'i'; 3199 break; 3200 case BuiltinType::Long: 3201 Out << 'l'; 3202 break; 3203 case BuiltinType::LongLong: 3204 Out << 'x'; 3205 break; 3206 case BuiltinType::Int128: 3207 Out << 'n'; 3208 break; 3209 case BuiltinType::Float16: 3210 Out << "DF16_"; 3211 break; 3212 case BuiltinType::ShortAccum: 3213 Out << "DAs"; 3214 break; 3215 case BuiltinType::Accum: 3216 Out << "DAi"; 3217 break; 3218 case BuiltinType::LongAccum: 3219 Out << "DAl"; 3220 break; 3221 case BuiltinType::UShortAccum: 3222 Out << "DAt"; 3223 break; 3224 case BuiltinType::UAccum: 3225 Out << "DAj"; 3226 break; 3227 case BuiltinType::ULongAccum: 3228 Out << "DAm"; 3229 break; 3230 case BuiltinType::ShortFract: 3231 Out << "DRs"; 3232 break; 3233 case BuiltinType::Fract: 3234 Out << "DRi"; 3235 break; 3236 case BuiltinType::LongFract: 3237 Out << "DRl"; 3238 break; 3239 case BuiltinType::UShortFract: 3240 Out << "DRt"; 3241 break; 3242 case BuiltinType::UFract: 3243 Out << "DRj"; 3244 break; 3245 case BuiltinType::ULongFract: 3246 Out << "DRm"; 3247 break; 3248 case BuiltinType::SatShortAccum: 3249 Out << "DSDAs"; 3250 break; 3251 case BuiltinType::SatAccum: 3252 Out << "DSDAi"; 3253 break; 3254 case BuiltinType::SatLongAccum: 3255 Out << "DSDAl"; 3256 break; 3257 case BuiltinType::SatUShortAccum: 3258 Out << "DSDAt"; 3259 break; 3260 case BuiltinType::SatUAccum: 3261 Out << "DSDAj"; 3262 break; 3263 case BuiltinType::SatULongAccum: 3264 Out << "DSDAm"; 3265 break; 3266 case BuiltinType::SatShortFract: 3267 Out << "DSDRs"; 3268 break; 3269 case BuiltinType::SatFract: 3270 Out << "DSDRi"; 3271 break; 3272 case BuiltinType::SatLongFract: 3273 Out << "DSDRl"; 3274 break; 3275 case BuiltinType::SatUShortFract: 3276 Out << "DSDRt"; 3277 break; 3278 case BuiltinType::SatUFract: 3279 Out << "DSDRj"; 3280 break; 3281 case BuiltinType::SatULongFract: 3282 Out << "DSDRm"; 3283 break; 3284 case BuiltinType::Half: 3285 Out << "Dh"; 3286 break; 3287 case BuiltinType::Float: 3288 Out << 'f'; 3289 break; 3290 case BuiltinType::Double: 3291 Out << 'd'; 3292 break; 3293 case BuiltinType::LongDouble: { 3294 const TargetInfo *TI = 3295 getASTContext().getLangOpts().OpenMP && 3296 getASTContext().getLangOpts().OpenMPIsTargetDevice 3297 ? getASTContext().getAuxTargetInfo() 3298 : &getASTContext().getTargetInfo(); 3299 Out << TI->getLongDoubleMangling(); 3300 break; 3301 } 3302 case BuiltinType::Float128: { 3303 const TargetInfo *TI = 3304 getASTContext().getLangOpts().OpenMP && 3305 getASTContext().getLangOpts().OpenMPIsTargetDevice 3306 ? getASTContext().getAuxTargetInfo() 3307 : &getASTContext().getTargetInfo(); 3308 Out << TI->getFloat128Mangling(); 3309 break; 3310 } 3311 case BuiltinType::BFloat16: { 3312 const TargetInfo *TI = 3313 ((getASTContext().getLangOpts().OpenMP && 3314 getASTContext().getLangOpts().OpenMPIsTargetDevice) || 3315 getASTContext().getLangOpts().SYCLIsDevice) 3316 ? getASTContext().getAuxTargetInfo() 3317 : &getASTContext().getTargetInfo(); 3318 Out << TI->getBFloat16Mangling(); 3319 break; 3320 } 3321 case BuiltinType::Ibm128: { 3322 const TargetInfo *TI = &getASTContext().getTargetInfo(); 3323 Out << TI->getIbm128Mangling(); 3324 break; 3325 } 3326 case BuiltinType::NullPtr: 3327 Out << "Dn"; 3328 break; 3329 3330 #define BUILTIN_TYPE(Id, SingletonId) 3331 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 3332 case BuiltinType::Id: 3333 #include "clang/AST/BuiltinTypes.def" 3334 case BuiltinType::Dependent: 3335 if (!NullOut) 3336 llvm_unreachable("mangling a placeholder type"); 3337 break; 3338 case BuiltinType::ObjCId: 3339 Out << "11objc_object"; 3340 break; 3341 case BuiltinType::ObjCClass: 3342 Out << "10objc_class"; 3343 break; 3344 case BuiltinType::ObjCSel: 3345 Out << "13objc_selector"; 3346 break; 3347 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 3348 case BuiltinType::Id: \ 3349 type_name = "ocl_" #ImgType "_" #Suffix; \ 3350 Out << type_name.size() << type_name; \ 3351 break; 3352 #include "clang/Basic/OpenCLImageTypes.def" 3353 case BuiltinType::OCLSampler: 3354 Out << "11ocl_sampler"; 3355 break; 3356 case BuiltinType::OCLEvent: 3357 Out << "9ocl_event"; 3358 break; 3359 case BuiltinType::OCLClkEvent: 3360 Out << "12ocl_clkevent"; 3361 break; 3362 case BuiltinType::OCLQueue: 3363 Out << "9ocl_queue"; 3364 break; 3365 case BuiltinType::OCLReserveID: 3366 Out << "13ocl_reserveid"; 3367 break; 3368 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 3369 case BuiltinType::Id: \ 3370 type_name = "ocl_" #ExtType; \ 3371 Out << type_name.size() << type_name; \ 3372 break; 3373 #include "clang/Basic/OpenCLExtensionTypes.def" 3374 // The SVE types are effectively target-specific. The mangling scheme 3375 // is defined in the appendices to the Procedure Call Standard for the 3376 // Arm Architecture. 3377 #define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \ 3378 ElBits, IsSigned, IsFP, IsBF) \ 3379 case BuiltinType::Id: \ 3380 if (T->getKind() == BuiltinType::SveBFloat16 && \ 3381 isCompatibleWith(LangOptions::ClangABI::Ver17)) { \ 3382 /* Prior to Clang 18.0 we used this incorrect mangled name */ \ 3383 type_name = "__SVBFloat16_t"; \ 3384 Out << "u" << type_name.size() << type_name; \ 3385 } else { \ 3386 type_name = MangledName; \ 3387 Out << (type_name == InternalName ? "u" : "") << type_name.size() \ 3388 << type_name; \ 3389 } \ 3390 break; 3391 #define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \ 3392 case BuiltinType::Id: \ 3393 type_name = MangledName; \ 3394 Out << (type_name == InternalName ? "u" : "") << type_name.size() \ 3395 << type_name; \ 3396 break; 3397 #define SVE_OPAQUE_TYPE(InternalName, MangledName, Id, SingletonId) \ 3398 case BuiltinType::Id: \ 3399 type_name = MangledName; \ 3400 Out << (type_name == InternalName ? "u" : "") << type_name.size() \ 3401 << type_name; \ 3402 break; 3403 #include "clang/Basic/AArch64SVEACLETypes.def" 3404 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 3405 case BuiltinType::Id: \ 3406 type_name = #Name; \ 3407 Out << 'u' << type_name.size() << type_name; \ 3408 break; 3409 #include "clang/Basic/PPCTypes.def" 3410 // TODO: Check the mangling scheme for RISC-V V. 3411 #define RVV_TYPE(Name, Id, SingletonId) \ 3412 case BuiltinType::Id: \ 3413 type_name = Name; \ 3414 Out << 'u' << type_name.size() << type_name; \ 3415 break; 3416 #include "clang/Basic/RISCVVTypes.def" 3417 #define WASM_REF_TYPE(InternalName, MangledName, Id, SingletonId, AS) \ 3418 case BuiltinType::Id: \ 3419 type_name = MangledName; \ 3420 Out << 'u' << type_name.size() << type_name; \ 3421 break; 3422 #include "clang/Basic/WebAssemblyReferenceTypes.def" 3423 } 3424 } 3425 3426 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) { 3427 switch (CC) { 3428 case CC_C: 3429 return ""; 3430 3431 case CC_X86VectorCall: 3432 case CC_X86Pascal: 3433 case CC_X86RegCall: 3434 case CC_AAPCS: 3435 case CC_AAPCS_VFP: 3436 case CC_AArch64VectorCall: 3437 case CC_AArch64SVEPCS: 3438 case CC_AMDGPUKernelCall: 3439 case CC_IntelOclBicc: 3440 case CC_SpirFunction: 3441 case CC_OpenCLKernel: 3442 case CC_PreserveMost: 3443 case CC_PreserveAll: 3444 case CC_M68kRTD: 3445 // FIXME: we should be mangling all of the above. 3446 return ""; 3447 3448 case CC_X86ThisCall: 3449 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is 3450 // used explicitly. At this point, we don't have that much information in 3451 // the AST, since clang tends to bake the convention into the canonical 3452 // function type. thiscall only rarely used explicitly, so don't mangle it 3453 // for now. 3454 return ""; 3455 3456 case CC_X86StdCall: 3457 return "stdcall"; 3458 case CC_X86FastCall: 3459 return "fastcall"; 3460 case CC_X86_64SysV: 3461 return "sysv_abi"; 3462 case CC_Win64: 3463 return "ms_abi"; 3464 case CC_Swift: 3465 return "swiftcall"; 3466 case CC_SwiftAsync: 3467 return "swiftasynccall"; 3468 } 3469 llvm_unreachable("bad calling convention"); 3470 } 3471 3472 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) { 3473 // Fast path. 3474 if (T->getExtInfo() == FunctionType::ExtInfo()) 3475 return; 3476 3477 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 3478 // This will get more complicated in the future if we mangle other 3479 // things here; but for now, since we mangle ns_returns_retained as 3480 // a qualifier on the result type, we can get away with this: 3481 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC()); 3482 if (!CCQualifier.empty()) 3483 mangleVendorQualifier(CCQualifier); 3484 3485 // FIXME: regparm 3486 // FIXME: noreturn 3487 } 3488 3489 void 3490 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) { 3491 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 3492 3493 // Note that these are *not* substitution candidates. Demanglers might 3494 // have trouble with this if the parameter type is fully substituted. 3495 3496 switch (PI.getABI()) { 3497 case ParameterABI::Ordinary: 3498 break; 3499 3500 // All of these start with "swift", so they come before "ns_consumed". 3501 case ParameterABI::SwiftContext: 3502 case ParameterABI::SwiftAsyncContext: 3503 case ParameterABI::SwiftErrorResult: 3504 case ParameterABI::SwiftIndirectResult: 3505 mangleVendorQualifier(getParameterABISpelling(PI.getABI())); 3506 break; 3507 } 3508 3509 if (PI.isConsumed()) 3510 mangleVendorQualifier("ns_consumed"); 3511 3512 if (PI.isNoEscape()) 3513 mangleVendorQualifier("noescape"); 3514 } 3515 3516 // <type> ::= <function-type> 3517 // <function-type> ::= [<CV-qualifiers>] F [Y] 3518 // <bare-function-type> [<ref-qualifier>] E 3519 void CXXNameMangler::mangleType(const FunctionProtoType *T) { 3520 mangleExtFunctionInfo(T); 3521 3522 // Mangle CV-qualifiers, if present. These are 'this' qualifiers, 3523 // e.g. "const" in "int (A::*)() const". 3524 mangleQualifiers(T->getMethodQuals()); 3525 3526 // Mangle instantiation-dependent exception-specification, if present, 3527 // per cxx-abi-dev proposal on 2016-10-11. 3528 if (T->hasInstantiationDependentExceptionSpec()) { 3529 if (isComputedNoexcept(T->getExceptionSpecType())) { 3530 Out << "DO"; 3531 mangleExpression(T->getNoexceptExpr()); 3532 Out << "E"; 3533 } else { 3534 assert(T->getExceptionSpecType() == EST_Dynamic); 3535 Out << "Dw"; 3536 for (auto ExceptTy : T->exceptions()) 3537 mangleType(ExceptTy); 3538 Out << "E"; 3539 } 3540 } else if (T->isNothrow()) { 3541 Out << "Do"; 3542 } 3543 3544 Out << 'F'; 3545 3546 // FIXME: We don't have enough information in the AST to produce the 'Y' 3547 // encoding for extern "C" function types. 3548 mangleBareFunctionType(T, /*MangleReturnType=*/true); 3549 3550 // Mangle the ref-qualifier, if present. 3551 mangleRefQualifier(T->getRefQualifier()); 3552 3553 Out << 'E'; 3554 } 3555 3556 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) { 3557 // Function types without prototypes can arise when mangling a function type 3558 // within an overloadable function in C. We mangle these as the absence of any 3559 // parameter types (not even an empty parameter list). 3560 Out << 'F'; 3561 3562 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 3563 3564 FunctionTypeDepth.enterResultType(); 3565 mangleType(T->getReturnType()); 3566 FunctionTypeDepth.leaveResultType(); 3567 3568 FunctionTypeDepth.pop(saved); 3569 Out << 'E'; 3570 } 3571 3572 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto, 3573 bool MangleReturnType, 3574 const FunctionDecl *FD) { 3575 // Record that we're in a function type. See mangleFunctionParam 3576 // for details on what we're trying to achieve here. 3577 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 3578 3579 // <bare-function-type> ::= <signature type>+ 3580 if (MangleReturnType) { 3581 FunctionTypeDepth.enterResultType(); 3582 3583 // Mangle ns_returns_retained as an order-sensitive qualifier here. 3584 if (Proto->getExtInfo().getProducesResult() && FD == nullptr) 3585 mangleVendorQualifier("ns_returns_retained"); 3586 3587 // Mangle the return type without any direct ARC ownership qualifiers. 3588 QualType ReturnTy = Proto->getReturnType(); 3589 if (ReturnTy.getObjCLifetime()) { 3590 auto SplitReturnTy = ReturnTy.split(); 3591 SplitReturnTy.Quals.removeObjCLifetime(); 3592 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy); 3593 } 3594 mangleType(ReturnTy); 3595 3596 FunctionTypeDepth.leaveResultType(); 3597 } 3598 3599 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) { 3600 // <builtin-type> ::= v # void 3601 Out << 'v'; 3602 } else { 3603 assert(!FD || FD->getNumParams() == Proto->getNumParams()); 3604 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) { 3605 // Mangle extended parameter info as order-sensitive qualifiers here. 3606 if (Proto->hasExtParameterInfos() && FD == nullptr) { 3607 mangleExtParameterInfo(Proto->getExtParameterInfo(I)); 3608 } 3609 3610 // Mangle the type. 3611 QualType ParamTy = Proto->getParamType(I); 3612 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy)); 3613 3614 if (FD) { 3615 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) { 3616 // Attr can only take 1 character, so we can hardcode the length 3617 // below. 3618 assert(Attr->getType() <= 9 && Attr->getType() >= 0); 3619 if (Attr->isDynamic()) 3620 Out << "U25pass_dynamic_object_size" << Attr->getType(); 3621 else 3622 Out << "U17pass_object_size" << Attr->getType(); 3623 } 3624 } 3625 } 3626 3627 // <builtin-type> ::= z # ellipsis 3628 if (Proto->isVariadic()) 3629 Out << 'z'; 3630 } 3631 3632 if (FD) { 3633 FunctionTypeDepth.enterResultType(); 3634 mangleRequiresClause(FD->getTrailingRequiresClause()); 3635 } 3636 3637 FunctionTypeDepth.pop(saved); 3638 } 3639 3640 // <type> ::= <class-enum-type> 3641 // <class-enum-type> ::= <name> 3642 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) { 3643 mangleName(T->getDecl()); 3644 } 3645 3646 // <type> ::= <class-enum-type> 3647 // <class-enum-type> ::= <name> 3648 void CXXNameMangler::mangleType(const EnumType *T) { 3649 mangleType(static_cast<const TagType*>(T)); 3650 } 3651 void CXXNameMangler::mangleType(const RecordType *T) { 3652 mangleType(static_cast<const TagType*>(T)); 3653 } 3654 void CXXNameMangler::mangleType(const TagType *T) { 3655 mangleName(T->getDecl()); 3656 } 3657 3658 // <type> ::= <array-type> 3659 // <array-type> ::= A <positive dimension number> _ <element type> 3660 // ::= A [<dimension expression>] _ <element type> 3661 void CXXNameMangler::mangleType(const ConstantArrayType *T) { 3662 Out << 'A' << T->getSize() << '_'; 3663 mangleType(T->getElementType()); 3664 } 3665 void CXXNameMangler::mangleType(const VariableArrayType *T) { 3666 Out << 'A'; 3667 // decayed vla types (size 0) will just be skipped. 3668 if (T->getSizeExpr()) 3669 mangleExpression(T->getSizeExpr()); 3670 Out << '_'; 3671 mangleType(T->getElementType()); 3672 } 3673 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) { 3674 Out << 'A'; 3675 // A DependentSizedArrayType might not have size expression as below 3676 // 3677 // template<int ...N> int arr[] = {N...}; 3678 if (T->getSizeExpr()) 3679 mangleExpression(T->getSizeExpr()); 3680 Out << '_'; 3681 mangleType(T->getElementType()); 3682 } 3683 void CXXNameMangler::mangleType(const IncompleteArrayType *T) { 3684 Out << "A_"; 3685 mangleType(T->getElementType()); 3686 } 3687 3688 // <type> ::= <pointer-to-member-type> 3689 // <pointer-to-member-type> ::= M <class type> <member type> 3690 void CXXNameMangler::mangleType(const MemberPointerType *T) { 3691 Out << 'M'; 3692 mangleType(QualType(T->getClass(), 0)); 3693 QualType PointeeType = T->getPointeeType(); 3694 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) { 3695 mangleType(FPT); 3696 3697 // Itanium C++ ABI 5.1.8: 3698 // 3699 // The type of a non-static member function is considered to be different, 3700 // for the purposes of substitution, from the type of a namespace-scope or 3701 // static member function whose type appears similar. The types of two 3702 // non-static member functions are considered to be different, for the 3703 // purposes of substitution, if the functions are members of different 3704 // classes. In other words, for the purposes of substitution, the class of 3705 // which the function is a member is considered part of the type of 3706 // function. 3707 3708 // Given that we already substitute member function pointers as a 3709 // whole, the net effect of this rule is just to unconditionally 3710 // suppress substitution on the function type in a member pointer. 3711 // We increment the SeqID here to emulate adding an entry to the 3712 // substitution table. 3713 ++SeqID; 3714 } else 3715 mangleType(PointeeType); 3716 } 3717 3718 // <type> ::= <template-param> 3719 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) { 3720 mangleTemplateParameter(T->getDepth(), T->getIndex()); 3721 } 3722 3723 // <type> ::= <template-param> 3724 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) { 3725 // FIXME: not clear how to mangle this! 3726 // template <class T...> class A { 3727 // template <class U...> void foo(T(*)(U) x...); 3728 // }; 3729 Out << "_SUBSTPACK_"; 3730 } 3731 3732 // <type> ::= P <type> # pointer-to 3733 void CXXNameMangler::mangleType(const PointerType *T) { 3734 Out << 'P'; 3735 mangleType(T->getPointeeType()); 3736 } 3737 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) { 3738 Out << 'P'; 3739 mangleType(T->getPointeeType()); 3740 } 3741 3742 // <type> ::= R <type> # reference-to 3743 void CXXNameMangler::mangleType(const LValueReferenceType *T) { 3744 Out << 'R'; 3745 mangleType(T->getPointeeType()); 3746 } 3747 3748 // <type> ::= O <type> # rvalue reference-to (C++0x) 3749 void CXXNameMangler::mangleType(const RValueReferenceType *T) { 3750 Out << 'O'; 3751 mangleType(T->getPointeeType()); 3752 } 3753 3754 // <type> ::= C <type> # complex pair (C 2000) 3755 void CXXNameMangler::mangleType(const ComplexType *T) { 3756 Out << 'C'; 3757 mangleType(T->getElementType()); 3758 } 3759 3760 // ARM's ABI for Neon vector types specifies that they should be mangled as 3761 // if they are structs (to match ARM's initial implementation). The 3762 // vector type must be one of the special types predefined by ARM. 3763 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) { 3764 QualType EltType = T->getElementType(); 3765 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3766 const char *EltName = nullptr; 3767 if (T->getVectorKind() == VectorKind::NeonPoly) { 3768 switch (cast<BuiltinType>(EltType)->getKind()) { 3769 case BuiltinType::SChar: 3770 case BuiltinType::UChar: 3771 EltName = "poly8_t"; 3772 break; 3773 case BuiltinType::Short: 3774 case BuiltinType::UShort: 3775 EltName = "poly16_t"; 3776 break; 3777 case BuiltinType::LongLong: 3778 case BuiltinType::ULongLong: 3779 EltName = "poly64_t"; 3780 break; 3781 default: llvm_unreachable("unexpected Neon polynomial vector element type"); 3782 } 3783 } else { 3784 switch (cast<BuiltinType>(EltType)->getKind()) { 3785 case BuiltinType::SChar: EltName = "int8_t"; break; 3786 case BuiltinType::UChar: EltName = "uint8_t"; break; 3787 case BuiltinType::Short: EltName = "int16_t"; break; 3788 case BuiltinType::UShort: EltName = "uint16_t"; break; 3789 case BuiltinType::Int: EltName = "int32_t"; break; 3790 case BuiltinType::UInt: EltName = "uint32_t"; break; 3791 case BuiltinType::LongLong: EltName = "int64_t"; break; 3792 case BuiltinType::ULongLong: EltName = "uint64_t"; break; 3793 case BuiltinType::Double: EltName = "float64_t"; break; 3794 case BuiltinType::Float: EltName = "float32_t"; break; 3795 case BuiltinType::Half: EltName = "float16_t"; break; 3796 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break; 3797 default: 3798 llvm_unreachable("unexpected Neon vector element type"); 3799 } 3800 } 3801 const char *BaseName = nullptr; 3802 unsigned BitSize = (T->getNumElements() * 3803 getASTContext().getTypeSize(EltType)); 3804 if (BitSize == 64) 3805 BaseName = "__simd64_"; 3806 else { 3807 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits"); 3808 BaseName = "__simd128_"; 3809 } 3810 Out << strlen(BaseName) + strlen(EltName); 3811 Out << BaseName << EltName; 3812 } 3813 3814 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) { 3815 DiagnosticsEngine &Diags = Context.getDiags(); 3816 unsigned DiagID = Diags.getCustomDiagID( 3817 DiagnosticsEngine::Error, 3818 "cannot mangle this dependent neon vector type yet"); 3819 Diags.Report(T->getAttributeLoc(), DiagID); 3820 } 3821 3822 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) { 3823 switch (EltType->getKind()) { 3824 case BuiltinType::SChar: 3825 return "Int8"; 3826 case BuiltinType::Short: 3827 return "Int16"; 3828 case BuiltinType::Int: 3829 return "Int32"; 3830 case BuiltinType::Long: 3831 case BuiltinType::LongLong: 3832 return "Int64"; 3833 case BuiltinType::UChar: 3834 return "Uint8"; 3835 case BuiltinType::UShort: 3836 return "Uint16"; 3837 case BuiltinType::UInt: 3838 return "Uint32"; 3839 case BuiltinType::ULong: 3840 case BuiltinType::ULongLong: 3841 return "Uint64"; 3842 case BuiltinType::Half: 3843 return "Float16"; 3844 case BuiltinType::Float: 3845 return "Float32"; 3846 case BuiltinType::Double: 3847 return "Float64"; 3848 case BuiltinType::BFloat16: 3849 return "Bfloat16"; 3850 default: 3851 llvm_unreachable("Unexpected vector element base type"); 3852 } 3853 } 3854 3855 // AArch64's ABI for Neon vector types specifies that they should be mangled as 3856 // the equivalent internal name. The vector type must be one of the special 3857 // types predefined by ARM. 3858 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) { 3859 QualType EltType = T->getElementType(); 3860 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3861 unsigned BitSize = 3862 (T->getNumElements() * getASTContext().getTypeSize(EltType)); 3863 (void)BitSize; // Silence warning. 3864 3865 assert((BitSize == 64 || BitSize == 128) && 3866 "Neon vector type not 64 or 128 bits"); 3867 3868 StringRef EltName; 3869 if (T->getVectorKind() == VectorKind::NeonPoly) { 3870 switch (cast<BuiltinType>(EltType)->getKind()) { 3871 case BuiltinType::UChar: 3872 EltName = "Poly8"; 3873 break; 3874 case BuiltinType::UShort: 3875 EltName = "Poly16"; 3876 break; 3877 case BuiltinType::ULong: 3878 case BuiltinType::ULongLong: 3879 EltName = "Poly64"; 3880 break; 3881 default: 3882 llvm_unreachable("unexpected Neon polynomial vector element type"); 3883 } 3884 } else 3885 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType)); 3886 3887 std::string TypeName = 3888 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str(); 3889 Out << TypeName.length() << TypeName; 3890 } 3891 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) { 3892 DiagnosticsEngine &Diags = Context.getDiags(); 3893 unsigned DiagID = Diags.getCustomDiagID( 3894 DiagnosticsEngine::Error, 3895 "cannot mangle this dependent neon vector type yet"); 3896 Diags.Report(T->getAttributeLoc(), DiagID); 3897 } 3898 3899 // The AArch64 ACLE specifies that fixed-length SVE vector and predicate types 3900 // defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64 3901 // type as the sizeless variants. 3902 // 3903 // The mangling scheme for VLS types is implemented as a "pseudo" template: 3904 // 3905 // '__SVE_VLS<<type>, <vector length>>' 3906 // 3907 // Combining the existing SVE type and a specific vector length (in bits). 3908 // For example: 3909 // 3910 // typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512))); 3911 // 3912 // is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as: 3913 // 3914 // "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE" 3915 // 3916 // i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE 3917 // 3918 // The latest ACLE specification (00bet5) does not contain details of this 3919 // mangling scheme, it will be specified in the next revision. The mangling 3920 // scheme is otherwise defined in the appendices to the Procedure Call Standard 3921 // for the Arm Architecture, see 3922 // https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling 3923 void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) { 3924 assert((T->getVectorKind() == VectorKind::SveFixedLengthData || 3925 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) && 3926 "expected fixed-length SVE vector!"); 3927 3928 QualType EltType = T->getElementType(); 3929 assert(EltType->isBuiltinType() && 3930 "expected builtin type for fixed-length SVE vector!"); 3931 3932 StringRef TypeName; 3933 switch (cast<BuiltinType>(EltType)->getKind()) { 3934 case BuiltinType::SChar: 3935 TypeName = "__SVInt8_t"; 3936 break; 3937 case BuiltinType::UChar: { 3938 if (T->getVectorKind() == VectorKind::SveFixedLengthData) 3939 TypeName = "__SVUint8_t"; 3940 else 3941 TypeName = "__SVBool_t"; 3942 break; 3943 } 3944 case BuiltinType::Short: 3945 TypeName = "__SVInt16_t"; 3946 break; 3947 case BuiltinType::UShort: 3948 TypeName = "__SVUint16_t"; 3949 break; 3950 case BuiltinType::Int: 3951 TypeName = "__SVInt32_t"; 3952 break; 3953 case BuiltinType::UInt: 3954 TypeName = "__SVUint32_t"; 3955 break; 3956 case BuiltinType::Long: 3957 TypeName = "__SVInt64_t"; 3958 break; 3959 case BuiltinType::ULong: 3960 TypeName = "__SVUint64_t"; 3961 break; 3962 case BuiltinType::Half: 3963 TypeName = "__SVFloat16_t"; 3964 break; 3965 case BuiltinType::Float: 3966 TypeName = "__SVFloat32_t"; 3967 break; 3968 case BuiltinType::Double: 3969 TypeName = "__SVFloat64_t"; 3970 break; 3971 case BuiltinType::BFloat16: 3972 TypeName = "__SVBfloat16_t"; 3973 break; 3974 default: 3975 llvm_unreachable("unexpected element type for fixed-length SVE vector!"); 3976 } 3977 3978 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width; 3979 3980 if (T->getVectorKind() == VectorKind::SveFixedLengthPredicate) 3981 VecSizeInBits *= 8; 3982 3983 Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj" 3984 << VecSizeInBits << "EE"; 3985 } 3986 3987 void CXXNameMangler::mangleAArch64FixedSveVectorType( 3988 const DependentVectorType *T) { 3989 DiagnosticsEngine &Diags = Context.getDiags(); 3990 unsigned DiagID = Diags.getCustomDiagID( 3991 DiagnosticsEngine::Error, 3992 "cannot mangle this dependent fixed-length SVE vector type yet"); 3993 Diags.Report(T->getAttributeLoc(), DiagID); 3994 } 3995 3996 void CXXNameMangler::mangleRISCVFixedRVVVectorType(const VectorType *T) { 3997 assert((T->getVectorKind() == VectorKind::RVVFixedLengthData || 3998 T->getVectorKind() == VectorKind::RVVFixedLengthMask) && 3999 "expected fixed-length RVV vector!"); 4000 4001 QualType EltType = T->getElementType(); 4002 assert(EltType->isBuiltinType() && 4003 "expected builtin type for fixed-length RVV vector!"); 4004 4005 SmallString<20> TypeNameStr; 4006 llvm::raw_svector_ostream TypeNameOS(TypeNameStr); 4007 TypeNameOS << "__rvv_"; 4008 switch (cast<BuiltinType>(EltType)->getKind()) { 4009 case BuiltinType::SChar: 4010 TypeNameOS << "int8"; 4011 break; 4012 case BuiltinType::UChar: 4013 if (T->getVectorKind() == VectorKind::RVVFixedLengthData) 4014 TypeNameOS << "uint8"; 4015 else 4016 TypeNameOS << "bool"; 4017 break; 4018 case BuiltinType::Short: 4019 TypeNameOS << "int16"; 4020 break; 4021 case BuiltinType::UShort: 4022 TypeNameOS << "uint16"; 4023 break; 4024 case BuiltinType::Int: 4025 TypeNameOS << "int32"; 4026 break; 4027 case BuiltinType::UInt: 4028 TypeNameOS << "uint32"; 4029 break; 4030 case BuiltinType::Long: 4031 TypeNameOS << "int64"; 4032 break; 4033 case BuiltinType::ULong: 4034 TypeNameOS << "uint64"; 4035 break; 4036 case BuiltinType::Float16: 4037 TypeNameOS << "float16"; 4038 break; 4039 case BuiltinType::Float: 4040 TypeNameOS << "float32"; 4041 break; 4042 case BuiltinType::Double: 4043 TypeNameOS << "float64"; 4044 break; 4045 default: 4046 llvm_unreachable("unexpected element type for fixed-length RVV vector!"); 4047 } 4048 4049 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width; 4050 4051 // Apend the LMUL suffix. 4052 auto VScale = getASTContext().getTargetInfo().getVScaleRange( 4053 getASTContext().getLangOpts()); 4054 unsigned VLen = VScale->first * llvm::RISCV::RVVBitsPerBlock; 4055 4056 if (T->getVectorKind() == VectorKind::RVVFixedLengthData) { 4057 TypeNameOS << 'm'; 4058 if (VecSizeInBits >= VLen) 4059 TypeNameOS << (VecSizeInBits / VLen); 4060 else 4061 TypeNameOS << 'f' << (VLen / VecSizeInBits); 4062 } else { 4063 TypeNameOS << (VLen / VecSizeInBits); 4064 } 4065 TypeNameOS << "_t"; 4066 4067 Out << "9__RVV_VLSI" << 'u' << TypeNameStr.size() << TypeNameStr << "Lj" 4068 << VecSizeInBits << "EE"; 4069 } 4070 4071 void CXXNameMangler::mangleRISCVFixedRVVVectorType( 4072 const DependentVectorType *T) { 4073 DiagnosticsEngine &Diags = Context.getDiags(); 4074 unsigned DiagID = Diags.getCustomDiagID( 4075 DiagnosticsEngine::Error, 4076 "cannot mangle this dependent fixed-length RVV vector type yet"); 4077 Diags.Report(T->getAttributeLoc(), DiagID); 4078 } 4079 4080 // GNU extension: vector types 4081 // <type> ::= <vector-type> 4082 // <vector-type> ::= Dv <positive dimension number> _ 4083 // <extended element type> 4084 // ::= Dv [<dimension expression>] _ <element type> 4085 // <extended element type> ::= <element type> 4086 // ::= p # AltiVec vector pixel 4087 // ::= b # Altivec vector bool 4088 void CXXNameMangler::mangleType(const VectorType *T) { 4089 if ((T->getVectorKind() == VectorKind::Neon || 4090 T->getVectorKind() == VectorKind::NeonPoly)) { 4091 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 4092 llvm::Triple::ArchType Arch = 4093 getASTContext().getTargetInfo().getTriple().getArch(); 4094 if ((Arch == llvm::Triple::aarch64 || 4095 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin()) 4096 mangleAArch64NeonVectorType(T); 4097 else 4098 mangleNeonVectorType(T); 4099 return; 4100 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData || 4101 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) { 4102 mangleAArch64FixedSveVectorType(T); 4103 return; 4104 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData || 4105 T->getVectorKind() == VectorKind::RVVFixedLengthMask) { 4106 mangleRISCVFixedRVVVectorType(T); 4107 return; 4108 } 4109 Out << "Dv" << T->getNumElements() << '_'; 4110 if (T->getVectorKind() == VectorKind::AltiVecPixel) 4111 Out << 'p'; 4112 else if (T->getVectorKind() == VectorKind::AltiVecBool) 4113 Out << 'b'; 4114 else 4115 mangleType(T->getElementType()); 4116 } 4117 4118 void CXXNameMangler::mangleType(const DependentVectorType *T) { 4119 if ((T->getVectorKind() == VectorKind::Neon || 4120 T->getVectorKind() == VectorKind::NeonPoly)) { 4121 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 4122 llvm::Triple::ArchType Arch = 4123 getASTContext().getTargetInfo().getTriple().getArch(); 4124 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) && 4125 !Target.isOSDarwin()) 4126 mangleAArch64NeonVectorType(T); 4127 else 4128 mangleNeonVectorType(T); 4129 return; 4130 } else if (T->getVectorKind() == VectorKind::SveFixedLengthData || 4131 T->getVectorKind() == VectorKind::SveFixedLengthPredicate) { 4132 mangleAArch64FixedSveVectorType(T); 4133 return; 4134 } else if (T->getVectorKind() == VectorKind::RVVFixedLengthData) { 4135 mangleRISCVFixedRVVVectorType(T); 4136 return; 4137 } 4138 4139 Out << "Dv"; 4140 mangleExpression(T->getSizeExpr()); 4141 Out << '_'; 4142 if (T->getVectorKind() == VectorKind::AltiVecPixel) 4143 Out << 'p'; 4144 else if (T->getVectorKind() == VectorKind::AltiVecBool) 4145 Out << 'b'; 4146 else 4147 mangleType(T->getElementType()); 4148 } 4149 4150 void CXXNameMangler::mangleType(const ExtVectorType *T) { 4151 mangleType(static_cast<const VectorType*>(T)); 4152 } 4153 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) { 4154 Out << "Dv"; 4155 mangleExpression(T->getSizeExpr()); 4156 Out << '_'; 4157 mangleType(T->getElementType()); 4158 } 4159 4160 void CXXNameMangler::mangleType(const ConstantMatrixType *T) { 4161 // Mangle matrix types as a vendor extended type: 4162 // u<Len>matrix_typeI<Rows><Columns><element type>E 4163 4164 StringRef VendorQualifier = "matrix_type"; 4165 Out << "u" << VendorQualifier.size() << VendorQualifier; 4166 4167 Out << "I"; 4168 auto &ASTCtx = getASTContext(); 4169 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType()); 4170 llvm::APSInt Rows(BitWidth); 4171 Rows = T->getNumRows(); 4172 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows); 4173 llvm::APSInt Columns(BitWidth); 4174 Columns = T->getNumColumns(); 4175 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns); 4176 mangleType(T->getElementType()); 4177 Out << "E"; 4178 } 4179 4180 void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) { 4181 // Mangle matrix types as a vendor extended type: 4182 // u<Len>matrix_typeI<row expr><column expr><element type>E 4183 StringRef VendorQualifier = "matrix_type"; 4184 Out << "u" << VendorQualifier.size() << VendorQualifier; 4185 4186 Out << "I"; 4187 mangleTemplateArgExpr(T->getRowExpr()); 4188 mangleTemplateArgExpr(T->getColumnExpr()); 4189 mangleType(T->getElementType()); 4190 Out << "E"; 4191 } 4192 4193 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) { 4194 SplitQualType split = T->getPointeeType().split(); 4195 mangleQualifiers(split.Quals, T); 4196 mangleType(QualType(split.Ty, 0)); 4197 } 4198 4199 void CXXNameMangler::mangleType(const PackExpansionType *T) { 4200 // <type> ::= Dp <type> # pack expansion (C++0x) 4201 Out << "Dp"; 4202 mangleType(T->getPattern()); 4203 } 4204 4205 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) { 4206 mangleSourceName(T->getDecl()->getIdentifier()); 4207 } 4208 4209 void CXXNameMangler::mangleType(const ObjCObjectType *T) { 4210 // Treat __kindof as a vendor extended type qualifier. 4211 if (T->isKindOfType()) 4212 Out << "U8__kindof"; 4213 4214 if (!T->qual_empty()) { 4215 // Mangle protocol qualifiers. 4216 SmallString<64> QualStr; 4217 llvm::raw_svector_ostream QualOS(QualStr); 4218 QualOS << "objcproto"; 4219 for (const auto *I : T->quals()) { 4220 StringRef name = I->getName(); 4221 QualOS << name.size() << name; 4222 } 4223 Out << 'U' << QualStr.size() << QualStr; 4224 } 4225 4226 mangleType(T->getBaseType()); 4227 4228 if (T->isSpecialized()) { 4229 // Mangle type arguments as I <type>+ E 4230 Out << 'I'; 4231 for (auto typeArg : T->getTypeArgs()) 4232 mangleType(typeArg); 4233 Out << 'E'; 4234 } 4235 } 4236 4237 void CXXNameMangler::mangleType(const BlockPointerType *T) { 4238 Out << "U13block_pointer"; 4239 mangleType(T->getPointeeType()); 4240 } 4241 4242 void CXXNameMangler::mangleType(const InjectedClassNameType *T) { 4243 // Mangle injected class name types as if the user had written the 4244 // specialization out fully. It may not actually be possible to see 4245 // this mangling, though. 4246 mangleType(T->getInjectedSpecializationType()); 4247 } 4248 4249 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) { 4250 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) { 4251 mangleTemplateName(TD, T->template_arguments()); 4252 } else { 4253 if (mangleSubstitution(QualType(T, 0))) 4254 return; 4255 4256 mangleTemplatePrefix(T->getTemplateName()); 4257 4258 // FIXME: GCC does not appear to mangle the template arguments when 4259 // the template in question is a dependent template name. Should we 4260 // emulate that badness? 4261 mangleTemplateArgs(T->getTemplateName(), T->template_arguments()); 4262 addSubstitution(QualType(T, 0)); 4263 } 4264 } 4265 4266 void CXXNameMangler::mangleType(const DependentNameType *T) { 4267 // Proposal by cxx-abi-dev, 2014-03-26 4268 // <class-enum-type> ::= <name> # non-dependent or dependent type name or 4269 // # dependent elaborated type specifier using 4270 // # 'typename' 4271 // ::= Ts <name> # dependent elaborated type specifier using 4272 // # 'struct' or 'class' 4273 // ::= Tu <name> # dependent elaborated type specifier using 4274 // # 'union' 4275 // ::= Te <name> # dependent elaborated type specifier using 4276 // # 'enum' 4277 switch (T->getKeyword()) { 4278 case ElaboratedTypeKeyword::None: 4279 case ElaboratedTypeKeyword::Typename: 4280 break; 4281 case ElaboratedTypeKeyword::Struct: 4282 case ElaboratedTypeKeyword::Class: 4283 case ElaboratedTypeKeyword::Interface: 4284 Out << "Ts"; 4285 break; 4286 case ElaboratedTypeKeyword::Union: 4287 Out << "Tu"; 4288 break; 4289 case ElaboratedTypeKeyword::Enum: 4290 Out << "Te"; 4291 break; 4292 } 4293 // Typename types are always nested 4294 Out << 'N'; 4295 manglePrefix(T->getQualifier()); 4296 mangleSourceName(T->getIdentifier()); 4297 Out << 'E'; 4298 } 4299 4300 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) { 4301 // Dependently-scoped template types are nested if they have a prefix. 4302 Out << 'N'; 4303 4304 // TODO: avoid making this TemplateName. 4305 TemplateName Prefix = 4306 getASTContext().getDependentTemplateName(T->getQualifier(), 4307 T->getIdentifier()); 4308 mangleTemplatePrefix(Prefix); 4309 4310 // FIXME: GCC does not appear to mangle the template arguments when 4311 // the template in question is a dependent template name. Should we 4312 // emulate that badness? 4313 mangleTemplateArgs(Prefix, T->template_arguments()); 4314 Out << 'E'; 4315 } 4316 4317 void CXXNameMangler::mangleType(const TypeOfType *T) { 4318 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 4319 // "extension with parameters" mangling. 4320 Out << "u6typeof"; 4321 } 4322 4323 void CXXNameMangler::mangleType(const TypeOfExprType *T) { 4324 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 4325 // "extension with parameters" mangling. 4326 Out << "u6typeof"; 4327 } 4328 4329 void CXXNameMangler::mangleType(const DecltypeType *T) { 4330 Expr *E = T->getUnderlyingExpr(); 4331 4332 // type ::= Dt <expression> E # decltype of an id-expression 4333 // # or class member access 4334 // ::= DT <expression> E # decltype of an expression 4335 4336 // This purports to be an exhaustive list of id-expressions and 4337 // class member accesses. Note that we do not ignore parentheses; 4338 // parentheses change the semantics of decltype for these 4339 // expressions (and cause the mangler to use the other form). 4340 if (isa<DeclRefExpr>(E) || 4341 isa<MemberExpr>(E) || 4342 isa<UnresolvedLookupExpr>(E) || 4343 isa<DependentScopeDeclRefExpr>(E) || 4344 isa<CXXDependentScopeMemberExpr>(E) || 4345 isa<UnresolvedMemberExpr>(E)) 4346 Out << "Dt"; 4347 else 4348 Out << "DT"; 4349 mangleExpression(E); 4350 Out << 'E'; 4351 } 4352 4353 void CXXNameMangler::mangleType(const UnaryTransformType *T) { 4354 // If this is dependent, we need to record that. If not, we simply 4355 // mangle it as the underlying type since they are equivalent. 4356 if (T->isDependentType()) { 4357 Out << "u"; 4358 4359 StringRef BuiltinName; 4360 switch (T->getUTTKind()) { 4361 #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \ 4362 case UnaryTransformType::Enum: \ 4363 BuiltinName = "__" #Trait; \ 4364 break; 4365 #include "clang/Basic/TransformTypeTraits.def" 4366 } 4367 Out << BuiltinName.size() << BuiltinName; 4368 } 4369 4370 Out << "I"; 4371 mangleType(T->getBaseType()); 4372 Out << "E"; 4373 } 4374 4375 void CXXNameMangler::mangleType(const AutoType *T) { 4376 assert(T->getDeducedType().isNull() && 4377 "Deduced AutoType shouldn't be handled here!"); 4378 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType && 4379 "shouldn't need to mangle __auto_type!"); 4380 // <builtin-type> ::= Da # auto 4381 // ::= Dc # decltype(auto) 4382 // ::= Dk # constrained auto 4383 // ::= DK # constrained decltype(auto) 4384 if (T->isConstrained() && !isCompatibleWith(LangOptions::ClangABI::Ver17)) { 4385 Out << (T->isDecltypeAuto() ? "DK" : "Dk"); 4386 mangleTypeConstraint(T->getTypeConstraintConcept(), 4387 T->getTypeConstraintArguments()); 4388 } else { 4389 Out << (T->isDecltypeAuto() ? "Dc" : "Da"); 4390 } 4391 } 4392 4393 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) { 4394 QualType Deduced = T->getDeducedType(); 4395 if (!Deduced.isNull()) 4396 return mangleType(Deduced); 4397 4398 TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl(); 4399 assert(TD && "shouldn't form deduced TST unless we know we have a template"); 4400 4401 if (mangleSubstitution(TD)) 4402 return; 4403 4404 mangleName(GlobalDecl(TD)); 4405 addSubstitution(TD); 4406 } 4407 4408 void CXXNameMangler::mangleType(const AtomicType *T) { 4409 // <type> ::= U <source-name> <type> # vendor extended type qualifier 4410 // (Until there's a standardized mangling...) 4411 Out << "U7_Atomic"; 4412 mangleType(T->getValueType()); 4413 } 4414 4415 void CXXNameMangler::mangleType(const PipeType *T) { 4416 // Pipe type mangling rules are described in SPIR 2.0 specification 4417 // A.1 Data types and A.3 Summary of changes 4418 // <type> ::= 8ocl_pipe 4419 Out << "8ocl_pipe"; 4420 } 4421 4422 void CXXNameMangler::mangleType(const BitIntType *T) { 4423 // 5.1.5.2 Builtin types 4424 // <type> ::= DB <number | instantiation-dependent expression> _ 4425 // ::= DU <number | instantiation-dependent expression> _ 4426 Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_"; 4427 } 4428 4429 void CXXNameMangler::mangleType(const DependentBitIntType *T) { 4430 // 5.1.5.2 Builtin types 4431 // <type> ::= DB <number | instantiation-dependent expression> _ 4432 // ::= DU <number | instantiation-dependent expression> _ 4433 Out << "D" << (T->isUnsigned() ? "U" : "B"); 4434 mangleExpression(T->getNumBitsExpr()); 4435 Out << "_"; 4436 } 4437 4438 void CXXNameMangler::mangleIntegerLiteral(QualType T, 4439 const llvm::APSInt &Value) { 4440 // <expr-primary> ::= L <type> <value number> E # integer literal 4441 Out << 'L'; 4442 4443 mangleType(T); 4444 if (T->isBooleanType()) { 4445 // Boolean values are encoded as 0/1. 4446 Out << (Value.getBoolValue() ? '1' : '0'); 4447 } else { 4448 mangleNumber(Value); 4449 } 4450 Out << 'E'; 4451 4452 } 4453 4454 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) { 4455 // Ignore member expressions involving anonymous unions. 4456 while (const auto *RT = Base->getType()->getAs<RecordType>()) { 4457 if (!RT->getDecl()->isAnonymousStructOrUnion()) 4458 break; 4459 const auto *ME = dyn_cast<MemberExpr>(Base); 4460 if (!ME) 4461 break; 4462 Base = ME->getBase(); 4463 IsArrow = ME->isArrow(); 4464 } 4465 4466 if (Base->isImplicitCXXThis()) { 4467 // Note: GCC mangles member expressions to the implicit 'this' as 4468 // *this., whereas we represent them as this->. The Itanium C++ ABI 4469 // does not specify anything here, so we follow GCC. 4470 Out << "dtdefpT"; 4471 } else { 4472 Out << (IsArrow ? "pt" : "dt"); 4473 mangleExpression(Base); 4474 } 4475 } 4476 4477 /// Mangles a member expression. 4478 void CXXNameMangler::mangleMemberExpr(const Expr *base, 4479 bool isArrow, 4480 NestedNameSpecifier *qualifier, 4481 NamedDecl *firstQualifierLookup, 4482 DeclarationName member, 4483 const TemplateArgumentLoc *TemplateArgs, 4484 unsigned NumTemplateArgs, 4485 unsigned arity) { 4486 // <expression> ::= dt <expression> <unresolved-name> 4487 // ::= pt <expression> <unresolved-name> 4488 if (base) 4489 mangleMemberExprBase(base, isArrow); 4490 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity); 4491 } 4492 4493 /// Look at the callee of the given call expression and determine if 4494 /// it's a parenthesized id-expression which would have triggered ADL 4495 /// otherwise. 4496 static bool isParenthesizedADLCallee(const CallExpr *call) { 4497 const Expr *callee = call->getCallee(); 4498 const Expr *fn = callee->IgnoreParens(); 4499 4500 // Must be parenthesized. IgnoreParens() skips __extension__ nodes, 4501 // too, but for those to appear in the callee, it would have to be 4502 // parenthesized. 4503 if (callee == fn) return false; 4504 4505 // Must be an unresolved lookup. 4506 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn); 4507 if (!lookup) return false; 4508 4509 assert(!lookup->requiresADL()); 4510 4511 // Must be an unqualified lookup. 4512 if (lookup->getQualifier()) return false; 4513 4514 // Must not have found a class member. Note that if one is a class 4515 // member, they're all class members. 4516 if (lookup->getNumDecls() > 0 && 4517 (*lookup->decls_begin())->isCXXClassMember()) 4518 return false; 4519 4520 // Otherwise, ADL would have been triggered. 4521 return true; 4522 } 4523 4524 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) { 4525 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E); 4526 Out << CastEncoding; 4527 mangleType(ECE->getType()); 4528 mangleExpression(ECE->getSubExpr()); 4529 } 4530 4531 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) { 4532 if (auto *Syntactic = InitList->getSyntacticForm()) 4533 InitList = Syntactic; 4534 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 4535 mangleExpression(InitList->getInit(i)); 4536 } 4537 4538 void CXXNameMangler::mangleRequirement(SourceLocation RequiresExprLoc, 4539 const concepts::Requirement *Req) { 4540 using concepts::Requirement; 4541 4542 // TODO: We can't mangle the result of a failed substitution. It's not clear 4543 // whether we should be mangling the original form prior to any substitution 4544 // instead. See https://lists.isocpp.org/core/2023/04/14118.php 4545 auto HandleSubstitutionFailure = 4546 [&](SourceLocation Loc) { 4547 DiagnosticsEngine &Diags = Context.getDiags(); 4548 unsigned DiagID = Diags.getCustomDiagID( 4549 DiagnosticsEngine::Error, "cannot mangle this requires-expression " 4550 "containing a substitution failure"); 4551 Diags.Report(Loc, DiagID); 4552 Out << 'F'; 4553 }; 4554 4555 switch (Req->getKind()) { 4556 case Requirement::RK_Type: { 4557 const auto *TR = cast<concepts::TypeRequirement>(Req); 4558 if (TR->isSubstitutionFailure()) 4559 return HandleSubstitutionFailure( 4560 TR->getSubstitutionDiagnostic()->DiagLoc); 4561 4562 Out << 'T'; 4563 mangleType(TR->getType()->getType()); 4564 break; 4565 } 4566 4567 case Requirement::RK_Simple: 4568 case Requirement::RK_Compound: { 4569 const auto *ER = cast<concepts::ExprRequirement>(Req); 4570 if (ER->isExprSubstitutionFailure()) 4571 return HandleSubstitutionFailure( 4572 ER->getExprSubstitutionDiagnostic()->DiagLoc); 4573 4574 Out << 'X'; 4575 mangleExpression(ER->getExpr()); 4576 4577 if (ER->hasNoexceptRequirement()) 4578 Out << 'N'; 4579 4580 if (!ER->getReturnTypeRequirement().isEmpty()) { 4581 if (ER->getReturnTypeRequirement().isSubstitutionFailure()) 4582 return HandleSubstitutionFailure(ER->getReturnTypeRequirement() 4583 .getSubstitutionDiagnostic() 4584 ->DiagLoc); 4585 4586 Out << 'R'; 4587 mangleTypeConstraint(ER->getReturnTypeRequirement().getTypeConstraint()); 4588 } 4589 break; 4590 } 4591 4592 case Requirement::RK_Nested: 4593 const auto *NR = cast<concepts::NestedRequirement>(Req); 4594 if (NR->hasInvalidConstraint()) { 4595 // FIXME: NestedRequirement should track the location of its requires 4596 // keyword. 4597 return HandleSubstitutionFailure(RequiresExprLoc); 4598 } 4599 4600 Out << 'Q'; 4601 mangleExpression(NR->getConstraintExpr()); 4602 break; 4603 } 4604 } 4605 4606 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity, 4607 bool AsTemplateArg) { 4608 // <expression> ::= <unary operator-name> <expression> 4609 // ::= <binary operator-name> <expression> <expression> 4610 // ::= <trinary operator-name> <expression> <expression> <expression> 4611 // ::= cv <type> expression # conversion with one argument 4612 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments 4613 // ::= dc <type> <expression> # dynamic_cast<type> (expression) 4614 // ::= sc <type> <expression> # static_cast<type> (expression) 4615 // ::= cc <type> <expression> # const_cast<type> (expression) 4616 // ::= rc <type> <expression> # reinterpret_cast<type> (expression) 4617 // ::= st <type> # sizeof (a type) 4618 // ::= at <type> # alignof (a type) 4619 // ::= <template-param> 4620 // ::= <function-param> 4621 // ::= fpT # 'this' expression (part of <function-param>) 4622 // ::= sr <type> <unqualified-name> # dependent name 4623 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id 4624 // ::= ds <expression> <expression> # expr.*expr 4625 // ::= sZ <template-param> # size of a parameter pack 4626 // ::= sZ <function-param> # size of a function parameter pack 4627 // ::= u <source-name> <template-arg>* E # vendor extended expression 4628 // ::= <expr-primary> 4629 // <expr-primary> ::= L <type> <value number> E # integer literal 4630 // ::= L <type> <value float> E # floating literal 4631 // ::= L <type> <string type> E # string literal 4632 // ::= L <nullptr type> E # nullptr literal "LDnE" 4633 // ::= L <pointer type> 0 E # null pointer template argument 4634 // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang 4635 // ::= L <mangled-name> E # external name 4636 QualType ImplicitlyConvertedToType; 4637 4638 // A top-level expression that's not <expr-primary> needs to be wrapped in 4639 // X...E in a template arg. 4640 bool IsPrimaryExpr = true; 4641 auto NotPrimaryExpr = [&] { 4642 if (AsTemplateArg && IsPrimaryExpr) 4643 Out << 'X'; 4644 IsPrimaryExpr = false; 4645 }; 4646 4647 auto MangleDeclRefExpr = [&](const NamedDecl *D) { 4648 switch (D->getKind()) { 4649 default: 4650 // <expr-primary> ::= L <mangled-name> E # external name 4651 Out << 'L'; 4652 mangle(D); 4653 Out << 'E'; 4654 break; 4655 4656 case Decl::ParmVar: 4657 NotPrimaryExpr(); 4658 mangleFunctionParam(cast<ParmVarDecl>(D)); 4659 break; 4660 4661 case Decl::EnumConstant: { 4662 // <expr-primary> 4663 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D); 4664 mangleIntegerLiteral(ED->getType(), ED->getInitVal()); 4665 break; 4666 } 4667 4668 case Decl::NonTypeTemplateParm: 4669 NotPrimaryExpr(); 4670 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D); 4671 mangleTemplateParameter(PD->getDepth(), PD->getIndex()); 4672 break; 4673 } 4674 }; 4675 4676 // 'goto recurse' is used when handling a simple "unwrapping" node which 4677 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need 4678 // to be preserved. 4679 recurse: 4680 switch (E->getStmtClass()) { 4681 case Expr::NoStmtClass: 4682 #define ABSTRACT_STMT(Type) 4683 #define EXPR(Type, Base) 4684 #define STMT(Type, Base) \ 4685 case Expr::Type##Class: 4686 #include "clang/AST/StmtNodes.inc" 4687 // fallthrough 4688 4689 // These all can only appear in local or variable-initialization 4690 // contexts and so should never appear in a mangling. 4691 case Expr::AddrLabelExprClass: 4692 case Expr::DesignatedInitUpdateExprClass: 4693 case Expr::ImplicitValueInitExprClass: 4694 case Expr::ArrayInitLoopExprClass: 4695 case Expr::ArrayInitIndexExprClass: 4696 case Expr::NoInitExprClass: 4697 case Expr::ParenListExprClass: 4698 case Expr::MSPropertyRefExprClass: 4699 case Expr::MSPropertySubscriptExprClass: 4700 case Expr::TypoExprClass: // This should no longer exist in the AST by now. 4701 case Expr::RecoveryExprClass: 4702 case Expr::OMPArraySectionExprClass: 4703 case Expr::OMPArrayShapingExprClass: 4704 case Expr::OMPIteratorExprClass: 4705 case Expr::CXXInheritedCtorInitExprClass: 4706 case Expr::CXXParenListInitExprClass: 4707 llvm_unreachable("unexpected statement kind"); 4708 4709 case Expr::ConstantExprClass: 4710 E = cast<ConstantExpr>(E)->getSubExpr(); 4711 goto recurse; 4712 4713 // FIXME: invent manglings for all these. 4714 case Expr::BlockExprClass: 4715 case Expr::ChooseExprClass: 4716 case Expr::CompoundLiteralExprClass: 4717 case Expr::ExtVectorElementExprClass: 4718 case Expr::GenericSelectionExprClass: 4719 case Expr::ObjCEncodeExprClass: 4720 case Expr::ObjCIsaExprClass: 4721 case Expr::ObjCIvarRefExprClass: 4722 case Expr::ObjCMessageExprClass: 4723 case Expr::ObjCPropertyRefExprClass: 4724 case Expr::ObjCProtocolExprClass: 4725 case Expr::ObjCSelectorExprClass: 4726 case Expr::ObjCStringLiteralClass: 4727 case Expr::ObjCBoxedExprClass: 4728 case Expr::ObjCArrayLiteralClass: 4729 case Expr::ObjCDictionaryLiteralClass: 4730 case Expr::ObjCSubscriptRefExprClass: 4731 case Expr::ObjCIndirectCopyRestoreExprClass: 4732 case Expr::ObjCAvailabilityCheckExprClass: 4733 case Expr::OffsetOfExprClass: 4734 case Expr::PredefinedExprClass: 4735 case Expr::ShuffleVectorExprClass: 4736 case Expr::ConvertVectorExprClass: 4737 case Expr::StmtExprClass: 4738 case Expr::ArrayTypeTraitExprClass: 4739 case Expr::ExpressionTraitExprClass: 4740 case Expr::VAArgExprClass: 4741 case Expr::CUDAKernelCallExprClass: 4742 case Expr::AsTypeExprClass: 4743 case Expr::PseudoObjectExprClass: 4744 case Expr::AtomicExprClass: 4745 case Expr::SourceLocExprClass: 4746 case Expr::BuiltinBitCastExprClass: 4747 { 4748 NotPrimaryExpr(); 4749 if (!NullOut) { 4750 // As bad as this diagnostic is, it's better than crashing. 4751 DiagnosticsEngine &Diags = Context.getDiags(); 4752 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 4753 "cannot yet mangle expression type %0"); 4754 Diags.Report(E->getExprLoc(), DiagID) 4755 << E->getStmtClassName() << E->getSourceRange(); 4756 return; 4757 } 4758 break; 4759 } 4760 4761 case Expr::CXXUuidofExprClass: { 4762 NotPrimaryExpr(); 4763 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E); 4764 // As of clang 12, uuidof uses the vendor extended expression 4765 // mangling. Previously, it used a special-cased nonstandard extension. 4766 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) { 4767 Out << "u8__uuidof"; 4768 if (UE->isTypeOperand()) 4769 mangleType(UE->getTypeOperand(Context.getASTContext())); 4770 else 4771 mangleTemplateArgExpr(UE->getExprOperand()); 4772 Out << 'E'; 4773 } else { 4774 if (UE->isTypeOperand()) { 4775 QualType UuidT = UE->getTypeOperand(Context.getASTContext()); 4776 Out << "u8__uuidoft"; 4777 mangleType(UuidT); 4778 } else { 4779 Expr *UuidExp = UE->getExprOperand(); 4780 Out << "u8__uuidofz"; 4781 mangleExpression(UuidExp); 4782 } 4783 } 4784 break; 4785 } 4786 4787 // Even gcc-4.5 doesn't mangle this. 4788 case Expr::BinaryConditionalOperatorClass: { 4789 NotPrimaryExpr(); 4790 DiagnosticsEngine &Diags = Context.getDiags(); 4791 unsigned DiagID = 4792 Diags.getCustomDiagID(DiagnosticsEngine::Error, 4793 "?: operator with omitted middle operand cannot be mangled"); 4794 Diags.Report(E->getExprLoc(), DiagID) 4795 << E->getStmtClassName() << E->getSourceRange(); 4796 return; 4797 } 4798 4799 // These are used for internal purposes and cannot be meaningfully mangled. 4800 case Expr::OpaqueValueExprClass: 4801 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?"); 4802 4803 case Expr::InitListExprClass: { 4804 NotPrimaryExpr(); 4805 Out << "il"; 4806 mangleInitListElements(cast<InitListExpr>(E)); 4807 Out << "E"; 4808 break; 4809 } 4810 4811 case Expr::DesignatedInitExprClass: { 4812 NotPrimaryExpr(); 4813 auto *DIE = cast<DesignatedInitExpr>(E); 4814 for (const auto &Designator : DIE->designators()) { 4815 if (Designator.isFieldDesignator()) { 4816 Out << "di"; 4817 mangleSourceName(Designator.getFieldName()); 4818 } else if (Designator.isArrayDesignator()) { 4819 Out << "dx"; 4820 mangleExpression(DIE->getArrayIndex(Designator)); 4821 } else { 4822 assert(Designator.isArrayRangeDesignator() && 4823 "unknown designator kind"); 4824 Out << "dX"; 4825 mangleExpression(DIE->getArrayRangeStart(Designator)); 4826 mangleExpression(DIE->getArrayRangeEnd(Designator)); 4827 } 4828 } 4829 mangleExpression(DIE->getInit()); 4830 break; 4831 } 4832 4833 case Expr::CXXDefaultArgExprClass: 4834 E = cast<CXXDefaultArgExpr>(E)->getExpr(); 4835 goto recurse; 4836 4837 case Expr::CXXDefaultInitExprClass: 4838 E = cast<CXXDefaultInitExpr>(E)->getExpr(); 4839 goto recurse; 4840 4841 case Expr::CXXStdInitializerListExprClass: 4842 E = cast<CXXStdInitializerListExpr>(E)->getSubExpr(); 4843 goto recurse; 4844 4845 case Expr::SubstNonTypeTemplateParmExprClass: { 4846 // Mangle a substituted parameter the same way we mangle the template 4847 // argument. 4848 auto *SNTTPE = cast<SubstNonTypeTemplateParmExpr>(E); 4849 if (auto *CE = dyn_cast<ConstantExpr>(SNTTPE->getReplacement())) { 4850 // Pull out the constant value and mangle it as a template argument. 4851 QualType ParamType = SNTTPE->getParameterType(Context.getASTContext()); 4852 assert(CE->hasAPValueResult() && "expected the NTTP to have an APValue"); 4853 mangleValueInTemplateArg(ParamType, CE->getAPValueResult(), false, 4854 /*NeedExactType=*/true); 4855 break; 4856 } 4857 // The remaining cases all happen to be substituted with expressions that 4858 // mangle the same as a corresponding template argument anyway. 4859 E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(); 4860 goto recurse; 4861 } 4862 4863 case Expr::UserDefinedLiteralClass: 4864 // We follow g++'s approach of mangling a UDL as a call to the literal 4865 // operator. 4866 case Expr::CXXMemberCallExprClass: // fallthrough 4867 case Expr::CallExprClass: { 4868 NotPrimaryExpr(); 4869 const CallExpr *CE = cast<CallExpr>(E); 4870 4871 // <expression> ::= cp <simple-id> <expression>* E 4872 // We use this mangling only when the call would use ADL except 4873 // for being parenthesized. Per discussion with David 4874 // Vandervoorde, 2011.04.25. 4875 if (isParenthesizedADLCallee(CE)) { 4876 Out << "cp"; 4877 // The callee here is a parenthesized UnresolvedLookupExpr with 4878 // no qualifier and should always get mangled as a <simple-id> 4879 // anyway. 4880 4881 // <expression> ::= cl <expression>* E 4882 } else { 4883 Out << "cl"; 4884 } 4885 4886 unsigned CallArity = CE->getNumArgs(); 4887 for (const Expr *Arg : CE->arguments()) 4888 if (isa<PackExpansionExpr>(Arg)) 4889 CallArity = UnknownArity; 4890 4891 mangleExpression(CE->getCallee(), CallArity); 4892 for (const Expr *Arg : CE->arguments()) 4893 mangleExpression(Arg); 4894 Out << 'E'; 4895 break; 4896 } 4897 4898 case Expr::CXXNewExprClass: { 4899 NotPrimaryExpr(); 4900 const CXXNewExpr *New = cast<CXXNewExpr>(E); 4901 if (New->isGlobalNew()) Out << "gs"; 4902 Out << (New->isArray() ? "na" : "nw"); 4903 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(), 4904 E = New->placement_arg_end(); I != E; ++I) 4905 mangleExpression(*I); 4906 Out << '_'; 4907 mangleType(New->getAllocatedType()); 4908 if (New->hasInitializer()) { 4909 if (New->getInitializationStyle() == CXXNewInitializationStyle::Braces) 4910 Out << "il"; 4911 else 4912 Out << "pi"; 4913 const Expr *Init = New->getInitializer(); 4914 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 4915 // Directly inline the initializers. 4916 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 4917 E = CCE->arg_end(); 4918 I != E; ++I) 4919 mangleExpression(*I); 4920 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) { 4921 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i) 4922 mangleExpression(PLE->getExpr(i)); 4923 } else if (New->getInitializationStyle() == 4924 CXXNewInitializationStyle::Braces && 4925 isa<InitListExpr>(Init)) { 4926 // Only take InitListExprs apart for list-initialization. 4927 mangleInitListElements(cast<InitListExpr>(Init)); 4928 } else 4929 mangleExpression(Init); 4930 } 4931 Out << 'E'; 4932 break; 4933 } 4934 4935 case Expr::CXXPseudoDestructorExprClass: { 4936 NotPrimaryExpr(); 4937 const auto *PDE = cast<CXXPseudoDestructorExpr>(E); 4938 if (const Expr *Base = PDE->getBase()) 4939 mangleMemberExprBase(Base, PDE->isArrow()); 4940 NestedNameSpecifier *Qualifier = PDE->getQualifier(); 4941 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) { 4942 if (Qualifier) { 4943 mangleUnresolvedPrefix(Qualifier, 4944 /*recursive=*/true); 4945 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()); 4946 Out << 'E'; 4947 } else { 4948 Out << "sr"; 4949 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType())) 4950 Out << 'E'; 4951 } 4952 } else if (Qualifier) { 4953 mangleUnresolvedPrefix(Qualifier); 4954 } 4955 // <base-unresolved-name> ::= dn <destructor-name> 4956 Out << "dn"; 4957 QualType DestroyedType = PDE->getDestroyedType(); 4958 mangleUnresolvedTypeOrSimpleId(DestroyedType); 4959 break; 4960 } 4961 4962 case Expr::MemberExprClass: { 4963 NotPrimaryExpr(); 4964 const MemberExpr *ME = cast<MemberExpr>(E); 4965 mangleMemberExpr(ME->getBase(), ME->isArrow(), 4966 ME->getQualifier(), nullptr, 4967 ME->getMemberDecl()->getDeclName(), 4968 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4969 Arity); 4970 break; 4971 } 4972 4973 case Expr::UnresolvedMemberExprClass: { 4974 NotPrimaryExpr(); 4975 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E); 4976 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 4977 ME->isArrow(), ME->getQualifier(), nullptr, 4978 ME->getMemberName(), 4979 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4980 Arity); 4981 break; 4982 } 4983 4984 case Expr::CXXDependentScopeMemberExprClass: { 4985 NotPrimaryExpr(); 4986 const CXXDependentScopeMemberExpr *ME 4987 = cast<CXXDependentScopeMemberExpr>(E); 4988 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 4989 ME->isArrow(), ME->getQualifier(), 4990 ME->getFirstQualifierFoundInScope(), 4991 ME->getMember(), 4992 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4993 Arity); 4994 break; 4995 } 4996 4997 case Expr::UnresolvedLookupExprClass: { 4998 NotPrimaryExpr(); 4999 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E); 5000 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), 5001 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(), 5002 Arity); 5003 break; 5004 } 5005 5006 case Expr::CXXUnresolvedConstructExprClass: { 5007 NotPrimaryExpr(); 5008 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E); 5009 unsigned N = CE->getNumArgs(); 5010 5011 if (CE->isListInitialization()) { 5012 assert(N == 1 && "unexpected form for list initialization"); 5013 auto *IL = cast<InitListExpr>(CE->getArg(0)); 5014 Out << "tl"; 5015 mangleType(CE->getType()); 5016 mangleInitListElements(IL); 5017 Out << "E"; 5018 break; 5019 } 5020 5021 Out << "cv"; 5022 mangleType(CE->getType()); 5023 if (N != 1) Out << '_'; 5024 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 5025 if (N != 1) Out << 'E'; 5026 break; 5027 } 5028 5029 case Expr::CXXConstructExprClass: { 5030 // An implicit cast is silent, thus may contain <expr-primary>. 5031 const auto *CE = cast<CXXConstructExpr>(E); 5032 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) { 5033 assert( 5034 CE->getNumArgs() >= 1 && 5035 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && 5036 "implicit CXXConstructExpr must have one argument"); 5037 E = cast<CXXConstructExpr>(E)->getArg(0); 5038 goto recurse; 5039 } 5040 NotPrimaryExpr(); 5041 Out << "il"; 5042 for (auto *E : CE->arguments()) 5043 mangleExpression(E); 5044 Out << "E"; 5045 break; 5046 } 5047 5048 case Expr::CXXTemporaryObjectExprClass: { 5049 NotPrimaryExpr(); 5050 const auto *CE = cast<CXXTemporaryObjectExpr>(E); 5051 unsigned N = CE->getNumArgs(); 5052 bool List = CE->isListInitialization(); 5053 5054 if (List) 5055 Out << "tl"; 5056 else 5057 Out << "cv"; 5058 mangleType(CE->getType()); 5059 if (!List && N != 1) 5060 Out << '_'; 5061 if (CE->isStdInitListInitialization()) { 5062 // We implicitly created a std::initializer_list<T> for the first argument 5063 // of a constructor of type U in an expression of the form U{a, b, c}. 5064 // Strip all the semantic gunk off the initializer list. 5065 auto *SILE = 5066 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit()); 5067 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit()); 5068 mangleInitListElements(ILE); 5069 } else { 5070 for (auto *E : CE->arguments()) 5071 mangleExpression(E); 5072 } 5073 if (List || N != 1) 5074 Out << 'E'; 5075 break; 5076 } 5077 5078 case Expr::CXXScalarValueInitExprClass: 5079 NotPrimaryExpr(); 5080 Out << "cv"; 5081 mangleType(E->getType()); 5082 Out << "_E"; 5083 break; 5084 5085 case Expr::CXXNoexceptExprClass: 5086 NotPrimaryExpr(); 5087 Out << "nx"; 5088 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand()); 5089 break; 5090 5091 case Expr::UnaryExprOrTypeTraitExprClass: { 5092 // Non-instantiation-dependent traits are an <expr-primary> integer literal. 5093 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); 5094 5095 if (!SAE->isInstantiationDependent()) { 5096 // Itanium C++ ABI: 5097 // If the operand of a sizeof or alignof operator is not 5098 // instantiation-dependent it is encoded as an integer literal 5099 // reflecting the result of the operator. 5100 // 5101 // If the result of the operator is implicitly converted to a known 5102 // integer type, that type is used for the literal; otherwise, the type 5103 // of std::size_t or std::ptrdiff_t is used. 5104 // 5105 // FIXME: We still include the operand in the profile in this case. This 5106 // can lead to mangling collisions between function templates that we 5107 // consider to be different. 5108 QualType T = (ImplicitlyConvertedToType.isNull() || 5109 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() 5110 : ImplicitlyConvertedToType; 5111 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); 5112 mangleIntegerLiteral(T, V); 5113 break; 5114 } 5115 5116 NotPrimaryExpr(); // But otherwise, they are not. 5117 5118 auto MangleAlignofSizeofArg = [&] { 5119 if (SAE->isArgumentType()) { 5120 Out << 't'; 5121 mangleType(SAE->getArgumentType()); 5122 } else { 5123 Out << 'z'; 5124 mangleExpression(SAE->getArgumentExpr()); 5125 } 5126 }; 5127 5128 switch(SAE->getKind()) { 5129 case UETT_SizeOf: 5130 Out << 's'; 5131 MangleAlignofSizeofArg(); 5132 break; 5133 case UETT_PreferredAlignOf: 5134 // As of clang 12, we mangle __alignof__ differently than alignof. (They 5135 // have acted differently since Clang 8, but were previously mangled the 5136 // same.) 5137 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) { 5138 Out << "u11__alignof__"; 5139 if (SAE->isArgumentType()) 5140 mangleType(SAE->getArgumentType()); 5141 else 5142 mangleTemplateArgExpr(SAE->getArgumentExpr()); 5143 Out << 'E'; 5144 break; 5145 } 5146 [[fallthrough]]; 5147 case UETT_AlignOf: 5148 Out << 'a'; 5149 MangleAlignofSizeofArg(); 5150 break; 5151 case UETT_DataSizeOf: { 5152 DiagnosticsEngine &Diags = Context.getDiags(); 5153 unsigned DiagID = 5154 Diags.getCustomDiagID(DiagnosticsEngine::Error, 5155 "cannot yet mangle __datasizeof expression"); 5156 Diags.Report(DiagID); 5157 return; 5158 } 5159 case UETT_VecStep: { 5160 DiagnosticsEngine &Diags = Context.getDiags(); 5161 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 5162 "cannot yet mangle vec_step expression"); 5163 Diags.Report(DiagID); 5164 return; 5165 } 5166 case UETT_OpenMPRequiredSimdAlign: { 5167 DiagnosticsEngine &Diags = Context.getDiags(); 5168 unsigned DiagID = Diags.getCustomDiagID( 5169 DiagnosticsEngine::Error, 5170 "cannot yet mangle __builtin_omp_required_simd_align expression"); 5171 Diags.Report(DiagID); 5172 return; 5173 } 5174 case UETT_VectorElements: { 5175 DiagnosticsEngine &Diags = Context.getDiags(); 5176 unsigned DiagID = Diags.getCustomDiagID( 5177 DiagnosticsEngine::Error, 5178 "cannot yet mangle __builtin_vectorelements expression"); 5179 Diags.Report(DiagID); 5180 return; 5181 } 5182 } 5183 break; 5184 } 5185 5186 case Expr::TypeTraitExprClass: { 5187 // <expression> ::= u <source-name> <template-arg>* E # vendor extension 5188 const TypeTraitExpr *TTE = cast<TypeTraitExpr>(E); 5189 NotPrimaryExpr(); 5190 Out << 'u'; 5191 llvm::StringRef Spelling = getTraitSpelling(TTE->getTrait()); 5192 Out << Spelling.size() << Spelling; 5193 for (TypeSourceInfo *TSI : TTE->getArgs()) { 5194 mangleType(TSI->getType()); 5195 } 5196 Out << 'E'; 5197 break; 5198 } 5199 5200 case Expr::CXXThrowExprClass: { 5201 NotPrimaryExpr(); 5202 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E); 5203 // <expression> ::= tw <expression> # throw expression 5204 // ::= tr # rethrow 5205 if (TE->getSubExpr()) { 5206 Out << "tw"; 5207 mangleExpression(TE->getSubExpr()); 5208 } else { 5209 Out << "tr"; 5210 } 5211 break; 5212 } 5213 5214 case Expr::CXXTypeidExprClass: { 5215 NotPrimaryExpr(); 5216 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E); 5217 // <expression> ::= ti <type> # typeid (type) 5218 // ::= te <expression> # typeid (expression) 5219 if (TIE->isTypeOperand()) { 5220 Out << "ti"; 5221 mangleType(TIE->getTypeOperand(Context.getASTContext())); 5222 } else { 5223 Out << "te"; 5224 mangleExpression(TIE->getExprOperand()); 5225 } 5226 break; 5227 } 5228 5229 case Expr::CXXDeleteExprClass: { 5230 NotPrimaryExpr(); 5231 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E); 5232 // <expression> ::= [gs] dl <expression> # [::] delete expr 5233 // ::= [gs] da <expression> # [::] delete [] expr 5234 if (DE->isGlobalDelete()) Out << "gs"; 5235 Out << (DE->isArrayForm() ? "da" : "dl"); 5236 mangleExpression(DE->getArgument()); 5237 break; 5238 } 5239 5240 case Expr::UnaryOperatorClass: { 5241 NotPrimaryExpr(); 5242 const UnaryOperator *UO = cast<UnaryOperator>(E); 5243 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()), 5244 /*Arity=*/1); 5245 mangleExpression(UO->getSubExpr()); 5246 break; 5247 } 5248 5249 case Expr::ArraySubscriptExprClass: { 5250 NotPrimaryExpr(); 5251 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E); 5252 5253 // Array subscript is treated as a syntactically weird form of 5254 // binary operator. 5255 Out << "ix"; 5256 mangleExpression(AE->getLHS()); 5257 mangleExpression(AE->getRHS()); 5258 break; 5259 } 5260 5261 case Expr::MatrixSubscriptExprClass: { 5262 NotPrimaryExpr(); 5263 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E); 5264 Out << "ixix"; 5265 mangleExpression(ME->getBase()); 5266 mangleExpression(ME->getRowIdx()); 5267 mangleExpression(ME->getColumnIdx()); 5268 break; 5269 } 5270 5271 case Expr::CompoundAssignOperatorClass: // fallthrough 5272 case Expr::BinaryOperatorClass: { 5273 NotPrimaryExpr(); 5274 const BinaryOperator *BO = cast<BinaryOperator>(E); 5275 if (BO->getOpcode() == BO_PtrMemD) 5276 Out << "ds"; 5277 else 5278 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()), 5279 /*Arity=*/2); 5280 mangleExpression(BO->getLHS()); 5281 mangleExpression(BO->getRHS()); 5282 break; 5283 } 5284 5285 case Expr::CXXRewrittenBinaryOperatorClass: { 5286 NotPrimaryExpr(); 5287 // The mangled form represents the original syntax. 5288 CXXRewrittenBinaryOperator::DecomposedForm Decomposed = 5289 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm(); 5290 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode), 5291 /*Arity=*/2); 5292 mangleExpression(Decomposed.LHS); 5293 mangleExpression(Decomposed.RHS); 5294 break; 5295 } 5296 5297 case Expr::ConditionalOperatorClass: { 5298 NotPrimaryExpr(); 5299 const ConditionalOperator *CO = cast<ConditionalOperator>(E); 5300 mangleOperatorName(OO_Conditional, /*Arity=*/3); 5301 mangleExpression(CO->getCond()); 5302 mangleExpression(CO->getLHS(), Arity); 5303 mangleExpression(CO->getRHS(), Arity); 5304 break; 5305 } 5306 5307 case Expr::ImplicitCastExprClass: { 5308 ImplicitlyConvertedToType = E->getType(); 5309 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 5310 goto recurse; 5311 } 5312 5313 case Expr::ObjCBridgedCastExprClass: { 5314 NotPrimaryExpr(); 5315 // Mangle ownership casts as a vendor extended operator __bridge, 5316 // __bridge_transfer, or __bridge_retain. 5317 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); 5318 Out << "v1U" << Kind.size() << Kind; 5319 mangleCastExpression(E, "cv"); 5320 break; 5321 } 5322 5323 case Expr::CStyleCastExprClass: 5324 NotPrimaryExpr(); 5325 mangleCastExpression(E, "cv"); 5326 break; 5327 5328 case Expr::CXXFunctionalCastExprClass: { 5329 NotPrimaryExpr(); 5330 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit(); 5331 // FIXME: Add isImplicit to CXXConstructExpr. 5332 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub)) 5333 if (CCE->getParenOrBraceRange().isInvalid()) 5334 Sub = CCE->getArg(0)->IgnoreImplicit(); 5335 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub)) 5336 Sub = StdInitList->getSubExpr()->IgnoreImplicit(); 5337 if (auto *IL = dyn_cast<InitListExpr>(Sub)) { 5338 Out << "tl"; 5339 mangleType(E->getType()); 5340 mangleInitListElements(IL); 5341 Out << "E"; 5342 } else { 5343 mangleCastExpression(E, "cv"); 5344 } 5345 break; 5346 } 5347 5348 case Expr::CXXStaticCastExprClass: 5349 NotPrimaryExpr(); 5350 mangleCastExpression(E, "sc"); 5351 break; 5352 case Expr::CXXDynamicCastExprClass: 5353 NotPrimaryExpr(); 5354 mangleCastExpression(E, "dc"); 5355 break; 5356 case Expr::CXXReinterpretCastExprClass: 5357 NotPrimaryExpr(); 5358 mangleCastExpression(E, "rc"); 5359 break; 5360 case Expr::CXXConstCastExprClass: 5361 NotPrimaryExpr(); 5362 mangleCastExpression(E, "cc"); 5363 break; 5364 case Expr::CXXAddrspaceCastExprClass: 5365 NotPrimaryExpr(); 5366 mangleCastExpression(E, "ac"); 5367 break; 5368 5369 case Expr::CXXOperatorCallExprClass: { 5370 NotPrimaryExpr(); 5371 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E); 5372 unsigned NumArgs = CE->getNumArgs(); 5373 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax 5374 // (the enclosing MemberExpr covers the syntactic portion). 5375 if (CE->getOperator() != OO_Arrow) 5376 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs); 5377 // Mangle the arguments. 5378 for (unsigned i = 0; i != NumArgs; ++i) 5379 mangleExpression(CE->getArg(i)); 5380 break; 5381 } 5382 5383 case Expr::ParenExprClass: 5384 E = cast<ParenExpr>(E)->getSubExpr(); 5385 goto recurse; 5386 5387 case Expr::ConceptSpecializationExprClass: { 5388 auto *CSE = cast<ConceptSpecializationExpr>(E); 5389 if (isCompatibleWith(LangOptions::ClangABI::Ver17)) { 5390 // Clang 17 and before mangled concept-ids as if they resolved to an 5391 // entity, meaning that references to enclosing template arguments don't 5392 // work. 5393 Out << "L_Z"; 5394 mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments()); 5395 Out << 'E'; 5396 break; 5397 } 5398 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24. 5399 NotPrimaryExpr(); 5400 mangleUnresolvedName( 5401 CSE->getNestedNameSpecifierLoc().getNestedNameSpecifier(), 5402 CSE->getConceptNameInfo().getName(), 5403 CSE->getTemplateArgsAsWritten()->getTemplateArgs(), 5404 CSE->getTemplateArgsAsWritten()->getNumTemplateArgs()); 5405 break; 5406 } 5407 5408 case Expr::RequiresExprClass: { 5409 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/24. 5410 auto *RE = cast<RequiresExpr>(E); 5411 // This is a primary-expression in the C++ grammar, but does not have an 5412 // <expr-primary> mangling (starting with 'L'). 5413 NotPrimaryExpr(); 5414 if (RE->getLParenLoc().isValid()) { 5415 Out << "rQ"; 5416 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 5417 if (RE->getLocalParameters().empty()) { 5418 Out << 'v'; 5419 } else { 5420 for (ParmVarDecl *Param : RE->getLocalParameters()) { 5421 mangleType(Context.getASTContext().getSignatureParameterType( 5422 Param->getType())); 5423 } 5424 } 5425 Out << '_'; 5426 5427 // The rest of the mangling is in the immediate scope of the parameters. 5428 FunctionTypeDepth.enterResultType(); 5429 for (const concepts::Requirement *Req : RE->getRequirements()) 5430 mangleRequirement(RE->getExprLoc(), Req); 5431 FunctionTypeDepth.pop(saved); 5432 Out << 'E'; 5433 } else { 5434 Out << "rq"; 5435 for (const concepts::Requirement *Req : RE->getRequirements()) 5436 mangleRequirement(RE->getExprLoc(), Req); 5437 Out << 'E'; 5438 } 5439 break; 5440 } 5441 5442 case Expr::DeclRefExprClass: 5443 // MangleDeclRefExpr helper handles primary-vs-nonprimary 5444 MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl()); 5445 break; 5446 5447 case Expr::SubstNonTypeTemplateParmPackExprClass: 5448 NotPrimaryExpr(); 5449 // FIXME: not clear how to mangle this! 5450 // template <unsigned N...> class A { 5451 // template <class U...> void foo(U (&x)[N]...); 5452 // }; 5453 Out << "_SUBSTPACK_"; 5454 break; 5455 5456 case Expr::FunctionParmPackExprClass: { 5457 NotPrimaryExpr(); 5458 // FIXME: not clear how to mangle this! 5459 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E); 5460 Out << "v110_SUBSTPACK"; 5461 MangleDeclRefExpr(FPPE->getParameterPack()); 5462 break; 5463 } 5464 5465 case Expr::DependentScopeDeclRefExprClass: { 5466 NotPrimaryExpr(); 5467 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E); 5468 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), 5469 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(), 5470 Arity); 5471 break; 5472 } 5473 5474 case Expr::CXXBindTemporaryExprClass: 5475 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr(); 5476 goto recurse; 5477 5478 case Expr::ExprWithCleanupsClass: 5479 E = cast<ExprWithCleanups>(E)->getSubExpr(); 5480 goto recurse; 5481 5482 case Expr::FloatingLiteralClass: { 5483 // <expr-primary> 5484 const FloatingLiteral *FL = cast<FloatingLiteral>(E); 5485 mangleFloatLiteral(FL->getType(), FL->getValue()); 5486 break; 5487 } 5488 5489 case Expr::FixedPointLiteralClass: 5490 // Currently unimplemented -- might be <expr-primary> in future? 5491 mangleFixedPointLiteral(); 5492 break; 5493 5494 case Expr::CharacterLiteralClass: 5495 // <expr-primary> 5496 Out << 'L'; 5497 mangleType(E->getType()); 5498 Out << cast<CharacterLiteral>(E)->getValue(); 5499 Out << 'E'; 5500 break; 5501 5502 // FIXME. __objc_yes/__objc_no are mangled same as true/false 5503 case Expr::ObjCBoolLiteralExprClass: 5504 // <expr-primary> 5505 Out << "Lb"; 5506 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 5507 Out << 'E'; 5508 break; 5509 5510 case Expr::CXXBoolLiteralExprClass: 5511 // <expr-primary> 5512 Out << "Lb"; 5513 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 5514 Out << 'E'; 5515 break; 5516 5517 case Expr::IntegerLiteralClass: { 5518 // <expr-primary> 5519 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue()); 5520 if (E->getType()->isSignedIntegerType()) 5521 Value.setIsSigned(true); 5522 mangleIntegerLiteral(E->getType(), Value); 5523 break; 5524 } 5525 5526 case Expr::ImaginaryLiteralClass: { 5527 // <expr-primary> 5528 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E); 5529 // Mangle as if a complex literal. 5530 // Proposal from David Vandevoorde, 2010.06.30. 5531 Out << 'L'; 5532 mangleType(E->getType()); 5533 if (const FloatingLiteral *Imag = 5534 dyn_cast<FloatingLiteral>(IE->getSubExpr())) { 5535 // Mangle a floating-point zero of the appropriate type. 5536 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics())); 5537 Out << '_'; 5538 mangleFloat(Imag->getValue()); 5539 } else { 5540 Out << "0_"; 5541 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue()); 5542 if (IE->getSubExpr()->getType()->isSignedIntegerType()) 5543 Value.setIsSigned(true); 5544 mangleNumber(Value); 5545 } 5546 Out << 'E'; 5547 break; 5548 } 5549 5550 case Expr::StringLiteralClass: { 5551 // <expr-primary> 5552 // Revised proposal from David Vandervoorde, 2010.07.15. 5553 Out << 'L'; 5554 assert(isa<ConstantArrayType>(E->getType())); 5555 mangleType(E->getType()); 5556 Out << 'E'; 5557 break; 5558 } 5559 5560 case Expr::GNUNullExprClass: 5561 // <expr-primary> 5562 // Mangle as if an integer literal 0. 5563 mangleIntegerLiteral(E->getType(), llvm::APSInt(32)); 5564 break; 5565 5566 case Expr::CXXNullPtrLiteralExprClass: { 5567 // <expr-primary> 5568 Out << "LDnE"; 5569 break; 5570 } 5571 5572 case Expr::LambdaExprClass: { 5573 // A lambda-expression can't appear in the signature of an 5574 // externally-visible declaration, so there's no standard mangling for 5575 // this, but mangling as a literal of the closure type seems reasonable. 5576 Out << "L"; 5577 mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass())); 5578 Out << "E"; 5579 break; 5580 } 5581 5582 case Expr::PackExpansionExprClass: 5583 NotPrimaryExpr(); 5584 Out << "sp"; 5585 mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); 5586 break; 5587 5588 case Expr::SizeOfPackExprClass: { 5589 NotPrimaryExpr(); 5590 auto *SPE = cast<SizeOfPackExpr>(E); 5591 if (SPE->isPartiallySubstituted()) { 5592 Out << "sP"; 5593 for (const auto &A : SPE->getPartialArguments()) 5594 mangleTemplateArg(A, false); 5595 Out << "E"; 5596 break; 5597 } 5598 5599 Out << "sZ"; 5600 const NamedDecl *Pack = SPE->getPack(); 5601 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack)) 5602 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 5603 else if (const NonTypeTemplateParmDecl *NTTP 5604 = dyn_cast<NonTypeTemplateParmDecl>(Pack)) 5605 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex()); 5606 else if (const TemplateTemplateParmDecl *TempTP 5607 = dyn_cast<TemplateTemplateParmDecl>(Pack)) 5608 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex()); 5609 else 5610 mangleFunctionParam(cast<ParmVarDecl>(Pack)); 5611 break; 5612 } 5613 5614 case Expr::MaterializeTemporaryExprClass: 5615 E = cast<MaterializeTemporaryExpr>(E)->getSubExpr(); 5616 goto recurse; 5617 5618 case Expr::CXXFoldExprClass: { 5619 NotPrimaryExpr(); 5620 auto *FE = cast<CXXFoldExpr>(E); 5621 if (FE->isLeftFold()) 5622 Out << (FE->getInit() ? "fL" : "fl"); 5623 else 5624 Out << (FE->getInit() ? "fR" : "fr"); 5625 5626 if (FE->getOperator() == BO_PtrMemD) 5627 Out << "ds"; 5628 else 5629 mangleOperatorName( 5630 BinaryOperator::getOverloadedOperator(FE->getOperator()), 5631 /*Arity=*/2); 5632 5633 if (FE->getLHS()) 5634 mangleExpression(FE->getLHS()); 5635 if (FE->getRHS()) 5636 mangleExpression(FE->getRHS()); 5637 break; 5638 } 5639 5640 case Expr::CXXThisExprClass: 5641 NotPrimaryExpr(); 5642 Out << "fpT"; 5643 break; 5644 5645 case Expr::CoawaitExprClass: 5646 // FIXME: Propose a non-vendor mangling. 5647 NotPrimaryExpr(); 5648 Out << "v18co_await"; 5649 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 5650 break; 5651 5652 case Expr::DependentCoawaitExprClass: 5653 // FIXME: Propose a non-vendor mangling. 5654 NotPrimaryExpr(); 5655 Out << "v18co_await"; 5656 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand()); 5657 break; 5658 5659 case Expr::CoyieldExprClass: 5660 // FIXME: Propose a non-vendor mangling. 5661 NotPrimaryExpr(); 5662 Out << "v18co_yield"; 5663 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 5664 break; 5665 case Expr::SYCLUniqueStableNameExprClass: { 5666 const auto *USN = cast<SYCLUniqueStableNameExpr>(E); 5667 NotPrimaryExpr(); 5668 5669 Out << "u33__builtin_sycl_unique_stable_name"; 5670 mangleType(USN->getTypeSourceInfo()->getType()); 5671 5672 Out << "E"; 5673 break; 5674 } 5675 } 5676 5677 if (AsTemplateArg && !IsPrimaryExpr) 5678 Out << 'E'; 5679 } 5680 5681 /// Mangle an expression which refers to a parameter variable. 5682 /// 5683 /// <expression> ::= <function-param> 5684 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0 5685 /// <function-param> ::= fp <top-level CV-qualifiers> 5686 /// <parameter-2 non-negative number> _ # L == 0, I > 0 5687 /// <function-param> ::= fL <L-1 non-negative number> 5688 /// p <top-level CV-qualifiers> _ # L > 0, I == 0 5689 /// <function-param> ::= fL <L-1 non-negative number> 5690 /// p <top-level CV-qualifiers> 5691 /// <I-1 non-negative number> _ # L > 0, I > 0 5692 /// 5693 /// L is the nesting depth of the parameter, defined as 1 if the 5694 /// parameter comes from the innermost function prototype scope 5695 /// enclosing the current context, 2 if from the next enclosing 5696 /// function prototype scope, and so on, with one special case: if 5697 /// we've processed the full parameter clause for the innermost 5698 /// function type, then L is one less. This definition conveniently 5699 /// makes it irrelevant whether a function's result type was written 5700 /// trailing or leading, but is otherwise overly complicated; the 5701 /// numbering was first designed without considering references to 5702 /// parameter in locations other than return types, and then the 5703 /// mangling had to be generalized without changing the existing 5704 /// manglings. 5705 /// 5706 /// I is the zero-based index of the parameter within its parameter 5707 /// declaration clause. Note that the original ABI document describes 5708 /// this using 1-based ordinals. 5709 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) { 5710 unsigned parmDepth = parm->getFunctionScopeDepth(); 5711 unsigned parmIndex = parm->getFunctionScopeIndex(); 5712 5713 // Compute 'L'. 5714 // parmDepth does not include the declaring function prototype. 5715 // FunctionTypeDepth does account for that. 5716 assert(parmDepth < FunctionTypeDepth.getDepth()); 5717 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth; 5718 if (FunctionTypeDepth.isInResultType()) 5719 nestingDepth--; 5720 5721 if (nestingDepth == 0) { 5722 Out << "fp"; 5723 } else { 5724 Out << "fL" << (nestingDepth - 1) << 'p'; 5725 } 5726 5727 // Top-level qualifiers. We don't have to worry about arrays here, 5728 // because parameters declared as arrays should already have been 5729 // transformed to have pointer type. FIXME: apparently these don't 5730 // get mangled if used as an rvalue of a known non-class type? 5731 assert(!parm->getType()->isArrayType() 5732 && "parameter's type is still an array type?"); 5733 5734 if (const DependentAddressSpaceType *DAST = 5735 dyn_cast<DependentAddressSpaceType>(parm->getType())) { 5736 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST); 5737 } else { 5738 mangleQualifiers(parm->getType().getQualifiers()); 5739 } 5740 5741 // Parameter index. 5742 if (parmIndex != 0) { 5743 Out << (parmIndex - 1); 5744 } 5745 Out << '_'; 5746 } 5747 5748 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T, 5749 const CXXRecordDecl *InheritedFrom) { 5750 // <ctor-dtor-name> ::= C1 # complete object constructor 5751 // ::= C2 # base object constructor 5752 // ::= CI1 <type> # complete inheriting constructor 5753 // ::= CI2 <type> # base inheriting constructor 5754 // 5755 // In addition, C5 is a comdat name with C1 and C2 in it. 5756 Out << 'C'; 5757 if (InheritedFrom) 5758 Out << 'I'; 5759 switch (T) { 5760 case Ctor_Complete: 5761 Out << '1'; 5762 break; 5763 case Ctor_Base: 5764 Out << '2'; 5765 break; 5766 case Ctor_Comdat: 5767 Out << '5'; 5768 break; 5769 case Ctor_DefaultClosure: 5770 case Ctor_CopyingClosure: 5771 llvm_unreachable("closure constructors don't exist for the Itanium ABI!"); 5772 } 5773 if (InheritedFrom) 5774 mangleName(InheritedFrom); 5775 } 5776 5777 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 5778 // <ctor-dtor-name> ::= D0 # deleting destructor 5779 // ::= D1 # complete object destructor 5780 // ::= D2 # base object destructor 5781 // 5782 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it. 5783 switch (T) { 5784 case Dtor_Deleting: 5785 Out << "D0"; 5786 break; 5787 case Dtor_Complete: 5788 Out << "D1"; 5789 break; 5790 case Dtor_Base: 5791 Out << "D2"; 5792 break; 5793 case Dtor_Comdat: 5794 Out << "D5"; 5795 break; 5796 } 5797 } 5798 5799 // Helper to provide ancillary information on a template used to mangle its 5800 // arguments. 5801 struct CXXNameMangler::TemplateArgManglingInfo { 5802 const CXXNameMangler &Mangler; 5803 TemplateDecl *ResolvedTemplate = nullptr; 5804 bool SeenPackExpansionIntoNonPack = false; 5805 const NamedDecl *UnresolvedExpandedPack = nullptr; 5806 5807 TemplateArgManglingInfo(const CXXNameMangler &Mangler, TemplateName TN) 5808 : Mangler(Mangler) { 5809 if (TemplateDecl *TD = TN.getAsTemplateDecl()) 5810 ResolvedTemplate = TD; 5811 } 5812 5813 /// Information about how to mangle a template argument. 5814 struct Info { 5815 /// Do we need to mangle the template argument with an exactly correct type? 5816 bool NeedExactType; 5817 /// If we need to prefix the mangling with a mangling of the template 5818 /// parameter, the corresponding parameter. 5819 const NamedDecl *TemplateParameterToMangle; 5820 }; 5821 5822 /// Determine whether the resolved template might be overloaded on its 5823 /// template parameter list. If so, the mangling needs to include enough 5824 /// information to reconstruct the template parameter list. 5825 bool isOverloadable() { 5826 // Function templates are generally overloadable. As a special case, a 5827 // member function template of a generic lambda is not overloadable. 5828 if (auto *FTD = dyn_cast_or_null<FunctionTemplateDecl>(ResolvedTemplate)) { 5829 auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext()); 5830 if (!RD || !RD->isGenericLambda()) 5831 return true; 5832 } 5833 5834 // All other templates are not overloadable. Partial specializations would 5835 // be, but we never mangle them. 5836 return false; 5837 } 5838 5839 /// Determine whether we need to prefix this <template-arg> mangling with a 5840 /// <template-param-decl>. This happens if the natural template parameter for 5841 /// the argument mangling is not the same as the actual template parameter. 5842 bool needToMangleTemplateParam(const NamedDecl *Param, 5843 const TemplateArgument &Arg) { 5844 // For a template type parameter, the natural parameter is 'typename T'. 5845 // The actual parameter might be constrained. 5846 if (auto *TTP = dyn_cast<TemplateTypeParmDecl>(Param)) 5847 return TTP->hasTypeConstraint(); 5848 5849 if (Arg.getKind() == TemplateArgument::Pack) { 5850 // For an empty pack, the natural parameter is `typename...`. 5851 if (Arg.pack_size() == 0) 5852 return true; 5853 5854 // For any other pack, we use the first argument to determine the natural 5855 // template parameter. 5856 return needToMangleTemplateParam(Param, *Arg.pack_begin()); 5857 } 5858 5859 // For a non-type template parameter, the natural parameter is `T V` (for a 5860 // prvalue argument) or `T &V` (for a glvalue argument), where `T` is the 5861 // type of the argument, which we require to exactly match. If the actual 5862 // parameter has a deduced or instantiation-dependent type, it is not 5863 // equivalent to the natural parameter. 5864 if (auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param)) 5865 return NTTP->getType()->isInstantiationDependentType() || 5866 NTTP->getType()->getContainedDeducedType(); 5867 5868 // For a template template parameter, the template-head might differ from 5869 // that of the template. 5870 auto *TTP = cast<TemplateTemplateParmDecl>(Param); 5871 TemplateName ArgTemplateName = Arg.getAsTemplateOrTemplatePattern(); 5872 const TemplateDecl *ArgTemplate = ArgTemplateName.getAsTemplateDecl(); 5873 if (!ArgTemplate) 5874 return true; 5875 5876 // Mangle the template parameter list of the parameter and argument to see 5877 // if they are the same. We can't use Profile for this, because it can't 5878 // model the depth difference between parameter and argument and might not 5879 // necessarily have the same definition of "identical" that we use here -- 5880 // that is, same mangling. 5881 auto MangleTemplateParamListToString = 5882 [&](SmallVectorImpl<char> &Buffer, const TemplateParameterList *Params, 5883 unsigned DepthOffset) { 5884 llvm::raw_svector_ostream Stream(Buffer); 5885 CXXNameMangler(Mangler.Context, Stream, 5886 WithTemplateDepthOffset{DepthOffset}) 5887 .mangleTemplateParameterList(Params); 5888 }; 5889 llvm::SmallString<128> ParamTemplateHead, ArgTemplateHead; 5890 MangleTemplateParamListToString(ParamTemplateHead, 5891 TTP->getTemplateParameters(), 0); 5892 // Add the depth of the parameter's template parameter list to all 5893 // parameters appearing in the argument to make the indexes line up 5894 // properly. 5895 MangleTemplateParamListToString(ArgTemplateHead, 5896 ArgTemplate->getTemplateParameters(), 5897 TTP->getTemplateParameters()->getDepth()); 5898 return ParamTemplateHead != ArgTemplateHead; 5899 } 5900 5901 /// Determine information about how this template argument should be mangled. 5902 /// This should be called exactly once for each parameter / argument pair, in 5903 /// order. 5904 Info getArgInfo(unsigned ParamIdx, const TemplateArgument &Arg) { 5905 // We need correct types when the template-name is unresolved or when it 5906 // names a template that is able to be overloaded. 5907 if (!ResolvedTemplate || SeenPackExpansionIntoNonPack) 5908 return {true, nullptr}; 5909 5910 // Move to the next parameter. 5911 const NamedDecl *Param = UnresolvedExpandedPack; 5912 if (!Param) { 5913 assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() && 5914 "no parameter for argument"); 5915 Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx); 5916 5917 // If we reach a parameter pack whose argument isn't in pack form, that 5918 // means Sema couldn't or didn't figure out which arguments belonged to 5919 // it, because it contains a pack expansion or because Sema bailed out of 5920 // computing parameter / argument correspondence before this point. Track 5921 // the pack as the corresponding parameter for all further template 5922 // arguments until we hit a pack expansion, at which point we don't know 5923 // the correspondence between parameters and arguments at all. 5924 if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) { 5925 UnresolvedExpandedPack = Param; 5926 } 5927 } 5928 5929 // If we encounter a pack argument that is expanded into a non-pack 5930 // parameter, we can no longer track parameter / argument correspondence, 5931 // and need to use exact types from this point onwards. 5932 if (Arg.isPackExpansion() && 5933 (!Param->isParameterPack() || UnresolvedExpandedPack)) { 5934 SeenPackExpansionIntoNonPack = true; 5935 return {true, nullptr}; 5936 } 5937 5938 // We need exact types for arguments of a template that might be overloaded 5939 // on template parameter type. 5940 if (isOverloadable()) 5941 return {true, needToMangleTemplateParam(Param, Arg) ? Param : nullptr}; 5942 5943 // Otherwise, we only need a correct type if the parameter has a deduced 5944 // type. 5945 // 5946 // Note: for an expanded parameter pack, getType() returns the type prior 5947 // to expansion. We could ask for the expanded type with getExpansionType(), 5948 // but it doesn't matter because substitution and expansion don't affect 5949 // whether a deduced type appears in the type. 5950 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param); 5951 bool NeedExactType = NTTP && NTTP->getType()->getContainedDeducedType(); 5952 return {NeedExactType, nullptr}; 5953 } 5954 5955 /// Determine if we should mangle a requires-clause after the template 5956 /// argument list. If so, returns the expression to mangle. 5957 const Expr *getTrailingRequiresClauseToMangle() { 5958 if (!isOverloadable()) 5959 return nullptr; 5960 return ResolvedTemplate->getTemplateParameters()->getRequiresClause(); 5961 } 5962 }; 5963 5964 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 5965 const TemplateArgumentLoc *TemplateArgs, 5966 unsigned NumTemplateArgs) { 5967 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E 5968 Out << 'I'; 5969 TemplateArgManglingInfo Info(*this, TN); 5970 for (unsigned i = 0; i != NumTemplateArgs; ++i) { 5971 mangleTemplateArg(Info, i, TemplateArgs[i].getArgument()); 5972 } 5973 mangleRequiresClause(Info.getTrailingRequiresClauseToMangle()); 5974 Out << 'E'; 5975 } 5976 5977 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 5978 const TemplateArgumentList &AL) { 5979 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E 5980 Out << 'I'; 5981 TemplateArgManglingInfo Info(*this, TN); 5982 for (unsigned i = 0, e = AL.size(); i != e; ++i) { 5983 mangleTemplateArg(Info, i, AL[i]); 5984 } 5985 mangleRequiresClause(Info.getTrailingRequiresClauseToMangle()); 5986 Out << 'E'; 5987 } 5988 5989 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 5990 ArrayRef<TemplateArgument> Args) { 5991 // <template-args> ::= I <template-arg>+ [Q <requires-clause expr>] E 5992 Out << 'I'; 5993 TemplateArgManglingInfo Info(*this, TN); 5994 for (unsigned i = 0; i != Args.size(); ++i) { 5995 mangleTemplateArg(Info, i, Args[i]); 5996 } 5997 mangleRequiresClause(Info.getTrailingRequiresClauseToMangle()); 5998 Out << 'E'; 5999 } 6000 6001 void CXXNameMangler::mangleTemplateArg(TemplateArgManglingInfo &Info, 6002 unsigned Index, TemplateArgument A) { 6003 TemplateArgManglingInfo::Info ArgInfo = Info.getArgInfo(Index, A); 6004 6005 // Proposed on https://github.com/itanium-cxx-abi/cxx-abi/issues/47. 6006 if (ArgInfo.TemplateParameterToMangle && 6007 !isCompatibleWith(LangOptions::ClangABI::Ver17)) { 6008 // The template parameter is mangled if the mangling would otherwise be 6009 // ambiguous. 6010 // 6011 // <template-arg> ::= <template-param-decl> <template-arg> 6012 // 6013 // Clang 17 and before did not do this. 6014 mangleTemplateParamDecl(ArgInfo.TemplateParameterToMangle); 6015 } 6016 6017 mangleTemplateArg(A, ArgInfo.NeedExactType); 6018 } 6019 6020 void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) { 6021 // <template-arg> ::= <type> # type or template 6022 // ::= X <expression> E # expression 6023 // ::= <expr-primary> # simple expressions 6024 // ::= J <template-arg>* E # argument pack 6025 if (!A.isInstantiationDependent() || A.isDependent()) 6026 A = Context.getASTContext().getCanonicalTemplateArgument(A); 6027 6028 switch (A.getKind()) { 6029 case TemplateArgument::Null: 6030 llvm_unreachable("Cannot mangle NULL template argument"); 6031 6032 case TemplateArgument::Type: 6033 mangleType(A.getAsType()); 6034 break; 6035 case TemplateArgument::Template: 6036 // This is mangled as <type>. 6037 mangleType(A.getAsTemplate()); 6038 break; 6039 case TemplateArgument::TemplateExpansion: 6040 // <type> ::= Dp <type> # pack expansion (C++0x) 6041 Out << "Dp"; 6042 mangleType(A.getAsTemplateOrTemplatePattern()); 6043 break; 6044 case TemplateArgument::Expression: 6045 mangleTemplateArgExpr(A.getAsExpr()); 6046 break; 6047 case TemplateArgument::Integral: 6048 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral()); 6049 break; 6050 case TemplateArgument::Declaration: { 6051 // <expr-primary> ::= L <mangled-name> E # external name 6052 ValueDecl *D = A.getAsDecl(); 6053 6054 // Template parameter objects are modeled by reproducing a source form 6055 // produced as if by aggregate initialization. 6056 if (A.getParamTypeForDecl()->isRecordType()) { 6057 auto *TPO = cast<TemplateParamObjectDecl>(D); 6058 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(), 6059 TPO->getValue(), /*TopLevel=*/true, 6060 NeedExactType); 6061 break; 6062 } 6063 6064 ASTContext &Ctx = Context.getASTContext(); 6065 APValue Value; 6066 if (D->isCXXInstanceMember()) 6067 // Simple pointer-to-member with no conversion. 6068 Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{}); 6069 else if (D->getType()->isArrayType() && 6070 Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()), 6071 A.getParamTypeForDecl()) && 6072 !isCompatibleWith(LangOptions::ClangABI::Ver11)) 6073 // Build a value corresponding to this implicit array-to-pointer decay. 6074 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(), 6075 {APValue::LValuePathEntry::ArrayIndex(0)}, 6076 /*OnePastTheEnd=*/false); 6077 else 6078 // Regular pointer or reference to a declaration. 6079 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(), 6080 ArrayRef<APValue::LValuePathEntry>(), 6081 /*OnePastTheEnd=*/false); 6082 mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true, 6083 NeedExactType); 6084 break; 6085 } 6086 case TemplateArgument::NullPtr: { 6087 mangleNullPointer(A.getNullPtrType()); 6088 break; 6089 } 6090 case TemplateArgument::StructuralValue: 6091 mangleValueInTemplateArg(A.getStructuralValueType(), 6092 A.getAsStructuralValue(), 6093 /*TopLevel=*/true, NeedExactType); 6094 break; 6095 case TemplateArgument::Pack: { 6096 // <template-arg> ::= J <template-arg>* E 6097 Out << 'J'; 6098 for (const auto &P : A.pack_elements()) 6099 mangleTemplateArg(P, NeedExactType); 6100 Out << 'E'; 6101 } 6102 } 6103 } 6104 6105 void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) { 6106 if (!isCompatibleWith(LangOptions::ClangABI::Ver11)) { 6107 mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true); 6108 return; 6109 } 6110 6111 // Prior to Clang 12, we didn't omit the X .. E around <expr-primary> 6112 // correctly in cases where the template argument was 6113 // constructed from an expression rather than an already-evaluated 6114 // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of 6115 // 'Li0E'. 6116 // 6117 // We did special-case DeclRefExpr to attempt to DTRT for that one 6118 // expression-kind, but while doing so, unfortunately handled ParmVarDecl 6119 // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of 6120 // the proper 'Xfp_E'. 6121 E = E->IgnoreParenImpCasts(); 6122 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 6123 const ValueDecl *D = DRE->getDecl(); 6124 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) { 6125 Out << 'L'; 6126 mangle(D); 6127 Out << 'E'; 6128 return; 6129 } 6130 } 6131 Out << 'X'; 6132 mangleExpression(E); 6133 Out << 'E'; 6134 } 6135 6136 /// Determine whether a given value is equivalent to zero-initialization for 6137 /// the purpose of discarding a trailing portion of a 'tl' mangling. 6138 /// 6139 /// Note that this is not in general equivalent to determining whether the 6140 /// value has an all-zeroes bit pattern. 6141 static bool isZeroInitialized(QualType T, const APValue &V) { 6142 // FIXME: mangleValueInTemplateArg has quadratic time complexity in 6143 // pathological cases due to using this, but it's a little awkward 6144 // to do this in linear time in general. 6145 switch (V.getKind()) { 6146 case APValue::None: 6147 case APValue::Indeterminate: 6148 case APValue::AddrLabelDiff: 6149 return false; 6150 6151 case APValue::Struct: { 6152 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6153 assert(RD && "unexpected type for record value"); 6154 unsigned I = 0; 6155 for (const CXXBaseSpecifier &BS : RD->bases()) { 6156 if (!isZeroInitialized(BS.getType(), V.getStructBase(I))) 6157 return false; 6158 ++I; 6159 } 6160 I = 0; 6161 for (const FieldDecl *FD : RD->fields()) { 6162 if (!FD->isUnnamedBitfield() && 6163 !isZeroInitialized(FD->getType(), V.getStructField(I))) 6164 return false; 6165 ++I; 6166 } 6167 return true; 6168 } 6169 6170 case APValue::Union: { 6171 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6172 assert(RD && "unexpected type for union value"); 6173 // Zero-initialization zeroes the first non-unnamed-bitfield field, if any. 6174 for (const FieldDecl *FD : RD->fields()) { 6175 if (!FD->isUnnamedBitfield()) 6176 return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) && 6177 isZeroInitialized(FD->getType(), V.getUnionValue()); 6178 } 6179 // If there are no fields (other than unnamed bitfields), the value is 6180 // necessarily zero-initialized. 6181 return true; 6182 } 6183 6184 case APValue::Array: { 6185 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0); 6186 for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I) 6187 if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I))) 6188 return false; 6189 return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller()); 6190 } 6191 6192 case APValue::Vector: { 6193 const VectorType *VT = T->castAs<VectorType>(); 6194 for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I) 6195 if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I))) 6196 return false; 6197 return true; 6198 } 6199 6200 case APValue::Int: 6201 return !V.getInt(); 6202 6203 case APValue::Float: 6204 return V.getFloat().isPosZero(); 6205 6206 case APValue::FixedPoint: 6207 return !V.getFixedPoint().getValue(); 6208 6209 case APValue::ComplexFloat: 6210 return V.getComplexFloatReal().isPosZero() && 6211 V.getComplexFloatImag().isPosZero(); 6212 6213 case APValue::ComplexInt: 6214 return !V.getComplexIntReal() && !V.getComplexIntImag(); 6215 6216 case APValue::LValue: 6217 return V.isNullPointer(); 6218 6219 case APValue::MemberPointer: 6220 return !V.getMemberPointerDecl(); 6221 } 6222 6223 llvm_unreachable("Unhandled APValue::ValueKind enum"); 6224 } 6225 6226 static QualType getLValueType(ASTContext &Ctx, const APValue &LV) { 6227 QualType T = LV.getLValueBase().getType(); 6228 for (APValue::LValuePathEntry E : LV.getLValuePath()) { 6229 if (const ArrayType *AT = Ctx.getAsArrayType(T)) 6230 T = AT->getElementType(); 6231 else if (const FieldDecl *FD = 6232 dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer())) 6233 T = FD->getType(); 6234 else 6235 T = Ctx.getRecordType( 6236 cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer())); 6237 } 6238 return T; 6239 } 6240 6241 static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc, 6242 DiagnosticsEngine &Diags, 6243 const FieldDecl *FD) { 6244 // According to: 6245 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous 6246 // For the purposes of mangling, the name of an anonymous union is considered 6247 // to be the name of the first named data member found by a pre-order, 6248 // depth-first, declaration-order walk of the data members of the anonymous 6249 // union. 6250 6251 if (FD->getIdentifier()) 6252 return FD->getIdentifier(); 6253 6254 // The only cases where the identifer of a FieldDecl would be blank is if the 6255 // field represents an anonymous record type or if it is an unnamed bitfield. 6256 // There is no type to descend into in the case of a bitfield, so we can just 6257 // return nullptr in that case. 6258 if (FD->isBitField()) 6259 return nullptr; 6260 const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl(); 6261 6262 // Consider only the fields in declaration order, searched depth-first. We 6263 // don't care about the active member of the union, as all we are doing is 6264 // looking for a valid name. We also don't check bases, due to guidance from 6265 // the Itanium ABI folks. 6266 for (const FieldDecl *RDField : RD->fields()) { 6267 if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField)) 6268 return II; 6269 } 6270 6271 // According to the Itanium ABI: If there is no such data member (i.e., if all 6272 // of the data members in the union are unnamed), then there is no way for a 6273 // program to refer to the anonymous union, and there is therefore no need to 6274 // mangle its name. However, we should diagnose this anyway. 6275 unsigned DiagID = Diags.getCustomDiagID( 6276 DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet"); 6277 Diags.Report(UnionLoc, DiagID); 6278 6279 return nullptr; 6280 } 6281 6282 void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V, 6283 bool TopLevel, 6284 bool NeedExactType) { 6285 // Ignore all top-level cv-qualifiers, to match GCC. 6286 Qualifiers Quals; 6287 T = getASTContext().getUnqualifiedArrayType(T, Quals); 6288 6289 // A top-level expression that's not a primary expression is wrapped in X...E. 6290 bool IsPrimaryExpr = true; 6291 auto NotPrimaryExpr = [&] { 6292 if (TopLevel && IsPrimaryExpr) 6293 Out << 'X'; 6294 IsPrimaryExpr = false; 6295 }; 6296 6297 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63. 6298 switch (V.getKind()) { 6299 case APValue::None: 6300 case APValue::Indeterminate: 6301 Out << 'L'; 6302 mangleType(T); 6303 Out << 'E'; 6304 break; 6305 6306 case APValue::AddrLabelDiff: 6307 llvm_unreachable("unexpected value kind in template argument"); 6308 6309 case APValue::Struct: { 6310 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 6311 assert(RD && "unexpected type for record value"); 6312 6313 // Drop trailing zero-initialized elements. 6314 llvm::SmallVector<const FieldDecl *, 16> Fields(RD->fields()); 6315 while ( 6316 !Fields.empty() && 6317 (Fields.back()->isUnnamedBitfield() || 6318 isZeroInitialized(Fields.back()->getType(), 6319 V.getStructField(Fields.back()->getFieldIndex())))) { 6320 Fields.pop_back(); 6321 } 6322 llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end()); 6323 if (Fields.empty()) { 6324 while (!Bases.empty() && 6325 isZeroInitialized(Bases.back().getType(), 6326 V.getStructBase(Bases.size() - 1))) 6327 Bases = Bases.drop_back(); 6328 } 6329 6330 // <expression> ::= tl <type> <braced-expression>* E 6331 NotPrimaryExpr(); 6332 Out << "tl"; 6333 mangleType(T); 6334 for (unsigned I = 0, N = Bases.size(); I != N; ++I) 6335 mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false); 6336 for (unsigned I = 0, N = Fields.size(); I != N; ++I) { 6337 if (Fields[I]->isUnnamedBitfield()) 6338 continue; 6339 mangleValueInTemplateArg(Fields[I]->getType(), 6340 V.getStructField(Fields[I]->getFieldIndex()), 6341 false); 6342 } 6343 Out << 'E'; 6344 break; 6345 } 6346 6347 case APValue::Union: { 6348 assert(T->getAsCXXRecordDecl() && "unexpected type for union value"); 6349 const FieldDecl *FD = V.getUnionField(); 6350 6351 if (!FD) { 6352 Out << 'L'; 6353 mangleType(T); 6354 Out << 'E'; 6355 break; 6356 } 6357 6358 // <braced-expression> ::= di <field source-name> <braced-expression> 6359 NotPrimaryExpr(); 6360 Out << "tl"; 6361 mangleType(T); 6362 if (!isZeroInitialized(T, V)) { 6363 Out << "di"; 6364 IdentifierInfo *II = (getUnionInitName( 6365 T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD)); 6366 if (II) 6367 mangleSourceName(II); 6368 mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false); 6369 } 6370 Out << 'E'; 6371 break; 6372 } 6373 6374 case APValue::Array: { 6375 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0); 6376 6377 NotPrimaryExpr(); 6378 Out << "tl"; 6379 mangleType(T); 6380 6381 // Drop trailing zero-initialized elements. 6382 unsigned N = V.getArraySize(); 6383 if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) { 6384 N = V.getArrayInitializedElts(); 6385 while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1))) 6386 --N; 6387 } 6388 6389 for (unsigned I = 0; I != N; ++I) { 6390 const APValue &Elem = I < V.getArrayInitializedElts() 6391 ? V.getArrayInitializedElt(I) 6392 : V.getArrayFiller(); 6393 mangleValueInTemplateArg(ElemT, Elem, false); 6394 } 6395 Out << 'E'; 6396 break; 6397 } 6398 6399 case APValue::Vector: { 6400 const VectorType *VT = T->castAs<VectorType>(); 6401 6402 NotPrimaryExpr(); 6403 Out << "tl"; 6404 mangleType(T); 6405 unsigned N = V.getVectorLength(); 6406 while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1))) 6407 --N; 6408 for (unsigned I = 0; I != N; ++I) 6409 mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false); 6410 Out << 'E'; 6411 break; 6412 } 6413 6414 case APValue::Int: 6415 mangleIntegerLiteral(T, V.getInt()); 6416 break; 6417 6418 case APValue::Float: 6419 mangleFloatLiteral(T, V.getFloat()); 6420 break; 6421 6422 case APValue::FixedPoint: 6423 mangleFixedPointLiteral(); 6424 break; 6425 6426 case APValue::ComplexFloat: { 6427 const ComplexType *CT = T->castAs<ComplexType>(); 6428 NotPrimaryExpr(); 6429 Out << "tl"; 6430 mangleType(T); 6431 if (!V.getComplexFloatReal().isPosZero() || 6432 !V.getComplexFloatImag().isPosZero()) 6433 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal()); 6434 if (!V.getComplexFloatImag().isPosZero()) 6435 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag()); 6436 Out << 'E'; 6437 break; 6438 } 6439 6440 case APValue::ComplexInt: { 6441 const ComplexType *CT = T->castAs<ComplexType>(); 6442 NotPrimaryExpr(); 6443 Out << "tl"; 6444 mangleType(T); 6445 if (V.getComplexIntReal().getBoolValue() || 6446 V.getComplexIntImag().getBoolValue()) 6447 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal()); 6448 if (V.getComplexIntImag().getBoolValue()) 6449 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag()); 6450 Out << 'E'; 6451 break; 6452 } 6453 6454 case APValue::LValue: { 6455 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47. 6456 assert((T->isPointerType() || T->isReferenceType()) && 6457 "unexpected type for LValue template arg"); 6458 6459 if (V.isNullPointer()) { 6460 mangleNullPointer(T); 6461 break; 6462 } 6463 6464 APValue::LValueBase B = V.getLValueBase(); 6465 if (!B) { 6466 // Non-standard mangling for integer cast to a pointer; this can only 6467 // occur as an extension. 6468 CharUnits Offset = V.getLValueOffset(); 6469 if (Offset.isZero()) { 6470 // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as 6471 // a cast, because L <type> 0 E means something else. 6472 NotPrimaryExpr(); 6473 Out << "rc"; 6474 mangleType(T); 6475 Out << "Li0E"; 6476 if (TopLevel) 6477 Out << 'E'; 6478 } else { 6479 Out << "L"; 6480 mangleType(T); 6481 Out << Offset.getQuantity() << 'E'; 6482 } 6483 break; 6484 } 6485 6486 ASTContext &Ctx = Context.getASTContext(); 6487 6488 enum { Base, Offset, Path } Kind; 6489 if (!V.hasLValuePath()) { 6490 // Mangle as (T*)((char*)&base + N). 6491 if (T->isReferenceType()) { 6492 NotPrimaryExpr(); 6493 Out << "decvP"; 6494 mangleType(T->getPointeeType()); 6495 } else { 6496 NotPrimaryExpr(); 6497 Out << "cv"; 6498 mangleType(T); 6499 } 6500 Out << "plcvPcad"; 6501 Kind = Offset; 6502 } else { 6503 // Clang 11 and before mangled an array subject to array-to-pointer decay 6504 // as if it were the declaration itself. 6505 bool IsArrayToPointerDecayMangledAsDecl = false; 6506 if (TopLevel && Ctx.getLangOpts().getClangABICompat() <= 6507 LangOptions::ClangABI::Ver11) { 6508 QualType BType = B.getType(); 6509 IsArrayToPointerDecayMangledAsDecl = 6510 BType->isArrayType() && V.getLValuePath().size() == 1 && 6511 V.getLValuePath()[0].getAsArrayIndex() == 0 && 6512 Ctx.hasSimilarType(T, Ctx.getDecayedType(BType)); 6513 } 6514 6515 if ((!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) && 6516 !IsArrayToPointerDecayMangledAsDecl) { 6517 NotPrimaryExpr(); 6518 // A final conversion to the template parameter's type is usually 6519 // folded into the 'so' mangling, but we can't do that for 'void*' 6520 // parameters without introducing collisions. 6521 if (NeedExactType && T->isVoidPointerType()) { 6522 Out << "cv"; 6523 mangleType(T); 6524 } 6525 if (T->isPointerType()) 6526 Out << "ad"; 6527 Out << "so"; 6528 mangleType(T->isVoidPointerType() 6529 ? getLValueType(Ctx, V).getUnqualifiedType() 6530 : T->getPointeeType()); 6531 Kind = Path; 6532 } else { 6533 if (NeedExactType && 6534 !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) && 6535 !isCompatibleWith(LangOptions::ClangABI::Ver11)) { 6536 NotPrimaryExpr(); 6537 Out << "cv"; 6538 mangleType(T); 6539 } 6540 if (T->isPointerType()) { 6541 NotPrimaryExpr(); 6542 Out << "ad"; 6543 } 6544 Kind = Base; 6545 } 6546 } 6547 6548 QualType TypeSoFar = B.getType(); 6549 if (auto *VD = B.dyn_cast<const ValueDecl*>()) { 6550 Out << 'L'; 6551 mangle(VD); 6552 Out << 'E'; 6553 } else if (auto *E = B.dyn_cast<const Expr*>()) { 6554 NotPrimaryExpr(); 6555 mangleExpression(E); 6556 } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) { 6557 NotPrimaryExpr(); 6558 Out << "ti"; 6559 mangleType(QualType(TI.getType(), 0)); 6560 } else { 6561 // We should never see dynamic allocations here. 6562 llvm_unreachable("unexpected lvalue base kind in template argument"); 6563 } 6564 6565 switch (Kind) { 6566 case Base: 6567 break; 6568 6569 case Offset: 6570 Out << 'L'; 6571 mangleType(Ctx.getPointerDiffType()); 6572 mangleNumber(V.getLValueOffset().getQuantity()); 6573 Out << 'E'; 6574 break; 6575 6576 case Path: 6577 // <expression> ::= so <referent type> <expr> [<offset number>] 6578 // <union-selector>* [p] E 6579 if (!V.getLValueOffset().isZero()) 6580 mangleNumber(V.getLValueOffset().getQuantity()); 6581 6582 // We model a past-the-end array pointer as array indexing with index N, 6583 // not with the "past the end" flag. Compensate for that. 6584 bool OnePastTheEnd = V.isLValueOnePastTheEnd(); 6585 6586 for (APValue::LValuePathEntry E : V.getLValuePath()) { 6587 if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) { 6588 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 6589 OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex(); 6590 TypeSoFar = AT->getElementType(); 6591 } else { 6592 const Decl *D = E.getAsBaseOrMember().getPointer(); 6593 if (auto *FD = dyn_cast<FieldDecl>(D)) { 6594 // <union-selector> ::= _ <number> 6595 if (FD->getParent()->isUnion()) { 6596 Out << '_'; 6597 if (FD->getFieldIndex()) 6598 Out << (FD->getFieldIndex() - 1); 6599 } 6600 TypeSoFar = FD->getType(); 6601 } else { 6602 TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D)); 6603 } 6604 } 6605 } 6606 6607 if (OnePastTheEnd) 6608 Out << 'p'; 6609 Out << 'E'; 6610 break; 6611 } 6612 6613 break; 6614 } 6615 6616 case APValue::MemberPointer: 6617 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47. 6618 if (!V.getMemberPointerDecl()) { 6619 mangleNullPointer(T); 6620 break; 6621 } 6622 6623 ASTContext &Ctx = Context.getASTContext(); 6624 6625 NotPrimaryExpr(); 6626 if (!V.getMemberPointerPath().empty()) { 6627 Out << "mc"; 6628 mangleType(T); 6629 } else if (NeedExactType && 6630 !Ctx.hasSameType( 6631 T->castAs<MemberPointerType>()->getPointeeType(), 6632 V.getMemberPointerDecl()->getType()) && 6633 !isCompatibleWith(LangOptions::ClangABI::Ver11)) { 6634 Out << "cv"; 6635 mangleType(T); 6636 } 6637 Out << "adL"; 6638 mangle(V.getMemberPointerDecl()); 6639 Out << 'E'; 6640 if (!V.getMemberPointerPath().empty()) { 6641 CharUnits Offset = 6642 Context.getASTContext().getMemberPointerPathAdjustment(V); 6643 if (!Offset.isZero()) 6644 mangleNumber(Offset.getQuantity()); 6645 Out << 'E'; 6646 } 6647 break; 6648 } 6649 6650 if (TopLevel && !IsPrimaryExpr) 6651 Out << 'E'; 6652 } 6653 6654 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) { 6655 // <template-param> ::= T_ # first template parameter 6656 // ::= T <parameter-2 non-negative number> _ 6657 // ::= TL <L-1 non-negative number> __ 6658 // ::= TL <L-1 non-negative number> _ 6659 // <parameter-2 non-negative number> _ 6660 // 6661 // The latter two manglings are from a proposal here: 6662 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117 6663 Out << 'T'; 6664 Depth += TemplateDepthOffset; 6665 if (Depth != 0) 6666 Out << 'L' << (Depth - 1) << '_'; 6667 if (Index != 0) 6668 Out << (Index - 1); 6669 Out << '_'; 6670 } 6671 6672 void CXXNameMangler::mangleSeqID(unsigned SeqID) { 6673 if (SeqID == 0) { 6674 // Nothing. 6675 } else if (SeqID == 1) { 6676 Out << '0'; 6677 } else { 6678 SeqID--; 6679 6680 // <seq-id> is encoded in base-36, using digits and upper case letters. 6681 char Buffer[7]; // log(2**32) / log(36) ~= 7 6682 MutableArrayRef<char> BufferRef(Buffer); 6683 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin(); 6684 6685 for (; SeqID != 0; SeqID /= 36) { 6686 unsigned C = SeqID % 36; 6687 *I++ = (C < 10 ? '0' + C : 'A' + C - 10); 6688 } 6689 6690 Out.write(I.base(), I - BufferRef.rbegin()); 6691 } 6692 Out << '_'; 6693 } 6694 6695 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) { 6696 bool result = mangleSubstitution(tname); 6697 assert(result && "no existing substitution for template name"); 6698 (void) result; 6699 } 6700 6701 // <substitution> ::= S <seq-id> _ 6702 // ::= S_ 6703 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) { 6704 // Try one of the standard substitutions first. 6705 if (mangleStandardSubstitution(ND)) 6706 return true; 6707 6708 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 6709 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND)); 6710 } 6711 6712 bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) { 6713 assert(NNS->getKind() == NestedNameSpecifier::Identifier && 6714 "mangleSubstitution(NestedNameSpecifier *) is only used for " 6715 "identifier nested name specifiers."); 6716 NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS); 6717 return mangleSubstitution(reinterpret_cast<uintptr_t>(NNS)); 6718 } 6719 6720 /// Determine whether the given type has any qualifiers that are relevant for 6721 /// substitutions. 6722 static bool hasMangledSubstitutionQualifiers(QualType T) { 6723 Qualifiers Qs = T.getQualifiers(); 6724 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned(); 6725 } 6726 6727 bool CXXNameMangler::mangleSubstitution(QualType T) { 6728 if (!hasMangledSubstitutionQualifiers(T)) { 6729 if (const RecordType *RT = T->getAs<RecordType>()) 6730 return mangleSubstitution(RT->getDecl()); 6731 } 6732 6733 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 6734 6735 return mangleSubstitution(TypePtr); 6736 } 6737 6738 bool CXXNameMangler::mangleSubstitution(TemplateName Template) { 6739 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 6740 return mangleSubstitution(TD); 6741 6742 Template = Context.getASTContext().getCanonicalTemplateName(Template); 6743 return mangleSubstitution( 6744 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 6745 } 6746 6747 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) { 6748 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr); 6749 if (I == Substitutions.end()) 6750 return false; 6751 6752 unsigned SeqID = I->second; 6753 Out << 'S'; 6754 mangleSeqID(SeqID); 6755 6756 return true; 6757 } 6758 6759 /// Returns whether S is a template specialization of std::Name with a single 6760 /// argument of type A. 6761 bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name, 6762 QualType A) { 6763 if (S.isNull()) 6764 return false; 6765 6766 const RecordType *RT = S->getAs<RecordType>(); 6767 if (!RT) 6768 return false; 6769 6770 const ClassTemplateSpecializationDecl *SD = 6771 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 6772 if (!SD || !SD->getIdentifier()->isStr(Name)) 6773 return false; 6774 6775 if (!isStdNamespace(Context.getEffectiveDeclContext(SD))) 6776 return false; 6777 6778 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 6779 if (TemplateArgs.size() != 1) 6780 return false; 6781 6782 if (TemplateArgs[0].getAsType() != A) 6783 return false; 6784 6785 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage()) 6786 return false; 6787 6788 return true; 6789 } 6790 6791 /// Returns whether SD is a template specialization std::Name<char, 6792 /// std::char_traits<char> [, std::allocator<char>]> 6793 /// HasAllocator controls whether the 3rd template argument is needed. 6794 bool CXXNameMangler::isStdCharSpecialization( 6795 const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name, 6796 bool HasAllocator) { 6797 if (!SD->getIdentifier()->isStr(Name)) 6798 return false; 6799 6800 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 6801 if (TemplateArgs.size() != (HasAllocator ? 3 : 2)) 6802 return false; 6803 6804 QualType A = TemplateArgs[0].getAsType(); 6805 if (A.isNull()) 6806 return false; 6807 // Plain 'char' is named Char_S or Char_U depending on the target ABI. 6808 if (!A->isSpecificBuiltinType(BuiltinType::Char_S) && 6809 !A->isSpecificBuiltinType(BuiltinType::Char_U)) 6810 return false; 6811 6812 if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A)) 6813 return false; 6814 6815 if (HasAllocator && 6816 !isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A)) 6817 return false; 6818 6819 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage()) 6820 return false; 6821 6822 return true; 6823 } 6824 6825 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) { 6826 // <substitution> ::= St # ::std:: 6827 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 6828 if (isStd(NS)) { 6829 Out << "St"; 6830 return true; 6831 } 6832 return false; 6833 } 6834 6835 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) { 6836 if (!isStdNamespace(Context.getEffectiveDeclContext(TD))) 6837 return false; 6838 6839 if (TD->getOwningModuleForLinkage()) 6840 return false; 6841 6842 // <substitution> ::= Sa # ::std::allocator 6843 if (TD->getIdentifier()->isStr("allocator")) { 6844 Out << "Sa"; 6845 return true; 6846 } 6847 6848 // <<substitution> ::= Sb # ::std::basic_string 6849 if (TD->getIdentifier()->isStr("basic_string")) { 6850 Out << "Sb"; 6851 return true; 6852 } 6853 return false; 6854 } 6855 6856 if (const ClassTemplateSpecializationDecl *SD = 6857 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 6858 if (!isStdNamespace(Context.getEffectiveDeclContext(SD))) 6859 return false; 6860 6861 if (SD->getSpecializedTemplate()->getOwningModuleForLinkage()) 6862 return false; 6863 6864 // <substitution> ::= Ss # ::std::basic_string<char, 6865 // ::std::char_traits<char>, 6866 // ::std::allocator<char> > 6867 if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) { 6868 Out << "Ss"; 6869 return true; 6870 } 6871 6872 // <substitution> ::= Si # ::std::basic_istream<char, 6873 // ::std::char_traits<char> > 6874 if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) { 6875 Out << "Si"; 6876 return true; 6877 } 6878 6879 // <substitution> ::= So # ::std::basic_ostream<char, 6880 // ::std::char_traits<char> > 6881 if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) { 6882 Out << "So"; 6883 return true; 6884 } 6885 6886 // <substitution> ::= Sd # ::std::basic_iostream<char, 6887 // ::std::char_traits<char> > 6888 if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) { 6889 Out << "Sd"; 6890 return true; 6891 } 6892 return false; 6893 } 6894 6895 return false; 6896 } 6897 6898 void CXXNameMangler::addSubstitution(QualType T) { 6899 if (!hasMangledSubstitutionQualifiers(T)) { 6900 if (const RecordType *RT = T->getAs<RecordType>()) { 6901 addSubstitution(RT->getDecl()); 6902 return; 6903 } 6904 } 6905 6906 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 6907 addSubstitution(TypePtr); 6908 } 6909 6910 void CXXNameMangler::addSubstitution(TemplateName Template) { 6911 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 6912 return addSubstitution(TD); 6913 6914 Template = Context.getASTContext().getCanonicalTemplateName(Template); 6915 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 6916 } 6917 6918 void CXXNameMangler::addSubstitution(uintptr_t Ptr) { 6919 assert(!Substitutions.count(Ptr) && "Substitution already exists!"); 6920 Substitutions[Ptr] = SeqID++; 6921 } 6922 6923 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) { 6924 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!"); 6925 if (Other->SeqID > SeqID) { 6926 Substitutions.swap(Other->Substitutions); 6927 SeqID = Other->SeqID; 6928 } 6929 } 6930 6931 CXXNameMangler::AbiTagList 6932 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) { 6933 // When derived abi tags are disabled there is no need to make any list. 6934 if (DisableDerivedAbiTags) 6935 return AbiTagList(); 6936 6937 llvm::raw_null_ostream NullOutStream; 6938 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream); 6939 TrackReturnTypeTags.disableDerivedAbiTags(); 6940 6941 const FunctionProtoType *Proto = 6942 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>()); 6943 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push(); 6944 TrackReturnTypeTags.FunctionTypeDepth.enterResultType(); 6945 TrackReturnTypeTags.mangleType(Proto->getReturnType()); 6946 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType(); 6947 TrackReturnTypeTags.FunctionTypeDepth.pop(saved); 6948 6949 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 6950 } 6951 6952 CXXNameMangler::AbiTagList 6953 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) { 6954 // When derived abi tags are disabled there is no need to make any list. 6955 if (DisableDerivedAbiTags) 6956 return AbiTagList(); 6957 6958 llvm::raw_null_ostream NullOutStream; 6959 CXXNameMangler TrackVariableType(*this, NullOutStream); 6960 TrackVariableType.disableDerivedAbiTags(); 6961 6962 TrackVariableType.mangleType(VD->getType()); 6963 6964 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 6965 } 6966 6967 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C, 6968 const VarDecl *VD) { 6969 llvm::raw_null_ostream NullOutStream; 6970 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true); 6971 TrackAbiTags.mangle(VD); 6972 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size(); 6973 } 6974 6975 // 6976 6977 /// Mangles the name of the declaration D and emits that name to the given 6978 /// output stream. 6979 /// 6980 /// If the declaration D requires a mangled name, this routine will emit that 6981 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged 6982 /// and this routine will return false. In this case, the caller should just 6983 /// emit the identifier of the declaration (\c D->getIdentifier()) as its 6984 /// name. 6985 void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD, 6986 raw_ostream &Out) { 6987 const NamedDecl *D = cast<NamedDecl>(GD.getDecl()); 6988 assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) && 6989 "Invalid mangleName() call, argument is not a variable or function!"); 6990 6991 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 6992 getASTContext().getSourceManager(), 6993 "Mangling declaration"); 6994 6995 if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) { 6996 auto Type = GD.getCtorType(); 6997 CXXNameMangler Mangler(*this, Out, CD, Type); 6998 return Mangler.mangle(GlobalDecl(CD, Type)); 6999 } 7000 7001 if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) { 7002 auto Type = GD.getDtorType(); 7003 CXXNameMangler Mangler(*this, Out, DD, Type); 7004 return Mangler.mangle(GlobalDecl(DD, Type)); 7005 } 7006 7007 CXXNameMangler Mangler(*this, Out, D); 7008 Mangler.mangle(GD); 7009 } 7010 7011 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D, 7012 raw_ostream &Out) { 7013 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat); 7014 Mangler.mangle(GlobalDecl(D, Ctor_Comdat)); 7015 } 7016 7017 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D, 7018 raw_ostream &Out) { 7019 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat); 7020 Mangler.mangle(GlobalDecl(D, Dtor_Comdat)); 7021 } 7022 7023 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 7024 const ThunkInfo &Thunk, 7025 raw_ostream &Out) { 7026 // <special-name> ::= T <call-offset> <base encoding> 7027 // # base is the nominal target function of thunk 7028 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding> 7029 // # base is the nominal target function of thunk 7030 // # first call-offset is 'this' adjustment 7031 // # second call-offset is result adjustment 7032 7033 assert(!isa<CXXDestructorDecl>(MD) && 7034 "Use mangleCXXDtor for destructor decls!"); 7035 CXXNameMangler Mangler(*this, Out); 7036 Mangler.getStream() << "_ZT"; 7037 if (!Thunk.Return.isEmpty()) 7038 Mangler.getStream() << 'c'; 7039 7040 // Mangle the 'this' pointer adjustment. 7041 Mangler.mangleCallOffset(Thunk.This.NonVirtual, 7042 Thunk.This.Virtual.Itanium.VCallOffsetOffset); 7043 7044 // Mangle the return pointer adjustment if there is one. 7045 if (!Thunk.Return.isEmpty()) 7046 Mangler.mangleCallOffset(Thunk.Return.NonVirtual, 7047 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset); 7048 7049 Mangler.mangleFunctionEncoding(MD); 7050 } 7051 7052 void ItaniumMangleContextImpl::mangleCXXDtorThunk( 7053 const CXXDestructorDecl *DD, CXXDtorType Type, 7054 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) { 7055 // <special-name> ::= T <call-offset> <base encoding> 7056 // # base is the nominal target function of thunk 7057 CXXNameMangler Mangler(*this, Out, DD, Type); 7058 Mangler.getStream() << "_ZT"; 7059 7060 // Mangle the 'this' pointer adjustment. 7061 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 7062 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); 7063 7064 Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type)); 7065 } 7066 7067 /// Returns the mangled name for a guard variable for the passed in VarDecl. 7068 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D, 7069 raw_ostream &Out) { 7070 // <special-name> ::= GV <object name> # Guard variable for one-time 7071 // # initialization 7072 CXXNameMangler Mangler(*this, Out); 7073 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to 7074 // be a bug that is fixed in trunk. 7075 Mangler.getStream() << "_ZGV"; 7076 Mangler.mangleName(D); 7077 } 7078 7079 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD, 7080 raw_ostream &Out) { 7081 // These symbols are internal in the Itanium ABI, so the names don't matter. 7082 // Clang has traditionally used this symbol and allowed LLVM to adjust it to 7083 // avoid duplicate symbols. 7084 Out << "__cxx_global_var_init"; 7085 } 7086 7087 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 7088 raw_ostream &Out) { 7089 // Prefix the mangling of D with __dtor_. 7090 CXXNameMangler Mangler(*this, Out); 7091 Mangler.getStream() << "__dtor_"; 7092 if (shouldMangleDeclName(D)) 7093 Mangler.mangle(D); 7094 else 7095 Mangler.getStream() << D->getName(); 7096 } 7097 7098 void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D, 7099 raw_ostream &Out) { 7100 // Clang generates these internal-linkage functions as part of its 7101 // implementation of the XL ABI. 7102 CXXNameMangler Mangler(*this, Out); 7103 Mangler.getStream() << "__finalize_"; 7104 if (shouldMangleDeclName(D)) 7105 Mangler.mangle(D); 7106 else 7107 Mangler.getStream() << D->getName(); 7108 } 7109 7110 void ItaniumMangleContextImpl::mangleSEHFilterExpression( 7111 GlobalDecl EnclosingDecl, raw_ostream &Out) { 7112 CXXNameMangler Mangler(*this, Out); 7113 Mangler.getStream() << "__filt_"; 7114 auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl()); 7115 if (shouldMangleDeclName(EnclosingFD)) 7116 Mangler.mangle(EnclosingDecl); 7117 else 7118 Mangler.getStream() << EnclosingFD->getName(); 7119 } 7120 7121 void ItaniumMangleContextImpl::mangleSEHFinallyBlock( 7122 GlobalDecl EnclosingDecl, raw_ostream &Out) { 7123 CXXNameMangler Mangler(*this, Out); 7124 Mangler.getStream() << "__fin_"; 7125 auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl()); 7126 if (shouldMangleDeclName(EnclosingFD)) 7127 Mangler.mangle(EnclosingDecl); 7128 else 7129 Mangler.getStream() << EnclosingFD->getName(); 7130 } 7131 7132 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D, 7133 raw_ostream &Out) { 7134 // <special-name> ::= TH <object name> 7135 CXXNameMangler Mangler(*this, Out); 7136 Mangler.getStream() << "_ZTH"; 7137 Mangler.mangleName(D); 7138 } 7139 7140 void 7141 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D, 7142 raw_ostream &Out) { 7143 // <special-name> ::= TW <object name> 7144 CXXNameMangler Mangler(*this, Out); 7145 Mangler.getStream() << "_ZTW"; 7146 Mangler.mangleName(D); 7147 } 7148 7149 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D, 7150 unsigned ManglingNumber, 7151 raw_ostream &Out) { 7152 // We match the GCC mangling here. 7153 // <special-name> ::= GR <object name> 7154 CXXNameMangler Mangler(*this, Out); 7155 Mangler.getStream() << "_ZGR"; 7156 Mangler.mangleName(D); 7157 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!"); 7158 Mangler.mangleSeqID(ManglingNumber - 1); 7159 } 7160 7161 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD, 7162 raw_ostream &Out) { 7163 // <special-name> ::= TV <type> # virtual table 7164 CXXNameMangler Mangler(*this, Out); 7165 Mangler.getStream() << "_ZTV"; 7166 Mangler.mangleNameOrStandardSubstitution(RD); 7167 } 7168 7169 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD, 7170 raw_ostream &Out) { 7171 // <special-name> ::= TT <type> # VTT structure 7172 CXXNameMangler Mangler(*this, Out); 7173 Mangler.getStream() << "_ZTT"; 7174 Mangler.mangleNameOrStandardSubstitution(RD); 7175 } 7176 7177 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD, 7178 int64_t Offset, 7179 const CXXRecordDecl *Type, 7180 raw_ostream &Out) { 7181 // <special-name> ::= TC <type> <offset number> _ <base type> 7182 CXXNameMangler Mangler(*this, Out); 7183 Mangler.getStream() << "_ZTC"; 7184 Mangler.mangleNameOrStandardSubstitution(RD); 7185 Mangler.getStream() << Offset; 7186 Mangler.getStream() << '_'; 7187 Mangler.mangleNameOrStandardSubstitution(Type); 7188 } 7189 7190 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) { 7191 // <special-name> ::= TI <type> # typeinfo structure 7192 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers"); 7193 CXXNameMangler Mangler(*this, Out); 7194 Mangler.getStream() << "_ZTI"; 7195 Mangler.mangleType(Ty); 7196 } 7197 7198 void ItaniumMangleContextImpl::mangleCXXRTTIName( 7199 QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) { 7200 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string) 7201 CXXNameMangler Mangler(*this, Out, NormalizeIntegers); 7202 Mangler.getStream() << "_ZTS"; 7203 Mangler.mangleType(Ty); 7204 } 7205 7206 void ItaniumMangleContextImpl::mangleCanonicalTypeName( 7207 QualType Ty, raw_ostream &Out, bool NormalizeIntegers = false) { 7208 mangleCXXRTTIName(Ty, Out, NormalizeIntegers); 7209 } 7210 7211 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) { 7212 llvm_unreachable("Can't mangle string literals"); 7213 } 7214 7215 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda, 7216 raw_ostream &Out) { 7217 CXXNameMangler Mangler(*this, Out); 7218 Mangler.mangleLambdaSig(Lambda); 7219 } 7220 7221 void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M, 7222 raw_ostream &Out) { 7223 // <special-name> ::= GI <module-name> # module initializer function 7224 CXXNameMangler Mangler(*this, Out); 7225 Mangler.getStream() << "_ZGI"; 7226 Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName()); 7227 if (M->isModulePartition()) { 7228 // The partition needs including, as partitions can have them too. 7229 auto Partition = M->Name.find(':'); 7230 Mangler.mangleModuleNamePrefix( 7231 StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1), 7232 /*IsPartition*/ true); 7233 } 7234 } 7235 7236 ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context, 7237 DiagnosticsEngine &Diags, 7238 bool IsAux) { 7239 return new ItaniumMangleContextImpl( 7240 Context, Diags, 7241 [](ASTContext &, const NamedDecl *) -> std::optional<unsigned> { 7242 return std::nullopt; 7243 }, 7244 IsAux); 7245 } 7246 7247 ItaniumMangleContext * 7248 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags, 7249 DiscriminatorOverrideTy DiscriminatorOverride, 7250 bool IsAux) { 7251 return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride, 7252 IsAux); 7253 } 7254