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 // Proposal on cxx-abi-dev, 2015-10-21. 1757 // ::= aw # co_await 1758 case OO_Coawait: Out << "aw"; break; 1759 1760 case OO_None: 1761 case NUM_OVERLOADED_OPERATORS: 1762 llvm_unreachable("Not an overloaded operator"); 1763 } 1764 } 1765 1766 void CXXNameMangler::mangleQualifiers(Qualifiers Quals) { 1767 // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const 1768 if (Quals.hasRestrict()) 1769 Out << 'r'; 1770 if (Quals.hasVolatile()) 1771 Out << 'V'; 1772 if (Quals.hasConst()) 1773 Out << 'K'; 1774 1775 if (Quals.hasAddressSpace()) { 1776 // Address space extension: 1777 // 1778 // <type> ::= U <target-addrspace> 1779 // <type> ::= U <OpenCL-addrspace> 1780 // <type> ::= U <CUDA-addrspace> 1781 1782 SmallString<64> ASString; 1783 unsigned AS = Quals.getAddressSpace(); 1784 1785 if (Context.getASTContext().addressSpaceMapManglingFor(AS)) { 1786 // <target-addrspace> ::= "AS" <address-space-number> 1787 unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS); 1788 ASString = "AS" + llvm::utostr_32(TargetAS); 1789 } else { 1790 switch (AS) { 1791 default: llvm_unreachable("Not a language specific address space"); 1792 // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" ] 1793 case LangAS::opencl_global: ASString = "CLglobal"; break; 1794 case LangAS::opencl_local: ASString = "CLlocal"; break; 1795 case LangAS::opencl_constant: ASString = "CLconstant"; break; 1796 // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ] 1797 case LangAS::cuda_device: ASString = "CUdevice"; break; 1798 case LangAS::cuda_constant: ASString = "CUconstant"; break; 1799 case LangAS::cuda_shared: ASString = "CUshared"; break; 1800 } 1801 } 1802 Out << 'U' << ASString.size() << ASString; 1803 } 1804 1805 StringRef LifetimeName; 1806 switch (Quals.getObjCLifetime()) { 1807 // Objective-C ARC Extension: 1808 // 1809 // <type> ::= U "__strong" 1810 // <type> ::= U "__weak" 1811 // <type> ::= U "__autoreleasing" 1812 case Qualifiers::OCL_None: 1813 break; 1814 1815 case Qualifiers::OCL_Weak: 1816 LifetimeName = "__weak"; 1817 break; 1818 1819 case Qualifiers::OCL_Strong: 1820 LifetimeName = "__strong"; 1821 break; 1822 1823 case Qualifiers::OCL_Autoreleasing: 1824 LifetimeName = "__autoreleasing"; 1825 break; 1826 1827 case Qualifiers::OCL_ExplicitNone: 1828 // The __unsafe_unretained qualifier is *not* mangled, so that 1829 // __unsafe_unretained types in ARC produce the same manglings as the 1830 // equivalent (but, naturally, unqualified) types in non-ARC, providing 1831 // better ABI compatibility. 1832 // 1833 // It's safe to do this because unqualified 'id' won't show up 1834 // in any type signatures that need to be mangled. 1835 break; 1836 } 1837 if (!LifetimeName.empty()) 1838 Out << 'U' << LifetimeName.size() << LifetimeName; 1839 } 1840 1841 void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) { 1842 // <ref-qualifier> ::= R # lvalue reference 1843 // ::= O # rvalue-reference 1844 switch (RefQualifier) { 1845 case RQ_None: 1846 break; 1847 1848 case RQ_LValue: 1849 Out << 'R'; 1850 break; 1851 1852 case RQ_RValue: 1853 Out << 'O'; 1854 break; 1855 } 1856 } 1857 1858 void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) { 1859 Context.mangleObjCMethodName(MD, Out); 1860 } 1861 1862 static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty) { 1863 if (Quals) 1864 return true; 1865 if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel)) 1866 return true; 1867 if (Ty->isOpenCLSpecificType()) 1868 return true; 1869 if (Ty->isBuiltinType()) 1870 return false; 1871 1872 return true; 1873 } 1874 1875 void CXXNameMangler::mangleType(QualType T) { 1876 // If our type is instantiation-dependent but not dependent, we mangle 1877 // it as it was written in the source, removing any top-level sugar. 1878 // Otherwise, use the canonical type. 1879 // 1880 // FIXME: This is an approximation of the instantiation-dependent name 1881 // mangling rules, since we should really be using the type as written and 1882 // augmented via semantic analysis (i.e., with implicit conversions and 1883 // default template arguments) for any instantiation-dependent type. 1884 // Unfortunately, that requires several changes to our AST: 1885 // - Instantiation-dependent TemplateSpecializationTypes will need to be 1886 // uniqued, so that we can handle substitutions properly 1887 // - Default template arguments will need to be represented in the 1888 // TemplateSpecializationType, since they need to be mangled even though 1889 // they aren't written. 1890 // - Conversions on non-type template arguments need to be expressed, since 1891 // they can affect the mangling of sizeof/alignof. 1892 if (!T->isInstantiationDependentType() || T->isDependentType()) 1893 T = T.getCanonicalType(); 1894 else { 1895 // Desugar any types that are purely sugar. 1896 do { 1897 // Don't desugar through template specialization types that aren't 1898 // type aliases. We need to mangle the template arguments as written. 1899 if (const TemplateSpecializationType *TST 1900 = dyn_cast<TemplateSpecializationType>(T)) 1901 if (!TST->isTypeAlias()) 1902 break; 1903 1904 QualType Desugared 1905 = T.getSingleStepDesugaredType(Context.getASTContext()); 1906 if (Desugared == T) 1907 break; 1908 1909 T = Desugared; 1910 } while (true); 1911 } 1912 SplitQualType split = T.split(); 1913 Qualifiers quals = split.Quals; 1914 const Type *ty = split.Ty; 1915 1916 bool isSubstitutable = isTypeSubstitutable(quals, ty); 1917 if (isSubstitutable && mangleSubstitution(T)) 1918 return; 1919 1920 // If we're mangling a qualified array type, push the qualifiers to 1921 // the element type. 1922 if (quals && isa<ArrayType>(T)) { 1923 ty = Context.getASTContext().getAsArrayType(T); 1924 quals = Qualifiers(); 1925 1926 // Note that we don't update T: we want to add the 1927 // substitution at the original type. 1928 } 1929 1930 if (quals) { 1931 mangleQualifiers(quals); 1932 // Recurse: even if the qualified type isn't yet substitutable, 1933 // the unqualified type might be. 1934 mangleType(QualType(ty, 0)); 1935 } else { 1936 switch (ty->getTypeClass()) { 1937 #define ABSTRACT_TYPE(CLASS, PARENT) 1938 #define NON_CANONICAL_TYPE(CLASS, PARENT) \ 1939 case Type::CLASS: \ 1940 llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \ 1941 return; 1942 #define TYPE(CLASS, PARENT) \ 1943 case Type::CLASS: \ 1944 mangleType(static_cast<const CLASS##Type*>(ty)); \ 1945 break; 1946 #include "clang/AST/TypeNodes.def" 1947 } 1948 } 1949 1950 // Add the substitution. 1951 if (isSubstitutable) 1952 addSubstitution(T); 1953 } 1954 1955 void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) { 1956 if (!mangleStandardSubstitution(ND)) 1957 mangleName(ND); 1958 } 1959 1960 void CXXNameMangler::mangleType(const BuiltinType *T) { 1961 // <type> ::= <builtin-type> 1962 // <builtin-type> ::= v # void 1963 // ::= w # wchar_t 1964 // ::= b # bool 1965 // ::= c # char 1966 // ::= a # signed char 1967 // ::= h # unsigned char 1968 // ::= s # short 1969 // ::= t # unsigned short 1970 // ::= i # int 1971 // ::= j # unsigned int 1972 // ::= l # long 1973 // ::= m # unsigned long 1974 // ::= x # long long, __int64 1975 // ::= y # unsigned long long, __int64 1976 // ::= n # __int128 1977 // ::= o # unsigned __int128 1978 // ::= f # float 1979 // ::= d # double 1980 // ::= e # long double, __float80 1981 // UNSUPPORTED: ::= g # __float128 1982 // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits) 1983 // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits) 1984 // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits) 1985 // ::= Dh # IEEE 754r half-precision floating point (16 bits) 1986 // ::= Di # char32_t 1987 // ::= Ds # char16_t 1988 // ::= Dn # std::nullptr_t (i.e., decltype(nullptr)) 1989 // ::= u <source-name> # vendor extended type 1990 switch (T->getKind()) { 1991 case BuiltinType::Void: 1992 Out << 'v'; 1993 break; 1994 case BuiltinType::Bool: 1995 Out << 'b'; 1996 break; 1997 case BuiltinType::Char_U: 1998 case BuiltinType::Char_S: 1999 Out << 'c'; 2000 break; 2001 case BuiltinType::UChar: 2002 Out << 'h'; 2003 break; 2004 case BuiltinType::UShort: 2005 Out << 't'; 2006 break; 2007 case BuiltinType::UInt: 2008 Out << 'j'; 2009 break; 2010 case BuiltinType::ULong: 2011 Out << 'm'; 2012 break; 2013 case BuiltinType::ULongLong: 2014 Out << 'y'; 2015 break; 2016 case BuiltinType::UInt128: 2017 Out << 'o'; 2018 break; 2019 case BuiltinType::SChar: 2020 Out << 'a'; 2021 break; 2022 case BuiltinType::WChar_S: 2023 case BuiltinType::WChar_U: 2024 Out << 'w'; 2025 break; 2026 case BuiltinType::Char16: 2027 Out << "Ds"; 2028 break; 2029 case BuiltinType::Char32: 2030 Out << "Di"; 2031 break; 2032 case BuiltinType::Short: 2033 Out << 's'; 2034 break; 2035 case BuiltinType::Int: 2036 Out << 'i'; 2037 break; 2038 case BuiltinType::Long: 2039 Out << 'l'; 2040 break; 2041 case BuiltinType::LongLong: 2042 Out << 'x'; 2043 break; 2044 case BuiltinType::Int128: 2045 Out << 'n'; 2046 break; 2047 case BuiltinType::Half: 2048 Out << "Dh"; 2049 break; 2050 case BuiltinType::Float: 2051 Out << 'f'; 2052 break; 2053 case BuiltinType::Double: 2054 Out << 'd'; 2055 break; 2056 case BuiltinType::LongDouble: 2057 Out << (getASTContext().getTargetInfo().useFloat128ManglingForLongDouble() 2058 ? 'g' 2059 : 'e'); 2060 break; 2061 case BuiltinType::NullPtr: 2062 Out << "Dn"; 2063 break; 2064 2065 #define BUILTIN_TYPE(Id, SingletonId) 2066 #define PLACEHOLDER_TYPE(Id, SingletonId) \ 2067 case BuiltinType::Id: 2068 #include "clang/AST/BuiltinTypes.def" 2069 case BuiltinType::Dependent: 2070 llvm_unreachable("mangling a placeholder type"); 2071 case BuiltinType::ObjCId: 2072 Out << "11objc_object"; 2073 break; 2074 case BuiltinType::ObjCClass: 2075 Out << "10objc_class"; 2076 break; 2077 case BuiltinType::ObjCSel: 2078 Out << "13objc_selector"; 2079 break; 2080 case BuiltinType::OCLImage1d: 2081 Out << "11ocl_image1d"; 2082 break; 2083 case BuiltinType::OCLImage1dArray: 2084 Out << "16ocl_image1darray"; 2085 break; 2086 case BuiltinType::OCLImage1dBuffer: 2087 Out << "17ocl_image1dbuffer"; 2088 break; 2089 case BuiltinType::OCLImage2d: 2090 Out << "11ocl_image2d"; 2091 break; 2092 case BuiltinType::OCLImage2dArray: 2093 Out << "16ocl_image2darray"; 2094 break; 2095 case BuiltinType::OCLImage2dDepth: 2096 Out << "16ocl_image2ddepth"; 2097 break; 2098 case BuiltinType::OCLImage2dArrayDepth: 2099 Out << "21ocl_image2darraydepth"; 2100 break; 2101 case BuiltinType::OCLImage2dMSAA: 2102 Out << "15ocl_image2dmsaa"; 2103 break; 2104 case BuiltinType::OCLImage2dArrayMSAA: 2105 Out << "20ocl_image2darraymsaa"; 2106 break; 2107 case BuiltinType::OCLImage2dMSAADepth: 2108 Out << "20ocl_image2dmsaadepth"; 2109 break; 2110 case BuiltinType::OCLImage2dArrayMSAADepth: 2111 Out << "35ocl_image2darraymsaadepth"; 2112 break; 2113 case BuiltinType::OCLImage3d: 2114 Out << "11ocl_image3d"; 2115 break; 2116 case BuiltinType::OCLSampler: 2117 Out << "11ocl_sampler"; 2118 break; 2119 case BuiltinType::OCLEvent: 2120 Out << "9ocl_event"; 2121 break; 2122 case BuiltinType::OCLClkEvent: 2123 Out << "12ocl_clkevent"; 2124 break; 2125 case BuiltinType::OCLQueue: 2126 Out << "9ocl_queue"; 2127 break; 2128 case BuiltinType::OCLNDRange: 2129 Out << "11ocl_ndrange"; 2130 break; 2131 case BuiltinType::OCLReserveID: 2132 Out << "13ocl_reserveid"; 2133 break; 2134 } 2135 } 2136 2137 // <type> ::= <function-type> 2138 // <function-type> ::= [<CV-qualifiers>] F [Y] 2139 // <bare-function-type> [<ref-qualifier>] E 2140 void CXXNameMangler::mangleType(const FunctionProtoType *T) { 2141 // Mangle CV-qualifiers, if present. These are 'this' qualifiers, 2142 // e.g. "const" in "int (A::*)() const". 2143 mangleQualifiers(Qualifiers::fromCVRMask(T->getTypeQuals())); 2144 2145 Out << 'F'; 2146 2147 // FIXME: We don't have enough information in the AST to produce the 'Y' 2148 // encoding for extern "C" function types. 2149 mangleBareFunctionType(T, /*MangleReturnType=*/true); 2150 2151 // Mangle the ref-qualifier, if present. 2152 mangleRefQualifier(T->getRefQualifier()); 2153 2154 Out << 'E'; 2155 } 2156 2157 void CXXNameMangler::mangleType(const FunctionNoProtoType *T) { 2158 // Function types without prototypes can arise when mangling a function type 2159 // within an overloadable function in C. We mangle these as the absence of any 2160 // parameter types (not even an empty parameter list). 2161 Out << 'F'; 2162 2163 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 2164 2165 FunctionTypeDepth.enterResultType(); 2166 mangleType(T->getReturnType()); 2167 FunctionTypeDepth.leaveResultType(); 2168 2169 FunctionTypeDepth.pop(saved); 2170 Out << 'E'; 2171 } 2172 2173 void CXXNameMangler::mangleBareFunctionType(const FunctionType *T, 2174 bool MangleReturnType) { 2175 // We should never be mangling something without a prototype. 2176 const FunctionProtoType *Proto = cast<FunctionProtoType>(T); 2177 2178 // Record that we're in a function type. See mangleFunctionParam 2179 // for details on what we're trying to achieve here. 2180 FunctionTypeDepthState saved = FunctionTypeDepth.push(); 2181 2182 // <bare-function-type> ::= <signature type>+ 2183 if (MangleReturnType) { 2184 FunctionTypeDepth.enterResultType(); 2185 mangleType(Proto->getReturnType()); 2186 FunctionTypeDepth.leaveResultType(); 2187 } 2188 2189 if (Proto->getNumParams() == 0 && !Proto->isVariadic()) { 2190 // <builtin-type> ::= v # void 2191 Out << 'v'; 2192 2193 FunctionTypeDepth.pop(saved); 2194 return; 2195 } 2196 2197 for (const auto &Arg : Proto->param_types()) 2198 mangleType(Context.getASTContext().getSignatureParameterType(Arg)); 2199 2200 FunctionTypeDepth.pop(saved); 2201 2202 // <builtin-type> ::= z # ellipsis 2203 if (Proto->isVariadic()) 2204 Out << 'z'; 2205 } 2206 2207 // <type> ::= <class-enum-type> 2208 // <class-enum-type> ::= <name> 2209 void CXXNameMangler::mangleType(const UnresolvedUsingType *T) { 2210 mangleName(T->getDecl()); 2211 } 2212 2213 // <type> ::= <class-enum-type> 2214 // <class-enum-type> ::= <name> 2215 void CXXNameMangler::mangleType(const EnumType *T) { 2216 mangleType(static_cast<const TagType*>(T)); 2217 } 2218 void CXXNameMangler::mangleType(const RecordType *T) { 2219 mangleType(static_cast<const TagType*>(T)); 2220 } 2221 void CXXNameMangler::mangleType(const TagType *T) { 2222 mangleName(T->getDecl()); 2223 } 2224 2225 // <type> ::= <array-type> 2226 // <array-type> ::= A <positive dimension number> _ <element type> 2227 // ::= A [<dimension expression>] _ <element type> 2228 void CXXNameMangler::mangleType(const ConstantArrayType *T) { 2229 Out << 'A' << T->getSize() << '_'; 2230 mangleType(T->getElementType()); 2231 } 2232 void CXXNameMangler::mangleType(const VariableArrayType *T) { 2233 Out << 'A'; 2234 // decayed vla types (size 0) will just be skipped. 2235 if (T->getSizeExpr()) 2236 mangleExpression(T->getSizeExpr()); 2237 Out << '_'; 2238 mangleType(T->getElementType()); 2239 } 2240 void CXXNameMangler::mangleType(const DependentSizedArrayType *T) { 2241 Out << 'A'; 2242 mangleExpression(T->getSizeExpr()); 2243 Out << '_'; 2244 mangleType(T->getElementType()); 2245 } 2246 void CXXNameMangler::mangleType(const IncompleteArrayType *T) { 2247 Out << "A_"; 2248 mangleType(T->getElementType()); 2249 } 2250 2251 // <type> ::= <pointer-to-member-type> 2252 // <pointer-to-member-type> ::= M <class type> <member type> 2253 void CXXNameMangler::mangleType(const MemberPointerType *T) { 2254 Out << 'M'; 2255 mangleType(QualType(T->getClass(), 0)); 2256 QualType PointeeType = T->getPointeeType(); 2257 if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) { 2258 mangleType(FPT); 2259 2260 // Itanium C++ ABI 5.1.8: 2261 // 2262 // The type of a non-static member function is considered to be different, 2263 // for the purposes of substitution, from the type of a namespace-scope or 2264 // static member function whose type appears similar. The types of two 2265 // non-static member functions are considered to be different, for the 2266 // purposes of substitution, if the functions are members of different 2267 // classes. In other words, for the purposes of substitution, the class of 2268 // which the function is a member is considered part of the type of 2269 // function. 2270 2271 // Given that we already substitute member function pointers as a 2272 // whole, the net effect of this rule is just to unconditionally 2273 // suppress substitution on the function type in a member pointer. 2274 // We increment the SeqID here to emulate adding an entry to the 2275 // substitution table. 2276 ++SeqID; 2277 } else 2278 mangleType(PointeeType); 2279 } 2280 2281 // <type> ::= <template-param> 2282 void CXXNameMangler::mangleType(const TemplateTypeParmType *T) { 2283 mangleTemplateParameter(T->getIndex()); 2284 } 2285 2286 // <type> ::= <template-param> 2287 void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) { 2288 // FIXME: not clear how to mangle this! 2289 // template <class T...> class A { 2290 // template <class U...> void foo(T(*)(U) x...); 2291 // }; 2292 Out << "_SUBSTPACK_"; 2293 } 2294 2295 // <type> ::= P <type> # pointer-to 2296 void CXXNameMangler::mangleType(const PointerType *T) { 2297 Out << 'P'; 2298 mangleType(T->getPointeeType()); 2299 } 2300 void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) { 2301 Out << 'P'; 2302 mangleType(T->getPointeeType()); 2303 } 2304 2305 // <type> ::= R <type> # reference-to 2306 void CXXNameMangler::mangleType(const LValueReferenceType *T) { 2307 Out << 'R'; 2308 mangleType(T->getPointeeType()); 2309 } 2310 2311 // <type> ::= O <type> # rvalue reference-to (C++0x) 2312 void CXXNameMangler::mangleType(const RValueReferenceType *T) { 2313 Out << 'O'; 2314 mangleType(T->getPointeeType()); 2315 } 2316 2317 // <type> ::= C <type> # complex pair (C 2000) 2318 void CXXNameMangler::mangleType(const ComplexType *T) { 2319 Out << 'C'; 2320 mangleType(T->getElementType()); 2321 } 2322 2323 // ARM's ABI for Neon vector types specifies that they should be mangled as 2324 // if they are structs (to match ARM's initial implementation). The 2325 // vector type must be one of the special types predefined by ARM. 2326 void CXXNameMangler::mangleNeonVectorType(const VectorType *T) { 2327 QualType EltType = T->getElementType(); 2328 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 2329 const char *EltName = nullptr; 2330 if (T->getVectorKind() == VectorType::NeonPolyVector) { 2331 switch (cast<BuiltinType>(EltType)->getKind()) { 2332 case BuiltinType::SChar: 2333 case BuiltinType::UChar: 2334 EltName = "poly8_t"; 2335 break; 2336 case BuiltinType::Short: 2337 case BuiltinType::UShort: 2338 EltName = "poly16_t"; 2339 break; 2340 case BuiltinType::ULongLong: 2341 EltName = "poly64_t"; 2342 break; 2343 default: llvm_unreachable("unexpected Neon polynomial vector element type"); 2344 } 2345 } else { 2346 switch (cast<BuiltinType>(EltType)->getKind()) { 2347 case BuiltinType::SChar: EltName = "int8_t"; break; 2348 case BuiltinType::UChar: EltName = "uint8_t"; break; 2349 case BuiltinType::Short: EltName = "int16_t"; break; 2350 case BuiltinType::UShort: EltName = "uint16_t"; break; 2351 case BuiltinType::Int: EltName = "int32_t"; break; 2352 case BuiltinType::UInt: EltName = "uint32_t"; break; 2353 case BuiltinType::LongLong: EltName = "int64_t"; break; 2354 case BuiltinType::ULongLong: EltName = "uint64_t"; break; 2355 case BuiltinType::Double: EltName = "float64_t"; break; 2356 case BuiltinType::Float: EltName = "float32_t"; break; 2357 case BuiltinType::Half: EltName = "float16_t";break; 2358 default: 2359 llvm_unreachable("unexpected Neon vector element type"); 2360 } 2361 } 2362 const char *BaseName = nullptr; 2363 unsigned BitSize = (T->getNumElements() * 2364 getASTContext().getTypeSize(EltType)); 2365 if (BitSize == 64) 2366 BaseName = "__simd64_"; 2367 else { 2368 assert(BitSize == 128 && "Neon vector type not 64 or 128 bits"); 2369 BaseName = "__simd128_"; 2370 } 2371 Out << strlen(BaseName) + strlen(EltName); 2372 Out << BaseName << EltName; 2373 } 2374 2375 static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) { 2376 switch (EltType->getKind()) { 2377 case BuiltinType::SChar: 2378 return "Int8"; 2379 case BuiltinType::Short: 2380 return "Int16"; 2381 case BuiltinType::Int: 2382 return "Int32"; 2383 case BuiltinType::Long: 2384 case BuiltinType::LongLong: 2385 return "Int64"; 2386 case BuiltinType::UChar: 2387 return "Uint8"; 2388 case BuiltinType::UShort: 2389 return "Uint16"; 2390 case BuiltinType::UInt: 2391 return "Uint32"; 2392 case BuiltinType::ULong: 2393 case BuiltinType::ULongLong: 2394 return "Uint64"; 2395 case BuiltinType::Half: 2396 return "Float16"; 2397 case BuiltinType::Float: 2398 return "Float32"; 2399 case BuiltinType::Double: 2400 return "Float64"; 2401 default: 2402 llvm_unreachable("Unexpected vector element base type"); 2403 } 2404 } 2405 2406 // AArch64's ABI for Neon vector types specifies that they should be mangled as 2407 // the equivalent internal name. The vector type must be one of the special 2408 // types predefined by ARM. 2409 void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) { 2410 QualType EltType = T->getElementType(); 2411 assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType"); 2412 unsigned BitSize = 2413 (T->getNumElements() * getASTContext().getTypeSize(EltType)); 2414 (void)BitSize; // Silence warning. 2415 2416 assert((BitSize == 64 || BitSize == 128) && 2417 "Neon vector type not 64 or 128 bits"); 2418 2419 StringRef EltName; 2420 if (T->getVectorKind() == VectorType::NeonPolyVector) { 2421 switch (cast<BuiltinType>(EltType)->getKind()) { 2422 case BuiltinType::UChar: 2423 EltName = "Poly8"; 2424 break; 2425 case BuiltinType::UShort: 2426 EltName = "Poly16"; 2427 break; 2428 case BuiltinType::ULong: 2429 case BuiltinType::ULongLong: 2430 EltName = "Poly64"; 2431 break; 2432 default: 2433 llvm_unreachable("unexpected Neon polynomial vector element type"); 2434 } 2435 } else 2436 EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType)); 2437 2438 std::string TypeName = 2439 ("__" + EltName + "x" + llvm::utostr(T->getNumElements()) + "_t").str(); 2440 Out << TypeName.length() << TypeName; 2441 } 2442 2443 // GNU extension: vector types 2444 // <type> ::= <vector-type> 2445 // <vector-type> ::= Dv <positive dimension number> _ 2446 // <extended element type> 2447 // ::= Dv [<dimension expression>] _ <element type> 2448 // <extended element type> ::= <element type> 2449 // ::= p # AltiVec vector pixel 2450 // ::= b # Altivec vector bool 2451 void CXXNameMangler::mangleType(const VectorType *T) { 2452 if ((T->getVectorKind() == VectorType::NeonVector || 2453 T->getVectorKind() == VectorType::NeonPolyVector)) { 2454 llvm::Triple Target = getASTContext().getTargetInfo().getTriple(); 2455 llvm::Triple::ArchType Arch = 2456 getASTContext().getTargetInfo().getTriple().getArch(); 2457 if ((Arch == llvm::Triple::aarch64 || 2458 Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin()) 2459 mangleAArch64NeonVectorType(T); 2460 else 2461 mangleNeonVectorType(T); 2462 return; 2463 } 2464 Out << "Dv" << T->getNumElements() << '_'; 2465 if (T->getVectorKind() == VectorType::AltiVecPixel) 2466 Out << 'p'; 2467 else if (T->getVectorKind() == VectorType::AltiVecBool) 2468 Out << 'b'; 2469 else 2470 mangleType(T->getElementType()); 2471 } 2472 void CXXNameMangler::mangleType(const ExtVectorType *T) { 2473 mangleType(static_cast<const VectorType*>(T)); 2474 } 2475 void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) { 2476 Out << "Dv"; 2477 mangleExpression(T->getSizeExpr()); 2478 Out << '_'; 2479 mangleType(T->getElementType()); 2480 } 2481 2482 void CXXNameMangler::mangleType(const PackExpansionType *T) { 2483 // <type> ::= Dp <type> # pack expansion (C++0x) 2484 Out << "Dp"; 2485 mangleType(T->getPattern()); 2486 } 2487 2488 void CXXNameMangler::mangleType(const ObjCInterfaceType *T) { 2489 mangleSourceName(T->getDecl()->getIdentifier()); 2490 } 2491 2492 void CXXNameMangler::mangleType(const ObjCObjectType *T) { 2493 // Treat __kindof as a vendor extended type qualifier. 2494 if (T->isKindOfType()) 2495 Out << "U8__kindof"; 2496 2497 if (!T->qual_empty()) { 2498 // Mangle protocol qualifiers. 2499 SmallString<64> QualStr; 2500 llvm::raw_svector_ostream QualOS(QualStr); 2501 QualOS << "objcproto"; 2502 for (const auto *I : T->quals()) { 2503 StringRef name = I->getName(); 2504 QualOS << name.size() << name; 2505 } 2506 Out << 'U' << QualStr.size() << QualStr; 2507 } 2508 2509 mangleType(T->getBaseType()); 2510 2511 if (T->isSpecialized()) { 2512 // Mangle type arguments as I <type>+ E 2513 Out << 'I'; 2514 for (auto typeArg : T->getTypeArgs()) 2515 mangleType(typeArg); 2516 Out << 'E'; 2517 } 2518 } 2519 2520 void CXXNameMangler::mangleType(const BlockPointerType *T) { 2521 Out << "U13block_pointer"; 2522 mangleType(T->getPointeeType()); 2523 } 2524 2525 void CXXNameMangler::mangleType(const InjectedClassNameType *T) { 2526 // Mangle injected class name types as if the user had written the 2527 // specialization out fully. It may not actually be possible to see 2528 // this mangling, though. 2529 mangleType(T->getInjectedSpecializationType()); 2530 } 2531 2532 void CXXNameMangler::mangleType(const TemplateSpecializationType *T) { 2533 if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) { 2534 mangleName(TD, T->getArgs(), T->getNumArgs()); 2535 } else { 2536 if (mangleSubstitution(QualType(T, 0))) 2537 return; 2538 2539 mangleTemplatePrefix(T->getTemplateName()); 2540 2541 // FIXME: GCC does not appear to mangle the template arguments when 2542 // the template in question is a dependent template name. Should we 2543 // emulate that badness? 2544 mangleTemplateArgs(T->getArgs(), T->getNumArgs()); 2545 addSubstitution(QualType(T, 0)); 2546 } 2547 } 2548 2549 void CXXNameMangler::mangleType(const DependentNameType *T) { 2550 // Proposal by cxx-abi-dev, 2014-03-26 2551 // <class-enum-type> ::= <name> # non-dependent or dependent type name or 2552 // # dependent elaborated type specifier using 2553 // # 'typename' 2554 // ::= Ts <name> # dependent elaborated type specifier using 2555 // # 'struct' or 'class' 2556 // ::= Tu <name> # dependent elaborated type specifier using 2557 // # 'union' 2558 // ::= Te <name> # dependent elaborated type specifier using 2559 // # 'enum' 2560 switch (T->getKeyword()) { 2561 case ETK_Typename: 2562 break; 2563 case ETK_Struct: 2564 case ETK_Class: 2565 case ETK_Interface: 2566 Out << "Ts"; 2567 break; 2568 case ETK_Union: 2569 Out << "Tu"; 2570 break; 2571 case ETK_Enum: 2572 Out << "Te"; 2573 break; 2574 default: 2575 llvm_unreachable("unexpected keyword for dependent type name"); 2576 } 2577 // Typename types are always nested 2578 Out << 'N'; 2579 manglePrefix(T->getQualifier()); 2580 mangleSourceName(T->getIdentifier()); 2581 Out << 'E'; 2582 } 2583 2584 void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) { 2585 // Dependently-scoped template types are nested if they have a prefix. 2586 Out << 'N'; 2587 2588 // TODO: avoid making this TemplateName. 2589 TemplateName Prefix = 2590 getASTContext().getDependentTemplateName(T->getQualifier(), 2591 T->getIdentifier()); 2592 mangleTemplatePrefix(Prefix); 2593 2594 // FIXME: GCC does not appear to mangle the template arguments when 2595 // the template in question is a dependent template name. Should we 2596 // emulate that badness? 2597 mangleTemplateArgs(T->getArgs(), T->getNumArgs()); 2598 Out << 'E'; 2599 } 2600 2601 void CXXNameMangler::mangleType(const TypeOfType *T) { 2602 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 2603 // "extension with parameters" mangling. 2604 Out << "u6typeof"; 2605 } 2606 2607 void CXXNameMangler::mangleType(const TypeOfExprType *T) { 2608 // FIXME: this is pretty unsatisfactory, but there isn't an obvious 2609 // "extension with parameters" mangling. 2610 Out << "u6typeof"; 2611 } 2612 2613 void CXXNameMangler::mangleType(const DecltypeType *T) { 2614 Expr *E = T->getUnderlyingExpr(); 2615 2616 // type ::= Dt <expression> E # decltype of an id-expression 2617 // # or class member access 2618 // ::= DT <expression> E # decltype of an expression 2619 2620 // This purports to be an exhaustive list of id-expressions and 2621 // class member accesses. Note that we do not ignore parentheses; 2622 // parentheses change the semantics of decltype for these 2623 // expressions (and cause the mangler to use the other form). 2624 if (isa<DeclRefExpr>(E) || 2625 isa<MemberExpr>(E) || 2626 isa<UnresolvedLookupExpr>(E) || 2627 isa<DependentScopeDeclRefExpr>(E) || 2628 isa<CXXDependentScopeMemberExpr>(E) || 2629 isa<UnresolvedMemberExpr>(E)) 2630 Out << "Dt"; 2631 else 2632 Out << "DT"; 2633 mangleExpression(E); 2634 Out << 'E'; 2635 } 2636 2637 void CXXNameMangler::mangleType(const UnaryTransformType *T) { 2638 // If this is dependent, we need to record that. If not, we simply 2639 // mangle it as the underlying type since they are equivalent. 2640 if (T->isDependentType()) { 2641 Out << 'U'; 2642 2643 switch (T->getUTTKind()) { 2644 case UnaryTransformType::EnumUnderlyingType: 2645 Out << "3eut"; 2646 break; 2647 } 2648 } 2649 2650 mangleType(T->getUnderlyingType()); 2651 } 2652 2653 void CXXNameMangler::mangleType(const AutoType *T) { 2654 QualType D = T->getDeducedType(); 2655 // <builtin-type> ::= Da # dependent auto 2656 if (D.isNull()) 2657 Out << (T->isDecltypeAuto() ? "Dc" : "Da"); 2658 else 2659 mangleType(D); 2660 } 2661 2662 void CXXNameMangler::mangleType(const AtomicType *T) { 2663 // <type> ::= U <source-name> <type> # vendor extended type qualifier 2664 // (Until there's a standardized mangling...) 2665 Out << "U7_Atomic"; 2666 mangleType(T->getValueType()); 2667 } 2668 2669 void CXXNameMangler::mangleIntegerLiteral(QualType T, 2670 const llvm::APSInt &Value) { 2671 // <expr-primary> ::= L <type> <value number> E # integer literal 2672 Out << 'L'; 2673 2674 mangleType(T); 2675 if (T->isBooleanType()) { 2676 // Boolean values are encoded as 0/1. 2677 Out << (Value.getBoolValue() ? '1' : '0'); 2678 } else { 2679 mangleNumber(Value); 2680 } 2681 Out << 'E'; 2682 2683 } 2684 2685 void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) { 2686 // Ignore member expressions involving anonymous unions. 2687 while (const auto *RT = Base->getType()->getAs<RecordType>()) { 2688 if (!RT->getDecl()->isAnonymousStructOrUnion()) 2689 break; 2690 const auto *ME = dyn_cast<MemberExpr>(Base); 2691 if (!ME) 2692 break; 2693 Base = ME->getBase(); 2694 IsArrow = ME->isArrow(); 2695 } 2696 2697 if (Base->isImplicitCXXThis()) { 2698 // Note: GCC mangles member expressions to the implicit 'this' as 2699 // *this., whereas we represent them as this->. The Itanium C++ ABI 2700 // does not specify anything here, so we follow GCC. 2701 Out << "dtdefpT"; 2702 } else { 2703 Out << (IsArrow ? "pt" : "dt"); 2704 mangleExpression(Base); 2705 } 2706 } 2707 2708 /// Mangles a member expression. 2709 void CXXNameMangler::mangleMemberExpr(const Expr *base, 2710 bool isArrow, 2711 NestedNameSpecifier *qualifier, 2712 NamedDecl *firstQualifierLookup, 2713 DeclarationName member, 2714 unsigned arity) { 2715 // <expression> ::= dt <expression> <unresolved-name> 2716 // ::= pt <expression> <unresolved-name> 2717 if (base) 2718 mangleMemberExprBase(base, isArrow); 2719 mangleUnresolvedName(qualifier, member, arity); 2720 } 2721 2722 /// Look at the callee of the given call expression and determine if 2723 /// it's a parenthesized id-expression which would have triggered ADL 2724 /// otherwise. 2725 static bool isParenthesizedADLCallee(const CallExpr *call) { 2726 const Expr *callee = call->getCallee(); 2727 const Expr *fn = callee->IgnoreParens(); 2728 2729 // Must be parenthesized. IgnoreParens() skips __extension__ nodes, 2730 // too, but for those to appear in the callee, it would have to be 2731 // parenthesized. 2732 if (callee == fn) return false; 2733 2734 // Must be an unresolved lookup. 2735 const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn); 2736 if (!lookup) return false; 2737 2738 assert(!lookup->requiresADL()); 2739 2740 // Must be an unqualified lookup. 2741 if (lookup->getQualifier()) return false; 2742 2743 // Must not have found a class member. Note that if one is a class 2744 // member, they're all class members. 2745 if (lookup->getNumDecls() > 0 && 2746 (*lookup->decls_begin())->isCXXClassMember()) 2747 return false; 2748 2749 // Otherwise, ADL would have been triggered. 2750 return true; 2751 } 2752 2753 void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) { 2754 const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E); 2755 Out << CastEncoding; 2756 mangleType(ECE->getType()); 2757 mangleExpression(ECE->getSubExpr()); 2758 } 2759 2760 void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) { 2761 if (auto *Syntactic = InitList->getSyntacticForm()) 2762 InitList = Syntactic; 2763 for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i) 2764 mangleExpression(InitList->getInit(i)); 2765 } 2766 2767 void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity) { 2768 // <expression> ::= <unary operator-name> <expression> 2769 // ::= <binary operator-name> <expression> <expression> 2770 // ::= <trinary operator-name> <expression> <expression> <expression> 2771 // ::= cv <type> expression # conversion with one argument 2772 // ::= cv <type> _ <expression>* E # conversion with a different number of arguments 2773 // ::= dc <type> <expression> # dynamic_cast<type> (expression) 2774 // ::= sc <type> <expression> # static_cast<type> (expression) 2775 // ::= cc <type> <expression> # const_cast<type> (expression) 2776 // ::= rc <type> <expression> # reinterpret_cast<type> (expression) 2777 // ::= st <type> # sizeof (a type) 2778 // ::= at <type> # alignof (a type) 2779 // ::= <template-param> 2780 // ::= <function-param> 2781 // ::= sr <type> <unqualified-name> # dependent name 2782 // ::= sr <type> <unqualified-name> <template-args> # dependent template-id 2783 // ::= ds <expression> <expression> # expr.*expr 2784 // ::= sZ <template-param> # size of a parameter pack 2785 // ::= sZ <function-param> # size of a function parameter pack 2786 // ::= <expr-primary> 2787 // <expr-primary> ::= L <type> <value number> E # integer literal 2788 // ::= L <type <value float> E # floating literal 2789 // ::= L <mangled-name> E # external name 2790 // ::= fpT # 'this' expression 2791 QualType ImplicitlyConvertedToType; 2792 2793 recurse: 2794 switch (E->getStmtClass()) { 2795 case Expr::NoStmtClass: 2796 #define ABSTRACT_STMT(Type) 2797 #define EXPR(Type, Base) 2798 #define STMT(Type, Base) \ 2799 case Expr::Type##Class: 2800 #include "clang/AST/StmtNodes.inc" 2801 // fallthrough 2802 2803 // These all can only appear in local or variable-initialization 2804 // contexts and so should never appear in a mangling. 2805 case Expr::AddrLabelExprClass: 2806 case Expr::DesignatedInitUpdateExprClass: 2807 case Expr::ImplicitValueInitExprClass: 2808 case Expr::NoInitExprClass: 2809 case Expr::ParenListExprClass: 2810 case Expr::LambdaExprClass: 2811 case Expr::MSPropertyRefExprClass: 2812 case Expr::TypoExprClass: // This should no longer exist in the AST by now. 2813 case Expr::OMPArraySectionExprClass: 2814 llvm_unreachable("unexpected statement kind"); 2815 2816 // FIXME: invent manglings for all these. 2817 case Expr::BlockExprClass: 2818 case Expr::ChooseExprClass: 2819 case Expr::CompoundLiteralExprClass: 2820 case Expr::DesignatedInitExprClass: 2821 case Expr::ExtVectorElementExprClass: 2822 case Expr::GenericSelectionExprClass: 2823 case Expr::ObjCEncodeExprClass: 2824 case Expr::ObjCIsaExprClass: 2825 case Expr::ObjCIvarRefExprClass: 2826 case Expr::ObjCMessageExprClass: 2827 case Expr::ObjCPropertyRefExprClass: 2828 case Expr::ObjCProtocolExprClass: 2829 case Expr::ObjCSelectorExprClass: 2830 case Expr::ObjCStringLiteralClass: 2831 case Expr::ObjCBoxedExprClass: 2832 case Expr::ObjCArrayLiteralClass: 2833 case Expr::ObjCDictionaryLiteralClass: 2834 case Expr::ObjCSubscriptRefExprClass: 2835 case Expr::ObjCIndirectCopyRestoreExprClass: 2836 case Expr::OffsetOfExprClass: 2837 case Expr::PredefinedExprClass: 2838 case Expr::ShuffleVectorExprClass: 2839 case Expr::ConvertVectorExprClass: 2840 case Expr::StmtExprClass: 2841 case Expr::TypeTraitExprClass: 2842 case Expr::ArrayTypeTraitExprClass: 2843 case Expr::ExpressionTraitExprClass: 2844 case Expr::VAArgExprClass: 2845 case Expr::CUDAKernelCallExprClass: 2846 case Expr::AsTypeExprClass: 2847 case Expr::PseudoObjectExprClass: 2848 case Expr::AtomicExprClass: 2849 { 2850 // As bad as this diagnostic is, it's better than crashing. 2851 DiagnosticsEngine &Diags = Context.getDiags(); 2852 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 2853 "cannot yet mangle expression type %0"); 2854 Diags.Report(E->getExprLoc(), DiagID) 2855 << E->getStmtClassName() << E->getSourceRange(); 2856 break; 2857 } 2858 2859 case Expr::CXXUuidofExprClass: { 2860 const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E); 2861 if (UE->isTypeOperand()) { 2862 QualType UuidT = UE->getTypeOperand(Context.getASTContext()); 2863 Out << "u8__uuidoft"; 2864 mangleType(UuidT); 2865 } else { 2866 Expr *UuidExp = UE->getExprOperand(); 2867 Out << "u8__uuidofz"; 2868 mangleExpression(UuidExp, Arity); 2869 } 2870 break; 2871 } 2872 2873 // Even gcc-4.5 doesn't mangle this. 2874 case Expr::BinaryConditionalOperatorClass: { 2875 DiagnosticsEngine &Diags = Context.getDiags(); 2876 unsigned DiagID = 2877 Diags.getCustomDiagID(DiagnosticsEngine::Error, 2878 "?: operator with omitted middle operand cannot be mangled"); 2879 Diags.Report(E->getExprLoc(), DiagID) 2880 << E->getStmtClassName() << E->getSourceRange(); 2881 break; 2882 } 2883 2884 // These are used for internal purposes and cannot be meaningfully mangled. 2885 case Expr::OpaqueValueExprClass: 2886 llvm_unreachable("cannot mangle opaque value; mangling wrong thing?"); 2887 2888 case Expr::InitListExprClass: { 2889 Out << "il"; 2890 mangleInitListElements(cast<InitListExpr>(E)); 2891 Out << "E"; 2892 break; 2893 } 2894 2895 case Expr::CXXDefaultArgExprClass: 2896 mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity); 2897 break; 2898 2899 case Expr::CXXDefaultInitExprClass: 2900 mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity); 2901 break; 2902 2903 case Expr::CXXStdInitializerListExprClass: 2904 mangleExpression(cast<CXXStdInitializerListExpr>(E)->getSubExpr(), Arity); 2905 break; 2906 2907 case Expr::SubstNonTypeTemplateParmExprClass: 2908 mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), 2909 Arity); 2910 break; 2911 2912 case Expr::UserDefinedLiteralClass: 2913 // We follow g++'s approach of mangling a UDL as a call to the literal 2914 // operator. 2915 case Expr::CXXMemberCallExprClass: // fallthrough 2916 case Expr::CallExprClass: { 2917 const CallExpr *CE = cast<CallExpr>(E); 2918 2919 // <expression> ::= cp <simple-id> <expression>* E 2920 // We use this mangling only when the call would use ADL except 2921 // for being parenthesized. Per discussion with David 2922 // Vandervoorde, 2011.04.25. 2923 if (isParenthesizedADLCallee(CE)) { 2924 Out << "cp"; 2925 // The callee here is a parenthesized UnresolvedLookupExpr with 2926 // no qualifier and should always get mangled as a <simple-id> 2927 // anyway. 2928 2929 // <expression> ::= cl <expression>* E 2930 } else { 2931 Out << "cl"; 2932 } 2933 2934 unsigned CallArity = CE->getNumArgs(); 2935 for (const Expr *Arg : CE->arguments()) 2936 if (isa<PackExpansionExpr>(Arg)) 2937 CallArity = UnknownArity; 2938 2939 mangleExpression(CE->getCallee(), CallArity); 2940 for (const Expr *Arg : CE->arguments()) 2941 mangleExpression(Arg); 2942 Out << 'E'; 2943 break; 2944 } 2945 2946 case Expr::CXXNewExprClass: { 2947 const CXXNewExpr *New = cast<CXXNewExpr>(E); 2948 if (New->isGlobalNew()) Out << "gs"; 2949 Out << (New->isArray() ? "na" : "nw"); 2950 for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(), 2951 E = New->placement_arg_end(); I != E; ++I) 2952 mangleExpression(*I); 2953 Out << '_'; 2954 mangleType(New->getAllocatedType()); 2955 if (New->hasInitializer()) { 2956 if (New->getInitializationStyle() == CXXNewExpr::ListInit) 2957 Out << "il"; 2958 else 2959 Out << "pi"; 2960 const Expr *Init = New->getInitializer(); 2961 if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) { 2962 // Directly inline the initializers. 2963 for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(), 2964 E = CCE->arg_end(); 2965 I != E; ++I) 2966 mangleExpression(*I); 2967 } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) { 2968 for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i) 2969 mangleExpression(PLE->getExpr(i)); 2970 } else if (New->getInitializationStyle() == CXXNewExpr::ListInit && 2971 isa<InitListExpr>(Init)) { 2972 // Only take InitListExprs apart for list-initialization. 2973 mangleInitListElements(cast<InitListExpr>(Init)); 2974 } else 2975 mangleExpression(Init); 2976 } 2977 Out << 'E'; 2978 break; 2979 } 2980 2981 case Expr::CXXPseudoDestructorExprClass: { 2982 const auto *PDE = cast<CXXPseudoDestructorExpr>(E); 2983 if (const Expr *Base = PDE->getBase()) 2984 mangleMemberExprBase(Base, PDE->isArrow()); 2985 NestedNameSpecifier *Qualifier = PDE->getQualifier(); 2986 QualType ScopeType; 2987 if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) { 2988 if (Qualifier) { 2989 mangleUnresolvedPrefix(Qualifier, 2990 /*Recursive=*/true); 2991 mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()); 2992 Out << 'E'; 2993 } else { 2994 Out << "sr"; 2995 if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType())) 2996 Out << 'E'; 2997 } 2998 } else if (Qualifier) { 2999 mangleUnresolvedPrefix(Qualifier); 3000 } 3001 // <base-unresolved-name> ::= dn <destructor-name> 3002 Out << "dn"; 3003 QualType DestroyedType = PDE->getDestroyedType(); 3004 mangleUnresolvedTypeOrSimpleId(DestroyedType); 3005 break; 3006 } 3007 3008 case Expr::MemberExprClass: { 3009 const MemberExpr *ME = cast<MemberExpr>(E); 3010 mangleMemberExpr(ME->getBase(), ME->isArrow(), 3011 ME->getQualifier(), nullptr, 3012 ME->getMemberDecl()->getDeclName(), Arity); 3013 break; 3014 } 3015 3016 case Expr::UnresolvedMemberExprClass: { 3017 const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E); 3018 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 3019 ME->isArrow(), ME->getQualifier(), nullptr, 3020 ME->getMemberName(), Arity); 3021 if (ME->hasExplicitTemplateArgs()) 3022 mangleTemplateArgs(ME->getExplicitTemplateArgs()); 3023 break; 3024 } 3025 3026 case Expr::CXXDependentScopeMemberExprClass: { 3027 const CXXDependentScopeMemberExpr *ME 3028 = cast<CXXDependentScopeMemberExpr>(E); 3029 mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(), 3030 ME->isArrow(), ME->getQualifier(), 3031 ME->getFirstQualifierFoundInScope(), 3032 ME->getMember(), Arity); 3033 if (ME->hasExplicitTemplateArgs()) 3034 mangleTemplateArgs(ME->getExplicitTemplateArgs()); 3035 break; 3036 } 3037 3038 case Expr::UnresolvedLookupExprClass: { 3039 const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E); 3040 mangleUnresolvedName(ULE->getQualifier(), ULE->getName(), Arity); 3041 3042 // All the <unresolved-name> productions end in a 3043 // base-unresolved-name, where <template-args> are just tacked 3044 // onto the end. 3045 if (ULE->hasExplicitTemplateArgs()) 3046 mangleTemplateArgs(ULE->getExplicitTemplateArgs()); 3047 break; 3048 } 3049 3050 case Expr::CXXUnresolvedConstructExprClass: { 3051 const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E); 3052 unsigned N = CE->arg_size(); 3053 3054 Out << "cv"; 3055 mangleType(CE->getType()); 3056 if (N != 1) Out << '_'; 3057 for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I)); 3058 if (N != 1) Out << 'E'; 3059 break; 3060 } 3061 3062 case Expr::CXXConstructExprClass: { 3063 const auto *CE = cast<CXXConstructExpr>(E); 3064 if (!CE->isListInitialization() || CE->isStdInitListInitialization()) { 3065 assert( 3066 CE->getNumArgs() >= 1 && 3067 (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) && 3068 "implicit CXXConstructExpr must have one argument"); 3069 return mangleExpression(cast<CXXConstructExpr>(E)->getArg(0)); 3070 } 3071 Out << "il"; 3072 for (auto *E : CE->arguments()) 3073 mangleExpression(E); 3074 Out << "E"; 3075 break; 3076 } 3077 3078 case Expr::CXXTemporaryObjectExprClass: { 3079 const auto *CE = cast<CXXTemporaryObjectExpr>(E); 3080 unsigned N = CE->getNumArgs(); 3081 bool List = CE->isListInitialization(); 3082 3083 if (List) 3084 Out << "tl"; 3085 else 3086 Out << "cv"; 3087 mangleType(CE->getType()); 3088 if (!List && N != 1) 3089 Out << '_'; 3090 if (CE->isStdInitListInitialization()) { 3091 // We implicitly created a std::initializer_list<T> for the first argument 3092 // of a constructor of type U in an expression of the form U{a, b, c}. 3093 // Strip all the semantic gunk off the initializer list. 3094 auto *SILE = 3095 cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit()); 3096 auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit()); 3097 mangleInitListElements(ILE); 3098 } else { 3099 for (auto *E : CE->arguments()) 3100 mangleExpression(E); 3101 } 3102 if (List || N != 1) 3103 Out << 'E'; 3104 break; 3105 } 3106 3107 case Expr::CXXScalarValueInitExprClass: 3108 Out << "cv"; 3109 mangleType(E->getType()); 3110 Out << "_E"; 3111 break; 3112 3113 case Expr::CXXNoexceptExprClass: 3114 Out << "nx"; 3115 mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand()); 3116 break; 3117 3118 case Expr::UnaryExprOrTypeTraitExprClass: { 3119 const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E); 3120 3121 if (!SAE->isInstantiationDependent()) { 3122 // Itanium C++ ABI: 3123 // If the operand of a sizeof or alignof operator is not 3124 // instantiation-dependent it is encoded as an integer literal 3125 // reflecting the result of the operator. 3126 // 3127 // If the result of the operator is implicitly converted to a known 3128 // integer type, that type is used for the literal; otherwise, the type 3129 // of std::size_t or std::ptrdiff_t is used. 3130 QualType T = (ImplicitlyConvertedToType.isNull() || 3131 !ImplicitlyConvertedToType->isIntegerType())? SAE->getType() 3132 : ImplicitlyConvertedToType; 3133 llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext()); 3134 mangleIntegerLiteral(T, V); 3135 break; 3136 } 3137 3138 switch(SAE->getKind()) { 3139 case UETT_SizeOf: 3140 Out << 's'; 3141 break; 3142 case UETT_AlignOf: 3143 Out << 'a'; 3144 break; 3145 case UETT_VecStep: { 3146 DiagnosticsEngine &Diags = Context.getDiags(); 3147 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error, 3148 "cannot yet mangle vec_step expression"); 3149 Diags.Report(DiagID); 3150 return; 3151 } 3152 case UETT_OpenMPRequiredSimdAlign: 3153 DiagnosticsEngine &Diags = Context.getDiags(); 3154 unsigned DiagID = Diags.getCustomDiagID( 3155 DiagnosticsEngine::Error, 3156 "cannot yet mangle __builtin_omp_required_simd_align expression"); 3157 Diags.Report(DiagID); 3158 return; 3159 } 3160 if (SAE->isArgumentType()) { 3161 Out << 't'; 3162 mangleType(SAE->getArgumentType()); 3163 } else { 3164 Out << 'z'; 3165 mangleExpression(SAE->getArgumentExpr()); 3166 } 3167 break; 3168 } 3169 3170 case Expr::CXXThrowExprClass: { 3171 const CXXThrowExpr *TE = cast<CXXThrowExpr>(E); 3172 // <expression> ::= tw <expression> # throw expression 3173 // ::= tr # rethrow 3174 if (TE->getSubExpr()) { 3175 Out << "tw"; 3176 mangleExpression(TE->getSubExpr()); 3177 } else { 3178 Out << "tr"; 3179 } 3180 break; 3181 } 3182 3183 case Expr::CXXTypeidExprClass: { 3184 const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E); 3185 // <expression> ::= ti <type> # typeid (type) 3186 // ::= te <expression> # typeid (expression) 3187 if (TIE->isTypeOperand()) { 3188 Out << "ti"; 3189 mangleType(TIE->getTypeOperand(Context.getASTContext())); 3190 } else { 3191 Out << "te"; 3192 mangleExpression(TIE->getExprOperand()); 3193 } 3194 break; 3195 } 3196 3197 case Expr::CXXDeleteExprClass: { 3198 const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E); 3199 // <expression> ::= [gs] dl <expression> # [::] delete expr 3200 // ::= [gs] da <expression> # [::] delete [] expr 3201 if (DE->isGlobalDelete()) Out << "gs"; 3202 Out << (DE->isArrayForm() ? "da" : "dl"); 3203 mangleExpression(DE->getArgument()); 3204 break; 3205 } 3206 3207 case Expr::UnaryOperatorClass: { 3208 const UnaryOperator *UO = cast<UnaryOperator>(E); 3209 mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()), 3210 /*Arity=*/1); 3211 mangleExpression(UO->getSubExpr()); 3212 break; 3213 } 3214 3215 case Expr::ArraySubscriptExprClass: { 3216 const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E); 3217 3218 // Array subscript is treated as a syntactically weird form of 3219 // binary operator. 3220 Out << "ix"; 3221 mangleExpression(AE->getLHS()); 3222 mangleExpression(AE->getRHS()); 3223 break; 3224 } 3225 3226 case Expr::CompoundAssignOperatorClass: // fallthrough 3227 case Expr::BinaryOperatorClass: { 3228 const BinaryOperator *BO = cast<BinaryOperator>(E); 3229 if (BO->getOpcode() == BO_PtrMemD) 3230 Out << "ds"; 3231 else 3232 mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()), 3233 /*Arity=*/2); 3234 mangleExpression(BO->getLHS()); 3235 mangleExpression(BO->getRHS()); 3236 break; 3237 } 3238 3239 case Expr::ConditionalOperatorClass: { 3240 const ConditionalOperator *CO = cast<ConditionalOperator>(E); 3241 mangleOperatorName(OO_Conditional, /*Arity=*/3); 3242 mangleExpression(CO->getCond()); 3243 mangleExpression(CO->getLHS(), Arity); 3244 mangleExpression(CO->getRHS(), Arity); 3245 break; 3246 } 3247 3248 case Expr::ImplicitCastExprClass: { 3249 ImplicitlyConvertedToType = E->getType(); 3250 E = cast<ImplicitCastExpr>(E)->getSubExpr(); 3251 goto recurse; 3252 } 3253 3254 case Expr::ObjCBridgedCastExprClass: { 3255 // Mangle ownership casts as a vendor extended operator __bridge, 3256 // __bridge_transfer, or __bridge_retain. 3257 StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName(); 3258 Out << "v1U" << Kind.size() << Kind; 3259 } 3260 // Fall through to mangle the cast itself. 3261 3262 case Expr::CStyleCastExprClass: 3263 mangleCastExpression(E, "cv"); 3264 break; 3265 3266 case Expr::CXXFunctionalCastExprClass: { 3267 auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit(); 3268 // FIXME: Add isImplicit to CXXConstructExpr. 3269 if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub)) 3270 if (CCE->getParenOrBraceRange().isInvalid()) 3271 Sub = CCE->getArg(0)->IgnoreImplicit(); 3272 if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub)) 3273 Sub = StdInitList->getSubExpr()->IgnoreImplicit(); 3274 if (auto *IL = dyn_cast<InitListExpr>(Sub)) { 3275 Out << "tl"; 3276 mangleType(E->getType()); 3277 mangleInitListElements(IL); 3278 Out << "E"; 3279 } else { 3280 mangleCastExpression(E, "cv"); 3281 } 3282 break; 3283 } 3284 3285 case Expr::CXXStaticCastExprClass: 3286 mangleCastExpression(E, "sc"); 3287 break; 3288 case Expr::CXXDynamicCastExprClass: 3289 mangleCastExpression(E, "dc"); 3290 break; 3291 case Expr::CXXReinterpretCastExprClass: 3292 mangleCastExpression(E, "rc"); 3293 break; 3294 case Expr::CXXConstCastExprClass: 3295 mangleCastExpression(E, "cc"); 3296 break; 3297 3298 case Expr::CXXOperatorCallExprClass: { 3299 const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E); 3300 unsigned NumArgs = CE->getNumArgs(); 3301 mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs); 3302 // Mangle the arguments. 3303 for (unsigned i = 0; i != NumArgs; ++i) 3304 mangleExpression(CE->getArg(i)); 3305 break; 3306 } 3307 3308 case Expr::ParenExprClass: 3309 mangleExpression(cast<ParenExpr>(E)->getSubExpr(), Arity); 3310 break; 3311 3312 case Expr::DeclRefExprClass: { 3313 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl(); 3314 3315 switch (D->getKind()) { 3316 default: 3317 // <expr-primary> ::= L <mangled-name> E # external name 3318 Out << 'L'; 3319 mangle(D); 3320 Out << 'E'; 3321 break; 3322 3323 case Decl::ParmVar: 3324 mangleFunctionParam(cast<ParmVarDecl>(D)); 3325 break; 3326 3327 case Decl::EnumConstant: { 3328 const EnumConstantDecl *ED = cast<EnumConstantDecl>(D); 3329 mangleIntegerLiteral(ED->getType(), ED->getInitVal()); 3330 break; 3331 } 3332 3333 case Decl::NonTypeTemplateParm: { 3334 const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D); 3335 mangleTemplateParameter(PD->getIndex()); 3336 break; 3337 } 3338 3339 } 3340 3341 break; 3342 } 3343 3344 case Expr::SubstNonTypeTemplateParmPackExprClass: 3345 // FIXME: not clear how to mangle this! 3346 // template <unsigned N...> class A { 3347 // template <class U...> void foo(U (&x)[N]...); 3348 // }; 3349 Out << "_SUBSTPACK_"; 3350 break; 3351 3352 case Expr::FunctionParmPackExprClass: { 3353 // FIXME: not clear how to mangle this! 3354 const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E); 3355 Out << "v110_SUBSTPACK"; 3356 mangleFunctionParam(FPPE->getParameterPack()); 3357 break; 3358 } 3359 3360 case Expr::DependentScopeDeclRefExprClass: { 3361 const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E); 3362 mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(), Arity); 3363 3364 // All the <unresolved-name> productions end in a 3365 // base-unresolved-name, where <template-args> are just tacked 3366 // onto the end. 3367 if (DRE->hasExplicitTemplateArgs()) 3368 mangleTemplateArgs(DRE->getExplicitTemplateArgs()); 3369 break; 3370 } 3371 3372 case Expr::CXXBindTemporaryExprClass: 3373 mangleExpression(cast<CXXBindTemporaryExpr>(E)->getSubExpr()); 3374 break; 3375 3376 case Expr::ExprWithCleanupsClass: 3377 mangleExpression(cast<ExprWithCleanups>(E)->getSubExpr(), Arity); 3378 break; 3379 3380 case Expr::FloatingLiteralClass: { 3381 const FloatingLiteral *FL = cast<FloatingLiteral>(E); 3382 Out << 'L'; 3383 mangleType(FL->getType()); 3384 mangleFloat(FL->getValue()); 3385 Out << 'E'; 3386 break; 3387 } 3388 3389 case Expr::CharacterLiteralClass: 3390 Out << 'L'; 3391 mangleType(E->getType()); 3392 Out << cast<CharacterLiteral>(E)->getValue(); 3393 Out << 'E'; 3394 break; 3395 3396 // FIXME. __objc_yes/__objc_no are mangled same as true/false 3397 case Expr::ObjCBoolLiteralExprClass: 3398 Out << "Lb"; 3399 Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 3400 Out << 'E'; 3401 break; 3402 3403 case Expr::CXXBoolLiteralExprClass: 3404 Out << "Lb"; 3405 Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0'); 3406 Out << 'E'; 3407 break; 3408 3409 case Expr::IntegerLiteralClass: { 3410 llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue()); 3411 if (E->getType()->isSignedIntegerType()) 3412 Value.setIsSigned(true); 3413 mangleIntegerLiteral(E->getType(), Value); 3414 break; 3415 } 3416 3417 case Expr::ImaginaryLiteralClass: { 3418 const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E); 3419 // Mangle as if a complex literal. 3420 // Proposal from David Vandevoorde, 2010.06.30. 3421 Out << 'L'; 3422 mangleType(E->getType()); 3423 if (const FloatingLiteral *Imag = 3424 dyn_cast<FloatingLiteral>(IE->getSubExpr())) { 3425 // Mangle a floating-point zero of the appropriate type. 3426 mangleFloat(llvm::APFloat(Imag->getValue().getSemantics())); 3427 Out << '_'; 3428 mangleFloat(Imag->getValue()); 3429 } else { 3430 Out << "0_"; 3431 llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue()); 3432 if (IE->getSubExpr()->getType()->isSignedIntegerType()) 3433 Value.setIsSigned(true); 3434 mangleNumber(Value); 3435 } 3436 Out << 'E'; 3437 break; 3438 } 3439 3440 case Expr::StringLiteralClass: { 3441 // Revised proposal from David Vandervoorde, 2010.07.15. 3442 Out << 'L'; 3443 assert(isa<ConstantArrayType>(E->getType())); 3444 mangleType(E->getType()); 3445 Out << 'E'; 3446 break; 3447 } 3448 3449 case Expr::GNUNullExprClass: 3450 // FIXME: should this really be mangled the same as nullptr? 3451 // fallthrough 3452 3453 case Expr::CXXNullPtrLiteralExprClass: { 3454 Out << "LDnE"; 3455 break; 3456 } 3457 3458 case Expr::PackExpansionExprClass: 3459 Out << "sp"; 3460 mangleExpression(cast<PackExpansionExpr>(E)->getPattern()); 3461 break; 3462 3463 case Expr::SizeOfPackExprClass: { 3464 auto *SPE = cast<SizeOfPackExpr>(E); 3465 if (SPE->isPartiallySubstituted()) { 3466 Out << "sP"; 3467 for (const auto &A : SPE->getPartialArguments()) 3468 mangleTemplateArg(A); 3469 Out << "E"; 3470 break; 3471 } 3472 3473 Out << "sZ"; 3474 const NamedDecl *Pack = SPE->getPack(); 3475 if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack)) 3476 mangleTemplateParameter(TTP->getIndex()); 3477 else if (const NonTypeTemplateParmDecl *NTTP 3478 = dyn_cast<NonTypeTemplateParmDecl>(Pack)) 3479 mangleTemplateParameter(NTTP->getIndex()); 3480 else if (const TemplateTemplateParmDecl *TempTP 3481 = dyn_cast<TemplateTemplateParmDecl>(Pack)) 3482 mangleTemplateParameter(TempTP->getIndex()); 3483 else 3484 mangleFunctionParam(cast<ParmVarDecl>(Pack)); 3485 break; 3486 } 3487 3488 case Expr::MaterializeTemporaryExprClass: { 3489 mangleExpression(cast<MaterializeTemporaryExpr>(E)->GetTemporaryExpr()); 3490 break; 3491 } 3492 3493 case Expr::CXXFoldExprClass: { 3494 auto *FE = cast<CXXFoldExpr>(E); 3495 if (FE->isLeftFold()) 3496 Out << (FE->getInit() ? "fL" : "fl"); 3497 else 3498 Out << (FE->getInit() ? "fR" : "fr"); 3499 3500 if (FE->getOperator() == BO_PtrMemD) 3501 Out << "ds"; 3502 else 3503 mangleOperatorName( 3504 BinaryOperator::getOverloadedOperator(FE->getOperator()), 3505 /*Arity=*/2); 3506 3507 if (FE->getLHS()) 3508 mangleExpression(FE->getLHS()); 3509 if (FE->getRHS()) 3510 mangleExpression(FE->getRHS()); 3511 break; 3512 } 3513 3514 case Expr::CXXThisExprClass: 3515 Out << "fpT"; 3516 break; 3517 } 3518 } 3519 3520 /// Mangle an expression which refers to a parameter variable. 3521 /// 3522 /// <expression> ::= <function-param> 3523 /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0 3524 /// <function-param> ::= fp <top-level CV-qualifiers> 3525 /// <parameter-2 non-negative number> _ # L == 0, I > 0 3526 /// <function-param> ::= fL <L-1 non-negative number> 3527 /// p <top-level CV-qualifiers> _ # L > 0, I == 0 3528 /// <function-param> ::= fL <L-1 non-negative number> 3529 /// p <top-level CV-qualifiers> 3530 /// <I-1 non-negative number> _ # L > 0, I > 0 3531 /// 3532 /// L is the nesting depth of the parameter, defined as 1 if the 3533 /// parameter comes from the innermost function prototype scope 3534 /// enclosing the current context, 2 if from the next enclosing 3535 /// function prototype scope, and so on, with one special case: if 3536 /// we've processed the full parameter clause for the innermost 3537 /// function type, then L is one less. This definition conveniently 3538 /// makes it irrelevant whether a function's result type was written 3539 /// trailing or leading, but is otherwise overly complicated; the 3540 /// numbering was first designed without considering references to 3541 /// parameter in locations other than return types, and then the 3542 /// mangling had to be generalized without changing the existing 3543 /// manglings. 3544 /// 3545 /// I is the zero-based index of the parameter within its parameter 3546 /// declaration clause. Note that the original ABI document describes 3547 /// this using 1-based ordinals. 3548 void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) { 3549 unsigned parmDepth = parm->getFunctionScopeDepth(); 3550 unsigned parmIndex = parm->getFunctionScopeIndex(); 3551 3552 // Compute 'L'. 3553 // parmDepth does not include the declaring function prototype. 3554 // FunctionTypeDepth does account for that. 3555 assert(parmDepth < FunctionTypeDepth.getDepth()); 3556 unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth; 3557 if (FunctionTypeDepth.isInResultType()) 3558 nestingDepth--; 3559 3560 if (nestingDepth == 0) { 3561 Out << "fp"; 3562 } else { 3563 Out << "fL" << (nestingDepth - 1) << 'p'; 3564 } 3565 3566 // Top-level qualifiers. We don't have to worry about arrays here, 3567 // because parameters declared as arrays should already have been 3568 // transformed to have pointer type. FIXME: apparently these don't 3569 // get mangled if used as an rvalue of a known non-class type? 3570 assert(!parm->getType()->isArrayType() 3571 && "parameter's type is still an array type?"); 3572 mangleQualifiers(parm->getType().getQualifiers()); 3573 3574 // Parameter index. 3575 if (parmIndex != 0) { 3576 Out << (parmIndex - 1); 3577 } 3578 Out << '_'; 3579 } 3580 3581 void CXXNameMangler::mangleCXXCtorType(CXXCtorType T) { 3582 // <ctor-dtor-name> ::= C1 # complete object constructor 3583 // ::= C2 # base object constructor 3584 // 3585 // In addition, C5 is a comdat name with C1 and C2 in it. 3586 switch (T) { 3587 case Ctor_Complete: 3588 Out << "C1"; 3589 break; 3590 case Ctor_Base: 3591 Out << "C2"; 3592 break; 3593 case Ctor_Comdat: 3594 Out << "C5"; 3595 break; 3596 case Ctor_DefaultClosure: 3597 case Ctor_CopyingClosure: 3598 llvm_unreachable("closure constructors don't exist for the Itanium ABI!"); 3599 } 3600 } 3601 3602 void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) { 3603 // <ctor-dtor-name> ::= D0 # deleting destructor 3604 // ::= D1 # complete object destructor 3605 // ::= D2 # base object destructor 3606 // 3607 // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it. 3608 switch (T) { 3609 case Dtor_Deleting: 3610 Out << "D0"; 3611 break; 3612 case Dtor_Complete: 3613 Out << "D1"; 3614 break; 3615 case Dtor_Base: 3616 Out << "D2"; 3617 break; 3618 case Dtor_Comdat: 3619 Out << "D5"; 3620 break; 3621 } 3622 } 3623 3624 void CXXNameMangler::mangleTemplateArgs( 3625 const ASTTemplateArgumentListInfo &TemplateArgs) { 3626 // <template-args> ::= I <template-arg>+ E 3627 Out << 'I'; 3628 for (unsigned i = 0, e = TemplateArgs.NumTemplateArgs; i != e; ++i) 3629 mangleTemplateArg(TemplateArgs.getTemplateArgs()[i].getArgument()); 3630 Out << 'E'; 3631 } 3632 3633 void CXXNameMangler::mangleTemplateArgs(const TemplateArgumentList &AL) { 3634 // <template-args> ::= I <template-arg>+ E 3635 Out << 'I'; 3636 for (unsigned i = 0, e = AL.size(); i != e; ++i) 3637 mangleTemplateArg(AL[i]); 3638 Out << 'E'; 3639 } 3640 3641 void CXXNameMangler::mangleTemplateArgs(const TemplateArgument *TemplateArgs, 3642 unsigned NumTemplateArgs) { 3643 // <template-args> ::= I <template-arg>+ E 3644 Out << 'I'; 3645 for (unsigned i = 0; i != NumTemplateArgs; ++i) 3646 mangleTemplateArg(TemplateArgs[i]); 3647 Out << 'E'; 3648 } 3649 3650 void CXXNameMangler::mangleTemplateArg(TemplateArgument A) { 3651 // <template-arg> ::= <type> # type or template 3652 // ::= X <expression> E # expression 3653 // ::= <expr-primary> # simple expressions 3654 // ::= J <template-arg>* E # argument pack 3655 if (!A.isInstantiationDependent() || A.isDependent()) 3656 A = Context.getASTContext().getCanonicalTemplateArgument(A); 3657 3658 switch (A.getKind()) { 3659 case TemplateArgument::Null: 3660 llvm_unreachable("Cannot mangle NULL template argument"); 3661 3662 case TemplateArgument::Type: 3663 mangleType(A.getAsType()); 3664 break; 3665 case TemplateArgument::Template: 3666 // This is mangled as <type>. 3667 mangleType(A.getAsTemplate()); 3668 break; 3669 case TemplateArgument::TemplateExpansion: 3670 // <type> ::= Dp <type> # pack expansion (C++0x) 3671 Out << "Dp"; 3672 mangleType(A.getAsTemplateOrTemplatePattern()); 3673 break; 3674 case TemplateArgument::Expression: { 3675 // It's possible to end up with a DeclRefExpr here in certain 3676 // dependent cases, in which case we should mangle as a 3677 // declaration. 3678 const Expr *E = A.getAsExpr()->IgnoreParens(); 3679 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) { 3680 const ValueDecl *D = DRE->getDecl(); 3681 if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) { 3682 Out << 'L'; 3683 mangle(D); 3684 Out << 'E'; 3685 break; 3686 } 3687 } 3688 3689 Out << 'X'; 3690 mangleExpression(E); 3691 Out << 'E'; 3692 break; 3693 } 3694 case TemplateArgument::Integral: 3695 mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral()); 3696 break; 3697 case TemplateArgument::Declaration: { 3698 // <expr-primary> ::= L <mangled-name> E # external name 3699 // Clang produces AST's where pointer-to-member-function expressions 3700 // and pointer-to-function expressions are represented as a declaration not 3701 // an expression. We compensate for it here to produce the correct mangling. 3702 ValueDecl *D = A.getAsDecl(); 3703 bool compensateMangling = !A.getParamTypeForDecl()->isReferenceType(); 3704 if (compensateMangling) { 3705 Out << 'X'; 3706 mangleOperatorName(OO_Amp, 1); 3707 } 3708 3709 Out << 'L'; 3710 // References to external entities use the mangled name; if the name would 3711 // not normally be manged then mangle it as unqualified. 3712 mangle(D); 3713 Out << 'E'; 3714 3715 if (compensateMangling) 3716 Out << 'E'; 3717 3718 break; 3719 } 3720 case TemplateArgument::NullPtr: { 3721 // <expr-primary> ::= L <type> 0 E 3722 Out << 'L'; 3723 mangleType(A.getNullPtrType()); 3724 Out << "0E"; 3725 break; 3726 } 3727 case TemplateArgument::Pack: { 3728 // <template-arg> ::= J <template-arg>* E 3729 Out << 'J'; 3730 for (const auto &P : A.pack_elements()) 3731 mangleTemplateArg(P); 3732 Out << 'E'; 3733 } 3734 } 3735 } 3736 3737 void CXXNameMangler::mangleTemplateParameter(unsigned Index) { 3738 // <template-param> ::= T_ # first template parameter 3739 // ::= T <parameter-2 non-negative number> _ 3740 if (Index == 0) 3741 Out << "T_"; 3742 else 3743 Out << 'T' << (Index - 1) << '_'; 3744 } 3745 3746 void CXXNameMangler::mangleSeqID(unsigned SeqID) { 3747 if (SeqID == 1) 3748 Out << '0'; 3749 else if (SeqID > 1) { 3750 SeqID--; 3751 3752 // <seq-id> is encoded in base-36, using digits and upper case letters. 3753 char Buffer[7]; // log(2**32) / log(36) ~= 7 3754 MutableArrayRef<char> BufferRef(Buffer); 3755 MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin(); 3756 3757 for (; SeqID != 0; SeqID /= 36) { 3758 unsigned C = SeqID % 36; 3759 *I++ = (C < 10 ? '0' + C : 'A' + C - 10); 3760 } 3761 3762 Out.write(I.base(), I - BufferRef.rbegin()); 3763 } 3764 Out << '_'; 3765 } 3766 3767 void CXXNameMangler::mangleExistingSubstitution(QualType type) { 3768 bool result = mangleSubstitution(type); 3769 assert(result && "no existing substitution for type"); 3770 (void) result; 3771 } 3772 3773 void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) { 3774 bool result = mangleSubstitution(tname); 3775 assert(result && "no existing substitution for template name"); 3776 (void) result; 3777 } 3778 3779 // <substitution> ::= S <seq-id> _ 3780 // ::= S_ 3781 bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) { 3782 // Try one of the standard substitutions first. 3783 if (mangleStandardSubstitution(ND)) 3784 return true; 3785 3786 ND = cast<NamedDecl>(ND->getCanonicalDecl()); 3787 return mangleSubstitution(reinterpret_cast<uintptr_t>(ND)); 3788 } 3789 3790 /// Determine whether the given type has any qualifiers that are relevant for 3791 /// substitutions. 3792 static bool hasMangledSubstitutionQualifiers(QualType T) { 3793 Qualifiers Qs = T.getQualifiers(); 3794 return Qs.getCVRQualifiers() || Qs.hasAddressSpace(); 3795 } 3796 3797 bool CXXNameMangler::mangleSubstitution(QualType T) { 3798 if (!hasMangledSubstitutionQualifiers(T)) { 3799 if (const RecordType *RT = T->getAs<RecordType>()) 3800 return mangleSubstitution(RT->getDecl()); 3801 } 3802 3803 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 3804 3805 return mangleSubstitution(TypePtr); 3806 } 3807 3808 bool CXXNameMangler::mangleSubstitution(TemplateName Template) { 3809 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 3810 return mangleSubstitution(TD); 3811 3812 Template = Context.getASTContext().getCanonicalTemplateName(Template); 3813 return mangleSubstitution( 3814 reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 3815 } 3816 3817 bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) { 3818 llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr); 3819 if (I == Substitutions.end()) 3820 return false; 3821 3822 unsigned SeqID = I->second; 3823 Out << 'S'; 3824 mangleSeqID(SeqID); 3825 3826 return true; 3827 } 3828 3829 static bool isCharType(QualType T) { 3830 if (T.isNull()) 3831 return false; 3832 3833 return T->isSpecificBuiltinType(BuiltinType::Char_S) || 3834 T->isSpecificBuiltinType(BuiltinType::Char_U); 3835 } 3836 3837 /// Returns whether a given type is a template specialization of a given name 3838 /// with a single argument of type char. 3839 static bool isCharSpecialization(QualType T, const char *Name) { 3840 if (T.isNull()) 3841 return false; 3842 3843 const RecordType *RT = T->getAs<RecordType>(); 3844 if (!RT) 3845 return false; 3846 3847 const ClassTemplateSpecializationDecl *SD = 3848 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl()); 3849 if (!SD) 3850 return false; 3851 3852 if (!isStdNamespace(getEffectiveDeclContext(SD))) 3853 return false; 3854 3855 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 3856 if (TemplateArgs.size() != 1) 3857 return false; 3858 3859 if (!isCharType(TemplateArgs[0].getAsType())) 3860 return false; 3861 3862 return SD->getIdentifier()->getName() == Name; 3863 } 3864 3865 template <std::size_t StrLen> 3866 static bool isStreamCharSpecialization(const ClassTemplateSpecializationDecl*SD, 3867 const char (&Str)[StrLen]) { 3868 if (!SD->getIdentifier()->isStr(Str)) 3869 return false; 3870 3871 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 3872 if (TemplateArgs.size() != 2) 3873 return false; 3874 3875 if (!isCharType(TemplateArgs[0].getAsType())) 3876 return false; 3877 3878 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 3879 return false; 3880 3881 return true; 3882 } 3883 3884 bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) { 3885 // <substitution> ::= St # ::std:: 3886 if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) { 3887 if (isStd(NS)) { 3888 Out << "St"; 3889 return true; 3890 } 3891 } 3892 3893 if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) { 3894 if (!isStdNamespace(getEffectiveDeclContext(TD))) 3895 return false; 3896 3897 // <substitution> ::= Sa # ::std::allocator 3898 if (TD->getIdentifier()->isStr("allocator")) { 3899 Out << "Sa"; 3900 return true; 3901 } 3902 3903 // <<substitution> ::= Sb # ::std::basic_string 3904 if (TD->getIdentifier()->isStr("basic_string")) { 3905 Out << "Sb"; 3906 return true; 3907 } 3908 } 3909 3910 if (const ClassTemplateSpecializationDecl *SD = 3911 dyn_cast<ClassTemplateSpecializationDecl>(ND)) { 3912 if (!isStdNamespace(getEffectiveDeclContext(SD))) 3913 return false; 3914 3915 // <substitution> ::= Ss # ::std::basic_string<char, 3916 // ::std::char_traits<char>, 3917 // ::std::allocator<char> > 3918 if (SD->getIdentifier()->isStr("basic_string")) { 3919 const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs(); 3920 3921 if (TemplateArgs.size() != 3) 3922 return false; 3923 3924 if (!isCharType(TemplateArgs[0].getAsType())) 3925 return false; 3926 3927 if (!isCharSpecialization(TemplateArgs[1].getAsType(), "char_traits")) 3928 return false; 3929 3930 if (!isCharSpecialization(TemplateArgs[2].getAsType(), "allocator")) 3931 return false; 3932 3933 Out << "Ss"; 3934 return true; 3935 } 3936 3937 // <substitution> ::= Si # ::std::basic_istream<char, 3938 // ::std::char_traits<char> > 3939 if (isStreamCharSpecialization(SD, "basic_istream")) { 3940 Out << "Si"; 3941 return true; 3942 } 3943 3944 // <substitution> ::= So # ::std::basic_ostream<char, 3945 // ::std::char_traits<char> > 3946 if (isStreamCharSpecialization(SD, "basic_ostream")) { 3947 Out << "So"; 3948 return true; 3949 } 3950 3951 // <substitution> ::= Sd # ::std::basic_iostream<char, 3952 // ::std::char_traits<char> > 3953 if (isStreamCharSpecialization(SD, "basic_iostream")) { 3954 Out << "Sd"; 3955 return true; 3956 } 3957 } 3958 return false; 3959 } 3960 3961 void CXXNameMangler::addSubstitution(QualType T) { 3962 if (!hasMangledSubstitutionQualifiers(T)) { 3963 if (const RecordType *RT = T->getAs<RecordType>()) { 3964 addSubstitution(RT->getDecl()); 3965 return; 3966 } 3967 } 3968 3969 uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr()); 3970 addSubstitution(TypePtr); 3971 } 3972 3973 void CXXNameMangler::addSubstitution(TemplateName Template) { 3974 if (TemplateDecl *TD = Template.getAsTemplateDecl()) 3975 return addSubstitution(TD); 3976 3977 Template = Context.getASTContext().getCanonicalTemplateName(Template); 3978 addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer())); 3979 } 3980 3981 void CXXNameMangler::addSubstitution(uintptr_t Ptr) { 3982 assert(!Substitutions.count(Ptr) && "Substitution already exists!"); 3983 Substitutions[Ptr] = SeqID++; 3984 } 3985 3986 // 3987 3988 /// Mangles the name of the declaration D and emits that name to the given 3989 /// output stream. 3990 /// 3991 /// If the declaration D requires a mangled name, this routine will emit that 3992 /// mangled name to \p os and return true. Otherwise, \p os will be unchanged 3993 /// and this routine will return false. In this case, the caller should just 3994 /// emit the identifier of the declaration (\c D->getIdentifier()) as its 3995 /// name. 3996 void ItaniumMangleContextImpl::mangleCXXName(const NamedDecl *D, 3997 raw_ostream &Out) { 3998 assert((isa<FunctionDecl>(D) || isa<VarDecl>(D)) && 3999 "Invalid mangleName() call, argument is not a variable or function!"); 4000 assert(!isa<CXXConstructorDecl>(D) && !isa<CXXDestructorDecl>(D) && 4001 "Invalid mangleName() call on 'structor decl!"); 4002 4003 PrettyStackTraceDecl CrashInfo(D, SourceLocation(), 4004 getASTContext().getSourceManager(), 4005 "Mangling declaration"); 4006 4007 CXXNameMangler Mangler(*this, Out, D); 4008 Mangler.mangle(D); 4009 } 4010 4011 void ItaniumMangleContextImpl::mangleCXXCtor(const CXXConstructorDecl *D, 4012 CXXCtorType Type, 4013 raw_ostream &Out) { 4014 CXXNameMangler Mangler(*this, Out, D, Type); 4015 Mangler.mangle(D); 4016 } 4017 4018 void ItaniumMangleContextImpl::mangleCXXDtor(const CXXDestructorDecl *D, 4019 CXXDtorType Type, 4020 raw_ostream &Out) { 4021 CXXNameMangler Mangler(*this, Out, D, Type); 4022 Mangler.mangle(D); 4023 } 4024 4025 void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D, 4026 raw_ostream &Out) { 4027 CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat); 4028 Mangler.mangle(D); 4029 } 4030 4031 void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D, 4032 raw_ostream &Out) { 4033 CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat); 4034 Mangler.mangle(D); 4035 } 4036 4037 void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD, 4038 const ThunkInfo &Thunk, 4039 raw_ostream &Out) { 4040 // <special-name> ::= T <call-offset> <base encoding> 4041 // # base is the nominal target function of thunk 4042 // <special-name> ::= Tc <call-offset> <call-offset> <base encoding> 4043 // # base is the nominal target function of thunk 4044 // # first call-offset is 'this' adjustment 4045 // # second call-offset is result adjustment 4046 4047 assert(!isa<CXXDestructorDecl>(MD) && 4048 "Use mangleCXXDtor for destructor decls!"); 4049 CXXNameMangler Mangler(*this, Out); 4050 Mangler.getStream() << "_ZT"; 4051 if (!Thunk.Return.isEmpty()) 4052 Mangler.getStream() << 'c'; 4053 4054 // Mangle the 'this' pointer adjustment. 4055 Mangler.mangleCallOffset(Thunk.This.NonVirtual, 4056 Thunk.This.Virtual.Itanium.VCallOffsetOffset); 4057 4058 // Mangle the return pointer adjustment if there is one. 4059 if (!Thunk.Return.isEmpty()) 4060 Mangler.mangleCallOffset(Thunk.Return.NonVirtual, 4061 Thunk.Return.Virtual.Itanium.VBaseOffsetOffset); 4062 4063 Mangler.mangleFunctionEncoding(MD); 4064 } 4065 4066 void ItaniumMangleContextImpl::mangleCXXDtorThunk( 4067 const CXXDestructorDecl *DD, CXXDtorType Type, 4068 const ThisAdjustment &ThisAdjustment, raw_ostream &Out) { 4069 // <special-name> ::= T <call-offset> <base encoding> 4070 // # base is the nominal target function of thunk 4071 CXXNameMangler Mangler(*this, Out, DD, Type); 4072 Mangler.getStream() << "_ZT"; 4073 4074 // Mangle the 'this' pointer adjustment. 4075 Mangler.mangleCallOffset(ThisAdjustment.NonVirtual, 4076 ThisAdjustment.Virtual.Itanium.VCallOffsetOffset); 4077 4078 Mangler.mangleFunctionEncoding(DD); 4079 } 4080 4081 /// Returns the mangled name for a guard variable for the passed in VarDecl. 4082 void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D, 4083 raw_ostream &Out) { 4084 // <special-name> ::= GV <object name> # Guard variable for one-time 4085 // # initialization 4086 CXXNameMangler Mangler(*this, Out); 4087 Mangler.getStream() << "_ZGV"; 4088 Mangler.mangleName(D); 4089 } 4090 4091 void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD, 4092 raw_ostream &Out) { 4093 // These symbols are internal in the Itanium ABI, so the names don't matter. 4094 // Clang has traditionally used this symbol and allowed LLVM to adjust it to 4095 // avoid duplicate symbols. 4096 Out << "__cxx_global_var_init"; 4097 } 4098 4099 void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D, 4100 raw_ostream &Out) { 4101 // Prefix the mangling of D with __dtor_. 4102 CXXNameMangler Mangler(*this, Out); 4103 Mangler.getStream() << "__dtor_"; 4104 if (shouldMangleDeclName(D)) 4105 Mangler.mangle(D); 4106 else 4107 Mangler.getStream() << D->getName(); 4108 } 4109 4110 void ItaniumMangleContextImpl::mangleSEHFilterExpression( 4111 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 4112 CXXNameMangler Mangler(*this, Out); 4113 Mangler.getStream() << "__filt_"; 4114 if (shouldMangleDeclName(EnclosingDecl)) 4115 Mangler.mangle(EnclosingDecl); 4116 else 4117 Mangler.getStream() << EnclosingDecl->getName(); 4118 } 4119 4120 void ItaniumMangleContextImpl::mangleSEHFinallyBlock( 4121 const NamedDecl *EnclosingDecl, raw_ostream &Out) { 4122 CXXNameMangler Mangler(*this, Out); 4123 Mangler.getStream() << "__fin_"; 4124 if (shouldMangleDeclName(EnclosingDecl)) 4125 Mangler.mangle(EnclosingDecl); 4126 else 4127 Mangler.getStream() << EnclosingDecl->getName(); 4128 } 4129 4130 void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D, 4131 raw_ostream &Out) { 4132 // <special-name> ::= TH <object name> 4133 CXXNameMangler Mangler(*this, Out); 4134 Mangler.getStream() << "_ZTH"; 4135 Mangler.mangleName(D); 4136 } 4137 4138 void 4139 ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D, 4140 raw_ostream &Out) { 4141 // <special-name> ::= TW <object name> 4142 CXXNameMangler Mangler(*this, Out); 4143 Mangler.getStream() << "_ZTW"; 4144 Mangler.mangleName(D); 4145 } 4146 4147 void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D, 4148 unsigned ManglingNumber, 4149 raw_ostream &Out) { 4150 // We match the GCC mangling here. 4151 // <special-name> ::= GR <object name> 4152 CXXNameMangler Mangler(*this, Out); 4153 Mangler.getStream() << "_ZGR"; 4154 Mangler.mangleName(D); 4155 assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!"); 4156 Mangler.mangleSeqID(ManglingNumber - 1); 4157 } 4158 4159 void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD, 4160 raw_ostream &Out) { 4161 // <special-name> ::= TV <type> # virtual table 4162 CXXNameMangler Mangler(*this, Out); 4163 Mangler.getStream() << "_ZTV"; 4164 Mangler.mangleNameOrStandardSubstitution(RD); 4165 } 4166 4167 void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD, 4168 raw_ostream &Out) { 4169 // <special-name> ::= TT <type> # VTT structure 4170 CXXNameMangler Mangler(*this, Out); 4171 Mangler.getStream() << "_ZTT"; 4172 Mangler.mangleNameOrStandardSubstitution(RD); 4173 } 4174 4175 void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD, 4176 int64_t Offset, 4177 const CXXRecordDecl *Type, 4178 raw_ostream &Out) { 4179 // <special-name> ::= TC <type> <offset number> _ <base type> 4180 CXXNameMangler Mangler(*this, Out); 4181 Mangler.getStream() << "_ZTC"; 4182 Mangler.mangleNameOrStandardSubstitution(RD); 4183 Mangler.getStream() << Offset; 4184 Mangler.getStream() << '_'; 4185 Mangler.mangleNameOrStandardSubstitution(Type); 4186 } 4187 4188 void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) { 4189 // <special-name> ::= TI <type> # typeinfo structure 4190 assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers"); 4191 CXXNameMangler Mangler(*this, Out); 4192 Mangler.getStream() << "_ZTI"; 4193 Mangler.mangleType(Ty); 4194 } 4195 4196 void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty, 4197 raw_ostream &Out) { 4198 // <special-name> ::= TS <type> # typeinfo name (null terminated byte string) 4199 CXXNameMangler Mangler(*this, Out); 4200 Mangler.getStream() << "_ZTS"; 4201 Mangler.mangleType(Ty); 4202 } 4203 4204 void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) { 4205 mangleCXXRTTIName(Ty, Out); 4206 } 4207 4208 void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) { 4209 llvm_unreachable("Can't mangle string literals"); 4210 } 4211 4212 ItaniumMangleContext * 4213 ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags) { 4214 return new ItaniumMangleContextImpl(Context, Diags); 4215 } 4216 4217