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