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