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