ItaniumMangle.cpp 224 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576
  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/ASTContext.h"
  17. #include "clang/AST/Attr.h"
  18. #include "clang/AST/Decl.h"
  19. #include "clang/AST/DeclCXX.h"
  20. #include "clang/AST/DeclObjC.h"
  21. #include "clang/AST/DeclOpenMP.h"
  22. #include "clang/AST/DeclTemplate.h"
  23. #include "clang/AST/Expr.h"
  24. #include "clang/AST/ExprCXX.h"
  25. #include "clang/AST/ExprConcepts.h"
  26. #include "clang/AST/ExprObjC.h"
  27. #include "clang/AST/Mangle.h"
  28. #include "clang/AST/TypeLoc.h"
  29. #include "clang/Basic/ABI.h"
  30. #include "clang/Basic/Module.h"
  31. #include "clang/Basic/SourceManager.h"
  32. #include "clang/Basic/TargetInfo.h"
  33. #include "clang/Basic/Thunk.h"
  34. #include "llvm/ADT/StringExtras.h"
  35. #include "llvm/Support/ErrorHandling.h"
  36. #include "llvm/Support/raw_ostream.h"
  37. #include <optional>
  38. using namespace clang;
  39. namespace {
  40. static bool isLocalContainerContext(const DeclContext *DC) {
  41. return isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC) || isa<BlockDecl>(DC);
  42. }
  43. static const FunctionDecl *getStructor(const FunctionDecl *fn) {
  44. if (const FunctionTemplateDecl *ftd = fn->getPrimaryTemplate())
  45. return ftd->getTemplatedDecl();
  46. return fn;
  47. }
  48. static const NamedDecl *getStructor(const NamedDecl *decl) {
  49. const FunctionDecl *fn = dyn_cast_or_null<FunctionDecl>(decl);
  50. return (fn ? getStructor(fn) : decl);
  51. }
  52. static bool isLambda(const NamedDecl *ND) {
  53. const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(ND);
  54. if (!Record)
  55. return false;
  56. return Record->isLambda();
  57. }
  58. static const unsigned UnknownArity = ~0U;
  59. class ItaniumMangleContextImpl : public ItaniumMangleContext {
  60. typedef std::pair<const DeclContext*, IdentifierInfo*> DiscriminatorKeyTy;
  61. llvm::DenseMap<DiscriminatorKeyTy, unsigned> Discriminator;
  62. llvm::DenseMap<const NamedDecl*, unsigned> Uniquifier;
  63. const DiscriminatorOverrideTy DiscriminatorOverride = nullptr;
  64. NamespaceDecl *StdNamespace = nullptr;
  65. bool NeedsUniqueInternalLinkageNames = false;
  66. public:
  67. explicit ItaniumMangleContextImpl(
  68. ASTContext &Context, DiagnosticsEngine &Diags,
  69. DiscriminatorOverrideTy DiscriminatorOverride, bool IsAux = false)
  70. : ItaniumMangleContext(Context, Diags, IsAux),
  71. DiscriminatorOverride(DiscriminatorOverride) {}
  72. /// @name Mangler Entry Points
  73. /// @{
  74. bool shouldMangleCXXName(const NamedDecl *D) override;
  75. bool shouldMangleStringLiteral(const StringLiteral *) override {
  76. return false;
  77. }
  78. bool isUniqueInternalLinkageDecl(const NamedDecl *ND) override;
  79. void needsUniqueInternalLinkageNames() override {
  80. NeedsUniqueInternalLinkageNames = true;
  81. }
  82. void mangleCXXName(GlobalDecl GD, raw_ostream &) override;
  83. void mangleThunk(const CXXMethodDecl *MD, const ThunkInfo &Thunk,
  84. raw_ostream &) override;
  85. void mangleCXXDtorThunk(const CXXDestructorDecl *DD, CXXDtorType Type,
  86. const ThisAdjustment &ThisAdjustment,
  87. raw_ostream &) override;
  88. void mangleReferenceTemporary(const VarDecl *D, unsigned ManglingNumber,
  89. raw_ostream &) override;
  90. void mangleCXXVTable(const CXXRecordDecl *RD, raw_ostream &) override;
  91. void mangleCXXVTT(const CXXRecordDecl *RD, raw_ostream &) override;
  92. void mangleCXXCtorVTable(const CXXRecordDecl *RD, int64_t Offset,
  93. const CXXRecordDecl *Type, raw_ostream &) override;
  94. void mangleCXXRTTI(QualType T, raw_ostream &) override;
  95. void mangleCXXRTTIName(QualType T, raw_ostream &) override;
  96. void mangleTypeName(QualType T, raw_ostream &) override;
  97. void mangleCXXCtorComdat(const CXXConstructorDecl *D, raw_ostream &) override;
  98. void mangleCXXDtorComdat(const CXXDestructorDecl *D, raw_ostream &) override;
  99. void mangleStaticGuardVariable(const VarDecl *D, raw_ostream &) override;
  100. void mangleDynamicInitializer(const VarDecl *D, raw_ostream &Out) override;
  101. void mangleDynamicAtExitDestructor(const VarDecl *D,
  102. raw_ostream &Out) override;
  103. void mangleDynamicStermFinalizer(const VarDecl *D, raw_ostream &Out) override;
  104. void mangleSEHFilterExpression(GlobalDecl EnclosingDecl,
  105. raw_ostream &Out) override;
  106. void mangleSEHFinallyBlock(GlobalDecl EnclosingDecl,
  107. raw_ostream &Out) override;
  108. void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &) override;
  109. void mangleItaniumThreadLocalWrapper(const VarDecl *D,
  110. raw_ostream &) override;
  111. void mangleStringLiteral(const StringLiteral *, raw_ostream &) override;
  112. void mangleLambdaSig(const CXXRecordDecl *Lambda, raw_ostream &) override;
  113. void mangleModuleInitializer(const Module *Module, raw_ostream &) override;
  114. bool getNextDiscriminator(const NamedDecl *ND, unsigned &disc) {
  115. // Lambda closure types are already numbered.
  116. if (isLambda(ND))
  117. return false;
  118. // Anonymous tags are already numbered.
  119. if (const TagDecl *Tag = dyn_cast<TagDecl>(ND)) {
  120. if (Tag->getName().empty() && !Tag->getTypedefNameForAnonDecl())
  121. return false;
  122. }
  123. // Use the canonical number for externally visible decls.
  124. if (ND->isExternallyVisible()) {
  125. unsigned discriminator = getASTContext().getManglingNumber(ND, isAux());
  126. if (discriminator == 1)
  127. return false;
  128. disc = discriminator - 2;
  129. return true;
  130. }
  131. // Make up a reasonable number for internal decls.
  132. unsigned &discriminator = Uniquifier[ND];
  133. if (!discriminator) {
  134. const DeclContext *DC = getEffectiveDeclContext(ND);
  135. discriminator = ++Discriminator[std::make_pair(DC, ND->getIdentifier())];
  136. }
  137. if (discriminator == 1)
  138. return false;
  139. disc = discriminator-2;
  140. return true;
  141. }
  142. std::string getLambdaString(const CXXRecordDecl *Lambda) override {
  143. // This function matches the one in MicrosoftMangle, which returns
  144. // the string that is used in lambda mangled names.
  145. assert(Lambda->isLambda() && "RD must be a lambda!");
  146. std::string Name("<lambda");
  147. Decl *LambdaContextDecl = Lambda->getLambdaContextDecl();
  148. unsigned LambdaManglingNumber = Lambda->getLambdaManglingNumber();
  149. unsigned LambdaId;
  150. const ParmVarDecl *Parm = dyn_cast_or_null<ParmVarDecl>(LambdaContextDecl);
  151. const FunctionDecl *Func =
  152. Parm ? dyn_cast<FunctionDecl>(Parm->getDeclContext()) : nullptr;
  153. if (Func) {
  154. unsigned DefaultArgNo =
  155. Func->getNumParams() - Parm->getFunctionScopeIndex();
  156. Name += llvm::utostr(DefaultArgNo);
  157. Name += "_";
  158. }
  159. if (LambdaManglingNumber)
  160. LambdaId = LambdaManglingNumber;
  161. else
  162. LambdaId = getAnonymousStructIdForDebugInfo(Lambda);
  163. Name += llvm::utostr(LambdaId);
  164. Name += '>';
  165. return Name;
  166. }
  167. DiscriminatorOverrideTy getDiscriminatorOverride() const override {
  168. return DiscriminatorOverride;
  169. }
  170. NamespaceDecl *getStdNamespace();
  171. const DeclContext *getEffectiveDeclContext(const Decl *D);
  172. const DeclContext *getEffectiveParentContext(const DeclContext *DC) {
  173. return getEffectiveDeclContext(cast<Decl>(DC));
  174. }
  175. bool isInternalLinkageDecl(const NamedDecl *ND);
  176. const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC);
  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 = 0;
  194. /// The next substitution sequence number.
  195. unsigned SeqID = 0;
  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. bool isStd(const NamespaceDecl *NS);
  323. bool isStdNamespace(const DeclContext *DC);
  324. const RecordDecl *GetLocalClassDecl(const Decl *D);
  325. const DeclContext *IgnoreLinkageSpecDecls(const DeclContext *DC);
  326. bool isSpecializedAs(QualType S, llvm::StringRef Name, QualType A);
  327. bool isStdCharSpecialization(const ClassTemplateSpecializationDecl *SD,
  328. llvm::StringRef Name, bool HasAllocator);
  329. public:
  330. CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
  331. const NamedDecl *D = nullptr, bool NullOut_ = false)
  332. : Context(C), Out(Out_), NullOut(NullOut_), Structor(getStructor(D)),
  333. AbiTagsRoot(AbiTags) {
  334. // These can't be mangled without a ctor type or dtor type.
  335. assert(!D || (!isa<CXXDestructorDecl>(D) &&
  336. !isa<CXXConstructorDecl>(D)));
  337. }
  338. CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
  339. const CXXConstructorDecl *D, CXXCtorType Type)
  340. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
  341. AbiTagsRoot(AbiTags) {}
  342. CXXNameMangler(ItaniumMangleContextImpl &C, raw_ostream &Out_,
  343. const CXXDestructorDecl *D, CXXDtorType Type)
  344. : Context(C), Out(Out_), Structor(getStructor(D)), StructorType(Type),
  345. AbiTagsRoot(AbiTags) {}
  346. CXXNameMangler(CXXNameMangler &Outer, raw_ostream &Out_)
  347. : Context(Outer.Context), Out(Out_), Structor(Outer.Structor),
  348. StructorType(Outer.StructorType), SeqID(Outer.SeqID),
  349. FunctionTypeDepth(Outer.FunctionTypeDepth), AbiTagsRoot(AbiTags),
  350. Substitutions(Outer.Substitutions),
  351. ModuleSubstitutions(Outer.ModuleSubstitutions) {}
  352. CXXNameMangler(CXXNameMangler &Outer, llvm::raw_null_ostream &Out_)
  353. : CXXNameMangler(Outer, (raw_ostream &)Out_) {
  354. NullOut = true;
  355. }
  356. raw_ostream &getStream() { return Out; }
  357. void disableDerivedAbiTags() { DisableDerivedAbiTags = true; }
  358. static bool shouldHaveAbiTags(ItaniumMangleContextImpl &C, const VarDecl *VD);
  359. void mangle(GlobalDecl GD);
  360. void mangleCallOffset(int64_t NonVirtual, int64_t Virtual);
  361. void mangleNumber(const llvm::APSInt &I);
  362. void mangleNumber(int64_t Number);
  363. void mangleFloat(const llvm::APFloat &F);
  364. void mangleFunctionEncoding(GlobalDecl GD);
  365. void mangleSeqID(unsigned SeqID);
  366. void mangleName(GlobalDecl GD);
  367. void mangleType(QualType T);
  368. void mangleNameOrStandardSubstitution(const NamedDecl *ND);
  369. void mangleLambdaSig(const CXXRecordDecl *Lambda);
  370. void mangleModuleNamePrefix(StringRef Name, bool IsPartition = false);
  371. private:
  372. bool mangleSubstitution(const NamedDecl *ND);
  373. bool mangleSubstitution(NestedNameSpecifier *NNS);
  374. bool mangleSubstitution(QualType T);
  375. bool mangleSubstitution(TemplateName Template);
  376. bool mangleSubstitution(uintptr_t Ptr);
  377. void mangleExistingSubstitution(TemplateName name);
  378. bool mangleStandardSubstitution(const NamedDecl *ND);
  379. void addSubstitution(const NamedDecl *ND) {
  380. ND = cast<NamedDecl>(ND->getCanonicalDecl());
  381. addSubstitution(reinterpret_cast<uintptr_t>(ND));
  382. }
  383. void addSubstitution(NestedNameSpecifier *NNS) {
  384. NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
  385. addSubstitution(reinterpret_cast<uintptr_t>(NNS));
  386. }
  387. void addSubstitution(QualType T);
  388. void addSubstitution(TemplateName Template);
  389. void addSubstitution(uintptr_t Ptr);
  390. // Destructive copy substitutions from other mangler.
  391. void extendSubstitutions(CXXNameMangler* Other);
  392. void mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
  393. bool recursive = false);
  394. void mangleUnresolvedName(NestedNameSpecifier *qualifier,
  395. DeclarationName name,
  396. const TemplateArgumentLoc *TemplateArgs,
  397. unsigned NumTemplateArgs,
  398. unsigned KnownArity = UnknownArity);
  399. void mangleFunctionEncodingBareType(const FunctionDecl *FD);
  400. void mangleNameWithAbiTags(GlobalDecl GD,
  401. const AbiTagList *AdditionalAbiTags);
  402. void mangleModuleName(const NamedDecl *ND);
  403. void mangleTemplateName(const TemplateDecl *TD,
  404. ArrayRef<TemplateArgument> Args);
  405. void mangleUnqualifiedName(GlobalDecl GD, const DeclContext *DC,
  406. const AbiTagList *AdditionalAbiTags) {
  407. mangleUnqualifiedName(GD, cast<NamedDecl>(GD.getDecl())->getDeclName(), DC,
  408. UnknownArity, AdditionalAbiTags);
  409. }
  410. void mangleUnqualifiedName(GlobalDecl GD, DeclarationName Name,
  411. const DeclContext *DC, unsigned KnownArity,
  412. const AbiTagList *AdditionalAbiTags);
  413. void mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
  414. const AbiTagList *AdditionalAbiTags);
  415. void mangleUnscopedTemplateName(GlobalDecl GD, const DeclContext *DC,
  416. const AbiTagList *AdditionalAbiTags);
  417. void mangleSourceName(const IdentifierInfo *II);
  418. void mangleRegCallName(const IdentifierInfo *II);
  419. void mangleDeviceStubName(const IdentifierInfo *II);
  420. void mangleSourceNameWithAbiTags(
  421. const NamedDecl *ND, const AbiTagList *AdditionalAbiTags = nullptr);
  422. void mangleLocalName(GlobalDecl GD,
  423. const AbiTagList *AdditionalAbiTags);
  424. void mangleBlockForPrefix(const BlockDecl *Block);
  425. void mangleUnqualifiedBlock(const BlockDecl *Block);
  426. void mangleTemplateParamDecl(const NamedDecl *Decl);
  427. void mangleLambda(const CXXRecordDecl *Lambda);
  428. void mangleNestedName(GlobalDecl GD, const DeclContext *DC,
  429. const AbiTagList *AdditionalAbiTags,
  430. bool NoFunction=false);
  431. void mangleNestedName(const TemplateDecl *TD,
  432. ArrayRef<TemplateArgument> Args);
  433. void mangleNestedNameWithClosurePrefix(GlobalDecl GD,
  434. const NamedDecl *PrefixND,
  435. const AbiTagList *AdditionalAbiTags);
  436. void manglePrefix(NestedNameSpecifier *qualifier);
  437. void manglePrefix(const DeclContext *DC, bool NoFunction=false);
  438. void manglePrefix(QualType type);
  439. void mangleTemplatePrefix(GlobalDecl GD, bool NoFunction=false);
  440. void mangleTemplatePrefix(TemplateName Template);
  441. const NamedDecl *getClosurePrefix(const Decl *ND);
  442. void mangleClosurePrefix(const NamedDecl *ND, bool NoFunction = false);
  443. bool mangleUnresolvedTypeOrSimpleId(QualType DestroyedType,
  444. StringRef Prefix = "");
  445. void mangleOperatorName(DeclarationName Name, unsigned Arity);
  446. void mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity);
  447. void mangleVendorQualifier(StringRef qualifier);
  448. void mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST = nullptr);
  449. void mangleRefQualifier(RefQualifierKind RefQualifier);
  450. void mangleObjCMethodName(const ObjCMethodDecl *MD);
  451. // Declare manglers for every type class.
  452. #define ABSTRACT_TYPE(CLASS, PARENT)
  453. #define NON_CANONICAL_TYPE(CLASS, PARENT)
  454. #define TYPE(CLASS, PARENT) void mangleType(const CLASS##Type *T);
  455. #include "clang/AST/TypeNodes.inc"
  456. void mangleType(const TagType*);
  457. void mangleType(TemplateName);
  458. static StringRef getCallingConvQualifierName(CallingConv CC);
  459. void mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo info);
  460. void mangleExtFunctionInfo(const FunctionType *T);
  461. void mangleBareFunctionType(const FunctionProtoType *T, bool MangleReturnType,
  462. const FunctionDecl *FD = nullptr);
  463. void mangleNeonVectorType(const VectorType *T);
  464. void mangleNeonVectorType(const DependentVectorType *T);
  465. void mangleAArch64NeonVectorType(const VectorType *T);
  466. void mangleAArch64NeonVectorType(const DependentVectorType *T);
  467. void mangleAArch64FixedSveVectorType(const VectorType *T);
  468. void mangleAArch64FixedSveVectorType(const DependentVectorType *T);
  469. void mangleIntegerLiteral(QualType T, const llvm::APSInt &Value);
  470. void mangleFloatLiteral(QualType T, const llvm::APFloat &V);
  471. void mangleFixedPointLiteral();
  472. void mangleNullPointer(QualType T);
  473. void mangleMemberExprBase(const Expr *base, bool isArrow);
  474. void mangleMemberExpr(const Expr *base, bool isArrow,
  475. NestedNameSpecifier *qualifier,
  476. NamedDecl *firstQualifierLookup,
  477. DeclarationName name,
  478. const TemplateArgumentLoc *TemplateArgs,
  479. unsigned NumTemplateArgs,
  480. unsigned knownArity);
  481. void mangleCastExpression(const Expr *E, StringRef CastEncoding);
  482. void mangleInitListElements(const InitListExpr *InitList);
  483. void mangleExpression(const Expr *E, unsigned Arity = UnknownArity,
  484. bool AsTemplateArg = false);
  485. void mangleCXXCtorType(CXXCtorType T, const CXXRecordDecl *InheritedFrom);
  486. void mangleCXXDtorType(CXXDtorType T);
  487. void mangleTemplateArgs(TemplateName TN,
  488. const TemplateArgumentLoc *TemplateArgs,
  489. unsigned NumTemplateArgs);
  490. void mangleTemplateArgs(TemplateName TN, ArrayRef<TemplateArgument> Args);
  491. void mangleTemplateArgs(TemplateName TN, const TemplateArgumentList &AL);
  492. void mangleTemplateArg(TemplateArgument A, bool NeedExactType);
  493. void mangleTemplateArgExpr(const Expr *E);
  494. void mangleValueInTemplateArg(QualType T, const APValue &V, bool TopLevel,
  495. bool NeedExactType = false);
  496. void mangleTemplateParameter(unsigned Depth, unsigned Index);
  497. void mangleFunctionParam(const ParmVarDecl *parm);
  498. void writeAbiTags(const NamedDecl *ND,
  499. const AbiTagList *AdditionalAbiTags);
  500. // Returns sorted unique list of ABI tags.
  501. AbiTagList makeFunctionReturnTypeTags(const FunctionDecl *FD);
  502. // Returns sorted unique list of ABI tags.
  503. AbiTagList makeVariableTypeTags(const VarDecl *VD);
  504. };
  505. }
  506. NamespaceDecl *ItaniumMangleContextImpl::getStdNamespace() {
  507. if (!StdNamespace) {
  508. StdNamespace = NamespaceDecl::Create(
  509. getASTContext(), getASTContext().getTranslationUnitDecl(),
  510. /*Inline=*/false, SourceLocation(), SourceLocation(),
  511. &getASTContext().Idents.get("std"),
  512. /*PrevDecl=*/nullptr, /*Nested=*/false);
  513. StdNamespace->setImplicit();
  514. }
  515. return StdNamespace;
  516. }
  517. /// Retrieve the declaration context that should be used when mangling the given
  518. /// declaration.
  519. const DeclContext *
  520. ItaniumMangleContextImpl::getEffectiveDeclContext(const Decl *D) {
  521. // The ABI assumes that lambda closure types that occur within
  522. // default arguments live in the context of the function. However, due to
  523. // the way in which Clang parses and creates function declarations, this is
  524. // not the case: the lambda closure type ends up living in the context
  525. // where the function itself resides, because the function declaration itself
  526. // had not yet been created. Fix the context here.
  527. if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
  528. if (RD->isLambda())
  529. if (ParmVarDecl *ContextParam =
  530. dyn_cast_or_null<ParmVarDecl>(RD->getLambdaContextDecl()))
  531. return ContextParam->getDeclContext();
  532. }
  533. // Perform the same check for block literals.
  534. if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  535. if (ParmVarDecl *ContextParam =
  536. dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl()))
  537. return ContextParam->getDeclContext();
  538. }
  539. // On ARM and AArch64, the va_list tag is always mangled as if in the std
  540. // namespace. We do not represent va_list as actually being in the std
  541. // namespace in C because this would result in incorrect debug info in C,
  542. // among other things. It is important for both languages to have the same
  543. // mangling in order for -fsanitize=cfi-icall to work.
  544. if (D == getASTContext().getVaListTagDecl()) {
  545. const llvm::Triple &T = getASTContext().getTargetInfo().getTriple();
  546. if (T.isARM() || T.isThumb() || T.isAArch64())
  547. return getStdNamespace();
  548. }
  549. const DeclContext *DC = D->getDeclContext();
  550. if (isa<CapturedDecl>(DC) || isa<OMPDeclareReductionDecl>(DC) ||
  551. isa<OMPDeclareMapperDecl>(DC)) {
  552. return getEffectiveDeclContext(cast<Decl>(DC));
  553. }
  554. if (const auto *VD = dyn_cast<VarDecl>(D))
  555. if (VD->isExternC())
  556. return getASTContext().getTranslationUnitDecl();
  557. if (const auto *FD = dyn_cast<FunctionDecl>(D))
  558. if (FD->isExternC())
  559. return getASTContext().getTranslationUnitDecl();
  560. return DC->getRedeclContext();
  561. }
  562. bool ItaniumMangleContextImpl::isInternalLinkageDecl(const NamedDecl *ND) {
  563. if (ND && ND->getFormalLinkage() == InternalLinkage &&
  564. !ND->isExternallyVisible() &&
  565. getEffectiveDeclContext(ND)->isFileContext() &&
  566. !ND->isInAnonymousNamespace())
  567. return true;
  568. return false;
  569. }
  570. // Check if this Function Decl needs a unique internal linkage name.
  571. bool ItaniumMangleContextImpl::isUniqueInternalLinkageDecl(
  572. const NamedDecl *ND) {
  573. if (!NeedsUniqueInternalLinkageNames || !ND)
  574. return false;
  575. const auto *FD = dyn_cast<FunctionDecl>(ND);
  576. if (!FD)
  577. return false;
  578. // For C functions without prototypes, return false as their
  579. // names should not be mangled.
  580. if (!FD->getType()->getAs<FunctionProtoType>())
  581. return false;
  582. if (isInternalLinkageDecl(ND))
  583. return true;
  584. return false;
  585. }
  586. bool ItaniumMangleContextImpl::shouldMangleCXXName(const NamedDecl *D) {
  587. if (const auto *FD = dyn_cast<FunctionDecl>(D)) {
  588. LanguageLinkage L = FD->getLanguageLinkage();
  589. // Overloadable functions need mangling.
  590. if (FD->hasAttr<OverloadableAttr>())
  591. return true;
  592. // "main" is not mangled.
  593. if (FD->isMain())
  594. return false;
  595. // The Windows ABI expects that we would never mangle "typical"
  596. // user-defined entry points regardless of visibility or freestanding-ness.
  597. //
  598. // N.B. This is distinct from asking about "main". "main" has a lot of
  599. // special rules associated with it in the standard while these
  600. // user-defined entry points are outside of the purview of the standard.
  601. // For example, there can be only one definition for "main" in a standards
  602. // compliant program; however nothing forbids the existence of wmain and
  603. // WinMain in the same translation unit.
  604. if (FD->isMSVCRTEntryPoint())
  605. return false;
  606. // C++ functions and those whose names are not a simple identifier need
  607. // mangling.
  608. if (!FD->getDeclName().isIdentifier() || L == CXXLanguageLinkage)
  609. return true;
  610. // C functions are not mangled.
  611. if (L == CLanguageLinkage)
  612. return false;
  613. }
  614. // Otherwise, no mangling is done outside C++ mode.
  615. if (!getASTContext().getLangOpts().CPlusPlus)
  616. return false;
  617. if (const auto *VD = dyn_cast<VarDecl>(D)) {
  618. // Decompositions are mangled.
  619. if (isa<DecompositionDecl>(VD))
  620. return true;
  621. // C variables are not mangled.
  622. if (VD->isExternC())
  623. return false;
  624. // Variables at global scope are not mangled unless they have internal
  625. // linkage or are specializations or are attached to a named module.
  626. const DeclContext *DC = getEffectiveDeclContext(D);
  627. // Check for extern variable declared locally.
  628. if (DC->isFunctionOrMethod() && D->hasLinkage())
  629. while (!DC->isFileContext())
  630. DC = getEffectiveParentContext(DC);
  631. if (DC->isTranslationUnit() && D->getFormalLinkage() != InternalLinkage &&
  632. !CXXNameMangler::shouldHaveAbiTags(*this, VD) &&
  633. !isa<VarTemplateSpecializationDecl>(VD) &&
  634. !VD->getOwningModuleForLinkage())
  635. return false;
  636. }
  637. return true;
  638. }
  639. void CXXNameMangler::writeAbiTags(const NamedDecl *ND,
  640. const AbiTagList *AdditionalAbiTags) {
  641. assert(AbiTags && "require AbiTagState");
  642. AbiTags->write(Out, ND, DisableDerivedAbiTags ? nullptr : AdditionalAbiTags);
  643. }
  644. void CXXNameMangler::mangleSourceNameWithAbiTags(
  645. const NamedDecl *ND, const AbiTagList *AdditionalAbiTags) {
  646. mangleSourceName(ND->getIdentifier());
  647. writeAbiTags(ND, AdditionalAbiTags);
  648. }
  649. void CXXNameMangler::mangle(GlobalDecl GD) {
  650. // <mangled-name> ::= _Z <encoding>
  651. // ::= <data name>
  652. // ::= <special-name>
  653. Out << "_Z";
  654. if (isa<FunctionDecl>(GD.getDecl()))
  655. mangleFunctionEncoding(GD);
  656. else if (isa<VarDecl, FieldDecl, MSGuidDecl, TemplateParamObjectDecl,
  657. BindingDecl>(GD.getDecl()))
  658. mangleName(GD);
  659. else if (const IndirectFieldDecl *IFD =
  660. dyn_cast<IndirectFieldDecl>(GD.getDecl()))
  661. mangleName(IFD->getAnonField());
  662. else
  663. llvm_unreachable("unexpected kind of global decl");
  664. }
  665. void CXXNameMangler::mangleFunctionEncoding(GlobalDecl GD) {
  666. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  667. // <encoding> ::= <function name> <bare-function-type>
  668. // Don't mangle in the type if this isn't a decl we should typically mangle.
  669. if (!Context.shouldMangleDeclName(FD)) {
  670. mangleName(GD);
  671. return;
  672. }
  673. AbiTagList ReturnTypeAbiTags = makeFunctionReturnTypeTags(FD);
  674. if (ReturnTypeAbiTags.empty()) {
  675. // There are no tags for return type, the simplest case.
  676. mangleName(GD);
  677. mangleFunctionEncodingBareType(FD);
  678. return;
  679. }
  680. // Mangle function name and encoding to temporary buffer.
  681. // We have to output name and encoding to the same mangler to get the same
  682. // substitution as it will be in final mangling.
  683. SmallString<256> FunctionEncodingBuf;
  684. llvm::raw_svector_ostream FunctionEncodingStream(FunctionEncodingBuf);
  685. CXXNameMangler FunctionEncodingMangler(*this, FunctionEncodingStream);
  686. // Output name of the function.
  687. FunctionEncodingMangler.disableDerivedAbiTags();
  688. FunctionEncodingMangler.mangleNameWithAbiTags(FD, nullptr);
  689. // Remember length of the function name in the buffer.
  690. size_t EncodingPositionStart = FunctionEncodingStream.str().size();
  691. FunctionEncodingMangler.mangleFunctionEncodingBareType(FD);
  692. // Get tags from return type that are not present in function name or
  693. // encoding.
  694. const AbiTagList &UsedAbiTags =
  695. FunctionEncodingMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
  696. AbiTagList AdditionalAbiTags(ReturnTypeAbiTags.size());
  697. AdditionalAbiTags.erase(
  698. std::set_difference(ReturnTypeAbiTags.begin(), ReturnTypeAbiTags.end(),
  699. UsedAbiTags.begin(), UsedAbiTags.end(),
  700. AdditionalAbiTags.begin()),
  701. AdditionalAbiTags.end());
  702. // Output name with implicit tags and function encoding from temporary buffer.
  703. mangleNameWithAbiTags(FD, &AdditionalAbiTags);
  704. Out << FunctionEncodingStream.str().substr(EncodingPositionStart);
  705. // Function encoding could create new substitutions so we have to add
  706. // temp mangled substitutions to main mangler.
  707. extendSubstitutions(&FunctionEncodingMangler);
  708. }
  709. void CXXNameMangler::mangleFunctionEncodingBareType(const FunctionDecl *FD) {
  710. if (FD->hasAttr<EnableIfAttr>()) {
  711. FunctionTypeDepthState Saved = FunctionTypeDepth.push();
  712. Out << "Ua9enable_ifI";
  713. for (AttrVec::const_iterator I = FD->getAttrs().begin(),
  714. E = FD->getAttrs().end();
  715. I != E; ++I) {
  716. EnableIfAttr *EIA = dyn_cast<EnableIfAttr>(*I);
  717. if (!EIA)
  718. continue;
  719. if (Context.getASTContext().getLangOpts().getClangABICompat() >
  720. LangOptions::ClangABI::Ver11) {
  721. mangleTemplateArgExpr(EIA->getCond());
  722. } else {
  723. // Prior to Clang 12, we hardcoded the X/E around enable-if's argument,
  724. // even though <template-arg> should not include an X/E around
  725. // <expr-primary>.
  726. Out << 'X';
  727. mangleExpression(EIA->getCond());
  728. Out << 'E';
  729. }
  730. }
  731. Out << 'E';
  732. FunctionTypeDepth.pop(Saved);
  733. }
  734. // When mangling an inheriting constructor, the bare function type used is
  735. // that of the inherited constructor.
  736. if (auto *CD = dyn_cast<CXXConstructorDecl>(FD))
  737. if (auto Inherited = CD->getInheritedConstructor())
  738. FD = Inherited.getConstructor();
  739. // Whether the mangling of a function type includes the return type depends on
  740. // the context and the nature of the function. The rules for deciding whether
  741. // the return type is included are:
  742. //
  743. // 1. Template functions (names or types) have return types encoded, with
  744. // the exceptions listed below.
  745. // 2. Function types not appearing as part of a function name mangling,
  746. // e.g. parameters, pointer types, etc., have return type encoded, with the
  747. // exceptions listed below.
  748. // 3. Non-template function names do not have return types encoded.
  749. //
  750. // The exceptions mentioned in (1) and (2) above, for which the return type is
  751. // never included, are
  752. // 1. Constructors.
  753. // 2. Destructors.
  754. // 3. Conversion operator functions, e.g. operator int.
  755. bool MangleReturnType = false;
  756. if (FunctionTemplateDecl *PrimaryTemplate = FD->getPrimaryTemplate()) {
  757. if (!(isa<CXXConstructorDecl>(FD) || isa<CXXDestructorDecl>(FD) ||
  758. isa<CXXConversionDecl>(FD)))
  759. MangleReturnType = true;
  760. // Mangle the type of the primary template.
  761. FD = PrimaryTemplate->getTemplatedDecl();
  762. }
  763. mangleBareFunctionType(FD->getType()->castAs<FunctionProtoType>(),
  764. MangleReturnType, FD);
  765. }
  766. /// Return whether a given namespace is the 'std' namespace.
  767. bool CXXNameMangler::isStd(const NamespaceDecl *NS) {
  768. if (!Context.getEffectiveParentContext(NS)->isTranslationUnit())
  769. return false;
  770. const IdentifierInfo *II = NS->getOriginalNamespace()->getIdentifier();
  771. return II && II->isStr("std");
  772. }
  773. // isStdNamespace - Return whether a given decl context is a toplevel 'std'
  774. // namespace.
  775. bool CXXNameMangler::isStdNamespace(const DeclContext *DC) {
  776. if (!DC->isNamespace())
  777. return false;
  778. return isStd(cast<NamespaceDecl>(DC));
  779. }
  780. static const GlobalDecl
  781. isTemplate(GlobalDecl GD, const TemplateArgumentList *&TemplateArgs) {
  782. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  783. // Check if we have a function template.
  784. if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
  785. if (const TemplateDecl *TD = FD->getPrimaryTemplate()) {
  786. TemplateArgs = FD->getTemplateSpecializationArgs();
  787. return GD.getWithDecl(TD);
  788. }
  789. }
  790. // Check if we have a class template.
  791. if (const ClassTemplateSpecializationDecl *Spec =
  792. dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
  793. TemplateArgs = &Spec->getTemplateArgs();
  794. return GD.getWithDecl(Spec->getSpecializedTemplate());
  795. }
  796. // Check if we have a variable template.
  797. if (const VarTemplateSpecializationDecl *Spec =
  798. dyn_cast<VarTemplateSpecializationDecl>(ND)) {
  799. TemplateArgs = &Spec->getTemplateArgs();
  800. return GD.getWithDecl(Spec->getSpecializedTemplate());
  801. }
  802. return GlobalDecl();
  803. }
  804. static TemplateName asTemplateName(GlobalDecl GD) {
  805. const TemplateDecl *TD = dyn_cast_or_null<TemplateDecl>(GD.getDecl());
  806. return TemplateName(const_cast<TemplateDecl*>(TD));
  807. }
  808. void CXXNameMangler::mangleName(GlobalDecl GD) {
  809. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  810. if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
  811. // Variables should have implicit tags from its type.
  812. AbiTagList VariableTypeAbiTags = makeVariableTypeTags(VD);
  813. if (VariableTypeAbiTags.empty()) {
  814. // Simple case no variable type tags.
  815. mangleNameWithAbiTags(VD, nullptr);
  816. return;
  817. }
  818. // Mangle variable name to null stream to collect tags.
  819. llvm::raw_null_ostream NullOutStream;
  820. CXXNameMangler VariableNameMangler(*this, NullOutStream);
  821. VariableNameMangler.disableDerivedAbiTags();
  822. VariableNameMangler.mangleNameWithAbiTags(VD, nullptr);
  823. // Get tags from variable type that are not present in its name.
  824. const AbiTagList &UsedAbiTags =
  825. VariableNameMangler.AbiTagsRoot.getSortedUniqueUsedAbiTags();
  826. AbiTagList AdditionalAbiTags(VariableTypeAbiTags.size());
  827. AdditionalAbiTags.erase(
  828. std::set_difference(VariableTypeAbiTags.begin(),
  829. VariableTypeAbiTags.end(), UsedAbiTags.begin(),
  830. UsedAbiTags.end(), AdditionalAbiTags.begin()),
  831. AdditionalAbiTags.end());
  832. // Output name with implicit tags.
  833. mangleNameWithAbiTags(VD, &AdditionalAbiTags);
  834. } else {
  835. mangleNameWithAbiTags(GD, nullptr);
  836. }
  837. }
  838. const RecordDecl *CXXNameMangler::GetLocalClassDecl(const Decl *D) {
  839. const DeclContext *DC = Context.getEffectiveDeclContext(D);
  840. while (!DC->isNamespace() && !DC->isTranslationUnit()) {
  841. if (isLocalContainerContext(DC))
  842. return dyn_cast<RecordDecl>(D);
  843. D = cast<Decl>(DC);
  844. DC = Context.getEffectiveDeclContext(D);
  845. }
  846. return nullptr;
  847. }
  848. void CXXNameMangler::mangleNameWithAbiTags(GlobalDecl GD,
  849. const AbiTagList *AdditionalAbiTags) {
  850. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  851. // <name> ::= [<module-name>] <nested-name>
  852. // ::= [<module-name>] <unscoped-name>
  853. // ::= [<module-name>] <unscoped-template-name> <template-args>
  854. // ::= <local-name>
  855. //
  856. const DeclContext *DC = Context.getEffectiveDeclContext(ND);
  857. // If this is an extern variable declared locally, the relevant DeclContext
  858. // is that of the containing namespace, or the translation unit.
  859. // FIXME: This is a hack; extern variables declared locally should have
  860. // a proper semantic declaration context!
  861. if (isLocalContainerContext(DC) && ND->hasLinkage() && !isLambda(ND))
  862. while (!DC->isNamespace() && !DC->isTranslationUnit())
  863. DC = Context.getEffectiveParentContext(DC);
  864. else if (GetLocalClassDecl(ND)) {
  865. mangleLocalName(GD, AdditionalAbiTags);
  866. return;
  867. }
  868. assert(!isa<LinkageSpecDecl>(DC) && "context cannot be LinkageSpecDecl");
  869. if (isLocalContainerContext(DC)) {
  870. mangleLocalName(GD, AdditionalAbiTags);
  871. return;
  872. }
  873. // Closures can require a nested-name mangling even if they're semantically
  874. // in the global namespace.
  875. if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
  876. mangleNestedNameWithClosurePrefix(GD, PrefixND, AdditionalAbiTags);
  877. return;
  878. }
  879. if (DC->isTranslationUnit() || isStdNamespace(DC)) {
  880. // Check if we have a template.
  881. const TemplateArgumentList *TemplateArgs = nullptr;
  882. if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
  883. mangleUnscopedTemplateName(TD, DC, AdditionalAbiTags);
  884. mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
  885. return;
  886. }
  887. mangleUnscopedName(GD, DC, AdditionalAbiTags);
  888. return;
  889. }
  890. mangleNestedName(GD, DC, AdditionalAbiTags);
  891. }
  892. void CXXNameMangler::mangleModuleName(const NamedDecl *ND) {
  893. if (ND->isExternallyVisible())
  894. if (Module *M = ND->getOwningModuleForLinkage())
  895. mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
  896. }
  897. // <module-name> ::= <module-subname>
  898. // ::= <module-name> <module-subname>
  899. // ::= <substitution>
  900. // <module-subname> ::= W <source-name>
  901. // ::= W P <source-name>
  902. void CXXNameMangler::mangleModuleNamePrefix(StringRef Name, bool IsPartition) {
  903. // <substitution> ::= S <seq-id> _
  904. auto It = ModuleSubstitutions.find(Name);
  905. if (It != ModuleSubstitutions.end()) {
  906. Out << 'S';
  907. mangleSeqID(It->second);
  908. return;
  909. }
  910. // FIXME: Preserve hierarchy in module names rather than flattening
  911. // them to strings; use Module*s as substitution keys.
  912. auto Parts = Name.rsplit('.');
  913. if (Parts.second.empty())
  914. Parts.second = Parts.first;
  915. else {
  916. mangleModuleNamePrefix(Parts.first, IsPartition);
  917. IsPartition = false;
  918. }
  919. Out << 'W';
  920. if (IsPartition)
  921. Out << 'P';
  922. Out << Parts.second.size() << Parts.second;
  923. ModuleSubstitutions.insert({Name, SeqID++});
  924. }
  925. void CXXNameMangler::mangleTemplateName(const TemplateDecl *TD,
  926. ArrayRef<TemplateArgument> Args) {
  927. const DeclContext *DC = Context.getEffectiveDeclContext(TD);
  928. if (DC->isTranslationUnit() || isStdNamespace(DC)) {
  929. mangleUnscopedTemplateName(TD, DC, nullptr);
  930. mangleTemplateArgs(asTemplateName(TD), Args);
  931. } else {
  932. mangleNestedName(TD, Args);
  933. }
  934. }
  935. void CXXNameMangler::mangleUnscopedName(GlobalDecl GD, const DeclContext *DC,
  936. const AbiTagList *AdditionalAbiTags) {
  937. // <unscoped-name> ::= <unqualified-name>
  938. // ::= St <unqualified-name> # ::std::
  939. assert(!isa<LinkageSpecDecl>(DC) && "unskipped LinkageSpecDecl");
  940. if (isStdNamespace(DC))
  941. Out << "St";
  942. mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
  943. }
  944. void CXXNameMangler::mangleUnscopedTemplateName(
  945. GlobalDecl GD, const DeclContext *DC, const AbiTagList *AdditionalAbiTags) {
  946. const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
  947. // <unscoped-template-name> ::= <unscoped-name>
  948. // ::= <substitution>
  949. if (mangleSubstitution(ND))
  950. return;
  951. // <template-template-param> ::= <template-param>
  952. if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
  953. assert(!AdditionalAbiTags &&
  954. "template template param cannot have abi tags");
  955. mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
  956. } else if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND)) {
  957. mangleUnscopedName(GD, DC, AdditionalAbiTags);
  958. } else {
  959. mangleUnscopedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
  960. AdditionalAbiTags);
  961. }
  962. addSubstitution(ND);
  963. }
  964. void CXXNameMangler::mangleFloat(const llvm::APFloat &f) {
  965. // ABI:
  966. // Floating-point literals are encoded using a fixed-length
  967. // lowercase hexadecimal string corresponding to the internal
  968. // representation (IEEE on Itanium), high-order bytes first,
  969. // without leading zeroes. For example: "Lf bf800000 E" is -1.0f
  970. // on Itanium.
  971. // The 'without leading zeroes' thing seems to be an editorial
  972. // mistake; see the discussion on cxx-abi-dev beginning on
  973. // 2012-01-16.
  974. // Our requirements here are just barely weird enough to justify
  975. // using a custom algorithm instead of post-processing APInt::toString().
  976. llvm::APInt valueBits = f.bitcastToAPInt();
  977. unsigned numCharacters = (valueBits.getBitWidth() + 3) / 4;
  978. assert(numCharacters != 0);
  979. // Allocate a buffer of the right number of characters.
  980. SmallVector<char, 20> buffer(numCharacters);
  981. // Fill the buffer left-to-right.
  982. for (unsigned stringIndex = 0; stringIndex != numCharacters; ++stringIndex) {
  983. // The bit-index of the next hex digit.
  984. unsigned digitBitIndex = 4 * (numCharacters - stringIndex - 1);
  985. // Project out 4 bits starting at 'digitIndex'.
  986. uint64_t hexDigit = valueBits.getRawData()[digitBitIndex / 64];
  987. hexDigit >>= (digitBitIndex % 64);
  988. hexDigit &= 0xF;
  989. // Map that over to a lowercase hex digit.
  990. static const char charForHex[16] = {
  991. '0', '1', '2', '3', '4', '5', '6', '7',
  992. '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  993. };
  994. buffer[stringIndex] = charForHex[hexDigit];
  995. }
  996. Out.write(buffer.data(), numCharacters);
  997. }
  998. void CXXNameMangler::mangleFloatLiteral(QualType T, const llvm::APFloat &V) {
  999. Out << 'L';
  1000. mangleType(T);
  1001. mangleFloat(V);
  1002. Out << 'E';
  1003. }
  1004. void CXXNameMangler::mangleFixedPointLiteral() {
  1005. DiagnosticsEngine &Diags = Context.getDiags();
  1006. unsigned DiagID = Diags.getCustomDiagID(
  1007. DiagnosticsEngine::Error, "cannot mangle fixed point literals yet");
  1008. Diags.Report(DiagID);
  1009. }
  1010. void CXXNameMangler::mangleNullPointer(QualType T) {
  1011. // <expr-primary> ::= L <type> 0 E
  1012. Out << 'L';
  1013. mangleType(T);
  1014. Out << "0E";
  1015. }
  1016. void CXXNameMangler::mangleNumber(const llvm::APSInt &Value) {
  1017. if (Value.isSigned() && Value.isNegative()) {
  1018. Out << 'n';
  1019. Value.abs().print(Out, /*signed*/ false);
  1020. } else {
  1021. Value.print(Out, /*signed*/ false);
  1022. }
  1023. }
  1024. void CXXNameMangler::mangleNumber(int64_t Number) {
  1025. // <number> ::= [n] <non-negative decimal integer>
  1026. if (Number < 0) {
  1027. Out << 'n';
  1028. Number = -Number;
  1029. }
  1030. Out << Number;
  1031. }
  1032. void CXXNameMangler::mangleCallOffset(int64_t NonVirtual, int64_t Virtual) {
  1033. // <call-offset> ::= h <nv-offset> _
  1034. // ::= v <v-offset> _
  1035. // <nv-offset> ::= <offset number> # non-virtual base override
  1036. // <v-offset> ::= <offset number> _ <virtual offset number>
  1037. // # virtual base override, with vcall offset
  1038. if (!Virtual) {
  1039. Out << 'h';
  1040. mangleNumber(NonVirtual);
  1041. Out << '_';
  1042. return;
  1043. }
  1044. Out << 'v';
  1045. mangleNumber(NonVirtual);
  1046. Out << '_';
  1047. mangleNumber(Virtual);
  1048. Out << '_';
  1049. }
  1050. void CXXNameMangler::manglePrefix(QualType type) {
  1051. if (const auto *TST = type->getAs<TemplateSpecializationType>()) {
  1052. if (!mangleSubstitution(QualType(TST, 0))) {
  1053. mangleTemplatePrefix(TST->getTemplateName());
  1054. // FIXME: GCC does not appear to mangle the template arguments when
  1055. // the template in question is a dependent template name. Should we
  1056. // emulate that badness?
  1057. mangleTemplateArgs(TST->getTemplateName(), TST->template_arguments());
  1058. addSubstitution(QualType(TST, 0));
  1059. }
  1060. } else if (const auto *DTST =
  1061. type->getAs<DependentTemplateSpecializationType>()) {
  1062. if (!mangleSubstitution(QualType(DTST, 0))) {
  1063. TemplateName Template = getASTContext().getDependentTemplateName(
  1064. DTST->getQualifier(), DTST->getIdentifier());
  1065. mangleTemplatePrefix(Template);
  1066. // FIXME: GCC does not appear to mangle the template arguments when
  1067. // the template in question is a dependent template name. Should we
  1068. // emulate that badness?
  1069. mangleTemplateArgs(Template, DTST->template_arguments());
  1070. addSubstitution(QualType(DTST, 0));
  1071. }
  1072. } else {
  1073. // We use the QualType mangle type variant here because it handles
  1074. // substitutions.
  1075. mangleType(type);
  1076. }
  1077. }
  1078. /// Mangle everything prior to the base-unresolved-name in an unresolved-name.
  1079. ///
  1080. /// \param recursive - true if this is being called recursively,
  1081. /// i.e. if there is more prefix "to the right".
  1082. void CXXNameMangler::mangleUnresolvedPrefix(NestedNameSpecifier *qualifier,
  1083. bool recursive) {
  1084. // x, ::x
  1085. // <unresolved-name> ::= [gs] <base-unresolved-name>
  1086. // T::x / decltype(p)::x
  1087. // <unresolved-name> ::= sr <unresolved-type> <base-unresolved-name>
  1088. // T::N::x /decltype(p)::N::x
  1089. // <unresolved-name> ::= srN <unresolved-type> <unresolved-qualifier-level>+ E
  1090. // <base-unresolved-name>
  1091. // A::x, N::y, A<T>::z; "gs" means leading "::"
  1092. // <unresolved-name> ::= [gs] sr <unresolved-qualifier-level>+ E
  1093. // <base-unresolved-name>
  1094. switch (qualifier->getKind()) {
  1095. case NestedNameSpecifier::Global:
  1096. Out << "gs";
  1097. // We want an 'sr' unless this is the entire NNS.
  1098. if (recursive)
  1099. Out << "sr";
  1100. // We never want an 'E' here.
  1101. return;
  1102. case NestedNameSpecifier::Super:
  1103. llvm_unreachable("Can't mangle __super specifier");
  1104. case NestedNameSpecifier::Namespace:
  1105. if (qualifier->getPrefix())
  1106. mangleUnresolvedPrefix(qualifier->getPrefix(),
  1107. /*recursive*/ true);
  1108. else
  1109. Out << "sr";
  1110. mangleSourceNameWithAbiTags(qualifier->getAsNamespace());
  1111. break;
  1112. case NestedNameSpecifier::NamespaceAlias:
  1113. if (qualifier->getPrefix())
  1114. mangleUnresolvedPrefix(qualifier->getPrefix(),
  1115. /*recursive*/ true);
  1116. else
  1117. Out << "sr";
  1118. mangleSourceNameWithAbiTags(qualifier->getAsNamespaceAlias());
  1119. break;
  1120. case NestedNameSpecifier::TypeSpec:
  1121. case NestedNameSpecifier::TypeSpecWithTemplate: {
  1122. const Type *type = qualifier->getAsType();
  1123. // We only want to use an unresolved-type encoding if this is one of:
  1124. // - a decltype
  1125. // - a template type parameter
  1126. // - a template template parameter with arguments
  1127. // In all of these cases, we should have no prefix.
  1128. if (qualifier->getPrefix()) {
  1129. mangleUnresolvedPrefix(qualifier->getPrefix(),
  1130. /*recursive*/ true);
  1131. } else {
  1132. // Otherwise, all the cases want this.
  1133. Out << "sr";
  1134. }
  1135. if (mangleUnresolvedTypeOrSimpleId(QualType(type, 0), recursive ? "N" : ""))
  1136. return;
  1137. break;
  1138. }
  1139. case NestedNameSpecifier::Identifier:
  1140. // Member expressions can have these without prefixes.
  1141. if (qualifier->getPrefix())
  1142. mangleUnresolvedPrefix(qualifier->getPrefix(),
  1143. /*recursive*/ true);
  1144. else
  1145. Out << "sr";
  1146. mangleSourceName(qualifier->getAsIdentifier());
  1147. // An Identifier has no type information, so we can't emit abi tags for it.
  1148. break;
  1149. }
  1150. // If this was the innermost part of the NNS, and we fell out to
  1151. // here, append an 'E'.
  1152. if (!recursive)
  1153. Out << 'E';
  1154. }
  1155. /// Mangle an unresolved-name, which is generally used for names which
  1156. /// weren't resolved to specific entities.
  1157. void CXXNameMangler::mangleUnresolvedName(
  1158. NestedNameSpecifier *qualifier, DeclarationName name,
  1159. const TemplateArgumentLoc *TemplateArgs, unsigned NumTemplateArgs,
  1160. unsigned knownArity) {
  1161. if (qualifier) mangleUnresolvedPrefix(qualifier);
  1162. switch (name.getNameKind()) {
  1163. // <base-unresolved-name> ::= <simple-id>
  1164. case DeclarationName::Identifier:
  1165. mangleSourceName(name.getAsIdentifierInfo());
  1166. break;
  1167. // <base-unresolved-name> ::= dn <destructor-name>
  1168. case DeclarationName::CXXDestructorName:
  1169. Out << "dn";
  1170. mangleUnresolvedTypeOrSimpleId(name.getCXXNameType());
  1171. break;
  1172. // <base-unresolved-name> ::= on <operator-name>
  1173. case DeclarationName::CXXConversionFunctionName:
  1174. case DeclarationName::CXXLiteralOperatorName:
  1175. case DeclarationName::CXXOperatorName:
  1176. Out << "on";
  1177. mangleOperatorName(name, knownArity);
  1178. break;
  1179. case DeclarationName::CXXConstructorName:
  1180. llvm_unreachable("Can't mangle a constructor name!");
  1181. case DeclarationName::CXXUsingDirective:
  1182. llvm_unreachable("Can't mangle a using directive name!");
  1183. case DeclarationName::CXXDeductionGuideName:
  1184. llvm_unreachable("Can't mangle a deduction guide name!");
  1185. case DeclarationName::ObjCMultiArgSelector:
  1186. case DeclarationName::ObjCOneArgSelector:
  1187. case DeclarationName::ObjCZeroArgSelector:
  1188. llvm_unreachable("Can't mangle Objective-C selector names here!");
  1189. }
  1190. // The <simple-id> and on <operator-name> productions end in an optional
  1191. // <template-args>.
  1192. if (TemplateArgs)
  1193. mangleTemplateArgs(TemplateName(), TemplateArgs, NumTemplateArgs);
  1194. }
  1195. void CXXNameMangler::mangleUnqualifiedName(
  1196. GlobalDecl GD, DeclarationName Name, const DeclContext *DC,
  1197. unsigned KnownArity, const AbiTagList *AdditionalAbiTags) {
  1198. const NamedDecl *ND = cast_or_null<NamedDecl>(GD.getDecl());
  1199. // <unqualified-name> ::= [<module-name>] <operator-name>
  1200. // ::= <ctor-dtor-name>
  1201. // ::= [<module-name>] <source-name>
  1202. // ::= [<module-name>] DC <source-name>* E
  1203. if (ND && DC && DC->isFileContext())
  1204. mangleModuleName(ND);
  1205. unsigned Arity = KnownArity;
  1206. switch (Name.getNameKind()) {
  1207. case DeclarationName::Identifier: {
  1208. const IdentifierInfo *II = Name.getAsIdentifierInfo();
  1209. // We mangle decomposition declarations as the names of their bindings.
  1210. if (auto *DD = dyn_cast<DecompositionDecl>(ND)) {
  1211. // FIXME: Non-standard mangling for decomposition declarations:
  1212. //
  1213. // <unqualified-name> ::= DC <source-name>* E
  1214. //
  1215. // Proposed on cxx-abi-dev on 2016-08-12
  1216. Out << "DC";
  1217. for (auto *BD : DD->bindings())
  1218. mangleSourceName(BD->getDeclName().getAsIdentifierInfo());
  1219. Out << 'E';
  1220. writeAbiTags(ND, AdditionalAbiTags);
  1221. break;
  1222. }
  1223. if (auto *GD = dyn_cast<MSGuidDecl>(ND)) {
  1224. // We follow MSVC in mangling GUID declarations as if they were variables
  1225. // with a particular reserved name. Continue the pretense here.
  1226. SmallString<sizeof("_GUID_12345678_1234_1234_1234_1234567890ab")> GUID;
  1227. llvm::raw_svector_ostream GUIDOS(GUID);
  1228. Context.mangleMSGuidDecl(GD, GUIDOS);
  1229. Out << GUID.size() << GUID;
  1230. break;
  1231. }
  1232. if (auto *TPO = dyn_cast<TemplateParamObjectDecl>(ND)) {
  1233. // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
  1234. Out << "TA";
  1235. mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
  1236. TPO->getValue(), /*TopLevel=*/true);
  1237. break;
  1238. }
  1239. if (II) {
  1240. // Match GCC's naming convention for internal linkage symbols, for
  1241. // symbols that are not actually visible outside of this TU. GCC
  1242. // distinguishes between internal and external linkage symbols in
  1243. // its mangling, to support cases like this that were valid C++ prior
  1244. // to DR426:
  1245. //
  1246. // void test() { extern void foo(); }
  1247. // static void foo();
  1248. //
  1249. // Don't bother with the L marker for names in anonymous namespaces; the
  1250. // 12_GLOBAL__N_1 mangling is quite sufficient there, and this better
  1251. // matches GCC anyway, because GCC does not treat anonymous namespaces as
  1252. // implying internal linkage.
  1253. if (Context.isInternalLinkageDecl(ND))
  1254. Out << 'L';
  1255. auto *FD = dyn_cast<FunctionDecl>(ND);
  1256. bool IsRegCall = FD &&
  1257. FD->getType()->castAs<FunctionType>()->getCallConv() ==
  1258. clang::CC_X86RegCall;
  1259. bool IsDeviceStub =
  1260. FD && FD->hasAttr<CUDAGlobalAttr>() &&
  1261. GD.getKernelReferenceKind() == KernelReferenceKind::Stub;
  1262. if (IsDeviceStub)
  1263. mangleDeviceStubName(II);
  1264. else if (IsRegCall)
  1265. mangleRegCallName(II);
  1266. else
  1267. mangleSourceName(II);
  1268. writeAbiTags(ND, AdditionalAbiTags);
  1269. break;
  1270. }
  1271. // Otherwise, an anonymous entity. We must have a declaration.
  1272. assert(ND && "mangling empty name without declaration");
  1273. if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
  1274. if (NS->isAnonymousNamespace()) {
  1275. // This is how gcc mangles these names.
  1276. Out << "12_GLOBAL__N_1";
  1277. break;
  1278. }
  1279. }
  1280. if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
  1281. // We must have an anonymous union or struct declaration.
  1282. const RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
  1283. // Itanium C++ ABI 5.1.2:
  1284. //
  1285. // For the purposes of mangling, the name of an anonymous union is
  1286. // considered to be the name of the first named data member found by a
  1287. // pre-order, depth-first, declaration-order walk of the data members of
  1288. // the anonymous union. If there is no such data member (i.e., if all of
  1289. // the data members in the union are unnamed), then there is no way for
  1290. // a program to refer to the anonymous union, and there is therefore no
  1291. // need to mangle its name.
  1292. assert(RD->isAnonymousStructOrUnion()
  1293. && "Expected anonymous struct or union!");
  1294. const FieldDecl *FD = RD->findFirstNamedDataMember();
  1295. // It's actually possible for various reasons for us to get here
  1296. // with an empty anonymous struct / union. Fortunately, it
  1297. // doesn't really matter what name we generate.
  1298. if (!FD) break;
  1299. assert(FD->getIdentifier() && "Data member name isn't an identifier!");
  1300. mangleSourceName(FD->getIdentifier());
  1301. // Not emitting abi tags: internal name anyway.
  1302. break;
  1303. }
  1304. // Class extensions have no name as a category, and it's possible
  1305. // for them to be the semantic parent of certain declarations
  1306. // (primarily, tag decls defined within declarations). Such
  1307. // declarations will always have internal linkage, so the name
  1308. // doesn't really matter, but we shouldn't crash on them. For
  1309. // safety, just handle all ObjC containers here.
  1310. if (isa<ObjCContainerDecl>(ND))
  1311. break;
  1312. // We must have an anonymous struct.
  1313. const TagDecl *TD = cast<TagDecl>(ND);
  1314. if (const TypedefNameDecl *D = TD->getTypedefNameForAnonDecl()) {
  1315. assert(TD->getDeclContext() == D->getDeclContext() &&
  1316. "Typedef should not be in another decl context!");
  1317. assert(D->getDeclName().getAsIdentifierInfo() &&
  1318. "Typedef was not named!");
  1319. mangleSourceName(D->getDeclName().getAsIdentifierInfo());
  1320. assert(!AdditionalAbiTags && "Type cannot have additional abi tags");
  1321. // Explicit abi tags are still possible; take from underlying type, not
  1322. // from typedef.
  1323. writeAbiTags(TD, nullptr);
  1324. break;
  1325. }
  1326. // <unnamed-type-name> ::= <closure-type-name>
  1327. //
  1328. // <closure-type-name> ::= Ul <lambda-sig> E [ <nonnegative number> ] _
  1329. // <lambda-sig> ::= <template-param-decl>* <parameter-type>+
  1330. // # Parameter types or 'v' for 'void'.
  1331. if (const CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(TD)) {
  1332. std::optional<unsigned> DeviceNumber =
  1333. Context.getDiscriminatorOverride()(Context.getASTContext(), Record);
  1334. // If we have a device-number via the discriminator, use that to mangle
  1335. // the lambda, otherwise use the typical lambda-mangling-number. In either
  1336. // case, a '0' should be mangled as a normal unnamed class instead of as a
  1337. // lambda.
  1338. if (Record->isLambda() &&
  1339. ((DeviceNumber && *DeviceNumber > 0) ||
  1340. (!DeviceNumber && Record->getLambdaManglingNumber() > 0))) {
  1341. assert(!AdditionalAbiTags &&
  1342. "Lambda type cannot have additional abi tags");
  1343. mangleLambda(Record);
  1344. break;
  1345. }
  1346. }
  1347. if (TD->isExternallyVisible()) {
  1348. unsigned UnnamedMangle =
  1349. getASTContext().getManglingNumber(TD, Context.isAux());
  1350. Out << "Ut";
  1351. if (UnnamedMangle > 1)
  1352. Out << UnnamedMangle - 2;
  1353. Out << '_';
  1354. writeAbiTags(TD, AdditionalAbiTags);
  1355. break;
  1356. }
  1357. // Get a unique id for the anonymous struct. If it is not a real output
  1358. // ID doesn't matter so use fake one.
  1359. unsigned AnonStructId =
  1360. NullOut ? 0
  1361. : Context.getAnonymousStructId(TD, dyn_cast<FunctionDecl>(DC));
  1362. // Mangle it as a source name in the form
  1363. // [n] $_<id>
  1364. // where n is the length of the string.
  1365. SmallString<8> Str;
  1366. Str += "$_";
  1367. Str += llvm::utostr(AnonStructId);
  1368. Out << Str.size();
  1369. Out << Str;
  1370. break;
  1371. }
  1372. case DeclarationName::ObjCZeroArgSelector:
  1373. case DeclarationName::ObjCOneArgSelector:
  1374. case DeclarationName::ObjCMultiArgSelector:
  1375. llvm_unreachable("Can't mangle Objective-C selector names here!");
  1376. case DeclarationName::CXXConstructorName: {
  1377. const CXXRecordDecl *InheritedFrom = nullptr;
  1378. TemplateName InheritedTemplateName;
  1379. const TemplateArgumentList *InheritedTemplateArgs = nullptr;
  1380. if (auto Inherited =
  1381. cast<CXXConstructorDecl>(ND)->getInheritedConstructor()) {
  1382. InheritedFrom = Inherited.getConstructor()->getParent();
  1383. InheritedTemplateName =
  1384. TemplateName(Inherited.getConstructor()->getPrimaryTemplate());
  1385. InheritedTemplateArgs =
  1386. Inherited.getConstructor()->getTemplateSpecializationArgs();
  1387. }
  1388. if (ND == Structor)
  1389. // If the named decl is the C++ constructor we're mangling, use the type
  1390. // we were given.
  1391. mangleCXXCtorType(static_cast<CXXCtorType>(StructorType), InheritedFrom);
  1392. else
  1393. // Otherwise, use the complete constructor name. This is relevant if a
  1394. // class with a constructor is declared within a constructor.
  1395. mangleCXXCtorType(Ctor_Complete, InheritedFrom);
  1396. // FIXME: The template arguments are part of the enclosing prefix or
  1397. // nested-name, but it's more convenient to mangle them here.
  1398. if (InheritedTemplateArgs)
  1399. mangleTemplateArgs(InheritedTemplateName, *InheritedTemplateArgs);
  1400. writeAbiTags(ND, AdditionalAbiTags);
  1401. break;
  1402. }
  1403. case DeclarationName::CXXDestructorName:
  1404. if (ND == Structor)
  1405. // If the named decl is the C++ destructor we're mangling, use the type we
  1406. // were given.
  1407. mangleCXXDtorType(static_cast<CXXDtorType>(StructorType));
  1408. else
  1409. // Otherwise, use the complete destructor name. This is relevant if a
  1410. // class with a destructor is declared within a destructor.
  1411. mangleCXXDtorType(Dtor_Complete);
  1412. writeAbiTags(ND, AdditionalAbiTags);
  1413. break;
  1414. case DeclarationName::CXXOperatorName:
  1415. if (ND && Arity == UnknownArity) {
  1416. Arity = cast<FunctionDecl>(ND)->getNumParams();
  1417. // If we have a member function, we need to include the 'this' pointer.
  1418. if (const auto *MD = dyn_cast<CXXMethodDecl>(ND))
  1419. if (!MD->isStatic())
  1420. Arity++;
  1421. }
  1422. [[fallthrough]];
  1423. case DeclarationName::CXXConversionFunctionName:
  1424. case DeclarationName::CXXLiteralOperatorName:
  1425. mangleOperatorName(Name, Arity);
  1426. writeAbiTags(ND, AdditionalAbiTags);
  1427. break;
  1428. case DeclarationName::CXXDeductionGuideName:
  1429. llvm_unreachable("Can't mangle a deduction guide name!");
  1430. case DeclarationName::CXXUsingDirective:
  1431. llvm_unreachable("Can't mangle a using directive name!");
  1432. }
  1433. }
  1434. void CXXNameMangler::mangleRegCallName(const IdentifierInfo *II) {
  1435. // <source-name> ::= <positive length number> __regcall3__ <identifier>
  1436. // <number> ::= [n] <non-negative decimal integer>
  1437. // <identifier> ::= <unqualified source code identifier>
  1438. Out << II->getLength() + sizeof("__regcall3__") - 1 << "__regcall3__"
  1439. << II->getName();
  1440. }
  1441. void CXXNameMangler::mangleDeviceStubName(const IdentifierInfo *II) {
  1442. // <source-name> ::= <positive length number> __device_stub__ <identifier>
  1443. // <number> ::= [n] <non-negative decimal integer>
  1444. // <identifier> ::= <unqualified source code identifier>
  1445. Out << II->getLength() + sizeof("__device_stub__") - 1 << "__device_stub__"
  1446. << II->getName();
  1447. }
  1448. void CXXNameMangler::mangleSourceName(const IdentifierInfo *II) {
  1449. // <source-name> ::= <positive length number> <identifier>
  1450. // <number> ::= [n] <non-negative decimal integer>
  1451. // <identifier> ::= <unqualified source code identifier>
  1452. Out << II->getLength() << II->getName();
  1453. }
  1454. void CXXNameMangler::mangleNestedName(GlobalDecl GD,
  1455. const DeclContext *DC,
  1456. const AbiTagList *AdditionalAbiTags,
  1457. bool NoFunction) {
  1458. const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
  1459. // <nested-name>
  1460. // ::= N [<CV-qualifiers>] [<ref-qualifier>] <prefix> <unqualified-name> E
  1461. // ::= N [<CV-qualifiers>] [<ref-qualifier>] <template-prefix>
  1462. // <template-args> E
  1463. Out << 'N';
  1464. if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(ND)) {
  1465. Qualifiers MethodQuals = Method->getMethodQualifiers();
  1466. // We do not consider restrict a distinguishing attribute for overloading
  1467. // purposes so we must not mangle it.
  1468. MethodQuals.removeRestrict();
  1469. mangleQualifiers(MethodQuals);
  1470. mangleRefQualifier(Method->getRefQualifier());
  1471. }
  1472. // Check if we have a template.
  1473. const TemplateArgumentList *TemplateArgs = nullptr;
  1474. if (GlobalDecl TD = isTemplate(GD, TemplateArgs)) {
  1475. mangleTemplatePrefix(TD, NoFunction);
  1476. mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
  1477. } else {
  1478. manglePrefix(DC, NoFunction);
  1479. mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
  1480. }
  1481. Out << 'E';
  1482. }
  1483. void CXXNameMangler::mangleNestedName(const TemplateDecl *TD,
  1484. ArrayRef<TemplateArgument> Args) {
  1485. // <nested-name> ::= N [<CV-qualifiers>] <template-prefix> <template-args> E
  1486. Out << 'N';
  1487. mangleTemplatePrefix(TD);
  1488. mangleTemplateArgs(asTemplateName(TD), Args);
  1489. Out << 'E';
  1490. }
  1491. void CXXNameMangler::mangleNestedNameWithClosurePrefix(
  1492. GlobalDecl GD, const NamedDecl *PrefixND,
  1493. const AbiTagList *AdditionalAbiTags) {
  1494. // A <closure-prefix> represents a variable or field, not a regular
  1495. // DeclContext, so needs special handling. In this case we're mangling a
  1496. // limited form of <nested-name>:
  1497. //
  1498. // <nested-name> ::= N <closure-prefix> <closure-type-name> E
  1499. Out << 'N';
  1500. mangleClosurePrefix(PrefixND);
  1501. mangleUnqualifiedName(GD, nullptr, AdditionalAbiTags);
  1502. Out << 'E';
  1503. }
  1504. static GlobalDecl getParentOfLocalEntity(const DeclContext *DC) {
  1505. GlobalDecl GD;
  1506. // The Itanium spec says:
  1507. // For entities in constructors and destructors, the mangling of the
  1508. // complete object constructor or destructor is used as the base function
  1509. // name, i.e. the C1 or D1 version.
  1510. if (auto *CD = dyn_cast<CXXConstructorDecl>(DC))
  1511. GD = GlobalDecl(CD, Ctor_Complete);
  1512. else if (auto *DD = dyn_cast<CXXDestructorDecl>(DC))
  1513. GD = GlobalDecl(DD, Dtor_Complete);
  1514. else
  1515. GD = GlobalDecl(cast<FunctionDecl>(DC));
  1516. return GD;
  1517. }
  1518. void CXXNameMangler::mangleLocalName(GlobalDecl GD,
  1519. const AbiTagList *AdditionalAbiTags) {
  1520. const Decl *D = GD.getDecl();
  1521. // <local-name> := Z <function encoding> E <entity name> [<discriminator>]
  1522. // := Z <function encoding> E s [<discriminator>]
  1523. // <local-name> := Z <function encoding> E d [ <parameter number> ]
  1524. // _ <entity name>
  1525. // <discriminator> := _ <non-negative number>
  1526. assert(isa<NamedDecl>(D) || isa<BlockDecl>(D));
  1527. const RecordDecl *RD = GetLocalClassDecl(D);
  1528. const DeclContext *DC = Context.getEffectiveDeclContext(RD ? RD : D);
  1529. Out << 'Z';
  1530. {
  1531. AbiTagState LocalAbiTags(AbiTags);
  1532. if (const ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(DC))
  1533. mangleObjCMethodName(MD);
  1534. else if (const BlockDecl *BD = dyn_cast<BlockDecl>(DC))
  1535. mangleBlockForPrefix(BD);
  1536. else
  1537. mangleFunctionEncoding(getParentOfLocalEntity(DC));
  1538. // Implicit ABI tags (from namespace) are not available in the following
  1539. // entity; reset to actually emitted tags, which are available.
  1540. LocalAbiTags.setUsedAbiTags(LocalAbiTags.getEmittedAbiTags());
  1541. }
  1542. Out << 'E';
  1543. // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
  1544. // be a bug that is fixed in trunk.
  1545. if (RD) {
  1546. // The parameter number is omitted for the last parameter, 0 for the
  1547. // second-to-last parameter, 1 for the third-to-last parameter, etc. The
  1548. // <entity name> will of course contain a <closure-type-name>: Its
  1549. // numbering will be local to the particular argument in which it appears
  1550. // -- other default arguments do not affect its encoding.
  1551. const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD);
  1552. if (CXXRD && CXXRD->isLambda()) {
  1553. if (const ParmVarDecl *Parm
  1554. = dyn_cast_or_null<ParmVarDecl>(CXXRD->getLambdaContextDecl())) {
  1555. if (const FunctionDecl *Func
  1556. = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
  1557. Out << 'd';
  1558. unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
  1559. if (Num > 1)
  1560. mangleNumber(Num - 2);
  1561. Out << '_';
  1562. }
  1563. }
  1564. }
  1565. // Mangle the name relative to the closest enclosing function.
  1566. // equality ok because RD derived from ND above
  1567. if (D == RD) {
  1568. mangleUnqualifiedName(RD, DC, AdditionalAbiTags);
  1569. } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  1570. if (const NamedDecl *PrefixND = getClosurePrefix(BD))
  1571. mangleClosurePrefix(PrefixND, true /*NoFunction*/);
  1572. else
  1573. manglePrefix(Context.getEffectiveDeclContext(BD), true /*NoFunction*/);
  1574. assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
  1575. mangleUnqualifiedBlock(BD);
  1576. } else {
  1577. const NamedDecl *ND = cast<NamedDecl>(D);
  1578. mangleNestedName(GD, Context.getEffectiveDeclContext(ND),
  1579. AdditionalAbiTags, true /*NoFunction*/);
  1580. }
  1581. } else if (const BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
  1582. // Mangle a block in a default parameter; see above explanation for
  1583. // lambdas.
  1584. if (const ParmVarDecl *Parm
  1585. = dyn_cast_or_null<ParmVarDecl>(BD->getBlockManglingContextDecl())) {
  1586. if (const FunctionDecl *Func
  1587. = dyn_cast<FunctionDecl>(Parm->getDeclContext())) {
  1588. Out << 'd';
  1589. unsigned Num = Func->getNumParams() - Parm->getFunctionScopeIndex();
  1590. if (Num > 1)
  1591. mangleNumber(Num - 2);
  1592. Out << '_';
  1593. }
  1594. }
  1595. assert(!AdditionalAbiTags && "Block cannot have additional abi tags");
  1596. mangleUnqualifiedBlock(BD);
  1597. } else {
  1598. mangleUnqualifiedName(GD, DC, AdditionalAbiTags);
  1599. }
  1600. if (const NamedDecl *ND = dyn_cast<NamedDecl>(RD ? RD : D)) {
  1601. unsigned disc;
  1602. if (Context.getNextDiscriminator(ND, disc)) {
  1603. if (disc < 10)
  1604. Out << '_' << disc;
  1605. else
  1606. Out << "__" << disc << '_';
  1607. }
  1608. }
  1609. }
  1610. void CXXNameMangler::mangleBlockForPrefix(const BlockDecl *Block) {
  1611. if (GetLocalClassDecl(Block)) {
  1612. mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
  1613. return;
  1614. }
  1615. const DeclContext *DC = Context.getEffectiveDeclContext(Block);
  1616. if (isLocalContainerContext(DC)) {
  1617. mangleLocalName(Block, /* AdditionalAbiTags */ nullptr);
  1618. return;
  1619. }
  1620. if (const NamedDecl *PrefixND = getClosurePrefix(Block))
  1621. mangleClosurePrefix(PrefixND);
  1622. else
  1623. manglePrefix(DC);
  1624. mangleUnqualifiedBlock(Block);
  1625. }
  1626. void CXXNameMangler::mangleUnqualifiedBlock(const BlockDecl *Block) {
  1627. // When trying to be ABI-compatibility with clang 12 and before, mangle a
  1628. // <data-member-prefix> now, with no substitutions and no <template-args>.
  1629. if (Decl *Context = Block->getBlockManglingContextDecl()) {
  1630. if (getASTContext().getLangOpts().getClangABICompat() <=
  1631. LangOptions::ClangABI::Ver12 &&
  1632. (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
  1633. Context->getDeclContext()->isRecord()) {
  1634. const auto *ND = cast<NamedDecl>(Context);
  1635. if (ND->getIdentifier()) {
  1636. mangleSourceNameWithAbiTags(ND);
  1637. Out << 'M';
  1638. }
  1639. }
  1640. }
  1641. // If we have a block mangling number, use it.
  1642. unsigned Number = Block->getBlockManglingNumber();
  1643. // Otherwise, just make up a number. It doesn't matter what it is because
  1644. // the symbol in question isn't externally visible.
  1645. if (!Number)
  1646. Number = Context.getBlockId(Block, false);
  1647. else {
  1648. // Stored mangling numbers are 1-based.
  1649. --Number;
  1650. }
  1651. Out << "Ub";
  1652. if (Number > 0)
  1653. Out << Number - 1;
  1654. Out << '_';
  1655. }
  1656. // <template-param-decl>
  1657. // ::= Ty # template type parameter
  1658. // ::= Tn <type> # template non-type parameter
  1659. // ::= Tt <template-param-decl>* E # template template parameter
  1660. // ::= Tp <template-param-decl> # template parameter pack
  1661. void CXXNameMangler::mangleTemplateParamDecl(const NamedDecl *Decl) {
  1662. if (auto *Ty = dyn_cast<TemplateTypeParmDecl>(Decl)) {
  1663. if (Ty->isParameterPack())
  1664. Out << "Tp";
  1665. Out << "Ty";
  1666. } else if (auto *Tn = dyn_cast<NonTypeTemplateParmDecl>(Decl)) {
  1667. if (Tn->isExpandedParameterPack()) {
  1668. for (unsigned I = 0, N = Tn->getNumExpansionTypes(); I != N; ++I) {
  1669. Out << "Tn";
  1670. mangleType(Tn->getExpansionType(I));
  1671. }
  1672. } else {
  1673. QualType T = Tn->getType();
  1674. if (Tn->isParameterPack()) {
  1675. Out << "Tp";
  1676. if (auto *PackExpansion = T->getAs<PackExpansionType>())
  1677. T = PackExpansion->getPattern();
  1678. }
  1679. Out << "Tn";
  1680. mangleType(T);
  1681. }
  1682. } else if (auto *Tt = dyn_cast<TemplateTemplateParmDecl>(Decl)) {
  1683. if (Tt->isExpandedParameterPack()) {
  1684. for (unsigned I = 0, N = Tt->getNumExpansionTemplateParameters(); I != N;
  1685. ++I) {
  1686. Out << "Tt";
  1687. for (auto *Param : *Tt->getExpansionTemplateParameters(I))
  1688. mangleTemplateParamDecl(Param);
  1689. Out << "E";
  1690. }
  1691. } else {
  1692. if (Tt->isParameterPack())
  1693. Out << "Tp";
  1694. Out << "Tt";
  1695. for (auto *Param : *Tt->getTemplateParameters())
  1696. mangleTemplateParamDecl(Param);
  1697. Out << "E";
  1698. }
  1699. }
  1700. }
  1701. void CXXNameMangler::mangleLambda(const CXXRecordDecl *Lambda) {
  1702. // When trying to be ABI-compatibility with clang 12 and before, mangle a
  1703. // <data-member-prefix> now, with no substitutions.
  1704. if (Decl *Context = Lambda->getLambdaContextDecl()) {
  1705. if (getASTContext().getLangOpts().getClangABICompat() <=
  1706. LangOptions::ClangABI::Ver12 &&
  1707. (isa<VarDecl>(Context) || isa<FieldDecl>(Context)) &&
  1708. !isa<ParmVarDecl>(Context)) {
  1709. if (const IdentifierInfo *Name
  1710. = cast<NamedDecl>(Context)->getIdentifier()) {
  1711. mangleSourceName(Name);
  1712. const TemplateArgumentList *TemplateArgs = nullptr;
  1713. if (GlobalDecl TD = isTemplate(cast<NamedDecl>(Context), TemplateArgs))
  1714. mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
  1715. Out << 'M';
  1716. }
  1717. }
  1718. }
  1719. Out << "Ul";
  1720. mangleLambdaSig(Lambda);
  1721. Out << "E";
  1722. // The number is omitted for the first closure type with a given
  1723. // <lambda-sig> in a given context; it is n-2 for the nth closure type
  1724. // (in lexical order) with that same <lambda-sig> and context.
  1725. //
  1726. // The AST keeps track of the number for us.
  1727. //
  1728. // In CUDA/HIP, to ensure the consistent lamba numbering between the device-
  1729. // and host-side compilations, an extra device mangle context may be created
  1730. // if the host-side CXX ABI has different numbering for lambda. In such case,
  1731. // if the mangle context is that device-side one, use the device-side lambda
  1732. // mangling number for this lambda.
  1733. std::optional<unsigned> DeviceNumber =
  1734. Context.getDiscriminatorOverride()(Context.getASTContext(), Lambda);
  1735. unsigned Number =
  1736. DeviceNumber ? *DeviceNumber : Lambda->getLambdaManglingNumber();
  1737. assert(Number > 0 && "Lambda should be mangled as an unnamed class");
  1738. if (Number > 1)
  1739. mangleNumber(Number - 2);
  1740. Out << '_';
  1741. }
  1742. void CXXNameMangler::mangleLambdaSig(const CXXRecordDecl *Lambda) {
  1743. for (auto *D : Lambda->getLambdaExplicitTemplateParameters())
  1744. mangleTemplateParamDecl(D);
  1745. auto *Proto =
  1746. Lambda->getLambdaTypeInfo()->getType()->castAs<FunctionProtoType>();
  1747. mangleBareFunctionType(Proto, /*MangleReturnType=*/false,
  1748. Lambda->getLambdaStaticInvoker());
  1749. }
  1750. void CXXNameMangler::manglePrefix(NestedNameSpecifier *qualifier) {
  1751. switch (qualifier->getKind()) {
  1752. case NestedNameSpecifier::Global:
  1753. // nothing
  1754. return;
  1755. case NestedNameSpecifier::Super:
  1756. llvm_unreachable("Can't mangle __super specifier");
  1757. case NestedNameSpecifier::Namespace:
  1758. mangleName(qualifier->getAsNamespace());
  1759. return;
  1760. case NestedNameSpecifier::NamespaceAlias:
  1761. mangleName(qualifier->getAsNamespaceAlias()->getNamespace());
  1762. return;
  1763. case NestedNameSpecifier::TypeSpec:
  1764. case NestedNameSpecifier::TypeSpecWithTemplate:
  1765. manglePrefix(QualType(qualifier->getAsType(), 0));
  1766. return;
  1767. case NestedNameSpecifier::Identifier:
  1768. // Clang 14 and before did not consider this substitutable.
  1769. bool Clang14Compat = getASTContext().getLangOpts().getClangABICompat() <=
  1770. LangOptions::ClangABI::Ver14;
  1771. if (!Clang14Compat && mangleSubstitution(qualifier))
  1772. return;
  1773. // Member expressions can have these without prefixes, but that
  1774. // should end up in mangleUnresolvedPrefix instead.
  1775. assert(qualifier->getPrefix());
  1776. manglePrefix(qualifier->getPrefix());
  1777. mangleSourceName(qualifier->getAsIdentifier());
  1778. if (!Clang14Compat)
  1779. addSubstitution(qualifier);
  1780. return;
  1781. }
  1782. llvm_unreachable("unexpected nested name specifier");
  1783. }
  1784. void CXXNameMangler::manglePrefix(const DeclContext *DC, bool NoFunction) {
  1785. // <prefix> ::= <prefix> <unqualified-name>
  1786. // ::= <template-prefix> <template-args>
  1787. // ::= <closure-prefix>
  1788. // ::= <template-param>
  1789. // ::= # empty
  1790. // ::= <substitution>
  1791. assert(!isa<LinkageSpecDecl>(DC) && "prefix cannot be LinkageSpecDecl");
  1792. if (DC->isTranslationUnit())
  1793. return;
  1794. if (NoFunction && isLocalContainerContext(DC))
  1795. return;
  1796. assert(!isLocalContainerContext(DC));
  1797. const NamedDecl *ND = cast<NamedDecl>(DC);
  1798. if (mangleSubstitution(ND))
  1799. return;
  1800. // Check if we have a template-prefix or a closure-prefix.
  1801. const TemplateArgumentList *TemplateArgs = nullptr;
  1802. if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
  1803. mangleTemplatePrefix(TD);
  1804. mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
  1805. } else if (const NamedDecl *PrefixND = getClosurePrefix(ND)) {
  1806. mangleClosurePrefix(PrefixND, NoFunction);
  1807. mangleUnqualifiedName(ND, nullptr, nullptr);
  1808. } else {
  1809. const DeclContext *DC = Context.getEffectiveDeclContext(ND);
  1810. manglePrefix(DC, NoFunction);
  1811. mangleUnqualifiedName(ND, DC, nullptr);
  1812. }
  1813. addSubstitution(ND);
  1814. }
  1815. void CXXNameMangler::mangleTemplatePrefix(TemplateName Template) {
  1816. // <template-prefix> ::= <prefix> <template unqualified-name>
  1817. // ::= <template-param>
  1818. // ::= <substitution>
  1819. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  1820. return mangleTemplatePrefix(TD);
  1821. DependentTemplateName *Dependent = Template.getAsDependentTemplateName();
  1822. assert(Dependent && "unexpected template name kind");
  1823. // Clang 11 and before mangled the substitution for a dependent template name
  1824. // after already having emitted (a substitution for) the prefix.
  1825. bool Clang11Compat = getASTContext().getLangOpts().getClangABICompat() <=
  1826. LangOptions::ClangABI::Ver11;
  1827. if (!Clang11Compat && mangleSubstitution(Template))
  1828. return;
  1829. if (NestedNameSpecifier *Qualifier = Dependent->getQualifier())
  1830. manglePrefix(Qualifier);
  1831. if (Clang11Compat && mangleSubstitution(Template))
  1832. return;
  1833. if (const IdentifierInfo *Id = Dependent->getIdentifier())
  1834. mangleSourceName(Id);
  1835. else
  1836. mangleOperatorName(Dependent->getOperator(), UnknownArity);
  1837. addSubstitution(Template);
  1838. }
  1839. void CXXNameMangler::mangleTemplatePrefix(GlobalDecl GD,
  1840. bool NoFunction) {
  1841. const TemplateDecl *ND = cast<TemplateDecl>(GD.getDecl());
  1842. // <template-prefix> ::= <prefix> <template unqualified-name>
  1843. // ::= <template-param>
  1844. // ::= <substitution>
  1845. // <template-template-param> ::= <template-param>
  1846. // <substitution>
  1847. if (mangleSubstitution(ND))
  1848. return;
  1849. // <template-template-param> ::= <template-param>
  1850. if (const auto *TTP = dyn_cast<TemplateTemplateParmDecl>(ND)) {
  1851. mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
  1852. } else {
  1853. const DeclContext *DC = Context.getEffectiveDeclContext(ND);
  1854. manglePrefix(DC, NoFunction);
  1855. if (isa<BuiltinTemplateDecl>(ND) || isa<ConceptDecl>(ND))
  1856. mangleUnqualifiedName(GD, DC, nullptr);
  1857. else
  1858. mangleUnqualifiedName(GD.getWithDecl(ND->getTemplatedDecl()), DC,
  1859. nullptr);
  1860. }
  1861. addSubstitution(ND);
  1862. }
  1863. const NamedDecl *CXXNameMangler::getClosurePrefix(const Decl *ND) {
  1864. if (getASTContext().getLangOpts().getClangABICompat() <=
  1865. LangOptions::ClangABI::Ver12)
  1866. return nullptr;
  1867. const NamedDecl *Context = nullptr;
  1868. if (auto *Block = dyn_cast<BlockDecl>(ND)) {
  1869. Context = dyn_cast_or_null<NamedDecl>(Block->getBlockManglingContextDecl());
  1870. } else if (auto *RD = dyn_cast<CXXRecordDecl>(ND)) {
  1871. if (RD->isLambda())
  1872. Context = dyn_cast_or_null<NamedDecl>(RD->getLambdaContextDecl());
  1873. }
  1874. if (!Context)
  1875. return nullptr;
  1876. // Only lambdas within the initializer of a non-local variable or non-static
  1877. // data member get a <closure-prefix>.
  1878. if ((isa<VarDecl>(Context) && cast<VarDecl>(Context)->hasGlobalStorage()) ||
  1879. isa<FieldDecl>(Context))
  1880. return Context;
  1881. return nullptr;
  1882. }
  1883. void CXXNameMangler::mangleClosurePrefix(const NamedDecl *ND, bool NoFunction) {
  1884. // <closure-prefix> ::= [ <prefix> ] <unqualified-name> M
  1885. // ::= <template-prefix> <template-args> M
  1886. if (mangleSubstitution(ND))
  1887. return;
  1888. const TemplateArgumentList *TemplateArgs = nullptr;
  1889. if (GlobalDecl TD = isTemplate(ND, TemplateArgs)) {
  1890. mangleTemplatePrefix(TD, NoFunction);
  1891. mangleTemplateArgs(asTemplateName(TD), *TemplateArgs);
  1892. } else {
  1893. const auto *DC = Context.getEffectiveDeclContext(ND);
  1894. manglePrefix(DC, NoFunction);
  1895. mangleUnqualifiedName(ND, DC, nullptr);
  1896. }
  1897. Out << 'M';
  1898. addSubstitution(ND);
  1899. }
  1900. /// Mangles a template name under the production <type>. Required for
  1901. /// template template arguments.
  1902. /// <type> ::= <class-enum-type>
  1903. /// ::= <template-param>
  1904. /// ::= <substitution>
  1905. void CXXNameMangler::mangleType(TemplateName TN) {
  1906. if (mangleSubstitution(TN))
  1907. return;
  1908. TemplateDecl *TD = nullptr;
  1909. switch (TN.getKind()) {
  1910. case TemplateName::QualifiedTemplate:
  1911. case TemplateName::UsingTemplate:
  1912. case TemplateName::Template:
  1913. TD = TN.getAsTemplateDecl();
  1914. goto HaveDecl;
  1915. HaveDecl:
  1916. if (auto *TTP = dyn_cast<TemplateTemplateParmDecl>(TD))
  1917. mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
  1918. else
  1919. mangleName(TD);
  1920. break;
  1921. case TemplateName::OverloadedTemplate:
  1922. case TemplateName::AssumedTemplate:
  1923. llvm_unreachable("can't mangle an overloaded template name as a <type>");
  1924. case TemplateName::DependentTemplate: {
  1925. const DependentTemplateName *Dependent = TN.getAsDependentTemplateName();
  1926. assert(Dependent->isIdentifier());
  1927. // <class-enum-type> ::= <name>
  1928. // <name> ::= <nested-name>
  1929. mangleUnresolvedPrefix(Dependent->getQualifier());
  1930. mangleSourceName(Dependent->getIdentifier());
  1931. break;
  1932. }
  1933. case TemplateName::SubstTemplateTemplateParm: {
  1934. // Substituted template parameters are mangled as the substituted
  1935. // template. This will check for the substitution twice, which is
  1936. // fine, but we have to return early so that we don't try to *add*
  1937. // the substitution twice.
  1938. SubstTemplateTemplateParmStorage *subst
  1939. = TN.getAsSubstTemplateTemplateParm();
  1940. mangleType(subst->getReplacement());
  1941. return;
  1942. }
  1943. case TemplateName::SubstTemplateTemplateParmPack: {
  1944. // FIXME: not clear how to mangle this!
  1945. // template <template <class> class T...> class A {
  1946. // template <template <class> class U...> void foo(B<T,U> x...);
  1947. // };
  1948. Out << "_SUBSTPACK_";
  1949. break;
  1950. }
  1951. }
  1952. addSubstitution(TN);
  1953. }
  1954. bool CXXNameMangler::mangleUnresolvedTypeOrSimpleId(QualType Ty,
  1955. StringRef Prefix) {
  1956. // Only certain other types are valid as prefixes; enumerate them.
  1957. switch (Ty->getTypeClass()) {
  1958. case Type::Builtin:
  1959. case Type::Complex:
  1960. case Type::Adjusted:
  1961. case Type::Decayed:
  1962. case Type::Pointer:
  1963. case Type::BlockPointer:
  1964. case Type::LValueReference:
  1965. case Type::RValueReference:
  1966. case Type::MemberPointer:
  1967. case Type::ConstantArray:
  1968. case Type::IncompleteArray:
  1969. case Type::VariableArray:
  1970. case Type::DependentSizedArray:
  1971. case Type::DependentAddressSpace:
  1972. case Type::DependentVector:
  1973. case Type::DependentSizedExtVector:
  1974. case Type::Vector:
  1975. case Type::ExtVector:
  1976. case Type::ConstantMatrix:
  1977. case Type::DependentSizedMatrix:
  1978. case Type::FunctionProto:
  1979. case Type::FunctionNoProto:
  1980. case Type::Paren:
  1981. case Type::Attributed:
  1982. case Type::BTFTagAttributed:
  1983. case Type::Auto:
  1984. case Type::DeducedTemplateSpecialization:
  1985. case Type::PackExpansion:
  1986. case Type::ObjCObject:
  1987. case Type::ObjCInterface:
  1988. case Type::ObjCObjectPointer:
  1989. case Type::ObjCTypeParam:
  1990. case Type::Atomic:
  1991. case Type::Pipe:
  1992. case Type::MacroQualified:
  1993. case Type::BitInt:
  1994. case Type::DependentBitInt:
  1995. llvm_unreachable("type is illegal as a nested name specifier");
  1996. case Type::SubstTemplateTypeParmPack:
  1997. // FIXME: not clear how to mangle this!
  1998. // template <class T...> class A {
  1999. // template <class U...> void foo(decltype(T::foo(U())) x...);
  2000. // };
  2001. Out << "_SUBSTPACK_";
  2002. break;
  2003. // <unresolved-type> ::= <template-param>
  2004. // ::= <decltype>
  2005. // ::= <template-template-param> <template-args>
  2006. // (this last is not official yet)
  2007. case Type::TypeOfExpr:
  2008. case Type::TypeOf:
  2009. case Type::Decltype:
  2010. case Type::TemplateTypeParm:
  2011. case Type::UnaryTransform:
  2012. case Type::SubstTemplateTypeParm:
  2013. unresolvedType:
  2014. // Some callers want a prefix before the mangled type.
  2015. Out << Prefix;
  2016. // This seems to do everything we want. It's not really
  2017. // sanctioned for a substituted template parameter, though.
  2018. mangleType(Ty);
  2019. // We never want to print 'E' directly after an unresolved-type,
  2020. // so we return directly.
  2021. return true;
  2022. case Type::Typedef:
  2023. mangleSourceNameWithAbiTags(cast<TypedefType>(Ty)->getDecl());
  2024. break;
  2025. case Type::UnresolvedUsing:
  2026. mangleSourceNameWithAbiTags(
  2027. cast<UnresolvedUsingType>(Ty)->getDecl());
  2028. break;
  2029. case Type::Enum:
  2030. case Type::Record:
  2031. mangleSourceNameWithAbiTags(cast<TagType>(Ty)->getDecl());
  2032. break;
  2033. case Type::TemplateSpecialization: {
  2034. const TemplateSpecializationType *TST =
  2035. cast<TemplateSpecializationType>(Ty);
  2036. TemplateName TN = TST->getTemplateName();
  2037. switch (TN.getKind()) {
  2038. case TemplateName::Template:
  2039. case TemplateName::QualifiedTemplate: {
  2040. TemplateDecl *TD = TN.getAsTemplateDecl();
  2041. // If the base is a template template parameter, this is an
  2042. // unresolved type.
  2043. assert(TD && "no template for template specialization type");
  2044. if (isa<TemplateTemplateParmDecl>(TD))
  2045. goto unresolvedType;
  2046. mangleSourceNameWithAbiTags(TD);
  2047. break;
  2048. }
  2049. case TemplateName::OverloadedTemplate:
  2050. case TemplateName::AssumedTemplate:
  2051. case TemplateName::DependentTemplate:
  2052. llvm_unreachable("invalid base for a template specialization type");
  2053. case TemplateName::SubstTemplateTemplateParm: {
  2054. SubstTemplateTemplateParmStorage *subst =
  2055. TN.getAsSubstTemplateTemplateParm();
  2056. mangleExistingSubstitution(subst->getReplacement());
  2057. break;
  2058. }
  2059. case TemplateName::SubstTemplateTemplateParmPack: {
  2060. // FIXME: not clear how to mangle this!
  2061. // template <template <class U> class T...> class A {
  2062. // template <class U...> void foo(decltype(T<U>::foo) x...);
  2063. // };
  2064. Out << "_SUBSTPACK_";
  2065. break;
  2066. }
  2067. case TemplateName::UsingTemplate: {
  2068. TemplateDecl *TD = TN.getAsTemplateDecl();
  2069. assert(TD && !isa<TemplateTemplateParmDecl>(TD));
  2070. mangleSourceNameWithAbiTags(TD);
  2071. break;
  2072. }
  2073. }
  2074. // Note: we don't pass in the template name here. We are mangling the
  2075. // original source-level template arguments, so we shouldn't consider
  2076. // conversions to the corresponding template parameter.
  2077. // FIXME: Other compilers mangle partially-resolved template arguments in
  2078. // unresolved-qualifier-levels.
  2079. mangleTemplateArgs(TemplateName(), TST->template_arguments());
  2080. break;
  2081. }
  2082. case Type::InjectedClassName:
  2083. mangleSourceNameWithAbiTags(
  2084. cast<InjectedClassNameType>(Ty)->getDecl());
  2085. break;
  2086. case Type::DependentName:
  2087. mangleSourceName(cast<DependentNameType>(Ty)->getIdentifier());
  2088. break;
  2089. case Type::DependentTemplateSpecialization: {
  2090. const DependentTemplateSpecializationType *DTST =
  2091. cast<DependentTemplateSpecializationType>(Ty);
  2092. TemplateName Template = getASTContext().getDependentTemplateName(
  2093. DTST->getQualifier(), DTST->getIdentifier());
  2094. mangleSourceName(DTST->getIdentifier());
  2095. mangleTemplateArgs(Template, DTST->template_arguments());
  2096. break;
  2097. }
  2098. case Type::Using:
  2099. return mangleUnresolvedTypeOrSimpleId(cast<UsingType>(Ty)->desugar(),
  2100. Prefix);
  2101. case Type::Elaborated:
  2102. return mangleUnresolvedTypeOrSimpleId(
  2103. cast<ElaboratedType>(Ty)->getNamedType(), Prefix);
  2104. }
  2105. return false;
  2106. }
  2107. void CXXNameMangler::mangleOperatorName(DeclarationName Name, unsigned Arity) {
  2108. switch (Name.getNameKind()) {
  2109. case DeclarationName::CXXConstructorName:
  2110. case DeclarationName::CXXDestructorName:
  2111. case DeclarationName::CXXDeductionGuideName:
  2112. case DeclarationName::CXXUsingDirective:
  2113. case DeclarationName::Identifier:
  2114. case DeclarationName::ObjCMultiArgSelector:
  2115. case DeclarationName::ObjCOneArgSelector:
  2116. case DeclarationName::ObjCZeroArgSelector:
  2117. llvm_unreachable("Not an operator name");
  2118. case DeclarationName::CXXConversionFunctionName:
  2119. // <operator-name> ::= cv <type> # (cast)
  2120. Out << "cv";
  2121. mangleType(Name.getCXXNameType());
  2122. break;
  2123. case DeclarationName::CXXLiteralOperatorName:
  2124. Out << "li";
  2125. mangleSourceName(Name.getCXXLiteralIdentifier());
  2126. return;
  2127. case DeclarationName::CXXOperatorName:
  2128. mangleOperatorName(Name.getCXXOverloadedOperator(), Arity);
  2129. break;
  2130. }
  2131. }
  2132. void
  2133. CXXNameMangler::mangleOperatorName(OverloadedOperatorKind OO, unsigned Arity) {
  2134. switch (OO) {
  2135. // <operator-name> ::= nw # new
  2136. case OO_New: Out << "nw"; break;
  2137. // ::= na # new[]
  2138. case OO_Array_New: Out << "na"; break;
  2139. // ::= dl # delete
  2140. case OO_Delete: Out << "dl"; break;
  2141. // ::= da # delete[]
  2142. case OO_Array_Delete: Out << "da"; break;
  2143. // ::= ps # + (unary)
  2144. // ::= pl # + (binary or unknown)
  2145. case OO_Plus:
  2146. Out << (Arity == 1? "ps" : "pl"); break;
  2147. // ::= ng # - (unary)
  2148. // ::= mi # - (binary or unknown)
  2149. case OO_Minus:
  2150. Out << (Arity == 1? "ng" : "mi"); break;
  2151. // ::= ad # & (unary)
  2152. // ::= an # & (binary or unknown)
  2153. case OO_Amp:
  2154. Out << (Arity == 1? "ad" : "an"); break;
  2155. // ::= de # * (unary)
  2156. // ::= ml # * (binary or unknown)
  2157. case OO_Star:
  2158. // Use binary when unknown.
  2159. Out << (Arity == 1? "de" : "ml"); break;
  2160. // ::= co # ~
  2161. case OO_Tilde: Out << "co"; break;
  2162. // ::= dv # /
  2163. case OO_Slash: Out << "dv"; break;
  2164. // ::= rm # %
  2165. case OO_Percent: Out << "rm"; break;
  2166. // ::= or # |
  2167. case OO_Pipe: Out << "or"; break;
  2168. // ::= eo # ^
  2169. case OO_Caret: Out << "eo"; break;
  2170. // ::= aS # =
  2171. case OO_Equal: Out << "aS"; break;
  2172. // ::= pL # +=
  2173. case OO_PlusEqual: Out << "pL"; break;
  2174. // ::= mI # -=
  2175. case OO_MinusEqual: Out << "mI"; break;
  2176. // ::= mL # *=
  2177. case OO_StarEqual: Out << "mL"; break;
  2178. // ::= dV # /=
  2179. case OO_SlashEqual: Out << "dV"; break;
  2180. // ::= rM # %=
  2181. case OO_PercentEqual: Out << "rM"; break;
  2182. // ::= aN # &=
  2183. case OO_AmpEqual: Out << "aN"; break;
  2184. // ::= oR # |=
  2185. case OO_PipeEqual: Out << "oR"; break;
  2186. // ::= eO # ^=
  2187. case OO_CaretEqual: Out << "eO"; break;
  2188. // ::= ls # <<
  2189. case OO_LessLess: Out << "ls"; break;
  2190. // ::= rs # >>
  2191. case OO_GreaterGreater: Out << "rs"; break;
  2192. // ::= lS # <<=
  2193. case OO_LessLessEqual: Out << "lS"; break;
  2194. // ::= rS # >>=
  2195. case OO_GreaterGreaterEqual: Out << "rS"; break;
  2196. // ::= eq # ==
  2197. case OO_EqualEqual: Out << "eq"; break;
  2198. // ::= ne # !=
  2199. case OO_ExclaimEqual: Out << "ne"; break;
  2200. // ::= lt # <
  2201. case OO_Less: Out << "lt"; break;
  2202. // ::= gt # >
  2203. case OO_Greater: Out << "gt"; break;
  2204. // ::= le # <=
  2205. case OO_LessEqual: Out << "le"; break;
  2206. // ::= ge # >=
  2207. case OO_GreaterEqual: Out << "ge"; break;
  2208. // ::= nt # !
  2209. case OO_Exclaim: Out << "nt"; break;
  2210. // ::= aa # &&
  2211. case OO_AmpAmp: Out << "aa"; break;
  2212. // ::= oo # ||
  2213. case OO_PipePipe: Out << "oo"; break;
  2214. // ::= pp # ++
  2215. case OO_PlusPlus: Out << "pp"; break;
  2216. // ::= mm # --
  2217. case OO_MinusMinus: Out << "mm"; break;
  2218. // ::= cm # ,
  2219. case OO_Comma: Out << "cm"; break;
  2220. // ::= pm # ->*
  2221. case OO_ArrowStar: Out << "pm"; break;
  2222. // ::= pt # ->
  2223. case OO_Arrow: Out << "pt"; break;
  2224. // ::= cl # ()
  2225. case OO_Call: Out << "cl"; break;
  2226. // ::= ix # []
  2227. case OO_Subscript: Out << "ix"; break;
  2228. // ::= qu # ?
  2229. // The conditional operator can't be overloaded, but we still handle it when
  2230. // mangling expressions.
  2231. case OO_Conditional: Out << "qu"; break;
  2232. // Proposal on cxx-abi-dev, 2015-10-21.
  2233. // ::= aw # co_await
  2234. case OO_Coawait: Out << "aw"; break;
  2235. // Proposed in cxx-abi github issue 43.
  2236. // ::= ss # <=>
  2237. case OO_Spaceship: Out << "ss"; break;
  2238. case OO_None:
  2239. case NUM_OVERLOADED_OPERATORS:
  2240. llvm_unreachable("Not an overloaded operator");
  2241. }
  2242. }
  2243. void CXXNameMangler::mangleQualifiers(Qualifiers Quals, const DependentAddressSpaceType *DAST) {
  2244. // Vendor qualifiers come first and if they are order-insensitive they must
  2245. // be emitted in reversed alphabetical order, see Itanium ABI 5.1.5.
  2246. // <type> ::= U <addrspace-expr>
  2247. if (DAST) {
  2248. Out << "U2ASI";
  2249. mangleExpression(DAST->getAddrSpaceExpr());
  2250. Out << "E";
  2251. }
  2252. // Address space qualifiers start with an ordinary letter.
  2253. if (Quals.hasAddressSpace()) {
  2254. // Address space extension:
  2255. //
  2256. // <type> ::= U <target-addrspace>
  2257. // <type> ::= U <OpenCL-addrspace>
  2258. // <type> ::= U <CUDA-addrspace>
  2259. SmallString<64> ASString;
  2260. LangAS AS = Quals.getAddressSpace();
  2261. if (Context.getASTContext().addressSpaceMapManglingFor(AS)) {
  2262. // <target-addrspace> ::= "AS" <address-space-number>
  2263. unsigned TargetAS = Context.getASTContext().getTargetAddressSpace(AS);
  2264. if (TargetAS != 0 ||
  2265. Context.getASTContext().getTargetAddressSpace(LangAS::Default) != 0)
  2266. ASString = "AS" + llvm::utostr(TargetAS);
  2267. } else {
  2268. switch (AS) {
  2269. default: llvm_unreachable("Not a language specific address space");
  2270. // <OpenCL-addrspace> ::= "CL" [ "global" | "local" | "constant" |
  2271. // "private"| "generic" | "device" |
  2272. // "host" ]
  2273. case LangAS::opencl_global:
  2274. ASString = "CLglobal";
  2275. break;
  2276. case LangAS::opencl_global_device:
  2277. ASString = "CLdevice";
  2278. break;
  2279. case LangAS::opencl_global_host:
  2280. ASString = "CLhost";
  2281. break;
  2282. case LangAS::opencl_local:
  2283. ASString = "CLlocal";
  2284. break;
  2285. case LangAS::opencl_constant:
  2286. ASString = "CLconstant";
  2287. break;
  2288. case LangAS::opencl_private:
  2289. ASString = "CLprivate";
  2290. break;
  2291. case LangAS::opencl_generic:
  2292. ASString = "CLgeneric";
  2293. break;
  2294. // <SYCL-addrspace> ::= "SY" [ "global" | "local" | "private" |
  2295. // "device" | "host" ]
  2296. case LangAS::sycl_global:
  2297. ASString = "SYglobal";
  2298. break;
  2299. case LangAS::sycl_global_device:
  2300. ASString = "SYdevice";
  2301. break;
  2302. case LangAS::sycl_global_host:
  2303. ASString = "SYhost";
  2304. break;
  2305. case LangAS::sycl_local:
  2306. ASString = "SYlocal";
  2307. break;
  2308. case LangAS::sycl_private:
  2309. ASString = "SYprivate";
  2310. break;
  2311. // <CUDA-addrspace> ::= "CU" [ "device" | "constant" | "shared" ]
  2312. case LangAS::cuda_device:
  2313. ASString = "CUdevice";
  2314. break;
  2315. case LangAS::cuda_constant:
  2316. ASString = "CUconstant";
  2317. break;
  2318. case LangAS::cuda_shared:
  2319. ASString = "CUshared";
  2320. break;
  2321. // <ptrsize-addrspace> ::= [ "ptr32_sptr" | "ptr32_uptr" | "ptr64" ]
  2322. case LangAS::ptr32_sptr:
  2323. ASString = "ptr32_sptr";
  2324. break;
  2325. case LangAS::ptr32_uptr:
  2326. ASString = "ptr32_uptr";
  2327. break;
  2328. case LangAS::ptr64:
  2329. ASString = "ptr64";
  2330. break;
  2331. }
  2332. }
  2333. if (!ASString.empty())
  2334. mangleVendorQualifier(ASString);
  2335. }
  2336. // The ARC ownership qualifiers start with underscores.
  2337. // Objective-C ARC Extension:
  2338. //
  2339. // <type> ::= U "__strong"
  2340. // <type> ::= U "__weak"
  2341. // <type> ::= U "__autoreleasing"
  2342. //
  2343. // Note: we emit __weak first to preserve the order as
  2344. // required by the Itanium ABI.
  2345. if (Quals.getObjCLifetime() == Qualifiers::OCL_Weak)
  2346. mangleVendorQualifier("__weak");
  2347. // __unaligned (from -fms-extensions)
  2348. if (Quals.hasUnaligned())
  2349. mangleVendorQualifier("__unaligned");
  2350. // Remaining ARC ownership qualifiers.
  2351. switch (Quals.getObjCLifetime()) {
  2352. case Qualifiers::OCL_None:
  2353. break;
  2354. case Qualifiers::OCL_Weak:
  2355. // Do nothing as we already handled this case above.
  2356. break;
  2357. case Qualifiers::OCL_Strong:
  2358. mangleVendorQualifier("__strong");
  2359. break;
  2360. case Qualifiers::OCL_Autoreleasing:
  2361. mangleVendorQualifier("__autoreleasing");
  2362. break;
  2363. case Qualifiers::OCL_ExplicitNone:
  2364. // The __unsafe_unretained qualifier is *not* mangled, so that
  2365. // __unsafe_unretained types in ARC produce the same manglings as the
  2366. // equivalent (but, naturally, unqualified) types in non-ARC, providing
  2367. // better ABI compatibility.
  2368. //
  2369. // It's safe to do this because unqualified 'id' won't show up
  2370. // in any type signatures that need to be mangled.
  2371. break;
  2372. }
  2373. // <CV-qualifiers> ::= [r] [V] [K] # restrict (C99), volatile, const
  2374. if (Quals.hasRestrict())
  2375. Out << 'r';
  2376. if (Quals.hasVolatile())
  2377. Out << 'V';
  2378. if (Quals.hasConst())
  2379. Out << 'K';
  2380. }
  2381. void CXXNameMangler::mangleVendorQualifier(StringRef name) {
  2382. Out << 'U' << name.size() << name;
  2383. }
  2384. void CXXNameMangler::mangleRefQualifier(RefQualifierKind RefQualifier) {
  2385. // <ref-qualifier> ::= R # lvalue reference
  2386. // ::= O # rvalue-reference
  2387. switch (RefQualifier) {
  2388. case RQ_None:
  2389. break;
  2390. case RQ_LValue:
  2391. Out << 'R';
  2392. break;
  2393. case RQ_RValue:
  2394. Out << 'O';
  2395. break;
  2396. }
  2397. }
  2398. void CXXNameMangler::mangleObjCMethodName(const ObjCMethodDecl *MD) {
  2399. Context.mangleObjCMethodNameAsSourceName(MD, Out);
  2400. }
  2401. static bool isTypeSubstitutable(Qualifiers Quals, const Type *Ty,
  2402. ASTContext &Ctx) {
  2403. if (Quals)
  2404. return true;
  2405. if (Ty->isSpecificBuiltinType(BuiltinType::ObjCSel))
  2406. return true;
  2407. if (Ty->isOpenCLSpecificType())
  2408. return true;
  2409. if (Ty->isBuiltinType())
  2410. return false;
  2411. // Through to Clang 6.0, we accidentally treated undeduced auto types as
  2412. // substitution candidates.
  2413. if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver6 &&
  2414. isa<AutoType>(Ty))
  2415. return false;
  2416. // A placeholder type for class template deduction is substitutable with
  2417. // its corresponding template name; this is handled specially when mangling
  2418. // the type.
  2419. if (auto *DeducedTST = Ty->getAs<DeducedTemplateSpecializationType>())
  2420. if (DeducedTST->getDeducedType().isNull())
  2421. return false;
  2422. return true;
  2423. }
  2424. void CXXNameMangler::mangleType(QualType T) {
  2425. // If our type is instantiation-dependent but not dependent, we mangle
  2426. // it as it was written in the source, removing any top-level sugar.
  2427. // Otherwise, use the canonical type.
  2428. //
  2429. // FIXME: This is an approximation of the instantiation-dependent name
  2430. // mangling rules, since we should really be using the type as written and
  2431. // augmented via semantic analysis (i.e., with implicit conversions and
  2432. // default template arguments) for any instantiation-dependent type.
  2433. // Unfortunately, that requires several changes to our AST:
  2434. // - Instantiation-dependent TemplateSpecializationTypes will need to be
  2435. // uniqued, so that we can handle substitutions properly
  2436. // - Default template arguments will need to be represented in the
  2437. // TemplateSpecializationType, since they need to be mangled even though
  2438. // they aren't written.
  2439. // - Conversions on non-type template arguments need to be expressed, since
  2440. // they can affect the mangling of sizeof/alignof.
  2441. //
  2442. // FIXME: This is wrong when mapping to the canonical type for a dependent
  2443. // type discards instantiation-dependent portions of the type, such as for:
  2444. //
  2445. // template<typename T, int N> void f(T (&)[sizeof(N)]);
  2446. // template<typename T> void f(T() throw(typename T::type)); (pre-C++17)
  2447. //
  2448. // It's also wrong in the opposite direction when instantiation-dependent,
  2449. // canonically-equivalent types differ in some irrelevant portion of inner
  2450. // type sugar. In such cases, we fail to form correct substitutions, eg:
  2451. //
  2452. // template<int N> void f(A<sizeof(N)> *, A<sizeof(N)> (*));
  2453. //
  2454. // We should instead canonicalize the non-instantiation-dependent parts,
  2455. // regardless of whether the type as a whole is dependent or instantiation
  2456. // dependent.
  2457. if (!T->isInstantiationDependentType() || T->isDependentType())
  2458. T = T.getCanonicalType();
  2459. else {
  2460. // Desugar any types that are purely sugar.
  2461. do {
  2462. // Don't desugar through template specialization types that aren't
  2463. // type aliases. We need to mangle the template arguments as written.
  2464. if (const TemplateSpecializationType *TST
  2465. = dyn_cast<TemplateSpecializationType>(T))
  2466. if (!TST->isTypeAlias())
  2467. break;
  2468. // FIXME: We presumably shouldn't strip off ElaboratedTypes with
  2469. // instantation-dependent qualifiers. See
  2470. // https://github.com/itanium-cxx-abi/cxx-abi/issues/114.
  2471. QualType Desugared
  2472. = T.getSingleStepDesugaredType(Context.getASTContext());
  2473. if (Desugared == T)
  2474. break;
  2475. T = Desugared;
  2476. } while (true);
  2477. }
  2478. SplitQualType split = T.split();
  2479. Qualifiers quals = split.Quals;
  2480. const Type *ty = split.Ty;
  2481. bool isSubstitutable =
  2482. isTypeSubstitutable(quals, ty, Context.getASTContext());
  2483. if (isSubstitutable && mangleSubstitution(T))
  2484. return;
  2485. // If we're mangling a qualified array type, push the qualifiers to
  2486. // the element type.
  2487. if (quals && isa<ArrayType>(T)) {
  2488. ty = Context.getASTContext().getAsArrayType(T);
  2489. quals = Qualifiers();
  2490. // Note that we don't update T: we want to add the
  2491. // substitution at the original type.
  2492. }
  2493. if (quals || ty->isDependentAddressSpaceType()) {
  2494. if (const DependentAddressSpaceType *DAST =
  2495. dyn_cast<DependentAddressSpaceType>(ty)) {
  2496. SplitQualType splitDAST = DAST->getPointeeType().split();
  2497. mangleQualifiers(splitDAST.Quals, DAST);
  2498. mangleType(QualType(splitDAST.Ty, 0));
  2499. } else {
  2500. mangleQualifiers(quals);
  2501. // Recurse: even if the qualified type isn't yet substitutable,
  2502. // the unqualified type might be.
  2503. mangleType(QualType(ty, 0));
  2504. }
  2505. } else {
  2506. switch (ty->getTypeClass()) {
  2507. #define ABSTRACT_TYPE(CLASS, PARENT)
  2508. #define NON_CANONICAL_TYPE(CLASS, PARENT) \
  2509. case Type::CLASS: \
  2510. llvm_unreachable("can't mangle non-canonical type " #CLASS "Type"); \
  2511. return;
  2512. #define TYPE(CLASS, PARENT) \
  2513. case Type::CLASS: \
  2514. mangleType(static_cast<const CLASS##Type*>(ty)); \
  2515. break;
  2516. #include "clang/AST/TypeNodes.inc"
  2517. }
  2518. }
  2519. // Add the substitution.
  2520. if (isSubstitutable)
  2521. addSubstitution(T);
  2522. }
  2523. void CXXNameMangler::mangleNameOrStandardSubstitution(const NamedDecl *ND) {
  2524. if (!mangleStandardSubstitution(ND))
  2525. mangleName(ND);
  2526. }
  2527. void CXXNameMangler::mangleType(const BuiltinType *T) {
  2528. // <type> ::= <builtin-type>
  2529. // <builtin-type> ::= v # void
  2530. // ::= w # wchar_t
  2531. // ::= b # bool
  2532. // ::= c # char
  2533. // ::= a # signed char
  2534. // ::= h # unsigned char
  2535. // ::= s # short
  2536. // ::= t # unsigned short
  2537. // ::= i # int
  2538. // ::= j # unsigned int
  2539. // ::= l # long
  2540. // ::= m # unsigned long
  2541. // ::= x # long long, __int64
  2542. // ::= y # unsigned long long, __int64
  2543. // ::= n # __int128
  2544. // ::= o # unsigned __int128
  2545. // ::= f # float
  2546. // ::= d # double
  2547. // ::= e # long double, __float80
  2548. // ::= g # __float128
  2549. // ::= g # __ibm128
  2550. // UNSUPPORTED: ::= Dd # IEEE 754r decimal floating point (64 bits)
  2551. // UNSUPPORTED: ::= De # IEEE 754r decimal floating point (128 bits)
  2552. // UNSUPPORTED: ::= Df # IEEE 754r decimal floating point (32 bits)
  2553. // ::= Dh # IEEE 754r half-precision floating point (16 bits)
  2554. // ::= DF <number> _ # ISO/IEC TS 18661 binary floating point type _FloatN (N bits);
  2555. // ::= Di # char32_t
  2556. // ::= Ds # char16_t
  2557. // ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
  2558. // ::= u <source-name> # vendor extended type
  2559. std::string type_name;
  2560. switch (T->getKind()) {
  2561. case BuiltinType::Void:
  2562. Out << 'v';
  2563. break;
  2564. case BuiltinType::Bool:
  2565. Out << 'b';
  2566. break;
  2567. case BuiltinType::Char_U:
  2568. case BuiltinType::Char_S:
  2569. Out << 'c';
  2570. break;
  2571. case BuiltinType::UChar:
  2572. Out << 'h';
  2573. break;
  2574. case BuiltinType::UShort:
  2575. Out << 't';
  2576. break;
  2577. case BuiltinType::UInt:
  2578. Out << 'j';
  2579. break;
  2580. case BuiltinType::ULong:
  2581. Out << 'm';
  2582. break;
  2583. case BuiltinType::ULongLong:
  2584. Out << 'y';
  2585. break;
  2586. case BuiltinType::UInt128:
  2587. Out << 'o';
  2588. break;
  2589. case BuiltinType::SChar:
  2590. Out << 'a';
  2591. break;
  2592. case BuiltinType::WChar_S:
  2593. case BuiltinType::WChar_U:
  2594. Out << 'w';
  2595. break;
  2596. case BuiltinType::Char8:
  2597. Out << "Du";
  2598. break;
  2599. case BuiltinType::Char16:
  2600. Out << "Ds";
  2601. break;
  2602. case BuiltinType::Char32:
  2603. Out << "Di";
  2604. break;
  2605. case BuiltinType::Short:
  2606. Out << 's';
  2607. break;
  2608. case BuiltinType::Int:
  2609. Out << 'i';
  2610. break;
  2611. case BuiltinType::Long:
  2612. Out << 'l';
  2613. break;
  2614. case BuiltinType::LongLong:
  2615. Out << 'x';
  2616. break;
  2617. case BuiltinType::Int128:
  2618. Out << 'n';
  2619. break;
  2620. case BuiltinType::Float16:
  2621. Out << "DF16_";
  2622. break;
  2623. case BuiltinType::ShortAccum:
  2624. case BuiltinType::Accum:
  2625. case BuiltinType::LongAccum:
  2626. case BuiltinType::UShortAccum:
  2627. case BuiltinType::UAccum:
  2628. case BuiltinType::ULongAccum:
  2629. case BuiltinType::ShortFract:
  2630. case BuiltinType::Fract:
  2631. case BuiltinType::LongFract:
  2632. case BuiltinType::UShortFract:
  2633. case BuiltinType::UFract:
  2634. case BuiltinType::ULongFract:
  2635. case BuiltinType::SatShortAccum:
  2636. case BuiltinType::SatAccum:
  2637. case BuiltinType::SatLongAccum:
  2638. case BuiltinType::SatUShortAccum:
  2639. case BuiltinType::SatUAccum:
  2640. case BuiltinType::SatULongAccum:
  2641. case BuiltinType::SatShortFract:
  2642. case BuiltinType::SatFract:
  2643. case BuiltinType::SatLongFract:
  2644. case BuiltinType::SatUShortFract:
  2645. case BuiltinType::SatUFract:
  2646. case BuiltinType::SatULongFract:
  2647. llvm_unreachable("Fixed point types are disabled for c++");
  2648. case BuiltinType::Half:
  2649. Out << "Dh";
  2650. break;
  2651. case BuiltinType::Float:
  2652. Out << 'f';
  2653. break;
  2654. case BuiltinType::Double:
  2655. Out << 'd';
  2656. break;
  2657. case BuiltinType::LongDouble: {
  2658. const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
  2659. getASTContext().getLangOpts().OpenMPIsDevice
  2660. ? getASTContext().getAuxTargetInfo()
  2661. : &getASTContext().getTargetInfo();
  2662. Out << TI->getLongDoubleMangling();
  2663. break;
  2664. }
  2665. case BuiltinType::Float128: {
  2666. const TargetInfo *TI = getASTContext().getLangOpts().OpenMP &&
  2667. getASTContext().getLangOpts().OpenMPIsDevice
  2668. ? getASTContext().getAuxTargetInfo()
  2669. : &getASTContext().getTargetInfo();
  2670. Out << TI->getFloat128Mangling();
  2671. break;
  2672. }
  2673. case BuiltinType::BFloat16: {
  2674. const TargetInfo *TI = &getASTContext().getTargetInfo();
  2675. Out << TI->getBFloat16Mangling();
  2676. break;
  2677. }
  2678. case BuiltinType::Ibm128: {
  2679. const TargetInfo *TI = &getASTContext().getTargetInfo();
  2680. Out << TI->getIbm128Mangling();
  2681. break;
  2682. }
  2683. case BuiltinType::NullPtr:
  2684. Out << "Dn";
  2685. break;
  2686. #define BUILTIN_TYPE(Id, SingletonId)
  2687. #define PLACEHOLDER_TYPE(Id, SingletonId) \
  2688. case BuiltinType::Id:
  2689. #include "clang/AST/BuiltinTypes.def"
  2690. case BuiltinType::Dependent:
  2691. if (!NullOut)
  2692. llvm_unreachable("mangling a placeholder type");
  2693. break;
  2694. case BuiltinType::ObjCId:
  2695. Out << "11objc_object";
  2696. break;
  2697. case BuiltinType::ObjCClass:
  2698. Out << "10objc_class";
  2699. break;
  2700. case BuiltinType::ObjCSel:
  2701. Out << "13objc_selector";
  2702. break;
  2703. #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
  2704. case BuiltinType::Id: \
  2705. type_name = "ocl_" #ImgType "_" #Suffix; \
  2706. Out << type_name.size() << type_name; \
  2707. break;
  2708. #include "clang/Basic/OpenCLImageTypes.def"
  2709. case BuiltinType::OCLSampler:
  2710. Out << "11ocl_sampler";
  2711. break;
  2712. case BuiltinType::OCLEvent:
  2713. Out << "9ocl_event";
  2714. break;
  2715. case BuiltinType::OCLClkEvent:
  2716. Out << "12ocl_clkevent";
  2717. break;
  2718. case BuiltinType::OCLQueue:
  2719. Out << "9ocl_queue";
  2720. break;
  2721. case BuiltinType::OCLReserveID:
  2722. Out << "13ocl_reserveid";
  2723. break;
  2724. #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
  2725. case BuiltinType::Id: \
  2726. type_name = "ocl_" #ExtType; \
  2727. Out << type_name.size() << type_name; \
  2728. break;
  2729. #include "clang/Basic/OpenCLExtensionTypes.def"
  2730. // The SVE types are effectively target-specific. The mangling scheme
  2731. // is defined in the appendices to the Procedure Call Standard for the
  2732. // Arm Architecture.
  2733. #define SVE_VECTOR_TYPE(InternalName, MangledName, Id, SingletonId, NumEls, \
  2734. ElBits, IsSigned, IsFP, IsBF) \
  2735. case BuiltinType::Id: \
  2736. type_name = MangledName; \
  2737. Out << (type_name == InternalName ? "u" : "") << type_name.size() \
  2738. << type_name; \
  2739. break;
  2740. #define SVE_PREDICATE_TYPE(InternalName, MangledName, Id, SingletonId, NumEls) \
  2741. case BuiltinType::Id: \
  2742. type_name = MangledName; \
  2743. Out << (type_name == InternalName ? "u" : "") << type_name.size() \
  2744. << type_name; \
  2745. break;
  2746. #include "clang/Basic/AArch64SVEACLETypes.def"
  2747. #define PPC_VECTOR_TYPE(Name, Id, Size) \
  2748. case BuiltinType::Id: \
  2749. type_name = #Name; \
  2750. Out << 'u' << type_name.size() << type_name; \
  2751. break;
  2752. #include "clang/Basic/PPCTypes.def"
  2753. // TODO: Check the mangling scheme for RISC-V V.
  2754. #define RVV_TYPE(Name, Id, SingletonId) \
  2755. case BuiltinType::Id: \
  2756. type_name = Name; \
  2757. Out << 'u' << type_name.size() << type_name; \
  2758. break;
  2759. #include "clang/Basic/RISCVVTypes.def"
  2760. }
  2761. }
  2762. StringRef CXXNameMangler::getCallingConvQualifierName(CallingConv CC) {
  2763. switch (CC) {
  2764. case CC_C:
  2765. return "";
  2766. case CC_X86VectorCall:
  2767. case CC_X86Pascal:
  2768. case CC_X86RegCall:
  2769. case CC_AAPCS:
  2770. case CC_AAPCS_VFP:
  2771. case CC_AArch64VectorCall:
  2772. case CC_AArch64SVEPCS:
  2773. case CC_AMDGPUKernelCall:
  2774. case CC_IntelOclBicc:
  2775. case CC_SpirFunction:
  2776. case CC_OpenCLKernel:
  2777. case CC_PreserveMost:
  2778. case CC_PreserveAll:
  2779. // FIXME: we should be mangling all of the above.
  2780. return "";
  2781. case CC_X86ThisCall:
  2782. // FIXME: To match mingw GCC, thiscall should only be mangled in when it is
  2783. // used explicitly. At this point, we don't have that much information in
  2784. // the AST, since clang tends to bake the convention into the canonical
  2785. // function type. thiscall only rarely used explicitly, so don't mangle it
  2786. // for now.
  2787. return "";
  2788. case CC_X86StdCall:
  2789. return "stdcall";
  2790. case CC_X86FastCall:
  2791. return "fastcall";
  2792. case CC_X86_64SysV:
  2793. return "sysv_abi";
  2794. case CC_Win64:
  2795. return "ms_abi";
  2796. case CC_Swift:
  2797. return "swiftcall";
  2798. case CC_SwiftAsync:
  2799. return "swiftasynccall";
  2800. }
  2801. llvm_unreachable("bad calling convention");
  2802. }
  2803. void CXXNameMangler::mangleExtFunctionInfo(const FunctionType *T) {
  2804. // Fast path.
  2805. if (T->getExtInfo() == FunctionType::ExtInfo())
  2806. return;
  2807. // Vendor-specific qualifiers are emitted in reverse alphabetical order.
  2808. // This will get more complicated in the future if we mangle other
  2809. // things here; but for now, since we mangle ns_returns_retained as
  2810. // a qualifier on the result type, we can get away with this:
  2811. StringRef CCQualifier = getCallingConvQualifierName(T->getExtInfo().getCC());
  2812. if (!CCQualifier.empty())
  2813. mangleVendorQualifier(CCQualifier);
  2814. // FIXME: regparm
  2815. // FIXME: noreturn
  2816. }
  2817. void
  2818. CXXNameMangler::mangleExtParameterInfo(FunctionProtoType::ExtParameterInfo PI) {
  2819. // Vendor-specific qualifiers are emitted in reverse alphabetical order.
  2820. // Note that these are *not* substitution candidates. Demanglers might
  2821. // have trouble with this if the parameter type is fully substituted.
  2822. switch (PI.getABI()) {
  2823. case ParameterABI::Ordinary:
  2824. break;
  2825. // All of these start with "swift", so they come before "ns_consumed".
  2826. case ParameterABI::SwiftContext:
  2827. case ParameterABI::SwiftAsyncContext:
  2828. case ParameterABI::SwiftErrorResult:
  2829. case ParameterABI::SwiftIndirectResult:
  2830. mangleVendorQualifier(getParameterABISpelling(PI.getABI()));
  2831. break;
  2832. }
  2833. if (PI.isConsumed())
  2834. mangleVendorQualifier("ns_consumed");
  2835. if (PI.isNoEscape())
  2836. mangleVendorQualifier("noescape");
  2837. }
  2838. // <type> ::= <function-type>
  2839. // <function-type> ::= [<CV-qualifiers>] F [Y]
  2840. // <bare-function-type> [<ref-qualifier>] E
  2841. void CXXNameMangler::mangleType(const FunctionProtoType *T) {
  2842. mangleExtFunctionInfo(T);
  2843. // Mangle CV-qualifiers, if present. These are 'this' qualifiers,
  2844. // e.g. "const" in "int (A::*)() const".
  2845. mangleQualifiers(T->getMethodQuals());
  2846. // Mangle instantiation-dependent exception-specification, if present,
  2847. // per cxx-abi-dev proposal on 2016-10-11.
  2848. if (T->hasInstantiationDependentExceptionSpec()) {
  2849. if (isComputedNoexcept(T->getExceptionSpecType())) {
  2850. Out << "DO";
  2851. mangleExpression(T->getNoexceptExpr());
  2852. Out << "E";
  2853. } else {
  2854. assert(T->getExceptionSpecType() == EST_Dynamic);
  2855. Out << "Dw";
  2856. for (auto ExceptTy : T->exceptions())
  2857. mangleType(ExceptTy);
  2858. Out << "E";
  2859. }
  2860. } else if (T->isNothrow()) {
  2861. Out << "Do";
  2862. }
  2863. Out << 'F';
  2864. // FIXME: We don't have enough information in the AST to produce the 'Y'
  2865. // encoding for extern "C" function types.
  2866. mangleBareFunctionType(T, /*MangleReturnType=*/true);
  2867. // Mangle the ref-qualifier, if present.
  2868. mangleRefQualifier(T->getRefQualifier());
  2869. Out << 'E';
  2870. }
  2871. void CXXNameMangler::mangleType(const FunctionNoProtoType *T) {
  2872. // Function types without prototypes can arise when mangling a function type
  2873. // within an overloadable function in C. We mangle these as the absence of any
  2874. // parameter types (not even an empty parameter list).
  2875. Out << 'F';
  2876. FunctionTypeDepthState saved = FunctionTypeDepth.push();
  2877. FunctionTypeDepth.enterResultType();
  2878. mangleType(T->getReturnType());
  2879. FunctionTypeDepth.leaveResultType();
  2880. FunctionTypeDepth.pop(saved);
  2881. Out << 'E';
  2882. }
  2883. void CXXNameMangler::mangleBareFunctionType(const FunctionProtoType *Proto,
  2884. bool MangleReturnType,
  2885. const FunctionDecl *FD) {
  2886. // Record that we're in a function type. See mangleFunctionParam
  2887. // for details on what we're trying to achieve here.
  2888. FunctionTypeDepthState saved = FunctionTypeDepth.push();
  2889. // <bare-function-type> ::= <signature type>+
  2890. if (MangleReturnType) {
  2891. FunctionTypeDepth.enterResultType();
  2892. // Mangle ns_returns_retained as an order-sensitive qualifier here.
  2893. if (Proto->getExtInfo().getProducesResult() && FD == nullptr)
  2894. mangleVendorQualifier("ns_returns_retained");
  2895. // Mangle the return type without any direct ARC ownership qualifiers.
  2896. QualType ReturnTy = Proto->getReturnType();
  2897. if (ReturnTy.getObjCLifetime()) {
  2898. auto SplitReturnTy = ReturnTy.split();
  2899. SplitReturnTy.Quals.removeObjCLifetime();
  2900. ReturnTy = getASTContext().getQualifiedType(SplitReturnTy);
  2901. }
  2902. mangleType(ReturnTy);
  2903. FunctionTypeDepth.leaveResultType();
  2904. }
  2905. if (Proto->getNumParams() == 0 && !Proto->isVariadic()) {
  2906. // <builtin-type> ::= v # void
  2907. Out << 'v';
  2908. FunctionTypeDepth.pop(saved);
  2909. return;
  2910. }
  2911. assert(!FD || FD->getNumParams() == Proto->getNumParams());
  2912. for (unsigned I = 0, E = Proto->getNumParams(); I != E; ++I) {
  2913. // Mangle extended parameter info as order-sensitive qualifiers here.
  2914. if (Proto->hasExtParameterInfos() && FD == nullptr) {
  2915. mangleExtParameterInfo(Proto->getExtParameterInfo(I));
  2916. }
  2917. // Mangle the type.
  2918. QualType ParamTy = Proto->getParamType(I);
  2919. mangleType(Context.getASTContext().getSignatureParameterType(ParamTy));
  2920. if (FD) {
  2921. if (auto *Attr = FD->getParamDecl(I)->getAttr<PassObjectSizeAttr>()) {
  2922. // Attr can only take 1 character, so we can hardcode the length below.
  2923. assert(Attr->getType() <= 9 && Attr->getType() >= 0);
  2924. if (Attr->isDynamic())
  2925. Out << "U25pass_dynamic_object_size" << Attr->getType();
  2926. else
  2927. Out << "U17pass_object_size" << Attr->getType();
  2928. }
  2929. }
  2930. }
  2931. FunctionTypeDepth.pop(saved);
  2932. // <builtin-type> ::= z # ellipsis
  2933. if (Proto->isVariadic())
  2934. Out << 'z';
  2935. }
  2936. // <type> ::= <class-enum-type>
  2937. // <class-enum-type> ::= <name>
  2938. void CXXNameMangler::mangleType(const UnresolvedUsingType *T) {
  2939. mangleName(T->getDecl());
  2940. }
  2941. // <type> ::= <class-enum-type>
  2942. // <class-enum-type> ::= <name>
  2943. void CXXNameMangler::mangleType(const EnumType *T) {
  2944. mangleType(static_cast<const TagType*>(T));
  2945. }
  2946. void CXXNameMangler::mangleType(const RecordType *T) {
  2947. mangleType(static_cast<const TagType*>(T));
  2948. }
  2949. void CXXNameMangler::mangleType(const TagType *T) {
  2950. mangleName(T->getDecl());
  2951. }
  2952. // <type> ::= <array-type>
  2953. // <array-type> ::= A <positive dimension number> _ <element type>
  2954. // ::= A [<dimension expression>] _ <element type>
  2955. void CXXNameMangler::mangleType(const ConstantArrayType *T) {
  2956. Out << 'A' << T->getSize() << '_';
  2957. mangleType(T->getElementType());
  2958. }
  2959. void CXXNameMangler::mangleType(const VariableArrayType *T) {
  2960. Out << 'A';
  2961. // decayed vla types (size 0) will just be skipped.
  2962. if (T->getSizeExpr())
  2963. mangleExpression(T->getSizeExpr());
  2964. Out << '_';
  2965. mangleType(T->getElementType());
  2966. }
  2967. void CXXNameMangler::mangleType(const DependentSizedArrayType *T) {
  2968. Out << 'A';
  2969. // A DependentSizedArrayType might not have size expression as below
  2970. //
  2971. // template<int ...N> int arr[] = {N...};
  2972. if (T->getSizeExpr())
  2973. mangleExpression(T->getSizeExpr());
  2974. Out << '_';
  2975. mangleType(T->getElementType());
  2976. }
  2977. void CXXNameMangler::mangleType(const IncompleteArrayType *T) {
  2978. Out << "A_";
  2979. mangleType(T->getElementType());
  2980. }
  2981. // <type> ::= <pointer-to-member-type>
  2982. // <pointer-to-member-type> ::= M <class type> <member type>
  2983. void CXXNameMangler::mangleType(const MemberPointerType *T) {
  2984. Out << 'M';
  2985. mangleType(QualType(T->getClass(), 0));
  2986. QualType PointeeType = T->getPointeeType();
  2987. if (const FunctionProtoType *FPT = dyn_cast<FunctionProtoType>(PointeeType)) {
  2988. mangleType(FPT);
  2989. // Itanium C++ ABI 5.1.8:
  2990. //
  2991. // The type of a non-static member function is considered to be different,
  2992. // for the purposes of substitution, from the type of a namespace-scope or
  2993. // static member function whose type appears similar. The types of two
  2994. // non-static member functions are considered to be different, for the
  2995. // purposes of substitution, if the functions are members of different
  2996. // classes. In other words, for the purposes of substitution, the class of
  2997. // which the function is a member is considered part of the type of
  2998. // function.
  2999. // Given that we already substitute member function pointers as a
  3000. // whole, the net effect of this rule is just to unconditionally
  3001. // suppress substitution on the function type in a member pointer.
  3002. // We increment the SeqID here to emulate adding an entry to the
  3003. // substitution table.
  3004. ++SeqID;
  3005. } else
  3006. mangleType(PointeeType);
  3007. }
  3008. // <type> ::= <template-param>
  3009. void CXXNameMangler::mangleType(const TemplateTypeParmType *T) {
  3010. mangleTemplateParameter(T->getDepth(), T->getIndex());
  3011. }
  3012. // <type> ::= <template-param>
  3013. void CXXNameMangler::mangleType(const SubstTemplateTypeParmPackType *T) {
  3014. // FIXME: not clear how to mangle this!
  3015. // template <class T...> class A {
  3016. // template <class U...> void foo(T(*)(U) x...);
  3017. // };
  3018. Out << "_SUBSTPACK_";
  3019. }
  3020. // <type> ::= P <type> # pointer-to
  3021. void CXXNameMangler::mangleType(const PointerType *T) {
  3022. Out << 'P';
  3023. mangleType(T->getPointeeType());
  3024. }
  3025. void CXXNameMangler::mangleType(const ObjCObjectPointerType *T) {
  3026. Out << 'P';
  3027. mangleType(T->getPointeeType());
  3028. }
  3029. // <type> ::= R <type> # reference-to
  3030. void CXXNameMangler::mangleType(const LValueReferenceType *T) {
  3031. Out << 'R';
  3032. mangleType(T->getPointeeType());
  3033. }
  3034. // <type> ::= O <type> # rvalue reference-to (C++0x)
  3035. void CXXNameMangler::mangleType(const RValueReferenceType *T) {
  3036. Out << 'O';
  3037. mangleType(T->getPointeeType());
  3038. }
  3039. // <type> ::= C <type> # complex pair (C 2000)
  3040. void CXXNameMangler::mangleType(const ComplexType *T) {
  3041. Out << 'C';
  3042. mangleType(T->getElementType());
  3043. }
  3044. // ARM's ABI for Neon vector types specifies that they should be mangled as
  3045. // if they are structs (to match ARM's initial implementation). The
  3046. // vector type must be one of the special types predefined by ARM.
  3047. void CXXNameMangler::mangleNeonVectorType(const VectorType *T) {
  3048. QualType EltType = T->getElementType();
  3049. assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
  3050. const char *EltName = nullptr;
  3051. if (T->getVectorKind() == VectorType::NeonPolyVector) {
  3052. switch (cast<BuiltinType>(EltType)->getKind()) {
  3053. case BuiltinType::SChar:
  3054. case BuiltinType::UChar:
  3055. EltName = "poly8_t";
  3056. break;
  3057. case BuiltinType::Short:
  3058. case BuiltinType::UShort:
  3059. EltName = "poly16_t";
  3060. break;
  3061. case BuiltinType::LongLong:
  3062. case BuiltinType::ULongLong:
  3063. EltName = "poly64_t";
  3064. break;
  3065. default: llvm_unreachable("unexpected Neon polynomial vector element type");
  3066. }
  3067. } else {
  3068. switch (cast<BuiltinType>(EltType)->getKind()) {
  3069. case BuiltinType::SChar: EltName = "int8_t"; break;
  3070. case BuiltinType::UChar: EltName = "uint8_t"; break;
  3071. case BuiltinType::Short: EltName = "int16_t"; break;
  3072. case BuiltinType::UShort: EltName = "uint16_t"; break;
  3073. case BuiltinType::Int: EltName = "int32_t"; break;
  3074. case BuiltinType::UInt: EltName = "uint32_t"; break;
  3075. case BuiltinType::LongLong: EltName = "int64_t"; break;
  3076. case BuiltinType::ULongLong: EltName = "uint64_t"; break;
  3077. case BuiltinType::Double: EltName = "float64_t"; break;
  3078. case BuiltinType::Float: EltName = "float32_t"; break;
  3079. case BuiltinType::Half: EltName = "float16_t"; break;
  3080. case BuiltinType::BFloat16: EltName = "bfloat16_t"; break;
  3081. default:
  3082. llvm_unreachable("unexpected Neon vector element type");
  3083. }
  3084. }
  3085. const char *BaseName = nullptr;
  3086. unsigned BitSize = (T->getNumElements() *
  3087. getASTContext().getTypeSize(EltType));
  3088. if (BitSize == 64)
  3089. BaseName = "__simd64_";
  3090. else {
  3091. assert(BitSize == 128 && "Neon vector type not 64 or 128 bits");
  3092. BaseName = "__simd128_";
  3093. }
  3094. Out << strlen(BaseName) + strlen(EltName);
  3095. Out << BaseName << EltName;
  3096. }
  3097. void CXXNameMangler::mangleNeonVectorType(const DependentVectorType *T) {
  3098. DiagnosticsEngine &Diags = Context.getDiags();
  3099. unsigned DiagID = Diags.getCustomDiagID(
  3100. DiagnosticsEngine::Error,
  3101. "cannot mangle this dependent neon vector type yet");
  3102. Diags.Report(T->getAttributeLoc(), DiagID);
  3103. }
  3104. static StringRef mangleAArch64VectorBase(const BuiltinType *EltType) {
  3105. switch (EltType->getKind()) {
  3106. case BuiltinType::SChar:
  3107. return "Int8";
  3108. case BuiltinType::Short:
  3109. return "Int16";
  3110. case BuiltinType::Int:
  3111. return "Int32";
  3112. case BuiltinType::Long:
  3113. case BuiltinType::LongLong:
  3114. return "Int64";
  3115. case BuiltinType::UChar:
  3116. return "Uint8";
  3117. case BuiltinType::UShort:
  3118. return "Uint16";
  3119. case BuiltinType::UInt:
  3120. return "Uint32";
  3121. case BuiltinType::ULong:
  3122. case BuiltinType::ULongLong:
  3123. return "Uint64";
  3124. case BuiltinType::Half:
  3125. return "Float16";
  3126. case BuiltinType::Float:
  3127. return "Float32";
  3128. case BuiltinType::Double:
  3129. return "Float64";
  3130. case BuiltinType::BFloat16:
  3131. return "Bfloat16";
  3132. default:
  3133. llvm_unreachable("Unexpected vector element base type");
  3134. }
  3135. }
  3136. // AArch64's ABI for Neon vector types specifies that they should be mangled as
  3137. // the equivalent internal name. The vector type must be one of the special
  3138. // types predefined by ARM.
  3139. void CXXNameMangler::mangleAArch64NeonVectorType(const VectorType *T) {
  3140. QualType EltType = T->getElementType();
  3141. assert(EltType->isBuiltinType() && "Neon vector element not a BuiltinType");
  3142. unsigned BitSize =
  3143. (T->getNumElements() * getASTContext().getTypeSize(EltType));
  3144. (void)BitSize; // Silence warning.
  3145. assert((BitSize == 64 || BitSize == 128) &&
  3146. "Neon vector type not 64 or 128 bits");
  3147. StringRef EltName;
  3148. if (T->getVectorKind() == VectorType::NeonPolyVector) {
  3149. switch (cast<BuiltinType>(EltType)->getKind()) {
  3150. case BuiltinType::UChar:
  3151. EltName = "Poly8";
  3152. break;
  3153. case BuiltinType::UShort:
  3154. EltName = "Poly16";
  3155. break;
  3156. case BuiltinType::ULong:
  3157. case BuiltinType::ULongLong:
  3158. EltName = "Poly64";
  3159. break;
  3160. default:
  3161. llvm_unreachable("unexpected Neon polynomial vector element type");
  3162. }
  3163. } else
  3164. EltName = mangleAArch64VectorBase(cast<BuiltinType>(EltType));
  3165. std::string TypeName =
  3166. ("__" + EltName + "x" + Twine(T->getNumElements()) + "_t").str();
  3167. Out << TypeName.length() << TypeName;
  3168. }
  3169. void CXXNameMangler::mangleAArch64NeonVectorType(const DependentVectorType *T) {
  3170. DiagnosticsEngine &Diags = Context.getDiags();
  3171. unsigned DiagID = Diags.getCustomDiagID(
  3172. DiagnosticsEngine::Error,
  3173. "cannot mangle this dependent neon vector type yet");
  3174. Diags.Report(T->getAttributeLoc(), DiagID);
  3175. }
  3176. // The AArch64 ACLE specifies that fixed-length SVE vector and predicate types
  3177. // defined with the 'arm_sve_vector_bits' attribute map to the same AAPCS64
  3178. // type as the sizeless variants.
  3179. //
  3180. // The mangling scheme for VLS types is implemented as a "pseudo" template:
  3181. //
  3182. // '__SVE_VLS<<type>, <vector length>>'
  3183. //
  3184. // Combining the existing SVE type and a specific vector length (in bits).
  3185. // For example:
  3186. //
  3187. // typedef __SVInt32_t foo __attribute__((arm_sve_vector_bits(512)));
  3188. //
  3189. // is described as '__SVE_VLS<__SVInt32_t, 512u>' and mangled as:
  3190. //
  3191. // "9__SVE_VLSI" + base type mangling + "Lj" + __ARM_FEATURE_SVE_BITS + "EE"
  3192. //
  3193. // i.e. 9__SVE_VLSIu11__SVInt32_tLj512EE
  3194. //
  3195. // The latest ACLE specification (00bet5) does not contain details of this
  3196. // mangling scheme, it will be specified in the next revision. The mangling
  3197. // scheme is otherwise defined in the appendices to the Procedure Call Standard
  3198. // for the Arm Architecture, see
  3199. // https://github.com/ARM-software/abi-aa/blob/main/aapcs64/aapcs64.rst#appendix-c-mangling
  3200. void CXXNameMangler::mangleAArch64FixedSveVectorType(const VectorType *T) {
  3201. assert((T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
  3202. T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) &&
  3203. "expected fixed-length SVE vector!");
  3204. QualType EltType = T->getElementType();
  3205. assert(EltType->isBuiltinType() &&
  3206. "expected builtin type for fixed-length SVE vector!");
  3207. StringRef TypeName;
  3208. switch (cast<BuiltinType>(EltType)->getKind()) {
  3209. case BuiltinType::SChar:
  3210. TypeName = "__SVInt8_t";
  3211. break;
  3212. case BuiltinType::UChar: {
  3213. if (T->getVectorKind() == VectorType::SveFixedLengthDataVector)
  3214. TypeName = "__SVUint8_t";
  3215. else
  3216. TypeName = "__SVBool_t";
  3217. break;
  3218. }
  3219. case BuiltinType::Short:
  3220. TypeName = "__SVInt16_t";
  3221. break;
  3222. case BuiltinType::UShort:
  3223. TypeName = "__SVUint16_t";
  3224. break;
  3225. case BuiltinType::Int:
  3226. TypeName = "__SVInt32_t";
  3227. break;
  3228. case BuiltinType::UInt:
  3229. TypeName = "__SVUint32_t";
  3230. break;
  3231. case BuiltinType::Long:
  3232. TypeName = "__SVInt64_t";
  3233. break;
  3234. case BuiltinType::ULong:
  3235. TypeName = "__SVUint64_t";
  3236. break;
  3237. case BuiltinType::Half:
  3238. TypeName = "__SVFloat16_t";
  3239. break;
  3240. case BuiltinType::Float:
  3241. TypeName = "__SVFloat32_t";
  3242. break;
  3243. case BuiltinType::Double:
  3244. TypeName = "__SVFloat64_t";
  3245. break;
  3246. case BuiltinType::BFloat16:
  3247. TypeName = "__SVBfloat16_t";
  3248. break;
  3249. default:
  3250. llvm_unreachable("unexpected element type for fixed-length SVE vector!");
  3251. }
  3252. unsigned VecSizeInBits = getASTContext().getTypeInfo(T).Width;
  3253. if (T->getVectorKind() == VectorType::SveFixedLengthPredicateVector)
  3254. VecSizeInBits *= 8;
  3255. Out << "9__SVE_VLSI" << 'u' << TypeName.size() << TypeName << "Lj"
  3256. << VecSizeInBits << "EE";
  3257. }
  3258. void CXXNameMangler::mangleAArch64FixedSveVectorType(
  3259. const DependentVectorType *T) {
  3260. DiagnosticsEngine &Diags = Context.getDiags();
  3261. unsigned DiagID = Diags.getCustomDiagID(
  3262. DiagnosticsEngine::Error,
  3263. "cannot mangle this dependent fixed-length SVE vector type yet");
  3264. Diags.Report(T->getAttributeLoc(), DiagID);
  3265. }
  3266. // GNU extension: vector types
  3267. // <type> ::= <vector-type>
  3268. // <vector-type> ::= Dv <positive dimension number> _
  3269. // <extended element type>
  3270. // ::= Dv [<dimension expression>] _ <element type>
  3271. // <extended element type> ::= <element type>
  3272. // ::= p # AltiVec vector pixel
  3273. // ::= b # Altivec vector bool
  3274. void CXXNameMangler::mangleType(const VectorType *T) {
  3275. if ((T->getVectorKind() == VectorType::NeonVector ||
  3276. T->getVectorKind() == VectorType::NeonPolyVector)) {
  3277. llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
  3278. llvm::Triple::ArchType Arch =
  3279. getASTContext().getTargetInfo().getTriple().getArch();
  3280. if ((Arch == llvm::Triple::aarch64 ||
  3281. Arch == llvm::Triple::aarch64_be) && !Target.isOSDarwin())
  3282. mangleAArch64NeonVectorType(T);
  3283. else
  3284. mangleNeonVectorType(T);
  3285. return;
  3286. } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
  3287. T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
  3288. mangleAArch64FixedSveVectorType(T);
  3289. return;
  3290. }
  3291. Out << "Dv" << T->getNumElements() << '_';
  3292. if (T->getVectorKind() == VectorType::AltiVecPixel)
  3293. Out << 'p';
  3294. else if (T->getVectorKind() == VectorType::AltiVecBool)
  3295. Out << 'b';
  3296. else
  3297. mangleType(T->getElementType());
  3298. }
  3299. void CXXNameMangler::mangleType(const DependentVectorType *T) {
  3300. if ((T->getVectorKind() == VectorType::NeonVector ||
  3301. T->getVectorKind() == VectorType::NeonPolyVector)) {
  3302. llvm::Triple Target = getASTContext().getTargetInfo().getTriple();
  3303. llvm::Triple::ArchType Arch =
  3304. getASTContext().getTargetInfo().getTriple().getArch();
  3305. if ((Arch == llvm::Triple::aarch64 || Arch == llvm::Triple::aarch64_be) &&
  3306. !Target.isOSDarwin())
  3307. mangleAArch64NeonVectorType(T);
  3308. else
  3309. mangleNeonVectorType(T);
  3310. return;
  3311. } else if (T->getVectorKind() == VectorType::SveFixedLengthDataVector ||
  3312. T->getVectorKind() == VectorType::SveFixedLengthPredicateVector) {
  3313. mangleAArch64FixedSveVectorType(T);
  3314. return;
  3315. }
  3316. Out << "Dv";
  3317. mangleExpression(T->getSizeExpr());
  3318. Out << '_';
  3319. if (T->getVectorKind() == VectorType::AltiVecPixel)
  3320. Out << 'p';
  3321. else if (T->getVectorKind() == VectorType::AltiVecBool)
  3322. Out << 'b';
  3323. else
  3324. mangleType(T->getElementType());
  3325. }
  3326. void CXXNameMangler::mangleType(const ExtVectorType *T) {
  3327. mangleType(static_cast<const VectorType*>(T));
  3328. }
  3329. void CXXNameMangler::mangleType(const DependentSizedExtVectorType *T) {
  3330. Out << "Dv";
  3331. mangleExpression(T->getSizeExpr());
  3332. Out << '_';
  3333. mangleType(T->getElementType());
  3334. }
  3335. void CXXNameMangler::mangleType(const ConstantMatrixType *T) {
  3336. // Mangle matrix types as a vendor extended type:
  3337. // u<Len>matrix_typeI<Rows><Columns><element type>E
  3338. StringRef VendorQualifier = "matrix_type";
  3339. Out << "u" << VendorQualifier.size() << VendorQualifier;
  3340. Out << "I";
  3341. auto &ASTCtx = getASTContext();
  3342. unsigned BitWidth = ASTCtx.getTypeSize(ASTCtx.getSizeType());
  3343. llvm::APSInt Rows(BitWidth);
  3344. Rows = T->getNumRows();
  3345. mangleIntegerLiteral(ASTCtx.getSizeType(), Rows);
  3346. llvm::APSInt Columns(BitWidth);
  3347. Columns = T->getNumColumns();
  3348. mangleIntegerLiteral(ASTCtx.getSizeType(), Columns);
  3349. mangleType(T->getElementType());
  3350. Out << "E";
  3351. }
  3352. void CXXNameMangler::mangleType(const DependentSizedMatrixType *T) {
  3353. // Mangle matrix types as a vendor extended type:
  3354. // u<Len>matrix_typeI<row expr><column expr><element type>E
  3355. StringRef VendorQualifier = "matrix_type";
  3356. Out << "u" << VendorQualifier.size() << VendorQualifier;
  3357. Out << "I";
  3358. mangleTemplateArgExpr(T->getRowExpr());
  3359. mangleTemplateArgExpr(T->getColumnExpr());
  3360. mangleType(T->getElementType());
  3361. Out << "E";
  3362. }
  3363. void CXXNameMangler::mangleType(const DependentAddressSpaceType *T) {
  3364. SplitQualType split = T->getPointeeType().split();
  3365. mangleQualifiers(split.Quals, T);
  3366. mangleType(QualType(split.Ty, 0));
  3367. }
  3368. void CXXNameMangler::mangleType(const PackExpansionType *T) {
  3369. // <type> ::= Dp <type> # pack expansion (C++0x)
  3370. Out << "Dp";
  3371. mangleType(T->getPattern());
  3372. }
  3373. void CXXNameMangler::mangleType(const ObjCInterfaceType *T) {
  3374. mangleSourceName(T->getDecl()->getIdentifier());
  3375. }
  3376. void CXXNameMangler::mangleType(const ObjCObjectType *T) {
  3377. // Treat __kindof as a vendor extended type qualifier.
  3378. if (T->isKindOfType())
  3379. Out << "U8__kindof";
  3380. if (!T->qual_empty()) {
  3381. // Mangle protocol qualifiers.
  3382. SmallString<64> QualStr;
  3383. llvm::raw_svector_ostream QualOS(QualStr);
  3384. QualOS << "objcproto";
  3385. for (const auto *I : T->quals()) {
  3386. StringRef name = I->getName();
  3387. QualOS << name.size() << name;
  3388. }
  3389. Out << 'U' << QualStr.size() << QualStr;
  3390. }
  3391. mangleType(T->getBaseType());
  3392. if (T->isSpecialized()) {
  3393. // Mangle type arguments as I <type>+ E
  3394. Out << 'I';
  3395. for (auto typeArg : T->getTypeArgs())
  3396. mangleType(typeArg);
  3397. Out << 'E';
  3398. }
  3399. }
  3400. void CXXNameMangler::mangleType(const BlockPointerType *T) {
  3401. Out << "U13block_pointer";
  3402. mangleType(T->getPointeeType());
  3403. }
  3404. void CXXNameMangler::mangleType(const InjectedClassNameType *T) {
  3405. // Mangle injected class name types as if the user had written the
  3406. // specialization out fully. It may not actually be possible to see
  3407. // this mangling, though.
  3408. mangleType(T->getInjectedSpecializationType());
  3409. }
  3410. void CXXNameMangler::mangleType(const TemplateSpecializationType *T) {
  3411. if (TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl()) {
  3412. mangleTemplateName(TD, T->template_arguments());
  3413. } else {
  3414. if (mangleSubstitution(QualType(T, 0)))
  3415. return;
  3416. mangleTemplatePrefix(T->getTemplateName());
  3417. // FIXME: GCC does not appear to mangle the template arguments when
  3418. // the template in question is a dependent template name. Should we
  3419. // emulate that badness?
  3420. mangleTemplateArgs(T->getTemplateName(), T->template_arguments());
  3421. addSubstitution(QualType(T, 0));
  3422. }
  3423. }
  3424. void CXXNameMangler::mangleType(const DependentNameType *T) {
  3425. // Proposal by cxx-abi-dev, 2014-03-26
  3426. // <class-enum-type> ::= <name> # non-dependent or dependent type name or
  3427. // # dependent elaborated type specifier using
  3428. // # 'typename'
  3429. // ::= Ts <name> # dependent elaborated type specifier using
  3430. // # 'struct' or 'class'
  3431. // ::= Tu <name> # dependent elaborated type specifier using
  3432. // # 'union'
  3433. // ::= Te <name> # dependent elaborated type specifier using
  3434. // # 'enum'
  3435. switch (T->getKeyword()) {
  3436. case ETK_None:
  3437. case ETK_Typename:
  3438. break;
  3439. case ETK_Struct:
  3440. case ETK_Class:
  3441. case ETK_Interface:
  3442. Out << "Ts";
  3443. break;
  3444. case ETK_Union:
  3445. Out << "Tu";
  3446. break;
  3447. case ETK_Enum:
  3448. Out << "Te";
  3449. break;
  3450. }
  3451. // Typename types are always nested
  3452. Out << 'N';
  3453. manglePrefix(T->getQualifier());
  3454. mangleSourceName(T->getIdentifier());
  3455. Out << 'E';
  3456. }
  3457. void CXXNameMangler::mangleType(const DependentTemplateSpecializationType *T) {
  3458. // Dependently-scoped template types are nested if they have a prefix.
  3459. Out << 'N';
  3460. // TODO: avoid making this TemplateName.
  3461. TemplateName Prefix =
  3462. getASTContext().getDependentTemplateName(T->getQualifier(),
  3463. T->getIdentifier());
  3464. mangleTemplatePrefix(Prefix);
  3465. // FIXME: GCC does not appear to mangle the template arguments when
  3466. // the template in question is a dependent template name. Should we
  3467. // emulate that badness?
  3468. mangleTemplateArgs(Prefix, T->template_arguments());
  3469. Out << 'E';
  3470. }
  3471. void CXXNameMangler::mangleType(const TypeOfType *T) {
  3472. // FIXME: this is pretty unsatisfactory, but there isn't an obvious
  3473. // "extension with parameters" mangling.
  3474. Out << "u6typeof";
  3475. }
  3476. void CXXNameMangler::mangleType(const TypeOfExprType *T) {
  3477. // FIXME: this is pretty unsatisfactory, but there isn't an obvious
  3478. // "extension with parameters" mangling.
  3479. Out << "u6typeof";
  3480. }
  3481. void CXXNameMangler::mangleType(const DecltypeType *T) {
  3482. Expr *E = T->getUnderlyingExpr();
  3483. // type ::= Dt <expression> E # decltype of an id-expression
  3484. // # or class member access
  3485. // ::= DT <expression> E # decltype of an expression
  3486. // This purports to be an exhaustive list of id-expressions and
  3487. // class member accesses. Note that we do not ignore parentheses;
  3488. // parentheses change the semantics of decltype for these
  3489. // expressions (and cause the mangler to use the other form).
  3490. if (isa<DeclRefExpr>(E) ||
  3491. isa<MemberExpr>(E) ||
  3492. isa<UnresolvedLookupExpr>(E) ||
  3493. isa<DependentScopeDeclRefExpr>(E) ||
  3494. isa<CXXDependentScopeMemberExpr>(E) ||
  3495. isa<UnresolvedMemberExpr>(E))
  3496. Out << "Dt";
  3497. else
  3498. Out << "DT";
  3499. mangleExpression(E);
  3500. Out << 'E';
  3501. }
  3502. void CXXNameMangler::mangleType(const UnaryTransformType *T) {
  3503. // If this is dependent, we need to record that. If not, we simply
  3504. // mangle it as the underlying type since they are equivalent.
  3505. if (T->isDependentType()) {
  3506. Out << "u";
  3507. StringRef BuiltinName;
  3508. switch (T->getUTTKind()) {
  3509. #define TRANSFORM_TYPE_TRAIT_DEF(Enum, Trait) \
  3510. case UnaryTransformType::Enum: \
  3511. BuiltinName = "__" #Trait; \
  3512. break;
  3513. #include "clang/Basic/TransformTypeTraits.def"
  3514. }
  3515. Out << BuiltinName.size() << BuiltinName;
  3516. }
  3517. Out << "I";
  3518. mangleType(T->getBaseType());
  3519. Out << "E";
  3520. }
  3521. void CXXNameMangler::mangleType(const AutoType *T) {
  3522. assert(T->getDeducedType().isNull() &&
  3523. "Deduced AutoType shouldn't be handled here!");
  3524. assert(T->getKeyword() != AutoTypeKeyword::GNUAutoType &&
  3525. "shouldn't need to mangle __auto_type!");
  3526. // <builtin-type> ::= Da # auto
  3527. // ::= Dc # decltype(auto)
  3528. Out << (T->isDecltypeAuto() ? "Dc" : "Da");
  3529. }
  3530. void CXXNameMangler::mangleType(const DeducedTemplateSpecializationType *T) {
  3531. QualType Deduced = T->getDeducedType();
  3532. if (!Deduced.isNull())
  3533. return mangleType(Deduced);
  3534. TemplateDecl *TD = T->getTemplateName().getAsTemplateDecl();
  3535. assert(TD && "shouldn't form deduced TST unless we know we have a template");
  3536. if (mangleSubstitution(TD))
  3537. return;
  3538. mangleName(GlobalDecl(TD));
  3539. addSubstitution(TD);
  3540. }
  3541. void CXXNameMangler::mangleType(const AtomicType *T) {
  3542. // <type> ::= U <source-name> <type> # vendor extended type qualifier
  3543. // (Until there's a standardized mangling...)
  3544. Out << "U7_Atomic";
  3545. mangleType(T->getValueType());
  3546. }
  3547. void CXXNameMangler::mangleType(const PipeType *T) {
  3548. // Pipe type mangling rules are described in SPIR 2.0 specification
  3549. // A.1 Data types and A.3 Summary of changes
  3550. // <type> ::= 8ocl_pipe
  3551. Out << "8ocl_pipe";
  3552. }
  3553. void CXXNameMangler::mangleType(const BitIntType *T) {
  3554. // 5.1.5.2 Builtin types
  3555. // <type> ::= DB <number | instantiation-dependent expression> _
  3556. // ::= DU <number | instantiation-dependent expression> _
  3557. Out << "D" << (T->isUnsigned() ? "U" : "B") << T->getNumBits() << "_";
  3558. }
  3559. void CXXNameMangler::mangleType(const DependentBitIntType *T) {
  3560. // 5.1.5.2 Builtin types
  3561. // <type> ::= DB <number | instantiation-dependent expression> _
  3562. // ::= DU <number | instantiation-dependent expression> _
  3563. Out << "D" << (T->isUnsigned() ? "U" : "B");
  3564. mangleExpression(T->getNumBitsExpr());
  3565. Out << "_";
  3566. }
  3567. void CXXNameMangler::mangleIntegerLiteral(QualType T,
  3568. const llvm::APSInt &Value) {
  3569. // <expr-primary> ::= L <type> <value number> E # integer literal
  3570. Out << 'L';
  3571. mangleType(T);
  3572. if (T->isBooleanType()) {
  3573. // Boolean values are encoded as 0/1.
  3574. Out << (Value.getBoolValue() ? '1' : '0');
  3575. } else {
  3576. mangleNumber(Value);
  3577. }
  3578. Out << 'E';
  3579. }
  3580. void CXXNameMangler::mangleMemberExprBase(const Expr *Base, bool IsArrow) {
  3581. // Ignore member expressions involving anonymous unions.
  3582. while (const auto *RT = Base->getType()->getAs<RecordType>()) {
  3583. if (!RT->getDecl()->isAnonymousStructOrUnion())
  3584. break;
  3585. const auto *ME = dyn_cast<MemberExpr>(Base);
  3586. if (!ME)
  3587. break;
  3588. Base = ME->getBase();
  3589. IsArrow = ME->isArrow();
  3590. }
  3591. if (Base->isImplicitCXXThis()) {
  3592. // Note: GCC mangles member expressions to the implicit 'this' as
  3593. // *this., whereas we represent them as this->. The Itanium C++ ABI
  3594. // does not specify anything here, so we follow GCC.
  3595. Out << "dtdefpT";
  3596. } else {
  3597. Out << (IsArrow ? "pt" : "dt");
  3598. mangleExpression(Base);
  3599. }
  3600. }
  3601. /// Mangles a member expression.
  3602. void CXXNameMangler::mangleMemberExpr(const Expr *base,
  3603. bool isArrow,
  3604. NestedNameSpecifier *qualifier,
  3605. NamedDecl *firstQualifierLookup,
  3606. DeclarationName member,
  3607. const TemplateArgumentLoc *TemplateArgs,
  3608. unsigned NumTemplateArgs,
  3609. unsigned arity) {
  3610. // <expression> ::= dt <expression> <unresolved-name>
  3611. // ::= pt <expression> <unresolved-name>
  3612. if (base)
  3613. mangleMemberExprBase(base, isArrow);
  3614. mangleUnresolvedName(qualifier, member, TemplateArgs, NumTemplateArgs, arity);
  3615. }
  3616. /// Look at the callee of the given call expression and determine if
  3617. /// it's a parenthesized id-expression which would have triggered ADL
  3618. /// otherwise.
  3619. static bool isParenthesizedADLCallee(const CallExpr *call) {
  3620. const Expr *callee = call->getCallee();
  3621. const Expr *fn = callee->IgnoreParens();
  3622. // Must be parenthesized. IgnoreParens() skips __extension__ nodes,
  3623. // too, but for those to appear in the callee, it would have to be
  3624. // parenthesized.
  3625. if (callee == fn) return false;
  3626. // Must be an unresolved lookup.
  3627. const UnresolvedLookupExpr *lookup = dyn_cast<UnresolvedLookupExpr>(fn);
  3628. if (!lookup) return false;
  3629. assert(!lookup->requiresADL());
  3630. // Must be an unqualified lookup.
  3631. if (lookup->getQualifier()) return false;
  3632. // Must not have found a class member. Note that if one is a class
  3633. // member, they're all class members.
  3634. if (lookup->getNumDecls() > 0 &&
  3635. (*lookup->decls_begin())->isCXXClassMember())
  3636. return false;
  3637. // Otherwise, ADL would have been triggered.
  3638. return true;
  3639. }
  3640. void CXXNameMangler::mangleCastExpression(const Expr *E, StringRef CastEncoding) {
  3641. const ExplicitCastExpr *ECE = cast<ExplicitCastExpr>(E);
  3642. Out << CastEncoding;
  3643. mangleType(ECE->getType());
  3644. mangleExpression(ECE->getSubExpr());
  3645. }
  3646. void CXXNameMangler::mangleInitListElements(const InitListExpr *InitList) {
  3647. if (auto *Syntactic = InitList->getSyntacticForm())
  3648. InitList = Syntactic;
  3649. for (unsigned i = 0, e = InitList->getNumInits(); i != e; ++i)
  3650. mangleExpression(InitList->getInit(i));
  3651. }
  3652. void CXXNameMangler::mangleExpression(const Expr *E, unsigned Arity,
  3653. bool AsTemplateArg) {
  3654. // <expression> ::= <unary operator-name> <expression>
  3655. // ::= <binary operator-name> <expression> <expression>
  3656. // ::= <trinary operator-name> <expression> <expression> <expression>
  3657. // ::= cv <type> expression # conversion with one argument
  3658. // ::= cv <type> _ <expression>* E # conversion with a different number of arguments
  3659. // ::= dc <type> <expression> # dynamic_cast<type> (expression)
  3660. // ::= sc <type> <expression> # static_cast<type> (expression)
  3661. // ::= cc <type> <expression> # const_cast<type> (expression)
  3662. // ::= rc <type> <expression> # reinterpret_cast<type> (expression)
  3663. // ::= st <type> # sizeof (a type)
  3664. // ::= at <type> # alignof (a type)
  3665. // ::= <template-param>
  3666. // ::= <function-param>
  3667. // ::= fpT # 'this' expression (part of <function-param>)
  3668. // ::= sr <type> <unqualified-name> # dependent name
  3669. // ::= sr <type> <unqualified-name> <template-args> # dependent template-id
  3670. // ::= ds <expression> <expression> # expr.*expr
  3671. // ::= sZ <template-param> # size of a parameter pack
  3672. // ::= sZ <function-param> # size of a function parameter pack
  3673. // ::= u <source-name> <template-arg>* E # vendor extended expression
  3674. // ::= <expr-primary>
  3675. // <expr-primary> ::= L <type> <value number> E # integer literal
  3676. // ::= L <type> <value float> E # floating literal
  3677. // ::= L <type> <string type> E # string literal
  3678. // ::= L <nullptr type> E # nullptr literal "LDnE"
  3679. // ::= L <pointer type> 0 E # null pointer template argument
  3680. // ::= L <type> <real-part float> _ <imag-part float> E # complex floating point literal (C99); not used by clang
  3681. // ::= L <mangled-name> E # external name
  3682. QualType ImplicitlyConvertedToType;
  3683. // A top-level expression that's not <expr-primary> needs to be wrapped in
  3684. // X...E in a template arg.
  3685. bool IsPrimaryExpr = true;
  3686. auto NotPrimaryExpr = [&] {
  3687. if (AsTemplateArg && IsPrimaryExpr)
  3688. Out << 'X';
  3689. IsPrimaryExpr = false;
  3690. };
  3691. auto MangleDeclRefExpr = [&](const NamedDecl *D) {
  3692. switch (D->getKind()) {
  3693. default:
  3694. // <expr-primary> ::= L <mangled-name> E # external name
  3695. Out << 'L';
  3696. mangle(D);
  3697. Out << 'E';
  3698. break;
  3699. case Decl::ParmVar:
  3700. NotPrimaryExpr();
  3701. mangleFunctionParam(cast<ParmVarDecl>(D));
  3702. break;
  3703. case Decl::EnumConstant: {
  3704. // <expr-primary>
  3705. const EnumConstantDecl *ED = cast<EnumConstantDecl>(D);
  3706. mangleIntegerLiteral(ED->getType(), ED->getInitVal());
  3707. break;
  3708. }
  3709. case Decl::NonTypeTemplateParm:
  3710. NotPrimaryExpr();
  3711. const NonTypeTemplateParmDecl *PD = cast<NonTypeTemplateParmDecl>(D);
  3712. mangleTemplateParameter(PD->getDepth(), PD->getIndex());
  3713. break;
  3714. }
  3715. };
  3716. // 'goto recurse' is used when handling a simple "unwrapping" node which
  3717. // produces no output, where ImplicitlyConvertedToType and AsTemplateArg need
  3718. // to be preserved.
  3719. recurse:
  3720. switch (E->getStmtClass()) {
  3721. case Expr::NoStmtClass:
  3722. #define ABSTRACT_STMT(Type)
  3723. #define EXPR(Type, Base)
  3724. #define STMT(Type, Base) \
  3725. case Expr::Type##Class:
  3726. #include "clang/AST/StmtNodes.inc"
  3727. // fallthrough
  3728. // These all can only appear in local or variable-initialization
  3729. // contexts and so should never appear in a mangling.
  3730. case Expr::AddrLabelExprClass:
  3731. case Expr::DesignatedInitUpdateExprClass:
  3732. case Expr::ImplicitValueInitExprClass:
  3733. case Expr::ArrayInitLoopExprClass:
  3734. case Expr::ArrayInitIndexExprClass:
  3735. case Expr::NoInitExprClass:
  3736. case Expr::ParenListExprClass:
  3737. case Expr::MSPropertyRefExprClass:
  3738. case Expr::MSPropertySubscriptExprClass:
  3739. case Expr::TypoExprClass: // This should no longer exist in the AST by now.
  3740. case Expr::RecoveryExprClass:
  3741. case Expr::OMPArraySectionExprClass:
  3742. case Expr::OMPArrayShapingExprClass:
  3743. case Expr::OMPIteratorExprClass:
  3744. case Expr::CXXInheritedCtorInitExprClass:
  3745. case Expr::CXXParenListInitExprClass:
  3746. llvm_unreachable("unexpected statement kind");
  3747. case Expr::ConstantExprClass:
  3748. E = cast<ConstantExpr>(E)->getSubExpr();
  3749. goto recurse;
  3750. // FIXME: invent manglings for all these.
  3751. case Expr::BlockExprClass:
  3752. case Expr::ChooseExprClass:
  3753. case Expr::CompoundLiteralExprClass:
  3754. case Expr::ExtVectorElementExprClass:
  3755. case Expr::GenericSelectionExprClass:
  3756. case Expr::ObjCEncodeExprClass:
  3757. case Expr::ObjCIsaExprClass:
  3758. case Expr::ObjCIvarRefExprClass:
  3759. case Expr::ObjCMessageExprClass:
  3760. case Expr::ObjCPropertyRefExprClass:
  3761. case Expr::ObjCProtocolExprClass:
  3762. case Expr::ObjCSelectorExprClass:
  3763. case Expr::ObjCStringLiteralClass:
  3764. case Expr::ObjCBoxedExprClass:
  3765. case Expr::ObjCArrayLiteralClass:
  3766. case Expr::ObjCDictionaryLiteralClass:
  3767. case Expr::ObjCSubscriptRefExprClass:
  3768. case Expr::ObjCIndirectCopyRestoreExprClass:
  3769. case Expr::ObjCAvailabilityCheckExprClass:
  3770. case Expr::OffsetOfExprClass:
  3771. case Expr::PredefinedExprClass:
  3772. case Expr::ShuffleVectorExprClass:
  3773. case Expr::ConvertVectorExprClass:
  3774. case Expr::StmtExprClass:
  3775. case Expr::TypeTraitExprClass:
  3776. case Expr::RequiresExprClass:
  3777. case Expr::ArrayTypeTraitExprClass:
  3778. case Expr::ExpressionTraitExprClass:
  3779. case Expr::VAArgExprClass:
  3780. case Expr::CUDAKernelCallExprClass:
  3781. case Expr::AsTypeExprClass:
  3782. case Expr::PseudoObjectExprClass:
  3783. case Expr::AtomicExprClass:
  3784. case Expr::SourceLocExprClass:
  3785. case Expr::BuiltinBitCastExprClass:
  3786. {
  3787. NotPrimaryExpr();
  3788. if (!NullOut) {
  3789. // As bad as this diagnostic is, it's better than crashing.
  3790. DiagnosticsEngine &Diags = Context.getDiags();
  3791. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3792. "cannot yet mangle expression type %0");
  3793. Diags.Report(E->getExprLoc(), DiagID)
  3794. << E->getStmtClassName() << E->getSourceRange();
  3795. return;
  3796. }
  3797. break;
  3798. }
  3799. case Expr::CXXUuidofExprClass: {
  3800. NotPrimaryExpr();
  3801. const CXXUuidofExpr *UE = cast<CXXUuidofExpr>(E);
  3802. // As of clang 12, uuidof uses the vendor extended expression
  3803. // mangling. Previously, it used a special-cased nonstandard extension.
  3804. if (Context.getASTContext().getLangOpts().getClangABICompat() >
  3805. LangOptions::ClangABI::Ver11) {
  3806. Out << "u8__uuidof";
  3807. if (UE->isTypeOperand())
  3808. mangleType(UE->getTypeOperand(Context.getASTContext()));
  3809. else
  3810. mangleTemplateArgExpr(UE->getExprOperand());
  3811. Out << 'E';
  3812. } else {
  3813. if (UE->isTypeOperand()) {
  3814. QualType UuidT = UE->getTypeOperand(Context.getASTContext());
  3815. Out << "u8__uuidoft";
  3816. mangleType(UuidT);
  3817. } else {
  3818. Expr *UuidExp = UE->getExprOperand();
  3819. Out << "u8__uuidofz";
  3820. mangleExpression(UuidExp);
  3821. }
  3822. }
  3823. break;
  3824. }
  3825. // Even gcc-4.5 doesn't mangle this.
  3826. case Expr::BinaryConditionalOperatorClass: {
  3827. NotPrimaryExpr();
  3828. DiagnosticsEngine &Diags = Context.getDiags();
  3829. unsigned DiagID =
  3830. Diags.getCustomDiagID(DiagnosticsEngine::Error,
  3831. "?: operator with omitted middle operand cannot be mangled");
  3832. Diags.Report(E->getExprLoc(), DiagID)
  3833. << E->getStmtClassName() << E->getSourceRange();
  3834. return;
  3835. }
  3836. // These are used for internal purposes and cannot be meaningfully mangled.
  3837. case Expr::OpaqueValueExprClass:
  3838. llvm_unreachable("cannot mangle opaque value; mangling wrong thing?");
  3839. case Expr::InitListExprClass: {
  3840. NotPrimaryExpr();
  3841. Out << "il";
  3842. mangleInitListElements(cast<InitListExpr>(E));
  3843. Out << "E";
  3844. break;
  3845. }
  3846. case Expr::DesignatedInitExprClass: {
  3847. NotPrimaryExpr();
  3848. auto *DIE = cast<DesignatedInitExpr>(E);
  3849. for (const auto &Designator : DIE->designators()) {
  3850. if (Designator.isFieldDesignator()) {
  3851. Out << "di";
  3852. mangleSourceName(Designator.getFieldName());
  3853. } else if (Designator.isArrayDesignator()) {
  3854. Out << "dx";
  3855. mangleExpression(DIE->getArrayIndex(Designator));
  3856. } else {
  3857. assert(Designator.isArrayRangeDesignator() &&
  3858. "unknown designator kind");
  3859. Out << "dX";
  3860. mangleExpression(DIE->getArrayRangeStart(Designator));
  3861. mangleExpression(DIE->getArrayRangeEnd(Designator));
  3862. }
  3863. }
  3864. mangleExpression(DIE->getInit());
  3865. break;
  3866. }
  3867. case Expr::CXXDefaultArgExprClass:
  3868. E = cast<CXXDefaultArgExpr>(E)->getExpr();
  3869. goto recurse;
  3870. case Expr::CXXDefaultInitExprClass:
  3871. E = cast<CXXDefaultInitExpr>(E)->getExpr();
  3872. goto recurse;
  3873. case Expr::CXXStdInitializerListExprClass:
  3874. E = cast<CXXStdInitializerListExpr>(E)->getSubExpr();
  3875. goto recurse;
  3876. case Expr::SubstNonTypeTemplateParmExprClass:
  3877. E = cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement();
  3878. goto recurse;
  3879. case Expr::UserDefinedLiteralClass:
  3880. // We follow g++'s approach of mangling a UDL as a call to the literal
  3881. // operator.
  3882. case Expr::CXXMemberCallExprClass: // fallthrough
  3883. case Expr::CallExprClass: {
  3884. NotPrimaryExpr();
  3885. const CallExpr *CE = cast<CallExpr>(E);
  3886. // <expression> ::= cp <simple-id> <expression>* E
  3887. // We use this mangling only when the call would use ADL except
  3888. // for being parenthesized. Per discussion with David
  3889. // Vandervoorde, 2011.04.25.
  3890. if (isParenthesizedADLCallee(CE)) {
  3891. Out << "cp";
  3892. // The callee here is a parenthesized UnresolvedLookupExpr with
  3893. // no qualifier and should always get mangled as a <simple-id>
  3894. // anyway.
  3895. // <expression> ::= cl <expression>* E
  3896. } else {
  3897. Out << "cl";
  3898. }
  3899. unsigned CallArity = CE->getNumArgs();
  3900. for (const Expr *Arg : CE->arguments())
  3901. if (isa<PackExpansionExpr>(Arg))
  3902. CallArity = UnknownArity;
  3903. mangleExpression(CE->getCallee(), CallArity);
  3904. for (const Expr *Arg : CE->arguments())
  3905. mangleExpression(Arg);
  3906. Out << 'E';
  3907. break;
  3908. }
  3909. case Expr::CXXNewExprClass: {
  3910. NotPrimaryExpr();
  3911. const CXXNewExpr *New = cast<CXXNewExpr>(E);
  3912. if (New->isGlobalNew()) Out << "gs";
  3913. Out << (New->isArray() ? "na" : "nw");
  3914. for (CXXNewExpr::const_arg_iterator I = New->placement_arg_begin(),
  3915. E = New->placement_arg_end(); I != E; ++I)
  3916. mangleExpression(*I);
  3917. Out << '_';
  3918. mangleType(New->getAllocatedType());
  3919. if (New->hasInitializer()) {
  3920. if (New->getInitializationStyle() == CXXNewExpr::ListInit)
  3921. Out << "il";
  3922. else
  3923. Out << "pi";
  3924. const Expr *Init = New->getInitializer();
  3925. if (const CXXConstructExpr *CCE = dyn_cast<CXXConstructExpr>(Init)) {
  3926. // Directly inline the initializers.
  3927. for (CXXConstructExpr::const_arg_iterator I = CCE->arg_begin(),
  3928. E = CCE->arg_end();
  3929. I != E; ++I)
  3930. mangleExpression(*I);
  3931. } else if (const ParenListExpr *PLE = dyn_cast<ParenListExpr>(Init)) {
  3932. for (unsigned i = 0, e = PLE->getNumExprs(); i != e; ++i)
  3933. mangleExpression(PLE->getExpr(i));
  3934. } else if (New->getInitializationStyle() == CXXNewExpr::ListInit &&
  3935. isa<InitListExpr>(Init)) {
  3936. // Only take InitListExprs apart for list-initialization.
  3937. mangleInitListElements(cast<InitListExpr>(Init));
  3938. } else
  3939. mangleExpression(Init);
  3940. }
  3941. Out << 'E';
  3942. break;
  3943. }
  3944. case Expr::CXXPseudoDestructorExprClass: {
  3945. NotPrimaryExpr();
  3946. const auto *PDE = cast<CXXPseudoDestructorExpr>(E);
  3947. if (const Expr *Base = PDE->getBase())
  3948. mangleMemberExprBase(Base, PDE->isArrow());
  3949. NestedNameSpecifier *Qualifier = PDE->getQualifier();
  3950. if (TypeSourceInfo *ScopeInfo = PDE->getScopeTypeInfo()) {
  3951. if (Qualifier) {
  3952. mangleUnresolvedPrefix(Qualifier,
  3953. /*recursive=*/true);
  3954. mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType());
  3955. Out << 'E';
  3956. } else {
  3957. Out << "sr";
  3958. if (!mangleUnresolvedTypeOrSimpleId(ScopeInfo->getType()))
  3959. Out << 'E';
  3960. }
  3961. } else if (Qualifier) {
  3962. mangleUnresolvedPrefix(Qualifier);
  3963. }
  3964. // <base-unresolved-name> ::= dn <destructor-name>
  3965. Out << "dn";
  3966. QualType DestroyedType = PDE->getDestroyedType();
  3967. mangleUnresolvedTypeOrSimpleId(DestroyedType);
  3968. break;
  3969. }
  3970. case Expr::MemberExprClass: {
  3971. NotPrimaryExpr();
  3972. const MemberExpr *ME = cast<MemberExpr>(E);
  3973. mangleMemberExpr(ME->getBase(), ME->isArrow(),
  3974. ME->getQualifier(), nullptr,
  3975. ME->getMemberDecl()->getDeclName(),
  3976. ME->getTemplateArgs(), ME->getNumTemplateArgs(),
  3977. Arity);
  3978. break;
  3979. }
  3980. case Expr::UnresolvedMemberExprClass: {
  3981. NotPrimaryExpr();
  3982. const UnresolvedMemberExpr *ME = cast<UnresolvedMemberExpr>(E);
  3983. mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
  3984. ME->isArrow(), ME->getQualifier(), nullptr,
  3985. ME->getMemberName(),
  3986. ME->getTemplateArgs(), ME->getNumTemplateArgs(),
  3987. Arity);
  3988. break;
  3989. }
  3990. case Expr::CXXDependentScopeMemberExprClass: {
  3991. NotPrimaryExpr();
  3992. const CXXDependentScopeMemberExpr *ME
  3993. = cast<CXXDependentScopeMemberExpr>(E);
  3994. mangleMemberExpr(ME->isImplicitAccess() ? nullptr : ME->getBase(),
  3995. ME->isArrow(), ME->getQualifier(),
  3996. ME->getFirstQualifierFoundInScope(),
  3997. ME->getMember(),
  3998. ME->getTemplateArgs(), ME->getNumTemplateArgs(),
  3999. Arity);
  4000. break;
  4001. }
  4002. case Expr::UnresolvedLookupExprClass: {
  4003. NotPrimaryExpr();
  4004. const UnresolvedLookupExpr *ULE = cast<UnresolvedLookupExpr>(E);
  4005. mangleUnresolvedName(ULE->getQualifier(), ULE->getName(),
  4006. ULE->getTemplateArgs(), ULE->getNumTemplateArgs(),
  4007. Arity);
  4008. break;
  4009. }
  4010. case Expr::CXXUnresolvedConstructExprClass: {
  4011. NotPrimaryExpr();
  4012. const CXXUnresolvedConstructExpr *CE = cast<CXXUnresolvedConstructExpr>(E);
  4013. unsigned N = CE->getNumArgs();
  4014. if (CE->isListInitialization()) {
  4015. assert(N == 1 && "unexpected form for list initialization");
  4016. auto *IL = cast<InitListExpr>(CE->getArg(0));
  4017. Out << "tl";
  4018. mangleType(CE->getType());
  4019. mangleInitListElements(IL);
  4020. Out << "E";
  4021. break;
  4022. }
  4023. Out << "cv";
  4024. mangleType(CE->getType());
  4025. if (N != 1) Out << '_';
  4026. for (unsigned I = 0; I != N; ++I) mangleExpression(CE->getArg(I));
  4027. if (N != 1) Out << 'E';
  4028. break;
  4029. }
  4030. case Expr::CXXConstructExprClass: {
  4031. // An implicit cast is silent, thus may contain <expr-primary>.
  4032. const auto *CE = cast<CXXConstructExpr>(E);
  4033. if (!CE->isListInitialization() || CE->isStdInitListInitialization()) {
  4034. assert(
  4035. CE->getNumArgs() >= 1 &&
  4036. (CE->getNumArgs() == 1 || isa<CXXDefaultArgExpr>(CE->getArg(1))) &&
  4037. "implicit CXXConstructExpr must have one argument");
  4038. E = cast<CXXConstructExpr>(E)->getArg(0);
  4039. goto recurse;
  4040. }
  4041. NotPrimaryExpr();
  4042. Out << "il";
  4043. for (auto *E : CE->arguments())
  4044. mangleExpression(E);
  4045. Out << "E";
  4046. break;
  4047. }
  4048. case Expr::CXXTemporaryObjectExprClass: {
  4049. NotPrimaryExpr();
  4050. const auto *CE = cast<CXXTemporaryObjectExpr>(E);
  4051. unsigned N = CE->getNumArgs();
  4052. bool List = CE->isListInitialization();
  4053. if (List)
  4054. Out << "tl";
  4055. else
  4056. Out << "cv";
  4057. mangleType(CE->getType());
  4058. if (!List && N != 1)
  4059. Out << '_';
  4060. if (CE->isStdInitListInitialization()) {
  4061. // We implicitly created a std::initializer_list<T> for the first argument
  4062. // of a constructor of type U in an expression of the form U{a, b, c}.
  4063. // Strip all the semantic gunk off the initializer list.
  4064. auto *SILE =
  4065. cast<CXXStdInitializerListExpr>(CE->getArg(0)->IgnoreImplicit());
  4066. auto *ILE = cast<InitListExpr>(SILE->getSubExpr()->IgnoreImplicit());
  4067. mangleInitListElements(ILE);
  4068. } else {
  4069. for (auto *E : CE->arguments())
  4070. mangleExpression(E);
  4071. }
  4072. if (List || N != 1)
  4073. Out << 'E';
  4074. break;
  4075. }
  4076. case Expr::CXXScalarValueInitExprClass:
  4077. NotPrimaryExpr();
  4078. Out << "cv";
  4079. mangleType(E->getType());
  4080. Out << "_E";
  4081. break;
  4082. case Expr::CXXNoexceptExprClass:
  4083. NotPrimaryExpr();
  4084. Out << "nx";
  4085. mangleExpression(cast<CXXNoexceptExpr>(E)->getOperand());
  4086. break;
  4087. case Expr::UnaryExprOrTypeTraitExprClass: {
  4088. // Non-instantiation-dependent traits are an <expr-primary> integer literal.
  4089. const UnaryExprOrTypeTraitExpr *SAE = cast<UnaryExprOrTypeTraitExpr>(E);
  4090. if (!SAE->isInstantiationDependent()) {
  4091. // Itanium C++ ABI:
  4092. // If the operand of a sizeof or alignof operator is not
  4093. // instantiation-dependent it is encoded as an integer literal
  4094. // reflecting the result of the operator.
  4095. //
  4096. // If the result of the operator is implicitly converted to a known
  4097. // integer type, that type is used for the literal; otherwise, the type
  4098. // of std::size_t or std::ptrdiff_t is used.
  4099. QualType T = (ImplicitlyConvertedToType.isNull() ||
  4100. !ImplicitlyConvertedToType->isIntegerType())? SAE->getType()
  4101. : ImplicitlyConvertedToType;
  4102. llvm::APSInt V = SAE->EvaluateKnownConstInt(Context.getASTContext());
  4103. mangleIntegerLiteral(T, V);
  4104. break;
  4105. }
  4106. NotPrimaryExpr(); // But otherwise, they are not.
  4107. auto MangleAlignofSizeofArg = [&] {
  4108. if (SAE->isArgumentType()) {
  4109. Out << 't';
  4110. mangleType(SAE->getArgumentType());
  4111. } else {
  4112. Out << 'z';
  4113. mangleExpression(SAE->getArgumentExpr());
  4114. }
  4115. };
  4116. switch(SAE->getKind()) {
  4117. case UETT_SizeOf:
  4118. Out << 's';
  4119. MangleAlignofSizeofArg();
  4120. break;
  4121. case UETT_PreferredAlignOf:
  4122. // As of clang 12, we mangle __alignof__ differently than alignof. (They
  4123. // have acted differently since Clang 8, but were previously mangled the
  4124. // same.)
  4125. if (Context.getASTContext().getLangOpts().getClangABICompat() >
  4126. LangOptions::ClangABI::Ver11) {
  4127. Out << "u11__alignof__";
  4128. if (SAE->isArgumentType())
  4129. mangleType(SAE->getArgumentType());
  4130. else
  4131. mangleTemplateArgExpr(SAE->getArgumentExpr());
  4132. Out << 'E';
  4133. break;
  4134. }
  4135. [[fallthrough]];
  4136. case UETT_AlignOf:
  4137. Out << 'a';
  4138. MangleAlignofSizeofArg();
  4139. break;
  4140. case UETT_VecStep: {
  4141. DiagnosticsEngine &Diags = Context.getDiags();
  4142. unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
  4143. "cannot yet mangle vec_step expression");
  4144. Diags.Report(DiagID);
  4145. return;
  4146. }
  4147. case UETT_OpenMPRequiredSimdAlign: {
  4148. DiagnosticsEngine &Diags = Context.getDiags();
  4149. unsigned DiagID = Diags.getCustomDiagID(
  4150. DiagnosticsEngine::Error,
  4151. "cannot yet mangle __builtin_omp_required_simd_align expression");
  4152. Diags.Report(DiagID);
  4153. return;
  4154. }
  4155. }
  4156. break;
  4157. }
  4158. case Expr::CXXThrowExprClass: {
  4159. NotPrimaryExpr();
  4160. const CXXThrowExpr *TE = cast<CXXThrowExpr>(E);
  4161. // <expression> ::= tw <expression> # throw expression
  4162. // ::= tr # rethrow
  4163. if (TE->getSubExpr()) {
  4164. Out << "tw";
  4165. mangleExpression(TE->getSubExpr());
  4166. } else {
  4167. Out << "tr";
  4168. }
  4169. break;
  4170. }
  4171. case Expr::CXXTypeidExprClass: {
  4172. NotPrimaryExpr();
  4173. const CXXTypeidExpr *TIE = cast<CXXTypeidExpr>(E);
  4174. // <expression> ::= ti <type> # typeid (type)
  4175. // ::= te <expression> # typeid (expression)
  4176. if (TIE->isTypeOperand()) {
  4177. Out << "ti";
  4178. mangleType(TIE->getTypeOperand(Context.getASTContext()));
  4179. } else {
  4180. Out << "te";
  4181. mangleExpression(TIE->getExprOperand());
  4182. }
  4183. break;
  4184. }
  4185. case Expr::CXXDeleteExprClass: {
  4186. NotPrimaryExpr();
  4187. const CXXDeleteExpr *DE = cast<CXXDeleteExpr>(E);
  4188. // <expression> ::= [gs] dl <expression> # [::] delete expr
  4189. // ::= [gs] da <expression> # [::] delete [] expr
  4190. if (DE->isGlobalDelete()) Out << "gs";
  4191. Out << (DE->isArrayForm() ? "da" : "dl");
  4192. mangleExpression(DE->getArgument());
  4193. break;
  4194. }
  4195. case Expr::UnaryOperatorClass: {
  4196. NotPrimaryExpr();
  4197. const UnaryOperator *UO = cast<UnaryOperator>(E);
  4198. mangleOperatorName(UnaryOperator::getOverloadedOperator(UO->getOpcode()),
  4199. /*Arity=*/1);
  4200. mangleExpression(UO->getSubExpr());
  4201. break;
  4202. }
  4203. case Expr::ArraySubscriptExprClass: {
  4204. NotPrimaryExpr();
  4205. const ArraySubscriptExpr *AE = cast<ArraySubscriptExpr>(E);
  4206. // Array subscript is treated as a syntactically weird form of
  4207. // binary operator.
  4208. Out << "ix";
  4209. mangleExpression(AE->getLHS());
  4210. mangleExpression(AE->getRHS());
  4211. break;
  4212. }
  4213. case Expr::MatrixSubscriptExprClass: {
  4214. NotPrimaryExpr();
  4215. const MatrixSubscriptExpr *ME = cast<MatrixSubscriptExpr>(E);
  4216. Out << "ixix";
  4217. mangleExpression(ME->getBase());
  4218. mangleExpression(ME->getRowIdx());
  4219. mangleExpression(ME->getColumnIdx());
  4220. break;
  4221. }
  4222. case Expr::CompoundAssignOperatorClass: // fallthrough
  4223. case Expr::BinaryOperatorClass: {
  4224. NotPrimaryExpr();
  4225. const BinaryOperator *BO = cast<BinaryOperator>(E);
  4226. if (BO->getOpcode() == BO_PtrMemD)
  4227. Out << "ds";
  4228. else
  4229. mangleOperatorName(BinaryOperator::getOverloadedOperator(BO->getOpcode()),
  4230. /*Arity=*/2);
  4231. mangleExpression(BO->getLHS());
  4232. mangleExpression(BO->getRHS());
  4233. break;
  4234. }
  4235. case Expr::CXXRewrittenBinaryOperatorClass: {
  4236. NotPrimaryExpr();
  4237. // The mangled form represents the original syntax.
  4238. CXXRewrittenBinaryOperator::DecomposedForm Decomposed =
  4239. cast<CXXRewrittenBinaryOperator>(E)->getDecomposedForm();
  4240. mangleOperatorName(BinaryOperator::getOverloadedOperator(Decomposed.Opcode),
  4241. /*Arity=*/2);
  4242. mangleExpression(Decomposed.LHS);
  4243. mangleExpression(Decomposed.RHS);
  4244. break;
  4245. }
  4246. case Expr::ConditionalOperatorClass: {
  4247. NotPrimaryExpr();
  4248. const ConditionalOperator *CO = cast<ConditionalOperator>(E);
  4249. mangleOperatorName(OO_Conditional, /*Arity=*/3);
  4250. mangleExpression(CO->getCond());
  4251. mangleExpression(CO->getLHS(), Arity);
  4252. mangleExpression(CO->getRHS(), Arity);
  4253. break;
  4254. }
  4255. case Expr::ImplicitCastExprClass: {
  4256. ImplicitlyConvertedToType = E->getType();
  4257. E = cast<ImplicitCastExpr>(E)->getSubExpr();
  4258. goto recurse;
  4259. }
  4260. case Expr::ObjCBridgedCastExprClass: {
  4261. NotPrimaryExpr();
  4262. // Mangle ownership casts as a vendor extended operator __bridge,
  4263. // __bridge_transfer, or __bridge_retain.
  4264. StringRef Kind = cast<ObjCBridgedCastExpr>(E)->getBridgeKindName();
  4265. Out << "v1U" << Kind.size() << Kind;
  4266. mangleCastExpression(E, "cv");
  4267. break;
  4268. }
  4269. case Expr::CStyleCastExprClass:
  4270. NotPrimaryExpr();
  4271. mangleCastExpression(E, "cv");
  4272. break;
  4273. case Expr::CXXFunctionalCastExprClass: {
  4274. NotPrimaryExpr();
  4275. auto *Sub = cast<ExplicitCastExpr>(E)->getSubExpr()->IgnoreImplicit();
  4276. // FIXME: Add isImplicit to CXXConstructExpr.
  4277. if (auto *CCE = dyn_cast<CXXConstructExpr>(Sub))
  4278. if (CCE->getParenOrBraceRange().isInvalid())
  4279. Sub = CCE->getArg(0)->IgnoreImplicit();
  4280. if (auto *StdInitList = dyn_cast<CXXStdInitializerListExpr>(Sub))
  4281. Sub = StdInitList->getSubExpr()->IgnoreImplicit();
  4282. if (auto *IL = dyn_cast<InitListExpr>(Sub)) {
  4283. Out << "tl";
  4284. mangleType(E->getType());
  4285. mangleInitListElements(IL);
  4286. Out << "E";
  4287. } else {
  4288. mangleCastExpression(E, "cv");
  4289. }
  4290. break;
  4291. }
  4292. case Expr::CXXStaticCastExprClass:
  4293. NotPrimaryExpr();
  4294. mangleCastExpression(E, "sc");
  4295. break;
  4296. case Expr::CXXDynamicCastExprClass:
  4297. NotPrimaryExpr();
  4298. mangleCastExpression(E, "dc");
  4299. break;
  4300. case Expr::CXXReinterpretCastExprClass:
  4301. NotPrimaryExpr();
  4302. mangleCastExpression(E, "rc");
  4303. break;
  4304. case Expr::CXXConstCastExprClass:
  4305. NotPrimaryExpr();
  4306. mangleCastExpression(E, "cc");
  4307. break;
  4308. case Expr::CXXAddrspaceCastExprClass:
  4309. NotPrimaryExpr();
  4310. mangleCastExpression(E, "ac");
  4311. break;
  4312. case Expr::CXXOperatorCallExprClass: {
  4313. NotPrimaryExpr();
  4314. const CXXOperatorCallExpr *CE = cast<CXXOperatorCallExpr>(E);
  4315. unsigned NumArgs = CE->getNumArgs();
  4316. // A CXXOperatorCallExpr for OO_Arrow models only semantics, not syntax
  4317. // (the enclosing MemberExpr covers the syntactic portion).
  4318. if (CE->getOperator() != OO_Arrow)
  4319. mangleOperatorName(CE->getOperator(), /*Arity=*/NumArgs);
  4320. // Mangle the arguments.
  4321. for (unsigned i = 0; i != NumArgs; ++i)
  4322. mangleExpression(CE->getArg(i));
  4323. break;
  4324. }
  4325. case Expr::ParenExprClass:
  4326. E = cast<ParenExpr>(E)->getSubExpr();
  4327. goto recurse;
  4328. case Expr::ConceptSpecializationExprClass: {
  4329. // <expr-primary> ::= L <mangled-name> E # external name
  4330. Out << "L_Z";
  4331. auto *CSE = cast<ConceptSpecializationExpr>(E);
  4332. mangleTemplateName(CSE->getNamedConcept(), CSE->getTemplateArguments());
  4333. Out << 'E';
  4334. break;
  4335. }
  4336. case Expr::DeclRefExprClass:
  4337. // MangleDeclRefExpr helper handles primary-vs-nonprimary
  4338. MangleDeclRefExpr(cast<DeclRefExpr>(E)->getDecl());
  4339. break;
  4340. case Expr::SubstNonTypeTemplateParmPackExprClass:
  4341. NotPrimaryExpr();
  4342. // FIXME: not clear how to mangle this!
  4343. // template <unsigned N...> class A {
  4344. // template <class U...> void foo(U (&x)[N]...);
  4345. // };
  4346. Out << "_SUBSTPACK_";
  4347. break;
  4348. case Expr::FunctionParmPackExprClass: {
  4349. NotPrimaryExpr();
  4350. // FIXME: not clear how to mangle this!
  4351. const FunctionParmPackExpr *FPPE = cast<FunctionParmPackExpr>(E);
  4352. Out << "v110_SUBSTPACK";
  4353. MangleDeclRefExpr(FPPE->getParameterPack());
  4354. break;
  4355. }
  4356. case Expr::DependentScopeDeclRefExprClass: {
  4357. NotPrimaryExpr();
  4358. const DependentScopeDeclRefExpr *DRE = cast<DependentScopeDeclRefExpr>(E);
  4359. mangleUnresolvedName(DRE->getQualifier(), DRE->getDeclName(),
  4360. DRE->getTemplateArgs(), DRE->getNumTemplateArgs(),
  4361. Arity);
  4362. break;
  4363. }
  4364. case Expr::CXXBindTemporaryExprClass:
  4365. E = cast<CXXBindTemporaryExpr>(E)->getSubExpr();
  4366. goto recurse;
  4367. case Expr::ExprWithCleanupsClass:
  4368. E = cast<ExprWithCleanups>(E)->getSubExpr();
  4369. goto recurse;
  4370. case Expr::FloatingLiteralClass: {
  4371. // <expr-primary>
  4372. const FloatingLiteral *FL = cast<FloatingLiteral>(E);
  4373. mangleFloatLiteral(FL->getType(), FL->getValue());
  4374. break;
  4375. }
  4376. case Expr::FixedPointLiteralClass:
  4377. // Currently unimplemented -- might be <expr-primary> in future?
  4378. mangleFixedPointLiteral();
  4379. break;
  4380. case Expr::CharacterLiteralClass:
  4381. // <expr-primary>
  4382. Out << 'L';
  4383. mangleType(E->getType());
  4384. Out << cast<CharacterLiteral>(E)->getValue();
  4385. Out << 'E';
  4386. break;
  4387. // FIXME. __objc_yes/__objc_no are mangled same as true/false
  4388. case Expr::ObjCBoolLiteralExprClass:
  4389. // <expr-primary>
  4390. Out << "Lb";
  4391. Out << (cast<ObjCBoolLiteralExpr>(E)->getValue() ? '1' : '0');
  4392. Out << 'E';
  4393. break;
  4394. case Expr::CXXBoolLiteralExprClass:
  4395. // <expr-primary>
  4396. Out << "Lb";
  4397. Out << (cast<CXXBoolLiteralExpr>(E)->getValue() ? '1' : '0');
  4398. Out << 'E';
  4399. break;
  4400. case Expr::IntegerLiteralClass: {
  4401. // <expr-primary>
  4402. llvm::APSInt Value(cast<IntegerLiteral>(E)->getValue());
  4403. if (E->getType()->isSignedIntegerType())
  4404. Value.setIsSigned(true);
  4405. mangleIntegerLiteral(E->getType(), Value);
  4406. break;
  4407. }
  4408. case Expr::ImaginaryLiteralClass: {
  4409. // <expr-primary>
  4410. const ImaginaryLiteral *IE = cast<ImaginaryLiteral>(E);
  4411. // Mangle as if a complex literal.
  4412. // Proposal from David Vandevoorde, 2010.06.30.
  4413. Out << 'L';
  4414. mangleType(E->getType());
  4415. if (const FloatingLiteral *Imag =
  4416. dyn_cast<FloatingLiteral>(IE->getSubExpr())) {
  4417. // Mangle a floating-point zero of the appropriate type.
  4418. mangleFloat(llvm::APFloat(Imag->getValue().getSemantics()));
  4419. Out << '_';
  4420. mangleFloat(Imag->getValue());
  4421. } else {
  4422. Out << "0_";
  4423. llvm::APSInt Value(cast<IntegerLiteral>(IE->getSubExpr())->getValue());
  4424. if (IE->getSubExpr()->getType()->isSignedIntegerType())
  4425. Value.setIsSigned(true);
  4426. mangleNumber(Value);
  4427. }
  4428. Out << 'E';
  4429. break;
  4430. }
  4431. case Expr::StringLiteralClass: {
  4432. // <expr-primary>
  4433. // Revised proposal from David Vandervoorde, 2010.07.15.
  4434. Out << 'L';
  4435. assert(isa<ConstantArrayType>(E->getType()));
  4436. mangleType(E->getType());
  4437. Out << 'E';
  4438. break;
  4439. }
  4440. case Expr::GNUNullExprClass:
  4441. // <expr-primary>
  4442. // Mangle as if an integer literal 0.
  4443. mangleIntegerLiteral(E->getType(), llvm::APSInt(32));
  4444. break;
  4445. case Expr::CXXNullPtrLiteralExprClass: {
  4446. // <expr-primary>
  4447. Out << "LDnE";
  4448. break;
  4449. }
  4450. case Expr::LambdaExprClass: {
  4451. // A lambda-expression can't appear in the signature of an
  4452. // externally-visible declaration, so there's no standard mangling for
  4453. // this, but mangling as a literal of the closure type seems reasonable.
  4454. Out << "L";
  4455. mangleType(Context.getASTContext().getRecordType(cast<LambdaExpr>(E)->getLambdaClass()));
  4456. Out << "E";
  4457. break;
  4458. }
  4459. case Expr::PackExpansionExprClass:
  4460. NotPrimaryExpr();
  4461. Out << "sp";
  4462. mangleExpression(cast<PackExpansionExpr>(E)->getPattern());
  4463. break;
  4464. case Expr::SizeOfPackExprClass: {
  4465. NotPrimaryExpr();
  4466. auto *SPE = cast<SizeOfPackExpr>(E);
  4467. if (SPE->isPartiallySubstituted()) {
  4468. Out << "sP";
  4469. for (const auto &A : SPE->getPartialArguments())
  4470. mangleTemplateArg(A, false);
  4471. Out << "E";
  4472. break;
  4473. }
  4474. Out << "sZ";
  4475. const NamedDecl *Pack = SPE->getPack();
  4476. if (const TemplateTypeParmDecl *TTP = dyn_cast<TemplateTypeParmDecl>(Pack))
  4477. mangleTemplateParameter(TTP->getDepth(), TTP->getIndex());
  4478. else if (const NonTypeTemplateParmDecl *NTTP
  4479. = dyn_cast<NonTypeTemplateParmDecl>(Pack))
  4480. mangleTemplateParameter(NTTP->getDepth(), NTTP->getIndex());
  4481. else if (const TemplateTemplateParmDecl *TempTP
  4482. = dyn_cast<TemplateTemplateParmDecl>(Pack))
  4483. mangleTemplateParameter(TempTP->getDepth(), TempTP->getIndex());
  4484. else
  4485. mangleFunctionParam(cast<ParmVarDecl>(Pack));
  4486. break;
  4487. }
  4488. case Expr::MaterializeTemporaryExprClass:
  4489. E = cast<MaterializeTemporaryExpr>(E)->getSubExpr();
  4490. goto recurse;
  4491. case Expr::CXXFoldExprClass: {
  4492. NotPrimaryExpr();
  4493. auto *FE = cast<CXXFoldExpr>(E);
  4494. if (FE->isLeftFold())
  4495. Out << (FE->getInit() ? "fL" : "fl");
  4496. else
  4497. Out << (FE->getInit() ? "fR" : "fr");
  4498. if (FE->getOperator() == BO_PtrMemD)
  4499. Out << "ds";
  4500. else
  4501. mangleOperatorName(
  4502. BinaryOperator::getOverloadedOperator(FE->getOperator()),
  4503. /*Arity=*/2);
  4504. if (FE->getLHS())
  4505. mangleExpression(FE->getLHS());
  4506. if (FE->getRHS())
  4507. mangleExpression(FE->getRHS());
  4508. break;
  4509. }
  4510. case Expr::CXXThisExprClass:
  4511. NotPrimaryExpr();
  4512. Out << "fpT";
  4513. break;
  4514. case Expr::CoawaitExprClass:
  4515. // FIXME: Propose a non-vendor mangling.
  4516. NotPrimaryExpr();
  4517. Out << "v18co_await";
  4518. mangleExpression(cast<CoawaitExpr>(E)->getOperand());
  4519. break;
  4520. case Expr::DependentCoawaitExprClass:
  4521. // FIXME: Propose a non-vendor mangling.
  4522. NotPrimaryExpr();
  4523. Out << "v18co_await";
  4524. mangleExpression(cast<DependentCoawaitExpr>(E)->getOperand());
  4525. break;
  4526. case Expr::CoyieldExprClass:
  4527. // FIXME: Propose a non-vendor mangling.
  4528. NotPrimaryExpr();
  4529. Out << "v18co_yield";
  4530. mangleExpression(cast<CoawaitExpr>(E)->getOperand());
  4531. break;
  4532. case Expr::SYCLUniqueStableNameExprClass: {
  4533. const auto *USN = cast<SYCLUniqueStableNameExpr>(E);
  4534. NotPrimaryExpr();
  4535. Out << "u33__builtin_sycl_unique_stable_name";
  4536. mangleType(USN->getTypeSourceInfo()->getType());
  4537. Out << "E";
  4538. break;
  4539. }
  4540. }
  4541. if (AsTemplateArg && !IsPrimaryExpr)
  4542. Out << 'E';
  4543. }
  4544. /// Mangle an expression which refers to a parameter variable.
  4545. ///
  4546. /// <expression> ::= <function-param>
  4547. /// <function-param> ::= fp <top-level CV-qualifiers> _ # L == 0, I == 0
  4548. /// <function-param> ::= fp <top-level CV-qualifiers>
  4549. /// <parameter-2 non-negative number> _ # L == 0, I > 0
  4550. /// <function-param> ::= fL <L-1 non-negative number>
  4551. /// p <top-level CV-qualifiers> _ # L > 0, I == 0
  4552. /// <function-param> ::= fL <L-1 non-negative number>
  4553. /// p <top-level CV-qualifiers>
  4554. /// <I-1 non-negative number> _ # L > 0, I > 0
  4555. ///
  4556. /// L is the nesting depth of the parameter, defined as 1 if the
  4557. /// parameter comes from the innermost function prototype scope
  4558. /// enclosing the current context, 2 if from the next enclosing
  4559. /// function prototype scope, and so on, with one special case: if
  4560. /// we've processed the full parameter clause for the innermost
  4561. /// function type, then L is one less. This definition conveniently
  4562. /// makes it irrelevant whether a function's result type was written
  4563. /// trailing or leading, but is otherwise overly complicated; the
  4564. /// numbering was first designed without considering references to
  4565. /// parameter in locations other than return types, and then the
  4566. /// mangling had to be generalized without changing the existing
  4567. /// manglings.
  4568. ///
  4569. /// I is the zero-based index of the parameter within its parameter
  4570. /// declaration clause. Note that the original ABI document describes
  4571. /// this using 1-based ordinals.
  4572. void CXXNameMangler::mangleFunctionParam(const ParmVarDecl *parm) {
  4573. unsigned parmDepth = parm->getFunctionScopeDepth();
  4574. unsigned parmIndex = parm->getFunctionScopeIndex();
  4575. // Compute 'L'.
  4576. // parmDepth does not include the declaring function prototype.
  4577. // FunctionTypeDepth does account for that.
  4578. assert(parmDepth < FunctionTypeDepth.getDepth());
  4579. unsigned nestingDepth = FunctionTypeDepth.getDepth() - parmDepth;
  4580. if (FunctionTypeDepth.isInResultType())
  4581. nestingDepth--;
  4582. if (nestingDepth == 0) {
  4583. Out << "fp";
  4584. } else {
  4585. Out << "fL" << (nestingDepth - 1) << 'p';
  4586. }
  4587. // Top-level qualifiers. We don't have to worry about arrays here,
  4588. // because parameters declared as arrays should already have been
  4589. // transformed to have pointer type. FIXME: apparently these don't
  4590. // get mangled if used as an rvalue of a known non-class type?
  4591. assert(!parm->getType()->isArrayType()
  4592. && "parameter's type is still an array type?");
  4593. if (const DependentAddressSpaceType *DAST =
  4594. dyn_cast<DependentAddressSpaceType>(parm->getType())) {
  4595. mangleQualifiers(DAST->getPointeeType().getQualifiers(), DAST);
  4596. } else {
  4597. mangleQualifiers(parm->getType().getQualifiers());
  4598. }
  4599. // Parameter index.
  4600. if (parmIndex != 0) {
  4601. Out << (parmIndex - 1);
  4602. }
  4603. Out << '_';
  4604. }
  4605. void CXXNameMangler::mangleCXXCtorType(CXXCtorType T,
  4606. const CXXRecordDecl *InheritedFrom) {
  4607. // <ctor-dtor-name> ::= C1 # complete object constructor
  4608. // ::= C2 # base object constructor
  4609. // ::= CI1 <type> # complete inheriting constructor
  4610. // ::= CI2 <type> # base inheriting constructor
  4611. //
  4612. // In addition, C5 is a comdat name with C1 and C2 in it.
  4613. Out << 'C';
  4614. if (InheritedFrom)
  4615. Out << 'I';
  4616. switch (T) {
  4617. case Ctor_Complete:
  4618. Out << '1';
  4619. break;
  4620. case Ctor_Base:
  4621. Out << '2';
  4622. break;
  4623. case Ctor_Comdat:
  4624. Out << '5';
  4625. break;
  4626. case Ctor_DefaultClosure:
  4627. case Ctor_CopyingClosure:
  4628. llvm_unreachable("closure constructors don't exist for the Itanium ABI!");
  4629. }
  4630. if (InheritedFrom)
  4631. mangleName(InheritedFrom);
  4632. }
  4633. void CXXNameMangler::mangleCXXDtorType(CXXDtorType T) {
  4634. // <ctor-dtor-name> ::= D0 # deleting destructor
  4635. // ::= D1 # complete object destructor
  4636. // ::= D2 # base object destructor
  4637. //
  4638. // In addition, D5 is a comdat name with D1, D2 and, if virtual, D0 in it.
  4639. switch (T) {
  4640. case Dtor_Deleting:
  4641. Out << "D0";
  4642. break;
  4643. case Dtor_Complete:
  4644. Out << "D1";
  4645. break;
  4646. case Dtor_Base:
  4647. Out << "D2";
  4648. break;
  4649. case Dtor_Comdat:
  4650. Out << "D5";
  4651. break;
  4652. }
  4653. }
  4654. namespace {
  4655. // Helper to provide ancillary information on a template used to mangle its
  4656. // arguments.
  4657. struct TemplateArgManglingInfo {
  4658. TemplateDecl *ResolvedTemplate = nullptr;
  4659. bool SeenPackExpansionIntoNonPack = false;
  4660. const NamedDecl *UnresolvedExpandedPack = nullptr;
  4661. TemplateArgManglingInfo(TemplateName TN) {
  4662. if (TemplateDecl *TD = TN.getAsTemplateDecl())
  4663. ResolvedTemplate = TD;
  4664. }
  4665. /// Do we need to mangle template arguments with exactly correct types?
  4666. ///
  4667. /// This should be called exactly once for each parameter / argument pair, in
  4668. /// order.
  4669. bool needExactType(unsigned ParamIdx, const TemplateArgument &Arg) {
  4670. // We need correct types when the template-name is unresolved or when it
  4671. // names a template that is able to be overloaded.
  4672. if (!ResolvedTemplate || SeenPackExpansionIntoNonPack)
  4673. return true;
  4674. // Move to the next parameter.
  4675. const NamedDecl *Param = UnresolvedExpandedPack;
  4676. if (!Param) {
  4677. assert(ParamIdx < ResolvedTemplate->getTemplateParameters()->size() &&
  4678. "no parameter for argument");
  4679. Param = ResolvedTemplate->getTemplateParameters()->getParam(ParamIdx);
  4680. // If we reach an expanded parameter pack whose argument isn't in pack
  4681. // form, that means Sema couldn't figure out which arguments belonged to
  4682. // it, because it contains a pack expansion. Track the expanded pack for
  4683. // all further template arguments until we hit that pack expansion.
  4684. if (Param->isParameterPack() && Arg.getKind() != TemplateArgument::Pack) {
  4685. assert(getExpandedPackSize(Param) &&
  4686. "failed to form pack argument for parameter pack");
  4687. UnresolvedExpandedPack = Param;
  4688. }
  4689. }
  4690. // If we encounter a pack argument that is expanded into a non-pack
  4691. // parameter, we can no longer track parameter / argument correspondence,
  4692. // and need to use exact types from this point onwards.
  4693. if (Arg.isPackExpansion() &&
  4694. (!Param->isParameterPack() || UnresolvedExpandedPack)) {
  4695. SeenPackExpansionIntoNonPack = true;
  4696. return true;
  4697. }
  4698. // We need exact types for function template arguments because they might be
  4699. // overloaded on template parameter type. As a special case, a member
  4700. // function template of a generic lambda is not overloadable.
  4701. if (auto *FTD = dyn_cast<FunctionTemplateDecl>(ResolvedTemplate)) {
  4702. auto *RD = dyn_cast<CXXRecordDecl>(FTD->getDeclContext());
  4703. if (!RD || !RD->isGenericLambda())
  4704. return true;
  4705. }
  4706. // Otherwise, we only need a correct type if the parameter has a deduced
  4707. // type.
  4708. //
  4709. // Note: for an expanded parameter pack, getType() returns the type prior
  4710. // to expansion. We could ask for the expanded type with getExpansionType(),
  4711. // but it doesn't matter because substitution and expansion don't affect
  4712. // whether a deduced type appears in the type.
  4713. auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Param);
  4714. return NTTP && NTTP->getType()->getContainedDeducedType();
  4715. }
  4716. };
  4717. }
  4718. void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
  4719. const TemplateArgumentLoc *TemplateArgs,
  4720. unsigned NumTemplateArgs) {
  4721. // <template-args> ::= I <template-arg>+ E
  4722. Out << 'I';
  4723. TemplateArgManglingInfo Info(TN);
  4724. for (unsigned i = 0; i != NumTemplateArgs; ++i)
  4725. mangleTemplateArg(TemplateArgs[i].getArgument(),
  4726. Info.needExactType(i, TemplateArgs[i].getArgument()));
  4727. Out << 'E';
  4728. }
  4729. void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
  4730. const TemplateArgumentList &AL) {
  4731. // <template-args> ::= I <template-arg>+ E
  4732. Out << 'I';
  4733. TemplateArgManglingInfo Info(TN);
  4734. for (unsigned i = 0, e = AL.size(); i != e; ++i)
  4735. mangleTemplateArg(AL[i], Info.needExactType(i, AL[i]));
  4736. Out << 'E';
  4737. }
  4738. void CXXNameMangler::mangleTemplateArgs(TemplateName TN,
  4739. ArrayRef<TemplateArgument> Args) {
  4740. // <template-args> ::= I <template-arg>+ E
  4741. Out << 'I';
  4742. TemplateArgManglingInfo Info(TN);
  4743. for (unsigned i = 0; i != Args.size(); ++i)
  4744. mangleTemplateArg(Args[i], Info.needExactType(i, Args[i]));
  4745. Out << 'E';
  4746. }
  4747. void CXXNameMangler::mangleTemplateArg(TemplateArgument A, bool NeedExactType) {
  4748. // <template-arg> ::= <type> # type or template
  4749. // ::= X <expression> E # expression
  4750. // ::= <expr-primary> # simple expressions
  4751. // ::= J <template-arg>* E # argument pack
  4752. if (!A.isInstantiationDependent() || A.isDependent())
  4753. A = Context.getASTContext().getCanonicalTemplateArgument(A);
  4754. switch (A.getKind()) {
  4755. case TemplateArgument::Null:
  4756. llvm_unreachable("Cannot mangle NULL template argument");
  4757. case TemplateArgument::Type:
  4758. mangleType(A.getAsType());
  4759. break;
  4760. case TemplateArgument::Template:
  4761. // This is mangled as <type>.
  4762. mangleType(A.getAsTemplate());
  4763. break;
  4764. case TemplateArgument::TemplateExpansion:
  4765. // <type> ::= Dp <type> # pack expansion (C++0x)
  4766. Out << "Dp";
  4767. mangleType(A.getAsTemplateOrTemplatePattern());
  4768. break;
  4769. case TemplateArgument::Expression:
  4770. mangleTemplateArgExpr(A.getAsExpr());
  4771. break;
  4772. case TemplateArgument::Integral:
  4773. mangleIntegerLiteral(A.getIntegralType(), A.getAsIntegral());
  4774. break;
  4775. case TemplateArgument::Declaration: {
  4776. // <expr-primary> ::= L <mangled-name> E # external name
  4777. ValueDecl *D = A.getAsDecl();
  4778. // Template parameter objects are modeled by reproducing a source form
  4779. // produced as if by aggregate initialization.
  4780. if (A.getParamTypeForDecl()->isRecordType()) {
  4781. auto *TPO = cast<TemplateParamObjectDecl>(D);
  4782. mangleValueInTemplateArg(TPO->getType().getUnqualifiedType(),
  4783. TPO->getValue(), /*TopLevel=*/true,
  4784. NeedExactType);
  4785. break;
  4786. }
  4787. ASTContext &Ctx = Context.getASTContext();
  4788. APValue Value;
  4789. if (D->isCXXInstanceMember())
  4790. // Simple pointer-to-member with no conversion.
  4791. Value = APValue(D, /*IsDerivedMember=*/false, /*Path=*/{});
  4792. else if (D->getType()->isArrayType() &&
  4793. Ctx.hasSimilarType(Ctx.getDecayedType(D->getType()),
  4794. A.getParamTypeForDecl()) &&
  4795. Ctx.getLangOpts().getClangABICompat() >
  4796. LangOptions::ClangABI::Ver11)
  4797. // Build a value corresponding to this implicit array-to-pointer decay.
  4798. Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
  4799. {APValue::LValuePathEntry::ArrayIndex(0)},
  4800. /*OnePastTheEnd=*/false);
  4801. else
  4802. // Regular pointer or reference to a declaration.
  4803. Value = APValue(APValue::LValueBase(D), CharUnits::Zero(),
  4804. ArrayRef<APValue::LValuePathEntry>(),
  4805. /*OnePastTheEnd=*/false);
  4806. mangleValueInTemplateArg(A.getParamTypeForDecl(), Value, /*TopLevel=*/true,
  4807. NeedExactType);
  4808. break;
  4809. }
  4810. case TemplateArgument::NullPtr: {
  4811. mangleNullPointer(A.getNullPtrType());
  4812. break;
  4813. }
  4814. case TemplateArgument::Pack: {
  4815. // <template-arg> ::= J <template-arg>* E
  4816. Out << 'J';
  4817. for (const auto &P : A.pack_elements())
  4818. mangleTemplateArg(P, NeedExactType);
  4819. Out << 'E';
  4820. }
  4821. }
  4822. }
  4823. void CXXNameMangler::mangleTemplateArgExpr(const Expr *E) {
  4824. ASTContext &Ctx = Context.getASTContext();
  4825. if (Ctx.getLangOpts().getClangABICompat() > LangOptions::ClangABI::Ver11) {
  4826. mangleExpression(E, UnknownArity, /*AsTemplateArg=*/true);
  4827. return;
  4828. }
  4829. // Prior to Clang 12, we didn't omit the X .. E around <expr-primary>
  4830. // correctly in cases where the template argument was
  4831. // constructed from an expression rather than an already-evaluated
  4832. // literal. In such a case, we would then e.g. emit 'XLi0EE' instead of
  4833. // 'Li0E'.
  4834. //
  4835. // We did special-case DeclRefExpr to attempt to DTRT for that one
  4836. // expression-kind, but while doing so, unfortunately handled ParmVarDecl
  4837. // (subtype of VarDecl) _incorrectly_, and emitted 'L_Z .. E' instead of
  4838. // the proper 'Xfp_E'.
  4839. E = E->IgnoreParenImpCasts();
  4840. if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  4841. const ValueDecl *D = DRE->getDecl();
  4842. if (isa<VarDecl>(D) || isa<FunctionDecl>(D)) {
  4843. Out << 'L';
  4844. mangle(D);
  4845. Out << 'E';
  4846. return;
  4847. }
  4848. }
  4849. Out << 'X';
  4850. mangleExpression(E);
  4851. Out << 'E';
  4852. }
  4853. /// Determine whether a given value is equivalent to zero-initialization for
  4854. /// the purpose of discarding a trailing portion of a 'tl' mangling.
  4855. ///
  4856. /// Note that this is not in general equivalent to determining whether the
  4857. /// value has an all-zeroes bit pattern.
  4858. static bool isZeroInitialized(QualType T, const APValue &V) {
  4859. // FIXME: mangleValueInTemplateArg has quadratic time complexity in
  4860. // pathological cases due to using this, but it's a little awkward
  4861. // to do this in linear time in general.
  4862. switch (V.getKind()) {
  4863. case APValue::None:
  4864. case APValue::Indeterminate:
  4865. case APValue::AddrLabelDiff:
  4866. return false;
  4867. case APValue::Struct: {
  4868. const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  4869. assert(RD && "unexpected type for record value");
  4870. unsigned I = 0;
  4871. for (const CXXBaseSpecifier &BS : RD->bases()) {
  4872. if (!isZeroInitialized(BS.getType(), V.getStructBase(I)))
  4873. return false;
  4874. ++I;
  4875. }
  4876. I = 0;
  4877. for (const FieldDecl *FD : RD->fields()) {
  4878. if (!FD->isUnnamedBitfield() &&
  4879. !isZeroInitialized(FD->getType(), V.getStructField(I)))
  4880. return false;
  4881. ++I;
  4882. }
  4883. return true;
  4884. }
  4885. case APValue::Union: {
  4886. const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  4887. assert(RD && "unexpected type for union value");
  4888. // Zero-initialization zeroes the first non-unnamed-bitfield field, if any.
  4889. for (const FieldDecl *FD : RD->fields()) {
  4890. if (!FD->isUnnamedBitfield())
  4891. return V.getUnionField() && declaresSameEntity(FD, V.getUnionField()) &&
  4892. isZeroInitialized(FD->getType(), V.getUnionValue());
  4893. }
  4894. // If there are no fields (other than unnamed bitfields), the value is
  4895. // necessarily zero-initialized.
  4896. return true;
  4897. }
  4898. case APValue::Array: {
  4899. QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
  4900. for (unsigned I = 0, N = V.getArrayInitializedElts(); I != N; ++I)
  4901. if (!isZeroInitialized(ElemT, V.getArrayInitializedElt(I)))
  4902. return false;
  4903. return !V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller());
  4904. }
  4905. case APValue::Vector: {
  4906. const VectorType *VT = T->castAs<VectorType>();
  4907. for (unsigned I = 0, N = V.getVectorLength(); I != N; ++I)
  4908. if (!isZeroInitialized(VT->getElementType(), V.getVectorElt(I)))
  4909. return false;
  4910. return true;
  4911. }
  4912. case APValue::Int:
  4913. return !V.getInt();
  4914. case APValue::Float:
  4915. return V.getFloat().isPosZero();
  4916. case APValue::FixedPoint:
  4917. return !V.getFixedPoint().getValue();
  4918. case APValue::ComplexFloat:
  4919. return V.getComplexFloatReal().isPosZero() &&
  4920. V.getComplexFloatImag().isPosZero();
  4921. case APValue::ComplexInt:
  4922. return !V.getComplexIntReal() && !V.getComplexIntImag();
  4923. case APValue::LValue:
  4924. return V.isNullPointer();
  4925. case APValue::MemberPointer:
  4926. return !V.getMemberPointerDecl();
  4927. }
  4928. llvm_unreachable("Unhandled APValue::ValueKind enum");
  4929. }
  4930. static QualType getLValueType(ASTContext &Ctx, const APValue &LV) {
  4931. QualType T = LV.getLValueBase().getType();
  4932. for (APValue::LValuePathEntry E : LV.getLValuePath()) {
  4933. if (const ArrayType *AT = Ctx.getAsArrayType(T))
  4934. T = AT->getElementType();
  4935. else if (const FieldDecl *FD =
  4936. dyn_cast<FieldDecl>(E.getAsBaseOrMember().getPointer()))
  4937. T = FD->getType();
  4938. else
  4939. T = Ctx.getRecordType(
  4940. cast<CXXRecordDecl>(E.getAsBaseOrMember().getPointer()));
  4941. }
  4942. return T;
  4943. }
  4944. static IdentifierInfo *getUnionInitName(SourceLocation UnionLoc,
  4945. DiagnosticsEngine &Diags,
  4946. const FieldDecl *FD) {
  4947. // According to:
  4948. // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#mangling.anonymous
  4949. // For the purposes of mangling, the name of an anonymous union is considered
  4950. // to be the name of the first named data member found by a pre-order,
  4951. // depth-first, declaration-order walk of the data members of the anonymous
  4952. // union.
  4953. if (FD->getIdentifier())
  4954. return FD->getIdentifier();
  4955. // The only cases where the identifer of a FieldDecl would be blank is if the
  4956. // field represents an anonymous record type or if it is an unnamed bitfield.
  4957. // There is no type to descend into in the case of a bitfield, so we can just
  4958. // return nullptr in that case.
  4959. if (FD->isBitField())
  4960. return nullptr;
  4961. const CXXRecordDecl *RD = FD->getType()->getAsCXXRecordDecl();
  4962. // Consider only the fields in declaration order, searched depth-first. We
  4963. // don't care about the active member of the union, as all we are doing is
  4964. // looking for a valid name. We also don't check bases, due to guidance from
  4965. // the Itanium ABI folks.
  4966. for (const FieldDecl *RDField : RD->fields()) {
  4967. if (IdentifierInfo *II = getUnionInitName(UnionLoc, Diags, RDField))
  4968. return II;
  4969. }
  4970. // According to the Itanium ABI: If there is no such data member (i.e., if all
  4971. // of the data members in the union are unnamed), then there is no way for a
  4972. // program to refer to the anonymous union, and there is therefore no need to
  4973. // mangle its name. However, we should diagnose this anyway.
  4974. unsigned DiagID = Diags.getCustomDiagID(
  4975. DiagnosticsEngine::Error, "cannot mangle this unnamed union NTTP yet");
  4976. Diags.Report(UnionLoc, DiagID);
  4977. return nullptr;
  4978. }
  4979. void CXXNameMangler::mangleValueInTemplateArg(QualType T, const APValue &V,
  4980. bool TopLevel,
  4981. bool NeedExactType) {
  4982. // Ignore all top-level cv-qualifiers, to match GCC.
  4983. Qualifiers Quals;
  4984. T = getASTContext().getUnqualifiedArrayType(T, Quals);
  4985. // A top-level expression that's not a primary expression is wrapped in X...E.
  4986. bool IsPrimaryExpr = true;
  4987. auto NotPrimaryExpr = [&] {
  4988. if (TopLevel && IsPrimaryExpr)
  4989. Out << 'X';
  4990. IsPrimaryExpr = false;
  4991. };
  4992. // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/63.
  4993. switch (V.getKind()) {
  4994. case APValue::None:
  4995. case APValue::Indeterminate:
  4996. Out << 'L';
  4997. mangleType(T);
  4998. Out << 'E';
  4999. break;
  5000. case APValue::AddrLabelDiff:
  5001. llvm_unreachable("unexpected value kind in template argument");
  5002. case APValue::Struct: {
  5003. const CXXRecordDecl *RD = T->getAsCXXRecordDecl();
  5004. assert(RD && "unexpected type for record value");
  5005. // Drop trailing zero-initialized elements.
  5006. llvm::SmallVector<const FieldDecl *, 16> Fields(RD->fields());
  5007. while (
  5008. !Fields.empty() &&
  5009. (Fields.back()->isUnnamedBitfield() ||
  5010. isZeroInitialized(Fields.back()->getType(),
  5011. V.getStructField(Fields.back()->getFieldIndex())))) {
  5012. Fields.pop_back();
  5013. }
  5014. llvm::ArrayRef<CXXBaseSpecifier> Bases(RD->bases_begin(), RD->bases_end());
  5015. if (Fields.empty()) {
  5016. while (!Bases.empty() &&
  5017. isZeroInitialized(Bases.back().getType(),
  5018. V.getStructBase(Bases.size() - 1)))
  5019. Bases = Bases.drop_back();
  5020. }
  5021. // <expression> ::= tl <type> <braced-expression>* E
  5022. NotPrimaryExpr();
  5023. Out << "tl";
  5024. mangleType(T);
  5025. for (unsigned I = 0, N = Bases.size(); I != N; ++I)
  5026. mangleValueInTemplateArg(Bases[I].getType(), V.getStructBase(I), false);
  5027. for (unsigned I = 0, N = Fields.size(); I != N; ++I) {
  5028. if (Fields[I]->isUnnamedBitfield())
  5029. continue;
  5030. mangleValueInTemplateArg(Fields[I]->getType(),
  5031. V.getStructField(Fields[I]->getFieldIndex()),
  5032. false);
  5033. }
  5034. Out << 'E';
  5035. break;
  5036. }
  5037. case APValue::Union: {
  5038. assert(T->getAsCXXRecordDecl() && "unexpected type for union value");
  5039. const FieldDecl *FD = V.getUnionField();
  5040. if (!FD) {
  5041. Out << 'L';
  5042. mangleType(T);
  5043. Out << 'E';
  5044. break;
  5045. }
  5046. // <braced-expression> ::= di <field source-name> <braced-expression>
  5047. NotPrimaryExpr();
  5048. Out << "tl";
  5049. mangleType(T);
  5050. if (!isZeroInitialized(T, V)) {
  5051. Out << "di";
  5052. IdentifierInfo *II = (getUnionInitName(
  5053. T->getAsCXXRecordDecl()->getLocation(), Context.getDiags(), FD));
  5054. if (II)
  5055. mangleSourceName(II);
  5056. mangleValueInTemplateArg(FD->getType(), V.getUnionValue(), false);
  5057. }
  5058. Out << 'E';
  5059. break;
  5060. }
  5061. case APValue::Array: {
  5062. QualType ElemT(T->getArrayElementTypeNoTypeQual(), 0);
  5063. NotPrimaryExpr();
  5064. Out << "tl";
  5065. mangleType(T);
  5066. // Drop trailing zero-initialized elements.
  5067. unsigned N = V.getArraySize();
  5068. if (!V.hasArrayFiller() || isZeroInitialized(ElemT, V.getArrayFiller())) {
  5069. N = V.getArrayInitializedElts();
  5070. while (N && isZeroInitialized(ElemT, V.getArrayInitializedElt(N - 1)))
  5071. --N;
  5072. }
  5073. for (unsigned I = 0; I != N; ++I) {
  5074. const APValue &Elem = I < V.getArrayInitializedElts()
  5075. ? V.getArrayInitializedElt(I)
  5076. : V.getArrayFiller();
  5077. mangleValueInTemplateArg(ElemT, Elem, false);
  5078. }
  5079. Out << 'E';
  5080. break;
  5081. }
  5082. case APValue::Vector: {
  5083. const VectorType *VT = T->castAs<VectorType>();
  5084. NotPrimaryExpr();
  5085. Out << "tl";
  5086. mangleType(T);
  5087. unsigned N = V.getVectorLength();
  5088. while (N && isZeroInitialized(VT->getElementType(), V.getVectorElt(N - 1)))
  5089. --N;
  5090. for (unsigned I = 0; I != N; ++I)
  5091. mangleValueInTemplateArg(VT->getElementType(), V.getVectorElt(I), false);
  5092. Out << 'E';
  5093. break;
  5094. }
  5095. case APValue::Int:
  5096. mangleIntegerLiteral(T, V.getInt());
  5097. break;
  5098. case APValue::Float:
  5099. mangleFloatLiteral(T, V.getFloat());
  5100. break;
  5101. case APValue::FixedPoint:
  5102. mangleFixedPointLiteral();
  5103. break;
  5104. case APValue::ComplexFloat: {
  5105. const ComplexType *CT = T->castAs<ComplexType>();
  5106. NotPrimaryExpr();
  5107. Out << "tl";
  5108. mangleType(T);
  5109. if (!V.getComplexFloatReal().isPosZero() ||
  5110. !V.getComplexFloatImag().isPosZero())
  5111. mangleFloatLiteral(CT->getElementType(), V.getComplexFloatReal());
  5112. if (!V.getComplexFloatImag().isPosZero())
  5113. mangleFloatLiteral(CT->getElementType(), V.getComplexFloatImag());
  5114. Out << 'E';
  5115. break;
  5116. }
  5117. case APValue::ComplexInt: {
  5118. const ComplexType *CT = T->castAs<ComplexType>();
  5119. NotPrimaryExpr();
  5120. Out << "tl";
  5121. mangleType(T);
  5122. if (V.getComplexIntReal().getBoolValue() ||
  5123. V.getComplexIntImag().getBoolValue())
  5124. mangleIntegerLiteral(CT->getElementType(), V.getComplexIntReal());
  5125. if (V.getComplexIntImag().getBoolValue())
  5126. mangleIntegerLiteral(CT->getElementType(), V.getComplexIntImag());
  5127. Out << 'E';
  5128. break;
  5129. }
  5130. case APValue::LValue: {
  5131. // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
  5132. assert((T->isPointerType() || T->isReferenceType()) &&
  5133. "unexpected type for LValue template arg");
  5134. if (V.isNullPointer()) {
  5135. mangleNullPointer(T);
  5136. break;
  5137. }
  5138. APValue::LValueBase B = V.getLValueBase();
  5139. if (!B) {
  5140. // Non-standard mangling for integer cast to a pointer; this can only
  5141. // occur as an extension.
  5142. CharUnits Offset = V.getLValueOffset();
  5143. if (Offset.isZero()) {
  5144. // This is reinterpret_cast<T*>(0), not a null pointer. Mangle this as
  5145. // a cast, because L <type> 0 E means something else.
  5146. NotPrimaryExpr();
  5147. Out << "rc";
  5148. mangleType(T);
  5149. Out << "Li0E";
  5150. if (TopLevel)
  5151. Out << 'E';
  5152. } else {
  5153. Out << "L";
  5154. mangleType(T);
  5155. Out << Offset.getQuantity() << 'E';
  5156. }
  5157. break;
  5158. }
  5159. ASTContext &Ctx = Context.getASTContext();
  5160. enum { Base, Offset, Path } Kind;
  5161. if (!V.hasLValuePath()) {
  5162. // Mangle as (T*)((char*)&base + N).
  5163. if (T->isReferenceType()) {
  5164. NotPrimaryExpr();
  5165. Out << "decvP";
  5166. mangleType(T->getPointeeType());
  5167. } else {
  5168. NotPrimaryExpr();
  5169. Out << "cv";
  5170. mangleType(T);
  5171. }
  5172. Out << "plcvPcad";
  5173. Kind = Offset;
  5174. } else {
  5175. if (!V.getLValuePath().empty() || V.isLValueOnePastTheEnd()) {
  5176. NotPrimaryExpr();
  5177. // A final conversion to the template parameter's type is usually
  5178. // folded into the 'so' mangling, but we can't do that for 'void*'
  5179. // parameters without introducing collisions.
  5180. if (NeedExactType && T->isVoidPointerType()) {
  5181. Out << "cv";
  5182. mangleType(T);
  5183. }
  5184. if (T->isPointerType())
  5185. Out << "ad";
  5186. Out << "so";
  5187. mangleType(T->isVoidPointerType()
  5188. ? getLValueType(Ctx, V).getUnqualifiedType()
  5189. : T->getPointeeType());
  5190. Kind = Path;
  5191. } else {
  5192. if (NeedExactType &&
  5193. !Ctx.hasSameType(T->getPointeeType(), getLValueType(Ctx, V)) &&
  5194. Ctx.getLangOpts().getClangABICompat() >
  5195. LangOptions::ClangABI::Ver11) {
  5196. NotPrimaryExpr();
  5197. Out << "cv";
  5198. mangleType(T);
  5199. }
  5200. if (T->isPointerType()) {
  5201. NotPrimaryExpr();
  5202. Out << "ad";
  5203. }
  5204. Kind = Base;
  5205. }
  5206. }
  5207. QualType TypeSoFar = B.getType();
  5208. if (auto *VD = B.dyn_cast<const ValueDecl*>()) {
  5209. Out << 'L';
  5210. mangle(VD);
  5211. Out << 'E';
  5212. } else if (auto *E = B.dyn_cast<const Expr*>()) {
  5213. NotPrimaryExpr();
  5214. mangleExpression(E);
  5215. } else if (auto TI = B.dyn_cast<TypeInfoLValue>()) {
  5216. NotPrimaryExpr();
  5217. Out << "ti";
  5218. mangleType(QualType(TI.getType(), 0));
  5219. } else {
  5220. // We should never see dynamic allocations here.
  5221. llvm_unreachable("unexpected lvalue base kind in template argument");
  5222. }
  5223. switch (Kind) {
  5224. case Base:
  5225. break;
  5226. case Offset:
  5227. Out << 'L';
  5228. mangleType(Ctx.getPointerDiffType());
  5229. mangleNumber(V.getLValueOffset().getQuantity());
  5230. Out << 'E';
  5231. break;
  5232. case Path:
  5233. // <expression> ::= so <referent type> <expr> [<offset number>]
  5234. // <union-selector>* [p] E
  5235. if (!V.getLValueOffset().isZero())
  5236. mangleNumber(V.getLValueOffset().getQuantity());
  5237. // We model a past-the-end array pointer as array indexing with index N,
  5238. // not with the "past the end" flag. Compensate for that.
  5239. bool OnePastTheEnd = V.isLValueOnePastTheEnd();
  5240. for (APValue::LValuePathEntry E : V.getLValuePath()) {
  5241. if (auto *AT = TypeSoFar->getAsArrayTypeUnsafe()) {
  5242. if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
  5243. OnePastTheEnd |= CAT->getSize() == E.getAsArrayIndex();
  5244. TypeSoFar = AT->getElementType();
  5245. } else {
  5246. const Decl *D = E.getAsBaseOrMember().getPointer();
  5247. if (auto *FD = dyn_cast<FieldDecl>(D)) {
  5248. // <union-selector> ::= _ <number>
  5249. if (FD->getParent()->isUnion()) {
  5250. Out << '_';
  5251. if (FD->getFieldIndex())
  5252. Out << (FD->getFieldIndex() - 1);
  5253. }
  5254. TypeSoFar = FD->getType();
  5255. } else {
  5256. TypeSoFar = Ctx.getRecordType(cast<CXXRecordDecl>(D));
  5257. }
  5258. }
  5259. }
  5260. if (OnePastTheEnd)
  5261. Out << 'p';
  5262. Out << 'E';
  5263. break;
  5264. }
  5265. break;
  5266. }
  5267. case APValue::MemberPointer:
  5268. // Proposed in https://github.com/itanium-cxx-abi/cxx-abi/issues/47.
  5269. if (!V.getMemberPointerDecl()) {
  5270. mangleNullPointer(T);
  5271. break;
  5272. }
  5273. ASTContext &Ctx = Context.getASTContext();
  5274. NotPrimaryExpr();
  5275. if (!V.getMemberPointerPath().empty()) {
  5276. Out << "mc";
  5277. mangleType(T);
  5278. } else if (NeedExactType &&
  5279. !Ctx.hasSameType(
  5280. T->castAs<MemberPointerType>()->getPointeeType(),
  5281. V.getMemberPointerDecl()->getType()) &&
  5282. Ctx.getLangOpts().getClangABICompat() >
  5283. LangOptions::ClangABI::Ver11) {
  5284. Out << "cv";
  5285. mangleType(T);
  5286. }
  5287. Out << "adL";
  5288. mangle(V.getMemberPointerDecl());
  5289. Out << 'E';
  5290. if (!V.getMemberPointerPath().empty()) {
  5291. CharUnits Offset =
  5292. Context.getASTContext().getMemberPointerPathAdjustment(V);
  5293. if (!Offset.isZero())
  5294. mangleNumber(Offset.getQuantity());
  5295. Out << 'E';
  5296. }
  5297. break;
  5298. }
  5299. if (TopLevel && !IsPrimaryExpr)
  5300. Out << 'E';
  5301. }
  5302. void CXXNameMangler::mangleTemplateParameter(unsigned Depth, unsigned Index) {
  5303. // <template-param> ::= T_ # first template parameter
  5304. // ::= T <parameter-2 non-negative number> _
  5305. // ::= TL <L-1 non-negative number> __
  5306. // ::= TL <L-1 non-negative number> _
  5307. // <parameter-2 non-negative number> _
  5308. //
  5309. // The latter two manglings are from a proposal here:
  5310. // https://github.com/itanium-cxx-abi/cxx-abi/issues/31#issuecomment-528122117
  5311. Out << 'T';
  5312. if (Depth != 0)
  5313. Out << 'L' << (Depth - 1) << '_';
  5314. if (Index != 0)
  5315. Out << (Index - 1);
  5316. Out << '_';
  5317. }
  5318. void CXXNameMangler::mangleSeqID(unsigned SeqID) {
  5319. if (SeqID == 0) {
  5320. // Nothing.
  5321. } else if (SeqID == 1) {
  5322. Out << '0';
  5323. } else {
  5324. SeqID--;
  5325. // <seq-id> is encoded in base-36, using digits and upper case letters.
  5326. char Buffer[7]; // log(2**32) / log(36) ~= 7
  5327. MutableArrayRef<char> BufferRef(Buffer);
  5328. MutableArrayRef<char>::reverse_iterator I = BufferRef.rbegin();
  5329. for (; SeqID != 0; SeqID /= 36) {
  5330. unsigned C = SeqID % 36;
  5331. *I++ = (C < 10 ? '0' + C : 'A' + C - 10);
  5332. }
  5333. Out.write(I.base(), I - BufferRef.rbegin());
  5334. }
  5335. Out << '_';
  5336. }
  5337. void CXXNameMangler::mangleExistingSubstitution(TemplateName tname) {
  5338. bool result = mangleSubstitution(tname);
  5339. assert(result && "no existing substitution for template name");
  5340. (void) result;
  5341. }
  5342. // <substitution> ::= S <seq-id> _
  5343. // ::= S_
  5344. bool CXXNameMangler::mangleSubstitution(const NamedDecl *ND) {
  5345. // Try one of the standard substitutions first.
  5346. if (mangleStandardSubstitution(ND))
  5347. return true;
  5348. ND = cast<NamedDecl>(ND->getCanonicalDecl());
  5349. return mangleSubstitution(reinterpret_cast<uintptr_t>(ND));
  5350. }
  5351. bool CXXNameMangler::mangleSubstitution(NestedNameSpecifier *NNS) {
  5352. assert(NNS->getKind() == NestedNameSpecifier::Identifier &&
  5353. "mangleSubstitution(NestedNameSpecifier *) is only used for "
  5354. "identifier nested name specifiers.");
  5355. NNS = Context.getASTContext().getCanonicalNestedNameSpecifier(NNS);
  5356. return mangleSubstitution(reinterpret_cast<uintptr_t>(NNS));
  5357. }
  5358. /// Determine whether the given type has any qualifiers that are relevant for
  5359. /// substitutions.
  5360. static bool hasMangledSubstitutionQualifiers(QualType T) {
  5361. Qualifiers Qs = T.getQualifiers();
  5362. return Qs.getCVRQualifiers() || Qs.hasAddressSpace() || Qs.hasUnaligned();
  5363. }
  5364. bool CXXNameMangler::mangleSubstitution(QualType T) {
  5365. if (!hasMangledSubstitutionQualifiers(T)) {
  5366. if (const RecordType *RT = T->getAs<RecordType>())
  5367. return mangleSubstitution(RT->getDecl());
  5368. }
  5369. uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
  5370. return mangleSubstitution(TypePtr);
  5371. }
  5372. bool CXXNameMangler::mangleSubstitution(TemplateName Template) {
  5373. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  5374. return mangleSubstitution(TD);
  5375. Template = Context.getASTContext().getCanonicalTemplateName(Template);
  5376. return mangleSubstitution(
  5377. reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
  5378. }
  5379. bool CXXNameMangler::mangleSubstitution(uintptr_t Ptr) {
  5380. llvm::DenseMap<uintptr_t, unsigned>::iterator I = Substitutions.find(Ptr);
  5381. if (I == Substitutions.end())
  5382. return false;
  5383. unsigned SeqID = I->second;
  5384. Out << 'S';
  5385. mangleSeqID(SeqID);
  5386. return true;
  5387. }
  5388. /// Returns whether S is a template specialization of std::Name with a single
  5389. /// argument of type A.
  5390. bool CXXNameMangler::isSpecializedAs(QualType S, llvm::StringRef Name,
  5391. QualType A) {
  5392. if (S.isNull())
  5393. return false;
  5394. const RecordType *RT = S->getAs<RecordType>();
  5395. if (!RT)
  5396. return false;
  5397. const ClassTemplateSpecializationDecl *SD =
  5398. dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
  5399. if (!SD || !SD->getIdentifier()->isStr(Name))
  5400. return false;
  5401. if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
  5402. return false;
  5403. const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
  5404. if (TemplateArgs.size() != 1)
  5405. return false;
  5406. if (TemplateArgs[0].getAsType() != A)
  5407. return false;
  5408. if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
  5409. return false;
  5410. return true;
  5411. }
  5412. /// Returns whether SD is a template specialization std::Name<char,
  5413. /// std::char_traits<char> [, std::allocator<char>]>
  5414. /// HasAllocator controls whether the 3rd template argument is needed.
  5415. bool CXXNameMangler::isStdCharSpecialization(
  5416. const ClassTemplateSpecializationDecl *SD, llvm::StringRef Name,
  5417. bool HasAllocator) {
  5418. if (!SD->getIdentifier()->isStr(Name))
  5419. return false;
  5420. const TemplateArgumentList &TemplateArgs = SD->getTemplateArgs();
  5421. if (TemplateArgs.size() != (HasAllocator ? 3 : 2))
  5422. return false;
  5423. QualType A = TemplateArgs[0].getAsType();
  5424. if (A.isNull())
  5425. return false;
  5426. // Plain 'char' is named Char_S or Char_U depending on the target ABI.
  5427. if (!A->isSpecificBuiltinType(BuiltinType::Char_S) &&
  5428. !A->isSpecificBuiltinType(BuiltinType::Char_U))
  5429. return false;
  5430. if (!isSpecializedAs(TemplateArgs[1].getAsType(), "char_traits", A))
  5431. return false;
  5432. if (HasAllocator &&
  5433. !isSpecializedAs(TemplateArgs[2].getAsType(), "allocator", A))
  5434. return false;
  5435. if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
  5436. return false;
  5437. return true;
  5438. }
  5439. bool CXXNameMangler::mangleStandardSubstitution(const NamedDecl *ND) {
  5440. // <substitution> ::= St # ::std::
  5441. if (const NamespaceDecl *NS = dyn_cast<NamespaceDecl>(ND)) {
  5442. if (isStd(NS)) {
  5443. Out << "St";
  5444. return true;
  5445. }
  5446. return false;
  5447. }
  5448. if (const ClassTemplateDecl *TD = dyn_cast<ClassTemplateDecl>(ND)) {
  5449. if (!isStdNamespace(Context.getEffectiveDeclContext(TD)))
  5450. return false;
  5451. if (TD->getOwningModuleForLinkage())
  5452. return false;
  5453. // <substitution> ::= Sa # ::std::allocator
  5454. if (TD->getIdentifier()->isStr("allocator")) {
  5455. Out << "Sa";
  5456. return true;
  5457. }
  5458. // <<substitution> ::= Sb # ::std::basic_string
  5459. if (TD->getIdentifier()->isStr("basic_string")) {
  5460. Out << "Sb";
  5461. return true;
  5462. }
  5463. return false;
  5464. }
  5465. if (const ClassTemplateSpecializationDecl *SD =
  5466. dyn_cast<ClassTemplateSpecializationDecl>(ND)) {
  5467. if (!isStdNamespace(Context.getEffectiveDeclContext(SD)))
  5468. return false;
  5469. if (SD->getSpecializedTemplate()->getOwningModuleForLinkage())
  5470. return false;
  5471. // <substitution> ::= Ss # ::std::basic_string<char,
  5472. // ::std::char_traits<char>,
  5473. // ::std::allocator<char> >
  5474. if (isStdCharSpecialization(SD, "basic_string", /*HasAllocator=*/true)) {
  5475. Out << "Ss";
  5476. return true;
  5477. }
  5478. // <substitution> ::= Si # ::std::basic_istream<char,
  5479. // ::std::char_traits<char> >
  5480. if (isStdCharSpecialization(SD, "basic_istream", /*HasAllocator=*/false)) {
  5481. Out << "Si";
  5482. return true;
  5483. }
  5484. // <substitution> ::= So # ::std::basic_ostream<char,
  5485. // ::std::char_traits<char> >
  5486. if (isStdCharSpecialization(SD, "basic_ostream", /*HasAllocator=*/false)) {
  5487. Out << "So";
  5488. return true;
  5489. }
  5490. // <substitution> ::= Sd # ::std::basic_iostream<char,
  5491. // ::std::char_traits<char> >
  5492. if (isStdCharSpecialization(SD, "basic_iostream", /*HasAllocator=*/false)) {
  5493. Out << "Sd";
  5494. return true;
  5495. }
  5496. return false;
  5497. }
  5498. return false;
  5499. }
  5500. void CXXNameMangler::addSubstitution(QualType T) {
  5501. if (!hasMangledSubstitutionQualifiers(T)) {
  5502. if (const RecordType *RT = T->getAs<RecordType>()) {
  5503. addSubstitution(RT->getDecl());
  5504. return;
  5505. }
  5506. }
  5507. uintptr_t TypePtr = reinterpret_cast<uintptr_t>(T.getAsOpaquePtr());
  5508. addSubstitution(TypePtr);
  5509. }
  5510. void CXXNameMangler::addSubstitution(TemplateName Template) {
  5511. if (TemplateDecl *TD = Template.getAsTemplateDecl())
  5512. return addSubstitution(TD);
  5513. Template = Context.getASTContext().getCanonicalTemplateName(Template);
  5514. addSubstitution(reinterpret_cast<uintptr_t>(Template.getAsVoidPointer()));
  5515. }
  5516. void CXXNameMangler::addSubstitution(uintptr_t Ptr) {
  5517. assert(!Substitutions.count(Ptr) && "Substitution already exists!");
  5518. Substitutions[Ptr] = SeqID++;
  5519. }
  5520. void CXXNameMangler::extendSubstitutions(CXXNameMangler* Other) {
  5521. assert(Other->SeqID >= SeqID && "Must be superset of substitutions!");
  5522. if (Other->SeqID > SeqID) {
  5523. Substitutions.swap(Other->Substitutions);
  5524. SeqID = Other->SeqID;
  5525. }
  5526. }
  5527. CXXNameMangler::AbiTagList
  5528. CXXNameMangler::makeFunctionReturnTypeTags(const FunctionDecl *FD) {
  5529. // When derived abi tags are disabled there is no need to make any list.
  5530. if (DisableDerivedAbiTags)
  5531. return AbiTagList();
  5532. llvm::raw_null_ostream NullOutStream;
  5533. CXXNameMangler TrackReturnTypeTags(*this, NullOutStream);
  5534. TrackReturnTypeTags.disableDerivedAbiTags();
  5535. const FunctionProtoType *Proto =
  5536. cast<FunctionProtoType>(FD->getType()->getAs<FunctionType>());
  5537. FunctionTypeDepthState saved = TrackReturnTypeTags.FunctionTypeDepth.push();
  5538. TrackReturnTypeTags.FunctionTypeDepth.enterResultType();
  5539. TrackReturnTypeTags.mangleType(Proto->getReturnType());
  5540. TrackReturnTypeTags.FunctionTypeDepth.leaveResultType();
  5541. TrackReturnTypeTags.FunctionTypeDepth.pop(saved);
  5542. return TrackReturnTypeTags.AbiTagsRoot.getSortedUniqueUsedAbiTags();
  5543. }
  5544. CXXNameMangler::AbiTagList
  5545. CXXNameMangler::makeVariableTypeTags(const VarDecl *VD) {
  5546. // When derived abi tags are disabled there is no need to make any list.
  5547. if (DisableDerivedAbiTags)
  5548. return AbiTagList();
  5549. llvm::raw_null_ostream NullOutStream;
  5550. CXXNameMangler TrackVariableType(*this, NullOutStream);
  5551. TrackVariableType.disableDerivedAbiTags();
  5552. TrackVariableType.mangleType(VD->getType());
  5553. return TrackVariableType.AbiTagsRoot.getSortedUniqueUsedAbiTags();
  5554. }
  5555. bool CXXNameMangler::shouldHaveAbiTags(ItaniumMangleContextImpl &C,
  5556. const VarDecl *VD) {
  5557. llvm::raw_null_ostream NullOutStream;
  5558. CXXNameMangler TrackAbiTags(C, NullOutStream, nullptr, true);
  5559. TrackAbiTags.mangle(VD);
  5560. return TrackAbiTags.AbiTagsRoot.getUsedAbiTags().size();
  5561. }
  5562. //
  5563. /// Mangles the name of the declaration D and emits that name to the given
  5564. /// output stream.
  5565. ///
  5566. /// If the declaration D requires a mangled name, this routine will emit that
  5567. /// mangled name to \p os and return true. Otherwise, \p os will be unchanged
  5568. /// and this routine will return false. In this case, the caller should just
  5569. /// emit the identifier of the declaration (\c D->getIdentifier()) as its
  5570. /// name.
  5571. void ItaniumMangleContextImpl::mangleCXXName(GlobalDecl GD,
  5572. raw_ostream &Out) {
  5573. const NamedDecl *D = cast<NamedDecl>(GD.getDecl());
  5574. assert((isa<FunctionDecl, VarDecl, TemplateParamObjectDecl>(D)) &&
  5575. "Invalid mangleName() call, argument is not a variable or function!");
  5576. PrettyStackTraceDecl CrashInfo(D, SourceLocation(),
  5577. getASTContext().getSourceManager(),
  5578. "Mangling declaration");
  5579. if (auto *CD = dyn_cast<CXXConstructorDecl>(D)) {
  5580. auto Type = GD.getCtorType();
  5581. CXXNameMangler Mangler(*this, Out, CD, Type);
  5582. return Mangler.mangle(GlobalDecl(CD, Type));
  5583. }
  5584. if (auto *DD = dyn_cast<CXXDestructorDecl>(D)) {
  5585. auto Type = GD.getDtorType();
  5586. CXXNameMangler Mangler(*this, Out, DD, Type);
  5587. return Mangler.mangle(GlobalDecl(DD, Type));
  5588. }
  5589. CXXNameMangler Mangler(*this, Out, D);
  5590. Mangler.mangle(GD);
  5591. }
  5592. void ItaniumMangleContextImpl::mangleCXXCtorComdat(const CXXConstructorDecl *D,
  5593. raw_ostream &Out) {
  5594. CXXNameMangler Mangler(*this, Out, D, Ctor_Comdat);
  5595. Mangler.mangle(GlobalDecl(D, Ctor_Comdat));
  5596. }
  5597. void ItaniumMangleContextImpl::mangleCXXDtorComdat(const CXXDestructorDecl *D,
  5598. raw_ostream &Out) {
  5599. CXXNameMangler Mangler(*this, Out, D, Dtor_Comdat);
  5600. Mangler.mangle(GlobalDecl(D, Dtor_Comdat));
  5601. }
  5602. void ItaniumMangleContextImpl::mangleThunk(const CXXMethodDecl *MD,
  5603. const ThunkInfo &Thunk,
  5604. raw_ostream &Out) {
  5605. // <special-name> ::= T <call-offset> <base encoding>
  5606. // # base is the nominal target function of thunk
  5607. // <special-name> ::= Tc <call-offset> <call-offset> <base encoding>
  5608. // # base is the nominal target function of thunk
  5609. // # first call-offset is 'this' adjustment
  5610. // # second call-offset is result adjustment
  5611. assert(!isa<CXXDestructorDecl>(MD) &&
  5612. "Use mangleCXXDtor for destructor decls!");
  5613. CXXNameMangler Mangler(*this, Out);
  5614. Mangler.getStream() << "_ZT";
  5615. if (!Thunk.Return.isEmpty())
  5616. Mangler.getStream() << 'c';
  5617. // Mangle the 'this' pointer adjustment.
  5618. Mangler.mangleCallOffset(Thunk.This.NonVirtual,
  5619. Thunk.This.Virtual.Itanium.VCallOffsetOffset);
  5620. // Mangle the return pointer adjustment if there is one.
  5621. if (!Thunk.Return.isEmpty())
  5622. Mangler.mangleCallOffset(Thunk.Return.NonVirtual,
  5623. Thunk.Return.Virtual.Itanium.VBaseOffsetOffset);
  5624. Mangler.mangleFunctionEncoding(MD);
  5625. }
  5626. void ItaniumMangleContextImpl::mangleCXXDtorThunk(
  5627. const CXXDestructorDecl *DD, CXXDtorType Type,
  5628. const ThisAdjustment &ThisAdjustment, raw_ostream &Out) {
  5629. // <special-name> ::= T <call-offset> <base encoding>
  5630. // # base is the nominal target function of thunk
  5631. CXXNameMangler Mangler(*this, Out, DD, Type);
  5632. Mangler.getStream() << "_ZT";
  5633. // Mangle the 'this' pointer adjustment.
  5634. Mangler.mangleCallOffset(ThisAdjustment.NonVirtual,
  5635. ThisAdjustment.Virtual.Itanium.VCallOffsetOffset);
  5636. Mangler.mangleFunctionEncoding(GlobalDecl(DD, Type));
  5637. }
  5638. /// Returns the mangled name for a guard variable for the passed in VarDecl.
  5639. void ItaniumMangleContextImpl::mangleStaticGuardVariable(const VarDecl *D,
  5640. raw_ostream &Out) {
  5641. // <special-name> ::= GV <object name> # Guard variable for one-time
  5642. // # initialization
  5643. CXXNameMangler Mangler(*this, Out);
  5644. // GCC 5.3.0 doesn't emit derived ABI tags for local names but that seems to
  5645. // be a bug that is fixed in trunk.
  5646. Mangler.getStream() << "_ZGV";
  5647. Mangler.mangleName(D);
  5648. }
  5649. void ItaniumMangleContextImpl::mangleDynamicInitializer(const VarDecl *MD,
  5650. raw_ostream &Out) {
  5651. // These symbols are internal in the Itanium ABI, so the names don't matter.
  5652. // Clang has traditionally used this symbol and allowed LLVM to adjust it to
  5653. // avoid duplicate symbols.
  5654. Out << "__cxx_global_var_init";
  5655. }
  5656. void ItaniumMangleContextImpl::mangleDynamicAtExitDestructor(const VarDecl *D,
  5657. raw_ostream &Out) {
  5658. // Prefix the mangling of D with __dtor_.
  5659. CXXNameMangler Mangler(*this, Out);
  5660. Mangler.getStream() << "__dtor_";
  5661. if (shouldMangleDeclName(D))
  5662. Mangler.mangle(D);
  5663. else
  5664. Mangler.getStream() << D->getName();
  5665. }
  5666. void ItaniumMangleContextImpl::mangleDynamicStermFinalizer(const VarDecl *D,
  5667. raw_ostream &Out) {
  5668. // Clang generates these internal-linkage functions as part of its
  5669. // implementation of the XL ABI.
  5670. CXXNameMangler Mangler(*this, Out);
  5671. Mangler.getStream() << "__finalize_";
  5672. if (shouldMangleDeclName(D))
  5673. Mangler.mangle(D);
  5674. else
  5675. Mangler.getStream() << D->getName();
  5676. }
  5677. void ItaniumMangleContextImpl::mangleSEHFilterExpression(
  5678. GlobalDecl EnclosingDecl, raw_ostream &Out) {
  5679. CXXNameMangler Mangler(*this, Out);
  5680. Mangler.getStream() << "__filt_";
  5681. auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());
  5682. if (shouldMangleDeclName(EnclosingFD))
  5683. Mangler.mangle(EnclosingDecl);
  5684. else
  5685. Mangler.getStream() << EnclosingFD->getName();
  5686. }
  5687. void ItaniumMangleContextImpl::mangleSEHFinallyBlock(
  5688. GlobalDecl EnclosingDecl, raw_ostream &Out) {
  5689. CXXNameMangler Mangler(*this, Out);
  5690. Mangler.getStream() << "__fin_";
  5691. auto *EnclosingFD = cast<FunctionDecl>(EnclosingDecl.getDecl());
  5692. if (shouldMangleDeclName(EnclosingFD))
  5693. Mangler.mangle(EnclosingDecl);
  5694. else
  5695. Mangler.getStream() << EnclosingFD->getName();
  5696. }
  5697. void ItaniumMangleContextImpl::mangleItaniumThreadLocalInit(const VarDecl *D,
  5698. raw_ostream &Out) {
  5699. // <special-name> ::= TH <object name>
  5700. CXXNameMangler Mangler(*this, Out);
  5701. Mangler.getStream() << "_ZTH";
  5702. Mangler.mangleName(D);
  5703. }
  5704. void
  5705. ItaniumMangleContextImpl::mangleItaniumThreadLocalWrapper(const VarDecl *D,
  5706. raw_ostream &Out) {
  5707. // <special-name> ::= TW <object name>
  5708. CXXNameMangler Mangler(*this, Out);
  5709. Mangler.getStream() << "_ZTW";
  5710. Mangler.mangleName(D);
  5711. }
  5712. void ItaniumMangleContextImpl::mangleReferenceTemporary(const VarDecl *D,
  5713. unsigned ManglingNumber,
  5714. raw_ostream &Out) {
  5715. // We match the GCC mangling here.
  5716. // <special-name> ::= GR <object name>
  5717. CXXNameMangler Mangler(*this, Out);
  5718. Mangler.getStream() << "_ZGR";
  5719. Mangler.mangleName(D);
  5720. assert(ManglingNumber > 0 && "Reference temporary mangling number is zero!");
  5721. Mangler.mangleSeqID(ManglingNumber - 1);
  5722. }
  5723. void ItaniumMangleContextImpl::mangleCXXVTable(const CXXRecordDecl *RD,
  5724. raw_ostream &Out) {
  5725. // <special-name> ::= TV <type> # virtual table
  5726. CXXNameMangler Mangler(*this, Out);
  5727. Mangler.getStream() << "_ZTV";
  5728. Mangler.mangleNameOrStandardSubstitution(RD);
  5729. }
  5730. void ItaniumMangleContextImpl::mangleCXXVTT(const CXXRecordDecl *RD,
  5731. raw_ostream &Out) {
  5732. // <special-name> ::= TT <type> # VTT structure
  5733. CXXNameMangler Mangler(*this, Out);
  5734. Mangler.getStream() << "_ZTT";
  5735. Mangler.mangleNameOrStandardSubstitution(RD);
  5736. }
  5737. void ItaniumMangleContextImpl::mangleCXXCtorVTable(const CXXRecordDecl *RD,
  5738. int64_t Offset,
  5739. const CXXRecordDecl *Type,
  5740. raw_ostream &Out) {
  5741. // <special-name> ::= TC <type> <offset number> _ <base type>
  5742. CXXNameMangler Mangler(*this, Out);
  5743. Mangler.getStream() << "_ZTC";
  5744. Mangler.mangleNameOrStandardSubstitution(RD);
  5745. Mangler.getStream() << Offset;
  5746. Mangler.getStream() << '_';
  5747. Mangler.mangleNameOrStandardSubstitution(Type);
  5748. }
  5749. void ItaniumMangleContextImpl::mangleCXXRTTI(QualType Ty, raw_ostream &Out) {
  5750. // <special-name> ::= TI <type> # typeinfo structure
  5751. assert(!Ty.hasQualifiers() && "RTTI info cannot have top-level qualifiers");
  5752. CXXNameMangler Mangler(*this, Out);
  5753. Mangler.getStream() << "_ZTI";
  5754. Mangler.mangleType(Ty);
  5755. }
  5756. void ItaniumMangleContextImpl::mangleCXXRTTIName(QualType Ty,
  5757. raw_ostream &Out) {
  5758. // <special-name> ::= TS <type> # typeinfo name (null terminated byte string)
  5759. CXXNameMangler Mangler(*this, Out);
  5760. Mangler.getStream() << "_ZTS";
  5761. Mangler.mangleType(Ty);
  5762. }
  5763. void ItaniumMangleContextImpl::mangleTypeName(QualType Ty, raw_ostream &Out) {
  5764. mangleCXXRTTIName(Ty, Out);
  5765. }
  5766. void ItaniumMangleContextImpl::mangleStringLiteral(const StringLiteral *, raw_ostream &) {
  5767. llvm_unreachable("Can't mangle string literals");
  5768. }
  5769. void ItaniumMangleContextImpl::mangleLambdaSig(const CXXRecordDecl *Lambda,
  5770. raw_ostream &Out) {
  5771. CXXNameMangler Mangler(*this, Out);
  5772. Mangler.mangleLambdaSig(Lambda);
  5773. }
  5774. void ItaniumMangleContextImpl::mangleModuleInitializer(const Module *M,
  5775. raw_ostream &Out) {
  5776. // <special-name> ::= GI <module-name> # module initializer function
  5777. CXXNameMangler Mangler(*this, Out);
  5778. Mangler.getStream() << "_ZGI";
  5779. Mangler.mangleModuleNamePrefix(M->getPrimaryModuleInterfaceName());
  5780. if (M->isModulePartition()) {
  5781. // The partition needs including, as partitions can have them too.
  5782. auto Partition = M->Name.find(':');
  5783. Mangler.mangleModuleNamePrefix(
  5784. StringRef(&M->Name[Partition + 1], M->Name.size() - Partition - 1),
  5785. /*IsPartition*/ true);
  5786. }
  5787. }
  5788. ItaniumMangleContext *ItaniumMangleContext::create(ASTContext &Context,
  5789. DiagnosticsEngine &Diags,
  5790. bool IsAux) {
  5791. return new ItaniumMangleContextImpl(
  5792. Context, Diags,
  5793. [](ASTContext &, const NamedDecl *) -> std::optional<unsigned> {
  5794. return std::nullopt;
  5795. },
  5796. IsAux);
  5797. }
  5798. ItaniumMangleContext *
  5799. ItaniumMangleContext::create(ASTContext &Context, DiagnosticsEngine &Diags,
  5800. DiscriminatorOverrideTy DiscriminatorOverride,
  5801. bool IsAux) {
  5802. return new ItaniumMangleContextImpl(Context, Diags, DiscriminatorOverride,
  5803. IsAux);
  5804. }