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::NullPtr: 2768 Out << "Dn"; 2769 break; 2770 2771 #define BUILTIN_TYPE(Id, SingletonId) 2772 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 2773 case BuiltinType::Id: 2774 #include "clang/AST/BuiltinTypes.def" 2775 case BuiltinType::Dependent: 2776 if (!NullOut) 2777 llvm_unreachable("mangling a placeholder type"); 2778 break; 2779 case BuiltinType::ObjCId: 2780 Out << "11objc_object"; 2781 break; 2782 case BuiltinType::ObjCClass: 2783 Out << "10objc_class"; 2784 break; 2785 case BuiltinType::ObjCSel: 2786 Out << "13objc_selector"; 2787 break; 2788 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2789 case BuiltinType::Id: \ 2790 type_name = "ocl_" #ImgType "_" #Suffix; \ 2791 Out << type_name.size() << type_name; \ 2792 break; 2793 #include "clang/Basic/OpenCLImageTypes.def" 2794 case BuiltinType::OCLSampler: 2795 Out << "11ocl_sampler"; 2796 break; 2797 case BuiltinType::OCLEvent: 2798 Out << "9ocl_event"; 2799 break; 2800 case BuiltinType::OCLClkEvent: 2801 Out << "12ocl_clkevent"; 2802 break; 2803 case BuiltinType::OCLQueue: 2804 Out << "9ocl_queue"; 2805 break; 2806 case BuiltinType::OCLReserveID: 2807 Out << "13ocl_reserveid"; 2808 break; 2809 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2810 case BuiltinType::Id: \ 2811 type_name = "ocl_" #ExtType; \ 2812 Out << type_name.size() << type_name; \ 2813 break; 2814 #include "clang/Basic/OpenCLExtensionTypes.def" 2815 // The SVE types are effectively target-specific. The mangling scheme 2816 // is defined in the appendices to the Procedure Call Standard for the 2817 // Arm Architecture. 2818 #define SVE_TYPE(Name, Id, SingletonId) \ 2819 case BuiltinType::Id: \ 2820 type_name = Name; \ 2821 Out << 'u' << type_name.size() << type_name; \ 2822 break; 2823 #include "clang/Basic/AArch64SVEACLETypes.def" 2824 } 2825 } 2826 2827 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) { 2828 switch (CC) { 2829 case CC_C: 2830 return ""; 2831 2832 case CC_X86VectorCall: 2833 case CC_X86Pascal: 2834 case CC_X86RegCall: 2835 case CC_AAPCS: 2836 case CC_AAPCS_VFP: 2837 case CC_AArch64VectorCall: 2838 case CC_IntelOclBicc: 2839 case CC_SpirFunction: 2840 case CC_OpenCLKernel: 2841 case CC_PreserveMost: 2842 case CC_PreserveAll: 2843 // FIXME: we should be mangling all of the above. 2844 return ""; 2845 2846 case CC_X86ThisCall: 2847 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is 2848 // used explicitly. At this point, we don't have that much information in 2849 // the AST, since clang tends to bake the convention into the canonical 2850 // function type. thiscall only rarely used explicitly, so don't mangle it 2851 // for now. 2852 return ""; 2853 2854 case CC_X86StdCall: 2855 return "stdcall"; 2856 case CC_X86FastCall: 2857 return "fastcall"; 2858 case CC_X86_64SysV: 2859 return "sysv_abi"; 2860 case CC_Win64: 2861 return "ms_abi"; 2862 case CC_Swift: 2863 return "swiftcall"; 2864 } 2865 llvm_unreachable("bad calling convention"); 2866 } 2867 2868 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) { 2869 // Fast path. 2870 if (T->getExtInfo() == FunctionType::ExtInfo()) 2871 return; 2872 2873 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 2874 // This will get more complicated in the future if we mangle other 2875 // things here; but for now, since we mangle ns_returns_retained as 2876 // a qualifier on the result type, we can get away with this: 2877 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC()); 2878 if (!CCQualifier.empty()) 2879 mangleVendorQualifier(CCQualifier); 2880 2881 // FIXME: regparm 2882 // FIXME: noreturn 2883 } 2884 2885 void 2886 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) { 2887 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 2888 2889 // Note that these are *not* substitution candidates. Demanglers might 2890 // have trouble with this if the parameter type is fully substituted. 2891 2892 switch (PI.getABI()) { 2893 case ParameterABI::Ordinary: 2894 break; 2895 2896 // All of these start with "swift", so they come before "ns_consumed". 2897 case ParameterABI::SwiftContext: 2898 case ParameterABI::SwiftErrorResult: 2899 case ParameterABI::SwiftIndirectResult: 2900 mangleVendorQualifier(getParameterABISpelling(PI.getABI())); 2901 break; 2902 } 2903 2904 if (PI.isConsumed()) 2905 mangleVendorQualifier("ns_consumed"); 2906 2907 if (PI.isNoEscape()) 2908 mangleVendorQualifier("noescape"); 2909 } 2910 2911 // <type> ::= <function-type> 2912 // <function-type> ::= [<CV-qualifiers>] F [Y] 2913 // <bare-function-type> [<ref-qualifier>] E 2914 void CXXNameMangler::mangleType(const FunctionProtoType *T) { 2915 mangleExtFunctionInfo(T); 2916 2917 // Mangle CV-qualifiers, if present. These are 'this' qualifiers, 2918 // e.g. "const" in "int (A::*)() const". 2919 mangleQualifiers(T->getMethodQuals()); 2920 2921 // Mangle instantiation-dependent exception-specification, if present, 2922 // per cxx-abi-dev proposal on 2016-10-11. 2923 if (T->hasInstantiationDependentExceptionSpec()) { 2924 if (isComputedNoexcept(T->getExceptionSpecType())) { 2925 Out << "DO"; 2926 mangleExpression(T->getNoexceptExpr()); 2927 Out << "E"; 2928 } else { 2929 assert(T->getExceptionSpecType() == EST_Dynamic); 2930 Out << "Dw"; 2931 for (auto ExceptTy : T->exceptions()) 2932 mangleType(ExceptTy); 2933 Out << "E"; 2934 } 2935 } else if (T->isNothrow()) { 2936 Out << "Do"; 2937 } 2938 2939 Out << 'F'; 2940 2941 // FIXME: We don't have enough information in the AST to produce the 'Y' 2942 // encoding for extern "C" function types. 2943 mangleBareFunctionType(T, /*MangleReturnType=*/true); 2944 2945 // Mangle the ref-qualifier, if present. 2946 mangleRefQualifier(T->getRefQualifier()); 2947 2948 Out << 'E'; 2949 } 2950 2951 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) { 2952 // Function types without prototypes can arise when mangling a function type 2953 // within an overloadable function in C. We mangle these as the absence of any 2954 // parameter types (not even an empty parameter list). 2955 Out << 'F'; 2956 2957 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 2958 2959 FunctionTypeDepth.enterResultType(); 2960 mangleType(T->getReturnType()); 2961 FunctionTypeDepth.leaveResultType(); 2962 2963 FunctionTypeDepth.pop(saved); 2964 Out << 'E'; 2965 } 2966 2967 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto, 2968 bool MangleReturnType, 2969 const FunctionDecl *FD) { 2970 // Record that we're in a function type. See mangleFunctionParam 2971 // for details on what we're trying to achieve here. 2972 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 2973 2974 // <bare-function-type> ::= <signature type>+ 2975 if (MangleReturnType) { 2976 FunctionTypeDepth.enterResultType(); 2977 2978 // Mangle ns_returns_retained as an order-sensitive qualifier here. 2979 if (Proto->getExtInfo().getProducesResult() && FD == nullptr) 2980 mangleVendorQualifier("ns_returns_retained"); 2981 2982 // Mangle the return type without any direct ARC ownership qualifiers. 2983 QualType ReturnTy = Proto->getReturnType(); 2984 if (ReturnTy.getObjCLifetime()) { 2985 auto SplitReturnTy = ReturnTy.split(); 2986 SplitReturnTy.Quals.removeObjCLifetime(); 2987 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy); 2988 } 2989 mangleType(ReturnTy); 2990 2991 FunctionTypeDepth.leaveResultType(); 2992 } 2993 2994 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) { 2995 // <builtin-type> ::= v # void 2996 Out << 'v'; 2997 2998 FunctionTypeDepth.pop(saved); 2999 return; 3000 } 3001 3002 assert(!FD || FD->getNumParams() == Proto->getNumParams()); 3003 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) { 3004 // Mangle extended parameter info as order-sensitive qualifiers here. 3005 if (Proto->hasExtParameterInfos() && FD == nullptr) { 3006 mangleExtParameterInfo(Proto->getExtParameterInfo(I)); 3007 } 3008 3009 // Mangle the type. 3010 QualType ParamTy = Proto->getParamType(I); 3011 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy)); 3012 3013 if (FD) { 3014 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) { 3015 // Attr can only take 1 character, so we can hardcode the length below. 3016 assert(Attr->getType() <= 9 && Attr->getType() >= 0); 3017 if (Attr->isDynamic()) 3018 Out << "U25pass_dynamic_object_size" << Attr->getType(); 3019 else 3020 Out << "U17pass_object_size" << Attr->getType(); 3021 } 3022 } 3023 } 3024 3025 FunctionTypeDepth.pop(saved); 3026 3027 // <builtin-type> ::= z # ellipsis 3028 if (Proto->isVariadic()) 3029 Out << 'z'; 3030 } 3031 3032 // <type> ::= <class-enum-type> 3033 // <class-enum-type> ::= <name> 3034 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) { 3035 mangleName(T->getDecl()); 3036 } 3037 3038 // <type> ::= <class-enum-type> 3039 // <class-enum-type> ::= <name> 3040 void CXXNameMangler::mangleType(const EnumType *T) { 3041 mangleType(static_cast<const TagType*>(T)); 3042 } 3043 void CXXNameMangler::mangleType(const RecordType *T) { 3044 mangleType(static_cast<const TagType*>(T)); 3045 } 3046 void CXXNameMangler::mangleType(const TagType *T) { 3047 mangleName(T->getDecl()); 3048 } 3049 3050 // <type> ::= <array-type> 3051 // <array-type> ::= A <positive dimension number> _ <element type> 3052 // ::= A [<dimension expression>] _ <element type> 3053 void CXXNameMangler::mangleType(const ConstantArrayType *T) { 3054 Out << 'A' << T->getSize() << '_'; 3055 mangleType(T->getElementType()); 3056 } 3057 void CXXNameMangler::mangleType(const VariableArrayType *T) { 3058 Out << 'A'; 3059 // decayed vla types (size 0) will just be skipped. 3060 if (T->getSizeExpr()) 3061 mangleExpression(T->getSizeExpr()); 3062 Out << '_'; 3063 mangleType(T->getElementType()); 3064 } 3065 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) { 3066 Out << 'A'; 3067 mangleExpression(T->getSizeExpr()); 3068 Out << '_'; 3069 mangleType(T->getElementType()); 3070 } 3071 void CXXNameMangler::mangleType(const IncompleteArrayType *T) { 3072 Out << "A_"; 3073 mangleType(T->getElementType()); 3074 } 3075 3076 // <type> ::= <pointer-to-member-type> 3077 // <pointer-to-member-type> ::= M <class type> <member type> 3078 void CXXNameMangler::mangleType(const MemberPointerType *T) { 3079 Out << 'M'; 3080 mangleType(QualType(T->getClass(), 0)); 3081 QualType PointeeType = T->getPointeeType(); 3082 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) { 3083 mangleType(FPT); 3084 3085 // Itanium C++ ABI 5.1.8: 3086 // 3087 // The type of a non-static member function is considered to be different, 3088 // for the purposes of substitution, from the type of a namespace-scope or 3089 // static member function whose type appears similar. The types of two 3090 // non-static member functions are considered to be different, for the 3091 // purposes of substitution, if the functions are members of different 3092 // classes. In other words, for the purposes of substitution, the class of 3093 // which the function is a member is considered part of the type of 3094 // function. 3095 3096 // Given that we already substitute member function pointers as a 3097 // whole, the net effect of this rule is just to unconditionally 3098 // suppress substitution on the function type in a member pointer. 3099 // We increment the SeqID here to emulate adding an entry to the 3100 // substitution table. 3101 ++SeqID; 3102 } else 3103 mangleType(PointeeType); 3104 } 3105 3106 // <type> ::= <template-param> 3107 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) { 3108 mangleTemplateParameter(T->getDepth(), T->getIndex()); 3109 } 3110 3111 // <type> ::= <template-param> 3112 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) { 3113 // FIXME: not clear how to mangle this! 3114 // template <class T...> class A { 3115 // template <class U...> void foo(T(*)(U) x...); 3116 // }; 3117 Out << "_SUBSTPACK_"; 3118 } 3119 3120 // <type> ::= P <type> # pointer-to 3121 void CXXNameMangler::mangleType(const PointerType *T) { 3122 Out << 'P'; 3123 mangleType(T->getPointeeType()); 3124 } 3125 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) { 3126 Out << 'P'; 3127 mangleType(T->getPointeeType()); 3128 } 3129 3130 // <type> ::= R <type> # reference-to 3131 void CXXNameMangler::mangleType(const LValueReferenceType *T) { 3132 Out << 'R'; 3133 mangleType(T->getPointeeType()); 3134 } 3135 3136 // <type> ::= O <type> # rvalue reference-to (C++0x) 3137 void CXXNameMangler::mangleType(const RValueReferenceType *T) { 3138 Out << 'O'; 3139 mangleType(T->getPointeeType()); 3140 } 3141 3142 // <type> ::= C <type> # complex pair (C 2000) 3143 void CXXNameMangler::mangleType(const ComplexType *T) { 3144 Out << 'C'; 3145 mangleType(T->getElementType()); 3146 } 3147 3148 // ARM's ABI for Neon vector types specifies that they should be mangled as 3149 // if they are structs (to match ARM's initial implementation). The 3150 // vector type must be one of the special types predefined by ARM. 3151 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) { 3152 QualType EltType = T->getElementType(); 3153 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3154 const char *EltName = nullptr; 3155 if (T->getVectorKind() == VectorType::NeonPolyVector) { 3156 switch (cast<BuiltinType>(EltType)->getKind()) { 3157 case BuiltinType::SChar: 3158 case BuiltinType::UChar: 3159 EltName = "poly8_t"; 3160 break; 3161 case BuiltinType::Short: 3162 case BuiltinType::UShort: 3163 EltName = "poly16_t"; 3164 break; 3165 case BuiltinType::ULongLong: 3166 EltName = "poly64_t"; 3167 break; 3168 default: llvm_unreachable("unexpected Neon polynomial vector element type"); 3169 } 3170 } else { 3171 switch (cast<BuiltinType>(EltType)->getKind()) { 3172 case BuiltinType::SChar: EltName = "int8_t"; break; 3173 case BuiltinType::UChar: EltName = "uint8_t"; break; 3174 case BuiltinType::Short: EltName = "int16_t"; break; 3175 case BuiltinType::UShort: EltName = "uint16_t"; break; 3176 case BuiltinType::Int: EltName = "int32_t"; break; 3177 case BuiltinType::UInt: EltName = "uint32_t"; break; 3178 case BuiltinType::LongLong: EltName = "int64_t"; break; 3179 case BuiltinType::ULongLong: EltName = "uint64_t"; break; 3180 case BuiltinType::Double: EltName = "float64_t"; break; 3181 case BuiltinType::Float: EltName = "float32_t"; break; 3182 case BuiltinType::Half: EltName = "float16_t";break; 3183 default: 3184 llvm_unreachable("unexpected Neon vector element type"); 3185 } 3186 } 3187 const char *BaseName = nullptr; 3188 unsigned BitSize = (T->getNumElements() * 3189 getASTContext().getTypeSize(EltType)); 3190 if (BitSize == 64) 3191 BaseName = "__simd64_"; 3192 else { 3193 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits"); 3194 BaseName = "__simd128_"; 3195 } 3196 Out << strlen(BaseName) + strlen(EltName); 3197 Out << BaseName << EltName; 3198 } 3199 3200 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) { 3201 DiagnosticsEngine &Diags = Context.getDiags(); 3202 unsigned DiagID = Diags.getCustomDiagID( 3203 DiagnosticsEngine::Error, 3204 "cannot mangle this dependent neon vector type yet"); 3205 Diags.Report(T->getAttributeLoc(), DiagID); 3206 } 3207 3208 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) { 3209 switch (EltType->getKind()) { 3210 case BuiltinType::SChar: 3211 return "Int8"; 3212 case BuiltinType::Short: 3213 return "Int16"; 3214 case BuiltinType::Int: 3215 return "Int32"; 3216 case BuiltinType::Long: 3217 case BuiltinType::LongLong: 3218 return "Int64"; 3219 case BuiltinType::UChar: 3220 return "Uint8"; 3221 case BuiltinType::UShort: 3222 return "Uint16"; 3223 case BuiltinType::UInt: 3224 return "Uint32"; 3225 case BuiltinType::ULong: 3226 case BuiltinType::ULongLong: 3227 return "Uint64"; 3228 case BuiltinType::Half: 3229 return "Float16"; 3230 case BuiltinType::Float: 3231 return "Float32"; 3232 case BuiltinType::Double: 3233 return "Float64"; 3234 default: 3235 llvm_unreachable("Unexpected vector element base type"); 3236 } 3237 } 3238 3239 // AArch64's ABI for Neon vector types specifies that they should be mangled as 3240 // the equivalent internal name. The vector type must be one of the special 3241 // types predefined by ARM. 3242 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) { 3243 QualType EltType = T->getElementType(); 3244 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3245 unsigned BitSize = 3246 (T->getNumElements() * getASTContext().getTypeSize(EltType)); 3247 (void)BitSize; // Silence warning. 3248 3249 assert((BitSize == 64 || BitSize == 128) && 3250 "Neon vector type not 64 or 128 bits"); 3251 3252 StringRef EltName; 3253 if (T->getVectorKind() == VectorType::NeonPolyVector) { 3254 switch (cast<BuiltinType>(EltType)->getKind()) { 3255 case BuiltinType::UChar: 3256 EltName = "Poly8"; 3257 break; 3258 case BuiltinType::UShort: 3259 EltName = "Poly16"; 3260 break; 3261 case BuiltinType::ULong: 3262 case BuiltinType::ULongLong: 3263 EltName = "Poly64"; 3264 break; 3265 default: 3266 llvm_unreachable("unexpected Neon polynomial vector element type"); 3267 } 3268 } else 3269 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType)); 3270 3271 std::string TypeName = 3272 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str(); 3273 Out << TypeName.length() << TypeName; 3274 } 3275 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) { 3276 DiagnosticsEngine &Diags = Context.getDiags(); 3277 unsigned DiagID = Diags.getCustomDiagID( 3278 DiagnosticsEngine::Error, 3279 "cannot mangle this dependent neon vector type yet"); 3280 Diags.Report(T->getAttributeLoc(), DiagID); 3281 } 3282 3283 // GNU extension: vector types 3284 // <type> ::= <vector-type> 3285 // <vector-type> ::= Dv <positive dimension number> _ 3286 // <extended element type> 3287 // ::= Dv [<dimension expression>] _ <element type> 3288 // <extended element type> ::= <element type> 3289 // ::= p # AltiVec vector pixel 3290 // ::= b # Altivec vector bool 3291 void CXXNameMangler::mangleType(const VectorType *T) { 3292 if ((T->getVectorKind() == VectorType::NeonVector || 3293 T->getVectorKind() == VectorType::NeonPolyVector)) { 3294 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 3295 llvm::Triple::ArchType Arch = 3296 getASTContext().getTargetInfo().getTriple().getArch(); 3297 if ((Arch == llvm::Triple::aarch64 || 3298 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin()) 3299 mangleAArch64NeonVectorType(T); 3300 else 3301 mangleNeonVectorType(T); 3302 return; 3303 } 3304 Out << "Dv" << T->getNumElements() << '_'; 3305 if (T->getVectorKind() == VectorType::AltiVecPixel) 3306 Out << 'p'; 3307 else if (T->getVectorKind() == VectorType::AltiVecBool) 3308 Out << 'b'; 3309 else 3310 mangleType(T->getElementType()); 3311 } 3312 3313 void CXXNameMangler::mangleType(const DependentVectorType *T) { 3314 if ((T->getVectorKind() == VectorType::NeonVector || 3315 T->getVectorKind() == VectorType::NeonPolyVector)) { 3316 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 3317 llvm::Triple::ArchType Arch = 3318 getASTContext().getTargetInfo().getTriple().getArch(); 3319 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) && 3320 !Target.isOSDarwin()) 3321 mangleAArch64NeonVectorType(T); 3322 else 3323 mangleNeonVectorType(T); 3324 return; 3325 } 3326 3327 Out << "Dv"; 3328 mangleExpression(T->getSizeExpr()); 3329 Out << '_'; 3330 if (T->getVectorKind() == VectorType::AltiVecPixel) 3331 Out << 'p'; 3332 else if (T->getVectorKind() == VectorType::AltiVecBool) 3333 Out << 'b'; 3334 else 3335 mangleType(T->getElementType()); 3336 } 3337 3338 void CXXNameMangler::mangleType(const ExtVectorType *T) { 3339 mangleType(static_cast<const VectorType*>(T)); 3340 } 3341 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) { 3342 Out << "Dv"; 3343 mangleExpression(T->getSizeExpr()); 3344 Out << '_'; 3345 mangleType(T->getElementType()); 3346 } 3347 3348 void CXXNameMangler::mangleType(const ConstantMatrixType *T) { 3349 // Mangle matrix types using a vendor extended type qualifier: 3350 // U<Len>matrix_type<Rows><Columns><element type> 3351 StringRef VendorQualifier = "matrix_type"; 3352 Out << "U" << VendorQualifier.size() << VendorQualifier; 3353 auto &ASTCtx = getASTContext(); 3354 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType()); 3355 llvm::APSInt Rows(BitWidth); 3356 Rows = T->getNumRows(); 3357 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows); 3358 llvm::APSInt Columns(BitWidth); 3359 Columns = T->getNumColumns(); 3360 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns); 3361 mangleType(T->getElementType()); 3362 } 3363 3364 void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) { 3365 // U<Len>matrix_type<row expr><column expr><element type> 3366 StringRef VendorQualifier = "matrix_type"; 3367 Out << "U" << VendorQualifier.size() << VendorQualifier; 3368 mangleTemplateArg(T->getRowExpr()); 3369 mangleTemplateArg(T->getColumnExpr()); 3370 mangleType(T->getElementType()); 3371 } 3372 3373 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) { 3374 SplitQualType split = T->getPointeeType().split(); 3375 mangleQualifiers(split.Quals, T); 3376 mangleType(QualType(split.Ty, 0)); 3377 } 3378 3379 void CXXNameMangler::mangleType(const PackExpansionType *T) { 3380 // <type> ::= Dp <type> # pack expansion (C++0x) 3381 Out << "Dp"; 3382 mangleType(T->getPattern()); 3383 } 3384 3385 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) { 3386 mangleSourceName(T->getDecl()->getIdentifier()); 3387 } 3388 3389 void CXXNameMangler::mangleType(const ObjCObjectType *T) { 3390 // Treat __kindof as a vendor extended type qualifier. 3391 if (T->isKindOfType()) 3392 Out << "U8__kindof"; 3393 3394 if (!T->qual_empty()) { 3395 // Mangle protocol qualifiers. 3396 SmallString<64> QualStr; 3397 llvm::raw_svector_ostream QualOS(QualStr); 3398 QualOS << "objcproto"; 3399 for (const auto *I : T->quals()) { 3400 StringRef name = I->getName(); 3401 QualOS << name.size() << name; 3402 } 3403 Out << 'U' << QualStr.size() << QualStr; 3404 } 3405 3406 mangleType(T->getBaseType()); 3407 3408 if (T->isSpecialized()) { 3409 // Mangle type arguments as I <type>+ E 3410 Out << 'I'; 3411 for (auto typeArg : T->getTypeArgs()) 3412 mangleType(typeArg); 3413 Out << 'E'; 3414 } 3415 } 3416 3417 void CXXNameMangler::mangleType(const BlockPointerType *T) { 3418 Out << "U13block_pointer"; 3419 mangleType(T->getPointeeType()); 3420 } 3421 3422 void CXXNameMangler::mangleType(const InjectedClassNameType *T) { 3423 // Mangle injected class name types as if the user had written the 3424 // specialization out fully. It may not actually be possible to see 3425 // this mangling, though. 3426 mangleType(T->getInjectedSpecializationType()); 3427 } 3428 3429 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) { 3430 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) { 3431 mangleTemplateName(TD, T->getArgs(), T->getNumArgs()); 3432 } else { 3433 if (mangleSubstitution(QualType(T, 0))) 3434 return; 3435 3436 mangleTemplatePrefix(T->getTemplateName()); 3437 3438 // FIXME: GCC does not appear to mangle the template arguments when 3439 // the template in question is a dependent template name. Should we 3440 // emulate that badness? 3441 mangleTemplateArgs(T->getArgs(), T->getNumArgs()); 3442 addSubstitution(QualType(T, 0)); 3443 } 3444 } 3445 3446 void CXXNameMangler::mangleType(const DependentNameType *T) { 3447 // Proposal by cxx-abi-dev, 2014-03-26 3448 // <class-enum-type> ::= <name> # non-dependent or dependent type name or 3449 // # dependent elaborated type specifier using 3450 // # 'typename' 3451 // ::= Ts <name> # dependent elaborated type specifier using 3452 // # 'struct' or 'class' 3453 // ::= Tu <name> # dependent elaborated type specifier using 3454 // # 'union' 3455 // ::= Te <name> # dependent elaborated type specifier using 3456 // # 'enum' 3457 switch (T->getKeyword()) { 3458 case ETK_None: 3459 case ETK_Typename: 3460 break; 3461 case ETK_Struct: 3462 case ETK_Class: 3463 case ETK_Interface: 3464 Out << "Ts"; 3465 break; 3466 case ETK_Union: 3467 Out << "Tu"; 3468 break; 3469 case ETK_Enum: 3470 Out << "Te"; 3471 break; 3472 } 3473 // Typename types are always nested 3474 Out << 'N'; 3475 manglePrefix(T->getQualifier()); 3476 mangleSourceName(T->getIdentifier()); 3477 Out << 'E'; 3478 } 3479 3480 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) { 3481 // Dependently-scoped template types are nested if they have a prefix. 3482 Out << 'N'; 3483 3484 // TODO: avoid making this TemplateName. 3485 TemplateName Prefix = 3486 getASTContext().getDependentTemplateName(T->getQualifier(), 3487 T->getIdentifier()); 3488 mangleTemplatePrefix(Prefix); 3489 3490 // FIXME: GCC does not appear to mangle the template arguments when 3491 // the template in question is a dependent template name. Should we 3492 // emulate that badness? 3493 mangleTemplateArgs(T->getArgs(), T->getNumArgs()); 3494 Out << 'E'; 3495 } 3496 3497 void CXXNameMangler::mangleType(const TypeOfType *T) { 3498 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 3499 // "extension with parameters" mangling. 3500 Out << "u6typeof"; 3501 } 3502 3503 void CXXNameMangler::mangleType(const TypeOfExprType *T) { 3504 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 3505 // "extension with parameters" mangling. 3506 Out << "u6typeof"; 3507 } 3508 3509 void CXXNameMangler::mangleType(const DecltypeType *T) { 3510 Expr *E = T->getUnderlyingExpr(); 3511 3512 // type ::= Dt <expression> E # decltype of an id-expression 3513 // # or class member access 3514 // ::= DT <expression> E # decltype of an expression 3515 3516 // This purports to be an exhaustive list of id-expressions and 3517 // class member accesses. Note that we do not ignore parentheses; 3518 // parentheses change the semantics of decltype for these 3519 // expressions (and cause the mangler to use the other form). 3520 if (isa<DeclRefExpr>(E) || 3521 isa<MemberExpr>(E) || 3522 isa<UnresolvedLookupExpr>(E) || 3523 isa<DependentScopeDeclRefExpr>(E) || 3524 isa<CXXDependentScopeMemberExpr>(E) || 3525 isa<UnresolvedMemberExpr>(E)) 3526 Out << "Dt"; 3527 else 3528 Out << "DT"; 3529 mangleExpression(E); 3530 Out << 'E'; 3531 } 3532 3533 void CXXNameMangler::mangleType(const UnaryTransformType *T) { 3534 // If this is dependent, we need to record that. If not, we simply 3535 // mangle it as the underlying type since they are equivalent. 3536 if (T->isDependentType()) { 3537 Out << 'U'; 3538 3539 switch (T->getUTTKind()) { 3540 case UnaryTransformType::EnumUnderlyingType: 3541 Out << "3eut"; 3542 break; 3543 } 3544 } 3545 3546 mangleType(T->getBaseType()); 3547 } 3548 3549 void CXXNameMangler::mangleType(const AutoType *T) { 3550 assert(T->getDeducedType().isNull() && 3551 "Deduced AutoType shouldn't be handled here!"); 3552 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType && 3553 "shouldn't need to mangle __auto_type!"); 3554 // <builtin-type> ::= Da # auto 3555 // ::= Dc # decltype(auto) 3556 Out << (T->isDecltypeAuto() ? "Dc" : "Da"); 3557 } 3558 3559 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) { 3560 // FIXME: This is not the right mangling. We also need to include a scope 3561 // here in some cases. 3562 QualType D = T->getDeducedType(); 3563 if (D.isNull()) 3564 mangleUnscopedTemplateName(T->getTemplateName(), nullptr); 3565 else 3566 mangleType(D); 3567 } 3568 3569 void CXXNameMangler::mangleType(const AtomicType *T) { 3570 // <type> ::= U <source-name> <type> # vendor extended type qualifier 3571 // (Until there's a standardized mangling...) 3572 Out << "U7_Atomic"; 3573 mangleType(T->getValueType()); 3574 } 3575 3576 void CXXNameMangler::mangleType(const PipeType *T) { 3577 // Pipe type mangling rules are described in SPIR 2.0 specification 3578 // A.1 Data types and A.3 Summary of changes 3579 // <type> ::= 8ocl_pipe 3580 Out << "8ocl_pipe"; 3581 } 3582 3583 void CXXNameMangler::mangleType(const ExtIntType *T) { 3584 Out << "U7_ExtInt"; 3585 llvm::APSInt BW(32, true); 3586 BW = T->getNumBits(); 3587 TemplateArgument TA(Context.getASTContext(), BW, getASTContext().IntTy); 3588 mangleTemplateArgs(&TA, 1); 3589 if (T->isUnsigned()) 3590 Out << "j"; 3591 else 3592 Out << "i"; 3593 } 3594 3595 void CXXNameMangler::mangleType(const DependentExtIntType *T) { 3596 Out << "U7_ExtInt"; 3597 TemplateArgument TA(T->getNumBitsExpr()); 3598 mangleTemplateArgs(&TA, 1); 3599 if (T->isUnsigned()) 3600 Out << "j"; 3601 else 3602 Out << "i"; 3603 } 3604 3605 void CXXNameMangler::mangleIntegerLiteral(QualType T, 3606 const llvm::APSInt &Value) { 3607 // <expr-primary> ::= L <type> <value number> E # integer literal 3608 Out << 'L'; 3609 3610 mangleType(T); 3611 if (T->isBooleanType()) { 3612 // Boolean values are encoded as 0/1. 3613 Out << (Value.getBoolValue() ? '1' : '0'); 3614 } else { 3615 mangleNumber(Value); 3616 } 3617 Out << 'E'; 3618 3619 } 3620 3621 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) { 3622 // Ignore member expressions involving anonymous unions. 3623 while (const auto *RT = Base->getType()->getAs<RecordType>()) { 3624 if (!RT->getDecl()->isAnonymousStructOrUnion()) 3625 break; 3626 const auto *ME = dyn_cast<MemberExpr>(Base); 3627 if (!ME) 3628 break; 3629 Base = ME->getBase(); 3630 IsArrow = ME->isArrow(); 3631 } 3632 3633 if (Base->isImplicitCXXThis()) { 3634 // Note: GCC mangles member expressions to the implicit 'this' as 3635 // *this., whereas we represent them as this->. The Itanium C++ ABI 3636 // does not specify anything here, so we follow GCC. 3637 Out << "dtdefpT"; 3638 } else { 3639 Out << (IsArrow ? "pt" : "dt"); 3640 mangleExpression(Base); 3641 } 3642 } 3643 3644 /// Mangles a member expression. 3645 void CXXNameMangler::mangleMemberExpr(const Expr *base, 3646 bool isArrow, 3647 NestedNameSpecifier *qualifier, 3648 NamedDecl *firstQualifierLookup, 3649 DeclarationName member, 3650 const TemplateArgumentLoc *TemplateArgs, 3651 unsigned NumTemplateArgs, 3652 unsigned arity) { 3653 // <expression> ::= dt <expression> <unresolved-name> 3654 // ::= pt <expression> <unresolved-name> 3655 if (base) 3656 mangleMemberExprBase(base, isArrow); 3657 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity); 3658 } 3659 3660 /// Look at the callee of the given call expression and determine if 3661 /// it's a parenthesized id-expression which would have triggered ADL 3662 /// otherwise. 3663 static bool isParenthesizedADLCallee(const CallExpr *call) { 3664 const Expr *callee = call->getCallee(); 3665 const Expr *fn = callee->IgnoreParens(); 3666 3667 // Must be parenthesized. IgnoreParens() skips __extension__ nodes, 3668 // too, but for those to appear in the callee, it would have to be 3669 // parenthesized. 3670 if (callee == fn) return false; 3671 3672 // Must be an unresolved lookup. 3673 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn); 3674 if (!lookup) return false; 3675 3676 assert(!lookup->requiresADL()); 3677 3678 // Must be an unqualified lookup. 3679 if (lookup->getQualifier()) return false; 3680 3681 // Must not have found a class member. Note that if one is a class 3682 // member, they're all class members. 3683 if (lookup->getNumDecls() > 0 && 3684 (*lookup->decls_begin())->isCXXClassMember()) 3685 return false; 3686 3687 // Otherwise, ADL would have been triggered. 3688 return true; 3689 } 3690 3691 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) { 3692 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E); 3693 Out << CastEncoding; 3694 mangleType(ECE->getType()); 3695 mangleExpression(ECE->getSubExpr()); 3696 } 3697 3698 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) { 3699 if (auto *Syntactic = InitList->getSyntacticForm()) 3700 InitList = Syntactic; 3701 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 3702 mangleExpression(InitList->getInit(i)); 3703 } 3704 3705 void CXXNameMangler::mangleDeclRefExpr(const NamedDecl *D) { 3706 switch (D->getKind()) { 3707 default: 3708 // <expr-primary> ::= L <mangled-name> E # external name 3709 Out << 'L'; 3710 mangle(D); 3711 Out << 'E'; 3712 break; 3713 3714 case Decl::ParmVar: 3715 mangleFunctionParam(cast<ParmVarDecl>(D)); 3716 break; 3717 3718 case Decl::EnumConstant: { 3719 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D); 3720 mangleIntegerLiteral(ED->getType(), ED->getInitVal()); 3721 break; 3722 } 3723 3724 case Decl::NonTypeTemplateParm: 3725 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D); 3726 mangleTemplateParameter(PD->getDepth(), PD->getIndex()); 3727 break; 3728 } 3729 } 3730 3731 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) { 3732 // <expression> ::= <unary operator-name> <expression> 3733 // ::= <binary operator-name> <expression> <expression> 3734 // ::= <trinary operator-name> <expression> <expression> <expression> 3735 // ::= cv <type> expression # conversion with one argument 3736 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments 3737 // ::= dc <type> <expression> # dynamic_cast<type> (expression) 3738 // ::= sc <type> <expression> # static_cast<type> (expression) 3739 // ::= cc <type> <expression> # const_cast<type> (expression) 3740 // ::= rc <type> <expression> # reinterpret_cast<type> (expression) 3741 // ::= st <type> # sizeof (a type) 3742 // ::= at <type> # alignof (a type) 3743 // ::= <template-param> 3744 // ::= <function-param> 3745 // ::= sr <type> <unqualified-name> # dependent name 3746 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id 3747 // ::= ds <expression> <expression> # expr.*expr 3748 // ::= sZ <template-param> # size of a parameter pack 3749 // ::= sZ <function-param> # size of a function parameter pack 3750 // ::= <expr-primary> 3751 // <expr-primary> ::= L <type> <value number> E # integer literal 3752 // ::= L <type <value float> E # floating literal 3753 // ::= L <mangled-name> E # external name 3754 // ::= fpT # 'this' expression 3755 QualType ImplicitlyConvertedToType; 3756 3757 recurse: 3758 switch (E->getStmtClass()) { 3759 case Expr::NoStmtClass: 3760 #define ABSTRACT_STMT(Type) 3761 #define EXPR(Type, Base) 3762 #define STMT(Type, Base) \ 3763 case Expr::Type##Class: 3764 #include "clang/AST/StmtNodes.inc" 3765 // fallthrough 3766 3767 // These all can only appear in local or variable-initialization 3768 // contexts and so should never appear in a mangling. 3769 case Expr::AddrLabelExprClass: 3770 case Expr::DesignatedInitUpdateExprClass: 3771 case Expr::ImplicitValueInitExprClass: 3772 case Expr::ArrayInitLoopExprClass: 3773 case Expr::ArrayInitIndexExprClass: 3774 case Expr::NoInitExprClass: 3775 case Expr::ParenListExprClass: 3776 case Expr::LambdaExprClass: 3777 case Expr::MSPropertyRefExprClass: 3778 case Expr::MSPropertySubscriptExprClass: 3779 case Expr::TypoExprClass: // This should no longer exist in the AST by now. 3780 case Expr::RecoveryExprClass: 3781 case Expr::OMPArraySectionExprClass: 3782 case Expr::OMPArrayShapingExprClass: 3783 case Expr::OMPIteratorExprClass: 3784 case Expr::CXXInheritedCtorInitExprClass: 3785 llvm_unreachable("unexpected statement kind"); 3786 3787 case Expr::ConstantExprClass: 3788 E = cast<ConstantExpr>(E)->getSubExpr(); 3789 goto recurse; 3790 3791 // FIXME: invent manglings for all these. 3792 case Expr::BlockExprClass: 3793 case Expr::ChooseExprClass: 3794 case Expr::CompoundLiteralExprClass: 3795 case Expr::ExtVectorElementExprClass: 3796 case Expr::GenericSelectionExprClass: 3797 case Expr::ObjCEncodeExprClass: 3798 case Expr::ObjCIsaExprClass: 3799 case Expr::ObjCIvarRefExprClass: 3800 case Expr::ObjCMessageExprClass: 3801 case Expr::ObjCPropertyRefExprClass: 3802 case Expr::ObjCProtocolExprClass: 3803 case Expr::ObjCSelectorExprClass: 3804 case Expr::ObjCStringLiteralClass: 3805 case Expr::ObjCBoxedExprClass: 3806 case Expr::ObjCArrayLiteralClass: 3807 case Expr::ObjCDictionaryLiteralClass: 3808 case Expr::ObjCSubscriptRefExprClass: 3809 case Expr::ObjCIndirectCopyRestoreExprClass: 3810 case Expr::ObjCAvailabilityCheckExprClass: 3811 case Expr::OffsetOfExprClass: 3812 case Expr::PredefinedExprClass: 3813 case Expr::ShuffleVectorExprClass: 3814 case Expr::ConvertVectorExprClass: 3815 case Expr::StmtExprClass: 3816 case Expr::TypeTraitExprClass: 3817 case Expr::RequiresExprClass: 3818 case Expr::ArrayTypeTraitExprClass: 3819 case Expr::ExpressionTraitExprClass: 3820 case Expr::VAArgExprClass: 3821 case Expr::CUDAKernelCallExprClass: 3822 case Expr::AsTypeExprClass: 3823 case Expr::PseudoObjectExprClass: 3824 case Expr::AtomicExprClass: 3825 case Expr::SourceLocExprClass: 3826 case Expr::FixedPointLiteralClass: 3827 case Expr::BuiltinBitCastExprClass: 3828 { 3829 if (!NullOut) { 3830 // As bad as this diagnostic is, it's better than crashing. 3831 DiagnosticsEngine &Diags = Context.getDiags(); 3832 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3833 "cannot yet mangle expression type %0"); 3834 Diags.Report(E->getExprLoc(), DiagID) 3835 << E->getStmtClassName() << E->getSourceRange(); 3836 } 3837 break; 3838 } 3839 3840 case Expr::CXXUuidofExprClass: { 3841 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E); 3842 if (UE->isTypeOperand()) { 3843 QualType UuidT = UE->getTypeOperand(Context.getASTContext()); 3844 Out << "u8__uuidoft"; 3845 mangleType(UuidT); 3846 } else { 3847 Expr *UuidExp = UE->getExprOperand(); 3848 Out << "u8__uuidofz"; 3849 mangleExpression(UuidExp, Arity); 3850 } 3851 break; 3852 } 3853 3854 // Even gcc-4.5 doesn't mangle this. 3855 case Expr::BinaryConditionalOperatorClass: { 3856 DiagnosticsEngine &Diags = Context.getDiags(); 3857 unsigned DiagID = 3858 Diags.getCustomDiagID(DiagnosticsEngine::Error, 3859 "?: operator with omitted middle operand cannot be mangled"); 3860 Diags.Report(E->getExprLoc(), DiagID) 3861 << E->getStmtClassName() << E->getSourceRange(); 3862 break; 3863 } 3864 3865 // These are used for internal purposes and cannot be meaningfully mangled. 3866 case Expr::OpaqueValueExprClass: 3867 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?"); 3868 3869 case Expr::InitListExprClass: { 3870 Out << "il"; 3871 mangleInitListElements(cast<InitListExpr>(E)); 3872 Out << "E"; 3873 break; 3874 } 3875 3876 case Expr::DesignatedInitExprClass: { 3877 auto *DIE = cast<DesignatedInitExpr>(E); 3878 for (const auto &Designator : DIE->designators()) { 3879 if (Designator.isFieldDesignator()) { 3880 Out << "di"; 3881 mangleSourceName(Designator.getFieldName()); 3882 } else if (Designator.isArrayDesignator()) { 3883 Out << "dx"; 3884 mangleExpression(DIE->getArrayIndex(Designator)); 3885 } else { 3886 assert(Designator.isArrayRangeDesignator() && 3887 "unknown designator kind"); 3888 Out << "dX"; 3889 mangleExpression(DIE->getArrayRangeStart(Designator)); 3890 mangleExpression(DIE->getArrayRangeEnd(Designator)); 3891 } 3892 } 3893 mangleExpression(DIE->getInit()); 3894 break; 3895 } 3896 3897 case Expr::CXXDefaultArgExprClass: 3898 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity); 3899 break; 3900 3901 case Expr::CXXDefaultInitExprClass: 3902 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity); 3903 break; 3904 3905 case Expr::CXXStdInitializerListExprClass: 3906 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity); 3907 break; 3908 3909 case Expr::SubstNonTypeTemplateParmExprClass: 3910 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), 3911 Arity); 3912 break; 3913 3914 case Expr::UserDefinedLiteralClass: 3915 // We follow g++'s approach of mangling a UDL as a call to the literal 3916 // operator. 3917 case Expr::CXXMemberCallExprClass: // fallthrough 3918 case Expr::CallExprClass: { 3919 const CallExpr *CE = cast<CallExpr>(E); 3920 3921 // <expression> ::= cp <simple-id> <expression>* E 3922 // We use this mangling only when the call would use ADL except 3923 // for being parenthesized. Per discussion with David 3924 // Vandervoorde, 2011.04.25. 3925 if (isParenthesizedADLCallee(CE)) { 3926 Out << "cp"; 3927 // The callee here is a parenthesized UnresolvedLookupExpr with 3928 // no qualifier and should always get mangled as a <simple-id> 3929 // anyway. 3930 3931 // <expression> ::= cl <expression>* E 3932 } else { 3933 Out << "cl"; 3934 } 3935 3936 unsigned CallArity = CE->getNumArgs(); 3937 for (const Expr *Arg : CE->arguments()) 3938 if (isa<PackExpansionExpr>(Arg)) 3939 CallArity = UnknownArity; 3940 3941 mangleExpression(CE->getCallee(), CallArity); 3942 for (const Expr *Arg : CE->arguments()) 3943 mangleExpression(Arg); 3944 Out << 'E'; 3945 break; 3946 } 3947 3948 case Expr::CXXNewExprClass: { 3949 const CXXNewExpr *New = cast<CXXNewExpr>(E); 3950 if (New->isGlobalNew()) Out << "gs"; 3951 Out << (New->isArray() ? "na" : "nw"); 3952 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(), 3953 E = New->placement_arg_end(); I != E; ++I) 3954 mangleExpression(*I); 3955 Out << '_'; 3956 mangleType(New->getAllocatedType()); 3957 if (New->hasInitializer()) { 3958 if (New->getInitializationStyle() == CXXNewExpr::ListInit) 3959 Out << "il"; 3960 else 3961 Out << "pi"; 3962 const Expr *Init = New->getInitializer(); 3963 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 3964 // Directly inline the initializers. 3965 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 3966 E = CCE->arg_end(); 3967 I != E; ++I) 3968 mangleExpression(*I); 3969 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) { 3970 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i) 3971 mangleExpression(PLE->getExpr(i)); 3972 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit && 3973 isa<InitListExpr>(Init)) { 3974 // Only take InitListExprs apart for list-initialization. 3975 mangleInitListElements(cast<InitListExpr>(Init)); 3976 } else 3977 mangleExpression(Init); 3978 } 3979 Out << 'E'; 3980 break; 3981 } 3982 3983 case Expr::CXXPseudoDestructorExprClass: { 3984 const auto *PDE = cast<CXXPseudoDestructorExpr>(E); 3985 if (const Expr *Base = PDE->getBase()) 3986 mangleMemberExprBase(Base, PDE->isArrow()); 3987 NestedNameSpecifier *Qualifier = PDE->getQualifier(); 3988 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) { 3989 if (Qualifier) { 3990 mangleUnresolvedPrefix(Qualifier, 3991 /*recursive=*/true); 3992 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()); 3993 Out << 'E'; 3994 } else { 3995 Out << "sr"; 3996 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType())) 3997 Out << 'E'; 3998 } 3999 } else if (Qualifier) { 4000 mangleUnresolvedPrefix(Qualifier); 4001 } 4002 // <base-unresolved-name> ::= dn <destructor-name> 4003 Out << "dn"; 4004 QualType DestroyedType = PDE->getDestroyedType(); 4005 mangleUnresolvedTypeOrSimpleId(DestroyedType); 4006 break; 4007 } 4008 4009 case Expr::MemberExprClass: { 4010 const MemberExpr *ME = cast<MemberExpr>(E); 4011 mangleMemberExpr(ME->getBase(), ME->isArrow(), 4012 ME->getQualifier(), nullptr, 4013 ME->getMemberDecl()->getDeclName(), 4014 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4015 Arity); 4016 break; 4017 } 4018 4019 case Expr::UnresolvedMemberExprClass: { 4020 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E); 4021 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 4022 ME->isArrow(), ME->getQualifier(), nullptr, 4023 ME->getMemberName(), 4024 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4025 Arity); 4026 break; 4027 } 4028 4029 case Expr::CXXDependentScopeMemberExprClass: { 4030 const CXXDependentScopeMemberExpr *ME 4031 = cast<CXXDependentScopeMemberExpr>(E); 4032 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 4033 ME->isArrow(), ME->getQualifier(), 4034 ME->getFirstQualifierFoundInScope(), 4035 ME->getMember(), 4036 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4037 Arity); 4038 break; 4039 } 4040 4041 case Expr::UnresolvedLookupExprClass: { 4042 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E); 4043 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), 4044 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(), 4045 Arity); 4046 break; 4047 } 4048 4049 case Expr::CXXUnresolvedConstructExprClass: { 4050 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E); 4051 unsigned N = CE->arg_size(); 4052 4053 if (CE->isListInitialization()) { 4054 assert(N == 1 && "unexpected form for list initialization"); 4055 auto *IL = cast<InitListExpr>(CE->getArg(0)); 4056 Out << "tl"; 4057 mangleType(CE->getType()); 4058 mangleInitListElements(IL); 4059 Out << "E"; 4060 return; 4061 } 4062 4063 Out << "cv"; 4064 mangleType(CE->getType()); 4065 if (N != 1) Out << '_'; 4066 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 4067 if (N != 1) Out << 'E'; 4068 break; 4069 } 4070 4071 case Expr::CXXConstructExprClass: { 4072 const auto *CE = cast<CXXConstructExpr>(E); 4073 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) { 4074 assert( 4075 CE->getNumArgs() >= 1 && 4076 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && 4077 "implicit CXXConstructExpr must have one argument"); 4078 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0)); 4079 } 4080 Out << "il"; 4081 for (auto *E : CE->arguments()) 4082 mangleExpression(E); 4083 Out << "E"; 4084 break; 4085 } 4086 4087 case Expr::CXXTemporaryObjectExprClass: { 4088 const auto *CE = cast<CXXTemporaryObjectExpr>(E); 4089 unsigned N = CE->getNumArgs(); 4090 bool List = CE->isListInitialization(); 4091 4092 if (List) 4093 Out << "tl"; 4094 else 4095 Out << "cv"; 4096 mangleType(CE->getType()); 4097 if (!List && N != 1) 4098 Out << '_'; 4099 if (CE->isStdInitListInitialization()) { 4100 // We implicitly created a std::initializer_list<T> for the first argument 4101 // of a constructor of type U in an expression of the form U{a, b, c}. 4102 // Strip all the semantic gunk off the initializer list. 4103 auto *SILE = 4104 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit()); 4105 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit()); 4106 mangleInitListElements(ILE); 4107 } else { 4108 for (auto *E : CE->arguments()) 4109 mangleExpression(E); 4110 } 4111 if (List || N != 1) 4112 Out << 'E'; 4113 break; 4114 } 4115 4116 case Expr::CXXScalarValueInitExprClass: 4117 Out << "cv"; 4118 mangleType(E->getType()); 4119 Out << "_E"; 4120 break; 4121 4122 case Expr::CXXNoexceptExprClass: 4123 Out << "nx"; 4124 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand()); 4125 break; 4126 4127 case Expr::UnaryExprOrTypeTraitExprClass: { 4128 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); 4129 4130 if (!SAE->isInstantiationDependent()) { 4131 // Itanium C++ ABI: 4132 // If the operand of a sizeof or alignof operator is not 4133 // instantiation-dependent it is encoded as an integer literal 4134 // reflecting the result of the operator. 4135 // 4136 // If the result of the operator is implicitly converted to a known 4137 // integer type, that type is used for the literal; otherwise, the type 4138 // of std::size_t or std::ptrdiff_t is used. 4139 QualType T = (ImplicitlyConvertedToType.isNull() || 4140 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() 4141 : ImplicitlyConvertedToType; 4142 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); 4143 mangleIntegerLiteral(T, V); 4144 break; 4145 } 4146 4147 switch(SAE->getKind()) { 4148 case UETT_SizeOf: 4149 Out << 's'; 4150 break; 4151 case UETT_PreferredAlignOf: 4152 case UETT_AlignOf: 4153 Out << 'a'; 4154 break; 4155 case UETT_VecStep: { 4156 DiagnosticsEngine &Diags = Context.getDiags(); 4157 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 4158 "cannot yet mangle vec_step expression"); 4159 Diags.Report(DiagID); 4160 return; 4161 } 4162 case UETT_OpenMPRequiredSimdAlign: { 4163 DiagnosticsEngine &Diags = Context.getDiags(); 4164 unsigned DiagID = Diags.getCustomDiagID( 4165 DiagnosticsEngine::Error, 4166 "cannot yet mangle __builtin_omp_required_simd_align expression"); 4167 Diags.Report(DiagID); 4168 return; 4169 } 4170 } 4171 if (SAE->isArgumentType()) { 4172 Out << 't'; 4173 mangleType(SAE->getArgumentType()); 4174 } else { 4175 Out << 'z'; 4176 mangleExpression(SAE->getArgumentExpr()); 4177 } 4178 break; 4179 } 4180 4181 case Expr::CXXThrowExprClass: { 4182 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E); 4183 // <expression> ::= tw <expression> # throw expression 4184 // ::= tr # rethrow 4185 if (TE->getSubExpr()) { 4186 Out << "tw"; 4187 mangleExpression(TE->getSubExpr()); 4188 } else { 4189 Out << "tr"; 4190 } 4191 break; 4192 } 4193 4194 case Expr::CXXTypeidExprClass: { 4195 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E); 4196 // <expression> ::= ti <type> # typeid (type) 4197 // ::= te <expression> # typeid (expression) 4198 if (TIE->isTypeOperand()) { 4199 Out << "ti"; 4200 mangleType(TIE->getTypeOperand(Context.getASTContext())); 4201 } else { 4202 Out << "te"; 4203 mangleExpression(TIE->getExprOperand()); 4204 } 4205 break; 4206 } 4207 4208 case Expr::CXXDeleteExprClass: { 4209 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E); 4210 // <expression> ::= [gs] dl <expression> # [::] delete expr 4211 // ::= [gs] da <expression> # [::] delete [] expr 4212 if (DE->isGlobalDelete()) Out << "gs"; 4213 Out << (DE->isArrayForm() ? "da" : "dl"); 4214 mangleExpression(DE->getArgument()); 4215 break; 4216 } 4217 4218 case Expr::UnaryOperatorClass: { 4219 const UnaryOperator *UO = cast<UnaryOperator>(E); 4220 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()), 4221 /*Arity=*/1); 4222 mangleExpression(UO->getSubExpr()); 4223 break; 4224 } 4225 4226 case Expr::ArraySubscriptExprClass: { 4227 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E); 4228 4229 // Array subscript is treated as a syntactically weird form of 4230 // binary operator. 4231 Out << "ix"; 4232 mangleExpression(AE->getLHS()); 4233 mangleExpression(AE->getRHS()); 4234 break; 4235 } 4236 4237 case Expr::MatrixSubscriptExprClass: { 4238 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E); 4239 Out << "ixix"; 4240 mangleExpression(ME->getBase()); 4241 mangleExpression(ME->getRowIdx()); 4242 mangleExpression(ME->getColumnIdx()); 4243 break; 4244 } 4245 4246 case Expr::CompoundAssignOperatorClass: // fallthrough 4247 case Expr::BinaryOperatorClass: { 4248 const BinaryOperator *BO = cast<BinaryOperator>(E); 4249 if (BO->getOpcode() == BO_PtrMemD) 4250 Out << "ds"; 4251 else 4252 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()), 4253 /*Arity=*/2); 4254 mangleExpression(BO->getLHS()); 4255 mangleExpression(BO->getRHS()); 4256 break; 4257 } 4258 4259 case Expr::CXXRewrittenBinaryOperatorClass: { 4260 // The mangled form represents the original syntax. 4261 CXXRewrittenBinaryOperator::DecomposedForm Decomposed = 4262 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm(); 4263 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode), 4264 /*Arity=*/2); 4265 mangleExpression(Decomposed.LHS); 4266 mangleExpression(Decomposed.RHS); 4267 break; 4268 } 4269 4270 case Expr::ConditionalOperatorClass: { 4271 const ConditionalOperator *CO = cast<ConditionalOperator>(E); 4272 mangleOperatorName(OO_Conditional, /*Arity=*/3); 4273 mangleExpression(CO->getCond()); 4274 mangleExpression(CO->getLHS(), Arity); 4275 mangleExpression(CO->getRHS(), Arity); 4276 break; 4277 } 4278 4279 case Expr::ImplicitCastExprClass: { 4280 ImplicitlyConvertedToType = E->getType(); 4281 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4282 goto recurse; 4283 } 4284 4285 case Expr::ObjCBridgedCastExprClass: { 4286 // Mangle ownership casts as a vendor extended operator __bridge, 4287 // __bridge_transfer, or __bridge_retain. 4288 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); 4289 Out << "v1U" << Kind.size() << Kind; 4290 } 4291 // Fall through to mangle the cast itself. 4292 LLVM_FALLTHROUGH; 4293 4294 case Expr::CStyleCastExprClass: 4295 mangleCastExpression(E, "cv"); 4296 break; 4297 4298 case Expr::CXXFunctionalCastExprClass: { 4299 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit(); 4300 // FIXME: Add isImplicit to CXXConstructExpr. 4301 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub)) 4302 if (CCE->getParenOrBraceRange().isInvalid()) 4303 Sub = CCE->getArg(0)->IgnoreImplicit(); 4304 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub)) 4305 Sub = StdInitList->getSubExpr()->IgnoreImplicit(); 4306 if (auto *IL = dyn_cast<InitListExpr>(Sub)) { 4307 Out << "tl"; 4308 mangleType(E->getType()); 4309 mangleInitListElements(IL); 4310 Out << "E"; 4311 } else { 4312 mangleCastExpression(E, "cv"); 4313 } 4314 break; 4315 } 4316 4317 case Expr::CXXStaticCastExprClass: 4318 mangleCastExpression(E, "sc"); 4319 break; 4320 case Expr::CXXDynamicCastExprClass: 4321 mangleCastExpression(E, "dc"); 4322 break; 4323 case Expr::CXXReinterpretCastExprClass: 4324 mangleCastExpression(E, "rc"); 4325 break; 4326 case Expr::CXXConstCastExprClass: 4327 mangleCastExpression(E, "cc"); 4328 break; 4329 case Expr::CXXAddrspaceCastExprClass: 4330 mangleCastExpression(E, "ac"); 4331 break; 4332 4333 case Expr::CXXOperatorCallExprClass: { 4334 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E); 4335 unsigned NumArgs = CE->getNumArgs(); 4336 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax 4337 // (the enclosing MemberExpr covers the syntactic portion). 4338 if (CE->getOperator() != OO_Arrow) 4339 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs); 4340 // Mangle the arguments. 4341 for (unsigned i = 0; i != NumArgs; ++i) 4342 mangleExpression(CE->getArg(i)); 4343 break; 4344 } 4345 4346 case Expr::ParenExprClass: 4347 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity); 4348 break; 4349 4350 4351 case Expr::ConceptSpecializationExprClass: { 4352 // <expr-primary> ::= L <mangled-name> E # external name 4353 Out << "L_Z"; 4354 auto *CSE = cast<ConceptSpecializationExpr>(E); 4355 mangleTemplateName(CSE->getNamedConcept(), 4356 CSE->getTemplateArguments().data(), 4357 CSE->getTemplateArguments().size()); 4358 Out << 'E'; 4359 break; 4360 } 4361 4362 case Expr::DeclRefExprClass: 4363 mangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl()); 4364 break; 4365 4366 case Expr::SubstNonTypeTemplateParmPackExprClass: 4367 // FIXME: not clear how to mangle this! 4368 // template <unsigned N...> class A { 4369 // template <class U...> void foo(U (&x)[N]...); 4370 // }; 4371 Out << "_SUBSTPACK_"; 4372 break; 4373 4374 case Expr::FunctionParmPackExprClass: { 4375 // FIXME: not clear how to mangle this! 4376 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E); 4377 Out << "v110_SUBSTPACK"; 4378 mangleDeclRefExpr(FPPE->getParameterPack()); 4379 break; 4380 } 4381 4382 case Expr::DependentScopeDeclRefExprClass: { 4383 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E); 4384 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), 4385 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(), 4386 Arity); 4387 break; 4388 } 4389 4390 case Expr::CXXBindTemporaryExprClass: 4391 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr()); 4392 break; 4393 4394 case Expr::ExprWithCleanupsClass: 4395 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity); 4396 break; 4397 4398 case Expr::FloatingLiteralClass: { 4399 const FloatingLiteral *FL = cast<FloatingLiteral>(E); 4400 Out << 'L'; 4401 mangleType(FL->getType()); 4402 mangleFloat(FL->getValue()); 4403 Out << 'E'; 4404 break; 4405 } 4406 4407 case Expr::CharacterLiteralClass: 4408 Out << 'L'; 4409 mangleType(E->getType()); 4410 Out << cast<CharacterLiteral>(E)->getValue(); 4411 Out << 'E'; 4412 break; 4413 4414 // FIXME. __objc_yes/__objc_no are mangled same as true/false 4415 case Expr::ObjCBoolLiteralExprClass: 4416 Out << "Lb"; 4417 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 4418 Out << 'E'; 4419 break; 4420 4421 case Expr::CXXBoolLiteralExprClass: 4422 Out << "Lb"; 4423 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 4424 Out << 'E'; 4425 break; 4426 4427 case Expr::IntegerLiteralClass: { 4428 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue()); 4429 if (E->getType()->isSignedIntegerType()) 4430 Value.setIsSigned(true); 4431 mangleIntegerLiteral(E->getType(), Value); 4432 break; 4433 } 4434 4435 case Expr::ImaginaryLiteralClass: { 4436 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E); 4437 // Mangle as if a complex literal. 4438 // Proposal from David Vandevoorde, 2010.06.30. 4439 Out << 'L'; 4440 mangleType(E->getType()); 4441 if (const FloatingLiteral *Imag = 4442 dyn_cast<FloatingLiteral>(IE->getSubExpr())) { 4443 // Mangle a floating-point zero of the appropriate type. 4444 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics())); 4445 Out << '_'; 4446 mangleFloat(Imag->getValue()); 4447 } else { 4448 Out << "0_"; 4449 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue()); 4450 if (IE->getSubExpr()->getType()->isSignedIntegerType()) 4451 Value.setIsSigned(true); 4452 mangleNumber(Value); 4453 } 4454 Out << 'E'; 4455 break; 4456 } 4457 4458 case Expr::StringLiteralClass: { 4459 // Revised proposal from David Vandervoorde, 2010.07.15. 4460 Out << 'L'; 4461 assert(isa<ConstantArrayType>(E->getType())); 4462 mangleType(E->getType()); 4463 Out << 'E'; 4464 break; 4465 } 4466 4467 case Expr::GNUNullExprClass: 4468 // Mangle as if an integer literal 0. 4469 Out << 'L'; 4470 mangleType(E->getType()); 4471 Out << "0E"; 4472 break; 4473 4474 case Expr::CXXNullPtrLiteralExprClass: { 4475 Out << "LDnE"; 4476 break; 4477 } 4478 4479 case Expr::PackExpansionExprClass: 4480 Out << "sp"; 4481 mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); 4482 break; 4483 4484 case Expr::SizeOfPackExprClass: { 4485 auto *SPE = cast<SizeOfPackExpr>(E); 4486 if (SPE->isPartiallySubstituted()) { 4487 Out << "sP"; 4488 for (const auto &A : SPE->getPartialArguments()) 4489 mangleTemplateArg(A); 4490 Out << "E"; 4491 break; 4492 } 4493 4494 Out << "sZ"; 4495 const NamedDecl *Pack = SPE->getPack(); 4496 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack)) 4497 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 4498 else if (const NonTypeTemplateParmDecl *NTTP 4499 = dyn_cast<NonTypeTemplateParmDecl>(Pack)) 4500 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex()); 4501 else if (const TemplateTemplateParmDecl *TempTP 4502 = dyn_cast<TemplateTemplateParmDecl>(Pack)) 4503 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex()); 4504 else 4505 mangleFunctionParam(cast<ParmVarDecl>(Pack)); 4506 break; 4507 } 4508 4509 case Expr::MaterializeTemporaryExprClass: { 4510 mangleExpression(cast<MaterializeTemporaryExpr>(E)->getSubExpr()); 4511 break; 4512 } 4513 4514 case Expr::CXXFoldExprClass: { 4515 auto *FE = cast<CXXFoldExpr>(E); 4516 if (FE->isLeftFold()) 4517 Out << (FE->getInit() ? "fL" : "fl"); 4518 else 4519 Out << (FE->getInit() ? "fR" : "fr"); 4520 4521 if (FE->getOperator() == BO_PtrMemD) 4522 Out << "ds"; 4523 else 4524 mangleOperatorName( 4525 BinaryOperator::getOverloadedOperator(FE->getOperator()), 4526 /*Arity=*/2); 4527 4528 if (FE->getLHS()) 4529 mangleExpression(FE->getLHS()); 4530 if (FE->getRHS()) 4531 mangleExpression(FE->getRHS()); 4532 break; 4533 } 4534 4535 case Expr::CXXThisExprClass: 4536 Out << "fpT"; 4537 break; 4538 4539 case Expr::CoawaitExprClass: 4540 // FIXME: Propose a non-vendor mangling. 4541 Out << "v18co_await"; 4542 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 4543 break; 4544 4545 case Expr::DependentCoawaitExprClass: 4546 // FIXME: Propose a non-vendor mangling. 4547 Out << "v18co_await"; 4548 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand()); 4549 break; 4550 4551 case Expr::CoyieldExprClass: 4552 // FIXME: Propose a non-vendor mangling. 4553 Out << "v18co_yield"; 4554 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 4555 break; 4556 } 4557 } 4558 4559 /// Mangle an expression which refers to a parameter variable. 4560 /// 4561 /// <expression> ::= <function-param> 4562 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0 4563 /// <function-param> ::= fp <top-level CV-qualifiers> 4564 /// <parameter-2 non-negative number> _ # L == 0, I > 0 4565 /// <function-param> ::= fL <L-1 non-negative number> 4566 /// p <top-level CV-qualifiers> _ # L > 0, I == 0 4567 /// <function-param> ::= fL <L-1 non-negative number> 4568 /// p <top-level CV-qualifiers> 4569 /// <I-1 non-negative number> _ # L > 0, I > 0 4570 /// 4571 /// L is the nesting depth of the parameter, defined as 1 if the 4572 /// parameter comes from the innermost function prototype scope 4573 /// enclosing the current context, 2 if from the next enclosing 4574 /// function prototype scope, and so on, with one special case: if 4575 /// we've processed the full parameter clause for the innermost 4576 /// function type, then L is one less. This definition conveniently 4577 /// makes it irrelevant whether a function's result type was written 4578 /// trailing or leading, but is otherwise overly complicated; the 4579 /// numbering was first designed without considering references to 4580 /// parameter in locations other than return types, and then the 4581 /// mangling had to be generalized without changing the existing 4582 /// manglings. 4583 /// 4584 /// I is the zero-based index of the parameter within its parameter 4585 /// declaration clause. Note that the original ABI document describes 4586 /// this using 1-based ordinals. 4587 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) { 4588 unsigned parmDepth = parm->getFunctionScopeDepth(); 4589 unsigned parmIndex = parm->getFunctionScopeIndex(); 4590 4591 // Compute 'L'. 4592 // parmDepth does not include the declaring function prototype. 4593 // FunctionTypeDepth does account for that. 4594 assert(parmDepth < FunctionTypeDepth.getDepth()); 4595 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth; 4596 if (FunctionTypeDepth.isInResultType()) 4597 nestingDepth--; 4598 4599 if (nestingDepth == 0) { 4600 Out << "fp"; 4601 } else { 4602 Out << "fL" << (nestingDepth - 1) << 'p'; 4603 } 4604 4605 // Top-level qualifiers. We don't have to worry about arrays here, 4606 // because parameters declared as arrays should already have been 4607 // transformed to have pointer type. FIXME: apparently these don't 4608 // get mangled if used as an rvalue of a known non-class type? 4609 assert(!parm->getType()->isArrayType() 4610 && "parameter's type is still an array type?"); 4611 4612 if (const DependentAddressSpaceType *DAST = 4613 dyn_cast<DependentAddressSpaceType>(parm->getType())) { 4614 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST); 4615 } else { 4616 mangleQualifiers(parm->getType().getQualifiers()); 4617 } 4618 4619 // Parameter index. 4620 if (parmIndex != 0) { 4621 Out << (parmIndex - 1); 4622 } 4623 Out << '_'; 4624 } 4625 4626 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T, 4627 const CXXRecordDecl *InheritedFrom) { 4628 // <ctor-dtor-name> ::= C1 # complete object constructor 4629 // ::= C2 # base object constructor 4630 // ::= CI1 <type> # complete inheriting constructor 4631 // ::= CI2 <type> # base inheriting constructor 4632 // 4633 // In addition, C5 is a comdat name with C1 and C2 in it. 4634 Out << 'C'; 4635 if (InheritedFrom) 4636 Out << 'I'; 4637 switch (T) { 4638 case Ctor_Complete: 4639 Out << '1'; 4640 break; 4641 case Ctor_Base: 4642 Out << '2'; 4643 break; 4644 case Ctor_Comdat: 4645 Out << '5'; 4646 break; 4647 case Ctor_DefaultClosure: 4648 case Ctor_CopyingClosure: 4649 llvm_unreachable("closure constructors don't exist for the Itanium ABI!"); 4650 } 4651 if (InheritedFrom) 4652 mangleName(InheritedFrom); 4653 } 4654 4655 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 4656 // <ctor-dtor-name> ::= D0 # deleting destructor 4657 // ::= D1 # complete object destructor 4658 // ::= D2 # base object destructor 4659 // 4660 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it. 4661 switch (T) { 4662 case Dtor_Deleting: 4663 Out << "D0"; 4664 break; 4665 case Dtor_Complete: 4666 Out << "D1"; 4667 break; 4668 case Dtor_Base: 4669 Out << "D2"; 4670 break; 4671 case Dtor_Comdat: 4672 Out << "D5"; 4673 break; 4674 } 4675 } 4676 4677 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentLoc *TemplateArgs, 4678 unsigned NumTemplateArgs) { 4679 // <template-args> ::= I <template-arg>+ E 4680 Out << 'I'; 4681 for (unsigned i = 0; i != NumTemplateArgs; ++i) 4682 mangleTemplateArg(TemplateArgs[i].getArgument()); 4683 Out << 'E'; 4684 } 4685 4686 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) { 4687 // <template-args> ::= I <template-arg>+ E 4688 Out << 'I'; 4689 for (unsigned i = 0, e = AL.size(); i != e; ++i) 4690 mangleTemplateArg(AL[i]); 4691 Out << 'E'; 4692 } 4693 4694 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs, 4695 unsigned NumTemplateArgs) { 4696 // <template-args> ::= I <template-arg>+ E 4697 Out << 'I'; 4698 for (unsigned i = 0; i != NumTemplateArgs; ++i) 4699 mangleTemplateArg(TemplateArgs[i]); 4700 Out << 'E'; 4701 } 4702 4703 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) { 4704 // <template-arg> ::= <type> # type or template 4705 // ::= X <expression> E # expression 4706 // ::= <expr-primary> # simple expressions 4707 // ::= J <template-arg>* E # argument pack 4708 if (!A.isInstantiationDependent() || A.isDependent()) 4709 A = Context.getASTContext().getCanonicalTemplateArgument(A); 4710 4711 switch (A.getKind()) { 4712 case TemplateArgument::Null: 4713 llvm_unreachable("Cannot mangle NULL template argument"); 4714 4715 case TemplateArgument::Type: 4716 mangleType(A.getAsType()); 4717 break; 4718 case TemplateArgument::Template: 4719 // This is mangled as <type>. 4720 mangleType(A.getAsTemplate()); 4721 break; 4722 case TemplateArgument::TemplateExpansion: 4723 // <type> ::= Dp <type> # pack expansion (C++0x) 4724 Out << "Dp"; 4725 mangleType(A.getAsTemplateOrTemplatePattern()); 4726 break; 4727 case TemplateArgument::Expression: { 4728 // It's possible to end up with a DeclRefExpr here in certain 4729 // dependent cases, in which case we should mangle as a 4730 // declaration. 4731 const Expr *E = A.getAsExpr()->IgnoreParenImpCasts(); 4732 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 4733 const ValueDecl *D = DRE->getDecl(); 4734 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) { 4735 Out << 'L'; 4736 mangle(D); 4737 Out << 'E'; 4738 break; 4739 } 4740 } 4741 4742 Out << 'X'; 4743 mangleExpression(E); 4744 Out << 'E'; 4745 break; 4746 } 4747 case TemplateArgument::Integral: 4748 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral()); 4749 break; 4750 case TemplateArgument::Declaration: { 4751 // <expr-primary> ::= L <mangled-name> E # external name 4752 // Clang produces AST's where pointer-to-member-function expressions 4753 // and pointer-to-function expressions are represented as a declaration not 4754 // an expression. We compensate for it here to produce the correct mangling. 4755 ValueDecl *D = A.getAsDecl(); 4756 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType(); 4757 if (compensateMangling) { 4758 Out << 'X'; 4759 mangleOperatorName(OO_Amp, 1); 4760 } 4761 4762 Out << 'L'; 4763 // References to external entities use the mangled name; if the name would 4764 // not normally be mangled then mangle it as unqualified. 4765 mangle(D); 4766 Out << 'E'; 4767 4768 if (compensateMangling) 4769 Out << 'E'; 4770 4771 break; 4772 } 4773 case TemplateArgument::NullPtr: { 4774 // <expr-primary> ::= L <type> 0 E 4775 Out << 'L'; 4776 mangleType(A.getNullPtrType()); 4777 Out << "0E"; 4778 break; 4779 } 4780 case TemplateArgument::Pack: { 4781 // <template-arg> ::= J <template-arg>* E 4782 Out << 'J'; 4783 for (const auto &P : A.pack_elements()) 4784 mangleTemplateArg(P); 4785 Out << 'E'; 4786 } 4787 } 4788 } 4789 4790 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) { 4791 // <template-param> ::= T_ # first template parameter 4792 // ::= T <parameter-2 non-negative number> _ 4793 // ::= TL <L-1 non-negative number> __ 4794 // ::= TL <L-1 non-negative number> _ 4795 // <parameter-2 non-negative number> _ 4796 // 4797 // The latter two manglings are from a proposal here: 4798 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117 4799 Out << 'T'; 4800 if (Depth != 0) 4801 Out << 'L' << (Depth - 1) << '_'; 4802 if (Index != 0) 4803 Out << (Index - 1); 4804 Out << '_'; 4805 } 4806 4807 void CXXNameMangler::mangleSeqID(unsigned SeqID) { 4808 if (SeqID == 1) 4809 Out << '0'; 4810 else if (SeqID > 1) { 4811 SeqID--; 4812 4813 // <seq-id> is encoded in base-36, using digits and upper case letters. 4814 char Buffer[7]; // log(2**32) / log(36) ~= 7 4815 MutableArrayRef<char> BufferRef(Buffer); 4816 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin(); 4817 4818 for (; SeqID != 0; SeqID /= 36) { 4819 unsigned C = SeqID % 36; 4820 *I++ = (C < 10 ? '0' + C : 'A' + C - 10); 4821 } 4822 4823 Out.write(I.base(), I - BufferRef.rbegin()); 4824 } 4825 Out << '_'; 4826 } 4827 4828 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) { 4829 bool result = mangleSubstitution(tname); 4830 assert(result && "no existing substitution for template name"); 4831 (void) result; 4832 } 4833 4834 // <substitution> ::= S <seq-id> _ 4835 // ::= S_ 4836 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) { 4837 // Try one of the standard substitutions first. 4838 if (mangleStandardSubstitution(ND)) 4839 return true; 4840 4841 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 4842 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND)); 4843 } 4844 4845 /// Determine whether the given type has any qualifiers that are relevant for 4846 /// substitutions. 4847 static bool hasMangledSubstitutionQualifiers(QualType T) { 4848 Qualifiers Qs = T.getQualifiers(); 4849 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned(); 4850 } 4851 4852 bool CXXNameMangler::mangleSubstitution(QualType T) { 4853 if (!hasMangledSubstitutionQualifiers(T)) { 4854 if (const RecordType *RT = T->getAs<RecordType>()) 4855 return mangleSubstitution(RT->getDecl()); 4856 } 4857 4858 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 4859 4860 return mangleSubstitution(TypePtr); 4861 } 4862 4863 bool CXXNameMangler::mangleSubstitution(TemplateName Template) { 4864 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 4865 return mangleSubstitution(TD); 4866 4867 Template = Context.getASTContext().getCanonicalTemplateName(Template); 4868 return mangleSubstitution( 4869 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 4870 } 4871 4872 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) { 4873 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr); 4874 if (I == Substitutions.end()) 4875 return false; 4876 4877 unsigned SeqID = I->second; 4878 Out << 'S'; 4879 mangleSeqID(SeqID); 4880 4881 return true; 4882 } 4883 4884 static bool isCharType(QualType T) { 4885 if (T.isNull()) 4886 return false; 4887 4888 return T->isSpecificBuiltinType(BuiltinType::Char_S) || 4889 T->isSpecificBuiltinType(BuiltinType::Char_U); 4890 } 4891 4892 /// Returns whether a given type is a template specialization of a given name 4893 /// with a single argument of type char. 4894 static bool isCharSpecialization(QualType T, const char *Name) { 4895 if (T.isNull()) 4896 return false; 4897 4898 const RecordType *RT = T->getAs<RecordType>(); 4899 if (!RT) 4900 return false; 4901 4902 const ClassTemplateSpecializationDecl *SD = 4903 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 4904 if (!SD) 4905 return false; 4906 4907 if (!isStdNamespace(getEffectiveDeclContext(SD))) 4908 return false; 4909 4910 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 4911 if (TemplateArgs.size() != 1) 4912 return false; 4913 4914 if (!isCharType(TemplateArgs[0].getAsType())) 4915 return false; 4916 4917 return SD->getIdentifier()->getName() == Name; 4918 } 4919 4920 template <std::size_t StrLen> 4921 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD, 4922 const char (&Str)[StrLen]) { 4923 if (!SD->getIdentifier()->isStr(Str)) 4924 return false; 4925 4926 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 4927 if (TemplateArgs.size() != 2) 4928 return false; 4929 4930 if (!isCharType(TemplateArgs[0].getAsType())) 4931 return false; 4932 4933 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 4934 return false; 4935 4936 return true; 4937 } 4938 4939 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) { 4940 // <substitution> ::= St # ::std:: 4941 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 4942 if (isStd(NS)) { 4943 Out << "St"; 4944 return true; 4945 } 4946 } 4947 4948 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) { 4949 if (!isStdNamespace(getEffectiveDeclContext(TD))) 4950 return false; 4951 4952 // <substitution> ::= Sa # ::std::allocator 4953 if (TD->getIdentifier()->isStr("allocator")) { 4954 Out << "Sa"; 4955 return true; 4956 } 4957 4958 // <<substitution> ::= Sb # ::std::basic_string 4959 if (TD->getIdentifier()->isStr("basic_string")) { 4960 Out << "Sb"; 4961 return true; 4962 } 4963 } 4964 4965 if (const ClassTemplateSpecializationDecl *SD = 4966 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 4967 if (!isStdNamespace(getEffectiveDeclContext(SD))) 4968 return false; 4969 4970 // <substitution> ::= Ss # ::std::basic_string<char, 4971 // ::std::char_traits<char>, 4972 // ::std::allocator<char> > 4973 if (SD->getIdentifier()->isStr("basic_string")) { 4974 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 4975 4976 if (TemplateArgs.size() != 3) 4977 return false; 4978 4979 if (!isCharType(TemplateArgs[0].getAsType())) 4980 return false; 4981 4982 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 4983 return false; 4984 4985 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator")) 4986 return false; 4987 4988 Out << "Ss"; 4989 return true; 4990 } 4991 4992 // <substitution> ::= Si # ::std::basic_istream<char, 4993 // ::std::char_traits<char> > 4994 if (isStreamCharSpecialization(SD, "basic_istream")) { 4995 Out << "Si"; 4996 return true; 4997 } 4998 4999 // <substitution> ::= So # ::std::basic_ostream<char, 5000 // ::std::char_traits<char> > 5001 if (isStreamCharSpecialization(SD, "basic_ostream")) { 5002 Out << "So"; 5003 return true; 5004 } 5005 5006 // <substitution> ::= Sd # ::std::basic_iostream<char, 5007 // ::std::char_traits<char> > 5008 if (isStreamCharSpecialization(SD, "basic_iostream")) { 5009 Out << "Sd"; 5010 return true; 5011 } 5012 } 5013 return false; 5014 } 5015 5016 void CXXNameMangler::addSubstitution(QualType T) { 5017 if (!hasMangledSubstitutionQualifiers(T)) { 5018 if (const RecordType *RT = T->getAs<RecordType>()) { 5019 addSubstitution(RT->getDecl()); 5020 return; 5021 } 5022 } 5023 5024 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 5025 addSubstitution(TypePtr); 5026 } 5027 5028 void CXXNameMangler::addSubstitution(TemplateName Template) { 5029 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 5030 return addSubstitution(TD); 5031 5032 Template = Context.getASTContext().getCanonicalTemplateName(Template); 5033 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 5034 } 5035 5036 void CXXNameMangler::addSubstitution(uintptr_t Ptr) { 5037 assert(!Substitutions.count(Ptr) && "Substitution already exists!"); 5038 Substitutions[Ptr] = SeqID++; 5039 } 5040 5041 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) { 5042 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!"); 5043 if (Other->SeqID > SeqID) { 5044 Substitutions.swap(Other->Substitutions); 5045 SeqID = Other->SeqID; 5046 } 5047 } 5048 5049 CXXNameMangler::AbiTagList 5050 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) { 5051 // When derived abi tags are disabled there is no need to make any list. 5052 if (DisableDerivedAbiTags) 5053 return AbiTagList(); 5054 5055 llvm::raw_null_ostream NullOutStream; 5056 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream); 5057 TrackReturnTypeTags.disableDerivedAbiTags(); 5058 5059 const FunctionProtoType *Proto = 5060 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>()); 5061 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push(); 5062 TrackReturnTypeTags.FunctionTypeDepth.enterResultType(); 5063 TrackReturnTypeTags.mangleType(Proto->getReturnType()); 5064 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType(); 5065 TrackReturnTypeTags.FunctionTypeDepth.pop(saved); 5066 5067 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 5068 } 5069 5070 CXXNameMangler::AbiTagList 5071 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) { 5072 // When derived abi tags are disabled there is no need to make any list. 5073 if (DisableDerivedAbiTags) 5074 return AbiTagList(); 5075 5076 llvm::raw_null_ostream NullOutStream; 5077 CXXNameMangler TrackVariableType(*this, NullOutStream); 5078 TrackVariableType.disableDerivedAbiTags(); 5079 5080 TrackVariableType.mangleType(VD->getType()); 5081 5082 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 5083 } 5084 5085 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C, 5086 const VarDecl *VD) { 5087 llvm::raw_null_ostream NullOutStream; 5088 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true); 5089 TrackAbiTags.mangle(VD); 5090 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size(); 5091 } 5092 5093 // 5094 5095 /// Mangles the name of the declaration D and emits that name to the given 5096 /// output stream. 5097 /// 5098 /// If the declaration D requires a mangled name, this routine will emit that 5099 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged 5100 /// and this routine will return false. In this case, the caller should just 5101 /// emit the identifier of the declaration (\c D->getIdentifier()) as its 5102 /// name. 5103 void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD, 5104 raw_ostream &Out) { 5105 const NamedDecl *D = cast<NamedDecl>(GD.getDecl()); 5106 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) && 5107 "Invalid mangleName() call, argument is not a variable or function!"); 5108 5109 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 5110 getASTContext().getSourceManager(), 5111 "Mangling declaration"); 5112 5113 if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) { 5114 auto Type = GD.getCtorType(); 5115 CXXNameMangler Mangler(*this, Out, CD, Type); 5116 return Mangler.mangle(GlobalDecl(CD, Type)); 5117 } 5118 5119 if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) { 5120 auto Type = GD.getDtorType(); 5121 CXXNameMangler Mangler(*this, Out, DD, Type); 5122 return Mangler.mangle(GlobalDecl(DD, Type)); 5123 } 5124 5125 CXXNameMangler Mangler(*this, Out, D); 5126 Mangler.mangle(GD); 5127 } 5128 5129 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D, 5130 raw_ostream &Out) { 5131 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat); 5132 Mangler.mangle(GlobalDecl(D, Ctor_Comdat)); 5133 } 5134 5135 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D, 5136 raw_ostream &Out) { 5137 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat); 5138 Mangler.mangle(GlobalDecl(D, Dtor_Comdat)); 5139 } 5140 5141 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 5142 const ThunkInfo &Thunk, 5143 raw_ostream &Out) { 5144 // <special-name> ::= T <call-offset> <base encoding> 5145 // # base is the nominal target function of thunk 5146 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding> 5147 // # base is the nominal target function of thunk 5148 // # first call-offset is 'this' adjustment 5149 // # second call-offset is result adjustment 5150 5151 assert(!isa<CXXDestructorDecl>(MD) && 5152 "Use mangleCXXDtor for destructor decls!"); 5153 CXXNameMangler Mangler(*this, Out); 5154 Mangler.getStream() << "_ZT"; 5155 if (!Thunk.Return.isEmpty()) 5156 Mangler.getStream() << 'c'; 5157 5158 // Mangle the 'this' pointer adjustment. 5159 Mangler.mangleCallOffset(Thunk.This.NonVirtual, 5160 Thunk.This.Virtual.Itanium.VCallOffsetOffset); 5161 5162 // Mangle the return pointer adjustment if there is one. 5163 if (!Thunk.Return.isEmpty()) 5164 Mangler.mangleCallOffset(Thunk.Return.NonVirtual, 5165 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset); 5166 5167 Mangler.mangleFunctionEncoding(MD); 5168 } 5169 5170 void ItaniumMangleContextImpl::mangleCXXDtorThunk( 5171 const CXXDestructorDecl *DD, CXXDtorType Type, 5172 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) { 5173 // <special-name> ::= T <call-offset> <base encoding> 5174 // # base is the nominal target function of thunk 5175 CXXNameMangler Mangler(*this, Out, DD, Type); 5176 Mangler.getStream() << "_ZT"; 5177 5178 // Mangle the 'this' pointer adjustment. 5179 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 5180 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); 5181 5182 Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type)); 5183 } 5184 5185 /// Returns the mangled name for a guard variable for the passed in VarDecl. 5186 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D, 5187 raw_ostream &Out) { 5188 // <special-name> ::= GV <object name> # Guard variable for one-time 5189 // # initialization 5190 CXXNameMangler Mangler(*this, Out); 5191 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to 5192 // be a bug that is fixed in trunk. 5193 Mangler.getStream() << "_ZGV"; 5194 Mangler.mangleName(D); 5195 } 5196 5197 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD, 5198 raw_ostream &Out) { 5199 // These symbols are internal in the Itanium ABI, so the names don't matter. 5200 // Clang has traditionally used this symbol and allowed LLVM to adjust it to 5201 // avoid duplicate symbols. 5202 Out << "__cxx_global_var_init"; 5203 } 5204 5205 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 5206 raw_ostream &Out) { 5207 // Prefix the mangling of D with __dtor_. 5208 CXXNameMangler Mangler(*this, Out); 5209 Mangler.getStream() << "__dtor_"; 5210 if (shouldMangleDeclName(D)) 5211 Mangler.mangle(D); 5212 else 5213 Mangler.getStream() << D->getName(); 5214 } 5215 5216 void ItaniumMangleContextImpl::mangleSEHFilterExpression( 5217 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 5218 CXXNameMangler Mangler(*this, Out); 5219 Mangler.getStream() << "__filt_"; 5220 if (shouldMangleDeclName(EnclosingDecl)) 5221 Mangler.mangle(EnclosingDecl); 5222 else 5223 Mangler.getStream() << EnclosingDecl->getName(); 5224 } 5225 5226 void ItaniumMangleContextImpl::mangleSEHFinallyBlock( 5227 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 5228 CXXNameMangler Mangler(*this, Out); 5229 Mangler.getStream() << "__fin_"; 5230 if (shouldMangleDeclName(EnclosingDecl)) 5231 Mangler.mangle(EnclosingDecl); 5232 else 5233 Mangler.getStream() << EnclosingDecl->getName(); 5234 } 5235 5236 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D, 5237 raw_ostream &Out) { 5238 // <special-name> ::= TH <object name> 5239 CXXNameMangler Mangler(*this, Out); 5240 Mangler.getStream() << "_ZTH"; 5241 Mangler.mangleName(D); 5242 } 5243 5244 void 5245 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D, 5246 raw_ostream &Out) { 5247 // <special-name> ::= TW <object name> 5248 CXXNameMangler Mangler(*this, Out); 5249 Mangler.getStream() << "_ZTW"; 5250 Mangler.mangleName(D); 5251 } 5252 5253 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D, 5254 unsigned ManglingNumber, 5255 raw_ostream &Out) { 5256 // We match the GCC mangling here. 5257 // <special-name> ::= GR <object name> 5258 CXXNameMangler Mangler(*this, Out); 5259 Mangler.getStream() << "_ZGR"; 5260 Mangler.mangleName(D); 5261 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!"); 5262 Mangler.mangleSeqID(ManglingNumber - 1); 5263 } 5264 5265 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD, 5266 raw_ostream &Out) { 5267 // <special-name> ::= TV <type> # virtual table 5268 CXXNameMangler Mangler(*this, Out); 5269 Mangler.getStream() << "_ZTV"; 5270 Mangler.mangleNameOrStandardSubstitution(RD); 5271 } 5272 5273 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD, 5274 raw_ostream &Out) { 5275 // <special-name> ::= TT <type> # VTT structure 5276 CXXNameMangler Mangler(*this, Out); 5277 Mangler.getStream() << "_ZTT"; 5278 Mangler.mangleNameOrStandardSubstitution(RD); 5279 } 5280 5281 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD, 5282 int64_t Offset, 5283 const CXXRecordDecl *Type, 5284 raw_ostream &Out) { 5285 // <special-name> ::= TC <type> <offset number> _ <base type> 5286 CXXNameMangler Mangler(*this, Out); 5287 Mangler.getStream() << "_ZTC"; 5288 Mangler.mangleNameOrStandardSubstitution(RD); 5289 Mangler.getStream() << Offset; 5290 Mangler.getStream() << '_'; 5291 Mangler.mangleNameOrStandardSubstitution(Type); 5292 } 5293 5294 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) { 5295 // <special-name> ::= TI <type> # typeinfo structure 5296 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers"); 5297 CXXNameMangler Mangler(*this, Out); 5298 Mangler.getStream() << "_ZTI"; 5299 Mangler.mangleType(Ty); 5300 } 5301 5302 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty, 5303 raw_ostream &Out) { 5304 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string) 5305 CXXNameMangler Mangler(*this, Out); 5306 Mangler.getStream() << "_ZTS"; 5307 Mangler.mangleType(Ty); 5308 } 5309 5310 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) { 5311 mangleCXXRTTIName(Ty, Out); 5312 } 5313 5314 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) { 5315 llvm_unreachable("Can't mangle string literals"); 5316 } 5317 5318 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda, 5319 raw_ostream &Out) { 5320 CXXNameMangler Mangler(*this, Out); 5321 Mangler.mangleLambdaSig(Lambda); 5322 } 5323 5324 ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context, 5325 DiagnosticsEngine &Diags, 5326 bool IsUniqueNameMangler) { 5327 return new ItaniumMangleContextImpl(Context, Diags, IsUniqueNameMangler); 5328 } 5329