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