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