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 QualType Desugared 2582 = T.getSingleStepDesugaredType(Context.getASTContext()); 2583 if (Desugared == T) 2584 break; 2585 2586 T = Desugared; 2587 } while (true); 2588 } 2589 SplitQualType split = T.split(); 2590 Qualifiers quals = split.Quals; 2591 const Type *ty = split.Ty; 2592 2593 bool isSubstitutable = 2594 isTypeSubstitutable(quals, ty, Context.getASTContext()); 2595 if (isSubstitutable && mangleSubstitution(T)) 2596 return; 2597 2598 // If we're mangling a qualified array type, push the qualifiers to 2599 // the element type. 2600 if (quals && isa<ArrayType>(T)) { 2601 ty = Context.getASTContext().getAsArrayType(T); 2602 quals = Qualifiers(); 2603 2604 // Note that we don't update T: we want to add the 2605 // substitution at the original type. 2606 } 2607 2608 if (quals || ty->isDependentAddressSpaceType()) { 2609 if (const DependentAddressSpaceType *DAST = 2610 dyn_cast<DependentAddressSpaceType>(ty)) { 2611 SplitQualType splitDAST = DAST->getPointeeType().split(); 2612 mangleQualifiers(splitDAST.Quals, DAST); 2613 mangleType(QualType(splitDAST.Ty, 0)); 2614 } else { 2615 mangleQualifiers(quals); 2616 2617 // Recurse: even if the qualified type isn't yet substitutable, 2618 // the unqualified type might be. 2619 mangleType(QualType(ty, 0)); 2620 } 2621 } else { 2622 switch (ty->getTypeClass()) { 2623 #define ABSTRACT_TYPE(CLASS, PARENT) 2624 #define NON_CANONICAL_TYPE(CLASS, PARENT) \ 2625 case Type::CLASS: \ 2626 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \ 2627 return; 2628 #define TYPE(CLASS, PARENT) \ 2629 case Type::CLASS: \ 2630 mangleType(static_cast<const CLASS##Type*>(ty)); \ 2631 break; 2632 #include "clang/AST/TypeNodes.inc" 2633 } 2634 } 2635 2636 // Add the substitution. 2637 if (isSubstitutable) 2638 addSubstitution(T); 2639 } 2640 2641 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) { 2642 if (!mangleStandardSubstitution(ND)) 2643 mangleName(ND); 2644 } 2645 2646 void CXXNameMangler::mangleType(const BuiltinType *T) { 2647 // <type> ::= <builtin-type> 2648 // <builtin-type> ::= v # void 2649 // ::= w # wchar_t 2650 // ::= b # bool 2651 // ::= c # char 2652 // ::= a # signed char 2653 // ::= h # unsigned char 2654 // ::= s # short 2655 // ::= t # unsigned short 2656 // ::= i # int 2657 // ::= j # unsigned int 2658 // ::= l # long 2659 // ::= m # unsigned long 2660 // ::= x # long long, __int64 2661 // ::= y # unsigned long long, __int64 2662 // ::= n # __int128 2663 // ::= o # unsigned __int128 2664 // ::= f # float 2665 // ::= d # double 2666 // ::= e # long double, __float80 2667 // ::= g # __float128 2668 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits) 2669 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits) 2670 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits) 2671 // ::= Dh # IEEE 754r half-precision floating point (16 bits) 2672 // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits); 2673 // ::= Di # char32_t 2674 // ::= Ds # char16_t 2675 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr)) 2676 // ::= u <source-name> # vendor extended type 2677 std::string type_name; 2678 switch (T->getKind()) { 2679 case BuiltinType::Void: 2680 Out << 'v'; 2681 break; 2682 case BuiltinType::Bool: 2683 Out << 'b'; 2684 break; 2685 case BuiltinType::Char_U: 2686 case BuiltinType::Char_S: 2687 Out << 'c'; 2688 break; 2689 case BuiltinType::UChar: 2690 Out << 'h'; 2691 break; 2692 case BuiltinType::UShort: 2693 Out << 't'; 2694 break; 2695 case BuiltinType::UInt: 2696 Out << 'j'; 2697 break; 2698 case BuiltinType::ULong: 2699 Out << 'm'; 2700 break; 2701 case BuiltinType::ULongLong: 2702 Out << 'y'; 2703 break; 2704 case BuiltinType::UInt128: 2705 Out << 'o'; 2706 break; 2707 case BuiltinType::SChar: 2708 Out << 'a'; 2709 break; 2710 case BuiltinType::WChar_S: 2711 case BuiltinType::WChar_U: 2712 Out << 'w'; 2713 break; 2714 case BuiltinType::Char8: 2715 Out << "Du"; 2716 break; 2717 case BuiltinType::Char16: 2718 Out << "Ds"; 2719 break; 2720 case BuiltinType::Char32: 2721 Out << "Di"; 2722 break; 2723 case BuiltinType::Short: 2724 Out << 's'; 2725 break; 2726 case BuiltinType::Int: 2727 Out << 'i'; 2728 break; 2729 case BuiltinType::Long: 2730 Out << 'l'; 2731 break; 2732 case BuiltinType::LongLong: 2733 Out << 'x'; 2734 break; 2735 case BuiltinType::Int128: 2736 Out << 'n'; 2737 break; 2738 case BuiltinType::Float16: 2739 Out << "DF16_"; 2740 break; 2741 case BuiltinType::ShortAccum: 2742 case BuiltinType::Accum: 2743 case BuiltinType::LongAccum: 2744 case BuiltinType::UShortAccum: 2745 case BuiltinType::UAccum: 2746 case BuiltinType::ULongAccum: 2747 case BuiltinType::ShortFract: 2748 case BuiltinType::Fract: 2749 case BuiltinType::LongFract: 2750 case BuiltinType::UShortFract: 2751 case BuiltinType::UFract: 2752 case BuiltinType::ULongFract: 2753 case BuiltinType::SatShortAccum: 2754 case BuiltinType::SatAccum: 2755 case BuiltinType::SatLongAccum: 2756 case BuiltinType::SatUShortAccum: 2757 case BuiltinType::SatUAccum: 2758 case BuiltinType::SatULongAccum: 2759 case BuiltinType::SatShortFract: 2760 case BuiltinType::SatFract: 2761 case BuiltinType::SatLongFract: 2762 case BuiltinType::SatUShortFract: 2763 case BuiltinType::SatUFract: 2764 case BuiltinType::SatULongFract: 2765 llvm_unreachable("Fixed point types are disabled for c++"); 2766 case BuiltinType::Half: 2767 Out << "Dh"; 2768 break; 2769 case BuiltinType::Float: 2770 Out << 'f'; 2771 break; 2772 case BuiltinType::Double: 2773 Out << 'd'; 2774 break; 2775 case BuiltinType::LongDouble: { 2776 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP && 2777 getASTContext().getLangOpts().OpenMPIsDevice 2778 ? getASTContext().getAuxTargetInfo() 2779 : &getASTContext().getTargetInfo(); 2780 Out << TI->getLongDoubleMangling(); 2781 break; 2782 } 2783 case BuiltinType::Float128: { 2784 const TargetInfo *TI = getASTContext().getLangOpts().OpenMP && 2785 getASTContext().getLangOpts().OpenMPIsDevice 2786 ? getASTContext().getAuxTargetInfo() 2787 : &getASTContext().getTargetInfo(); 2788 Out << TI->getFloat128Mangling(); 2789 break; 2790 } 2791 case BuiltinType::BFloat16: { 2792 const TargetInfo *TI = &getASTContext().getTargetInfo(); 2793 Out << TI->getBFloat16Mangling(); 2794 break; 2795 } 2796 case BuiltinType::NullPtr: 2797 Out << "Dn"; 2798 break; 2799 2800 #define BUILTIN_TYPE(Id, SingletonId) 2801 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 2802 case BuiltinType::Id: 2803 #include "clang/AST/BuiltinTypes.def" 2804 case BuiltinType::Dependent: 2805 if (!NullOut) 2806 llvm_unreachable("mangling a placeholder type"); 2807 break; 2808 case BuiltinType::ObjCId: 2809 Out << "11objc_object"; 2810 break; 2811 case BuiltinType::ObjCClass: 2812 Out << "10objc_class"; 2813 break; 2814 case BuiltinType::ObjCSel: 2815 Out << "13objc_selector"; 2816 break; 2817 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 2818 case BuiltinType::Id: \ 2819 type_name = "ocl_" #ImgType "_" #Suffix; \ 2820 Out << type_name.size() << type_name; \ 2821 break; 2822 #include "clang/Basic/OpenCLImageTypes.def" 2823 case BuiltinType::OCLSampler: 2824 Out << "11ocl_sampler"; 2825 break; 2826 case BuiltinType::OCLEvent: 2827 Out << "9ocl_event"; 2828 break; 2829 case BuiltinType::OCLClkEvent: 2830 Out << "12ocl_clkevent"; 2831 break; 2832 case BuiltinType::OCLQueue: 2833 Out << "9ocl_queue"; 2834 break; 2835 case BuiltinType::OCLReserveID: 2836 Out << "13ocl_reserveid"; 2837 break; 2838 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 2839 case BuiltinType::Id: \ 2840 type_name = "ocl_" #ExtType; \ 2841 Out << type_name.size() << type_name; \ 2842 break; 2843 #include "clang/Basic/OpenCLExtensionTypes.def" 2844 // The SVE types are effectively target-specific. The mangling scheme 2845 // is defined in the appendices to the Procedure Call Standard for the 2846 // Arm Architecture. 2847 #define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \ 2848 ElBits, IsSigned, IsFP, IsBF) \ 2849 case BuiltinType::Id: \ 2850 type_name = MangledName; \ 2851 Out << (type_name == InternalName ? "u" : "") << type_name.size() \ 2852 << type_name; \ 2853 break; 2854 #define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \ 2855 case BuiltinType::Id: \ 2856 type_name = MangledName; \ 2857 Out << (type_name == InternalName ? "u" : "") << type_name.size() \ 2858 << type_name; \ 2859 break; 2860 #include "clang/Basic/AArch64SVEACLETypes.def" 2861 #define PPC_VECTOR_TYPE(Name, Id, Size) \ 2862 case BuiltinType::Id: \ 2863 type_name = #Name; \ 2864 Out << 'u' << type_name.size() << type_name; \ 2865 break; 2866 #include "clang/Basic/PPCTypes.def" 2867 } 2868 } 2869 2870 StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) { 2871 switch (CC) { 2872 case CC_C: 2873 return ""; 2874 2875 case CC_X86VectorCall: 2876 case CC_X86Pascal: 2877 case CC_X86RegCall: 2878 case CC_AAPCS: 2879 case CC_AAPCS_VFP: 2880 case CC_AArch64VectorCall: 2881 case CC_IntelOclBicc: 2882 case CC_SpirFunction: 2883 case CC_OpenCLKernel: 2884 case CC_PreserveMost: 2885 case CC_PreserveAll: 2886 // FIXME: we should be mangling all of the above. 2887 return ""; 2888 2889 case CC_X86ThisCall: 2890 // FIXME: To match mingw GCC, thiscall should only be mangled in when it is 2891 // used explicitly. At this point, we don't have that much information in 2892 // the AST, since clang tends to bake the convention into the canonical 2893 // function type. thiscall only rarely used explicitly, so don't mangle it 2894 // for now. 2895 return ""; 2896 2897 case CC_X86StdCall: 2898 return "stdcall"; 2899 case CC_X86FastCall: 2900 return "fastcall"; 2901 case CC_X86_64SysV: 2902 return "sysv_abi"; 2903 case CC_Win64: 2904 return "ms_abi"; 2905 case CC_Swift: 2906 return "swiftcall"; 2907 } 2908 llvm_unreachable("bad calling convention"); 2909 } 2910 2911 void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) { 2912 // Fast path. 2913 if (T->getExtInfo() == FunctionType::ExtInfo()) 2914 return; 2915 2916 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 2917 // This will get more complicated in the future if we mangle other 2918 // things here; but for now, since we mangle ns_returns_retained as 2919 // a qualifier on the result type, we can get away with this: 2920 StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC()); 2921 if (!CCQualifier.empty()) 2922 mangleVendorQualifier(CCQualifier); 2923 2924 // FIXME: regparm 2925 // FIXME: noreturn 2926 } 2927 2928 void 2929 CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) { 2930 // Vendor-specific qualifiers are emitted in reverse alphabetical order. 2931 2932 // Note that these are *not* substitution candidates. Demanglers might 2933 // have trouble with this if the parameter type is fully substituted. 2934 2935 switch (PI.getABI()) { 2936 case ParameterABI::Ordinary: 2937 break; 2938 2939 // All of these start with "swift", so they come before "ns_consumed". 2940 case ParameterABI::SwiftContext: 2941 case ParameterABI::SwiftErrorResult: 2942 case ParameterABI::SwiftIndirectResult: 2943 mangleVendorQualifier(getParameterABISpelling(PI.getABI())); 2944 break; 2945 } 2946 2947 if (PI.isConsumed()) 2948 mangleVendorQualifier("ns_consumed"); 2949 2950 if (PI.isNoEscape()) 2951 mangleVendorQualifier("noescape"); 2952 } 2953 2954 // <type> ::= <function-type> 2955 // <function-type> ::= [<CV-qualifiers>] F [Y] 2956 // <bare-function-type> [<ref-qualifier>] E 2957 void CXXNameMangler::mangleType(const FunctionProtoType *T) { 2958 mangleExtFunctionInfo(T); 2959 2960 // Mangle CV-qualifiers, if present. These are 'this' qualifiers, 2961 // e.g. "const" in "int (A::*)() const". 2962 mangleQualifiers(T->getMethodQuals()); 2963 2964 // Mangle instantiation-dependent exception-specification, if present, 2965 // per cxx-abi-dev proposal on 2016-10-11. 2966 if (T->hasInstantiationDependentExceptionSpec()) { 2967 if (isComputedNoexcept(T->getExceptionSpecType())) { 2968 Out << "DO"; 2969 mangleExpression(T->getNoexceptExpr()); 2970 Out << "E"; 2971 } else { 2972 assert(T->getExceptionSpecType() == EST_Dynamic); 2973 Out << "Dw"; 2974 for (auto ExceptTy : T->exceptions()) 2975 mangleType(ExceptTy); 2976 Out << "E"; 2977 } 2978 } else if (T->isNothrow()) { 2979 Out << "Do"; 2980 } 2981 2982 Out << 'F'; 2983 2984 // FIXME: We don't have enough information in the AST to produce the 'Y' 2985 // encoding for extern "C" function types. 2986 mangleBareFunctionType(T, /*MangleReturnType=*/true); 2987 2988 // Mangle the ref-qualifier, if present. 2989 mangleRefQualifier(T->getRefQualifier()); 2990 2991 Out << 'E'; 2992 } 2993 2994 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) { 2995 // Function types without prototypes can arise when mangling a function type 2996 // within an overloadable function in C. We mangle these as the absence of any 2997 // parameter types (not even an empty parameter list). 2998 Out << 'F'; 2999 3000 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 3001 3002 FunctionTypeDepth.enterResultType(); 3003 mangleType(T->getReturnType()); 3004 FunctionTypeDepth.leaveResultType(); 3005 3006 FunctionTypeDepth.pop(saved); 3007 Out << 'E'; 3008 } 3009 3010 void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto, 3011 bool MangleReturnType, 3012 const FunctionDecl *FD) { 3013 // Record that we're in a function type. See mangleFunctionParam 3014 // for details on what we're trying to achieve here. 3015 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 3016 3017 // <bare-function-type> ::= <signature type>+ 3018 if (MangleReturnType) { 3019 FunctionTypeDepth.enterResultType(); 3020 3021 // Mangle ns_returns_retained as an order-sensitive qualifier here. 3022 if (Proto->getExtInfo().getProducesResult() && FD == nullptr) 3023 mangleVendorQualifier("ns_returns_retained"); 3024 3025 // Mangle the return type without any direct ARC ownership qualifiers. 3026 QualType ReturnTy = Proto->getReturnType(); 3027 if (ReturnTy.getObjCLifetime()) { 3028 auto SplitReturnTy = ReturnTy.split(); 3029 SplitReturnTy.Quals.removeObjCLifetime(); 3030 ReturnTy = getASTContext().getQualifiedType(SplitReturnTy); 3031 } 3032 mangleType(ReturnTy); 3033 3034 FunctionTypeDepth.leaveResultType(); 3035 } 3036 3037 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) { 3038 // <builtin-type> ::= v # void 3039 Out << 'v'; 3040 3041 FunctionTypeDepth.pop(saved); 3042 return; 3043 } 3044 3045 assert(!FD || FD->getNumParams() == Proto->getNumParams()); 3046 for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) { 3047 // Mangle extended parameter info as order-sensitive qualifiers here. 3048 if (Proto->hasExtParameterInfos() && FD == nullptr) { 3049 mangleExtParameterInfo(Proto->getExtParameterInfo(I)); 3050 } 3051 3052 // Mangle the type. 3053 QualType ParamTy = Proto->getParamType(I); 3054 mangleType(Context.getASTContext().getSignatureParameterType(ParamTy)); 3055 3056 if (FD) { 3057 if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) { 3058 // Attr can only take 1 character, so we can hardcode the length below. 3059 assert(Attr->getType() <= 9 && Attr->getType() >= 0); 3060 if (Attr->isDynamic()) 3061 Out << "U25pass_dynamic_object_size" << Attr->getType(); 3062 else 3063 Out << "U17pass_object_size" << Attr->getType(); 3064 } 3065 } 3066 } 3067 3068 FunctionTypeDepth.pop(saved); 3069 3070 // <builtin-type> ::= z # ellipsis 3071 if (Proto->isVariadic()) 3072 Out << 'z'; 3073 } 3074 3075 // <type> ::= <class-enum-type> 3076 // <class-enum-type> ::= <name> 3077 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) { 3078 mangleName(T->getDecl()); 3079 } 3080 3081 // <type> ::= <class-enum-type> 3082 // <class-enum-type> ::= <name> 3083 void CXXNameMangler::mangleType(const EnumType *T) { 3084 mangleType(static_cast<const TagType*>(T)); 3085 } 3086 void CXXNameMangler::mangleType(const RecordType *T) { 3087 mangleType(static_cast<const TagType*>(T)); 3088 } 3089 void CXXNameMangler::mangleType(const TagType *T) { 3090 mangleName(T->getDecl()); 3091 } 3092 3093 // <type> ::= <array-type> 3094 // <array-type> ::= A <positive dimension number> _ <element type> 3095 // ::= A [<dimension expression>] _ <element type> 3096 void CXXNameMangler::mangleType(const ConstantArrayType *T) { 3097 Out << 'A' << T->getSize() << '_'; 3098 mangleType(T->getElementType()); 3099 } 3100 void CXXNameMangler::mangleType(const VariableArrayType *T) { 3101 Out << 'A'; 3102 // decayed vla types (size 0) will just be skipped. 3103 if (T->getSizeExpr()) 3104 mangleExpression(T->getSizeExpr()); 3105 Out << '_'; 3106 mangleType(T->getElementType()); 3107 } 3108 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) { 3109 Out << 'A'; 3110 mangleExpression(T->getSizeExpr()); 3111 Out << '_'; 3112 mangleType(T->getElementType()); 3113 } 3114 void CXXNameMangler::mangleType(const IncompleteArrayType *T) { 3115 Out << "A_"; 3116 mangleType(T->getElementType()); 3117 } 3118 3119 // <type> ::= <pointer-to-member-type> 3120 // <pointer-to-member-type> ::= M <class type> <member type> 3121 void CXXNameMangler::mangleType(const MemberPointerType *T) { 3122 Out << 'M'; 3123 mangleType(QualType(T->getClass(), 0)); 3124 QualType PointeeType = T->getPointeeType(); 3125 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) { 3126 mangleType(FPT); 3127 3128 // Itanium C++ ABI 5.1.8: 3129 // 3130 // The type of a non-static member function is considered to be different, 3131 // for the purposes of substitution, from the type of a namespace-scope or 3132 // static member function whose type appears similar. The types of two 3133 // non-static member functions are considered to be different, for the 3134 // purposes of substitution, if the functions are members of different 3135 // classes. In other words, for the purposes of substitution, the class of 3136 // which the function is a member is considered part of the type of 3137 // function. 3138 3139 // Given that we already substitute member function pointers as a 3140 // whole, the net effect of this rule is just to unconditionally 3141 // suppress substitution on the function type in a member pointer. 3142 // We increment the SeqID here to emulate adding an entry to the 3143 // substitution table. 3144 ++SeqID; 3145 } else 3146 mangleType(PointeeType); 3147 } 3148 3149 // <type> ::= <template-param> 3150 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) { 3151 mangleTemplateParameter(T->getDepth(), T->getIndex()); 3152 } 3153 3154 // <type> ::= <template-param> 3155 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) { 3156 // FIXME: not clear how to mangle this! 3157 // template <class T...> class A { 3158 // template <class U...> void foo(T(*)(U) x...); 3159 // }; 3160 Out << "_SUBSTPACK_"; 3161 } 3162 3163 // <type> ::= P <type> # pointer-to 3164 void CXXNameMangler::mangleType(const PointerType *T) { 3165 Out << 'P'; 3166 mangleType(T->getPointeeType()); 3167 } 3168 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) { 3169 Out << 'P'; 3170 mangleType(T->getPointeeType()); 3171 } 3172 3173 // <type> ::= R <type> # reference-to 3174 void CXXNameMangler::mangleType(const LValueReferenceType *T) { 3175 Out << 'R'; 3176 mangleType(T->getPointeeType()); 3177 } 3178 3179 // <type> ::= O <type> # rvalue reference-to (C++0x) 3180 void CXXNameMangler::mangleType(const RValueReferenceType *T) { 3181 Out << 'O'; 3182 mangleType(T->getPointeeType()); 3183 } 3184 3185 // <type> ::= C <type> # complex pair (C 2000) 3186 void CXXNameMangler::mangleType(const ComplexType *T) { 3187 Out << 'C'; 3188 mangleType(T->getElementType()); 3189 } 3190 3191 // ARM's ABI for Neon vector types specifies that they should be mangled as 3192 // if they are structs (to match ARM's initial implementation). The 3193 // vector type must be one of the special types predefined by ARM. 3194 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) { 3195 QualType EltType = T->getElementType(); 3196 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3197 const char *EltName = nullptr; 3198 if (T->getVectorKind() == VectorType::NeonPolyVector) { 3199 switch (cast<BuiltinType>(EltType)->getKind()) { 3200 case BuiltinType::SChar: 3201 case BuiltinType::UChar: 3202 EltName = "poly8_t"; 3203 break; 3204 case BuiltinType::Short: 3205 case BuiltinType::UShort: 3206 EltName = "poly16_t"; 3207 break; 3208 case BuiltinType::LongLong: 3209 case BuiltinType::ULongLong: 3210 EltName = "poly64_t"; 3211 break; 3212 default: llvm_unreachable("unexpected Neon polynomial vector element type"); 3213 } 3214 } else { 3215 switch (cast<BuiltinType>(EltType)->getKind()) { 3216 case BuiltinType::SChar: EltName = "int8_t"; break; 3217 case BuiltinType::UChar: EltName = "uint8_t"; break; 3218 case BuiltinType::Short: EltName = "int16_t"; break; 3219 case BuiltinType::UShort: EltName = "uint16_t"; break; 3220 case BuiltinType::Int: EltName = "int32_t"; break; 3221 case BuiltinType::UInt: EltName = "uint32_t"; break; 3222 case BuiltinType::LongLong: EltName = "int64_t"; break; 3223 case BuiltinType::ULongLong: EltName = "uint64_t"; break; 3224 case BuiltinType::Double: EltName = "float64_t"; break; 3225 case BuiltinType::Float: EltName = "float32_t"; break; 3226 case BuiltinType::Half: EltName = "float16_t"; break; 3227 case BuiltinType::BFloat16: EltName = "bfloat16_t"; break; 3228 default: 3229 llvm_unreachable("unexpected Neon vector element type"); 3230 } 3231 } 3232 const char *BaseName = nullptr; 3233 unsigned BitSize = (T->getNumElements() * 3234 getASTContext().getTypeSize(EltType)); 3235 if (BitSize == 64) 3236 BaseName = "__simd64_"; 3237 else { 3238 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits"); 3239 BaseName = "__simd128_"; 3240 } 3241 Out << strlen(BaseName) + strlen(EltName); 3242 Out << BaseName << EltName; 3243 } 3244 3245 void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) { 3246 DiagnosticsEngine &Diags = Context.getDiags(); 3247 unsigned DiagID = Diags.getCustomDiagID( 3248 DiagnosticsEngine::Error, 3249 "cannot mangle this dependent neon vector type yet"); 3250 Diags.Report(T->getAttributeLoc(), DiagID); 3251 } 3252 3253 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) { 3254 switch (EltType->getKind()) { 3255 case BuiltinType::SChar: 3256 return "Int8"; 3257 case BuiltinType::Short: 3258 return "Int16"; 3259 case BuiltinType::Int: 3260 return "Int32"; 3261 case BuiltinType::Long: 3262 case BuiltinType::LongLong: 3263 return "Int64"; 3264 case BuiltinType::UChar: 3265 return "Uint8"; 3266 case BuiltinType::UShort: 3267 return "Uint16"; 3268 case BuiltinType::UInt: 3269 return "Uint32"; 3270 case BuiltinType::ULong: 3271 case BuiltinType::ULongLong: 3272 return "Uint64"; 3273 case BuiltinType::Half: 3274 return "Float16"; 3275 case BuiltinType::Float: 3276 return "Float32"; 3277 case BuiltinType::Double: 3278 return "Float64"; 3279 case BuiltinType::BFloat16: 3280 return "Bfloat16"; 3281 default: 3282 llvm_unreachable("Unexpected vector element base type"); 3283 } 3284 } 3285 3286 // AArch64's ABI for Neon vector types specifies that they should be mangled as 3287 // the equivalent internal name. The vector type must be one of the special 3288 // types predefined by ARM. 3289 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) { 3290 QualType EltType = T->getElementType(); 3291 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 3292 unsigned BitSize = 3293 (T->getNumElements() * getASTContext().getTypeSize(EltType)); 3294 (void)BitSize; // Silence warning. 3295 3296 assert((BitSize == 64 || BitSize == 128) && 3297 "Neon vector type not 64 or 128 bits"); 3298 3299 StringRef EltName; 3300 if (T->getVectorKind() == VectorType::NeonPolyVector) { 3301 switch (cast<BuiltinType>(EltType)->getKind()) { 3302 case BuiltinType::UChar: 3303 EltName = "Poly8"; 3304 break; 3305 case BuiltinType::UShort: 3306 EltName = "Poly16"; 3307 break; 3308 case BuiltinType::ULong: 3309 case BuiltinType::ULongLong: 3310 EltName = "Poly64"; 3311 break; 3312 default: 3313 llvm_unreachable("unexpected Neon polynomial vector element type"); 3314 } 3315 } else 3316 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType)); 3317 3318 std::string TypeName = 3319 ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str(); 3320 Out << TypeName.length() << TypeName; 3321 } 3322 void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) { 3323 DiagnosticsEngine &Diags = Context.getDiags(); 3324 unsigned DiagID = Diags.getCustomDiagID( 3325 DiagnosticsEngine::Error, 3326 "cannot mangle this dependent neon vector type yet"); 3327 Diags.Report(T->getAttributeLoc(), DiagID); 3328 } 3329 3330 // The AArch64 ACLE specifies that fixed-length SVE vector and predicate types 3331 // defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64 3332 // type as the sizeless variants. 3333 // 3334 // The mangling scheme for VLS types is implemented as a "pseudo" template: 3335 // 3336 // '__SVE_VLS<<type>, <vector length>>' 3337 // 3338 // Combining the existing SVE type and a specific vector length (in bits). 3339 // For example: 3340 // 3341 // typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512))); 3342 // 3343 // is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as: 3344 // 3345 // "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE" 3346 // 3347 // i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE 3348 // 3349 // The latest ACLE specification (00bet5) does not contain details of this 3350 // mangling scheme, it will be specified in the next revision. The mangling 3351 // scheme is otherwise defined in the appendices to the Procedure Call Standard 3352 // for the Arm Architecture, see 3353 // https://github.com/ARM-software/abi-aa/blob/master/aapcs64/aapcs64.rst#appendix-c-mangling 3354 void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) { 3355 assert((T->getVectorKind() == VectorType::SveFixedLengthDataVector || 3356 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) && 3357 "expected fixed-length SVE vector!"); 3358 3359 QualType EltType = T->getElementType(); 3360 assert(EltType->isBuiltinType() && 3361 "expected builtin type for fixed-length SVE vector!"); 3362 3363 StringRef TypeName; 3364 switch (cast<BuiltinType>(EltType)->getKind()) { 3365 case BuiltinType::SChar: 3366 TypeName = "__SVInt8_t"; 3367 break; 3368 case BuiltinType::UChar: { 3369 if (T->getVectorKind() == VectorType::SveFixedLengthDataVector) 3370 TypeName = "__SVUint8_t"; 3371 else 3372 TypeName = "__SVBool_t"; 3373 break; 3374 } 3375 case BuiltinType::Short: 3376 TypeName = "__SVInt16_t"; 3377 break; 3378 case BuiltinType::UShort: 3379 TypeName = "__SVUint16_t"; 3380 break; 3381 case BuiltinType::Int: 3382 TypeName = "__SVInt32_t"; 3383 break; 3384 case BuiltinType::UInt: 3385 TypeName = "__SVUint32_t"; 3386 break; 3387 case BuiltinType::Long: 3388 TypeName = "__SVInt64_t"; 3389 break; 3390 case BuiltinType::ULong: 3391 TypeName = "__SVUint64_t"; 3392 break; 3393 case BuiltinType::Half: 3394 TypeName = "__SVFloat16_t"; 3395 break; 3396 case BuiltinType::Float: 3397 TypeName = "__SVFloat32_t"; 3398 break; 3399 case BuiltinType::Double: 3400 TypeName = "__SVFloat64_t"; 3401 break; 3402 case BuiltinType::BFloat16: 3403 TypeName = "__SVBfloat16_t"; 3404 break; 3405 default: 3406 llvm_unreachable("unexpected element type for fixed-length SVE vector!"); 3407 } 3408 3409 unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width; 3410 3411 if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) 3412 VecSizeInBits *= 8; 3413 3414 Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj" 3415 << VecSizeInBits << "EE"; 3416 } 3417 3418 void CXXNameMangler::mangleAArch64FixedSveVectorType( 3419 const DependentVectorType *T) { 3420 DiagnosticsEngine &Diags = Context.getDiags(); 3421 unsigned DiagID = Diags.getCustomDiagID( 3422 DiagnosticsEngine::Error, 3423 "cannot mangle this dependent fixed-length SVE vector type yet"); 3424 Diags.Report(T->getAttributeLoc(), DiagID); 3425 } 3426 3427 // GNU extension: vector types 3428 // <type> ::= <vector-type> 3429 // <vector-type> ::= Dv <positive dimension number> _ 3430 // <extended element type> 3431 // ::= Dv [<dimension expression>] _ <element type> 3432 // <extended element type> ::= <element type> 3433 // ::= p # AltiVec vector pixel 3434 // ::= b # Altivec vector bool 3435 void CXXNameMangler::mangleType(const VectorType *T) { 3436 if ((T->getVectorKind() == VectorType::NeonVector || 3437 T->getVectorKind() == VectorType::NeonPolyVector)) { 3438 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 3439 llvm::Triple::ArchType Arch = 3440 getASTContext().getTargetInfo().getTriple().getArch(); 3441 if ((Arch == llvm::Triple::aarch64 || 3442 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin()) 3443 mangleAArch64NeonVectorType(T); 3444 else 3445 mangleNeonVectorType(T); 3446 return; 3447 } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector || 3448 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 3449 mangleAArch64FixedSveVectorType(T); 3450 return; 3451 } 3452 Out << "Dv" << T->getNumElements() << '_'; 3453 if (T->getVectorKind() == VectorType::AltiVecPixel) 3454 Out << 'p'; 3455 else if (T->getVectorKind() == VectorType::AltiVecBool) 3456 Out << 'b'; 3457 else 3458 mangleType(T->getElementType()); 3459 } 3460 3461 void CXXNameMangler::mangleType(const DependentVectorType *T) { 3462 if ((T->getVectorKind() == VectorType::NeonVector || 3463 T->getVectorKind() == VectorType::NeonPolyVector)) { 3464 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 3465 llvm::Triple::ArchType Arch = 3466 getASTContext().getTargetInfo().getTriple().getArch(); 3467 if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) && 3468 !Target.isOSDarwin()) 3469 mangleAArch64NeonVectorType(T); 3470 else 3471 mangleNeonVectorType(T); 3472 return; 3473 } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector || 3474 T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) { 3475 mangleAArch64FixedSveVectorType(T); 3476 return; 3477 } 3478 3479 Out << "Dv"; 3480 mangleExpression(T->getSizeExpr()); 3481 Out << '_'; 3482 if (T->getVectorKind() == VectorType::AltiVecPixel) 3483 Out << 'p'; 3484 else if (T->getVectorKind() == VectorType::AltiVecBool) 3485 Out << 'b'; 3486 else 3487 mangleType(T->getElementType()); 3488 } 3489 3490 void CXXNameMangler::mangleType(const ExtVectorType *T) { 3491 mangleType(static_cast<const VectorType*>(T)); 3492 } 3493 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) { 3494 Out << "Dv"; 3495 mangleExpression(T->getSizeExpr()); 3496 Out << '_'; 3497 mangleType(T->getElementType()); 3498 } 3499 3500 void CXXNameMangler::mangleType(const ConstantMatrixType *T) { 3501 // Mangle matrix types as a vendor extended type: 3502 // u<Len>matrix_typeI<Rows><Columns><element type>E 3503 3504 StringRef VendorQualifier = "matrix_type"; 3505 Out << "u" << VendorQualifier.size() << VendorQualifier; 3506 3507 Out << "I"; 3508 auto &ASTCtx = getASTContext(); 3509 unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType()); 3510 llvm::APSInt Rows(BitWidth); 3511 Rows = T->getNumRows(); 3512 mangleIntegerLiteral(ASTCtx.getSizeType(), Rows); 3513 llvm::APSInt Columns(BitWidth); 3514 Columns = T->getNumColumns(); 3515 mangleIntegerLiteral(ASTCtx.getSizeType(), Columns); 3516 mangleType(T->getElementType()); 3517 Out << "E"; 3518 } 3519 3520 void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) { 3521 // Mangle matrix types as a vendor extended type: 3522 // u<Len>matrix_typeI<row expr><column expr><element type>E 3523 StringRef VendorQualifier = "matrix_type"; 3524 Out << "u" << VendorQualifier.size() << VendorQualifier; 3525 3526 Out << "I"; 3527 mangleTemplateArg(T->getRowExpr(), false); 3528 mangleTemplateArg(T->getColumnExpr(), false); 3529 mangleType(T->getElementType()); 3530 Out << "E"; 3531 } 3532 3533 void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) { 3534 SplitQualType split = T->getPointeeType().split(); 3535 mangleQualifiers(split.Quals, T); 3536 mangleType(QualType(split.Ty, 0)); 3537 } 3538 3539 void CXXNameMangler::mangleType(const PackExpansionType *T) { 3540 // <type> ::= Dp <type> # pack expansion (C++0x) 3541 Out << "Dp"; 3542 mangleType(T->getPattern()); 3543 } 3544 3545 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) { 3546 mangleSourceName(T->getDecl()->getIdentifier()); 3547 } 3548 3549 void CXXNameMangler::mangleType(const ObjCObjectType *T) { 3550 // Treat __kindof as a vendor extended type qualifier. 3551 if (T->isKindOfType()) 3552 Out << "U8__kindof"; 3553 3554 if (!T->qual_empty()) { 3555 // Mangle protocol qualifiers. 3556 SmallString<64> QualStr; 3557 llvm::raw_svector_ostream QualOS(QualStr); 3558 QualOS << "objcproto"; 3559 for (const auto *I : T->quals()) { 3560 StringRef name = I->getName(); 3561 QualOS << name.size() << name; 3562 } 3563 Out << 'U' << QualStr.size() << QualStr; 3564 } 3565 3566 mangleType(T->getBaseType()); 3567 3568 if (T->isSpecialized()) { 3569 // Mangle type arguments as I <type>+ E 3570 Out << 'I'; 3571 for (auto typeArg : T->getTypeArgs()) 3572 mangleType(typeArg); 3573 Out << 'E'; 3574 } 3575 } 3576 3577 void CXXNameMangler::mangleType(const BlockPointerType *T) { 3578 Out << "U13block_pointer"; 3579 mangleType(T->getPointeeType()); 3580 } 3581 3582 void CXXNameMangler::mangleType(const InjectedClassNameType *T) { 3583 // Mangle injected class name types as if the user had written the 3584 // specialization out fully. It may not actually be possible to see 3585 // this mangling, though. 3586 mangleType(T->getInjectedSpecializationType()); 3587 } 3588 3589 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) { 3590 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) { 3591 mangleTemplateName(TD, T->getArgs(), T->getNumArgs()); 3592 } else { 3593 if (mangleSubstitution(QualType(T, 0))) 3594 return; 3595 3596 mangleTemplatePrefix(T->getTemplateName()); 3597 3598 // FIXME: GCC does not appear to mangle the template arguments when 3599 // the template in question is a dependent template name. Should we 3600 // emulate that badness? 3601 mangleTemplateArgs(T->getTemplateName(), T->getArgs(), T->getNumArgs()); 3602 addSubstitution(QualType(T, 0)); 3603 } 3604 } 3605 3606 void CXXNameMangler::mangleType(const DependentNameType *T) { 3607 // Proposal by cxx-abi-dev, 2014-03-26 3608 // <class-enum-type> ::= <name> # non-dependent or dependent type name or 3609 // # dependent elaborated type specifier using 3610 // # 'typename' 3611 // ::= Ts <name> # dependent elaborated type specifier using 3612 // # 'struct' or 'class' 3613 // ::= Tu <name> # dependent elaborated type specifier using 3614 // # 'union' 3615 // ::= Te <name> # dependent elaborated type specifier using 3616 // # 'enum' 3617 switch (T->getKeyword()) { 3618 case ETK_None: 3619 case ETK_Typename: 3620 break; 3621 case ETK_Struct: 3622 case ETK_Class: 3623 case ETK_Interface: 3624 Out << "Ts"; 3625 break; 3626 case ETK_Union: 3627 Out << "Tu"; 3628 break; 3629 case ETK_Enum: 3630 Out << "Te"; 3631 break; 3632 } 3633 // Typename types are always nested 3634 Out << 'N'; 3635 manglePrefix(T->getQualifier()); 3636 mangleSourceName(T->getIdentifier()); 3637 Out << 'E'; 3638 } 3639 3640 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) { 3641 // Dependently-scoped template types are nested if they have a prefix. 3642 Out << 'N'; 3643 3644 // TODO: avoid making this TemplateName. 3645 TemplateName Prefix = 3646 getASTContext().getDependentTemplateName(T->getQualifier(), 3647 T->getIdentifier()); 3648 mangleTemplatePrefix(Prefix); 3649 3650 // FIXME: GCC does not appear to mangle the template arguments when 3651 // the template in question is a dependent template name. Should we 3652 // emulate that badness? 3653 mangleTemplateArgs(Prefix, T->getArgs(), T->getNumArgs()); 3654 Out << 'E'; 3655 } 3656 3657 void CXXNameMangler::mangleType(const TypeOfType *T) { 3658 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 3659 // "extension with parameters" mangling. 3660 Out << "u6typeof"; 3661 } 3662 3663 void CXXNameMangler::mangleType(const TypeOfExprType *T) { 3664 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 3665 // "extension with parameters" mangling. 3666 Out << "u6typeof"; 3667 } 3668 3669 void CXXNameMangler::mangleType(const DecltypeType *T) { 3670 Expr *E = T->getUnderlyingExpr(); 3671 3672 // type ::= Dt <expression> E # decltype of an id-expression 3673 // # or class member access 3674 // ::= DT <expression> E # decltype of an expression 3675 3676 // This purports to be an exhaustive list of id-expressions and 3677 // class member accesses. Note that we do not ignore parentheses; 3678 // parentheses change the semantics of decltype for these 3679 // expressions (and cause the mangler to use the other form). 3680 if (isa<DeclRefExpr>(E) || 3681 isa<MemberExpr>(E) || 3682 isa<UnresolvedLookupExpr>(E) || 3683 isa<DependentScopeDeclRefExpr>(E) || 3684 isa<CXXDependentScopeMemberExpr>(E) || 3685 isa<UnresolvedMemberExpr>(E)) 3686 Out << "Dt"; 3687 else 3688 Out << "DT"; 3689 mangleExpression(E); 3690 Out << 'E'; 3691 } 3692 3693 void CXXNameMangler::mangleType(const UnaryTransformType *T) { 3694 // If this is dependent, we need to record that. If not, we simply 3695 // mangle it as the underlying type since they are equivalent. 3696 if (T->isDependentType()) { 3697 Out << 'U'; 3698 3699 switch (T->getUTTKind()) { 3700 case UnaryTransformType::EnumUnderlyingType: 3701 Out << "3eut"; 3702 break; 3703 } 3704 } 3705 3706 mangleType(T->getBaseType()); 3707 } 3708 3709 void CXXNameMangler::mangleType(const AutoType *T) { 3710 assert(T->getDeducedType().isNull() && 3711 "Deduced AutoType shouldn't be handled here!"); 3712 assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType && 3713 "shouldn't need to mangle __auto_type!"); 3714 // <builtin-type> ::= Da # auto 3715 // ::= Dc # decltype(auto) 3716 Out << (T->isDecltypeAuto() ? "Dc" : "Da"); 3717 } 3718 3719 void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) { 3720 QualType Deduced = T->getDeducedType(); 3721 if (!Deduced.isNull()) 3722 return mangleType(Deduced); 3723 3724 TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl(); 3725 assert(TD && "shouldn't form deduced TST unless we know we have a template"); 3726 3727 if (mangleSubstitution(TD)) 3728 return; 3729 3730 mangleName(GlobalDecl(TD)); 3731 addSubstitution(TD); 3732 } 3733 3734 void CXXNameMangler::mangleType(const AtomicType *T) { 3735 // <type> ::= U <source-name> <type> # vendor extended type qualifier 3736 // (Until there's a standardized mangling...) 3737 Out << "U7_Atomic"; 3738 mangleType(T->getValueType()); 3739 } 3740 3741 void CXXNameMangler::mangleType(const PipeType *T) { 3742 // Pipe type mangling rules are described in SPIR 2.0 specification 3743 // A.1 Data types and A.3 Summary of changes 3744 // <type> ::= 8ocl_pipe 3745 Out << "8ocl_pipe"; 3746 } 3747 3748 void CXXNameMangler::mangleType(const ExtIntType *T) { 3749 Out << "U7_ExtInt"; 3750 llvm::APSInt BW(32, true); 3751 BW = T->getNumBits(); 3752 TemplateArgument TA(Context.getASTContext(), BW, getASTContext().IntTy); 3753 mangleTemplateArgs(TemplateName(), &TA, 1); 3754 if (T->isUnsigned()) 3755 Out << "j"; 3756 else 3757 Out << "i"; 3758 } 3759 3760 void CXXNameMangler::mangleType(const DependentExtIntType *T) { 3761 Out << "U7_ExtInt"; 3762 TemplateArgument TA(T->getNumBitsExpr()); 3763 mangleTemplateArgs(TemplateName(), &TA, 1); 3764 if (T->isUnsigned()) 3765 Out << "j"; 3766 else 3767 Out << "i"; 3768 } 3769 3770 void CXXNameMangler::mangleIntegerLiteral(QualType T, 3771 const llvm::APSInt &Value) { 3772 // <expr-primary> ::= L <type> <value number> E # integer literal 3773 Out << 'L'; 3774 3775 mangleType(T); 3776 if (T->isBooleanType()) { 3777 // Boolean values are encoded as 0/1. 3778 Out << (Value.getBoolValue() ? '1' : '0'); 3779 } else { 3780 mangleNumber(Value); 3781 } 3782 Out << 'E'; 3783 3784 } 3785 3786 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) { 3787 // Ignore member expressions involving anonymous unions. 3788 while (const auto *RT = Base->getType()->getAs<RecordType>()) { 3789 if (!RT->getDecl()->isAnonymousStructOrUnion()) 3790 break; 3791 const auto *ME = dyn_cast<MemberExpr>(Base); 3792 if (!ME) 3793 break; 3794 Base = ME->getBase(); 3795 IsArrow = ME->isArrow(); 3796 } 3797 3798 if (Base->isImplicitCXXThis()) { 3799 // Note: GCC mangles member expressions to the implicit 'this' as 3800 // *this., whereas we represent them as this->. The Itanium C++ ABI 3801 // does not specify anything here, so we follow GCC. 3802 Out << "dtdefpT"; 3803 } else { 3804 Out << (IsArrow ? "pt" : "dt"); 3805 mangleExpression(Base); 3806 } 3807 } 3808 3809 /// Mangles a member expression. 3810 void CXXNameMangler::mangleMemberExpr(const Expr *base, 3811 bool isArrow, 3812 NestedNameSpecifier *qualifier, 3813 NamedDecl *firstQualifierLookup, 3814 DeclarationName member, 3815 const TemplateArgumentLoc *TemplateArgs, 3816 unsigned NumTemplateArgs, 3817 unsigned arity) { 3818 // <expression> ::= dt <expression> <unresolved-name> 3819 // ::= pt <expression> <unresolved-name> 3820 if (base) 3821 mangleMemberExprBase(base, isArrow); 3822 mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity); 3823 } 3824 3825 /// Look at the callee of the given call expression and determine if 3826 /// it's a parenthesized id-expression which would have triggered ADL 3827 /// otherwise. 3828 static bool isParenthesizedADLCallee(const CallExpr *call) { 3829 const Expr *callee = call->getCallee(); 3830 const Expr *fn = callee->IgnoreParens(); 3831 3832 // Must be parenthesized. IgnoreParens() skips __extension__ nodes, 3833 // too, but for those to appear in the callee, it would have to be 3834 // parenthesized. 3835 if (callee == fn) return false; 3836 3837 // Must be an unresolved lookup. 3838 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn); 3839 if (!lookup) return false; 3840 3841 assert(!lookup->requiresADL()); 3842 3843 // Must be an unqualified lookup. 3844 if (lookup->getQualifier()) return false; 3845 3846 // Must not have found a class member. Note that if one is a class 3847 // member, they're all class members. 3848 if (lookup->getNumDecls() > 0 && 3849 (*lookup->decls_begin())->isCXXClassMember()) 3850 return false; 3851 3852 // Otherwise, ADL would have been triggered. 3853 return true; 3854 } 3855 3856 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) { 3857 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E); 3858 Out << CastEncoding; 3859 mangleType(ECE->getType()); 3860 mangleExpression(ECE->getSubExpr()); 3861 } 3862 3863 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) { 3864 if (auto *Syntactic = InitList->getSyntacticForm()) 3865 InitList = Syntactic; 3866 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 3867 mangleExpression(InitList->getInit(i)); 3868 } 3869 3870 void CXXNameMangler::mangleDeclRefExpr(const NamedDecl *D) { 3871 switch (D->getKind()) { 3872 default: 3873 // <expr-primary> ::= L <mangled-name> E # external name 3874 Out << 'L'; 3875 mangle(D); 3876 Out << 'E'; 3877 break; 3878 3879 case Decl::ParmVar: 3880 mangleFunctionParam(cast<ParmVarDecl>(D)); 3881 break; 3882 3883 case Decl::EnumConstant: { 3884 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D); 3885 mangleIntegerLiteral(ED->getType(), ED->getInitVal()); 3886 break; 3887 } 3888 3889 case Decl::NonTypeTemplateParm: 3890 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D); 3891 mangleTemplateParameter(PD->getDepth(), PD->getIndex()); 3892 break; 3893 } 3894 } 3895 3896 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) { 3897 // <expression> ::= <unary operator-name> <expression> 3898 // ::= <binary operator-name> <expression> <expression> 3899 // ::= <trinary operator-name> <expression> <expression> <expression> 3900 // ::= cv <type> expression # conversion with one argument 3901 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments 3902 // ::= dc <type> <expression> # dynamic_cast<type> (expression) 3903 // ::= sc <type> <expression> # static_cast<type> (expression) 3904 // ::= cc <type> <expression> # const_cast<type> (expression) 3905 // ::= rc <type> <expression> # reinterpret_cast<type> (expression) 3906 // ::= st <type> # sizeof (a type) 3907 // ::= at <type> # alignof (a type) 3908 // ::= <template-param> 3909 // ::= <function-param> 3910 // ::= sr <type> <unqualified-name> # dependent name 3911 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id 3912 // ::= ds <expression> <expression> # expr.*expr 3913 // ::= sZ <template-param> # size of a parameter pack 3914 // ::= sZ <function-param> # size of a function parameter pack 3915 // ::= <expr-primary> 3916 // <expr-primary> ::= L <type> <value number> E # integer literal 3917 // ::= L <type <value float> E # floating literal 3918 // ::= L <mangled-name> E # external name 3919 // ::= fpT # 'this' expression 3920 QualType ImplicitlyConvertedToType; 3921 3922 recurse: 3923 switch (E->getStmtClass()) { 3924 case Expr::NoStmtClass: 3925 #define ABSTRACT_STMT(Type) 3926 #define EXPR(Type, Base) 3927 #define STMT(Type, Base) \ 3928 case Expr::Type##Class: 3929 #include "clang/AST/StmtNodes.inc" 3930 // fallthrough 3931 3932 // These all can only appear in local or variable-initialization 3933 // contexts and so should never appear in a mangling. 3934 case Expr::AddrLabelExprClass: 3935 case Expr::DesignatedInitUpdateExprClass: 3936 case Expr::ImplicitValueInitExprClass: 3937 case Expr::ArrayInitLoopExprClass: 3938 case Expr::ArrayInitIndexExprClass: 3939 case Expr::NoInitExprClass: 3940 case Expr::ParenListExprClass: 3941 case Expr::LambdaExprClass: 3942 case Expr::MSPropertyRefExprClass: 3943 case Expr::MSPropertySubscriptExprClass: 3944 case Expr::TypoExprClass: // This should no longer exist in the AST by now. 3945 case Expr::RecoveryExprClass: 3946 case Expr::OMPArraySectionExprClass: 3947 case Expr::OMPArrayShapingExprClass: 3948 case Expr::OMPIteratorExprClass: 3949 case Expr::CXXInheritedCtorInitExprClass: 3950 llvm_unreachable("unexpected statement kind"); 3951 3952 case Expr::ConstantExprClass: 3953 E = cast<ConstantExpr>(E)->getSubExpr(); 3954 goto recurse; 3955 3956 // FIXME: invent manglings for all these. 3957 case Expr::BlockExprClass: 3958 case Expr::ChooseExprClass: 3959 case Expr::CompoundLiteralExprClass: 3960 case Expr::ExtVectorElementExprClass: 3961 case Expr::GenericSelectionExprClass: 3962 case Expr::ObjCEncodeExprClass: 3963 case Expr::ObjCIsaExprClass: 3964 case Expr::ObjCIvarRefExprClass: 3965 case Expr::ObjCMessageExprClass: 3966 case Expr::ObjCPropertyRefExprClass: 3967 case Expr::ObjCProtocolExprClass: 3968 case Expr::ObjCSelectorExprClass: 3969 case Expr::ObjCStringLiteralClass: 3970 case Expr::ObjCBoxedExprClass: 3971 case Expr::ObjCArrayLiteralClass: 3972 case Expr::ObjCDictionaryLiteralClass: 3973 case Expr::ObjCSubscriptRefExprClass: 3974 case Expr::ObjCIndirectCopyRestoreExprClass: 3975 case Expr::ObjCAvailabilityCheckExprClass: 3976 case Expr::OffsetOfExprClass: 3977 case Expr::PredefinedExprClass: 3978 case Expr::ShuffleVectorExprClass: 3979 case Expr::ConvertVectorExprClass: 3980 case Expr::StmtExprClass: 3981 case Expr::TypeTraitExprClass: 3982 case Expr::RequiresExprClass: 3983 case Expr::ArrayTypeTraitExprClass: 3984 case Expr::ExpressionTraitExprClass: 3985 case Expr::VAArgExprClass: 3986 case Expr::CUDAKernelCallExprClass: 3987 case Expr::AsTypeExprClass: 3988 case Expr::PseudoObjectExprClass: 3989 case Expr::AtomicExprClass: 3990 case Expr::SourceLocExprClass: 3991 case Expr::BuiltinBitCastExprClass: 3992 { 3993 if (!NullOut) { 3994 // As bad as this diagnostic is, it's better than crashing. 3995 DiagnosticsEngine &Diags = Context.getDiags(); 3996 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3997 "cannot yet mangle expression type %0"); 3998 Diags.Report(E->getExprLoc(), DiagID) 3999 << E->getStmtClassName() << E->getSourceRange(); 4000 } 4001 break; 4002 } 4003 4004 case Expr::CXXUuidofExprClass: { 4005 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E); 4006 if (UE->isTypeOperand()) { 4007 QualType UuidT = UE->getTypeOperand(Context.getASTContext()); 4008 Out << "u8__uuidoft"; 4009 mangleType(UuidT); 4010 } else { 4011 Expr *UuidExp = UE->getExprOperand(); 4012 Out << "u8__uuidofz"; 4013 mangleExpression(UuidExp, Arity); 4014 } 4015 break; 4016 } 4017 4018 // Even gcc-4.5 doesn't mangle this. 4019 case Expr::BinaryConditionalOperatorClass: { 4020 DiagnosticsEngine &Diags = Context.getDiags(); 4021 unsigned DiagID = 4022 Diags.getCustomDiagID(DiagnosticsEngine::Error, 4023 "?: operator with omitted middle operand cannot be mangled"); 4024 Diags.Report(E->getExprLoc(), DiagID) 4025 << E->getStmtClassName() << E->getSourceRange(); 4026 break; 4027 } 4028 4029 // These are used for internal purposes and cannot be meaningfully mangled. 4030 case Expr::OpaqueValueExprClass: 4031 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?"); 4032 4033 case Expr::InitListExprClass: { 4034 Out << "il"; 4035 mangleInitListElements(cast<InitListExpr>(E)); 4036 Out << "E"; 4037 break; 4038 } 4039 4040 case Expr::DesignatedInitExprClass: { 4041 auto *DIE = cast<DesignatedInitExpr>(E); 4042 for (const auto &Designator : DIE->designators()) { 4043 if (Designator.isFieldDesignator()) { 4044 Out << "di"; 4045 mangleSourceName(Designator.getFieldName()); 4046 } else if (Designator.isArrayDesignator()) { 4047 Out << "dx"; 4048 mangleExpression(DIE->getArrayIndex(Designator)); 4049 } else { 4050 assert(Designator.isArrayRangeDesignator() && 4051 "unknown designator kind"); 4052 Out << "dX"; 4053 mangleExpression(DIE->getArrayRangeStart(Designator)); 4054 mangleExpression(DIE->getArrayRangeEnd(Designator)); 4055 } 4056 } 4057 mangleExpression(DIE->getInit()); 4058 break; 4059 } 4060 4061 case Expr::CXXDefaultArgExprClass: 4062 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity); 4063 break; 4064 4065 case Expr::CXXDefaultInitExprClass: 4066 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity); 4067 break; 4068 4069 case Expr::CXXStdInitializerListExprClass: 4070 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity); 4071 break; 4072 4073 case Expr::SubstNonTypeTemplateParmExprClass: 4074 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), 4075 Arity); 4076 break; 4077 4078 case Expr::UserDefinedLiteralClass: 4079 // We follow g++'s approach of mangling a UDL as a call to the literal 4080 // operator. 4081 case Expr::CXXMemberCallExprClass: // fallthrough 4082 case Expr::CallExprClass: { 4083 const CallExpr *CE = cast<CallExpr>(E); 4084 4085 // <expression> ::= cp <simple-id> <expression>* E 4086 // We use this mangling only when the call would use ADL except 4087 // for being parenthesized. Per discussion with David 4088 // Vandervoorde, 2011.04.25. 4089 if (isParenthesizedADLCallee(CE)) { 4090 Out << "cp"; 4091 // The callee here is a parenthesized UnresolvedLookupExpr with 4092 // no qualifier and should always get mangled as a <simple-id> 4093 // anyway. 4094 4095 // <expression> ::= cl <expression>* E 4096 } else { 4097 Out << "cl"; 4098 } 4099 4100 unsigned CallArity = CE->getNumArgs(); 4101 for (const Expr *Arg : CE->arguments()) 4102 if (isa<PackExpansionExpr>(Arg)) 4103 CallArity = UnknownArity; 4104 4105 mangleExpression(CE->getCallee(), CallArity); 4106 for (const Expr *Arg : CE->arguments()) 4107 mangleExpression(Arg); 4108 Out << 'E'; 4109 break; 4110 } 4111 4112 case Expr::CXXNewExprClass: { 4113 const CXXNewExpr *New = cast<CXXNewExpr>(E); 4114 if (New->isGlobalNew()) Out << "gs"; 4115 Out << (New->isArray() ? "na" : "nw"); 4116 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(), 4117 E = New->placement_arg_end(); I != E; ++I) 4118 mangleExpression(*I); 4119 Out << '_'; 4120 mangleType(New->getAllocatedType()); 4121 if (New->hasInitializer()) { 4122 if (New->getInitializationStyle() == CXXNewExpr::ListInit) 4123 Out << "il"; 4124 else 4125 Out << "pi"; 4126 const Expr *Init = New->getInitializer(); 4127 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 4128 // Directly inline the initializers. 4129 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 4130 E = CCE->arg_end(); 4131 I != E; ++I) 4132 mangleExpression(*I); 4133 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) { 4134 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i) 4135 mangleExpression(PLE->getExpr(i)); 4136 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit && 4137 isa<InitListExpr>(Init)) { 4138 // Only take InitListExprs apart for list-initialization. 4139 mangleInitListElements(cast<InitListExpr>(Init)); 4140 } else 4141 mangleExpression(Init); 4142 } 4143 Out << 'E'; 4144 break; 4145 } 4146 4147 case Expr::CXXPseudoDestructorExprClass: { 4148 const auto *PDE = cast<CXXPseudoDestructorExpr>(E); 4149 if (const Expr *Base = PDE->getBase()) 4150 mangleMemberExprBase(Base, PDE->isArrow()); 4151 NestedNameSpecifier *Qualifier = PDE->getQualifier(); 4152 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) { 4153 if (Qualifier) { 4154 mangleUnresolvedPrefix(Qualifier, 4155 /*recursive=*/true); 4156 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()); 4157 Out << 'E'; 4158 } else { 4159 Out << "sr"; 4160 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType())) 4161 Out << 'E'; 4162 } 4163 } else if (Qualifier) { 4164 mangleUnresolvedPrefix(Qualifier); 4165 } 4166 // <base-unresolved-name> ::= dn <destructor-name> 4167 Out << "dn"; 4168 QualType DestroyedType = PDE->getDestroyedType(); 4169 mangleUnresolvedTypeOrSimpleId(DestroyedType); 4170 break; 4171 } 4172 4173 case Expr::MemberExprClass: { 4174 const MemberExpr *ME = cast<MemberExpr>(E); 4175 mangleMemberExpr(ME->getBase(), ME->isArrow(), 4176 ME->getQualifier(), nullptr, 4177 ME->getMemberDecl()->getDeclName(), 4178 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4179 Arity); 4180 break; 4181 } 4182 4183 case Expr::UnresolvedMemberExprClass: { 4184 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E); 4185 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 4186 ME->isArrow(), ME->getQualifier(), nullptr, 4187 ME->getMemberName(), 4188 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4189 Arity); 4190 break; 4191 } 4192 4193 case Expr::CXXDependentScopeMemberExprClass: { 4194 const CXXDependentScopeMemberExpr *ME 4195 = cast<CXXDependentScopeMemberExpr>(E); 4196 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 4197 ME->isArrow(), ME->getQualifier(), 4198 ME->getFirstQualifierFoundInScope(), 4199 ME->getMember(), 4200 ME->getTemplateArgs(), ME->getNumTemplateArgs(), 4201 Arity); 4202 break; 4203 } 4204 4205 case Expr::UnresolvedLookupExprClass: { 4206 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E); 4207 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), 4208 ULE->getTemplateArgs(), ULE->getNumTemplateArgs(), 4209 Arity); 4210 break; 4211 } 4212 4213 case Expr::CXXUnresolvedConstructExprClass: { 4214 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E); 4215 unsigned N = CE->getNumArgs(); 4216 4217 if (CE->isListInitialization()) { 4218 assert(N == 1 && "unexpected form for list initialization"); 4219 auto *IL = cast<InitListExpr>(CE->getArg(0)); 4220 Out << "tl"; 4221 mangleType(CE->getType()); 4222 mangleInitListElements(IL); 4223 Out << "E"; 4224 return; 4225 } 4226 4227 Out << "cv"; 4228 mangleType(CE->getType()); 4229 if (N != 1) Out << '_'; 4230 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 4231 if (N != 1) Out << 'E'; 4232 break; 4233 } 4234 4235 case Expr::CXXConstructExprClass: { 4236 const auto *CE = cast<CXXConstructExpr>(E); 4237 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) { 4238 assert( 4239 CE->getNumArgs() >= 1 && 4240 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && 4241 "implicit CXXConstructExpr must have one argument"); 4242 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0)); 4243 } 4244 Out << "il"; 4245 for (auto *E : CE->arguments()) 4246 mangleExpression(E); 4247 Out << "E"; 4248 break; 4249 } 4250 4251 case Expr::CXXTemporaryObjectExprClass: { 4252 const auto *CE = cast<CXXTemporaryObjectExpr>(E); 4253 unsigned N = CE->getNumArgs(); 4254 bool List = CE->isListInitialization(); 4255 4256 if (List) 4257 Out << "tl"; 4258 else 4259 Out << "cv"; 4260 mangleType(CE->getType()); 4261 if (!List && N != 1) 4262 Out << '_'; 4263 if (CE->isStdInitListInitialization()) { 4264 // We implicitly created a std::initializer_list<T> for the first argument 4265 // of a constructor of type U in an expression of the form U{a, b, c}. 4266 // Strip all the semantic gunk off the initializer list. 4267 auto *SILE = 4268 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit()); 4269 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit()); 4270 mangleInitListElements(ILE); 4271 } else { 4272 for (auto *E : CE->arguments()) 4273 mangleExpression(E); 4274 } 4275 if (List || N != 1) 4276 Out << 'E'; 4277 break; 4278 } 4279 4280 case Expr::CXXScalarValueInitExprClass: 4281 Out << "cv"; 4282 mangleType(E->getType()); 4283 Out << "_E"; 4284 break; 4285 4286 case Expr::CXXNoexceptExprClass: 4287 Out << "nx"; 4288 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand()); 4289 break; 4290 4291 case Expr::UnaryExprOrTypeTraitExprClass: { 4292 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); 4293 4294 if (!SAE->isInstantiationDependent()) { 4295 // Itanium C++ ABI: 4296 // If the operand of a sizeof or alignof operator is not 4297 // instantiation-dependent it is encoded as an integer literal 4298 // reflecting the result of the operator. 4299 // 4300 // If the result of the operator is implicitly converted to a known 4301 // integer type, that type is used for the literal; otherwise, the type 4302 // of std::size_t or std::ptrdiff_t is used. 4303 QualType T = (ImplicitlyConvertedToType.isNull() || 4304 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() 4305 : ImplicitlyConvertedToType; 4306 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); 4307 mangleIntegerLiteral(T, V); 4308 break; 4309 } 4310 4311 switch(SAE->getKind()) { 4312 case UETT_SizeOf: 4313 Out << 's'; 4314 break; 4315 case UETT_PreferredAlignOf: 4316 case UETT_AlignOf: 4317 Out << 'a'; 4318 break; 4319 case UETT_VecStep: { 4320 DiagnosticsEngine &Diags = Context.getDiags(); 4321 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 4322 "cannot yet mangle vec_step expression"); 4323 Diags.Report(DiagID); 4324 return; 4325 } 4326 case UETT_OpenMPRequiredSimdAlign: { 4327 DiagnosticsEngine &Diags = Context.getDiags(); 4328 unsigned DiagID = Diags.getCustomDiagID( 4329 DiagnosticsEngine::Error, 4330 "cannot yet mangle __builtin_omp_required_simd_align expression"); 4331 Diags.Report(DiagID); 4332 return; 4333 } 4334 } 4335 if (SAE->isArgumentType()) { 4336 Out << 't'; 4337 mangleType(SAE->getArgumentType()); 4338 } else { 4339 Out << 'z'; 4340 mangleExpression(SAE->getArgumentExpr()); 4341 } 4342 break; 4343 } 4344 4345 case Expr::CXXThrowExprClass: { 4346 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E); 4347 // <expression> ::= tw <expression> # throw expression 4348 // ::= tr # rethrow 4349 if (TE->getSubExpr()) { 4350 Out << "tw"; 4351 mangleExpression(TE->getSubExpr()); 4352 } else { 4353 Out << "tr"; 4354 } 4355 break; 4356 } 4357 4358 case Expr::CXXTypeidExprClass: { 4359 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E); 4360 // <expression> ::= ti <type> # typeid (type) 4361 // ::= te <expression> # typeid (expression) 4362 if (TIE->isTypeOperand()) { 4363 Out << "ti"; 4364 mangleType(TIE->getTypeOperand(Context.getASTContext())); 4365 } else { 4366 Out << "te"; 4367 mangleExpression(TIE->getExprOperand()); 4368 } 4369 break; 4370 } 4371 4372 case Expr::CXXDeleteExprClass: { 4373 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E); 4374 // <expression> ::= [gs] dl <expression> # [::] delete expr 4375 // ::= [gs] da <expression> # [::] delete [] expr 4376 if (DE->isGlobalDelete()) Out << "gs"; 4377 Out << (DE->isArrayForm() ? "da" : "dl"); 4378 mangleExpression(DE->getArgument()); 4379 break; 4380 } 4381 4382 case Expr::UnaryOperatorClass: { 4383 const UnaryOperator *UO = cast<UnaryOperator>(E); 4384 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()), 4385 /*Arity=*/1); 4386 mangleExpression(UO->getSubExpr()); 4387 break; 4388 } 4389 4390 case Expr::ArraySubscriptExprClass: { 4391 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E); 4392 4393 // Array subscript is treated as a syntactically weird form of 4394 // binary operator. 4395 Out << "ix"; 4396 mangleExpression(AE->getLHS()); 4397 mangleExpression(AE->getRHS()); 4398 break; 4399 } 4400 4401 case Expr::MatrixSubscriptExprClass: { 4402 const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E); 4403 Out << "ixix"; 4404 mangleExpression(ME->getBase()); 4405 mangleExpression(ME->getRowIdx()); 4406 mangleExpression(ME->getColumnIdx()); 4407 break; 4408 } 4409 4410 case Expr::CompoundAssignOperatorClass: // fallthrough 4411 case Expr::BinaryOperatorClass: { 4412 const BinaryOperator *BO = cast<BinaryOperator>(E); 4413 if (BO->getOpcode() == BO_PtrMemD) 4414 Out << "ds"; 4415 else 4416 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()), 4417 /*Arity=*/2); 4418 mangleExpression(BO->getLHS()); 4419 mangleExpression(BO->getRHS()); 4420 break; 4421 } 4422 4423 case Expr::CXXRewrittenBinaryOperatorClass: { 4424 // The mangled form represents the original syntax. 4425 CXXRewrittenBinaryOperator::DecomposedForm Decomposed = 4426 cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm(); 4427 mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode), 4428 /*Arity=*/2); 4429 mangleExpression(Decomposed.LHS); 4430 mangleExpression(Decomposed.RHS); 4431 break; 4432 } 4433 4434 case Expr::ConditionalOperatorClass: { 4435 const ConditionalOperator *CO = cast<ConditionalOperator>(E); 4436 mangleOperatorName(OO_Conditional, /*Arity=*/3); 4437 mangleExpression(CO->getCond()); 4438 mangleExpression(CO->getLHS(), Arity); 4439 mangleExpression(CO->getRHS(), Arity); 4440 break; 4441 } 4442 4443 case Expr::ImplicitCastExprClass: { 4444 ImplicitlyConvertedToType = E->getType(); 4445 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 4446 goto recurse; 4447 } 4448 4449 case Expr::ObjCBridgedCastExprClass: { 4450 // Mangle ownership casts as a vendor extended operator __bridge, 4451 // __bridge_transfer, or __bridge_retain. 4452 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); 4453 Out << "v1U" << Kind.size() << Kind; 4454 } 4455 // Fall through to mangle the cast itself. 4456 LLVM_FALLTHROUGH; 4457 4458 case Expr::CStyleCastExprClass: 4459 mangleCastExpression(E, "cv"); 4460 break; 4461 4462 case Expr::CXXFunctionalCastExprClass: { 4463 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit(); 4464 // FIXME: Add isImplicit to CXXConstructExpr. 4465 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub)) 4466 if (CCE->getParenOrBraceRange().isInvalid()) 4467 Sub = CCE->getArg(0)->IgnoreImplicit(); 4468 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub)) 4469 Sub = StdInitList->getSubExpr()->IgnoreImplicit(); 4470 if (auto *IL = dyn_cast<InitListExpr>(Sub)) { 4471 Out << "tl"; 4472 mangleType(E->getType()); 4473 mangleInitListElements(IL); 4474 Out << "E"; 4475 } else { 4476 mangleCastExpression(E, "cv"); 4477 } 4478 break; 4479 } 4480 4481 case Expr::CXXStaticCastExprClass: 4482 mangleCastExpression(E, "sc"); 4483 break; 4484 case Expr::CXXDynamicCastExprClass: 4485 mangleCastExpression(E, "dc"); 4486 break; 4487 case Expr::CXXReinterpretCastExprClass: 4488 mangleCastExpression(E, "rc"); 4489 break; 4490 case Expr::CXXConstCastExprClass: 4491 mangleCastExpression(E, "cc"); 4492 break; 4493 case Expr::CXXAddrspaceCastExprClass: 4494 mangleCastExpression(E, "ac"); 4495 break; 4496 4497 case Expr::CXXOperatorCallExprClass: { 4498 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E); 4499 unsigned NumArgs = CE->getNumArgs(); 4500 // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax 4501 // (the enclosing MemberExpr covers the syntactic portion). 4502 if (CE->getOperator() != OO_Arrow) 4503 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs); 4504 // Mangle the arguments. 4505 for (unsigned i = 0; i != NumArgs; ++i) 4506 mangleExpression(CE->getArg(i)); 4507 break; 4508 } 4509 4510 case Expr::ParenExprClass: 4511 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity); 4512 break; 4513 4514 4515 case Expr::ConceptSpecializationExprClass: { 4516 // <expr-primary> ::= L <mangled-name> E # external name 4517 Out << "L_Z"; 4518 auto *CSE = cast<ConceptSpecializationExpr>(E); 4519 mangleTemplateName(CSE->getNamedConcept(), 4520 CSE->getTemplateArguments().data(), 4521 CSE->getTemplateArguments().size()); 4522 Out << 'E'; 4523 break; 4524 } 4525 4526 case Expr::DeclRefExprClass: 4527 mangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl()); 4528 break; 4529 4530 case Expr::SubstNonTypeTemplateParmPackExprClass: 4531 // FIXME: not clear how to mangle this! 4532 // template <unsigned N...> class A { 4533 // template <class U...> void foo(U (&x)[N]...); 4534 // }; 4535 Out << "_SUBSTPACK_"; 4536 break; 4537 4538 case Expr::FunctionParmPackExprClass: { 4539 // FIXME: not clear how to mangle this! 4540 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E); 4541 Out << "v110_SUBSTPACK"; 4542 mangleDeclRefExpr(FPPE->getParameterPack()); 4543 break; 4544 } 4545 4546 case Expr::DependentScopeDeclRefExprClass: { 4547 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E); 4548 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), 4549 DRE->getTemplateArgs(), DRE->getNumTemplateArgs(), 4550 Arity); 4551 break; 4552 } 4553 4554 case Expr::CXXBindTemporaryExprClass: 4555 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr()); 4556 break; 4557 4558 case Expr::ExprWithCleanupsClass: 4559 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity); 4560 break; 4561 4562 case Expr::FloatingLiteralClass: { 4563 const FloatingLiteral *FL = cast<FloatingLiteral>(E); 4564 mangleFloatLiteral(FL->getType(), FL->getValue()); 4565 break; 4566 } 4567 4568 case Expr::FixedPointLiteralClass: 4569 mangleFixedPointLiteral(); 4570 break; 4571 4572 case Expr::CharacterLiteralClass: 4573 Out << 'L'; 4574 mangleType(E->getType()); 4575 Out << cast<CharacterLiteral>(E)->getValue(); 4576 Out << 'E'; 4577 break; 4578 4579 // FIXME. __objc_yes/__objc_no are mangled same as true/false 4580 case Expr::ObjCBoolLiteralExprClass: 4581 Out << "Lb"; 4582 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 4583 Out << 'E'; 4584 break; 4585 4586 case Expr::CXXBoolLiteralExprClass: 4587 Out << "Lb"; 4588 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 4589 Out << 'E'; 4590 break; 4591 4592 case Expr::IntegerLiteralClass: { 4593 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue()); 4594 if (E->getType()->isSignedIntegerType()) 4595 Value.setIsSigned(true); 4596 mangleIntegerLiteral(E->getType(), Value); 4597 break; 4598 } 4599 4600 case Expr::ImaginaryLiteralClass: { 4601 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E); 4602 // Mangle as if a complex literal. 4603 // Proposal from David Vandevoorde, 2010.06.30. 4604 Out << 'L'; 4605 mangleType(E->getType()); 4606 if (const FloatingLiteral *Imag = 4607 dyn_cast<FloatingLiteral>(IE->getSubExpr())) { 4608 // Mangle a floating-point zero of the appropriate type. 4609 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics())); 4610 Out << '_'; 4611 mangleFloat(Imag->getValue()); 4612 } else { 4613 Out << "0_"; 4614 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue()); 4615 if (IE->getSubExpr()->getType()->isSignedIntegerType()) 4616 Value.setIsSigned(true); 4617 mangleNumber(Value); 4618 } 4619 Out << 'E'; 4620 break; 4621 } 4622 4623 case Expr::StringLiteralClass: { 4624 // Revised proposal from David Vandervoorde, 2010.07.15. 4625 Out << 'L'; 4626 assert(isa<ConstantArrayType>(E->getType())); 4627 mangleType(E->getType()); 4628 Out << 'E'; 4629 break; 4630 } 4631 4632 case Expr::GNUNullExprClass: 4633 // Mangle as if an integer literal 0. 4634 mangleIntegerLiteral(E->getType(), llvm::APSInt(32)); 4635 break; 4636 4637 case Expr::CXXNullPtrLiteralExprClass: { 4638 Out << "LDnE"; 4639 break; 4640 } 4641 4642 case Expr::PackExpansionExprClass: 4643 Out << "sp"; 4644 mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); 4645 break; 4646 4647 case Expr::SizeOfPackExprClass: { 4648 auto *SPE = cast<SizeOfPackExpr>(E); 4649 if (SPE->isPartiallySubstituted()) { 4650 Out << "sP"; 4651 for (const auto &A : SPE->getPartialArguments()) 4652 mangleTemplateArg(A, false); 4653 Out << "E"; 4654 break; 4655 } 4656 4657 Out << "sZ"; 4658 const NamedDecl *Pack = SPE->getPack(); 4659 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack)) 4660 mangleTemplateParameter(TTP->getDepth(), TTP->getIndex()); 4661 else if (const NonTypeTemplateParmDecl *NTTP 4662 = dyn_cast<NonTypeTemplateParmDecl>(Pack)) 4663 mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex()); 4664 else if (const TemplateTemplateParmDecl *TempTP 4665 = dyn_cast<TemplateTemplateParmDecl>(Pack)) 4666 mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex()); 4667 else 4668 mangleFunctionParam(cast<ParmVarDecl>(Pack)); 4669 break; 4670 } 4671 4672 case Expr::MaterializeTemporaryExprClass: { 4673 mangleExpression(cast<MaterializeTemporaryExpr>(E)->getSubExpr()); 4674 break; 4675 } 4676 4677 case Expr::CXXFoldExprClass: { 4678 auto *FE = cast<CXXFoldExpr>(E); 4679 if (FE->isLeftFold()) 4680 Out << (FE->getInit() ? "fL" : "fl"); 4681 else 4682 Out << (FE->getInit() ? "fR" : "fr"); 4683 4684 if (FE->getOperator() == BO_PtrMemD) 4685 Out << "ds"; 4686 else 4687 mangleOperatorName( 4688 BinaryOperator::getOverloadedOperator(FE->getOperator()), 4689 /*Arity=*/2); 4690 4691 if (FE->getLHS()) 4692 mangleExpression(FE->getLHS()); 4693 if (FE->getRHS()) 4694 mangleExpression(FE->getRHS()); 4695 break; 4696 } 4697 4698 case Expr::CXXThisExprClass: 4699 Out << "fpT"; 4700 break; 4701 4702 case Expr::CoawaitExprClass: 4703 // FIXME: Propose a non-vendor mangling. 4704 Out << "v18co_await"; 4705 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 4706 break; 4707 4708 case Expr::DependentCoawaitExprClass: 4709 // FIXME: Propose a non-vendor mangling. 4710 Out << "v18co_await"; 4711 mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand()); 4712 break; 4713 4714 case Expr::CoyieldExprClass: 4715 // FIXME: Propose a non-vendor mangling. 4716 Out << "v18co_yield"; 4717 mangleExpression(cast<CoawaitExpr>(E)->getOperand()); 4718 break; 4719 } 4720 } 4721 4722 /// Mangle an expression which refers to a parameter variable. 4723 /// 4724 /// <expression> ::= <function-param> 4725 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0 4726 /// <function-param> ::= fp <top-level CV-qualifiers> 4727 /// <parameter-2 non-negative number> _ # L == 0, I > 0 4728 /// <function-param> ::= fL <L-1 non-negative number> 4729 /// p <top-level CV-qualifiers> _ # L > 0, I == 0 4730 /// <function-param> ::= fL <L-1 non-negative number> 4731 /// p <top-level CV-qualifiers> 4732 /// <I-1 non-negative number> _ # L > 0, I > 0 4733 /// 4734 /// L is the nesting depth of the parameter, defined as 1 if the 4735 /// parameter comes from the innermost function prototype scope 4736 /// enclosing the current context, 2 if from the next enclosing 4737 /// function prototype scope, and so on, with one special case: if 4738 /// we've processed the full parameter clause for the innermost 4739 /// function type, then L is one less. This definition conveniently 4740 /// makes it irrelevant whether a function's result type was written 4741 /// trailing or leading, but is otherwise overly complicated; the 4742 /// numbering was first designed without considering references to 4743 /// parameter in locations other than return types, and then the 4744 /// mangling had to be generalized without changing the existing 4745 /// manglings. 4746 /// 4747 /// I is the zero-based index of the parameter within its parameter 4748 /// declaration clause. Note that the original ABI document describes 4749 /// this using 1-based ordinals. 4750 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) { 4751 unsigned parmDepth = parm->getFunctionScopeDepth(); 4752 unsigned parmIndex = parm->getFunctionScopeIndex(); 4753 4754 // Compute 'L'. 4755 // parmDepth does not include the declaring function prototype. 4756 // FunctionTypeDepth does account for that. 4757 assert(parmDepth < FunctionTypeDepth.getDepth()); 4758 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth; 4759 if (FunctionTypeDepth.isInResultType()) 4760 nestingDepth--; 4761 4762 if (nestingDepth == 0) { 4763 Out << "fp"; 4764 } else { 4765 Out << "fL" << (nestingDepth - 1) << 'p'; 4766 } 4767 4768 // Top-level qualifiers. We don't have to worry about arrays here, 4769 // because parameters declared as arrays should already have been 4770 // transformed to have pointer type. FIXME: apparently these don't 4771 // get mangled if used as an rvalue of a known non-class type? 4772 assert(!parm->getType()->isArrayType() 4773 && "parameter's type is still an array type?"); 4774 4775 if (const DependentAddressSpaceType *DAST = 4776 dyn_cast<DependentAddressSpaceType>(parm->getType())) { 4777 mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST); 4778 } else { 4779 mangleQualifiers(parm->getType().getQualifiers()); 4780 } 4781 4782 // Parameter index. 4783 if (parmIndex != 0) { 4784 Out << (parmIndex - 1); 4785 } 4786 Out << '_'; 4787 } 4788 4789 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T, 4790 const CXXRecordDecl *InheritedFrom) { 4791 // <ctor-dtor-name> ::= C1 # complete object constructor 4792 // ::= C2 # base object constructor 4793 // ::= CI1 <type> # complete inheriting constructor 4794 // ::= CI2 <type> # base inheriting constructor 4795 // 4796 // In addition, C5 is a comdat name with C1 and C2 in it. 4797 Out << 'C'; 4798 if (InheritedFrom) 4799 Out << 'I'; 4800 switch (T) { 4801 case Ctor_Complete: 4802 Out << '1'; 4803 break; 4804 case Ctor_Base: 4805 Out << '2'; 4806 break; 4807 case Ctor_Comdat: 4808 Out << '5'; 4809 break; 4810 case Ctor_DefaultClosure: 4811 case Ctor_CopyingClosure: 4812 llvm_unreachable("closure constructors don't exist for the Itanium ABI!"); 4813 } 4814 if (InheritedFrom) 4815 mangleName(InheritedFrom); 4816 } 4817 4818 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 4819 // <ctor-dtor-name> ::= D0 # deleting destructor 4820 // ::= D1 # complete object destructor 4821 // ::= D2 # base object destructor 4822 // 4823 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it. 4824 switch (T) { 4825 case Dtor_Deleting: 4826 Out << "D0"; 4827 break; 4828 case Dtor_Complete: 4829 Out << "D1"; 4830 break; 4831 case Dtor_Base: 4832 Out << "D2"; 4833 break; 4834 case Dtor_Comdat: 4835 Out << "D5"; 4836 break; 4837 } 4838 } 4839 4840 namespace { 4841 // Helper to provide ancillary information on a template used to mangle its 4842 // arguments. 4843 struct TemplateArgManglingInfo { 4844 TemplateDecl *ResolvedTemplate = nullptr; 4845 bool SeenPackExpansionIntoNonPack = false; 4846 const NamedDecl *UnresolvedExpandedPack = nullptr; 4847 4848 TemplateArgManglingInfo(TemplateName TN) { 4849 if (TemplateDecl *TD = TN.getAsTemplateDecl()) 4850 ResolvedTemplate = TD; 4851 } 4852 4853 /// Do we need to mangle template arguments with exactly correct types? 4854 /// 4855 /// This should be called exactly once for each parameter / argument pair, in 4856 /// order. 4857 bool needExactType(unsigned ParamIdx, const TemplateArgument &Arg) { 4858 // We need correct types when the template-name is unresolved or when it 4859 // names a template that is able to be overloaded. 4860 if (!ResolvedTemplate || SeenPackExpansionIntoNonPack) 4861 return true; 4862 4863 // Move to the next parameter. 4864 const NamedDecl *Param = UnresolvedExpandedPack; 4865 if (!Param) { 4866 assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() && 4867 "no parameter for argument"); 4868 Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx); 4869 4870 // If we reach an expanded parameter pack whose argument isn't in pack 4871 // form, that means Sema couldn't figure out which arguments belonged to 4872 // it, because it contains a pack expansion. Track the expanded pack for 4873 // all further template arguments until we hit that pack expansion. 4874 if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) { 4875 assert(getExpandedPackSize(Param) && 4876 "failed to form pack argument for parameter pack"); 4877 UnresolvedExpandedPack = Param; 4878 } 4879 } 4880 4881 // If we encounter a pack argument that is expanded into a non-pack 4882 // parameter, we can no longer track parameter / argument correspondence, 4883 // and need to use exact types from this point onwards. 4884 if (Arg.isPackExpansion() && 4885 (!Param->isParameterPack() || UnresolvedExpandedPack)) { 4886 SeenPackExpansionIntoNonPack = true; 4887 return true; 4888 } 4889 4890 // We need exact types for function template arguments because they might be 4891 // overloaded on template parameter type. As a special case, a member 4892 // function template of a generic lambda is not overloadable. 4893 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ResolvedTemplate)) { 4894 auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext()); 4895 if (!RD || !RD->isGenericLambda()) 4896 return true; 4897 } 4898 4899 // Otherwise, we only need a correct type if the parameter has a deduced 4900 // type. 4901 // 4902 // Note: for an expanded parameter pack, getType() returns the type prior 4903 // to expansion. We could ask for the expanded type with getExpansionType(), 4904 // but it doesn't matter because substitution and expansion don't affect 4905 // whether a deduced type appears in the type. 4906 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param); 4907 return NTTP && NTTP->getType()->getContainedDeducedType(); 4908 } 4909 }; 4910 } 4911 4912 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 4913 const TemplateArgumentLoc *TemplateArgs, 4914 unsigned NumTemplateArgs) { 4915 // <template-args> ::= I <template-arg>+ E 4916 Out << 'I'; 4917 TemplateArgManglingInfo Info(TN); 4918 for (unsigned i = 0; i != NumTemplateArgs; ++i) 4919 mangleTemplateArg(TemplateArgs[i].getArgument(), 4920 Info.needExactType(i, TemplateArgs[i].getArgument())); 4921 Out << 'E'; 4922 } 4923 4924 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 4925 const TemplateArgumentList &AL) { 4926 // <template-args> ::= I <template-arg>+ E 4927 Out << 'I'; 4928 TemplateArgManglingInfo Info(TN); 4929 for (unsigned i = 0, e = AL.size(); i != e; ++i) 4930 mangleTemplateArg(AL[i], Info.needExactType(i, AL[i])); 4931 Out << 'E'; 4932 } 4933 4934 void CXXNameMangler::mangleTemplateArgs(TemplateName TN, 4935 const TemplateArgument *TemplateArgs, 4936 unsigned NumTemplateArgs) { 4937 // <template-args> ::= I <template-arg>+ E 4938 Out << 'I'; 4939 TemplateArgManglingInfo Info(TN); 4940 for (unsigned i = 0; i != NumTemplateArgs; ++i) 4941 mangleTemplateArg(TemplateArgs[i], Info.needExactType(i, TemplateArgs[i])); 4942 Out << 'E'; 4943 } 4944 4945 void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) { 4946 // <template-arg> ::= <type> # type or template 4947 // ::= X <expression> E # expression 4948 // ::= <expr-primary> # simple expressions 4949 // ::= J <template-arg>* E # argument pack 4950 if (!A.isInstantiationDependent() || A.isDependent()) 4951 A = Context.getASTContext().getCanonicalTemplateArgument(A); 4952 4953 switch (A.getKind()) { 4954 case TemplateArgument::Null: 4955 llvm_unreachable("Cannot mangle NULL template argument"); 4956 4957 case TemplateArgument::Type: 4958 mangleType(A.getAsType()); 4959 break; 4960 case TemplateArgument::Template: 4961 // This is mangled as <type>. 4962 mangleType(A.getAsTemplate()); 4963 break; 4964 case TemplateArgument::TemplateExpansion: 4965 // <type> ::= Dp <type> # pack expansion (C++0x) 4966 Out << "Dp"; 4967 mangleType(A.getAsTemplateOrTemplatePattern()); 4968 break; 4969 case TemplateArgument::Expression: { 4970 // It's possible to end up with a DeclRefExpr here in certain 4971 // dependent cases, in which case we should mangle as a 4972 // declaration. 4973 const Expr *E = A.getAsExpr()->IgnoreParenImpCasts(); 4974 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 4975 const ValueDecl *D = DRE->getDecl(); 4976 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) { 4977 Out << 'L'; 4978 mangle(D); 4979 Out << 'E'; 4980 break; 4981 } 4982 } 4983 4984 Out << 'X'; 4985 mangleExpression(E); 4986 Out << 'E'; 4987 break; 4988 } 4989 case TemplateArgument::Integral: 4990 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral()); 4991 break; 4992 case TemplateArgument::Declaration: { 4993 // <expr-primary> ::= L <mangled-name> E # external name 4994 ValueDecl *D = A.getAsDecl(); 4995 4996 // Template parameter objects are modeled by reproducing a source form 4997 // produced as if by aggregate initialization. 4998 if (A.getParamTypeForDecl()->isRecordType()) { 4999 auto *TPO = cast<TemplateParamObjectDecl>(D); 5000 mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(), 5001 TPO->getValue(), /*TopLevel=*/true, 5002 NeedExactType); 5003 break; 5004 } 5005 5006 ASTContext &Ctx = Context.getASTContext(); 5007 APValue Value; 5008 if (D->isCXXInstanceMember()) 5009 // Simple pointer-to-member with no conversion. 5010 Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{}); 5011 else if (D->getType()->isArrayType() && 5012 Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()), 5013 A.getParamTypeForDecl()) && 5014 Ctx.getLangOpts().getClangABICompat() > 5015 LangOptions::ClangABI::Ver11) 5016 // Build a value corresponding to this implicit array-to-pointer decay. 5017 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(), 5018 {APValue::LValuePathEntry::ArrayIndex(0)}, 5019 /*OnePastTheEnd=*/false); 5020 else 5021 // Regular pointer or reference to a declaration. 5022 Value = APValue(APValue::LValueBase(D), CharUnits::Zero(), 5023 ArrayRef<APValue::LValuePathEntry>(), 5024 /*OnePastTheEnd=*/false); 5025 mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true, 5026 NeedExactType); 5027 break; 5028 } 5029 case TemplateArgument::NullPtr: { 5030 mangleNullPointer(A.getNullPtrType()); 5031 break; 5032 } 5033 case TemplateArgument::Pack: { 5034 // <template-arg> ::= J <template-arg>* E 5035 Out << 'J'; 5036 for (const auto &P : A.pack_elements()) 5037 mangleTemplateArg(P, NeedExactType); 5038 Out << 'E'; 5039 } 5040 } 5041 } 5042 5043 /// Determine whether a given value is equivalent to zero-initialization for 5044 /// the purpose of discarding a trailing portion of a 'tl' mangling. 5045 /// 5046 /// Note that this is not in general equivalent to determining whether the 5047 /// value has an all-zeroes bit pattern. 5048 static bool isZeroInitialized(QualType T, const APValue &V) { 5049 // FIXME: mangleValueInTemplateArg has quadratic time complexity in 5050 // pathological cases due to using this, but it's a little awkward 5051 // to do this in linear time in general. 5052 switch (V.getKind()) { 5053 case APValue::None: 5054 case APValue::Indeterminate: 5055 case APValue::AddrLabelDiff: 5056 return false; 5057 5058 case APValue::Struct: { 5059 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5060 assert(RD && "unexpected type for record value"); 5061 unsigned I = 0; 5062 for (const CXXBaseSpecifier &BS : RD->bases()) { 5063 if (!isZeroInitialized(BS.getType(), V.getStructBase(I))) 5064 return false; 5065 ++I; 5066 } 5067 I = 0; 5068 for (const FieldDecl *FD : RD->fields()) { 5069 if (!FD->isUnnamedBitfield() && 5070 !isZeroInitialized(FD->getType(), V.getStructField(I))) 5071 return false; 5072 ++I; 5073 } 5074 return true; 5075 } 5076 5077 case APValue::Union: { 5078 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5079 assert(RD && "unexpected type for union value"); 5080 // Zero-initialization zeroes the first non-unnamed-bitfield field, if any. 5081 for (const FieldDecl *FD : RD->fields()) { 5082 if (!FD->isUnnamedBitfield()) 5083 return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) && 5084 isZeroInitialized(FD->getType(), V.getUnionValue()); 5085 } 5086 // If there are no fields (other than unnamed bitfields), the value is 5087 // necessarily zero-initialized. 5088 return true; 5089 } 5090 5091 case APValue::Array: { 5092 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0); 5093 for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I) 5094 if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I))) 5095 return false; 5096 return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller()); 5097 } 5098 5099 case APValue::Vector: { 5100 const VectorType *VT = T->castAs<VectorType>(); 5101 for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I) 5102 if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I))) 5103 return false; 5104 return true; 5105 } 5106 5107 case APValue::Int: 5108 return !V.getInt(); 5109 5110 case APValue::Float: 5111 return V.getFloat().isPosZero(); 5112 5113 case APValue::FixedPoint: 5114 return !V.getFixedPoint().getValue(); 5115 5116 case APValue::ComplexFloat: 5117 return V.getComplexFloatReal().isPosZero() && 5118 V.getComplexFloatImag().isPosZero(); 5119 5120 case APValue::ComplexInt: 5121 return !V.getComplexIntReal() && !V.getComplexIntImag(); 5122 5123 case APValue::LValue: 5124 return V.isNullPointer(); 5125 5126 case APValue::MemberPointer: 5127 return !V.getMemberPointerDecl(); 5128 } 5129 5130 llvm_unreachable("Unhandled APValue::ValueKind enum"); 5131 } 5132 5133 static QualType getLValueType(ASTContext &Ctx, const APValue &LV) { 5134 QualType T = LV.getLValueBase().getType(); 5135 for (APValue::LValuePathEntry E : LV.getLValuePath()) { 5136 if (const ArrayType *AT = Ctx.getAsArrayType(T)) 5137 T = AT->getElementType(); 5138 else if (const FieldDecl *FD = 5139 dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer())) 5140 T = FD->getType(); 5141 else 5142 T = Ctx.getRecordType( 5143 cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer())); 5144 } 5145 return T; 5146 } 5147 5148 void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V, 5149 bool TopLevel, 5150 bool NeedExactType) { 5151 // Ignore all top-level cv-qualifiers, to match GCC. 5152 Qualifiers Quals; 5153 T = getASTContext().getUnqualifiedArrayType(T, Quals); 5154 5155 // A top-level expression that's not a primary expression is wrapped in X...E. 5156 bool IsPrimaryExpr = true; 5157 auto NotPrimaryExpr = [&] { 5158 if (TopLevel && IsPrimaryExpr) 5159 Out << 'X'; 5160 IsPrimaryExpr = false; 5161 }; 5162 5163 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63. 5164 switch (V.getKind()) { 5165 case APValue::None: 5166 case APValue::Indeterminate: 5167 Out << 'L'; 5168 mangleType(T); 5169 Out << 'E'; 5170 break; 5171 5172 case APValue::AddrLabelDiff: 5173 llvm_unreachable("unexpected value kind in template argument"); 5174 5175 case APValue::Struct: { 5176 const CXXRecordDecl *RD = T->getAsCXXRecordDecl(); 5177 assert(RD && "unexpected type for record value"); 5178 5179 // Drop trailing zero-initialized elements. 5180 llvm::SmallVector<const FieldDecl *, 16> Fields(RD->field_begin(), 5181 RD->field_end()); 5182 while ( 5183 !Fields.empty() && 5184 (Fields.back()->isUnnamedBitfield() || 5185 isZeroInitialized(Fields.back()->getType(), 5186 V.getStructField(Fields.back()->getFieldIndex())))) { 5187 Fields.pop_back(); 5188 } 5189 llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end()); 5190 if (Fields.empty()) { 5191 while (!Bases.empty() && 5192 isZeroInitialized(Bases.back().getType(), 5193 V.getStructBase(Bases.size() - 1))) 5194 Bases = Bases.drop_back(); 5195 } 5196 5197 // <expression> ::= tl <type> <braced-expression>* E 5198 NotPrimaryExpr(); 5199 Out << "tl"; 5200 mangleType(T); 5201 for (unsigned I = 0, N = Bases.size(); I != N; ++I) 5202 mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false); 5203 for (unsigned I = 0, N = Fields.size(); I != N; ++I) { 5204 if (Fields[I]->isUnnamedBitfield()) 5205 continue; 5206 mangleValueInTemplateArg(Fields[I]->getType(), 5207 V.getStructField(Fields[I]->getFieldIndex()), 5208 false); 5209 } 5210 Out << 'E'; 5211 break; 5212 } 5213 5214 case APValue::Union: { 5215 assert(T->getAsCXXRecordDecl() && "unexpected type for union value"); 5216 const FieldDecl *FD = V.getUnionField(); 5217 5218 if (!FD) { 5219 Out << 'L'; 5220 mangleType(T); 5221 Out << 'E'; 5222 break; 5223 } 5224 5225 // <braced-expression> ::= di <field source-name> <braced-expression> 5226 NotPrimaryExpr(); 5227 Out << "tl"; 5228 mangleType(T); 5229 if (!isZeroInitialized(T, V)) { 5230 Out << "di"; 5231 mangleSourceName(FD->getIdentifier()); 5232 mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false); 5233 } 5234 Out << 'E'; 5235 break; 5236 } 5237 5238 case APValue::Array: { 5239 QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0); 5240 5241 NotPrimaryExpr(); 5242 Out << "tl"; 5243 mangleType(T); 5244 5245 // Drop trailing zero-initialized elements. 5246 unsigned N = V.getArraySize(); 5247 if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) { 5248 N = V.getArrayInitializedElts(); 5249 while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1))) 5250 --N; 5251 } 5252 5253 for (unsigned I = 0; I != N; ++I) { 5254 const APValue &Elem = I < V.getArrayInitializedElts() 5255 ? V.getArrayInitializedElt(I) 5256 : V.getArrayFiller(); 5257 mangleValueInTemplateArg(ElemT, Elem, false); 5258 } 5259 Out << 'E'; 5260 break; 5261 } 5262 5263 case APValue::Vector: { 5264 const VectorType *VT = T->castAs<VectorType>(); 5265 5266 NotPrimaryExpr(); 5267 Out << "tl"; 5268 mangleType(T); 5269 unsigned N = V.getVectorLength(); 5270 while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1))) 5271 --N; 5272 for (unsigned I = 0; I != N; ++I) 5273 mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false); 5274 Out << 'E'; 5275 break; 5276 } 5277 5278 case APValue::Int: 5279 mangleIntegerLiteral(T, V.getInt()); 5280 break; 5281 5282 case APValue::Float: 5283 mangleFloatLiteral(T, V.getFloat()); 5284 break; 5285 5286 case APValue::FixedPoint: 5287 mangleFixedPointLiteral(); 5288 break; 5289 5290 case APValue::ComplexFloat: { 5291 const ComplexType *CT = T->castAs<ComplexType>(); 5292 NotPrimaryExpr(); 5293 Out << "tl"; 5294 mangleType(T); 5295 if (!V.getComplexFloatReal().isPosZero() || 5296 !V.getComplexFloatImag().isPosZero()) 5297 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal()); 5298 if (!V.getComplexFloatImag().isPosZero()) 5299 mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag()); 5300 Out << 'E'; 5301 break; 5302 } 5303 5304 case APValue::ComplexInt: { 5305 const ComplexType *CT = T->castAs<ComplexType>(); 5306 NotPrimaryExpr(); 5307 Out << "tl"; 5308 mangleType(T); 5309 if (V.getComplexIntReal().getBoolValue() || 5310 V.getComplexIntImag().getBoolValue()) 5311 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal()); 5312 if (V.getComplexIntImag().getBoolValue()) 5313 mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag()); 5314 Out << 'E'; 5315 break; 5316 } 5317 5318 case APValue::LValue: { 5319 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47. 5320 assert((T->isPointerType() || T->isReferenceType()) && 5321 "unexpected type for LValue template arg"); 5322 5323 if (V.isNullPointer()) { 5324 mangleNullPointer(T); 5325 break; 5326 } 5327 5328 APValue::LValueBase B = V.getLValueBase(); 5329 if (!B) { 5330 // Non-standard mangling for integer cast to a pointer; this can only 5331 // occur as an extension. 5332 CharUnits Offset = V.getLValueOffset(); 5333 if (Offset.isZero()) { 5334 // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as 5335 // a cast, because L <type> 0 E means something else. 5336 NotPrimaryExpr(); 5337 Out << "rc"; 5338 mangleType(T); 5339 Out << "Li0E"; 5340 if (TopLevel) 5341 Out << 'E'; 5342 } else { 5343 Out << "L"; 5344 mangleType(T); 5345 Out << Offset.getQuantity() << 'E'; 5346 } 5347 break; 5348 } 5349 5350 ASTContext &Ctx = Context.getASTContext(); 5351 5352 enum { Base, Offset, Path } Kind; 5353 if (!V.hasLValuePath()) { 5354 // Mangle as (T*)((char*)&base + N). 5355 if (T->isReferenceType()) { 5356 NotPrimaryExpr(); 5357 Out << "decvP"; 5358 mangleType(T->getPointeeType()); 5359 } else { 5360 NotPrimaryExpr(); 5361 Out << "cv"; 5362 mangleType(T); 5363 } 5364 Out << "plcvPcad"; 5365 Kind = Offset; 5366 } else { 5367 if (!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) { 5368 NotPrimaryExpr(); 5369 // A final conversion to the template parameter's type is usually 5370 // folded into the 'so' mangling, but we can't do that for 'void*' 5371 // parameters without introducing collisions. 5372 if (NeedExactType && T->isVoidPointerType()) { 5373 Out << "cv"; 5374 mangleType(T); 5375 } 5376 if (T->isPointerType()) 5377 Out << "ad"; 5378 Out << "so"; 5379 mangleType(T->isVoidPointerType() 5380 ? getLValueType(Ctx, V).getUnqualifiedType() 5381 : T->getPointeeType()); 5382 Kind = Path; 5383 } else { 5384 if (NeedExactType && 5385 !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) && 5386 Ctx.getLangOpts().getClangABICompat() > 5387 LangOptions::ClangABI::Ver11) { 5388 NotPrimaryExpr(); 5389 Out << "cv"; 5390 mangleType(T); 5391 } 5392 if (T->isPointerType()) { 5393 NotPrimaryExpr(); 5394 Out << "ad"; 5395 } 5396 Kind = Base; 5397 } 5398 } 5399 5400 QualType TypeSoFar = B.getType(); 5401 if (auto *VD = B.dyn_cast<const ValueDecl*>()) { 5402 Out << 'L'; 5403 mangle(VD); 5404 Out << 'E'; 5405 } else if (auto *E = B.dyn_cast<const Expr*>()) { 5406 NotPrimaryExpr(); 5407 mangleExpression(E); 5408 } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) { 5409 NotPrimaryExpr(); 5410 Out << "ti"; 5411 mangleType(QualType(TI.getType(), 0)); 5412 } else { 5413 // We should never see dynamic allocations here. 5414 llvm_unreachable("unexpected lvalue base kind in template argument"); 5415 } 5416 5417 switch (Kind) { 5418 case Base: 5419 break; 5420 5421 case Offset: 5422 Out << 'L'; 5423 mangleType(Ctx.getPointerDiffType()); 5424 mangleNumber(V.getLValueOffset().getQuantity()); 5425 Out << 'E'; 5426 break; 5427 5428 case Path: 5429 // <expression> ::= so <referent type> <expr> [<offset number>] 5430 // <union-selector>* [p] E 5431 if (!V.getLValueOffset().isZero()) 5432 mangleNumber(V.getLValueOffset().getQuantity()); 5433 5434 // We model a past-the-end array pointer as array indexing with index N, 5435 // not with the "past the end" flag. Compensate for that. 5436 bool OnePastTheEnd = V.isLValueOnePastTheEnd(); 5437 5438 for (APValue::LValuePathEntry E : V.getLValuePath()) { 5439 if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) { 5440 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) 5441 OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex(); 5442 TypeSoFar = AT->getElementType(); 5443 } else { 5444 const Decl *D = E.getAsBaseOrMember().getPointer(); 5445 if (auto *FD = dyn_cast<FieldDecl>(D)) { 5446 // <union-selector> ::= _ <number> 5447 if (FD->getParent()->isUnion()) { 5448 Out << '_'; 5449 if (FD->getFieldIndex()) 5450 Out << (FD->getFieldIndex() - 1); 5451 } 5452 TypeSoFar = FD->getType(); 5453 } else { 5454 TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D)); 5455 } 5456 } 5457 } 5458 5459 if (OnePastTheEnd) 5460 Out << 'p'; 5461 Out << 'E'; 5462 break; 5463 } 5464 5465 break; 5466 } 5467 5468 case APValue::MemberPointer: 5469 // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47. 5470 if (!V.getMemberPointerDecl()) { 5471 mangleNullPointer(T); 5472 break; 5473 } 5474 5475 ASTContext &Ctx = Context.getASTContext(); 5476 5477 NotPrimaryExpr(); 5478 if (!V.getMemberPointerPath().empty()) { 5479 Out << "mc"; 5480 mangleType(T); 5481 } else if (NeedExactType && 5482 !Ctx.hasSameType( 5483 T->castAs<MemberPointerType>()->getPointeeType(), 5484 V.getMemberPointerDecl()->getType()) && 5485 Ctx.getLangOpts().getClangABICompat() > 5486 LangOptions::ClangABI::Ver11) { 5487 Out << "cv"; 5488 mangleType(T); 5489 } 5490 Out << "adL"; 5491 mangle(V.getMemberPointerDecl()); 5492 Out << 'E'; 5493 if (!V.getMemberPointerPath().empty()) { 5494 CharUnits Offset = 5495 Context.getASTContext().getMemberPointerPathAdjustment(V); 5496 if (!Offset.isZero()) 5497 mangleNumber(Offset.getQuantity()); 5498 Out << 'E'; 5499 } 5500 break; 5501 } 5502 5503 if (TopLevel && !IsPrimaryExpr) 5504 Out << 'E'; 5505 } 5506 5507 void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) { 5508 // <template-param> ::= T_ # first template parameter 5509 // ::= T <parameter-2 non-negative number> _ 5510 // ::= TL <L-1 non-negative number> __ 5511 // ::= TL <L-1 non-negative number> _ 5512 // <parameter-2 non-negative number> _ 5513 // 5514 // The latter two manglings are from a proposal here: 5515 // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117 5516 Out << 'T'; 5517 if (Depth != 0) 5518 Out << 'L' << (Depth - 1) << '_'; 5519 if (Index != 0) 5520 Out << (Index - 1); 5521 Out << '_'; 5522 } 5523 5524 void CXXNameMangler::mangleSeqID(unsigned SeqID) { 5525 if (SeqID == 1) 5526 Out << '0'; 5527 else if (SeqID > 1) { 5528 SeqID--; 5529 5530 // <seq-id> is encoded in base-36, using digits and upper case letters. 5531 char Buffer[7]; // log(2**32) / log(36) ~= 7 5532 MutableArrayRef<char> BufferRef(Buffer); 5533 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin(); 5534 5535 for (; SeqID != 0; SeqID /= 36) { 5536 unsigned C = SeqID % 36; 5537 *I++ = (C < 10 ? '0' + C : 'A' + C - 10); 5538 } 5539 5540 Out.write(I.base(), I - BufferRef.rbegin()); 5541 } 5542 Out << '_'; 5543 } 5544 5545 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) { 5546 bool result = mangleSubstitution(tname); 5547 assert(result && "no existing substitution for template name"); 5548 (void) result; 5549 } 5550 5551 // <substitution> ::= S <seq-id> _ 5552 // ::= S_ 5553 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) { 5554 // Try one of the standard substitutions first. 5555 if (mangleStandardSubstitution(ND)) 5556 return true; 5557 5558 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 5559 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND)); 5560 } 5561 5562 /// Determine whether the given type has any qualifiers that are relevant for 5563 /// substitutions. 5564 static bool hasMangledSubstitutionQualifiers(QualType T) { 5565 Qualifiers Qs = T.getQualifiers(); 5566 return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned(); 5567 } 5568 5569 bool CXXNameMangler::mangleSubstitution(QualType T) { 5570 if (!hasMangledSubstitutionQualifiers(T)) { 5571 if (const RecordType *RT = T->getAs<RecordType>()) 5572 return mangleSubstitution(RT->getDecl()); 5573 } 5574 5575 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 5576 5577 return mangleSubstitution(TypePtr); 5578 } 5579 5580 bool CXXNameMangler::mangleSubstitution(TemplateName Template) { 5581 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 5582 return mangleSubstitution(TD); 5583 5584 Template = Context.getASTContext().getCanonicalTemplateName(Template); 5585 return mangleSubstitution( 5586 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 5587 } 5588 5589 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) { 5590 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr); 5591 if (I == Substitutions.end()) 5592 return false; 5593 5594 unsigned SeqID = I->second; 5595 Out << 'S'; 5596 mangleSeqID(SeqID); 5597 5598 return true; 5599 } 5600 5601 static bool isCharType(QualType T) { 5602 if (T.isNull()) 5603 return false; 5604 5605 return T->isSpecificBuiltinType(BuiltinType::Char_S) || 5606 T->isSpecificBuiltinType(BuiltinType::Char_U); 5607 } 5608 5609 /// Returns whether a given type is a template specialization of a given name 5610 /// with a single argument of type char. 5611 static bool isCharSpecialization(QualType T, const char *Name) { 5612 if (T.isNull()) 5613 return false; 5614 5615 const RecordType *RT = T->getAs<RecordType>(); 5616 if (!RT) 5617 return false; 5618 5619 const ClassTemplateSpecializationDecl *SD = 5620 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 5621 if (!SD) 5622 return false; 5623 5624 if (!isStdNamespace(getEffectiveDeclContext(SD))) 5625 return false; 5626 5627 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 5628 if (TemplateArgs.size() != 1) 5629 return false; 5630 5631 if (!isCharType(TemplateArgs[0].getAsType())) 5632 return false; 5633 5634 return SD->getIdentifier()->getName() == Name; 5635 } 5636 5637 template <std::size_t StrLen> 5638 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD, 5639 const char (&Str)[StrLen]) { 5640 if (!SD->getIdentifier()->isStr(Str)) 5641 return false; 5642 5643 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 5644 if (TemplateArgs.size() != 2) 5645 return false; 5646 5647 if (!isCharType(TemplateArgs[0].getAsType())) 5648 return false; 5649 5650 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 5651 return false; 5652 5653 return true; 5654 } 5655 5656 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) { 5657 // <substitution> ::= St # ::std:: 5658 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 5659 if (isStd(NS)) { 5660 Out << "St"; 5661 return true; 5662 } 5663 } 5664 5665 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) { 5666 if (!isStdNamespace(getEffectiveDeclContext(TD))) 5667 return false; 5668 5669 // <substitution> ::= Sa # ::std::allocator 5670 if (TD->getIdentifier()->isStr("allocator")) { 5671 Out << "Sa"; 5672 return true; 5673 } 5674 5675 // <<substitution> ::= Sb # ::std::basic_string 5676 if (TD->getIdentifier()->isStr("basic_string")) { 5677 Out << "Sb"; 5678 return true; 5679 } 5680 } 5681 5682 if (const ClassTemplateSpecializationDecl *SD = 5683 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 5684 if (!isStdNamespace(getEffectiveDeclContext(SD))) 5685 return false; 5686 5687 // <substitution> ::= Ss # ::std::basic_string<char, 5688 // ::std::char_traits<char>, 5689 // ::std::allocator<char> > 5690 if (SD->getIdentifier()->isStr("basic_string")) { 5691 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 5692 5693 if (TemplateArgs.size() != 3) 5694 return false; 5695 5696 if (!isCharType(TemplateArgs[0].getAsType())) 5697 return false; 5698 5699 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 5700 return false; 5701 5702 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator")) 5703 return false; 5704 5705 Out << "Ss"; 5706 return true; 5707 } 5708 5709 // <substitution> ::= Si # ::std::basic_istream<char, 5710 // ::std::char_traits<char> > 5711 if (isStreamCharSpecialization(SD, "basic_istream")) { 5712 Out << "Si"; 5713 return true; 5714 } 5715 5716 // <substitution> ::= So # ::std::basic_ostream<char, 5717 // ::std::char_traits<char> > 5718 if (isStreamCharSpecialization(SD, "basic_ostream")) { 5719 Out << "So"; 5720 return true; 5721 } 5722 5723 // <substitution> ::= Sd # ::std::basic_iostream<char, 5724 // ::std::char_traits<char> > 5725 if (isStreamCharSpecialization(SD, "basic_iostream")) { 5726 Out << "Sd"; 5727 return true; 5728 } 5729 } 5730 return false; 5731 } 5732 5733 void CXXNameMangler::addSubstitution(QualType T) { 5734 if (!hasMangledSubstitutionQualifiers(T)) { 5735 if (const RecordType *RT = T->getAs<RecordType>()) { 5736 addSubstitution(RT->getDecl()); 5737 return; 5738 } 5739 } 5740 5741 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 5742 addSubstitution(TypePtr); 5743 } 5744 5745 void CXXNameMangler::addSubstitution(TemplateName Template) { 5746 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 5747 return addSubstitution(TD); 5748 5749 Template = Context.getASTContext().getCanonicalTemplateName(Template); 5750 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 5751 } 5752 5753 void CXXNameMangler::addSubstitution(uintptr_t Ptr) { 5754 assert(!Substitutions.count(Ptr) && "Substitution already exists!"); 5755 Substitutions[Ptr] = SeqID++; 5756 } 5757 5758 void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) { 5759 assert(Other->SeqID >= SeqID && "Must be superset of substitutions!"); 5760 if (Other->SeqID > SeqID) { 5761 Substitutions.swap(Other->Substitutions); 5762 SeqID = Other->SeqID; 5763 } 5764 } 5765 5766 CXXNameMangler::AbiTagList 5767 CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) { 5768 // When derived abi tags are disabled there is no need to make any list. 5769 if (DisableDerivedAbiTags) 5770 return AbiTagList(); 5771 5772 llvm::raw_null_ostream NullOutStream; 5773 CXXNameMangler TrackReturnTypeTags(*this, NullOutStream); 5774 TrackReturnTypeTags.disableDerivedAbiTags(); 5775 5776 const FunctionProtoType *Proto = 5777 cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>()); 5778 FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push(); 5779 TrackReturnTypeTags.FunctionTypeDepth.enterResultType(); 5780 TrackReturnTypeTags.mangleType(Proto->getReturnType()); 5781 TrackReturnTypeTags.FunctionTypeDepth.leaveResultType(); 5782 TrackReturnTypeTags.FunctionTypeDepth.pop(saved); 5783 5784 return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 5785 } 5786 5787 CXXNameMangler::AbiTagList 5788 CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) { 5789 // When derived abi tags are disabled there is no need to make any list. 5790 if (DisableDerivedAbiTags) 5791 return AbiTagList(); 5792 5793 llvm::raw_null_ostream NullOutStream; 5794 CXXNameMangler TrackVariableType(*this, NullOutStream); 5795 TrackVariableType.disableDerivedAbiTags(); 5796 5797 TrackVariableType.mangleType(VD->getType()); 5798 5799 return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags(); 5800 } 5801 5802 bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C, 5803 const VarDecl *VD) { 5804 llvm::raw_null_ostream NullOutStream; 5805 CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true); 5806 TrackAbiTags.mangle(VD); 5807 return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size(); 5808 } 5809 5810 // 5811 5812 /// Mangles the name of the declaration D and emits that name to the given 5813 /// output stream. 5814 /// 5815 /// If the declaration D requires a mangled name, this routine will emit that 5816 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged 5817 /// and this routine will return false. In this case, the caller should just 5818 /// emit the identifier of the declaration (\c D->getIdentifier()) as its 5819 /// name. 5820 void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD, 5821 raw_ostream &Out) { 5822 const NamedDecl *D = cast<NamedDecl>(GD.getDecl()); 5823 assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) && 5824 "Invalid mangleName() call, argument is not a variable or function!"); 5825 5826 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 5827 getASTContext().getSourceManager(), 5828 "Mangling declaration"); 5829 5830 if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) { 5831 auto Type = GD.getCtorType(); 5832 CXXNameMangler Mangler(*this, Out, CD, Type); 5833 return Mangler.mangle(GlobalDecl(CD, Type)); 5834 } 5835 5836 if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) { 5837 auto Type = GD.getDtorType(); 5838 CXXNameMangler Mangler(*this, Out, DD, Type); 5839 return Mangler.mangle(GlobalDecl(DD, Type)); 5840 } 5841 5842 CXXNameMangler Mangler(*this, Out, D); 5843 Mangler.mangle(GD); 5844 } 5845 5846 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D, 5847 raw_ostream &Out) { 5848 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat); 5849 Mangler.mangle(GlobalDecl(D, Ctor_Comdat)); 5850 } 5851 5852 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D, 5853 raw_ostream &Out) { 5854 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat); 5855 Mangler.mangle(GlobalDecl(D, Dtor_Comdat)); 5856 } 5857 5858 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 5859 const ThunkInfo &Thunk, 5860 raw_ostream &Out) { 5861 // <special-name> ::= T <call-offset> <base encoding> 5862 // # base is the nominal target function of thunk 5863 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding> 5864 // # base is the nominal target function of thunk 5865 // # first call-offset is 'this' adjustment 5866 // # second call-offset is result adjustment 5867 5868 assert(!isa<CXXDestructorDecl>(MD) && 5869 "Use mangleCXXDtor for destructor decls!"); 5870 CXXNameMangler Mangler(*this, Out); 5871 Mangler.getStream() << "_ZT"; 5872 if (!Thunk.Return.isEmpty()) 5873 Mangler.getStream() << 'c'; 5874 5875 // Mangle the 'this' pointer adjustment. 5876 Mangler.mangleCallOffset(Thunk.This.NonVirtual, 5877 Thunk.This.Virtual.Itanium.VCallOffsetOffset); 5878 5879 // Mangle the return pointer adjustment if there is one. 5880 if (!Thunk.Return.isEmpty()) 5881 Mangler.mangleCallOffset(Thunk.Return.NonVirtual, 5882 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset); 5883 5884 Mangler.mangleFunctionEncoding(MD); 5885 } 5886 5887 void ItaniumMangleContextImpl::mangleCXXDtorThunk( 5888 const CXXDestructorDecl *DD, CXXDtorType Type, 5889 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) { 5890 // <special-name> ::= T <call-offset> <base encoding> 5891 // # base is the nominal target function of thunk 5892 CXXNameMangler Mangler(*this, Out, DD, Type); 5893 Mangler.getStream() << "_ZT"; 5894 5895 // Mangle the 'this' pointer adjustment. 5896 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 5897 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); 5898 5899 Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type)); 5900 } 5901 5902 /// Returns the mangled name for a guard variable for the passed in VarDecl. 5903 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D, 5904 raw_ostream &Out) { 5905 // <special-name> ::= GV <object name> # Guard variable for one-time 5906 // # initialization 5907 CXXNameMangler Mangler(*this, Out); 5908 // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to 5909 // be a bug that is fixed in trunk. 5910 Mangler.getStream() << "_ZGV"; 5911 Mangler.mangleName(D); 5912 } 5913 5914 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD, 5915 raw_ostream &Out) { 5916 // These symbols are internal in the Itanium ABI, so the names don't matter. 5917 // Clang has traditionally used this symbol and allowed LLVM to adjust it to 5918 // avoid duplicate symbols. 5919 Out << "__cxx_global_var_init"; 5920 } 5921 5922 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 5923 raw_ostream &Out) { 5924 // Prefix the mangling of D with __dtor_. 5925 CXXNameMangler Mangler(*this, Out); 5926 Mangler.getStream() << "__dtor_"; 5927 if (shouldMangleDeclName(D)) 5928 Mangler.mangle(D); 5929 else 5930 Mangler.getStream() << D->getName(); 5931 } 5932 5933 void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D, 5934 raw_ostream &Out) { 5935 // Clang generates these internal-linkage functions as part of its 5936 // implementation of the XL ABI. 5937 CXXNameMangler Mangler(*this, Out); 5938 Mangler.getStream() << "__finalize_"; 5939 if (shouldMangleDeclName(D)) 5940 Mangler.mangle(D); 5941 else 5942 Mangler.getStream() << D->getName(); 5943 } 5944 5945 void ItaniumMangleContextImpl::mangleSEHFilterExpression( 5946 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 5947 CXXNameMangler Mangler(*this, Out); 5948 Mangler.getStream() << "__filt_"; 5949 if (shouldMangleDeclName(EnclosingDecl)) 5950 Mangler.mangle(EnclosingDecl); 5951 else 5952 Mangler.getStream() << EnclosingDecl->getName(); 5953 } 5954 5955 void ItaniumMangleContextImpl::mangleSEHFinallyBlock( 5956 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 5957 CXXNameMangler Mangler(*this, Out); 5958 Mangler.getStream() << "__fin_"; 5959 if (shouldMangleDeclName(EnclosingDecl)) 5960 Mangler.mangle(EnclosingDecl); 5961 else 5962 Mangler.getStream() << EnclosingDecl->getName(); 5963 } 5964 5965 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D, 5966 raw_ostream &Out) { 5967 // <special-name> ::= TH <object name> 5968 CXXNameMangler Mangler(*this, Out); 5969 Mangler.getStream() << "_ZTH"; 5970 Mangler.mangleName(D); 5971 } 5972 5973 void 5974 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D, 5975 raw_ostream &Out) { 5976 // <special-name> ::= TW <object name> 5977 CXXNameMangler Mangler(*this, Out); 5978 Mangler.getStream() << "_ZTW"; 5979 Mangler.mangleName(D); 5980 } 5981 5982 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D, 5983 unsigned ManglingNumber, 5984 raw_ostream &Out) { 5985 // We match the GCC mangling here. 5986 // <special-name> ::= GR <object name> 5987 CXXNameMangler Mangler(*this, Out); 5988 Mangler.getStream() << "_ZGR"; 5989 Mangler.mangleName(D); 5990 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!"); 5991 Mangler.mangleSeqID(ManglingNumber - 1); 5992 } 5993 5994 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD, 5995 raw_ostream &Out) { 5996 // <special-name> ::= TV <type> # virtual table 5997 CXXNameMangler Mangler(*this, Out); 5998 Mangler.getStream() << "_ZTV"; 5999 Mangler.mangleNameOrStandardSubstitution(RD); 6000 } 6001 6002 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD, 6003 raw_ostream &Out) { 6004 // <special-name> ::= TT <type> # VTT structure 6005 CXXNameMangler Mangler(*this, Out); 6006 Mangler.getStream() << "_ZTT"; 6007 Mangler.mangleNameOrStandardSubstitution(RD); 6008 } 6009 6010 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD, 6011 int64_t Offset, 6012 const CXXRecordDecl *Type, 6013 raw_ostream &Out) { 6014 // <special-name> ::= TC <type> <offset number> _ <base type> 6015 CXXNameMangler Mangler(*this, Out); 6016 Mangler.getStream() << "_ZTC"; 6017 Mangler.mangleNameOrStandardSubstitution(RD); 6018 Mangler.getStream() << Offset; 6019 Mangler.getStream() << '_'; 6020 Mangler.mangleNameOrStandardSubstitution(Type); 6021 } 6022 6023 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) { 6024 // <special-name> ::= TI <type> # typeinfo structure 6025 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers"); 6026 CXXNameMangler Mangler(*this, Out); 6027 Mangler.getStream() << "_ZTI"; 6028 Mangler.mangleType(Ty); 6029 } 6030 6031 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty, 6032 raw_ostream &Out) { 6033 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string) 6034 CXXNameMangler Mangler(*this, Out); 6035 Mangler.getStream() << "_ZTS"; 6036 Mangler.mangleType(Ty); 6037 } 6038 6039 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) { 6040 mangleCXXRTTIName(Ty, Out); 6041 } 6042 6043 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) { 6044 llvm_unreachable("Can't mangle string literals"); 6045 } 6046 6047 void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda, 6048 raw_ostream &Out) { 6049 CXXNameMangler Mangler(*this, Out); 6050 Mangler.mangleLambdaSig(Lambda); 6051 } 6052 6053 ItaniumMangleContext * 6054 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) { 6055 return new ItaniumMangleContextImpl(Context, Diags); 6056 } 6057