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