ItaniumMangle.cpp 172 KB

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