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