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