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