ItaniumMangle.cpp 170 KB

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