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