ItaniumMangle.cpp 220 KB

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