ItaniumMangle.cpp 174 KB

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