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