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