ItaniumMangle.cpp 174 KB

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