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