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