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