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 TemplateTemplateParmDecl *TTP 641 = dyn_cast<TemplateTemplateParmDecl>(ND)) { 642 mangleTemplateParameter(TTP->getIndex()); 643 return; 644 } 645 646 mangleUnscopedName(ND->getTemplatedDecl()); 647 addSubstitution(ND); 648 } 649 650 void CXXNameMangler::mangleUnscopedTemplateName(TemplateName Template) { 651 // <unscoped-template-name> ::= <unscoped-name> 652 // ::= <substitution> 653 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 654 return mangleUnscopedTemplateName(TD); 655 656 if (mangleSubstitution(Template)) 657 return; 658 659 DependentTemplateName *Dependent = Template.getAsDependentTemplateName(); 660 assert(Dependent && "Not a dependent template name?"); 661 if (const IdentifierInfo *Id = Dependent->getIdentifier()) 662 mangleSourceName(Id); 663 else 664 mangleOperatorName(Dependent->getOperator(), UnknownArity); 665 666 addSubstitution(Template); 667 } 668 669 void CXXNameMangler::mangleFloat(const llvm::APFloat &f) { 670 // ABI: 671 // Floating-point literals are encoded using a fixed-length 672 // lowercase hexadecimal string corresponding to the internal 673 // representation (IEEE on Itanium), high-order bytes first, 674 // without leading zeroes. For example: "Lf bf800000 E" is -1.0f 675 // on Itanium. 676 // The 'without leading zeroes' thing seems to be an editorial 677 // mistake; see the discussion on cxx-abi-dev beginning on 678 // 2012-01-16. 679 680 // Our requirements here are just barely weird enough to justify 681 // using a custom algorithm instead of post-processing APInt::toString(). 682 683 llvm::APInt valueBits = f.bitcastToAPInt(); 684 unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4; 685 assert(numCharacters != 0); 686 687 // Allocate a buffer of the right number of characters. 688 SmallVector<char, 20> buffer; 689 buffer.set_size(numCharacters); 690 691 // Fill the buffer left-to-right. 692 for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) { 693 // The bit-index of the next hex digit. 694 unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1); 695 696 // Project out 4 bits starting at 'digitIndex'. 697 llvm::integerPart hexDigit 698 = valueBits.getRawData()[digitBitIndex / llvm::integerPartWidth]; 699 hexDigit >>= (digitBitIndex % llvm::integerPartWidth); 700 hexDigit &= 0xF; 701 702 // Map that over to a lowercase hex digit. 703 static const char charForHex[16] = { 704 '0', '1', '2', '3', '4', '5', '6', '7', 705 '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' 706 }; 707 buffer[stringIndex] = charForHex[hexDigit]; 708 } 709 710 Out.write(buffer.data(), numCharacters); 711 } 712 713 void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) { 714 if (Value.isSigned() && Value.isNegative()) { 715 Out << 'n'; 716 Value.abs().print(Out, /*signed*/ false); 717 } else { 718 Value.print(Out, /*signed*/ false); 719 } 720 } 721 722 void CXXNameMangler::mangleNumber(int64_t Number) { 723 // <number> ::= [n] <non-negative decimal integer> 724 if (Number < 0) { 725 Out << 'n'; 726 Number = -Number; 727 } 728 729 Out << Number; 730 } 731 732 void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) { 733 // <call-offset> ::= h <nv-offset> _ 734 // ::= v <v-offset> _ 735 // <nv-offset> ::= <offset number> # non-virtual base override 736 // <v-offset> ::= <offset number> _ <virtual offset number> 737 // # virtual base override, with vcall offset 738 if (!Virtual) { 739 Out << 'h'; 740 mangleNumber(NonVirtual); 741 Out << '_'; 742 return; 743 } 744 745 Out << 'v'; 746 mangleNumber(NonVirtual); 747 Out << '_'; 748 mangleNumber(Virtual); 749 Out << '_'; 750 } 751 752 void CXXNameMangler::manglePrefix(QualType type) { 753 if (const TemplateSpecializationType *TST = 754 type->getAs<TemplateSpecializationType>()) { 755 if (!mangleSubstitution(QualType(TST, 0))) { 756 mangleTemplatePrefix(TST->getTemplateName()); 757 758 // FIXME: GCC does not appear to mangle the template arguments when 759 // the template in question is a dependent template name. Should we 760 // emulate that badness? 761 mangleTemplateArgs(TST->getArgs(), TST->getNumArgs()); 762 addSubstitution(QualType(TST, 0)); 763 } 764 } else if (const DependentTemplateSpecializationType *DTST 765 = type->getAs<DependentTemplateSpecializationType>()) { 766 TemplateName Template 767 = getASTContext().getDependentTemplateName(DTST->getQualifier(), 768 DTST->getIdentifier()); 769 mangleTemplatePrefix(Template); 770 771 // FIXME: GCC does not appear to mangle the template arguments when 772 // the template in question is a dependent template name. Should we 773 // emulate that badness? 774 mangleTemplateArgs(DTST->getArgs(), DTST->getNumArgs()); 775 } else { 776 // We use the QualType mangle type variant here because it handles 777 // substitutions. 778 mangleType(type); 779 } 780 } 781 782 /// Mangle everything prior to the base-unresolved-name in an unresolved-name. 783 /// 784 /// \param firstQualifierLookup - the entity found by unqualified lookup 785 /// for the first name in the qualifier, if this is for a member expression 786 /// \param recursive - true if this is being called recursively, 787 /// i.e. if there is more prefix "to the right". 788 void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier, 789 NamedDecl *firstQualifierLookup, 790 bool recursive) { 791 792 // x, ::x 793 // <unresolved-name> ::= [gs] <base-unresolved-name> 794 795 // T::x / decltype(p)::x 796 // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name> 797 798 // T::N::x /decltype(p)::N::x 799 // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E 800 // <base-unresolved-name> 801 802 // A::x, N::y, A<T>::z; "gs" means leading "::" 803 // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E 804 // <base-unresolved-name> 805 806 switch (qualifier->getKind()) { 807 case NestedNameSpecifier::Global: 808 Out << "gs"; 809 810 // We want an 'sr' unless this is the entire NNS. 811 if (recursive) 812 Out << "sr"; 813 814 // We never want an 'E' here. 815 return; 816 817 case NestedNameSpecifier::Namespace: 818 if (qualifier->getPrefix()) 819 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup, 820 /*recursive*/ true); 821 else 822 Out << "sr"; 823 mangleSourceName(qualifier->getAsNamespace()->getIdentifier()); 824 break; 825 case NestedNameSpecifier::NamespaceAlias: 826 if (qualifier->getPrefix()) 827 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup, 828 /*recursive*/ true); 829 else 830 Out << "sr"; 831 mangleSourceName(qualifier->getAsNamespaceAlias()->getIdentifier()); 832 break; 833 834 case NestedNameSpecifier::TypeSpec: 835 case NestedNameSpecifier::TypeSpecWithTemplate: { 836 const Type *type = qualifier->getAsType(); 837 838 // We only want to use an unresolved-type encoding if this is one of: 839 // - a decltype 840 // - a template type parameter 841 // - a template template parameter with arguments 842 // In all of these cases, we should have no prefix. 843 if (qualifier->getPrefix()) { 844 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup, 845 /*recursive*/ true); 846 } else { 847 // Otherwise, all the cases want this. 848 Out << "sr"; 849 } 850 851 // Only certain other types are valid as prefixes; enumerate them. 852 switch (type->getTypeClass()) { 853 case Type::Builtin: 854 case Type::Complex: 855 case Type::Adjusted: 856 case Type::Decayed: 857 case Type::Pointer: 858 case Type::BlockPointer: 859 case Type::LValueReference: 860 case Type::RValueReference: 861 case Type::MemberPointer: 862 case Type::ConstantArray: 863 case Type::IncompleteArray: 864 case Type::VariableArray: 865 case Type::DependentSizedArray: 866 case Type::DependentSizedExtVector: 867 case Type::Vector: 868 case Type::ExtVector: 869 case Type::FunctionProto: 870 case Type::FunctionNoProto: 871 case Type::Enum: 872 case Type::Paren: 873 case Type::Elaborated: 874 case Type::Attributed: 875 case Type::Auto: 876 case Type::PackExpansion: 877 case Type::ObjCObject: 878 case Type::ObjCInterface: 879 case Type::ObjCObjectPointer: 880 case Type::Atomic: 881 llvm_unreachable("type is illegal as a nested name specifier"); 882 883 case Type::SubstTemplateTypeParmPack: 884 // FIXME: not clear how to mangle this! 885 // template <class T...> class A { 886 // template <class U...> void foo(decltype(T::foo(U())) x...); 887 // }; 888 Out << "_SUBSTPACK_"; 889 break; 890 891 // <unresolved-type> ::= <template-param> 892 // ::= <decltype> 893 // ::= <template-template-param> <template-args> 894 // (this last is not official yet) 895 case Type::TypeOfExpr: 896 case Type::TypeOf: 897 case Type::Decltype: 898 case Type::TemplateTypeParm: 899 case Type::UnaryTransform: 900 case Type::SubstTemplateTypeParm: 901 unresolvedType: 902 assert(!qualifier->getPrefix()); 903 904 // We only get here recursively if we're followed by identifiers. 905 if (recursive) Out << 'N'; 906 907 // This seems to do everything we want. It's not really 908 // sanctioned for a substituted template parameter, though. 909 mangleType(QualType(type, 0)); 910 911 // We never want to print 'E' directly after an unresolved-type, 912 // so we return directly. 913 return; 914 915 case Type::Typedef: 916 mangleSourceName(cast<TypedefType>(type)->getDecl()->getIdentifier()); 917 break; 918 919 case Type::UnresolvedUsing: 920 mangleSourceName(cast<UnresolvedUsingType>(type)->getDecl() 921 ->getIdentifier()); 922 break; 923 924 case Type::Record: 925 mangleSourceName(cast<RecordType>(type)->getDecl()->getIdentifier()); 926 break; 927 928 case Type::TemplateSpecialization: { 929 const TemplateSpecializationType *tst 930 = cast<TemplateSpecializationType>(type); 931 TemplateName name = tst->getTemplateName(); 932 switch (name.getKind()) { 933 case TemplateName::Template: 934 case TemplateName::QualifiedTemplate: { 935 TemplateDecl *temp = name.getAsTemplateDecl(); 936 937 // If the base is a template template parameter, this is an 938 // unresolved type. 939 assert(temp && "no template for template specialization type"); 940 if (isa<TemplateTemplateParmDecl>(temp)) goto unresolvedType; 941 942 mangleSourceName(temp->getIdentifier()); 943 break; 944 } 945 946 case TemplateName::OverloadedTemplate: 947 case TemplateName::DependentTemplate: 948 llvm_unreachable("invalid base for a template specialization type"); 949 950 case TemplateName::SubstTemplateTemplateParm: { 951 SubstTemplateTemplateParmStorage *subst 952 = name.getAsSubstTemplateTemplateParm(); 953 mangleExistingSubstitution(subst->getReplacement()); 954 break; 955 } 956 957 case TemplateName::SubstTemplateTemplateParmPack: { 958 // FIXME: not clear how to mangle this! 959 // template <template <class U> class T...> class A { 960 // template <class U...> void foo(decltype(T<U>::foo) x...); 961 // }; 962 Out << "_SUBSTPACK_"; 963 break; 964 } 965 } 966 967 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs()); 968 break; 969 } 970 971 case Type::InjectedClassName: 972 mangleSourceName(cast<InjectedClassNameType>(type)->getDecl() 973 ->getIdentifier()); 974 break; 975 976 case Type::DependentName: 977 mangleSourceName(cast<DependentNameType>(type)->getIdentifier()); 978 break; 979 980 case Type::DependentTemplateSpecialization: { 981 const DependentTemplateSpecializationType *tst 982 = cast<DependentTemplateSpecializationType>(type); 983 mangleSourceName(tst->getIdentifier()); 984 mangleTemplateArgs(tst->getArgs(), tst->getNumArgs()); 985 break; 986 } 987 } 988 break; 989 } 990 991 case NestedNameSpecifier::Identifier: 992 // Member expressions can have these without prefixes. 993 if (qualifier->getPrefix()) { 994 mangleUnresolvedPrefix(qualifier->getPrefix(), firstQualifierLookup, 995 /*recursive*/ true); 996 } else if (firstQualifierLookup) { 997 998 // Try to make a proper qualifier out of the lookup result, and 999 // then just recurse on that. 1000 NestedNameSpecifier *newQualifier; 1001 if (TypeDecl *typeDecl = dyn_cast<TypeDecl>(firstQualifierLookup)) { 1002 QualType type = getASTContext().getTypeDeclType(typeDecl); 1003 1004 // Pretend we had a different nested name specifier. 1005 newQualifier = NestedNameSpecifier::Create(getASTContext(), 1006 /*prefix*/ nullptr, 1007 /*template*/ false, 1008 type.getTypePtr()); 1009 } else if (NamespaceDecl *nspace = 1010 dyn_cast<NamespaceDecl>(firstQualifierLookup)) { 1011 newQualifier = NestedNameSpecifier::Create(getASTContext(), 1012 /*prefix*/ nullptr, 1013 nspace); 1014 } else if (NamespaceAliasDecl *alias = 1015 dyn_cast<NamespaceAliasDecl>(firstQualifierLookup)) { 1016 newQualifier = NestedNameSpecifier::Create(getASTContext(), 1017 /*prefix*/ nullptr, 1018 alias); 1019 } else { 1020 // No sensible mangling to do here. 1021 newQualifier = nullptr; 1022 } 1023 1024 if (newQualifier) 1025 return mangleUnresolvedPrefix(newQualifier, /*lookup*/ nullptr, 1026 recursive); 1027 1028 } else { 1029 Out << "sr"; 1030 } 1031 1032 mangleSourceName(qualifier->getAsIdentifier()); 1033 break; 1034 } 1035 1036 // If this was the innermost part of the NNS, and we fell out to 1037 // here, append an 'E'. 1038 if (!recursive) 1039 Out << 'E'; 1040 } 1041 1042 /// Mangle an unresolved-name, which is generally used for names which 1043 /// weren't resolved to specific entities. 1044 void CXXNameMangler::mangleUnresolvedName(NestedNameSpecifier *qualifier, 1045 NamedDecl *firstQualifierLookup, 1046 DeclarationName name, 1047 unsigned knownArity) { 1048 if (qualifier) mangleUnresolvedPrefix(qualifier, firstQualifierLookup); 1049 mangleUnqualifiedName(nullptr, name, knownArity); 1050 } 1051 1052 static const FieldDecl *FindFirstNamedDataMember(const RecordDecl *RD) { 1053 assert(RD->isAnonymousStructOrUnion() && 1054 "Expected anonymous struct or union!"); 1055 1056 for (const auto *I : RD->fields()) { 1057 if (I->getIdentifier()) 1058 return I; 1059 1060 if (const RecordType *RT = I->getType()->getAs<RecordType>()) 1061 if (const FieldDecl *NamedDataMember = 1062 FindFirstNamedDataMember(RT->getDecl())) 1063 return NamedDataMember; 1064 } 1065 1066 // We didn't find a named data member. 1067 return nullptr; 1068 } 1069 1070 void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND, 1071 DeclarationName Name, 1072 unsigned KnownArity) { 1073 // <unqualified-name> ::= <operator-name> 1074 // ::= <ctor-dtor-name> 1075 // ::= <source-name> 1076 switch (Name.getNameKind()) { 1077 case DeclarationName::Identifier: { 1078 if (const IdentifierInfo *II = Name.getAsIdentifierInfo()) { 1079 // We must avoid conflicts between internally- and externally- 1080 // linked variable and function declaration names in the same TU: 1081 // void test() { extern void foo(); } 1082 // static void foo(); 1083 // This naming convention is the same as that followed by GCC, 1084 // though it shouldn't actually matter. 1085 if (ND && ND->getFormalLinkage() == InternalLinkage && 1086 getEffectiveDeclContext(ND)->isFileContext()) 1087 Out << 'L'; 1088 1089 mangleSourceName(II); 1090 break; 1091 } 1092 1093 // Otherwise, an anonymous entity. We must have a declaration. 1094 assert(ND && "mangling empty name without declaration"); 1095 1096 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 1097 if (NS->isAnonymousNamespace()) { 1098 // This is how gcc mangles these names. 1099 Out << "12_GLOBAL__N_1"; 1100 break; 1101 } 1102 } 1103 1104 if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) { 1105 // We must have an anonymous union or struct declaration. 1106 const RecordDecl *RD = 1107 cast<RecordDecl>(VD->getType()->getAs<RecordType>()->getDecl()); 1108 1109 // Itanium C++ ABI 5.1.2: 1110 // 1111 // For the purposes of mangling, the name of an anonymous union is 1112 // considered to be the name of the first named data member found by a 1113 // pre-order, depth-first, declaration-order walk of the data members of 1114 // the anonymous union. If there is no such data member (i.e., if all of 1115 // the data members in the union are unnamed), then there is no way for 1116 // a program to refer to the anonymous union, and there is therefore no 1117 // need to mangle its name. 1118 const FieldDecl *FD = FindFirstNamedDataMember(RD); 1119 1120 // It's actually possible for various reasons for us to get here 1121 // with an empty anonymous struct / union. Fortunately, it 1122 // doesn't really matter what name we generate. 1123 if (!FD) break; 1124 assert(FD->getIdentifier() && "Data member name isn't an identifier!"); 1125 1126 mangleSourceName(FD->getIdentifier()); 1127 break; 1128 } 1129 1130 // Class extensions have no name as a category, and it's possible 1131 // for them to be the semantic parent of certain declarations 1132 // (primarily, tag decls defined within declarations). Such 1133 // declarations will always have internal linkage, so the name 1134 // doesn't really matter, but we shouldn't crash on them. For 1135 // safety, just handle all ObjC containers here. 1136 if (isa<ObjCContainerDecl>(ND)) 1137 break; 1138 1139 // We must have an anonymous struct. 1140 const TagDecl *TD = cast<TagDecl>(ND); 1141 if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) { 1142 assert(TD->getDeclContext() == D->getDeclContext() && 1143 "Typedef should not be in another decl context!"); 1144 assert(D->getDeclName().getAsIdentifierInfo() && 1145 "Typedef was not named!"); 1146 mangleSourceName(D->getDeclName().getAsIdentifierInfo()); 1147 break; 1148 } 1149 1150 // <unnamed-type-name> ::= <closure-type-name> 1151 // 1152 // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _ 1153 // <lambda-sig> ::= <parameter-type>+ # Parameter types or 'v' for 'void'. 1154 if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) { 1155 if (Record->isLambda() && Record->getLambdaManglingNumber()) { 1156 mangleLambda(Record); 1157 break; 1158 } 1159 } 1160 1161 if (TD->isExternallyVisible()) { 1162 unsigned UnnamedMangle = getASTContext().getManglingNumber(TD); 1163 Out << "Ut"; 1164 if (UnnamedMangle > 1) 1165 Out << llvm::utostr(UnnamedMangle - 2); 1166 Out << '_'; 1167 break; 1168 } 1169 1170 // Get a unique id for the anonymous struct. 1171 unsigned AnonStructId = Context.getAnonymousStructId(TD); 1172 1173 // Mangle it as a source name in the form 1174 // [n] $_<id> 1175 // where n is the length of the string. 1176 SmallString<8> Str; 1177 Str += "$_"; 1178 Str += llvm::utostr(AnonStructId); 1179 1180 Out << Str.size(); 1181 Out << Str.str(); 1182 break; 1183 } 1184 1185 case DeclarationName::ObjCZeroArgSelector: 1186 case DeclarationName::ObjCOneArgSelector: 1187 case DeclarationName::ObjCMultiArgSelector: 1188 llvm_unreachable("Can't mangle Objective-C selector names here!"); 1189 1190 case DeclarationName::CXXConstructorName: 1191 if (ND == Structor) 1192 // If the named decl is the C++ constructor we're mangling, use the type 1193 // we were given. 1194 mangleCXXCtorType(static_cast<CXXCtorType>(StructorType)); 1195 else 1196 // Otherwise, use the complete constructor name. This is relevant if a 1197 // class with a constructor is declared within a constructor. 1198 mangleCXXCtorType(Ctor_Complete); 1199 break; 1200 1201 case DeclarationName::CXXDestructorName: 1202 if (ND == Structor) 1203 // If the named decl is the C++ destructor we're mangling, use the type we 1204 // were given. 1205 mangleCXXDtorType(static_cast<CXXDtorType>(StructorType)); 1206 else 1207 // Otherwise, use the complete destructor name. This is relevant if a 1208 // class with a destructor is declared within a destructor. 1209 mangleCXXDtorType(Dtor_Complete); 1210 break; 1211 1212 case DeclarationName::CXXConversionFunctionName: 1213 // <operator-name> ::= cv <type> # (cast) 1214 Out << "cv"; 1215 mangleType(Name.getCXXNameType()); 1216 break; 1217 1218 case DeclarationName::CXXOperatorName: { 1219 unsigned Arity; 1220 if (ND) { 1221 Arity = cast<FunctionDecl>(ND)->getNumParams(); 1222 1223 // If we have a C++ member function, we need to include the 'this' pointer. 1224 // FIXME: This does not make sense for operators that are static, but their 1225 // names stay the same regardless of the arity (operator new for instance). 1226 if (isa<CXXMethodDecl>(ND)) 1227 Arity++; 1228 } else 1229 Arity = KnownArity; 1230 1231 mangleOperatorName(Name.getCXXOverloadedOperator(), Arity); 1232 break; 1233 } 1234 1235 case DeclarationName::CXXLiteralOperatorName: 1236 // FIXME: This mangling is not yet official. 1237 Out << "li"; 1238 mangleSourceName(Name.getCXXLiteralIdentifier()); 1239 break; 1240 1241 case DeclarationName::CXXUsingDirective: 1242 llvm_unreachable("Can't mangle a using directive name!"); 1243 } 1244 } 1245 1246 void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) { 1247 // <source-name> ::= <positive length number> <identifier> 1248 // <number> ::= [n] <non-negative decimal integer> 1249 // <identifier> ::= <unqualified source code identifier> 1250 Out << II->getLength() << II->getName(); 1251 } 1252 1253 void CXXNameMangler::mangleNestedName(const NamedDecl *ND, 1254 const DeclContext *DC, 1255 bool NoFunction) { 1256 // <nested-name> 1257 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E 1258 // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix> 1259 // <template-args> E 1260 1261 Out << 'N'; 1262 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) { 1263 Qualifiers MethodQuals = 1264 Qualifiers::fromCVRMask(Method->getTypeQualifiers()); 1265 // We do not consider restrict a distinguishing attribute for overloading 1266 // purposes so we must not mangle it. 1267 MethodQuals.removeRestrict(); 1268 mangleQualifiers(MethodQuals); 1269 mangleRefQualifier(Method->getRefQualifier()); 1270 } 1271 1272 // Check if we have a template. 1273 const TemplateArgumentList *TemplateArgs = nullptr; 1274 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { 1275 mangleTemplatePrefix(TD, NoFunction); 1276 mangleTemplateArgs(*TemplateArgs); 1277 } 1278 else { 1279 manglePrefix(DC, NoFunction); 1280 mangleUnqualifiedName(ND); 1281 } 1282 1283 Out << 'E'; 1284 } 1285 void CXXNameMangler::mangleNestedName(const TemplateDecl *TD, 1286 const TemplateArgument *TemplateArgs, 1287 unsigned NumTemplateArgs) { 1288 // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E 1289 1290 Out << 'N'; 1291 1292 mangleTemplatePrefix(TD); 1293 mangleTemplateArgs(TemplateArgs, NumTemplateArgs); 1294 1295 Out << 'E'; 1296 } 1297 1298 void CXXNameMangler::mangleLocalName(const Decl *D) { 1299 // <local-name> := Z <function encoding> E <entity name> [<discriminator>] 1300 // := Z <function encoding> E s [<discriminator>] 1301 // <local-name> := Z <function encoding> E d [ <parameter number> ] 1302 // _ <entity name> 1303 // <discriminator> := _ <non-negative number> 1304 assert(isa<NamedDecl>(D) || isa<BlockDecl>(D)); 1305 const RecordDecl *RD = GetLocalClassDecl(D); 1306 const DeclContext *DC = getEffectiveDeclContext(RD ? RD : D); 1307 1308 Out << 'Z'; 1309 1310 if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC)) 1311 mangleObjCMethodName(MD); 1312 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC)) 1313 mangleBlockForPrefix(BD); 1314 else 1315 mangleFunctionEncoding(cast<FunctionDecl>(DC)); 1316 1317 Out << 'E'; 1318 1319 if (RD) { 1320 // The parameter number is omitted for the last parameter, 0 for the 1321 // second-to-last parameter, 1 for the third-to-last parameter, etc. The 1322 // <entity name> will of course contain a <closure-type-name>: Its 1323 // numbering will be local to the particular argument in which it appears 1324 // -- other default arguments do not affect its encoding. 1325 const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD); 1326 if (CXXRD->isLambda()) { 1327 if (const ParmVarDecl *Parm 1328 = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) { 1329 if (const FunctionDecl *Func 1330 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) { 1331 Out << 'd'; 1332 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex(); 1333 if (Num > 1) 1334 mangleNumber(Num - 2); 1335 Out << '_'; 1336 } 1337 } 1338 } 1339 1340 // Mangle the name relative to the closest enclosing function. 1341 // equality ok because RD derived from ND above 1342 if (D == RD) { 1343 mangleUnqualifiedName(RD); 1344 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 1345 manglePrefix(getEffectiveDeclContext(BD), true /*NoFunction*/); 1346 mangleUnqualifiedBlock(BD); 1347 } else { 1348 const NamedDecl *ND = cast<NamedDecl>(D); 1349 mangleNestedName(ND, getEffectiveDeclContext(ND), true /*NoFunction*/); 1350 } 1351 } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) { 1352 // Mangle a block in a default parameter; see above explanation for 1353 // lambdas. 1354 if (const ParmVarDecl *Parm 1355 = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) { 1356 if (const FunctionDecl *Func 1357 = dyn_cast<FunctionDecl>(Parm->getDeclContext())) { 1358 Out << 'd'; 1359 unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex(); 1360 if (Num > 1) 1361 mangleNumber(Num - 2); 1362 Out << '_'; 1363 } 1364 } 1365 1366 mangleUnqualifiedBlock(BD); 1367 } else { 1368 mangleUnqualifiedName(cast<NamedDecl>(D)); 1369 } 1370 1371 if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) { 1372 unsigned disc; 1373 if (Context.getNextDiscriminator(ND, disc)) { 1374 if (disc < 10) 1375 Out << '_' << disc; 1376 else 1377 Out << "__" << disc << '_'; 1378 } 1379 } 1380 } 1381 1382 void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) { 1383 if (GetLocalClassDecl(Block)) { 1384 mangleLocalName(Block); 1385 return; 1386 } 1387 const DeclContext *DC = getEffectiveDeclContext(Block); 1388 if (isLocalContainerContext(DC)) { 1389 mangleLocalName(Block); 1390 return; 1391 } 1392 manglePrefix(getEffectiveDeclContext(Block)); 1393 mangleUnqualifiedBlock(Block); 1394 } 1395 1396 void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) { 1397 if (Decl *Context = Block->getBlockManglingContextDecl()) { 1398 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) && 1399 Context->getDeclContext()->isRecord()) { 1400 if (const IdentifierInfo *Name 1401 = cast<NamedDecl>(Context)->getIdentifier()) { 1402 mangleSourceName(Name); 1403 Out << 'M'; 1404 } 1405 } 1406 } 1407 1408 // If we have a block mangling number, use it. 1409 unsigned Number = Block->getBlockManglingNumber(); 1410 // Otherwise, just make up a number. It doesn't matter what it is because 1411 // the symbol in question isn't externally visible. 1412 if (!Number) 1413 Number = Context.getBlockId(Block, false); 1414 Out << "Ub"; 1415 if (Number > 0) 1416 Out << Number - 1; 1417 Out << '_'; 1418 } 1419 1420 void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) { 1421 // If the context of a closure type is an initializer for a class member 1422 // (static or nonstatic), it is encoded in a qualified name with a final 1423 // <prefix> of the form: 1424 // 1425 // <data-member-prefix> := <member source-name> M 1426 // 1427 // Technically, the data-member-prefix is part of the <prefix>. However, 1428 // since a closure type will always be mangled with a prefix, it's easier 1429 // to emit that last part of the prefix here. 1430 if (Decl *Context = Lambda->getLambdaContextDecl()) { 1431 if ((isa<VarDecl>(Context) || isa<FieldDecl>(Context)) && 1432 Context->getDeclContext()->isRecord()) { 1433 if (const IdentifierInfo *Name 1434 = cast<NamedDecl>(Context)->getIdentifier()) { 1435 mangleSourceName(Name); 1436 Out << 'M'; 1437 } 1438 } 1439 } 1440 1441 Out << "Ul"; 1442 const FunctionProtoType *Proto = Lambda->getLambdaTypeInfo()->getType()-> 1443 getAs<FunctionProtoType>(); 1444 mangleBareFunctionType(Proto, /*MangleReturnType=*/false); 1445 Out << "E"; 1446 1447 // The number is omitted for the first closure type with a given 1448 // <lambda-sig> in a given context; it is n-2 for the nth closure type 1449 // (in lexical order) with that same <lambda-sig> and context. 1450 // 1451 // The AST keeps track of the number for us. 1452 unsigned Number = Lambda->getLambdaManglingNumber(); 1453 assert(Number > 0 && "Lambda should be mangled as an unnamed class"); 1454 if (Number > 1) 1455 mangleNumber(Number - 2); 1456 Out << '_'; 1457 } 1458 1459 void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) { 1460 switch (qualifier->getKind()) { 1461 case NestedNameSpecifier::Global: 1462 // nothing 1463 return; 1464 1465 case NestedNameSpecifier::Namespace: 1466 mangleName(qualifier->getAsNamespace()); 1467 return; 1468 1469 case NestedNameSpecifier::NamespaceAlias: 1470 mangleName(qualifier->getAsNamespaceAlias()->getNamespace()); 1471 return; 1472 1473 case NestedNameSpecifier::TypeSpec: 1474 case NestedNameSpecifier::TypeSpecWithTemplate: 1475 manglePrefix(QualType(qualifier->getAsType(), 0)); 1476 return; 1477 1478 case NestedNameSpecifier::Identifier: 1479 // Member expressions can have these without prefixes, but that 1480 // should end up in mangleUnresolvedPrefix instead. 1481 assert(qualifier->getPrefix()); 1482 manglePrefix(qualifier->getPrefix()); 1483 1484 mangleSourceName(qualifier->getAsIdentifier()); 1485 return; 1486 } 1487 1488 llvm_unreachable("unexpected nested name specifier"); 1489 } 1490 1491 void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) { 1492 // <prefix> ::= <prefix> <unqualified-name> 1493 // ::= <template-prefix> <template-args> 1494 // ::= <template-param> 1495 // ::= # empty 1496 // ::= <substitution> 1497 1498 DC = IgnoreLinkageSpecDecls(DC); 1499 1500 if (DC->isTranslationUnit()) 1501 return; 1502 1503 if (NoFunction && isLocalContainerContext(DC)) 1504 return; 1505 1506 assert(!isLocalContainerContext(DC)); 1507 1508 const NamedDecl *ND = cast<NamedDecl>(DC); 1509 if (mangleSubstitution(ND)) 1510 return; 1511 1512 // Check if we have a template. 1513 const TemplateArgumentList *TemplateArgs = nullptr; 1514 if (const TemplateDecl *TD = isTemplate(ND, TemplateArgs)) { 1515 mangleTemplatePrefix(TD); 1516 mangleTemplateArgs(*TemplateArgs); 1517 } else { 1518 manglePrefix(getEffectiveDeclContext(ND), NoFunction); 1519 mangleUnqualifiedName(ND); 1520 } 1521 1522 addSubstitution(ND); 1523 } 1524 1525 void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) { 1526 // <template-prefix> ::= <prefix> <template unqualified-name> 1527 // ::= <template-param> 1528 // ::= <substitution> 1529 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 1530 return mangleTemplatePrefix(TD); 1531 1532 if (QualifiedTemplateName *Qualified = Template.getAsQualifiedTemplateName()) 1533 manglePrefix(Qualified->getQualifier()); 1534 1535 if (OverloadedTemplateStorage *Overloaded 1536 = Template.getAsOverloadedTemplate()) { 1537 mangleUnqualifiedName(nullptr, (*Overloaded->begin())->getDeclName(), 1538 UnknownArity); 1539 return; 1540 } 1541 1542 DependentTemplateName *Dependent = Template.getAsDependentTemplateName(); 1543 assert(Dependent && "Unknown template name kind?"); 1544 manglePrefix(Dependent->getQualifier()); 1545 mangleUnscopedTemplateName(Template); 1546 } 1547 1548 void CXXNameMangler::mangleTemplatePrefix(const TemplateDecl *ND, 1549 bool NoFunction) { 1550 // <template-prefix> ::= <prefix> <template unqualified-name> 1551 // ::= <template-param> 1552 // ::= <substitution> 1553 // <template-template-param> ::= <template-param> 1554 // <substitution> 1555 1556 if (mangleSubstitution(ND)) 1557 return; 1558 1559 // <template-template-param> ::= <template-param> 1560 if (const TemplateTemplateParmDecl *TTP 1561 = dyn_cast<TemplateTemplateParmDecl>(ND)) { 1562 mangleTemplateParameter(TTP->getIndex()); 1563 return; 1564 } 1565 1566 manglePrefix(getEffectiveDeclContext(ND), NoFunction); 1567 mangleUnqualifiedName(ND->getTemplatedDecl()); 1568 addSubstitution(ND); 1569 } 1570 1571 /// Mangles a template name under the production <type>. Required for 1572 /// template template arguments. 1573 /// <type> ::= <class-enum-type> 1574 /// ::= <template-param> 1575 /// ::= <substitution> 1576 void CXXNameMangler::mangleType(TemplateName TN) { 1577 if (mangleSubstitution(TN)) 1578 return; 1579 1580 TemplateDecl *TD = nullptr; 1581 1582 switch (TN.getKind()) { 1583 case TemplateName::QualifiedTemplate: 1584 TD = TN.getAsQualifiedTemplateName()->getTemplateDecl(); 1585 goto HaveDecl; 1586 1587 case TemplateName::Template: 1588 TD = TN.getAsTemplateDecl(); 1589 goto HaveDecl; 1590 1591 HaveDecl: 1592 if (isa<TemplateTemplateParmDecl>(TD)) 1593 mangleTemplateParameter(cast<TemplateTemplateParmDecl>(TD)->getIndex()); 1594 else 1595 mangleName(TD); 1596 break; 1597 1598 case TemplateName::OverloadedTemplate: 1599 llvm_unreachable("can't mangle an overloaded template name as a <type>"); 1600 1601 case TemplateName::DependentTemplate: { 1602 const DependentTemplateName *Dependent = TN.getAsDependentTemplateName(); 1603 assert(Dependent->isIdentifier()); 1604 1605 // <class-enum-type> ::= <name> 1606 // <name> ::= <nested-name> 1607 mangleUnresolvedPrefix(Dependent->getQualifier(), nullptr); 1608 mangleSourceName(Dependent->getIdentifier()); 1609 break; 1610 } 1611 1612 case TemplateName::SubstTemplateTemplateParm: { 1613 // Substituted template parameters are mangled as the substituted 1614 // template. This will check for the substitution twice, which is 1615 // fine, but we have to return early so that we don't try to *add* 1616 // the substitution twice. 1617 SubstTemplateTemplateParmStorage *subst 1618 = TN.getAsSubstTemplateTemplateParm(); 1619 mangleType(subst->getReplacement()); 1620 return; 1621 } 1622 1623 case TemplateName::SubstTemplateTemplateParmPack: { 1624 // FIXME: not clear how to mangle this! 1625 // template <template <class> class T...> class A { 1626 // template <template <class> class U...> void foo(B<T,U> x...); 1627 // }; 1628 Out << "_SUBSTPACK_"; 1629 break; 1630 } 1631 } 1632 1633 addSubstitution(TN); 1634 } 1635 1636 void 1637 CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) { 1638 switch (OO) { 1639 // <operator-name> ::= nw # new 1640 case OO_New: Out << "nw"; break; 1641 // ::= na # new[] 1642 case OO_Array_New: Out << "na"; break; 1643 // ::= dl # delete 1644 case OO_Delete: Out << "dl"; break; 1645 // ::= da # delete[] 1646 case OO_Array_Delete: Out << "da"; break; 1647 // ::= ps # + (unary) 1648 // ::= pl # + (binary or unknown) 1649 case OO_Plus: 1650 Out << (Arity == 1? "ps" : "pl"); break; 1651 // ::= ng # - (unary) 1652 // ::= mi # - (binary or unknown) 1653 case OO_Minus: 1654 Out << (Arity == 1? "ng" : "mi"); break; 1655 // ::= ad # & (unary) 1656 // ::= an # & (binary or unknown) 1657 case OO_Amp: 1658 Out << (Arity == 1? "ad" : "an"); break; 1659 // ::= de # * (unary) 1660 // ::= ml # * (binary or unknown) 1661 case OO_Star: 1662 // Use binary when unknown. 1663 Out << (Arity == 1? "de" : "ml"); break; 1664 // ::= co # ~ 1665 case OO_Tilde: Out << "co"; break; 1666 // ::= dv # / 1667 case OO_Slash: Out << "dv"; break; 1668 // ::= rm # % 1669 case OO_Percent: Out << "rm"; break; 1670 // ::= or # | 1671 case OO_Pipe: Out << "or"; break; 1672 // ::= eo # ^ 1673 case OO_Caret: Out << "eo"; break; 1674 // ::= aS # = 1675 case OO_Equal: Out << "aS"; break; 1676 // ::= pL # += 1677 case OO_PlusEqual: Out << "pL"; break; 1678 // ::= mI # -= 1679 case OO_MinusEqual: Out << "mI"; break; 1680 // ::= mL # *= 1681 case OO_StarEqual: Out << "mL"; break; 1682 // ::= dV # /= 1683 case OO_SlashEqual: Out << "dV"; break; 1684 // ::= rM # %= 1685 case OO_PercentEqual: Out << "rM"; break; 1686 // ::= aN # &= 1687 case OO_AmpEqual: Out << "aN"; break; 1688 // ::= oR # |= 1689 case OO_PipeEqual: Out << "oR"; break; 1690 // ::= eO # ^= 1691 case OO_CaretEqual: Out << "eO"; break; 1692 // ::= ls # << 1693 case OO_LessLess: Out << "ls"; break; 1694 // ::= rs # >> 1695 case OO_GreaterGreater: Out << "rs"; break; 1696 // ::= lS # <<= 1697 case OO_LessLessEqual: Out << "lS"; break; 1698 // ::= rS # >>= 1699 case OO_GreaterGreaterEqual: Out << "rS"; break; 1700 // ::= eq # == 1701 case OO_EqualEqual: Out << "eq"; break; 1702 // ::= ne # != 1703 case OO_ExclaimEqual: Out << "ne"; break; 1704 // ::= lt # < 1705 case OO_Less: Out << "lt"; break; 1706 // ::= gt # > 1707 case OO_Greater: Out << "gt"; break; 1708 // ::= le # <= 1709 case OO_LessEqual: Out << "le"; break; 1710 // ::= ge # >= 1711 case OO_GreaterEqual: Out << "ge"; break; 1712 // ::= nt # ! 1713 case OO_Exclaim: Out << "nt"; break; 1714 // ::= aa # && 1715 case OO_AmpAmp: Out << "aa"; break; 1716 // ::= oo # || 1717 case OO_PipePipe: Out << "oo"; break; 1718 // ::= pp # ++ 1719 case OO_PlusPlus: Out << "pp"; break; 1720 // ::= mm # -- 1721 case OO_MinusMinus: Out << "mm"; break; 1722 // ::= cm # , 1723 case OO_Comma: Out << "cm"; break; 1724 // ::= pm # ->* 1725 case OO_ArrowStar: Out << "pm"; break; 1726 // ::= pt # -> 1727 case OO_Arrow: Out << "pt"; break; 1728 // ::= cl # () 1729 case OO_Call: Out << "cl"; break; 1730 // ::= ix # [] 1731 case OO_Subscript: Out << "ix"; break; 1732 1733 // ::= qu # ? 1734 // The conditional operator can't be overloaded, but we still handle it when 1735 // mangling expressions. 1736 case OO_Conditional: Out << "qu"; break; 1737 1738 case OO_None: 1739 case NUM_OVERLOADED_OPERATORS: 1740 llvm_unreachable("Not an overloaded operator"); 1741 } 1742 } 1743 1744 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) { 1745 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const 1746 if (Quals.hasRestrict()) 1747 Out << 'r'; 1748 if (Quals.hasVolatile()) 1749 Out << 'V'; 1750 if (Quals.hasConst()) 1751 Out << 'K'; 1752 1753 if (Quals.hasAddressSpace()) { 1754 // Address space extension: 1755 // 1756 // <type> ::= U <target-addrspace> 1757 // <type> ::= U <OpenCL-addrspace> 1758 // <type> ::= U <CUDA-addrspace> 1759 1760 SmallString<64> ASString; 1761 unsigned AS = Quals.getAddressSpace(); 1762 1763 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) { 1764 // <target-addrspace> ::= "AS" <address-space-number> 1765 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS); 1766 ASString = "AS" + llvm::utostr_32(TargetAS); 1767 } else { 1768 switch (AS) { 1769 default: llvm_unreachable("Not a language specific address space"); 1770 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ] 1771 case LangAS::opencl_global: ASString = "CLglobal"; break; 1772 case LangAS::opencl_local: ASString = "CLlocal"; break; 1773 case LangAS::opencl_constant: ASString = "CLconstant"; break; 1774 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ] 1775 case LangAS::cuda_device: ASString = "CUdevice"; break; 1776 case LangAS::cuda_constant: ASString = "CUconstant"; break; 1777 case LangAS::cuda_shared: ASString = "CUshared"; break; 1778 } 1779 } 1780 Out << 'U' << ASString.size() << ASString; 1781 } 1782 1783 StringRef LifetimeName; 1784 switch (Quals.getObjCLifetime()) { 1785 // Objective-C ARC Extension: 1786 // 1787 // <type> ::= U "__strong" 1788 // <type> ::= U "__weak" 1789 // <type> ::= U "__autoreleasing" 1790 case Qualifiers::OCL_None: 1791 break; 1792 1793 case Qualifiers::OCL_Weak: 1794 LifetimeName = "__weak"; 1795 break; 1796 1797 case Qualifiers::OCL_Strong: 1798 LifetimeName = "__strong"; 1799 break; 1800 1801 case Qualifiers::OCL_Autoreleasing: 1802 LifetimeName = "__autoreleasing"; 1803 break; 1804 1805 case Qualifiers::OCL_ExplicitNone: 1806 // The __unsafe_unretained qualifier is *not* mangled, so that 1807 // __unsafe_unretained types in ARC produce the same manglings as the 1808 // equivalent (but, naturally, unqualified) types in non-ARC, providing 1809 // better ABI compatibility. 1810 // 1811 // It's safe to do this because unqualified 'id' won't show up 1812 // in any type signatures that need to be mangled. 1813 break; 1814 } 1815 if (!LifetimeName.empty()) 1816 Out << 'U' << LifetimeName.size() << LifetimeName; 1817 } 1818 1819 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) { 1820 // <ref-qualifier> ::= R # lvalue reference 1821 // ::= O # rvalue-reference 1822 switch (RefQualifier) { 1823 case RQ_None: 1824 break; 1825 1826 case RQ_LValue: 1827 Out << 'R'; 1828 break; 1829 1830 case RQ_RValue: 1831 Out << 'O'; 1832 break; 1833 } 1834 } 1835 1836 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) { 1837 Context.mangleObjCMethodName(MD, Out); 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 = quals || !isa<BuiltinType>(T); 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 if (base->isImplicitCXXThis()) { 2533 // Note: GCC mangles member expressions to the implicit 'this' as 2534 // *this., whereas we represent them as this->. The Itanium C++ ABI 2535 // does not specify anything here, so we follow GCC. 2536 Out << "dtdefpT"; 2537 } else { 2538 Out << (isArrow ? "pt" : "dt"); 2539 mangleExpression(base); 2540 } 2541 } 2542 mangleUnresolvedName(qualifier, firstQualifierLookup, member, arity); 2543 } 2544 2545 /// Look at the callee of the given call expression and determine if 2546 /// it's a parenthesized id-expression which would have triggered ADL 2547 /// otherwise. 2548 static bool isParenthesizedADLCallee(const CallExpr *call) { 2549 const Expr *callee = call->getCallee(); 2550 const Expr *fn = callee->IgnoreParens(); 2551 2552 // Must be parenthesized. IgnoreParens() skips __extension__ nodes, 2553 // too, but for those to appear in the callee, it would have to be 2554 // parenthesized. 2555 if (callee == fn) return false; 2556 2557 // Must be an unresolved lookup. 2558 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn); 2559 if (!lookup) return false; 2560 2561 assert(!lookup->requiresADL()); 2562 2563 // Must be an unqualified lookup. 2564 if (lookup->getQualifier()) return false; 2565 2566 // Must not have found a class member. Note that if one is a class 2567 // member, they're all class members. 2568 if (lookup->getNumDecls() > 0 && 2569 (*lookup->decls_begin())->isCXXClassMember()) 2570 return false; 2571 2572 // Otherwise, ADL would have been triggered. 2573 return true; 2574 } 2575 2576 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) { 2577 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E); 2578 Out << CastEncoding; 2579 mangleType(ECE->getType()); 2580 mangleExpression(ECE->getSubExpr()); 2581 } 2582 2583 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) { 2584 // <expression> ::= <unary operator-name> <expression> 2585 // ::= <binary operator-name> <expression> <expression> 2586 // ::= <trinary operator-name> <expression> <expression> <expression> 2587 // ::= cv <type> expression # conversion with one argument 2588 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments 2589 // ::= dc <type> <expression> # dynamic_cast<type> (expression) 2590 // ::= sc <type> <expression> # static_cast<type> (expression) 2591 // ::= cc <type> <expression> # const_cast<type> (expression) 2592 // ::= rc <type> <expression> # reinterpret_cast<type> (expression) 2593 // ::= st <type> # sizeof (a type) 2594 // ::= at <type> # alignof (a type) 2595 // ::= <template-param> 2596 // ::= <function-param> 2597 // ::= sr <type> <unqualified-name> # dependent name 2598 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id 2599 // ::= ds <expression> <expression> # expr.*expr 2600 // ::= sZ <template-param> # size of a parameter pack 2601 // ::= sZ <function-param> # size of a function parameter pack 2602 // ::= <expr-primary> 2603 // <expr-primary> ::= L <type> <value number> E # integer literal 2604 // ::= L <type <value float> E # floating literal 2605 // ::= L <mangled-name> E # external name 2606 // ::= fpT # 'this' expression 2607 QualType ImplicitlyConvertedToType; 2608 2609 recurse: 2610 switch (E->getStmtClass()) { 2611 case Expr::NoStmtClass: 2612 #define ABSTRACT_STMT(Type) 2613 #define EXPR(Type, Base) 2614 #define STMT(Type, Base) \ 2615 case Expr::Type##Class: 2616 #include "clang/AST/StmtNodes.inc" 2617 // fallthrough 2618 2619 // These all can only appear in local or variable-initialization 2620 // contexts and so should never appear in a mangling. 2621 case Expr::AddrLabelExprClass: 2622 case Expr::DesignatedInitExprClass: 2623 case Expr::ImplicitValueInitExprClass: 2624 case Expr::ParenListExprClass: 2625 case Expr::LambdaExprClass: 2626 case Expr::MSPropertyRefExprClass: 2627 llvm_unreachable("unexpected statement kind"); 2628 2629 // FIXME: invent manglings for all these. 2630 case Expr::BlockExprClass: 2631 case Expr::CXXPseudoDestructorExprClass: 2632 case Expr::ChooseExprClass: 2633 case Expr::CompoundLiteralExprClass: 2634 case Expr::ExtVectorElementExprClass: 2635 case Expr::GenericSelectionExprClass: 2636 case Expr::ObjCEncodeExprClass: 2637 case Expr::ObjCIsaExprClass: 2638 case Expr::ObjCIvarRefExprClass: 2639 case Expr::ObjCMessageExprClass: 2640 case Expr::ObjCPropertyRefExprClass: 2641 case Expr::ObjCProtocolExprClass: 2642 case Expr::ObjCSelectorExprClass: 2643 case Expr::ObjCStringLiteralClass: 2644 case Expr::ObjCBoxedExprClass: 2645 case Expr::ObjCArrayLiteralClass: 2646 case Expr::ObjCDictionaryLiteralClass: 2647 case Expr::ObjCSubscriptRefExprClass: 2648 case Expr::ObjCIndirectCopyRestoreExprClass: 2649 case Expr::OffsetOfExprClass: 2650 case Expr::PredefinedExprClass: 2651 case Expr::ShuffleVectorExprClass: 2652 case Expr::ConvertVectorExprClass: 2653 case Expr::StmtExprClass: 2654 case Expr::TypeTraitExprClass: 2655 case Expr::ArrayTypeTraitExprClass: 2656 case Expr::ExpressionTraitExprClass: 2657 case Expr::VAArgExprClass: 2658 case Expr::CXXUuidofExprClass: 2659 case Expr::CUDAKernelCallExprClass: 2660 case Expr::AsTypeExprClass: 2661 case Expr::PseudoObjectExprClass: 2662 case Expr::AtomicExprClass: 2663 { 2664 // As bad as this diagnostic is, it's better than crashing. 2665 DiagnosticsEngine &Diags = Context.getDiags(); 2666 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2667 "cannot yet mangle expression type %0"); 2668 Diags.Report(E->getExprLoc(), DiagID) 2669 << E->getStmtClassName() << E->getSourceRange(); 2670 break; 2671 } 2672 2673 // Even gcc-4.5 doesn't mangle this. 2674 case Expr::BinaryConditionalOperatorClass: { 2675 DiagnosticsEngine &Diags = Context.getDiags(); 2676 unsigned DiagID = 2677 Diags.getCustomDiagID(DiagnosticsEngine::Error, 2678 "?: operator with omitted middle operand cannot be mangled"); 2679 Diags.Report(E->getExprLoc(), DiagID) 2680 << E->getStmtClassName() << E->getSourceRange(); 2681 break; 2682 } 2683 2684 // These are used for internal purposes and cannot be meaningfully mangled. 2685 case Expr::OpaqueValueExprClass: 2686 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?"); 2687 2688 case Expr::InitListExprClass: { 2689 Out << "il"; 2690 const InitListExpr *InitList = cast<InitListExpr>(E); 2691 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 2692 mangleExpression(InitList->getInit(i)); 2693 Out << "E"; 2694 break; 2695 } 2696 2697 case Expr::CXXDefaultArgExprClass: 2698 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity); 2699 break; 2700 2701 case Expr::CXXDefaultInitExprClass: 2702 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity); 2703 break; 2704 2705 case Expr::CXXStdInitializerListExprClass: 2706 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity); 2707 break; 2708 2709 case Expr::SubstNonTypeTemplateParmExprClass: 2710 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), 2711 Arity); 2712 break; 2713 2714 case Expr::UserDefinedLiteralClass: 2715 // We follow g++'s approach of mangling a UDL as a call to the literal 2716 // operator. 2717 case Expr::CXXMemberCallExprClass: // fallthrough 2718 case Expr::CallExprClass: { 2719 const CallExpr *CE = cast<CallExpr>(E); 2720 2721 // <expression> ::= cp <simple-id> <expression>* E 2722 // We use this mangling only when the call would use ADL except 2723 // for being parenthesized. Per discussion with David 2724 // Vandervoorde, 2011.04.25. 2725 if (isParenthesizedADLCallee(CE)) { 2726 Out << "cp"; 2727 // The callee here is a parenthesized UnresolvedLookupExpr with 2728 // no qualifier and should always get mangled as a <simple-id> 2729 // anyway. 2730 2731 // <expression> ::= cl <expression>* E 2732 } else { 2733 Out << "cl"; 2734 } 2735 2736 mangleExpression(CE->getCallee(), CE->getNumArgs()); 2737 for (unsigned I = 0, N = CE->getNumArgs(); I != N; ++I) 2738 mangleExpression(CE->getArg(I)); 2739 Out << 'E'; 2740 break; 2741 } 2742 2743 case Expr::CXXNewExprClass: { 2744 const CXXNewExpr *New = cast<CXXNewExpr>(E); 2745 if (New->isGlobalNew()) Out << "gs"; 2746 Out << (New->isArray() ? "na" : "nw"); 2747 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(), 2748 E = New->placement_arg_end(); I != E; ++I) 2749 mangleExpression(*I); 2750 Out << '_'; 2751 mangleType(New->getAllocatedType()); 2752 if (New->hasInitializer()) { 2753 if (New->getInitializationStyle() == CXXNewExpr::ListInit) 2754 Out << "il"; 2755 else 2756 Out << "pi"; 2757 const Expr *Init = New->getInitializer(); 2758 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 2759 // Directly inline the initializers. 2760 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 2761 E = CCE->arg_end(); 2762 I != E; ++I) 2763 mangleExpression(*I); 2764 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) { 2765 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i) 2766 mangleExpression(PLE->getExpr(i)); 2767 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit && 2768 isa<InitListExpr>(Init)) { 2769 // Only take InitListExprs apart for list-initialization. 2770 const InitListExpr *InitList = cast<InitListExpr>(Init); 2771 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 2772 mangleExpression(InitList->getInit(i)); 2773 } else 2774 mangleExpression(Init); 2775 } 2776 Out << 'E'; 2777 break; 2778 } 2779 2780 case Expr::MemberExprClass: { 2781 const MemberExpr *ME = cast<MemberExpr>(E); 2782 mangleMemberExpr(ME->getBase(), ME->isArrow(), 2783 ME->getQualifier(), nullptr, 2784 ME->getMemberDecl()->getDeclName(), Arity); 2785 break; 2786 } 2787 2788 case Expr::UnresolvedMemberExprClass: { 2789 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E); 2790 mangleMemberExpr(ME->getBase(), ME->isArrow(), 2791 ME->getQualifier(), nullptr, ME->getMemberName(), 2792 Arity); 2793 if (ME->hasExplicitTemplateArgs()) 2794 mangleTemplateArgs(ME->getExplicitTemplateArgs()); 2795 break; 2796 } 2797 2798 case Expr::CXXDependentScopeMemberExprClass: { 2799 const CXXDependentScopeMemberExpr *ME 2800 = cast<CXXDependentScopeMemberExpr>(E); 2801 mangleMemberExpr(ME->getBase(), ME->isArrow(), 2802 ME->getQualifier(), ME->getFirstQualifierFoundInScope(), 2803 ME->getMember(), Arity); 2804 if (ME->hasExplicitTemplateArgs()) 2805 mangleTemplateArgs(ME->getExplicitTemplateArgs()); 2806 break; 2807 } 2808 2809 case Expr::UnresolvedLookupExprClass: { 2810 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E); 2811 mangleUnresolvedName(ULE->getQualifier(), nullptr, ULE->getName(), Arity); 2812 2813 // All the <unresolved-name> productions end in a 2814 // base-unresolved-name, where <template-args> are just tacked 2815 // onto the end. 2816 if (ULE->hasExplicitTemplateArgs()) 2817 mangleTemplateArgs(ULE->getExplicitTemplateArgs()); 2818 break; 2819 } 2820 2821 case Expr::CXXUnresolvedConstructExprClass: { 2822 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E); 2823 unsigned N = CE->arg_size(); 2824 2825 Out << "cv"; 2826 mangleType(CE->getType()); 2827 if (N != 1) Out << '_'; 2828 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 2829 if (N != 1) Out << 'E'; 2830 break; 2831 } 2832 2833 case Expr::CXXTemporaryObjectExprClass: 2834 case Expr::CXXConstructExprClass: { 2835 const CXXConstructExpr *CE = cast<CXXConstructExpr>(E); 2836 unsigned N = CE->getNumArgs(); 2837 2838 if (CE->isListInitialization()) 2839 Out << "tl"; 2840 else 2841 Out << "cv"; 2842 mangleType(CE->getType()); 2843 if (N != 1) Out << '_'; 2844 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 2845 if (N != 1) Out << 'E'; 2846 break; 2847 } 2848 2849 case Expr::CXXScalarValueInitExprClass: 2850 Out <<"cv"; 2851 mangleType(E->getType()); 2852 Out <<"_E"; 2853 break; 2854 2855 case Expr::CXXNoexceptExprClass: 2856 Out << "nx"; 2857 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand()); 2858 break; 2859 2860 case Expr::UnaryExprOrTypeTraitExprClass: { 2861 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); 2862 2863 if (!SAE->isInstantiationDependent()) { 2864 // Itanium C++ ABI: 2865 // If the operand of a sizeof or alignof operator is not 2866 // instantiation-dependent it is encoded as an integer literal 2867 // reflecting the result of the operator. 2868 // 2869 // If the result of the operator is implicitly converted to a known 2870 // integer type, that type is used for the literal; otherwise, the type 2871 // of std::size_t or std::ptrdiff_t is used. 2872 QualType T = (ImplicitlyConvertedToType.isNull() || 2873 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() 2874 : ImplicitlyConvertedToType; 2875 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); 2876 mangleIntegerLiteral(T, V); 2877 break; 2878 } 2879 2880 switch(SAE->getKind()) { 2881 case UETT_SizeOf: 2882 Out << 's'; 2883 break; 2884 case UETT_AlignOf: 2885 Out << 'a'; 2886 break; 2887 case UETT_VecStep: 2888 DiagnosticsEngine &Diags = Context.getDiags(); 2889 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2890 "cannot yet mangle vec_step expression"); 2891 Diags.Report(DiagID); 2892 return; 2893 } 2894 if (SAE->isArgumentType()) { 2895 Out << 't'; 2896 mangleType(SAE->getArgumentType()); 2897 } else { 2898 Out << 'z'; 2899 mangleExpression(SAE->getArgumentExpr()); 2900 } 2901 break; 2902 } 2903 2904 case Expr::CXXThrowExprClass: { 2905 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E); 2906 // <expression> ::= tw <expression> # throw expression 2907 // ::= tr # rethrow 2908 if (TE->getSubExpr()) { 2909 Out << "tw"; 2910 mangleExpression(TE->getSubExpr()); 2911 } else { 2912 Out << "tr"; 2913 } 2914 break; 2915 } 2916 2917 case Expr::CXXTypeidExprClass: { 2918 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E); 2919 // <expression> ::= ti <type> # typeid (type) 2920 // ::= te <expression> # typeid (expression) 2921 if (TIE->isTypeOperand()) { 2922 Out << "ti"; 2923 mangleType(TIE->getTypeOperand(Context.getASTContext())); 2924 } else { 2925 Out << "te"; 2926 mangleExpression(TIE->getExprOperand()); 2927 } 2928 break; 2929 } 2930 2931 case Expr::CXXDeleteExprClass: { 2932 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E); 2933 // <expression> ::= [gs] dl <expression> # [::] delete expr 2934 // ::= [gs] da <expression> # [::] delete [] expr 2935 if (DE->isGlobalDelete()) Out << "gs"; 2936 Out << (DE->isArrayForm() ? "da" : "dl"); 2937 mangleExpression(DE->getArgument()); 2938 break; 2939 } 2940 2941 case Expr::UnaryOperatorClass: { 2942 const UnaryOperator *UO = cast<UnaryOperator>(E); 2943 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()), 2944 /*Arity=*/1); 2945 mangleExpression(UO->getSubExpr()); 2946 break; 2947 } 2948 2949 case Expr::ArraySubscriptExprClass: { 2950 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E); 2951 2952 // Array subscript is treated as a syntactically weird form of 2953 // binary operator. 2954 Out << "ix"; 2955 mangleExpression(AE->getLHS()); 2956 mangleExpression(AE->getRHS()); 2957 break; 2958 } 2959 2960 case Expr::CompoundAssignOperatorClass: // fallthrough 2961 case Expr::BinaryOperatorClass: { 2962 const BinaryOperator *BO = cast<BinaryOperator>(E); 2963 if (BO->getOpcode() == BO_PtrMemD) 2964 Out << "ds"; 2965 else 2966 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()), 2967 /*Arity=*/2); 2968 mangleExpression(BO->getLHS()); 2969 mangleExpression(BO->getRHS()); 2970 break; 2971 } 2972 2973 case Expr::ConditionalOperatorClass: { 2974 const ConditionalOperator *CO = cast<ConditionalOperator>(E); 2975 mangleOperatorName(OO_Conditional, /*Arity=*/3); 2976 mangleExpression(CO->getCond()); 2977 mangleExpression(CO->getLHS(), Arity); 2978 mangleExpression(CO->getRHS(), Arity); 2979 break; 2980 } 2981 2982 case Expr::ImplicitCastExprClass: { 2983 ImplicitlyConvertedToType = E->getType(); 2984 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 2985 goto recurse; 2986 } 2987 2988 case Expr::ObjCBridgedCastExprClass: { 2989 // Mangle ownership casts as a vendor extended operator __bridge, 2990 // __bridge_transfer, or __bridge_retain. 2991 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); 2992 Out << "v1U" << Kind.size() << Kind; 2993 } 2994 // Fall through to mangle the cast itself. 2995 2996 case Expr::CStyleCastExprClass: 2997 case Expr::CXXFunctionalCastExprClass: 2998 mangleCastExpression(E, "cv"); 2999 break; 3000 3001 case Expr::CXXStaticCastExprClass: 3002 mangleCastExpression(E, "sc"); 3003 break; 3004 case Expr::CXXDynamicCastExprClass: 3005 mangleCastExpression(E, "dc"); 3006 break; 3007 case Expr::CXXReinterpretCastExprClass: 3008 mangleCastExpression(E, "rc"); 3009 break; 3010 case Expr::CXXConstCastExprClass: 3011 mangleCastExpression(E, "cc"); 3012 break; 3013 3014 case Expr::CXXOperatorCallExprClass: { 3015 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E); 3016 unsigned NumArgs = CE->getNumArgs(); 3017 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs); 3018 // Mangle the arguments. 3019 for (unsigned i = 0; i != NumArgs; ++i) 3020 mangleExpression(CE->getArg(i)); 3021 break; 3022 } 3023 3024 case Expr::ParenExprClass: 3025 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity); 3026 break; 3027 3028 case Expr::DeclRefExprClass: { 3029 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 3030 3031 switch (D->getKind()) { 3032 default: 3033 // <expr-primary> ::= L <mangled-name> E # external name 3034 Out << 'L'; 3035 mangle(D, "_Z"); 3036 Out << 'E'; 3037 break; 3038 3039 case Decl::ParmVar: 3040 mangleFunctionParam(cast<ParmVarDecl>(D)); 3041 break; 3042 3043 case Decl::EnumConstant: { 3044 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D); 3045 mangleIntegerLiteral(ED->getType(), ED->getInitVal()); 3046 break; 3047 } 3048 3049 case Decl::NonTypeTemplateParm: { 3050 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D); 3051 mangleTemplateParameter(PD->getIndex()); 3052 break; 3053 } 3054 3055 } 3056 3057 break; 3058 } 3059 3060 case Expr::SubstNonTypeTemplateParmPackExprClass: 3061 // FIXME: not clear how to mangle this! 3062 // template <unsigned N...> class A { 3063 // template <class U...> void foo(U (&x)[N]...); 3064 // }; 3065 Out << "_SUBSTPACK_"; 3066 break; 3067 3068 case Expr::FunctionParmPackExprClass: { 3069 // FIXME: not clear how to mangle this! 3070 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E); 3071 Out << "v110_SUBSTPACK"; 3072 mangleFunctionParam(FPPE->getParameterPack()); 3073 break; 3074 } 3075 3076 case Expr::DependentScopeDeclRefExprClass: { 3077 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E); 3078 mangleUnresolvedName(DRE->getQualifier(), nullptr, DRE->getDeclName(), 3079 Arity); 3080 3081 // All the <unresolved-name> productions end in a 3082 // base-unresolved-name, where <template-args> are just tacked 3083 // onto the end. 3084 if (DRE->hasExplicitTemplateArgs()) 3085 mangleTemplateArgs(DRE->getExplicitTemplateArgs()); 3086 break; 3087 } 3088 3089 case Expr::CXXBindTemporaryExprClass: 3090 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr()); 3091 break; 3092 3093 case Expr::ExprWithCleanupsClass: 3094 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity); 3095 break; 3096 3097 case Expr::FloatingLiteralClass: { 3098 const FloatingLiteral *FL = cast<FloatingLiteral>(E); 3099 Out << 'L'; 3100 mangleType(FL->getType()); 3101 mangleFloat(FL->getValue()); 3102 Out << 'E'; 3103 break; 3104 } 3105 3106 case Expr::CharacterLiteralClass: 3107 Out << 'L'; 3108 mangleType(E->getType()); 3109 Out << cast<CharacterLiteral>(E)->getValue(); 3110 Out << 'E'; 3111 break; 3112 3113 // FIXME. __objc_yes/__objc_no are mangled same as true/false 3114 case Expr::ObjCBoolLiteralExprClass: 3115 Out << "Lb"; 3116 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 3117 Out << 'E'; 3118 break; 3119 3120 case Expr::CXXBoolLiteralExprClass: 3121 Out << "Lb"; 3122 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 3123 Out << 'E'; 3124 break; 3125 3126 case Expr::IntegerLiteralClass: { 3127 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue()); 3128 if (E->getType()->isSignedIntegerType()) 3129 Value.setIsSigned(true); 3130 mangleIntegerLiteral(E->getType(), Value); 3131 break; 3132 } 3133 3134 case Expr::ImaginaryLiteralClass: { 3135 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E); 3136 // Mangle as if a complex literal. 3137 // Proposal from David Vandevoorde, 2010.06.30. 3138 Out << 'L'; 3139 mangleType(E->getType()); 3140 if (const FloatingLiteral *Imag = 3141 dyn_cast<FloatingLiteral>(IE->getSubExpr())) { 3142 // Mangle a floating-point zero of the appropriate type. 3143 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics())); 3144 Out << '_'; 3145 mangleFloat(Imag->getValue()); 3146 } else { 3147 Out << "0_"; 3148 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue()); 3149 if (IE->getSubExpr()->getType()->isSignedIntegerType()) 3150 Value.setIsSigned(true); 3151 mangleNumber(Value); 3152 } 3153 Out << 'E'; 3154 break; 3155 } 3156 3157 case Expr::StringLiteralClass: { 3158 // Revised proposal from David Vandervoorde, 2010.07.15. 3159 Out << 'L'; 3160 assert(isa<ConstantArrayType>(E->getType())); 3161 mangleType(E->getType()); 3162 Out << 'E'; 3163 break; 3164 } 3165 3166 case Expr::GNUNullExprClass: 3167 // FIXME: should this really be mangled the same as nullptr? 3168 // fallthrough 3169 3170 case Expr::CXXNullPtrLiteralExprClass: { 3171 Out << "LDnE"; 3172 break; 3173 } 3174 3175 case Expr::PackExpansionExprClass: 3176 Out << "sp"; 3177 mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); 3178 break; 3179 3180 case Expr::SizeOfPackExprClass: { 3181 Out << "sZ"; 3182 const NamedDecl *Pack = cast<SizeOfPackExpr>(E)->getPack(); 3183 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack)) 3184 mangleTemplateParameter(TTP->getIndex()); 3185 else if (const NonTypeTemplateParmDecl *NTTP 3186 = dyn_cast<NonTypeTemplateParmDecl>(Pack)) 3187 mangleTemplateParameter(NTTP->getIndex()); 3188 else if (const TemplateTemplateParmDecl *TempTP 3189 = dyn_cast<TemplateTemplateParmDecl>(Pack)) 3190 mangleTemplateParameter(TempTP->getIndex()); 3191 else 3192 mangleFunctionParam(cast<ParmVarDecl>(Pack)); 3193 break; 3194 } 3195 3196 case Expr::MaterializeTemporaryExprClass: { 3197 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()); 3198 break; 3199 } 3200 3201 case Expr::CXXThisExprClass: 3202 Out << "fpT"; 3203 break; 3204 } 3205 } 3206 3207 /// Mangle an expression which refers to a parameter variable. 3208 /// 3209 /// <expression> ::= <function-param> 3210 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0 3211 /// <function-param> ::= fp <top-level CV-qualifiers> 3212 /// <parameter-2 non-negative number> _ # L == 0, I > 0 3213 /// <function-param> ::= fL <L-1 non-negative number> 3214 /// p <top-level CV-qualifiers> _ # L > 0, I == 0 3215 /// <function-param> ::= fL <L-1 non-negative number> 3216 /// p <top-level CV-qualifiers> 3217 /// <I-1 non-negative number> _ # L > 0, I > 0 3218 /// 3219 /// L is the nesting depth of the parameter, defined as 1 if the 3220 /// parameter comes from the innermost function prototype scope 3221 /// enclosing the current context, 2 if from the next enclosing 3222 /// function prototype scope, and so on, with one special case: if 3223 /// we've processed the full parameter clause for the innermost 3224 /// function type, then L is one less. This definition conveniently 3225 /// makes it irrelevant whether a function's result type was written 3226 /// trailing or leading, but is otherwise overly complicated; the 3227 /// numbering was first designed without considering references to 3228 /// parameter in locations other than return types, and then the 3229 /// mangling had to be generalized without changing the existing 3230 /// manglings. 3231 /// 3232 /// I is the zero-based index of the parameter within its parameter 3233 /// declaration clause. Note that the original ABI document describes 3234 /// this using 1-based ordinals. 3235 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) { 3236 unsigned parmDepth = parm->getFunctionScopeDepth(); 3237 unsigned parmIndex = parm->getFunctionScopeIndex(); 3238 3239 // Compute 'L'. 3240 // parmDepth does not include the declaring function prototype. 3241 // FunctionTypeDepth does account for that. 3242 assert(parmDepth < FunctionTypeDepth.getDepth()); 3243 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth; 3244 if (FunctionTypeDepth.isInResultType()) 3245 nestingDepth--; 3246 3247 if (nestingDepth == 0) { 3248 Out << "fp"; 3249 } else { 3250 Out << "fL" << (nestingDepth - 1) << 'p'; 3251 } 3252 3253 // Top-level qualifiers. We don't have to worry about arrays here, 3254 // because parameters declared as arrays should already have been 3255 // transformed to have pointer type. FIXME: apparently these don't 3256 // get mangled if used as an rvalue of a known non-class type? 3257 assert(!parm->getType()->isArrayType() 3258 && "parameter's type is still an array type?"); 3259 mangleQualifiers(parm->getType().getQualifiers()); 3260 3261 // Parameter index. 3262 if (parmIndex != 0) { 3263 Out << (parmIndex - 1); 3264 } 3265 Out << '_'; 3266 } 3267 3268 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) { 3269 // <ctor-dtor-name> ::= C1 # complete object constructor 3270 // ::= C2 # base object constructor 3271 // 3272 // In addition, C5 is a comdat name with C1 and C2 in it. 3273 switch (T) { 3274 case Ctor_Complete: 3275 Out << "C1"; 3276 break; 3277 case Ctor_Base: 3278 Out << "C2"; 3279 break; 3280 case Ctor_Comdat: 3281 Out << "C5"; 3282 break; 3283 } 3284 } 3285 3286 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 3287 // <ctor-dtor-name> ::= D0 # deleting destructor 3288 // ::= D1 # complete object destructor 3289 // ::= D2 # base object destructor 3290 // 3291 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it. 3292 switch (T) { 3293 case Dtor_Deleting: 3294 Out << "D0"; 3295 break; 3296 case Dtor_Complete: 3297 Out << "D1"; 3298 break; 3299 case Dtor_Base: 3300 Out << "D2"; 3301 break; 3302 case Dtor_Comdat: 3303 Out << "D5"; 3304 break; 3305 } 3306 } 3307 3308 void CXXNameMangler::mangleTemplateArgs( 3309 const ASTTemplateArgumentListInfo &TemplateArgs) { 3310 // <template-args> ::= I <template-arg>+ E 3311 Out << 'I'; 3312 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i) 3313 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument()); 3314 Out << 'E'; 3315 } 3316 3317 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) { 3318 // <template-args> ::= I <template-arg>+ E 3319 Out << 'I'; 3320 for (unsigned i = 0, e = AL.size(); i != e; ++i) 3321 mangleTemplateArg(AL[i]); 3322 Out << 'E'; 3323 } 3324 3325 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs, 3326 unsigned NumTemplateArgs) { 3327 // <template-args> ::= I <template-arg>+ E 3328 Out << 'I'; 3329 for (unsigned i = 0; i != NumTemplateArgs; ++i) 3330 mangleTemplateArg(TemplateArgs[i]); 3331 Out << 'E'; 3332 } 3333 3334 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) { 3335 // <template-arg> ::= <type> # type or template 3336 // ::= X <expression> E # expression 3337 // ::= <expr-primary> # simple expressions 3338 // ::= J <template-arg>* E # argument pack 3339 if (!A.isInstantiationDependent() || A.isDependent()) 3340 A = Context.getASTContext().getCanonicalTemplateArgument(A); 3341 3342 switch (A.getKind()) { 3343 case TemplateArgument::Null: 3344 llvm_unreachable("Cannot mangle NULL template argument"); 3345 3346 case TemplateArgument::Type: 3347 mangleType(A.getAsType()); 3348 break; 3349 case TemplateArgument::Template: 3350 // This is mangled as <type>. 3351 mangleType(A.getAsTemplate()); 3352 break; 3353 case TemplateArgument::TemplateExpansion: 3354 // <type> ::= Dp <type> # pack expansion (C++0x) 3355 Out << "Dp"; 3356 mangleType(A.getAsTemplateOrTemplatePattern()); 3357 break; 3358 case TemplateArgument::Expression: { 3359 // It's possible to end up with a DeclRefExpr here in certain 3360 // dependent cases, in which case we should mangle as a 3361 // declaration. 3362 const Expr *E = A.getAsExpr()->IgnoreParens(); 3363 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3364 const ValueDecl *D = DRE->getDecl(); 3365 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) { 3366 Out << "L"; 3367 mangle(D, "_Z"); 3368 Out << 'E'; 3369 break; 3370 } 3371 } 3372 3373 Out << 'X'; 3374 mangleExpression(E); 3375 Out << 'E'; 3376 break; 3377 } 3378 case TemplateArgument::Integral: 3379 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral()); 3380 break; 3381 case TemplateArgument::Declaration: { 3382 // <expr-primary> ::= L <mangled-name> E # external name 3383 // Clang produces AST's where pointer-to-member-function expressions 3384 // and pointer-to-function expressions are represented as a declaration not 3385 // an expression. We compensate for it here to produce the correct mangling. 3386 ValueDecl *D = A.getAsDecl(); 3387 bool compensateMangling = !A.isDeclForReferenceParam(); 3388 if (compensateMangling) { 3389 Out << 'X'; 3390 mangleOperatorName(OO_Amp, 1); 3391 } 3392 3393 Out << 'L'; 3394 // References to external entities use the mangled name; if the name would 3395 // not normally be manged then mangle it as unqualified. 3396 // 3397 // FIXME: The ABI specifies that external names here should have _Z, but 3398 // gcc leaves this off. 3399 if (compensateMangling) 3400 mangle(D, "_Z"); 3401 else 3402 mangle(D, "Z"); 3403 Out << 'E'; 3404 3405 if (compensateMangling) 3406 Out << 'E'; 3407 3408 break; 3409 } 3410 case TemplateArgument::NullPtr: { 3411 // <expr-primary> ::= L <type> 0 E 3412 Out << 'L'; 3413 mangleType(A.getNullPtrType()); 3414 Out << "0E"; 3415 break; 3416 } 3417 case TemplateArgument::Pack: { 3418 // <template-arg> ::= J <template-arg>* E 3419 Out << 'J'; 3420 for (const auto &P : A.pack_elements()) 3421 mangleTemplateArg(P); 3422 Out << 'E'; 3423 } 3424 } 3425 } 3426 3427 void CXXNameMangler::mangleTemplateParameter(unsigned Index) { 3428 // <template-param> ::= T_ # first template parameter 3429 // ::= T <parameter-2 non-negative number> _ 3430 if (Index == 0) 3431 Out << "T_"; 3432 else 3433 Out << 'T' << (Index - 1) << '_'; 3434 } 3435 3436 void CXXNameMangler::mangleSeqID(unsigned SeqID) { 3437 if (SeqID == 1) 3438 Out << '0'; 3439 else if (SeqID > 1) { 3440 SeqID--; 3441 3442 // <seq-id> is encoded in base-36, using digits and upper case letters. 3443 char Buffer[7]; // log(2**32) / log(36) ~= 7 3444 MutableArrayRef<char> BufferRef(Buffer); 3445 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin(); 3446 3447 for (; SeqID != 0; SeqID /= 36) { 3448 unsigned C = SeqID % 36; 3449 *I++ = (C < 10 ? '0' + C : 'A' + C - 10); 3450 } 3451 3452 Out.write(I.base(), I - BufferRef.rbegin()); 3453 } 3454 Out << '_'; 3455 } 3456 3457 void CXXNameMangler::mangleExistingSubstitution(QualType type) { 3458 bool result = mangleSubstitution(type); 3459 assert(result && "no existing substitution for type"); 3460 (void) result; 3461 } 3462 3463 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) { 3464 bool result = mangleSubstitution(tname); 3465 assert(result && "no existing substitution for template name"); 3466 (void) result; 3467 } 3468 3469 // <substitution> ::= S <seq-id> _ 3470 // ::= S_ 3471 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) { 3472 // Try one of the standard substitutions first. 3473 if (mangleStandardSubstitution(ND)) 3474 return true; 3475 3476 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 3477 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND)); 3478 } 3479 3480 /// \brief Determine whether the given type has any qualifiers that are 3481 /// relevant for substitutions. 3482 static bool hasMangledSubstitutionQualifiers(QualType T) { 3483 Qualifiers Qs = T.getQualifiers(); 3484 return Qs.getCVRQualifiers() || Qs.hasAddressSpace(); 3485 } 3486 3487 bool CXXNameMangler::mangleSubstitution(QualType T) { 3488 if (!hasMangledSubstitutionQualifiers(T)) { 3489 if (const RecordType *RT = T->getAs<RecordType>()) 3490 return mangleSubstitution(RT->getDecl()); 3491 } 3492 3493 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 3494 3495 return mangleSubstitution(TypePtr); 3496 } 3497 3498 bool CXXNameMangler::mangleSubstitution(TemplateName Template) { 3499 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 3500 return mangleSubstitution(TD); 3501 3502 Template = Context.getASTContext().getCanonicalTemplateName(Template); 3503 return mangleSubstitution( 3504 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 3505 } 3506 3507 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) { 3508 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr); 3509 if (I == Substitutions.end()) 3510 return false; 3511 3512 unsigned SeqID = I->second; 3513 Out << 'S'; 3514 mangleSeqID(SeqID); 3515 3516 return true; 3517 } 3518 3519 static bool isCharType(QualType T) { 3520 if (T.isNull()) 3521 return false; 3522 3523 return T->isSpecificBuiltinType(BuiltinType::Char_S) || 3524 T->isSpecificBuiltinType(BuiltinType::Char_U); 3525 } 3526 3527 /// isCharSpecialization - Returns whether a given type is a template 3528 /// specialization of a given name with a single argument of type char. 3529 static bool isCharSpecialization(QualType T, const char *Name) { 3530 if (T.isNull()) 3531 return false; 3532 3533 const RecordType *RT = T->getAs<RecordType>(); 3534 if (!RT) 3535 return false; 3536 3537 const ClassTemplateSpecializationDecl *SD = 3538 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 3539 if (!SD) 3540 return false; 3541 3542 if (!isStdNamespace(getEffectiveDeclContext(SD))) 3543 return false; 3544 3545 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 3546 if (TemplateArgs.size() != 1) 3547 return false; 3548 3549 if (!isCharType(TemplateArgs[0].getAsType())) 3550 return false; 3551 3552 return SD->getIdentifier()->getName() == Name; 3553 } 3554 3555 template <std::size_t StrLen> 3556 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD, 3557 const char (&Str)[StrLen]) { 3558 if (!SD->getIdentifier()->isStr(Str)) 3559 return false; 3560 3561 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 3562 if (TemplateArgs.size() != 2) 3563 return false; 3564 3565 if (!isCharType(TemplateArgs[0].getAsType())) 3566 return false; 3567 3568 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 3569 return false; 3570 3571 return true; 3572 } 3573 3574 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) { 3575 // <substitution> ::= St # ::std:: 3576 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 3577 if (isStd(NS)) { 3578 Out << "St"; 3579 return true; 3580 } 3581 } 3582 3583 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) { 3584 if (!isStdNamespace(getEffectiveDeclContext(TD))) 3585 return false; 3586 3587 // <substitution> ::= Sa # ::std::allocator 3588 if (TD->getIdentifier()->isStr("allocator")) { 3589 Out << "Sa"; 3590 return true; 3591 } 3592 3593 // <<substitution> ::= Sb # ::std::basic_string 3594 if (TD->getIdentifier()->isStr("basic_string")) { 3595 Out << "Sb"; 3596 return true; 3597 } 3598 } 3599 3600 if (const ClassTemplateSpecializationDecl *SD = 3601 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 3602 if (!isStdNamespace(getEffectiveDeclContext(SD))) 3603 return false; 3604 3605 // <substitution> ::= Ss # ::std::basic_string<char, 3606 // ::std::char_traits<char>, 3607 // ::std::allocator<char> > 3608 if (SD->getIdentifier()->isStr("basic_string")) { 3609 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 3610 3611 if (TemplateArgs.size() != 3) 3612 return false; 3613 3614 if (!isCharType(TemplateArgs[0].getAsType())) 3615 return false; 3616 3617 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 3618 return false; 3619 3620 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator")) 3621 return false; 3622 3623 Out << "Ss"; 3624 return true; 3625 } 3626 3627 // <substitution> ::= Si # ::std::basic_istream<char, 3628 // ::std::char_traits<char> > 3629 if (isStreamCharSpecialization(SD, "basic_istream")) { 3630 Out << "Si"; 3631 return true; 3632 } 3633 3634 // <substitution> ::= So # ::std::basic_ostream<char, 3635 // ::std::char_traits<char> > 3636 if (isStreamCharSpecialization(SD, "basic_ostream")) { 3637 Out << "So"; 3638 return true; 3639 } 3640 3641 // <substitution> ::= Sd # ::std::basic_iostream<char, 3642 // ::std::char_traits<char> > 3643 if (isStreamCharSpecialization(SD, "basic_iostream")) { 3644 Out << "Sd"; 3645 return true; 3646 } 3647 } 3648 return false; 3649 } 3650 3651 void CXXNameMangler::addSubstitution(QualType T) { 3652 if (!hasMangledSubstitutionQualifiers(T)) { 3653 if (const RecordType *RT = T->getAs<RecordType>()) { 3654 addSubstitution(RT->getDecl()); 3655 return; 3656 } 3657 } 3658 3659 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 3660 addSubstitution(TypePtr); 3661 } 3662 3663 void CXXNameMangler::addSubstitution(TemplateName Template) { 3664 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 3665 return addSubstitution(TD); 3666 3667 Template = Context.getASTContext().getCanonicalTemplateName(Template); 3668 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 3669 } 3670 3671 void CXXNameMangler::addSubstitution(uintptr_t Ptr) { 3672 assert(!Substitutions.count(Ptr) && "Substitution already exists!"); 3673 Substitutions[Ptr] = SeqID++; 3674 } 3675 3676 // 3677 3678 /// \brief Mangles the name of the declaration D and emits that name to the 3679 /// given output stream. 3680 /// 3681 /// If the declaration D requires a mangled name, this routine will emit that 3682 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged 3683 /// and this routine will return false. In this case, the caller should just 3684 /// emit the identifier of the declaration (\c D->getIdentifier()) as its 3685 /// name. 3686 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D, 3687 raw_ostream &Out) { 3688 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) && 3689 "Invalid mangleName() call, argument is not a variable or function!"); 3690 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) && 3691 "Invalid mangleName() call on 'structor decl!"); 3692 3693 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 3694 getASTContext().getSourceManager(), 3695 "Mangling declaration"); 3696 3697 CXXNameMangler Mangler(*this, Out, D); 3698 return Mangler.mangle(D); 3699 } 3700 3701 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D, 3702 CXXCtorType Type, 3703 raw_ostream &Out) { 3704 CXXNameMangler Mangler(*this, Out, D, Type); 3705 Mangler.mangle(D); 3706 } 3707 3708 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D, 3709 CXXDtorType Type, 3710 raw_ostream &Out) { 3711 CXXNameMangler Mangler(*this, Out, D, Type); 3712 Mangler.mangle(D); 3713 } 3714 3715 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D, 3716 raw_ostream &Out) { 3717 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat); 3718 Mangler.mangle(D); 3719 } 3720 3721 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D, 3722 raw_ostream &Out) { 3723 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat); 3724 Mangler.mangle(D); 3725 } 3726 3727 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 3728 const ThunkInfo &Thunk, 3729 raw_ostream &Out) { 3730 // <special-name> ::= T <call-offset> <base encoding> 3731 // # base is the nominal target function of thunk 3732 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding> 3733 // # base is the nominal target function of thunk 3734 // # first call-offset is 'this' adjustment 3735 // # second call-offset is result adjustment 3736 3737 assert(!isa<CXXDestructorDecl>(MD) && 3738 "Use mangleCXXDtor for destructor decls!"); 3739 CXXNameMangler Mangler(*this, Out); 3740 Mangler.getStream() << "_ZT"; 3741 if (!Thunk.Return.isEmpty()) 3742 Mangler.getStream() << 'c'; 3743 3744 // Mangle the 'this' pointer adjustment. 3745 Mangler.mangleCallOffset(Thunk.This.NonVirtual, 3746 Thunk.This.Virtual.Itanium.VCallOffsetOffset); 3747 3748 // Mangle the return pointer adjustment if there is one. 3749 if (!Thunk.Return.isEmpty()) 3750 Mangler.mangleCallOffset(Thunk.Return.NonVirtual, 3751 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset); 3752 3753 Mangler.mangleFunctionEncoding(MD); 3754 } 3755 3756 void ItaniumMangleContextImpl::mangleCXXDtorThunk( 3757 const CXXDestructorDecl *DD, CXXDtorType Type, 3758 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) { 3759 // <special-name> ::= T <call-offset> <base encoding> 3760 // # base is the nominal target function of thunk 3761 CXXNameMangler Mangler(*this, Out, DD, Type); 3762 Mangler.getStream() << "_ZT"; 3763 3764 // Mangle the 'this' pointer adjustment. 3765 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 3766 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); 3767 3768 Mangler.mangleFunctionEncoding(DD); 3769 } 3770 3771 /// mangleGuardVariable - Returns the mangled name for a guard variable 3772 /// for the passed in VarDecl. 3773 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D, 3774 raw_ostream &Out) { 3775 // <special-name> ::= GV <object name> # Guard variable for one-time 3776 // # initialization 3777 CXXNameMangler Mangler(*this, Out); 3778 Mangler.getStream() << "_ZGV"; 3779 Mangler.mangleName(D); 3780 } 3781 3782 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD, 3783 raw_ostream &Out) { 3784 // These symbols are internal in the Itanium ABI, so the names don't matter. 3785 // Clang has traditionally used this symbol and allowed LLVM to adjust it to 3786 // avoid duplicate symbols. 3787 Out << "__cxx_global_var_init"; 3788 } 3789 3790 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 3791 raw_ostream &Out) { 3792 // Prefix the mangling of D with __dtor_. 3793 CXXNameMangler Mangler(*this, Out); 3794 Mangler.getStream() << "__dtor_"; 3795 if (shouldMangleDeclName(D)) 3796 Mangler.mangle(D); 3797 else 3798 Mangler.getStream() << D->getName(); 3799 } 3800 3801 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D, 3802 raw_ostream &Out) { 3803 // <special-name> ::= TH <object name> 3804 CXXNameMangler Mangler(*this, Out); 3805 Mangler.getStream() << "_ZTH"; 3806 Mangler.mangleName(D); 3807 } 3808 3809 void 3810 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D, 3811 raw_ostream &Out) { 3812 // <special-name> ::= TW <object name> 3813 CXXNameMangler Mangler(*this, Out); 3814 Mangler.getStream() << "_ZTW"; 3815 Mangler.mangleName(D); 3816 } 3817 3818 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D, 3819 unsigned ManglingNumber, 3820 raw_ostream &Out) { 3821 // We match the GCC mangling here. 3822 // <special-name> ::= GR <object name> 3823 CXXNameMangler Mangler(*this, Out); 3824 Mangler.getStream() << "_ZGR"; 3825 Mangler.mangleName(D); 3826 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!"); 3827 Mangler.mangleSeqID(ManglingNumber - 1); 3828 } 3829 3830 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD, 3831 raw_ostream &Out) { 3832 // <special-name> ::= TV <type> # virtual table 3833 CXXNameMangler Mangler(*this, Out); 3834 Mangler.getStream() << "_ZTV"; 3835 Mangler.mangleNameOrStandardSubstitution(RD); 3836 } 3837 3838 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD, 3839 raw_ostream &Out) { 3840 // <special-name> ::= TT <type> # VTT structure 3841 CXXNameMangler Mangler(*this, Out); 3842 Mangler.getStream() << "_ZTT"; 3843 Mangler.mangleNameOrStandardSubstitution(RD); 3844 } 3845 3846 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD, 3847 int64_t Offset, 3848 const CXXRecordDecl *Type, 3849 raw_ostream &Out) { 3850 // <special-name> ::= TC <type> <offset number> _ <base type> 3851 CXXNameMangler Mangler(*this, Out); 3852 Mangler.getStream() << "_ZTC"; 3853 Mangler.mangleNameOrStandardSubstitution(RD); 3854 Mangler.getStream() << Offset; 3855 Mangler.getStream() << '_'; 3856 Mangler.mangleNameOrStandardSubstitution(Type); 3857 } 3858 3859 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) { 3860 // <special-name> ::= TI <type> # typeinfo structure 3861 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers"); 3862 CXXNameMangler Mangler(*this, Out); 3863 Mangler.getStream() << "_ZTI"; 3864 Mangler.mangleType(Ty); 3865 } 3866 3867 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty, 3868 raw_ostream &Out) { 3869 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string) 3870 CXXNameMangler Mangler(*this, Out); 3871 Mangler.getStream() << "_ZTS"; 3872 Mangler.mangleType(Ty); 3873 } 3874 3875 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) { 3876 mangleCXXRTTIName(Ty, Out); 3877 } 3878 3879 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) { 3880 llvm_unreachable("Can't mangle string literals"); 3881 } 3882 3883 ItaniumMangleContext * 3884 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) { 3885 return new ItaniumMangleContextImpl(Context, Diags); 3886 } 3887