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::ExtInt: 2267 case Type::DependentExtInt: 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::Elaborated: 2384 return mangleUnresolvedTypeOrSimpleId( 2385 cast<ElaboratedType>(Ty)->getNamedType(), Prefix); 2386 } 2387 2388 return false; 2389 } 2390 2391 void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) { 2392 switch (Name.getNameKind()) { 2393 case DeclarationName::CXXConstructorName: 2394 case DeclarationName::CXXDestructorName: 2395 case DeclarationName::CXXDeductionGuideName: 2396 case DeclarationName::CXXUsingDirective: 2397 case DeclarationName::Identifier: 2398 case DeclarationName::ObjCMultiArgSelector: 2399 case DeclarationName::ObjCOneArgSelector: 2400 case DeclarationName::ObjCZeroArgSelector: 2401 llvm_unreachable("Not an operator name"); 2402 2403 case DeclarationName::CXXConversionFunctionName: 2404 // <operator-name> ::= cv <type> # (cast) 2405 Out << "cv"; 2406 mangleType(Name.getCXXNameType()); 2407 break; 2408 2409 case DeclarationName::CXXLiteralOperatorName: 2410 Out << "li"; 2411 mangleSourceName(Name.getCXXLiteralIdentifier()); 2412 return; 2413 2414 case DeclarationName::CXXOperatorName: 2415 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity); 2416 break; 2417 } 2418 } 2419 2420 void 2421 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) { 2422 switch (OO) { 2423 // <operator-name> ::= nw # new 2424 case OO_New: Out << "nw"; break; 2425 // ::= na # new[] 2426 case OO_Array_New: Out << "na"; break; 2427 // ::= dl # delete 2428 case OO_Delete: Out << "dl"; break; 2429 // ::= da # delete[] 2430 case OO_Array_Delete: Out << "da"; break; 2431 // ::= ps # + (unary) 2432 // ::= pl # + (binary or unknown) 2433 case OO_Plus: 2434 Out << (Arity == 1? "ps" : "pl"); break; 2435 // ::= ng # - (unary) 2436 // ::= mi # - (binary or unknown) 2437 case OO_Minus: 2438 Out << (Arity == 1? "ng" : "mi"); break; 2439 // ::= ad # & (unary) 2440 // ::= an # & (binary or unknown) 2441 case OO_Amp: 2442 Out << (Arity == 1? "ad" : "an"); break; 2443 // ::= de # * (unary) 2444 // ::= ml # * (binary or unknown) 2445 case OO_Star: 2446 // Use binary when unknown. 2447 Out << (Arity == 1? "de" : "ml"); break; 2448 // ::= co # ~ 2449 case OO_Tilde: Out << "co"; break; 2450 // ::= dv # / 2451 case OO_Slash: Out << "dv"; break; 2452 // ::= rm # % 2453 case OO_Percent: Out << "rm"; break; 2454 // ::= or # | 2455 case OO_Pipe: Out << "or"; break; 2456 // ::= eo # ^ 2457 case OO_Caret: Out << "eo"; break; 2458 // ::= aS # = 2459 case OO_Equal: Out << "aS"; break; 2460 // ::= pL # += 2461 case OO_PlusEqual: Out << "pL"; break; 2462 // ::= mI # -= 2463 case OO_MinusEqual: Out << "mI"; break; 2464 // ::= mL # *= 2465 case OO_StarEqual: Out << "mL"; break; 2466 // ::= dV # /= 2467 case OO_SlashEqual: Out << "dV"; break; 2468 // ::= rM # %= 2469 case OO_PercentEqual: Out << "rM"; break; 2470 // ::= aN # &= 2471 case OO_AmpEqual: Out << "aN"; break; 2472 // ::= oR # |= 2473 case OO_PipeEqual: Out << "oR"; break; 2474 // ::= eO # ^= 2475 case OO_CaretEqual: Out << "eO"; break; 2476 // ::= ls # << 2477 case OO_LessLess: Out << "ls"; break; 2478 // ::= rs # >> 2479 case OO_GreaterGreater: Out << "rs"; break; 2480 // ::= lS # <<= 2481 case OO_LessLessEqual: Out << "lS"; break; 2482 // ::= rS # >>= 2483 case OO_GreaterGreaterEqual: Out << "rS"; break; 2484 // ::= eq # == 2485 case OO_EqualEqual: Out << "eq"; break; 2486 // ::= ne # != 2487 case OO_ExclaimEqual: Out << "ne"; break; 2488 // ::= lt # < 2489 case OO_Less: Out << "lt"; break; 2490 // ::= gt # > 2491 case OO_Greater: Out << "gt"; break; 2492 // ::= le # <= 2493 case OO_LessEqual: Out << "le"; break; 2494 // ::= ge # >= 2495 case OO_GreaterEqual: Out << "ge"; break; 2496 // ::= nt # ! 2497 case OO_Exclaim: Out << "nt"; break; 2498 // ::= aa # && 2499 case OO_AmpAmp: Out << "aa"; break; 2500 // ::= oo # || 2501 case OO_PipePipe: Out << "oo"; break; 2502 // ::= pp # ++ 2503 case OO_PlusPlus: Out << "pp"; break; 2504 // ::= mm # -- 2505 case OO_MinusMinus: Out << "mm"; break; 2506 // ::= cm # , 2507 case OO_Comma: Out << "cm"; break; 2508 // ::= pm # ->* 2509 case OO_ArrowStar: Out << "pm"; break; 2510 // ::= pt # -> 2511 case OO_Arrow: Out << "pt"; break; 2512 // ::= cl # () 2513 case OO_Call: Out << "cl"; break; 2514 // ::= ix # [] 2515 case OO_Subscript: Out << "ix"; break; 2516 2517 // ::= qu # ? 2518 // The conditional operator can't be overloaded, but we still handle it when 2519 // mangling expressions. 2520 case OO_Conditional: Out << "qu"; break; 2521 // Proposal on cxx-abi-dev, 2015-10-21. 2522 // ::= aw # co_await 2523 case OO_Coawait: Out << "aw"; break; 2524 // Proposed in cxx-abi github issue 43. 2525 // ::= ss # <=> 2526 case OO_Spaceship: Out << "ss"; break; 2527 2528 case OO_None: 2529 case NUM_OVERLOADED_OPERATORS: 2530 llvm_unreachable("Not an overloaded operator"); 2531 } 2532 } 2533 2534 void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) { 2535 // Vendor qualifiers come first and if they are order-insensitive they must 2536 // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5. 2537 2538 // <type> ::= U <addrspace-expr> 2539 if (DAST) { 2540 Out << "U2ASI"; 2541 mangleExpression(DAST->getAddrSpaceExpr()); 2542 Out << "E"; 2543 } 2544 2545 // Address space qualifiers start with an ordinary letter. 2546 if (Quals.hasAddressSpace()) { 2547 // Address space extension: 2548 // 2549 // <type> ::= U <target-addrspace> 2550 // <type> ::= U <OpenCL-addrspace> 2551 // <type> ::= U <CUDA-addrspace> 2552 2553 SmallString<64> ASString; 2554 LangAS AS = Quals.getAddressSpace(); 2555 2556 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) { 2557 // <target-addrspace> ::= "AS" <address-space-number> 2558 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS); 2559 if (TargetAS != 0 || 2560 Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0) 2561 ASString = "AS" + llvm::utostr(TargetAS); 2562 } else { 2563 switch (AS) { 2564 default: llvm_unreachable("Not a language specific address space"); 2565 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" | 2566 // "private"| "generic" | "device" | 2567 // "host" ] 2568 case LangAS::opencl_global: 2569 ASString = "CLglobal"; 2570 break; 2571 case LangAS::opencl_global_device: 2572 ASString = "CLdevice"; 2573 break; 2574 case LangAS::opencl_global_host: 2575 ASString = "CLhost"; 2576 break; 2577 case LangAS::opencl_local: 2578 ASString = "CLlocal"; 2579 break; 2580 case LangAS::opencl_constant: 2581 ASString = "CLconstant"; 2582 break; 2583 case LangAS::opencl_private: 2584 ASString = "CLprivate"; 2585 break; 2586 case LangAS::opencl_generic: 2587 ASString = "CLgeneric"; 2588 break; 2589 // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" | 2590 // "device" | "host" ] 2591 case LangAS::sycl_global: 2592 ASString = "SYglobal"; 2593 break; 2594 case LangAS::sycl_global_device: 2595 ASString = "SYdevice"; 2596 break; 2597 case LangAS::sycl_global_host: 2598 ASString = "SYhost"; 2599 break; 2600 case LangAS::sycl_local: 2601 ASString = "SYlocal"; 2602 break; 2603 case LangAS::sycl_private: 2604 ASString = "SYprivate"; 2605 break; 2606 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ] 2607 case LangAS::cuda_device: 2608 ASString = "CUdevice"; 2609 break; 2610 case LangAS::cuda_constant: 2611 ASString = "CUconstant"; 2612 break; 2613 case LangAS::cuda_shared: 2614 ASString = "CUshared"; 2615 break; 2616 // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ] 2617 case LangAS::ptr32_sptr: 2618 ASString = "ptr32_sptr"; 2619 break; 2620 case LangAS::ptr32_uptr: 2621 ASString = "ptr32_uptr"; 2622 break; 2623 case LangAS::ptr64: 2624 ASString = "ptr64"; 2625 break; 2626 } 2627 } 2628 if (!ASString.empty()) 2629 mangleVendorQualifier(ASString); 2630 } 2631 2632 // The ARC ownership qualifiers start with underscores. 2633 // Objective-C ARC Extension: 2634 // 2635 // <type> ::= U "__strong" 2636 // <type> ::= U "__weak" 2637 // <type> ::= U "__autoreleasing" 2638 // 2639 // Note: we emit __weak first to preserve the order as 2640 // required by the Itanium ABI. 2641 if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak) 2642 mangleVendorQualifier("__weak"); 2643 2644 // __unaligned (from -fms-extensions) 2645 if (Quals.hasUnaligned()) 2646 mangleVendorQualifier("__unaligned"); 2647 2648 // Remaining ARC ownership qualifiers. 2649 switch (Quals.getObjCLifetime()) { 2650 case Qualifiers::OCL_None: 2651 break; 2652 2653 case Qualifiers::OCL_Weak: 2654 // Do nothing as we already handled this case above. 2655 break; 2656 2657 case Qualifiers::OCL_Strong: 2658 mangleVendorQualifier("__strong"); 2659 break; 2660 2661 case Qualifiers::OCL_Autoreleasing: 2662 mangleVendorQualifier("__autoreleasing"); 2663 break; 2664 2665 case Qualifiers::OCL_ExplicitNone: 2666 // The __unsafe_unretained qualifier is *not* mangled, so that 2667 // __unsafe_unretained types in ARC produce the same manglings as the 2668 // equivalent (but, naturally, unqualified) types in non-ARC, providing 2669 // better ABI compatibility. 2670 // 2671 // It's safe to do this because unqualified 'id' won't show up 2672 // in any type signatures that need to be mangled. 2673 break; 2674 } 2675 2676 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const 2677 if (Quals.hasRestrict()) 2678 Out << 'r'; 2679 if (Quals.hasVolatile()) 2680 Out << 'V'; 2681 if (Quals.hasConst()) 2682 Out << 'K'; 2683 } 2684 2685 void CXXNameMangler::mangleVendorQualifier(StringRef name) { 2686 Out << 'U' << name.size() << name; 2687 } 2688 2689 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) { 2690 // <ref-qualifier> ::= R # lvalue reference 2691 // ::= O # rvalue-reference 2692 switch (RefQualifier) { 2693 case RQ_None: 2694 break; 2695 2696 case RQ_LValue: 2697 Out << 'R'; 2698 break; 2699 2700 case RQ_RValue: 2701 Out << 'O'; 2702 break; 2703 } 2704 } 2705 2706 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) { 2707 Context.mangleObjCMethodNameAsSourceName(MD, Out); 2708 } 2709 2710 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty, 2711 ASTContext &Ctx) { 2712 if (Quals) 2713 return true; 2714 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel)) 2715 return true; 2716 if (Ty->isOpenCLSpecificType()) 2717 return true; 2718 if (Ty->isBuiltinType()) 2719 return false; 2720 // Through to Clang 6.0, we accidentally treated undeduced auto types as 2721 // substitution candidates. 2722 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 && 2723 isa<AutoType>(Ty)) 2724 return false; 2725 // A placeholder type for class template deduction is substitutable with 2726 // its corresponding template name; this is handled specially when mangling 2727 // the type. 2728 if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>()) 2729 if (DeducedTST->getDeducedType().isNull()) 2730 return false; 2731 return true; 2732 } 2733 2734 void CXXNameMangler::mangleType(QualType T) { 2735 // If our type is instantiation-dependent but not dependent, we mangle 2736 // it as it was written in the source, removing any top-level sugar. 2737 // Otherwise, use the canonical type. 2738 // 2739 // FIXME: This is an approximation of the instantiation-dependent name 2740 // mangling rules, since we should really be using the type as written and 2741 // augmented via semantic analysis (i.e., with implicit conversions and 2742 // default template arguments) for any instantiation-dependent type. 2743 // Unfortunately, that requires several changes to our AST: 2744 // - Instantiation-dependent TemplateSpecializationTypes will need to be 2745 // uniqued, so that we can handle substitutions properly 2746 // - Default template arguments will need to be represented in the 2747 // TemplateSpecializationType, since they need to be mangled even though 2748 // they aren't written. 2749 // - Conversions on non-type template arguments need to be expressed, since 2750 // they can affect the mangling of sizeof/alignof. 2751 // 2752 // FIXME: This is wrong when mapping to the canonical type for a dependent 2753 // type discards instantiation-dependent portions of the type, such as for: 2754 // 2755 // template<typename T, int N> void f(T (&)[sizeof(N)]); 2756 // template<typename T> void f(T() throw(typename T::type)); (pre-C++17) 2757 // 2758 // It's also wrong in the opposite direction when instantiation-dependent, 2759 // canonically-equivalent types differ in some irrelevant portion of inner 2760 // type sugar. In such cases, we fail to form correct substitutions, eg: 2761 // 2762 // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*)); 2763 // 2764 // We should instead canonicalize the non-instantiation-dependent parts, 2765 // regardless of whether the type as a whole is dependent or instantiation 2766 // dependent. 2767 if (!T->isInstantiationDependentType() || T->isDependentType()) 2768 T = T.getCanonicalType(); 2769 else { 2770 // Desugar any types that are purely sugar. 2771 do { 2772 // Don't desugar through template specialization types that aren't 2773 // type aliases. We need to mangle the template arguments as written. 2774 if (const TemplateSpecializationType *TST 2775 = dyn_cast<TemplateSpecializationType>(T)) 2776 if (!TST->isTypeAlias()) 2777 break; 2778 2779 // FIXME: We presumably shouldn't strip off ElaboratedTypes with 2780 // instantation-dependent qualifiers. See 2781 // https://github.com/itanium-cxx-abi/cxx-abi/issues/114. 2782 2783 QualType Desugared 2784 = T.getSingleStepDesugaredType(Context.getASTContext()); 2785 if (Desugared == T) 2786 break; 2787 2788 T = Desugared; 2789 } while (true); 2790 } 2791 SplitQualType split = T.split(); 2792 Qualifiers quals = split.Quals; 2793 const Type *ty = split.Ty; 2794 2795 bool isSubstitutable = 2796 isTypeSubstitutable(quals, ty, Context.getASTContext()); 2797 if (isSubstitutable && mangleSubstitution(T)) 2798 return; 2799 2800 // If we're mangling a qualified array type, push the qualifiers to 2801 // the element type. 2802 if (quals && isa<ArrayType>(T)) { 2803 ty = Context.getASTContext().getAsArrayType(T); 2804 quals = Qualifiers(); 2805 2806 // Note that we don't update T: we want to add the 2807 // substitution at the original type. 2808 } 2809 2810 if (quals || ty->isDependentAddressSpaceType()) { 2811 if (const DependentAddressSpaceType *DAST = 2812 dyn_cast<DependentAddressSpaceType>(ty)) { 2813 SplitQualType splitDAST = DAST->getPointeeType().split(); 2814 mangleQualifiers(splitDAST.Quals, DAST); 2815 mangleType(QualType(splitDAST.Ty, 0)); 2816 } else { 2817 mangleQualifiers(quals); 2818 2819 // Recurse: even if the qualified type isn't yet substitutable, 2820 // the unqualified type might be. 2821 mangleType(QualType(ty, 0)); 2822 } 2823 } else { 2824 switch (ty->getTypeClass()) { 2825 #define ABSTRACT_TYPE(CLASS, PARENT) 2826 #define NON_CANONICAL_TYPE(CLASS, PARENT) \ 2827 case Type::CLASS: \ 2828 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \ 2829 return; 2830 #define TYPE(CLASS, PARENT) \ 2831 case Type::CLASS: \ 2832 mangleType(static_cast<const CLASS##Type*>(ty)); \ 2833 break; 2834 #include "clang/AST/TypeNodes.inc" 2835 } 2836 } 2837 2838 // Add the substitution. 2839 if (isSubstitutable) 2840 addSubstitution(T); 2841 } 2842 2843 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) { 2844 if (!mangleStandardSubstitution(ND)) 2845 mangleName(ND); 2846 } 2847 2848 void CXXNameMangler::mangleType(const BuiltinType *T) { 2849 // <type> ::= <builtin-type> 2850 // <builtin-type> ::= v # void 2851 // ::= w # wchar_t 2852 // ::= b # bool 2853 // ::= c # char 2854 // ::= a # signed char 2855 // ::= h # unsigned char 2856 // ::= s # short 2857 // ::= t # unsigned short 2858 // ::= i # int 2859 // ::= j # unsigned int 2860 // ::= l # long 2861 // ::= m # unsigned long 2862 // ::= x # long long, __int64 2863 // ::= y # unsigned long long, __int64 2864 // ::= n # __int128 2865 // ::= o # unsigned __int128 2866 // ::= f # float 2867 // ::= d # double 2868 // ::= e # long double, __float80 2869 // ::= g # __float128 2870 // ::= g # __ibm128 2871 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits) 2872 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits) 2873 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits) 2874 // ::= Dh # IEEE 754r half-precision floating point (16 bits) 2875 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits); 2876 // ::= Di # char32_t 2877 // ::= Ds # char16_t 2878 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr)) 2879 // ::= u <source-name> # vendor extended type 2880 std::string type_name; 2881 switch (T->getKind()) { 2882 case BuiltinType::Void: 2883 Out << 'v'; 2884 break; 2885 case BuiltinType::Bool: 2886 Out << 'b'; 2887 break; 2888 case BuiltinType::Char_U: 2889 case BuiltinType::Char_S: 2890 Out << 'c'; 2891 break; 2892 case BuiltinType::UChar: 2893 Out << 'h'; 2894 break; 2895 case BuiltinType::UShort: 2896 Out << 't'; 2897 break; 2898 case BuiltinType::UInt: 2899 Out << 'j'; 2900 break; 2901 case BuiltinType::ULong: 2902 Out << 'm'; 2903 break; 2904 case BuiltinType::ULongLong: 2905 Out << 'y'; 2906 break; 2907 case BuiltinType::UInt128: 2908 Out << 'o'; 2909 break; 2910 case BuiltinType::SChar: 2911 Out << 'a'; 2912 break; 2913 case BuiltinType::WChar_S: 2914 case BuiltinType::WChar_U: 2915 Out << 'w'; 2916 break; 2917 case BuiltinType::Char8: 2918 Out << "Du"; 2919 break; 2920 case BuiltinType::Char16: 2921 Out << "Ds"; 2922 break; 2923 case BuiltinType::Char32: 2924 Out << "Di"; 2925 break; 2926 case BuiltinType::Short: 2927 Out << 's'; 2928 break; 2929 case BuiltinType::Int: 2930 Out << 'i'; 2931 break; 2932 case BuiltinType::Long: 2933 Out << 'l'; 2934 break; 2935 case BuiltinType::LongLong: 2936 Out << 'x'; 2937 break; 2938 case BuiltinType::Int128: 2939 Out << 'n'; 2940 break; 2941 case BuiltinType::Float16: 2942 Out << "DF16_"; 2943 break; 2944 case BuiltinType::ShortAccum: 2945 case BuiltinType::Accum: 2946 case BuiltinType::LongAccum: 2947 case BuiltinType::UShortAccum: 2948 case BuiltinType::UAccum: 2949 case BuiltinType::ULongAccum: 2950 case BuiltinType::ShortFract: 2951 case BuiltinType::Fract: 2952 case BuiltinType::LongFract: 2953 case BuiltinType::UShortFract: 2954 case BuiltinType::UFract: 2955 case BuiltinType::ULongFract: 2956 case BuiltinType::SatShortAccum: 2957 case BuiltinType::SatAccum: 2958 case BuiltinType::SatLongAccum: 2959 case BuiltinType::SatUShortAccum: 2960 case BuiltinType::SatUAccum: 2961 case BuiltinType::SatULongAccum: 2962 case BuiltinType::SatShortFract: 2963 case BuiltinType::SatFract: 2964 case BuiltinType::SatLongFract: 2965 case BuiltinType::SatUShortFract: 2966 case BuiltinType::SatUFract: 2967 case BuiltinType::SatULongFract: 2968 llvm_unreachable("Fixed point types are disabled for c++"); 2969 case BuiltinType::Half: 2970 Out << "Dh"; 2971 break; 2972 case BuiltinType::Float: 2973 Out << 'f'; 2974 break; 2975 case BuiltinType::Double: 2976 Out << 'd'; 2977 break; 2978 case BuiltinType::LongDouble: { 2979 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP && 2980 getASTContext().getLangOpts().OpenMPIsDevice 2981 ? getASTContext().getAuxTargetInfo() 2982 : &getASTContext().getTargetInfo(); 2983 Out << TI->getLongDoubleMangling(); 2984 break; 2985 } 2986 case BuiltinType::Float128: { 2987 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP && 2988 getASTContext().getLangOpts().OpenMPIsDevice 2989 ? getASTContext().getAuxTargetInfo() 2990 : &getASTContext().getTargetInfo(); 2991 Out << TI->getFloat128Mangling(); 2992 break; 2993 } 2994 case BuiltinType::BFloat16: { 2995 const TargetInfo *TI = &getASTContext().getTargetInfo(); 2996 Out << TI->getBFloat16Mangling(); 2997 break; 2998 } 2999 case BuiltinType::Ibm128: { 3000 const TargetInfo *TI = &getASTContext().getTargetInfo(); 3001 Out << TI->getIbm128Mangling(); 3002 break; 3003 } 3004 case BuiltinType::NullPtr: 3005 Out << "Dn"; 3006 break; 3007 3008 #define BUILTIN_TYPE(Id, SingletonId) 3009 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 3010 case BuiltinType::Id: 3011 #include "clang/AST/BuiltinTypes.def" 3012 case BuiltinType::Dependent: 3013 if (!NullOut) 3014 llvm_unreachable("mangling a placeholder type"); 3015 break; 3016 case BuiltinType::ObjCId: 3017 Out << "11objc_object"; 3018 break; 3019 case BuiltinType::ObjCClass: 3020 Out << "10objc_class"; 3021 break; 3022 case BuiltinType::ObjCSel: 3023 Out << "13objc_selector"; 3024 break; 3025 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 3026 case BuiltinType::Id: \ 3027 type_name = "ocl_" #ImgType "_" #Suffix; \ 3028 Out << type_name.size() << type_name; \ 3029 break; 3030 #include "clang/Basic/OpenCLImageTypes.def" 3031 case BuiltinType::OCLSampler: 3032 Out << "11ocl_sampler"; 3033 break; 3034 case BuiltinType::OCLEvent: 3035 Out << "9ocl_event"; 3036 break; 3037 case BuiltinType::OCLClkEvent: 3038 Out << "12ocl_clkevent"; 3039 break; 3040 case BuiltinType::OCLQueue: 3041 Out << "9ocl_queue"; 3042 break; 3043 case BuiltinType::OCLReserveID: 3044 Out << "13ocl_reserveid"; 3045 break; 3046 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 3047 case BuiltinType::Id: \ 3048 type_name = "ocl_" #ExtType; \ 3049 Out << type_name.size() << type_name; \ 3050 break; 3051 #include "clang/Basic/OpenCLExtensionTypes.def" 3052 // The SVE types are effectively target-specific. The mangling scheme 3053 // is defined in the appendices to the Procedure Call Standard for the 3054 // Arm Architecture. 3055 #define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \ 3056 ElBits, IsSigned, IsFP, IsBF) \ 3057 case BuiltinType::Id: \ 3058 type_name = MangledName; \ 3059 Out << (type_name == InternalName ? "u" : "") << type_name.size() \ 3060 << type_name; \ 3061 break; 3062 #define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \ 3063 case BuiltinType::Id: \ 3064 type_name = MangledName; \ 3065 Out << (type_name == InternalName ? "u" : "") << type_name.size() \ 3066 << type_name; \ 3067 break; 3068 #include "clang/Basic/AArch64SVEACLETypes.def" 3069 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 3070 case BuiltinType::Id: \ 3071 type_name = #Name; \ 3072 Out << 'u' << type_name.size() << type_name; \ 3073 break; 3074 #include "clang/Basic/PPCTypes.def" 3075 // TODO: Check the mangling scheme for RISC-V V. 3076 #define RVV_TYPE(Name, Id, SingletonId) \ 3077 case BuiltinType::Id: \ 3078 type_name = Name; \ 3079 Out << 'u' << type_name.size() << type_name; \ 3080 break; 3081 #include "clang/Basic/RISCVVTypes.def" 3082 } 3083 } 3084 3085 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) { 3086 switch (CC) { 3087 case CC_C: 3088 return ""; 3089 3090 case CC_X86VectorCall: 3091 case CC_X86Pascal: 3092 case CC_X86RegCall: 3093 case CC_AAPCS: 3094 case CC_AAPCS_VFP: 3095 case CC_AArch64VectorCall: 3096 case CC_IntelOclBicc: 3097 case CC_SpirFunction: 3098 case CC_OpenCLKernel: 3099 case CC_PreserveMost: 3100 case CC_PreserveAll: 3101 // FIXME: we should be mangling all of the above. 3102 return ""; 3103 3104 case CC_X86ThisCall: 3105 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is 3106 // used explicitly. At this point, we don't have that much information in 3107 // the AST, since clang tends to bake the convention into the canonical 3108 // function type. thiscall only rarely used explicitly, so don't mangle it 3109 // for now. 3110 return ""; 3111 3112 case CC_X86StdCall: 3113 return "stdcall"; 3114 case CC_X86FastCall: 3115 return "fastcall"; 3116 case CC_X86_64SysV: 3117 return "sysv_abi"; 3118 case CC_Win64: 3119 return "ms_abi"; 3120 case CC_Swift: 3121 return "swiftcall"; 3122 case CC_SwiftAsync: 3123 return "swiftasynccall"; 3124 } 3125 llvm_unreachable("bad calling convention"); 3126 } 3127 3128 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) { 3129 // Fast path. 3130 if (T->getExtInfo() == FunctionType::ExtInfo()) 3131 return; 3132 3133 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 3134 // This will get more complicated in the future if we mangle other 3135 // things here; but for now, since we mangle ns_returns_retained as 3136 // a qualifier on the result type, we can get away with this: 3137 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC()); 3138 if (!CCQualifier.empty()) 3139 mangleVendorQualifier(CCQualifier); 3140 3141 // FIXME: regparm 3142 // FIXME: noreturn 3143 } 3144 3145 void 3146 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) { 3147 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 3148 3149 // Note that these are *not* substitution candidates. Demanglers might 3150 // have trouble with this if the parameter type is fully substituted. 3151 3152 switch (PI.getABI()) { 3153 case ParameterABI::Ordinary: 3154 break; 3155 3156 // All of these start with "swift", so they come before "ns_consumed". 3157 case ParameterABI::SwiftContext: 3158 case ParameterABI::SwiftAsyncContext: 3159 case ParameterABI::SwiftErrorResult: 3160 case ParameterABI::SwiftIndirectResult: 3161 mangleVendorQualifier(getParameterABISpelling(PI.getABI())); 3162 break; 3163 } 3164 3165 if (PI.isConsumed()) 3166 mangleVendorQualifier("ns_consumed"); 3167 3168 if (PI.isNoEscape()) 3169 mangleVendorQualifier("noescape"); 3170 } 3171 3172 // <type> ::= <function-type> 3173 // <function-type> ::= [<CV-qualifiers>] F [Y] 3174 // <bare-function-type> [<ref-qualifier>] E 3175 void CXXNameMangler::mangleType(const FunctionProtoType *T) { 3176 mangleExtFunctionInfo(T); 3177 3178 // Mangle CV-qualifiers, if present. These are 'this' qualifiers, 3179 // e.g. "const" in "int (A::*)() const". 3180 mangleQualifiers(T->getMethodQuals()); 3181 3182 // Mangle instantiation-dependent exception-specification, if present, 3183 // per cxx-abi-dev proposal on 2016-10-11. 3184 if (T->hasInstantiationDependentExceptionSpec()) { 3185 if (isComputedNoexcept(T->getExceptionSpecType())) { 3186 Out << "DO"; 3187 mangleExpression(T->getNoexceptExpr()); 3188 Out << "E"; 3189 } else { 3190 assert(T->getExceptionSpecType() == EST_Dynamic); 3191 Out << "Dw"; 3192 for (auto ExceptTy : T->exceptions()) 3193 mangleType(ExceptTy); 3194 Out << "E"; 3195 } 3196 } else if (T->isNothrow()) { 3197 Out << "Do"; 3198 } 3199 3200 Out << 'F'; 3201 3202 // FIXME: We don't have enough information in the AST to produce the 'Y' 3203 // encoding for extern "C" function types. 3204 mangleBareFunctionType(T, /*MangleReturnType=*/true); 3205 3206 // Mangle the ref-qualifier, if present. 3207 mangleRefQualifier(T->getRefQualifier()); 3208 3209 Out << 'E'; 3210 } 3211 3212 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) { 3213 // Function types without prototypes can arise when mangling a function type 3214 // within an overloadable function in C. We mangle these as the absence of any 3215 // parameter types (not even an empty parameter list). 3216 Out << 'F'; 3217 3218 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 3219 3220 FunctionTypeDepth.enterResultType(); 3221 mangleType(T->getReturnType()); 3222 FunctionTypeDepth.leaveResultType(); 3223 3224 FunctionTypeDepth.pop(saved); 3225 Out << 'E'; 3226 } 3227 3228 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto, 3229 bool MangleReturnType, 3230 const FunctionDecl *FD) { 3231 // Record that we're in a function type. See mangleFunctionParam 3232 // for details on what we're trying to achieve here. 3233 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 3234 3235 // <bare-function-type> ::= <signature type>+ 3236 if (MangleReturnType) { 3237 FunctionTypeDepth.enterResultType(); 3238 3239 // Mangle ns_returns_retained as an order-sensitive qualifier here. 3240 if (Proto->getExtInfo().getProducesResult() && FD == nullptr) 3241 mangleVendorQualifier("ns_returns_retained"); 3242 3243 // Mangle the return type without any direct ARC ownership qualifiers. 3244 QualType ReturnTy = Proto->getReturnType(); 3245 if (ReturnTy.getObjCLifetime()) { 3246 auto SplitReturnTy = ReturnTy.split(); 3247 SplitReturnTy.Quals.removeObjCLifetime(); 3248 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy); 3249 } 3250 mangleType(ReturnTy); 3251 3252 FunctionTypeDepth.leaveResultType(); 3253 } 3254 3255 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) { 3256 // <builtin-type> ::= v # void 3257 Out << 'v'; 3258 3259 FunctionTypeDepth.pop(saved); 3260 return; 3261 } 3262 3263 assert(!FD || FD->getNumParams() == Proto->getNumParams()); 3264 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) { 3265 // Mangle extended parameter info as order-sensitive qualifiers here. 3266 if (Proto->hasExtParameterInfos() && FD == nullptr) { 3267 mangleExtParameterInfo(Proto->getExtParameterInfo(I)); 3268 } 3269 3270 // Mangle the type. 3271 QualType ParamTy = Proto->getParamType(I); 3272 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy)); 3273 3274 if (FD) { 3275 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) { 3276 // Attr can only take 1 character, so we can hardcode the length below. 3277 assert(Attr->getType() <= 9 && Attr->getType() >= 0); 3278 if (Attr->isDynamic()) 3279 Out << "U25pass_dynamic_object_size" << Attr->getType(); 3280 else 3281 Out << "U17pass_object_size" << Attr->getType(); 3282 } 3283 } 3284 } 3285 3286 FunctionTypeDepth.pop(saved); 3287 3288 // <builtin-type> ::= z # ellipsis 3289 if (Proto->isVariadic()) 3290 Out << 'z'; 3291 } 3292 3293 // <type> ::= <class-enum-type> 3294 // <class-enum-type> ::= <name> 3295 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) { 3296 mangleName(T->getDecl()); 3297 } 3298 3299 // <type> ::= <class-enum-type> 3300 // <class-enum-type> ::= <name> 3301 void CXXNameMangler::mangleType(const EnumType *T) { 3302 mangleType(static_cast<const TagType*>(T)); 3303 } 3304 void CXXNameMangler::mangleType(const RecordType *T) { 3305 mangleType(static_cast<const TagType*>(T)); 3306 } 3307 void CXXNameMangler::mangleType(const TagType *T) { 3308 mangleName(T->getDecl()); 3309 } 3310 3311 // <type> ::= <array-type> 3312 // <array-type> ::= A <positive dimension number> _ <element type> 3313 // ::= A [<dimension expression>] _ <element type> 3314 void CXXNameMangler::mangleType(const ConstantArrayType *T) { 3315 Out << 'A' << T->getSize() << '_'; 3316 mangleType(T->getElementType()); 3317 } 3318 void CXXNameMangler::mangleType(const VariableArrayType *T) { 3319 Out << 'A'; 3320 // decayed vla types (size 0) will just be skipped. 3321 if (T->getSizeExpr()) 3322 mangleExpression(T->getSizeExpr()); 3323 Out << '_'; 3324 mangleType(T->getElementType()); 3325 } 3326 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) { 3327 Out << 'A'; 3328 // A DependentSizedArrayType might not have size expression as below 3329 // 3330 // template<int ...N> int arr[] = {N...}; 3331 if (T->getSizeExpr()) 3332 mangleExpression(T->getSizeExpr()); 3333 Out << '_'; 3334 mangleType(T->getElementType()); 3335 } 3336 void CXXNameMangler::mangleType(const IncompleteArrayType *T) { 3337 Out << "A_"; 3338 mangleType(T->getElementType()); 3339 } 3340 3341 // <type> ::= <pointer-to-member-type> 3342 // <pointer-to-member-type> ::= M <class type> <member type> 3343 void CXXNameMangler::mangleType(const MemberPointerType *T) { 3344 Out << 'M'; 3345 mangleType(QualType(T->getClass(), 0)); 3346 QualType PointeeType = T->getPointeeType(); 3347 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) { 3348 mangleType(FPT); 3349 3350 // Itanium C++ ABI 5.1.8: 3351 // 3352 // The type of a non-static member function is considered to be different, 3353 // for the purposes of substitution, from the type of a namespace-scope or 3354 // static member function whose type appears similar. The types of two 3355 // non-static member functions are considered to be different, for the 3356 // purposes of substitution, if the functions are members of different 3357 // classes. In other words, for the purposes of substitution, the class of 3358 // which the function is a member is considered part of the type of 3359 // function. 3360 3361 // Given that we already substitute member function pointers as a 3362 // whole, the net effect of this rule is just to unconditionally 3363 // suppress substitution on the function type in a member pointer. 3364 // We increment the SeqID here to emulate adding an entry to the 3365 // substitution table. 3366 ++SeqID; 3367 } else 3368 mangleType(PointeeType); 3369 } 3370 3371 // <type> ::= <template-param> 3372 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) { 3373 mangleTemplateParameter(T->getDepth(), T->getIndex()); 3374 } 3375 3376 // <type> ::= <template-param> 3377 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) { 3378 // FIXME: not clear how to mangle this! 3379 // template <class T...> class A { 3380 // template <class U...> void foo(T(*)(U) x...); 3381 // }; 3382 Out << "_SUBSTPACK_"; 3383 } 3384 3385 // <type> ::= P <type> # pointer-to 3386 void CXXNameMangler::mangleType(const PointerType *T) { 3387 Out << 'P'; 3388 mangleType(T->getPointeeType()); 3389 } 3390 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) { 3391 Out << 'P'; 3392 mangleType(T->getPointeeType()); 3393 } 3394 3395 // <type> ::= R <type> # reference-to 3396 void CXXNameMangler::mangleType(const LValueReferenceType *T) { 3397 Out << 'R'; 3398 mangleType(T->getPointeeType()); 3399 } 3400 3401 // <type> ::= O <type> # rvalue reference-to (C++0x) 3402 void CXXNameMangler::mangleType(const RValueReferenceType *T) { 3403 Out << 'O'; 3404 mangleType(T->getPointeeType()); 3405 } 3406 3407 // <type> ::= C <type> # complex pair (C 2000) 3408 void CXXNameMangler::mangleType(const ComplexType *T) { 3409 Out << 'C'; 3410 mangleType(T->getElementType()); 3411 } 3412 3413 // ARM's ABI for Neon vector types specifies that they should be mangled as 3414 // if they are structs (to match ARM's initial implementation). The 3415 // vector type must be one of the special types predefined by ARM. 3416 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) { 3417 QualType EltType = T->getElementType(); 3418 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3419 const char *EltName = nullptr; 3420 if (T->getVectorKind() == VectorType::NeonPolyVector) { 3421 switch (cast<BuiltinType>(EltType)->getKind()) { 3422 case BuiltinType::SChar: 3423 case BuiltinType::UChar: 3424 EltName = "poly8_t"; 3425 break; 3426 case BuiltinType::Short: 3427 case BuiltinType::UShort: 3428 EltName = "poly16_t"; 3429 break; 3430 case BuiltinType::LongLong: 3431 case BuiltinType::ULongLong: 3432 EltName = "poly64_t"; 3433 break; 3434 default: llvm_unreachable("unexpected Neon polynomial vector element type"); 3435 } 3436 } else { 3437 switch (cast<BuiltinType>(EltType)->getKind()) { 3438 case BuiltinType::SChar: EltName = "int8_t"; break; 3439 case BuiltinType::UChar: EltName = "uint8_t"; break; 3440 case BuiltinType::Short: EltName = "int16_t"; break; 3441 case BuiltinType::UShort: EltName = "uint16_t"; break; 3442 case BuiltinType::Int: EltName = "int32_t"; break; 3443 case BuiltinType::UInt: EltName = "uint32_t"; break; 3444 case BuiltinType::LongLong: EltName = "int64_t"; break; 3445 case BuiltinType::ULongLong: EltName = "uint64_t"; break; 3446 case BuiltinType::Double: EltName = "float64_t"; break; 3447 case BuiltinType::Float: EltName = "float32_t"; break; 3448 case BuiltinType::Half: EltName = "float16_t"; break; 3449 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break; 3450 default: 3451 llvm_unreachable("unexpected Neon vector element type"); 3452 } 3453 } 3454 const char *BaseName = nullptr; 3455 unsigned BitSize = (T->getNumElements() * 3456 getASTContext().getTypeSize(EltType)); 3457 if (BitSize == 64) 3458 BaseName = "__simd64_"; 3459 else { 3460 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits"); 3461 BaseName = "__simd128_"; 3462 } 3463 Out << strlen(BaseName) + strlen(EltName); 3464 Out << BaseName << EltName; 3465 } 3466 3467 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) { 3468 DiagnosticsEngine &Diags = Context.getDiags(); 3469 unsigned DiagID = Diags.getCustomDiagID( 3470 DiagnosticsEngine::Error, 3471 "cannot mangle this dependent neon vector type yet"); 3472 Diags.Report(T->getAttributeLoc(), DiagID); 3473 } 3474 3475 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) { 3476 switch (EltType->getKind()) { 3477 case BuiltinType::SChar: 3478 return "Int8"; 3479 case BuiltinType::Short: 3480 return "Int16"; 3481 case BuiltinType::Int: 3482 return "Int32"; 3483 case BuiltinType::Long: 3484 case BuiltinType::LongLong: 3485 return "Int64"; 3486 case BuiltinType::UChar: 3487 return "Uint8"; 3488 case BuiltinType::UShort: 3489 return "Uint16"; 3490 case BuiltinType::UInt: 3491 return "Uint32"; 3492 case BuiltinType::ULong: 3493 case BuiltinType::ULongLong: 3494 return "Uint64"; 3495 case BuiltinType::Half: 3496 return "Float16"; 3497 case BuiltinType::Float: 3498 return "Float32"; 3499 case BuiltinType::Double: 3500 return "Float64"; 3501 case BuiltinType::BFloat16: 3502 return "Bfloat16"; 3503 default: 3504 llvm_unreachable("Unexpected vector element base type"); 3505 } 3506 } 3507 3508 // AArch64's ABI for Neon vector types specifies that they should be mangled as 3509 // the equivalent internal name. The vector type must be one of the special 3510 // types predefined by ARM. 3511 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) { 3512 QualType EltType = T->getElementType(); 3513 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3514 unsigned BitSize = 3515 (T->getNumElements() * getASTContext().getTypeSize(EltType)); 3516 (void)BitSize; // Silence warning. 3517 3518 assert((BitSize == 64 || BitSize == 128) && 3519 "Neon vector type not 64 or 128 bits"); 3520 3521 StringRef EltName; 3522 if (T->getVectorKind() == VectorType::NeonPolyVector) { 3523 switch (cast<BuiltinType>(EltType)->getKind()) { 3524 case BuiltinType::UChar: 3525 EltName = "Poly8"; 3526 break; 3527 case BuiltinType::UShort: 3528 EltName = "Poly16"; 3529 break; 3530 case BuiltinType::ULong: 3531 case BuiltinType::ULongLong: 3532 EltName = "Poly64"; 3533 break; 3534 default: 3535 llvm_unreachable("unexpected Neon polynomial vector element type"); 3536 } 3537 } else 3538 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType)); 3539 3540 std::string TypeName = 3541 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str(); 3542 Out << TypeName.length() << TypeName; 3543 } 3544 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) { 3545 DiagnosticsEngine &Diags = Context.getDiags(); 3546 unsigned DiagID = Diags.getCustomDiagID( 3547 DiagnosticsEngine::Error, 3548 "cannot mangle this dependent neon vector type yet"); 3549 Diags.Report(T->getAttributeLoc(), DiagID); 3550 } 3551 3552 // The AArch64 ACLE specifies that fixed-length SVE vector and predicate types 3553 // defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64 3554 // type as the sizeless variants. 3555 // 3556 // The mangling scheme for VLS types is implemented as a "pseudo" template: 3557 // 3558 // '__SVE_VLS<<type>, <vector length>>' 3559 // 3560 // Combining the existing SVE type and a specific vector length (in bits). 3561 // For example: 3562 // 3563 // typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512))); 3564 // 3565 // is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as: 3566 // 3567 // "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE" 3568 // 3569 // i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE 3570 // 3571 // The latest ACLE specification (00bet5) does not contain details of this 3572 // mangling scheme, it will be specified in the next revision. The mangling 3573 // scheme is otherwise defined in the appendices to the Procedure Call Standard 3574 // for the Arm Architecture, see 3575 // https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling 3576 void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) { 3577 assert((T->getVectorKind() == VectorType::SveFixedLengthDataVector || 3578 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) && 3579 "expected fixed-length SVE vector!"); 3580 3581 QualType EltType = T->getElementType(); 3582 assert(EltType->isBuiltinType() && 3583 "expected builtin type for fixed-length SVE vector!"); 3584 3585 StringRef TypeName; 3586 switch (cast<BuiltinType>(EltType)->getKind()) { 3587 case BuiltinType::SChar: 3588 TypeName = "__SVInt8_t"; 3589 break; 3590 case BuiltinType::UChar: { 3591 if (T->getVectorKind() == VectorType::SveFixedLengthDataVector) 3592 TypeName = "__SVUint8_t"; 3593 else 3594 TypeName = "__SVBool_t"; 3595 break; 3596 } 3597 case BuiltinType::Short: 3598 TypeName = "__SVInt16_t"; 3599 break; 3600 case BuiltinType::UShort: 3601 TypeName = "__SVUint16_t"; 3602 break; 3603 case BuiltinType::Int: 3604 TypeName = "__SVInt32_t"; 3605 break; 3606 case BuiltinType::UInt: 3607 TypeName = "__SVUint32_t"; 3608 break; 3609 case BuiltinType::Long: 3610 TypeName = "__SVInt64_t"; 3611 break; 3612 case BuiltinType::ULong: 3613 TypeName = "__SVUint64_t"; 3614 break; 3615 case BuiltinType::Half: 3616 TypeName = "__SVFloat16_t"; 3617 break; 3618 case BuiltinType::Float: 3619 TypeName = "__SVFloat32_t"; 3620 break; 3621 case BuiltinType::Double: 3622 TypeName = "__SVFloat64_t"; 3623 break; 3624 case BuiltinType::BFloat16: 3625 TypeName = "__SVBfloat16_t"; 3626 break; 3627 default: 3628 llvm_unreachable("unexpected element type for fixed-length SVE vector!"); 3629 } 3630 3631 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width; 3632 3633 if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 3634 VecSizeInBits *= 8; 3635 3636 Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj" 3637 << VecSizeInBits << "EE"; 3638 } 3639 3640 void CXXNameMangler::mangleAArch64FixedSveVectorType( 3641 const DependentVectorType *T) { 3642 DiagnosticsEngine &Diags = Context.getDiags(); 3643 unsigned DiagID = Diags.getCustomDiagID( 3644 DiagnosticsEngine::Error, 3645 "cannot mangle this dependent fixed-length SVE vector type yet"); 3646 Diags.Report(T->getAttributeLoc(), DiagID); 3647 } 3648 3649 // GNU extension: vector types 3650 // <type> ::= <vector-type> 3651 // <vector-type> ::= Dv <positive dimension number> _ 3652 // <extended element type> 3653 // ::= Dv [<dimension expression>] _ <element type> 3654 // <extended element type> ::= <element type> 3655 // ::= p # AltiVec vector pixel 3656 // ::= b # Altivec vector bool 3657 void CXXNameMangler::mangleType(const VectorType *T) { 3658 if ((T->getVectorKind() == VectorType::NeonVector || 3659 T->getVectorKind() == VectorType::NeonPolyVector)) { 3660 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 3661 llvm::Triple::ArchType Arch = 3662 getASTContext().getTargetInfo().getTriple().getArch(); 3663 if ((Arch == llvm::Triple::aarch64 || 3664 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin()) 3665 mangleAArch64NeonVectorType(T); 3666 else 3667 mangleNeonVectorType(T); 3668 return; 3669 } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector || 3670 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 3671 mangleAArch64FixedSveVectorType(T); 3672 return; 3673 } 3674 Out << "Dv" << T->getNumElements() << '_'; 3675 if (T->getVectorKind() == VectorType::AltiVecPixel) 3676 Out << 'p'; 3677 else if (T->getVectorKind() == VectorType::AltiVecBool) 3678 Out << 'b'; 3679 else 3680 mangleType(T->getElementType()); 3681 } 3682 3683 void CXXNameMangler::mangleType(const DependentVectorType *T) { 3684 if ((T->getVectorKind() == VectorType::NeonVector || 3685 T->getVectorKind() == VectorType::NeonPolyVector)) { 3686 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 3687 llvm::Triple::ArchType Arch = 3688 getASTContext().getTargetInfo().getTriple().getArch(); 3689 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) && 3690 !Target.isOSDarwin()) 3691 mangleAArch64NeonVectorType(T); 3692 else 3693 mangleNeonVectorType(T); 3694 return; 3695 } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector || 3696 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 3697 mangleAArch64FixedSveVectorType(T); 3698 return; 3699 } 3700 3701 Out << "Dv"; 3702 mangleExpression(T->getSizeExpr()); 3703 Out << '_'; 3704 if (T->getVectorKind() == VectorType::AltiVecPixel) 3705 Out << 'p'; 3706 else if (T->getVectorKind() == VectorType::AltiVecBool) 3707 Out << 'b'; 3708 else 3709 mangleType(T->getElementType()); 3710 } 3711 3712 void CXXNameMangler::mangleType(const ExtVectorType *T) { 3713 mangleType(static_cast<const VectorType*>(T)); 3714 } 3715 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) { 3716 Out << "Dv"; 3717 mangleExpression(T->getSizeExpr()); 3718 Out << '_'; 3719 mangleType(T->getElementType()); 3720 } 3721 3722 void CXXNameMangler::mangleType(const ConstantMatrixType *T) { 3723 // Mangle matrix types as a vendor extended type: 3724 // u<Len>matrix_typeI<Rows><Columns><element type>E 3725 3726 StringRef VendorQualifier = "matrix_type"; 3727 Out << "u" << VendorQualifier.size() << VendorQualifier; 3728 3729 Out << "I"; 3730 auto &ASTCtx = getASTContext(); 3731 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType()); 3732 llvm::APSInt Rows(BitWidth); 3733 Rows = T->getNumRows(); 3734 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows); 3735 llvm::APSInt Columns(BitWidth); 3736 Columns = T->getNumColumns(); 3737 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns); 3738 mangleType(T->getElementType()); 3739 Out << "E"; 3740 } 3741 3742 void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) { 3743 // Mangle matrix types as a vendor extended type: 3744 // u<Len>matrix_typeI<row expr><column expr><element type>E 3745 StringRef VendorQualifier = "matrix_type"; 3746 Out << "u" << VendorQualifier.size() << VendorQualifier; 3747 3748 Out << "I"; 3749 mangleTemplateArgExpr(T->getRowExpr()); 3750 mangleTemplateArgExpr(T->getColumnExpr()); 3751 mangleType(T->getElementType()); 3752 Out << "E"; 3753 } 3754 3755 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) { 3756 SplitQualType split = T->getPointeeType().split(); 3757 mangleQualifiers(split.Quals, T); 3758 mangleType(QualType(split.Ty, 0)); 3759 } 3760 3761 void CXXNameMangler::mangleType(const PackExpansionType *T) { 3762 // <type> ::= Dp <type> # pack expansion (C++0x) 3763 Out << "Dp"; 3764 mangleType(T->getPattern()); 3765 } 3766 3767 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) { 3768 mangleSourceName(T->getDecl()->getIdentifier()); 3769 } 3770 3771 void CXXNameMangler::mangleType(const ObjCObjectType *T) { 3772 // Treat __kindof as a vendor extended type qualifier. 3773 if (T->isKindOfType()) 3774 Out << "U8__kindof"; 3775 3776 if (!T->qual_empty()) { 3777 // Mangle protocol qualifiers. 3778 SmallString<64> QualStr; 3779 llvm::raw_svector_ostream QualOS(QualStr); 3780 QualOS << "objcproto"; 3781 for (const auto *I : T->quals()) { 3782 StringRef name = I->getName(); 3783 QualOS << name.size() << name; 3784 } 3785 Out << 'U' << QualStr.size() << QualStr; 3786 } 3787 3788 mangleType(T->getBaseType()); 3789 3790 if (T->isSpecialized()) { 3791 // Mangle type arguments as I <type>+ E 3792 Out << 'I'; 3793 for (auto typeArg : T->getTypeArgs()) 3794 mangleType(typeArg); 3795 Out << 'E'; 3796 } 3797 } 3798 3799 void CXXNameMangler::mangleType(const BlockPointerType *T) { 3800 Out << "U13block_pointer"; 3801 mangleType(T->getPointeeType()); 3802 } 3803 3804 void CXXNameMangler::mangleType(const InjectedClassNameType *T) { 3805 // Mangle injected class name types as if the user had written the 3806 // specialization out fully. It may not actually be possible to see 3807 // this mangling, though. 3808 mangleType(T->getInjectedSpecializationType()); 3809 } 3810 3811 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) { 3812 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) { 3813 mangleTemplateName(TD, T->getArgs(), T->getNumArgs()); 3814 } else { 3815 if (mangleSubstitution(QualType(T, 0))) 3816 return; 3817 3818 mangleTemplatePrefix(T->getTemplateName()); 3819 3820 // FIXME: GCC does not appear to mangle the template arguments when 3821 // the template in question is a dependent template name. Should we 3822 // emulate that badness? 3823 mangleTemplateArgs(T->getTemplateName(), T->getArgs(), T->getNumArgs()); 3824 addSubstitution(QualType(T, 0)); 3825 } 3826 } 3827 3828 void CXXNameMangler::mangleType(const DependentNameType *T) { 3829 // Proposal by cxx-abi-dev, 2014-03-26 3830 // <class-enum-type> ::= <name> # non-dependent or dependent type name or 3831 // # dependent elaborated type specifier using 3832 // # 'typename' 3833 // ::= Ts <name> # dependent elaborated type specifier using 3834 // # 'struct' or 'class' 3835 // ::= Tu <name> # dependent elaborated type specifier using 3836 // # 'union' 3837 // ::= Te <name> # dependent elaborated type specifier using 3838 // # 'enum' 3839 switch (T->getKeyword()) { 3840 case ETK_None: 3841 case ETK_Typename: 3842 break; 3843 case ETK_Struct: 3844 case ETK_Class: 3845 case ETK_Interface: 3846 Out << "Ts"; 3847 break; 3848 case ETK_Union: 3849 Out << "Tu"; 3850 break; 3851 case ETK_Enum: 3852 Out << "Te"; 3853 break; 3854 } 3855 // Typename types are always nested 3856 Out << 'N'; 3857 manglePrefix(T->getQualifier()); 3858 mangleSourceName(T->getIdentifier()); 3859 Out << 'E'; 3860 } 3861 3862 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) { 3863 // Dependently-scoped template types are nested if they have a prefix. 3864 Out << 'N'; 3865 3866 // TODO: avoid making this TemplateName. 3867 TemplateName Prefix = 3868 getASTContext().getDependentTemplateName(T->getQualifier(), 3869 T->getIdentifier()); 3870 mangleTemplatePrefix(Prefix); 3871 3872 // FIXME: GCC does not appear to mangle the template arguments when 3873 // the template in question is a dependent template name. Should we 3874 // emulate that badness? 3875 mangleTemplateArgs(Prefix, T->getArgs(), T->getNumArgs()); 3876 Out << 'E'; 3877 } 3878 3879 void CXXNameMangler::mangleType(const TypeOfType *T) { 3880 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 3881 // "extension with parameters" mangling. 3882 Out << "u6typeof"; 3883 } 3884 3885 void CXXNameMangler::mangleType(const TypeOfExprType *T) { 3886 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 3887 // "extension with parameters" mangling. 3888 Out << "u6typeof"; 3889 } 3890 3891 void CXXNameMangler::mangleType(const DecltypeType *T) { 3892 Expr *E = T->getUnderlyingExpr(); 3893 3894 // type ::= Dt <expression> E # decltype of an id-expression 3895 // # or class member access 3896 // ::= DT <expression> E # decltype of an expression 3897 3898 // This purports to be an exhaustive list of id-expressions and 3899 // class member accesses. Note that we do not ignore parentheses; 3900 // parentheses change the semantics of decltype for these 3901 // expressions (and cause the mangler to use the other form). 3902 if (isa<DeclRefExpr>(E) || 3903 isa<MemberExpr>(E) || 3904 isa<UnresolvedLookupExpr>(E) || 3905 isa<DependentScopeDeclRefExpr>(E) || 3906 isa<CXXDependentScopeMemberExpr>(E) || 3907 isa<UnresolvedMemberExpr>(E)) 3908 Out << "Dt"; 3909 else 3910 Out << "DT"; 3911 mangleExpression(E); 3912 Out << 'E'; 3913 } 3914 3915 void CXXNameMangler::mangleType(const UnaryTransformType *T) { 3916 // If this is dependent, we need to record that. If not, we simply 3917 // mangle it as the underlying type since they are equivalent. 3918 if (T->isDependentType()) { 3919 Out << 'U'; 3920 3921 switch (T->getUTTKind()) { 3922 case UnaryTransformType::EnumUnderlyingType: 3923 Out << "3eut"; 3924 break; 3925 } 3926 } 3927 3928 mangleType(T->getBaseType()); 3929 } 3930 3931 void CXXNameMangler::mangleType(const AutoType *T) { 3932 assert(T->getDeducedType().isNull() && 3933 "Deduced AutoType shouldn't be handled here!"); 3934 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType && 3935 "shouldn't need to mangle __auto_type!"); 3936 // <builtin-type> ::= Da # auto 3937 // ::= Dc # decltype(auto) 3938 Out << (T->isDecltypeAuto() ? "Dc" : "Da"); 3939 } 3940 3941 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) { 3942 QualType Deduced = T->getDeducedType(); 3943 if (!Deduced.isNull()) 3944 return mangleType(Deduced); 3945 3946 TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl(); 3947 assert(TD && "shouldn't form deduced TST unless we know we have a template"); 3948 3949 if (mangleSubstitution(TD)) 3950 return; 3951 3952 mangleName(GlobalDecl(TD)); 3953 addSubstitution(TD); 3954 } 3955 3956 void CXXNameMangler::mangleType(const AtomicType *T) { 3957 // <type> ::= U <source-name> <type> # vendor extended type qualifier 3958 // (Until there's a standardized mangling...) 3959 Out << "U7_Atomic"; 3960 mangleType(T->getValueType()); 3961 } 3962 3963 void CXXNameMangler::mangleType(const PipeType *T) { 3964 // Pipe type mangling rules are described in SPIR 2.0 specification 3965 // A.1 Data types and A.3 Summary of changes 3966 // <type> ::= 8ocl_pipe 3967 Out << "8ocl_pipe"; 3968 } 3969 3970 void CXXNameMangler::mangleType(const ExtIntType *T) { 3971 Out << "U7_ExtInt"; 3972 llvm::APSInt BW(32, true); 3973 BW = T->getNumBits(); 3974 TemplateArgument TA(Context.getASTContext(), BW, getASTContext().IntTy); 3975 mangleTemplateArgs(TemplateName(), &TA, 1); 3976 if (T->isUnsigned()) 3977 Out << "j"; 3978 else 3979 Out << "i"; 3980 } 3981 3982 void CXXNameMangler::mangleType(const DependentExtIntType *T) { 3983 Out << "U7_ExtInt"; 3984 TemplateArgument TA(T->getNumBitsExpr()); 3985 mangleTemplateArgs(TemplateName(), &TA, 1); 3986 if (T->isUnsigned()) 3987 Out << "j"; 3988 else 3989 Out << "i"; 3990 } 3991 3992 void CXXNameMangler::mangleIntegerLiteral(QualType T, 3993 const llvm::APSInt &Value) { 3994 // <expr-primary> ::= L <type> <value number> E # integer literal 3995 Out << 'L'; 3996 3997 mangleType(T); 3998 if (T->isBooleanType()) { 3999 // Boolean values are encoded as 0/1. 4000 Out << (Value.getBoolValue() ? '1' : '0'); 4001 } else { 4002 mangleNumber(Value); 4003 } 4004 Out << 'E'; 4005 4006 } 4007 4008 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) { 4009 // Ignore member expressions involving anonymous unions. 4010 while (const auto *RT = Base->getType()->getAs<RecordType>()) { 4011 if (!RT->getDecl()->isAnonymousStructOrUnion()) 4012 break; 4013 const auto *ME = dyn_cast<MemberExpr>(Base); 4014 if (!ME) 4015 break; 4016 Base = ME->getBase(); 4017 IsArrow = ME->isArrow(); 4018 } 4019 4020 if (Base->isImplicitCXXThis()) { 4021 // Note: GCC mangles member expressions to the implicit 'this' as 4022 // *this., whereas we represent them as this->. The Itanium C++ ABI 4023 // does not specify anything here, so we follow GCC. 4024 Out << "dtdefpT"; 4025 } else { 4026 Out << (IsArrow ? "pt" : "dt"); 4027 mangleExpression(Base); 4028 } 4029 } 4030 4031 /// Mangles a member expression. 4032 void CXXNameMangler::mangleMemberExpr(const Expr *base, 4033 bool isArrow, 4034 NestedNameSpecifier *qualifier, 4035 NamedDecl *firstQualifierLookup, 4036 DeclarationName member, 4037 const TemplateArgumentLoc *TemplateArgs, 4038 unsigned NumTemplateArgs, 4039 unsigned arity) { 4040 // <expression> ::= dt <expression> <unresolved-name> 4041 // ::= pt <expression> <unresolved-name> 4042 if (base) 4043 mangleMemberExprBase(base, isArrow); 4044 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity); 4045 } 4046 4047 /// Look at the callee of the given call expression and determine if 4048 /// it's a parenthesized id-expression which would have triggered ADL 4049 /// otherwise. 4050 static bool isParenthesizedADLCallee(const CallExpr *call) { 4051 const Expr *callee = call->getCallee(); 4052 const Expr *fn = callee->IgnoreParens(); 4053 4054 // Must be parenthesized. IgnoreParens() skips __extension__ nodes, 4055 // too, but for those to appear in the callee, it would have to be 4056 // parenthesized. 4057 if (callee == fn) return false; 4058 4059 // Must be an unresolved lookup. 4060 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn); 4061 if (!lookup) return false; 4062 4063 assert(!lookup->requiresADL()); 4064 4065 // Must be an unqualified lookup. 4066 if (lookup->getQualifier()) return false; 4067 4068 // Must not have found a class member. Note that if one is a class 4069 // member, they're all class members. 4070 if (lookup->getNumDecls() > 0 && 4071 (*lookup->decls_begin())->isCXXClassMember()) 4072 return false; 4073 4074 // Otherwise, ADL would have been triggered. 4075 return true; 4076 } 4077 4078 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) { 4079 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E); 4080 Out << CastEncoding; 4081 mangleType(ECE->getType()); 4082 mangleExpression(ECE->getSubExpr()); 4083 } 4084 4085 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) { 4086 if (auto *Syntactic = InitList->getSyntacticForm()) 4087 InitList = Syntactic; 4088 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 4089 mangleExpression(InitList->getInit(i)); 4090 } 4091 4092 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity, 4093 bool AsTemplateArg) { 4094 // <expression> ::= <unary operator-name> <expression> 4095 // ::= <binary operator-name> <expression> <expression> 4096 // ::= <trinary operator-name> <expression> <expression> <expression> 4097 // ::= cv <type> expression # conversion with one argument 4098 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments 4099 // ::= dc <type> <expression> # dynamic_cast<type> (expression) 4100 // ::= sc <type> <expression> # static_cast<type> (expression) 4101 // ::= cc <type> <expression> # const_cast<type> (expression) 4102 // ::= rc <type> <expression> # reinterpret_cast<type> (expression) 4103 // ::= st <type> # sizeof (a type) 4104 // ::= at <type> # alignof (a type) 4105 // ::= <template-param> 4106 // ::= <function-param> 4107 // ::= fpT # 'this' expression (part of <function-param>) 4108 // ::= sr <type> <unqualified-name> # dependent name 4109 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id 4110 // ::= ds <expression> <expression> # expr.*expr 4111 // ::= sZ <template-param> # size of a parameter pack 4112 // ::= sZ <function-param> # size of a function parameter pack 4113 // ::= u <source-name> <template-arg>* E # vendor extended expression 4114 // ::= <expr-primary> 4115 // <expr-primary> ::= L <type> <value number> E # integer literal 4116 // ::= L <type> <value float> E # floating literal 4117 // ::= L <type> <string type> E # string literal 4118 // ::= L <nullptr type> E # nullptr literal "LDnE" 4119 // ::= L <pointer type> 0 E # null pointer template argument 4120 // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang 4121 // ::= L <mangled-name> E # external name 4122 QualType ImplicitlyConvertedToType; 4123 4124 // A top-level expression that's not <expr-primary> needs to be wrapped in 4125 // X...E in a template arg. 4126 bool IsPrimaryExpr = true; 4127 auto NotPrimaryExpr = [&] { 4128 if (AsTemplateArg && IsPrimaryExpr) 4129 Out << 'X'; 4130 IsPrimaryExpr = false; 4131 }; 4132 4133 auto MangleDeclRefExpr = [&](const NamedDecl *D) { 4134 switch (D->getKind()) { 4135 default: 4136 // <expr-primary> ::= L <mangled-name> E # external name 4137 Out << 'L'; 4138 mangle(D); 4139 Out << 'E'; 4140 break; 4141 4142 case Decl::ParmVar: 4143 NotPrimaryExpr(); 4144 mangleFunctionParam(cast<ParmVarDecl>(D)); 4145 break; 4146 4147 case Decl::EnumConstant: { 4148 // <expr-primary> 4149 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D); 4150 mangleIntegerLiteral(ED->getType(), ED->getInitVal()); 4151 break; 4152 } 4153 4154 case Decl::NonTypeTemplateParm: 4155 NotPrimaryExpr(); 4156 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D); 4157 mangleTemplateParameter(PD->getDepth(), PD->getIndex()); 4158 break; 4159 } 4160 }; 4161 4162 // 'goto recurse' is used when handling a simple "unwrapping" node which 4163 // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need 4164 // to be preserved. 4165 recurse: 4166 switch (E->getStmtClass()) { 4167 case Expr::NoStmtClass: 4168 #define ABSTRACT_STMT(Type) 4169 #define EXPR(Type, Base) 4170 #define STMT(Type, Base) \ 4171 case Expr::Type##Class: 4172 #include "clang/AST/StmtNodes.inc" 4173 // fallthrough 4174 4175 // These all can only appear in local or variable-initialization 4176 // contexts and so should never appear in a mangling. 4177 case Expr::AddrLabelExprClass: 4178 case Expr::DesignatedInitUpdateExprClass: 4179 case Expr::ImplicitValueInitExprClass: 4180 case Expr::ArrayInitLoopExprClass: 4181 case Expr::ArrayInitIndexExprClass: 4182 case Expr::NoInitExprClass: 4183 case Expr::ParenListExprClass: 4184 case Expr::MSPropertyRefExprClass: 4185 case Expr::MSPropertySubscriptExprClass: 4186 case Expr::TypoExprClass: // This should no longer exist in the AST by now. 4187 case Expr::RecoveryExprClass: 4188 case Expr::OMPArraySectionExprClass: 4189 case Expr::OMPArrayShapingExprClass: 4190 case Expr::OMPIteratorExprClass: 4191 case Expr::CXXInheritedCtorInitExprClass: 4192 llvm_unreachable("unexpected statement kind"); 4193 4194 case Expr::ConstantExprClass: 4195 E = cast<ConstantExpr>(E)->getSubExpr(); 4196 goto recurse; 4197 4198 // FIXME: invent manglings for all these. 4199 case Expr::BlockExprClass: 4200 case Expr::ChooseExprClass: 4201 case Expr::CompoundLiteralExprClass: 4202 case Expr::ExtVectorElementExprClass: 4203 case Expr::GenericSelectionExprClass: 4204 case Expr::ObjCEncodeExprClass: 4205 case Expr::ObjCIsaExprClass: 4206 case Expr::ObjCIvarRefExprClass: 4207 case Expr::ObjCMessageExprClass: 4208 case Expr::ObjCPropertyRefExprClass: 4209 case Expr::ObjCProtocolExprClass: 4210 case Expr::ObjCSelectorExprClass: 4211 case Expr::ObjCStringLiteralClass: 4212 case Expr::ObjCBoxedExprClass: 4213 case Expr::ObjCArrayLiteralClass: 4214 case Expr::ObjCDictionaryLiteralClass: 4215 case Expr::ObjCSubscriptRefExprClass: 4216 case Expr::ObjCIndirectCopyRestoreExprClass: 4217 case Expr::ObjCAvailabilityCheckExprClass: 4218 case Expr::OffsetOfExprClass: 4219 case Expr::PredefinedExprClass: 4220 case Expr::ShuffleVectorExprClass: 4221 case Expr::ConvertVectorExprClass: 4222 case Expr::StmtExprClass: 4223 case Expr::TypeTraitExprClass: 4224 case Expr::RequiresExprClass: 4225 case Expr::ArrayTypeTraitExprClass: 4226 case Expr::ExpressionTraitExprClass: 4227 case Expr::VAArgExprClass: 4228 case Expr::CUDAKernelCallExprClass: 4229 case Expr::AsTypeExprClass: 4230 case Expr::PseudoObjectExprClass: 4231 case Expr::AtomicExprClass: 4232 case Expr::SourceLocExprClass: 4233 case Expr::BuiltinBitCastExprClass: 4234 { 4235 NotPrimaryExpr(); 4236 if (!NullOut) { 4237 // As bad as this diagnostic is, it's better than crashing. 4238 DiagnosticsEngine &Diags = Context.getDiags(); 4239 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 4240 "cannot yet mangle expression type %0"); 4241 Diags.Report(E->getExprLoc(), DiagID) 4242 << E->getStmtClassName() << E->getSourceRange(); 4243 return; 4244 } 4245 break; 4246 } 4247 4248 case Expr::CXXUuidofExprClass: { 4249 NotPrimaryExpr(); 4250 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E); 4251 // As of clang 12, uuidof uses the vendor extended expression 4252 // mangling. Previously, it used a special-cased nonstandard extension. 4253 if (Context.getASTContext().getLangOpts().getClangABICompat() > 4254 LangOptions::ClangABI::Ver11) { 4255 Out << "u8__uuidof"; 4256 if (UE->isTypeOperand()) 4257 mangleType(UE->getTypeOperand(Context.getASTContext())); 4258 else 4259 mangleTemplateArgExpr(UE->getExprOperand()); 4260 Out << 'E'; 4261 } else { 4262 if (UE->isTypeOperand()) { 4263 QualType UuidT = UE->getTypeOperand(Context.getASTContext()); 4264 Out << "u8__uuidoft"; 4265 mangleType(UuidT); 4266 } else { 4267 Expr *UuidExp = UE->getExprOperand(); 4268 Out << "u8__uuidofz"; 4269 mangleExpression(UuidExp); 4270 } 4271 } 4272 break; 4273 } 4274 4275 // Even gcc-4.5 doesn't mangle this. 4276 case Expr::BinaryConditionalOperatorClass: { 4277 NotPrimaryExpr(); 4278 DiagnosticsEngine &Diags = Context.getDiags(); 4279 unsigned DiagID = 4280 Diags.getCustomDiagID(DiagnosticsEngine::Error, 4281 "?: operator with omitted middle operand cannot be mangled"); 4282 Diags.Report(E->getExprLoc(), DiagID) 4283 << E->getStmtClassName() << E->getSourceRange(); 4284 return; 4285 } 4286 4287 // These are used for internal purposes and cannot be meaningfully mangled. 4288 case Expr::OpaqueValueExprClass: 4289 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?"); 4290 4291 case Expr::InitListExprClass: { 4292 NotPrimaryExpr(); 4293 Out << "il"; 4294 mangleInitListElements(cast<InitListExpr>(E)); 4295 Out << "E"; 4296 break; 4297 } 4298 4299 case Expr::DesignatedInitExprClass: { 4300 NotPrimaryExpr(); 4301 auto *DIE = cast<DesignatedInitExpr>(E); 4302 for (const auto &Designator : DIE->designators()) { 4303 if (Designator.isFieldDesignator()) { 4304 Out << "di"; 4305 mangleSourceName(Designator.getFieldName()); 4306 } else if (Designator.isArrayDesignator()) { 4307 Out << "dx"; 4308 mangleExpression(DIE->getArrayIndex(Designator)); 4309 } else { 4310 assert(Designator.isArrayRangeDesignator() && 4311 "unknown designator kind"); 4312 Out << "dX"; 4313 mangleExpression(DIE->getArrayRangeStart(Designator)); 4314 mangleExpression(DIE->getArrayRangeEnd(Designator)); 4315 } 4316 } 4317 mangleExpression(DIE->getInit()); 4318 break; 4319 } 4320 4321 case Expr::CXXDefaultArgExprClass: 4322 E = cast<CXXDefaultArgExpr>(E)->getExpr(); 4323 goto recurse; 4324 4325 case Expr::CXXDefaultInitExprClass: 4326 E = cast<CXXDefaultInitExpr>(E)->getExpr(); 4327 goto recurse; 4328 4329 case Expr::CXXStdInitializerListExprClass: 4330 E = cast<CXXStdInitializerListExpr>(E)->getSubExpr(); 4331 goto recurse; 4332 4333 case Expr::SubstNonTypeTemplateParmExprClass: 4334 E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(); 4335 goto recurse; 4336 4337 case Expr::UserDefinedLiteralClass: 4338 // We follow g++'s approach of mangling a UDL as a call to the literal 4339 // operator. 4340 case Expr::CXXMemberCallExprClass: // fallthrough 4341 case Expr::CallExprClass: { 4342 NotPrimaryExpr(); 4343 const CallExpr *CE = cast<CallExpr>(E); 4344 4345 // <expression> ::= cp <simple-id> <expression>* E 4346 // We use this mangling only when the call would use ADL except 4347 // for being parenthesized. Per discussion with David 4348 // Vandervoorde, 2011.04.25. 4349 if (isParenthesizedADLCallee(CE)) { 4350 Out << "cp"; 4351 // The callee here is a parenthesized UnresolvedLookupExpr with 4352 // no qualifier and should always get mangled as a <simple-id> 4353 // anyway. 4354 4355 // <expression> ::= cl <expression>* E 4356 } else { 4357 Out << "cl"; 4358 } 4359 4360 unsigned CallArity = CE->getNumArgs(); 4361 for (const Expr *Arg : CE->arguments()) 4362 if (isa<PackExpansionExpr>(Arg)) 4363 CallArity = UnknownArity; 4364 4365 mangleExpression(CE->getCallee(), CallArity); 4366 for (const Expr *Arg : CE->arguments()) 4367 mangleExpression(Arg); 4368 Out << 'E'; 4369 break; 4370 } 4371 4372 case Expr::CXXNewExprClass: { 4373 NotPrimaryExpr(); 4374 const CXXNewExpr *New = cast<CXXNewExpr>(E); 4375 if (New->isGlobalNew()) Out << "gs"; 4376 Out << (New->isArray() ? "na" : "nw"); 4377 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(), 4378 E = New->placement_arg_end(); I != E; ++I) 4379 mangleExpression(*I); 4380 Out << '_'; 4381 mangleType(New->getAllocatedType()); 4382 if (New->hasInitializer()) { 4383 if (New->getInitializationStyle() == CXXNewExpr::ListInit) 4384 Out << "il"; 4385 else 4386 Out << "pi"; 4387 const Expr *Init = New->getInitializer(); 4388 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 4389 // Directly inline the initializers. 4390 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 4391 E = CCE->arg_end(); 4392 I != E; ++I) 4393 mangleExpression(*I); 4394 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) { 4395 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i) 4396 mangleExpression(PLE->getExpr(i)); 4397 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit && 4398 isa<InitListExpr>(Init)) { 4399 // Only take InitListExprs apart for list-initialization. 4400 mangleInitListElements(cast<InitListExpr>(Init)); 4401 } else 4402 mangleExpression(Init); 4403 } 4404 Out << 'E'; 4405 break; 4406 } 4407 4408 case Expr::CXXPseudoDestructorExprClass: { 4409 NotPrimaryExpr(); 4410 const auto *PDE = cast<CXXPseudoDestructorExpr>(E); 4411 if (const Expr *Base = PDE->getBase()) 4412 mangleMemberExprBase(Base, PDE->isArrow()); 4413 NestedNameSpecifier *Qualifier = PDE->getQualifier(); 4414 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) { 4415 if (Qualifier) { 4416 mangleUnresolvedPrefix(Qualifier, 4417 /*recursive=*/true); 4418 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()); 4419 Out << 'E'; 4420 } else { 4421 Out << "sr"; 4422 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType())) 4423 Out << 'E'; 4424 } 4425 } else if (Qualifier) { 4426 mangleUnresolvedPrefix(Qualifier); 4427 } 4428 // <base-unresolved-name> ::= dn <destructor-name> 4429 Out << "dn"; 4430 QualType DestroyedType = PDE->getDestroyedType(); 4431 mangleUnresolvedTypeOrSimpleId(DestroyedType); 4432 break; 4433 } 4434 4435 case Expr::MemberExprClass: { 4436 NotPrimaryExpr(); 4437 const MemberExpr *ME = cast<MemberExpr>(E); 4438 mangleMemberExpr(ME->getBase(), ME->isArrow(), 4439 ME->getQualifier(), nullptr, 4440 ME->getMemberDecl()->getDeclName(), 4441 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4442 Arity); 4443 break; 4444 } 4445 4446 case Expr::UnresolvedMemberExprClass: { 4447 NotPrimaryExpr(); 4448 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E); 4449 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 4450 ME->isArrow(), ME->getQualifier(), nullptr, 4451 ME->getMemberName(), 4452 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4453 Arity); 4454 break; 4455 } 4456 4457 case Expr::CXXDependentScopeMemberExprClass: { 4458 NotPrimaryExpr(); 4459 const CXXDependentScopeMemberExpr *ME 4460 = cast<CXXDependentScopeMemberExpr>(E); 4461 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 4462 ME->isArrow(), ME->getQualifier(), 4463 ME->getFirstQualifierFoundInScope(), 4464 ME->getMember(), 4465 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4466 Arity); 4467 break; 4468 } 4469 4470 case Expr::UnresolvedLookupExprClass: { 4471 NotPrimaryExpr(); 4472 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E); 4473 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), 4474 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(), 4475 Arity); 4476 break; 4477 } 4478 4479 case Expr::CXXUnresolvedConstructExprClass: { 4480 NotPrimaryExpr(); 4481 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E); 4482 unsigned N = CE->getNumArgs(); 4483 4484 if (CE->isListInitialization()) { 4485 assert(N == 1 && "unexpected form for list initialization"); 4486 auto *IL = cast<InitListExpr>(CE->getArg(0)); 4487 Out << "tl"; 4488 mangleType(CE->getType()); 4489 mangleInitListElements(IL); 4490 Out << "E"; 4491 break; 4492 } 4493 4494 Out << "cv"; 4495 mangleType(CE->getType()); 4496 if (N != 1) Out << '_'; 4497 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 4498 if (N != 1) Out << 'E'; 4499 break; 4500 } 4501 4502 case Expr::CXXConstructExprClass: { 4503 // An implicit cast is silent, thus may contain <expr-primary>. 4504 const auto *CE = cast<CXXConstructExpr>(E); 4505 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) { 4506 assert( 4507 CE->getNumArgs() >= 1 && 4508 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && 4509 "implicit CXXConstructExpr must have one argument"); 4510 E = cast<CXXConstructExpr>(E)->getArg(0); 4511 goto recurse; 4512 } 4513 NotPrimaryExpr(); 4514 Out << "il"; 4515 for (auto *E : CE->arguments()) 4516 mangleExpression(E); 4517 Out << "E"; 4518 break; 4519 } 4520 4521 case Expr::CXXTemporaryObjectExprClass: { 4522 NotPrimaryExpr(); 4523 const auto *CE = cast<CXXTemporaryObjectExpr>(E); 4524 unsigned N = CE->getNumArgs(); 4525 bool List = CE->isListInitialization(); 4526 4527 if (List) 4528 Out << "tl"; 4529 else 4530 Out << "cv"; 4531 mangleType(CE->getType()); 4532 if (!List && N != 1) 4533 Out << '_'; 4534 if (CE->isStdInitListInitialization()) { 4535 // We implicitly created a std::initializer_list<T> for the first argument 4536 // of a constructor of type U in an expression of the form U{a, b, c}. 4537 // Strip all the semantic gunk off the initializer list. 4538 auto *SILE = 4539 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit()); 4540 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit()); 4541 mangleInitListElements(ILE); 4542 } else { 4543 for (auto *E : CE->arguments()) 4544 mangleExpression(E); 4545 } 4546 if (List || N != 1) 4547 Out << 'E'; 4548 break; 4549 } 4550 4551 case Expr::CXXScalarValueInitExprClass: 4552 NotPrimaryExpr(); 4553 Out << "cv"; 4554 mangleType(E->getType()); 4555 Out << "_E"; 4556 break; 4557 4558 case Expr::CXXNoexceptExprClass: 4559 NotPrimaryExpr(); 4560 Out << "nx"; 4561 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand()); 4562 break; 4563 4564 case Expr::UnaryExprOrTypeTraitExprClass: { 4565 // Non-instantiation-dependent traits are an <expr-primary> integer literal. 4566 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); 4567 4568 if (!SAE->isInstantiationDependent()) { 4569 // Itanium C++ ABI: 4570 // If the operand of a sizeof or alignof operator is not 4571 // instantiation-dependent it is encoded as an integer literal 4572 // reflecting the result of the operator. 4573 // 4574 // If the result of the operator is implicitly converted to a known 4575 // integer type, that type is used for the literal; otherwise, the type 4576 // of std::size_t or std::ptrdiff_t is used. 4577 QualType T = (ImplicitlyConvertedToType.isNull() || 4578 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() 4579 : ImplicitlyConvertedToType; 4580 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); 4581 mangleIntegerLiteral(T, V); 4582 break; 4583 } 4584 4585 NotPrimaryExpr(); // But otherwise, they are not. 4586 4587 auto MangleAlignofSizeofArg = [&] { 4588 if (SAE->isArgumentType()) { 4589 Out << 't'; 4590 mangleType(SAE->getArgumentType()); 4591 } else { 4592 Out << 'z'; 4593 mangleExpression(SAE->getArgumentExpr()); 4594 } 4595 }; 4596 4597 switch(SAE->getKind()) { 4598 case UETT_SizeOf: 4599 Out << 's'; 4600 MangleAlignofSizeofArg(); 4601 break; 4602 case UETT_PreferredAlignOf: 4603 // As of clang 12, we mangle __alignof__ differently than alignof. (They 4604 // have acted differently since Clang 8, but were previously mangled the 4605 // same.) 4606 if (Context.getASTContext().getLangOpts().getClangABICompat() > 4607 LangOptions::ClangABI::Ver11) { 4608 Out << "u11__alignof__"; 4609 if (SAE->isArgumentType()) 4610 mangleType(SAE->getArgumentType()); 4611 else 4612 mangleTemplateArgExpr(SAE->getArgumentExpr()); 4613 Out << 'E'; 4614 break; 4615 } 4616 LLVM_FALLTHROUGH; 4617 case UETT_AlignOf: 4618 Out << 'a'; 4619 MangleAlignofSizeofArg(); 4620 break; 4621 case UETT_VecStep: { 4622 DiagnosticsEngine &Diags = Context.getDiags(); 4623 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 4624 "cannot yet mangle vec_step expression"); 4625 Diags.Report(DiagID); 4626 return; 4627 } 4628 case UETT_OpenMPRequiredSimdAlign: { 4629 DiagnosticsEngine &Diags = Context.getDiags(); 4630 unsigned DiagID = Diags.getCustomDiagID( 4631 DiagnosticsEngine::Error, 4632 "cannot yet mangle __builtin_omp_required_simd_align expression"); 4633 Diags.Report(DiagID); 4634 return; 4635 } 4636 } 4637 break; 4638 } 4639 4640 case Expr::CXXThrowExprClass: { 4641 NotPrimaryExpr(); 4642 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E); 4643 // <expression> ::= tw <expression> # throw expression 4644 // ::= tr # rethrow 4645 if (TE->getSubExpr()) { 4646 Out << "tw"; 4647 mangleExpression(TE->getSubExpr()); 4648 } else { 4649 Out << "tr"; 4650 } 4651 break; 4652 } 4653 4654 case Expr::CXXTypeidExprClass: { 4655 NotPrimaryExpr(); 4656 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E); 4657 // <expression> ::= ti <type> # typeid (type) 4658 // ::= te <expression> # typeid (expression) 4659 if (TIE->isTypeOperand()) { 4660 Out << "ti"; 4661 mangleType(TIE->getTypeOperand(Context.getASTContext())); 4662 } else { 4663 Out << "te"; 4664 mangleExpression(TIE->getExprOperand()); 4665 } 4666 break; 4667 } 4668 4669 case Expr::CXXDeleteExprClass: { 4670 NotPrimaryExpr(); 4671 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E); 4672 // <expression> ::= [gs] dl <expression> # [::] delete expr 4673 // ::= [gs] da <expression> # [::] delete [] expr 4674 if (DE->isGlobalDelete()) Out << "gs"; 4675 Out << (DE->isArrayForm() ? "da" : "dl"); 4676 mangleExpression(DE->getArgument()); 4677 break; 4678 } 4679 4680 case Expr::UnaryOperatorClass: { 4681 NotPrimaryExpr(); 4682 const UnaryOperator *UO = cast<UnaryOperator>(E); 4683 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()), 4684 /*Arity=*/1); 4685 mangleExpression(UO->getSubExpr()); 4686 break; 4687 } 4688 4689 case Expr::ArraySubscriptExprClass: { 4690 NotPrimaryExpr(); 4691 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E); 4692 4693 // Array subscript is treated as a syntactically weird form of 4694 // binary operator. 4695 Out << "ix"; 4696 mangleExpression(AE->getLHS()); 4697 mangleExpression(AE->getRHS()); 4698 break; 4699 } 4700 4701 case Expr::MatrixSubscriptExprClass: { 4702 NotPrimaryExpr(); 4703 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E); 4704 Out << "ixix"; 4705 mangleExpression(ME->getBase()); 4706 mangleExpression(ME->getRowIdx()); 4707 mangleExpression(ME->getColumnIdx()); 4708 break; 4709 } 4710 4711 case Expr::CompoundAssignOperatorClass: // fallthrough 4712 case Expr::BinaryOperatorClass: { 4713 NotPrimaryExpr(); 4714 const BinaryOperator *BO = cast<BinaryOperator>(E); 4715 if (BO->getOpcode() == BO_PtrMemD) 4716 Out << "ds"; 4717 else 4718 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()), 4719 /*Arity=*/2); 4720 mangleExpression(BO->getLHS()); 4721 mangleExpression(BO->getRHS()); 4722 break; 4723 } 4724 4725 case Expr::CXXRewrittenBinaryOperatorClass: { 4726 NotPrimaryExpr(); 4727 // The mangled form represents the original syntax. 4728 CXXRewrittenBinaryOperator::DecomposedForm Decomposed = 4729 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm(); 4730 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode), 4731 /*Arity=*/2); 4732 mangleExpression(Decomposed.LHS); 4733 mangleExpression(Decomposed.RHS); 4734 break; 4735 } 4736 4737 case Expr::ConditionalOperatorClass: { 4738 NotPrimaryExpr(); 4739 const ConditionalOperator *CO = cast<ConditionalOperator>(E); 4740 mangleOperatorName(OO_Conditional, /*Arity=*/3); 4741 mangleExpression(CO->getCond()); 4742 mangleExpression(CO->getLHS(), Arity); 4743 mangleExpression(CO->getRHS(), Arity); 4744 break; 4745 } 4746 4747 case Expr::ImplicitCastExprClass: { 4748 ImplicitlyConvertedToType = E->getType(); 4749 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4750 goto recurse; 4751 } 4752 4753 case Expr::ObjCBridgedCastExprClass: { 4754 NotPrimaryExpr(); 4755 // Mangle ownership casts as a vendor extended operator __bridge, 4756 // __bridge_transfer, or __bridge_retain. 4757 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); 4758 Out << "v1U" << Kind.size() << Kind; 4759 mangleCastExpression(E, "cv"); 4760 break; 4761 } 4762 4763 case Expr::CStyleCastExprClass: 4764 NotPrimaryExpr(); 4765 mangleCastExpression(E, "cv"); 4766 break; 4767 4768 case Expr::CXXFunctionalCastExprClass: { 4769 NotPrimaryExpr(); 4770 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit(); 4771 // FIXME: Add isImplicit to CXXConstructExpr. 4772 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub)) 4773 if (CCE->getParenOrBraceRange().isInvalid()) 4774 Sub = CCE->getArg(0)->IgnoreImplicit(); 4775 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub)) 4776 Sub = StdInitList->getSubExpr()->IgnoreImplicit(); 4777 if (auto *IL = dyn_cast<InitListExpr>(Sub)) { 4778 Out << "tl"; 4779 mangleType(E->getType()); 4780 mangleInitListElements(IL); 4781 Out << "E"; 4782 } else { 4783 mangleCastExpression(E, "cv"); 4784 } 4785 break; 4786 } 4787 4788 case Expr::CXXStaticCastExprClass: 4789 NotPrimaryExpr(); 4790 mangleCastExpression(E, "sc"); 4791 break; 4792 case Expr::CXXDynamicCastExprClass: 4793 NotPrimaryExpr(); 4794 mangleCastExpression(E, "dc"); 4795 break; 4796 case Expr::CXXReinterpretCastExprClass: 4797 NotPrimaryExpr(); 4798 mangleCastExpression(E, "rc"); 4799 break; 4800 case Expr::CXXConstCastExprClass: 4801 NotPrimaryExpr(); 4802 mangleCastExpression(E, "cc"); 4803 break; 4804 case Expr::CXXAddrspaceCastExprClass: 4805 NotPrimaryExpr(); 4806 mangleCastExpression(E, "ac"); 4807 break; 4808 4809 case Expr::CXXOperatorCallExprClass: { 4810 NotPrimaryExpr(); 4811 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E); 4812 unsigned NumArgs = CE->getNumArgs(); 4813 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax 4814 // (the enclosing MemberExpr covers the syntactic portion). 4815 if (CE->getOperator() != OO_Arrow) 4816 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs); 4817 // Mangle the arguments. 4818 for (unsigned i = 0; i != NumArgs; ++i) 4819 mangleExpression(CE->getArg(i)); 4820 break; 4821 } 4822 4823 case Expr::ParenExprClass: 4824 E = cast<ParenExpr>(E)->getSubExpr(); 4825 goto recurse; 4826 4827 case Expr::ConceptSpecializationExprClass: { 4828 // <expr-primary> ::= L <mangled-name> E # external name 4829 Out << "L_Z"; 4830 auto *CSE = cast<ConceptSpecializationExpr>(E); 4831 mangleTemplateName(CSE->getNamedConcept(), 4832 CSE->getTemplateArguments().data(), 4833 CSE->getTemplateArguments().size()); 4834 Out << 'E'; 4835 break; 4836 } 4837 4838 case Expr::DeclRefExprClass: 4839 // MangleDeclRefExpr helper handles primary-vs-nonprimary 4840 MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl()); 4841 break; 4842 4843 case Expr::SubstNonTypeTemplateParmPackExprClass: 4844 NotPrimaryExpr(); 4845 // FIXME: not clear how to mangle this! 4846 // template <unsigned N...> class A { 4847 // template <class U...> void foo(U (&x)[N]...); 4848 // }; 4849 Out << "_SUBSTPACK_"; 4850 break; 4851 4852 case Expr::FunctionParmPackExprClass: { 4853 NotPrimaryExpr(); 4854 // FIXME: not clear how to mangle this! 4855 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E); 4856 Out << "v110_SUBSTPACK"; 4857 MangleDeclRefExpr(FPPE->getParameterPack()); 4858 break; 4859 } 4860 4861 case Expr::DependentScopeDeclRefExprClass: { 4862 NotPrimaryExpr(); 4863 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E); 4864 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), 4865 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(), 4866 Arity); 4867 break; 4868 } 4869 4870 case Expr::CXXBindTemporaryExprClass: 4871 E = cast<CXXBindTemporaryExpr>(E)->getSubExpr(); 4872 goto recurse; 4873 4874 case Expr::ExprWithCleanupsClass: 4875 E = cast<ExprWithCleanups>(E)->getSubExpr(); 4876 goto recurse; 4877 4878 case Expr::FloatingLiteralClass: { 4879 // <expr-primary> 4880 const FloatingLiteral *FL = cast<FloatingLiteral>(E); 4881 mangleFloatLiteral(FL->getType(), FL->getValue()); 4882 break; 4883 } 4884 4885 case Expr::FixedPointLiteralClass: 4886 // Currently unimplemented -- might be <expr-primary> in future? 4887 mangleFixedPointLiteral(); 4888 break; 4889 4890 case Expr::CharacterLiteralClass: 4891 // <expr-primary> 4892 Out << 'L'; 4893 mangleType(E->getType()); 4894 Out << cast<CharacterLiteral>(E)->getValue(); 4895 Out << 'E'; 4896 break; 4897 4898 // FIXME. __objc_yes/__objc_no are mangled same as true/false 4899 case Expr::ObjCBoolLiteralExprClass: 4900 // <expr-primary> 4901 Out << "Lb"; 4902 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 4903 Out << 'E'; 4904 break; 4905 4906 case Expr::CXXBoolLiteralExprClass: 4907 // <expr-primary> 4908 Out << "Lb"; 4909 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 4910 Out << 'E'; 4911 break; 4912 4913 case Expr::IntegerLiteralClass: { 4914 // <expr-primary> 4915 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue()); 4916 if (E->getType()->isSignedIntegerType()) 4917 Value.setIsSigned(true); 4918 mangleIntegerLiteral(E->getType(), Value); 4919 break; 4920 } 4921 4922 case Expr::ImaginaryLiteralClass: { 4923 // <expr-primary> 4924 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E); 4925 // Mangle as if a complex literal. 4926 // Proposal from David Vandevoorde, 2010.06.30. 4927 Out << 'L'; 4928 mangleType(E->getType()); 4929 if (const FloatingLiteral *Imag = 4930 dyn_cast<FloatingLiteral>(IE->getSubExpr())) { 4931 // Mangle a floating-point zero of the appropriate type. 4932 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics())); 4933 Out << '_'; 4934 mangleFloat(Imag->getValue()); 4935 } else { 4936 Out << "0_"; 4937 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue()); 4938 if (IE->getSubExpr()->getType()->isSignedIntegerType()) 4939 Value.setIsSigned(true); 4940 mangleNumber(Value); 4941 } 4942 Out << 'E'; 4943 break; 4944 } 4945 4946 case Expr::StringLiteralClass: { 4947 // <expr-primary> 4948 // Revised proposal from David Vandervoorde, 2010.07.15. 4949 Out << 'L'; 4950 assert(isa<ConstantArrayType>(E->getType())); 4951 mangleType(E->getType()); 4952 Out << 'E'; 4953 break; 4954 } 4955 4956 case Expr::GNUNullExprClass: 4957 // <expr-primary> 4958 // Mangle as if an integer literal 0. 4959 mangleIntegerLiteral(E->getType(), llvm::APSInt(32)); 4960 break; 4961 4962 case Expr::CXXNullPtrLiteralExprClass: { 4963 // <expr-primary> 4964 Out << "LDnE"; 4965 break; 4966 } 4967 4968 case Expr::LambdaExprClass: { 4969 // A lambda-expression can't appear in the signature of an 4970 // externally-visible declaration, so there's no standard mangling for 4971 // this, but mangling as a literal of the closure type seems reasonable. 4972 Out << "L"; 4973 mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass())); 4974 Out << "E"; 4975 break; 4976 } 4977 4978 case Expr::PackExpansionExprClass: 4979 NotPrimaryExpr(); 4980 Out << "sp"; 4981 mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); 4982 break; 4983 4984 case Expr::SizeOfPackExprClass: { 4985 NotPrimaryExpr(); 4986 auto *SPE = cast<SizeOfPackExpr>(E); 4987 if (SPE->isPartiallySubstituted()) { 4988 Out << "sP"; 4989 for (const auto &A : SPE->getPartialArguments()) 4990 mangleTemplateArg(A, false); 4991 Out << "E"; 4992 break; 4993 } 4994 4995 Out << "sZ"; 4996 const NamedDecl *Pack = SPE->getPack(); 4997 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack)) 4998 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 4999 else if (const NonTypeTemplateParmDecl *NTTP 5000 = dyn_cast<NonTypeTemplateParmDecl>(Pack)) 5001 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex()); 5002 else if (const TemplateTemplateParmDecl *TempTP 5003 = dyn_cast<TemplateTemplateParmDecl>(Pack)) 5004 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex()); 5005 else 5006 mangleFunctionParam(cast<ParmVarDecl>(Pack)); 5007 break; 5008 } 5009 5010 case Expr::MaterializeTemporaryExprClass: 5011 E = cast<MaterializeTemporaryExpr>(E)->getSubExpr(); 5012 goto recurse; 5013 5014 case Expr::CXXFoldExprClass: { 5015 NotPrimaryExpr(); 5016 auto *FE = cast<CXXFoldExpr>(E); 5017 if (FE->isLeftFold()) 5018 Out << (FE->getInit() ? "fL" : "fl"); 5019 else 5020 Out << (FE->getInit() ? "fR" : "fr"); 5021 5022 if (FE->getOperator() == BO_PtrMemD) 5023 Out << "ds"; 5024 else 5025 mangleOperatorName( 5026 BinaryOperator::getOverloadedOperator(FE->getOperator()), 5027 /*Arity=*/2); 5028 5029 if (FE->getLHS()) 5030 mangleExpression(FE->getLHS()); 5031 if (FE->getRHS()) 5032 mangleExpression(FE->getRHS()); 5033 break; 5034 } 5035 5036 case Expr::CXXThisExprClass: 5037 NotPrimaryExpr(); 5038 Out << "fpT"; 5039 break; 5040 5041 case Expr::CoawaitExprClass: 5042 // FIXME: Propose a non-vendor mangling. 5043 NotPrimaryExpr(); 5044 Out << "v18co_await"; 5045 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 5046 break; 5047 5048 case Expr::DependentCoawaitExprClass: 5049 // FIXME: Propose a non-vendor mangling. 5050 NotPrimaryExpr(); 5051 Out << "v18co_await"; 5052 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand()); 5053 break; 5054 5055 case Expr::CoyieldExprClass: 5056 // FIXME: Propose a non-vendor mangling. 5057 NotPrimaryExpr(); 5058 Out << "v18co_yield"; 5059 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 5060 break; 5061 case Expr::SYCLUniqueStableNameExprClass: { 5062 const auto *USN = cast<SYCLUniqueStableNameExpr>(E); 5063 NotPrimaryExpr(); 5064 5065 Out << "u33__builtin_sycl_unique_stable_name"; 5066 mangleType(USN->getTypeSourceInfo()->getType()); 5067 5068 Out << "E"; 5069 break; 5070 } 5071 } 5072 5073 if (AsTemplateArg && !IsPrimaryExpr) 5074 Out << 'E'; 5075 } 5076 5077 /// Mangle an expression which refers to a parameter variable. 5078 /// 5079 /// <expression> ::= <function-param> 5080 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0 5081 /// <function-param> ::= fp <top-level CV-qualifiers> 5082 /// <parameter-2 non-negative number> _ # L == 0, I > 0 5083 /// <function-param> ::= fL <L-1 non-negative number> 5084 /// p <top-level CV-qualifiers> _ # L > 0, I == 0 5085 /// <function-param> ::= fL <L-1 non-negative number> 5086 /// p <top-level CV-qualifiers> 5087 /// <I-1 non-negative number> _ # L > 0, I > 0 5088 /// 5089 /// L is the nesting depth of the parameter, defined as 1 if the 5090 /// parameter comes from the innermost function prototype scope 5091 /// enclosing the current context, 2 if from the next enclosing 5092 /// function prototype scope, and so on, with one special case: if 5093 /// we've processed the full parameter clause for the innermost 5094 /// function type, then L is one less. This definition conveniently 5095 /// makes it irrelevant whether a function's result type was written 5096 /// trailing or leading, but is otherwise overly complicated; the 5097 /// numbering was first designed without considering references to 5098 /// parameter in locations other than return types, and then the 5099 /// mangling had to be generalized without changing the existing 5100 /// manglings. 5101 /// 5102 /// I is the zero-based index of the parameter within its parameter 5103 /// declaration clause. Note that the original ABI document describes 5104 /// this using 1-based ordinals. 5105 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) { 5106 unsigned parmDepth = parm->getFunctionScopeDepth(); 5107 unsigned parmIndex = parm->getFunctionScopeIndex(); 5108 5109 // Compute 'L'. 5110 // parmDepth does not include the declaring function prototype. 5111 // FunctionTypeDepth does account for that. 5112 assert(parmDepth < FunctionTypeDepth.getDepth()); 5113 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth; 5114 if (FunctionTypeDepth.isInResultType()) 5115 nestingDepth--; 5116 5117 if (nestingDepth == 0) { 5118 Out << "fp"; 5119 } else { 5120 Out << "fL" << (nestingDepth - 1) << 'p'; 5121 } 5122 5123 // Top-level qualifiers. We don't have to worry about arrays here, 5124 // because parameters declared as arrays should already have been 5125 // transformed to have pointer type. FIXME: apparently these don't 5126 // get mangled if used as an rvalue of a known non-class type? 5127 assert(!parm->getType()->isArrayType() 5128 && "parameter's type is still an array type?"); 5129 5130 if (const DependentAddressSpaceType *DAST = 5131 dyn_cast<DependentAddressSpaceType>(parm->getType())) { 5132 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST); 5133 } else { 5134 mangleQualifiers(parm->getType().getQualifiers()); 5135 } 5136 5137 // Parameter index. 5138 if (parmIndex != 0) { 5139 Out << (parmIndex - 1); 5140 } 5141 Out << '_'; 5142 } 5143 5144 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T, 5145 const CXXRecordDecl *InheritedFrom) { 5146 // <ctor-dtor-name> ::= C1 # complete object constructor 5147 // ::= C2 # base object constructor 5148 // ::= CI1 <type> # complete inheriting constructor 5149 // ::= CI2 <type> # base inheriting constructor 5150 // 5151 // In addition, C5 is a comdat name with C1 and C2 in it. 5152 Out << 'C'; 5153 if (InheritedFrom) 5154 Out << 'I'; 5155 switch (T) { 5156 case Ctor_Complete: 5157 Out << '1'; 5158 break; 5159 case Ctor_Base: 5160 Out << '2'; 5161 break; 5162 case Ctor_Comdat: 5163 Out << '5'; 5164 break; 5165 case Ctor_DefaultClosure: 5166 case Ctor_CopyingClosure: 5167 llvm_unreachable("closure constructors don't exist for the Itanium ABI!"); 5168 } 5169 if (InheritedFrom) 5170 mangleName(InheritedFrom); 5171 } 5172 5173 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 5174 // <ctor-dtor-name> ::= D0 # deleting destructor 5175 // ::= D1 # complete object destructor 5176 // ::= D2 # base object destructor 5177 // 5178 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it. 5179 switch (T) { 5180 case Dtor_Deleting: 5181 Out << "D0"; 5182 break; 5183 case Dtor_Complete: 5184 Out << "D1"; 5185 break; 5186 case Dtor_Base: 5187 Out << "D2"; 5188 break; 5189 case Dtor_Comdat: 5190 Out << "D5"; 5191 break; 5192 } 5193 } 5194 5195 namespace { 5196 // Helper to provide ancillary information on a template used to mangle its 5197 // arguments. 5198 struct TemplateArgManglingInfo { 5199 TemplateDecl *ResolvedTemplate = nullptr; 5200 bool SeenPackExpansionIntoNonPack = false; 5201 const NamedDecl *UnresolvedExpandedPack = nullptr; 5202 5203 TemplateArgManglingInfo(TemplateName TN) { 5204 if (TemplateDecl *TD = TN.getAsTemplateDecl()) 5205 ResolvedTemplate = TD; 5206 } 5207 5208 /// Do we need to mangle template arguments with exactly correct types? 5209 /// 5210 /// This should be called exactly once for each parameter / argument pair, in 5211 /// order. 5212 bool needExactType(unsigned ParamIdx, const TemplateArgument &Arg) { 5213 // We need correct types when the template-name is unresolved or when it 5214 // names a template that is able to be overloaded. 5215 if (!ResolvedTemplate || SeenPackExpansionIntoNonPack) 5216 return true; 5217 5218 // Move to the next parameter. 5219 const NamedDecl *Param = UnresolvedExpandedPack; 5220 if (!Param) { 5221 assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() && 5222 "no parameter for argument"); 5223 Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx); 5224 5225 // If we reach an expanded parameter pack whose argument isn't in pack 5226 // form, that means Sema couldn't figure out which arguments belonged to 5227 // it, because it contains a pack expansion. Track the expanded pack for 5228 // all further template arguments until we hit that pack expansion. 5229 if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) { 5230 assert(getExpandedPackSize(Param) && 5231 "failed to form pack argument for parameter pack"); 5232 UnresolvedExpandedPack = Param; 5233 } 5234 } 5235 5236 // If we encounter a pack argument that is expanded into a non-pack 5237 // parameter, we can no longer track parameter / argument correspondence, 5238 // and need to use exact types from this point onwards. 5239 if (Arg.isPackExpansion() && 5240 (!Param->isParameterPack() || UnresolvedExpandedPack)) { 5241 SeenPackExpansionIntoNonPack = true; 5242 return true; 5243 } 5244 5245 // We need exact types for function template arguments because they might be 5246 // overloaded on template parameter type. As a special case, a member 5247 // function template of a generic lambda is not overloadable. 5248 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ResolvedTemplate)) { 5249 auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext()); 5250 if (!RD || !RD->isGenericLambda()) 5251 return true; 5252 } 5253 5254 // Otherwise, we only need a correct type if the parameter has a deduced 5255 // type. 5256 // 5257 // Note: for an expanded parameter pack, getType() returns the type prior 5258 // to expansion. We could ask for the expanded type with getExpansionType(), 5259 // but it doesn't matter because substitution and expansion don't affect 5260 // whether a deduced type appears in the type. 5261 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param); 5262 return NTTP && NTTP->getType()->getContainedDeducedType(); 5263 } 5264 }; 5265 } 5266 5267 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 5268 const TemplateArgumentLoc *TemplateArgs, 5269 unsigned NumTemplateArgs) { 5270 // <template-args> ::= I <template-arg>+ E 5271 Out << 'I'; 5272 TemplateArgManglingInfo Info(TN); 5273 for (unsigned i = 0; i != NumTemplateArgs; ++i) 5274 mangleTemplateArg(TemplateArgs[i].getArgument(), 5275 Info.needExactType(i, TemplateArgs[i].getArgument())); 5276 Out << 'E'; 5277 } 5278 5279 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 5280 const TemplateArgumentList &AL) { 5281 // <template-args> ::= I <template-arg>+ E 5282 Out << 'I'; 5283 TemplateArgManglingInfo Info(TN); 5284 for (unsigned i = 0, e = AL.size(); i != e; ++i) 5285 mangleTemplateArg(AL[i], Info.needExactType(i, AL[i])); 5286 Out << 'E'; 5287 } 5288 5289 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 5290 const TemplateArgument *TemplateArgs, 5291 unsigned NumTemplateArgs) { 5292 // <template-args> ::= I <template-arg>+ E 5293 Out << 'I'; 5294 TemplateArgManglingInfo Info(TN); 5295 for (unsigned i = 0; i != NumTemplateArgs; ++i) 5296 mangleTemplateArg(TemplateArgs[i], Info.needExactType(i, TemplateArgs[i])); 5297 Out << 'E'; 5298 } 5299 5300 void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) { 5301 // <template-arg> ::= <type> # type or template 5302 // ::= X <expression> E # expression 5303 // ::= <expr-primary> # simple expressions 5304 // ::= J <template-arg>* E # argument pack 5305 if (!A.isInstantiationDependent() || A.isDependent()) 5306 A = Context.getASTContext().getCanonicalTemplateArgument(A); 5307 5308 switch (A.getKind()) { 5309 case TemplateArgument::Null: 5310 llvm_unreachable("Cannot mangle NULL template argument"); 5311 5312 case TemplateArgument::Type: 5313 mangleType(A.getAsType()); 5314 break; 5315 case TemplateArgument::Template: 5316 // This is mangled as <type>. 5317 mangleType(A.getAsTemplate()); 5318 break; 5319 case TemplateArgument::TemplateExpansion: 5320 // <type> ::= Dp <type> # pack expansion (C++0x) 5321 Out << "Dp"; 5322 mangleType(A.getAsTemplateOrTemplatePattern()); 5323 break; 5324 case TemplateArgument::Expression: 5325 mangleTemplateArgExpr(A.getAsExpr()); 5326 break; 5327 case TemplateArgument::Integral: 5328 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral()); 5329 break; 5330 case TemplateArgument::Declaration: { 5331 // <expr-primary> ::= L <mangled-name> E # external name 5332 ValueDecl *D = A.getAsDecl(); 5333 5334 // Template parameter objects are modeled by reproducing a source form 5335 // produced as if by aggregate initialization. 5336 if (A.getParamTypeForDecl()->isRecordType()) { 5337 auto *TPO = cast<TemplateParamObjectDecl>(D); 5338 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(), 5339 TPO->getValue(), /*TopLevel=*/true, 5340 NeedExactType); 5341 break; 5342 } 5343 5344 ASTContext &Ctx = Context.getASTContext(); 5345 APValue Value; 5346 if (D->isCXXInstanceMember()) 5347 // Simple pointer-to-member with no conversion. 5348 Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{}); 5349 else if (D->getType()->isArrayType() && 5350 Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()), 5351 A.getParamTypeForDecl()) && 5352 Ctx.getLangOpts().getClangABICompat() > 5353 LangOptions::ClangABI::Ver11) 5354 // Build a value corresponding to this implicit array-to-pointer decay. 5355 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(), 5356 {APValue::LValuePathEntry::ArrayIndex(0)}, 5357 /*OnePastTheEnd=*/false); 5358 else 5359 // Regular pointer or reference to a declaration. 5360 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(), 5361 ArrayRef<APValue::LValuePathEntry>(), 5362 /*OnePastTheEnd=*/false); 5363 mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true, 5364 NeedExactType); 5365 break; 5366 } 5367 case TemplateArgument::NullPtr: { 5368 mangleNullPointer(A.getNullPtrType()); 5369 break; 5370 } 5371 case TemplateArgument::Pack: { 5372 // <template-arg> ::= J <template-arg>* E 5373 Out << 'J'; 5374 for (const auto &P : A.pack_elements()) 5375 mangleTemplateArg(P, NeedExactType); 5376 Out << 'E'; 5377 } 5378 } 5379 } 5380 5381 void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) { 5382 ASTContext &Ctx = Context.getASTContext(); 5383 if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver11) { 5384 mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true); 5385 return; 5386 } 5387 5388 // Prior to Clang 12, we didn't omit the X .. E around <expr-primary> 5389 // correctly in cases where the template argument was 5390 // constructed from an expression rather than an already-evaluated 5391 // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of 5392 // 'Li0E'. 5393 // 5394 // We did special-case DeclRefExpr to attempt to DTRT for that one 5395 // expression-kind, but while doing so, unfortunately handled ParmVarDecl 5396 // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of 5397 // the proper 'Xfp_E'. 5398 E = E->IgnoreParenImpCasts(); 5399 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 5400 const ValueDecl *D = DRE->getDecl(); 5401 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) { 5402 Out << 'L'; 5403 mangle(D); 5404 Out << 'E'; 5405 return; 5406 } 5407 } 5408 Out << 'X'; 5409 mangleExpression(E); 5410 Out << 'E'; 5411 } 5412 5413 /// Determine whether a given value is equivalent to zero-initialization for 5414 /// the purpose of discarding a trailing portion of a 'tl' mangling. 5415 /// 5416 /// Note that this is not in general equivalent to determining whether the 5417 /// value has an all-zeroes bit pattern. 5418 static bool isZeroInitialized(QualType T, const APValue &V) { 5419 // FIXME: mangleValueInTemplateArg has quadratic time complexity in 5420 // pathological cases due to using this, but it's a little awkward 5421 // to do this in linear time in general. 5422 switch (V.getKind()) { 5423 case APValue::None: 5424 case APValue::Indeterminate: 5425 case APValue::AddrLabelDiff: 5426 return false; 5427 5428 case APValue::Struct: { 5429 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5430 assert(RD && "unexpected type for record value"); 5431 unsigned I = 0; 5432 for (const CXXBaseSpecifier &BS : RD->bases()) { 5433 if (!isZeroInitialized(BS.getType(), V.getStructBase(I))) 5434 return false; 5435 ++I; 5436 } 5437 I = 0; 5438 for (const FieldDecl *FD : RD->fields()) { 5439 if (!FD->isUnnamedBitfield() && 5440 !isZeroInitialized(FD->getType(), V.getStructField(I))) 5441 return false; 5442 ++I; 5443 } 5444 return true; 5445 } 5446 5447 case APValue::Union: { 5448 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5449 assert(RD && "unexpected type for union value"); 5450 // Zero-initialization zeroes the first non-unnamed-bitfield field, if any. 5451 for (const FieldDecl *FD : RD->fields()) { 5452 if (!FD->isUnnamedBitfield()) 5453 return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) && 5454 isZeroInitialized(FD->getType(), V.getUnionValue()); 5455 } 5456 // If there are no fields (other than unnamed bitfields), the value is 5457 // necessarily zero-initialized. 5458 return true; 5459 } 5460 5461 case APValue::Array: { 5462 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0); 5463 for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I) 5464 if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I))) 5465 return false; 5466 return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller()); 5467 } 5468 5469 case APValue::Vector: { 5470 const VectorType *VT = T->castAs<VectorType>(); 5471 for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I) 5472 if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I))) 5473 return false; 5474 return true; 5475 } 5476 5477 case APValue::Int: 5478 return !V.getInt(); 5479 5480 case APValue::Float: 5481 return V.getFloat().isPosZero(); 5482 5483 case APValue::FixedPoint: 5484 return !V.getFixedPoint().getValue(); 5485 5486 case APValue::ComplexFloat: 5487 return V.getComplexFloatReal().isPosZero() && 5488 V.getComplexFloatImag().isPosZero(); 5489 5490 case APValue::ComplexInt: 5491 return !V.getComplexIntReal() && !V.getComplexIntImag(); 5492 5493 case APValue::LValue: 5494 return V.isNullPointer(); 5495 5496 case APValue::MemberPointer: 5497 return !V.getMemberPointerDecl(); 5498 } 5499 5500 llvm_unreachable("Unhandled APValue::ValueKind enum"); 5501 } 5502 5503 static QualType getLValueType(ASTContext &Ctx, const APValue &LV) { 5504 QualType T = LV.getLValueBase().getType(); 5505 for (APValue::LValuePathEntry E : LV.getLValuePath()) { 5506 if (const ArrayType *AT = Ctx.getAsArrayType(T)) 5507 T = AT->getElementType(); 5508 else if (const FieldDecl *FD = 5509 dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer())) 5510 T = FD->getType(); 5511 else 5512 T = Ctx.getRecordType( 5513 cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer())); 5514 } 5515 return T; 5516 } 5517 5518 void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V, 5519 bool TopLevel, 5520 bool NeedExactType) { 5521 // Ignore all top-level cv-qualifiers, to match GCC. 5522 Qualifiers Quals; 5523 T = getASTContext().getUnqualifiedArrayType(T, Quals); 5524 5525 // A top-level expression that's not a primary expression is wrapped in X...E. 5526 bool IsPrimaryExpr = true; 5527 auto NotPrimaryExpr = [&] { 5528 if (TopLevel && IsPrimaryExpr) 5529 Out << 'X'; 5530 IsPrimaryExpr = false; 5531 }; 5532 5533 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63. 5534 switch (V.getKind()) { 5535 case APValue::None: 5536 case APValue::Indeterminate: 5537 Out << 'L'; 5538 mangleType(T); 5539 Out << 'E'; 5540 break; 5541 5542 case APValue::AddrLabelDiff: 5543 llvm_unreachable("unexpected value kind in template argument"); 5544 5545 case APValue::Struct: { 5546 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5547 assert(RD && "unexpected type for record value"); 5548 5549 // Drop trailing zero-initialized elements. 5550 llvm::SmallVector<const FieldDecl *, 16> Fields(RD->field_begin(), 5551 RD->field_end()); 5552 while ( 5553 !Fields.empty() && 5554 (Fields.back()->isUnnamedBitfield() || 5555 isZeroInitialized(Fields.back()->getType(), 5556 V.getStructField(Fields.back()->getFieldIndex())))) { 5557 Fields.pop_back(); 5558 } 5559 llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end()); 5560 if (Fields.empty()) { 5561 while (!Bases.empty() && 5562 isZeroInitialized(Bases.back().getType(), 5563 V.getStructBase(Bases.size() - 1))) 5564 Bases = Bases.drop_back(); 5565 } 5566 5567 // <expression> ::= tl <type> <braced-expression>* E 5568 NotPrimaryExpr(); 5569 Out << "tl"; 5570 mangleType(T); 5571 for (unsigned I = 0, N = Bases.size(); I != N; ++I) 5572 mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false); 5573 for (unsigned I = 0, N = Fields.size(); I != N; ++I) { 5574 if (Fields[I]->isUnnamedBitfield()) 5575 continue; 5576 mangleValueInTemplateArg(Fields[I]->getType(), 5577 V.getStructField(Fields[I]->getFieldIndex()), 5578 false); 5579 } 5580 Out << 'E'; 5581 break; 5582 } 5583 5584 case APValue::Union: { 5585 assert(T->getAsCXXRecordDecl() && "unexpected type for union value"); 5586 const FieldDecl *FD = V.getUnionField(); 5587 5588 if (!FD) { 5589 Out << 'L'; 5590 mangleType(T); 5591 Out << 'E'; 5592 break; 5593 } 5594 5595 // <braced-expression> ::= di <field source-name> <braced-expression> 5596 NotPrimaryExpr(); 5597 Out << "tl"; 5598 mangleType(T); 5599 if (!isZeroInitialized(T, V)) { 5600 Out << "di"; 5601 mangleSourceName(FD->getIdentifier()); 5602 mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false); 5603 } 5604 Out << 'E'; 5605 break; 5606 } 5607 5608 case APValue::Array: { 5609 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0); 5610 5611 NotPrimaryExpr(); 5612 Out << "tl"; 5613 mangleType(T); 5614 5615 // Drop trailing zero-initialized elements. 5616 unsigned N = V.getArraySize(); 5617 if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) { 5618 N = V.getArrayInitializedElts(); 5619 while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1))) 5620 --N; 5621 } 5622 5623 for (unsigned I = 0; I != N; ++I) { 5624 const APValue &Elem = I < V.getArrayInitializedElts() 5625 ? V.getArrayInitializedElt(I) 5626 : V.getArrayFiller(); 5627 mangleValueInTemplateArg(ElemT, Elem, false); 5628 } 5629 Out << 'E'; 5630 break; 5631 } 5632 5633 case APValue::Vector: { 5634 const VectorType *VT = T->castAs<VectorType>(); 5635 5636 NotPrimaryExpr(); 5637 Out << "tl"; 5638 mangleType(T); 5639 unsigned N = V.getVectorLength(); 5640 while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1))) 5641 --N; 5642 for (unsigned I = 0; I != N; ++I) 5643 mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false); 5644 Out << 'E'; 5645 break; 5646 } 5647 5648 case APValue::Int: 5649 mangleIntegerLiteral(T, V.getInt()); 5650 break; 5651 5652 case APValue::Float: 5653 mangleFloatLiteral(T, V.getFloat()); 5654 break; 5655 5656 case APValue::FixedPoint: 5657 mangleFixedPointLiteral(); 5658 break; 5659 5660 case APValue::ComplexFloat: { 5661 const ComplexType *CT = T->castAs<ComplexType>(); 5662 NotPrimaryExpr(); 5663 Out << "tl"; 5664 mangleType(T); 5665 if (!V.getComplexFloatReal().isPosZero() || 5666 !V.getComplexFloatImag().isPosZero()) 5667 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal()); 5668 if (!V.getComplexFloatImag().isPosZero()) 5669 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag()); 5670 Out << 'E'; 5671 break; 5672 } 5673 5674 case APValue::ComplexInt: { 5675 const ComplexType *CT = T->castAs<ComplexType>(); 5676 NotPrimaryExpr(); 5677 Out << "tl"; 5678 mangleType(T); 5679 if (V.getComplexIntReal().getBoolValue() || 5680 V.getComplexIntImag().getBoolValue()) 5681 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal()); 5682 if (V.getComplexIntImag().getBoolValue()) 5683 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag()); 5684 Out << 'E'; 5685 break; 5686 } 5687 5688 case APValue::LValue: { 5689 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47. 5690 assert((T->isPointerType() || T->isReferenceType()) && 5691 "unexpected type for LValue template arg"); 5692 5693 if (V.isNullPointer()) { 5694 mangleNullPointer(T); 5695 break; 5696 } 5697 5698 APValue::LValueBase B = V.getLValueBase(); 5699 if (!B) { 5700 // Non-standard mangling for integer cast to a pointer; this can only 5701 // occur as an extension. 5702 CharUnits Offset = V.getLValueOffset(); 5703 if (Offset.isZero()) { 5704 // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as 5705 // a cast, because L <type> 0 E means something else. 5706 NotPrimaryExpr(); 5707 Out << "rc"; 5708 mangleType(T); 5709 Out << "Li0E"; 5710 if (TopLevel) 5711 Out << 'E'; 5712 } else { 5713 Out << "L"; 5714 mangleType(T); 5715 Out << Offset.getQuantity() << 'E'; 5716 } 5717 break; 5718 } 5719 5720 ASTContext &Ctx = Context.getASTContext(); 5721 5722 enum { Base, Offset, Path } Kind; 5723 if (!V.hasLValuePath()) { 5724 // Mangle as (T*)((char*)&base + N). 5725 if (T->isReferenceType()) { 5726 NotPrimaryExpr(); 5727 Out << "decvP"; 5728 mangleType(T->getPointeeType()); 5729 } else { 5730 NotPrimaryExpr(); 5731 Out << "cv"; 5732 mangleType(T); 5733 } 5734 Out << "plcvPcad"; 5735 Kind = Offset; 5736 } else { 5737 if (!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) { 5738 NotPrimaryExpr(); 5739 // A final conversion to the template parameter's type is usually 5740 // folded into the 'so' mangling, but we can't do that for 'void*' 5741 // parameters without introducing collisions. 5742 if (NeedExactType && T->isVoidPointerType()) { 5743 Out << "cv"; 5744 mangleType(T); 5745 } 5746 if (T->isPointerType()) 5747 Out << "ad"; 5748 Out << "so"; 5749 mangleType(T->isVoidPointerType() 5750 ? getLValueType(Ctx, V).getUnqualifiedType() 5751 : T->getPointeeType()); 5752 Kind = Path; 5753 } else { 5754 if (NeedExactType && 5755 !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) && 5756 Ctx.getLangOpts().getClangABICompat() > 5757 LangOptions::ClangABI::Ver11) { 5758 NotPrimaryExpr(); 5759 Out << "cv"; 5760 mangleType(T); 5761 } 5762 if (T->isPointerType()) { 5763 NotPrimaryExpr(); 5764 Out << "ad"; 5765 } 5766 Kind = Base; 5767 } 5768 } 5769 5770 QualType TypeSoFar = B.getType(); 5771 if (auto *VD = B.dyn_cast<const ValueDecl*>()) { 5772 Out << 'L'; 5773 mangle(VD); 5774 Out << 'E'; 5775 } else if (auto *E = B.dyn_cast<const Expr*>()) { 5776 NotPrimaryExpr(); 5777 mangleExpression(E); 5778 } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) { 5779 NotPrimaryExpr(); 5780 Out << "ti"; 5781 mangleType(QualType(TI.getType(), 0)); 5782 } else { 5783 // We should never see dynamic allocations here. 5784 llvm_unreachable("unexpected lvalue base kind in template argument"); 5785 } 5786 5787 switch (Kind) { 5788 case Base: 5789 break; 5790 5791 case Offset: 5792 Out << 'L'; 5793 mangleType(Ctx.getPointerDiffType()); 5794 mangleNumber(V.getLValueOffset().getQuantity()); 5795 Out << 'E'; 5796 break; 5797 5798 case Path: 5799 // <expression> ::= so <referent type> <expr> [<offset number>] 5800 // <union-selector>* [p] E 5801 if (!V.getLValueOffset().isZero()) 5802 mangleNumber(V.getLValueOffset().getQuantity()); 5803 5804 // We model a past-the-end array pointer as array indexing with index N, 5805 // not with the "past the end" flag. Compensate for that. 5806 bool OnePastTheEnd = V.isLValueOnePastTheEnd(); 5807 5808 for (APValue::LValuePathEntry E : V.getLValuePath()) { 5809 if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) { 5810 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 5811 OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex(); 5812 TypeSoFar = AT->getElementType(); 5813 } else { 5814 const Decl *D = E.getAsBaseOrMember().getPointer(); 5815 if (auto *FD = dyn_cast<FieldDecl>(D)) { 5816 // <union-selector> ::= _ <number> 5817 if (FD->getParent()->isUnion()) { 5818 Out << '_'; 5819 if (FD->getFieldIndex()) 5820 Out << (FD->getFieldIndex() - 1); 5821 } 5822 TypeSoFar = FD->getType(); 5823 } else { 5824 TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D)); 5825 } 5826 } 5827 } 5828 5829 if (OnePastTheEnd) 5830 Out << 'p'; 5831 Out << 'E'; 5832 break; 5833 } 5834 5835 break; 5836 } 5837 5838 case APValue::MemberPointer: 5839 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47. 5840 if (!V.getMemberPointerDecl()) { 5841 mangleNullPointer(T); 5842 break; 5843 } 5844 5845 ASTContext &Ctx = Context.getASTContext(); 5846 5847 NotPrimaryExpr(); 5848 if (!V.getMemberPointerPath().empty()) { 5849 Out << "mc"; 5850 mangleType(T); 5851 } else if (NeedExactType && 5852 !Ctx.hasSameType( 5853 T->castAs<MemberPointerType>()->getPointeeType(), 5854 V.getMemberPointerDecl()->getType()) && 5855 Ctx.getLangOpts().getClangABICompat() > 5856 LangOptions::ClangABI::Ver11) { 5857 Out << "cv"; 5858 mangleType(T); 5859 } 5860 Out << "adL"; 5861 mangle(V.getMemberPointerDecl()); 5862 Out << 'E'; 5863 if (!V.getMemberPointerPath().empty()) { 5864 CharUnits Offset = 5865 Context.getASTContext().getMemberPointerPathAdjustment(V); 5866 if (!Offset.isZero()) 5867 mangleNumber(Offset.getQuantity()); 5868 Out << 'E'; 5869 } 5870 break; 5871 } 5872 5873 if (TopLevel && !IsPrimaryExpr) 5874 Out << 'E'; 5875 } 5876 5877 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) { 5878 // <template-param> ::= T_ # first template parameter 5879 // ::= T <parameter-2 non-negative number> _ 5880 // ::= TL <L-1 non-negative number> __ 5881 // ::= TL <L-1 non-negative number> _ 5882 // <parameter-2 non-negative number> _ 5883 // 5884 // The latter two manglings are from a proposal here: 5885 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117 5886 Out << 'T'; 5887 if (Depth != 0) 5888 Out << 'L' << (Depth - 1) << '_'; 5889 if (Index != 0) 5890 Out << (Index - 1); 5891 Out << '_'; 5892 } 5893 5894 void CXXNameMangler::mangleSeqID(unsigned SeqID) { 5895 if (SeqID == 1) 5896 Out << '0'; 5897 else if (SeqID > 1) { 5898 SeqID--; 5899 5900 // <seq-id> is encoded in base-36, using digits and upper case letters. 5901 char Buffer[7]; // log(2**32) / log(36) ~= 7 5902 MutableArrayRef<char> BufferRef(Buffer); 5903 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin(); 5904 5905 for (; SeqID != 0; SeqID /= 36) { 5906 unsigned C = SeqID % 36; 5907 *I++ = (C < 10 ? '0' + C : 'A' + C - 10); 5908 } 5909 5910 Out.write(I.base(), I - BufferRef.rbegin()); 5911 } 5912 Out << '_'; 5913 } 5914 5915 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) { 5916 bool result = mangleSubstitution(tname); 5917 assert(result && "no existing substitution for template name"); 5918 (void) result; 5919 } 5920 5921 // <substitution> ::= S <seq-id> _ 5922 // ::= S_ 5923 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) { 5924 // Try one of the standard substitutions first. 5925 if (mangleStandardSubstitution(ND)) 5926 return true; 5927 5928 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 5929 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND)); 5930 } 5931 5932 /// Determine whether the given type has any qualifiers that are relevant for 5933 /// substitutions. 5934 static bool hasMangledSubstitutionQualifiers(QualType T) { 5935 Qualifiers Qs = T.getQualifiers(); 5936 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned(); 5937 } 5938 5939 bool CXXNameMangler::mangleSubstitution(QualType T) { 5940 if (!hasMangledSubstitutionQualifiers(T)) { 5941 if (const RecordType *RT = T->getAs<RecordType>()) 5942 return mangleSubstitution(RT->getDecl()); 5943 } 5944 5945 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 5946 5947 return mangleSubstitution(TypePtr); 5948 } 5949 5950 bool CXXNameMangler::mangleSubstitution(TemplateName Template) { 5951 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 5952 return mangleSubstitution(TD); 5953 5954 Template = Context.getASTContext().getCanonicalTemplateName(Template); 5955 return mangleSubstitution( 5956 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 5957 } 5958 5959 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) { 5960 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr); 5961 if (I == Substitutions.end()) 5962 return false; 5963 5964 unsigned SeqID = I->second; 5965 Out << 'S'; 5966 mangleSeqID(SeqID); 5967 5968 return true; 5969 } 5970 5971 static bool isCharType(QualType T) { 5972 if (T.isNull()) 5973 return false; 5974 5975 return T->isSpecificBuiltinType(BuiltinType::Char_S) || 5976 T->isSpecificBuiltinType(BuiltinType::Char_U); 5977 } 5978 5979 /// Returns whether a given type is a template specialization of a given name 5980 /// with a single argument of type char. 5981 static bool isCharSpecialization(QualType T, const char *Name) { 5982 if (T.isNull()) 5983 return false; 5984 5985 const RecordType *RT = T->getAs<RecordType>(); 5986 if (!RT) 5987 return false; 5988 5989 const ClassTemplateSpecializationDecl *SD = 5990 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 5991 if (!SD) 5992 return false; 5993 5994 if (!isStdNamespace(getEffectiveDeclContext(SD))) 5995 return false; 5996 5997 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 5998 if (TemplateArgs.size() != 1) 5999 return false; 6000 6001 if (!isCharType(TemplateArgs[0].getAsType())) 6002 return false; 6003 6004 return SD->getIdentifier()->getName() == Name; 6005 } 6006 6007 template <std::size_t StrLen> 6008 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD, 6009 const char (&Str)[StrLen]) { 6010 if (!SD->getIdentifier()->isStr(Str)) 6011 return false; 6012 6013 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 6014 if (TemplateArgs.size() != 2) 6015 return false; 6016 6017 if (!isCharType(TemplateArgs[0].getAsType())) 6018 return false; 6019 6020 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 6021 return false; 6022 6023 return true; 6024 } 6025 6026 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) { 6027 // <substitution> ::= St # ::std:: 6028 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 6029 if (isStd(NS)) { 6030 Out << "St"; 6031 return true; 6032 } 6033 } 6034 6035 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) { 6036 if (!isStdNamespace(getEffectiveDeclContext(TD))) 6037 return false; 6038 6039 // <substitution> ::= Sa # ::std::allocator 6040 if (TD->getIdentifier()->isStr("allocator")) { 6041 Out << "Sa"; 6042 return true; 6043 } 6044 6045 // <<substitution> ::= Sb # ::std::basic_string 6046 if (TD->getIdentifier()->isStr("basic_string")) { 6047 Out << "Sb"; 6048 return true; 6049 } 6050 } 6051 6052 if (const ClassTemplateSpecializationDecl *SD = 6053 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 6054 if (!isStdNamespace(getEffectiveDeclContext(SD))) 6055 return false; 6056 6057 // <substitution> ::= Ss # ::std::basic_string<char, 6058 // ::std::char_traits<char>, 6059 // ::std::allocator<char> > 6060 if (SD->getIdentifier()->isStr("basic_string")) { 6061 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 6062 6063 if (TemplateArgs.size() != 3) 6064 return false; 6065 6066 if (!isCharType(TemplateArgs[0].getAsType())) 6067 return false; 6068 6069 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 6070 return false; 6071 6072 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator")) 6073 return false; 6074 6075 Out << "Ss"; 6076 return true; 6077 } 6078 6079 // <substitution> ::= Si # ::std::basic_istream<char, 6080 // ::std::char_traits<char> > 6081 if (isStreamCharSpecialization(SD, "basic_istream")) { 6082 Out << "Si"; 6083 return true; 6084 } 6085 6086 // <substitution> ::= So # ::std::basic_ostream<char, 6087 // ::std::char_traits<char> > 6088 if (isStreamCharSpecialization(SD, "basic_ostream")) { 6089 Out << "So"; 6090 return true; 6091 } 6092 6093 // <substitution> ::= Sd # ::std::basic_iostream<char, 6094 // ::std::char_traits<char> > 6095 if (isStreamCharSpecialization(SD, "basic_iostream")) { 6096 Out << "Sd"; 6097 return true; 6098 } 6099 } 6100 return false; 6101 } 6102 6103 void CXXNameMangler::addSubstitution(QualType T) { 6104 if (!hasMangledSubstitutionQualifiers(T)) { 6105 if (const RecordType *RT = T->getAs<RecordType>()) { 6106 addSubstitution(RT->getDecl()); 6107 return; 6108 } 6109 } 6110 6111 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 6112 addSubstitution(TypePtr); 6113 } 6114 6115 void CXXNameMangler::addSubstitution(TemplateName Template) { 6116 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 6117 return addSubstitution(TD); 6118 6119 Template = Context.getASTContext().getCanonicalTemplateName(Template); 6120 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 6121 } 6122 6123 void CXXNameMangler::addSubstitution(uintptr_t Ptr) { 6124 assert(!Substitutions.count(Ptr) && "Substitution already exists!"); 6125 Substitutions[Ptr] = SeqID++; 6126 } 6127 6128 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) { 6129 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!"); 6130 if (Other->SeqID > SeqID) { 6131 Substitutions.swap(Other->Substitutions); 6132 SeqID = Other->SeqID; 6133 } 6134 } 6135 6136 CXXNameMangler::AbiTagList 6137 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) { 6138 // When derived abi tags are disabled there is no need to make any list. 6139 if (DisableDerivedAbiTags) 6140 return AbiTagList(); 6141 6142 llvm::raw_null_ostream NullOutStream; 6143 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream); 6144 TrackReturnTypeTags.disableDerivedAbiTags(); 6145 6146 const FunctionProtoType *Proto = 6147 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>()); 6148 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push(); 6149 TrackReturnTypeTags.FunctionTypeDepth.enterResultType(); 6150 TrackReturnTypeTags.mangleType(Proto->getReturnType()); 6151 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType(); 6152 TrackReturnTypeTags.FunctionTypeDepth.pop(saved); 6153 6154 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 6155 } 6156 6157 CXXNameMangler::AbiTagList 6158 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) { 6159 // When derived abi tags are disabled there is no need to make any list. 6160 if (DisableDerivedAbiTags) 6161 return AbiTagList(); 6162 6163 llvm::raw_null_ostream NullOutStream; 6164 CXXNameMangler TrackVariableType(*this, NullOutStream); 6165 TrackVariableType.disableDerivedAbiTags(); 6166 6167 TrackVariableType.mangleType(VD->getType()); 6168 6169 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 6170 } 6171 6172 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C, 6173 const VarDecl *VD) { 6174 llvm::raw_null_ostream NullOutStream; 6175 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true); 6176 TrackAbiTags.mangle(VD); 6177 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size(); 6178 } 6179 6180 // 6181 6182 /// Mangles the name of the declaration D and emits that name to the given 6183 /// output stream. 6184 /// 6185 /// If the declaration D requires a mangled name, this routine will emit that 6186 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged 6187 /// and this routine will return false. In this case, the caller should just 6188 /// emit the identifier of the declaration (\c D->getIdentifier()) as its 6189 /// name. 6190 void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD, 6191 raw_ostream &Out) { 6192 const NamedDecl *D = cast<NamedDecl>(GD.getDecl()); 6193 assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) && 6194 "Invalid mangleName() call, argument is not a variable or function!"); 6195 6196 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 6197 getASTContext().getSourceManager(), 6198 "Mangling declaration"); 6199 6200 if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) { 6201 auto Type = GD.getCtorType(); 6202 CXXNameMangler Mangler(*this, Out, CD, Type); 6203 return Mangler.mangle(GlobalDecl(CD, Type)); 6204 } 6205 6206 if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) { 6207 auto Type = GD.getDtorType(); 6208 CXXNameMangler Mangler(*this, Out, DD, Type); 6209 return Mangler.mangle(GlobalDecl(DD, Type)); 6210 } 6211 6212 CXXNameMangler Mangler(*this, Out, D); 6213 Mangler.mangle(GD); 6214 } 6215 6216 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D, 6217 raw_ostream &Out) { 6218 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat); 6219 Mangler.mangle(GlobalDecl(D, Ctor_Comdat)); 6220 } 6221 6222 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D, 6223 raw_ostream &Out) { 6224 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat); 6225 Mangler.mangle(GlobalDecl(D, Dtor_Comdat)); 6226 } 6227 6228 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 6229 const ThunkInfo &Thunk, 6230 raw_ostream &Out) { 6231 // <special-name> ::= T <call-offset> <base encoding> 6232 // # base is the nominal target function of thunk 6233 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding> 6234 // # base is the nominal target function of thunk 6235 // # first call-offset is 'this' adjustment 6236 // # second call-offset is result adjustment 6237 6238 assert(!isa<CXXDestructorDecl>(MD) && 6239 "Use mangleCXXDtor for destructor decls!"); 6240 CXXNameMangler Mangler(*this, Out); 6241 Mangler.getStream() << "_ZT"; 6242 if (!Thunk.Return.isEmpty()) 6243 Mangler.getStream() << 'c'; 6244 6245 // Mangle the 'this' pointer adjustment. 6246 Mangler.mangleCallOffset(Thunk.This.NonVirtual, 6247 Thunk.This.Virtual.Itanium.VCallOffsetOffset); 6248 6249 // Mangle the return pointer adjustment if there is one. 6250 if (!Thunk.Return.isEmpty()) 6251 Mangler.mangleCallOffset(Thunk.Return.NonVirtual, 6252 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset); 6253 6254 Mangler.mangleFunctionEncoding(MD); 6255 } 6256 6257 void ItaniumMangleContextImpl::mangleCXXDtorThunk( 6258 const CXXDestructorDecl *DD, CXXDtorType Type, 6259 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) { 6260 // <special-name> ::= T <call-offset> <base encoding> 6261 // # base is the nominal target function of thunk 6262 CXXNameMangler Mangler(*this, Out, DD, Type); 6263 Mangler.getStream() << "_ZT"; 6264 6265 // Mangle the 'this' pointer adjustment. 6266 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 6267 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); 6268 6269 Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type)); 6270 } 6271 6272 /// Returns the mangled name for a guard variable for the passed in VarDecl. 6273 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D, 6274 raw_ostream &Out) { 6275 // <special-name> ::= GV <object name> # Guard variable for one-time 6276 // # initialization 6277 CXXNameMangler Mangler(*this, Out); 6278 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to 6279 // be a bug that is fixed in trunk. 6280 Mangler.getStream() << "_ZGV"; 6281 Mangler.mangleName(D); 6282 } 6283 6284 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD, 6285 raw_ostream &Out) { 6286 // These symbols are internal in the Itanium ABI, so the names don't matter. 6287 // Clang has traditionally used this symbol and allowed LLVM to adjust it to 6288 // avoid duplicate symbols. 6289 Out << "__cxx_global_var_init"; 6290 } 6291 6292 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 6293 raw_ostream &Out) { 6294 // Prefix the mangling of D with __dtor_. 6295 CXXNameMangler Mangler(*this, Out); 6296 Mangler.getStream() << "__dtor_"; 6297 if (shouldMangleDeclName(D)) 6298 Mangler.mangle(D); 6299 else 6300 Mangler.getStream() << D->getName(); 6301 } 6302 6303 void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D, 6304 raw_ostream &Out) { 6305 // Clang generates these internal-linkage functions as part of its 6306 // implementation of the XL ABI. 6307 CXXNameMangler Mangler(*this, Out); 6308 Mangler.getStream() << "__finalize_"; 6309 if (shouldMangleDeclName(D)) 6310 Mangler.mangle(D); 6311 else 6312 Mangler.getStream() << D->getName(); 6313 } 6314 6315 void ItaniumMangleContextImpl::mangleSEHFilterExpression( 6316 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 6317 CXXNameMangler Mangler(*this, Out); 6318 Mangler.getStream() << "__filt_"; 6319 if (shouldMangleDeclName(EnclosingDecl)) 6320 Mangler.mangle(EnclosingDecl); 6321 else 6322 Mangler.getStream() << EnclosingDecl->getName(); 6323 } 6324 6325 void ItaniumMangleContextImpl::mangleSEHFinallyBlock( 6326 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 6327 CXXNameMangler Mangler(*this, Out); 6328 Mangler.getStream() << "__fin_"; 6329 if (shouldMangleDeclName(EnclosingDecl)) 6330 Mangler.mangle(EnclosingDecl); 6331 else 6332 Mangler.getStream() << EnclosingDecl->getName(); 6333 } 6334 6335 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D, 6336 raw_ostream &Out) { 6337 // <special-name> ::= TH <object name> 6338 CXXNameMangler Mangler(*this, Out); 6339 Mangler.getStream() << "_ZTH"; 6340 Mangler.mangleName(D); 6341 } 6342 6343 void 6344 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D, 6345 raw_ostream &Out) { 6346 // <special-name> ::= TW <object name> 6347 CXXNameMangler Mangler(*this, Out); 6348 Mangler.getStream() << "_ZTW"; 6349 Mangler.mangleName(D); 6350 } 6351 6352 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D, 6353 unsigned ManglingNumber, 6354 raw_ostream &Out) { 6355 // We match the GCC mangling here. 6356 // <special-name> ::= GR <object name> 6357 CXXNameMangler Mangler(*this, Out); 6358 Mangler.getStream() << "_ZGR"; 6359 Mangler.mangleName(D); 6360 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!"); 6361 Mangler.mangleSeqID(ManglingNumber - 1); 6362 } 6363 6364 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD, 6365 raw_ostream &Out) { 6366 // <special-name> ::= TV <type> # virtual table 6367 CXXNameMangler Mangler(*this, Out); 6368 Mangler.getStream() << "_ZTV"; 6369 Mangler.mangleNameOrStandardSubstitution(RD); 6370 } 6371 6372 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD, 6373 raw_ostream &Out) { 6374 // <special-name> ::= TT <type> # VTT structure 6375 CXXNameMangler Mangler(*this, Out); 6376 Mangler.getStream() << "_ZTT"; 6377 Mangler.mangleNameOrStandardSubstitution(RD); 6378 } 6379 6380 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD, 6381 int64_t Offset, 6382 const CXXRecordDecl *Type, 6383 raw_ostream &Out) { 6384 // <special-name> ::= TC <type> <offset number> _ <base type> 6385 CXXNameMangler Mangler(*this, Out); 6386 Mangler.getStream() << "_ZTC"; 6387 Mangler.mangleNameOrStandardSubstitution(RD); 6388 Mangler.getStream() << Offset; 6389 Mangler.getStream() << '_'; 6390 Mangler.mangleNameOrStandardSubstitution(Type); 6391 } 6392 6393 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) { 6394 // <special-name> ::= TI <type> # typeinfo structure 6395 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers"); 6396 CXXNameMangler Mangler(*this, Out); 6397 Mangler.getStream() << "_ZTI"; 6398 Mangler.mangleType(Ty); 6399 } 6400 6401 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty, 6402 raw_ostream &Out) { 6403 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string) 6404 CXXNameMangler Mangler(*this, Out); 6405 Mangler.getStream() << "_ZTS"; 6406 Mangler.mangleType(Ty); 6407 } 6408 6409 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) { 6410 mangleCXXRTTIName(Ty, Out); 6411 } 6412 6413 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) { 6414 llvm_unreachable("Can't mangle string literals"); 6415 } 6416 6417 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda, 6418 raw_ostream &Out) { 6419 CXXNameMangler Mangler(*this, Out); 6420 Mangler.mangleLambdaSig(Lambda); 6421 } 6422 6423 ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context, 6424 DiagnosticsEngine &Diags) { 6425 return new ItaniumMangleContextImpl( 6426 Context, Diags, 6427 [](ASTContext &, const NamedDecl *) -> llvm::Optional<unsigned> { 6428 return llvm::None; 6429 }); 6430 } 6431 6432 ItaniumMangleContext * 6433 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags, 6434 DiscriminatorOverrideTy DiscriminatorOverride) { 6435 return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride); 6436 } 6437