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://mentorembedded.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/DeclTemplate.h" 24 #include "clang/AST/Expr.h" 25 #include "clang/AST/ExprCXX.h" 26 #include "clang/AST/ExprObjC.h" 27 #include "clang/AST/TypeLoc.h" 28 #include "clang/Basic/ABI.h" 29 #include "clang/Basic/SourceManager.h" 30 #include "clang/Basic/TargetInfo.h" 31 #include "llvm/ADT/StringExtras.h" 32 #include "llvm/Support/ErrorHandling.h" 33 #include "llvm/Support/raw_ostream.h" 34 35 #define MANGLE_CHECKER 0 36 37 #if MANGLE_CHECKER 38 #include <cxxabi.h> 39 #endif 40 41 using namespace clang; 42 43 namespace { 44 45 /// \brief Retrieve the declaration context that should be used when mangling 46 /// the given declaration. 47 static const DeclContext *getEffectiveDeclContext(const Decl *D) { 48 // The ABI assumes that lambda closure types that occur within 49 // default arguments live in the context of the function. However, due to 50 // the way in which Clang parses and creates function declarations, this is 51 // not the case: the lambda closure type ends up living in the context 52 // where the function itself resides, because the function declaration itself 53 // had not yet been created. Fix the context here. 54 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) { 55 if (RD->isLambda()) 56 if (ParmVarDecl *ContextParam 57 = dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl())) 58 return ContextParam->getDeclContext(); 59 } 60 61 // Perform the same check for block literals. 62 if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 63 if (ParmVarDecl *ContextParam 64 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) 65 return ContextParam->getDeclContext(); 66 } 67 68 const DeclContext *DC = D->getDeclContext(); 69 if (const CapturedDecl *CD = dyn_cast<CapturedDecl>(DC)) 70 return getEffectiveDeclContext(CD); 71 72 return DC; 73 } 74 75 static const DeclContext *getEffectiveParentContext(const DeclContext *DC) { 76 return getEffectiveDeclContext(cast<Decl>(DC)); 77 } 78 79 static bool isLocalContainerContext(const DeclContext *DC) { 80 return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC); 81 } 82 83 static const RecordDecl *GetLocalClassDecl(const Decl *D) { 84 const DeclContext *DC = getEffectiveDeclContext(D); 85 while (!DC->isNamespace() && !DC->isTranslationUnit()) { 86 if (isLocalContainerContext(DC)) 87 return dyn_cast<RecordDecl>(D); 88 D = cast<Decl>(DC); 89 DC = getEffectiveDeclContext(D); 90 } 91 return nullptr; 92 } 93 94 static const FunctionDecl *getStructor(const FunctionDecl *fn) { 95 if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate()) 96 return ftd->getTemplatedDecl(); 97 98 return fn; 99 } 100 101 static const NamedDecl *getStructor(const NamedDecl *decl) { 102 const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl); 103 return (fn ? getStructor(fn) : decl); 104 } 105 106 static bool isLambda(const NamedDecl *ND) { 107 const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND); 108 if (!Record) 109 return false; 110 111 return Record->isLambda(); 112 } 113 114 static const unsigned UnknownArity = ~0U; 115 116 class ItaniumMangleContextImpl : public ItaniumMangleContext { 117 typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy; 118 llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator; 119 llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier; 120 121 public: 122 explicit ItaniumMangleContextImpl(ASTContext &Context, 123 DiagnosticsEngine &Diags) 124 : ItaniumMangleContext(Context, Diags) {} 125 126 /// @name Mangler Entry Points 127 /// @{ 128 129 bool shouldMangleCXXName(const NamedDecl *D) override; 130 bool shouldMangleStringLiteral(const StringLiteral *) override { 131 return false; 132 } 133 void mangleCXXName(const NamedDecl *D, raw_ostream &) override; 134 void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk, 135 raw_ostream &) override; 136 void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type, 137 const ThisAdjustment &ThisAdjustment, 138 raw_ostream &) override; 139 void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber, 140 raw_ostream &) override; 141 void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override; 142 void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override; 143 void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset, 144 const CXXRecordDecl *Type, raw_ostream &) override; 145 void mangleCXXRTTI(QualType T, raw_ostream &) override; 146 void mangleCXXRTTIName(QualType T, raw_ostream &) override; 147 void mangleTypeName(QualType T, raw_ostream &) override; 148 void mangleCXXCtor(const CXXConstructorDecl *D, CXXCtorType Type, 149 raw_ostream &) override; 150 void mangleCXXDtor(const CXXDestructorDecl *D, CXXDtorType Type, 151 raw_ostream &) override; 152 153 void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override; 154 void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override; 155 void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override; 156 void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override; 157 void mangleDynamicAtExitDestructor(const VarDecl *D, 158 raw_ostream &Out) override; 159 void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override; 160 void mangleItaniumThreadLocalWrapper(const VarDecl *D, 161 raw_ostream &) override; 162 163 void mangleStringLiteral(const StringLiteral *, raw_ostream &) override; 164 165 bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) { 166 // Lambda closure types are already numbered. 167 if (isLambda(ND)) 168 return false; 169 170 // Anonymous tags are already numbered. 171 if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) { 172 if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl()) 173 return false; 174 } 175 176 // Use the canonical number for externally visible decls. 177 if (ND->isExternallyVisible()) { 178 unsigned discriminator = getASTContext().getManglingNumber(ND); 179 if (discriminator == 1) 180 return false; 181 disc = discriminator - 2; 182 return true; 183 } 184 185 // Make up a reasonable number for internal decls. 186 unsigned &discriminator = Uniquifier[ND]; 187 if (!discriminator) { 188 const DeclContext *DC = getEffectiveDeclContext(ND); 189 discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())]; 190 } 191 if (discriminator == 1) 192 return false; 193 disc = discriminator-2; 194 return true; 195 } 196 /// @} 197 }; 198 199 /// CXXNameMangler - Manage the mangling of a single name. 200 class CXXNameMangler { 201 ItaniumMangleContextImpl &Context; 202 raw_ostream &Out; 203 204 /// The "structor" is the top-level declaration being mangled, if 205 /// that's not a template specialization; otherwise it's the pattern 206 /// for that specialization. 207 const NamedDecl *Structor; 208 unsigned StructorType; 209 210 /// SeqID - The next subsitution sequence number. 211 unsigned SeqID; 212 213 class FunctionTypeDepthState { 214 unsigned Bits; 215 216 enum { InResultTypeMask = 1 }; 217 218 public: 219 FunctionTypeDepthState() : Bits(0) {} 220 221 /// The number of function types we're inside. 222 unsigned getDepth() const { 223 return Bits >> 1; 224 } 225 226 /// True if we're in the return type of the innermost function type. 227 bool isInResultType() const { 228 return Bits & InResultTypeMask; 229 } 230 231 FunctionTypeDepthState push() { 232 FunctionTypeDepthState tmp = *this; 233 Bits = (Bits & ~InResultTypeMask) + 2; 234 return tmp; 235 } 236 237 void enterResultType() { 238 Bits |= InResultTypeMask; 239 } 240 241 void leaveResultType() { 242 Bits &= ~InResultTypeMask; 243 } 244 245 void pop(FunctionTypeDepthState saved) { 246 assert(getDepth() == saved.getDepth() + 1); 247 Bits = saved.Bits; 248 } 249 250 } FunctionTypeDepth; 251 252 llvm::DenseMap<uintptr_t, unsigned> Substitutions; 253 254 ASTContext &getASTContext() const { return Context.getASTContext(); } 255 256 public: 257 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, 258 const NamedDecl *D = nullptr) 259 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(0), 260 SeqID(0) { 261 // These can't be mangled without a ctor type or dtor type. 262 assert(!D || (!isa<CXXDestructorDecl>(D) && 263 !isa<CXXConstructorDecl>(D))); 264 } 265 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, 266 const CXXConstructorDecl *D, CXXCtorType Type) 267 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), 268 SeqID(0) { } 269 CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_, 270 const CXXDestructorDecl *D, CXXDtorType Type) 271 : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type), 272 SeqID(0) { } 273 274 #if MANGLE_CHECKER 275 ~CXXNameMangler() { 276 if (Out.str()[0] == '\01') 277 return; 278 279 int status = 0; 280 char *result = abi::__cxa_demangle(Out.str().str().c_str(), 0, 0, &status); 281 assert(status == 0 && "Could not demangle mangled name!"); 282 free(result); 283 } 284 #endif 285 raw_ostream &getStream() { return Out; } 286 287 void mangle(const NamedDecl *D, StringRef Prefix = "_Z"); 288 void mangleCallOffset(int64_t NonVirtual, int64_t Virtual); 289 void mangleNumber(const llvm::APSInt &I); 290 void mangleNumber(int64_t Number); 291 void mangleFloat(const llvm::APFloat &F); 292 void mangleFunctionEncoding(const FunctionDecl *FD); 293 void mangleSeqID(unsigned SeqID); 294 void mangleName(const NamedDecl *ND); 295 void mangleType(QualType T); 296 void mangleNameOrStandardSubstitution(const NamedDecl *ND); 297 298 private: 299 300 bool mangleSubstitution(const NamedDecl *ND); 301 bool mangleSubstitution(QualType T); 302 bool mangleSubstitution(TemplateName Template); 303 bool mangleSubstitution(uintptr_t Ptr); 304 305 void mangleExistingSubstitution(QualType type); 306 void mangleExistingSubstitution(TemplateName name); 307 308 bool mangleStandardSubstitution(const NamedDecl *ND); 309 310 void addSubstitution(const NamedDecl *ND) { 311 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 312 313 addSubstitution(reinterpret_cast<uintptr_t>(ND)); 314 } 315 void addSubstitution(QualType T); 316 void addSubstitution(TemplateName Template); 317 void addSubstitution(uintptr_t Ptr); 318 319 void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier, 320 NamedDecl *firstQualifierLookup, 321 bool recursive = false); 322 void mangleUnresolvedName(NestedNameSpecifier *qualifier, 323 NamedDecl *firstQualifierLookup, 324 DeclarationName name, 325 unsigned KnownArity = UnknownArity); 326 327 void mangleName(const TemplateDecl *TD, 328 const TemplateArgument *TemplateArgs, 329 unsigned NumTemplateArgs); 330 void mangleUnqualifiedName(const NamedDecl *ND) { 331 mangleUnqualifiedName(ND, ND->getDeclName(), UnknownArity); 332 } 333 void mangleUnqualifiedName(const NamedDecl *ND, DeclarationName Name, 334 unsigned KnownArity); 335 void mangleUnscopedName(const NamedDecl *ND); 336 void mangleUnscopedTemplateName(const TemplateDecl *ND); 337 void mangleUnscopedTemplateName(TemplateName); 338 void mangleSourceName(const IdentifierInfo *II); 339 void mangleLocalName(const Decl *D); 340 void mangleBlockForPrefix(const BlockDecl *Block); 341 void mangleUnqualifiedBlock(const BlockDecl *Block); 342 void mangleLambda(const CXXRecordDecl *Lambda); 343 void mangleNestedName(const NamedDecl *ND, const DeclContext *DC, 344 bool NoFunction=false); 345 void mangleNestedName(const TemplateDecl *TD, 346 const TemplateArgument *TemplateArgs, 347 unsigned NumTemplateArgs); 348 void manglePrefix(NestedNameSpecifier *qualifier); 349 void manglePrefix(const DeclContext *DC, bool NoFunction=false); 350 void manglePrefix(QualType type); 351 void mangleTemplatePrefix(const TemplateDecl *ND, bool NoFunction=false); 352 void mangleTemplatePrefix(TemplateName Template); 353 void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity); 354 void mangleQualifiers(Qualifiers Quals); 355 void mangleRefQualifier(RefQualifierKind RefQualifier); 356 357 void mangleObjCMethodName(const ObjCMethodDecl *MD); 358 359 // Declare manglers for every type class. 360 #define ABSTRACT_TYPE(CLASS, PARENT) 361 #define NON_CANONICAL_TYPE(CLASS, PARENT) 362 #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T); 363 #include "clang/AST/TypeNodes.def" 364 365 void mangleType(const TagType*); 366 void mangleType(TemplateName); 367 void mangleBareFunctionType(const FunctionType *T, 368 bool MangleReturnType); 369 void mangleNeonVectorType(const VectorType *T); 370 void mangleAArch64NeonVectorType(const VectorType *T); 371 372 void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value); 373 void mangleMemberExpr(const Expr *base, bool isArrow, 374 NestedNameSpecifier *qualifier, 375 NamedDecl *firstQualifierLookup, 376 DeclarationName name, 377 unsigned knownArity); 378 void mangleCastExpression(const Expr *E, StringRef CastEncoding); 379 void mangleExpression(const Expr *E, unsigned Arity = UnknownArity); 380 void mangleCXXCtorType(CXXCtorType T); 381 void mangleCXXDtorType(CXXDtorType T); 382 383 void mangleTemplateArgs(const ASTTemplateArgumentListInfo &TemplateArgs); 384 void mangleTemplateArgs(const TemplateArgument *TemplateArgs, 385 unsigned NumTemplateArgs); 386 void mangleTemplateArgs(const TemplateArgumentList &AL); 387 void mangleTemplateArg(TemplateArgument A); 388 389 void mangleTemplateParameter(unsigned Index); 390 391 void mangleFunctionParam(const ParmVarDecl *parm); 392 }; 393 394 } 395 396 bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) { 397 const FunctionDecl *FD = dyn_cast<FunctionDecl>(D); 398 if (FD) { 399 LanguageLinkage L = FD->getLanguageLinkage(); 400 // Overloadable functions need mangling. 401 if (FD->hasAttr<OverloadableAttr>()) 402 return true; 403 404 // "main" is not mangled. 405 if (FD->isMain()) 406 return false; 407 408 // C++ functions and those whose names are not a simple identifier need 409 // mangling. 410 if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage) 411 return true; 412 413 // C functions are not mangled. 414 if (L == CLanguageLinkage) 415 return false; 416 } 417 418 // Otherwise, no mangling is done outside C++ mode. 419 if (!getASTContext().getLangOpts().CPlusPlus) 420 return false; 421 422 const VarDecl *VD = dyn_cast<VarDecl>(D); 423 if (VD) { 424 // C variables are not mangled. 425 if (VD->isExternC()) 426 return false; 427 428 // Variables at global scope with non-internal linkage are not mangled 429 const DeclContext *DC = getEffectiveDeclContext(D); 430 // Check for extern variable declared locally. 431 if (DC->isFunctionOrMethod() && D->hasLinkage()) 432 while (!DC->isNamespace() && !DC->isTranslationUnit()) 433 DC = getEffectiveParentContext(DC); 434 if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage && 435 !isa<VarTemplateSpecializationDecl>(D)) 436 return false; 437 } 438 439 return true; 440 } 441 442 void CXXNameMangler::mangle(const NamedDecl *D, StringRef Prefix) { 443 // <mangled-name> ::= _Z <encoding> 444 // ::= <data name> 445 // ::= <special-name> 446 Out << Prefix; 447 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) 448 mangleFunctionEncoding(FD); 449 else if (const VarDecl *VD = dyn_cast<VarDecl>(D)) 450 mangleName(VD); 451 else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(D)) 452 mangleName(IFD->getAnonField()); 453 else 454 mangleName(cast<FieldDecl>(D)); 455 } 456 457 void CXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) { 458 // <encoding> ::= <function name> <bare-function-type> 459 mangleName(FD); 460 461 // Don't mangle in the type if this isn't a decl we should typically mangle. 462 if (!Context.shouldMangleDeclName(FD)) 463 return; 464 465 if (FD->hasAttr<EnableIfAttr>()) { 466 FunctionTypeDepthState Saved = FunctionTypeDepth.push(); 467 Out << "Ua9enable_ifI"; 468 // FIXME: specific_attr_iterator iterates in reverse order. Fix that and use 469 // it here. 470 for (AttrVec::const_reverse_iterator I = FD->getAttrs().rbegin(), 471 E = FD->getAttrs().rend(); 472 I != E; ++I) { 473 EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I); 474 if (!EIA) 475 continue; 476 Out << 'X'; 477 mangleExpression(EIA->getCond()); 478 Out << 'E'; 479 } 480 Out << 'E'; 481 FunctionTypeDepth.pop(Saved); 482 } 483 484 // Whether the mangling of a function type includes the return type depends on 485 // the context and the nature of the function. The rules for deciding whether 486 // the return type is included are: 487 // 488 // 1. Template functions (names or types) have return types encoded, with 489 // the exceptions listed below. 490 // 2. Function types not appearing as part of a function name mangling, 491 // e.g. parameters, pointer types, etc., have return type encoded, with the 492 // exceptions listed below. 493 // 3. Non-template function names do not have return types encoded. 494 // 495 // The exceptions mentioned in (1) and (2) above, for which the return type is 496 // never included, are 497 // 1. Constructors. 498 // 2. Destructors. 499 // 3. Conversion operator functions, e.g. operator int. 500 bool MangleReturnType = false; 501 if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) { 502 if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) || 503 isa<CXXConversionDecl>(FD))) 504 MangleReturnType = true; 505 506 // Mangle the type of the primary template. 507 FD = PrimaryTemplate->getTemplatedDecl(); 508 } 509 510 mangleBareFunctionType(FD->getType()->getAs<FunctionType>(), 511 MangleReturnType); 512 } 513 514 static const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC) { 515 while (isa<LinkageSpecDecl>(DC)) { 516 DC = getEffectiveParentContext(DC); 517 } 518 519 return DC; 520 } 521 522 /// isStd - Return whether a given namespace is the 'std' namespace. 523 static bool isStd(const NamespaceDecl *NS) { 524 if (!IgnoreLinkageSpecDecls(getEffectiveParentContext(NS)) 525 ->isTranslationUnit()) 526 return false; 527 528 const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier(); 529 return II && II->isStr("std"); 530 } 531 532 // isStdNamespace - Return whether a given decl context is a toplevel 'std' 533 // namespace. 534 static bool isStdNamespace(const DeclContext *DC) { 535 if (!DC->isNamespace()) 536 return false; 537 538 return isStd(cast<NamespaceDecl>(DC)); 539 } 540 541 static const TemplateDecl * 542 isTemplate(const NamedDecl *ND, const TemplateArgumentList *&TemplateArgs) { 543 // Check if we have a function template. 544 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)){ 545 if (const TemplateDecl *TD = FD->getPrimaryTemplate()) { 546 TemplateArgs = FD->getTemplateSpecializationArgs(); 547 return TD; 548 } 549 } 550 551 // Check if we have a class template. 552 if (const ClassTemplateSpecializationDecl *Spec = 553 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 554 TemplateArgs = &Spec->getTemplateArgs(); 555 return Spec->getSpecializedTemplate(); 556 } 557 558 // Check if we have a variable template. 559 if (const VarTemplateSpecializationDecl *Spec = 560 dyn_cast<VarTemplateSpecializationDecl>(ND)) { 561 TemplateArgs = &Spec->getTemplateArgs(); 562 return Spec->getSpecializedTemplate(); 563 } 564 565 return nullptr; 566 } 567 568 void CXXNameMangler::mangleName(const NamedDecl *ND) { 569 // <name> ::= <nested-name> 570 // ::= <unscoped-name> 571 // ::= <unscoped-template-name> <template-args> 572 // ::= <local-name> 573 // 574 const DeclContext *DC = getEffectiveDeclContext(ND); 575 576 // If this is an extern variable declared locally, the relevant DeclContext 577 // is that of the containing namespace, or the translation unit. 578 // FIXME: This is a hack; extern variables declared locally should have 579 // a proper semantic declaration context! 580 if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND)) 581 while (!DC->isNamespace() && !DC->isTranslationUnit()) 582 DC = getEffectiveParentContext(DC); 583 else if (GetLocalClassDecl(ND)) { 584 mangleLocalName(ND); 585 return; 586 } 587 588 DC = IgnoreLinkageSpecDecls(DC); 589 590 if (DC->isTranslationUnit() || isStdNamespace(DC)) { 591 // Check if we have a template. 592 const TemplateArgumentList *TemplateArgs = nullptr; 593 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { 594 mangleUnscopedTemplateName(TD); 595 mangleTemplateArgs(*TemplateArgs); 596 return; 597 } 598 599 mangleUnscopedName(ND); 600 return; 601 } 602 603 if (isLocalContainerContext(DC)) { 604 mangleLocalName(ND); 605 return; 606 } 607 608 mangleNestedName(ND, DC); 609 } 610 void CXXNameMangler::mangleName(const TemplateDecl *TD, 611 const TemplateArgument *TemplateArgs, 612 unsigned NumTemplateArgs) { 613 const DeclContext *DC = IgnoreLinkageSpecDecls(getEffectiveDeclContext(TD)); 614 615 if (DC->isTranslationUnit() || isStdNamespace(DC)) { 616 mangleUnscopedTemplateName(TD); 617 mangleTemplateArgs(TemplateArgs, NumTemplateArgs); 618 } else { 619 mangleNestedName(TD, TemplateArgs, NumTemplateArgs); 620 } 621 } 622 623 void CXXNameMangler::mangleUnscopedName(const NamedDecl *ND) { 624 // <unscoped-name> ::= <unqualified-name> 625 // ::= St <unqualified-name> # ::std:: 626 627 if (isStdNamespace(IgnoreLinkageSpecDecls(getEffectiveDeclContext(ND)))) 628 Out << "St"; 629 630 mangleUnqualifiedName(ND); 631 } 632 633 void CXXNameMangler::mangleUnscopedTemplateName(const TemplateDecl *ND) { 634 // <unscoped-template-name> ::= <unscoped-name> 635 // ::= <substitution> 636 if (mangleSubstitution(ND)) 637 return; 638 639 // <template-template-param> ::= <template-param> 640 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) 641 mangleTemplateParameter(TTP->getIndex()); 642 else 643 mangleUnscopedName(ND->getTemplatedDecl()); 644 645 addSubstitution(ND); 646 } 647 648 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) { 649 // <unscoped-template-name> ::= <unscoped-name> 650 // ::= <substitution> 651 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 652 return mangleUnscopedTemplateName(TD); 653 654 if (mangleSubstitution(Template)) 655 return; 656 657 DependentTemplateName *Dependent = Template.getAsDependentTemplateName(); 658 assert(Dependent && "Not a dependent template name?"); 659 if (const IdentifierInfo *Id = Dependent->getIdentifier()) 660 mangleSourceName(Id); 661 else 662 mangleOperatorName(Dependent->getOperator(), UnknownArity); 663 664 addSubstitution(Template); 665 } 666 667 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) { 668 // ABI: 669 // Floating-point literals are encoded using a fixed-length 670 // lowercase hexadecimal string corresponding to the internal 671 // representation (IEEE on Itanium), high-order bytes first, 672 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f 673 // on Itanium. 674 // The 'without leading zeroes' thing seems to be an editorial 675 // mistake; see the discussion on cxx-abi-dev beginning on 676 // 2012-01-16. 677 678 // Our requirements here are just barely weird enough to justify 679 // using a custom algorithm instead of post-processing APInt::toString(). 680 681 llvm::APInt valueBits = f.bitcastToAPInt(); 682 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4; 683 assert(numCharacters != 0); 684 685 // Allocate a buffer of the right number of characters. 686 SmallVector<char, 20> buffer; 687 buffer.set_size(numCharacters); 688 689 // Fill the buffer left-to-right. 690 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) { 691 // The bit-index of the next hex digit. 692 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1); 693 694 // Project out 4 bits starting at 'digitIndex'. 695 llvm::integerPart hexDigit 696 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth]; 697 hexDigit >>= (digitBitIndex % llvm::integerPartWidth); 698 hexDigit &= 0xF; 699 700 // Map that over to a lowercase hex digit. 701 static const char charForHex[16] = { 702 '0', '1', '2', '3', '4', '5', '6', '7', 703 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 704 }; 705 buffer[stringIndex] = charForHex[hexDigit]; 706 } 707 708 Out.write(buffer.data(), numCharacters); 709 } 710 711 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) { 712 if (Value.isSigned() && Value.isNegative()) { 713 Out << 'n'; 714 Value.abs().print(Out, /*signed*/ false); 715 } else { 716 Value.print(Out, /*signed*/ false); 717 } 718 } 719 720 void CXXNameMangler::mangleNumber(int64_t Number) { 721 // <number> ::= [n] <non-negative decimal integer> 722 if (Number < 0) { 723 Out << 'n'; 724 Number = -Number; 725 } 726 727 Out << Number; 728 } 729 730 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) { 731 // <call-offset> ::= h <nv-offset> _ 732 // ::= v <v-offset> _ 733 // <nv-offset> ::= <offset number> # non-virtual base override 734 // <v-offset> ::= <offset number> _ <virtual offset number> 735 // # virtual base override, with vcall offset 736 if (!Virtual) { 737 Out << 'h'; 738 mangleNumber(NonVirtual); 739 Out << '_'; 740 return; 741 } 742 743 Out << 'v'; 744 mangleNumber(NonVirtual); 745 Out << '_'; 746 mangleNumber(Virtual); 747 Out << '_'; 748 } 749 750 void CXXNameMangler::manglePrefix(QualType type) { 751 if (const TemplateSpecializationType *TST = 752 type->getAs<TemplateSpecializationType>()) { 753 if (!mangleSubstitution(QualType(TST, 0))) { 754 mangleTemplatePrefix(TST->getTemplateName()); 755 756 // FIXME: GCC does not appear to mangle the template arguments when 757 // the template in question is a dependent template name. Should we 758 // emulate that badness? 759 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs()); 760 addSubstitution(QualType(TST, 0)); 761 } 762 } else if (const DependentTemplateSpecializationType *DTST 763 = type->getAs<DependentTemplateSpecializationType>()) { 764 TemplateName Template 765 = getASTContext().getDependentTemplateName(DTST->getQualifier(), 766 DTST->getIdentifier()); 767 mangleTemplatePrefix(Template); 768 769 // FIXME: GCC does not appear to mangle the template arguments when 770 // the template in question is a dependent template name. Should we 771 // emulate that badness? 772 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs()); 773 } else { 774 // We use the QualType mangle type variant here because it handles 775 // substitutions. 776 mangleType(type); 777 } 778 } 779 780 /// Mangle everything prior to the base-unresolved-name in an unresolved-name. 781 /// 782 /// \param firstQualifierLookup - the entity found by unqualified lookup 783 /// for the first name in the qualifier, if this is for a member expression 784 /// \param recursive - true if this is being called recursively, 785 /// i.e. if there is more prefix "to the right". 786 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier, 787 NamedDecl *firstQualifierLookup, 788 bool recursive) { 789 790 // x, ::x 791 // <unresolved-name> ::= [gs] <base-unresolved-name> 792 793 // T::x / decltype(p)::x 794 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name> 795 796 // T::N::x /decltype(p)::N::x 797 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E 798 // <base-unresolved-name> 799 800 // A::x, N::y, A<T>::z; "gs" means leading "::" 801 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E 802 // <base-unresolved-name> 803 804 switch (qualifier->getKind()) { 805 case NestedNameSpecifier::Global: 806 Out << "gs"; 807 808 // We want an 'sr' unless this is the entire NNS. 809 if (recursive) 810 Out << "sr"; 811 812 // We never want an 'E' here. 813 return; 814 815 case NestedNameSpecifier::Super: 816 llvm_unreachable("Can't mangle __super specifier"); 817 818 case NestedNameSpecifier::Namespace: 819 if (qualifier->getPrefix()) 820 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup, 821 /*recursive*/ true); 822 else 823 Out << "sr"; 824 mangleSourceName(qualifier->getAsNamespace()->getIdentifier()); 825 break; 826 case NestedNameSpecifier::NamespaceAlias: 827 if (qualifier->getPrefix()) 828 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup, 829 /*recursive*/ true); 830 else 831 Out << "sr"; 832 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier()); 833 break; 834 835 case NestedNameSpecifier::TypeSpec: 836 case NestedNameSpecifier::TypeSpecWithTemplate: { 837 const Type *type = qualifier->getAsType(); 838 839 // We only want to use an unresolved-type encoding if this is one of: 840 // - a decltype 841 // - a template type parameter 842 // - a template template parameter with arguments 843 // In all of these cases, we should have no prefix. 844 if (qualifier->getPrefix()) { 845 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup, 846 /*recursive*/ true); 847 } else { 848 // Otherwise, all the cases want this. 849 Out << "sr"; 850 } 851 852 // Only certain other types are valid as prefixes; enumerate them. 853 switch (type->getTypeClass()) { 854 case Type::Builtin: 855 case Type::Complex: 856 case Type::Adjusted: 857 case Type::Decayed: 858 case Type::Pointer: 859 case Type::BlockPointer: 860 case Type::LValueReference: 861 case Type::RValueReference: 862 case Type::MemberPointer: 863 case Type::ConstantArray: 864 case Type::IncompleteArray: 865 case Type::VariableArray: 866 case Type::DependentSizedArray: 867 case Type::DependentSizedExtVector: 868 case Type::Vector: 869 case Type::ExtVector: 870 case Type::FunctionProto: 871 case Type::FunctionNoProto: 872 case Type::Enum: 873 case Type::Paren: 874 case Type::Elaborated: 875 case Type::Attributed: 876 case Type::Auto: 877 case Type::PackExpansion: 878 case Type::ObjCObject: 879 case Type::ObjCInterface: 880 case Type::ObjCObjectPointer: 881 case Type::Atomic: 882 llvm_unreachable("type is illegal as a nested name specifier"); 883 884 case Type::SubstTemplateTypeParmPack: 885 // FIXME: not clear how to mangle this! 886 // template <class T...> class A { 887 // template <class U...> void foo(decltype(T::foo(U())) x...); 888 // }; 889 Out << "_SUBSTPACK_"; 890 break; 891 892 // <unresolved-type> ::= <template-param> 893 // ::= <decltype> 894 // ::= <template-template-param> <template-args> 895 // (this last is not official yet) 896 case Type::TypeOfExpr: 897 case Type::TypeOf: 898 case Type::Decltype: 899 case Type::TemplateTypeParm: 900 case Type::UnaryTransform: 901 case Type::SubstTemplateTypeParm: 902 unresolvedType: 903 assert(!qualifier->getPrefix()); 904 905 // We only get here recursively if we're followed by identifiers. 906 if (recursive) Out << 'N'; 907 908 // This seems to do everything we want. It's not really 909 // sanctioned for a substituted template parameter, though. 910 mangleType(QualType(type, 0)); 911 912 // We never want to print 'E' directly after an unresolved-type, 913 // so we return directly. 914 return; 915 916 case Type::Typedef: 917 mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier()); 918 break; 919 920 case Type::UnresolvedUsing: 921 mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl() 922 ->getIdentifier()); 923 break; 924 925 case Type::Record: 926 mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier()); 927 break; 928 929 case Type::TemplateSpecialization: { 930 const TemplateSpecializationType *tst 931 = cast<TemplateSpecializationType>(type); 932 TemplateName name = tst->getTemplateName(); 933 switch (name.getKind()) { 934 case TemplateName::Template: 935 case TemplateName::QualifiedTemplate: { 936 TemplateDecl *temp = name.getAsTemplateDecl(); 937 938 // If the base is a template template parameter, this is an 939 // unresolved type. 940 assert(temp && "no template for template specialization type"); 941 if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType; 942 943 mangleSourceName(temp->getIdentifier()); 944 break; 945 } 946 947 case TemplateName::OverloadedTemplate: 948 case TemplateName::DependentTemplate: 949 llvm_unreachable("invalid base for a template specialization type"); 950 951 case TemplateName::SubstTemplateTemplateParm: { 952 SubstTemplateTemplateParmStorage *subst 953 = name.getAsSubstTemplateTemplateParm(); 954 mangleExistingSubstitution(subst->getReplacement()); 955 break; 956 } 957 958 case TemplateName::SubstTemplateTemplateParmPack: { 959 // FIXME: not clear how to mangle this! 960 // template <template <class U> class T...> class A { 961 // template <class U...> void foo(decltype(T<U>::foo) x...); 962 // }; 963 Out << "_SUBSTPACK_"; 964 break; 965 } 966 } 967 968 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs()); 969 break; 970 } 971 972 case Type::InjectedClassName: 973 mangleSourceName(cast<InjectedClassNameType>(type)->getDecl() 974 ->getIdentifier()); 975 break; 976 977 case Type::DependentName: 978 mangleSourceName(cast<DependentNameType>(type)->getIdentifier()); 979 break; 980 981 case Type::DependentTemplateSpecialization: { 982 const DependentTemplateSpecializationType *tst 983 = cast<DependentTemplateSpecializationType>(type); 984 mangleSourceName(tst->getIdentifier()); 985 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs()); 986 break; 987 } 988 } 989 break; 990 } 991 992 case NestedNameSpecifier::Identifier: 993 // Member expressions can have these without prefixes. 994 if (qualifier->getPrefix()) { 995 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup, 996 /*recursive*/ true); 997 } else if (firstQualifierLookup) { 998 999 // Try to make a proper qualifier out of the lookup result, and 1000 // then just recurse on that. 1001 NestedNameSpecifier *newQualifier; 1002 if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) { 1003 QualType type = getASTContext().getTypeDeclType(typeDecl); 1004 1005 // Pretend we had a different nested name specifier. 1006 newQualifier = NestedNameSpecifier::Create(getASTContext(), 1007 /*prefix*/ nullptr, 1008 /*template*/ false, 1009 type.getTypePtr()); 1010 } else if (NamespaceDecl *nspace = 1011 dyn_cast<NamespaceDecl>(firstQualifierLookup)) { 1012 newQualifier = NestedNameSpecifier::Create(getASTContext(), 1013 /*prefix*/ nullptr, 1014 nspace); 1015 } else if (NamespaceAliasDecl *alias = 1016 dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) { 1017 newQualifier = NestedNameSpecifier::Create(getASTContext(), 1018 /*prefix*/ nullptr, 1019 alias); 1020 } else { 1021 // No sensible mangling to do here. 1022 newQualifier = nullptr; 1023 } 1024 1025 if (newQualifier) 1026 return mangleUnresolvedPrefix(newQualifier, /*lookup*/ nullptr, 1027 recursive); 1028 1029 } else { 1030 Out << "sr"; 1031 } 1032 1033 mangleSourceName(qualifier->getAsIdentifier()); 1034 break; 1035 } 1036 1037 // If this was the innermost part of the NNS, and we fell out to 1038 // here, append an 'E'. 1039 if (!recursive) 1040 Out << 'E'; 1041 } 1042 1043 /// Mangle an unresolved-name, which is generally used for names which 1044 /// weren't resolved to specific entities. 1045 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier, 1046 NamedDecl *firstQualifierLookup, 1047 DeclarationName name, 1048 unsigned knownArity) { 1049 if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup); 1050 mangleUnqualifiedName(nullptr, name, knownArity); 1051 } 1052 1053 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND, 1054 DeclarationName Name, 1055 unsigned KnownArity) { 1056 // <unqualified-name> ::= <operator-name> 1057 // ::= <ctor-dtor-name> 1058 // ::= <source-name> 1059 switch (Name.getNameKind()) { 1060 case DeclarationName::Identifier: { 1061 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) { 1062 // We must avoid conflicts between internally- and externally- 1063 // linked variable and function declaration names in the same TU: 1064 // void test() { extern void foo(); } 1065 // static void foo(); 1066 // This naming convention is the same as that followed by GCC, 1067 // though it shouldn't actually matter. 1068 if (ND && ND->getFormalLinkage() == InternalLinkage && 1069 getEffectiveDeclContext(ND)->isFileContext()) 1070 Out << 'L'; 1071 1072 mangleSourceName(II); 1073 break; 1074 } 1075 1076 // Otherwise, an anonymous entity. We must have a declaration. 1077 assert(ND && "mangling empty name without declaration"); 1078 1079 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 1080 if (NS->isAnonymousNamespace()) { 1081 // This is how gcc mangles these names. 1082 Out << "12_GLOBAL__N_1"; 1083 break; 1084 } 1085 } 1086 1087 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 1088 // We must have an anonymous union or struct declaration. 1089 const RecordDecl *RD = 1090 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl()); 1091 1092 // Itanium C++ ABI 5.1.2: 1093 // 1094 // For the purposes of mangling, the name of an anonymous union is 1095 // considered to be the name of the first named data member found by a 1096 // pre-order, depth-first, declaration-order walk of the data members of 1097 // the anonymous union. If there is no such data member (i.e., if all of 1098 // the data members in the union are unnamed), then there is no way for 1099 // a program to refer to the anonymous union, and there is therefore no 1100 // need to mangle its name. 1101 assert(RD->isAnonymousStructOrUnion() 1102 && "Expected anonymous struct or union!"); 1103 const FieldDecl *FD = RD->findFirstNamedDataMember(); 1104 1105 // It's actually possible for various reasons for us to get here 1106 // with an empty anonymous struct / union. Fortunately, it 1107 // doesn't really matter what name we generate. 1108 if (!FD) break; 1109 assert(FD->getIdentifier() && "Data member name isn't an identifier!"); 1110 1111 mangleSourceName(FD->getIdentifier()); 1112 break; 1113 } 1114 1115 // Class extensions have no name as a category, and it's possible 1116 // for them to be the semantic parent of certain declarations 1117 // (primarily, tag decls defined within declarations). Such 1118 // declarations will always have internal linkage, so the name 1119 // doesn't really matter, but we shouldn't crash on them. For 1120 // safety, just handle all ObjC containers here. 1121 if (isa<ObjCContainerDecl>(ND)) 1122 break; 1123 1124 // We must have an anonymous struct. 1125 const TagDecl *TD = cast<TagDecl>(ND); 1126 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) { 1127 assert(TD->getDeclContext() == D->getDeclContext() && 1128 "Typedef should not be in another decl context!"); 1129 assert(D->getDeclName().getAsIdentifierInfo() && 1130 "Typedef was not named!"); 1131 mangleSourceName(D->getDeclName().getAsIdentifierInfo()); 1132 break; 1133 } 1134 1135 // <unnamed-type-name> ::= <closure-type-name> 1136 // 1137 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _ 1138 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'. 1139 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) { 1140 if (Record->isLambda() && Record->getLambdaManglingNumber()) { 1141 mangleLambda(Record); 1142 break; 1143 } 1144 } 1145 1146 if (TD->isExternallyVisible()) { 1147 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD); 1148 Out << "Ut"; 1149 if (UnnamedMangle > 1) 1150 Out << llvm::utostr(UnnamedMangle - 2); 1151 Out << '_'; 1152 break; 1153 } 1154 1155 // Get a unique id for the anonymous struct. 1156 unsigned AnonStructId = Context.getAnonymousStructId(TD); 1157 1158 // Mangle it as a source name in the form 1159 // [n] $_<id> 1160 // where n is the length of the string. 1161 SmallString<8> Str; 1162 Str += "$_"; 1163 Str += llvm::utostr(AnonStructId); 1164 1165 Out << Str.size(); 1166 Out << Str.str(); 1167 break; 1168 } 1169 1170 case DeclarationName::ObjCZeroArgSelector: 1171 case DeclarationName::ObjCOneArgSelector: 1172 case DeclarationName::ObjCMultiArgSelector: 1173 llvm_unreachable("Can't mangle Objective-C selector names here!"); 1174 1175 case DeclarationName::CXXConstructorName: 1176 if (ND == Structor) 1177 // If the named decl is the C++ constructor we're mangling, use the type 1178 // we were given. 1179 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType)); 1180 else 1181 // Otherwise, use the complete constructor name. This is relevant if a 1182 // class with a constructor is declared within a constructor. 1183 mangleCXXCtorType(Ctor_Complete); 1184 break; 1185 1186 case DeclarationName::CXXDestructorName: 1187 if (ND == Structor) 1188 // If the named decl is the C++ destructor we're mangling, use the type we 1189 // were given. 1190 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType)); 1191 else 1192 // Otherwise, use the complete destructor name. This is relevant if a 1193 // class with a destructor is declared within a destructor. 1194 mangleCXXDtorType(Dtor_Complete); 1195 break; 1196 1197 case DeclarationName::CXXConversionFunctionName: 1198 // <operator-name> ::= cv <type> # (cast) 1199 Out << "cv"; 1200 mangleType(Name.getCXXNameType()); 1201 break; 1202 1203 case DeclarationName::CXXOperatorName: { 1204 unsigned Arity; 1205 if (ND) { 1206 Arity = cast<FunctionDecl>(ND)->getNumParams(); 1207 1208 // If we have a C++ member function, we need to include the 'this' pointer. 1209 // FIXME: This does not make sense for operators that are static, but their 1210 // names stay the same regardless of the arity (operator new for instance). 1211 if (isa<CXXMethodDecl>(ND)) 1212 Arity++; 1213 } else 1214 Arity = KnownArity; 1215 1216 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity); 1217 break; 1218 } 1219 1220 case DeclarationName::CXXLiteralOperatorName: 1221 // FIXME: This mangling is not yet official. 1222 Out << "li"; 1223 mangleSourceName(Name.getCXXLiteralIdentifier()); 1224 break; 1225 1226 case DeclarationName::CXXUsingDirective: 1227 llvm_unreachable("Can't mangle a using directive name!"); 1228 } 1229 } 1230 1231 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) { 1232 // <source-name> ::= <positive length number> <identifier> 1233 // <number> ::= [n] <non-negative decimal integer> 1234 // <identifier> ::= <unqualified source code identifier> 1235 Out << II->getLength() << II->getName(); 1236 } 1237 1238 void CXXNameMangler::mangleNestedName(const NamedDecl *ND, 1239 const DeclContext *DC, 1240 bool NoFunction) { 1241 // <nested-name> 1242 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E 1243 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> 1244 // <template-args> E 1245 1246 Out << 'N'; 1247 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) { 1248 Qualifiers MethodQuals = 1249 Qualifiers::fromCVRMask(Method->getTypeQualifiers()); 1250 // We do not consider restrict a distinguishing attribute for overloading 1251 // purposes so we must not mangle it. 1252 MethodQuals.removeRestrict(); 1253 mangleQualifiers(MethodQuals); 1254 mangleRefQualifier(Method->getRefQualifier()); 1255 } 1256 1257 // Check if we have a template. 1258 const TemplateArgumentList *TemplateArgs = nullptr; 1259 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { 1260 mangleTemplatePrefix(TD, NoFunction); 1261 mangleTemplateArgs(*TemplateArgs); 1262 } 1263 else { 1264 manglePrefix(DC, NoFunction); 1265 mangleUnqualifiedName(ND); 1266 } 1267 1268 Out << 'E'; 1269 } 1270 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD, 1271 const TemplateArgument *TemplateArgs, 1272 unsigned NumTemplateArgs) { 1273 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E 1274 1275 Out << 'N'; 1276 1277 mangleTemplatePrefix(TD); 1278 mangleTemplateArgs(TemplateArgs, NumTemplateArgs); 1279 1280 Out << 'E'; 1281 } 1282 1283 void CXXNameMangler::mangleLocalName(const Decl *D) { 1284 // <local-name> := Z <function encoding> E <entity name> [<discriminator>] 1285 // := Z <function encoding> E s [<discriminator>] 1286 // <local-name> := Z <function encoding> E d [ <parameter number> ] 1287 // _ <entity name> 1288 // <discriminator> := _ <non-negative number> 1289 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D)); 1290 const RecordDecl *RD = GetLocalClassDecl(D); 1291 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D); 1292 1293 Out << 'Z'; 1294 1295 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC)) 1296 mangleObjCMethodName(MD); 1297 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) 1298 mangleBlockForPrefix(BD); 1299 else 1300 mangleFunctionEncoding(cast<FunctionDecl>(DC)); 1301 1302 Out << 'E'; 1303 1304 if (RD) { 1305 // The parameter number is omitted for the last parameter, 0 for the 1306 // second-to-last parameter, 1 for the third-to-last parameter, etc. The 1307 // <entity name> will of course contain a <closure-type-name>: Its 1308 // numbering will be local to the particular argument in which it appears 1309 // -- other default arguments do not affect its encoding. 1310 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD); 1311 if (CXXRD->isLambda()) { 1312 if (const ParmVarDecl *Parm 1313 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) { 1314 if (const FunctionDecl *Func 1315 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) { 1316 Out << 'd'; 1317 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex(); 1318 if (Num > 1) 1319 mangleNumber(Num - 2); 1320 Out << '_'; 1321 } 1322 } 1323 } 1324 1325 // Mangle the name relative to the closest enclosing function. 1326 // equality ok because RD derived from ND above 1327 if (D == RD) { 1328 mangleUnqualifiedName(RD); 1329 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 1330 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/); 1331 mangleUnqualifiedBlock(BD); 1332 } else { 1333 const NamedDecl *ND = cast<NamedDecl>(D); 1334 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/); 1335 } 1336 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 1337 // Mangle a block in a default parameter; see above explanation for 1338 // lambdas. 1339 if (const ParmVarDecl *Parm 1340 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) { 1341 if (const FunctionDecl *Func 1342 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) { 1343 Out << 'd'; 1344 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex(); 1345 if (Num > 1) 1346 mangleNumber(Num - 2); 1347 Out << '_'; 1348 } 1349 } 1350 1351 mangleUnqualifiedBlock(BD); 1352 } else { 1353 mangleUnqualifiedName(cast<NamedDecl>(D)); 1354 } 1355 1356 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) { 1357 unsigned disc; 1358 if (Context.getNextDiscriminator(ND, disc)) { 1359 if (disc < 10) 1360 Out << '_' << disc; 1361 else 1362 Out << "__" << disc << '_'; 1363 } 1364 } 1365 } 1366 1367 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) { 1368 if (GetLocalClassDecl(Block)) { 1369 mangleLocalName(Block); 1370 return; 1371 } 1372 const DeclContext *DC = getEffectiveDeclContext(Block); 1373 if (isLocalContainerContext(DC)) { 1374 mangleLocalName(Block); 1375 return; 1376 } 1377 manglePrefix(getEffectiveDeclContext(Block)); 1378 mangleUnqualifiedBlock(Block); 1379 } 1380 1381 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) { 1382 if (Decl *Context = Block->getBlockManglingContextDecl()) { 1383 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) && 1384 Context->getDeclContext()->isRecord()) { 1385 if (const IdentifierInfo *Name 1386 = cast<NamedDecl>(Context)->getIdentifier()) { 1387 mangleSourceName(Name); 1388 Out << 'M'; 1389 } 1390 } 1391 } 1392 1393 // If we have a block mangling number, use it. 1394 unsigned Number = Block->getBlockManglingNumber(); 1395 // Otherwise, just make up a number. It doesn't matter what it is because 1396 // the symbol in question isn't externally visible. 1397 if (!Number) 1398 Number = Context.getBlockId(Block, false); 1399 Out << "Ub"; 1400 if (Number > 0) 1401 Out << Number - 1; 1402 Out << '_'; 1403 } 1404 1405 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { 1406 // If the context of a closure type is an initializer for a class member 1407 // (static or nonstatic), it is encoded in a qualified name with a final 1408 // <prefix> of the form: 1409 // 1410 // <data-member-prefix> := <member source-name> M 1411 // 1412 // Technically, the data-member-prefix is part of the <prefix>. However, 1413 // since a closure type will always be mangled with a prefix, it's easier 1414 // to emit that last part of the prefix here. 1415 if (Decl *Context = Lambda->getLambdaContextDecl()) { 1416 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) && 1417 Context->getDeclContext()->isRecord()) { 1418 if (const IdentifierInfo *Name 1419 = cast<NamedDecl>(Context)->getIdentifier()) { 1420 mangleSourceName(Name); 1421 Out << 'M'; 1422 } 1423 } 1424 } 1425 1426 Out << "Ul"; 1427 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()-> 1428 getAs<FunctionProtoType>(); 1429 mangleBareFunctionType(Proto, /*MangleReturnType=*/false); 1430 Out << "E"; 1431 1432 // The number is omitted for the first closure type with a given 1433 // <lambda-sig> in a given context; it is n-2 for the nth closure type 1434 // (in lexical order) with that same <lambda-sig> and context. 1435 // 1436 // The AST keeps track of the number for us. 1437 unsigned Number = Lambda->getLambdaManglingNumber(); 1438 assert(Number > 0 && "Lambda should be mangled as an unnamed class"); 1439 if (Number > 1) 1440 mangleNumber(Number - 2); 1441 Out << '_'; 1442 } 1443 1444 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) { 1445 switch (qualifier->getKind()) { 1446 case NestedNameSpecifier::Global: 1447 // nothing 1448 return; 1449 1450 case NestedNameSpecifier::Super: 1451 llvm_unreachable("Can't mangle __super specifier"); 1452 1453 case NestedNameSpecifier::Namespace: 1454 mangleName(qualifier->getAsNamespace()); 1455 return; 1456 1457 case NestedNameSpecifier::NamespaceAlias: 1458 mangleName(qualifier->getAsNamespaceAlias()->getNamespace()); 1459 return; 1460 1461 case NestedNameSpecifier::TypeSpec: 1462 case NestedNameSpecifier::TypeSpecWithTemplate: 1463 manglePrefix(QualType(qualifier->getAsType(), 0)); 1464 return; 1465 1466 case NestedNameSpecifier::Identifier: 1467 // Member expressions can have these without prefixes, but that 1468 // should end up in mangleUnresolvedPrefix instead. 1469 assert(qualifier->getPrefix()); 1470 manglePrefix(qualifier->getPrefix()); 1471 1472 mangleSourceName(qualifier->getAsIdentifier()); 1473 return; 1474 } 1475 1476 llvm_unreachable("unexpected nested name specifier"); 1477 } 1478 1479 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) { 1480 // <prefix> ::= <prefix> <unqualified-name> 1481 // ::= <template-prefix> <template-args> 1482 // ::= <template-param> 1483 // ::= # empty 1484 // ::= <substitution> 1485 1486 DC = IgnoreLinkageSpecDecls(DC); 1487 1488 if (DC->isTranslationUnit()) 1489 return; 1490 1491 if (NoFunction && isLocalContainerContext(DC)) 1492 return; 1493 1494 assert(!isLocalContainerContext(DC)); 1495 1496 const NamedDecl *ND = cast<NamedDecl>(DC); 1497 if (mangleSubstitution(ND)) 1498 return; 1499 1500 // Check if we have a template. 1501 const TemplateArgumentList *TemplateArgs = nullptr; 1502 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { 1503 mangleTemplatePrefix(TD); 1504 mangleTemplateArgs(*TemplateArgs); 1505 } else { 1506 manglePrefix(getEffectiveDeclContext(ND), NoFunction); 1507 mangleUnqualifiedName(ND); 1508 } 1509 1510 addSubstitution(ND); 1511 } 1512 1513 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) { 1514 // <template-prefix> ::= <prefix> <template unqualified-name> 1515 // ::= <template-param> 1516 // ::= <substitution> 1517 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 1518 return mangleTemplatePrefix(TD); 1519 1520 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName()) 1521 manglePrefix(Qualified->getQualifier()); 1522 1523 if (OverloadedTemplateStorage *Overloaded 1524 = Template.getAsOverloadedTemplate()) { 1525 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(), 1526 UnknownArity); 1527 return; 1528 } 1529 1530 DependentTemplateName *Dependent = Template.getAsDependentTemplateName(); 1531 assert(Dependent && "Unknown template name kind?"); 1532 manglePrefix(Dependent->getQualifier()); 1533 mangleUnscopedTemplateName(Template); 1534 } 1535 1536 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND, 1537 bool NoFunction) { 1538 // <template-prefix> ::= <prefix> <template unqualified-name> 1539 // ::= <template-param> 1540 // ::= <substitution> 1541 // <template-template-param> ::= <template-param> 1542 // <substitution> 1543 1544 if (mangleSubstitution(ND)) 1545 return; 1546 1547 // <template-template-param> ::= <template-param> 1548 if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) { 1549 mangleTemplateParameter(TTP->getIndex()); 1550 } else { 1551 manglePrefix(getEffectiveDeclContext(ND), NoFunction); 1552 mangleUnqualifiedName(ND->getTemplatedDecl()); 1553 } 1554 1555 addSubstitution(ND); 1556 } 1557 1558 /// Mangles a template name under the production <type>. Required for 1559 /// template template arguments. 1560 /// <type> ::= <class-enum-type> 1561 /// ::= <template-param> 1562 /// ::= <substitution> 1563 void CXXNameMangler::mangleType(TemplateName TN) { 1564 if (mangleSubstitution(TN)) 1565 return; 1566 1567 TemplateDecl *TD = nullptr; 1568 1569 switch (TN.getKind()) { 1570 case TemplateName::QualifiedTemplate: 1571 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl(); 1572 goto HaveDecl; 1573 1574 case TemplateName::Template: 1575 TD = TN.getAsTemplateDecl(); 1576 goto HaveDecl; 1577 1578 HaveDecl: 1579 if (isa<TemplateTemplateParmDecl>(TD)) 1580 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex()); 1581 else 1582 mangleName(TD); 1583 break; 1584 1585 case TemplateName::OverloadedTemplate: 1586 llvm_unreachable("can't mangle an overloaded template name as a <type>"); 1587 1588 case TemplateName::DependentTemplate: { 1589 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName(); 1590 assert(Dependent->isIdentifier()); 1591 1592 // <class-enum-type> ::= <name> 1593 // <name> ::= <nested-name> 1594 mangleUnresolvedPrefix(Dependent->getQualifier(), nullptr); 1595 mangleSourceName(Dependent->getIdentifier()); 1596 break; 1597 } 1598 1599 case TemplateName::SubstTemplateTemplateParm: { 1600 // Substituted template parameters are mangled as the substituted 1601 // template. This will check for the substitution twice, which is 1602 // fine, but we have to return early so that we don't try to *add* 1603 // the substitution twice. 1604 SubstTemplateTemplateParmStorage *subst 1605 = TN.getAsSubstTemplateTemplateParm(); 1606 mangleType(subst->getReplacement()); 1607 return; 1608 } 1609 1610 case TemplateName::SubstTemplateTemplateParmPack: { 1611 // FIXME: not clear how to mangle this! 1612 // template <template <class> class T...> class A { 1613 // template <template <class> class U...> void foo(B<T,U> x...); 1614 // }; 1615 Out << "_SUBSTPACK_"; 1616 break; 1617 } 1618 } 1619 1620 addSubstitution(TN); 1621 } 1622 1623 void 1624 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) { 1625 switch (OO) { 1626 // <operator-name> ::= nw # new 1627 case OO_New: Out << "nw"; break; 1628 // ::= na # new[] 1629 case OO_Array_New: Out << "na"; break; 1630 // ::= dl # delete 1631 case OO_Delete: Out << "dl"; break; 1632 // ::= da # delete[] 1633 case OO_Array_Delete: Out << "da"; break; 1634 // ::= ps # + (unary) 1635 // ::= pl # + (binary or unknown) 1636 case OO_Plus: 1637 Out << (Arity == 1? "ps" : "pl"); break; 1638 // ::= ng # - (unary) 1639 // ::= mi # - (binary or unknown) 1640 case OO_Minus: 1641 Out << (Arity == 1? "ng" : "mi"); break; 1642 // ::= ad # & (unary) 1643 // ::= an # & (binary or unknown) 1644 case OO_Amp: 1645 Out << (Arity == 1? "ad" : "an"); break; 1646 // ::= de # * (unary) 1647 // ::= ml # * (binary or unknown) 1648 case OO_Star: 1649 // Use binary when unknown. 1650 Out << (Arity == 1? "de" : "ml"); break; 1651 // ::= co # ~ 1652 case OO_Tilde: Out << "co"; break; 1653 // ::= dv # / 1654 case OO_Slash: Out << "dv"; break; 1655 // ::= rm # % 1656 case OO_Percent: Out << "rm"; break; 1657 // ::= or # | 1658 case OO_Pipe: Out << "or"; break; 1659 // ::= eo # ^ 1660 case OO_Caret: Out << "eo"; break; 1661 // ::= aS # = 1662 case OO_Equal: Out << "aS"; break; 1663 // ::= pL # += 1664 case OO_PlusEqual: Out << "pL"; break; 1665 // ::= mI # -= 1666 case OO_MinusEqual: Out << "mI"; break; 1667 // ::= mL # *= 1668 case OO_StarEqual: Out << "mL"; break; 1669 // ::= dV # /= 1670 case OO_SlashEqual: Out << "dV"; break; 1671 // ::= rM # %= 1672 case OO_PercentEqual: Out << "rM"; break; 1673 // ::= aN # &= 1674 case OO_AmpEqual: Out << "aN"; break; 1675 // ::= oR # |= 1676 case OO_PipeEqual: Out << "oR"; break; 1677 // ::= eO # ^= 1678 case OO_CaretEqual: Out << "eO"; break; 1679 // ::= ls # << 1680 case OO_LessLess: Out << "ls"; break; 1681 // ::= rs # >> 1682 case OO_GreaterGreater: Out << "rs"; break; 1683 // ::= lS # <<= 1684 case OO_LessLessEqual: Out << "lS"; break; 1685 // ::= rS # >>= 1686 case OO_GreaterGreaterEqual: Out << "rS"; break; 1687 // ::= eq # == 1688 case OO_EqualEqual: Out << "eq"; break; 1689 // ::= ne # != 1690 case OO_ExclaimEqual: Out << "ne"; break; 1691 // ::= lt # < 1692 case OO_Less: Out << "lt"; break; 1693 // ::= gt # > 1694 case OO_Greater: Out << "gt"; break; 1695 // ::= le # <= 1696 case OO_LessEqual: Out << "le"; break; 1697 // ::= ge # >= 1698 case OO_GreaterEqual: Out << "ge"; break; 1699 // ::= nt # ! 1700 case OO_Exclaim: Out << "nt"; break; 1701 // ::= aa # && 1702 case OO_AmpAmp: Out << "aa"; break; 1703 // ::= oo # || 1704 case OO_PipePipe: Out << "oo"; break; 1705 // ::= pp # ++ 1706 case OO_PlusPlus: Out << "pp"; break; 1707 // ::= mm # -- 1708 case OO_MinusMinus: Out << "mm"; break; 1709 // ::= cm # , 1710 case OO_Comma: Out << "cm"; break; 1711 // ::= pm # ->* 1712 case OO_ArrowStar: Out << "pm"; break; 1713 // ::= pt # -> 1714 case OO_Arrow: Out << "pt"; break; 1715 // ::= cl # () 1716 case OO_Call: Out << "cl"; break; 1717 // ::= ix # [] 1718 case OO_Subscript: Out << "ix"; break; 1719 1720 // ::= qu # ? 1721 // The conditional operator can't be overloaded, but we still handle it when 1722 // mangling expressions. 1723 case OO_Conditional: Out << "qu"; break; 1724 1725 case OO_None: 1726 case NUM_OVERLOADED_OPERATORS: 1727 llvm_unreachable("Not an overloaded operator"); 1728 } 1729 } 1730 1731 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) { 1732 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const 1733 if (Quals.hasRestrict()) 1734 Out << 'r'; 1735 if (Quals.hasVolatile()) 1736 Out << 'V'; 1737 if (Quals.hasConst()) 1738 Out << 'K'; 1739 1740 if (Quals.hasAddressSpace()) { 1741 // Address space extension: 1742 // 1743 // <type> ::= U <target-addrspace> 1744 // <type> ::= U <OpenCL-addrspace> 1745 // <type> ::= U <CUDA-addrspace> 1746 1747 SmallString<64> ASString; 1748 unsigned AS = Quals.getAddressSpace(); 1749 1750 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) { 1751 // <target-addrspace> ::= "AS" <address-space-number> 1752 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS); 1753 ASString = "AS" + llvm::utostr_32(TargetAS); 1754 } else { 1755 switch (AS) { 1756 default: llvm_unreachable("Not a language specific address space"); 1757 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ] 1758 case LangAS::opencl_global: ASString = "CLglobal"; break; 1759 case LangAS::opencl_local: ASString = "CLlocal"; break; 1760 case LangAS::opencl_constant: ASString = "CLconstant"; break; 1761 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ] 1762 case LangAS::cuda_device: ASString = "CUdevice"; break; 1763 case LangAS::cuda_constant: ASString = "CUconstant"; break; 1764 case LangAS::cuda_shared: ASString = "CUshared"; break; 1765 } 1766 } 1767 Out << 'U' << ASString.size() << ASString; 1768 } 1769 1770 StringRef LifetimeName; 1771 switch (Quals.getObjCLifetime()) { 1772 // Objective-C ARC Extension: 1773 // 1774 // <type> ::= U "__strong" 1775 // <type> ::= U "__weak" 1776 // <type> ::= U "__autoreleasing" 1777 case Qualifiers::OCL_None: 1778 break; 1779 1780 case Qualifiers::OCL_Weak: 1781 LifetimeName = "__weak"; 1782 break; 1783 1784 case Qualifiers::OCL_Strong: 1785 LifetimeName = "__strong"; 1786 break; 1787 1788 case Qualifiers::OCL_Autoreleasing: 1789 LifetimeName = "__autoreleasing"; 1790 break; 1791 1792 case Qualifiers::OCL_ExplicitNone: 1793 // The __unsafe_unretained qualifier is *not* mangled, so that 1794 // __unsafe_unretained types in ARC produce the same manglings as the 1795 // equivalent (but, naturally, unqualified) types in non-ARC, providing 1796 // better ABI compatibility. 1797 // 1798 // It's safe to do this because unqualified 'id' won't show up 1799 // in any type signatures that need to be mangled. 1800 break; 1801 } 1802 if (!LifetimeName.empty()) 1803 Out << 'U' << LifetimeName.size() << LifetimeName; 1804 } 1805 1806 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) { 1807 // <ref-qualifier> ::= R # lvalue reference 1808 // ::= O # rvalue-reference 1809 switch (RefQualifier) { 1810 case RQ_None: 1811 break; 1812 1813 case RQ_LValue: 1814 Out << 'R'; 1815 break; 1816 1817 case RQ_RValue: 1818 Out << 'O'; 1819 break; 1820 } 1821 } 1822 1823 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) { 1824 Context.mangleObjCMethodName(MD, Out); 1825 } 1826 1827 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) { 1828 if (Quals) 1829 return true; 1830 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel)) 1831 return true; 1832 if (Ty->isOpenCLSpecificType()) 1833 return true; 1834 if (Ty->isBuiltinType()) 1835 return false; 1836 1837 return true; 1838 } 1839 1840 void CXXNameMangler::mangleType(QualType T) { 1841 // If our type is instantiation-dependent but not dependent, we mangle 1842 // it as it was written in the source, removing any top-level sugar. 1843 // Otherwise, use the canonical type. 1844 // 1845 // FIXME: This is an approximation of the instantiation-dependent name 1846 // mangling rules, since we should really be using the type as written and 1847 // augmented via semantic analysis (i.e., with implicit conversions and 1848 // default template arguments) for any instantiation-dependent type. 1849 // Unfortunately, that requires several changes to our AST: 1850 // - Instantiation-dependent TemplateSpecializationTypes will need to be 1851 // uniqued, so that we can handle substitutions properly 1852 // - Default template arguments will need to be represented in the 1853 // TemplateSpecializationType, since they need to be mangled even though 1854 // they aren't written. 1855 // - Conversions on non-type template arguments need to be expressed, since 1856 // they can affect the mangling of sizeof/alignof. 1857 if (!T->isInstantiationDependentType() || T->isDependentType()) 1858 T = T.getCanonicalType(); 1859 else { 1860 // Desugar any types that are purely sugar. 1861 do { 1862 // Don't desugar through template specialization types that aren't 1863 // type aliases. We need to mangle the template arguments as written. 1864 if (const TemplateSpecializationType *TST 1865 = dyn_cast<TemplateSpecializationType>(T)) 1866 if (!TST->isTypeAlias()) 1867 break; 1868 1869 QualType Desugared 1870 = T.getSingleStepDesugaredType(Context.getASTContext()); 1871 if (Desugared == T) 1872 break; 1873 1874 T = Desugared; 1875 } while (true); 1876 } 1877 SplitQualType split = T.split(); 1878 Qualifiers quals = split.Quals; 1879 const Type *ty = split.Ty; 1880 1881 bool isSubstitutable = isTypeSubstitutable(quals, ty); 1882 if (isSubstitutable && mangleSubstitution(T)) 1883 return; 1884 1885 // If we're mangling a qualified array type, push the qualifiers to 1886 // the element type. 1887 if (quals && isa<ArrayType>(T)) { 1888 ty = Context.getASTContext().getAsArrayType(T); 1889 quals = Qualifiers(); 1890 1891 // Note that we don't update T: we want to add the 1892 // substitution at the original type. 1893 } 1894 1895 if (quals) { 1896 mangleQualifiers(quals); 1897 // Recurse: even if the qualified type isn't yet substitutable, 1898 // the unqualified type might be. 1899 mangleType(QualType(ty, 0)); 1900 } else { 1901 switch (ty->getTypeClass()) { 1902 #define ABSTRACT_TYPE(CLASS, PARENT) 1903 #define NON_CANONICAL_TYPE(CLASS, PARENT) \ 1904 case Type::CLASS: \ 1905 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \ 1906 return; 1907 #define TYPE(CLASS, PARENT) \ 1908 case Type::CLASS: \ 1909 mangleType(static_cast<const CLASS##Type*>(ty)); \ 1910 break; 1911 #include "clang/AST/TypeNodes.def" 1912 } 1913 } 1914 1915 // Add the substitution. 1916 if (isSubstitutable) 1917 addSubstitution(T); 1918 } 1919 1920 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) { 1921 if (!mangleStandardSubstitution(ND)) 1922 mangleName(ND); 1923 } 1924 1925 void CXXNameMangler::mangleType(const BuiltinType *T) { 1926 // <type> ::= <builtin-type> 1927 // <builtin-type> ::= v # void 1928 // ::= w # wchar_t 1929 // ::= b # bool 1930 // ::= c # char 1931 // ::= a # signed char 1932 // ::= h # unsigned char 1933 // ::= s # short 1934 // ::= t # unsigned short 1935 // ::= i # int 1936 // ::= j # unsigned int 1937 // ::= l # long 1938 // ::= m # unsigned long 1939 // ::= x # long long, __int64 1940 // ::= y # unsigned long long, __int64 1941 // ::= n # __int128 1942 // ::= o # unsigned __int128 1943 // ::= f # float 1944 // ::= d # double 1945 // ::= e # long double, __float80 1946 // UNSUPPORTED: ::= g # __float128 1947 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits) 1948 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits) 1949 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits) 1950 // ::= Dh # IEEE 754r half-precision floating point (16 bits) 1951 // ::= Di # char32_t 1952 // ::= Ds # char16_t 1953 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr)) 1954 // ::= u <source-name> # vendor extended type 1955 switch (T->getKind()) { 1956 case BuiltinType::Void: Out << 'v'; break; 1957 case BuiltinType::Bool: Out << 'b'; break; 1958 case BuiltinType::Char_U: case BuiltinType::Char_S: Out << 'c'; break; 1959 case BuiltinType::UChar: Out << 'h'; break; 1960 case BuiltinType::UShort: Out << 't'; break; 1961 case BuiltinType::UInt: Out << 'j'; break; 1962 case BuiltinType::ULong: Out << 'm'; break; 1963 case BuiltinType::ULongLong: Out << 'y'; break; 1964 case BuiltinType::UInt128: Out << 'o'; break; 1965 case BuiltinType::SChar: Out << 'a'; break; 1966 case BuiltinType::WChar_S: 1967 case BuiltinType::WChar_U: Out << 'w'; break; 1968 case BuiltinType::Char16: Out << "Ds"; break; 1969 case BuiltinType::Char32: Out << "Di"; break; 1970 case BuiltinType::Short: Out << 's'; break; 1971 case BuiltinType::Int: Out << 'i'; break; 1972 case BuiltinType::Long: Out << 'l'; break; 1973 case BuiltinType::LongLong: Out << 'x'; break; 1974 case BuiltinType::Int128: Out << 'n'; break; 1975 case BuiltinType::Half: Out << "Dh"; break; 1976 case BuiltinType::Float: Out << 'f'; break; 1977 case BuiltinType::Double: Out << 'd'; break; 1978 case BuiltinType::LongDouble: Out << 'e'; break; 1979 case BuiltinType::NullPtr: Out << "Dn"; break; 1980 1981 #define BUILTIN_TYPE(Id, SingletonId) 1982 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 1983 case BuiltinType::Id: 1984 #include "clang/AST/BuiltinTypes.def" 1985 case BuiltinType::Dependent: 1986 llvm_unreachable("mangling a placeholder type"); 1987 case BuiltinType::ObjCId: Out << "11objc_object"; break; 1988 case BuiltinType::ObjCClass: Out << "10objc_class"; break; 1989 case BuiltinType::ObjCSel: Out << "13objc_selector"; break; 1990 case BuiltinType::OCLImage1d: Out << "11ocl_image1d"; break; 1991 case BuiltinType::OCLImage1dArray: Out << "16ocl_image1darray"; break; 1992 case BuiltinType::OCLImage1dBuffer: Out << "17ocl_image1dbuffer"; break; 1993 case BuiltinType::OCLImage2d: Out << "11ocl_image2d"; break; 1994 case BuiltinType::OCLImage2dArray: Out << "16ocl_image2darray"; break; 1995 case BuiltinType::OCLImage3d: Out << "11ocl_image3d"; break; 1996 case BuiltinType::OCLSampler: Out << "11ocl_sampler"; break; 1997 case BuiltinType::OCLEvent: Out << "9ocl_event"; break; 1998 } 1999 } 2000 2001 // <type> ::= <function-type> 2002 // <function-type> ::= [<CV-qualifiers>] F [Y] 2003 // <bare-function-type> [<ref-qualifier>] E 2004 void CXXNameMangler::mangleType(const FunctionProtoType *T) { 2005 // Mangle CV-qualifiers, if present. These are 'this' qualifiers, 2006 // e.g. "const" in "int (A::*)() const". 2007 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals())); 2008 2009 Out << 'F'; 2010 2011 // FIXME: We don't have enough information in the AST to produce the 'Y' 2012 // encoding for extern "C" function types. 2013 mangleBareFunctionType(T, /*MangleReturnType=*/true); 2014 2015 // Mangle the ref-qualifier, if present. 2016 mangleRefQualifier(T->getRefQualifier()); 2017 2018 Out << 'E'; 2019 } 2020 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) { 2021 llvm_unreachable("Can't mangle K&R function prototypes"); 2022 } 2023 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T, 2024 bool MangleReturnType) { 2025 // We should never be mangling something without a prototype. 2026 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 2027 2028 // Record that we're in a function type. See mangleFunctionParam 2029 // for details on what we're trying to achieve here. 2030 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 2031 2032 // <bare-function-type> ::= <signature type>+ 2033 if (MangleReturnType) { 2034 FunctionTypeDepth.enterResultType(); 2035 mangleType(Proto->getReturnType()); 2036 FunctionTypeDepth.leaveResultType(); 2037 } 2038 2039 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) { 2040 // <builtin-type> ::= v # void 2041 Out << 'v'; 2042 2043 FunctionTypeDepth.pop(saved); 2044 return; 2045 } 2046 2047 for (const auto &Arg : Proto->param_types()) 2048 mangleType(Context.getASTContext().getSignatureParameterType(Arg)); 2049 2050 FunctionTypeDepth.pop(saved); 2051 2052 // <builtin-type> ::= z # ellipsis 2053 if (Proto->isVariadic()) 2054 Out << 'z'; 2055 } 2056 2057 // <type> ::= <class-enum-type> 2058 // <class-enum-type> ::= <name> 2059 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) { 2060 mangleName(T->getDecl()); 2061 } 2062 2063 // <type> ::= <class-enum-type> 2064 // <class-enum-type> ::= <name> 2065 void CXXNameMangler::mangleType(const EnumType *T) { 2066 mangleType(static_cast<const TagType*>(T)); 2067 } 2068 void CXXNameMangler::mangleType(const RecordType *T) { 2069 mangleType(static_cast<const TagType*>(T)); 2070 } 2071 void CXXNameMangler::mangleType(const TagType *T) { 2072 mangleName(T->getDecl()); 2073 } 2074 2075 // <type> ::= <array-type> 2076 // <array-type> ::= A <positive dimension number> _ <element type> 2077 // ::= A [<dimension expression>] _ <element type> 2078 void CXXNameMangler::mangleType(const ConstantArrayType *T) { 2079 Out << 'A' << T->getSize() << '_'; 2080 mangleType(T->getElementType()); 2081 } 2082 void CXXNameMangler::mangleType(const VariableArrayType *T) { 2083 Out << 'A'; 2084 // decayed vla types (size 0) will just be skipped. 2085 if (T->getSizeExpr()) 2086 mangleExpression(T->getSizeExpr()); 2087 Out << '_'; 2088 mangleType(T->getElementType()); 2089 } 2090 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) { 2091 Out << 'A'; 2092 mangleExpression(T->getSizeExpr()); 2093 Out << '_'; 2094 mangleType(T->getElementType()); 2095 } 2096 void CXXNameMangler::mangleType(const IncompleteArrayType *T) { 2097 Out << "A_"; 2098 mangleType(T->getElementType()); 2099 } 2100 2101 // <type> ::= <pointer-to-member-type> 2102 // <pointer-to-member-type> ::= M <class type> <member type> 2103 void CXXNameMangler::mangleType(const MemberPointerType *T) { 2104 Out << 'M'; 2105 mangleType(QualType(T->getClass(), 0)); 2106 QualType PointeeType = T->getPointeeType(); 2107 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) { 2108 mangleType(FPT); 2109 2110 // Itanium C++ ABI 5.1.8: 2111 // 2112 // The type of a non-static member function is considered to be different, 2113 // for the purposes of substitution, from the type of a namespace-scope or 2114 // static member function whose type appears similar. The types of two 2115 // non-static member functions are considered to be different, for the 2116 // purposes of substitution, if the functions are members of different 2117 // classes. In other words, for the purposes of substitution, the class of 2118 // which the function is a member is considered part of the type of 2119 // function. 2120 2121 // Given that we already substitute member function pointers as a 2122 // whole, the net effect of this rule is just to unconditionally 2123 // suppress substitution on the function type in a member pointer. 2124 // We increment the SeqID here to emulate adding an entry to the 2125 // substitution table. 2126 ++SeqID; 2127 } else 2128 mangleType(PointeeType); 2129 } 2130 2131 // <type> ::= <template-param> 2132 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) { 2133 mangleTemplateParameter(T->getIndex()); 2134 } 2135 2136 // <type> ::= <template-param> 2137 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) { 2138 // FIXME: not clear how to mangle this! 2139 // template <class T...> class A { 2140 // template <class U...> void foo(T(*)(U) x...); 2141 // }; 2142 Out << "_SUBSTPACK_"; 2143 } 2144 2145 // <type> ::= P <type> # pointer-to 2146 void CXXNameMangler::mangleType(const PointerType *T) { 2147 Out << 'P'; 2148 mangleType(T->getPointeeType()); 2149 } 2150 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) { 2151 Out << 'P'; 2152 mangleType(T->getPointeeType()); 2153 } 2154 2155 // <type> ::= R <type> # reference-to 2156 void CXXNameMangler::mangleType(const LValueReferenceType *T) { 2157 Out << 'R'; 2158 mangleType(T->getPointeeType()); 2159 } 2160 2161 // <type> ::= O <type> # rvalue reference-to (C++0x) 2162 void CXXNameMangler::mangleType(const RValueReferenceType *T) { 2163 Out << 'O'; 2164 mangleType(T->getPointeeType()); 2165 } 2166 2167 // <type> ::= C <type> # complex pair (C 2000) 2168 void CXXNameMangler::mangleType(const ComplexType *T) { 2169 Out << 'C'; 2170 mangleType(T->getElementType()); 2171 } 2172 2173 // ARM's ABI for Neon vector types specifies that they should be mangled as 2174 // if they are structs (to match ARM's initial implementation). The 2175 // vector type must be one of the special types predefined by ARM. 2176 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) { 2177 QualType EltType = T->getElementType(); 2178 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 2179 const char *EltName = nullptr; 2180 if (T->getVectorKind() == VectorType::NeonPolyVector) { 2181 switch (cast<BuiltinType>(EltType)->getKind()) { 2182 case BuiltinType::SChar: 2183 case BuiltinType::UChar: 2184 EltName = "poly8_t"; 2185 break; 2186 case BuiltinType::Short: 2187 case BuiltinType::UShort: 2188 EltName = "poly16_t"; 2189 break; 2190 case BuiltinType::ULongLong: 2191 EltName = "poly64_t"; 2192 break; 2193 default: llvm_unreachable("unexpected Neon polynomial vector element type"); 2194 } 2195 } else { 2196 switch (cast<BuiltinType>(EltType)->getKind()) { 2197 case BuiltinType::SChar: EltName = "int8_t"; break; 2198 case BuiltinType::UChar: EltName = "uint8_t"; break; 2199 case BuiltinType::Short: EltName = "int16_t"; break; 2200 case BuiltinType::UShort: EltName = "uint16_t"; break; 2201 case BuiltinType::Int: EltName = "int32_t"; break; 2202 case BuiltinType::UInt: EltName = "uint32_t"; break; 2203 case BuiltinType::LongLong: EltName = "int64_t"; break; 2204 case BuiltinType::ULongLong: EltName = "uint64_t"; break; 2205 case BuiltinType::Double: EltName = "float64_t"; break; 2206 case BuiltinType::Float: EltName = "float32_t"; break; 2207 case BuiltinType::Half: EltName = "float16_t";break; 2208 default: 2209 llvm_unreachable("unexpected Neon vector element type"); 2210 } 2211 } 2212 const char *BaseName = nullptr; 2213 unsigned BitSize = (T->getNumElements() * 2214 getASTContext().getTypeSize(EltType)); 2215 if (BitSize == 64) 2216 BaseName = "__simd64_"; 2217 else { 2218 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits"); 2219 BaseName = "__simd128_"; 2220 } 2221 Out << strlen(BaseName) + strlen(EltName); 2222 Out << BaseName << EltName; 2223 } 2224 2225 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) { 2226 switch (EltType->getKind()) { 2227 case BuiltinType::SChar: 2228 return "Int8"; 2229 case BuiltinType::Short: 2230 return "Int16"; 2231 case BuiltinType::Int: 2232 return "Int32"; 2233 case BuiltinType::Long: 2234 case BuiltinType::LongLong: 2235 return "Int64"; 2236 case BuiltinType::UChar: 2237 return "Uint8"; 2238 case BuiltinType::UShort: 2239 return "Uint16"; 2240 case BuiltinType::UInt: 2241 return "Uint32"; 2242 case BuiltinType::ULong: 2243 case BuiltinType::ULongLong: 2244 return "Uint64"; 2245 case BuiltinType::Half: 2246 return "Float16"; 2247 case BuiltinType::Float: 2248 return "Float32"; 2249 case BuiltinType::Double: 2250 return "Float64"; 2251 default: 2252 llvm_unreachable("Unexpected vector element base type"); 2253 } 2254 } 2255 2256 // AArch64's ABI for Neon vector types specifies that they should be mangled as 2257 // the equivalent internal name. The vector type must be one of the special 2258 // types predefined by ARM. 2259 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) { 2260 QualType EltType = T->getElementType(); 2261 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 2262 unsigned BitSize = 2263 (T->getNumElements() * getASTContext().getTypeSize(EltType)); 2264 (void)BitSize; // Silence warning. 2265 2266 assert((BitSize == 64 || BitSize == 128) && 2267 "Neon vector type not 64 or 128 bits"); 2268 2269 StringRef EltName; 2270 if (T->getVectorKind() == VectorType::NeonPolyVector) { 2271 switch (cast<BuiltinType>(EltType)->getKind()) { 2272 case BuiltinType::UChar: 2273 EltName = "Poly8"; 2274 break; 2275 case BuiltinType::UShort: 2276 EltName = "Poly16"; 2277 break; 2278 case BuiltinType::ULong: 2279 EltName = "Poly64"; 2280 break; 2281 default: 2282 llvm_unreachable("unexpected Neon polynomial vector element type"); 2283 } 2284 } else 2285 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType)); 2286 2287 std::string TypeName = 2288 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str(); 2289 Out << TypeName.length() << TypeName; 2290 } 2291 2292 // GNU extension: vector types 2293 // <type> ::= <vector-type> 2294 // <vector-type> ::= Dv <positive dimension number> _ 2295 // <extended element type> 2296 // ::= Dv [<dimension expression>] _ <element type> 2297 // <extended element type> ::= <element type> 2298 // ::= p # AltiVec vector pixel 2299 // ::= b # Altivec vector bool 2300 void CXXNameMangler::mangleType(const VectorType *T) { 2301 if ((T->getVectorKind() == VectorType::NeonVector || 2302 T->getVectorKind() == VectorType::NeonPolyVector)) { 2303 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 2304 llvm::Triple::ArchType Arch = 2305 getASTContext().getTargetInfo().getTriple().getArch(); 2306 if ((Arch == llvm::Triple::aarch64 || 2307 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin()) 2308 mangleAArch64NeonVectorType(T); 2309 else 2310 mangleNeonVectorType(T); 2311 return; 2312 } 2313 Out << "Dv" << T->getNumElements() << '_'; 2314 if (T->getVectorKind() == VectorType::AltiVecPixel) 2315 Out << 'p'; 2316 else if (T->getVectorKind() == VectorType::AltiVecBool) 2317 Out << 'b'; 2318 else 2319 mangleType(T->getElementType()); 2320 } 2321 void CXXNameMangler::mangleType(const ExtVectorType *T) { 2322 mangleType(static_cast<const VectorType*>(T)); 2323 } 2324 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) { 2325 Out << "Dv"; 2326 mangleExpression(T->getSizeExpr()); 2327 Out << '_'; 2328 mangleType(T->getElementType()); 2329 } 2330 2331 void CXXNameMangler::mangleType(const PackExpansionType *T) { 2332 // <type> ::= Dp <type> # pack expansion (C++0x) 2333 Out << "Dp"; 2334 mangleType(T->getPattern()); 2335 } 2336 2337 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) { 2338 mangleSourceName(T->getDecl()->getIdentifier()); 2339 } 2340 2341 void CXXNameMangler::mangleType(const ObjCObjectType *T) { 2342 if (!T->qual_empty()) { 2343 // Mangle protocol qualifiers. 2344 SmallString<64> QualStr; 2345 llvm::raw_svector_ostream QualOS(QualStr); 2346 QualOS << "objcproto"; 2347 for (const auto *I : T->quals()) { 2348 StringRef name = I->getName(); 2349 QualOS << name.size() << name; 2350 } 2351 QualOS.flush(); 2352 Out << 'U' << QualStr.size() << QualStr; 2353 } 2354 mangleType(T->getBaseType()); 2355 } 2356 2357 void CXXNameMangler::mangleType(const BlockPointerType *T) { 2358 Out << "U13block_pointer"; 2359 mangleType(T->getPointeeType()); 2360 } 2361 2362 void CXXNameMangler::mangleType(const InjectedClassNameType *T) { 2363 // Mangle injected class name types as if the user had written the 2364 // specialization out fully. It may not actually be possible to see 2365 // this mangling, though. 2366 mangleType(T->getInjectedSpecializationType()); 2367 } 2368 2369 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) { 2370 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) { 2371 mangleName(TD, T->getArgs(), T->getNumArgs()); 2372 } else { 2373 if (mangleSubstitution(QualType(T, 0))) 2374 return; 2375 2376 mangleTemplatePrefix(T->getTemplateName()); 2377 2378 // FIXME: GCC does not appear to mangle the template arguments when 2379 // the template in question is a dependent template name. Should we 2380 // emulate that badness? 2381 mangleTemplateArgs(T->getArgs(), T->getNumArgs()); 2382 addSubstitution(QualType(T, 0)); 2383 } 2384 } 2385 2386 void CXXNameMangler::mangleType(const DependentNameType *T) { 2387 // Proposal by cxx-abi-dev, 2014-03-26 2388 // <class-enum-type> ::= <name> # non-dependent or dependent type name or 2389 // # dependent elaborated type specifier using 2390 // # 'typename' 2391 // ::= Ts <name> # dependent elaborated type specifier using 2392 // # 'struct' or 'class' 2393 // ::= Tu <name> # dependent elaborated type specifier using 2394 // # 'union' 2395 // ::= Te <name> # dependent elaborated type specifier using 2396 // # 'enum' 2397 switch (T->getKeyword()) { 2398 case ETK_Typename: 2399 break; 2400 case ETK_Struct: 2401 case ETK_Class: 2402 case ETK_Interface: 2403 Out << "Ts"; 2404 break; 2405 case ETK_Union: 2406 Out << "Tu"; 2407 break; 2408 case ETK_Enum: 2409 Out << "Te"; 2410 break; 2411 default: 2412 llvm_unreachable("unexpected keyword for dependent type name"); 2413 } 2414 // Typename types are always nested 2415 Out << 'N'; 2416 manglePrefix(T->getQualifier()); 2417 mangleSourceName(T->getIdentifier()); 2418 Out << 'E'; 2419 } 2420 2421 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) { 2422 // Dependently-scoped template types are nested if they have a prefix. 2423 Out << 'N'; 2424 2425 // TODO: avoid making this TemplateName. 2426 TemplateName Prefix = 2427 getASTContext().getDependentTemplateName(T->getQualifier(), 2428 T->getIdentifier()); 2429 mangleTemplatePrefix(Prefix); 2430 2431 // FIXME: GCC does not appear to mangle the template arguments when 2432 // the template in question is a dependent template name. Should we 2433 // emulate that badness? 2434 mangleTemplateArgs(T->getArgs(), T->getNumArgs()); 2435 Out << 'E'; 2436 } 2437 2438 void CXXNameMangler::mangleType(const TypeOfType *T) { 2439 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 2440 // "extension with parameters" mangling. 2441 Out << "u6typeof"; 2442 } 2443 2444 void CXXNameMangler::mangleType(const TypeOfExprType *T) { 2445 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 2446 // "extension with parameters" mangling. 2447 Out << "u6typeof"; 2448 } 2449 2450 void CXXNameMangler::mangleType(const DecltypeType *T) { 2451 Expr *E = T->getUnderlyingExpr(); 2452 2453 // type ::= Dt <expression> E # decltype of an id-expression 2454 // # or class member access 2455 // ::= DT <expression> E # decltype of an expression 2456 2457 // This purports to be an exhaustive list of id-expressions and 2458 // class member accesses. Note that we do not ignore parentheses; 2459 // parentheses change the semantics of decltype for these 2460 // expressions (and cause the mangler to use the other form). 2461 if (isa<DeclRefExpr>(E) || 2462 isa<MemberExpr>(E) || 2463 isa<UnresolvedLookupExpr>(E) || 2464 isa<DependentScopeDeclRefExpr>(E) || 2465 isa<CXXDependentScopeMemberExpr>(E) || 2466 isa<UnresolvedMemberExpr>(E)) 2467 Out << "Dt"; 2468 else 2469 Out << "DT"; 2470 mangleExpression(E); 2471 Out << 'E'; 2472 } 2473 2474 void CXXNameMangler::mangleType(const UnaryTransformType *T) { 2475 // If this is dependent, we need to record that. If not, we simply 2476 // mangle it as the underlying type since they are equivalent. 2477 if (T->isDependentType()) { 2478 Out << 'U'; 2479 2480 switch (T->getUTTKind()) { 2481 case UnaryTransformType::EnumUnderlyingType: 2482 Out << "3eut"; 2483 break; 2484 } 2485 } 2486 2487 mangleType(T->getUnderlyingType()); 2488 } 2489 2490 void CXXNameMangler::mangleType(const AutoType *T) { 2491 QualType D = T->getDeducedType(); 2492 // <builtin-type> ::= Da # dependent auto 2493 if (D.isNull()) 2494 Out << (T->isDecltypeAuto() ? "Dc" : "Da"); 2495 else 2496 mangleType(D); 2497 } 2498 2499 void CXXNameMangler::mangleType(const AtomicType *T) { 2500 // <type> ::= U <source-name> <type> # vendor extended type qualifier 2501 // (Until there's a standardized mangling...) 2502 Out << "U7_Atomic"; 2503 mangleType(T->getValueType()); 2504 } 2505 2506 void CXXNameMangler::mangleIntegerLiteral(QualType T, 2507 const llvm::APSInt &Value) { 2508 // <expr-primary> ::= L <type> <value number> E # integer literal 2509 Out << 'L'; 2510 2511 mangleType(T); 2512 if (T->isBooleanType()) { 2513 // Boolean values are encoded as 0/1. 2514 Out << (Value.getBoolValue() ? '1' : '0'); 2515 } else { 2516 mangleNumber(Value); 2517 } 2518 Out << 'E'; 2519 2520 } 2521 2522 /// Mangles a member expression. 2523 void CXXNameMangler::mangleMemberExpr(const Expr *base, 2524 bool isArrow, 2525 NestedNameSpecifier *qualifier, 2526 NamedDecl *firstQualifierLookup, 2527 DeclarationName member, 2528 unsigned arity) { 2529 // <expression> ::= dt <expression> <unresolved-name> 2530 // ::= pt <expression> <unresolved-name> 2531 if (base) { 2532 2533 // Ignore member expressions involving anonymous unions. 2534 while (const auto *RT = base->getType()->getAs<RecordType>()) { 2535 if (!RT->getDecl()->isAnonymousStructOrUnion()) 2536 break; 2537 const auto *ME = dyn_cast<MemberExpr>(base); 2538 if (!ME) 2539 break; 2540 base = ME->getBase(); 2541 isArrow = ME->isArrow(); 2542 } 2543 2544 if (base->isImplicitCXXThis()) { 2545 // Note: GCC mangles member expressions to the implicit 'this' as 2546 // *this., whereas we represent them as this->. The Itanium C++ ABI 2547 // does not specify anything here, so we follow GCC. 2548 Out << "dtdefpT"; 2549 } else { 2550 Out << (isArrow ? "pt" : "dt"); 2551 mangleExpression(base); 2552 } 2553 } 2554 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity); 2555 } 2556 2557 /// Look at the callee of the given call expression and determine if 2558 /// it's a parenthesized id-expression which would have triggered ADL 2559 /// otherwise. 2560 static bool isParenthesizedADLCallee(const CallExpr *call) { 2561 const Expr *callee = call->getCallee(); 2562 const Expr *fn = callee->IgnoreParens(); 2563 2564 // Must be parenthesized. IgnoreParens() skips __extension__ nodes, 2565 // too, but for those to appear in the callee, it would have to be 2566 // parenthesized. 2567 if (callee == fn) return false; 2568 2569 // Must be an unresolved lookup. 2570 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn); 2571 if (!lookup) return false; 2572 2573 assert(!lookup->requiresADL()); 2574 2575 // Must be an unqualified lookup. 2576 if (lookup->getQualifier()) return false; 2577 2578 // Must not have found a class member. Note that if one is a class 2579 // member, they're all class members. 2580 if (lookup->getNumDecls() > 0 && 2581 (*lookup->decls_begin())->isCXXClassMember()) 2582 return false; 2583 2584 // Otherwise, ADL would have been triggered. 2585 return true; 2586 } 2587 2588 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) { 2589 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E); 2590 Out << CastEncoding; 2591 mangleType(ECE->getType()); 2592 mangleExpression(ECE->getSubExpr()); 2593 } 2594 2595 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) { 2596 // <expression> ::= <unary operator-name> <expression> 2597 // ::= <binary operator-name> <expression> <expression> 2598 // ::= <trinary operator-name> <expression> <expression> <expression> 2599 // ::= cv <type> expression # conversion with one argument 2600 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments 2601 // ::= dc <type> <expression> # dynamic_cast<type> (expression) 2602 // ::= sc <type> <expression> # static_cast<type> (expression) 2603 // ::= cc <type> <expression> # const_cast<type> (expression) 2604 // ::= rc <type> <expression> # reinterpret_cast<type> (expression) 2605 // ::= st <type> # sizeof (a type) 2606 // ::= at <type> # alignof (a type) 2607 // ::= <template-param> 2608 // ::= <function-param> 2609 // ::= sr <type> <unqualified-name> # dependent name 2610 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id 2611 // ::= ds <expression> <expression> # expr.*expr 2612 // ::= sZ <template-param> # size of a parameter pack 2613 // ::= sZ <function-param> # size of a function parameter pack 2614 // ::= <expr-primary> 2615 // <expr-primary> ::= L <type> <value number> E # integer literal 2616 // ::= L <type <value float> E # floating literal 2617 // ::= L <mangled-name> E # external name 2618 // ::= fpT # 'this' expression 2619 QualType ImplicitlyConvertedToType; 2620 2621 recurse: 2622 switch (E->getStmtClass()) { 2623 case Expr::NoStmtClass: 2624 #define ABSTRACT_STMT(Type) 2625 #define EXPR(Type, Base) 2626 #define STMT(Type, Base) \ 2627 case Expr::Type##Class: 2628 #include "clang/AST/StmtNodes.inc" 2629 // fallthrough 2630 2631 // These all can only appear in local or variable-initialization 2632 // contexts and so should never appear in a mangling. 2633 case Expr::AddrLabelExprClass: 2634 case Expr::DesignatedInitExprClass: 2635 case Expr::ImplicitValueInitExprClass: 2636 case Expr::ParenListExprClass: 2637 case Expr::LambdaExprClass: 2638 case Expr::MSPropertyRefExprClass: 2639 case Expr::TypoExprClass: // This should no longer exist in the AST by now. 2640 llvm_unreachable("unexpected statement kind"); 2641 2642 // FIXME: invent manglings for all these. 2643 case Expr::BlockExprClass: 2644 case Expr::CXXPseudoDestructorExprClass: 2645 case Expr::ChooseExprClass: 2646 case Expr::CompoundLiteralExprClass: 2647 case Expr::ExtVectorElementExprClass: 2648 case Expr::GenericSelectionExprClass: 2649 case Expr::ObjCEncodeExprClass: 2650 case Expr::ObjCIsaExprClass: 2651 case Expr::ObjCIvarRefExprClass: 2652 case Expr::ObjCMessageExprClass: 2653 case Expr::ObjCPropertyRefExprClass: 2654 case Expr::ObjCProtocolExprClass: 2655 case Expr::ObjCSelectorExprClass: 2656 case Expr::ObjCStringLiteralClass: 2657 case Expr::ObjCBoxedExprClass: 2658 case Expr::ObjCArrayLiteralClass: 2659 case Expr::ObjCDictionaryLiteralClass: 2660 case Expr::ObjCSubscriptRefExprClass: 2661 case Expr::ObjCIndirectCopyRestoreExprClass: 2662 case Expr::OffsetOfExprClass: 2663 case Expr::PredefinedExprClass: 2664 case Expr::ShuffleVectorExprClass: 2665 case Expr::ConvertVectorExprClass: 2666 case Expr::StmtExprClass: 2667 case Expr::TypeTraitExprClass: 2668 case Expr::ArrayTypeTraitExprClass: 2669 case Expr::ExpressionTraitExprClass: 2670 case Expr::VAArgExprClass: 2671 case Expr::CUDAKernelCallExprClass: 2672 case Expr::AsTypeExprClass: 2673 case Expr::PseudoObjectExprClass: 2674 case Expr::AtomicExprClass: 2675 { 2676 // As bad as this diagnostic is, it's better than crashing. 2677 DiagnosticsEngine &Diags = Context.getDiags(); 2678 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2679 "cannot yet mangle expression type %0"); 2680 Diags.Report(E->getExprLoc(), DiagID) 2681 << E->getStmtClassName() << E->getSourceRange(); 2682 break; 2683 } 2684 2685 case Expr::CXXUuidofExprClass: { 2686 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E); 2687 if (UE->isTypeOperand()) { 2688 QualType UuidT = UE->getTypeOperand(Context.getASTContext()); 2689 Out << "u8__uuidoft"; 2690 mangleType(UuidT); 2691 } else { 2692 Expr *UuidExp = UE->getExprOperand(); 2693 Out << "u8__uuidofz"; 2694 mangleExpression(UuidExp, Arity); 2695 } 2696 break; 2697 } 2698 2699 // Even gcc-4.5 doesn't mangle this. 2700 case Expr::BinaryConditionalOperatorClass: { 2701 DiagnosticsEngine &Diags = Context.getDiags(); 2702 unsigned DiagID = 2703 Diags.getCustomDiagID(DiagnosticsEngine::Error, 2704 "?: operator with omitted middle operand cannot be mangled"); 2705 Diags.Report(E->getExprLoc(), DiagID) 2706 << E->getStmtClassName() << E->getSourceRange(); 2707 break; 2708 } 2709 2710 // These are used for internal purposes and cannot be meaningfully mangled. 2711 case Expr::OpaqueValueExprClass: 2712 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?"); 2713 2714 case Expr::InitListExprClass: { 2715 Out << "il"; 2716 const InitListExpr *InitList = cast<InitListExpr>(E); 2717 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 2718 mangleExpression(InitList->getInit(i)); 2719 Out << "E"; 2720 break; 2721 } 2722 2723 case Expr::CXXDefaultArgExprClass: 2724 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity); 2725 break; 2726 2727 case Expr::CXXDefaultInitExprClass: 2728 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity); 2729 break; 2730 2731 case Expr::CXXStdInitializerListExprClass: 2732 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity); 2733 break; 2734 2735 case Expr::SubstNonTypeTemplateParmExprClass: 2736 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), 2737 Arity); 2738 break; 2739 2740 case Expr::UserDefinedLiteralClass: 2741 // We follow g++'s approach of mangling a UDL as a call to the literal 2742 // operator. 2743 case Expr::CXXMemberCallExprClass: // fallthrough 2744 case Expr::CallExprClass: { 2745 const CallExpr *CE = cast<CallExpr>(E); 2746 2747 // <expression> ::= cp <simple-id> <expression>* E 2748 // We use this mangling only when the call would use ADL except 2749 // for being parenthesized. Per discussion with David 2750 // Vandervoorde, 2011.04.25. 2751 if (isParenthesizedADLCallee(CE)) { 2752 Out << "cp"; 2753 // The callee here is a parenthesized UnresolvedLookupExpr with 2754 // no qualifier and should always get mangled as a <simple-id> 2755 // anyway. 2756 2757 // <expression> ::= cl <expression>* E 2758 } else { 2759 Out << "cl"; 2760 } 2761 2762 mangleExpression(CE->getCallee(), CE->getNumArgs()); 2763 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I) 2764 mangleExpression(CE->getArg(I)); 2765 Out << 'E'; 2766 break; 2767 } 2768 2769 case Expr::CXXNewExprClass: { 2770 const CXXNewExpr *New = cast<CXXNewExpr>(E); 2771 if (New->isGlobalNew()) Out << "gs"; 2772 Out << (New->isArray() ? "na" : "nw"); 2773 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(), 2774 E = New->placement_arg_end(); I != E; ++I) 2775 mangleExpression(*I); 2776 Out << '_'; 2777 mangleType(New->getAllocatedType()); 2778 if (New->hasInitializer()) { 2779 if (New->getInitializationStyle() == CXXNewExpr::ListInit) 2780 Out << "il"; 2781 else 2782 Out << "pi"; 2783 const Expr *Init = New->getInitializer(); 2784 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 2785 // Directly inline the initializers. 2786 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 2787 E = CCE->arg_end(); 2788 I != E; ++I) 2789 mangleExpression(*I); 2790 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) { 2791 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i) 2792 mangleExpression(PLE->getExpr(i)); 2793 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit && 2794 isa<InitListExpr>(Init)) { 2795 // Only take InitListExprs apart for list-initialization. 2796 const InitListExpr *InitList = cast<InitListExpr>(Init); 2797 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 2798 mangleExpression(InitList->getInit(i)); 2799 } else 2800 mangleExpression(Init); 2801 } 2802 Out << 'E'; 2803 break; 2804 } 2805 2806 case Expr::MemberExprClass: { 2807 const MemberExpr *ME = cast<MemberExpr>(E); 2808 mangleMemberExpr(ME->getBase(), ME->isArrow(), 2809 ME->getQualifier(), nullptr, 2810 ME->getMemberDecl()->getDeclName(), Arity); 2811 break; 2812 } 2813 2814 case Expr::UnresolvedMemberExprClass: { 2815 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E); 2816 mangleMemberExpr(ME->getBase(), ME->isArrow(), 2817 ME->getQualifier(), nullptr, ME->getMemberName(), 2818 Arity); 2819 if (ME->hasExplicitTemplateArgs()) 2820 mangleTemplateArgs(ME->getExplicitTemplateArgs()); 2821 break; 2822 } 2823 2824 case Expr::CXXDependentScopeMemberExprClass: { 2825 const CXXDependentScopeMemberExpr *ME 2826 = cast<CXXDependentScopeMemberExpr>(E); 2827 mangleMemberExpr(ME->getBase(), ME->isArrow(), 2828 ME->getQualifier(), ME->getFirstQualifierFoundInScope(), 2829 ME->getMember(), Arity); 2830 if (ME->hasExplicitTemplateArgs()) 2831 mangleTemplateArgs(ME->getExplicitTemplateArgs()); 2832 break; 2833 } 2834 2835 case Expr::UnresolvedLookupExprClass: { 2836 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E); 2837 mangleUnresolvedName(ULE->getQualifier(), nullptr, ULE->getName(), Arity); 2838 2839 // All the <unresolved-name> productions end in a 2840 // base-unresolved-name, where <template-args> are just tacked 2841 // onto the end. 2842 if (ULE->hasExplicitTemplateArgs()) 2843 mangleTemplateArgs(ULE->getExplicitTemplateArgs()); 2844 break; 2845 } 2846 2847 case Expr::CXXUnresolvedConstructExprClass: { 2848 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E); 2849 unsigned N = CE->arg_size(); 2850 2851 Out << "cv"; 2852 mangleType(CE->getType()); 2853 if (N != 1) Out << '_'; 2854 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 2855 if (N != 1) Out << 'E'; 2856 break; 2857 } 2858 2859 case Expr::CXXTemporaryObjectExprClass: 2860 case Expr::CXXConstructExprClass: { 2861 const CXXConstructExpr *CE = cast<CXXConstructExpr>(E); 2862 unsigned N = CE->getNumArgs(); 2863 2864 if (CE->isListInitialization()) 2865 Out << "tl"; 2866 else 2867 Out << "cv"; 2868 mangleType(CE->getType()); 2869 if (N != 1) Out << '_'; 2870 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 2871 if (N != 1) Out << 'E'; 2872 break; 2873 } 2874 2875 case Expr::CXXScalarValueInitExprClass: 2876 Out <<"cv"; 2877 mangleType(E->getType()); 2878 Out <<"_E"; 2879 break; 2880 2881 case Expr::CXXNoexceptExprClass: 2882 Out << "nx"; 2883 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand()); 2884 break; 2885 2886 case Expr::UnaryExprOrTypeTraitExprClass: { 2887 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); 2888 2889 if (!SAE->isInstantiationDependent()) { 2890 // Itanium C++ ABI: 2891 // If the operand of a sizeof or alignof operator is not 2892 // instantiation-dependent it is encoded as an integer literal 2893 // reflecting the result of the operator. 2894 // 2895 // If the result of the operator is implicitly converted to a known 2896 // integer type, that type is used for the literal; otherwise, the type 2897 // of std::size_t or std::ptrdiff_t is used. 2898 QualType T = (ImplicitlyConvertedToType.isNull() || 2899 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() 2900 : ImplicitlyConvertedToType; 2901 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); 2902 mangleIntegerLiteral(T, V); 2903 break; 2904 } 2905 2906 switch(SAE->getKind()) { 2907 case UETT_SizeOf: 2908 Out << 's'; 2909 break; 2910 case UETT_AlignOf: 2911 Out << 'a'; 2912 break; 2913 case UETT_VecStep: 2914 DiagnosticsEngine &Diags = Context.getDiags(); 2915 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2916 "cannot yet mangle vec_step expression"); 2917 Diags.Report(DiagID); 2918 return; 2919 } 2920 if (SAE->isArgumentType()) { 2921 Out << 't'; 2922 mangleType(SAE->getArgumentType()); 2923 } else { 2924 Out << 'z'; 2925 mangleExpression(SAE->getArgumentExpr()); 2926 } 2927 break; 2928 } 2929 2930 case Expr::CXXThrowExprClass: { 2931 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E); 2932 // <expression> ::= tw <expression> # throw expression 2933 // ::= tr # rethrow 2934 if (TE->getSubExpr()) { 2935 Out << "tw"; 2936 mangleExpression(TE->getSubExpr()); 2937 } else { 2938 Out << "tr"; 2939 } 2940 break; 2941 } 2942 2943 case Expr::CXXTypeidExprClass: { 2944 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E); 2945 // <expression> ::= ti <type> # typeid (type) 2946 // ::= te <expression> # typeid (expression) 2947 if (TIE->isTypeOperand()) { 2948 Out << "ti"; 2949 mangleType(TIE->getTypeOperand(Context.getASTContext())); 2950 } else { 2951 Out << "te"; 2952 mangleExpression(TIE->getExprOperand()); 2953 } 2954 break; 2955 } 2956 2957 case Expr::CXXDeleteExprClass: { 2958 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E); 2959 // <expression> ::= [gs] dl <expression> # [::] delete expr 2960 // ::= [gs] da <expression> # [::] delete [] expr 2961 if (DE->isGlobalDelete()) Out << "gs"; 2962 Out << (DE->isArrayForm() ? "da" : "dl"); 2963 mangleExpression(DE->getArgument()); 2964 break; 2965 } 2966 2967 case Expr::UnaryOperatorClass: { 2968 const UnaryOperator *UO = cast<UnaryOperator>(E); 2969 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()), 2970 /*Arity=*/1); 2971 mangleExpression(UO->getSubExpr()); 2972 break; 2973 } 2974 2975 case Expr::ArraySubscriptExprClass: { 2976 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E); 2977 2978 // Array subscript is treated as a syntactically weird form of 2979 // binary operator. 2980 Out << "ix"; 2981 mangleExpression(AE->getLHS()); 2982 mangleExpression(AE->getRHS()); 2983 break; 2984 } 2985 2986 case Expr::CompoundAssignOperatorClass: // fallthrough 2987 case Expr::BinaryOperatorClass: { 2988 const BinaryOperator *BO = cast<BinaryOperator>(E); 2989 if (BO->getOpcode() == BO_PtrMemD) 2990 Out << "ds"; 2991 else 2992 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()), 2993 /*Arity=*/2); 2994 mangleExpression(BO->getLHS()); 2995 mangleExpression(BO->getRHS()); 2996 break; 2997 } 2998 2999 case Expr::ConditionalOperatorClass: { 3000 const ConditionalOperator *CO = cast<ConditionalOperator>(E); 3001 mangleOperatorName(OO_Conditional, /*Arity=*/3); 3002 mangleExpression(CO->getCond()); 3003 mangleExpression(CO->getLHS(), Arity); 3004 mangleExpression(CO->getRHS(), Arity); 3005 break; 3006 } 3007 3008 case Expr::ImplicitCastExprClass: { 3009 ImplicitlyConvertedToType = E->getType(); 3010 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 3011 goto recurse; 3012 } 3013 3014 case Expr::ObjCBridgedCastExprClass: { 3015 // Mangle ownership casts as a vendor extended operator __bridge, 3016 // __bridge_transfer, or __bridge_retain. 3017 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); 3018 Out << "v1U" << Kind.size() << Kind; 3019 } 3020 // Fall through to mangle the cast itself. 3021 3022 case Expr::CStyleCastExprClass: 3023 case Expr::CXXFunctionalCastExprClass: 3024 mangleCastExpression(E, "cv"); 3025 break; 3026 3027 case Expr::CXXStaticCastExprClass: 3028 mangleCastExpression(E, "sc"); 3029 break; 3030 case Expr::CXXDynamicCastExprClass: 3031 mangleCastExpression(E, "dc"); 3032 break; 3033 case Expr::CXXReinterpretCastExprClass: 3034 mangleCastExpression(E, "rc"); 3035 break; 3036 case Expr::CXXConstCastExprClass: 3037 mangleCastExpression(E, "cc"); 3038 break; 3039 3040 case Expr::CXXOperatorCallExprClass: { 3041 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E); 3042 unsigned NumArgs = CE->getNumArgs(); 3043 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs); 3044 // Mangle the arguments. 3045 for (unsigned i = 0; i != NumArgs; ++i) 3046 mangleExpression(CE->getArg(i)); 3047 break; 3048 } 3049 3050 case Expr::ParenExprClass: 3051 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity); 3052 break; 3053 3054 case Expr::DeclRefExprClass: { 3055 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 3056 3057 switch (D->getKind()) { 3058 default: 3059 // <expr-primary> ::= L <mangled-name> E # external name 3060 Out << 'L'; 3061 mangle(D, "_Z"); 3062 Out << 'E'; 3063 break; 3064 3065 case Decl::ParmVar: 3066 mangleFunctionParam(cast<ParmVarDecl>(D)); 3067 break; 3068 3069 case Decl::EnumConstant: { 3070 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D); 3071 mangleIntegerLiteral(ED->getType(), ED->getInitVal()); 3072 break; 3073 } 3074 3075 case Decl::NonTypeTemplateParm: { 3076 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D); 3077 mangleTemplateParameter(PD->getIndex()); 3078 break; 3079 } 3080 3081 } 3082 3083 break; 3084 } 3085 3086 case Expr::SubstNonTypeTemplateParmPackExprClass: 3087 // FIXME: not clear how to mangle this! 3088 // template <unsigned N...> class A { 3089 // template <class U...> void foo(U (&x)[N]...); 3090 // }; 3091 Out << "_SUBSTPACK_"; 3092 break; 3093 3094 case Expr::FunctionParmPackExprClass: { 3095 // FIXME: not clear how to mangle this! 3096 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E); 3097 Out << "v110_SUBSTPACK"; 3098 mangleFunctionParam(FPPE->getParameterPack()); 3099 break; 3100 } 3101 3102 case Expr::DependentScopeDeclRefExprClass: { 3103 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E); 3104 mangleUnresolvedName(DRE->getQualifier(), nullptr, DRE->getDeclName(), 3105 Arity); 3106 3107 // All the <unresolved-name> productions end in a 3108 // base-unresolved-name, where <template-args> are just tacked 3109 // onto the end. 3110 if (DRE->hasExplicitTemplateArgs()) 3111 mangleTemplateArgs(DRE->getExplicitTemplateArgs()); 3112 break; 3113 } 3114 3115 case Expr::CXXBindTemporaryExprClass: 3116 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr()); 3117 break; 3118 3119 case Expr::ExprWithCleanupsClass: 3120 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity); 3121 break; 3122 3123 case Expr::FloatingLiteralClass: { 3124 const FloatingLiteral *FL = cast<FloatingLiteral>(E); 3125 Out << 'L'; 3126 mangleType(FL->getType()); 3127 mangleFloat(FL->getValue()); 3128 Out << 'E'; 3129 break; 3130 } 3131 3132 case Expr::CharacterLiteralClass: 3133 Out << 'L'; 3134 mangleType(E->getType()); 3135 Out << cast<CharacterLiteral>(E)->getValue(); 3136 Out << 'E'; 3137 break; 3138 3139 // FIXME. __objc_yes/__objc_no are mangled same as true/false 3140 case Expr::ObjCBoolLiteralExprClass: 3141 Out << "Lb"; 3142 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 3143 Out << 'E'; 3144 break; 3145 3146 case Expr::CXXBoolLiteralExprClass: 3147 Out << "Lb"; 3148 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 3149 Out << 'E'; 3150 break; 3151 3152 case Expr::IntegerLiteralClass: { 3153 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue()); 3154 if (E->getType()->isSignedIntegerType()) 3155 Value.setIsSigned(true); 3156 mangleIntegerLiteral(E->getType(), Value); 3157 break; 3158 } 3159 3160 case Expr::ImaginaryLiteralClass: { 3161 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E); 3162 // Mangle as if a complex literal. 3163 // Proposal from David Vandevoorde, 2010.06.30. 3164 Out << 'L'; 3165 mangleType(E->getType()); 3166 if (const FloatingLiteral *Imag = 3167 dyn_cast<FloatingLiteral>(IE->getSubExpr())) { 3168 // Mangle a floating-point zero of the appropriate type. 3169 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics())); 3170 Out << '_'; 3171 mangleFloat(Imag->getValue()); 3172 } else { 3173 Out << "0_"; 3174 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue()); 3175 if (IE->getSubExpr()->getType()->isSignedIntegerType()) 3176 Value.setIsSigned(true); 3177 mangleNumber(Value); 3178 } 3179 Out << 'E'; 3180 break; 3181 } 3182 3183 case Expr::StringLiteralClass: { 3184 // Revised proposal from David Vandervoorde, 2010.07.15. 3185 Out << 'L'; 3186 assert(isa<ConstantArrayType>(E->getType())); 3187 mangleType(E->getType()); 3188 Out << 'E'; 3189 break; 3190 } 3191 3192 case Expr::GNUNullExprClass: 3193 // FIXME: should this really be mangled the same as nullptr? 3194 // fallthrough 3195 3196 case Expr::CXXNullPtrLiteralExprClass: { 3197 Out << "LDnE"; 3198 break; 3199 } 3200 3201 case Expr::PackExpansionExprClass: 3202 Out << "sp"; 3203 mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); 3204 break; 3205 3206 case Expr::SizeOfPackExprClass: { 3207 Out << "sZ"; 3208 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack(); 3209 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack)) 3210 mangleTemplateParameter(TTP->getIndex()); 3211 else if (const NonTypeTemplateParmDecl *NTTP 3212 = dyn_cast<NonTypeTemplateParmDecl>(Pack)) 3213 mangleTemplateParameter(NTTP->getIndex()); 3214 else if (const TemplateTemplateParmDecl *TempTP 3215 = dyn_cast<TemplateTemplateParmDecl>(Pack)) 3216 mangleTemplateParameter(TempTP->getIndex()); 3217 else 3218 mangleFunctionParam(cast<ParmVarDecl>(Pack)); 3219 break; 3220 } 3221 3222 case Expr::MaterializeTemporaryExprClass: { 3223 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()); 3224 break; 3225 } 3226 3227 case Expr::CXXFoldExprClass: { 3228 auto *FE = cast<CXXFoldExpr>(E); 3229 if (FE->isLeftFold()) 3230 Out << (FE->getInit() ? "fL" : "fl"); 3231 else 3232 Out << (FE->getInit() ? "fR" : "fr"); 3233 3234 if (FE->getOperator() == BO_PtrMemD) 3235 Out << "ds"; 3236 else 3237 mangleOperatorName( 3238 BinaryOperator::getOverloadedOperator(FE->getOperator()), 3239 /*Arity=*/2); 3240 3241 if (FE->getLHS()) 3242 mangleExpression(FE->getLHS()); 3243 if (FE->getRHS()) 3244 mangleExpression(FE->getRHS()); 3245 break; 3246 } 3247 3248 case Expr::CXXThisExprClass: 3249 Out << "fpT"; 3250 break; 3251 } 3252 } 3253 3254 /// Mangle an expression which refers to a parameter variable. 3255 /// 3256 /// <expression> ::= <function-param> 3257 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0 3258 /// <function-param> ::= fp <top-level CV-qualifiers> 3259 /// <parameter-2 non-negative number> _ # L == 0, I > 0 3260 /// <function-param> ::= fL <L-1 non-negative number> 3261 /// p <top-level CV-qualifiers> _ # L > 0, I == 0 3262 /// <function-param> ::= fL <L-1 non-negative number> 3263 /// p <top-level CV-qualifiers> 3264 /// <I-1 non-negative number> _ # L > 0, I > 0 3265 /// 3266 /// L is the nesting depth of the parameter, defined as 1 if the 3267 /// parameter comes from the innermost function prototype scope 3268 /// enclosing the current context, 2 if from the next enclosing 3269 /// function prototype scope, and so on, with one special case: if 3270 /// we've processed the full parameter clause for the innermost 3271 /// function type, then L is one less. This definition conveniently 3272 /// makes it irrelevant whether a function's result type was written 3273 /// trailing or leading, but is otherwise overly complicated; the 3274 /// numbering was first designed without considering references to 3275 /// parameter in locations other than return types, and then the 3276 /// mangling had to be generalized without changing the existing 3277 /// manglings. 3278 /// 3279 /// I is the zero-based index of the parameter within its parameter 3280 /// declaration clause. Note that the original ABI document describes 3281 /// this using 1-based ordinals. 3282 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) { 3283 unsigned parmDepth = parm->getFunctionScopeDepth(); 3284 unsigned parmIndex = parm->getFunctionScopeIndex(); 3285 3286 // Compute 'L'. 3287 // parmDepth does not include the declaring function prototype. 3288 // FunctionTypeDepth does account for that. 3289 assert(parmDepth < FunctionTypeDepth.getDepth()); 3290 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth; 3291 if (FunctionTypeDepth.isInResultType()) 3292 nestingDepth--; 3293 3294 if (nestingDepth == 0) { 3295 Out << "fp"; 3296 } else { 3297 Out << "fL" << (nestingDepth - 1) << 'p'; 3298 } 3299 3300 // Top-level qualifiers. We don't have to worry about arrays here, 3301 // because parameters declared as arrays should already have been 3302 // transformed to have pointer type. FIXME: apparently these don't 3303 // get mangled if used as an rvalue of a known non-class type? 3304 assert(!parm->getType()->isArrayType() 3305 && "parameter's type is still an array type?"); 3306 mangleQualifiers(parm->getType().getQualifiers()); 3307 3308 // Parameter index. 3309 if (parmIndex != 0) { 3310 Out << (parmIndex - 1); 3311 } 3312 Out << '_'; 3313 } 3314 3315 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) { 3316 // <ctor-dtor-name> ::= C1 # complete object constructor 3317 // ::= C2 # base object constructor 3318 // 3319 // In addition, C5 is a comdat name with C1 and C2 in it. 3320 switch (T) { 3321 case Ctor_Complete: 3322 Out << "C1"; 3323 break; 3324 case Ctor_Base: 3325 Out << "C2"; 3326 break; 3327 case Ctor_Comdat: 3328 Out << "C5"; 3329 break; 3330 } 3331 } 3332 3333 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 3334 // <ctor-dtor-name> ::= D0 # deleting destructor 3335 // ::= D1 # complete object destructor 3336 // ::= D2 # base object destructor 3337 // 3338 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it. 3339 switch (T) { 3340 case Dtor_Deleting: 3341 Out << "D0"; 3342 break; 3343 case Dtor_Complete: 3344 Out << "D1"; 3345 break; 3346 case Dtor_Base: 3347 Out << "D2"; 3348 break; 3349 case Dtor_Comdat: 3350 Out << "D5"; 3351 break; 3352 } 3353 } 3354 3355 void CXXNameMangler::mangleTemplateArgs( 3356 const ASTTemplateArgumentListInfo &TemplateArgs) { 3357 // <template-args> ::= I <template-arg>+ E 3358 Out << 'I'; 3359 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i) 3360 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument()); 3361 Out << 'E'; 3362 } 3363 3364 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) { 3365 // <template-args> ::= I <template-arg>+ E 3366 Out << 'I'; 3367 for (unsigned i = 0, e = AL.size(); i != e; ++i) 3368 mangleTemplateArg(AL[i]); 3369 Out << 'E'; 3370 } 3371 3372 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs, 3373 unsigned NumTemplateArgs) { 3374 // <template-args> ::= I <template-arg>+ E 3375 Out << 'I'; 3376 for (unsigned i = 0; i != NumTemplateArgs; ++i) 3377 mangleTemplateArg(TemplateArgs[i]); 3378 Out << 'E'; 3379 } 3380 3381 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) { 3382 // <template-arg> ::= <type> # type or template 3383 // ::= X <expression> E # expression 3384 // ::= <expr-primary> # simple expressions 3385 // ::= J <template-arg>* E # argument pack 3386 if (!A.isInstantiationDependent() || A.isDependent()) 3387 A = Context.getASTContext().getCanonicalTemplateArgument(A); 3388 3389 switch (A.getKind()) { 3390 case TemplateArgument::Null: 3391 llvm_unreachable("Cannot mangle NULL template argument"); 3392 3393 case TemplateArgument::Type: 3394 mangleType(A.getAsType()); 3395 break; 3396 case TemplateArgument::Template: 3397 // This is mangled as <type>. 3398 mangleType(A.getAsTemplate()); 3399 break; 3400 case TemplateArgument::TemplateExpansion: 3401 // <type> ::= Dp <type> # pack expansion (C++0x) 3402 Out << "Dp"; 3403 mangleType(A.getAsTemplateOrTemplatePattern()); 3404 break; 3405 case TemplateArgument::Expression: { 3406 // It's possible to end up with a DeclRefExpr here in certain 3407 // dependent cases, in which case we should mangle as a 3408 // declaration. 3409 const Expr *E = A.getAsExpr()->IgnoreParens(); 3410 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3411 const ValueDecl *D = DRE->getDecl(); 3412 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) { 3413 Out << "L"; 3414 mangle(D, "_Z"); 3415 Out << 'E'; 3416 break; 3417 } 3418 } 3419 3420 Out << 'X'; 3421 mangleExpression(E); 3422 Out << 'E'; 3423 break; 3424 } 3425 case TemplateArgument::Integral: 3426 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral()); 3427 break; 3428 case TemplateArgument::Declaration: { 3429 // <expr-primary> ::= L <mangled-name> E # external name 3430 // Clang produces AST's where pointer-to-member-function expressions 3431 // and pointer-to-function expressions are represented as a declaration not 3432 // an expression. We compensate for it here to produce the correct mangling. 3433 ValueDecl *D = A.getAsDecl(); 3434 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType(); 3435 if (compensateMangling) { 3436 Out << 'X'; 3437 mangleOperatorName(OO_Amp, 1); 3438 } 3439 3440 Out << 'L'; 3441 // References to external entities use the mangled name; if the name would 3442 // not normally be manged then mangle it as unqualified. 3443 // 3444 // FIXME: The ABI specifies that external names here should have _Z, but 3445 // gcc leaves this off. 3446 if (compensateMangling) 3447 mangle(D, "_Z"); 3448 else 3449 mangle(D, "Z"); 3450 Out << 'E'; 3451 3452 if (compensateMangling) 3453 Out << 'E'; 3454 3455 break; 3456 } 3457 case TemplateArgument::NullPtr: { 3458 // <expr-primary> ::= L <type> 0 E 3459 Out << 'L'; 3460 mangleType(A.getNullPtrType()); 3461 Out << "0E"; 3462 break; 3463 } 3464 case TemplateArgument::Pack: { 3465 // <template-arg> ::= J <template-arg>* E 3466 Out << 'J'; 3467 for (const auto &P : A.pack_elements()) 3468 mangleTemplateArg(P); 3469 Out << 'E'; 3470 } 3471 } 3472 } 3473 3474 void CXXNameMangler::mangleTemplateParameter(unsigned Index) { 3475 // <template-param> ::= T_ # first template parameter 3476 // ::= T <parameter-2 non-negative number> _ 3477 if (Index == 0) 3478 Out << "T_"; 3479 else 3480 Out << 'T' << (Index - 1) << '_'; 3481 } 3482 3483 void CXXNameMangler::mangleSeqID(unsigned SeqID) { 3484 if (SeqID == 1) 3485 Out << '0'; 3486 else if (SeqID > 1) { 3487 SeqID--; 3488 3489 // <seq-id> is encoded in base-36, using digits and upper case letters. 3490 char Buffer[7]; // log(2**32) / log(36) ~= 7 3491 MutableArrayRef<char> BufferRef(Buffer); 3492 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin(); 3493 3494 for (; SeqID != 0; SeqID /= 36) { 3495 unsigned C = SeqID % 36; 3496 *I++ = (C < 10 ? '0' + C : 'A' + C - 10); 3497 } 3498 3499 Out.write(I.base(), I - BufferRef.rbegin()); 3500 } 3501 Out << '_'; 3502 } 3503 3504 void CXXNameMangler::mangleExistingSubstitution(QualType type) { 3505 bool result = mangleSubstitution(type); 3506 assert(result && "no existing substitution for type"); 3507 (void) result; 3508 } 3509 3510 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) { 3511 bool result = mangleSubstitution(tname); 3512 assert(result && "no existing substitution for template name"); 3513 (void) result; 3514 } 3515 3516 // <substitution> ::= S <seq-id> _ 3517 // ::= S_ 3518 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) { 3519 // Try one of the standard substitutions first. 3520 if (mangleStandardSubstitution(ND)) 3521 return true; 3522 3523 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 3524 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND)); 3525 } 3526 3527 /// \brief Determine whether the given type has any qualifiers that are 3528 /// relevant for substitutions. 3529 static bool hasMangledSubstitutionQualifiers(QualType T) { 3530 Qualifiers Qs = T.getQualifiers(); 3531 return Qs.getCVRQualifiers() || Qs.hasAddressSpace(); 3532 } 3533 3534 bool CXXNameMangler::mangleSubstitution(QualType T) { 3535 if (!hasMangledSubstitutionQualifiers(T)) { 3536 if (const RecordType *RT = T->getAs<RecordType>()) 3537 return mangleSubstitution(RT->getDecl()); 3538 } 3539 3540 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 3541 3542 return mangleSubstitution(TypePtr); 3543 } 3544 3545 bool CXXNameMangler::mangleSubstitution(TemplateName Template) { 3546 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 3547 return mangleSubstitution(TD); 3548 3549 Template = Context.getASTContext().getCanonicalTemplateName(Template); 3550 return mangleSubstitution( 3551 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 3552 } 3553 3554 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) { 3555 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr); 3556 if (I == Substitutions.end()) 3557 return false; 3558 3559 unsigned SeqID = I->second; 3560 Out << 'S'; 3561 mangleSeqID(SeqID); 3562 3563 return true; 3564 } 3565 3566 static bool isCharType(QualType T) { 3567 if (T.isNull()) 3568 return false; 3569 3570 return T->isSpecificBuiltinType(BuiltinType::Char_S) || 3571 T->isSpecificBuiltinType(BuiltinType::Char_U); 3572 } 3573 3574 /// isCharSpecialization - Returns whether a given type is a template 3575 /// specialization of a given name with a single argument of type char. 3576 static bool isCharSpecialization(QualType T, const char *Name) { 3577 if (T.isNull()) 3578 return false; 3579 3580 const RecordType *RT = T->getAs<RecordType>(); 3581 if (!RT) 3582 return false; 3583 3584 const ClassTemplateSpecializationDecl *SD = 3585 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 3586 if (!SD) 3587 return false; 3588 3589 if (!isStdNamespace(getEffectiveDeclContext(SD))) 3590 return false; 3591 3592 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 3593 if (TemplateArgs.size() != 1) 3594 return false; 3595 3596 if (!isCharType(TemplateArgs[0].getAsType())) 3597 return false; 3598 3599 return SD->getIdentifier()->getName() == Name; 3600 } 3601 3602 template <std::size_t StrLen> 3603 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD, 3604 const char (&Str)[StrLen]) { 3605 if (!SD->getIdentifier()->isStr(Str)) 3606 return false; 3607 3608 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 3609 if (TemplateArgs.size() != 2) 3610 return false; 3611 3612 if (!isCharType(TemplateArgs[0].getAsType())) 3613 return false; 3614 3615 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 3616 return false; 3617 3618 return true; 3619 } 3620 3621 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) { 3622 // <substitution> ::= St # ::std:: 3623 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 3624 if (isStd(NS)) { 3625 Out << "St"; 3626 return true; 3627 } 3628 } 3629 3630 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) { 3631 if (!isStdNamespace(getEffectiveDeclContext(TD))) 3632 return false; 3633 3634 // <substitution> ::= Sa # ::std::allocator 3635 if (TD->getIdentifier()->isStr("allocator")) { 3636 Out << "Sa"; 3637 return true; 3638 } 3639 3640 // <<substitution> ::= Sb # ::std::basic_string 3641 if (TD->getIdentifier()->isStr("basic_string")) { 3642 Out << "Sb"; 3643 return true; 3644 } 3645 } 3646 3647 if (const ClassTemplateSpecializationDecl *SD = 3648 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 3649 if (!isStdNamespace(getEffectiveDeclContext(SD))) 3650 return false; 3651 3652 // <substitution> ::= Ss # ::std::basic_string<char, 3653 // ::std::char_traits<char>, 3654 // ::std::allocator<char> > 3655 if (SD->getIdentifier()->isStr("basic_string")) { 3656 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 3657 3658 if (TemplateArgs.size() != 3) 3659 return false; 3660 3661 if (!isCharType(TemplateArgs[0].getAsType())) 3662 return false; 3663 3664 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 3665 return false; 3666 3667 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator")) 3668 return false; 3669 3670 Out << "Ss"; 3671 return true; 3672 } 3673 3674 // <substitution> ::= Si # ::std::basic_istream<char, 3675 // ::std::char_traits<char> > 3676 if (isStreamCharSpecialization(SD, "basic_istream")) { 3677 Out << "Si"; 3678 return true; 3679 } 3680 3681 // <substitution> ::= So # ::std::basic_ostream<char, 3682 // ::std::char_traits<char> > 3683 if (isStreamCharSpecialization(SD, "basic_ostream")) { 3684 Out << "So"; 3685 return true; 3686 } 3687 3688 // <substitution> ::= Sd # ::std::basic_iostream<char, 3689 // ::std::char_traits<char> > 3690 if (isStreamCharSpecialization(SD, "basic_iostream")) { 3691 Out << "Sd"; 3692 return true; 3693 } 3694 } 3695 return false; 3696 } 3697 3698 void CXXNameMangler::addSubstitution(QualType T) { 3699 if (!hasMangledSubstitutionQualifiers(T)) { 3700 if (const RecordType *RT = T->getAs<RecordType>()) { 3701 addSubstitution(RT->getDecl()); 3702 return; 3703 } 3704 } 3705 3706 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 3707 addSubstitution(TypePtr); 3708 } 3709 3710 void CXXNameMangler::addSubstitution(TemplateName Template) { 3711 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 3712 return addSubstitution(TD); 3713 3714 Template = Context.getASTContext().getCanonicalTemplateName(Template); 3715 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 3716 } 3717 3718 void CXXNameMangler::addSubstitution(uintptr_t Ptr) { 3719 assert(!Substitutions.count(Ptr) && "Substitution already exists!"); 3720 Substitutions[Ptr] = SeqID++; 3721 } 3722 3723 // 3724 3725 /// \brief Mangles the name of the declaration D and emits that name to the 3726 /// given output stream. 3727 /// 3728 /// If the declaration D requires a mangled name, this routine will emit that 3729 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged 3730 /// and this routine will return false. In this case, the caller should just 3731 /// emit the identifier of the declaration (\c D->getIdentifier()) as its 3732 /// name. 3733 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D, 3734 raw_ostream &Out) { 3735 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) && 3736 "Invalid mangleName() call, argument is not a variable or function!"); 3737 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) && 3738 "Invalid mangleName() call on 'structor decl!"); 3739 3740 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 3741 getASTContext().getSourceManager(), 3742 "Mangling declaration"); 3743 3744 CXXNameMangler Mangler(*this, Out, D); 3745 Mangler.mangle(D); 3746 } 3747 3748 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D, 3749 CXXCtorType Type, 3750 raw_ostream &Out) { 3751 CXXNameMangler Mangler(*this, Out, D, Type); 3752 Mangler.mangle(D); 3753 } 3754 3755 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D, 3756 CXXDtorType Type, 3757 raw_ostream &Out) { 3758 CXXNameMangler Mangler(*this, Out, D, Type); 3759 Mangler.mangle(D); 3760 } 3761 3762 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D, 3763 raw_ostream &Out) { 3764 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat); 3765 Mangler.mangle(D); 3766 } 3767 3768 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D, 3769 raw_ostream &Out) { 3770 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat); 3771 Mangler.mangle(D); 3772 } 3773 3774 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 3775 const ThunkInfo &Thunk, 3776 raw_ostream &Out) { 3777 // <special-name> ::= T <call-offset> <base encoding> 3778 // # base is the nominal target function of thunk 3779 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding> 3780 // # base is the nominal target function of thunk 3781 // # first call-offset is 'this' adjustment 3782 // # second call-offset is result adjustment 3783 3784 assert(!isa<CXXDestructorDecl>(MD) && 3785 "Use mangleCXXDtor for destructor decls!"); 3786 CXXNameMangler Mangler(*this, Out); 3787 Mangler.getStream() << "_ZT"; 3788 if (!Thunk.Return.isEmpty()) 3789 Mangler.getStream() << 'c'; 3790 3791 // Mangle the 'this' pointer adjustment. 3792 Mangler.mangleCallOffset(Thunk.This.NonVirtual, 3793 Thunk.This.Virtual.Itanium.VCallOffsetOffset); 3794 3795 // Mangle the return pointer adjustment if there is one. 3796 if (!Thunk.Return.isEmpty()) 3797 Mangler.mangleCallOffset(Thunk.Return.NonVirtual, 3798 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset); 3799 3800 Mangler.mangleFunctionEncoding(MD); 3801 } 3802 3803 void ItaniumMangleContextImpl::mangleCXXDtorThunk( 3804 const CXXDestructorDecl *DD, CXXDtorType Type, 3805 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) { 3806 // <special-name> ::= T <call-offset> <base encoding> 3807 // # base is the nominal target function of thunk 3808 CXXNameMangler Mangler(*this, Out, DD, Type); 3809 Mangler.getStream() << "_ZT"; 3810 3811 // Mangle the 'this' pointer adjustment. 3812 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 3813 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); 3814 3815 Mangler.mangleFunctionEncoding(DD); 3816 } 3817 3818 /// mangleGuardVariable - Returns the mangled name for a guard variable 3819 /// for the passed in VarDecl. 3820 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D, 3821 raw_ostream &Out) { 3822 // <special-name> ::= GV <object name> # Guard variable for one-time 3823 // # initialization 3824 CXXNameMangler Mangler(*this, Out); 3825 Mangler.getStream() << "_ZGV"; 3826 Mangler.mangleName(D); 3827 } 3828 3829 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD, 3830 raw_ostream &Out) { 3831 // These symbols are internal in the Itanium ABI, so the names don't matter. 3832 // Clang has traditionally used this symbol and allowed LLVM to adjust it to 3833 // avoid duplicate symbols. 3834 Out << "__cxx_global_var_init"; 3835 } 3836 3837 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 3838 raw_ostream &Out) { 3839 // Prefix the mangling of D with __dtor_. 3840 CXXNameMangler Mangler(*this, Out); 3841 Mangler.getStream() << "__dtor_"; 3842 if (shouldMangleDeclName(D)) 3843 Mangler.mangle(D); 3844 else 3845 Mangler.getStream() << D->getName(); 3846 } 3847 3848 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D, 3849 raw_ostream &Out) { 3850 // <special-name> ::= TH <object name> 3851 CXXNameMangler Mangler(*this, Out); 3852 Mangler.getStream() << "_ZTH"; 3853 Mangler.mangleName(D); 3854 } 3855 3856 void 3857 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D, 3858 raw_ostream &Out) { 3859 // <special-name> ::= TW <object name> 3860 CXXNameMangler Mangler(*this, Out); 3861 Mangler.getStream() << "_ZTW"; 3862 Mangler.mangleName(D); 3863 } 3864 3865 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D, 3866 unsigned ManglingNumber, 3867 raw_ostream &Out) { 3868 // We match the GCC mangling here. 3869 // <special-name> ::= GR <object name> 3870 CXXNameMangler Mangler(*this, Out); 3871 Mangler.getStream() << "_ZGR"; 3872 Mangler.mangleName(D); 3873 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!"); 3874 Mangler.mangleSeqID(ManglingNumber - 1); 3875 } 3876 3877 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD, 3878 raw_ostream &Out) { 3879 // <special-name> ::= TV <type> # virtual table 3880 CXXNameMangler Mangler(*this, Out); 3881 Mangler.getStream() << "_ZTV"; 3882 Mangler.mangleNameOrStandardSubstitution(RD); 3883 } 3884 3885 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD, 3886 raw_ostream &Out) { 3887 // <special-name> ::= TT <type> # VTT structure 3888 CXXNameMangler Mangler(*this, Out); 3889 Mangler.getStream() << "_ZTT"; 3890 Mangler.mangleNameOrStandardSubstitution(RD); 3891 } 3892 3893 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD, 3894 int64_t Offset, 3895 const CXXRecordDecl *Type, 3896 raw_ostream &Out) { 3897 // <special-name> ::= TC <type> <offset number> _ <base type> 3898 CXXNameMangler Mangler(*this, Out); 3899 Mangler.getStream() << "_ZTC"; 3900 Mangler.mangleNameOrStandardSubstitution(RD); 3901 Mangler.getStream() << Offset; 3902 Mangler.getStream() << '_'; 3903 Mangler.mangleNameOrStandardSubstitution(Type); 3904 } 3905 3906 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) { 3907 // <special-name> ::= TI <type> # typeinfo structure 3908 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers"); 3909 CXXNameMangler Mangler(*this, Out); 3910 Mangler.getStream() << "_ZTI"; 3911 Mangler.mangleType(Ty); 3912 } 3913 3914 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty, 3915 raw_ostream &Out) { 3916 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string) 3917 CXXNameMangler Mangler(*this, Out); 3918 Mangler.getStream() << "_ZTS"; 3919 Mangler.mangleType(Ty); 3920 } 3921 3922 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) { 3923 mangleCXXRTTIName(Ty, Out); 3924 } 3925 3926 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) { 3927 llvm_unreachable("Can't mangle string literals"); 3928 } 3929 3930 ItaniumMangleContext * 3931 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) { 3932 return new ItaniumMangleContextImpl(Context, Diags); 3933 } 3934 3935