mlir.js 614 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974
  1. // Experimental
  2. const mlir = {};
  3. mlir.ModelFactory = class {
  4. async match(context) {
  5. const stream = context.stream;
  6. const identifier = context.identifier;
  7. const extension = identifier.split('.').pop().toLowerCase();
  8. if (stream && stream.length > 4) {
  9. const buffer = stream.peek(4);
  10. const signature = String.fromCharCode.apply(null, buffer);
  11. if (signature === 'ML\xEFR') {
  12. return context.set('mlir.binary');
  13. }
  14. }
  15. try {
  16. const reader = await context.read('text', 0x10000);
  17. let whitespace = true;
  18. for (let line = reader.read('\n'); line !== undefined; line = reader.read('\n')) {
  19. if (/module\s+(@\w+|\w+|attributes|\{)/.test(line) ||
  20. /tensor<[\w\d]+>/.test(line) ||
  21. /func[.\s]*@\w+/.test(line) ||
  22. /%\w+\s*=\s*"[\w.]+/.test(line) ||
  23. /%\w+\s*=\s*\w+\./.test(line) ||
  24. /!\w+\s*=\s*![\w.]+</.test(line) ||
  25. /#\w+\s*=\s*#[\w.]+</.test(line) ||
  26. /#\w+\s*=\s*loc\s*\(/.test(line) ||
  27. /\w+\.\w+(?:\s+\w+)*\s+@\w+/.test(line) ||
  28. /\w+\.\w+\.\w+\s*\{/.test(line) ||
  29. /:\s*![\w.]+/.test(line) ||
  30. /(%\w+|\w{2,}|[)])\s*:\s*(\[|tensor<)/.test(line) ||
  31. /->\s*(![\w.]+|\(|tensor<)/.test(line)) {
  32. return context.set('mlir.text');
  33. }
  34. if (line && !line.trim().startsWith('//')) {
  35. whitespace = false;
  36. }
  37. }
  38. if (extension === 'mlir' && whitespace) {
  39. return context.set('mlir.text');
  40. }
  41. } catch {
  42. // continue regardless of error
  43. }
  44. return null;
  45. }
  46. async open(context) {
  47. const metadata = await mlir.Metadata.open(context);
  48. switch (context.type) {
  49. case 'mlir.text': {
  50. const decoder = await context.read('text.decoder');
  51. const state = new mlir.ParserState();
  52. const parser = new mlir.Parser(state, decoder, metadata);
  53. const block = await parser.parse();
  54. return new mlir.Model(metadata, block, state.attributeAliasDefinitions);
  55. }
  56. case 'mlir.binary': {
  57. const reader = await context.read('binary');
  58. const parser = new mlir.BytecodeReader(reader);
  59. parser.read();
  60. throw new mlir.Error('File contains unsupported MLIR bytecode data.');
  61. }
  62. default: {
  63. throw new mlir.Error(`Unsupported MLIR format '${context.type}'.`);
  64. }
  65. }
  66. }
  67. };
  68. mlir.Model = class {
  69. constructor(metadata, block, attributeAliasDefinitions) {
  70. this.format = 'MLIR';
  71. this.modules = [];
  72. this.metadata = [];
  73. for (const op of block.operations) {
  74. if (op.name.endsWith('.func')) {
  75. const graph = new mlir.Graph(metadata, op);
  76. this.modules.push(graph);
  77. }
  78. if (op.name.endsWith('.module')) {
  79. for (const region of op.regions) {
  80. for (const block of region.blocks) {
  81. for (const op of block.operations) {
  82. if (op.name.endsWith('.func')) {
  83. const graph = new mlir.Graph(metadata, op);
  84. this.modules.push(graph);
  85. }
  86. }
  87. }
  88. }
  89. }
  90. }
  91. for (const [name, attribute] of attributeAliasDefinitions) {
  92. let value = attribute.type;
  93. if (!value) {
  94. value = typeof attribute.value === 'string' ? attribute.value : JSON.stringify(attribute.value);
  95. }
  96. const metadata = new mlir.Argument(name, value, 'attribute');
  97. this.metadata.push(metadata);
  98. }
  99. }
  100. };
  101. mlir.Graph = class {
  102. constructor(metadata, func) {
  103. const attr = Object.fromEntries(func.attributes.map((attr) => [attr.name, attr.value]));
  104. this.name = attr.sym_name || '';
  105. this.type = func.name === 'func' || func.name.endsWith('.func') ? 'function' : '';
  106. this.description = func.name;
  107. this.inputs = [];
  108. this.outputs = [];
  109. this.nodes = [];
  110. const tensors = new Map();
  111. const tensor = (arg) => {
  112. if (!tensors.has(arg.name)) {
  113. tensors.set(arg.name, new mlir.Value(arg.name, arg.type, null, arg.value));
  114. }
  115. return tensors.get(arg.name);
  116. };
  117. const function_type = attr.function_type;
  118. const args = func.regions && func.regions[0] && func.regions[0].blocks && func.regions[0].blocks[0] && func.regions[0].blocks[0].arguments ? func.regions[0].blocks[0].arguments : [];
  119. for (let i = 0; i < function_type.inputs.length; i++) {
  120. const input = function_type.inputs[i];
  121. let name = '';
  122. if (args[i] && args[i].value) {
  123. name = args[i].value;
  124. } else if (input.value) {
  125. name = input.value;
  126. } else {
  127. name = i.toString();
  128. }
  129. const type = mlir.Utility.valueType(input.type || input);
  130. const value = new mlir.Value(name, type, '', null);
  131. const argument = new mlir.Argument(name, [value]);
  132. this.inputs.push(argument);
  133. }
  134. for (let i = 0; i < function_type.results.length; i++) {
  135. const output = function_type.results[i];
  136. const name = output.value || i.toString();
  137. const type = mlir.Utility.valueType(output.type);
  138. const valueName = output.value || output.name || `%result${i}`;
  139. const value = new mlir.Value(valueName, type, '', null);
  140. const argument = new mlir.Argument(name, [value]);
  141. this.outputs.push(argument);
  142. }
  143. const values = new Map();
  144. values.map = (name) => {
  145. if (!values.has(name)) {
  146. values.set(name, { name, to: [], from: [] });
  147. }
  148. return values.get(name);
  149. };
  150. const operations = [];
  151. for (const region of func.regions) {
  152. for (const block of region.blocks) {
  153. for (const op of block.operations) {
  154. const operation = {
  155. type: op.kind || op.name,
  156. identifier: op.name,
  157. attributes: op.attributes,
  158. operands: [],
  159. results: [],
  160. delete: false,
  161. };
  162. const opMetadata = op.metadata;
  163. const operands = op.operands || [];
  164. for (let i = 0; i < operands.length; i++) {
  165. const input = op.operands[i];
  166. const inputName = input.name || (opMetadata && opMetadata.inputs && opMetadata.inputs[i] ? opMetadata.inputs[i].name : null) || i.toString();
  167. if (input.value instanceof Uint8Array) {
  168. operation.operands.push({
  169. name: inputName,
  170. value: input.value,
  171. type: input.type
  172. });
  173. } else if (Number.isInteger(input.value)) {
  174. operation.operands.push({
  175. name: inputName,
  176. value: input.value,
  177. type: new mlir.PrimitiveType('i64')
  178. });
  179. } else if (typeof input.value === 'boolean') {
  180. operation.operands.push({
  181. name: inputName,
  182. value: input.value,
  183. type: new mlir.PrimitiveType('i1')
  184. });
  185. } else if (Array.isArray(input.value)) {
  186. operation.operands.push({
  187. name: inputName,
  188. value: input.value
  189. });
  190. } else if (typeof input.value === 'string' && input.value) {
  191. const value = values.map(input);
  192. value.to.push(operation);
  193. const args = [{ name: input.value, type: input.type }];
  194. operation.operands.push({
  195. name: inputName,
  196. value: args
  197. });
  198. } else {
  199. operation.operands.push({
  200. name: inputName,
  201. value: input
  202. });
  203. }
  204. }
  205. const results = op.results || [];
  206. for (let i = 0; i < results.length; i++) {
  207. const output = results[i];
  208. if (!output.value) {
  209. // Skip results without value identifiers
  210. continue;
  211. }
  212. const value = values.map(output.value);
  213. value.type = mlir.Utility.valueType(output.type);
  214. value.from.push(operation);
  215. const outputName = output.name || (opMetadata && opMetadata.outputs && opMetadata.outputs[i] ? opMetadata.outputs[i].name : null) || i.toString();
  216. operation.results.push({
  217. name: outputName,
  218. value: [value]
  219. });
  220. }
  221. operations.push(operation);
  222. }
  223. }
  224. }
  225. for (const input of this.inputs) {
  226. for (const arg of input.value) {
  227. if (!tensors.has(arg.name)) {
  228. tensors.set(arg.name, arg);
  229. }
  230. }
  231. }
  232. // Find return operation and connect its operands to graph outputs
  233. const returnOp = operations.find((op) => op.type === 'return' || op.type.endsWith('.return'));
  234. if (returnOp && returnOp.operands.length > 0) {
  235. for (let i = 0; i < this.outputs.length && i < returnOp.operands.length; i++) {
  236. const operand = returnOp.operands[i];
  237. if (Array.isArray(operand.value) && operand.value.length > 0) {
  238. const [returnValue] = operand.value;
  239. if (returnValue && typeof returnValue.name === 'string' && returnValue.name.startsWith('%')) {
  240. const output = this.outputs[i];
  241. output.value[0] = new mlir.Value(returnValue.name, returnValue.type || output.value[0].type, '', null);
  242. }
  243. }
  244. }
  245. returnOp.delete = true;
  246. }
  247. for (const output of this.outputs) {
  248. for (let i = 0; i < output.value.length; i++) {
  249. const arg = output.value[i];
  250. if (tensors.has(arg.name)) {
  251. output.value[i] = tensors.get(arg.name);
  252. } else {
  253. tensors.set(arg.name, arg);
  254. }
  255. }
  256. }
  257. for (const op of operations) {
  258. if (op.delete) {
  259. continue;
  260. }
  261. op.operands = op.operands.map((input) => {
  262. if (input.type) {
  263. const typeStr = input.type instanceof mlir.Type ? input.type.toString() : input.type;
  264. if (typeStr.startsWith('tensor<')) {
  265. const type = mlir.Utility.valueType(typeStr);
  266. const tensor = new mlir.Tensor(type, input.value);
  267. return new mlir.Argument(input.name, tensor, 'tensor');
  268. }
  269. return new mlir.Argument(input.name, input.value, input.type);
  270. }
  271. if (Array.isArray(input.value) && !input.value.every((value) => typeof value.name === 'string' && value.name.startsWith('%'))) {
  272. return new mlir.Argument(input.name, input.value, input.type || 'attribute');
  273. }
  274. if (!Array.isArray(input.value)) {
  275. // Handle non-array values (e.g., affine maps, complex expressions) as attributes
  276. return new mlir.Argument(input.name, input.value, input.type || 'attribute');
  277. }
  278. return new mlir.Argument(input.name, input.value.map((argument) => tensor(argument)));
  279. });
  280. op.results = op.results.map((output) => {
  281. return new mlir.Argument(output.name, output.value.map((argument) => tensor(argument)));
  282. });
  283. }
  284. for (const op of operations.filter((op) => !op.delete)) {
  285. const node = new mlir.Node(metadata, op);
  286. this.nodes.push(node);
  287. }
  288. }
  289. };
  290. mlir.Argument = class {
  291. constructor(name, value, type = null) {
  292. this.name = name;
  293. this.value = value;
  294. this.type = type;
  295. // Normalize common type aliases and accept extended MLIR types
  296. if (this.type) {
  297. // Convert mlir.Type objects to strings for high-level usage
  298. const typeStr = this.type instanceof mlir.Type ? this.type.toString() : this.type;
  299. switch (typeStr) {
  300. case 'i64': case 'si64': this.type = 'int64'; break;
  301. case 'i48': case 'si48': this.type = 'int48'; break;
  302. case 'i32': case 'si32': this.type = 'int32'; break;
  303. case 'i16': case 'si16': this.type = 'int16'; break;
  304. case 'i8': case 'si8': this.type = 'int8'; break;
  305. case 'i1': this.type = 'boolean'; break;
  306. case 'f32': case 'float32': this.type = 'float32'; break;
  307. case 'f64': case 'float64': this.type = 'float64'; break;
  308. case 'f16': this.type = 'float16'; break;
  309. case null:
  310. case 'attribute':
  311. case 'boolean':
  312. case 'string':
  313. case 'int64':
  314. case 'int32':
  315. case 'int16':
  316. case 'int8':
  317. case 'float16':
  318. case 'tensor':
  319. case 'type':
  320. case 'dense':
  321. break;
  322. default:
  323. // Accept other MLIR types without normalization
  324. if (/^[usi]i?[0-9]+$/.test(typeStr) || /^f[0-9]+$/.test(typeStr) ||
  325. typeStr === 'bf16' || typeStr === 'index' || typeStr === 'none' ||
  326. typeStr === 'unit' || typeStr.startsWith('!') || typeStr.startsWith('tensor<') ||
  327. typeStr.startsWith('memref<') || typeStr.startsWith('vector<')) {
  328. // Store as string for high-level usage
  329. this.type = typeStr;
  330. break;
  331. }
  332. throw new mlir.Error(`Unsupported argument type '${typeStr}'.`);
  333. }
  334. }
  335. }
  336. };
  337. mlir.Value = class {
  338. constructor(name, type, description, initializer) {
  339. if (typeof name !== 'string') {
  340. throw new mlir.Error(`Invalid value identifier '${JSON.stringify(name)}'.`);
  341. }
  342. this.name = name;
  343. this.type = !type && initializer ? initializer.type : type;
  344. this.description = description || null;
  345. this.initializer = initializer || null;
  346. }
  347. };
  348. mlir.Node = class {
  349. constructor(metadata, op) {
  350. if (!op.type) {
  351. throw new mlir.Error('Undefined node type.');
  352. }
  353. this.type = { ...metadata.type(op.identifier || '') };
  354. this.type.name = op.type || '';
  355. this.type.identifier = op.identifier || '';
  356. this.name = op.name || '';
  357. this.inputs = op.operands || [];
  358. this.outputs = op.results || [];
  359. this.attributes = [];
  360. if (op.attributes) {
  361. for (let i = 0; i < op.attributes.length; i++) {
  362. const attr = op.attributes[i];
  363. const name = attr.name || i.toString();
  364. let type = attr.type;
  365. let value = attr.value;
  366. if (type) {
  367. if (type.toString().startsWith('tensor<')) {
  368. value = new mlir.Tensor(mlir.Utility.valueType(type), value);
  369. type = 'tensor';
  370. }
  371. }
  372. const attribute = new mlir.Argument(name, value, type || 'attribute');
  373. this.attributes.push(attribute);
  374. }
  375. }
  376. }
  377. };
  378. mlir.Tensor = class {
  379. constructor(type, data) {
  380. this.type = type;
  381. this.values = data;
  382. this.encoding = data instanceof Uint8Array ? '<' : '|';
  383. }
  384. };
  385. mlir.TensorType = class {
  386. constructor(dataType, shape) {
  387. this.dataType = mlir.Utility.dataType(dataType); // string
  388. this.shape = shape || new mlir.TensorShape([]); // mlir.TensorShape
  389. }
  390. toString() {
  391. return this.dataType + this.shape.toString();
  392. }
  393. };
  394. mlir.TensorShape = class {
  395. constructor(dimensions) {
  396. this.dimensions = dimensions;
  397. }
  398. toString() {
  399. if (!this.dimensions || this.dimensions.length === 0) {
  400. return '';
  401. }
  402. return `[${this.dimensions.map((dimension) => dimension.toString()).join(',')}]`;
  403. }
  404. };
  405. mlir.Token = class {
  406. constructor(kind, value, text) {
  407. this.kind = kind;
  408. this.value = value;
  409. this.text = text;
  410. }
  411. };
  412. mlir.Tokenizer = class {
  413. constructor(decoder) {
  414. this._decoder = decoder;
  415. this._currentPosition = this._decoder.position;
  416. this._current = this._decoder.decode();
  417. this._nextPosition = this._decoder.position;
  418. this._next = this._decoder.decode();
  419. this._tokens = [new mlir.Token(null, null, null), new mlir.Token(null, null, null), new mlir.Token(null, null, null), new mlir.Token(null, null, null)];
  420. this._index = 0;
  421. }
  422. read() {
  423. this._position = this._currentPosition;
  424. while (this._current) {
  425. switch (this._current) {
  426. case ' ':
  427. case '\t':
  428. case '\n':
  429. case '\r':
  430. case '\f':
  431. this._skipWhitespace();
  432. this._position = this._currentPosition;
  433. continue;
  434. case '/':
  435. this._skipComment();
  436. this._position = this._currentPosition;
  437. continue;
  438. case '.':
  439. if (/[0-9]/.test(this._peek())) {
  440. return this._number();
  441. }
  442. this._read();
  443. if (this._current === '.' && this._next === '.') {
  444. this._read();
  445. this._read();
  446. return this._token('ellipsis', '...');
  447. }
  448. return this._token('.', '.');
  449. case '-':
  450. if (/[0-9]/.test(this._peek())) {
  451. return this._number();
  452. } else if (this._peek() === '>') {
  453. this._read();
  454. this._read();
  455. return this._token('->', '->');
  456. }
  457. this._read();
  458. return this._token('keyword', '-');
  459. case '+':
  460. this._read();
  461. return this._token('keyword', '+');
  462. case '"':
  463. return this._stringLiteral();
  464. case '@':
  465. return this._symbolRefId();
  466. case '%':
  467. return this._valueId();
  468. case '#':
  469. if (this._peek() === '-') {
  470. const position = this._decoder.position;
  471. const next = this._decoder.decode();
  472. this._decoder.position = position;
  473. if (next === '}') {
  474. this._read();
  475. this._read();
  476. this._read();
  477. return this._token('#-}', '#-}');
  478. }
  479. }
  480. return this._attributeAlias();
  481. case '!': { // type alias
  482. return this._typeAlias();
  483. }
  484. case '^':
  485. return this._caretId();
  486. case '=':
  487. if (this._peek() === '=') {
  488. this._read();
  489. this._read();
  490. return this._token('==', '==');
  491. }
  492. this._read();
  493. return this._token('=', '=');
  494. case ':':
  495. if (this._peek() === ':') {
  496. this._read();
  497. this._read();
  498. return this._token('::', '::');
  499. }
  500. this._read();
  501. return this._token(':', ':');
  502. case ',':
  503. case '(':
  504. case ')':
  505. case '{': {
  506. if (this._peek() === '-') {
  507. const position = this._decoder.position;
  508. const next = this._decoder.decode();
  509. this._decoder.position = position;
  510. if (next === '#') {
  511. this._read();
  512. this._read();
  513. this._read();
  514. return this._token('{-#', '{-#');
  515. }
  516. }
  517. const value = this._read();
  518. return this._token(value, value);
  519. }
  520. case '}':
  521. case '[':
  522. case ']':
  523. case '<':
  524. case '?':
  525. case '*':
  526. case '|': {
  527. const value = this._read();
  528. return this._token(value, value);
  529. }
  530. case '>':
  531. if (this._peek() === '=') {
  532. this._read();
  533. this._read();
  534. return this._token('>=', '>=');
  535. }
  536. this._read();
  537. return this._token('>', '>');
  538. default:
  539. if (/[a-zA-Z_$]/.test(this._current) || /[-.]/.test(this._current)) {
  540. return this._identifier();
  541. }
  542. if (/[0-9]/.test(this._current)) {
  543. return this._number();
  544. }
  545. throw new mlir.Error(`Unexpected character '${this._current}' ${this.location()}`);
  546. }
  547. }
  548. return this._token('eof', null);
  549. }
  550. resetPointer(offset) {
  551. if (offset < 0) {
  552. throw new mlir.Error('resetPointer does not support negative offsets.');
  553. }
  554. this._decoder.position = this._position;
  555. for (let i = 0; i < offset; i++) {
  556. this._decoder.decode();
  557. }
  558. this._nextPosition = this._decoder.position;
  559. this._next = this._decoder.decode();
  560. this._read();
  561. }
  562. location() {
  563. let line = 1;
  564. let column = 1;
  565. const position = this._decoder.position;
  566. this._decoder.position = 0;
  567. let c = '';
  568. do {
  569. if (this._decoder.position === this._position) {
  570. this._decoder.position = position;
  571. return `at ${line}:${column}.`;
  572. }
  573. c = this._decoder.decode();
  574. if (c === '\n') {
  575. line++;
  576. column = 1;
  577. } else {
  578. column++;
  579. }
  580. }
  581. while (c !== undefined);
  582. this._decoder.position = position;
  583. return `at ${line}:${column}.`;
  584. }
  585. _read() {
  586. const current = this._current;
  587. this._current = this._next;
  588. this._currentPosition = this._nextPosition;
  589. this._nextPosition = this._decoder.position;
  590. this._next = this._decoder.decode();
  591. return current;
  592. }
  593. _peek() {
  594. return this._next;
  595. }
  596. _skipWhitespace() {
  597. while (this._current !== undefined && (this._current === ' ' || this._current === '\t' || this._current === '\n' || this._current === '\r' || this._current === '\f')) {
  598. this._read();
  599. }
  600. }
  601. _eat(value) {
  602. if (this._current === value) {
  603. this._read();
  604. return true;
  605. }
  606. return false;
  607. }
  608. _skipComment() {
  609. this._read('/');
  610. if (this._current === '/') {
  611. while (this._current && this._current !== '\n') {
  612. this._read();
  613. }
  614. return;
  615. }
  616. if (this._current === '*') {
  617. this._read();
  618. while (this._current) {
  619. if (this._current === '*') {
  620. this._read();
  621. if (this._current === '/') {
  622. this._read();
  623. return;
  624. }
  625. } else {
  626. this._read();
  627. }
  628. }
  629. return;
  630. }
  631. throw new mlir.Error('Invalid comment.');
  632. }
  633. _number() {
  634. let v = '';
  635. let type = 'int';
  636. if (this._current === '-') {
  637. v += this._read();
  638. }
  639. while (this._current && /[0-9]/.test(this._current)) {
  640. v += this._read();
  641. }
  642. if (v === '0' && this._current === 'x' && /[0-9a-fA-F]/.test(this._peek())) {
  643. v += this._read();
  644. while (this._current && /[0-9a-fA-F]/.test(this._current)) {
  645. v += this._read();
  646. }
  647. return this._token(type, parseInt(v, 16), v);
  648. }
  649. if (this._current === '.') {
  650. v += this._read();
  651. type = 'float';
  652. while (this._current && /[0-9]/.test(this._current)) {
  653. v += this._read();
  654. }
  655. if (this._current === 'e' || this._current === 'E') {
  656. v += this._read();
  657. if (this._current === '+' || this._current === '-') {
  658. v += this._read();
  659. }
  660. while (this._current && /[0-9]/.test(this._current)) {
  661. v += this._read();
  662. }
  663. }
  664. return this._token(type, parseFloat(v), v);
  665. }
  666. return this._token(type, parseInt(v, 10), v);
  667. }
  668. _stringLiteral() {
  669. let result = '';
  670. this._read();
  671. while (this._current && this._current !== '"') {
  672. if (this._eat('\\')) {
  673. const hexDigit = /[0-9a-fA-F]/;
  674. if (hexDigit.test(this._current) && this._next && hexDigit.test(this._next)) {
  675. const hex = this._current + this._next;
  676. result += String.fromCharCode(parseInt(hex, 16));
  677. this._read();
  678. this._read();
  679. continue;
  680. }
  681. switch (this._current) {
  682. case 'n':
  683. result += '\n';
  684. this._read();
  685. break;
  686. case 'r':
  687. result += '\r';
  688. this._read();
  689. break;
  690. case 't':
  691. result += '\t';
  692. this._read();
  693. break;
  694. case '"':
  695. case '\\':
  696. result += this._current;
  697. this._read();
  698. break;
  699. default:
  700. throw new mlir.Error(`Unknown escape sequence '\\${this._current}' in string literal`);
  701. }
  702. } else {
  703. result += this._current;
  704. this._read();
  705. }
  706. }
  707. if (this._eat('"')) {
  708. return this._token('string', result);
  709. }
  710. throw new mlir.Error('Unterminated string literal');
  711. }
  712. _identifier() {
  713. let result = '';
  714. while (this._current && (/[a-zA-Z_$\-.]/.test(this._current) || /[0-9]/.test(this._current))) {
  715. result += this._read();
  716. }
  717. switch (result) {
  718. case 'loc':
  719. return this._token('keyword', result);
  720. case 'true':
  721. case 'false':
  722. return this._token('boolean', result === 'true');
  723. case 'unknown':
  724. return this._token('id', result);
  725. default:
  726. return this._token('id', result);
  727. }
  728. }
  729. _attributeAlias() {
  730. let value = '#';
  731. this._read();
  732. if (this._current === '"') {
  733. value += this._stringLiteral().value;
  734. } else {
  735. while (this._current && (/[a-zA-Z_$]/.test(this._current) || /[0-9]/.test(this._current) || /[-.]/.test(this._current))) {
  736. value += this._read();
  737. }
  738. if (this._current === ':' && this._peek() === ':') {
  739. value += this._read();
  740. value += this._read();
  741. value += this._symbolRefId().value;
  742. }
  743. }
  744. return this._token('#', value);
  745. }
  746. _symbolRefId() {
  747. let result = '@';
  748. this._read();
  749. if (this._current === '"') {
  750. result += this._stringLiteral().value;
  751. } else {
  752. while (this._current && (/[a-zA-Z_$]/.test(this._current) || /[0-9]/.test(this._current) || /[-.]/.test(this._current))) {
  753. result += this._read();
  754. }
  755. if (this._current === ':' && this._peek() === ':') {
  756. result += this._read();
  757. result += this._read();
  758. result += this._symbolRefId().value;
  759. }
  760. }
  761. return this._token('@', result);
  762. }
  763. _typeAlias() {
  764. this._read();
  765. let dialectName = '';
  766. while (this._current && /[a-zA-Z_$0-9]/.test(this._current)) {
  767. dialectName += this._read();
  768. }
  769. if (!dialectName) {
  770. throw new mlir.Error('Invalid type alias.');
  771. }
  772. return this._token('!', `!${dialectName}`);
  773. }
  774. _valueId() {
  775. let result = '';
  776. if (this._current === '%') {
  777. result = '%';
  778. } else if (this._current === '$') {
  779. result = '$';
  780. }
  781. this._read();
  782. while (this._current) {
  783. if (/[a-zA-Z_$]/.test(this._current) || /[0-9]/.test(this._current) || /[-.#]/.test(this._current)) {
  784. result += this._read();
  785. } else if (/[:]/.test(this._current) && /[0-9]/.test(this._next)) { // %myid:3 case
  786. result += this._read();
  787. } else {
  788. break;
  789. }
  790. }
  791. return this._token('%', result);
  792. }
  793. _caretId() {
  794. let result = '^';
  795. this._read();
  796. if (this._current === ':' && this._peek() !== ':') {
  797. result += this._read();
  798. return this._token('^', result);
  799. }
  800. while (this._current && (/[a-zA-Z_$]/.test(this._current) || /[0-9]/.test(this._current) || /[-.]/.test(this._current))) {
  801. result += this._read();
  802. }
  803. if (this._current === ':' && this._peek() === ':') {
  804. result += this._read();
  805. result += this._read();
  806. result += this._caretId().value;
  807. }
  808. return this._token('^', result);
  809. }
  810. _token(kind, value, text) {
  811. const token = this._tokens[this._index];
  812. this._index = (this._index + 1) % this._tokens.length;
  813. token.kind = kind;
  814. token.value = value;
  815. token.text = text;
  816. return token;
  817. }
  818. };
  819. mlir.ParserState = class {
  820. constructor() {
  821. this.defaultDialectStack = ['builtin'];
  822. this.attributeAliasDefinitions = new Map();
  823. this.typeAliasDefinitions = new Map();
  824. }
  825. };
  826. mlir.Parser = class {
  827. constructor(state, decoder, metadata) {
  828. this._tokenizer = new mlir.Tokenizer(decoder);
  829. this._token = this._tokenizer.read();
  830. this._state = state;
  831. this._dialects = new Map();
  832. const operations = metadata.operations;
  833. this._dialects.set('builtin', new mlir.BuiltinDialect(operations));
  834. this._dialects.set('bufferization', new mlir.BufferizationDialect(operations));
  835. this._dialects.set('stablehlo', new mlir.StableHLODialect(operations));
  836. this._dialects.set('vhlo', new mlir.VhloDialect(operations));
  837. this._dialects.set('interpreter', new mlir.InterpreterDialect(operations));
  838. this._dialects.set('affine', new mlir.AffineDialect(operations));
  839. this._dialects.set('asuka', new mlir.AsukaDialect(operations));
  840. this._dialects.set('arith', new mlir.ArithDialect(operations));
  841. this._dialects.set('async', new mlir.AsyncDialect(operations));
  842. this._dialects.set('cf', new mlir.CFDialect(operations));
  843. this._dialects.set('emitc', new mlir.EmitCDialect(operations));
  844. this._dialects.set('complex', new mlir.Dialect('complex', operations));
  845. this._dialects.set('index', new mlir.Dialect('index', operations));
  846. this._dialects.set('pdl', new mlir.PDLDialect(operations));
  847. this._dialects.set('ptr', new mlir.PtrDialect(operations));
  848. this._dialects.set('ub', new mlir.Dialect('ub', operations));
  849. this._dialects.set('amdgpu', new mlir.AMDGPUDialect(operations));
  850. this._dialects.set('nvgpu', new mlir.NVGPUDialect(operations));
  851. this._dialects.set('nvvm', new mlir.NVVMDialect(operations));
  852. this._dialects.set('rocdl', new mlir.ROCDLDialect(operations));
  853. this._dialects.set('nvws', new mlir.Dialect('nvws', operations));
  854. this._dialects.set('tti', new mlir.Dialect('tti', operations));
  855. this._dialects.set('omp', new mlir.OpenMPDialect(operations));
  856. this._dialects.set('proton', new mlir.ProtonDialect(operations));
  857. this._dialects.set('proton_gpu', new mlir.Dialect('proton_gpu', operations));
  858. this._dialects.set('arm_sme', new mlir.ArmSMEDialect(operations));
  859. this._dialects.set('arm_neon', new mlir.ArmNeonDialect(operations));
  860. this._dialects.set('arm_sve', new mlir.ArmSVEDialect(operations));
  861. this._dialects.set('shard', new mlir.ShardDialect(operations));
  862. this._dialects.set('amx', new mlir.Dialect('amx', operations));
  863. this._dialects.set('smt', new mlir.SMTDialect(operations));
  864. this._dialects.set('lagrad', new mlir.Dialect('lagrad', operations));
  865. this._dialects.set('iree_codegen', new mlir.Dialect('iree_codegen', operations));
  866. this._dialects.set('iree_encoding', new mlir.Dialect('iree_encoding', operations));
  867. this._dialects.set('test', new mlir.TestDialect(operations));
  868. this._dialects.set('scf', new mlir.SCFDialect(operations));
  869. this._dialects.set('shape', new mlir.ShapeDialect(operations));
  870. this._dialects.set('sparse_tensor', new mlir.SparseTensorDialect(operations));
  871. this._dialects.set('func', new mlir.FuncDialect(operations));
  872. this._dialects.set('gpu', new mlir.GpuDialect(operations));
  873. this._dialects.set('llvm', new mlir.LLVMDialect(operations));
  874. this._dialects.set('xegpu', new mlir.XeGPUDialect(operations));
  875. this._dialects.set('memref', new mlir.MemRefDialect(operations));
  876. this._dialects.set('vector', new mlir.VectorDialect(operations));
  877. this._dialects.set('x86vector', new mlir.Dialect('x86vector', operations));
  878. this._dialects.set('onnx', new mlir.ONNXDialect(operations));
  879. this._dialects.set('krnl', new mlir.KrnlDialect(operations));
  880. this._dialects.set('torch', new mlir.TorchDialect(operations));
  881. this._dialects.set('torch_c', new mlir.Dialect('torch_c', operations));
  882. this._dialects.set('hal', new mlir.HALDialect(operations));
  883. this._dialects.set('hal_loader', new mlir.Dialect('hal_loader', operations));
  884. this._dialects.set('hal_inline', new mlir.Dialect('hal_inline', operations));
  885. this._dialects.set('util', new mlir.UtilDialect(operations));
  886. this._dialects.set('mhlo', new mlir.MhloDialect(operations));
  887. this._dialects.set('chlo', new mlir.Dialect('chlo', operations));
  888. this._dialects.set('flow', new mlir.FlowDialect(operations));
  889. this._dialects.set('stream', new mlir.StreamDialect(operations));
  890. this._dialects.set('iree_vector_ext', new mlir.IREEVectorExtDialect(operations));
  891. this._dialects.set('iree_tensor_ext', new mlir.IREETensorExtDialect(operations));
  892. this._dialects.set('linalg', new mlir.LinalgDialect(operations));
  893. this._dialects.set('iree_linalg_ext', new mlir.Dialect('iree_linalg_ext', operations));
  894. this._dialects.set('quant', new mlir.QuantDialect(operations));
  895. this._dialects.set('tensor', new mlir.Dialect('tensor', operations));
  896. this._dialects.set('tosa', new mlir.TosaDialect(operations));
  897. this._dialects.set('tf', new mlir.TFDialect(operations));
  898. this._dialects.set('tf_saved_model', new mlir.Dialect('tf_saved_model', operations));
  899. this._dialects.set('tf_type', new mlir.TFTypeDialect(operations));
  900. this._dialects.set('tf_device', new mlir.TFDeviceDialect(operations));
  901. this._dialects.set('tf_executor', new mlir.TFExecutorDialect(operations));
  902. this._dialects.set('tf_framework', new mlir.TFFrameworkDialect(operations));
  903. this._dialects.set('tfr', new mlir.TFRDialect(operations));
  904. this._dialects.set('corert', new mlir.CoreRTDialect(operations));
  905. this._dialects.set('tfrt', new mlir.TFRTDialect(operations));
  906. this._dialects.set('tfrt_fallback', new mlir.Dialect('tfrt_fallback', operations));
  907. this._dialects.set('tfrt_fallback_async', new mlir.TFRTFallbackAsyncDialect(operations));
  908. this._dialects.set('tfl', new mlir.TFLDialect(operations));
  909. this._dialects.set('stdx', new mlir.StdxDialect(operations));
  910. this._dialects.set('vm', new mlir.VMDialect(operations));
  911. this._dialects.set('math', new mlir.MathDialect(operations));
  912. this._dialects.set('tm_tensor', new mlir.TMTensorDialect(operations));
  913. this._dialects.set('ml_program', new mlir.MLProgramDialect(operations));
  914. this._dialects.set('iree_gpu', new mlir.IREEGPUDialect(operations));
  915. this._dialects.set('tile', new mlir.TileDialect(operations));
  916. this._dialects.set('pxa', new mlir.PXADialect(operations));
  917. this._dialects.set('irdl', new mlir.IRDLDialect(operations));
  918. this._dialects.set('transform', new mlir.TransformDialect(operations));
  919. this._dialects.set('wasmssa', new mlir.Dialect('wasmssa', operations));
  920. this._dialects.set('spirv', new mlir.SPIRVDialect(operations));
  921. this._dialects.set('spv', this._dialects.get('spirv'));
  922. this._dialects.set('toy', new mlir.ToyDialect(operations));
  923. this._dialects.set('top', new mlir.Dialect('top', operations));
  924. this._dialects.set('tpu', new mlir.Dialect('tpu', operations));
  925. this._dialects.set('sdfg', new mlir.SdfgDialect(operations));
  926. this._dialects.set('sdir', this._dialects.get('sdfg'));
  927. this._dialects.set('check', new mlir.CheckDialect(operations));
  928. this._dialects.set('tt', new mlir.TritonDialect(operations));
  929. this._dialects.set('ttg', new mlir.TritonGPUDialect(operations));
  930. this._dialects.set('triton_gpu', this._dialects.get('ttg'));
  931. this._dialects.set('gluon', new mlir.GluonDialect(operations));
  932. this._dialects.set('ttng', new mlir.TritonNvidiaGPUDialect(operations));
  933. this._dialects.set('nvidia_gpu', this._dialects.get('ttng'));
  934. this._dialects.set('amdg', new mlir.TritonAMDGPUDialect(operations));
  935. this._dialects.set('amd_gpu', this._dialects.get('amdg'));
  936. this._dialects.set('michelson', new mlir.MichelsonDialect(operations));
  937. this._dialects.set('tensorrt', new mlir.TensorRTDialect(operations));
  938. this._dialects.set('executor', new mlir.ExecutorDialect(operations));
  939. this._dialects.set('exec', this._dialects.get('executor'));
  940. this._dialects.set('tfrt_test', new mlir.TFRTTestDialect(operations));
  941. this._dialects.set('xevm', new mlir.XeVMDialect(operations));
  942. this._dialects.set('vmvx', new mlir.VMVXDialect(operations));
  943. this._dialects.set('mlrt', new mlir.MLRTDialect(operations));
  944. this._dialects.set('tfrt_tensor', new mlir.TFRTTensorDialect(operations));
  945. this._dialects.set('tfrt_dht', new mlir.TFRTDHTDialect(operations));
  946. this._dialects.set('tfd', new mlir.TFDDialect(operations));
  947. this._dialects.set('acc', new mlir.ACCDialect(operations));
  948. this._dialects.set('cuda', new mlir.Dialect('cuda', operations));
  949. this._dialects.set('trtrt', new mlir.Dialect('trtrt', operations));
  950. this._dialects.set('plan', new mlir.PlanDialect(operations));
  951. this._dialects.set('kernel', new mlir.KernelDialect(operations));
  952. this._dialects.set('nvg', new mlir.Dialect('nvg', operations));
  953. this._dialects.set('mpi', new mlir.Dialect('mpi', operations));
  954. this._dialects.set('pdl_interp', new mlir.Dialect('pdl_interp', operations));
  955. this._dialects.set('standalone', new mlir.Dialect('standalone', operations));
  956. this._dialects.set('ts', new mlir.Dialect('ts', operations));
  957. this._dialects.set('tf_mlrt', new mlir.Dialect('tf_mlrt', operations));
  958. this._dialects.set('io_parameters', new mlir.Dialect('io_parameters', operations));
  959. this._dialects.set('pcf', new mlir.Dialect('pcf', operations));
  960. this._dialects.set('linalgx', new mlir.Dialect('linalgx', operations));
  961. this._dialects.set('xsmm', new mlir.Dialect('xsmm', operations));
  962. this._dialects.set('sdy', new mlir.Dialect('sdy', operations));
  963. this._dialects.set('tfg', new mlir.Dialect('tfg', operations));
  964. this._dialects.set('vt', new mlir.Dialect('vt', operations));
  965. this._dialects.set('thlo', new mlir.Dialect('thlo', operations));
  966. this._dialects.set('testd', new mlir.Dialect('testd', operations));
  967. this._dialects.set('cmath', new mlir.Dialect('cmath', operations));
  968. this._dialects.set('bytecode', new mlir.Dialect('bytecode', operations));
  969. this._dialects.set('test_irdl_to_cpp', new mlir.Dialect('test_irdl_to_cpp', operations));
  970. this._dialects.set('iree_unregistered', new mlir.Dialect('iree_unregistered', operations));
  971. this._redirect = new Map([
  972. ['builtin.func', 'func.func'],
  973. ['builtin.constant', 'arith.constant'],
  974. ['func.constant', 'arith.constant'],
  975. ['builtin.return', 'func.return'],
  976. ['builtin.select', 'arith.select'],
  977. ['scf.select', 'arith.select'],
  978. ['scf.call', 'func.call'],
  979. ['builtin.view', 'memref.view'],
  980. ['builtin.dealloc', 'memref.dealloc'], ['func.dealloc', 'memref.dealloc'],
  981. // Arith operations (from both builtin and func default dialects)
  982. ['builtin.addi', 'arith.addi'], ['func.addi', 'arith.addi'],
  983. ['builtin.subi', 'arith.subi'], ['func.subi', 'arith.subi'],
  984. ['builtin.muli', 'arith.muli'], ['func.muli', 'arith.muli'],
  985. ['builtin.divi_signed', 'arith.divsi'], ['func.divi_signed', 'arith.divsi'],
  986. ['builtin.divi_unsigned', 'arith.divui'], ['func.divi_unsigned', 'arith.divui'],
  987. ['builtin.divsi', 'arith.divsi'], ['func.divsi', 'arith.divsi'],
  988. ['builtin.divui', 'arith.divui'], ['func.divui', 'arith.divui'],
  989. ['builtin.remi_signed', 'arith.remsi'], ['func.remi_signed', 'arith.remsi'],
  990. ['builtin.remi_unsigned', 'arith.remui'], ['func.remi_unsigned', 'arith.remui'],
  991. ['builtin.andi', 'arith.andi'], ['func.andi', 'arith.andi'],
  992. ['builtin.ori', 'arith.ori'], ['func.ori', 'arith.ori'],
  993. ['builtin.xori', 'arith.xori'], ['func.xori', 'arith.xori'],
  994. ['builtin.shli', 'arith.shli'], ['func.shli', 'arith.shli'],
  995. ['builtin.shrsi', 'arith.shrsi'], ['func.shrsi', 'arith.shrsi'],
  996. ['builtin.shrui', 'arith.shrui'], ['func.shrui', 'arith.shrui'],
  997. ['builtin.addf', 'arith.addf'], ['func.addf', 'arith.addf'],
  998. ['builtin.subf', 'arith.subf'], ['func.subf', 'arith.subf'],
  999. ['builtin.mulf', 'arith.mulf'], ['func.mulf', 'arith.mulf'],
  1000. ['builtin.divf', 'arith.divf'], ['func.divf', 'arith.divf'],
  1001. ['builtin.cmpi', 'arith.cmpi'], ['func.cmpi', 'arith.cmpi'],
  1002. ['builtin.cmpf', 'arith.cmpf'], ['func.cmpf', 'arith.cmpf'],
  1003. ['builtin.index_cast', 'arith.index_cast'], ['func.index_cast', 'arith.index_cast'],
  1004. ['builtin.sitofp', 'arith.sitofp'], ['func.sitofp', 'arith.sitofp'],
  1005. ['builtin.fptosi', 'arith.fptosi'], ['func.fptosi', 'arith.fptosi'],
  1006. ['builtin.truncf', 'arith.truncf'], ['func.truncf', 'arith.truncf'],
  1007. ['builtin.extf', 'arith.extf'], ['func.extf', 'arith.extf'],
  1008. ['builtin.splat', 'vector.splat'],
  1009. ['func.splat', 'vector.splat'],
  1010. ['scf.splat', 'vector.splat'],
  1011. // Memref operations
  1012. ['builtin.alloc', 'memref.alloc'], ['func.alloc', 'memref.alloc'],
  1013. ['builtin.load', 'memref.load'], ['func.load', 'memref.load'],
  1014. ['builtin.store', 'memref.store'], ['func.store', 'memref.store'],
  1015. ['builtin.subview', 'memref.subview'], ['func.subview', 'memref.subview'],
  1016. ['builtin.dim', 'memref.dim'], ['func.dim', 'memref.dim'],
  1017. ['builtin.view', 'memref.view'], ['func.view', 'memref.view'],
  1018. // Control flow operations
  1019. ['builtin.cond_br', 'cf.cond_br'], ['func.cond_br', 'cf.cond_br'],
  1020. ['builtin.br', 'cf.br'], ['func.br', 'cf.br'],
  1021. ['builtin.switch', 'cf.switch'], ['func.switch', 'cf.switch'],
  1022. ['builtin.assert', 'cf.assert'], ['func.assert', 'cf.assert'],
  1023. // Other redirects
  1024. ['flow.constant', 'flow.tensor.constant'],
  1025. ['util.initializer.return', 'util.return']
  1026. ]);
  1027. }
  1028. async parse() {
  1029. // Reference: Parser.cpp TopLevelOperationParser::parse
  1030. // https://mlir.llvm.org/docs/LangRef/#top-level-productions
  1031. const block = {
  1032. operations: []
  1033. };
  1034. while (true) {
  1035. if (this.match('eof')) {
  1036. break;
  1037. }
  1038. if (this.match('#')) {
  1039. // Reference: parseAttributeAliasDef stores in state.symbols.attributeAliasDefinitions
  1040. this.parseAttributeAliasDef();
  1041. continue;
  1042. }
  1043. if (this.match('!')) {
  1044. // Reference: parseTypeAliasDef stores in state.symbols.typeAliasDefinitions
  1045. this.parseTypeAliasDef();
  1046. continue;
  1047. }
  1048. if (this.match('{-#')) {
  1049. this.parseFileMetadataDictionary();
  1050. continue;
  1051. }
  1052. const op = this.parseOperation();
  1053. block.operations.push(op);
  1054. }
  1055. return block;
  1056. }
  1057. // Reference: Parser.cpp parseAttributeAliasDef lines 2695-2725
  1058. // attribute-alias-def ::= '#' alias-name `=` attribute-value
  1059. parseAttributeAliasDef() {
  1060. const aliasName = this.expect();
  1061. this.expect('=');
  1062. // Handle pre-2020 bare affine map syntax: (dims) [symbols] -> (results)
  1063. // Changed to affine_map<...> in llvm/llvm-project@4268e4f4b84b (Jan 2020)
  1064. let attr = null;
  1065. if (this.match('(')) {
  1066. const dims = this.skip('(', ')');
  1067. const symbols = this.match('[') ? this.skip('[', ']') : '';
  1068. this.expect('->');
  1069. const results = this.match('(') ? this.skip('(', ')') : '';
  1070. attr = { value: `affine_map<${dims}${symbols} -> ${results}>`, name: 'affine_map' };
  1071. } else {
  1072. // Reference: Attribute attr = parseAttribute();
  1073. attr = this.parseAttribute();
  1074. }
  1075. // Reference: state.symbols.attributeAliasDefinitions[aliasName] = attr;
  1076. this._state.attributeAliasDefinitions.set(aliasName, attr);
  1077. }
  1078. // Reference: Parser.cpp parseTypeAliasDef lines 2727-2757
  1079. // type-alias-def ::= '!' alias-name `=` type
  1080. parseTypeAliasDef() {
  1081. const aliasName = this.expect('!');
  1082. this.expect('=');
  1083. const type = this.parseType();
  1084. // Reference: state.symbols.typeAliasDefinitions[aliasName] = type;
  1085. this._state.typeAliasDefinitions.set(aliasName, type);
  1086. }
  1087. // Reference: Parser.cpp parseFileMetadataDictionary
  1088. // file-metadata-dict ::= '{-#' file-metadata-entry* `#-}'
  1089. parseFileMetadataDictionary() {
  1090. this.expect('{-#');
  1091. while (!this.match('#-}') && !this.match('eof')) {
  1092. this._token = this._tokenizer.read();
  1093. }
  1094. this.expect('#-}');
  1095. }
  1096. parseFunctionArgumentList(allowVariadic) {
  1097. const inputs = [];
  1098. let isVariadic = false;
  1099. if (this.accept('(')) {
  1100. while (!this.accept(')')) {
  1101. if (this.match(')')) {
  1102. break;
  1103. }
  1104. if (allowVariadic && this.accept('ellipsis')) {
  1105. isVariadic = true;
  1106. this.expect(')');
  1107. break;
  1108. }
  1109. if (this.match('%')) {
  1110. const input = {};
  1111. input.value = this._token.value;
  1112. this.expect('%');
  1113. this.expect(':');
  1114. input.type = this.parseType();
  1115. if (this.match('{')) {
  1116. input.attributes = [];
  1117. this.parseAttributeDict(input.attributes);
  1118. }
  1119. input.loc = this.parseLocation();
  1120. inputs.push(input);
  1121. } else {
  1122. const input = {};
  1123. input.value = `%arg${inputs.length}`;
  1124. input.type = this.parseType();
  1125. if (this.match('{')) {
  1126. input.attributes = [];
  1127. this.parseAttributeDict(input.attributes);
  1128. }
  1129. inputs.push(input);
  1130. }
  1131. if (!this.match(')')) {
  1132. if (!this.accept(',')) {
  1133. break;
  1134. }
  1135. if (this.match(')')) {
  1136. break;
  1137. }
  1138. }
  1139. }
  1140. }
  1141. return { arguments: inputs, isVariadic };
  1142. }
  1143. parseFunctionSignatureWithArguments(allowVariadic) {
  1144. const argResult = this.parseFunctionArgumentList(allowVariadic);
  1145. const resultTypes = [];
  1146. const resultAttrs = [];
  1147. if (this.accept('->')) {
  1148. this.parseFunctionResultList(resultTypes, resultAttrs);
  1149. }
  1150. return { arguments: argResult.arguments, isVariadic: argResult.isVariadic, resultTypes, resultAttrs };
  1151. }
  1152. parseFunctionOp(op, allowVariadic) {
  1153. this.parseOptionalVisibilityKeyword(op.attributes);
  1154. this.parseSymbolName('sym_name', op.attributes);
  1155. const sig = this.parseFunctionSignatureWithArguments(allowVariadic);
  1156. const argTypes = [];
  1157. for (const arg of sig.arguments) {
  1158. if (arg.value !== '...') {
  1159. argTypes.push(arg.type);
  1160. }
  1161. }
  1162. const type = { inputs: argTypes, results: sig.resultTypes };
  1163. op.attributes.push({ name: 'function_type', value: type });
  1164. if (sig.resultAttrs.some((a) => a !== null)) {
  1165. op.attributes.push({ name: 'res_attrs', value: sig.resultAttrs });
  1166. }
  1167. const argAttrs = sig.arguments.filter((a) => a.value !== '...').map((a) => a.attributes || null);
  1168. if (argAttrs.some((a) => a !== null)) {
  1169. op.attributes.push({ name: 'arg_attrs', value: argAttrs });
  1170. }
  1171. this.parseOptionalAttrDictWithKeyword(op.attributes);
  1172. if (this.match('{')) {
  1173. const region = {};
  1174. this.parseRegion(region, sig.arguments);
  1175. op.regions.push(region);
  1176. }
  1177. }
  1178. // Reference: OpImplementation.h AsmParser::parseTypeList
  1179. // Parse comma-separated type list: type, type, type
  1180. parseTypeList() {
  1181. return this.parseCommaSeparatedList('none', () => this.parseType());
  1182. }
  1183. // Reference: TypeParser.cpp parseTypeListNoParens
  1184. // Parse comma-separated type list without parens: type, type, type
  1185. parseTypeListNoParens() {
  1186. return this.parseCommaSeparatedList('none', () => this.parseType());
  1187. }
  1188. // Reference: TypeParser.cpp parseTypeListParens
  1189. // Parse parenthesized type list: (type, type, type)
  1190. parseTypeListParens() {
  1191. this.expect('(');
  1192. if (this.accept(')')) {
  1193. return [];
  1194. }
  1195. const types = this.parseTypeListNoParens();
  1196. this.expect(')');
  1197. return types;
  1198. }
  1199. skip(open, close) {
  1200. let value = '';
  1201. if (this.match(open)) {
  1202. value += this.expect();
  1203. let count = 1;
  1204. while (count > 0) {
  1205. if (this.match('eof')) {
  1206. throw new mlir.Error(`Unexpected end of file while looking for '${close}' ${this.location()}`);
  1207. }
  1208. if (this.match(open)) {
  1209. count++;
  1210. } else if (this.match(close)) {
  1211. count--;
  1212. }
  1213. value += this.expect();
  1214. }
  1215. }
  1216. return value;
  1217. }
  1218. // Reference: Parser.cpp parseOperation
  1219. parseOperation() {
  1220. const results = [];
  1221. if (this.match('%')) {
  1222. // Parse result SSA ids: %result, %result:N, ...
  1223. const parseNextResult = () => {
  1224. const value = this.expect('%');
  1225. const index = value.indexOf(':');
  1226. if (index === -1) {
  1227. results.push({ value });
  1228. } else {
  1229. const id = value.substring(0, index);
  1230. const length = parseInt(value.substring(index + 1), 10);
  1231. for (let i = 0; i < length; i++) {
  1232. results.push({ value: `${id}#${i}` });
  1233. }
  1234. }
  1235. return true;
  1236. };
  1237. this.parseCommaSeparatedList('none', parseNextResult);
  1238. this.expect('=');
  1239. }
  1240. let op = null;
  1241. if (this.match('id')) {
  1242. op = this.parseCustomOperation(results);
  1243. } else if (this.match('string')) {
  1244. op = this.parseGenericOperation();
  1245. } else {
  1246. throw new mlir.Error(`Unexpected operation name '${this._token.value}' ${this.location()}`);
  1247. }
  1248. if (!op) {
  1249. throw new mlir.Error(`Failed to parse operation ${this.location()}`);
  1250. }
  1251. op.results = results;
  1252. return op;
  1253. }
  1254. // Parse comma-separated SSA use list (just names, no types)
  1255. // Reference: Parser.cpp parseOptionalSSAUseList
  1256. parseOptionalSSAUseList(results) {
  1257. if (!this.match('%')) {
  1258. return;
  1259. }
  1260. do {
  1261. const value = this.expect('%');
  1262. results.push({ value });
  1263. } while (this.accept(',') && this.match('%'));
  1264. }
  1265. parseOperandList(delimiter) {
  1266. delimiter = delimiter || 'none';
  1267. if (delimiter === 'none') {
  1268. if (!this.match('%')) {
  1269. return [];
  1270. }
  1271. }
  1272. const parseOneOperand = () => {
  1273. if (this.match('%')) {
  1274. const value = this.expect('%');
  1275. return { value };
  1276. }
  1277. return null;
  1278. };
  1279. return this.parseCommaSeparatedList(delimiter, parseOneOperand);
  1280. }
  1281. // Reference: OpImplementation.h resolveOperands
  1282. // Resolve a list of operands with a list of types by assigning types to operands
  1283. resolveOperands(operands, types) {
  1284. const count = Math.min(operands.length, types.length);
  1285. for (let i = 0; i < count; i++) {
  1286. operands[i].type = types[i];
  1287. }
  1288. // If more types than operands, create new operand entries
  1289. for (let i = operands.length; i < types.length; i++) {
  1290. operands.push({ type: types[i], value: `%${i}` });
  1291. }
  1292. }
  1293. // Parse successor list: [^block1, ^block2, ...]
  1294. // Reference: Parser.cpp parseSuccessors
  1295. parseSuccessors(successors) {
  1296. const parsed = this.parseCommaSeparatedList('square', () => {
  1297. return { label: this.expect('^') };
  1298. });
  1299. for (const s of parsed) {
  1300. successors.push(s);
  1301. }
  1302. }
  1303. // Parse generic operation after the op name has been parsed
  1304. // Reference: Parser.cpp parseGenericOperationAfterOpName
  1305. // Generic form: "op"(operands) [successors] <properties> (regions) {attrs} : fn-type
  1306. parseGenericOperationAfterOpName(op) {
  1307. op.attributes = op.attributes || [];
  1308. op.operands = op.operands || [];
  1309. op.regions = op.regions || [];
  1310. op.results = op.results || [];
  1311. // 1. Parse operand list: (operands...)
  1312. this.expect('(');
  1313. this.parseOptionalSSAUseList(op.operands);
  1314. this.expect(')');
  1315. // 2. Parse successor list: [^block1, ^block2, ...]
  1316. if (this.match('[')) {
  1317. op.successors = [];
  1318. this.parseSuccessors(op.successors);
  1319. }
  1320. // 3. Parse properties: <attr>
  1321. if (this.accept('<')) {
  1322. op.properties = this.parseAttribute();
  1323. this.expect('>');
  1324. }
  1325. // 4. Parse region list: (region1, region2, ...)
  1326. if (this.accept('(')) {
  1327. do {
  1328. const region = {};
  1329. this.parseRegion(region);
  1330. op.regions.push(region);
  1331. } while (this.accept(','));
  1332. this.expect(')');
  1333. }
  1334. // 5. Parse attributes: {attr = value, ...}
  1335. if (this.match('{')) {
  1336. this.parseAttributeDict(op.attributes);
  1337. }
  1338. // 6. Parse function type: : (input_types) -> (result_types)
  1339. this.expect(':');
  1340. const fnType = this.parseType();
  1341. if (!(fnType instanceof mlir.FunctionType)) {
  1342. throw new mlir.Error(`Expected function type ${this.location()}`);
  1343. }
  1344. // Apply input types to operands
  1345. for (let i = 0; i < fnType.inputs.length && i < op.operands.length; i++) {
  1346. op.operands[i].type = fnType.inputs[i].toString();
  1347. }
  1348. // Apply result types to results
  1349. for (let i = 0; i < fnType.results.length; i++) {
  1350. if (i < op.results.length) {
  1351. op.results[i].type = fnType.results[i].toString();
  1352. } else {
  1353. op.results.push({ type: fnType.results[i].toString() });
  1354. }
  1355. }
  1356. // Parse optional location
  1357. op.loc = this.parseLocation();
  1358. return op;
  1359. }
  1360. parseCustomOperation(results) {
  1361. const opNameInfo = this.parseCustomOperationName();
  1362. const op = { name: opNameInfo, results, attributes: [], operands: [], regions: [] };
  1363. let opName = op.name;
  1364. if (this._redirect.has(op.name)) {
  1365. opName = this._redirect.get(op.name);
  1366. }
  1367. const index = opName.indexOf('.');
  1368. if (index === -1) {
  1369. throw new mlir.Error(`No dialect found '${opName}' ${this.location()}`);
  1370. }
  1371. const dialectName = opName.substring(0, index);
  1372. if (!this._dialects.has(dialectName)) {
  1373. throw new mlir.Error(`Unsupported dialect '${dialectName}' ${this.location()}`);
  1374. }
  1375. const dialect = this._dialects.get(dialectName);
  1376. // Normalize operation name to canonical dialect name for metadata lookup
  1377. // (e.g., spv.Load -> spirv.Load when dialect.name is spirv)
  1378. opName = dialectName === dialect.name ? opName : opName.replace(`${dialectName}.`, `${dialect.name}.`);
  1379. const opInfo = dialect.getOperation(opName);
  1380. if (!opInfo) {
  1381. // Do not remove and address the underlying root cause.
  1382. throw new mlir.Error(`Unsupported operation '${op.name}'.`);
  1383. }
  1384. op.metadata = opInfo.metadata;
  1385. const defaultDialect = (opInfo && opInfo.metadata && opInfo.metadata.defaultDialect) || '';
  1386. this._state.defaultDialectStack.push(defaultDialect);
  1387. if (dialect.parseOperation(this, opName, op)) {
  1388. if (!dialect.hasParser(opName) && !dialect.hasCustomAssemblyFormat(opName) && dialect.hasAssemblyFormat(opName) && dialect.hasParseOperation(opName) !== false) {
  1389. throw new mlir.Error(`Operation '${op.name}' has assembly format but was handled by custom dialect code.`);
  1390. }
  1391. if (this.match('{')) {
  1392. this.parseAttributeDict(op.attributes);
  1393. }
  1394. op.loc = this.parseLocation() || {};
  1395. this._state.defaultDialectStack.pop();
  1396. return op;
  1397. }
  1398. this._state.defaultDialectStack.pop();
  1399. throw new mlir.Error(`Unsupported custom operation '${op.name}' ${this.location()}`);
  1400. }
  1401. parseCustomOperationName() {
  1402. let opName = this.expect('id');
  1403. if (opName.indexOf('.') === -1) {
  1404. for (let i = this._state.defaultDialectStack.length - 1; i >= 0; i--) {
  1405. const dialect = this._state.defaultDialectStack[i];
  1406. if (dialect) {
  1407. opName = `${dialect}.${opName}`;
  1408. break;
  1409. }
  1410. }
  1411. }
  1412. return opName;
  1413. }
  1414. parseGenericOperation() {
  1415. const op = { name: this.expect('string'), attributes: [], operands: [], regions: [], results: [] };
  1416. return this.parseGenericOperationAfterOpName(op);
  1417. }
  1418. parseOptionalVisibilityKeyword(attributes) {
  1419. if (this.match('id', 'private') || this.match('id', 'public') || this.match('id', 'nested')) {
  1420. const value = this.expect();
  1421. attributes.push({ name: 'sym_visibility', value });
  1422. }
  1423. }
  1424. parseSymbolName(name, attributes) {
  1425. const value = this.expect('@');
  1426. attributes.push({ name, value });
  1427. }
  1428. parseOptionalAttrDictWithKeyword(attributes) {
  1429. if (this.accept('id', 'attributes')) {
  1430. this.parseAttributeDict(attributes);
  1431. }
  1432. }
  1433. parseOptionalAttrDict(attributes) {
  1434. if (this.match('{')) {
  1435. this.parseAttributeDict(attributes);
  1436. }
  1437. }
  1438. parseAttributeDict(attributes) {
  1439. if (this.accept('{')) {
  1440. while (!this.accept('}')) {
  1441. let name = null;
  1442. if (this.match('id') || this.match('string') || this.match('keyword')) {
  1443. name = this.expect();
  1444. } else if (this.match('[')) {
  1445. const arrayValue = this.parseAttribute();
  1446. attributes.push({ name: 'array', value: arrayValue.value });
  1447. this.accept(',');
  1448. continue;
  1449. } else if (!this.match('=') && !this.match(':') && !this.match('}')) {
  1450. throw new mlir.Error(`Expected attribute name or '}', but got '${this._token.value}' ${this.location()}`);
  1451. }
  1452. let attribute = {};
  1453. if (this.accept('=') || this.accept(':')) {
  1454. attribute = this.parseAttribute();
  1455. if (this.accept(':')) {
  1456. attribute.type = this.parseType();
  1457. }
  1458. } else if (name) {
  1459. attribute = { name };
  1460. attributes.push(attribute);
  1461. this.accept(',');
  1462. continue;
  1463. } else {
  1464. break;
  1465. }
  1466. attribute.name = name;
  1467. attributes.push(attribute);
  1468. if (!this.accept(',') && !this.match('}')) {
  1469. throw new mlir.Error(`Expected ',' or '}' after attribute, but got '${this._token.value}' ${this.location()}`);
  1470. }
  1471. }
  1472. }
  1473. }
  1474. parsePropertyDict(attributes) {
  1475. if (this.accept('<')) {
  1476. if (this.accept('{')) {
  1477. while (!this.accept('}')) {
  1478. let name = null;
  1479. if (this.match('id') || this.match('string') || this.match('keyword')) {
  1480. name = this.expect();
  1481. } else if (!this.match('=') && !this.match(':') && !this.match('}')) {
  1482. throw new mlir.Error(`Expected property name or '}', but got '${this._token.value}' ${this.location()}`);
  1483. }
  1484. let attribute = {};
  1485. if (this.accept('=') || this.accept(':')) {
  1486. attribute = this.parseAttribute();
  1487. if (this.accept(':')) {
  1488. attribute.type = this.parseType();
  1489. }
  1490. } else if (name) {
  1491. attribute = { name };
  1492. attributes.push(attribute);
  1493. this.accept(',');
  1494. continue;
  1495. } else {
  1496. break;
  1497. }
  1498. attribute.name = name;
  1499. attributes.push(attribute);
  1500. if (!this.accept(',') && !this.match('}')) {
  1501. throw new mlir.Error(`Expected ',' or '}' after property, but got '${this._token.value}' ${this.location()}`);
  1502. }
  1503. }
  1504. }
  1505. this.expect('>');
  1506. }
  1507. }
  1508. parseRegion(region, entryArguments) {
  1509. region.blocks = Array.isArray(region.blocks) ? region.blocks : [];
  1510. const block = {};
  1511. this.parseBlock(block);
  1512. if (entryArguments && entryArguments.length > 0) {
  1513. block.arguments = entryArguments;
  1514. }
  1515. region.blocks.push(block);
  1516. let hasMultipleBlocks = false;
  1517. while ((this._token.kind === '^' || (this._token.kind === 'id' && this._token.value && this._token.value.startsWith('^'))) && !this.match('}')) {
  1518. hasMultipleBlocks = true;
  1519. const nextBlock = {};
  1520. nextBlock.operations = [];
  1521. nextBlock.arguments = [];
  1522. if (this._token.kind === '^') {
  1523. nextBlock.name = this.expect('^');
  1524. } else {
  1525. nextBlock.name = this.expect('id');
  1526. }
  1527. if (this.accept('(')) {
  1528. while (!this.accept(')')) {
  1529. const value = this.expect('%');
  1530. this.expect(':');
  1531. const type = this.parseType();
  1532. const arg = { value, type };
  1533. const loc = this.parseLocation();
  1534. if (loc) {
  1535. arg.loc = loc;
  1536. }
  1537. nextBlock.arguments.push(arg);
  1538. this.accept(',');
  1539. }
  1540. }
  1541. if (nextBlock.name && nextBlock.name.endsWith(':')) {
  1542. nextBlock.name = nextBlock.name.slice(0, -1);
  1543. } else {
  1544. this.expect(':');
  1545. }
  1546. while (!(this._token.kind === '^' || (this._token.kind === 'id' && this._token.value && this._token.value.startsWith('^'))) && !this.match('}')) {
  1547. const op = this.parseOperation();
  1548. nextBlock.operations.push(op);
  1549. }
  1550. region.blocks.push(nextBlock);
  1551. }
  1552. if (hasMultipleBlocks && this.match('}')) {
  1553. this.expect('}');
  1554. }
  1555. return region;
  1556. }
  1557. parseBlock(block) {
  1558. block.operations = Array.isArray(block.operations) ? block.operations : [];
  1559. block.arguments = Array.isArray(block.arguments) ? block.arguments : [];
  1560. this.expect('{');
  1561. if (this._token.kind === '^' || (this._token.kind === 'id' && this._token.value && this._token.value.startsWith('^'))) {
  1562. if (this._token.kind === '^') {
  1563. block.name = this.expect('^');
  1564. } else {
  1565. block.name = this.expect('id');
  1566. }
  1567. if (this.accept('(')) {
  1568. while (!this.accept(')') && !this.match('^')) {
  1569. const value = this.expect('%');
  1570. this.expect(':');
  1571. const type = this.parseType();
  1572. const arg = { value, type };
  1573. const loc = this.parseLocation();
  1574. if (loc) {
  1575. arg.loc = loc;
  1576. }
  1577. block.arguments.push(arg);
  1578. this.accept(',');
  1579. }
  1580. }
  1581. if (block.name && block.name.endsWith(':')) {
  1582. block.name = block.name.slice(0, -1);
  1583. } else {
  1584. this.expect(':');
  1585. }
  1586. }
  1587. while (!this.accept('}')) {
  1588. if (this._token.kind === '^' || (this._token.kind === 'id' && this._token.value && this._token.value.startsWith('^'))) {
  1589. break;
  1590. }
  1591. const op = this.parseOperation();
  1592. block.operations.push(op);
  1593. }
  1594. block.loc = this.parseLocation();
  1595. return block;
  1596. }
  1597. parseLocation() {
  1598. if (this.accept('keyword', 'loc')) {
  1599. const location = {};
  1600. this.expect('(');
  1601. if (this.match('string')) {
  1602. const text = this.expect('string');
  1603. let content = `"${text}"`;
  1604. if (this.accept('(')) {
  1605. const child = this.parseLocationContent();
  1606. this.expect(')');
  1607. content += `(${child})`;
  1608. } else if (this.accept(':')) {
  1609. const line = this.expect('int');
  1610. content += `:${line}`;
  1611. if (this.accept(':')) {
  1612. const col = this.expect('int');
  1613. content += `:${col}`;
  1614. if (this.accept('id', 'to')) {
  1615. if (this.accept(':')) {
  1616. const endLine = this.expect('int');
  1617. content += ` to:${endLine}`;
  1618. if (this.accept(':')) {
  1619. const endCol = this.expect('int');
  1620. content += `:${endCol}`;
  1621. }
  1622. }
  1623. }
  1624. }
  1625. }
  1626. location.value = `loc(${content})`;
  1627. } else if (this.match('#')) {
  1628. const alias = this.expect();
  1629. location.value = `loc(${alias})`;
  1630. } else if (this.accept('id', 'unknown')) {
  1631. location.value = 'loc(unknown)';
  1632. } else if (this.accept('id', 'callsite')) {
  1633. this.expect('(');
  1634. location.type = 'callsite';
  1635. location.callee = this.parseLocationContent();
  1636. this.expect('id', 'at');
  1637. location.caller = this.parseLocationContent();
  1638. this.expect(')');
  1639. } else if (this.accept('id', 'fused')) {
  1640. // Reference: LocationParser.cpp parseFusedLocation
  1641. location.type = 'fused';
  1642. if (this.accept('<')) {
  1643. location.metadata = this.parseAttribute();
  1644. this.expect('>');
  1645. }
  1646. location.locations = this.parseCommaSeparatedList('square', () => this.parseLocationContent());
  1647. } else {
  1648. throw new mlir.Error(`Unexpected location '${this._token.value}' ${this.location()}`);
  1649. }
  1650. this.expect(')');
  1651. return location;
  1652. }
  1653. return null;
  1654. }
  1655. parseLocationContent() {
  1656. if (this.match('#')) {
  1657. return { alias: this.expect() };
  1658. }
  1659. if (this.match('keyword', 'loc')) {
  1660. return this.parseLocation();
  1661. }
  1662. if (this.accept('id', 'callsite')) {
  1663. const location = { type: 'callsite' };
  1664. this.expect('(');
  1665. location.callee = this.parseLocationContent();
  1666. this.expect('id', 'at');
  1667. location.caller = this.parseLocationContent();
  1668. this.expect(')');
  1669. return location;
  1670. }
  1671. if (this.match('string')) {
  1672. const location = {};
  1673. location.file = this.expect('string');
  1674. if (this.accept(':')) {
  1675. location.line = this.expect('int');
  1676. if (this.accept(':')) {
  1677. location.col = this.expect('int');
  1678. }
  1679. } else if (this.accept('(')) {
  1680. // NameLoc with child location: "name"(child_location)
  1681. location.child = this.parseLocationContent();
  1682. this.expect(')');
  1683. }
  1684. return location;
  1685. }
  1686. throw new mlir.Error(`Expected location content, got '${this._token.value}' ${this.location()}`);
  1687. }
  1688. parseOperationName() {
  1689. switch (this._token.kind) {
  1690. case 'string':
  1691. return this.expect();
  1692. case 'id':
  1693. return this.expect('id');
  1694. default:
  1695. throw new mlir.Error(`Unexpected operation name '${this._token.value}' ${this.location()}`);
  1696. }
  1697. }
  1698. parseArguments() {
  1699. const inputs = [];
  1700. if (this.match('{')) {
  1701. return inputs;
  1702. }
  1703. const open = this.accept('(');
  1704. // eslint-disable-next-line no-unmodified-loop-condition
  1705. while (!this.match(')') && !this.match('->') && !this.match('{') && !this.match('}') && !this.match('=') && !this.match('^') && !(this.match(':') && !open)) {
  1706. const input = {};
  1707. if (this.match('[')) {
  1708. this.expect('[');
  1709. const array = [];
  1710. while (!this.match(']')) {
  1711. if (this.match('%')) {
  1712. array.push(this.expect());
  1713. } else if (this.match('int')) {
  1714. array.push(this.parseInteger());
  1715. } else if (this.match('-')) {
  1716. this.expect('-');
  1717. if (this.match('int')) {
  1718. array.push(-this.parseInteger());
  1719. } else {
  1720. throw new mlir.Error(`Expected integer after '-' in array literal ${this.location()}`);
  1721. }
  1722. } else {
  1723. break;
  1724. }
  1725. if (!this.accept(',')) {
  1726. break;
  1727. }
  1728. }
  1729. this.expect(']');
  1730. input.value = array;
  1731. inputs.push(input);
  1732. if (!this.accept(',')) {
  1733. break;
  1734. }
  1735. continue;
  1736. }
  1737. if (this._token.kind === 'id' && this._token.value !== 'dense' && this._token.value !== 'dense_resource') {
  1738. const identifier = this.expect('id');
  1739. if (this.accept('(')) {
  1740. const args = this.parseArguments();
  1741. for (let i = 0; i < args.length; i++) {
  1742. const arg = args[i];
  1743. arg.name = `${identifier}.${i}`;
  1744. inputs.push(arg);
  1745. }
  1746. // Reference: parseOptionalColonTypeList
  1747. this.resolveOperands(inputs, this.parseOptionalColonTypeList());
  1748. this.expect(')');
  1749. continue;
  1750. } else if (this.match('=')) {
  1751. input.name = identifier;
  1752. this.expect('=');
  1753. } else if (this.match(':')) {
  1754. // Named argument syntax: identifier: value (e.g., init: %init)
  1755. input.name = identifier;
  1756. this.expect(':');
  1757. } else {
  1758. input.value = identifier;
  1759. inputs.push(input);
  1760. if (!this.accept(',')) {
  1761. break;
  1762. }
  1763. continue;
  1764. }
  1765. }
  1766. if (this.match('%')) {
  1767. input.value = this.expect();
  1768. if (open && this.accept(':')) {
  1769. input.type = this.parseType();
  1770. }
  1771. } else if (this.match('keyword', 'loc')) {
  1772. break;
  1773. } else {
  1774. const value = this.parseAttribute();
  1775. input.type = value.type;
  1776. input.value = value.value;
  1777. if (open && this.accept(':')) {
  1778. input.type = this.parseType();
  1779. }
  1780. }
  1781. inputs.push(input);
  1782. if (!this.accept(',') && !this.match('id')) {
  1783. break;
  1784. }
  1785. }
  1786. if (open) {
  1787. this.expect(')');
  1788. }
  1789. return inputs;
  1790. }
  1791. parseElementTypeFromPrefix(prefix, dimensions) {
  1792. if (/^[0-9?]/.test(prefix)) {
  1793. let i = 0;
  1794. while (i < prefix.length) {
  1795. if (prefix[i] === '?') {
  1796. dimensions.push('?');
  1797. i++;
  1798. } else if (/[0-9]/.test(prefix[i])) {
  1799. let numStr = '';
  1800. while (i < prefix.length && /[0-9]/.test(prefix[i])) {
  1801. numStr += prefix[i];
  1802. i++;
  1803. }
  1804. dimensions.push(parseInt(numStr, 10));
  1805. } else {
  1806. break;
  1807. }
  1808. if (i < prefix.length && prefix[i] === 'x') {
  1809. i++;
  1810. } else {
  1811. break;
  1812. }
  1813. }
  1814. prefix = prefix.substring(i);
  1815. }
  1816. // Handle nested types like memref<4xvector<16xf32>> or tensor<20x20xcomplex<f32>>
  1817. if (prefix === 'complex') {
  1818. if (this.accept('<')) {
  1819. const elementType = this.parseType();
  1820. this.expect('>');
  1821. return `complex<${elementType}>`;
  1822. }
  1823. } else if (prefix === 'tensor' || prefix === 'vector' || prefix === 'memref') {
  1824. if (this.accept('<')) {
  1825. const nestedDimInfo = this.parseDimensionListRanked();
  1826. let nestedElementType = null;
  1827. if (nestedDimInfo.elementTypePrefix) {
  1828. nestedElementType = this.parseElementTypeFromPrefix(nestedDimInfo.elementTypePrefix, nestedDimInfo.dimensions);
  1829. if (!nestedElementType) {
  1830. if (this.match('?') || this.match('int')) {
  1831. const moreDims = this.parseDimensionListRanked();
  1832. nestedDimInfo.dimensions.push(...moreDims.dimensions);
  1833. if (moreDims.elementTypePrefix) {
  1834. nestedElementType = this.parseElementTypeFromPrefix(moreDims.elementTypePrefix, nestedDimInfo.dimensions);
  1835. } else {
  1836. nestedElementType = this.parseType();
  1837. }
  1838. } else {
  1839. nestedElementType = this.parseType();
  1840. }
  1841. }
  1842. } else {
  1843. nestedElementType = this.parseType();
  1844. }
  1845. this.expect('>');
  1846. let nestedTypeStr = `${prefix}<`;
  1847. if (nestedDimInfo.unranked) {
  1848. nestedTypeStr += '*x';
  1849. } else if (nestedDimInfo.dimensions.length > 0) {
  1850. nestedTypeStr += `${nestedDimInfo.dimensions.join('x')}x`;
  1851. }
  1852. nestedTypeStr += `${nestedElementType}>`;
  1853. return nestedTypeStr;
  1854. }
  1855. }
  1856. if (prefix.startsWith('!')) {
  1857. // Reuse current token by mutating it (tokens are pooled)
  1858. this._token.kind = '!';
  1859. this._token.value = prefix;
  1860. this._token.text = prefix;
  1861. return this.parseType();
  1862. }
  1863. return prefix;
  1864. }
  1865. // Reference: TypeParser.cpp parseDimensionListRanked
  1866. // allowDynamic: whether to allow '?' for dynamic dimensions (default true)
  1867. // withTrailingX: whether format is NxNxNx (true) or NxNxN (false) (default true)
  1868. parseDimensionListRanked(allowDynamic, withTrailingX) {
  1869. allowDynamic = allowDynamic === false ? false : true;
  1870. withTrailingX = withTrailingX === false ? false : true;
  1871. const dimensions = [];
  1872. if (this.accept('*')) {
  1873. if (this.match('id')) {
  1874. const token = this._token.value;
  1875. if (token === 'x' || token.startsWith('x')) {
  1876. this.expect('id');
  1877. return { unranked: true, dimensions: [], elementTypePrefix: token === 'x' ? null : token.substring(1) };
  1878. }
  1879. }
  1880. return { unranked: true, dimensions: [], elementTypePrefix: null };
  1881. }
  1882. const parseDim = () => {
  1883. if (this.accept('[')) {
  1884. if (this.match('int')) {
  1885. dimensions.push(`[${this.expect('int')}]`);
  1886. } else if (allowDynamic && this.match('?')) {
  1887. dimensions.push('[?]');
  1888. this.expect('?');
  1889. }
  1890. this.expect(']');
  1891. return true;
  1892. } else if (allowDynamic && this.match('?')) {
  1893. dimensions.push('?');
  1894. this.expect('?');
  1895. return true;
  1896. } else if (this.match('int')) {
  1897. const text = this._token.text;
  1898. if (text && text.length > 1 && text[1] === 'x') {
  1899. dimensions.push(0);
  1900. this._tokenizer.resetPointer(1);
  1901. this._token = this._tokenizer.read();
  1902. } else {
  1903. dimensions.push(this.parseInteger());
  1904. }
  1905. return true;
  1906. }
  1907. return false;
  1908. };
  1909. const parseX = () => {
  1910. if (this.match('id')) {
  1911. const token = this._token.value;
  1912. if (token === 'x') {
  1913. this.expect('id', 'x');
  1914. return { consumed: true, elementTypePrefix: null };
  1915. } else if (token.startsWith('x')) {
  1916. this.expect('id');
  1917. const rest = token.substring(1);
  1918. // Check if rest is a dimension or type prefix
  1919. if (/^[0-9]/.test(rest) || (allowDynamic && rest === '?')) {
  1920. // Dimension merged with x - need to parse it
  1921. let remaining = rest;
  1922. while (remaining.length > 0) {
  1923. if (/^[0-9]/.test(remaining)) {
  1924. let i = 0;
  1925. while (i < remaining.length && /[0-9]/.test(remaining[i])) {
  1926. i++;
  1927. }
  1928. const numPart = remaining.substring(0, i);
  1929. dimensions.push(parseInt(numPart, 10));
  1930. remaining = remaining.substring(i);
  1931. if (remaining.startsWith('x')) {
  1932. remaining = remaining.substring(1);
  1933. continue;
  1934. }
  1935. if (remaining.length > 0) {
  1936. return { consumed: true, elementTypePrefix: remaining };
  1937. }
  1938. break;
  1939. } else if (allowDynamic && remaining === '?') {
  1940. dimensions.push('?');
  1941. break;
  1942. } else {
  1943. return { consumed: true, elementTypePrefix: remaining };
  1944. }
  1945. }
  1946. return { consumed: true, elementTypePrefix: null };
  1947. }
  1948. return { consumed: true, elementTypePrefix: rest };
  1949. }
  1950. }
  1951. return { consumed: false, elementTypePrefix: null };
  1952. };
  1953. if (withTrailingX) {
  1954. // Format: NxNxNx... (trailing x)
  1955. while (true) {
  1956. if (!parseDim()) {
  1957. break;
  1958. }
  1959. const xResult = parseX();
  1960. if (!xResult.consumed) {
  1961. break;
  1962. }
  1963. if (xResult.elementTypePrefix) {
  1964. return { unranked: false, dimensions, elementTypePrefix: xResult.elementTypePrefix };
  1965. }
  1966. }
  1967. } else if (parseDim()) {
  1968. while (this.match('id') && this._token.value.startsWith('x')) {
  1969. const xResult = parseX();
  1970. if (!xResult.consumed) {
  1971. break;
  1972. }
  1973. if (xResult.elementTypePrefix) {
  1974. return { unranked: false, dimensions, elementTypePrefix: xResult.elementTypePrefix };
  1975. }
  1976. // If parseX already consumed a merged dimension, don't call parseDim again
  1977. if (!this.match('int') && !(allowDynamic && this.match('?'))) {
  1978. break;
  1979. }
  1980. if (!parseDim()) {
  1981. break;
  1982. }
  1983. }
  1984. }
  1985. return { unranked: false, dimensions, elementTypePrefix: null };
  1986. }
  1987. parseTensorType() {
  1988. this.expect('<');
  1989. const dimInfo = this.parseDimensionListRanked();
  1990. let elementType = null;
  1991. if (dimInfo.elementTypePrefix) {
  1992. elementType = this.parseElementTypeFromPrefix(dimInfo.elementTypePrefix, dimInfo.dimensions);
  1993. if (!elementType) {
  1994. if (this.match('?') || this.match('int')) {
  1995. const moreDims = this.parseDimensionListRanked();
  1996. dimInfo.dimensions.push(...moreDims.dimensions);
  1997. if (moreDims.elementTypePrefix) {
  1998. elementType = this.parseElementTypeFromPrefix(moreDims.elementTypePrefix, dimInfo.dimensions);
  1999. } else {
  2000. elementType = this.parseType();
  2001. }
  2002. } else {
  2003. elementType = this.parseType();
  2004. }
  2005. }
  2006. } else {
  2007. elementType = this.parseType();
  2008. }
  2009. let encoding = null;
  2010. if (this.accept(',')) {
  2011. encoding = this.parseAttribute();
  2012. }
  2013. this.expect('>');
  2014. let typeStr = 'tensor<';
  2015. if (dimInfo.unranked) {
  2016. typeStr += '*x';
  2017. } else if (dimInfo.dimensions.length > 0) {
  2018. typeStr += `${dimInfo.dimensions.join('x')}x`;
  2019. }
  2020. // Convert mlir.Type to string if needed
  2021. typeStr += elementType instanceof mlir.Type ? elementType.toString() : elementType;
  2022. if (encoding) {
  2023. const enc = typeof encoding === 'object' ? JSON.stringify(encoding) : encoding;
  2024. typeStr += `, ${enc}`;
  2025. }
  2026. typeStr += '>';
  2027. return new mlir.Type(typeStr);
  2028. }
  2029. parseMemRefType() {
  2030. this.expect('<');
  2031. const dimInfo = this.parseDimensionListRanked();
  2032. let elementType = null;
  2033. if (dimInfo.elementTypePrefix) {
  2034. elementType = this.parseElementTypeFromPrefix(dimInfo.elementTypePrefix, dimInfo.dimensions);
  2035. if (!elementType) {
  2036. if (this.match('?') || this.match('int')) {
  2037. const moreDims = this.parseDimensionListRanked();
  2038. dimInfo.dimensions.push(...moreDims.dimensions);
  2039. if (moreDims.elementTypePrefix) {
  2040. elementType = this.parseElementTypeFromPrefix(moreDims.elementTypePrefix, dimInfo.dimensions);
  2041. } else {
  2042. elementType = this.parseType();
  2043. }
  2044. } else {
  2045. elementType = this.parseType();
  2046. }
  2047. }
  2048. } else {
  2049. elementType = this.parseType();
  2050. }
  2051. const extras = [];
  2052. while (this.accept(',')) {
  2053. const extra = this.parseAttribute();
  2054. extras.push(extra);
  2055. }
  2056. this.expect('>');
  2057. let typeStr = 'memref<';
  2058. if (dimInfo.unranked) {
  2059. typeStr += '*x';
  2060. } else if (dimInfo.dimensions.length > 0) {
  2061. typeStr += `${dimInfo.dimensions.join('x')}x`;
  2062. }
  2063. typeStr += elementType instanceof mlir.Type ? elementType.toString() : elementType;
  2064. if (extras.length > 0) {
  2065. const content = extras.map((e) => typeof e === 'object' ? JSON.stringify(e) : e).join(', ');
  2066. typeStr += `, ${content}`;
  2067. }
  2068. typeStr += '>';
  2069. return new mlir.Type(typeStr);
  2070. }
  2071. parseVectorType() {
  2072. this.expect('<');
  2073. const dimInfo = this.parseDimensionListRanked();
  2074. let elementType = null;
  2075. if (dimInfo.elementTypePrefix) {
  2076. elementType = this.parseElementTypeFromPrefix(dimInfo.elementTypePrefix, dimInfo.dimensions);
  2077. if (!elementType) {
  2078. if (this.match('?') || this.match('int')) {
  2079. const moreDims = this.parseDimensionListRanked();
  2080. dimInfo.dimensions.push(...moreDims.dimensions);
  2081. if (moreDims.elementTypePrefix) {
  2082. elementType = this.parseElementTypeFromPrefix(moreDims.elementTypePrefix, dimInfo.dimensions);
  2083. } else {
  2084. elementType = this.parseType();
  2085. }
  2086. } else {
  2087. elementType = this.parseType();
  2088. }
  2089. }
  2090. } else {
  2091. elementType = this.parseType();
  2092. }
  2093. this.expect('>');
  2094. let typeStr = 'vector<';
  2095. if (dimInfo.dimensions.length > 0) {
  2096. typeStr += `${dimInfo.dimensions.join('x')}x`;
  2097. }
  2098. typeStr += elementType instanceof mlir.Type ? elementType.toString() : elementType;
  2099. typeStr += '>';
  2100. return new mlir.Type(typeStr);
  2101. }
  2102. parseComplexType() {
  2103. this.expect('<');
  2104. const elementType = this.parseType();
  2105. this.expect('>');
  2106. const elementTypeStr = elementType instanceof mlir.Type ? elementType.toString() : elementType;
  2107. return new mlir.Type(`complex<${elementTypeStr}>`);
  2108. }
  2109. parseTupleType() {
  2110. this.expect('<');
  2111. const types = [];
  2112. while (!this.match('>')) {
  2113. types.push(this.parseType());
  2114. this.accept(',');
  2115. }
  2116. this.expect('>');
  2117. const typeStrs = types.map((t) => t instanceof mlir.Type ? t.toString() : t);
  2118. return new mlir.Type(`tuple<${typeStrs.join(', ')}>`);
  2119. }
  2120. parseCustomTypeWithFallback(typeT) {
  2121. if (typeT && !this.match('!')) {
  2122. if (typeof typeT === 'function') {
  2123. return typeT(this);
  2124. }
  2125. const index = typeT.name.indexOf('.');
  2126. if (index === -1) {
  2127. throw new mlir.Error(`Invalid type name '${typeT.name}.`);
  2128. }
  2129. const dialectName = typeT.name.substring(0, index);
  2130. if (!this._dialects.has(dialectName)) {
  2131. throw new mlir.Error(`Unsupported dialect '${dialectName}' ${this.location()}`);
  2132. }
  2133. const dialect = this._dialects.get(dialectName);
  2134. return dialect.parseCustomTypeWithFallback(this, typeT.type);
  2135. }
  2136. return this.parseType();
  2137. }
  2138. parseCustomAttributeWithFallback(attrT, type) {
  2139. if (attrT) {
  2140. return attrT(this, type);
  2141. }
  2142. return this.parseAttribute();
  2143. }
  2144. parseType() {
  2145. if (this.match('(')) {
  2146. return this.parseFunctionType();
  2147. }
  2148. return this.parseNonFunctionType();
  2149. }
  2150. parseOptionalType() {
  2151. if (this.match('(') || this.match('!')) {
  2152. return this.parseType();
  2153. } else if (this.match('id')) {
  2154. switch (this._token.value) {
  2155. case 'memref':
  2156. case 'tensor':
  2157. case 'complex':
  2158. case 'tuple':
  2159. case 'vector':
  2160. case 'f4E2M1FN':
  2161. case 'f6E2M3FN':
  2162. case 'f6E3M2FN':
  2163. case 'f8E5M2':
  2164. case 'f8E4M3':
  2165. case 'f8E4M3FN':
  2166. case 'f8E5M2FNUZ':
  2167. case 'f8E4M3FNUZ':
  2168. case 'f8E4M3B11FNUZ':
  2169. case 'f8E3M4':
  2170. case 'f8E8M0FNU':
  2171. case 'bf16':
  2172. case 'f16':
  2173. case 'tf32':
  2174. case 'f32':
  2175. case 'f64':
  2176. case 'f80':
  2177. case 'f128':
  2178. case 'index':
  2179. case 'none':
  2180. return this.parseType();
  2181. default:
  2182. // Check for integer types (inttype in reference)
  2183. if (/^[su]?i[0-9]+$/.test(this._token.value)) {
  2184. return this.parseType();
  2185. }
  2186. break;
  2187. }
  2188. }
  2189. return null;
  2190. }
  2191. parseNonFunctionType() {
  2192. if (this.match('id')) {
  2193. const value = this.expect('id');
  2194. switch (value) {
  2195. case 'tensor': return this.parseTensorType();
  2196. case 'vector': return this.parseVectorType();
  2197. case 'memref': return this.parseMemRefType();
  2198. case 'complex': return this.parseComplexType();
  2199. case 'tuple': return this.parseTupleType();
  2200. case 'none': return new mlir.PrimitiveType(value);
  2201. case 'index': return new mlir.PrimitiveType(value);
  2202. case 'bf16':
  2203. case 'f16':
  2204. case 'f32':
  2205. case 'f64':
  2206. case 'f80':
  2207. case 'f128':
  2208. case 'tf32':
  2209. case 'f8E5M2':
  2210. case 'f8E4M3':
  2211. case 'f8E4M3FN':
  2212. case 'f8E5M2FNUZ':
  2213. case 'f8E4M3FNUZ':
  2214. case 'f8E4M3B11FNUZ':
  2215. case 'f8E3M4':
  2216. case 'f8E8M0FNU':
  2217. case 'f4E2M1FN':
  2218. case 'f6E2M3FN':
  2219. case 'f6E3M2FN':
  2220. return new mlir.PrimitiveType(value);
  2221. default:
  2222. if (/^[su]?i[0-9]+$/.test(value)) {
  2223. return new mlir.PrimitiveType(value);
  2224. }
  2225. break;
  2226. }
  2227. }
  2228. if (this.match('!')) {
  2229. return this.parseExtendedType();
  2230. }
  2231. throw new mlir.Error(`Invalid type '${this._token.value}' ${this.location()}`);
  2232. }
  2233. // Reference: DialectSymbolParser.cpp parseExtendedType
  2234. parseExtendedType() {
  2235. return this.parseExtendedSymbol('!', this._state.typeAliasDefinitions, (dialectName, symbolData) => {
  2236. if (!this._dialects.has(dialectName)) {
  2237. throw new mlir.Error(`Unsupported dialect '${dialectName}' ${this.location()}`);
  2238. }
  2239. const dialect = this._dialects.get(dialectName);
  2240. if (symbolData) {
  2241. return new mlir.Type(`!${dialectName}${symbolData}`);
  2242. }
  2243. const type = dialect.parseType(this, dialectName);
  2244. if (type) {
  2245. return type;
  2246. }
  2247. throw new mlir.Error(`Invalid type '!${dialectName}' ${this.location()}`);
  2248. });
  2249. }
  2250. // Reference: DialectSymbolParser.cpp parseExtendedSymbol
  2251. parseExtendedSymbol(prefix, aliases, createSymbol) {
  2252. const token = this.expect(prefix);
  2253. if (aliases.has(token)) {
  2254. const alias = aliases.get(token);
  2255. return alias instanceof mlir.Type ? alias : new mlir.Type(alias);
  2256. }
  2257. const identifier = token.substring(1);
  2258. // Check to see if this is a pretty name (has '.') or verbose form (has '<')
  2259. const dotIndex = identifier.indexOf('.');
  2260. const isPrettyName = dotIndex !== -1 || identifier.endsWith('.') || this.match('.');
  2261. const hasTrailingData = this.match('<');
  2262. // If no '<' and no '.', it's an alias reference
  2263. if (!hasTrailingData && !isPrettyName) {
  2264. throw new mlir.Error(`Undefined symbol alias '${identifier}' ${this.location()}`);
  2265. }
  2266. // Extract dialect name
  2267. let dialectName = null;
  2268. let symbolData = null;
  2269. if (isPrettyName) {
  2270. if (dotIndex !== -1) {
  2271. dialectName = identifier.substring(0, dotIndex);
  2272. } else if (identifier.endsWith('.')) {
  2273. dialectName = identifier.substring(0, identifier.length - 1);
  2274. } else {
  2275. dialectName = identifier;
  2276. this.expect('.');
  2277. }
  2278. if (hasTrailingData) {
  2279. symbolData = this.skip('<', '>');
  2280. }
  2281. } else {
  2282. // Verbose form: !dialect<...>
  2283. dialectName = identifier;
  2284. symbolData = this.skip('<', '>');
  2285. }
  2286. return createSymbol(dialectName, symbolData);
  2287. }
  2288. // Reference: TypeParser.cpp parseFunctionType
  2289. parseFunctionType() {
  2290. const inputs = this.parseTypeListParens();
  2291. this.expect('->');
  2292. const results = this.parseFunctionResultTypes();
  2293. return new mlir.FunctionType(inputs, results);
  2294. }
  2295. // Reference: OpImplementation.h parseCommaSeparatedList
  2296. // Parse a comma-separated list of elements with optional delimiters
  2297. // delimiter: 'none', 'paren', 'square', 'angle', 'brace', 'optionalParen', 'optionalSquare', 'optionalAngle', 'optionalBrace'
  2298. // parseElement: function that parses a single element, returns the element or null to stop
  2299. // Returns array of parsed elements
  2300. parseCommaSeparatedList(delimiter, parseElement) {
  2301. const results = [];
  2302. const delimiters = {
  2303. none: [null, null],
  2304. paren: ['(', ')'],
  2305. square: ['[', ']'],
  2306. angle: ['<', '>'],
  2307. brace: ['{', '}'],
  2308. optionalParen: ['(', ')'],
  2309. optionalSquare: ['[', ']'],
  2310. optionalAngle: ['<', '>'],
  2311. optionalBrace: ['{', '}']
  2312. };
  2313. const [open, close] = delimiters[delimiter] || [null, null];
  2314. const isOptional = delimiter && delimiter.startsWith('optional');
  2315. // Handle opening delimiter
  2316. if (open) {
  2317. if (isOptional) {
  2318. if (!this.accept(open)) {
  2319. return results; // Optional delimiter not present, return empty
  2320. }
  2321. } else {
  2322. this.expect(open);
  2323. }
  2324. // Check for empty list
  2325. if (close && this.accept(close)) {
  2326. return results;
  2327. }
  2328. }
  2329. // Parse first element
  2330. const first = parseElement();
  2331. if (first !== null && first !== undefined) {
  2332. results.push(first);
  2333. }
  2334. // Parse remaining elements
  2335. while (this.accept(',')) {
  2336. const elem = parseElement();
  2337. if (elem !== null && elem !== undefined) {
  2338. results.push(elem);
  2339. }
  2340. }
  2341. // Handle closing delimiter
  2342. if (close) {
  2343. this.expect(close);
  2344. }
  2345. return results;
  2346. }
  2347. // Reference: TypeParser.cpp parseFunctionResultTypes
  2348. // Parse function result types: (type, type) OR single non-function type
  2349. parseFunctionResultTypes() {
  2350. if (this.match('(')) {
  2351. return this.parseTypeListParens();
  2352. }
  2353. // Parse single non-function type
  2354. const type = this.parseNonFunctionType();
  2355. return type ? [type] : [];
  2356. }
  2357. // Reference: OpImplementation.h parseColonType
  2358. // Parse colon followed by single type: : type
  2359. parseColonType() {
  2360. this.expect(':');
  2361. return this.parseType();
  2362. }
  2363. // Reference: OpImplementation.h parseColonTypeList
  2364. // Parse colon followed by type list: : type, type, type
  2365. parseColonTypeList() {
  2366. this.expect(':');
  2367. return this.parseTypeList();
  2368. }
  2369. // Reference: OpImplementation.h parseOptionalColonTypeList
  2370. // Parse optional colon followed by type list
  2371. parseOptionalColonTypeList() {
  2372. if (this.accept(':')) {
  2373. return this.parseTypeList();
  2374. }
  2375. return [];
  2376. }
  2377. // Reference: OpImplementation.h parseArrowTypeList
  2378. // Parse arrow followed by type list: -> type, type
  2379. parseArrowTypeList() {
  2380. this.expect('->');
  2381. return this.parseFunctionResultTypes();
  2382. }
  2383. // Reference: AsmParserImpl.h parseOptionalArrowTypeList
  2384. // Parse optional arrow followed by function result types
  2385. parseOptionalArrowTypeList() {
  2386. if (this.accept('->')) {
  2387. return this.parseFunctionResultTypes();
  2388. }
  2389. return [];
  2390. }
  2391. // Reference: OpImplementation.h parseOptionalArrow
  2392. // Parse '->' token if present, returns true if found
  2393. parseOptionalArrow() {
  2394. return this.accept('->');
  2395. }
  2396. // Helper to parse optional arrow followed by result types and populate op.results
  2397. // Parses: -> type or -> (type, type, ...)
  2398. // Returns true if arrow was found, false otherwise
  2399. parseOptionalArrowResultTypes(op) {
  2400. if (!this.accept('->')) {
  2401. return false;
  2402. }
  2403. const types = this.parseFunctionResultTypes();
  2404. this.resolveOperands(op.results, types);
  2405. return true;
  2406. }
  2407. // Matches call_interface_impl::parseFunctionSignature from CallInterfaces.cpp
  2408. // Parses: (type {attr}, type {attr}, ...) -> (type {attr}, ...)
  2409. // Returns { argTypes: [...], argAttrs: [...], resultTypes: [...], resultAttrs: [...] }
  2410. parseFunctionSignature(argOperands) {
  2411. const argTypes = [];
  2412. const argAttrs = [];
  2413. const resultTypes = [];
  2414. const resultAttrs = [];
  2415. this.expect('(');
  2416. if (!this.match(')')) {
  2417. this.parseTypeAndAttrList(argTypes, argAttrs, argOperands);
  2418. }
  2419. this.expect(')');
  2420. if (this.accept('->')) {
  2421. this.parseFunctionResultList(resultTypes, resultAttrs);
  2422. }
  2423. return { argTypes, argAttrs, resultTypes, resultAttrs };
  2424. }
  2425. // Reference: CallInterfaces.cpp parseTypeAndAttrList
  2426. // Parses: type {attr}, type {attr}, ...
  2427. parseTypeAndAttrList(types, attrs, operands) {
  2428. let index = 0;
  2429. this.parseCommaSeparatedList('none', () => {
  2430. const type = this.parseType();
  2431. types.push(type);
  2432. // Parse optional attribute dict after each type
  2433. if (this.match('{')) {
  2434. const attrList = [];
  2435. this.parseAttributeDict(attrList);
  2436. attrs.push(attrList);
  2437. // Associate attrs with operand if available
  2438. if (operands && index < operands.length) {
  2439. operands[index].attributes = attrList;
  2440. }
  2441. } else {
  2442. attrs.push(null);
  2443. }
  2444. index++;
  2445. return true;
  2446. });
  2447. }
  2448. // Reference: CallInterfaces.cpp call_interface_impl::parseFunctionResultList
  2449. // Parses: type or (type {attr}, type {attr}, ...)
  2450. parseFunctionResultList(types, attrs) {
  2451. // Try to parse with parens first
  2452. if (this.accept('(')) {
  2453. // Special case for empty parens ()
  2454. if (this.accept(')')) {
  2455. return;
  2456. }
  2457. this.parseTypeAndAttrList(types, attrs);
  2458. this.expect(')');
  2459. } else {
  2460. // Without parens, parse a single type (per reference impl)
  2461. const type = this.parseType();
  2462. types.push(type);
  2463. attrs.push(null);
  2464. }
  2465. }
  2466. parseSSAUse(allowResultNumber) {
  2467. allowResultNumber = allowResultNumber === undefined ? true : allowResultNumber;
  2468. const result = {};
  2469. result.name = this._token.value;
  2470. result.number = 0;
  2471. result.location = this.location();
  2472. this.expect('%');
  2473. if (this.match('#')) {
  2474. if (!allowResultNumber) {
  2475. throw new mlir.Error(`Result number not allowed in argument list ${this.location()}`);
  2476. }
  2477. const hashValue = this.expect('#');
  2478. // Extract the number from the hash identifier (e.g., '#0' -> 0)
  2479. const numberStr = hashValue.substring(1);
  2480. const number = parseInt(numberStr, 10);
  2481. if (isNaN(number)) {
  2482. throw new mlir.Error(`Invalid SSA value result number ${this.location()}`);
  2483. }
  2484. result.number = number;
  2485. }
  2486. return result;
  2487. }
  2488. parseOperand(allowResultNumber) {
  2489. allowResultNumber = allowResultNumber === undefined ? true : allowResultNumber;
  2490. return this.parseSSAUse(allowResultNumber);
  2491. }
  2492. parseOptionalOperand(allowResultNumber = true) {
  2493. allowResultNumber = allowResultNumber === undefined ? true : allowResultNumber;
  2494. if (this.match('%')) {
  2495. return this.parseOperand(allowResultNumber);
  2496. }
  2497. return null;
  2498. }
  2499. // Reference: AttributeParser.cpp parseAttribute(Type type = {})
  2500. // When type is null (default), parse `: type` suffix for int/float/string
  2501. // When type is provided, use it directly without parsing suffix
  2502. parseAttribute(type = null) {
  2503. // Parse an AffineMap or IntegerSet attribute.
  2504. if (this.match('id', 'affine_map') || this.match('id', 'affine_set')) {
  2505. const name = this.expect();
  2506. const args = this.skip('<', '>');
  2507. return { value: `${name}${args}` };
  2508. }
  2509. // Parse an array attribute.
  2510. // Reference: AttributeParser.cpp lines 73-84
  2511. if (this.match('[')) {
  2512. this.expect('[');
  2513. const elements = [];
  2514. while (!this.accept(']')) {
  2515. // Reference: elements.push_back(parseAttribute());
  2516. const item = this.parseAttribute();
  2517. elements.push(item.value);
  2518. this.accept(',');
  2519. }
  2520. // Handle special `[a] x [b]` syntax (dialect-specific)
  2521. if (this.accept('id', 'x')) {
  2522. const value = [Array.from(elements)];
  2523. this.expect('[');
  2524. const second = [];
  2525. while (!this.accept(']')) {
  2526. const item = this.parseAttribute();
  2527. second.push(item.value);
  2528. this.accept(',');
  2529. }
  2530. value.push(second);
  2531. return { value };
  2532. }
  2533. return { value: elements };
  2534. }
  2535. // Parse a boolean attribute.
  2536. if (this.match('boolean')) {
  2537. const value = this.expect();
  2538. return { value, type: new mlir.PrimitiveType('i1') };
  2539. }
  2540. // Parse a dense elements attribute.
  2541. // Reference: AttributeParser.cpp parseDenseElementsAttr(Type attrType)
  2542. // Format: dense<literal> : type (type suffix only if attrType not provided)
  2543. if (this.match('id', 'dense')) {
  2544. this.expect('id');
  2545. this.expect('<');
  2546. let value = null;
  2547. if (!this.accept('>')) {
  2548. const literalParser = new mlir.TensorLiteralParser(this);
  2549. value = literalParser.parse(/* allowHex */ true);
  2550. this.expect('>');
  2551. }
  2552. // Reference: if (!attrType) { parseToken(Token::colon); attrType = parseType(); }
  2553. if (!type) {
  2554. this.expect(':');
  2555. type = this.parseType();
  2556. }
  2557. return { value, type };
  2558. }
  2559. // Parse a dense resource elements attribute.
  2560. // Reference: AttributeParser.cpp parseDenseResourceElementsAttr(Type attrType)
  2561. // Format: dense_resource<handle> : type (type suffix only if attrType not provided)
  2562. if (this.match('id', 'dense_resource')) {
  2563. this.expect('id');
  2564. this.expect('<');
  2565. const value = this.expect();
  2566. this.expect('>');
  2567. if (!type) {
  2568. this.expect(':');
  2569. type = this.parseType();
  2570. }
  2571. return { value, type };
  2572. }
  2573. // Parse a dense array attribute.
  2574. if (this.match('id', 'array')) {
  2575. this.expect('id');
  2576. this.expect('<');
  2577. const arrayType = this.parseType();
  2578. const arrayValues = [];
  2579. if (this.accept(':')) {
  2580. while (!this.match('>')) {
  2581. const val = this.parseAttribute();
  2582. arrayValues.push(val.value === undefined ? val : val.value);
  2583. this.accept(',');
  2584. }
  2585. }
  2586. this.expect('>');
  2587. return { value: arrayValues, type: arrayType };
  2588. }
  2589. // Parse a dictionary attribute.
  2590. if (this.match('{')) {
  2591. const attributes = [];
  2592. this.parseAttributeDict(attributes);
  2593. const value = {};
  2594. for (const attribute of attributes) {
  2595. value[attribute.name] = attribute.value;
  2596. }
  2597. return { value };
  2598. }
  2599. // Parse an extended attribute, i.e. alias or dialect attribute.
  2600. if (this.match('#')) {
  2601. return this.parseExtendedAttr();
  2602. }
  2603. const parseType = (type, defaultType) => {
  2604. if (type) {
  2605. return type;
  2606. }
  2607. return this.accept(':') ? this.parseType() : defaultType;
  2608. };
  2609. // Parse floating point attribute.
  2610. // Reference: AttributeParser.cpp parseFloatAttr
  2611. if (this.match('float')) {
  2612. const value = this.expect();
  2613. type = parseType(type, new mlir.PrimitiveType('f64'));
  2614. return { value, type };
  2615. }
  2616. // Parse integer attribute.
  2617. // Reference: AttributeParser.cpp parseDecOrHexAttr lines 406-418
  2618. if (this.match('int')) {
  2619. const value = this.expect();
  2620. type = parseType(type, new mlir.PrimitiveType('i64'));
  2621. return { value, type };
  2622. }
  2623. // Parse negative number.
  2624. // Reference: AttributeParser.cpp parseAttribute case Token::minus
  2625. if (this.match('keyword', '-')) {
  2626. this.expect();
  2627. if (this.match('int')) {
  2628. const value = `-${this.expect()}`;
  2629. type = parseType(type, new mlir.PrimitiveType('i64'));
  2630. return { value, type };
  2631. }
  2632. if (this.match('float')) {
  2633. const value = `-${this.expect()}`;
  2634. type = parseType(type, new mlir.PrimitiveType('f64'));
  2635. return { value, type };
  2636. }
  2637. throw new mlir.Error(`Expected integer or float after '-' ${this.location()}`);
  2638. }
  2639. // Parse a location attribute.
  2640. if (this.match('keyword', 'loc')) {
  2641. return this.parseLocation();
  2642. }
  2643. // Parse a sparse elements attribute.
  2644. // Reference: AttributeParser.cpp parseSparseElementsAttr(Type attrType)
  2645. // Format: sparse<indices, values> : type (type suffix only if attrType not provided)
  2646. if (this.match('id', 'sparse')) {
  2647. this.expect('id');
  2648. this.expect('<');
  2649. let indices = null;
  2650. let values = null;
  2651. // Parse empty sparse: sparse<>
  2652. if (!this.accept('>')) {
  2653. // Parse indices (no hex allowed)
  2654. const indiceParser = new mlir.TensorLiteralParser(this);
  2655. indices = indiceParser.parse(/* allowHex */ false);
  2656. this.expect(',');
  2657. // Parse values (hex allowed)
  2658. const valuesParser = new mlir.TensorLiteralParser(this);
  2659. values = valuesParser.parse(/* allowHex */ true);
  2660. this.expect('>');
  2661. }
  2662. let sparseType = type;
  2663. if (!sparseType) {
  2664. this.expect(':');
  2665. sparseType = this.parseType();
  2666. }
  2667. return { value: { indices, values }, type: sparseType };
  2668. }
  2669. // Parse a strided layout attribute.
  2670. if (this.match('id', 'strided')) {
  2671. this.expect('id');
  2672. const body = this.skip('<', '>');
  2673. return { value: `strided${body}`, type: 'strided' };
  2674. }
  2675. // Parse a distinct attribute.
  2676. // Reference: AttributeParser.cpp parseDistinctAttr
  2677. // Format: distinct[id]<attribute>
  2678. if (this.match('id', 'distinct')) {
  2679. this.expect('id');
  2680. const id = this.skip('[', ']');
  2681. this.expect('<');
  2682. let referencedAttr = null;
  2683. if (!this.match('>')) {
  2684. // Reference: referencedAttr = parseAttribute(type);
  2685. referencedAttr = this.parseAttribute();
  2686. }
  2687. this.expect('>');
  2688. return { value: `distinct${id}`, referencedAttr, type: 'distinct' };
  2689. }
  2690. // Parse a string attribute.
  2691. // Reference: AttributeParser.cpp case Token::string lines 160-168
  2692. if (this.match('string')) {
  2693. const value = this.expect();
  2694. type = parseType(type, new mlir.PrimitiveType('string'));
  2695. return { value, type };
  2696. }
  2697. // Parse a symbol reference attribute.
  2698. if (this.match('@')) {
  2699. const value = this.expect();
  2700. return { value };
  2701. }
  2702. // Parse a 'unit' attribute.
  2703. if (this.match('id', 'unit')) {
  2704. this.expect('id');
  2705. return { value: 'unit', type: new mlir.PrimitiveType('unit') };
  2706. }
  2707. // Parse a type attribute.
  2708. if (this._token.kind === 'id') {
  2709. const tokenValue = this._token.value;
  2710. if (tokenValue === 'tensor' || tokenValue === 'vector' || tokenValue === 'memref' ||
  2711. tokenValue === 'none' || tokenValue === 'index' || /^[su]?i[0-9]+$/.test(tokenValue) ||
  2712. /^f[0-9]+$/.test(tokenValue) || tokenValue === 'bf16' || tokenValue === 'tf32' ||
  2713. tokenValue.startsWith('f8')) {
  2714. const type = this.parseType();
  2715. return { value: type, type: new mlir.PrimitiveType('type') };
  2716. }
  2717. }
  2718. if (this.match('!')) {
  2719. const type = this.parseType();
  2720. return { value: type, type: new mlir.PrimitiveType('type') };
  2721. }
  2722. // Handle SSA value references.
  2723. if (this.match('%')) {
  2724. const value = this.expect();
  2725. return { value };
  2726. }
  2727. // Handle DEFAULT identifier.
  2728. if (this.match('id', 'DEFAULT')) {
  2729. const value = this.expect();
  2730. return { value };
  2731. }
  2732. // Handle bare <...> attribute (dialect-specific).
  2733. if (this.match('<')) {
  2734. const value = this.skip('<', '>');
  2735. return { value };
  2736. }
  2737. // Handle other identifiers.
  2738. if (this.match('id')) {
  2739. const value = this.expect('id');
  2740. if (this.match('<')) {
  2741. return { value: value + this.skip('<', '>') };
  2742. }
  2743. return { value };
  2744. }
  2745. // Reference: AttributeParser.cpp default case - try to parse a type attribute
  2746. const typeAttr = this.parseOptionalType();
  2747. if (typeAttr) {
  2748. return { value: typeAttr, type: 'type' };
  2749. }
  2750. throw new mlir.Error(`Unexpected attribute token '${this._token.value}' ${this.location()}`);
  2751. }
  2752. parseExtendedAttr() {
  2753. const name = this.expect('#');
  2754. let value = name;
  2755. if (this.match('<')) {
  2756. const body = this.skip('<', '>');
  2757. value = name + body;
  2758. } else if (this.match('(')) {
  2759. const body = this.skip('(', ')');
  2760. value = name + body;
  2761. }
  2762. // Parse an optional trailing colon type.
  2763. // Reference: DialectSymbolParser.cpp line 264-267
  2764. let type = null;
  2765. if (this.accept(':')) {
  2766. type = this.parseType();
  2767. }
  2768. return { value, type };
  2769. }
  2770. parseOptionalAttribute(type) {
  2771. switch (this._token.kind) {
  2772. case '@':
  2773. case '%':
  2774. case 'int':
  2775. case 'float':
  2776. case '#':
  2777. case '[':
  2778. case '{':
  2779. case '<':
  2780. case 'string':
  2781. case 'boolean':
  2782. return this.parseAttribute(type);
  2783. case 'keyword':
  2784. if (this._token.value === '-' || this._token.value === 'loc') {
  2785. return this.parseAttribute(type);
  2786. }
  2787. return null;
  2788. case 'id':
  2789. if (this._token.value === 'affine_map' || this._token.value === 'affine_set' ||
  2790. this._token.value === 'dense' || this._token.value === 'dense_resource' ||
  2791. this._token.value === 'array' || this._token.value === 'sparse' ||
  2792. this._token.value === 'strided' || this._token.value === 'distinct' ||
  2793. this._token.value === 'unit' || this._token.value === 'DEFAULT') {
  2794. return this.parseAttribute(type);
  2795. }
  2796. // Fall through to default for type attributes
  2797. default: {
  2798. const value = this.parseOptionalType(type);
  2799. if (value) {
  2800. return { value, type: 'type' };
  2801. }
  2802. return null;
  2803. }
  2804. }
  2805. }
  2806. parseOptionalSymbolName() {
  2807. if (this.match('@')) {
  2808. const value = this.expect('@');
  2809. return value.substring(1);
  2810. }
  2811. return null;
  2812. }
  2813. parseKeyword() {
  2814. if (this._token.kind === 'id') {
  2815. return this.expect('id');
  2816. }
  2817. return null;
  2818. }
  2819. parseOptionalKeyword(values) {
  2820. if (this._token.kind === 'id') {
  2821. if (values.some((v) => this._token.value === v)) {
  2822. return this.expect('id');
  2823. }
  2824. }
  2825. return null;
  2826. }
  2827. // Reference: OpImplementation.h parseInteger
  2828. // Parse an integer value from the stream
  2829. parseInteger() {
  2830. const value = this.expect('int');
  2831. return parseInt(value, 10);
  2832. }
  2833. // Reference: OpImplementation.h parseOptionalInteger
  2834. // Parse an optional integer value from the stream
  2835. parseOptionalInteger() {
  2836. if (this.match('int')) {
  2837. return this.parseInteger();
  2838. }
  2839. return null;
  2840. }
  2841. getToken() {
  2842. return this._token;
  2843. }
  2844. match(kind, value) {
  2845. return (this._token.kind === kind && (!value || this._token.value === value));
  2846. }
  2847. expect(kind, value) {
  2848. if (kind && this._token.kind !== kind) {
  2849. throw new mlir.Error(`Expected token of type '${kind}', but got '${this._token.value}' ${this.location()}`);
  2850. }
  2851. if (value && this._token.value !== value) {
  2852. throw new mlir.Error(`Expected token with value '${value}', but got '${this._token.value}' ${this.location()}`);
  2853. }
  2854. const token = this._token;
  2855. this._token = this._tokenizer.read();
  2856. return token.value;
  2857. }
  2858. accept(kind, value) {
  2859. if (this.match(kind, value)) {
  2860. return this.expect();
  2861. }
  2862. return null;
  2863. }
  2864. get token() {
  2865. return this._token;
  2866. }
  2867. location() {
  2868. return this._tokenizer.location();
  2869. }
  2870. };
  2871. // Reference: AttributeParser.cpp TensorLiteralParser
  2872. // Parse tensor literal elements for dense<...> and sparse<...>
  2873. mlir.TensorLiteralParser = class {
  2874. constructor(parser) {
  2875. this._parser = parser;
  2876. this._storage = []; // Flat storage for all elements (matches reference)
  2877. }
  2878. // Reference: TensorLiteralParser::parse(bool allowHex)
  2879. parse(allowHex) {
  2880. // If hex is allowed, check for a string literal.
  2881. if (allowHex && this._parser.match('string')) {
  2882. const hexStr = this._parser.expect();
  2883. if (hexStr.startsWith('"0x') || hexStr.startsWith('0x')) {
  2884. const cleanHex = hexStr.replace(/"/g, '').substring(2);
  2885. const data = new Uint8Array(cleanHex.length >> 1);
  2886. for (let i = 0; i < data.length; i++) {
  2887. const index = i << 1;
  2888. data[i] = parseInt(cleanHex.substring(index, index + 2), 16);
  2889. }
  2890. return data;
  2891. }
  2892. this._storage.push(hexStr);
  2893. return this._storage;
  2894. }
  2895. // Otherwise, parse a list or an individual element.
  2896. if (this._parser.match('[')) {
  2897. this.parseList();
  2898. } else {
  2899. this.parseElement();
  2900. }
  2901. return this._storage;
  2902. }
  2903. // Reference: TensorLiteralParser::parseList()
  2904. // Parse nested lists, storing elements flat in storage
  2905. parseList() {
  2906. this._parser.expect('[');
  2907. while (!this._parser.accept(']')) {
  2908. if (this._parser.match('[')) {
  2909. this.parseList();
  2910. } else {
  2911. this.parseElement();
  2912. }
  2913. this._parser.accept(',');
  2914. }
  2915. }
  2916. // Reference: TensorLiteralParser::parseElement()
  2917. // Parse a single element and store it in the flat storage
  2918. parseElement() {
  2919. // Parse a complex element (real, imag)
  2920. if (this._parser.accept('(')) {
  2921. this.parseElement();
  2922. this._parser.expect(',');
  2923. this.parseElement();
  2924. this._parser.expect(')');
  2925. return;
  2926. }
  2927. // Parse a boolean element
  2928. if (this._parser.match('boolean')) {
  2929. this._storage.push(this._parser.expect());
  2930. return;
  2931. }
  2932. // Parse a negative number
  2933. if (this._parser.accept('keyword', '-')) {
  2934. if (this._parser.match('int')) {
  2935. this._storage.push(`-${this._parser.expect()}`);
  2936. return;
  2937. }
  2938. if (this._parser.match('float')) {
  2939. this._storage.push(`-${this._parser.expect()}`);
  2940. return;
  2941. }
  2942. throw new mlir.Error(`Expected integer or float after '-' ${this._parser.location()}`);
  2943. }
  2944. // Parse a number (int or float)
  2945. if (this._parser.match('int') || this._parser.match('float')) {
  2946. this._storage.push(this._parser.expect());
  2947. return;
  2948. }
  2949. // Parse a string element
  2950. if (this._parser.match('string')) {
  2951. this._storage.push(this._parser.expect());
  2952. return;
  2953. }
  2954. throw new mlir.Error(`Expected element literal of primitive type ${this._parser.location()}`);
  2955. }
  2956. };
  2957. mlir.BytecodeReader = class {
  2958. constructor(reader) {
  2959. this._reader = new mlir.BinaryReader(reader);
  2960. }
  2961. read() {
  2962. const reader = this._reader;
  2963. reader.read(4); // signature 'ML\xEFR'
  2964. this.version = reader.varint().toNumber();
  2965. this.producer = reader.string();
  2966. this.sections = new Map();
  2967. while (reader.position < reader.length) {
  2968. // https://mlir.llvm.org/docs/BytecodeFormat/
  2969. // https://github.com/llvm/llvm-project/blob/main/mlir/lib/Bytecode/Reader/BytecodeReader.cpp
  2970. const sectionIDAndHasAlignment = reader.byte();
  2971. const sectionID = sectionIDAndHasAlignment & 0x7F;
  2972. const length = reader.varint().toNumber();
  2973. const hasAlignment = sectionIDAndHasAlignment & 0x80;
  2974. if (sectionID >= 9) {
  2975. throw new mlir.Error(`Unsupported section identifier '${sectionID}'.`);
  2976. }
  2977. if (hasAlignment) {
  2978. const alignment = reader.varint();
  2979. reader.skip(alignment);
  2980. }
  2981. const offset = reader.position;
  2982. reader.skip(length);
  2983. this.sections.set(sectionID, { start: offset, end: reader.position });
  2984. }
  2985. if (!this.sections.has(0) || !this.sections.has(1) ||
  2986. !this.sections.has(2) || !this.sections.has(3) ||
  2987. !this.sections.has(4) || (this.version >= 5 && !this.sections.has(8))) {
  2988. throw new mlir.Error('Missing required section.');
  2989. }
  2990. this._parseStringSection();
  2991. if (this.sections.has(8)) {
  2992. this._parsePropertiesSection();
  2993. }
  2994. this._parseDialectSection();
  2995. this._parseResourceSection();
  2996. this._parseAttrTypeSection();
  2997. }
  2998. _parseStringSection() {
  2999. const section = this.sections.get(0);
  3000. const reader = this._reader;
  3001. reader.seek(section.start);
  3002. const lengths = new Array(reader.varint().toNumber());
  3003. for (let i = 0; i < lengths.length; i++) {
  3004. lengths[i] = reader.varint().toNumber();
  3005. }
  3006. const decoder = new TextDecoder('utf-8');
  3007. this.strings = new Array(lengths.length);
  3008. for (let i = 0; i < this.strings.length; i++) {
  3009. const size = lengths[lengths.length - 1 - i];
  3010. const buffer = reader.read(size);
  3011. this.strings[i] = decoder.decode(buffer);
  3012. }
  3013. if (reader.position !== section.end) {
  3014. throw new mlir.Error(`Invalid string section size.`);
  3015. }
  3016. }
  3017. _parseDialectSection() {
  3018. const section = this.sections.get(1);
  3019. const reader = this._reader;
  3020. reader.seek(section.start);
  3021. const numDialects = reader.varint().toNumber();
  3022. this.dialects = new Array(numDialects);
  3023. for (let i = 0; i < this.dialects.length; i++) {
  3024. this.dialects[i] = {};
  3025. if (this.version < 1) { // kDialectVersioning
  3026. const entryIdx = reader.varint().toNumber();
  3027. this.dialects[i].name = this.strings[entryIdx];
  3028. continue;
  3029. }
  3030. const nameAndIsVersioned = reader.varint();
  3031. const dialectNameIdx = (nameAndIsVersioned >> 1n).toNumber();
  3032. this.dialects[i].name = this.strings[dialectNameIdx];
  3033. if (nameAndIsVersioned & 1n) {
  3034. const size = reader.varint().toNumber();
  3035. this.dialects[i].version = reader.read(size);
  3036. }
  3037. }
  3038. let numOps = -1;
  3039. this.opNames = [];
  3040. if (this.version > 4) { // kElideUnknownBlockArgLocation
  3041. numOps = reader.varint().toNumber();
  3042. this.opNames = new Array(numOps);
  3043. }
  3044. let i = 0;
  3045. while (reader.position < section.end) {
  3046. const dialect = this.dialects[reader.varint().toNumber()];
  3047. const numEntries = reader.varint().toNumber();
  3048. for (let j = 0; j < numEntries; j++) {
  3049. const opName = {};
  3050. if (this.version < 5) { // kNativePropertiesEncoding
  3051. opName.name = this.strings[reader.varint().toNumber()];
  3052. opName.dialect = dialect;
  3053. } else {
  3054. const nameAndIsRegistered = reader.varint();
  3055. opName.name = this.strings[(nameAndIsRegistered >> 1n).toNumber()];
  3056. opName.dialect = dialect;
  3057. opName.isRegistered = (nameAndIsRegistered & 1n) === 1n;
  3058. }
  3059. if (numOps < 0) {
  3060. this.opNames.push(opName);
  3061. } else {
  3062. this.opNames[i++] = opName;
  3063. }
  3064. }
  3065. }
  3066. if (reader.position !== section.end) {
  3067. throw new mlir.Error(`Invalid dialect section size.`);
  3068. }
  3069. }
  3070. _parseResourceSection() {
  3071. const section = this.sections.get(6);
  3072. const reader = this._reader;
  3073. reader.seek(section.start);
  3074. const numExternalResourceGroups = reader.varint().toNumber();
  3075. if (numExternalResourceGroups > 0) {
  3076. throw new mlir.Error(`Unsupported resource section.`);
  3077. }
  3078. /*
  3079. for (let i = 0; i < numExternalResourceGroups; i++) {
  3080. const numResources = reader.varint().toNumber();
  3081. for (let j = 0; j < numResources; j++) {
  3082. const resource = {};
  3083. resource.key = this.strings[reader.varint().toNumber()];
  3084. resource.offset = reader.varint().toNumber();
  3085. resource.kind = reader.byte();
  3086. }
  3087. }
  3088. */
  3089. if (reader.position !== section.end) {
  3090. throw new mlir.Error(`Invalid dialect section size.`);
  3091. }
  3092. }
  3093. _parseAttrTypeSection() {
  3094. const section = this.sections.get(3);
  3095. const reader = this._reader;
  3096. reader.seek(section.start);
  3097. this.attributes = new Array(reader.varint().toNumber());
  3098. this.types = new Array(reader.varint().toNumber());
  3099. let offset = 0;
  3100. const parseEntries = (range) => {
  3101. for (let i = 0; i < range.length;) {
  3102. const dialect = this.dialects[reader.varint().toNumber()];
  3103. const numEntries = reader.varint().toNumber();
  3104. for (let j = 0; j < numEntries; j++) {
  3105. const entry = {};
  3106. const entrySizeWithFlag = reader.varint();
  3107. entry.hasCustomEncoding = (entrySizeWithFlag & 1n) === 1n;
  3108. entry.size = (entrySizeWithFlag >> 1n).toNumber();
  3109. entry.offset = offset;
  3110. entry.dialect = dialect;
  3111. offset += entry.size;
  3112. range[i++] = entry;
  3113. }
  3114. }
  3115. };
  3116. parseEntries(this.attributes);
  3117. parseEntries(this.types);
  3118. if (reader.position !== section.end) {
  3119. throw new mlir.Error(`Invalid dialect section size.`);
  3120. }
  3121. offset = this.sections.get(2).start;
  3122. const parseCustomEntry = (/* entry, reader, entryType */) => {
  3123. };
  3124. const parseAsmEntry = (/* entry, reader, entryType */) => {
  3125. };
  3126. const resolveEntries = (range, entryType) => {
  3127. for (const entry of this.attributes) {
  3128. reader.seek(offset + entry.offset);
  3129. if (entry.hasCustomEncoding) {
  3130. parseCustomEntry(entry, reader);
  3131. } else {
  3132. parseAsmEntry(entry, reader, entryType);
  3133. }
  3134. }
  3135. };
  3136. resolveEntries(this.attributes, 'attribute');
  3137. resolveEntries(this.types, 'type');
  3138. }
  3139. _parsePropertiesSection() {
  3140. const section = this.sections.get(8);
  3141. const reader = this._reader;
  3142. reader.seek(section.start);
  3143. const count = reader.varint().toNumber();
  3144. const offsetTable = new Array(count);
  3145. for (let i = 0; i < offsetTable.length; i++) {
  3146. const offset = reader.position;
  3147. const size = reader.varint().toNumber();
  3148. const data = reader.read(size);
  3149. offsetTable[i] = { offset, data };
  3150. }
  3151. if (reader.position !== section.end) {
  3152. throw new mlir.Error(`Invalid properties section size.`);
  3153. }
  3154. }
  3155. };
  3156. mlir.BinaryReader = class {
  3157. constructor(reader) {
  3158. this._reader = reader;
  3159. }
  3160. get length() {
  3161. return this._reader.length;
  3162. }
  3163. get position() {
  3164. return this._reader.position;
  3165. }
  3166. skip(length) {
  3167. this._reader.skip(length);
  3168. }
  3169. seek(offset) {
  3170. this._reader.seek(offset);
  3171. }
  3172. read(length) {
  3173. return this._reader.read(length);
  3174. }
  3175. stream(length) {
  3176. return this._reader.stream(length);
  3177. }
  3178. byte() {
  3179. return this._reader.byte();
  3180. }
  3181. varint() {
  3182. let result = this._reader.byte();
  3183. if (result & 1) {
  3184. return BigInt(result >> 1);
  3185. }
  3186. if (result === 0) {
  3187. return this._reader.uint64();
  3188. }
  3189. result = BigInt(result);
  3190. let mask = 1n;
  3191. let numBytes = 0n;
  3192. let shift = 8n;
  3193. while (result > 0n && (result & mask) === 0n) {
  3194. result |= (BigInt(this._reader.byte()) << shift);
  3195. mask <<= 1n;
  3196. shift += 8n;
  3197. numBytes++;
  3198. }
  3199. result >>= BigInt(numBytes + 1n);
  3200. return result;
  3201. }
  3202. string() {
  3203. const reader = this._reader;
  3204. let result = '';
  3205. let value = -1;
  3206. for (; ;) {
  3207. value = reader.byte();
  3208. if (value === 0x00) {
  3209. break;
  3210. }
  3211. result += String.fromCharCode(value);
  3212. }
  3213. return result;
  3214. }
  3215. };
  3216. mlir.Type = class {
  3217. constructor(value) {
  3218. this._value = value;
  3219. }
  3220. toString() {
  3221. return this._value;
  3222. }
  3223. };
  3224. mlir.PrimitiveType = class extends mlir.Type {
  3225. };
  3226. mlir.FunctionType = class extends mlir.Type {
  3227. constructor(inputs, results) {
  3228. super(null);
  3229. this.inputs = inputs || [];
  3230. this.results = results || [];
  3231. }
  3232. toString() {
  3233. const inputs = this.inputs.map((t) => t.toString());
  3234. const results = this.results.map((t) => t.toString());
  3235. const input = inputs.length === 1 ? inputs[0] : `(${inputs.join(', ')})`;
  3236. const result = results.length === 1 ? results[0] : `(${results.join(', ')})`;
  3237. return `${input} -> ${result}`;
  3238. }
  3239. };
  3240. mlir.LLVMFunctionType = class extends mlir.Type {
  3241. constructor(returnType, params, varArg = false) {
  3242. super(null);
  3243. this.returnType = returnType;
  3244. this.params = params || [];
  3245. this.varArg = varArg;
  3246. }
  3247. get inputs() {
  3248. return this.params;
  3249. }
  3250. get results() {
  3251. return this.returnType ? [this.returnType] : [];
  3252. }
  3253. toString() {
  3254. const params = this.params.map((t) => t.toString());
  3255. if (this.varArg) {
  3256. params.push('...');
  3257. }
  3258. const returnType = this.returnType ? this.returnType.toString() : 'void';
  3259. return `!llvm.func<${returnType} (${params.join(', ')})>`;
  3260. }
  3261. };
  3262. mlir.Utility = class {
  3263. static dataType(value) {
  3264. switch (value) {
  3265. case 'index': return 'index';
  3266. case 'f16': return 'float16';
  3267. case 'f32': return 'float32';
  3268. case 'f64': return 'float64';
  3269. case 'bf16': return 'bfloat16';
  3270. case 'fp8': return 'float8';
  3271. case 'fp8e4m3': return 'float8e4m3';
  3272. case 'fp8_e4m3': return 'float8e4m3';
  3273. case 'fp8e4m3fn': return 'float8e4m3fn';
  3274. case 'fp8e5m2': return 'float8e5m2';
  3275. case 'fp8_e5m2': return 'float8e5m2';
  3276. case 'f4E2M1FN': return 'float4e2m1fn';
  3277. case 'f6E2M3FN': return 'float6e2m3fn';
  3278. case 'f6E3M2FN': return 'float6e3m2fn';
  3279. case 'f8E3M4': return 'float8e3m4';
  3280. case 'f8E4M3': return 'float8e4m3';
  3281. case 'f8E4M3B11FNUZ': return 'float8e4m3b11fnuz';
  3282. case 'f8E4M3FN': return 'float8e4m3fn';
  3283. case 'f8E4M3FNUZ': return 'float8e4m3fnuz';
  3284. case 'f8E5M2': return 'float8e5m2';
  3285. case 'f8E5M2FNUZ': return 'float8e5m2fnuz';
  3286. case 'f8E8M0FNU': return 'float8e8m0fnu';
  3287. case 'float8': return 'float8';
  3288. case 'tf32': return 'tensorfloat32';
  3289. case 'i1': return 'boolean';
  3290. case 'i2': return 'int2';
  3291. case 'i4': return 'int4';
  3292. case 'i8': return 'int8';
  3293. case 'i16': return 'int16';
  3294. case 'i32': return 'int32';
  3295. case 'i48': return 'int48';
  3296. case 'i64': return 'int64';
  3297. case 'si8': return 'int8';
  3298. case 'si16': return 'int16';
  3299. case 'si32': return 'int32';
  3300. case 'si64': return 'int64';
  3301. case 'ui1': return 'uint1';
  3302. case 'ui2': return 'uint2';
  3303. case 'ui4': return 'uint4';
  3304. case 'ui8': return 'uint8';
  3305. case 'ui16': return 'uint16';
  3306. case 'ui32': return 'uint32';
  3307. case 'ui64': return 'uint64';
  3308. case 'complex<f32>': return 'complex64';
  3309. case 'complex<f64>': return 'complex128';
  3310. case 'b8': return 'int8';
  3311. case 'unk': return 'unk'; // torch dialect unknown dtype
  3312. default:
  3313. if (value && value.startsWith('!')) {
  3314. return value;
  3315. }
  3316. throw new mlir.Error(`Unknown data type '${value}'.`);
  3317. }
  3318. }
  3319. static valueType(type) {
  3320. if (type === undefined) {
  3321. return null;
  3322. }
  3323. // Convert mlir.Type objects to strings
  3324. const typeStr = type instanceof mlir.Type ? type.toString() : type;
  3325. // Handle dialect-specific types like !tosa.shape<3>, !quant.uniform<...>, etc.
  3326. // These should be returned as-is without trying to decompose them
  3327. if (typeStr.startsWith('!') && !typeStr.startsWith('!torch.vtensor<')) {
  3328. return typeStr;
  3329. }
  3330. if (typeStr.startsWith('tensor<') && typeStr.endsWith('>')) {
  3331. const spec = typeStr.substring(7, typeStr.length - 1).trim();
  3332. if (spec.startsWith('!')) {
  3333. return mlir.Utility.valueType(spec);
  3334. }
  3335. let i = 0;
  3336. const shape = [];
  3337. while (i < spec.length) {
  3338. if (spec[i] === '?' || spec[i] === '*') {
  3339. shape.push('?');
  3340. i++;
  3341. } else if (/[0-9]/.test(spec[i])) {
  3342. let numStr = '';
  3343. while (i < spec.length && /[0-9]/.test(spec[i])) {
  3344. numStr += spec[i];
  3345. i++;
  3346. }
  3347. const dim = parseInt(numStr, 10);
  3348. if (isNaN(dim)) {
  3349. // This shouldn't happen, but handle it gracefully
  3350. shape.push('?');
  3351. } else {
  3352. shape.push(dim);
  3353. }
  3354. } else {
  3355. // Not a dimension, rest is the element type
  3356. break;
  3357. }
  3358. // Skip 'x' separator
  3359. if (i < spec.length && spec[i] === 'x') {
  3360. i++;
  3361. } else {
  3362. break;
  3363. }
  3364. }
  3365. let dataType = spec.substring(i);
  3366. const encodingIndex = dataType.indexOf(',');
  3367. if (encodingIndex !== -1) {
  3368. dataType = dataType.substring(0, encodingIndex).trim();
  3369. }
  3370. return new mlir.TensorType(dataType, new mlir.TensorShape(shape));
  3371. }
  3372. if (typeStr.startsWith('!torch.vtensor<') && typeStr.endsWith('>')) {
  3373. const spec = typeStr.substring(15, typeStr.length - 1);
  3374. const index = spec.lastIndexOf(',');
  3375. const shapeStr = spec.substring(0, index);
  3376. let shape = null;
  3377. if (shapeStr !== '*') {
  3378. const jsonStr = shapeStr.replace(/\?/g, '"?"');
  3379. shape = JSON.parse(jsonStr);
  3380. }
  3381. const dataType = spec.substring(index + 1);
  3382. return new mlir.TensorType(dataType, shape ? new mlir.TensorShape(shape) : null);
  3383. }
  3384. if (typeStr.startsWith('tuple<') && typeStr.endsWith('>')) {
  3385. return typeStr;
  3386. }
  3387. return typeStr;
  3388. }
  3389. };
  3390. // Dialect Plugin System
  3391. mlir.AssemblyFormatParser = class {
  3392. constructor(metadata) {
  3393. this._metadata = metadata;
  3394. this._buffer = metadata.assemblyFormat || '';
  3395. this._pos = 0;
  3396. }
  3397. match(char) {
  3398. return this._pos < this._buffer.length && this._buffer[this._pos] === char;
  3399. }
  3400. accept(str) {
  3401. // Handle single character
  3402. if (str.length === 1) {
  3403. if (this.match(str)) {
  3404. this._pos++;
  3405. return true;
  3406. }
  3407. return false;
  3408. }
  3409. // Handle multi-character keywords
  3410. const remaining = this._buffer.substring(this._pos);
  3411. if (remaining.startsWith(str)) {
  3412. // Check that keyword is not followed by alphanumeric (to avoid matching "type" in "typename")
  3413. const nextChar = this._buffer[this._pos + str.length];
  3414. if (nextChar && /[a-zA-Z0-9_-]/.test(nextChar)) {
  3415. return false;
  3416. }
  3417. this._pos += str.length;
  3418. return true;
  3419. }
  3420. return false;
  3421. }
  3422. expect(char) {
  3423. if (!this.match(char)) {
  3424. throw new mlir.Error(`Expected '${char}'.`);
  3425. }
  3426. this._pos++;
  3427. }
  3428. parse() {
  3429. const directives = [];
  3430. this._skipWhitespace();
  3431. while (this._pos < this._buffer.length) {
  3432. const directive = this._parseDirective();
  3433. directives.push(directive);
  3434. this._skipWhitespace();
  3435. }
  3436. return directives;
  3437. }
  3438. _parseDirective() {
  3439. const ch = this._buffer[this._pos];
  3440. if (!ch || this._pos >= this._buffer.length) {
  3441. throw new mlir.Error(`Unexpected end of format string.`);
  3442. }
  3443. // Parenthesized group: can be optional (...)? or conditional (...):(...) or just grouping (...)
  3444. if (this.match('(')) {
  3445. this.accept('(');
  3446. const elements = [];
  3447. let anchorElement = null;
  3448. // Parse all elements inside the parentheses
  3449. this._skipWhitespace();
  3450. while (!this.match(')')) {
  3451. const elem = this._parseDirective();
  3452. if (elem.type === 'anchor') {
  3453. // Standalone anchor - applies to the previous element
  3454. if (elements.length > 0) {
  3455. const prev = elements[elements.length - 1];
  3456. anchorElement = prev.name || prev.type;
  3457. }
  3458. } else {
  3459. if (elem.anchor) {
  3460. anchorElement = elem.name || elem.type;
  3461. }
  3462. elements.push(elem);
  3463. }
  3464. this._skipWhitespace();
  3465. }
  3466. this.expect(')');
  3467. this._skipWhitespace();
  3468. // Check what follows to determine the group type
  3469. if (this.accept('?')) {
  3470. // Optional group: (...)?
  3471. return { type: 'optional_group', elements, anchor: anchorElement };
  3472. }
  3473. if (this.accept(':')) {
  3474. // Conditional alternative: (...):(...)?
  3475. this._skipWhitespace();
  3476. const secondAlt = [];
  3477. let isSecondOptional = false;
  3478. if (this.accept('(')) {
  3479. this._skipWhitespace();
  3480. while (!this.match(')')) {
  3481. const elem = this._parseDirective();
  3482. secondAlt.push(elem);
  3483. this._skipWhitespace();
  3484. }
  3485. this.expect(')');
  3486. this._skipWhitespace();
  3487. if (this.accept('?')) {
  3488. isSecondOptional = true;
  3489. }
  3490. }
  3491. return { type: 'conditional_alternative', firstAlt: elements, secondAlt, secondOptional: isSecondOptional };
  3492. }
  3493. // Just a regular group for grouping purposes
  3494. return { type: 'group', elements };
  3495. }
  3496. // Literal: `keyword`
  3497. if (this.accept('`')) {
  3498. const value = this._parseUntil('`');
  3499. this.expect('`');
  3500. // MLIR reference: Empty literals (`` or ` `) are whitespace, not literals
  3501. if (value.length === 0 || value === ' ' || value === '\\n') {
  3502. return { type: 'whitespace', value }; // Return whitespace as a directive
  3503. }
  3504. return { type: 'literal', value };
  3505. }
  3506. if (this.accept('$')) {
  3507. const name = this._parseIdentifier();
  3508. const anchor = this.accept('^');
  3509. const metadata = this._metadata;
  3510. // Determine variable type from metadata first - matches reference implementation
  3511. // Check each metadata category in priority order
  3512. if (metadata.successors && metadata.successors.some((a) => a.name === name)) {
  3513. return { type: 'successor_ref', name, anchor };
  3514. }
  3515. if (metadata.attributes && metadata.attributes.some((a) => a.name === name)) {
  3516. return { type: 'attribute_ref', name, anchor };
  3517. }
  3518. if (metadata.inputs && metadata.inputs.some((a) => a.name === name)) {
  3519. return { type: 'operand_ref', name, anchor };
  3520. }
  3521. if (metadata.regions && metadata.regions.some((a) => a.name === name)) {
  3522. return { type: 'region_ref', name, anchor };
  3523. }
  3524. // Special keywords for collections (only used if not found in metadata)
  3525. if (name === 'operands') {
  3526. return { type: 'operands', anchor };
  3527. }
  3528. if (name === 'results') {
  3529. return { type: 'results', anchor };
  3530. }
  3531. if (name === 'regions') {
  3532. return { type: 'regions', anchor };
  3533. }
  3534. if (name === 'successors') {
  3535. return { type: 'successors', anchor };
  3536. }
  3537. // Variable not found in metadata - this indicates incomplete metadata or parsing of non-existent variable
  3538. // Assume it's an operand_ref for backward compatibility, but this should be investigated
  3539. return { type: 'operand_ref', name, anchor };
  3540. }
  3541. if (this.accept('type')) {
  3542. const args = this._parseParenList();
  3543. const anchor = this.accept('^');
  3544. return { type: 'type', args, anchor };
  3545. }
  3546. if (this.accept('qualified')) {
  3547. const args = this._parseParenList();
  3548. const anchor = this.accept('^');
  3549. return { type: 'qualified', args, anchor };
  3550. }
  3551. if (this.accept('attr-dict-with-keyword')) {
  3552. return { type: 'attr_dict_with_keyword' };
  3553. }
  3554. if (this.accept('attr-dict')) {
  3555. return { type: 'attr_dict' };
  3556. }
  3557. if (this.accept('prop-dict')) {
  3558. return { type: 'prop_dict' };
  3559. }
  3560. if (this.accept('functional-type')) {
  3561. const args = this._parseParenList();
  3562. const anchor = this.accept('^');
  3563. return { type: 'functional_type', args, anchor };
  3564. }
  3565. if (this.accept('params')) {
  3566. return { type: 'params' };
  3567. }
  3568. if (this.accept('struct')) {
  3569. this.expect('(');
  3570. const args = [];
  3571. while (!this.match(')')) {
  3572. this._skipWhitespace();
  3573. if (this.match(')')) {
  3574. break;
  3575. }
  3576. const arg = this._parseDirective();
  3577. args.push(arg);
  3578. this._skipWhitespace();
  3579. this.accept(',');
  3580. }
  3581. this.expect(')');
  3582. return { type: 'struct', args };
  3583. }
  3584. if (this.accept('ref')) {
  3585. this.expect('(');
  3586. const arg = this._parseDirective();
  3587. this._skipWhitespace();
  3588. this.expect(')');
  3589. return { type: 'ref', arg };
  3590. }
  3591. if (this.accept('custom')) {
  3592. this.expect('<');
  3593. const parser = this._parseUntil('>');
  3594. this.expect('>');
  3595. const args = this._parseParenList();
  3596. const anchor = this.accept('^');
  3597. return { type: 'custom', parser, args, anchor };
  3598. }
  3599. if (this.accept('oilist')) {
  3600. this._skipWhitespace();
  3601. this.expect('(');
  3602. let content = '';
  3603. let depth = 1;
  3604. while (this._pos < this._buffer.length && depth > 0) {
  3605. const ch = this._buffer[this._pos];
  3606. if (ch === '(') {
  3607. depth++;
  3608. content += ch;
  3609. this._pos++;
  3610. } else if (ch === ')') {
  3611. depth--;
  3612. if (depth > 0) {
  3613. content += ch;
  3614. }
  3615. this._pos++;
  3616. } else {
  3617. content += ch;
  3618. this._pos++;
  3619. }
  3620. }
  3621. return { type: 'oilist', content };
  3622. }
  3623. if (this.accept('operands')) {
  3624. return { type: 'operands' };
  3625. }
  3626. if (this.accept('results')) {
  3627. return { type: 'results' };
  3628. }
  3629. if (this.accept('regions')) {
  3630. return { type: 'regions' };
  3631. }
  3632. if (this.accept('successors')) {
  3633. return { type: 'successors' };
  3634. }
  3635. if (ch === '^') {
  3636. this._pos++;
  3637. return { type: 'anchor' };
  3638. }
  3639. if (/^[:()[\]{}<>,=|]/.test(ch)) {
  3640. this._pos++;
  3641. return { type: 'literal', value: ch };
  3642. }
  3643. const context = this._buffer.substring(Math.max(0, this._pos - 10), Math.min(this._buffer.length, this._pos + 10));
  3644. throw new mlir.Error(`Unexpected '${ch}' in assembly format '${context}...'.`);
  3645. }
  3646. _parseIdentifier() {
  3647. let name = '';
  3648. while (this._pos < this._buffer.length) {
  3649. const ch = this._buffer[this._pos];
  3650. if (/[a-zA-Z0-9_]/.test(ch)) {
  3651. name += ch;
  3652. this._pos++;
  3653. } else {
  3654. break;
  3655. }
  3656. }
  3657. return name;
  3658. }
  3659. _parseUntil(terminator) {
  3660. let value = '';
  3661. while (this._pos < this._buffer.length && this._buffer[this._pos] !== terminator) {
  3662. value += this._buffer[this._pos];
  3663. this._pos++;
  3664. }
  3665. return value;
  3666. }
  3667. _parseParenList() {
  3668. if (!this.accept('(')) {
  3669. return [];
  3670. }
  3671. this._skipWhitespace();
  3672. if (this.accept(')')) {
  3673. return [];
  3674. }
  3675. const items = [];
  3676. const parseElement = () => {
  3677. let element = '';
  3678. let depth = 0;
  3679. while (this._pos < this._buffer.length) {
  3680. this._skipWhitespace();
  3681. if (this.accept('"')) {
  3682. // String literal - consume as a unit
  3683. element += '"';
  3684. element += this._parseUntil('"');
  3685. element += '"';
  3686. this.expect('"');
  3687. } else if (this.accept('$')) {
  3688. element += '$';
  3689. const id = this._parseIdentifier();
  3690. element += id;
  3691. } else if (this.accept('(')) {
  3692. // Nested parentheses - include in element (e.g., type($list))
  3693. element += '(';
  3694. depth++;
  3695. } else if (this.match(')')) {
  3696. if (depth === 0) {
  3697. // End of this element
  3698. break;
  3699. }
  3700. element += ')';
  3701. this.accept(')');
  3702. depth--;
  3703. } else if (this.match(',') && depth === 0) {
  3704. // Comma at top level - end of this element
  3705. break;
  3706. } else {
  3707. // Plain identifier (e.g., "type" in type($list))
  3708. const id = this._parseIdentifier();
  3709. if (!id) {
  3710. throw new mlir.Error(`Unexpected '${this._buffer[this._pos]}' in assembly format directive list.`);
  3711. }
  3712. element += id;
  3713. }
  3714. }
  3715. return element.trim();
  3716. };
  3717. const first = parseElement();
  3718. if (!first) {
  3719. throw new mlir.Error('Expected element.');
  3720. }
  3721. items.push(first);
  3722. this._skipWhitespace();
  3723. while (this.accept(',')) {
  3724. this._skipWhitespace();
  3725. const elem = parseElement();
  3726. if (!elem) {
  3727. throw new mlir.Error('Expected element after comma');
  3728. }
  3729. items.push(elem);
  3730. this._skipWhitespace();
  3731. }
  3732. this.expect(')');
  3733. return items;
  3734. }
  3735. _skipWhitespace() {
  3736. while (this._pos < this._buffer.length && /\s/.test(this._buffer[this._pos])) {
  3737. this._pos++;
  3738. }
  3739. }
  3740. };
  3741. mlir.Dialect = class {
  3742. constructor(name, operations) {
  3743. this._name = name;
  3744. this._operations = new Map();
  3745. this._customDirectives = new Map();
  3746. this._customTypes = new Map();
  3747. this._customAttributes = new Map();
  3748. this.registerCustomDirective('DynamicIndexList', this._parseDynamicIndexList.bind(this));
  3749. this.registerCustomDirective('Offsets', this._parseOffsets.bind(this));
  3750. this.registerCustomDirective('SymbolVisibility', this._parseSymbolVisibility.bind(this));
  3751. this.registerCustomDirective('TypeOrAttr', this._parseTypeOrAttr.bind(this));
  3752. this.registerCustomAttribute('TypedAttrInterface', this._parseTypedAttrInterface.bind(this));
  3753. this.registerCustomAttribute('VM_ConstantIntegerValueAttr', this._parseTypedAttrInterface.bind(this));
  3754. this.registerCustomAttribute('Util_AnySerializableAttr', this._parseTypedAttrInterface.bind(this));
  3755. this.registerCustomAttribute('ElementsAttr', this._parseTypedAttrInterface.bind(this));
  3756. this.registerCustomAttribute('AnyAttr', this._parseTypedAttrInterface.bind(this));
  3757. this.registerCustomAttribute('UnitAttr', this._parseUnitAttr.bind(this));
  3758. this.registerCustomAttribute('UnitProp', this._parseUnitAttr.bind(this));
  3759. this.registerCustomAttribute('SymbolNameAttr', this._parseSymbolNameAttr.bind(this));
  3760. this.registerCustomAttribute('OptionalAttr', this._parseOptionalAttr.bind(this));
  3761. this.registerCustomAttribute('OptionalProp', this._parseOptionalAttr.bind(this));
  3762. this.registerCustomAttribute('DefaultValuedOptionalAttr', this._parseDefaultValuedOptionalAttr.bind(this));
  3763. this.registerCustomAttribute('DefaultValuedAttr', this._parseDefaultValuedAttr.bind(this));
  3764. this.registerCustomAttribute('DefaultValuedProp', this._parseDefaultValuedAttr.bind(this));
  3765. this.registerCustomAttribute('ConfinedAttr', this._parseConfinedAttr.bind(this));
  3766. this.registerCustomAttribute('TypeAttrOf', this._parseTypeAttrOf.bind(this));
  3767. this.registerCustomAttribute('AnyAttrOf', this._parseAnyAttrOf.bind(this));
  3768. this.registerCustomAttribute('ArrayAttr', this._parseArrayAttr.bind(this));
  3769. this.registerCustomAttribute('TypedArrayAttrBase', this._parseArrayAttr.bind(this));
  3770. // Register integer attribute types - parse without : type suffix
  3771. // Reference: for typed attributes, the type is known so no suffix needed
  3772. this.registerCustomAttribute('I64Attr', this._parseIntegerAttr.bind(this, 'i64'));
  3773. this.registerCustomAttribute('I32Attr', this._parseIntegerAttr.bind(this, 'i32'));
  3774. this.registerCustomAttribute('I16Attr', this._parseIntegerAttr.bind(this, 'i16'));
  3775. this.registerCustomAttribute('I8Attr', this._parseIntegerAttr.bind(this, 'i8'));
  3776. this.registerCustomAttribute('I1Attr', this._parseIntegerAttr.bind(this, 'i1'));
  3777. this.registerCustomAttribute('SI64Attr', this._parseIntegerAttr.bind(this, 'si64'));
  3778. this.registerCustomAttribute('SI32Attr', this._parseIntegerAttr.bind(this, 'si32'));
  3779. this.registerCustomAttribute('UI64Attr', this._parseIntegerAttr.bind(this, 'ui64'));
  3780. this.registerCustomAttribute('UI32Attr', this._parseIntegerAttr.bind(this, 'ui32'));
  3781. this.registerCustomAttribute('IndexAttr', this._parseIntegerAttr.bind(this, 'index'));
  3782. // Register float attribute types
  3783. this.registerCustomAttribute('F64Attr', this._parseFloatAttr.bind(this, 'f64'));
  3784. this.registerCustomAttribute('F32Attr', this._parseFloatAttr.bind(this, 'f32'));
  3785. this.registerCustomAttribute('F16Attr', this._parseFloatAttr.bind(this, 'f16'));
  3786. this.registerCustomAttribute('BF16Attr', this._parseFloatAttr.bind(this, 'bf16'));
  3787. // String attributes - pass string type to prevent : type suffix parsing
  3788. this.registerCustomAttribute('StrAttr', this._parseStrAttr.bind(this));
  3789. // Level attribute - parse as index to prevent : type suffix parsing
  3790. this.registerCustomAttribute('LevelAttr', this._parseIntegerAttr.bind(this, 'index'));
  3791. this.registerCustomType('Optional', this._parseOptional.bind(this));
  3792. for (const metadata of operations.get(name) || []) {
  3793. const op = { metadata };
  3794. if (metadata.assemblyFormat) {
  3795. const parser = new mlir.AssemblyFormatParser(metadata);
  3796. op.directives = parser.parse();
  3797. }
  3798. this._operations.set(metadata.name, op);
  3799. }
  3800. }
  3801. get name() {
  3802. return this._name;
  3803. }
  3804. _parseConstraint(value) {
  3805. if (!value || typeof value !== 'string') {
  3806. return null;
  3807. }
  3808. value = value.trim();
  3809. if (!value) {
  3810. return null;
  3811. }
  3812. // Tokenize
  3813. const tokenize = (str) => {
  3814. const tokens = [];
  3815. let i = 0;
  3816. while (i < str.length) {
  3817. const ch = str[i];
  3818. if (/\s/.test(ch)) {
  3819. i++;
  3820. continue;
  3821. }
  3822. if ('<>={}[](),|'.indexOf(ch) !== -1) {
  3823. tokens.push({ type: ch, value: ch, pos: i });
  3824. i++;
  3825. continue;
  3826. }
  3827. if (ch === ':' && i + 1 < str.length && str[i + 1] === ':') {
  3828. tokens.push({ type: '::', value: '::', pos: i });
  3829. i += 2;
  3830. continue;
  3831. }
  3832. if (ch === ':') {
  3833. i++;
  3834. continue;
  3835. }
  3836. if (ch === '"' || ch === "'") {
  3837. const quote = ch;
  3838. let j = i + 1;
  3839. while (j < str.length && str[j] !== quote) {
  3840. if (str[j] === '\\' && j + 1 < str.length) {
  3841. j += 2;
  3842. } else {
  3843. j++;
  3844. }
  3845. }
  3846. if (j < str.length) {
  3847. tokens.push({ type: 'string', value: str.substring(i + 1, j), pos: i });
  3848. i = j + 1;
  3849. } else {
  3850. tokens.push({ type: 'ident', value: str.substring(i), pos: i });
  3851. break;
  3852. }
  3853. continue;
  3854. }
  3855. if (/[a-zA-Z_0-9-]/.test(ch)) {
  3856. let j = i;
  3857. while (j < str.length && /[a-zA-Z_0-9-]/.test(str[j])) {
  3858. j++;
  3859. }
  3860. const ident = str.substring(i, j);
  3861. tokens.push({ type: 'ident', value: ident, pos: i });
  3862. i = j;
  3863. continue;
  3864. }
  3865. i++;
  3866. }
  3867. return tokens;
  3868. };
  3869. // Parse tokens into constraint structure
  3870. const parseTokens = (tokens, pos) => {
  3871. if (pos >= tokens.length) {
  3872. return null;
  3873. }
  3874. const token = tokens[pos];
  3875. if (token.type === '::') {
  3876. // eslint-disable-next-line no-use-before-define
  3877. return parseScopedIdentifier(tokens, pos);
  3878. }
  3879. if (token.type !== 'ident') {
  3880. return null;
  3881. }
  3882. let name = token.value;
  3883. let nextPos = pos + 1;
  3884. while (nextPos < tokens.length && tokens[nextPos].type === '::') {
  3885. nextPos++;
  3886. if (nextPos < tokens.length && tokens[nextPos].type === 'ident') {
  3887. const value = tokens[nextPos++].value;
  3888. name += `::${value}`;
  3889. } else {
  3890. break;
  3891. }
  3892. }
  3893. if (nextPos >= tokens.length) {
  3894. return { value: { name }, nextPos };
  3895. }
  3896. const nextToken = tokens[nextPos];
  3897. if (nextToken.type === '{') {
  3898. // eslint-disable-next-line no-use-before-define
  3899. return parseEnum(tokens, pos, name);
  3900. }
  3901. if (nextToken.type === '<') {
  3902. // eslint-disable-next-line no-use-before-define
  3903. return parseGeneric(tokens, pos, name);
  3904. }
  3905. return { value: { name }, nextPos };
  3906. };
  3907. const parseScopedIdentifier = (tokens, pos) => {
  3908. let name = '';
  3909. let nextPos = pos;
  3910. while (nextPos < tokens.length) {
  3911. if (tokens[nextPos].type === '::') {
  3912. name += '::';
  3913. nextPos++;
  3914. } else if (tokens[nextPos].type === 'ident') {
  3915. name += tokens[nextPos].value;
  3916. nextPos++;
  3917. } else {
  3918. break;
  3919. }
  3920. }
  3921. if (!name) {
  3922. return null;
  3923. }
  3924. if (nextPos < tokens.length) {
  3925. const nextToken = tokens[nextPos];
  3926. if (nextToken.type === '{') {
  3927. // eslint-disable-next-line no-use-before-define
  3928. return parseEnum(tokens, pos, name);
  3929. }
  3930. if (nextToken.type === '<') {
  3931. // eslint-disable-next-line no-use-before-define
  3932. return parseGeneric(tokens, pos, name);
  3933. }
  3934. }
  3935. return { value: { name }, nextPos };
  3936. };
  3937. const parseEnum = (tokens, startPos, name) => {
  3938. let pos = startPos;
  3939. while (pos < tokens.length && (tokens[pos].type === 'ident' || tokens[pos].type === '::')) {
  3940. pos++;
  3941. }
  3942. if (pos >= tokens.length || tokens[pos].type !== '{') {
  3943. return null;
  3944. }
  3945. pos++;
  3946. const values = [];
  3947. let currentValue = '';
  3948. while (pos < tokens.length && tokens[pos].type !== '}') {
  3949. const token = tokens[pos];
  3950. if (token.type === '|') {
  3951. if (currentValue.trim()) {
  3952. values.push(currentValue.trim());
  3953. currentValue = '';
  3954. }
  3955. pos++;
  3956. } else if (token.type === 'ident') {
  3957. if (currentValue) {
  3958. currentValue += ' ';
  3959. }
  3960. currentValue += token.value;
  3961. pos++;
  3962. } else if (token.type === '::') {
  3963. currentValue += '::';
  3964. pos++;
  3965. } else {
  3966. pos++;
  3967. }
  3968. }
  3969. if (currentValue.trim()) {
  3970. values.push(currentValue.trim());
  3971. }
  3972. if (pos < tokens.length && tokens[pos].type === '}') {
  3973. pos++;
  3974. }
  3975. return { value: { name, values }, nextPos: pos };
  3976. };
  3977. const parseGeneric = (tokens, startPos, name) => {
  3978. let pos = startPos;
  3979. while (pos < tokens.length && (tokens[pos].type === 'ident' || tokens[pos].type === '::')) {
  3980. pos++;
  3981. }
  3982. if (pos >= tokens.length || tokens[pos].type !== '<') {
  3983. return null;
  3984. }
  3985. pos++;
  3986. const args = [];
  3987. let angleDepth = 1;
  3988. let bracketDepth = 0;
  3989. let currentArg = [];
  3990. while (pos < tokens.length && (angleDepth > 0 || bracketDepth > 0)) {
  3991. const token = tokens[pos];
  3992. if (token.type === '<') {
  3993. angleDepth++;
  3994. currentArg.push(token);
  3995. pos++;
  3996. } else if (token.type === '>') {
  3997. angleDepth--;
  3998. if (angleDepth === 0 && bracketDepth === 0) {
  3999. if (currentArg.length > 0) {
  4000. // eslint-disable-next-line no-use-before-define
  4001. const parsed = parseArgumentTokens(currentArg);
  4002. if (parsed !== null) {
  4003. args.push(parsed);
  4004. }
  4005. }
  4006. pos++;
  4007. break;
  4008. } else {
  4009. currentArg.push(token);
  4010. pos++;
  4011. }
  4012. } else if (token.type === '[') {
  4013. bracketDepth++;
  4014. currentArg.push(token);
  4015. pos++;
  4016. } else if (token.type === ']') {
  4017. bracketDepth--;
  4018. currentArg.push(token);
  4019. pos++;
  4020. } else if (token.type === ',' && angleDepth === 1 && bracketDepth === 0) {
  4021. if (currentArg.length > 0) {
  4022. // eslint-disable-next-line no-use-before-define
  4023. const parsed = parseArgumentTokens(currentArg);
  4024. if (parsed !== null) {
  4025. args.push(parsed);
  4026. }
  4027. currentArg = [];
  4028. }
  4029. pos++;
  4030. } else {
  4031. currentArg.push(token);
  4032. pos++;
  4033. }
  4034. }
  4035. return { value: { name, args }, nextPos: pos };
  4036. };
  4037. const parseArgumentTokens = (tokens) => {
  4038. if (!tokens || tokens.length === 0) {
  4039. return null;
  4040. }
  4041. tokens = tokens.filter((t) => t.type !== undefined);
  4042. if (tokens[0].type === '[') {
  4043. // eslint-disable-next-line no-use-before-define
  4044. return parseListArgument(tokens);
  4045. }
  4046. if (tokens[0].type === 'string') {
  4047. return tokens[0].value;
  4048. }
  4049. if (tokens[0].type === 'ident' || tokens[0].type === '::') {
  4050. const result = parseTokens(tokens, 0);
  4051. if (result && result.nextPos === tokens.length) {
  4052. return result.value;
  4053. }
  4054. }
  4055. let literal = '';
  4056. for (const token of tokens) {
  4057. if (token.type === 'ident' || token.type === 'string') {
  4058. if (literal && !/^[,[]\(\):\.]$/.test(literal[literal.length - 1])) {
  4059. literal += ' ';
  4060. }
  4061. literal += token.value;
  4062. } else if (token.type === '::') {
  4063. literal += '::';
  4064. } else if ('{}[](),.'.indexOf(token.type) !== -1) {
  4065. literal += token.value;
  4066. }
  4067. }
  4068. return literal.trim() || null;
  4069. };
  4070. const parseListArgument = (tokens) => {
  4071. if (!tokens || tokens.length === 0 || tokens[0].type !== '[') {
  4072. return null;
  4073. }
  4074. let pos = 1;
  4075. const items = [];
  4076. let bracketDepth = 1;
  4077. let angleDepth = 0;
  4078. let currentItem = [];
  4079. while (pos < tokens.length && (bracketDepth > 0 || angleDepth > 0)) {
  4080. const token = tokens[pos];
  4081. if (token.type === '[') {
  4082. bracketDepth++;
  4083. currentItem.push(token);
  4084. pos++;
  4085. } else if (token.type === ']') {
  4086. bracketDepth--;
  4087. if (bracketDepth === 0 && angleDepth === 0) {
  4088. if (currentItem.length > 0) {
  4089. const parsed = parseArgumentTokens(currentItem);
  4090. if (parsed !== null) {
  4091. items.push(parsed);
  4092. }
  4093. }
  4094. break;
  4095. } else {
  4096. currentItem.push(token);
  4097. pos++;
  4098. }
  4099. } else if (token.type === '<') {
  4100. angleDepth++;
  4101. currentItem.push(token);
  4102. pos++;
  4103. } else if (token.type === '>') {
  4104. angleDepth--;
  4105. currentItem.push(token);
  4106. pos++;
  4107. } else if (token.type === ',' && bracketDepth === 1 && angleDepth === 0) {
  4108. if (currentItem.length > 0) {
  4109. const parsed = parseArgumentTokens(currentItem);
  4110. if (parsed !== null) {
  4111. items.push(parsed);
  4112. }
  4113. currentItem = [];
  4114. }
  4115. pos++;
  4116. } else {
  4117. currentItem.push(token);
  4118. pos++;
  4119. }
  4120. }
  4121. return items;
  4122. };
  4123. const tokens = tokenize(value);
  4124. if (!tokens || tokens.length === 0) {
  4125. return null;
  4126. }
  4127. const result = parseTokens(tokens, 0);
  4128. return result ? result.value : null;
  4129. }
  4130. getOperation(opName) {
  4131. const op = this._operations.get(opName);
  4132. if (op && !op.metadata._) {
  4133. if (Array.isArray(op.metadata.inputs)) {
  4134. for (const input of op.metadata.inputs) {
  4135. if (input && input.type) {
  4136. input.type = this._parseConstraint(input.type);
  4137. }
  4138. }
  4139. }
  4140. if (Array.isArray(op.metadata.outputs)) {
  4141. for (const output of op.metadata.outputs) {
  4142. if (output && output.type) {
  4143. output.type = this._parseConstraint(output.type);
  4144. }
  4145. }
  4146. }
  4147. if (Array.isArray(op.metadata.attributes)) {
  4148. for (const attribute of op.metadata.attributes) {
  4149. if (attribute && attribute.type) {
  4150. attribute.type = this._parseConstraint(attribute.type);
  4151. }
  4152. }
  4153. }
  4154. if (Array.isArray(op.metadata.regions)) {
  4155. for (const region of op.metadata.regions) {
  4156. if (region && region.type) {
  4157. region.type = this._parseConstraint(region.type);
  4158. }
  4159. }
  4160. }
  4161. op.metadata._ = true;
  4162. }
  4163. return op || null;
  4164. }
  4165. hasParser(opName) {
  4166. const opInfo = this.getOperation(opName);
  4167. return opInfo ? opInfo.metadata.parser : null;
  4168. }
  4169. hasAssemblyFormat(opName) {
  4170. const opInfo = this.getOperation(opName);
  4171. return opInfo ? opInfo.metadata.assemblyFormat : false;
  4172. }
  4173. hasCustomAssemblyFormat(opName) {
  4174. const opInfo = this.getOperation(opName);
  4175. return opInfo ? opInfo.metadata.hasCustomAssemblyFormat : false;
  4176. }
  4177. hasParseOperation(opName) {
  4178. const opInfo = this.getOperation(opName);
  4179. return opInfo ? opInfo.hasParseOperation : false;
  4180. }
  4181. registerCustomDirective(name, parserFn) {
  4182. this._customDirectives.set(name, parserFn);
  4183. }
  4184. registerCustomType(name, parserFn) {
  4185. this._customTypes.set(name, parserFn);
  4186. }
  4187. registerCustomAttribute(name, parserFn) {
  4188. this._customAttributes.set(name, parserFn);
  4189. }
  4190. parseType(parser, dialectName) {
  4191. const typeName = parser.parseKeyword();
  4192. if (!typeName) {
  4193. return null;
  4194. }
  4195. let type = `!${dialectName}.${typeName}`;
  4196. if (parser.match('<')) {
  4197. type += parser.skip('<', '>');
  4198. }
  4199. return new mlir.Type(type);
  4200. }
  4201. parseDirective(directive, parser, op, opInfo, directives, i) {
  4202. const varidic = (type) => {
  4203. if (type.name === 'Variadic') {
  4204. return true;
  4205. }
  4206. if (Array.isArray(type.args) && type.args.length > 0) {
  4207. return varidic(type.args[0]);
  4208. }
  4209. return false;
  4210. };
  4211. switch (directive.type) {
  4212. case 'whitespace':
  4213. // Skip whitespace directives - they're just formatting hints
  4214. break;
  4215. case 'literal':
  4216. parser.expect(null, directive.value);
  4217. break;
  4218. case 'region_ref': {
  4219. // Parse region variable - matches reference implementation
  4220. // Check if this is a variadic region from metadata
  4221. const regionMeta = opInfo.metadata && opInfo.metadata.regions && opInfo.metadata.regions.find((r) => r.name === directive.name);
  4222. const isVariadicRegion = regionMeta && regionMeta.type && regionMeta.type.name === 'VariadicRegion';
  4223. if (isVariadicRegion) {
  4224. // Parse multiple regions separated by commas
  4225. // For variadic regions, may have zero or more regions
  4226. if (parser.match('{')) {
  4227. do {
  4228. const region = {};
  4229. parser.parseRegion(region);
  4230. op.regions.push(region);
  4231. } while (parser.accept(',') && parser.match('{'));
  4232. }
  4233. } else {
  4234. const region = {};
  4235. parser.parseRegion(region);
  4236. op.regions.push(region);
  4237. }
  4238. break;
  4239. }
  4240. case 'successor_ref': {
  4241. // Parse successor variable - matches reference implementation
  4242. if (!op.successors) {
  4243. op.successors = [];
  4244. }
  4245. const successor = {};
  4246. successor.label = parser.expect('^');
  4247. if (parser.accept('(')) {
  4248. successor.arguments = [];
  4249. while (!parser.match(':') && !parser.match(')')) {
  4250. if (parser.match('%')) {
  4251. const arg = {};
  4252. arg.value = parser.expect('%');
  4253. successor.arguments.push(arg);
  4254. parser.accept(',');
  4255. } else {
  4256. break;
  4257. }
  4258. }
  4259. if (parser.accept(':')) {
  4260. let idx = 0;
  4261. while (idx < successor.arguments.length && !parser.match(')')) {
  4262. const type = parser.parseType();
  4263. successor.arguments[idx].type = type.toString();
  4264. idx++;
  4265. parser.accept(',');
  4266. }
  4267. }
  4268. parser.accept(')');
  4269. }
  4270. op.successors.push(successor);
  4271. break;
  4272. }
  4273. case 'attribute_ref': {
  4274. const refName = directive.name;
  4275. // Check if attribute was already parsed in optional group lookahead
  4276. if (op.attributes.find((attr) => attr.name === refName)) {
  4277. break;
  4278. }
  4279. const attrInfo = opInfo.metadata && opInfo.metadata.attributes && opInfo.metadata.attributes.find((attr) => attr.name === refName);
  4280. const attrType = attrInfo ? attrInfo.type : null;
  4281. let attrValue = null;
  4282. if (attrType && attrType !== 'Attribute') {
  4283. attrValue = this._parseCustomAttributeWithFallback(parser, attrType);
  4284. } else {
  4285. // In assembly format, don't parse : type suffix (default parseTypeSuffix = false)
  4286. attrValue = parser.parseAttribute();
  4287. }
  4288. if (attrValue) {
  4289. const value = attrValue.value === undefined ? attrValue : attrValue.value;
  4290. op.attributes.push({ name: refName, value });
  4291. }
  4292. break;
  4293. }
  4294. case 'operand_ref': {
  4295. const refName = directive.name;
  4296. // Check if this is a variadic operand
  4297. let isVariadic = false;
  4298. if (opInfo.metadata && opInfo.metadata.inputs) {
  4299. const input = opInfo.metadata.inputs.find((inp) => inp.name === refName);
  4300. if (input) {
  4301. isVariadic = varidic(input.type);
  4302. }
  4303. }
  4304. // Parse variadic operands
  4305. if (isVariadic) {
  4306. while (!parser.match(')') && !parser.match(']') && !parser.match('}') && !parser.match(':') && !parser.match('{') && !parser.match('=')) {
  4307. if (parser.match('%')) {
  4308. const input = {};
  4309. input.value = parser.expect();
  4310. op.operands.push(input);
  4311. if (!parser.accept(',')) {
  4312. break;
  4313. }
  4314. } else {
  4315. break;
  4316. }
  4317. }
  4318. } else if (parser.match('%')) {
  4319. // Parse single operand starting with %
  4320. const input = {};
  4321. input.value = parser.expect();
  4322. op.operands.push(input);
  4323. } else if (parser.match('{')) {
  4324. // Only parse as region if this variable is NOT an actual operand
  4325. const isActualOperand = opInfo.metadata && opInfo.metadata.inputs && opInfo.metadata.inputs.some((inp) => inp.name === refName);
  4326. if (!isActualOperand) {
  4327. // Check if region is variadic from metadata
  4328. const regionMeta = opInfo.metadata && opInfo.metadata.regions && opInfo.metadata.regions.find((r) => r.name === refName);
  4329. const isVariadicRegion = regionMeta && regionMeta.type && regionMeta.type.startsWith('VariadicRegion');
  4330. if (isVariadicRegion) {
  4331. // Parse variadic regions - comma-separated
  4332. do {
  4333. const region = {};
  4334. parser.parseRegion(region);
  4335. op.regions.push(region);
  4336. } while (parser.accept(',') && parser.match('{'));
  4337. } else {
  4338. // Parse single region
  4339. const region = {};
  4340. parser.parseRegion(region);
  4341. op.regions.push(region);
  4342. }
  4343. }
  4344. // If it IS an actual operand, leave the '{' for attr_dict to handle
  4345. } else if (parser.match('@')) {
  4346. // Parse symbol reference (function name, etc.)
  4347. const value = parser.expect('@');
  4348. if (directive.name) {
  4349. op.attributes.push({ name: directive.name, value });
  4350. } else {
  4351. op.attributes.push({ name: 'callee', value });
  4352. }
  4353. } else if (parser.match('id')) {
  4354. // Parse identifier as operand
  4355. const input = {};
  4356. input.value = parser.expect('id');
  4357. op.operands.push(input);
  4358. } else if (parser.match('int')) {
  4359. // Parse integer as operand
  4360. const input = {};
  4361. input.value = parser.expect('int');
  4362. op.operands.push(input);
  4363. } else if (!parser.match(':') && !parser.match(')') && !parser.match(']') && !parser.match('}') && !parser.match('eof')) {
  4364. // Try to parse as a general value, but not if we're at a delimiter
  4365. const input = parser.parseAttribute();
  4366. if (input) {
  4367. op.operands.push(input);
  4368. }
  4369. }
  4370. break;
  4371. }
  4372. case 'operands':
  4373. // Reference: OpFormatGen.cpp - 'operands' directive parses SSA operand values
  4374. // Generates: parser.parseOperandList(allOperands)
  4375. op.operands = parser.parseOperandList();
  4376. break;
  4377. case 'results':
  4378. op.results = parser.parseArguments();
  4379. break;
  4380. case 'type':
  4381. case 'qualified':
  4382. if (directive.args && directive.args.length > 0) {
  4383. const arg = directive.args[0] === 'type' && directive.args.length > 1 ? directive.args[1] : directive.args[0];
  4384. if (arg === 'results' || arg === '$results') {
  4385. const opMetadata = opInfo.metadata;
  4386. // Check if "results" is an input (operand) or output (result)
  4387. // For scf.yield, "results" is an input (the values it yields)
  4388. let isInput = false;
  4389. if (opMetadata && opMetadata.inputs) {
  4390. isInput = opMetadata.inputs.some((inp) => inp.name === 'results');
  4391. }
  4392. if (isInput) {
  4393. // Parse as operands (e.g., scf.yield $results)
  4394. const types = parser.parseTypeListNoParens();
  4395. parser.resolveOperands(op.operands, types);
  4396. } else {
  4397. // Parse as results (outputs)
  4398. let hasVariadicResult = false;
  4399. if (opMetadata && opMetadata.outputs) {
  4400. if (opMetadata.outputs.length > 1) {
  4401. hasVariadicResult = true;
  4402. } else if (opMetadata.outputs.length === 1) {
  4403. hasVariadicResult = varidic(opMetadata.outputs[0].type);
  4404. }
  4405. }
  4406. if (hasVariadicResult) {
  4407. const types = parser.parseTypeListNoParens();
  4408. parser.resolveOperands(op.results, types);
  4409. } else {
  4410. const type = parser.parseType();
  4411. if (op.results.length === 0) {
  4412. op.results.push({ type });
  4413. } else {
  4414. op.results[0].type = type;
  4415. }
  4416. }
  4417. }
  4418. } else if (arg === 'operands' || arg === '$operands' || arg === 'type(operands)') {
  4419. const types = parser.parseTypeListNoParens();
  4420. parser.resolveOperands(op.operands, types);
  4421. } else if (arg === 'type(results)') {
  4422. const types = parser.parseTypeListNoParens();
  4423. parser.resolveOperands(op.results, types);
  4424. } else {
  4425. let name = null;
  4426. switch (directive.type) {
  4427. case 'type':
  4428. if (!arg.startsWith('$')) {
  4429. throw new mlir.Error(`Invalid operand directive argument '${arg}'.`);
  4430. }
  4431. name = arg.substring(1);
  4432. break;
  4433. case 'qualified':
  4434. // Reference: OpFormatGen.cpp - 'qualified' expects attribute or type directive
  4435. // qualified(type($name)) -> parse type of $name
  4436. // qualified($name) -> parse attribute $name (like attribute_ref)
  4437. if (arg.startsWith('type($') && arg.endsWith(')')) {
  4438. name = arg.substring(6, arg.length - 1);
  4439. } else if (arg.startsWith('$')) {
  4440. // qualified($name) - parse as attribute reference
  4441. const attrName = arg.substring(1);
  4442. const attr = parser.parseAttribute();
  4443. if (attr) {
  4444. op.attributes.push({ name: attrName, value: attr.value || attr });
  4445. }
  4446. return; // Early return - attribute handled
  4447. } else {
  4448. throw new mlir.Error(`Invalid operand directive argument '${arg}'.`);
  4449. }
  4450. break;
  4451. default:
  4452. throw new mlir.Error(`Unknown directive type argument '${arg}'.`);
  4453. }
  4454. const opMetadata = opInfo.metadata;
  4455. let isResult = false;
  4456. let isVariadic = false;
  4457. if (opMetadata && opMetadata.outputs) {
  4458. for (const output of opMetadata.outputs) {
  4459. if (output.name === name) {
  4460. isResult = true;
  4461. isVariadic = varidic(output.type);
  4462. break;
  4463. }
  4464. }
  4465. }
  4466. if (!isResult && opMetadata && opMetadata.inputs) {
  4467. for (const input of opMetadata.inputs) {
  4468. if (input.name === name) {
  4469. isVariadic = varidic(input.type);
  4470. break;
  4471. }
  4472. }
  4473. }
  4474. if (isResult) {
  4475. if (isVariadic) {
  4476. const types = parser.parseTypeListNoParens();
  4477. parser.resolveOperands(op.results, types);
  4478. } else {
  4479. const output = opMetadata.outputs ? opMetadata.outputs.find((output) => output.name === name) : null;
  4480. const outputType = output && output.type ? output.type : null;
  4481. const type = this.parseCustomTypeWithFallback(parser, outputType);
  4482. if (op.results.length === 0) {
  4483. op.results.push({ type });
  4484. } else {
  4485. op.results[0].type = type;
  4486. }
  4487. }
  4488. } else if (isVariadic) {
  4489. const types = parser.parseTypeListNoParens();
  4490. parser.resolveOperands(op.operands, types);
  4491. } else if (op.operands.length > 0) {
  4492. const input = opMetadata.inputs ? opMetadata.inputs.find((input) => input.name === name) : null;
  4493. const inputType = input && input.type ? input.type : null;
  4494. const type = this.parseCustomTypeWithFallback(parser, inputType);
  4495. op.operands[op.operands.length - 1].type = type;
  4496. } else {
  4497. parser.parseType();
  4498. }
  4499. }
  4500. } else {
  4501. const types = parser.parseTypeListNoParens();
  4502. parser.resolveOperands(op.operands, types);
  4503. }
  4504. break;
  4505. case 'attr_dict_with_keyword':
  4506. if (parser.accept('id', 'attributes')) {
  4507. parser.parseAttributeDict(op.attributes);
  4508. }
  4509. break;
  4510. case 'attr_dict':
  4511. parser.parseAttributeDict(op.attributes);
  4512. break;
  4513. case 'prop_dict':
  4514. if (parser.match('<')) {
  4515. parser.parsePropertyDict(op.attributes);
  4516. }
  4517. break;
  4518. case 'regions':
  4519. while (parser.match('{')) {
  4520. const region = {};
  4521. parser.parseRegion(region);
  4522. op.regions.push(region);
  4523. if (!parser.accept(',')) {
  4524. break;
  4525. }
  4526. }
  4527. break;
  4528. case 'successors':
  4529. if (parser.match('[')) {
  4530. parser.skip('[', ']');
  4531. }
  4532. break;
  4533. case 'functional_type': {
  4534. const type = parser.parseFunctionType();
  4535. if (type instanceof mlir.FunctionType === false) {
  4536. throw new mlir.Error('Invalid functional-type function type.');
  4537. }
  4538. for (let i = 0; i < type.inputs.length && i < op.operands.length; i++) {
  4539. if (!op.operands[i].type) {
  4540. op.operands[i].type = type.inputs[i].toString();
  4541. }
  4542. }
  4543. for (let i = 0; i < type.results.length; i++) {
  4544. if (i < op.results.length) {
  4545. op.results[i].type = op.results[i].type || type.results[i].toString();
  4546. } else {
  4547. op.results.push({ type: type.results[i].toString() });
  4548. }
  4549. }
  4550. break;
  4551. }
  4552. case 'custom': {
  4553. const fn = this._customDirectives.get(directive.parser);
  4554. if (!fn) {
  4555. throw new mlir.Error(`Custom directive parser '${directive.parser}' not implemented.`);
  4556. }
  4557. fn(parser, op, directive.args);
  4558. break;
  4559. }
  4560. case 'oilist': {
  4561. const clauses = directive.content.split('|').map((c) => c.trim());
  4562. const parsedClauses = [];
  4563. for (const clauseStr of clauses) {
  4564. const clauseParser = new mlir.AssemblyFormatParser({ ...opInfo.metadata, assemblyFormat: clauseStr });
  4565. const elements = clauseParser.parse();
  4566. parsedClauses.push({ elements, parsed: false, clauseStr });
  4567. }
  4568. // Helper to check if a clause's variables are used by later custom directives
  4569. const isHandledByCustomDirective = (clauseStr) => {
  4570. const varMatches = clauseStr.matchAll(/\$(\w+)/g);
  4571. const clauseVars = [...varMatches].map((m) => m[1]);
  4572. if (clauseVars.length === 0) {
  4573. return false;
  4574. }
  4575. for (let j = i + 1; j < directives.length; j++) {
  4576. const laterDir = directives[j];
  4577. if (laterDir.type === 'custom' && laterDir.args && Array.isArray(laterDir.args)) {
  4578. const customVarNames = [];
  4579. for (const arg of laterDir.args) {
  4580. const argVarMatches = arg.matchAll(/\$(\w+)/g);
  4581. for (const match of argVarMatches) {
  4582. customVarNames.push(match[1]);
  4583. }
  4584. }
  4585. if (clauseVars.some((v) => customVarNames.includes(v))) {
  4586. return true;
  4587. }
  4588. }
  4589. }
  4590. return false;
  4591. };
  4592. let progress = true;
  4593. while (progress) {
  4594. progress = false;
  4595. for (const clause of parsedClauses) {
  4596. if (clause.parsed) {
  4597. continue;
  4598. }
  4599. if (clause.elements.length === 0) {
  4600. continue;
  4601. }
  4602. if (isHandledByCustomDirective(clause.clauseStr)) {
  4603. clause.parsed = true;
  4604. continue;
  4605. }
  4606. const [firstElem] = clause.elements;
  4607. let matches = false;
  4608. if (firstElem.type === 'literal') {
  4609. if (firstElem.value.length === 1 && /[(){}[\],:<>=]/.test(firstElem.value)) {
  4610. matches = parser.match(firstElem.value);
  4611. } else {
  4612. matches = parser.match('id', firstElem.value) || parser.match('keyword', firstElem.value);
  4613. }
  4614. }
  4615. if (matches) {
  4616. for (const elem of clause.elements) {
  4617. this.parseDirective(elem, parser, op, opInfo, directives, i);
  4618. }
  4619. clause.parsed = true;
  4620. progress = true;
  4621. }
  4622. }
  4623. }
  4624. break;
  4625. }
  4626. case 'optional_group': {
  4627. let shouldParse = false;
  4628. const firstElem = directive.elements.find((elem) => elem.type !== 'whitespace');
  4629. if (firstElem) {
  4630. if (firstElem.type === 'literal') {
  4631. if (firstElem.value.length === 1 && /[(){}[\],:<>=]/.test(firstElem.value)) {
  4632. shouldParse = parser.match(firstElem.value);
  4633. } else if (firstElem.value === '->') {
  4634. shouldParse = parser.match('->');
  4635. } else {
  4636. shouldParse = parser.match('id', firstElem.value) || parser.match('keyword', firstElem.value);
  4637. }
  4638. } else if (firstElem.type === 'attribute_ref') {
  4639. // Handle attribute variables in optional groups
  4640. // For optional groups, do lookahead before attempting to parse
  4641. // Attribute types parse as: identifiers (enums), @ (symbols), # (attributes), string (strings), [ (arrays)
  4642. if (parser.match('id') || parser.match('#') || parser.match('@') || parser.match('string') || parser.match('[')) {
  4643. const attrInfo = opInfo.metadata && opInfo.metadata.attributes && opInfo.metadata.attributes.find((attr) => attr.name === firstElem.name);
  4644. const attrType = attrInfo ? attrInfo.type : null;
  4645. const result = this._parseCustomAttributeWithFallback(parser, attrType);
  4646. if (result !== null) {
  4647. const value = result.value === undefined ? result : result.value;
  4648. op.attributes.push({ name: firstElem.name, value });
  4649. shouldParse = true;
  4650. }
  4651. }
  4652. } else if (firstElem.type === 'successor_ref') {
  4653. // Handle successor variables in optional groups
  4654. shouldParse = parser.match('^');
  4655. } else if (firstElem.type === 'region_ref') {
  4656. // Handle region variables in optional groups
  4657. shouldParse = parser.match('{');
  4658. } else if (firstElem.type === 'operand_ref') {
  4659. // Handle operand variables in optional groups
  4660. // Check if this is a keyword/enum input rather than an SSA value
  4661. let isKeywordInput = false;
  4662. if (opInfo.metadata && opInfo.metadata.inputs) {
  4663. const inputInfo = opInfo.metadata.inputs.find((inp) => inp.name === firstElem.name);
  4664. if (inputInfo) {
  4665. const inputType = inputInfo.type;
  4666. if (typeof inputType === 'string' &&
  4667. (inputType.includes('Prop') || inputType.endsWith('Predicate') ||
  4668. inputType.includes('Flags') || inputType.includes('Enum'))) {
  4669. isKeywordInput = true;
  4670. }
  4671. }
  4672. }
  4673. if (isKeywordInput) {
  4674. shouldParse = parser.match('id');
  4675. } else {
  4676. // For regular operands, check for %
  4677. shouldParse = parser.match('%');
  4678. }
  4679. } else if (firstElem.type === 'operands') {
  4680. shouldParse = parser.match('(') || parser.match('%');
  4681. } else if (firstElem.type === 'custom') {
  4682. const fn = this._customDirectives.get(firstElem.parser);
  4683. if (fn) {
  4684. const result = fn(parser, op, firstElem.args);
  4685. if (result === null) {
  4686. shouldParse = false;
  4687. } else {
  4688. shouldParse = 'skip_first';
  4689. }
  4690. }
  4691. }
  4692. }
  4693. if (shouldParse) {
  4694. // Recursively parse nested elements using the same parseDirective method
  4695. // If shouldParse === 'skip_first', the custom directive already parsed the first element
  4696. const startIdx = shouldParse === 'skip_first' ? 1 : 0;
  4697. for (let elemIdx = startIdx; elemIdx < directive.elements.length; elemIdx++) {
  4698. this.parseDirective(directive.elements[elemIdx], parser, op, opInfo, directive.elements, elemIdx);
  4699. }
  4700. }
  4701. break;
  4702. }
  4703. case 'conditional_alternative': {
  4704. const checkMatch = (elem) => {
  4705. if (elem.type === 'literal') {
  4706. if (elem.value.length === 1 && /[(){}[\],:<>=]/.test(elem.value)) {
  4707. return parser.match(elem.value);
  4708. }
  4709. return parser.match('id', elem.value) || parser.match('keyword', elem.value);
  4710. }
  4711. if (elem.type === 'operand_ref') {
  4712. return parser.match('%');
  4713. }
  4714. if (elem.type === 'attribute_ref') {
  4715. return parser.match('id') || parser.match('int') || parser.match('float') || parser.match('[') || parser.match('@') || parser.match('#');
  4716. }
  4717. if (elem.type === 'region_ref') {
  4718. return parser.match('{');
  4719. }
  4720. if (elem.type === 'successor_ref') {
  4721. return parser.match('^');
  4722. }
  4723. if (elem.type === 'custom') {
  4724. // Custom directives can start with various tokens including negative integers
  4725. return parser.match('id') || parser.match('int') || parser.match('-') || parser.match('%') || parser.match('[') || parser.match('(');
  4726. }
  4727. return false;
  4728. };
  4729. const firstElem = directive.firstAlt.find((e) => e.type !== 'whitespace');
  4730. const matchedFirst = firstElem && checkMatch(firstElem);
  4731. if (matchedFirst) {
  4732. for (const elem of directive.firstAlt) {
  4733. this.parseDirective(elem, parser, op, opInfo, directive.firstAlt, 0);
  4734. }
  4735. } else if (directive.secondOptional) {
  4736. const secondElem = directive.secondAlt.find((e) => e.type !== 'whitespace');
  4737. const matchedSecond = secondElem && checkMatch(secondElem);
  4738. if (matchedSecond) {
  4739. for (const elem of directive.secondAlt) {
  4740. this.parseDirective(elem, parser, op, opInfo, directive.secondAlt, 0);
  4741. }
  4742. }
  4743. } else if (directive.secondAlt && directive.secondAlt.length > 0) {
  4744. for (const elem of directive.secondAlt) {
  4745. this.parseDirective(elem, parser, op, opInfo, directive.secondAlt, 0);
  4746. }
  4747. }
  4748. break;
  4749. }
  4750. default: {
  4751. throw new mlir.Error(`Unsupported directive type '${directive.type}' ${parser.location()}.`);
  4752. }
  4753. }
  4754. }
  4755. parseOperation(parser, opName, op) {
  4756. const opInfo = this.getOperation(opName);
  4757. if (!opInfo) {
  4758. return false;
  4759. }
  4760. if ((this.hasParser(opName) || this.hasCustomAssemblyFormat(opName)) && !this.hasAssemblyFormat(opName)) {
  4761. throw new mlir.Error(`Operation parser '${opName}' not implemented.`);
  4762. }
  4763. const directives = opInfo.directives || [];
  4764. for (let i = 0; i < directives.length; i++) {
  4765. opInfo.hasParseOperation = false;
  4766. this.parseDirective(directives[i], parser, op, opInfo, directives, i);
  4767. }
  4768. return true;
  4769. }
  4770. parseCustomTypeWithFallback(parser, type) {
  4771. if (type && this._customTypes.has(type.name)) {
  4772. let typeT = this._customTypes.get(type.name);
  4773. if (typeof typeT !== 'function') {
  4774. typeT = { type, name: typeT };
  4775. }
  4776. return parser.parseCustomTypeWithFallback(typeT);
  4777. }
  4778. return parser.parseType();
  4779. }
  4780. _parseCustomAttributeWithFallback(parser, type) {
  4781. if (this._customAttributes.has(type.name)) {
  4782. const attrT = this._customAttributes.get(type.name);
  4783. return parser.parseCustomAttributeWithFallback(attrT, type);
  4784. }
  4785. if (Array.isArray(type.values)) {
  4786. const value = parser.parseOptionalKeyword(type.values);
  4787. if (value !== null) {
  4788. return { value };
  4789. }
  4790. }
  4791. return parser.parseOptionalAttribute();
  4792. }
  4793. _parseOptionalAttr(parser, type) {
  4794. if (!Array.isArray(type.args) || type.args.length === 0) {
  4795. throw new mlir.Error(`Invalid OptionalAttr type.`);
  4796. }
  4797. const [elementType] = type.args;
  4798. return this._parseCustomAttributeWithFallback(parser, elementType);
  4799. }
  4800. _parseDefaultValuedAttr(parser, type) {
  4801. if (!Array.isArray(type.args) || type.args.length === 0) {
  4802. throw new mlir.Error(`Invalid DefaultValuedAttr type.`);
  4803. }
  4804. const [elementType] = type.args;
  4805. return this._parseCustomAttributeWithFallback(parser, elementType);
  4806. }
  4807. _parseDefaultValuedOptionalAttr(parser, type) {
  4808. if (!Array.isArray(type.args) || type.args.length === 0) {
  4809. throw new mlir.Error(`Invalid DefaultValuedOptionalAttr type.`);
  4810. }
  4811. const [elementType] = type.args;
  4812. return this._parseCustomAttributeWithFallback(parser, elementType);
  4813. }
  4814. _parseTypeAttrOf(parser, type) {
  4815. if (!Array.isArray(type.args) || type.args.length === 0) {
  4816. throw new mlir.Error(`Invalid TypeAttrOf type.`);
  4817. }
  4818. const parsedType = parser.parseOptionalType();
  4819. if (parsedType) {
  4820. return { value: parsedType, type: 'type' };
  4821. }
  4822. return null;
  4823. }
  4824. _parseAnyAttrOf(parser, type) {
  4825. if (!Array.isArray(type.args) || type.args.length === 0) {
  4826. throw new mlir.Error(`Invalid AnyAttrOf type.`);
  4827. }
  4828. const [types] = type.args;
  4829. for (const allowedType of types) {
  4830. const result = this._parseCustomAttributeWithFallback(parser, allowedType);
  4831. if (result !== null) {
  4832. return result;
  4833. }
  4834. }
  4835. return null;
  4836. }
  4837. _parseArrayAttr(parser) {
  4838. if (parser.match('[')) {
  4839. return parser.parseOptionalAttribute();
  4840. }
  4841. return null;
  4842. }
  4843. _parseConfinedAttr(parser, type) {
  4844. // ConfinedAttr<BaseAttr, Constraints> - parse the base attribute type
  4845. if (!Array.isArray(type.args) || type.args.length === 0) {
  4846. throw new mlir.Error(`Invalid ConfinedAttr type.`);
  4847. }
  4848. const [baseType] = type.args;
  4849. return this._parseCustomAttributeWithFallback(parser, baseType);
  4850. }
  4851. // Reference: TypedAttrInterface attributes parse via parseAttribute()
  4852. // parseAttribute handles `: type` suffix internally when type is null
  4853. _parseTypedAttrInterface(parser) {
  4854. return parser.parseAttribute();
  4855. }
  4856. _parseUnitAttr() {
  4857. return { value: true };
  4858. }
  4859. _parseSymbolNameAttr(parser) {
  4860. if (parser.match('@')) {
  4861. const value = parser.expect('@');
  4862. return { value: value.substring(1) };
  4863. }
  4864. return null;
  4865. }
  4866. // Parse typed integer attribute (I64Attr, I32Attr, etc.)
  4867. // Reference: for typed attributes, the type is known so no : type suffix parsing
  4868. _parseIntegerAttr(typeName, parser) {
  4869. const type = new mlir.PrimitiveType(typeName);
  4870. // Use parseAttribute with the known type to avoid suffix parsing
  4871. return parser.parseAttribute(type);
  4872. }
  4873. // Parse typed float attribute (F64Attr, F32Attr, etc.)
  4874. _parseFloatAttr(typeName, parser) {
  4875. const type = new mlir.PrimitiveType(typeName);
  4876. // Use parseAttribute with the known type to avoid suffix parsing
  4877. return parser.parseAttribute(type);
  4878. }
  4879. // Parse string attribute (StrAttr)
  4880. // Pass string type to prevent : type suffix parsing
  4881. _parseStrAttr(parser) {
  4882. const type = new mlir.PrimitiveType('string');
  4883. return parser.parseAttribute(type);
  4884. }
  4885. _parseDynamicIndexList(parser, op, args) {
  4886. // Determine delimiter from args (default to square brackets for backward compatibility)
  4887. // Args format: [$dynamic_basis, $static_basis, $scalable_basis, "::mlir::AsmParser::Delimiter::Paren"]
  4888. let openDelim = '[';
  4889. let closeDelim = ']';
  4890. if (args && args.length > 3) {
  4891. const [, , , delimiterSpec] = args;
  4892. if (typeof delimiterSpec === 'string' && delimiterSpec.includes('Paren')) {
  4893. openDelim = '(';
  4894. closeDelim = ')';
  4895. }
  4896. }
  4897. const dynamicOperands = [];
  4898. const staticValues = [];
  4899. const scalableFlags = [];
  4900. if (parser.accept(openDelim)) {
  4901. while (!parser.match(closeDelim)) {
  4902. const isScalable = parser.accept('[');
  4903. if (parser.match('%')) {
  4904. const value = parser.expect('%');
  4905. dynamicOperands.push({ value });
  4906. staticValues.push(-9223372036854775808); // ShapedType::kDynamic
  4907. if (parser.accept(':')) {
  4908. parser.parseType();
  4909. }
  4910. } else if (parser.match('int') || parser.match('number')) {
  4911. const intVal = parseInt(parser.expect(), 10);
  4912. staticValues.push(intVal);
  4913. } else {
  4914. break;
  4915. }
  4916. scalableFlags.push(isScalable);
  4917. if (isScalable) {
  4918. if (!parser.accept(']')) {
  4919. throw new mlir.Error(`Expected ']' for scalable index ${parser.location()}`);
  4920. }
  4921. }
  4922. parser.accept(',');
  4923. }
  4924. parser.expect(closeDelim);
  4925. }
  4926. for (const operand of dynamicOperands) {
  4927. op.operands.push(operand);
  4928. }
  4929. if (args && args.length > 1) {
  4930. const staticAttrName = args[1].replace(/^\$/, '');
  4931. op.attributes.push({ name: staticAttrName, value: staticValues });
  4932. }
  4933. if (args && args.length > 2 && scalableFlags.length > 0) {
  4934. const scalableAttrName = args[2].replace(/^\$/, '');
  4935. op.attributes.push({ name: scalableAttrName, value: scalableFlags });
  4936. }
  4937. }
  4938. _parseOffsets(parser, op, args) {
  4939. const values = [];
  4940. while (parser.match('int') || parser.match('-')) {
  4941. if (parser.accept('-')) {
  4942. if (parser.match('int')) {
  4943. values.push(-parser.parseInteger());
  4944. } else {
  4945. throw new mlir.Error(`Expected integer after '-' in offsets ${parser.location()}`);
  4946. }
  4947. } else {
  4948. values.push(parser.parseInteger());
  4949. }
  4950. if (!parser.accept(',')) {
  4951. break;
  4952. }
  4953. }
  4954. if (args && args.length > 0) {
  4955. const attrName = args[0].replace(/^\$/, '');
  4956. op.attributes.push({ name: attrName, value: values });
  4957. }
  4958. }
  4959. _parseSymbolVisibility(parser, op, args) {
  4960. let visibility = null;
  4961. if (parser.match('id', 'private') || parser.match('id', 'public') || parser.match('id', 'nested')) {
  4962. visibility = parser.expect('id');
  4963. } else if (parser.match('string')) {
  4964. visibility = parser.expect('string');
  4965. }
  4966. if (visibility && args && args.length > 0) {
  4967. const attrName = args[0].replace(/^\$/, '');
  4968. op.attributes.push({ name: attrName, value: visibility });
  4969. }
  4970. }
  4971. _parseTypeOrAttr(parser, op, args) {
  4972. const [typeArg, attrArg] = args;
  4973. if (parser.accept('=')) {
  4974. const attr = parser.parseAttribute();
  4975. if (parser.accept(':')) {
  4976. const type = parser.parseType();
  4977. const typeIndex = op.attributes.findIndex((a) => a.name === typeArg);
  4978. if (typeIndex === -1) {
  4979. op.attributes.push({ name: typeArg, value: type });
  4980. } else {
  4981. op.attributes[typeIndex].value = type;
  4982. }
  4983. attr.type = type;
  4984. } else if (attr && attr.type) {
  4985. const typeIndex = op.attributes.findIndex((a) => a.name === typeArg);
  4986. if (typeIndex === -1) {
  4987. op.attributes.push({ name: typeArg, value: attr.type });
  4988. } else {
  4989. op.attributes[typeIndex].value = attr.type;
  4990. }
  4991. }
  4992. const attrIndex = op.attributes.findIndex((a) => a.name === attrArg);
  4993. if (attrIndex === -1) {
  4994. op.attributes.push({ name: attrArg, value: attr });
  4995. } else {
  4996. op.attributes[attrIndex].value = attr;
  4997. }
  4998. return;
  4999. }
  5000. if (parser.accept(':')) {
  5001. const type = parser.parseType();
  5002. const typeIndex = op.attributes.findIndex((a) => a.name === typeArg);
  5003. if (typeIndex === -1) {
  5004. op.attributes.push({ name: typeArg, value: type });
  5005. } else {
  5006. op.attributes[typeIndex].value = type;
  5007. }
  5008. if (parser.accept('=')) {
  5009. const attr = parser.parseAttribute();
  5010. // Handle typed attribute with trailing : type (e.g., -2 : i8)
  5011. if (parser.accept(':')) {
  5012. const attrType = parser.parseType();
  5013. attr.type = attrType;
  5014. }
  5015. const attrIndex = op.attributes.findIndex((a) => a.name === attrArg);
  5016. if (attrIndex === -1) {
  5017. op.attributes.push({ name: attrArg, value: attr });
  5018. } else {
  5019. op.attributes[attrIndex].value = attr;
  5020. }
  5021. }
  5022. return;
  5023. }
  5024. throw new mlir.Error(`Expected ':' or '=' in TypeOrAttr ${parser.location()}`);
  5025. }
  5026. _parseEnumFlags(parser, type, separator) {
  5027. const flags = [];
  5028. do {
  5029. const value = parser.expect('id');
  5030. if (!type.values.includes(value)) {
  5031. throw new mlir.Error(`Invalid enum value '${value}' ${parser.location()}`);
  5032. }
  5033. flags.push(value);
  5034. } while (parser.accept(separator));
  5035. return { value: flags.join(', ') };
  5036. }
  5037. _parseEnumFlagsAngleBracketComma(parser, type) {
  5038. if (parser.accept('<')) {
  5039. const value = this._parseEnumFlags(parser, type, ',');
  5040. parser.expect('>');
  5041. return value;
  5042. }
  5043. return parser.parseOptionalAttribute();
  5044. }
  5045. _parseEnumFlagsAngleBracketPipe(parser, type) {
  5046. if (parser.accept('<')) {
  5047. const value = this._parseEnumFlags(parser, type, '|');
  5048. parser.expect('>');
  5049. return value;
  5050. }
  5051. return parser.parseOptionalAttribute();
  5052. }
  5053. _parseOptional(parser) {
  5054. return parser.parseOptionalType();
  5055. }
  5056. };
  5057. mlir.HLODialect = class extends mlir.Dialect {
  5058. constructor(name, operations) {
  5059. super(name, operations);
  5060. this.registerCustomDirective('SameOperandsAndResultType', this._parseSameOperandsAndResultType.bind(this));
  5061. this.registerCustomDirective('VariadicSameOperandsAndResultType', this._parseVariadicSameOperandsAndResultType.bind(this));
  5062. this.registerCustomDirective('ComplexOpType', this._parseComplexOpType.bind(this));
  5063. this.registerCustomDirective('SelectOpType', this._parseSelectOpType.bind(this));
  5064. this.registerCustomDirective('TupleOpType', this._parseTupleOpType.bind(this));
  5065. this.registerCustomDirective('PairwiseOpType', this._parsePairwiseOpType.bind(this));
  5066. this.registerCustomDirective('ConvolutionDimensions', this._parseConvolutionDimensions.bind(this));
  5067. this.registerCustomDirective('DotDimensionNumbers', this._parseDotDimensionNumbers.bind(this));
  5068. this.registerCustomDirective('PrecisionConfig', this._parsePrecisionConfig.bind(this));
  5069. this.registerCustomDirective('PrecisionConfigAndAlgorithm', this._parsePrecisionConfigAndAlgorithm.bind(this));
  5070. this.registerCustomDirective('WindowAttributes', this._parseWindowAttributes.bind(this));
  5071. this.registerCustomDirective('SliceRanges', this._parseSliceRanges.bind(this));
  5072. this.registerCustomDirective('CustomCallTarget', this._parseCustomCallTarget.bind(this));
  5073. this.registerCustomDirective('VariadicOperandWithAttribute', this._parseVariadicOperandWithAttribute.bind(this));
  5074. }
  5075. _parseSameOperandsAndResultType(parser, op /*, args */) {
  5076. const type = parser.parseType();
  5077. if (type instanceof mlir.FunctionType) {
  5078. for (let i = 0; i < op.operands.length; i++) {
  5079. const inputType = type.inputs[i];
  5080. if (inputType) {
  5081. op.operands[i].type = op.operands[i].type || inputType;
  5082. }
  5083. }
  5084. const [resultType] = type.results;
  5085. if (type.results[0] && op.results.length > 0 && !op.results[0].type) {
  5086. op.results[0].type = resultType;
  5087. }
  5088. } else {
  5089. for (const operand of op.operands) {
  5090. operand.type = operand.type || type;
  5091. }
  5092. if (op.results.length > 0 && !op.results[0].type) {
  5093. op.results[0].type = type;
  5094. }
  5095. }
  5096. }
  5097. _parseVariadicSameOperandsAndResultType(parser, op /*, args */) {
  5098. // Parse type: either a bare type (all operands/results same) or function type
  5099. const type = parser.parseType();
  5100. if (type instanceof mlir.FunctionType) {
  5101. // Function type: zip each operand with corresponding input type
  5102. for (let i = 0; i < op.operands.length; i++) {
  5103. const inputType = type.getInput(i);
  5104. if (inputType && !op.operands[i].type) {
  5105. op.operands[i].type = inputType;
  5106. }
  5107. }
  5108. // Handle multiple results
  5109. for (let i = 0; i < op.results.length; i++) {
  5110. const resultType = type.getResult(i);
  5111. if (resultType && !op.results[i].type) {
  5112. op.results[i].type = resultType;
  5113. }
  5114. }
  5115. } else {
  5116. // Bare type: all operands and results have the same type
  5117. const typeString = type.toString();
  5118. for (const operand of op.operands) {
  5119. if (!operand.type) {
  5120. operand.type = typeString;
  5121. }
  5122. }
  5123. for (const result of op.results) {
  5124. if (!result.type) {
  5125. result.type = typeString;
  5126. }
  5127. }
  5128. }
  5129. }
  5130. _parseComplexOpType(parser, op /*, args */) {
  5131. const type = parser.parseType();
  5132. const typeString = type.toString();
  5133. // Apply type to operands and results (for complex operations)
  5134. for (const operand of op.operands) {
  5135. if (!operand.type) {
  5136. operand.type = typeString;
  5137. }
  5138. }
  5139. for (const result of op.results) {
  5140. if (!result.type) {
  5141. result.type = typeString;
  5142. }
  5143. }
  5144. }
  5145. _parseSelectOpType(parser, op /*, args */) {
  5146. const firstType = parser.parseType();
  5147. const firstTypeString = firstType.toString();
  5148. if (parser.accept(',')) {
  5149. const secondType = parser.parseType();
  5150. const secondTypeString = secondType.toString();
  5151. // predType and resultType case
  5152. if (op.operands.length > 0 && !op.operands[0].type) {
  5153. op.operands[0].type = firstTypeString;
  5154. }
  5155. if (op.results.length > 0 && !op.results[0].type) {
  5156. op.results[0].type = secondTypeString;
  5157. }
  5158. } else if (op.results.length > 0 && !op.results[0].type) {
  5159. op.results[0].type = firstTypeString;
  5160. }
  5161. }
  5162. _parseTupleOpType(parser, op /*, args */) {
  5163. const type = parser.parseType();
  5164. // Apply type to operands and results
  5165. for (const operand of op.operands) {
  5166. if (!operand.type) {
  5167. operand.type = type;
  5168. }
  5169. }
  5170. for (const result of op.results) {
  5171. if (!result.type) {
  5172. result.type = type;
  5173. }
  5174. }
  5175. }
  5176. _parsePairwiseOpType(parser, op /*, args */) {
  5177. const types = [];
  5178. while (true) {
  5179. const type = parser.parseType();
  5180. if (!type) {
  5181. break;
  5182. }
  5183. types.push(type);
  5184. if (!parser.accept(',')) {
  5185. break;
  5186. }
  5187. }
  5188. // Apply types pairwise to operands and results
  5189. for (let i = 0; i < types.length && i < op.operands.length; i++) {
  5190. if (!op.operands[i].type) {
  5191. op.operands[i].type = types[i];
  5192. }
  5193. }
  5194. for (let i = 0; i < types.length && i < op.results.length; i++) {
  5195. if (!op.results[i].type) {
  5196. op.results[i].type = types[i];
  5197. }
  5198. }
  5199. }
  5200. _parseConvolutionDimensions(parser, op, args) {
  5201. const dimensions = {
  5202. input: [],
  5203. kernel: [],
  5204. output: []
  5205. };
  5206. if (parser.accept('[')) {
  5207. while (!parser.match(']')) {
  5208. if (parser.match('int') || parser.match('number')) {
  5209. dimensions.input.push(parseInt(parser.expect(), 10));
  5210. } else if (parser.match('id')) {
  5211. dimensions.input.push(parser.expect('id'));
  5212. } else {
  5213. break;
  5214. }
  5215. parser.accept(',');
  5216. }
  5217. parser.accept(']');
  5218. }
  5219. if (parser.accept('id', 'x')) {
  5220. if (parser.accept('[')) {
  5221. while (!parser.match(']')) {
  5222. if (parser.match('int') || parser.match('number')) {
  5223. dimensions.kernel.push(parseInt(parser.expect(), 10));
  5224. } else if (parser.match('id')) {
  5225. dimensions.kernel.push(parser.expect('id'));
  5226. } else {
  5227. break;
  5228. }
  5229. parser.accept(',');
  5230. }
  5231. parser.accept(']');
  5232. }
  5233. }
  5234. if (parser.accept('->')) {
  5235. if (parser.accept('[')) {
  5236. while (!parser.match(']')) {
  5237. if (parser.match('int') || parser.match('number')) {
  5238. dimensions.output.push(parseInt(parser.expect(), 10));
  5239. } else if (parser.match('id')) {
  5240. dimensions.output.push(parser.expect('id'));
  5241. } else {
  5242. break;
  5243. }
  5244. parser.accept(',');
  5245. }
  5246. parser.accept(']');
  5247. }
  5248. }
  5249. const attrName = args && args.length > 0 ? args[0].replace(/^\$/, '') : 'dimension_numbers';
  5250. op.attributes.push({ name: attrName, value: dimensions });
  5251. }
  5252. _parseWindowAttributes(parser, op, args) {
  5253. const windowAttrs = {
  5254. stride: [],
  5255. pad: [],
  5256. lhs_dilate: [],
  5257. rhs_dilate: [],
  5258. window_reversal: []
  5259. };
  5260. // Reference: StablehloOps.cpp:3902 parseWindowAttributes uses parseCommaSeparatedList
  5261. const parseArray = () => {
  5262. return parser.parseCommaSeparatedList('square', () => {
  5263. if (parser.match('[')) {
  5264. return parseArray();
  5265. } else if (parser.match('int') || parser.match('number')) {
  5266. return parseInt(parser.expect(), 10);
  5267. } else if (parser.match('boolean')) {
  5268. return parser.expect('boolean');
  5269. } else if (parser.match('id')) {
  5270. return parser.expect('id');
  5271. }
  5272. return null;
  5273. });
  5274. };
  5275. while (!parser.match('}')) {
  5276. if (parser.match('id')) {
  5277. const key = parser.expect('id');
  5278. if (parser.accept('=')) {
  5279. windowAttrs[key] = parseArray();
  5280. }
  5281. parser.accept(',');
  5282. } else {
  5283. break;
  5284. }
  5285. }
  5286. if (args && args.length > 0) {
  5287. for (let i = 0; i < args.length; i++) {
  5288. const argName = args[i].replace(/^\$/, '');
  5289. if (argName === 'window_strides' && windowAttrs.stride) {
  5290. op.attributes.push({ name: argName, value: windowAttrs.stride });
  5291. } else if (argName === 'padding' && windowAttrs.pad) {
  5292. op.attributes.push({ name: argName, value: windowAttrs.pad });
  5293. } else if (argName === 'lhs_dilation' && windowAttrs.lhs_dilate) {
  5294. op.attributes.push({ name: argName, value: windowAttrs.lhs_dilate });
  5295. } else if (argName === 'rhs_dilation' && windowAttrs.rhs_dilate) {
  5296. op.attributes.push({ name: argName, value: windowAttrs.rhs_dilate });
  5297. } else if (argName === 'window_reversal' && windowAttrs.window_reversal) {
  5298. op.attributes.push({ name: argName, value: windowAttrs.window_reversal });
  5299. }
  5300. }
  5301. }
  5302. }
  5303. _parseDotDimensionNumbers(parser, op, args) {
  5304. const dimensions = {
  5305. lhs_batching_dimensions: [],
  5306. rhs_batching_dimensions: [],
  5307. lhs_contracting_dimensions: [],
  5308. rhs_contracting_dimensions: []
  5309. };
  5310. // Reference: AssemblyFormat.h:343 parseDotDimensionNumbers uses DenseI64ArrayAttr::parse
  5311. // which uses parseCommaSeparatedList (BuiltinAttributes.cpp:836)
  5312. const parseIntArray = () => {
  5313. return parser.parseCommaSeparatedList('optionalSquare', () => {
  5314. if (parser.match('int')) {
  5315. return parser.parseInteger();
  5316. }
  5317. parser.expect();
  5318. return null;
  5319. });
  5320. };
  5321. const parsePair = () => {
  5322. const first = parseIntArray();
  5323. let second = [];
  5324. if (parser.accept('id', 'x')) {
  5325. second = parseIntArray();
  5326. }
  5327. return { first, second };
  5328. };
  5329. if (parser.match('id', 'batching_dims') || parser.match('id', 'batch_dims')) {
  5330. parser.expect('id');
  5331. parser.accept('=');
  5332. const pair = parsePair();
  5333. dimensions.lhs_batching_dimensions = pair.first;
  5334. dimensions.rhs_batching_dimensions = pair.second;
  5335. parser.accept(',');
  5336. }
  5337. if (parser.accept('id', 'contracting_dims')) {
  5338. parser.accept('=');
  5339. const pair = parsePair();
  5340. dimensions.lhs_contracting_dimensions = pair.first;
  5341. dimensions.rhs_contracting_dimensions = pair.second;
  5342. }
  5343. // Add as attribute with name from args
  5344. const attrName = args && args.length > 0 ? args[0].replace(/^\$/, '') : 'dot_dimension_numbers';
  5345. op.attributes.push({ name: attrName, value: dimensions });
  5346. }
  5347. _parsePrecisionConfig(parser, op /*, args */) {
  5348. parser.accept(',');
  5349. if (!parser.match('id', 'precision')) {
  5350. return;
  5351. }
  5352. parser.expect('id', 'precision');
  5353. parser.expect('=');
  5354. // Reference: StablehloOps.cpp:762 parsePrecisionConfigImpl uses parseCommaSeparatedList
  5355. const precision = parser.parseCommaSeparatedList('square', () => {
  5356. if (parser.match('id')) {
  5357. return parser.expect('id');
  5358. }
  5359. parser.expect();
  5360. return null;
  5361. });
  5362. if (precision.length > 0) {
  5363. op.attributes.push({ name: 'precision_config', value: precision });
  5364. }
  5365. }
  5366. _parsePrecisionConfigAndAlgorithm(parser, op /*, args */) {
  5367. if (!parser.accept(',')) {
  5368. return;
  5369. }
  5370. if (parser.accept('id', 'algorithm')) {
  5371. parser.accept('=');
  5372. const algorithm = parser.parseAttribute();
  5373. op.attributes.push({ name: 'algorithm', value: algorithm });
  5374. return;
  5375. }
  5376. if (parser.accept('id', 'precision')) {
  5377. parser.accept('=');
  5378. // Reference: StablehloOps.cpp:810 calls parsePrecisionConfigImpl which uses parseCommaSeparatedList
  5379. const precision = parser.parseCommaSeparatedList('optionalSquare', () => {
  5380. if (parser.match('id')) {
  5381. return parser.expect('id');
  5382. }
  5383. parser.expect();
  5384. return null;
  5385. });
  5386. if (precision.length > 0) {
  5387. op.attributes.push({ name: 'precision_config', value: precision });
  5388. }
  5389. if (parser.accept(',')) {
  5390. if (parser.accept('id', 'algorithm')) {
  5391. parser.accept('=');
  5392. const algorithm = parser.parseAttribute();
  5393. op.attributes.push({ name: 'algorithm', value: algorithm });
  5394. }
  5395. }
  5396. }
  5397. }
  5398. _parseSliceRanges(parser, op /*, args */) {
  5399. const ranges = {
  5400. start_indices: [],
  5401. limit_indices: [],
  5402. strides: []
  5403. };
  5404. if (parser.accept('[')) {
  5405. while (!parser.match(']')) {
  5406. if (parser.match('int')) {
  5407. ranges.start_indices.push(parser.parseInteger());
  5408. }
  5409. parser.accept(':');
  5410. if (parser.match('int')) {
  5411. ranges.limit_indices.push(parser.parseInteger());
  5412. }
  5413. if (parser.accept(':')) {
  5414. if (parser.match('int')) {
  5415. ranges.strides.push(parser.parseInteger());
  5416. }
  5417. } else {
  5418. ranges.strides.push(1);
  5419. }
  5420. parser.accept(',');
  5421. }
  5422. parser.accept(']');
  5423. }
  5424. // Add as attributes
  5425. op.attributes.push({ name: 'start_indices', value: ranges.start_indices });
  5426. op.attributes.push({ name: 'limit_indices', value: ranges.limit_indices });
  5427. op.attributes.push({ name: 'strides', value: ranges.strides });
  5428. }
  5429. _parseCustomCallTarget(parser, op, args) {
  5430. let target = null;
  5431. if (parser.match('@')) {
  5432. target = parser.expect('@');
  5433. } else if (parser.match('string')) {
  5434. target = parser.expect('string');
  5435. } else {
  5436. throw new mlir.Error(`Expected '@' or string for CustomCallTarget at ${parser.location()}`);
  5437. }
  5438. // Add as attribute
  5439. const attrName = args && args.length > 0 ? args[0].replace(/^\$/, '') : 'call_target_name';
  5440. op.attributes.push({ name: attrName, value: target });
  5441. }
  5442. _parseVariadicOperandWithAttribute(parser, op /*, args */) {
  5443. while (parser.match('%')) {
  5444. const operand = {
  5445. value: parser.expect('%'),
  5446. attributes: []
  5447. };
  5448. // Check for inline attributes
  5449. if (parser.match('{')) {
  5450. parser.parseAttributeDict(operand.attributes);
  5451. }
  5452. op.operands.push(operand);
  5453. if (!parser.accept(',')) {
  5454. break;
  5455. }
  5456. }
  5457. }
  5458. };
  5459. mlir.StableHLODialect = class extends mlir.HLODialect {
  5460. constructor(operations) {
  5461. super('stablehlo', operations);
  5462. this.registerCustomDirective('ExponentMantissa', this._parseExponentMantissa.bind(this));
  5463. }
  5464. _parseExponentMantissa(parser, op, args) {
  5465. const keyword = parser.expect('id');
  5466. const match = /^e(\d+)m(\d+)$/.exec(keyword);
  5467. if (!match) {
  5468. throw new mlir.Error(`Expected exponent mantissa in format e#m#, got '${keyword}'`);
  5469. }
  5470. const exponent = parseInt(match[1], 10);
  5471. const mantissa = parseInt(match[2], 10);
  5472. const exponentVar = args[0].replace('$', '');
  5473. const mantissaVar = args[1].replace('$', '');
  5474. op.attributes.push({ name: exponentVar, value: exponent });
  5475. op.attributes.push({ name: mantissaVar, value: mantissa });
  5476. }
  5477. parseType(parser, dialectName) {
  5478. const typeName = parser.parseKeyword();
  5479. if (typeName === 'token') {
  5480. return new mlir.Type(`!${dialectName}.token`);
  5481. }
  5482. return null;
  5483. }
  5484. parseOperation(parser, opName, op) {
  5485. // Reference: stablehlo/dialect/StablehloOps.cpp parseConstantOp
  5486. if (opName === 'stablehlo.constant') {
  5487. // Generic form: () <properties> {attrs} : () -> type
  5488. if (parser.accept('(') && parser.accept(')')) {
  5489. // Parse optional properties <...>
  5490. if (parser.accept('<')) {
  5491. op.properties = parser.parseAttribute();
  5492. parser.expect('>');
  5493. }
  5494. // Parse optional attributes
  5495. parser.parseOptionalAttrDict(op.attributes);
  5496. // Parse type signature: : () -> type
  5497. parser.expect(':');
  5498. parser.expect('(');
  5499. parser.expect(')');
  5500. parser.expect('->');
  5501. const type = parser.parseType();
  5502. op.results.push({ type: type.toString() });
  5503. } else {
  5504. // Custom form: {attrs} value : type
  5505. parser.parseOptionalAttrDict(op.attributes);
  5506. const value = parser.parseAttribute();
  5507. if (value) {
  5508. op.attributes.push({ name: 'value', value: value.value });
  5509. }
  5510. // Parse result type - either explicit `: type` or from value's type
  5511. const types = parser.parseOptionalColonTypeList();
  5512. if (types.length > 0) {
  5513. op.results.push({ type: types[0].toString() });
  5514. } else if (value && value.type) {
  5515. op.results.push({ type: value.type.toString() });
  5516. }
  5517. }
  5518. return true;
  5519. }
  5520. if (opName === 'stablehlo.while' && parser.match('(')) {
  5521. parser.accept('(');
  5522. while (!parser.match(')')) {
  5523. const arg = {};
  5524. arg.value = parser.expect('%');
  5525. if (parser.accept('=')) {
  5526. arg.name = arg.value;
  5527. arg.value = parser.expect('%');
  5528. }
  5529. op.operands.push(arg);
  5530. parser.accept(',');
  5531. }
  5532. parser.expect(')');
  5533. if (parser.accept(':')) {
  5534. let index = 0;
  5535. while (!parser.match('id', 'cond') && !parser.match('id', 'attributes') && index < op.operands.length * 2) {
  5536. const type = parser.parseType();
  5537. if (index < op.operands.length) {
  5538. op.operands[index].type = type;
  5539. }
  5540. if (index < op.results.length) {
  5541. op.results[index].type = type;
  5542. }
  5543. index++;
  5544. if (!parser.accept(',')) {
  5545. break;
  5546. }
  5547. }
  5548. }
  5549. if (parser.accept('id', 'attributes')) {
  5550. if (parser.match('{')) {
  5551. parser.parseAttributeDict(op.attributes);
  5552. }
  5553. }
  5554. if (parser.accept('id', 'cond')) {
  5555. const condRegion = {};
  5556. parser.parseRegion(condRegion);
  5557. op.regions.push(condRegion);
  5558. }
  5559. if (parser.accept('id', 'do')) {
  5560. const bodyRegion = {};
  5561. parser.parseRegion(bodyRegion);
  5562. op.regions.push(bodyRegion);
  5563. }
  5564. return true;
  5565. }
  5566. if ((opName === 'stablehlo.reduce' || opName === 'stablehlo.scan') && parser.match('(')) {
  5567. return this._parseReduceLikeOp(parser, op);
  5568. }
  5569. return super.parseOperation(parser, opName, op);
  5570. }
  5571. _parseReduceLikeOp(parser, op) {
  5572. op.operands = parser.parseArguments();
  5573. while (parser.accept(',')) {
  5574. const moreOperands = parser.parseArguments();
  5575. op.operands.push(...moreOperands);
  5576. }
  5577. if (parser.accept('id', 'applies')) {
  5578. const innerOpName = parser.expect('id');
  5579. op.attributes.push({ name: 'body_op', value: innerOpName });
  5580. if (parser.accept('id', 'across')) {
  5581. if (parser.accept('id', 'dimensions')) {
  5582. parser.accept('=');
  5583. const dims = parser.parseAttribute();
  5584. op.attributes.push({ name: 'dimensions', value: dims });
  5585. }
  5586. }
  5587. if (parser.match('{')) {
  5588. parser.parseAttributeDict(op.attributes);
  5589. }
  5590. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  5591. parser.resolveOperands(op.results, parser.parseOptionalArrowTypeList());
  5592. return true;
  5593. }
  5594. if (parser.match('(')) {
  5595. // Generic form with parenthesized region-list: ({ ... })
  5596. if (parser.accept('(') && parser.match('{')) {
  5597. let regionCount = 0;
  5598. while (!parser.match(')')) {
  5599. if (regionCount++ > 10) {
  5600. throw new mlir.Error(`Too many regions in region-list (>10) - possible infinite loop at ${parser.location()}, current token: '${parser.token.value}'`);
  5601. }
  5602. if (!parser.match('{')) {
  5603. throw new mlir.Error(`Expected '{' for region in region-list, got '${parser.token.value}' at ${parser.location()}`);
  5604. }
  5605. const region = {};
  5606. parser.parseRegion(region);
  5607. op.regions.push(region);
  5608. if (!parser.accept(',') && !parser.match(')')) {
  5609. throw new mlir.Error(`Expected ',' or ')' after region, got '${parser.token.value}' at ${parser.location()}`);
  5610. }
  5611. }
  5612. parser.expect(')');
  5613. }
  5614. // Parse attributes dictionary { dimensions = ... }
  5615. if (parser.match('{')) {
  5616. parser.parseAttributeDict(op.attributes);
  5617. }
  5618. // Parse type signature : (...) -> (...)
  5619. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  5620. if (parser.accept('->') || parser.accept('id', 'to')) {
  5621. if (op.results.length > 0) {
  5622. const types = parser.parseFunctionResultTypes();
  5623. parser.resolveOperands(op.results, types);
  5624. } else {
  5625. op.results = parser.parseArguments();
  5626. }
  5627. }
  5628. return true;
  5629. }
  5630. // Handle "across dimensions = [...]"
  5631. if (parser.accept('id', 'across')) {
  5632. if (parser.accept('id', 'dimensions')) {
  5633. parser.expect('=');
  5634. parser.skip('[', ']');
  5635. }
  5636. }
  5637. // Type signature
  5638. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  5639. if (parser.accept('->') || parser.accept('id', 'to')) {
  5640. if (op.results.length > 0) {
  5641. const types = parser.parseFunctionResultTypes();
  5642. parser.resolveOperands(op.results, types);
  5643. } else {
  5644. op.results = parser.parseArguments();
  5645. }
  5646. }
  5647. // Handle regions
  5648. if (parser.match('id') && !parser.match('keyword', 'loc')) {
  5649. // Labeled region: reducer(...) { ... } or reducer(...) (...) { ... }
  5650. const label = parser.expect('id');
  5651. const region = { blocks: [] };
  5652. const block = { operations: [], arguments: [], name: label };
  5653. while (parser.accept('(')) {
  5654. while (!parser.accept(')')) {
  5655. const value = parser.expect('%');
  5656. parser.expect(':');
  5657. const type = parser.parseType();
  5658. block.arguments.push({ value, type });
  5659. parser.accept(',');
  5660. }
  5661. }
  5662. parser.expect('{');
  5663. while (!parser.accept('}')) {
  5664. const innerOp = parser.parseOperation();
  5665. block.operations.push(innerOp);
  5666. }
  5667. block.loc = parser.parseLocation();
  5668. region.blocks.push(block);
  5669. op.regions.push(region);
  5670. } else if (parser.accept('(') && parser.match('{')) {
  5671. // Parenthesized region list: ({ ... })
  5672. const region = {};
  5673. parser.parseRegion(region);
  5674. op.regions.push(region);
  5675. parser.expect(')');
  5676. } else if (parser.match('{')) {
  5677. // Simple region: { ... }
  5678. const region = {};
  5679. parser.parseRegion(region);
  5680. op.regions.push(region);
  5681. }
  5682. return true;
  5683. }
  5684. };
  5685. mlir.VhloDialect = class extends mlir.Dialect {
  5686. constructor(operations) {
  5687. super('vhlo', operations);
  5688. }
  5689. parseOperation(parser, opName, op) {
  5690. if (opName === 'vhlo.constant_v1') {
  5691. if (parser.match('{')) {
  5692. parser.parseAttributeDict(op.attributes);
  5693. }
  5694. const value = parser.parseAttribute();
  5695. if (value) {
  5696. op.attributes.push({ name: 'value', value: value.value });
  5697. }
  5698. // Parse result type: : tensor<...>
  5699. parser.resolveOperands(op.results, parser.parseOptionalColonTypeList());
  5700. return true;
  5701. }
  5702. if (opName === 'vhlo.return_v1') {
  5703. op.operands = parser.parseArguments();
  5704. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  5705. return true;
  5706. }
  5707. if (opName === 'vhlo.func_v1') {
  5708. parser.parseOptionalVisibilityKeyword(op.attributes);
  5709. parser.parseSymbolName(opName, op.attributes);
  5710. if (parser.accept('(')) {
  5711. op.attributes.push({ name: 'inputs', value: parser.parseTypeList() });
  5712. parser.accept(')');
  5713. }
  5714. if (parser.accept('->')) {
  5715. const outputType = parser.parseType();
  5716. if (outputType) {
  5717. const outputs = outputType.value === 'tuple' ? outputType.params : [outputType];
  5718. op.attributes.push({ name: 'outputs', value: outputs });
  5719. }
  5720. }
  5721. if (parser.match('{')) {
  5722. parser.parseAttributeDict(op.attributes);
  5723. }
  5724. op.regions = [parser.parseRegion()];
  5725. return true;
  5726. }
  5727. return false;
  5728. }
  5729. };
  5730. mlir.InterpreterDialect = class extends mlir.Dialect {
  5731. constructor(operations) {
  5732. super('interpreter', operations);
  5733. }
  5734. };
  5735. mlir.AffineDialect = class extends mlir.Dialect {
  5736. constructor(operations) {
  5737. super('affine', operations);
  5738. }
  5739. parseOperation(parser, opName, op) {
  5740. if (opName === 'affine.parallel') {
  5741. return this._parseParallelOp(parser, op);
  5742. }
  5743. // Special handling for affine.for - similar to scf.for but with affine expressions
  5744. if (opName === 'affine.for') {
  5745. return this._parseForOp(parser, op);
  5746. }
  5747. // Special handling for affine.if - has condition before region
  5748. if (opName === 'affine.if') {
  5749. // affine.if #set(dims)[symbols] [-> (type)] { region }
  5750. // Or: affine.if affine_set<(d0) : (constraint)>(dims)[symbols]
  5751. if (parser.match('#')) {
  5752. const condition = parser.parseAttribute();
  5753. op.attributes.push({ name: 'condition', value: condition });
  5754. } else if (parser.match('id', 'affine_set')) {
  5755. parser.expect('id', 'affine_set');
  5756. const content = parser.skip('<', '>');
  5757. op.attributes.push({ name: 'condition', value: `affine_set${content}` });
  5758. }
  5759. // Parse dimension operands in (...)
  5760. if (parser.accept('(')) {
  5761. while (!parser.accept(')')) {
  5762. if (parser.match('%')) {
  5763. const operand = parser.expect('%');
  5764. op.operands.push({ value: operand });
  5765. }
  5766. parser.accept(',');
  5767. }
  5768. }
  5769. // Parse symbol operands in [...]
  5770. if (parser.accept('[')) {
  5771. while (!parser.accept(']')) {
  5772. if (parser.match('%')) {
  5773. const operand = parser.expect('%');
  5774. op.operands.push({ value: operand });
  5775. }
  5776. parser.accept(',');
  5777. }
  5778. }
  5779. // Parse optional result types
  5780. parser.parseOptionalArrowResultTypes(op);
  5781. const region = {};
  5782. parser.parseRegion(region);
  5783. op.regions.push(region);
  5784. if (parser.accept('id', 'else')) {
  5785. const elseRegion = {};
  5786. parser.parseRegion(elseRegion);
  5787. op.regions.push(elseRegion);
  5788. }
  5789. return true;
  5790. }
  5791. // Special handling for affine.apply, affine.min, and affine.max
  5792. if (opName === 'affine.apply' || opName === 'affine.min' || opName === 'affine.max') {
  5793. // Reference: parseAffineMinMaxOp in AffineOps.cpp
  5794. // Syntax: affine.min #map(%dims)[%symbols]
  5795. // 1. Parse affine map attribute
  5796. if (parser.match('#') || parser.match('id', 'affine_map') || parser.match('id', 'affine_set')) {
  5797. const value = parser.parseAttribute();
  5798. op.attributes.push({ name: 'map', value });
  5799. }
  5800. // 2. Parse dimension operands in (...)
  5801. // Reference: AffineOps.cpp uses parseOperandList with Delimiter::Paren
  5802. if (parser.match('(')) {
  5803. const dimOperands = parser.parseOperandList('paren');
  5804. op.operands.push(...dimOperands);
  5805. }
  5806. // 3. Parse symbol operands in [...]
  5807. // Reference: AffineOps.cpp:3621 uses parseOperandList
  5808. const symOperands = parser.parseOperandList('optionalSquare');
  5809. op.operands.push(...symOperands);
  5810. // 4. Parse optional attr-dict
  5811. if (parser.match('{')) {
  5812. parser.parseAttributeDict(op.attributes);
  5813. }
  5814. return true;
  5815. }
  5816. if (opName === 'affine.store') {
  5817. return this._parseStoreOp(parser, op);
  5818. }
  5819. if (opName === 'affine.load') {
  5820. return this._parseLoadOp(parser, op);
  5821. }
  5822. if (opName === 'affine.vector_load') {
  5823. return this._parseVectorLoadOp(parser, op);
  5824. }
  5825. if (opName === 'affine.vector_store') {
  5826. return this._parseVectorStoreOp(parser, op);
  5827. }
  5828. if (opName === 'affine.prefetch') {
  5829. // Format: affine.prefetch %memref[affine_map] , read|write, locality<n>, data|instr : memref_type
  5830. const memref = parser.expect('%');
  5831. op.operands.push({ value: memref });
  5832. // Parse affine map with SSA operands in [...]
  5833. parser.skip('[', ']');
  5834. // Parse read/write specifier
  5835. parser.expect(',');
  5836. const rwSpecifier = parser.parseKeyword();
  5837. op.attributes.push({ name: 'isWrite', value: rwSpecifier === 'write' });
  5838. // Parse locality<n>
  5839. parser.expect(',');
  5840. parser.expect('id', 'locality');
  5841. parser.expect('<');
  5842. const locality = parser.expect('int');
  5843. op.attributes.push({ name: 'localityHint', value: locality });
  5844. parser.expect('>');
  5845. // Parse data/instr cache type
  5846. parser.expect(',');
  5847. const cacheType = parser.parseKeyword();
  5848. op.attributes.push({ name: 'isDataCache', value: cacheType === 'data' });
  5849. // Parse optional attr-dict
  5850. parser.parseOptionalAttrDict(op.attributes);
  5851. // Parse : memref_type
  5852. if (parser.accept(':')) {
  5853. const type = parser.parseType();
  5854. op.operands[0].type = type;
  5855. }
  5856. return true;
  5857. }
  5858. // C++-only operation: affine.dma_start
  5859. // Defined in mlir/lib/Dialect/Affine/IR/AffineOps.cpp
  5860. if (opName === 'affine.dma_start') {
  5861. // Format: affine.dma_start %src[indices], %dst[indices], %tag[indices], %num_elements [, %stride, %num_elt_per_stride] : memref, memref, memref
  5862. // Parse all operands including memrefs and their indices
  5863. while (!parser.match(':') && !parser.match('{')) {
  5864. if (parser.match('%')) {
  5865. const operand = parser.expect('%');
  5866. op.operands.push({ value: operand });
  5867. }
  5868. if (parser.match('[')) {
  5869. parser.skip('[', ']');
  5870. }
  5871. parser.accept(',');
  5872. }
  5873. // Parse optional attr-dict
  5874. parser.parseOptionalAttrDict(op.attributes);
  5875. // Parse : type list
  5876. if (parser.accept(':')) {
  5877. // Parse comma-separated type list
  5878. do {
  5879. parser.parseType();
  5880. } while (parser.accept(','));
  5881. }
  5882. return true;
  5883. }
  5884. if (opName === 'affine.dma_wait') {
  5885. // Format: affine.dma_wait %tag[indices], %num_elements : memref
  5886. while (!parser.match(':') && !parser.match('{')) {
  5887. if (parser.match('%')) {
  5888. const operand = parser.expect('%');
  5889. op.operands.push({ value: operand });
  5890. }
  5891. if (parser.match('[')) {
  5892. parser.skip('[', ']');
  5893. }
  5894. parser.accept(',');
  5895. }
  5896. // Parse optional attr-dict
  5897. parser.parseOptionalAttrDict(op.attributes);
  5898. // Parse : type
  5899. if (parser.accept(':')) {
  5900. parser.parseType();
  5901. }
  5902. return true;
  5903. }
  5904. return super.parseOperation(parser, opName, op);
  5905. }
  5906. _parseForOp(parser, op) {
  5907. const inductionVar = parser.expect('%');
  5908. parser.parseLocation();
  5909. parser.expect('=');
  5910. this._parseAffineBound(parser, op, 'lowerBound');
  5911. parser.expect('id', 'to');
  5912. this._parseAffineBound(parser, op, 'upperBound');
  5913. if (parser.accept('id', 'step')) {
  5914. if (parser.match('int')) {
  5915. const step = parser.expect('int');
  5916. op.attributes.push({ name: 'step', value: step });
  5917. }
  5918. }
  5919. if (parser.accept('id', 'iter_args')) {
  5920. if (parser.accept('(')) {
  5921. while (!parser.accept(')')) {
  5922. if (parser.match('%')) {
  5923. parser.expect('%');
  5924. }
  5925. if (parser.accept('=')) {
  5926. if (parser.match('%')) {
  5927. op.operands.push({ value: parser.expect('%') });
  5928. } else {
  5929. const value = parser.parseAttribute();
  5930. if (value) {
  5931. op.operands.push(value);
  5932. }
  5933. }
  5934. }
  5935. parser.accept(',');
  5936. }
  5937. }
  5938. parser.parseOptionalArrowResultTypes(op);
  5939. }
  5940. if (parser.match('{')) {
  5941. const region = {};
  5942. parser.parseRegion(region);
  5943. if (region.blocks && region.blocks.length > 0) {
  5944. if (!region.blocks[0].arguments) {
  5945. region.blocks[0].arguments = [];
  5946. }
  5947. if (region.blocks[0].arguments.length > 0) {
  5948. region.blocks[0].arguments[0] = { value: inductionVar };
  5949. } else {
  5950. region.blocks[0].arguments.push({ value: inductionVar });
  5951. }
  5952. }
  5953. op.regions.push(region);
  5954. }
  5955. return true;
  5956. }
  5957. _parseAffineBound(parser, op, boundName) {
  5958. // Parse affine bound following reference implementation in AffineOps.cpp parseBound()
  5959. // Syntax: [max|min] (ssa-id | integer | affine-map dim-and-symbol-list)
  5960. // Try parsing SSA value first (shorthand for identity map)
  5961. if (parser.match('%')) {
  5962. const value = parser.expect('%');
  5963. op.operands.push({ value });
  5964. // Store as identity map in metadata
  5965. const mapAttrName = boundName === 'lowerBound' ? 'lowerBoundMap' : 'upperBoundMap';
  5966. op.attributes.push({ name: mapAttrName, value: 'symbol_identity' });
  5967. return;
  5968. }
  5969. // Try parsing integer literal (shorthand for constant map)
  5970. if (parser.match('int') || parser.match('-')) {
  5971. const negate = parser.accept('-');
  5972. let value = parser.parseInteger();
  5973. if (negate) {
  5974. value = -value;
  5975. }
  5976. const mapAttrName = boundName === 'lowerBound' ? 'lowerBoundMap' : 'upperBoundMap';
  5977. op.attributes.push({ name: mapAttrName, value });
  5978. return;
  5979. }
  5980. // Parse optional min/max keyword
  5981. if (!parser.accept('id', 'min')) {
  5982. parser.accept('id', 'max');
  5983. }
  5984. // Parse affine map attribute (either #map or affine_map<...>)
  5985. if (parser.match('#') || parser.match('id', 'affine_map')) {
  5986. const mapValue = parser.parseAttribute();
  5987. if (mapValue) {
  5988. const mapAttrName = boundName === 'lowerBound' ? 'lowerBoundMap' : 'upperBoundMap';
  5989. op.attributes.push({ name: mapAttrName, value: mapValue });
  5990. // Parse dim and symbol operands in ()[...] or (...)
  5991. if (parser.accept('(')) {
  5992. while (!parser.accept(')')) {
  5993. if (parser.match('%')) {
  5994. const operand = parser.expect('%');
  5995. op.operands.push({ value: operand });
  5996. }
  5997. parser.accept(',');
  5998. }
  5999. }
  6000. if (parser.accept('[')) {
  6001. while (!parser.accept(']')) {
  6002. if (parser.match('%')) {
  6003. const operand = parser.expect('%');
  6004. op.operands.push({ value: operand });
  6005. }
  6006. parser.accept(',');
  6007. }
  6008. }
  6009. return;
  6010. }
  6011. }
  6012. throw new mlir.Error(`Expected loop bound (SSA value, integer, or affine map) in affine.for ${parser.location()}`);
  6013. }
  6014. _parseStoreOp(parser, op) {
  6015. if (parser.match('%')) {
  6016. const value = parser.expect('%');
  6017. op.operands.push({ value });
  6018. } else {
  6019. const value = parser.parseAttribute();
  6020. op.operands.push(value);
  6021. }
  6022. if (!parser.accept('id', 'to')) {
  6023. parser.accept(',');
  6024. }
  6025. const address = parser.expect('%');
  6026. op.operands.push({ value: address });
  6027. parser.skip('[', ']');
  6028. if (parser.accept(':')) {
  6029. const type = parser.parseType();
  6030. op.operands[1].type = type;
  6031. }
  6032. return true;
  6033. }
  6034. _parseLoadOp(parser, op) {
  6035. const address = parser.expect('%');
  6036. op.operands.push({ value: address });
  6037. parser.skip('[', ']');
  6038. if (parser.accept(':')) {
  6039. const type = parser.parseType();
  6040. op.operands[0].type = type;
  6041. }
  6042. return true;
  6043. }
  6044. _parseVectorLoadOp(parser, op) {
  6045. const memref = parser.expect('%');
  6046. op.operands.push({ value: memref });
  6047. parser.skip('[', ']');
  6048. parser.parseOptionalAttrDict(op.attributes);
  6049. if (parser.accept(':')) {
  6050. const memrefType = parser.parseType();
  6051. op.operands[0].type = memrefType;
  6052. parser.expect(',');
  6053. const vectorType = parser.parseType();
  6054. op.results.push({ type: vectorType });
  6055. }
  6056. return true;
  6057. }
  6058. _parseVectorStoreOp(parser, op) {
  6059. const value = parser.expect('%');
  6060. op.operands.push({ value });
  6061. parser.expect(',');
  6062. const memref = parser.expect('%');
  6063. op.operands.push({ value: memref });
  6064. parser.skip('[', ']');
  6065. parser.parseOptionalAttrDict(op.attributes);
  6066. if (parser.accept(':')) {
  6067. const memrefType = parser.parseType();
  6068. op.operands[1].type = memrefType;
  6069. parser.expect(',');
  6070. const vectorType = parser.parseType();
  6071. op.operands[0].type = vectorType;
  6072. }
  6073. return true;
  6074. }
  6075. _parseParallelOp(parser, op) {
  6076. const ivs = parser.parseArguments();
  6077. if (!parser.accept('=')) {
  6078. return false;
  6079. }
  6080. parser.skip('(', ')');
  6081. if (!parser.accept('id', 'to')) {
  6082. return false;
  6083. }
  6084. parser.skip('(', ')');
  6085. if (parser.accept('id', 'step')) {
  6086. parser.skip('(', ')');
  6087. }
  6088. if (parser.accept('id', 'reduce')) {
  6089. parser.expect('(');
  6090. while (!parser.match(')')) {
  6091. if (parser.match('string')) {
  6092. parser.expect('string');
  6093. }
  6094. if (!parser.accept(',')) {
  6095. break;
  6096. }
  6097. }
  6098. parser.expect(')');
  6099. }
  6100. if (parser.accept('->')) {
  6101. const resultTypes = [];
  6102. const resultAttrs = [];
  6103. parser.parseFunctionResultList(resultTypes, resultAttrs);
  6104. }
  6105. if (parser.match('{')) {
  6106. const region = {};
  6107. parser.parseRegion(region);
  6108. if (region.blocks && region.blocks.length > 0) {
  6109. if (!region.blocks[0].arguments) {
  6110. region.blocks[0].arguments = [];
  6111. }
  6112. region.blocks[0].arguments = ivs;
  6113. }
  6114. op.regions.push(region);
  6115. }
  6116. return true;
  6117. }
  6118. };
  6119. mlir.MemRefDialect = class extends mlir.Dialect {
  6120. constructor(operations) {
  6121. super('memref', operations);
  6122. this.registerCustomDirective('GlobalMemrefOpTypeAndInitialValue', this._parseGlobalMemrefOpTypeAndInitialValue.bind(this));
  6123. }
  6124. _parseGlobalMemrefOpTypeAndInitialValue(parser, op, args) {
  6125. // Parse: type [= initializer]
  6126. // args[0] is "$type", args[1] is "$initial_value"
  6127. const typeArg = args && args.length > 0 ? args[0].replace(/^\$/, '') : 'type';
  6128. const initialValueArg = args && args.length > 1 ? args[1].replace(/^\$/, '') : 'initial_value';
  6129. // Parse type
  6130. const type = parser.parseType();
  6131. op.attributes.push({ name: typeArg, value: type, type: 'type' });
  6132. // Parse optional initializer: = <value> or = uninitialized
  6133. if (parser.accept('=')) {
  6134. if (parser.accept('id', 'uninitialized')) {
  6135. op.attributes.push({ name: initialValueArg, value: 'uninitialized' });
  6136. } else {
  6137. // Pass the type to parseAttribute to suppress : type suffix parsing
  6138. const initialValue = parser.parseAttribute(type);
  6139. op.attributes.push({ name: initialValueArg, value: initialValue });
  6140. }
  6141. }
  6142. }
  6143. parseOperation(parser, opName, op) {
  6144. if (opName === 'memref.tensor_load') {
  6145. op.operands = parser.parseArguments();
  6146. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  6147. return true;
  6148. }
  6149. if (opName === 'memref.store') {
  6150. this._operations.get(opName).hasParseOperation = false; // compatibility
  6151. return this._parseStoreOp(parser, op);
  6152. }
  6153. if (opName === 'memref.alloca_scope') {
  6154. return this._parseAllocaScopeOp(parser, op);
  6155. }
  6156. if (opName === 'memref.transpose') {
  6157. return this._parseTransposeOp(parser, op);
  6158. }
  6159. return super.parseOperation(parser, opName, op);
  6160. }
  6161. _parseTransposeOp(parser, op) {
  6162. // Reference: MemRefOps.cpp TransposeOp::parse
  6163. // Format: $in $permutation attr-dict : type($in) `to` type(results)
  6164. const operand = { value: parser.expect('%') };
  6165. op.operands.push(operand);
  6166. // Parse affine map permutation: (d0, d1) -> (d1, d0)
  6167. // This is a bare affine map, not wrapped in affine_map<...>
  6168. const dims = parser.skip('(', ')');
  6169. parser.expect('->');
  6170. const results = parser.skip('(', ')');
  6171. const permutation = `affine_map<${dims} -> ${results}>`;
  6172. op.attributes.push({ name: 'permutation', value: permutation });
  6173. parser.parseOptionalAttrDict(op.attributes);
  6174. if (parser.accept(':')) {
  6175. const srcType = parser.parseType();
  6176. operand.type = srcType;
  6177. }
  6178. parser.expect('id', 'to');
  6179. const dstType = parser.parseType();
  6180. parser.resolveOperands(op.results, [dstType]);
  6181. return true;
  6182. }
  6183. _parseAllocaScopeOp(parser, op) {
  6184. // Reference: MemRefOps.cpp AllocaScopeOp::parse
  6185. // Format: [-> (type, ...)] { region } [attr-dict]
  6186. const resultTypes = parser.parseOptionalArrowTypeList();
  6187. parser.resolveOperands(op.results, resultTypes);
  6188. const region = {};
  6189. parser.parseRegion(region);
  6190. op.regions.push(region);
  6191. parser.parseOptionalAttrDict(op.attributes);
  6192. return true;
  6193. }
  6194. _parseStoreOp(parser, op) {
  6195. // Parse: value, memref[indices] {attributes} : type
  6196. // or old: value to memref[indices] : type
  6197. if (parser.match('%')) {
  6198. const value = parser.expect('%');
  6199. op.operands.push({ value });
  6200. } else {
  6201. const value = parser.parseAttribute();
  6202. op.operands.push(value);
  6203. }
  6204. // Accept either ',' (new) or 'to' (old)
  6205. if (!parser.accept('id', 'to')) {
  6206. parser.accept(',');
  6207. }
  6208. const address = parser.expect('%');
  6209. op.operands.push({ value: address });
  6210. parser.skip('[', ']');
  6211. // Parse optional attribute dict
  6212. parser.parseAttributeDict(op.attributes);
  6213. if (parser.accept(':')) {
  6214. const type = parser.parseType();
  6215. op.operands[1].type = type;
  6216. }
  6217. return true;
  6218. }
  6219. };
  6220. mlir.VectorDialect = class extends mlir.Dialect {
  6221. constructor(operations) {
  6222. super('vector', operations);
  6223. this.registerCustomAttribute('Vector_CombiningKindAttr', this._parseEnumFlagsAngleBracketComma.bind(this));
  6224. this.registerCustomAttribute('Arith_FastMathAttr', this._parseEnumFlagsAngleBracketComma.bind(this));
  6225. }
  6226. parseOperation(parser, opName, op) {
  6227. if (opName === 'vector.splat') {
  6228. op.operands = parser.parseArguments();
  6229. // Reference: parseOptionalColonTypeList
  6230. parser.resolveOperands(op.results, parser.parseOptionalColonTypeList());
  6231. return true;
  6232. }
  6233. if (opName === 'vector.contract') {
  6234. if (parser.match('{')) {
  6235. parser.skip('{', '}');
  6236. } else if (parser.match('#')) {
  6237. parser.expect('#');
  6238. }
  6239. op.operands = parser.parseArguments();
  6240. parser.parseOptionalAttrDict(op.attributes);
  6241. // Reference: parseColonTypeList (mandatory)
  6242. const types = parser.parseColonTypeList();
  6243. parser.resolveOperands(op.operands, types);
  6244. // Reference: parseKeywordType("into", resultType)
  6245. parser.expect('id', 'into');
  6246. const resultType = parser.parseType();
  6247. parser.resolveOperands(op.results, [resultType]);
  6248. return true;
  6249. }
  6250. if (opName === 'vector.mask') {
  6251. if (parser.match('%')) {
  6252. const mask = parser.expect('%');
  6253. op.operands.push({ value: mask, name: 'mask' });
  6254. }
  6255. if (parser.accept(',')) {
  6256. const passthru = parser.expect('%');
  6257. op.operands.push({ value: passthru, name: 'passthru' });
  6258. }
  6259. if (parser.match('{')) {
  6260. const region = {};
  6261. parser.parseRegion(region);
  6262. op.regions.push(region);
  6263. }
  6264. parser.parseOptionalAttrDict(op.attributes);
  6265. // Reference: parseOptionalColonTypeList for operands
  6266. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  6267. // Reference: parseOptionalArrowTypeList for results
  6268. parser.resolveOperands(op.results, parser.parseOptionalArrowTypeList());
  6269. return true;
  6270. }
  6271. if (opName === 'vector.outerproduct') {
  6272. return this._parseOuterProductOp(parser, op);
  6273. }
  6274. if (opName === 'vector.transfer_read' || opName === 'vector.transfer_write') {
  6275. return this._parseTransferOp(parser, op);
  6276. }
  6277. if (opName === 'vector.extract' && !op.isGeneric) {
  6278. this._operations.get(opName).hasParseOperation = false; // compatibility
  6279. return this._parseExtractOp(parser, op);
  6280. }
  6281. return super.parseOperation(parser, opName, op);
  6282. }
  6283. _parseOuterProductOp(parser, op) {
  6284. const lhs = parser.expect('%');
  6285. op.operands.push({ value: lhs, name: 'lhs' });
  6286. parser.expect(',');
  6287. const rhs = parser.expect('%');
  6288. op.operands.push({ value: rhs, name: 'rhs' });
  6289. if (parser.accept(',')) {
  6290. const acc = parser.expect('%');
  6291. op.operands.push({ value: acc, name: 'acc' });
  6292. }
  6293. parser.parseOptionalAttrDict(op.attributes);
  6294. if (parser.accept(':')) {
  6295. const lhsType = parser.parseType();
  6296. op.operands[0].type = lhsType.toString();
  6297. parser.expect(',');
  6298. const rhsType = parser.parseType();
  6299. op.operands[1].type = rhsType.toString();
  6300. }
  6301. return true;
  6302. }
  6303. _parseExtractOp(parser, op) {
  6304. // Parse: %source [ indices ] : result_type [from source_type]
  6305. // The 'from' keyword indicates new syntax (current MLIR)
  6306. // Old syntax (pre-2023): %r = vector.extract %v[0] : vector<4xf32>
  6307. // New syntax: %r = vector.extract %v[0] : f32 from vector<4xf32>
  6308. // Parse source operand
  6309. const source = parser.expect('%');
  6310. op.operands.push({ value: source });
  6311. // Parse indices: [0, 1, ...]
  6312. if (parser.accept('[')) {
  6313. while (!parser.match(']')) {
  6314. if (parser.match('int') || parser.match('number')) {
  6315. parser.expect(); // Consume index but don't store (indices are in static_position attribute)
  6316. } else if (parser.match('%')) {
  6317. const dynIndex = parser.expect('%');
  6318. op.operands.push({ value: dynIndex }); // Dynamic indices are operands
  6319. } else {
  6320. break;
  6321. }
  6322. parser.accept(',');
  6323. }
  6324. parser.accept(']');
  6325. }
  6326. // Parse optional attributes
  6327. if (parser.match('{')) {
  6328. parser.parseAttributeDict(op.attributes);
  6329. }
  6330. // Parse type signature: : result_type [from source_type]
  6331. if (parser.accept(':')) {
  6332. const resultType = parser.parseType();
  6333. // Check for 'from' keyword (new syntax)
  6334. if (parser.accept('id', 'from')) {
  6335. const sourceType = parser.parseType();
  6336. op.operands[0].type = sourceType;
  6337. op.results.push({ type: resultType });
  6338. } else {
  6339. // Old syntax: the type after ':' is the source type
  6340. // Result type is extracted element type (scalar or sub-vector)
  6341. op.operands[0].type = resultType;
  6342. // We don't set result type - let the default inference handle it
  6343. }
  6344. }
  6345. return true;
  6346. }
  6347. _parseTransferOp(parser, op) {
  6348. // Parse: vector.transfer_read %source[%i, %j, ...], %padding {attrs} : memref_type, vector_type
  6349. // or: vector.transfer_read %source[%i, %j, ...], %padding, %mask {attrs} : memref_type, vector_type
  6350. // or: vector.transfer_write %value, %dest[%i, %j, ...] {attrs} : vector_type, memref_type
  6351. // or: vector.transfer_write %value, %dest[%i, %j, ...], %mask {attrs} : vector_type, memref_type
  6352. // First operand: source/value
  6353. const first = parser.expect('%');
  6354. op.operands.push({ value: first });
  6355. // Check if indices follow first operand or second operand
  6356. const hasIndicesAfterFirst = parser.match('[');
  6357. if (hasIndicesAfterFirst) {
  6358. parser.skip('[', ']');
  6359. }
  6360. // Comma
  6361. parser.accept(',');
  6362. // Second operand: padding value or destination
  6363. const second = parser.expect('%');
  6364. op.operands.push({ value: second });
  6365. // If indices didn't follow first operand, they follow second operand
  6366. if (!hasIndicesAfterFirst && parser.match('[')) {
  6367. parser.skip('[', ']');
  6368. }
  6369. // Optional mask parameter (third operand)
  6370. if (parser.accept(',')) {
  6371. const mask = parser.expect('%');
  6372. op.operands.push({ value: mask });
  6373. }
  6374. // Optional attribute dictionary
  6375. if (parser.match('{')) {
  6376. parser.parseAttributeDict(op.attributes);
  6377. }
  6378. // Type signature: : memref_type, vector_type
  6379. if (parser.accept(':')) {
  6380. const type1 = parser.parseType();
  6381. op.operands[0].type = type1.toString();
  6382. parser.accept(',');
  6383. const type2 = parser.parseType();
  6384. // For transfer_read, type2 is the result type
  6385. // For transfer_write, type2 is just the vector type
  6386. if (op.results.length > 0) {
  6387. op.results[0].type = type2.toString();
  6388. }
  6389. op.operands[1].type = type2.toString();
  6390. }
  6391. return true;
  6392. }
  6393. };
  6394. mlir.TorchDialect = class extends mlir.Dialect {
  6395. constructor(operations) {
  6396. super('torch', operations);
  6397. this.simpleTypes = new Set([
  6398. 'int', 'float', 'bool', 'str', 'none', 'Device', 'Generator',
  6399. 'qint8', 'quint8', 'qint16', 'qint32', 'quint4x2', 'quint2x4',
  6400. 'LinearParams', 'number', 'any'
  6401. ]);
  6402. }
  6403. parseType(parser, dialectName) {
  6404. const typeName = parser.parseKeyword();
  6405. if (!typeName) {
  6406. return null;
  6407. }
  6408. let type = `!${dialectName}.${typeName}`;
  6409. if (this.simpleTypes.has(typeName)) {
  6410. return new mlir.Type(type);
  6411. }
  6412. if (typeName === 'vtensor' || typeName === 'tensor' || typeName === 'list' || typeName === 'tuple' || typeName === 'union' || typeName === 'optional' || typeName === 'dict' || typeName.startsWith('nn.')) {
  6413. if (parser.match('<')) {
  6414. const content = parser.skip('<', '>');
  6415. type += content;
  6416. }
  6417. return new mlir.Type(type);
  6418. }
  6419. return null;
  6420. }
  6421. parseOperation(parser, opName, op) {
  6422. if (opName === 'torch.constant.int') {
  6423. if (parser.match('int')) {
  6424. const value = parser.expect('int');
  6425. op.attributes.push({ name: 'value', value });
  6426. }
  6427. return true;
  6428. }
  6429. if (opName === 'torch.onnx.rotary_embedding') {
  6430. op.operands = parser.parseArguments();
  6431. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  6432. if (parser.accept('->')) {
  6433. const resultType = parser.parseType();
  6434. op.results.push({ type: resultType });
  6435. }
  6436. return true;
  6437. }
  6438. if (opName === 'torch.bind_symbolic_shape') {
  6439. const operand = { value: parser.expect('%') };
  6440. op.operands.push(operand);
  6441. parser.accept(',');
  6442. // Reference: TorchOps.cpp:6363 uses parseOperandList
  6443. const shapeSymbols = parser.parseOperandList('square');
  6444. op.operands.push(...shapeSymbols);
  6445. parser.accept(',');
  6446. const shapeExpr = parser.parseAttribute();
  6447. op.attributes.push({ name: 'shape_expressions', value: shapeExpr.value || shapeExpr });
  6448. parser.parseOptionalAttrDict(op.attributes);
  6449. if (parser.accept(':')) {
  6450. operand.type = parser.parseType();
  6451. }
  6452. return true;
  6453. }
  6454. if (this.hasCustomAssemblyFormat(opName) && !this.hasAssemblyFormat(opName)) {
  6455. return this._parseDefaultTorchOp(parser, op);
  6456. }
  6457. return super.parseOperation(parser, opName, op);
  6458. }
  6459. _parseDefaultTorchOp(parser, op) {
  6460. op.operands = parser.parseArguments();
  6461. parser.parseOptionalAttrDict(op.attributes);
  6462. if (parser.accept(':')) {
  6463. parser.resolveOperands(op.operands, parser.parseTypeList());
  6464. }
  6465. if (parser.accept('->')) {
  6466. // Handle both -> (type, type) and -> type, type syntaxes
  6467. const types = parser.match('(') ? parser.parseTypeListParens() : parser.parseTypeListNoParens();
  6468. parser.resolveOperands(op.results, types);
  6469. }
  6470. if (parser.match('{')) {
  6471. const region = {};
  6472. parser.parseRegion(region);
  6473. op.regions.push(region);
  6474. if (parser.accept('id', 'else') && parser.match('{')) {
  6475. const elseRegion = {};
  6476. parser.parseRegion(elseRegion);
  6477. op.regions.push(elseRegion);
  6478. }
  6479. }
  6480. return true;
  6481. }
  6482. };
  6483. mlir.IREEDialect = class extends mlir.Dialect {
  6484. constructor(name, operations) {
  6485. super(name, operations);
  6486. this.registerCustomDirective('DispatchEntryPoints', this._parseDispatchEntryPoints.bind(this));
  6487. this.registerCustomDirective('ShapedTiedResult', this._parseShapedTiedResult.bind(this));
  6488. this.registerCustomDirective('SymbolAlias', this._parseSymbolAlias.bind(this));
  6489. this.registerCustomDirective('TypeAlias', this._parseTypeAlias.bind(this));
  6490. this.registerCustomDirective('WorkgroupCountRegion', this._parseWorkgroupCountRegion.bind(this));
  6491. }
  6492. _parseDispatchEntryPoints(parser, op, args) {
  6493. // Parse either:
  6494. // - Single: @symbol or @symbol::@nested
  6495. // - Multiple: {@symbol1, @symbol2::@nested2}
  6496. const entryPoints = [];
  6497. if (parser.accept('{')) {
  6498. // Parse multiple entry points
  6499. do {
  6500. if (parser.match('@')) {
  6501. let symbol = parser.expect('@');
  6502. // Handle :: nested symbol reference
  6503. if (parser.accept('id', '::') || (parser.match(':') && parser.accept(':') && parser.accept(':'))) {
  6504. if (parser.match('@')) {
  6505. const nested = parser.expect('@');
  6506. symbol += `::${nested}`;
  6507. }
  6508. }
  6509. entryPoints.push(symbol);
  6510. }
  6511. } while (parser.accept(','));
  6512. parser.expect('}');
  6513. } else if (parser.match('@')) {
  6514. // Parse single entry point
  6515. let symbol = parser.expect('@');
  6516. // Handle :: nested symbol reference
  6517. if (parser.accept('id', '::') || (parser.match(':') && parser.accept(':') && parser.accept(':'))) {
  6518. if (parser.match('@')) {
  6519. const nested = parser.expect('@');
  6520. symbol += `::${nested}`;
  6521. }
  6522. }
  6523. entryPoints.push(symbol);
  6524. }
  6525. // Add as attribute with name from args
  6526. const attrName = args && args.length > 0 ? args[0].replace(/^\$/, '') : 'entry_points';
  6527. // Store as array if multiple, or single value if one
  6528. const value = entryPoints.length === 1 ? entryPoints[0] : entryPoints;
  6529. op.attributes.push({ name: attrName, value });
  6530. }
  6531. _parseShapedTiedResult(parser, op /*, args */) {
  6532. // Parse: %arg0 as tensor<?x?xf32>{%d0, %d1}
  6533. // or: tensor<?x?xf32>{%d0, %d1}
  6534. let tiedOperand = null;
  6535. if (parser.match('%')) {
  6536. tiedOperand = parser.expect('%');
  6537. parser.expect('id', 'as');
  6538. }
  6539. const resultType = parser.parseType();
  6540. const dims = [];
  6541. if (parser.accept('{')) {
  6542. while (!parser.match('}')) {
  6543. if (parser.match('%')) {
  6544. const dim = parser.expect('%');
  6545. dims.push(dim);
  6546. parser.accept(',');
  6547. } else {
  6548. break;
  6549. }
  6550. }
  6551. parser.expect('}');
  6552. }
  6553. // Add result with type and tied operand info
  6554. op.results.push({ type: resultType, tiedOperand, dims });
  6555. }
  6556. _parseSymbolAlias(parser, op, args) {
  6557. // @foo or @foo as("bar")
  6558. const alias = parser.expect('@');
  6559. let symName = alias;
  6560. if (parser.accept('id', 'as')) {
  6561. if (parser.accept('(')) {
  6562. if (parser.match('string')) {
  6563. symName = parser.expect('string');
  6564. } else if (parser.match('@')) {
  6565. symName = parser.expect('@');
  6566. }
  6567. parser.accept(')');
  6568. }
  6569. }
  6570. if (args && args.length >= 2) {
  6571. const symNameArg = args[0].replace(/^\$/, '');
  6572. const aliasArg = args[1].replace(/^\$/, '');
  6573. op.attributes.push({ name: symNameArg, value: symName });
  6574. op.attributes.push({ name: aliasArg, value: alias });
  6575. }
  6576. }
  6577. _parseTypeAlias(parser, op, args) {
  6578. const encodingType = parser.parseType();
  6579. let storageType = encodingType;
  6580. if (parser.accept('id', 'as')) {
  6581. storageType = parser.parseType();
  6582. }
  6583. if (args && args.length >= 1) {
  6584. const encodingAttrName = args[0].replace(/^\$/, '');
  6585. op.attributes.push({ name: encodingAttrName, value: encodingType });
  6586. }
  6587. if (args && args.length >= 2) {
  6588. const typeMatch = args[1].match(/type\(\$(\w+)\)/);
  6589. if (typeMatch) {
  6590. if (op.results.length > 0) {
  6591. op.results[0].type = storageType;
  6592. } else {
  6593. op.results.push({ type: storageType });
  6594. }
  6595. } else if (op.operands.length > 0) {
  6596. op.operands[0].type = storageType;
  6597. }
  6598. }
  6599. }
  6600. _parseWorkgroupCountRegion(parser, op, args) {
  6601. if (!parser.match('id', 'workgroups')) {
  6602. return;
  6603. }
  6604. parser.expect('id', 'workgroups');
  6605. const region = { blocks: [] };
  6606. const block = { arguments: [], operations: [] };
  6607. if (parser.accept('(')) {
  6608. while (!parser.match(')')) {
  6609. const arg = { value: parser.expect('%') };
  6610. if (parser.accept(':')) {
  6611. arg.type = parser.parseType();
  6612. }
  6613. block.arguments.push(arg);
  6614. if (!parser.accept(',')) {
  6615. break;
  6616. }
  6617. }
  6618. parser.expect(')');
  6619. }
  6620. if (parser.accept('->')) {
  6621. parser.expect('(');
  6622. while (!parser.match(')')) {
  6623. parser.parseType();
  6624. if (!parser.accept(',')) {
  6625. break;
  6626. }
  6627. }
  6628. parser.expect(')');
  6629. }
  6630. if (parser.accept('{')) {
  6631. while (!parser.match('}')) {
  6632. const innerOp = parser.parseOperation();
  6633. if (innerOp) {
  6634. block.operations.push(innerOp);
  6635. }
  6636. if (parser.match('}')) {
  6637. break;
  6638. }
  6639. }
  6640. parser.expect('}');
  6641. }
  6642. region.blocks.push(block);
  6643. if (args && args.length > 0) {
  6644. const regionArgName = args[0].replace(/^\$/, '');
  6645. if (regionArgName) {
  6646. op.regions.push(region);
  6647. }
  6648. } else {
  6649. op.regions.push(region);
  6650. }
  6651. }
  6652. };
  6653. mlir.HALDialect = class extends mlir.IREEDialect {
  6654. constructor(operations) {
  6655. super('hal', operations);
  6656. this.simpleTypes = new Set(['allocator', 'buffer', 'buffer_view', 'channel', 'command_buffer', 'descriptor_set', 'descriptor_set_layout', 'device', 'event', 'executable', 'executable_layout', 'fence', 'file', 'semaphore']);
  6657. this.registerCustomAttribute('HAL_PipelineLayoutAttr', this._parsePipelineLayoutAttr.bind(this));
  6658. }
  6659. parseType(parser, dialectName) {
  6660. const typeName = parser.parseKeyword();
  6661. if (!typeName) {
  6662. return null;
  6663. }
  6664. if (this.simpleTypes.has(typeName)) {
  6665. let typeStr = `!${dialectName}.${typeName}`;
  6666. // Handle dynamic dimensions/parameters like {%sz_4}
  6667. if (parser.match('{')) {
  6668. const params = parser.skip('{', '}');
  6669. typeStr += `{${params}}`;
  6670. }
  6671. return new mlir.Type(typeStr);
  6672. }
  6673. return null;
  6674. }
  6675. parseOperation(parser, opName, op) {
  6676. if (opName === 'hal.tensor.cast') {
  6677. op.operands = parser.parseArguments();
  6678. if (parser.accept(':')) {
  6679. const type = parser.parseType();
  6680. if (op.operands.length > 0) {
  6681. op.operands[0].type = type;
  6682. }
  6683. }
  6684. if (parser.accept('->')) {
  6685. const types = parser.parseFunctionResultTypes();
  6686. parser.resolveOperands(op.results, types);
  6687. }
  6688. return true;
  6689. }
  6690. if (opName === 'hal.constant') {
  6691. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  6692. const value = parser.parseAttribute();
  6693. op.attributes.push({ name: 'value', value: value.value === undefined ? value : value.value });
  6694. // Reference: parseOptionalColonTypeList
  6695. parser.resolveOperands(op.results, parser.parseOptionalColonTypeList());
  6696. return true;
  6697. }
  6698. if (opName === 'hal.device.switch') {
  6699. if (parser.accept('<')) {
  6700. while (!parser.accept('>')) {
  6701. const operand = parser.expect('%');
  6702. op.operands.push({ value: operand });
  6703. if (parser.accept(':')) {
  6704. const type = parser.parseType();
  6705. if (op.operands.length > 0) {
  6706. op.operands[op.operands.length - 1].type = type;
  6707. }
  6708. }
  6709. parser.accept(',');
  6710. }
  6711. }
  6712. if (parser.accept('->') || parser.accept(':')) {
  6713. const resultType = parser.parseType();
  6714. op.results = [{ type: resultType }];
  6715. }
  6716. while (parser.match('#')) {
  6717. const region = {};
  6718. const caseAttr = parser.parseAttribute();
  6719. region.caseAttribute = caseAttr;
  6720. if (parser.match('{')) {
  6721. parser.parseRegion(region);
  6722. }
  6723. op.regions.push(region);
  6724. parser.accept(',');
  6725. }
  6726. return true;
  6727. }
  6728. if (opName === 'hal.executable.constant.block' && this.hasCustomAssemblyFormat(opName) && !this.hasAssemblyFormat(opName)) {
  6729. if (parser.accept('(')) {
  6730. while (!parser.match(')')) {
  6731. if (parser.match('%')) {
  6732. const arg = parser.expect('%');
  6733. parser.expect(':');
  6734. const type = parser.parseType();
  6735. op.operands.push({ value: arg, type });
  6736. }
  6737. if (!parser.accept(',')) {
  6738. break;
  6739. }
  6740. }
  6741. parser.expect(')');
  6742. }
  6743. if (parser.accept('->')) {
  6744. const resultTypes = parser.parseFunctionResultTypes();
  6745. op.attributes.push({ name: 'function_type', value: resultTypes });
  6746. }
  6747. if (parser.accept('id', 'as')) {
  6748. if (parser.match('(')) {
  6749. parser.expect('(');
  6750. const keys = [];
  6751. while (!parser.match(')')) {
  6752. if (parser.match('string')) {
  6753. keys.push(parser.expect('string'));
  6754. }
  6755. if (!parser.accept(',')) {
  6756. break;
  6757. }
  6758. }
  6759. parser.expect(')');
  6760. op.attributes.push({ name: 'keys', value: keys });
  6761. } else if (parser.match('string')) {
  6762. const key = parser.expect('string');
  6763. op.attributes.push({ name: 'keys', value: [key] });
  6764. }
  6765. }
  6766. if (parser.match('{')) {
  6767. const region = {};
  6768. parser.parseRegion(region);
  6769. op.regions.push(region);
  6770. }
  6771. return true;
  6772. }
  6773. // Handle hal.executable.create with both old (layouts) and new (affinity) syntax
  6774. if (opName === 'hal.executable.create') {
  6775. this.getOperation(opName).hasParseOperation = false; // compatibility?
  6776. // Parse named parameters: device(...), target(...), and either layouts(...) or affinity(...)
  6777. while (parser.match('id') && !parser.match(':') && !parser.match('loc')) {
  6778. const paramName = parser.expect('id');
  6779. if (parser.accept('(')) {
  6780. let parenDepth = 1;
  6781. let paramValue = '';
  6782. while (parenDepth > 0 && !parser.match('eof')) {
  6783. if (parser.match('(')) {
  6784. parenDepth++;
  6785. paramValue += parser.expect();
  6786. } else if (parser.match(')')) {
  6787. parenDepth--;
  6788. if (parenDepth > 0) {
  6789. paramValue += parser.expect();
  6790. } else {
  6791. parser.expect(')');
  6792. }
  6793. } else {
  6794. paramValue += parser.expect();
  6795. }
  6796. }
  6797. // Normalize old 'layouts' parameter to 'affinity' for consistency
  6798. const normalizedName = paramName === 'layouts' ? 'affinity' : paramName;
  6799. op.attributes.push({ name: normalizedName, value: paramValue });
  6800. } else {
  6801. break;
  6802. }
  6803. }
  6804. // Parse result type
  6805. // Reference: parseOptionalColonTypeList
  6806. parser.resolveOperands(op.results, parser.parseOptionalColonTypeList());
  6807. return true;
  6808. }
  6809. // Handle operations with <%operand : type> syntax and/or named parameters
  6810. // e.g., hal.allocator.compute_size<%allocator : !hal.allocator> shape([...]) type(...) encoding(...) : index
  6811. // or hal.executable_layout.lookup device(%device : !hal.device) layouts([[...]]) : !hal.executable_layout
  6812. // Exclude hal.executable, hal.interface, and hal.device.switch which have special handling
  6813. if ((opName.startsWith('hal.allocator.') || opName.startsWith('hal.buffer.') || opName.startsWith('hal.buffer_view.') ||
  6814. opName.startsWith('hal.command_buffer.') || opName.startsWith('hal.executable_layout') ||
  6815. opName.startsWith('hal.executable.') || opName.startsWith('hal.descriptor_set_layout') ||
  6816. opName.startsWith('hal.device.')) &&
  6817. opName !== 'hal.device.allocator' &&
  6818. opName !== 'hal.buffer_view.buffer' &&
  6819. opName !== 'hal.executable' &&
  6820. opName !== 'hal.interface' &&
  6821. opName !== 'hal.device.switch' &&
  6822. opName !== 'hal.command_buffer.execution_barrier' &&
  6823. opName !== 'hal.executable.entry_point' &&
  6824. opName !== 'hal.executable.variant' &&
  6825. opName !== 'hal.executable.lookup' &&
  6826. opName !== 'hal.interface.binding' &&
  6827. opName !== 'hal.executable.create' &&
  6828. opName !== 'hal.executable.export' &&
  6829. opName !== 'hal.executable.binary' &&
  6830. opName !== 'hal.executable.condition' &&
  6831. opName !== 'hal.executable.constant.block') {
  6832. // Parse <%operand : type> if present
  6833. if (opName === 'hal.allocator.allocate' || opName === 'hal.command_buffer.create' || opName === 'hal.buffer_view.create' || opName === 'hal.command_buffer.device' || opName === 'hal.command_buffer.dispatch' || opName === 'hal.device.query') {
  6834. this.getOperation(opName).hasParseOperation = false; // compatibility?
  6835. }
  6836. if (parser.accept('<')) {
  6837. while (!parser.accept('>')) {
  6838. const operand = parser.expect('%');
  6839. op.operands.push({ value: operand });
  6840. if (parser.accept(':')) {
  6841. const type = parser.parseType();
  6842. if (op.operands.length > 0) {
  6843. op.operands[op.operands.length - 1].type = type;
  6844. }
  6845. }
  6846. parser.accept(',');
  6847. }
  6848. }
  6849. // Parse named parameters like shape([...]) type(...) encoding(...)
  6850. // Also handle bracket expressions between parameters like layout(...)[%c0]
  6851. // Stop when we hit a colon (result type) or something that doesn't look like a parameter
  6852. // Named parameters don't have dots, so if we see an id with a dot, it's likely the next operation
  6853. // Also exclude common operation keywords that shouldn't be treated as parameters
  6854. const notParameterNames = new Set(['br', 'cond_br', 'return', 'yield', 'call', 'unreachable', 'assert']);
  6855. while (parser.match('[') ||
  6856. (parser.match('id') && !parser.match('id', 'attributes') &&
  6857. !parser.match(':') && !parser.match('loc') &&
  6858. parser.token.value && parser.token.value.indexOf('.') === -1 &&
  6859. !notParameterNames.has(parser.token.value))) {
  6860. // Handle bracket expressions (e.g., [%c0])
  6861. if (parser.match('[')) {
  6862. parser.skip('[', ']');
  6863. continue;
  6864. }
  6865. // Try to parse a named parameter (id followed by '(')
  6866. const paramName = parser.expect('id');
  6867. if (parser.accept('(')) {
  6868. // This is a named parameter, parse the value
  6869. // Track depth separately for () and []
  6870. let parenDepth = 1; // We've already consumed the opening (
  6871. let paramValue = '';
  6872. while (parenDepth > 0 && !parser.match('eof')) {
  6873. if (parser.match('(')) {
  6874. parenDepth++;
  6875. paramValue += parser.expect();
  6876. } else if (parser.match(')')) {
  6877. parenDepth--;
  6878. if (parenDepth > 0) {
  6879. paramValue += parser.expect();
  6880. } else {
  6881. // This is the closing ), consume it
  6882. parser.expect(')');
  6883. }
  6884. } else {
  6885. paramValue += parser.expect();
  6886. }
  6887. }
  6888. op.attributes.push({ name: paramName, value: paramValue });
  6889. } else {
  6890. // Not a named parameter - we've consumed an id token that doesn't belong to us
  6891. // This shouldn't happen with proper MLIR, but break gracefully
  6892. break;
  6893. }
  6894. }
  6895. // Parse result types if present (: type1, type2, ...)
  6896. // Reference: parseOptionalColonTypeList
  6897. parser.resolveOperands(op.results, parser.parseOptionalColonTypeList());
  6898. // Parse optional = <value> (default value or attribute)
  6899. if (parser.accept('=')) {
  6900. const value = parser.parseAttribute();
  6901. op.attributes.push({ name: 'default', value: value.value });
  6902. }
  6903. return true;
  6904. }
  6905. if (opName === 'hal.executable.condition' || opName === 'hal.executable.constant.block') {
  6906. const sig = parser.parseFunctionSignatureWithArguments(false);
  6907. const argTypes = sig.arguments.map((a) => a.type);
  6908. const type = { inputs: argTypes, results: sig.resultTypes };
  6909. op.attributes.push({ name: 'function_type', value: type });
  6910. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  6911. if (parser.match('{')) {
  6912. const region = {};
  6913. parser.parseRegion(region, sig.arguments);
  6914. op.regions.push(region);
  6915. }
  6916. return true;
  6917. }
  6918. // Handle operations with visibility + symbol (similar to flow dialect)
  6919. if (opName === 'hal.executable' || opName === 'hal.interface' || opName === 'hal.executable.binary') {
  6920. this.getOperation(opName).hasParseOperation = false; // compatibility?
  6921. if (parser.match('id', 'private') || parser.match('id', 'public') || parser.match('id', 'nested')) {
  6922. parser.expect('id');
  6923. }
  6924. if (parser.match('@')) {
  6925. const symbol = parser.expect('@');
  6926. op.attributes.push({ name: 'sym_name', value: symbol });
  6927. }
  6928. if (parser.accept('id', 'attributes')) {
  6929. parser.parseAttributeDict(op.attributes);
  6930. }
  6931. if (parser.match('{')) {
  6932. const region = {};
  6933. parser.parseRegion(region);
  6934. op.regions.push(region);
  6935. }
  6936. return true;
  6937. }
  6938. // Handle hal.interface.binding.subspan with old syntax (symbol reference)
  6939. // Old syntax: hal.interface.binding.subspan @io::@binding[operand] : type
  6940. // New syntax: hal.interface.binding.subspan layout(...) binding(...) : type
  6941. if (opName === 'hal.interface.binding.subspan' && parser.match('@')) {
  6942. this.getOperation(opName).hasParseOperation = false; // compatibility?
  6943. // Old syntax - parse symbol reference and bracket expression
  6944. const symbolRef = parser.expect('@');
  6945. op.attributes.push({ name: 'layout', value: symbolRef });
  6946. // Parse optional bracket expression [operand]
  6947. if (parser.accept('[')) {
  6948. while (!parser.accept(']')) {
  6949. if (parser.match('%')) {
  6950. const operand = parser.expect('%');
  6951. op.operands.push({ value: operand });
  6952. } else {
  6953. parser.expect();
  6954. }
  6955. parser.accept(',');
  6956. }
  6957. }
  6958. // Parse result type: type($result) (`{` $dynamic_dims^ `}`)?
  6959. if (parser.accept(':')) {
  6960. const type = parser.parseType();
  6961. if (type) {
  6962. op.results.push({ type: type.toString() });
  6963. }
  6964. // Parse optional dynamic dimensions: {%dim1, %dim2, ...}
  6965. if (parser.accept('{')) {
  6966. const dynamicDims = [];
  6967. if (!parser.match('}')) {
  6968. do {
  6969. const dimOperand = parser.parseSSAUse();
  6970. dynamicDims.push(dimOperand);
  6971. op.operands.push({ value: dimOperand.name, kind: 'dynamic_dim' });
  6972. } while (parser.accept(','));
  6973. }
  6974. parser.expect('}');
  6975. }
  6976. }
  6977. return true;
  6978. }
  6979. // Handle operations with named parameters: hal.interface.binding, hal.executable.variant, etc.
  6980. if (opName === 'hal.interface.binding' || opName === 'hal.executable.variant' || opName === 'hal.executable.entry_point' || opName === 'hal.executable.export') {
  6981. this.getOperation(opName).hasParseOperation = false; // compatibility?
  6982. if (parser.match('id', 'private') || parser.match('id', 'public') || parser.match('id', 'nested')) {
  6983. parser.expect('id');
  6984. }
  6985. if (parser.match('@')) {
  6986. const symbol = parser.expect('@');
  6987. op.attributes.push({ name: 'sym_name', value: symbol });
  6988. parser.accept(',');
  6989. }
  6990. while (parser.match('id') && !parser.match('id', 'attributes') && !parser.match('{') && !parser.match('loc')) {
  6991. const tokenValue = parser.token.value;
  6992. if (tokenValue && tokenValue.includes('.')) {
  6993. break;
  6994. }
  6995. const paramName = parser.expect('id');
  6996. if (parser.accept('(')) {
  6997. let parenDepth = 1;
  6998. let paramValue = '';
  6999. while (parenDepth > 0 && !parser.match('eof')) {
  7000. if (parser.match('(')) {
  7001. parenDepth++;
  7002. paramValue += parser.expect();
  7003. } else if (parser.match(')')) {
  7004. parenDepth--;
  7005. if (parenDepth > 0) {
  7006. paramValue += parser.expect();
  7007. } else {
  7008. parser.expect(')');
  7009. }
  7010. } else {
  7011. paramValue += parser.expect();
  7012. }
  7013. }
  7014. op.attributes.push({ name: paramName, value: paramValue });
  7015. parser.accept(',');
  7016. } else if (parser.accept('=')) {
  7017. if (parser.match('#')) {
  7018. const value = parser.parseAttribute();
  7019. op.attributes.push({ name: paramName, value: value.value });
  7020. } else if (parser.match('string')) {
  7021. const value = parser.expect('string');
  7022. op.attributes.push({ name: paramName, value });
  7023. } else {
  7024. const value = parser.expect();
  7025. op.attributes.push({ name: paramName, value });
  7026. }
  7027. if (!parser.accept(',')) {
  7028. break;
  7029. }
  7030. } else {
  7031. break;
  7032. }
  7033. }
  7034. if (parser.accept('->')) {
  7035. const resultTypes = [];
  7036. const resultAttrs = [];
  7037. parser.parseFunctionResultList(resultTypes, resultAttrs);
  7038. }
  7039. if (parser.accept('id', 'attributes')) {
  7040. parser.parseAttributeDict(op.attributes);
  7041. }
  7042. if (parser.match('{')) {
  7043. const region = {};
  7044. parser.parseRegion(region);
  7045. op.regions.push(region);
  7046. }
  7047. if (parser.accept('id', 'attributes')) {
  7048. parser.parseAttributeDict(op.attributes);
  7049. }
  7050. return true;
  7051. }
  7052. return super.parseOperation(parser, opName, op);
  7053. }
  7054. _parsePipelineLayoutAttr(parser) {
  7055. // HAL_PipelineLayoutAttr format: <constants = N, bindings = [...], flags = ...>
  7056. if (parser.match('<')) {
  7057. return parser.parseAttribute();
  7058. }
  7059. return parser.parseOptionalAttribute();
  7060. }
  7061. };
  7062. mlir.UtilDialect = class extends mlir.IREEDialect {
  7063. constructor(operations) {
  7064. super('util', operations);
  7065. this.registerCustomDirective('OperandTypeList', this._parseOperandTypeList.bind(this));
  7066. this.registerCustomDirective('TiedFunctionResultList', this._parseTiedFunctionResultList.bind(this));
  7067. this.registerCustomDirective('TypeAlias', this._parseTypeAlias.bind(this));
  7068. this.registerCustomDirective('TypedValueList', this._parseTypedValueList.bind(this));
  7069. this.simpleTypes = new Set(['buffer', 'list', 'object', 'ptr']);
  7070. }
  7071. _parseTypeAlias(parser /*, op, args */) {
  7072. parser.parseType();
  7073. if (parser.accept('id', 'as')) {
  7074. parser.parseType();
  7075. }
  7076. }
  7077. _parseTypedValueList(parser /*, op, args */) {
  7078. do {
  7079. parser.expect('%');
  7080. parser.expect(':');
  7081. parser.parseType();
  7082. } while (parser.accept(','));
  7083. }
  7084. parseType(parser, dialectName) {
  7085. const typeName = parser.parseKeyword();
  7086. if (!typeName) {
  7087. return null;
  7088. }
  7089. let type = `!${dialectName}.${typeName}`;
  7090. if (this.simpleTypes.has(typeName)) {
  7091. if (parser.match('<')) {
  7092. const content = parser.skip('<', '>');
  7093. type += content;
  7094. }
  7095. return new mlir.Type(type);
  7096. }
  7097. return null;
  7098. }
  7099. _parseOperandTypeList(parser, op /*, args */) {
  7100. parser.expect('(');
  7101. if (!parser.match(')')) {
  7102. let index = 0;
  7103. do {
  7104. const type = parser.parseType();
  7105. if (index < op.operands.length) {
  7106. op.operands[index].type = type;
  7107. }
  7108. index++;
  7109. } while (parser.accept(','));
  7110. }
  7111. parser.expect(')');
  7112. }
  7113. _parseTiedFunctionResultList(parser, op /*, args */) {
  7114. if (parser.accept('(')) {
  7115. let index = 0;
  7116. if (!parser.match(')')) {
  7117. do {
  7118. const type = parser.parseType();
  7119. if (index < op.results.length) {
  7120. op.results[index].type = type;
  7121. } else {
  7122. op.results.push({ type });
  7123. }
  7124. index++;
  7125. } while (parser.accept(','));
  7126. }
  7127. parser.expect(')');
  7128. } else {
  7129. let index = 0;
  7130. do {
  7131. const type = parser.parseType();
  7132. if (index < op.results.length) {
  7133. op.results[index].type = type;
  7134. } else {
  7135. op.results.push({ type });
  7136. }
  7137. index++;
  7138. } while (parser.accept(','));
  7139. }
  7140. }
  7141. parseOperation(parser, opName, op) {
  7142. if (opName === 'util.assume.int') {
  7143. return this._parseAssumeIntOp(parser, op);
  7144. }
  7145. if (opName === 'util.initializer') {
  7146. if (parser.accept('id', 'attributes')) {
  7147. parser.parseAttributeDict(op.attributes);
  7148. }
  7149. if (parser.match('{')) {
  7150. const region = {};
  7151. parser.parseRegion(region);
  7152. op.regions.push(region);
  7153. }
  7154. return true;
  7155. }
  7156. if (opName === 'util.unreachable') {
  7157. this.getOperation(opName).hasParseOperation = false; // compatibility?
  7158. if (parser.match('string')) {
  7159. const message = parser.expect('string');
  7160. op.attributes.push({ name: 'message', value: message });
  7161. }
  7162. if (parser.match('{')) {
  7163. parser.parseAttributeDict(op.attributes);
  7164. }
  7165. return true;
  7166. }
  7167. if (opName === 'util.func') {
  7168. this._parseUtilFuncOp(parser, op);
  7169. return true;
  7170. }
  7171. if (opName === 'util.unfoldable_constant') {
  7172. // Format: util.unfoldable_constant {attr-dict} value : type
  7173. // Parse optional attr-dict
  7174. if (parser.match('{')) {
  7175. parser.parseAttributeDict(op.attributes);
  7176. }
  7177. // Parse value (constant attribute - can be integer, float, symbol ref, etc.)
  7178. const value = parser.parseAttribute();
  7179. op.attributes.push({ name: 'value', value });
  7180. // Parse : type
  7181. if (parser.accept(':')) {
  7182. const type = parser.parseType();
  7183. op.results.push({ type });
  7184. }
  7185. return true;
  7186. }
  7187. return super.parseOperation(parser, opName, op);
  7188. }
  7189. _parseUtilFuncOp(parser, op) {
  7190. parser.parseOptionalVisibilityKeyword(op.attributes);
  7191. parser.parseSymbolName('sym_name', op.attributes);
  7192. const argResult = parser.parseFunctionArgumentList(false);
  7193. const resultTypes = [];
  7194. const resultAttrs = [];
  7195. if (parser.accept('->')) {
  7196. if (parser.accept('(')) {
  7197. if (!parser.match(')')) {
  7198. do {
  7199. resultTypes.push(parser.parseType());
  7200. if (parser.match('{')) {
  7201. const attrList = [];
  7202. parser.parseAttributeDict(attrList);
  7203. resultAttrs.push(attrList);
  7204. } else {
  7205. resultAttrs.push(null);
  7206. }
  7207. } while (parser.accept(','));
  7208. }
  7209. parser.expect(')');
  7210. } else {
  7211. do {
  7212. resultTypes.push(parser.parseType());
  7213. resultAttrs.push(null);
  7214. } while (parser.accept(','));
  7215. }
  7216. }
  7217. const argTypes = argResult.arguments.filter((a) => a.value !== '...').map((a) => a.type);
  7218. const type = { inputs: argTypes, results: resultTypes };
  7219. op.attributes.push({ name: 'function_type', value: type });
  7220. if (resultAttrs.some((a) => a !== null)) {
  7221. op.attributes.push({ name: 'res_attrs', value: resultAttrs });
  7222. }
  7223. const argAttrs = argResult.arguments.filter((a) => a.value !== '...').map((a) => a.attributes || null);
  7224. if (argAttrs.some((a) => a !== null)) {
  7225. op.attributes.push({ name: 'arg_attrs', value: argAttrs });
  7226. }
  7227. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  7228. if (parser.match('{')) {
  7229. const region = {};
  7230. parser.parseRegion(region, argResult.arguments);
  7231. op.regions.push(region);
  7232. }
  7233. }
  7234. _parseAssumeIntOp(parser, op) {
  7235. const allOperandAssumptions = [];
  7236. const parsedOperands = [];
  7237. const parsedOperandTypes = [];
  7238. do {
  7239. const operand = parser.parseAttribute();
  7240. parsedOperands.push(operand);
  7241. const operandAssumptions = [];
  7242. if (parser.accept('[')) {
  7243. if (!parser.match(']')) {
  7244. do {
  7245. const assumption = this._parseIntAssumptionAttr(parser);
  7246. operandAssumptions.push(assumption);
  7247. } while (parser.accept(','));
  7248. }
  7249. parser.expect(']');
  7250. } else if (parser.match('<')) {
  7251. const assumption = this._parseIntAssumptionAttr(parser);
  7252. operandAssumptions.push(assumption);
  7253. }
  7254. allOperandAssumptions.push(operandAssumptions);
  7255. } while (parser.accept(','));
  7256. parser.expect(':');
  7257. do {
  7258. const type = parser.parseType();
  7259. parsedOperandTypes.push(type);
  7260. } while (parser.accept(','));
  7261. for (let i = 0; i < parsedOperands.length; i++) {
  7262. const operand = parsedOperands[i];
  7263. if (parsedOperandTypes[i]) {
  7264. operand.type = parsedOperandTypes[i];
  7265. }
  7266. op.operands.push(operand);
  7267. op.results.push({ type: parsedOperandTypes[i] || null });
  7268. }
  7269. op.attributes.push({ name: 'assumptions', value: allOperandAssumptions });
  7270. if (parser.match('{')) {
  7271. parser.parseAttributeDict(op.attributes);
  7272. }
  7273. return true;
  7274. }
  7275. _parseIntAssumptionAttr(parser) {
  7276. parser.expect('<');
  7277. const assumption = {};
  7278. if (!parser.match('>')) {
  7279. do {
  7280. const key = parser.expect('id');
  7281. if (!parser.accept('=')) {
  7282. throw new mlir.Error(`Expected '=' after ${key} ${parser.location()}`);
  7283. }
  7284. const value = parser.expect('int');
  7285. assumption[key] = value;
  7286. } while (parser.accept(','));
  7287. }
  7288. parser.expect('>');
  7289. return assumption;
  7290. }
  7291. };
  7292. mlir.FlowDialect = class extends mlir.IREEDialect {
  7293. constructor(operations) {
  7294. super('flow', operations);
  7295. this.registerCustomDirective('DispatchWorkgroupBody', this._parseDispatchWorkgroupBody.bind(this));
  7296. this.registerCustomDirective('DispatchWorkgroupsCountRegion', this._parseDispatchWorkgroupsCountRegion.bind(this));
  7297. this.registerCustomDirective('ShapedFunctionType', this._parseShapedFunctionType.bind(this));
  7298. }
  7299. parseType(parser, dialectName) {
  7300. const typeName = parser.parseKeyword();
  7301. if (!typeName) {
  7302. return null;
  7303. }
  7304. let type = `!${dialectName}.${typeName}`;
  7305. if (typeName === 'channel') {
  7306. return new mlir.Type(type);
  7307. }
  7308. if (typeName === 'dispatch.tensor') {
  7309. if (parser.match('<')) {
  7310. const content = parser.skip('<', '>');
  7311. type += content;
  7312. }
  7313. return new mlir.Type(type);
  7314. }
  7315. return null;
  7316. }
  7317. parseOperation(parser, opName, op) {
  7318. if (opName === 'flow.ex.stream.fragment') {
  7319. return this._parseDispatchWorkgroupsOp(parser, op);
  7320. }
  7321. if (opName === 'flow.dispatch.region') {
  7322. return this._parseDispatchRegionOp(parser, op);
  7323. }
  7324. if (opName === 'flow.dispatch.tensor.load' || opName === 'flow.dispatch.tensor.store') {
  7325. return this._parseTensorLoadStoreOp(parser, op);
  7326. }
  7327. // Handle operations with visibility + symbol that aren't in schema or need manual parsing
  7328. if (opName === 'flow.dispatch.entry') {
  7329. if (parser.match('id', 'private') || parser.match('id', 'public') || parser.match('id', 'nested')) {
  7330. parser.expect('id');
  7331. }
  7332. if (parser.match('@')) {
  7333. const symbol = parser.expect('@');
  7334. op.attributes.push({ name: 'sym_name', value: symbol });
  7335. }
  7336. if (parser.accept('id', 'attributes')) {
  7337. parser.parseAttributeDict(op.attributes);
  7338. }
  7339. if (parser.match('{')) {
  7340. const region = {};
  7341. parser.parseRegion(region);
  7342. op.regions.push(region);
  7343. }
  7344. return true;
  7345. }
  7346. if (opName === 'flow.func') {
  7347. parser.parseFunctionOp(op, false);
  7348. return true;
  7349. }
  7350. return super.parseOperation(parser, opName, op);
  7351. }
  7352. _parseDispatchRegionOp(parser, op) {
  7353. // Reference: FlowOps.cpp:426 uses parseOperandList
  7354. const workloadOperands = parser.parseOperandList('optionalSquare');
  7355. op.operands.push(...workloadOperands);
  7356. if (parser.accept('->')) {
  7357. if (parser.accept('(')) {
  7358. while (!parser.accept(')')) {
  7359. const result = {};
  7360. result.type = parser.parseType();
  7361. if (parser.accept('{')) {
  7362. while (!parser.accept('}')) {
  7363. const operand = {};
  7364. operand.value = parser.expect('%');
  7365. op.operands.push(operand);
  7366. parser.accept(',');
  7367. }
  7368. }
  7369. op.results.push(result);
  7370. parser.accept(',');
  7371. }
  7372. }
  7373. }
  7374. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  7375. if (parser.match('{')) {
  7376. const region = {};
  7377. parser.parseRegion(region);
  7378. op.regions.push(region);
  7379. }
  7380. return true;
  7381. }
  7382. _parseDispatchWorkgroupsOp(parser, op) {
  7383. // Parse subscript values: [%c32, %c112, %c112]
  7384. if (parser.accept('[')) {
  7385. while (!parser.accept(']')) {
  7386. parser.expect(); // read subscript value
  7387. parser.accept(',');
  7388. }
  7389. }
  7390. // Parse operands: (%0, %1)
  7391. op.operands = parser.parseArguments();
  7392. // Parse type signature : (...) -> (...)
  7393. // Reference: parseOptionalColonTypeList for operands
  7394. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  7395. // Reference: parseOptionalArrowTypeList for results
  7396. if (parser.accept('->')) {
  7397. if (op.results.length > 0) {
  7398. const types = parser.parseFunctionResultTypes();
  7399. parser.resolveOperands(op.results, types);
  7400. } else {
  7401. op.results = parser.parseArguments();
  7402. }
  7403. }
  7404. // Parse optional attributes before =
  7405. if (parser.accept('id', 'attributes')) {
  7406. parser.parseAttributeDict(op.attributes);
  7407. }
  7408. // Parse region with arguments: = (%arg2: type, %arg3: type) { ... }
  7409. if (parser.accept('=')) {
  7410. const region = {};
  7411. region.blocks = [];
  7412. const block = {};
  7413. block.operations = [];
  7414. block.arguments = [];
  7415. // Parse region arguments
  7416. if (parser.accept('(')) {
  7417. while (!parser.accept(')')) {
  7418. const value = parser.expect('%');
  7419. parser.expect(':');
  7420. const type = parser.parseType();
  7421. block.arguments.push({ value, type });
  7422. parser.accept(',');
  7423. }
  7424. }
  7425. // Some operations like flow.ex.stream.fragment have -> type after region args
  7426. if (parser.accept('->') || parser.accept('id', 'to')) {
  7427. parser.parseType();
  7428. }
  7429. // Parse region body
  7430. parser.parseBlock(block);
  7431. region.blocks.push(block);
  7432. op.regions.push(region);
  7433. }
  7434. return true;
  7435. }
  7436. _parseShapedFunctionType(parser, op /*, args */) {
  7437. // Parse: (operand_types) -> result_types
  7438. // This handles shaped function types with dynamic dimensions
  7439. // Example: (tensor<?x?xf32>{%dim0, %dim1}, tensor<4xf32>) -> tensor<?xf32>
  7440. // Parse input types
  7441. if (parser.accept('(')) {
  7442. let index = 0;
  7443. if (!parser.match(')')) {
  7444. do {
  7445. const type = parser.parseType();
  7446. if (type) {
  7447. const startIdx = Math.max(0, op.operands.length - (index + 1));
  7448. if (startIdx + index < op.operands.length && !op.operands[startIdx + index].type) {
  7449. op.operands[startIdx + index].type = type;
  7450. }
  7451. index++;
  7452. }
  7453. if (parser.accept('{')) {
  7454. while (!parser.accept('}')) {
  7455. parser.expect('%');
  7456. parser.accept(',');
  7457. }
  7458. }
  7459. } while (parser.accept(','));
  7460. }
  7461. parser.expect(')');
  7462. }
  7463. // Parse arrow and result types
  7464. if (parser.accept('->')) {
  7465. let index = 0;
  7466. const hasParens = parser.accept('(');
  7467. if (!parser.match(')') && !parser.match('{') && !parser.match('loc') && !parser.match('=')) {
  7468. do {
  7469. if (parser.accept('%')) {
  7470. index++;
  7471. continue;
  7472. }
  7473. const type = parser.parseType();
  7474. if (type) {
  7475. if (index < op.results.length) {
  7476. op.results[index].type = type;
  7477. } else {
  7478. op.results.push({ type });
  7479. }
  7480. index++;
  7481. }
  7482. if (parser.accept('{')) {
  7483. while (!parser.accept('}')) {
  7484. parser.expect('%');
  7485. parser.accept(',');
  7486. }
  7487. }
  7488. if (!hasParens) {
  7489. break;
  7490. }
  7491. } while (parser.accept(','));
  7492. }
  7493. if (hasParens) {
  7494. parser.expect(')');
  7495. }
  7496. }
  7497. }
  7498. _parseTensorLoadStoreOp(parser, op) {
  7499. // Parse: load %arg2, offsets = [...] : type -> type
  7500. // or: store %26, %arg4, offsets = [...] : type -> type
  7501. while (parser.match('%')) {
  7502. const value = parser.expect('%');
  7503. op.operands.push({ value });
  7504. if (!parser.accept(',')) {
  7505. break;
  7506. }
  7507. if (!parser.match('%')) {
  7508. break;
  7509. }
  7510. }
  7511. // At this point, if we broke because of named params, we've already consumed the comma
  7512. // Parse comma-separated named parameters: offsets = [...], sizes = [...], strides = [...]
  7513. // Note: first parameter might not need comma-eating if we just broke from operand loop
  7514. let needComma = !parser.match('id'); // If we're not at 'id', we need to eat commas
  7515. while (needComma ? parser.accept(',') : true) {
  7516. needComma = true; // After first iteration, always need comma
  7517. if (parser.match('id')) {
  7518. const paramName = parser.expect('id');
  7519. if (parser.accept('=')) {
  7520. // Skip the parameter value (usually an array)
  7521. if (parser.match('[')) {
  7522. parser.skip('[', ']');
  7523. } else {
  7524. parser.expect(); // Read single value
  7525. }
  7526. op.attributes.push({ name: paramName, value: paramName });
  7527. }
  7528. } else {
  7529. break;
  7530. }
  7531. }
  7532. // Parse type signature : type -> type
  7533. // Reference: parseOptionalColonTypeList
  7534. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  7535. // For tensor.load, there's a -> result type
  7536. // For tensor.store, the -> is followed by the output tensor type (not a result)
  7537. if (parser.accept('->') || parser.accept('id', 'to')) {
  7538. // Just skip the type - we don't need to parse it as results
  7539. parser.parseType();
  7540. }
  7541. return true;
  7542. }
  7543. _parseDispatchWorkgroupBody(parser, op /*, args */) {
  7544. parser.expect('(');
  7545. const regionArgs = [];
  7546. if (!parser.match(')')) {
  7547. do {
  7548. const arg = parser.expect('%');
  7549. parser.expect(':');
  7550. const argType = parser.parseType();
  7551. regionArgs.push({ name: arg, type: argType });
  7552. } while (parser.accept(','));
  7553. }
  7554. parser.expect(')');
  7555. const region = { blocks: [{ arguments: regionArgs, operations: [] }] };
  7556. parser.parseRegion(region);
  7557. op.regions.push(region);
  7558. }
  7559. _parseDispatchWorkgroupsCountRegion(parser, op /*, args */) {
  7560. if (!parser.accept('id', 'count')) {
  7561. return;
  7562. }
  7563. parser.expect('(');
  7564. const regionArgs = [];
  7565. if (!parser.match(')')) {
  7566. do {
  7567. const arg = parser.expect('%');
  7568. parser.expect(':');
  7569. const argType = parser.parseType();
  7570. regionArgs.push({ name: arg, type: argType });
  7571. } while (parser.accept(','));
  7572. }
  7573. parser.expect(')');
  7574. parser.expect('->');
  7575. if (parser.accept('(')) {
  7576. parser.parseType();
  7577. parser.accept(',');
  7578. parser.parseType();
  7579. parser.accept(',');
  7580. parser.parseType();
  7581. parser.expect(')');
  7582. } else {
  7583. parser.parseType();
  7584. parser.accept(',');
  7585. parser.parseType();
  7586. parser.accept(',');
  7587. parser.parseType();
  7588. }
  7589. const region = { blocks: [{ arguments: regionArgs, operations: [] }] };
  7590. parser.parseRegion(region);
  7591. op.regions.push(region);
  7592. }
  7593. };
  7594. mlir.StreamDialect = class extends mlir.IREEDialect {
  7595. constructor(operations) {
  7596. super('stream', operations);
  7597. this.registerCustomDirective('DispatchOperands', this._parseDispatchOperands.bind(this));
  7598. this.registerCustomDirective('DispatchResources', this._parseDispatchResources.bind(this));
  7599. this.registerCustomDirective('ExplicitResourceRegion', this._parseExplicitResourceRegion.bind(this));
  7600. this.registerCustomDirective('ShapedFunctionType', this._parseShapedFunctionType.bind(this));
  7601. this.registerCustomDirective('ShapedTypeList', this._parseShapedTypeList.bind(this));
  7602. this.registerCustomDirective('ResourceRegion', this._parseResourceRegion.bind(this));
  7603. this.registerCustomDirective('ParameterLoadOperations', this._parseParameterLoadOperations.bind(this));
  7604. this.registerCustomDirective('EncodedResourceOperands', this._parseEncodedResourceOperands.bind(this));
  7605. this.registerCustomDirective('DispatchEntryPoints', this._parseDispatchEntryPoints.bind(this));
  7606. this.registerCustomDirective('ShapedTiedResult', this._parseShapedTiedResult.bind(this));
  7607. this.registerCustomDirective('SymbolVisibility', this._parseSymbolVisibility.bind(this));
  7608. this.registerCustomDirective('EncodedShapedFunctionType', this._parseEncodedShapedFunctionType.bind(this));
  7609. this.registerCustomDirective('CollectiveParam', this._parseCollectiveParam.bind(this));
  7610. this.registerCustomDirective('PackSliceRanges', this._parsePackSliceRanges.bind(this));
  7611. this.registerCustomDirective('WorkgroupCountRegion', this._parseWorkgroupCountRegion.bind(this));
  7612. this.registerCustomDirective('DispatchFunctionSignature', this._parseDispatchFunctionSignature.bind(this));
  7613. this.registerCustomDirective('ShapedFunctionSignature', this._parseShapedFunctionSignature.bind(this));
  7614. this.registerCustomDirective('ConstantValueList', this._parseConstantValueList.bind(this));
  7615. this.registerCustomDirective('CmdCallOperands', this._parseCmdCallOperands.bind(this));
  7616. this.registerCustomDirective('ParameterReference', this._parseParameterReference.bind(this));
  7617. this.registerCustomDirective('ParameterGatherOperations', this._parseParameterGatherOperations.bind(this));
  7618. this.registerCustomDirective('ParameterScatterOperations', this._parseParameterScatterOperations.bind(this));
  7619. this.registerCustomDirective('SymbolAlias', this._parseSymbolAlias.bind(this));
  7620. }
  7621. _parseDispatchResources(parser, op /*, args */) {
  7622. do {
  7623. const accessMode = parser.expect('id');
  7624. const resource = parser.expect('%');
  7625. op.operands.push({ value: resource });
  7626. parser.expect('[');
  7627. const offset = parser.expect('%');
  7628. op.operands.push({ value: offset });
  7629. parser.expect('id', 'for');
  7630. const length = parser.expect('%');
  7631. op.operands.push({ value: length });
  7632. parser.expect(']');
  7633. parser.expect(':');
  7634. parser.parseType();
  7635. if (parser.match('{')) {
  7636. parser.skip('{', '}');
  7637. }
  7638. op.attributes.push({ name: 'resource_access', value: accessMode });
  7639. } while (parser.accept(','));
  7640. }
  7641. _parseShapedFunctionType(parser /*, op, args */) {
  7642. parser.expect('(');
  7643. if (!parser.match(')')) {
  7644. do {
  7645. parser.parseType();
  7646. if (parser.match('{')) {
  7647. parser.skip('{', '}');
  7648. }
  7649. } while (parser.accept(','));
  7650. }
  7651. parser.expect(')');
  7652. parser.expect('->');
  7653. if (parser.accept('(')) {
  7654. if (!parser.match(')')) {
  7655. do {
  7656. parser.parseType();
  7657. if (parser.match('{')) {
  7658. parser.skip('{', '}');
  7659. }
  7660. } while (parser.accept(','));
  7661. }
  7662. parser.expect(')');
  7663. } else {
  7664. parser.parseType();
  7665. if (parser.match('{')) {
  7666. parser.skip('{', '}');
  7667. }
  7668. }
  7669. }
  7670. _parseShapedTypeList(parser /*, op, args */) {
  7671. do {
  7672. parser.parseType();
  7673. if (parser.match('{')) {
  7674. parser.skip('{', '}');
  7675. }
  7676. } while (parser.accept(','));
  7677. }
  7678. _parseExplicitResourceRegion(parser, op /*, args */) {
  7679. parser.expect('(');
  7680. const regionArgs = [];
  7681. if (!parser.match(')')) {
  7682. do {
  7683. const operand = parser.parseAttribute();
  7684. if (operand) {
  7685. op.operands.push(operand);
  7686. }
  7687. parser.expect('id', 'as');
  7688. const arg = parser.expect('%');
  7689. parser.expect(':');
  7690. const argType = parser.parseType();
  7691. regionArgs.push({ name: arg, type: argType });
  7692. if (parser.accept('{')) {
  7693. const size = parser.parseAttribute();
  7694. if (size) {
  7695. op.operands.push(size);
  7696. }
  7697. parser.expect('}');
  7698. }
  7699. } while (parser.accept(','));
  7700. }
  7701. parser.expect(')');
  7702. const region = { blocks: [{ arguments: regionArgs, operations: [] }] };
  7703. parser.parseRegion(region);
  7704. op.regions.push(region);
  7705. }
  7706. _parseResourceRegion(parser, op /*, args */) {
  7707. // Reference: StreamOps.cpp parseResourceRegion
  7708. // Format: (operand as arg: type{size}, ...) -> (result_type{size}, ...) { region }
  7709. const regionArgs = [];
  7710. parser.expect('(');
  7711. if (!parser.match(')')) {
  7712. do {
  7713. const operand = parser.expect('%');
  7714. op.operands.push({ value: operand });
  7715. parser.expect('id', 'as');
  7716. const arg = parser.expect('%');
  7717. parser.expect(':');
  7718. const argType = parser.parseType();
  7719. regionArgs.push({ name: arg, type: argType });
  7720. if (parser.accept('{')) {
  7721. const size = parser.parseAttribute();
  7722. if (size) {
  7723. op.operands.push(size);
  7724. }
  7725. parser.expect('}');
  7726. }
  7727. } while (parser.accept(','));
  7728. }
  7729. parser.expect(')');
  7730. // Parse optional result types
  7731. if (parser.accept('->')) {
  7732. if (parser.accept('(')) {
  7733. if (!parser.match(')')) {
  7734. do {
  7735. // Parse tied result format: %operand as type{size} or just type{size}
  7736. if (parser.match('%')) {
  7737. parser.expect('%');
  7738. parser.expect('id', 'as');
  7739. }
  7740. const resultType = parser.parseType();
  7741. op.results.push({ type: resultType });
  7742. if (parser.accept('{')) {
  7743. const size = parser.parseAttribute();
  7744. if (size) {
  7745. op.operands.push(size);
  7746. }
  7747. parser.expect('}');
  7748. }
  7749. } while (parser.accept(','));
  7750. }
  7751. parser.expect(')');
  7752. } else {
  7753. // Single result without parens
  7754. if (parser.match('%')) {
  7755. parser.expect('%');
  7756. parser.expect('id', 'as');
  7757. }
  7758. const resultType = parser.parseType();
  7759. op.results.push({ type: resultType });
  7760. if (parser.accept('{')) {
  7761. const size = parser.parseAttribute();
  7762. if (size) {
  7763. op.operands.push(size);
  7764. }
  7765. parser.expect('}');
  7766. }
  7767. }
  7768. }
  7769. // Parse region
  7770. if (parser.match('{')) {
  7771. const region = { blocks: [{ arguments: regionArgs, operations: [] }] };
  7772. parser.parseRegion(region);
  7773. op.regions.push(region);
  7774. }
  7775. }
  7776. _parseParameterLoadOperations(parser, op /*, args */) {
  7777. // Reference: IOParametersOps.cpp parseParameterLoadOperations
  7778. // Format: "scope"::"key"[%offset] : type{%size}, ...
  7779. do {
  7780. // Parse parameter reference: "scope"::"key" or just "key"
  7781. const firstAttr = parser.expect('string');
  7782. // Check for :: (scope::key) pattern - the lexer produces '::' as a single token
  7783. if (parser.accept('id', '::') || parser.accept('::')) {
  7784. const keyAttr = parser.expect('string');
  7785. op.attributes.push({ name: 'source_scope', value: firstAttr });
  7786. op.attributes.push({ name: 'source_key', value: keyAttr });
  7787. } else {
  7788. op.attributes.push({ name: 'source_key', value: firstAttr });
  7789. }
  7790. parser.expect('[');
  7791. const offset = parser.expect('%');
  7792. op.operands.push({ name: 'source_offset', value: offset });
  7793. parser.expect(']');
  7794. parser.expect(':');
  7795. const resultType = parser.parseType();
  7796. op.results.push({ type: resultType });
  7797. if (parser.accept('{')) {
  7798. const size = parser.expect('%');
  7799. op.operands.push({ name: 'result_size', value: size });
  7800. parser.expect('}');
  7801. }
  7802. } while (parser.accept(','));
  7803. }
  7804. _parseEncodedResourceOperands(parser /*, op, args */) {
  7805. do {
  7806. parser.expect('%');
  7807. if (parser.match('[')) {
  7808. parser.skip('[', ']');
  7809. }
  7810. } while (parser.accept(','));
  7811. }
  7812. // Parse: @entry_point or {@entry_point1, @entry_point2}
  7813. // Reference: StreamOps.cpp parseDispatchEntryPoints
  7814. _parseDispatchEntryPoints(parser, op /*, args */) {
  7815. if (parser.accept('{')) {
  7816. do {
  7817. const symbol = parser.expect('@');
  7818. op.attributes.push({ name: 'entry_point', value: symbol });
  7819. } while (parser.accept(','));
  7820. parser.expect('}');
  7821. } else {
  7822. const symbol = parser.expect('@');
  7823. op.attributes.push({ name: 'entry_point', value: symbol });
  7824. }
  7825. }
  7826. _parseShapedTiedResult(parser, op /*, args */) {
  7827. let tiedOperand = null;
  7828. if (parser.match('%')) {
  7829. tiedOperand = parser.expect('%');
  7830. parser.expect('id', 'as');
  7831. }
  7832. const type = parser.parseType();
  7833. op.results.push({ type, tiedOperand });
  7834. if (parser.accept('{')) {
  7835. const size = parser.parseAttribute();
  7836. if (size) {
  7837. op.operands.push(size);
  7838. }
  7839. parser.expect('}');
  7840. }
  7841. }
  7842. // Parse: public/private/nested
  7843. _parseSymbolVisibility(parser, op /*, args */) {
  7844. if (parser.accept('id', 'public')) {
  7845. op.attributes.push({ name: 'sym_visibility', value: 'public' });
  7846. } else if (parser.accept('id', 'private')) {
  7847. op.attributes.push({ name: 'sym_visibility', value: 'private' });
  7848. } else if (parser.accept('id', 'nested')) {
  7849. op.attributes.push({ name: 'sym_visibility', value: 'nested' });
  7850. }
  7851. }
  7852. // Parse: (types) -> (types) with sizes in {}
  7853. _parseEncodedShapedFunctionType(parser /*, op, args */) {
  7854. parser.expect('(');
  7855. if (!parser.match(')')) {
  7856. do {
  7857. parser.parseType();
  7858. if (parser.match('{')) {
  7859. parser.skip('{', '}');
  7860. }
  7861. } while (parser.accept(','));
  7862. }
  7863. parser.expect(')');
  7864. parser.expect('->');
  7865. if (parser.accept('(')) {
  7866. if (!parser.match(')')) {
  7867. do {
  7868. parser.parseType();
  7869. if (parser.match('{')) {
  7870. parser.skip('{', '}');
  7871. }
  7872. } while (parser.accept(','));
  7873. }
  7874. parser.expect(')');
  7875. } else {
  7876. parser.parseType();
  7877. if (parser.match('{')) {
  7878. parser.skip('{', '}');
  7879. }
  7880. }
  7881. }
  7882. // Parse: collective operation parameters
  7883. _parseCollectiveParam(parser, op /*, args */) {
  7884. // Parse channel operand or attribute
  7885. if (parser.match('%')) {
  7886. const channel = parser.expect('%');
  7887. op.operands.push({ value: channel });
  7888. }
  7889. }
  7890. // Parse: [offset, length] pairs
  7891. _parsePackSliceRanges(parser /*, op, args */) {
  7892. parser.expect('[');
  7893. if (!parser.match(']')) {
  7894. do {
  7895. parser.expect('[');
  7896. parser.parseAttribute();
  7897. parser.expect(',');
  7898. parser.parseAttribute();
  7899. parser.expect(']');
  7900. } while (parser.accept(','));
  7901. }
  7902. parser.expect(']');
  7903. }
  7904. // Parse: workgroups(%x: type, %y: type, %z: type) -> (index, index, index) { ... }
  7905. _parseWorkgroupCountRegion(parser, op /*, args */) {
  7906. if (!parser.accept('id', 'workgroups')) {
  7907. return;
  7908. }
  7909. const region = { blocks: [] };
  7910. const block = { arguments: [], operations: [] };
  7911. if (parser.accept('(')) {
  7912. while (!parser.match(')')) {
  7913. const arg = { value: parser.expect('%') };
  7914. if (parser.accept(':')) {
  7915. arg.type = parser.parseType();
  7916. }
  7917. block.arguments.push(arg);
  7918. if (!parser.accept(',')) {
  7919. break;
  7920. }
  7921. }
  7922. parser.expect(')');
  7923. }
  7924. // Parse optional return type -> (types)
  7925. if (parser.accept('->')) {
  7926. parser.expect('(');
  7927. while (!parser.match(')')) {
  7928. parser.parseType();
  7929. if (!parser.accept(',')) {
  7930. break;
  7931. }
  7932. }
  7933. parser.expect(')');
  7934. }
  7935. region.blocks.push(block);
  7936. if (parser.match('{')) {
  7937. parser.parseRegion(region);
  7938. }
  7939. op.regions.push(region);
  7940. }
  7941. // Parse: dispatch function signature
  7942. _parseDispatchFunctionSignature(parser /*, op, args */) {
  7943. parser.expect('(');
  7944. if (!parser.match(')')) {
  7945. do {
  7946. parser.expect('%');
  7947. if (parser.accept('[')) {
  7948. parser.skip('[', ']');
  7949. }
  7950. parser.expect(':');
  7951. parser.parseType();
  7952. if (parser.match('{')) {
  7953. parser.skip('{', '}');
  7954. }
  7955. } while (parser.accept(','));
  7956. }
  7957. parser.expect(')');
  7958. if (parser.accept('->')) {
  7959. if (parser.accept('(')) {
  7960. if (!parser.match(')')) {
  7961. do {
  7962. parser.parseType();
  7963. if (parser.match('{')) {
  7964. parser.skip('{', '}');
  7965. }
  7966. } while (parser.accept(','));
  7967. }
  7968. parser.expect(')');
  7969. } else {
  7970. parser.parseType();
  7971. if (parser.match('{')) {
  7972. parser.skip('{', '}');
  7973. }
  7974. }
  7975. }
  7976. }
  7977. // Parse: shaped function signature
  7978. _parseShapedFunctionSignature(parser /*, op, args */) {
  7979. this._parseDispatchFunctionSignature(parser);
  7980. }
  7981. // Parse: constant value list
  7982. _parseConstantValueList(parser /*, op, args */) {
  7983. do {
  7984. parser.parseAttribute();
  7985. parser.expect(':');
  7986. parser.parseType();
  7987. if (parser.match('{')) {
  7988. parser.skip('{', '}');
  7989. }
  7990. } while (parser.accept(','));
  7991. }
  7992. // Parse: cmd call operands similar to dispatch operands
  7993. _parseCmdCallOperands(parser, op /*, args */) {
  7994. parser.expect('(');
  7995. if (!parser.match(')')) {
  7996. do {
  7997. const operand = parser.parseAttribute();
  7998. if (operand) {
  7999. op.operands.push(operand);
  8000. if (parser.accept('[')) {
  8001. const offset = parser.parseAttribute();
  8002. if (offset) {
  8003. op.operands.push(offset);
  8004. }
  8005. parser.expect('id', 'to');
  8006. const end = parser.parseAttribute();
  8007. if (end) {
  8008. op.operands.push(end);
  8009. }
  8010. parser.expect('id', 'for');
  8011. const length = parser.parseAttribute();
  8012. if (length) {
  8013. op.operands.push(length);
  8014. }
  8015. parser.expect(']');
  8016. }
  8017. }
  8018. } while (parser.accept(','));
  8019. }
  8020. parser.expect(')');
  8021. }
  8022. // Parse: "scope"::"key"
  8023. _parseParameterReference(parser /*, op, args */) {
  8024. if (parser.match('string')) {
  8025. parser.expect('string');
  8026. }
  8027. if (parser.accept(':')) {
  8028. parser.expect(':');
  8029. if (parser.match('string')) {
  8030. parser.expect('string');
  8031. }
  8032. }
  8033. }
  8034. // Parse: parameter gather operations
  8035. _parseParameterGatherOperations(parser /*, op, args */) {
  8036. do {
  8037. // "scope"::"key"[offset] -> %target[offset for length] : type{size}
  8038. this._parseParameterReference(parser);
  8039. if (parser.accept('[')) {
  8040. parser.parseAttribute();
  8041. parser.expect(']');
  8042. }
  8043. parser.expect('->');
  8044. parser.expect('%');
  8045. if (parser.accept('[')) {
  8046. parser.parseAttribute();
  8047. parser.expect('id', 'for');
  8048. parser.parseAttribute();
  8049. parser.expect(']');
  8050. }
  8051. parser.expect(':');
  8052. parser.parseType();
  8053. if (parser.match('{')) {
  8054. parser.skip('{', '}');
  8055. }
  8056. } while (parser.accept(','));
  8057. }
  8058. // Parse: parameter scatter operations
  8059. _parseParameterScatterOperations(parser /*, op, args */) {
  8060. do {
  8061. // %source[offset for length] : type{size} -> "scope"::"key"[offset]
  8062. parser.expect('%');
  8063. if (parser.accept('[')) {
  8064. parser.parseAttribute();
  8065. parser.expect('id', 'for');
  8066. parser.parseAttribute();
  8067. parser.expect(']');
  8068. }
  8069. parser.expect(':');
  8070. parser.parseType();
  8071. if (parser.match('{')) {
  8072. parser.skip('{', '}');
  8073. }
  8074. parser.expect('->');
  8075. this._parseParameterReference(parser);
  8076. if (parser.accept('[')) {
  8077. parser.parseAttribute();
  8078. parser.expect(']');
  8079. }
  8080. } while (parser.accept(','));
  8081. }
  8082. // Parse: symbol alias @name = @ref
  8083. _parseSymbolAlias(parser, op /*, args */) {
  8084. const name = parser.expect('@');
  8085. op.attributes.push({ name: 'sym_name', value: name });
  8086. if (parser.accept('=')) {
  8087. const ref = parser.expect('@');
  8088. op.attributes.push({ name: 'function_ref', value: ref });
  8089. }
  8090. }
  8091. parseType(parser, dialectName) {
  8092. const typeName = parser.parseKeyword();
  8093. if (!typeName) {
  8094. return null;
  8095. }
  8096. let type = `!${dialectName}.${typeName}`;
  8097. const simpleTypes = ['binding', 'channel', 'timepoint', 'file'];
  8098. if (simpleTypes.includes(typeName)) {
  8099. return new mlir.Type(type);
  8100. }
  8101. if (typeName === 'resource') {
  8102. if (parser.match('<')) {
  8103. const content = parser.skip('<', '>');
  8104. type += content;
  8105. }
  8106. return new mlir.Type(type);
  8107. }
  8108. // Handle test.fence type (Stream_TestFence in StreamTypes.td)
  8109. if (typeName === 'test') {
  8110. parser.expect('.');
  8111. const subtype = parser.parseKeyword();
  8112. if (subtype === 'fence') {
  8113. return new mlir.Type(`!${dialectName}.test.fence`);
  8114. }
  8115. }
  8116. return null;
  8117. }
  8118. parseOperation(parser, opName, op) {
  8119. return super.parseOperation(parser, opName, op);
  8120. }
  8121. _parseDispatchOperands(parser, op /*, args */) {
  8122. // Parse: (operand1, operand2[offset to end for length], ...)
  8123. // args would be: [$resource_operands, $resource_operand_offsets, $resource_operand_ends, $resource_operand_lengths]
  8124. parser.expect('(');
  8125. if (parser.match(')')) {
  8126. parser.expect(')');
  8127. return;
  8128. }
  8129. do {
  8130. // Parse the operand
  8131. const operand = parser.parseAttribute();
  8132. if (operand) {
  8133. op.operands.push(operand);
  8134. // Check for slice notation: [offset to end for length]
  8135. if (parser.accept('[')) {
  8136. // Parse offset operand
  8137. const offset = parser.parseAttribute();
  8138. if (offset) {
  8139. op.operands.push(offset);
  8140. }
  8141. // Parse "to" keyword
  8142. parser.expect('id', 'to');
  8143. // Parse end operand
  8144. const end = parser.parseAttribute();
  8145. if (end) {
  8146. op.operands.push(end);
  8147. }
  8148. // Parse "for" keyword
  8149. parser.expect('id', 'for');
  8150. // Parse length operand
  8151. const length = parser.parseAttribute();
  8152. if (length) {
  8153. op.operands.push(length);
  8154. }
  8155. parser.expect(']');
  8156. }
  8157. }
  8158. } while (parser.accept(','));
  8159. parser.expect(')');
  8160. }
  8161. };
  8162. mlir.IREEVectorExtDialect = class extends mlir.Dialect {
  8163. constructor(operations) {
  8164. super('iree_vector_ext', operations);
  8165. }
  8166. parseOperation(parser, opName, op) {
  8167. if (opName === 'iree_vector_ext.transfer_gather') {
  8168. // Format: iree_vector_ext.transfer_gather %source[%indices][index_vec_list], %padding [, %mask] { attr_dict } : source_type, result_type
  8169. // Parse source operand
  8170. const source = parser.expect('%');
  8171. op.operands.push({ value: source });
  8172. // Parse indices in [...]
  8173. parser.expect('[');
  8174. while (!parser.accept(']')) {
  8175. if (parser.match('%')) {
  8176. const index = parser.expect('%');
  8177. op.operands.push({ value: index, name: 'index' });
  8178. }
  8179. parser.accept(',');
  8180. }
  8181. // Parse index vectors in [...]
  8182. // Format: [None, %operand: type, None, %operand: type, ...]
  8183. parser.expect('[');
  8184. const indexed = [];
  8185. while (!parser.accept(']')) {
  8186. if (parser.accept('id', 'None')) {
  8187. indexed.push(false);
  8188. } else if (parser.match('%')) {
  8189. const indexVec = parser.expect('%');
  8190. parser.expect(':');
  8191. const indexVecType = parser.parseType();
  8192. op.operands.push({ value: indexVec, type: indexVecType, name: 'indexVec' });
  8193. indexed.push(true);
  8194. }
  8195. parser.accept(',');
  8196. }
  8197. op.attributes.push({ name: 'indexed', value: indexed });
  8198. // Parse padding operand
  8199. parser.expect(',');
  8200. const padding = parser.parseAttribute();
  8201. op.operands.push({ value: padding, name: 'padding' });
  8202. // Parse optional mask operand
  8203. if (parser.accept(',')) {
  8204. if (parser.match('%')) {
  8205. const mask = parser.expect('%');
  8206. op.operands.push({ value: mask, name: 'mask' });
  8207. }
  8208. }
  8209. // Parse optional attr-dict
  8210. if (parser.match('{')) {
  8211. parser.parseAttributeDict(op.attributes);
  8212. }
  8213. // Parse : source_type, result_type
  8214. if (parser.accept(':')) {
  8215. const sourceType = parser.parseType();
  8216. op.operands[0].type = sourceType;
  8217. parser.expect(',');
  8218. const resultType = parser.parseType();
  8219. op.results.push({ type: resultType });
  8220. }
  8221. return true;
  8222. }
  8223. return super.parseOperation(parser, opName, op);
  8224. }
  8225. };
  8226. mlir.IREETensorExtDialect = class extends mlir.Dialect {
  8227. constructor(operations) {
  8228. super('iree_tensor_ext', operations);
  8229. }
  8230. parseType(parser, dialectName) {
  8231. const typeName = parser.parseKeyword();
  8232. if (typeName === 'dispatch.tensor') {
  8233. let type = `!${dialectName}.${typeName}`;
  8234. if (parser.match('<')) {
  8235. const content = parser.skip('<', '>');
  8236. type += content;
  8237. }
  8238. return new mlir.Type(type);
  8239. }
  8240. return null;
  8241. }
  8242. };
  8243. mlir.LinalgDialect = class extends mlir.Dialect {
  8244. constructor(operations) {
  8245. super('linalg', operations);
  8246. this._namedStructuredOps = new Set([
  8247. 'linalg.matmul', 'linalg.batch_matmul', 'linalg.batch_reduce_matmul',
  8248. 'linalg.matvec', 'linalg.vecmat', 'linalg.dot', 'linalg.batch_matvec',
  8249. 'linalg.conv_1d', 'linalg.conv_1d_ncw_fcw', 'linalg.conv_1d_nwc_wcf',
  8250. 'linalg.conv_2d', 'linalg.conv_2d_nchw_fchw', 'linalg.conv_2d_nchw_fchw_q',
  8251. 'linalg.conv_2d_ngchw_fgchw', 'linalg.conv_2d_ngchw_gfchw', 'linalg.conv_2d_ngchw_gfchw_q',
  8252. 'linalg.conv_2d_nhwc_fhwc', 'linalg.conv_2d_nhwc_fhwc_q',
  8253. 'linalg.conv_2d_nhwc_hwcf', 'linalg.conv_2d_nhwc_hwcf_q',
  8254. 'linalg.conv_2d_nhwgc_gfhwc', 'linalg.conv_2d_nhwgc_gfhwc_q',
  8255. 'linalg.conv_3d', 'linalg.conv_3d_ncdhw_fcdhw', 'linalg.conv_3d_ndhwc_dhwcf', 'linalg.conv_3d_ndhwc_dhwcf_q',
  8256. 'linalg.depthwise_conv_1d_ncw_cw', 'linalg.depthwise_conv_1d_nwc_wc', 'linalg.depthwise_conv_1d_nwc_wcm',
  8257. 'linalg.depthwise_conv_2d_nchw_chw', 'linalg.depthwise_conv_2d_nhwc_hwc', 'linalg.depthwise_conv_2d_nhwc_hwc_q',
  8258. 'linalg.depthwise_conv_2d_nhwc_hwcm', 'linalg.depthwise_conv_2d_nhwc_hwcm_q',
  8259. 'linalg.depthwise_conv_3d_ncdhw_cdhw', 'linalg.depthwise_conv_3d_ndhwc_dhwc', 'linalg.depthwise_conv_3d_ndhwc_dhwcm',
  8260. 'linalg.pooling_nchw_max', 'linalg.pooling_nchw_sum',
  8261. 'linalg.pooling_nhwc_max', 'linalg.pooling_nhwc_max_unsigned', 'linalg.pooling_nhwc_min', 'linalg.pooling_nhwc_min_unsigned', 'linalg.pooling_nhwc_sum',
  8262. 'linalg.pooling_ncw_max', 'linalg.pooling_ncw_sum',
  8263. 'linalg.pooling_nwc_max', 'linalg.pooling_nwc_max_unsigned', 'linalg.pooling_nwc_min', 'linalg.pooling_nwc_min_unsigned', 'linalg.pooling_nwc_sum',
  8264. 'linalg.pooling_ndhwc_max', 'linalg.pooling_ndhwc_min', 'linalg.pooling_ndhwc_sum',
  8265. 'linalg.broadcast', 'linalg.reduce'
  8266. ]);
  8267. }
  8268. parseOperation(parser, opName, op) {
  8269. if (opName === 'linalg.generic') {
  8270. return this._parseGenericOp(parser, op);
  8271. }
  8272. if (op.name === 'linalg.init_tensor') {
  8273. if (parser.accept('[')) {
  8274. const dims = [];
  8275. while (!parser.match(']')) {
  8276. if (parser.match('%')) {
  8277. dims.push(parser.expect('%'));
  8278. } else if (parser.match('int')) {
  8279. dims.push(parser.expect('int'));
  8280. }
  8281. parser.accept(',');
  8282. }
  8283. parser.expect(']');
  8284. op.attributes.push({ name: 'static_sizes', value: dims });
  8285. }
  8286. // Reference: parseOptionalColonTypeList
  8287. parser.resolveOperands(op.results, parser.parseOptionalColonTypeList());
  8288. return true;
  8289. }
  8290. if (opName === 'linalg.fill') {
  8291. if (parser.match('id', 'ins') || parser.match('{')) {
  8292. return this._parseInsOutsOp(parser, op);
  8293. }
  8294. if (parser.accept('(')) {
  8295. op.operands = parser.parseArguments();
  8296. parser.expect(')');
  8297. }
  8298. if (parser.match('{')) {
  8299. parser.parseAttributeDict(op.attributes);
  8300. }
  8301. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  8302. if (parser.accept('->')) {
  8303. const types = parser.parseFunctionResultTypes();
  8304. parser.resolveOperands(op.results, types);
  8305. }
  8306. return true;
  8307. }
  8308. if (opName === 'linalg.conv') {
  8309. if (parser.accept('(')) {
  8310. op.operands = parser.parseArguments();
  8311. parser.expect(')');
  8312. }
  8313. if (parser.match('{')) {
  8314. parser.parseAttributeDict(op.attributes);
  8315. }
  8316. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  8317. return true;
  8318. }
  8319. if (opName === 'linalg.yield') {
  8320. op.operands = parser.parseArguments();
  8321. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  8322. return true;
  8323. }
  8324. if (opName === 'linalg.transpose') {
  8325. if (!this._parseInsOutsOp(parser, op)) {
  8326. return false;
  8327. }
  8328. if (parser.match('id', 'permutation')) {
  8329. parser.expect('id', 'permutation');
  8330. parser.expect('=');
  8331. const permutation = parser.skip('[', ']');
  8332. op.attributes.push({ name: 'permutation', value: permutation });
  8333. }
  8334. return true;
  8335. }
  8336. if (opName === 'linalg.elementwise') {
  8337. if (parser.accept('id', 'kind')) {
  8338. parser.expect('=');
  8339. const kind = parser.parseAttribute();
  8340. op.attributes.push({ name: 'kind', value: kind.value });
  8341. }
  8342. if (parser.accept('id', 'indexing_maps')) {
  8343. parser.expect('=');
  8344. const indexingMaps = parser.skip('[', ']');
  8345. op.attributes.push({ name: 'indexing_maps', value: indexingMaps });
  8346. }
  8347. return this._parseInsOutsOp(parser, op);
  8348. }
  8349. if (opName === 'linalg.contract') {
  8350. if (parser.accept('id', 'indexing_maps')) {
  8351. parser.expect('=');
  8352. const indexingMaps = parser.skip('[', ']');
  8353. op.attributes.push({ name: 'indexing_maps', value: indexingMaps });
  8354. }
  8355. return this._parseInsOutsOp(parser, op);
  8356. }
  8357. // Many linalg operations (especially named structured ops) follow the pattern:
  8358. // linalg.<op_name> <{properties}> [indexing_maps = [...]] {attributes} ins(...) outs(...) [-> type]
  8359. // These named structured ops are generated at LLVM build time from YAML.
  8360. if (this._namedStructuredOps.has(opName)) {
  8361. parser.parsePropertyDict(op.attributes);
  8362. if (parser.match('id', 'indexing_maps')) {
  8363. parser.expect('id', 'indexing_maps');
  8364. parser.expect('=');
  8365. const indexingMaps = parser.skip('[', ']');
  8366. op.attributes.push({ name: 'indexing_maps', value: indexingMaps });
  8367. }
  8368. return this._parseInsOutsOp(parser, op);
  8369. }
  8370. const opInfo = this.getOperation(opName);
  8371. if (opInfo && opInfo.metadata.assemblyFormat) {
  8372. return super.parseOperation(parser, opName, op);
  8373. }
  8374. if (parser.match('{') || parser.match('id', 'ins') || parser.match('id', 'outs')) {
  8375. return this._parseInsOutsOp(parser, op);
  8376. }
  8377. return false;
  8378. }
  8379. _parseInsOutsOp(parser, op) {
  8380. // Parse: linalg.op {attrs} ins(%0, %1 : type, type) outs(%2 : type) [-> type]
  8381. // Parse optional attribute dictionary
  8382. if (parser.match('{')) {
  8383. parser.parseAttributeDict(op.attributes);
  8384. }
  8385. // Parse 'ins' section
  8386. if (parser.accept('id', 'ins')) {
  8387. if (!parser.accept('(')) {
  8388. return false;
  8389. }
  8390. // Parse operands: %0, %1
  8391. while (parser.match('%')) {
  8392. const value = parser.expect('%');
  8393. op.operands.push({ value });
  8394. if (!parser.accept(',')) {
  8395. break;
  8396. }
  8397. }
  8398. // Parse types: : type1, type2
  8399. if (parser.accept(':')) {
  8400. let idx = 0;
  8401. const startIdx = 0;
  8402. while (!parser.match(')')) {
  8403. const type = parser.parseType();
  8404. if (startIdx + idx < op.operands.length) {
  8405. op.operands[startIdx + idx].type = type;
  8406. }
  8407. idx++;
  8408. if (!parser.accept(',')) {
  8409. break;
  8410. }
  8411. }
  8412. }
  8413. if (!parser.accept(')')) {
  8414. return false;
  8415. }
  8416. }
  8417. // Parse 'outs' section
  8418. if (parser.accept('id', 'outs')) {
  8419. if (!parser.accept('(')) {
  8420. return false;
  8421. }
  8422. const outsStart = op.operands.length;
  8423. // Parse operands: %2, %3
  8424. while (parser.match('%')) {
  8425. const value = parser.expect('%');
  8426. op.operands.push({ value });
  8427. if (!parser.accept(',')) {
  8428. break;
  8429. }
  8430. }
  8431. // Parse types: : type1, type2
  8432. if (parser.accept(':')) {
  8433. let idx = 0;
  8434. while (!parser.match(')')) {
  8435. const type = parser.parseType();
  8436. if (outsStart + idx < op.operands.length) {
  8437. op.operands[outsStart + idx].type = type;
  8438. }
  8439. idx++;
  8440. if (!parser.accept(',')) {
  8441. break;
  8442. }
  8443. }
  8444. }
  8445. if (!parser.accept(')')) {
  8446. return false;
  8447. }
  8448. }
  8449. // Parse optional dimensions/permutation attribute (for broadcast, transpose, reduce)
  8450. // Format: dimensions = [0, 1] or permutation = [1, 0]
  8451. if (parser.match('id', 'dimensions') || parser.match('id', 'permutation')) {
  8452. const attrName = parser.expect('id');
  8453. parser.expect('=');
  8454. const attrValue = parser.parseAttribute();
  8455. if (attrValue) {
  8456. op.attributes.push({ name: attrName, value: attrValue.value });
  8457. }
  8458. }
  8459. // Some linalg operations (map, reduce) have block arguments before the region
  8460. // Format: (%arg1: type, %arg2: type) { body }
  8461. const blockArguments = [];
  8462. if (parser.match('(')) {
  8463. parser.expect('(');
  8464. while (!parser.match(')')) {
  8465. const value = parser.expect('%');
  8466. parser.expect(':');
  8467. const type = parser.parseType();
  8468. blockArguments.push({ value, type });
  8469. if (!parser.accept(',')) {
  8470. break;
  8471. }
  8472. }
  8473. parser.expect(')');
  8474. }
  8475. // Some linalg operations may have a region after the signature
  8476. if (parser.match('{')) {
  8477. const region = { blocks: [] };
  8478. const block = { operations: [], arguments: blockArguments };
  8479. parser.expect('{');
  8480. while (!parser.accept('}')) {
  8481. if (parser.match('^') || (parser.match('id') && parser.getToken().value && parser.getToken().value.startsWith('^'))) {
  8482. break;
  8483. }
  8484. const operation = parser.parseOperation();
  8485. block.operations.push(operation);
  8486. }
  8487. region.blocks.push(block);
  8488. op.regions.push(region);
  8489. }
  8490. // Parse optional return type (can come after region for linalg.generic)
  8491. if (parser.accept('->') || parser.accept('id', 'to')) {
  8492. if (op.results.length > 0) {
  8493. const types = parser.parseFunctionResultTypes();
  8494. parser.resolveOperands(op.results, types);
  8495. } else {
  8496. const type = parser.parseType();
  8497. op.results.push({ type });
  8498. }
  8499. }
  8500. return true;
  8501. }
  8502. _parseGenericOp(parser, op) {
  8503. if (parser.match('{') || parser.match('#')) {
  8504. if (parser.match('#')) {
  8505. const attrRef = parser.expect('#');
  8506. op.attributes.push({ name: 'trait', value: attrRef });
  8507. } else {
  8508. parser.parseAttributeDict(op.attributes);
  8509. }
  8510. }
  8511. if (parser.accept('id', 'ins')) {
  8512. parser.expect('(');
  8513. while (parser.match('%')) {
  8514. const value = parser.expect('%');
  8515. op.operands.push({ value });
  8516. if (!parser.accept(',')) {
  8517. break;
  8518. }
  8519. }
  8520. if (parser.accept(':')) {
  8521. let idx = 0;
  8522. while (!parser.match(')')) {
  8523. const type = parser.parseType();
  8524. if (idx < op.operands.length) {
  8525. op.operands[idx].type = type;
  8526. }
  8527. idx++;
  8528. if (!parser.accept(',')) {
  8529. break;
  8530. }
  8531. }
  8532. }
  8533. parser.expect(')');
  8534. }
  8535. if (parser.accept('id', 'outs')) {
  8536. parser.expect('(');
  8537. const outsStart = op.operands.length;
  8538. while (parser.match('%')) {
  8539. const value = parser.expect('%');
  8540. op.operands.push({ value });
  8541. if (!parser.accept(',')) {
  8542. break;
  8543. }
  8544. }
  8545. if (parser.accept(':')) {
  8546. let idx = 0;
  8547. while (!parser.match(')')) {
  8548. const type = parser.parseType();
  8549. if (outsStart + idx < op.operands.length) {
  8550. op.operands[outsStart + idx].type = type;
  8551. }
  8552. idx++;
  8553. if (!parser.accept(',')) {
  8554. break;
  8555. }
  8556. }
  8557. }
  8558. parser.expect(')');
  8559. }
  8560. if (parser.accept('id', 'attrs')) {
  8561. parser.expect('=');
  8562. parser.parseAttributeDict(op.attributes);
  8563. }
  8564. if (parser.match('{')) {
  8565. const region = {};
  8566. parser.parseRegion(region);
  8567. op.regions.push(region);
  8568. }
  8569. if (parser.accept('->')) {
  8570. const hasParens = parser.match('(');
  8571. const types = hasParens ? parser.parseTypeListParens() : parser.parseFunctionResultTypes();
  8572. parser.resolveOperands(op.results, types);
  8573. }
  8574. return true;
  8575. }
  8576. };
  8577. mlir.ONNXDialect = class extends mlir.Dialect {
  8578. constructor(operations) {
  8579. super('onnx', operations);
  8580. }
  8581. parseOperation(parser, opName, op) {
  8582. // onnx.Constant has custom assembly format: dense<...> : type
  8583. // Similar to stablehlo.constant
  8584. if (opName === 'onnx.Constant') {
  8585. // Parse attribute (e.g., dense<"0x...">, dense<[1, 2, 3]>, etc.)
  8586. const value = parser.parseAttribute();
  8587. if (value) {
  8588. op.attributes.push({ name: 'value', value: value.value });
  8589. }
  8590. // Parse optional : type
  8591. for (const type of parser.parseOptionalColonTypeList()) {
  8592. op.results.push({ type: type.toString() });
  8593. }
  8594. return true;
  8595. }
  8596. return super.parseOperation(parser, opName, op);
  8597. }
  8598. };
  8599. mlir.KrnlDialect = class extends mlir.Dialect {
  8600. constructor(operations) {
  8601. super('krnl', operations);
  8602. }
  8603. parseOperation(parser, opName, op) {
  8604. if (opName === 'krnl.define_loops') {
  8605. if (parser.match('int')) {
  8606. const count = parser.expect('int');
  8607. op.attributes.push({ name: 'num_loops', value: count });
  8608. }
  8609. return true;
  8610. }
  8611. if (opName === 'krnl.get_linear_offset_index') {
  8612. const memref = parser.parseAttribute();
  8613. op.operands = [memref];
  8614. if (parser.accept('id', 'at')) {
  8615. parser.expect('[');
  8616. while (!parser.match(']')) {
  8617. const index = parser.parseAttribute();
  8618. op.operands.push(index);
  8619. if (!parser.match(']')) {
  8620. parser.accept(',');
  8621. }
  8622. }
  8623. parser.expect(']');
  8624. }
  8625. if (parser.accept(':')) {
  8626. parser.parseType();
  8627. }
  8628. return true;
  8629. }
  8630. if (opName === 'krnl.iterate') {
  8631. op.operands = parser.parseArguments();
  8632. if (parser.accept('id', 'with')) {
  8633. parser.expect('(');
  8634. const numOptimizedLoops = op.operands.length;
  8635. while (!parser.match(')')) {
  8636. parser.expect('%');
  8637. parser.expect('->');
  8638. parser.expect('%');
  8639. parser.expect('=');
  8640. parser.accept('id', 'max');
  8641. if (parser.match('id', 'affine_map') || parser.match('id', 'affine_set')) {
  8642. parser.parseAttribute();
  8643. if (parser.match('(')) {
  8644. parser.skip('(', ')');
  8645. }
  8646. if (parser.match('[')) {
  8647. parser.skip('[', ']');
  8648. }
  8649. } else {
  8650. parser.parseAttribute();
  8651. }
  8652. parser.expect('id', 'to');
  8653. parser.accept('id', 'min');
  8654. if (parser.match('id', 'affine_map') || parser.match('id', 'affine_set')) {
  8655. parser.parseAttribute();
  8656. if (parser.match('(')) {
  8657. parser.skip('(', ')');
  8658. }
  8659. if (parser.match('[')) {
  8660. parser.skip('[', ']');
  8661. }
  8662. } else {
  8663. parser.parseAttribute();
  8664. }
  8665. if (!parser.match(')')) {
  8666. parser.accept(',');
  8667. }
  8668. }
  8669. parser.expect(')');
  8670. op.attributes.push({ name: 'num_optimized_loops', value: numOptimizedLoops });
  8671. }
  8672. if (parser.accept('id', 'iter_args')) {
  8673. parser.expect('(');
  8674. while (!parser.match(')')) {
  8675. parser.expect('%');
  8676. parser.expect('=');
  8677. parser.parseAttribute();
  8678. if (!parser.match(')')) {
  8679. parser.accept(',');
  8680. }
  8681. }
  8682. parser.expect(')');
  8683. if (parser.accept('->')) {
  8684. const types = parser.parseFunctionResultTypes();
  8685. parser.resolveOperands(op.results, types);
  8686. }
  8687. }
  8688. if (parser.match('{')) {
  8689. const region = {};
  8690. parser.parseRegion(region);
  8691. op.regions = [region];
  8692. }
  8693. return true;
  8694. }
  8695. return super.parseOperation(parser, opName, op);
  8696. }
  8697. };
  8698. mlir.MhloDialect = class extends mlir.HLODialect {
  8699. constructor(operations) {
  8700. super('mhlo', operations);
  8701. }
  8702. parseOperation(parser, opName, op) {
  8703. const opInfo = this.getOperation(opName);
  8704. if (opInfo && opInfo.metadata.parser && opInfo.metadata.parser.includes('parseOneResultSameOperandTypeOp')) {
  8705. return this.parseOneResultSameOperandTypeOp(parser, op);
  8706. }
  8707. if (opName === 'mhlo.constant') {
  8708. if (parser.accept('(') && parser.accept(')')) {
  8709. if (parser.match('{')) {
  8710. parser.parseAttributeDict(op.attributes);
  8711. }
  8712. // Reference: parseOptionalColonTypeList for operands
  8713. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  8714. // Reference: parseOptionalArrowTypeList for results
  8715. parser.resolveOperands(op.results, parser.parseOptionalArrowTypeList());
  8716. } else {
  8717. if (parser.match('{')) {
  8718. parser.parseAttributeDict(op.attributes);
  8719. }
  8720. const value = parser.parseAttribute();
  8721. if (value) {
  8722. op.attributes.push({ name: 'value', value: value.value });
  8723. }
  8724. // Parse result type: : tensor<...>
  8725. // Reference: parseOptionalColonTypeList
  8726. parser.resolveOperands(op.results, parser.parseOptionalColonTypeList());
  8727. }
  8728. return true;
  8729. }
  8730. if (opName === 'mhlo.compare') {
  8731. // Use modern assemblyFormat if available, but only if this is modern syntax
  8732. // Old format has 'attributes' keyword, new format has attr-dict directly
  8733. if (opInfo && opInfo.metadata.assemblyFormat && !parser.match('id', 'attributes')) {
  8734. return super.parseOperation(parser, opName, op);
  8735. }
  8736. // Parse: comparison_direction, lhs, rhs [, compare_type] : (type, type) -> type
  8737. // Legacy parser for old mhlo.compare without assembly format
  8738. if (parser.match('id')) {
  8739. const comparisonDirection = parser.expect('id');
  8740. op.attributes.push({ name: 'comparison_direction', value: comparisonDirection });
  8741. parser.expect(',');
  8742. op.operands = parser.parseArguments();
  8743. // Check for optional compare_type
  8744. if (parser.accept(',') && parser.match('id')) {
  8745. const compareType = parser.expect('id');
  8746. op.attributes.push({ name: 'compare_type', value: compareType });
  8747. }
  8748. parser.parseOptionalAttrDict(op.attributes);
  8749. if (parser.accept(':')) {
  8750. // Reference: Parse FunctionType (type, type) -> type or just type list
  8751. const type = parser.parseType();
  8752. if (type instanceof mlir.FunctionType) {
  8753. parser.resolveOperands(op.operands, type.inputs);
  8754. parser.resolveOperands(op.results, type.results);
  8755. } else {
  8756. // Single type applied to all operands
  8757. for (const operand of op.operands) {
  8758. if (!operand.type) {
  8759. operand.type = type;
  8760. }
  8761. }
  8762. }
  8763. }
  8764. return true;
  8765. }
  8766. }
  8767. if (opName === 'mhlo.reduce') {
  8768. return this._parseReduceOp(parser, op);
  8769. }
  8770. if (opName === 'mhlo.while') {
  8771. // mhlo.while always uses parenthesized form with named arguments
  8772. parser.expect('(');
  8773. while (!parser.match(')')) {
  8774. const arg = {};
  8775. arg.value = parser.expect('%');
  8776. if (parser.accept('=')) {
  8777. arg.name = arg.value;
  8778. arg.value = parser.expect('%');
  8779. }
  8780. op.operands.push(arg);
  8781. parser.accept(',');
  8782. }
  8783. parser.expect(')');
  8784. if (parser.accept(':')) {
  8785. let index = 0;
  8786. while (!parser.match('id', 'cond') && !parser.match('id', 'attributes') && index < op.operands.length * 2) {
  8787. const type = parser.parseType();
  8788. if (index < op.operands.length) {
  8789. op.operands[index].type = type;
  8790. }
  8791. if (index < op.results.length) {
  8792. op.results[index].type = type;
  8793. }
  8794. index++;
  8795. if (!parser.accept(',')) {
  8796. break;
  8797. }
  8798. }
  8799. }
  8800. if (parser.accept('id', 'attributes')) {
  8801. if (parser.match('{')) {
  8802. parser.parseAttributeDict(op.attributes);
  8803. }
  8804. }
  8805. if (parser.accept('id', 'cond')) {
  8806. const condRegion = {};
  8807. parser.parseRegion(condRegion);
  8808. op.regions.push(condRegion);
  8809. }
  8810. if (parser.accept('id', 'do')) {
  8811. const bodyRegion = {};
  8812. parser.parseRegion(bodyRegion);
  8813. op.regions.push(bodyRegion);
  8814. }
  8815. return true;
  8816. }
  8817. return super.parseOperation(parser, opName, op);
  8818. }
  8819. _parseReduceOp(parser, op) {
  8820. const operands = [];
  8821. const initOperands = [];
  8822. while (true) {
  8823. if (!parser.accept('(')) {
  8824. break;
  8825. }
  8826. const operand = { value: parser.expect('%') };
  8827. parser.expect('id', 'init');
  8828. parser.expect(':');
  8829. const initOperand = { value: parser.expect('%') };
  8830. parser.expect(')');
  8831. operands.push(operand);
  8832. initOperands.push(initOperand);
  8833. parser.accept(',');
  8834. }
  8835. op.operands = operands.concat(initOperands);
  8836. // Check if compact syntax: "applies <inner-op>"
  8837. if (parser.accept('id', 'applies')) {
  8838. // Parse the inner operation name (e.g., "mhlo.add")
  8839. const innerOpName = parser.parseCustomOperationName();
  8840. // Parse "across dimensions = [...]"
  8841. parser.expect('id', 'across');
  8842. parser.expect('id', 'dimensions');
  8843. parser.expect('=');
  8844. parser.expect('[');
  8845. const dimensions = [];
  8846. while (!parser.match(']')) {
  8847. if (parser.match('int')) {
  8848. dimensions.push(parser.expect('int'));
  8849. } else {
  8850. throw new mlir.Error(`Expected integer dimension in reduce operation ${parser.location()}`);
  8851. }
  8852. if (!parser.accept(',') && !parser.match(']')) {
  8853. throw new mlir.Error(`Expected ',' or ']' in dimensions list ${parser.location()}`);
  8854. }
  8855. }
  8856. parser.expect(']');
  8857. op.attributes.push({ name: 'dimensions', value: dimensions });
  8858. // Parse optional attribute dict
  8859. parser.parseOptionalAttrDict(op.attributes);
  8860. // Parse function type: (input types) -> result types
  8861. // Reference: Use FunctionType pattern
  8862. if (parser.accept(':')) {
  8863. const type = parser.parseType();
  8864. if (type instanceof mlir.FunctionType) {
  8865. parser.resolveOperands(op.operands, type.inputs);
  8866. parser.resolveOperands(op.results, type.results);
  8867. } else {
  8868. // Single type or type list for operands
  8869. if (Array.isArray(type)) {
  8870. parser.resolveOperands(op.operands, type);
  8871. } else {
  8872. for (const operand of op.operands) {
  8873. if (!operand.type) {
  8874. operand.type = type;
  8875. }
  8876. }
  8877. }
  8878. // Check for arrow followed by result types
  8879. if (parser.accept('->')) {
  8880. const resultTypes = parser.parseFunctionResultTypes();
  8881. parser.resolveOperands(op.results, resultTypes);
  8882. }
  8883. }
  8884. }
  8885. // Create a region with the inner operation
  8886. const region = { blocks: [] };
  8887. const block = { operations: [], arguments: [] };
  8888. // Get element type from first input
  8889. let elementType = null;
  8890. if (op.operands.length > 0 && op.operands[0].type) {
  8891. const tensorMatch = op.operands[0].type.toString().match(/tensor<.*?x([^>]+)>/);
  8892. if (tensorMatch) {
  8893. [, elementType] = tensorMatch;
  8894. } else {
  8895. const scalarMatch = op.operands[0].type.toString().match(/tensor<([^>]+)>/);
  8896. if (scalarMatch) {
  8897. [, elementType] = scalarMatch;
  8898. }
  8899. }
  8900. }
  8901. // Add block arguments
  8902. block.arguments.push({ value: '%lhs', type: elementType ? `tensor<${elementType}>` : null });
  8903. block.arguments.push({ value: '%rhs', type: elementType ? `tensor<${elementType}>` : null });
  8904. // Add the inner operation
  8905. const innerOp = {
  8906. name: innerOpName,
  8907. operands: [{ value: '%lhs' }, { value: '%rhs' }],
  8908. results: [{ value: '%0', type: elementType ? `tensor<${elementType}>` : null }],
  8909. attributes: [],
  8910. regions: []
  8911. };
  8912. block.operations.push(innerOp);
  8913. // Add return operation
  8914. const returnOp = {
  8915. name: 'mhlo.return',
  8916. operands: [{ value: '%0' }],
  8917. results: [],
  8918. attributes: [],
  8919. regions: []
  8920. };
  8921. block.operations.push(returnOp);
  8922. region.blocks.push(block);
  8923. op.regions.push(region);
  8924. return true;
  8925. }
  8926. // Non-compact syntax: parse "across dimensions = [...] : type reducer"
  8927. parser.expect('id', 'across');
  8928. parser.expect('id', 'dimensions');
  8929. parser.expect('=');
  8930. parser.expect('[');
  8931. const dimensions = [];
  8932. while (!parser.match(']')) {
  8933. if (parser.match('int')) {
  8934. dimensions.push(parser.expect('int'));
  8935. } else {
  8936. throw new mlir.Error(`Expected integer dimension in reduce operation ${parser.location()}`);
  8937. }
  8938. if (!parser.accept(',') && !parser.match(']')) {
  8939. throw new mlir.Error(`Expected ',' or ']' in dimensions list ${parser.location()}`);
  8940. }
  8941. }
  8942. parser.expect(']');
  8943. op.attributes.push({ name: 'dimensions', value: dimensions });
  8944. parser.parseOptionalAttrDict(op.attributes);
  8945. if (parser.accept(':')) {
  8946. const fnType = parser.parseFunctionType();
  8947. parser.resolveOperands(op.operands, fnType.inputs);
  8948. parser.resolveOperands(op.results, fnType.results);
  8949. }
  8950. parser.expect('id', 'reducer');
  8951. const reducerArgs = [];
  8952. while (parser.accept('(')) {
  8953. const arg1 = { value: parser.expect('%') };
  8954. parser.expect(':');
  8955. arg1.type = parser.parseType();
  8956. parser.expect(',');
  8957. const arg2 = { value: parser.expect('%') };
  8958. parser.expect(':');
  8959. arg2.type = parser.parseType();
  8960. parser.expect(')');
  8961. reducerArgs.push(arg1, arg2);
  8962. }
  8963. const region = {};
  8964. region.blocks = [];
  8965. const block = { operations: [], arguments: reducerArgs };
  8966. parser.expect('{');
  8967. while (!parser.accept('}')) {
  8968. const innerOp = parser.parseOperation();
  8969. block.operations.push(innerOp);
  8970. }
  8971. region.blocks.push(block);
  8972. op.regions.push(region);
  8973. return true;
  8974. }
  8975. parseOneResultSameOperandTypeOp(parser, op) {
  8976. op.operands = parser.parseArguments();
  8977. parser.parseOptionalAttrDict(op.attributes);
  8978. if (parser.accept(':')) {
  8979. const type = parser.parseType();
  8980. for (const operand of op.operands) {
  8981. operand.type = type;
  8982. }
  8983. if (op.results.length > 0) {
  8984. op.results[0].type = type;
  8985. }
  8986. }
  8987. return true;
  8988. }
  8989. };
  8990. mlir.QuantDialect = class extends mlir.Dialect {
  8991. constructor(operations) {
  8992. super('quant', operations);
  8993. }
  8994. parseType(parser, dialectName) {
  8995. const typeName = parser.parseKeyword();
  8996. if (typeName === 'uniform' || typeName === 'calibrated' || typeName === 'any') {
  8997. let type = `!${dialectName}.${typeName}`;
  8998. if (parser.match('<')) {
  8999. const content = parser.skip('<', '>');
  9000. type += content;
  9001. }
  9002. return new mlir.Type(type);
  9003. }
  9004. return null;
  9005. }
  9006. };
  9007. mlir.TosaDialect = class extends mlir.Dialect {
  9008. constructor(operations) {
  9009. super('tosa', operations);
  9010. this._customOps = new Set([
  9011. 'tosa.apply_scale', 'tosa.argmax', 'tosa.cast_from_block_scaled',
  9012. 'tosa.cast_to_block_scaled', 'tosa.clamp', 'tosa.max_pool2d',
  9013. 'tosa.maximum', 'tosa.minimum', 'tosa.reduce_max', 'tosa.reduce_min',
  9014. 'tosa.rescale', 'tosa.resize', 'tosa.matmul_t_block_scaled'
  9015. ]);
  9016. this._regionOps = new Set(['tosa.cond_if', 'tosa.while_loop']);
  9017. }
  9018. parseType(parser, dialectName) {
  9019. const typeName = parser.parseKeyword();
  9020. if (typeName === 'shape') {
  9021. let type = `!${dialectName}.${typeName}`;
  9022. if (parser.match('<')) {
  9023. const content = parser.skip('<', '>');
  9024. type += content;
  9025. }
  9026. return new mlir.Type(type);
  9027. }
  9028. return null;
  9029. }
  9030. parseOperation(parser, opName, op) {
  9031. if (opName === 'tosa.variable' && !this.hasAssemblyFormat(opName)) {
  9032. parser.parseSymbolName('sym_name', op.attributes);
  9033. if (parser.accept('=')) {
  9034. const initialValue = parser.parseAttribute();
  9035. op.attributes.push({ name: 'initial_value', value: initialValue });
  9036. }
  9037. if (parser.accept(':')) {
  9038. const type = parser.parseType();
  9039. op.attributes.push({ name: 'type', value: type });
  9040. }
  9041. return true;
  9042. }
  9043. if (this._regionOps.has(opName) && this.hasCustomAssemblyFormat(opName) && !this.hasAssemblyFormat(opName)) {
  9044. if (parser.match('%')) {
  9045. const cond = parser.expect('%');
  9046. op.operands.push({ value: cond });
  9047. }
  9048. if (parser.accept('(')) {
  9049. while (!parser.match(')')) {
  9050. if (parser.match('%')) {
  9051. const blockArg = parser.expect('%');
  9052. parser.expect('=');
  9053. const inputVal = parser.expect('%');
  9054. op.operands.push({ blockArg, value: inputVal });
  9055. }
  9056. if (!parser.accept(',')) {
  9057. break;
  9058. }
  9059. }
  9060. parser.expect(')');
  9061. }
  9062. if (parser.accept(':')) {
  9063. const type = parser.parseType();
  9064. if (type instanceof mlir.FunctionType) {
  9065. parser.resolveOperands(op.operands, type.inputs);
  9066. parser.resolveOperands(op.results, type.results);
  9067. } else {
  9068. if (op.operands.length > 0 && !op.operands[0].type) {
  9069. op.operands[0].type = type;
  9070. }
  9071. if (parser.accept('->')) {
  9072. const resultTypes = parser.parseFunctionResultTypes();
  9073. parser.resolveOperands(op.results, resultTypes);
  9074. }
  9075. }
  9076. }
  9077. if (parser.match('{')) {
  9078. const region = {};
  9079. parser.parseRegion(region);
  9080. op.regions.push(region);
  9081. }
  9082. if (parser.accept('id', 'else') || parser.accept('id', 'do')) {
  9083. if (parser.match('{')) {
  9084. const secondRegion = {};
  9085. parser.parseRegion(secondRegion);
  9086. op.regions.push(secondRegion);
  9087. }
  9088. }
  9089. return true;
  9090. }
  9091. if (this._customOps.has(opName) && this.hasCustomAssemblyFormat(opName) && !this.hasAssemblyFormat(opName)) {
  9092. op.operands = parser.parseArguments();
  9093. if (parser.match('{')) {
  9094. parser.parseAttributeDict(op.attributes);
  9095. }
  9096. if (parser.accept(':')) {
  9097. const type = parser.parseType();
  9098. if (type instanceof mlir.FunctionType) {
  9099. parser.resolveOperands(op.operands, type.inputs);
  9100. parser.resolveOperands(op.results, type.results);
  9101. } else {
  9102. for (const operand of op.operands) {
  9103. if (!operand.type) {
  9104. operand.type = type;
  9105. }
  9106. }
  9107. if (parser.accept('->')) {
  9108. const resultTypes = parser.parseFunctionResultTypes();
  9109. parser.resolveOperands(op.results, resultTypes);
  9110. }
  9111. }
  9112. }
  9113. return true;
  9114. }
  9115. return super.parseOperation(parser, opName, op);
  9116. }
  9117. };
  9118. mlir.IRDLDialect = class extends mlir.Dialect {
  9119. constructor(operations) {
  9120. super('irdl', operations);
  9121. this.registerCustomDirective('SingleBlockRegion', this._parseSingleBlockRegion.bind(this));
  9122. this.registerCustomDirective('NamedValueList', this._parseNamedValueList.bind(this));
  9123. this.registerCustomDirective('NamedValueListWithVariadicity', this._parseNamedValueListWithVariadicity.bind(this));
  9124. }
  9125. parseOperation(parser, opName, op) {
  9126. // Only use custom parsing for operations that don't have assemblyFormat
  9127. // Operations with assemblyFormat should be handled by the base class
  9128. if ((opName === 'irdl.operands' || opName === 'irdl.results' ||
  9129. opName === 'irdl.parameters' || opName === 'irdl.attributes' ||
  9130. opName === 'irdl.regions') && !this.hasAssemblyFormat(opName)) {
  9131. if (parser.accept('(')) {
  9132. while (!parser.accept(')')) {
  9133. if (parser.match('id') || parser.match('string')) {
  9134. const paramName = parser.expect();
  9135. parser.expect(':');
  9136. const paramValue = parser.expect(); // Read the SSA value like %tensor
  9137. op.attributes.push({ name: paramName, value: paramValue });
  9138. }
  9139. parser.accept(',');
  9140. }
  9141. }
  9142. op.loc = parser.parseLocation();
  9143. return true;
  9144. }
  9145. return super.parseOperation(parser, opName, op);
  9146. }
  9147. _parseSingleBlockRegion(parser, op, /* args */) {
  9148. if (parser.match('{')) {
  9149. const region = {};
  9150. parser.parseRegion(region);
  9151. op.regions.push(region);
  9152. }
  9153. }
  9154. _parseNamedValueList(parser, op, args) {
  9155. const argValues = [];
  9156. const nameValues = [];
  9157. const parseOne = () => {
  9158. // Parse name
  9159. const name = parser.expect();
  9160. nameValues.push(name);
  9161. // Parse ':'
  9162. parser.expect(':');
  9163. // Parse value (SSA value like %0)
  9164. const value = parser.expect();
  9165. argValues.push(value);
  9166. return value;
  9167. };
  9168. parser.parseCommaSeparatedList('paren', parseOne);
  9169. if (args && args.length >= 2) {
  9170. const argsAttrName = args[0].replace(/^\$/, '');
  9171. const namesAttrName = args[1].replace(/^\$/, '');
  9172. op.attributes.push({ name: argsAttrName, value: argValues });
  9173. op.attributes.push({ name: namesAttrName, value: nameValues });
  9174. }
  9175. }
  9176. _parseNamedValueListWithVariadicity(parser, op, args) {
  9177. const argValues = [];
  9178. const nameValues = [];
  9179. const variadicityValues = [];
  9180. const parseOne = () => {
  9181. let variadicity = null;
  9182. if (parser.match('id')) {
  9183. const peekValue = parser.getToken().value;
  9184. if (peekValue === 'single' || peekValue === 'optional' || peekValue === 'variadic') {
  9185. variadicity = parser.expect('id');
  9186. }
  9187. }
  9188. const name = parser.expect();
  9189. nameValues.push(name);
  9190. parser.expect(':');
  9191. const value = parser.expect();
  9192. argValues.push(value);
  9193. variadicityValues.push(variadicity || 'single');
  9194. return value;
  9195. };
  9196. parser.parseCommaSeparatedList('paren', parseOne);
  9197. if (args && args.length >= 2) {
  9198. const argsAttrName = args[0].replace(/^\$/, '');
  9199. const namesAttrName = args[1].replace(/^\$/, '');
  9200. op.attributes.push({ name: argsAttrName, value: argValues });
  9201. op.attributes.push({ name: namesAttrName, value: nameValues });
  9202. if (args.length >= 3) {
  9203. const variadicityAttrName = args[2].replace(/^\$/, '');
  9204. op.attributes.push({ name: variadicityAttrName, value: variadicityValues });
  9205. }
  9206. }
  9207. }
  9208. };
  9209. mlir.XeGPUDialect = class extends mlir.Dialect {
  9210. constructor(operations) {
  9211. super('xegpu', operations);
  9212. this.registerCustomDirective('OptionalDynamicIndexList', this._parseOptionalDynamicIndexList.bind(this));
  9213. }
  9214. _parseOptionalDynamicIndexList(parser, op, args) {
  9215. const indices = [];
  9216. const dynamicValues = [];
  9217. if (parser.accept('[')) {
  9218. while (!parser.match(']')) {
  9219. if (parser.match('int') || parser.match('number')) {
  9220. indices.push(parseInt(parser.expect(), 10));
  9221. } else if (parser.match('%')) {
  9222. const value = parser.expect('%');
  9223. dynamicValues.push(value);
  9224. indices.push(-9223372036854775808);
  9225. } else {
  9226. break;
  9227. }
  9228. parser.accept(',');
  9229. }
  9230. parser.accept(']');
  9231. if (args && args.length >= 2) {
  9232. const dynamicAttrName = args[0].replace(/^\$/, '');
  9233. const staticAttrName = args[1].replace(/^\$/, '');
  9234. if (dynamicValues.length > 0) {
  9235. op.attributes.push({ name: dynamicAttrName, value: dynamicValues });
  9236. }
  9237. if (indices.length > 0) {
  9238. op.attributes.push({ name: staticAttrName, value: indices });
  9239. }
  9240. }
  9241. }
  9242. }
  9243. };
  9244. mlir.ShardDialect = class extends mlir.Dialect {
  9245. constructor(operations) {
  9246. super('shard', operations);
  9247. this.registerCustomDirective('DimensionList', this._parseDimensionList.bind(this));
  9248. }
  9249. _parseDimensionList(parser, op, args) {
  9250. const dimensions = [];
  9251. while (true) {
  9252. if (parser.match('?')) {
  9253. parser.expect('?');
  9254. dimensions.push(-1);
  9255. } else if (parser.match('int')) {
  9256. dimensions.push(parser.parseInteger());
  9257. } else {
  9258. break;
  9259. }
  9260. if (parser.match('id')) {
  9261. const token = parser.getToken().value;
  9262. if (token === 'x') {
  9263. parser.expect('id');
  9264. continue;
  9265. } else if (token.startsWith('x')) {
  9266. parser.expect('id');
  9267. const remaining = token.substring(1);
  9268. const parts = remaining.split('x');
  9269. for (const part of parts) {
  9270. if (part === '?') {
  9271. dimensions.push(-1);
  9272. } else if (part !== '') {
  9273. const num = parseInt(part, 10);
  9274. if (!isNaN(num)) {
  9275. dimensions.push(num);
  9276. }
  9277. }
  9278. }
  9279. break;
  9280. }
  9281. break;
  9282. }
  9283. if (!parser.match('id') && !parser.match('?')) {
  9284. break;
  9285. }
  9286. }
  9287. if (args && args.length > 0) {
  9288. const attrName = args[0].replace(/^\$/, '');
  9289. op.attributes.push({ name: attrName, value: dimensions });
  9290. }
  9291. }
  9292. };
  9293. mlir.SPIRVDialect = class extends mlir.Dialect {
  9294. constructor(operations) {
  9295. super('spirv', operations);
  9296. this.typesWithOptionalParams = new Set(['sampler', 'sampled_image', 'matrix', 'image', 'rtarray', 'ptr', 'array', 'struct', 'coopmatrix']);
  9297. this.registerCustomDirective('ImageOperands', this._parseImageOperands.bind(this));
  9298. this.registerCustomAttribute('SPIRV_ScopeAttr', this._parseEnumFlagsAngleBracketPipe.bind(this));
  9299. this.registerCustomAttribute('SPIRV_MemorySemanticsAttr', this._parseEnumFlagsAngleBracketPipe.bind(this));
  9300. this.registerCustomAttribute('SPIRV_MemoryAccessAttr', this._parseEnumFlagsAngleBracketPipe.bind(this));
  9301. this.registerCustomAttribute('SPIRV_GroupOperationAttr', this._parseEnumFlagsAngleBracketPipe.bind(this));
  9302. this.registerCustomAttribute('SPIRV_KHR_CooperativeMatrixLayoutAttr', this._parseEnumFlagsAngleBracketPipe.bind(this));
  9303. this.registerCustomAttribute('SPIRV_KHR_CooperativeMatrixOperandsAttr', this._parseEnumFlagsAngleBracketPipe.bind(this));
  9304. }
  9305. _parseImageOperands(parser /*, op, args */) {
  9306. if (parser.match('[')) {
  9307. parser.skip('[', ']');
  9308. }
  9309. }
  9310. parseType(parser, dialectName) {
  9311. let typeName = parser.parseKeyword();
  9312. if (!typeName) {
  9313. return null;
  9314. }
  9315. // Handle sub-dialect types like arm.tensor, KHR.CooperativeMatrix, etc.
  9316. while (parser.accept('.')) {
  9317. const subType = parser.parseKeyword();
  9318. if (subType) {
  9319. typeName += `.${subType}`;
  9320. } else {
  9321. break;
  9322. }
  9323. }
  9324. // Build the full type string
  9325. let type = `!${dialectName}.${typeName}`;
  9326. if (parser.match('<')) {
  9327. const content = parser.skip('<', '>');
  9328. type += content;
  9329. }
  9330. return new mlir.Type(type);
  9331. }
  9332. parseOperation(parser, opName, op) {
  9333. // Operations with '->' in their assembly format should use assembly format parsing
  9334. const arrowFormatOps = new Set([
  9335. 'spirv.GL.Distance', 'spirv.GL.FMix', 'spirv.GL.FrexpStruct', 'spirv.GL.Ldexp',
  9336. 'spirv.GL.Length', 'spirv.GL.PackHalf2x16', 'spirv.GL.UnpackHalf2x16',
  9337. 'spirv.GLSL.Distance', 'spirv.GLSL.FMix', 'spirv.GLSL.FrexpStruct', 'spirv.GLSL.Ldexp',
  9338. 'spirv.GLSL.Length', 'spirv.GLSL.PackHalf2x16', 'spirv.GLSL.UnpackHalf2x16',
  9339. 'spv.GL.Distance', 'spv.GL.FMix', 'spv.GL.FrexpStruct', 'spv.GL.Ldexp',
  9340. 'spv.GL.Length', 'spv.GL.PackHalf2x16', 'spv.GL.UnpackHalf2x16',
  9341. 'spv.GLSL.Distance', 'spv.GLSL.FMix', 'spv.GLSL.FrexpStruct', 'spv.GLSL.Ldexp',
  9342. 'spv.GLSL.Length', 'spv.GLSL.PackHalf2x16', 'spv.GLSL.UnpackHalf2x16'
  9343. ]);
  9344. if ((opName.startsWith('spirv.GLSL.') || opName.startsWith('spv.GLSL.') || opName.startsWith('spirv.GL.') || opName.startsWith('spv.GL.')) && !arrowFormatOps.has(opName)) {
  9345. while (!parser.match(':')) {
  9346. const operand = parser.parseAttribute();
  9347. op.operands.push(operand);
  9348. if (!parser.accept(',')) {
  9349. break;
  9350. }
  9351. }
  9352. if (parser.accept(':')) {
  9353. const type = parser.parseType();
  9354. op.results.push({ type });
  9355. }
  9356. return true;
  9357. }
  9358. if (opName === 'spirv.Constant' || opName === 'spv.Constant') {
  9359. const value = parser.parseAttribute();
  9360. if (parser.accept(':')) {
  9361. const valueType = parser.parseType();
  9362. op.attributes.push({ name: 'value', value: { ...value, valueType } });
  9363. } else {
  9364. op.attributes.push({ name: 'value', value });
  9365. }
  9366. if (parser.accept(':')) {
  9367. const type = parser.parseType();
  9368. op.results.push({ type });
  9369. }
  9370. return true;
  9371. }
  9372. if (opName === 'spirv.Load' || opName === 'spv.Load') {
  9373. const storageClass = parser.expect('string');
  9374. op.attributes.push({ name: 'storage_class', value: storageClass });
  9375. const ptr = parser.parseAttribute();
  9376. op.operands.push(ptr);
  9377. if (parser.accept('[')) {
  9378. const memoryAccess = [];
  9379. while (!parser.match(']')) {
  9380. if (parser.match('string')) {
  9381. memoryAccess.push(parser.expect('string'));
  9382. } else if (parser.match('int')) {
  9383. memoryAccess.push(parser.expect('int'));
  9384. } else {
  9385. break;
  9386. }
  9387. parser.accept(',');
  9388. }
  9389. parser.expect(']');
  9390. if (memoryAccess.length > 0) {
  9391. op.attributes.push({ name: 'memory_access', value: memoryAccess.join(', ') });
  9392. }
  9393. }
  9394. if (parser.accept(':')) {
  9395. const type = parser.parseType();
  9396. op.results.push({ type });
  9397. }
  9398. return true;
  9399. }
  9400. if (opName === 'spirv.CompositeExtract' || opName === 'spv.CompositeExtract') {
  9401. const composite = parser.parseAttribute();
  9402. op.operands.push(composite);
  9403. if (parser.accept('[')) {
  9404. const indices = [];
  9405. while (!parser.match(']')) {
  9406. if (parser.match('int')) {
  9407. indices.push(parser.parseInteger());
  9408. }
  9409. if (parser.accept(':')) {
  9410. parser.parseType();
  9411. }
  9412. if (!parser.accept(',')) {
  9413. break;
  9414. }
  9415. }
  9416. parser.expect(']');
  9417. op.attributes.push({ name: 'indices', value: indices });
  9418. }
  9419. if (parser.accept(':')) {
  9420. const type = parser.parseType();
  9421. op.results.push({ type });
  9422. }
  9423. return true;
  9424. }
  9425. // Handle AccessChain with old syntax (no -> for result type)
  9426. // Format: base_ptr[indices] : base_type, index_types (without -> result_type)
  9427. if (opName === 'spirv.AccessChain' || opName === 'spv.AccessChain') {
  9428. this._operations.get('spirv.AccessChain').hasParseOperation = false; // compatibility
  9429. const basePtr = parser.parseAttribute();
  9430. op.operands.push(basePtr);
  9431. if (parser.accept('[')) {
  9432. while (!parser.match(']')) {
  9433. const index = parser.parseAttribute();
  9434. op.operands.push(index);
  9435. if (!parser.accept(',')) {
  9436. break;
  9437. }
  9438. }
  9439. parser.expect(']');
  9440. }
  9441. parser.parseOptionalAttrDict(op.attributes);
  9442. if (parser.accept(':')) {
  9443. // Parse base pointer type
  9444. const basePtrType = parser.parseType();
  9445. op.operands[0].type = basePtrType;
  9446. // Parse index types
  9447. let idx = 1;
  9448. while (parser.accept(',') && idx < op.operands.length) {
  9449. const indexType = parser.parseType();
  9450. if (op.operands[idx]) {
  9451. op.operands[idx].type = indexType;
  9452. }
  9453. idx++;
  9454. }
  9455. // Check for optional -> result_type (newer syntax)
  9456. if (parser.accept('->')) {
  9457. const resultType = parser.parseType();
  9458. op.results.push({ type: resultType });
  9459. }
  9460. }
  9461. return true;
  9462. }
  9463. if (opName === 'spirv.mlir.loop' || opName === 'spv.mlir.loop') {
  9464. if (parser.match('{')) {
  9465. const region = {};
  9466. parser.parseRegion(region);
  9467. op.regions.push(region);
  9468. }
  9469. return true;
  9470. }
  9471. if (opName === 'spirv.Variable' || opName === 'spv.Variable') {
  9472. if (parser.accept('id', 'init')) {
  9473. parser.expect('(');
  9474. const init = parser.parseAttribute();
  9475. op.operands.push(init);
  9476. parser.expect(')');
  9477. }
  9478. if (parser.match('{')) {
  9479. parser.parseAttributeDict(op.attributes);
  9480. }
  9481. if (parser.accept(':')) {
  9482. const type = parser.parseType();
  9483. op.results.push({ type });
  9484. }
  9485. return true;
  9486. }
  9487. if (opName === 'spirv.Store' || opName === 'spv.Store') {
  9488. const storageClass = parser.expect('string');
  9489. op.attributes.push({ name: 'storage_class', value: storageClass });
  9490. const ptr = parser.parseAttribute();
  9491. op.operands.push(ptr);
  9492. parser.expect(',');
  9493. const value = parser.parseAttribute();
  9494. op.operands.push(value);
  9495. if (parser.accept('[')) {
  9496. const memoryAccess = [];
  9497. while (!parser.match(']')) {
  9498. if (parser.match('string')) {
  9499. memoryAccess.push(parser.expect('string'));
  9500. } else if (parser.match('int')) {
  9501. memoryAccess.push(parser.expect('int'));
  9502. } else {
  9503. break;
  9504. }
  9505. parser.accept(',');
  9506. }
  9507. parser.expect(']');
  9508. if (memoryAccess.length > 0) {
  9509. op.attributes.push({ name: 'memory_access', value: memoryAccess.join(', ') });
  9510. }
  9511. }
  9512. if (parser.accept(':')) {
  9513. parser.parseType();
  9514. }
  9515. return true;
  9516. }
  9517. if (opName === 'spirv.CompositeInsert' || opName === 'spv.CompositeInsert') {
  9518. const object = parser.parseAttribute();
  9519. op.operands.push(object);
  9520. parser.expect(',');
  9521. const composite = parser.parseAttribute();
  9522. op.operands.push(composite);
  9523. if (parser.accept('[')) {
  9524. const indices = [];
  9525. while (!parser.match(']')) {
  9526. if (parser.match('int')) {
  9527. indices.push(parser.parseInteger());
  9528. }
  9529. if (parser.accept(':')) {
  9530. parser.parseType();
  9531. }
  9532. if (!parser.accept(',')) {
  9533. break;
  9534. }
  9535. }
  9536. parser.expect(']');
  9537. op.attributes.push({ name: 'indices', value: indices });
  9538. }
  9539. if (parser.accept(':')) {
  9540. parser.parseType();
  9541. if (parser.accept('id', 'into')) {
  9542. const type = parser.parseType();
  9543. op.results.push({ type });
  9544. }
  9545. }
  9546. return true;
  9547. }
  9548. // Reference: ControlFlowOps.cpp BranchConditionalOp::parse
  9549. // Format: spirv.BranchConditional %cond [trueWeight, falseWeight]?, ^trueTarget(args)?, ^falseTarget(args)?
  9550. if (opName === 'spirv.BranchConditional' || opName === 'spv.BranchConditional') {
  9551. const condition = parser.parseAttribute();
  9552. op.operands.push(condition);
  9553. // Parse optional branch weights [trueWeight, falseWeight]
  9554. if (parser.accept('[')) {
  9555. const weights = [];
  9556. while (!parser.match(']')) {
  9557. if (parser.match('int')) {
  9558. weights.push(parser.expect('int'));
  9559. }
  9560. parser.accept(',');
  9561. }
  9562. parser.expect(']');
  9563. if (weights.length > 0) {
  9564. op.attributes.push({ name: 'branch_weights', value: weights });
  9565. }
  9566. }
  9567. parser.expect(',');
  9568. if (!op.successors) {
  9569. op.successors = [];
  9570. }
  9571. // Parse true branch successor
  9572. const trueLabel = parser.expect('^');
  9573. const trueSucc = { label: trueLabel };
  9574. if (parser.accept('(')) {
  9575. trueSucc.arguments = [];
  9576. while (!parser.match(')') && !parser.match(':')) {
  9577. if (parser.match('%')) {
  9578. trueSucc.arguments.push({ value: parser.expect('%') });
  9579. parser.accept(',');
  9580. } else {
  9581. break;
  9582. }
  9583. }
  9584. if (parser.accept(':')) {
  9585. let idx = 0;
  9586. while (!parser.match(')') && idx < trueSucc.arguments.length) {
  9587. trueSucc.arguments[idx].type = parser.parseType().toString();
  9588. idx++;
  9589. parser.accept(',');
  9590. }
  9591. }
  9592. parser.expect(')');
  9593. }
  9594. op.successors.push(trueSucc);
  9595. parser.expect(',');
  9596. // Parse false branch successor
  9597. const falseLabel = parser.expect('^');
  9598. const falseSucc = { label: falseLabel };
  9599. if (parser.accept('(')) {
  9600. falseSucc.arguments = [];
  9601. while (!parser.match(')') && !parser.match(':')) {
  9602. if (parser.match('%')) {
  9603. falseSucc.arguments.push({ value: parser.expect('%') });
  9604. parser.accept(',');
  9605. } else {
  9606. break;
  9607. }
  9608. }
  9609. if (parser.accept(':')) {
  9610. let idx = 0;
  9611. while (!parser.match(')') && idx < falseSucc.arguments.length) {
  9612. falseSucc.arguments[idx].type = parser.parseType().toString();
  9613. idx++;
  9614. parser.accept(',');
  9615. }
  9616. }
  9617. parser.expect(')');
  9618. }
  9619. op.successors.push(falseSucc);
  9620. return true;
  9621. }
  9622. if (opName === 'spirv.CompositeConstruct' || opName === 'spv.CompositeConstruct') {
  9623. this.getOperation(opName).hasParseOperation = false; // compatibility?
  9624. while (!parser.match(':')) {
  9625. const constituent = parser.parseAttribute();
  9626. op.operands.push(constituent);
  9627. if (!parser.accept(',')) {
  9628. break;
  9629. }
  9630. }
  9631. if (parser.accept(':')) {
  9632. if (parser.accept('(')) {
  9633. parser.parseTypeList();
  9634. parser.expect(')');
  9635. parser.expect('->');
  9636. }
  9637. const type = parser.parseType();
  9638. op.results.push({ type });
  9639. }
  9640. return true;
  9641. }
  9642. if (opName === 'spirv.SpecConstant' || opName === 'spv.SpecConstant') {
  9643. parser.parseSymbolName('sym_name', op.attributes);
  9644. if (parser.match('id', 'spec_id')) {
  9645. parser.expect('id', 'spec_id');
  9646. parser.expect('(');
  9647. const specId = parser.parseAttribute();
  9648. op.attributes.push({ name: 'spec_id', value: specId });
  9649. parser.expect(')');
  9650. }
  9651. if (parser.accept('=')) {
  9652. const defaultValue = parser.parseAttribute();
  9653. op.attributes.push({ name: 'default_value', value: defaultValue });
  9654. }
  9655. if (parser.accept(':')) {
  9656. const type = parser.parseType();
  9657. op.attributes.push({ name: 'type', value: type });
  9658. }
  9659. return true;
  9660. }
  9661. if (opName === 'spirv.module' || opName === 'spv.module') {
  9662. if (parser.match('id')) {
  9663. const addressingModel = parser.expect('id');
  9664. op.attributes.push({ name: 'addressing_model', value: addressingModel });
  9665. }
  9666. if (parser.match('id')) {
  9667. const memoryModel = parser.expect('id');
  9668. op.attributes.push({ name: 'memory_model', value: memoryModel });
  9669. }
  9670. if (parser.accept('id', 'requires')) {
  9671. const vce = parser.parseAttribute();
  9672. op.attributes.push({ name: 'vce_triple', value: vce });
  9673. }
  9674. if (parser.accept('id', 'attributes')) {
  9675. parser.parseAttributeDict(op.attributes);
  9676. }
  9677. if (parser.match('{')) {
  9678. const region = {};
  9679. parser.parseRegion(region);
  9680. op.regions.push(region);
  9681. }
  9682. return true;
  9683. }
  9684. if (opName === 'spirv.ARM.Graph') {
  9685. // Reference: ArmGraphOps.cpp GraphARMOp::parse
  9686. // Format: @name (args) -> (results) [attributes] { body }
  9687. parser.parseFunctionOp(op, false);
  9688. return true;
  9689. }
  9690. if (opName === 'spirv.ARM.GraphEntryPoint') {
  9691. // Reference: ArmGraphOps.cpp GraphEntryPointARMOp::parse
  9692. // Format: @fn_name, @interface1, @interface2, ...
  9693. const fn = parser.expect('@');
  9694. op.attributes.push({ name: 'fn', value: fn });
  9695. const interfaceVars = [];
  9696. while (parser.accept(',')) {
  9697. const varSymbol = parser.expect('@');
  9698. interfaceVars.push(varSymbol);
  9699. }
  9700. op.attributes.push({ name: 'interface', value: interfaceVars });
  9701. return true;
  9702. }
  9703. if (opName === 'spirv.func' || opName === 'spv.func') {
  9704. if (parser.match('@')) {
  9705. const symbol = parser.expect('@');
  9706. op.attributes.push({ name: 'sym_name', value: symbol });
  9707. }
  9708. const function_type = {
  9709. inputs: [],
  9710. results: []
  9711. };
  9712. const resultAttrs = [];
  9713. if (parser.match('(')) {
  9714. const argResult = parser.parseFunctionArgumentList();
  9715. function_type.inputs = argResult.arguments.map((a) => a.type);
  9716. }
  9717. if (parser.accept('->')) {
  9718. parser.parseFunctionResultList(function_type.results, resultAttrs);
  9719. }
  9720. op.attributes.push({ name: 'function_type', value: function_type });
  9721. if (parser.match('string')) {
  9722. const control = parser.expect('string');
  9723. op.attributes.push({ name: 'function_control', value: control });
  9724. }
  9725. if (parser.accept('id', 'attributes')) {
  9726. parser.parseAttributeDict(op.attributes);
  9727. }
  9728. if (parser.match('{')) {
  9729. const region = {};
  9730. parser.parseRegion(region);
  9731. op.regions.push(region);
  9732. }
  9733. return true;
  9734. }
  9735. if (opName === 'spirv.GlobalVariable' || opName === 'spv.GlobalVariable') {
  9736. if (parser.match('@')) {
  9737. const symbol = parser.expect('@');
  9738. op.attributes.push({ name: 'sym_name', value: symbol });
  9739. }
  9740. if (parser.accept('id', 'built_in')) {
  9741. parser.expect('(');
  9742. const builtIn = parser.expect('string');
  9743. parser.expect(')');
  9744. op.attributes.push({ name: 'built_in', value: builtIn });
  9745. }
  9746. if (parser.accept('id', 'bind')) {
  9747. parser.expect('(');
  9748. const binding = parser.expect();
  9749. parser.accept(',');
  9750. const set = parser.expect();
  9751. parser.expect(')');
  9752. op.attributes.push({ name: 'descriptor_set', value: set });
  9753. op.attributes.push({ name: 'binding', value: binding });
  9754. }
  9755. if (parser.match('{')) {
  9756. parser.parseAttributeDict(op.attributes);
  9757. }
  9758. if (parser.accept(':')) {
  9759. const type = parser.parseType();
  9760. op.results = [{ type }];
  9761. }
  9762. return true;
  9763. }
  9764. if (opName === 'spirv.EntryPoint' || opName === 'spv.EntryPoint') {
  9765. // Parse execution model string ("GLCompute", "Vertex", "Fragment", etc.)
  9766. if (parser.match('string')) {
  9767. const executionModel = parser.expect('string');
  9768. op.attributes.push({ name: 'execution_model', value: executionModel });
  9769. }
  9770. op.operands = [];
  9771. while (parser.match('@')) {
  9772. const symbol = parser.expect('@');
  9773. op.operands.push({ value: symbol });
  9774. parser.accept(',');
  9775. }
  9776. return true;
  9777. }
  9778. if (opName === 'spirv.ExecutionMode' || opName === 'spv.ExecutionMode') {
  9779. if (parser.match('@')) {
  9780. const symbol = parser.expect('@');
  9781. op.operands.push({ value: symbol });
  9782. }
  9783. if (parser.match('string')) {
  9784. const mode = parser.expect('string');
  9785. op.attributes.push({ name: 'execution_mode', value: mode });
  9786. }
  9787. while (parser.accept(',')) {
  9788. if (parser.match('int') || parser.match('number') || parser.match('id')) {
  9789. const param = parser.expect();
  9790. op.operands.push({ value: param });
  9791. } else {
  9792. break;
  9793. }
  9794. }
  9795. return true;
  9796. }
  9797. if (opName === 'spirv.mlir.loop' || opName === 'spv.mlir.loop' || opName === 'spirv.mlir.selection' || opName === 'spv.mlir.selection') {
  9798. // Parse optional control(EnumValue) attribute
  9799. if (parser.accept('id', 'control')) {
  9800. parser.expect('(');
  9801. const controlValue = parser.parseKeyword();
  9802. op.attributes.push({ name: 'selection_control', value: controlValue });
  9803. parser.expect(')');
  9804. }
  9805. // Parse optional -> result types
  9806. parser.parseOptionalArrowResultTypes(op);
  9807. // Parse region
  9808. if (parser.match('{')) {
  9809. const region = {};
  9810. parser.parseRegion(region);
  9811. op.regions.push(region);
  9812. }
  9813. return true;
  9814. }
  9815. // spirv.CompositeInsert with 'into' keyword
  9816. // Format: spirv.CompositeInsert %object, %composite[indices] : object-type into composite-type
  9817. if (opName === 'spirv.CompositeInsert' || opName === 'spv.CompositeInsert') {
  9818. // Parse operands (object and composite)
  9819. op.operands = parser.parseArguments();
  9820. // Parse indices as attributes
  9821. if (parser.accept('[')) {
  9822. const indices = [];
  9823. while (!parser.accept(']')) {
  9824. const index = parser.expect();
  9825. if (parser.accept(':')) {
  9826. parser.expect(); // Skip type (e.g., i32)
  9827. }
  9828. indices.push(index);
  9829. parser.accept(',');
  9830. }
  9831. op.attributes.push({ name: 'indices', value: indices });
  9832. }
  9833. // Parse operand types after ':'
  9834. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  9835. // Parse result type after 'into'
  9836. if (parser.accept('id', 'into')) {
  9837. const resultType = parser.parseType();
  9838. op.results = [{ type: resultType }];
  9839. }
  9840. return true;
  9841. }
  9842. return super.parseOperation(parser, opName, op);
  9843. }
  9844. };
  9845. mlir.CFDialect = class extends mlir.Dialect {
  9846. constructor(operations) {
  9847. super('cf', operations);
  9848. this.registerCustomDirective('SwitchOpCases', this._parseSwitchOpCases.bind(this));
  9849. }
  9850. _parseSwitchOpCases(parser, op) {
  9851. if (!parser.accept('id', 'default')) {
  9852. return false;
  9853. }
  9854. if (!parser.accept(':')) {
  9855. return false;
  9856. }
  9857. if (!parser.match('^')) {
  9858. return false;
  9859. }
  9860. const defaultDestination = parser.expect('^');
  9861. const defaultDest = { label: defaultDestination, arguments: [] };
  9862. if (parser.accept('(')) {
  9863. while (!parser.match(')') && !parser.match(':')) {
  9864. const value = parser.expect('%');
  9865. defaultDest.arguments.push({ value });
  9866. if (!parser.accept(',')) {
  9867. break;
  9868. }
  9869. }
  9870. if (parser.accept(':')) {
  9871. let idx = 0;
  9872. while (idx < defaultDest.arguments.length && !parser.match(')')) {
  9873. const type = parser.parseType();
  9874. if (defaultDest.arguments[idx]) {
  9875. defaultDest.arguments[idx].type = type;
  9876. }
  9877. idx++;
  9878. parser.accept(',');
  9879. }
  9880. }
  9881. parser.accept(')');
  9882. }
  9883. op.successors = op.successors || [];
  9884. op.successors.push(defaultDest);
  9885. const caseValues = [];
  9886. const caseOperandSegments = [defaultDest.arguments.length];
  9887. while (parser.accept(',')) {
  9888. if (!parser.match('int')) {
  9889. break;
  9890. }
  9891. const value = parser.parseInteger();
  9892. caseValues.push(value);
  9893. if (!parser.accept(':')) {
  9894. break;
  9895. }
  9896. if (!parser.match('^')) {
  9897. break;
  9898. }
  9899. const caseDestination = parser.expect('^');
  9900. const caseDest = { label: caseDestination, arguments: [] };
  9901. if (parser.accept('(')) {
  9902. while (!parser.match(')') && !parser.match(':')) {
  9903. const operandValue = parser.expect('%');
  9904. caseDest.arguments.push({ value: operandValue });
  9905. if (!parser.accept(',')) {
  9906. break;
  9907. }
  9908. }
  9909. if (parser.accept(':')) {
  9910. let idx = 0;
  9911. while (idx < caseDest.arguments.length && !parser.match(')')) {
  9912. const type = parser.parseType();
  9913. if (caseDest.arguments[idx]) {
  9914. caseDest.arguments[idx].type = type;
  9915. }
  9916. idx++;
  9917. parser.accept(',');
  9918. }
  9919. }
  9920. parser.accept(')');
  9921. }
  9922. op.successors.push(caseDest);
  9923. caseOperandSegments.push(caseDest.arguments.length);
  9924. }
  9925. if (caseValues.length > 0) {
  9926. op.attributes.push({ name: 'case_values', value: caseValues });
  9927. op.attributes.push({ name: 'case_operand_segments', value: caseOperandSegments });
  9928. }
  9929. return true;
  9930. }
  9931. };
  9932. mlir.PDLDialect = class extends mlir.Dialect {
  9933. constructor(operations) {
  9934. super('pdl', operations);
  9935. this.registerCustomDirective('OperationOpAttributes', this._parseOperationOpAttributes.bind(this));
  9936. this.registerCustomDirective('RangeType', this._parseRangeType.bind(this));
  9937. this._customParse = new Set(['pdl.operation']);
  9938. }
  9939. parseOperation(parser, opName, op) {
  9940. if (opName === 'pdl.operation') {
  9941. this._operations.get(opName).hasParseOperation = false;
  9942. return this._parseOperationOp(parser, op);
  9943. }
  9944. return super.parseOperation(parser, opName, op);
  9945. }
  9946. _parseOperationOp(parser, op) {
  9947. if (parser.match('string')) {
  9948. const opNameValue = parser.expect('string');
  9949. op.attributes.push({ name: 'opName', value: opNameValue });
  9950. }
  9951. if (parser.accept('(')) {
  9952. while (!parser.match(')')) {
  9953. const value = parser.expect('%');
  9954. op.operands.push({ value, name: 'operandValue' });
  9955. if (!parser.accept(',')) {
  9956. break;
  9957. }
  9958. }
  9959. if (parser.accept(':')) {
  9960. let idx = 0;
  9961. while (idx < op.operands.length && !parser.match(')')) {
  9962. const type = parser.parseType();
  9963. op.operands[idx].type = type;
  9964. idx++;
  9965. parser.accept(',');
  9966. }
  9967. }
  9968. parser.accept(')');
  9969. }
  9970. this._parseOperationOpAttributes(parser, op);
  9971. if (parser.accept('->')) {
  9972. parser.accept('(');
  9973. while (!parser.match(')') && !parser.match('{') && !parser.match('id', 'loc')) {
  9974. const value = parser.expect('%');
  9975. op.operands.push({ value, name: 'typeValue' });
  9976. if (!parser.accept(',')) {
  9977. break;
  9978. }
  9979. }
  9980. if (parser.accept(':')) {
  9981. const typeValueStartIdx = op.operands.findIndex((o) => o.name === 'typeValue');
  9982. let idx = typeValueStartIdx >= 0 ? typeValueStartIdx : op.operands.length;
  9983. while (idx < op.operands.length && !parser.match(')')) {
  9984. const type = parser.parseType();
  9985. if (op.operands[idx]) {
  9986. op.operands[idx].type = type;
  9987. }
  9988. idx++;
  9989. parser.accept(',');
  9990. }
  9991. }
  9992. parser.accept(')');
  9993. }
  9994. return true;
  9995. }
  9996. _parseOperationOpAttributes(parser, op) {
  9997. if (!parser.accept('{')) {
  9998. return true;
  9999. }
  10000. const attributeNames = [];
  10001. while (!parser.match('}')) {
  10002. const name = parser.parseAttribute();
  10003. if (!parser.accept('=')) {
  10004. break;
  10005. }
  10006. const value = parser.expect('%');
  10007. op.operands.push({ value, name: 'attributeValue' });
  10008. attributeNames.push(name);
  10009. if (!parser.accept(',')) {
  10010. break;
  10011. }
  10012. }
  10013. parser.accept('}');
  10014. if (attributeNames.length > 0) {
  10015. op.attributes.push({ name: 'attributeValueNames', value: attributeNames });
  10016. }
  10017. return true;
  10018. }
  10019. _parseRangeType(parser, op) {
  10020. parser.accept(':');
  10021. const type = parser.parseType();
  10022. if (op.results.length > 0) {
  10023. op.results[0].type = type;
  10024. }
  10025. return true;
  10026. }
  10027. };
  10028. mlir.PtrDialect = class extends mlir.Dialect {
  10029. constructor(operations) {
  10030. super('ptr', operations);
  10031. this.registerCustomAttribute('EnumProp', this._parseEnumProp.bind(this));
  10032. this.registerCustomAttribute('Ptr_PtrDiffFlags', this._parsePtrDiffFlags.bind(this));
  10033. }
  10034. _parseEnumProp(parser, type) {
  10035. const [innerType] = type.args;
  10036. return this._parseCustomAttributeWithFallback(parser, innerType);
  10037. }
  10038. _parsePtrDiffFlags(parser, type) {
  10039. if (type.values.includes(parser.getToken().value)) {
  10040. return this._parseEnumFlags(parser, type, '|');
  10041. }
  10042. return null;
  10043. }
  10044. };
  10045. mlir.EmitCDialect = class extends mlir.Dialect {
  10046. constructor(operations) {
  10047. super('emitc', operations);
  10048. this.registerCustomType('EmitC_LValueType', this._parseLValueType.bind(this));
  10049. }
  10050. parseOperation(parser, opName, op) {
  10051. if (opName === 'emitc.func') {
  10052. parser.parseFunctionOp(op, false);
  10053. return true;
  10054. }
  10055. if (opName === 'emitc.expression') {
  10056. // Format: emitc.expression %operands [noinline] : (inputs) -> output { region }
  10057. // Parse operands
  10058. while (parser.match('%')) {
  10059. const operand = parser.expect('%');
  10060. op.operands.push({ value: operand });
  10061. if (!parser.accept(',')) {
  10062. break;
  10063. }
  10064. }
  10065. // Parse optional noinline
  10066. if (parser.accept('id', 'noinline')) {
  10067. op.attributes.push({ name: 'do_not_inline', value: true });
  10068. }
  10069. // Parse function type
  10070. if (parser.accept(':')) {
  10071. const type = parser.parseType();
  10072. // Function type is (inputs) -> outputs
  10073. // We extract the result type from the function type
  10074. if (type && type.value) {
  10075. op.attributes.push({ name: 'type', value: type });
  10076. // Try to extract result type from function type
  10077. const match = type.value.match(/\) -> (.+)$/);
  10078. if (match) {
  10079. op.results.push({ type: new mlir.Type(match[1]) });
  10080. }
  10081. }
  10082. }
  10083. // Parse region
  10084. if (parser.match('{')) {
  10085. const region = {};
  10086. parser.parseRegion(region);
  10087. op.regions.push(region);
  10088. }
  10089. return true;
  10090. }
  10091. if (opName === 'emitc.global' || opName === 'emitc.field') {
  10092. if (parser.match('id', 'extern')) {
  10093. const externAttr = parser.expect('id');
  10094. op.attributes.push({ name: 'extern', value: externAttr });
  10095. }
  10096. if (parser.match('id', 'static')) {
  10097. const staticAttr = parser.expect('id');
  10098. op.attributes.push({ name: 'static', value: staticAttr });
  10099. }
  10100. if (parser.match('id', 'const')) {
  10101. const constAttr = parser.expect('id');
  10102. op.attributes.push({ name: 'const', value: constAttr });
  10103. }
  10104. parser.parseSymbolName('sym_name', op.attributes);
  10105. if (parser.accept(':')) {
  10106. const type = parser.parseType();
  10107. op.attributes.push({ name: 'type', value: type });
  10108. }
  10109. if (parser.accept('=')) {
  10110. const initialValue = parser.parseAttribute();
  10111. op.attributes.push({ name: 'initial_value', value: initialValue });
  10112. }
  10113. return true;
  10114. }
  10115. return super.parseOperation(parser, opName, op);
  10116. }
  10117. _parseLValueType(parser) {
  10118. if (parser.match('<')) {
  10119. const content = parser.skip('<', '>');
  10120. return new mlir.Type(`!emitc.lvalue${content}`);
  10121. }
  10122. return null;
  10123. }
  10124. };
  10125. mlir.AsukaDialect = class extends mlir.Dialect {
  10126. constructor(operations) {
  10127. super('asuka', operations);
  10128. // https://github.com/monellz/FlashTensor/blob/main/bench/ea.mlir
  10129. // uses batch_dims and reduce_dims not valid given the assemblyFormat spec.
  10130. // Custom parsing preserves compatibility with this file.
  10131. this._customParse = new Set(['asuka.dot', 'asuka.add', 'asuka.split', 'asuka.softmax']);
  10132. }
  10133. parseOperation(parser, opName, op) {
  10134. if (this._customParse.has(opName)) {
  10135. this._operations.get(opName).hasParseOperation = false;
  10136. op.operands = parser.parseArguments();
  10137. while (parser.match('id') && !parser.match(':') && !parser.match('{')) {
  10138. const attrName = parser.expect('id');
  10139. if (parser.accept('=')) {
  10140. let attrValue = null;
  10141. if (parser.match('[')) {
  10142. attrValue = parser.parseAttribute();
  10143. if (parser.match('id') && parser.token.value === 'x') {
  10144. parser.expect('id'); // consume 'x'
  10145. const secondValue = parser.parseAttribute();
  10146. attrValue = { kind: 'pair', first: attrValue, second: secondValue };
  10147. }
  10148. } else {
  10149. attrValue = parser.parseAttribute();
  10150. }
  10151. op.attributes.push({ name: attrName, value: attrValue });
  10152. parser.accept(',');
  10153. }
  10154. }
  10155. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  10156. if (parser.accept('->')) {
  10157. if (op.results.length > 0) {
  10158. const types = parser.parseFunctionResultTypes();
  10159. parser.resolveOperands(op.results, types);
  10160. } else {
  10161. op.results = parser.parseArguments();
  10162. }
  10163. }
  10164. return true;
  10165. }
  10166. return super.parseOperation(parser, opName, op);
  10167. }
  10168. };
  10169. mlir.AsyncDialect = class extends mlir.Dialect {
  10170. constructor(operations) {
  10171. super('async', operations);
  10172. this.registerCustomDirective('AwaitResultType', this._parseAwaitResultType.bind(this));
  10173. }
  10174. parseType(parser, dialectName) {
  10175. const typeName = parser.parseKeyword();
  10176. if (typeName) {
  10177. let type = `!${dialectName}.${typeName}`;
  10178. if (typeName === 'coro' && parser.match('.')) {
  10179. parser.expect('.');
  10180. const subType = parser.expect('id');
  10181. type += `.${subType}`;
  10182. return new mlir.Type(type);
  10183. }
  10184. const simpleTypes = ['token', 'group'];
  10185. if (simpleTypes.includes(typeName)) {
  10186. return new mlir.Type(type);
  10187. }
  10188. if (typeName === 'value') {
  10189. if (parser.match('<')) {
  10190. const content = parser.skip('<', '>');
  10191. type += content;
  10192. }
  10193. return new mlir.Type(type);
  10194. }
  10195. }
  10196. return null;
  10197. }
  10198. parseOperation(parser, opName, op) {
  10199. if (opName === 'async.execute') {
  10200. return this._parseExecuteOp(parser, op);
  10201. }
  10202. if (opName === 'async.func') {
  10203. return this._parseFuncOp(parser, op);
  10204. }
  10205. return super.parseOperation(parser, opName, op);
  10206. }
  10207. _parseExecuteOp(parser, op) {
  10208. // Reference: Async.cpp:143 uses parseOperandList
  10209. const tokenArgs = parser.parseOperandList('optionalSquare');
  10210. op.operands.push(...tokenArgs);
  10211. if (parser.accept('(')) {
  10212. while (!parser.match(')')) {
  10213. const operand = { value: parser.expect('%') };
  10214. if (parser.accept('id', 'as')) {
  10215. parser.expect('%');
  10216. }
  10217. if (parser.accept(':')) {
  10218. operand.type = parser.parseType().toString();
  10219. }
  10220. op.operands.push(operand);
  10221. if (!parser.accept(',')) {
  10222. break;
  10223. }
  10224. }
  10225. parser.expect(')');
  10226. }
  10227. if (parser.accept('->')) {
  10228. if (parser.accept('(')) {
  10229. while (!parser.match(')')) {
  10230. const resultType = parser.parseType();
  10231. if (op.results.length < 1) {
  10232. op.results.push({ type: '!async.token' });
  10233. }
  10234. op.results.push({ type: resultType });
  10235. if (!parser.accept(',')) {
  10236. break;
  10237. }
  10238. }
  10239. parser.expect(')');
  10240. } else {
  10241. const resultType = parser.parseType();
  10242. if (op.results.length < 1) {
  10243. op.results.push({ type: '!async.token' });
  10244. }
  10245. op.results.push({ type: resultType });
  10246. }
  10247. } else if (op.results.length === 1 && !op.results[0].type) {
  10248. op.results[0].type = '!async.token';
  10249. }
  10250. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  10251. if (parser.match('{')) {
  10252. const region = {};
  10253. parser.parseRegion(region);
  10254. op.regions.push(region);
  10255. }
  10256. return true;
  10257. }
  10258. _parseFuncOp(parser, op) {
  10259. parser.parseOptionalVisibilityKeyword(op.attributes);
  10260. parser.parseSymbolName('sym_name', op.attributes);
  10261. const type = {};
  10262. const argResult = parser.parseFunctionArgumentList();
  10263. type.inputs = argResult.arguments.map((a) => a.type);
  10264. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  10265. type.results = [];
  10266. const resultAttrs = [];
  10267. if (parser.accept('->')) {
  10268. parser.parseFunctionResultList(type.results, resultAttrs);
  10269. }
  10270. op.attributes.push({ name: 'function_type', value: type });
  10271. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  10272. if (parser.match('{')) {
  10273. const region = {};
  10274. parser.parseRegion(region);
  10275. op.regions.push(region);
  10276. }
  10277. return true;
  10278. }
  10279. _parseAwaitResultType(parser, op, args) {
  10280. // custom<AwaitResultType>(type($operand), type($result))
  10281. // This parses the operand type and derives the result type
  10282. const operandType = parser.parseType();
  10283. if (args && args.length > 0 && op.operands.length > 0) {
  10284. op.operands[0].type = operandType;
  10285. }
  10286. const operandTypeStr = operandType ? operandType.toString() : '';
  10287. if (operandTypeStr && operandTypeStr.startsWith('!async.value')) {
  10288. const match = operandTypeStr.match(/!async\.value<(.+)>/);
  10289. if (match && args && args.length > 1) {
  10290. // Extract the inner type and set it as the result type
  10291. const [, innerType] = match;
  10292. if (op.results.length > 0) {
  10293. op.results[0].type = new mlir.Type(innerType);
  10294. }
  10295. }
  10296. }
  10297. }
  10298. };
  10299. mlir.ArithDialect = class extends mlir.Dialect {
  10300. constructor(operations) {
  10301. super('arith', operations);
  10302. // Register custom attribute parsers for attributes with <value> assemblyFormat
  10303. this.registerCustomAttribute('Arith_FastMathAttr', this._parseEnumFlagsAngleBracketComma.bind(this));
  10304. this.registerCustomAttribute('Arith_IntegerOverflowAttr', this._parseEnumFlagsAngleBracketComma.bind(this));
  10305. }
  10306. parseOperation(parser, opName, op) {
  10307. if (opName === 'arith.select') {
  10308. return this._parseSelectOp(parser, op);
  10309. }
  10310. return super.parseOperation(parser, opName, op);
  10311. }
  10312. _parseSelectOp(parser, op) {
  10313. op.operands = parser.parseArguments();
  10314. if (parser.match('{')) {
  10315. parser.parseAttributeDict(op.attributes);
  10316. }
  10317. if (parser.accept(':')) {
  10318. const condType = parser.parseType();
  10319. if (parser.accept(',')) {
  10320. const resultType = parser.parseType();
  10321. if (op.operands.length > 0) {
  10322. op.operands[0].type = condType;
  10323. }
  10324. if (op.operands.length > 1) {
  10325. op.operands[1].type = resultType;
  10326. op.operands[2].type = resultType;
  10327. }
  10328. if (op.results.length > 0) {
  10329. op.results[0].type = resultType;
  10330. } else {
  10331. op.results.push({ type: resultType });
  10332. }
  10333. } else if (op.results.length > 0) {
  10334. op.results[0].type = condType;
  10335. } else {
  10336. op.results.push({ type: condType });
  10337. }
  10338. }
  10339. return true;
  10340. }
  10341. };
  10342. mlir.BuiltinDialect = class extends mlir.Dialect {
  10343. constructor(operations) {
  10344. super('builtin', operations);
  10345. }
  10346. parseOperation(parser, opName, op) {
  10347. if (opName === 'builtin.call' || opName === 'builtin.call_indirect') {
  10348. parser.parseSymbolName('callee', op.attributes);
  10349. op.operands = parser.parseArguments();
  10350. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  10351. if (parser.accept('->')) {
  10352. const resultTypes = parser.parseFunctionResultTypes();
  10353. parser.resolveOperands(op.results, resultTypes);
  10354. }
  10355. return true;
  10356. }
  10357. return super.parseOperation(parser, opName, op);
  10358. }
  10359. };
  10360. mlir.BufferizationDialect = class extends mlir.Dialect {
  10361. constructor(operations) {
  10362. super('bufferization', operations);
  10363. }
  10364. parseOperation(parser, opName, op) {
  10365. if (opName === 'bufferization.alloc_tensor') {
  10366. if (!parser.accept('(')) {
  10367. return false;
  10368. }
  10369. while (!parser.match(')')) {
  10370. if (parser.match('%')) {
  10371. const operand = {};
  10372. operand.value = parser.expect('%');
  10373. op.operands.push(operand);
  10374. if (!parser.accept(',')) {
  10375. break;
  10376. }
  10377. } else {
  10378. break;
  10379. }
  10380. }
  10381. parser.expect(')');
  10382. if (parser.accept('id', 'copy')) {
  10383. parser.expect('(');
  10384. const copyOperand = {};
  10385. copyOperand.value = parser.expect('%');
  10386. copyOperand.name = 'copy';
  10387. op.operands.push(copyOperand);
  10388. parser.expect(')');
  10389. }
  10390. if (parser.accept('id', 'size_hint')) {
  10391. parser.expect('=');
  10392. const sizeHintOperand = {};
  10393. sizeHintOperand.value = parser.expect('%');
  10394. sizeHintOperand.name = 'size_hint';
  10395. op.operands.push(sizeHintOperand);
  10396. }
  10397. parser.parseOptionalAttrDict(op.attributes);
  10398. if (parser.accept(':')) {
  10399. const type = parser.parseType();
  10400. if (op.results.length === 0) {
  10401. op.results.push({ type });
  10402. } else {
  10403. op.results[0].type = type;
  10404. }
  10405. }
  10406. return true;
  10407. }
  10408. // bufferization.to_memref %tensor read_only : tensor_type to memref_type
  10409. if (opName === 'bufferization.to_memref') {
  10410. // Parse operand
  10411. if (parser.match('%')) {
  10412. const operand = parser.expect('%');
  10413. op.operands.push({ value: operand });
  10414. }
  10415. // Parse optional read_only
  10416. if (parser.accept('id', 'read_only')) {
  10417. op.attributes.push({ name: 'read_only', value: true });
  10418. }
  10419. // Parse optional attr-dict
  10420. parser.parseOptionalAttrDict(op.attributes);
  10421. // Parse : source_type to dest_type
  10422. if (parser.accept(':')) {
  10423. const sourceType = parser.parseType();
  10424. op.attributes.push({ name: 'source_type', value: sourceType });
  10425. parser.expect('id', 'to');
  10426. const destType = parser.parseType();
  10427. op.results.push({ type: destType });
  10428. }
  10429. return true;
  10430. }
  10431. return super.parseOperation(parser, opName, op);
  10432. }
  10433. };
  10434. mlir.SCFDialect = class extends mlir.Dialect {
  10435. constructor(operations) {
  10436. super('scf', operations);
  10437. this.registerCustomDirective('SwitchCases', this._parseSwitchCases.bind(this));
  10438. }
  10439. parseOperation(parser, opName, op) {
  10440. if (opName === 'scf.for') {
  10441. return this._parseForOp(parser, op);
  10442. }
  10443. if (opName === 'scf.if') {
  10444. return this._parseIfOp(parser, op);
  10445. }
  10446. if (opName === 'scf.while') {
  10447. return this._parseWhileOp(parser, op);
  10448. }
  10449. if (opName === 'scf.forall') {
  10450. return this._parseForallOp(parser, op);
  10451. }
  10452. if (opName === 'scf.forall.in_parallel') {
  10453. return this._parseInParallelOp(parser, op);
  10454. }
  10455. if (opName === 'scf.parallel') {
  10456. return this._parseParallelOp(parser, op);
  10457. }
  10458. if (opName === 'scf.execute_region') {
  10459. return this._parseExecuteRegionOp(parser, op);
  10460. }
  10461. return super.parseOperation(parser, opName, op);
  10462. }
  10463. _parseForOp(parser, op) {
  10464. if (parser.accept('id', 'unsigned')) {
  10465. op.attributes.push({ name: 'unsignedCmp', value: true });
  10466. }
  10467. if (!parser.match('%')) {
  10468. return false;
  10469. }
  10470. const inductionVar = parser.expect('%');
  10471. if (!parser.accept('=')) {
  10472. return false;
  10473. }
  10474. if (parser.match('%')) {
  10475. op.operands.push({ value: parser.expect('%') });
  10476. } else {
  10477. return false;
  10478. }
  10479. if (!parser.accept('id', 'to')) {
  10480. return false;
  10481. }
  10482. if (parser.match('%')) {
  10483. op.operands.push({ value: parser.expect('%') });
  10484. } else {
  10485. return false;
  10486. }
  10487. if (!parser.accept('id', 'step')) {
  10488. return false;
  10489. }
  10490. if (parser.match('%')) {
  10491. op.operands.push({ value: parser.expect('%') });
  10492. } else {
  10493. return false;
  10494. }
  10495. if (parser.accept('id', 'iter_args')) {
  10496. if (parser.accept('(')) {
  10497. while (!parser.accept(')')) {
  10498. if (parser.match('%')) {
  10499. parser.expect('%'); // Skip the loop-carried variable name
  10500. }
  10501. if (parser.accept('=')) {
  10502. if (parser.match('%')) {
  10503. op.operands.push({ value: parser.expect('%') });
  10504. } else {
  10505. const value = parser.parseAttribute();
  10506. if (value) {
  10507. op.operands.push(value);
  10508. }
  10509. }
  10510. }
  10511. parser.accept(',');
  10512. }
  10513. }
  10514. parser.parseOptionalArrowResultTypes(op);
  10515. }
  10516. if (parser.accept(':')) {
  10517. parser.parseType();
  10518. }
  10519. if (parser.match('{')) {
  10520. const region = {};
  10521. parser.parseRegion(region);
  10522. if (region.blocks && region.blocks.length > 0) {
  10523. if (!region.blocks[0].arguments) {
  10524. region.blocks[0].arguments = [];
  10525. }
  10526. if (region.blocks[0].arguments.length > 0) {
  10527. region.blocks[0].arguments[0] = { value: inductionVar };
  10528. } else {
  10529. region.blocks[0].arguments.push({ value: inductionVar });
  10530. }
  10531. }
  10532. op.regions.push(region);
  10533. }
  10534. return true;
  10535. }
  10536. _parseIfOp(parser, op) {
  10537. if (parser.match('%')) {
  10538. op.operands.push({ value: parser.expect('%') });
  10539. } else {
  10540. return false;
  10541. }
  10542. parser.parseOptionalArrowResultTypes(op);
  10543. if (parser.match('{')) {
  10544. const region = {};
  10545. parser.parseRegion(region);
  10546. op.regions.push(region);
  10547. } else {
  10548. return false;
  10549. }
  10550. // Parse optional else region
  10551. if (parser.accept('id', 'else')) {
  10552. if (parser.match('{')) {
  10553. const region = {};
  10554. parser.parseRegion(region);
  10555. op.regions.push(region);
  10556. }
  10557. }
  10558. return true;
  10559. }
  10560. _parseWhileOp(parser, op) {
  10561. if (parser.accept('(')) {
  10562. while (!parser.accept(')')) {
  10563. if (parser.match('%')) {
  10564. parser.expect('%'); // Skip variable name
  10565. }
  10566. if (parser.accept('=')) {
  10567. if (parser.match('%')) {
  10568. op.operands.push({ value: parser.expect('%') });
  10569. } else {
  10570. const value = parser.parseAttribute();
  10571. if (value) {
  10572. op.operands.push(value);
  10573. }
  10574. }
  10575. }
  10576. parser.accept(',');
  10577. }
  10578. }
  10579. if (parser.accept(':')) {
  10580. if (parser.accept('(')) {
  10581. while (!parser.accept(')')) {
  10582. parser.parseType();
  10583. parser.accept(',');
  10584. }
  10585. } else {
  10586. parser.parseType();
  10587. }
  10588. parser.parseOptionalArrowResultTypes(op);
  10589. }
  10590. if (parser.match('{')) {
  10591. const region = {};
  10592. parser.parseRegion(region);
  10593. op.regions.push(region);
  10594. }
  10595. if (parser.accept('id', 'do')) {
  10596. if (parser.match('{')) {
  10597. const region = {};
  10598. parser.parseRegion(region);
  10599. op.regions.push(region);
  10600. }
  10601. }
  10602. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  10603. return true;
  10604. }
  10605. _parseForallOp(parser, op) {
  10606. const inductionVars = [];
  10607. if (!parser.accept('(')) {
  10608. return false;
  10609. }
  10610. while (!parser.accept(')')) {
  10611. if (parser.match('%')) {
  10612. inductionVars.push(parser.expect('%'));
  10613. } else {
  10614. return false;
  10615. }
  10616. if (!parser.accept(',')) {
  10617. if (parser.match(')')) {
  10618. parser.accept(')');
  10619. break;
  10620. }
  10621. return false;
  10622. }
  10623. }
  10624. const isNormalized = parser.accept('id', 'in');
  10625. if (!isNormalized && !parser.accept('=')) {
  10626. return false;
  10627. }
  10628. if (isNormalized) {
  10629. if (!parser.accept('(')) {
  10630. return false;
  10631. }
  10632. while (!parser.accept(')')) {
  10633. if (parser.match('%')) {
  10634. const value = parser.expect('%');
  10635. op.operands.push({ value });
  10636. } else if (parser.match('int')) {
  10637. const value = parser.expect('int');
  10638. op.operands.push({ value, type: new mlir.PrimitiveType('i64') });
  10639. } else {
  10640. return false;
  10641. }
  10642. parser.accept(',');
  10643. }
  10644. } else {
  10645. if (!parser.accept('(')) {
  10646. return false;
  10647. }
  10648. while (!parser.accept(')')) {
  10649. if (parser.match('%')) {
  10650. const value = parser.expect('%');
  10651. op.operands.push({ value });
  10652. } else if (parser.match('int')) {
  10653. const value = parser.expect('int');
  10654. op.operands.push({ value, type: new mlir.PrimitiveType('i64') });
  10655. } else {
  10656. return false;
  10657. }
  10658. parser.accept(',');
  10659. }
  10660. if (!parser.accept('id', 'to')) {
  10661. return false;
  10662. }
  10663. if (!parser.accept('(')) {
  10664. return false;
  10665. }
  10666. while (!parser.accept(')')) {
  10667. if (parser.match('%')) {
  10668. const value = parser.expect('%');
  10669. op.operands.push({ value });
  10670. } else if (parser.match('int')) {
  10671. const value = parser.expect('int');
  10672. op.operands.push({ value, type: new mlir.PrimitiveType('i64') });
  10673. } else {
  10674. return false;
  10675. }
  10676. parser.accept(',');
  10677. }
  10678. if (!parser.accept('id', 'step')) {
  10679. return false;
  10680. }
  10681. if (!parser.accept('(')) {
  10682. return false;
  10683. }
  10684. while (!parser.accept(')')) {
  10685. if (parser.match('%')) {
  10686. const value = parser.expect('%');
  10687. op.operands.push({ value });
  10688. } else if (parser.match('int')) {
  10689. const value = parser.expect('int');
  10690. op.operands.push({ value, type: new mlir.PrimitiveType('i64') });
  10691. } else {
  10692. return false;
  10693. }
  10694. parser.accept(',');
  10695. }
  10696. }
  10697. if (parser.accept('id', 'shared_outs')) {
  10698. if (!parser.accept('(')) {
  10699. return false;
  10700. }
  10701. while (!parser.accept(')')) {
  10702. if (parser.match('%')) {
  10703. parser.expect('%'); // Skip arg name
  10704. }
  10705. if (parser.accept('=')) {
  10706. if (parser.match('%')) {
  10707. op.operands.push({ value: parser.expect('%') });
  10708. } else {
  10709. const value = parser.parseAttribute();
  10710. if (value) {
  10711. op.operands.push(value);
  10712. }
  10713. }
  10714. }
  10715. parser.accept(',');
  10716. }
  10717. }
  10718. if (parser.accept('->')) {
  10719. if (parser.accept('(')) {
  10720. while (!parser.accept(')')) {
  10721. const type = parser.parseType();
  10722. op.results.push({ type });
  10723. parser.accept(',');
  10724. }
  10725. } else {
  10726. const type = parser.parseType();
  10727. op.results.push({ type });
  10728. }
  10729. }
  10730. if (parser.match('{')) {
  10731. const region = {};
  10732. parser.parseRegion(region);
  10733. op.regions.push(region);
  10734. } else {
  10735. return false;
  10736. }
  10737. return true;
  10738. }
  10739. _parseParallelOp(parser, op) {
  10740. const inductionVars = [];
  10741. if (!parser.accept('(')) {
  10742. return false;
  10743. }
  10744. while (!parser.accept(')')) {
  10745. if (parser.match('%')) {
  10746. inductionVars.push(parser.expect('%'));
  10747. } else {
  10748. return false;
  10749. }
  10750. parser.accept(',');
  10751. }
  10752. if (!parser.accept('=')) {
  10753. return false;
  10754. }
  10755. if (!parser.accept('(')) {
  10756. return false;
  10757. }
  10758. while (!parser.accept(')')) {
  10759. if (parser.match('%')) {
  10760. op.operands.push({ value: parser.expect('%') });
  10761. } else {
  10762. return false;
  10763. }
  10764. parser.accept(',');
  10765. }
  10766. if (!parser.accept('id', 'to')) {
  10767. return false;
  10768. }
  10769. if (!parser.accept('(')) {
  10770. return false;
  10771. }
  10772. while (!parser.accept(')')) {
  10773. if (parser.match('%')) {
  10774. op.operands.push({ value: parser.expect('%') });
  10775. } else {
  10776. return false;
  10777. }
  10778. parser.accept(',');
  10779. }
  10780. if (!parser.accept('id', 'step')) {
  10781. return false;
  10782. }
  10783. if (!parser.accept('(')) {
  10784. return false;
  10785. }
  10786. while (!parser.accept(')')) {
  10787. if (parser.match('%')) {
  10788. op.operands.push({ value: parser.expect('%') });
  10789. } else {
  10790. return false;
  10791. }
  10792. parser.accept(',');
  10793. }
  10794. if (parser.accept('id', 'init')) {
  10795. if (!parser.accept('(')) {
  10796. return false;
  10797. }
  10798. while (!parser.accept(')')) {
  10799. if (parser.match('%')) {
  10800. op.operands.push({ value: parser.expect('%') });
  10801. } else {
  10802. const value = parser.parseAttribute();
  10803. if (value) {
  10804. op.operands.push(value);
  10805. }
  10806. }
  10807. parser.accept(',');
  10808. }
  10809. }
  10810. if (parser.accept('->')) {
  10811. if (parser.accept('(')) {
  10812. while (!parser.accept(')')) {
  10813. const type = parser.parseType();
  10814. op.results.push({ type });
  10815. parser.accept(',');
  10816. }
  10817. } else {
  10818. const type = parser.parseType();
  10819. op.results.push({ type });
  10820. }
  10821. }
  10822. if (parser.match('{')) {
  10823. const region = {};
  10824. parser.parseRegion(region);
  10825. if (region.blocks && region.blocks.length > 0 && inductionVars.length > 0) {
  10826. if (!region.blocks[0].arguments) {
  10827. region.blocks[0].arguments = [];
  10828. }
  10829. for (const iv of inductionVars) {
  10830. region.blocks[0].arguments.push({ value: iv });
  10831. }
  10832. }
  10833. op.regions.push(region);
  10834. } else {
  10835. return false;
  10836. }
  10837. return true;
  10838. }
  10839. _parseInParallelOp(parser, op) {
  10840. // scf.forall.in_parallel { region }
  10841. // Just parse the region
  10842. if (parser.match('{')) {
  10843. const region = {};
  10844. parser.parseRegion(region);
  10845. op.regions.push(region);
  10846. } else {
  10847. return false;
  10848. }
  10849. return true;
  10850. }
  10851. _parseSwitchCases(parser, op, args) {
  10852. const caseValues = [];
  10853. while (parser.accept('id', 'case')) {
  10854. if (!parser.match('int')) {
  10855. break;
  10856. }
  10857. const value = parser.parseInteger();
  10858. caseValues.push(value);
  10859. if (parser.match('{')) {
  10860. const region = {};
  10861. parser.parseRegion(region);
  10862. op.regions.push(region);
  10863. } else {
  10864. break;
  10865. }
  10866. }
  10867. if (args && args.length > 0) {
  10868. const casesAttrName = args[0].replace(/^\$/, '');
  10869. op.attributes.push({ name: casesAttrName, value: caseValues });
  10870. }
  10871. }
  10872. _parseExecuteRegionOp(parser, op) {
  10873. parser.parseOptionalArrowResultTypes(op);
  10874. if (parser.accept('id', 'no_inline')) {
  10875. op.attributes.push({ name: 'no_inline', value: true });
  10876. }
  10877. if (parser.match('{')) {
  10878. const region = {};
  10879. parser.parseRegion(region);
  10880. op.regions.push(region);
  10881. }
  10882. return true;
  10883. }
  10884. };
  10885. mlir.ShapeDialect = class extends mlir.Dialect {
  10886. constructor(operations) {
  10887. super('shape', operations);
  10888. }
  10889. parseType(parser, dialectName) {
  10890. const typeName = parser.parseKeyword();
  10891. if (!typeName) {
  10892. return null;
  10893. }
  10894. let type = `!${dialectName}.${typeName}`;
  10895. if (typeName === 'value' && parser.match('_')) {
  10896. parser.expect('_');
  10897. const subType = parser.expect('id');
  10898. type += `_${subType}`;
  10899. }
  10900. const simpleTypes = ['shape', 'witness', 'size', 'value_shape'];
  10901. if (simpleTypes.includes(type.substring(7))) { // Remove "!shape." prefix
  10902. return new mlir.Type(type);
  10903. }
  10904. return null;
  10905. }
  10906. parseOperation(parser, opName, op) {
  10907. if (opName === 'shape.func') {
  10908. parser.parseFunctionOp(op, false);
  10909. return true;
  10910. }
  10911. if (opName === 'shape.assuming') {
  10912. return this._parseAssumingOp(parser, op);
  10913. }
  10914. if (opName === 'shape.const_shape') {
  10915. return this._parseConstShapeOp(parser, op);
  10916. }
  10917. if (opName === 'shape.reduce') {
  10918. return this._parseReduceOp(parser, op);
  10919. }
  10920. if (opName === 'shape.function_library') {
  10921. return this._parseFunctionLibraryOp(parser, op);
  10922. }
  10923. return super.parseOperation(parser, opName, op);
  10924. }
  10925. _parseAssumingOp(parser, op) {
  10926. if (!parser.match('%')) {
  10927. return false;
  10928. }
  10929. op.operands.push({ value: parser.expect('%') });
  10930. if (parser.accept('->')) {
  10931. const types = parser.parseFunctionResultTypes();
  10932. parser.resolveOperands(op.results, types);
  10933. }
  10934. if (parser.match('{')) {
  10935. const region = {};
  10936. parser.parseRegion(region);
  10937. op.regions.push(region);
  10938. }
  10939. parser.parseOptionalAttrDict(op.attributes);
  10940. return true;
  10941. }
  10942. _parseConstShapeOp(parser, op) {
  10943. parser.parseOptionalAttrDict(op.attributes);
  10944. const extents = parser.parseAttribute();
  10945. op.attributes.push({ name: 'shape', value: extents });
  10946. if (parser.accept(':')) {
  10947. const type = parser.parseType();
  10948. op.results.push({ type });
  10949. }
  10950. return true;
  10951. }
  10952. _parseReduceOp(parser, op) {
  10953. if (!parser.match('(')) {
  10954. return false;
  10955. }
  10956. parser.accept('(');
  10957. while (parser.match('%')) {
  10958. op.operands.push({ value: parser.expect('%') });
  10959. if (!parser.accept(',')) {
  10960. break;
  10961. }
  10962. }
  10963. parser.accept(')');
  10964. if (parser.accept(':')) {
  10965. const shapeType = parser.parseType();
  10966. if (op.operands.length > 0) {
  10967. op.operands[0].type = shapeType;
  10968. }
  10969. }
  10970. if (parser.accept('->')) {
  10971. const types = parser.parseFunctionResultTypes();
  10972. parser.resolveOperands(op.results, types);
  10973. for (let i = 1; i < op.operands.length && i - 1 < op.results.length; i++) {
  10974. op.operands[i].type = op.results[i - 1].type;
  10975. }
  10976. }
  10977. if (parser.match('{')) {
  10978. const region = {};
  10979. parser.parseRegion(region);
  10980. op.regions.push(region);
  10981. }
  10982. parser.parseOptionalAttrDict(op.attributes);
  10983. return true;
  10984. }
  10985. _parseFunctionLibraryOp(parser, op) {
  10986. parser.parseSymbolName('sym_name', op.attributes);
  10987. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  10988. if (parser.match('{')) {
  10989. const region = {};
  10990. parser.parseRegion(region);
  10991. op.regions.push(region);
  10992. }
  10993. return true;
  10994. }
  10995. };
  10996. mlir.SparseTensorDialect = class extends mlir.Dialect {
  10997. constructor(operations) {
  10998. super('sparse_tensor', operations);
  10999. this.registerCustomDirective('LevelRange', this._parseLevelRange.bind(this));
  11000. }
  11001. _parseLevelRange(parser, op, args) {
  11002. const start = parser.parseInteger();
  11003. parser.expect('id', 'to');
  11004. const end = parser.parseInteger();
  11005. if (args && args.length >= 2) {
  11006. const startAttr = args[0].replace('$', '');
  11007. const endAttr = args[1].replace('$', '');
  11008. op.attributes.push({ name: startAttr, value: start });
  11009. op.attributes.push({ name: endAttr, value: end });
  11010. }
  11011. }
  11012. parseOperation(parser, opName, op) {
  11013. if (opName === 'sparse_tensor.iterate') {
  11014. return this._parseIterateOp(parser, op);
  11015. }
  11016. if (opName === 'sparse_tensor.coiterate') {
  11017. return this._parseCoIterateOp(parser, op);
  11018. }
  11019. return super.parseOperation(parser, opName, op);
  11020. }
  11021. _parseIterateOp(parser, op) {
  11022. if (!parser.match('%')) {
  11023. return false;
  11024. }
  11025. parser.expect('%');
  11026. if (!parser.accept('id', 'in')) {
  11027. return false;
  11028. }
  11029. if (!parser.match('%')) {
  11030. return false;
  11031. }
  11032. op.operands.push({ value: parser.expect('%') });
  11033. if (parser.accept('id', 'at')) {
  11034. parser.accept('(');
  11035. while (parser.match('%') || parser.match('id')) {
  11036. parser.expect();
  11037. if (!parser.accept(',')) {
  11038. break;
  11039. }
  11040. }
  11041. parser.accept(')');
  11042. }
  11043. if (parser.accept('id', 'iter_args')) {
  11044. parser.accept('(');
  11045. while (parser.match('%')) {
  11046. op.operands.push({ value: parser.expect('%') });
  11047. if (parser.accept('=')) {
  11048. parser.expect('%');
  11049. }
  11050. if (!parser.accept(',')) {
  11051. break;
  11052. }
  11053. }
  11054. parser.accept(')');
  11055. }
  11056. if (parser.accept(':')) {
  11057. parser.parseType();
  11058. }
  11059. if (parser.accept('->')) {
  11060. const types = parser.parseFunctionResultTypes();
  11061. parser.resolveOperands(op.results, types);
  11062. }
  11063. if (parser.match('{')) {
  11064. const region = {};
  11065. parser.parseRegion(region);
  11066. op.regions.push(region);
  11067. }
  11068. parser.parseOptionalAttrDict(op.attributes);
  11069. return true;
  11070. }
  11071. _parseCoIterateOp(parser, op) {
  11072. if (!parser.accept('(')) {
  11073. return false;
  11074. }
  11075. while (parser.match('%')) {
  11076. op.operands.push({ value: parser.expect('%') });
  11077. if (!parser.accept(',')) {
  11078. break;
  11079. }
  11080. }
  11081. parser.accept(')');
  11082. if (parser.accept('id', 'at')) {
  11083. parser.accept('(');
  11084. while (parser.match('%') || parser.match('id')) {
  11085. parser.expect();
  11086. if (!parser.accept(',')) {
  11087. break;
  11088. }
  11089. }
  11090. parser.accept(')');
  11091. }
  11092. if (parser.accept('id', 'iter_args')) {
  11093. parser.accept('(');
  11094. while (parser.match('%')) {
  11095. op.operands.push({ value: parser.expect('%') });
  11096. if (parser.accept('=')) {
  11097. parser.expect('%');
  11098. }
  11099. if (!parser.accept(',')) {
  11100. break;
  11101. }
  11102. }
  11103. parser.accept(')');
  11104. }
  11105. if (parser.accept(':')) {
  11106. parser.accept('(');
  11107. while (!parser.match(')')) {
  11108. parser.parseType();
  11109. if (!parser.accept(',')) {
  11110. break;
  11111. }
  11112. }
  11113. parser.accept(')');
  11114. }
  11115. if (parser.accept('->')) {
  11116. const types = parser.parseFunctionResultTypes();
  11117. parser.resolveOperands(op.results, types);
  11118. }
  11119. while (parser.accept('id', 'case')) {
  11120. while (parser.match('%') || parser.match('id')) {
  11121. parser.expect();
  11122. if (!parser.accept(',')) {
  11123. break;
  11124. }
  11125. }
  11126. if (parser.match('{')) {
  11127. const region = {};
  11128. parser.parseRegion(region);
  11129. op.regions.push(region);
  11130. }
  11131. }
  11132. parser.parseOptionalAttrDict(op.attributes);
  11133. return true;
  11134. }
  11135. };
  11136. mlir.FuncDialect = class extends mlir.Dialect {
  11137. constructor(operations) {
  11138. super('func', operations);
  11139. }
  11140. parseOperation(parser, opName, op) {
  11141. if (opName === 'func.func') {
  11142. parser.parseFunctionOp(op, false);
  11143. return true;
  11144. }
  11145. return super.parseOperation(parser, opName, op);
  11146. }
  11147. };
  11148. mlir.GpuDialect = class extends mlir.Dialect {
  11149. constructor(operations) {
  11150. super('gpu', operations);
  11151. this.registerCustomDirective('AllReduceOperation', this._parseAllReduceOperation.bind(this));
  11152. this.registerCustomDirective('LaunchFuncOperands', this._parseLaunchFuncOperands.bind(this));
  11153. this.registerCustomDirective('AsyncDependencies', this._parseAsyncDependencies.bind(this));
  11154. this.registerCustomDirective('LaunchDimType', this._parseLaunchDimType.bind(this));
  11155. this.registerCustomDirective('OffloadingHandler', this._parseOffloadingHandler.bind(this));
  11156. }
  11157. _parseAllReduceOperation(parser, op, args) {
  11158. const validOps = ['add', 'mul', 'minui', 'minsi', 'minnumf', 'maxui', 'maxsi', 'maxnumf', 'and', 'or', 'xor', 'minimumf', 'maximumf'];
  11159. if (parser.match('id')) {
  11160. const opName = parser.getToken().value;
  11161. if (validOps.includes(opName)) {
  11162. parser.expect('id');
  11163. const attrName = args && args.length > 0 ? args[0].replace(/^\$/, '') : 'op';
  11164. op.attributes.push({ name: attrName, value: opName });
  11165. }
  11166. }
  11167. }
  11168. _parseLaunchDimType(parser, op, args) {
  11169. if (parser.accept(':')) {
  11170. const dimType = parser.parseType();
  11171. if (args && args.length > 0) {
  11172. for (const result of op.results) {
  11173. if (!result.type) {
  11174. result.type = dimType;
  11175. break;
  11176. }
  11177. }
  11178. if (args.length >= 4) {
  11179. for (let i = 2; i < 5 && i < args.length; i++) {
  11180. const clusterTypeArgName = args[i].replace(/^\$/, '');
  11181. op.attributes.push({ name: clusterTypeArgName, value: dimType });
  11182. }
  11183. }
  11184. }
  11185. }
  11186. }
  11187. parseOperation(parser, opName, op) {
  11188. if (opName === 'gpu.func') {
  11189. parser.parseOptionalVisibilityKeyword(op.attributes);
  11190. parser.parseSymbolName('sym_name', op.attributes);
  11191. const sig = parser.parseFunctionSignatureWithArguments(false);
  11192. const argTypes = sig.arguments.map((a) => a.type);
  11193. const type = { inputs: argTypes, results: sig.resultTypes };
  11194. op.attributes.push({ name: 'function_type', value: type });
  11195. if (parser.match('id', 'kernel')) {
  11196. parser.expect();
  11197. op.attributes.push({ name: 'gpu.kernel', value: true });
  11198. }
  11199. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  11200. if (parser.match('{')) {
  11201. const region = {};
  11202. parser.parseRegion(region, sig.arguments);
  11203. op.regions.push(region);
  11204. }
  11205. return true;
  11206. }
  11207. if (opName === 'gpu.launch') {
  11208. if (parser.accept('id', 'async')) {
  11209. if (op.results.length === 0) {
  11210. throw new mlir.Error(`Operation '${opName}' needs to be named when marked 'async' ${parser.location()}`);
  11211. }
  11212. op.results[0].type = 'gpu.async.token';
  11213. }
  11214. // Reference: GPUDialect.cpp:500 parseAsyncDependencies uses parseOperandList
  11215. const asyncDeps = parser.parseOperandList('optionalSquare');
  11216. op.operands.push(...asyncDeps);
  11217. if (parser.accept('id', 'clusters')) {
  11218. this._parseSizeAssignment(parser, op);
  11219. parser.expect('id', 'in');
  11220. this._parseSizeAssignment(parser, op);
  11221. }
  11222. parser.expect('id', 'blocks');
  11223. this._parseSizeAssignment(parser, op);
  11224. parser.expect('id', 'in');
  11225. this._parseSizeAssignment(parser, op);
  11226. parser.expect('id', 'threads');
  11227. this._parseSizeAssignment(parser, op);
  11228. parser.expect('id', 'in');
  11229. this._parseSizeAssignment(parser, op);
  11230. if (parser.accept('id', 'dynamic_shared_memory_size')) {
  11231. const operand = {};
  11232. operand.value = parser.expect('%');
  11233. operand.name = 'dynamic_shared_memory_size';
  11234. op.operands.push(operand);
  11235. }
  11236. if (parser.accept('id', 'module')) {
  11237. parser.expect('(');
  11238. const moduleSymbol = parser.expect('@');
  11239. op.attributes.push({ name: 'module', value: moduleSymbol });
  11240. parser.expect(')');
  11241. }
  11242. if (parser.accept('id', 'function')) {
  11243. parser.expect('(');
  11244. const funcSymbol = parser.expect('@');
  11245. op.attributes.push({ name: 'function', value: funcSymbol });
  11246. parser.expect(')');
  11247. }
  11248. if (parser.accept('id', 'workgroup')) {
  11249. parser.expect('(');
  11250. while (!parser.match(')')) {
  11251. parser.expect('%');
  11252. parser.expect(':');
  11253. parser.parseType();
  11254. if (!parser.accept(',')) {
  11255. break;
  11256. }
  11257. }
  11258. parser.expect(')');
  11259. }
  11260. if (parser.accept('id', 'private')) {
  11261. parser.expect('(');
  11262. while (!parser.match(')')) {
  11263. parser.expect('%');
  11264. parser.expect(':');
  11265. parser.parseType();
  11266. if (!parser.accept(',')) {
  11267. break;
  11268. }
  11269. }
  11270. parser.expect(')');
  11271. }
  11272. if (parser.match('{')) {
  11273. const region = {};
  11274. parser.parseRegion(region);
  11275. op.regions.push(region);
  11276. }
  11277. parser.parseOptionalAttrDict(op.attributes);
  11278. return true;
  11279. }
  11280. if (opName === 'gpu.warp_execute_on_lane_0') {
  11281. return this._parseWarpExecuteOnLane0Op(parser, op);
  11282. }
  11283. return super.parseOperation(parser, opName, op);
  11284. }
  11285. _parseWarpExecuteOnLane0Op(parser, op) {
  11286. parser.expect('(');
  11287. const laneId = parser.expect('%');
  11288. op.operands.push(laneId);
  11289. parser.expect(')');
  11290. parser.expect('[');
  11291. const warpSize = parser.expect('int');
  11292. op.attributes.push({ name: 'warp_size', value: parseInt(warpSize, 10) });
  11293. parser.expect(']');
  11294. if (parser.accept('id', 'args')) {
  11295. parser.expect('(');
  11296. op.operands.push(...parser.parseArguments());
  11297. if (parser.accept(':')) {
  11298. const types = parser.parseTypeListNoParens();
  11299. parser.resolveOperands(op.operands.slice(1), types);
  11300. }
  11301. parser.expect(')');
  11302. }
  11303. // Reference: parseOptionalArrowTypeList uses parseFunctionResultTypes which handles (type, type) and single type
  11304. if (parser.accept('->')) {
  11305. const types = parser.parseFunctionResultTypes();
  11306. if (op.results.length > 0) {
  11307. parser.resolveOperands(op.results, types);
  11308. } else {
  11309. for (const type of types) {
  11310. op.results.push({ type });
  11311. }
  11312. }
  11313. }
  11314. if (parser.match('{')) {
  11315. const region = {};
  11316. parser.parseRegion(region);
  11317. op.regions.push(region);
  11318. }
  11319. parser.parseOptionalAttrDict(op.attributes);
  11320. return true;
  11321. }
  11322. _parseSizeAssignment(parser, op) {
  11323. // Parse: (%id, %id, %id) or (%id = %val, %id = %val, %id = %val)
  11324. parser.expect('(');
  11325. while (!parser.match(')')) {
  11326. if (parser.match('%')) {
  11327. parser.expect('%');
  11328. if (parser.accept('=')) {
  11329. const operand = {};
  11330. operand.value = parser.expect('%');
  11331. op.operands.push(operand);
  11332. }
  11333. if (!parser.accept(',')) {
  11334. break;
  11335. }
  11336. } else {
  11337. break;
  11338. }
  11339. }
  11340. parser.expect(')');
  11341. }
  11342. _parseLaunchFuncOperands(parser, op /*, args */) {
  11343. if (parser.match('id', 'args')) {
  11344. parser.expect();
  11345. parser.expect('(');
  11346. while (!parser.match(')')) {
  11347. const value = parser.expect('%');
  11348. parser.expect(':');
  11349. const type = parser.parseType();
  11350. op.operands.push({ value, type });
  11351. if (!parser.match(')')) {
  11352. parser.expect(',');
  11353. }
  11354. }
  11355. parser.expect(')');
  11356. }
  11357. }
  11358. _parseAsyncDependencies(parser /*, op, args */) {
  11359. parser.accept('id', 'async');
  11360. if (parser.match('[')) {
  11361. parser.skip('[', ']');
  11362. }
  11363. }
  11364. _parseOffloadingHandler(parser /*, op, args */) {
  11365. if (parser.accept('<')) {
  11366. parser.parseAttribute();
  11367. parser.expect('>');
  11368. }
  11369. }
  11370. };
  11371. mlir.ArmSMEDialect = class extends mlir.Dialect {
  11372. constructor(operations) {
  11373. super('arm_sme', operations);
  11374. this.registerCustomAttribute('ArmSME_TypeSizeAttr', this._parseEnumFlagsAngleBracketComma.bind(this));
  11375. this.registerCustomAttribute('ArmSME_TileSliceLayoutAttr', this._parseEnumFlagsAngleBracketComma.bind(this));
  11376. this.registerCustomAttribute('ArmSME_CombiningKindAttr', this._parseEnumFlagsAngleBracketComma.bind(this));
  11377. }
  11378. };
  11379. mlir.ArmNeonDialect = class extends mlir.Dialect {
  11380. constructor(operations) {
  11381. super('arm_neon', operations);
  11382. }
  11383. };
  11384. mlir.ArmSVEDialect = class extends mlir.Dialect {
  11385. constructor(operations) {
  11386. super('arm_sve', operations);
  11387. }
  11388. };
  11389. mlir.AMDGPUDialect = class extends mlir.Dialect {
  11390. constructor(operations) {
  11391. super('amdgpu', operations);
  11392. this.registerCustomDirective('MNKDimensionList', this._parseMNKDimensionList.bind(this));
  11393. }
  11394. _parseMNKDimensionList(parser, op, args) {
  11395. // Reference: TypeParser.cpp parseDimensionListRanked with allowDynamic=false, withTrailingX=false
  11396. const dimInfo = parser.parseDimensionListRanked(false, false);
  11397. const dims = dimInfo.dimensions;
  11398. if (dims.length >= 3 && args && args.length >= 3) {
  11399. const mAttr = args[0].replace('$', '');
  11400. const nAttr = args[1].replace('$', '');
  11401. const kAttr = args[2].replace('$', '');
  11402. op.attributes.push({ name: mAttr, value: dims[0] });
  11403. op.attributes.push({ name: nAttr, value: dims[1] });
  11404. op.attributes.push({ name: kAttr, value: dims[2] });
  11405. }
  11406. }
  11407. };
  11408. mlir.NVGPUDialect = class extends mlir.Dialect {
  11409. constructor(operations) {
  11410. super('nvgpu', operations);
  11411. this.registerCustomType('NVGPU_TensorMapDescriptor', this._parseTensorMapDescriptor.bind(this));
  11412. this.registerCustomType('NVGPU_WarpgroupAccumulator', this._parseWarpgroupAccumulator.bind(this));
  11413. this.registerCustomType('NVGPU_WarpgroupMatrixDescriptor', this._parseWarpgroupMatrixDescriptor.bind(this));
  11414. this.registerCustomType('NVGPU_MBarrierGroup', this._parseMBarrierGroup.bind(this));
  11415. }
  11416. _parseTensorMapDescriptor(parser) {
  11417. if (parser.match('<')) {
  11418. const content = parser.skip('<', '>');
  11419. return new mlir.Type(`!nvgpu.tensormap.descriptor${content}`);
  11420. }
  11421. return null;
  11422. }
  11423. _parseWarpgroupAccumulator(parser) {
  11424. if (parser.match('<')) {
  11425. const content = parser.skip('<', '>');
  11426. return new mlir.Type(`!nvgpu.warpgroup.accumulator${content}`);
  11427. }
  11428. return null;
  11429. }
  11430. _parseWarpgroupMatrixDescriptor(parser) {
  11431. if (parser.match('<')) {
  11432. const content = parser.skip('<', '>');
  11433. return new mlir.Type(`!nvgpu.warpgroup.descriptor${content}`);
  11434. }
  11435. return null;
  11436. }
  11437. _parseMBarrierGroup(parser) {
  11438. if (parser.match('<')) {
  11439. const content = parser.skip('<', '>');
  11440. return new mlir.Type(`!nvgpu.mbarrier.barrier${content}`);
  11441. }
  11442. return null;
  11443. }
  11444. };
  11445. mlir.NVVMDialect = class extends mlir.Dialect {
  11446. constructor(operations) {
  11447. super('nvvm', operations);
  11448. }
  11449. };
  11450. mlir.OpenMPDialect = class extends mlir.Dialect {
  11451. constructor(operations) {
  11452. super('omp', operations);
  11453. this.registerCustomDirective('MapClause', this._parseMapClause.bind(this));
  11454. this.registerCustomDirective('CaptureType', this._parseCaptureType.bind(this));
  11455. this.registerCustomDirective('MembersIndex', this._parseMembersIndex.bind(this));
  11456. this.registerCustomDirective('PrivateReductionRegion', this._parsePrivateReductionRegion.bind(this));
  11457. this.registerCustomDirective('PrivateRegion', this._parsePrivateReductionRegion.bind(this));
  11458. this.registerCustomDirective('InReductionPrivateRegion', this._parsePrivateReductionRegion.bind(this));
  11459. this.registerCustomDirective('InReductionPrivateReductionRegion', this._parsePrivateReductionRegion.bind(this));
  11460. this.registerCustomDirective('TaskReductionRegion', this._parsePrivateReductionRegion.bind(this));
  11461. this.registerCustomDirective('UseDeviceAddrUseDevicePtrRegion', this._parsePrivateReductionRegion.bind(this));
  11462. this.registerCustomDirective('TargetOpRegion', this._parseTargetOpRegion.bind(this));
  11463. this.registerCustomDirective('ClauseAttr', this._parseClauseAttr.bind(this));
  11464. this.registerCustomAttribute('DataSharingClauseTypeAttr', this._parseDataSharingClauseTypeAttr.bind(this));
  11465. }
  11466. parseOperation(parser, opName, op) {
  11467. if (opName === 'omp.loop_nest') {
  11468. return this._parseLoopNestOp(parser, op);
  11469. }
  11470. if (opName === 'omp.canonical_loop') {
  11471. return this._parseCanonicalLoopOp(parser, op);
  11472. }
  11473. if (opName === 'omp.unroll_heuristic') {
  11474. return this._parseUnrollHeuristicOp(parser, op);
  11475. }
  11476. return super.parseOperation(parser, opName, op);
  11477. }
  11478. _parseClauseAttr(parser /*, op, args */) {
  11479. if (parser.match('{')) {
  11480. parser.skip('{', '}');
  11481. }
  11482. }
  11483. _parseTargetOpRegion(parser, op, args) {
  11484. const unitAttrKeywords = ['nowait', 'bare'];
  11485. for (const kw of unitAttrKeywords) {
  11486. if (parser.accept('id', kw)) {
  11487. op.attributes.push({ name: kw, value: true });
  11488. }
  11489. }
  11490. if (parser.accept('id', 'depend')) {
  11491. parser.skip('(', ')');
  11492. }
  11493. const singleValueKeywords = ['device', 'if', 'thread_limit'];
  11494. for (const kw of singleValueKeywords) {
  11495. if (parser.accept('id', kw)) {
  11496. parser.expect('(');
  11497. if (parser.match('%')) {
  11498. const operand = parser.expect('%');
  11499. op.operands.push({ name: kw, value: operand });
  11500. }
  11501. if (parser.accept(':')) {
  11502. parser.parseType();
  11503. }
  11504. parser.expect(')');
  11505. }
  11506. }
  11507. if (parser.accept('id', 'is_device_ptr')) {
  11508. parser.expect('(');
  11509. while (!parser.match(')') && !parser.match(':')) {
  11510. if (parser.match('%')) {
  11511. parser.expect('%');
  11512. }
  11513. if (!parser.accept(',')) {
  11514. break;
  11515. }
  11516. }
  11517. if (parser.accept(':')) {
  11518. while (!parser.match(')')) {
  11519. parser.parseType();
  11520. if (!parser.accept(',')) {
  11521. break;
  11522. }
  11523. }
  11524. }
  11525. parser.expect(')');
  11526. }
  11527. const keywords = ['has_device_addr', 'host_eval', 'in_reduction', 'map_entries', 'private', 'reduction', 'task_reduction', 'use_device_addr', 'use_device_ptr'];
  11528. while (keywords.some((kw) => parser.match('id', kw))) {
  11529. parser.expect('id');
  11530. if (parser.accept('(')) {
  11531. while (!parser.match(')') && !parser.match(':')) {
  11532. parser.accept('id', 'byref');
  11533. if (parser.match('@')) {
  11534. parser.expect('@');
  11535. }
  11536. if (parser.match('%')) {
  11537. parser.expect('%');
  11538. }
  11539. if (parser.accept('->')) {
  11540. if (parser.match('%')) {
  11541. parser.expect('%');
  11542. }
  11543. }
  11544. if (parser.accept('[')) {
  11545. parser.expect('id', 'map_idx');
  11546. parser.expect('=');
  11547. parser.expect('int');
  11548. parser.expect(']');
  11549. }
  11550. if (!parser.accept(',') || parser.match(':')) {
  11551. break;
  11552. }
  11553. }
  11554. if (parser.accept(':')) {
  11555. while (!parser.match(')')) {
  11556. parser.parseType();
  11557. if (!parser.accept(',')) {
  11558. break;
  11559. }
  11560. }
  11561. }
  11562. parser.expect(')');
  11563. }
  11564. }
  11565. if (parser.accept('id', 'private_barrier')) {
  11566. op.attributes.push({ name: 'private_needs_barrier', value: true });
  11567. }
  11568. if (!parser.match('{')) {
  11569. return;
  11570. }
  11571. const region = {};
  11572. parser.parseRegion(region);
  11573. if (args && args.length > 0) {
  11574. const regionArgName = args[0].replace(/^\$/, '');
  11575. if (regionArgName === 'region') {
  11576. op.regions.push(region);
  11577. }
  11578. } else {
  11579. op.regions.push(region);
  11580. }
  11581. }
  11582. _parseMapClause(parser, op, args) {
  11583. const mapFlags = [];
  11584. do {
  11585. if (parser.match('id')) {
  11586. const flag = parser.expect('id');
  11587. mapFlags.push(flag);
  11588. }
  11589. } while (parser.accept(','));
  11590. if (args && args.length > 0) {
  11591. const attrName = args[0].replace(/^\$/, '');
  11592. op.attributes.push({ name: attrName, value: mapFlags.join(', ') });
  11593. }
  11594. }
  11595. _parseCaptureType(parser, op, args) {
  11596. if (parser.match('id')) {
  11597. const captureType = parser.expect('id');
  11598. if (args && args.length > 0) {
  11599. const attrName = args[0].replace(/^\$/, '');
  11600. op.attributes.push({ name: attrName, value: captureType });
  11601. }
  11602. }
  11603. }
  11604. _parseMembersIndex(parser, op, args) {
  11605. const memberIndices = [];
  11606. do {
  11607. if (parser.accept('[')) {
  11608. const indices = [];
  11609. do {
  11610. if (parser.match('int')) {
  11611. const idx = parser.expect('int');
  11612. indices.push(idx);
  11613. }
  11614. } while (parser.accept(','));
  11615. parser.expect(']');
  11616. memberIndices.push(indices);
  11617. }
  11618. } while (parser.accept(','));
  11619. if (args && args.length > 0 && memberIndices.length > 0) {
  11620. const attrName = args[0].replace(/^\$/, '');
  11621. op.attributes.push({ name: attrName, value: memberIndices });
  11622. }
  11623. }
  11624. _parsePrivateReductionRegion(parser, op, args) {
  11625. // Parse optional clauses that appear before the region (oilist in assembly format)
  11626. // Reference: OpenMPOpBase.td clausesAssemblyFormat
  11627. const singleValueClauses = ['if', 'num_threads', 'thread_limit', 'device', 'safelen', 'simdlen', 'priority', 'grainsize', 'num_tasks', 'final', 'filter'];
  11628. const enumClauses = ['proc_bind', 'order', 'schedule', 'dist_schedule', 'memory_order', 'hint'];
  11629. const listClauses = ['private', 'reduction', 'in_reduction', 'task_reduction', 'copyin', 'copyprivate', 'firstprivate', 'lastprivate', 'shared', 'linear', 'aligned', 'nontemporal', 'inclusive', 'exclusive', 'allocate', 'depend'];
  11630. const unitClauses = ['nowait', 'untied', 'mergeable', 'nogroup', 'simd', 'threads', 'seq_cst', 'acq_rel', 'acquire', 'release', 'relaxed'];
  11631. let progress = true;
  11632. while (progress) {
  11633. progress = false;
  11634. // Handle single-value clauses: keyword(value : type)
  11635. for (const kw of singleValueClauses) {
  11636. if (parser.accept('id', kw)) {
  11637. progress = true;
  11638. parser.expect('(');
  11639. if (parser.match('%')) {
  11640. const operand = parser.expect('%');
  11641. op.operands.push({ name: kw, value: operand });
  11642. } else if (parser.match('int')) {
  11643. const value = parser.expect('int');
  11644. op.attributes.push({ name: kw, value });
  11645. }
  11646. if (parser.accept(':')) {
  11647. parser.parseType();
  11648. }
  11649. parser.expect(')');
  11650. }
  11651. }
  11652. // Handle enum clauses: keyword(enum_value)
  11653. for (const kw of enumClauses) {
  11654. if (parser.accept('id', kw)) {
  11655. progress = true;
  11656. parser.expect('(');
  11657. const value = parser.expect('id');
  11658. op.attributes.push({ name: kw, value });
  11659. // Handle modifier syntax like schedule(static, value)
  11660. while (parser.accept(',')) {
  11661. if (parser.match('%')) {
  11662. const operand = parser.expect('%');
  11663. op.operands.push({ name: `${kw}_operand`, value: operand });
  11664. } else if (parser.match('id')) {
  11665. parser.expect('id');
  11666. }
  11667. if (parser.accept(':')) {
  11668. parser.parseType();
  11669. }
  11670. }
  11671. parser.expect(')');
  11672. }
  11673. }
  11674. // Handle list clauses: keyword(syms %vals -> %new_vals : types) or keyword(@sym %val : type, ...)
  11675. for (const kw of listClauses) {
  11676. if (parser.accept('id', kw)) {
  11677. progress = true;
  11678. if (parser.accept('(')) {
  11679. if (parser.accept('id', 'mod')) {
  11680. parser.expect(':');
  11681. parser.expect('id');
  11682. parser.expect(',');
  11683. }
  11684. while (!parser.match(')') && !parser.match(':')) {
  11685. parser.accept('id', 'byref');
  11686. if (parser.match('@')) {
  11687. parser.expect('@');
  11688. }
  11689. if (parser.match('%')) {
  11690. const operand = parser.expect('%');
  11691. op.operands.push({ name: kw, value: operand });
  11692. }
  11693. if (parser.accept('->')) {
  11694. if (parser.match('%')) {
  11695. parser.expect('%');
  11696. }
  11697. }
  11698. if (parser.accept('[')) {
  11699. parser.expect('id', 'map_idx');
  11700. parser.expect('=');
  11701. parser.expect('int');
  11702. parser.expect(']');
  11703. }
  11704. if (!parser.accept(',') || parser.match(':')) {
  11705. break;
  11706. }
  11707. }
  11708. if (parser.accept(':')) {
  11709. while (!parser.match(')')) {
  11710. parser.parseType();
  11711. if (!parser.accept(',')) {
  11712. break;
  11713. }
  11714. }
  11715. }
  11716. parser.expect(')');
  11717. }
  11718. }
  11719. }
  11720. // Handle unit clauses (boolean flags)
  11721. for (const kw of unitClauses) {
  11722. if (parser.accept('id', kw)) {
  11723. progress = true;
  11724. op.attributes.push({ name: kw, value: true });
  11725. }
  11726. }
  11727. // Handle map_entries clause: map_entries(%vars : types)
  11728. if (parser.accept('id', 'map_entries')) {
  11729. progress = true;
  11730. parser.expect('(');
  11731. while (!parser.match(')') && !parser.match(':')) {
  11732. if (parser.match('%')) {
  11733. const operand = parser.expect('%');
  11734. op.operands.push({ name: 'map_vars', value: operand });
  11735. }
  11736. if (!parser.accept(',') || parser.match(':')) {
  11737. break;
  11738. }
  11739. }
  11740. if (parser.accept(':')) {
  11741. while (!parser.match(')')) {
  11742. parser.parseType();
  11743. if (!parser.accept(',')) {
  11744. break;
  11745. }
  11746. }
  11747. }
  11748. parser.expect(')');
  11749. }
  11750. // Handle num_teams clause: num_teams(lower : type to upper : type) or num_teams(to upper : type)
  11751. if (parser.accept('id', 'num_teams')) {
  11752. progress = true;
  11753. parser.expect('(');
  11754. if (parser.accept('id', 'to')) {
  11755. if (parser.match('%')) {
  11756. const upper = parser.expect('%');
  11757. op.operands.push({ name: 'num_teams_upper', value: upper });
  11758. }
  11759. if (parser.accept(':')) {
  11760. parser.parseType();
  11761. }
  11762. } else if (parser.match('%')) {
  11763. const lower = parser.expect('%');
  11764. op.operands.push({ name: 'num_teams_lower', value: lower });
  11765. if (parser.accept(':')) {
  11766. parser.parseType();
  11767. }
  11768. parser.expect('id', 'to');
  11769. if (parser.match('%')) {
  11770. const upper = parser.expect('%');
  11771. op.operands.push({ name: 'num_teams_upper', value: upper });
  11772. }
  11773. if (parser.accept(':')) {
  11774. parser.parseType();
  11775. }
  11776. }
  11777. parser.expect(')');
  11778. }
  11779. // Handle use_device_addr/use_device_ptr clauses: keyword(%var -> %arg : type, ...)
  11780. for (const kw of ['use_device_addr', 'use_device_ptr', 'has_device_addr', 'host_eval']) {
  11781. if (parser.accept('id', kw)) {
  11782. progress = true;
  11783. parser.expect('(');
  11784. while (!parser.match(')') && !parser.match(':')) {
  11785. if (parser.match('%')) {
  11786. const operand = parser.expect('%');
  11787. op.operands.push({ name: kw, value: operand });
  11788. }
  11789. if (parser.accept('->')) {
  11790. if (parser.match('%')) {
  11791. parser.expect('%');
  11792. }
  11793. }
  11794. if (!parser.accept(',') || parser.match(':')) {
  11795. break;
  11796. }
  11797. }
  11798. if (parser.accept(':')) {
  11799. while (!parser.match(')')) {
  11800. parser.parseType();
  11801. if (!parser.accept(',')) {
  11802. break;
  11803. }
  11804. }
  11805. }
  11806. parser.expect(')');
  11807. }
  11808. }
  11809. }
  11810. if (parser.accept('id', 'private_barrier')) {
  11811. op.attributes.push({ name: 'private_needs_barrier', value: true });
  11812. }
  11813. if (parser.match('{')) {
  11814. const region = {};
  11815. parser.parseRegion(region);
  11816. if (args && args.length > 0) {
  11817. const regionArgName = args[0].replace(/^\$/, '');
  11818. if (regionArgName === 'region') {
  11819. op.regions.push(region);
  11820. }
  11821. } else {
  11822. op.regions.push(region);
  11823. }
  11824. }
  11825. }
  11826. _parseCanonicalLoopOp(parser, op) {
  11827. if (parser.accept('(')) {
  11828. const cliOperand = parser.expect('%');
  11829. op.operands.push(cliOperand);
  11830. parser.expect(')');
  11831. }
  11832. const inductionVar = parser.expect('%');
  11833. parser.expect(':');
  11834. const ivType = parser.parseType();
  11835. parser.expect('id', 'in');
  11836. parser.expect('id', 'range');
  11837. parser.expect('(');
  11838. parser.expect('%');
  11839. parser.expect(')');
  11840. if (parser.match('{')) {
  11841. const region = {};
  11842. parser.parseRegion(region);
  11843. if (region.blocks && region.blocks.length > 0) {
  11844. if (!region.blocks[0].arguments) {
  11845. region.blocks[0].arguments = [];
  11846. }
  11847. region.blocks[0].arguments.push({ value: inductionVar, type: ivType });
  11848. }
  11849. op.regions.push(region);
  11850. }
  11851. parser.parseOptionalAttrDict(op.attributes);
  11852. return true;
  11853. }
  11854. _parseUnrollHeuristicOp(parser, op) {
  11855. parser.expect('(');
  11856. const applyee = parser.expect('%');
  11857. op.operands.push(applyee);
  11858. parser.expect(')');
  11859. if (parser.accept('->')) {
  11860. parser.expect('(');
  11861. parser.expect(')');
  11862. }
  11863. parser.parseOptionalAttrDict(op.attributes);
  11864. return true;
  11865. }
  11866. _parseLoopNestOp(parser, op) {
  11867. if (parser.accept('(')) {
  11868. while (!parser.match(')')) {
  11869. parser.expect('%');
  11870. if (!parser.accept(',')) {
  11871. break;
  11872. }
  11873. }
  11874. parser.expect(')');
  11875. }
  11876. if (parser.accept(':')) {
  11877. while (!parser.match('=')) {
  11878. parser.parseType();
  11879. if (!parser.accept(',')) {
  11880. break;
  11881. }
  11882. }
  11883. }
  11884. if (parser.accept('=')) {
  11885. if (parser.accept('(')) {
  11886. op.operands = parser.parseArguments();
  11887. parser.expect(')');
  11888. }
  11889. if (parser.accept('id', 'to')) {
  11890. if (parser.accept('(')) {
  11891. while (!parser.match(')')) {
  11892. parser.expect('%');
  11893. if (!parser.accept(',')) {
  11894. break;
  11895. }
  11896. }
  11897. parser.expect(')');
  11898. }
  11899. }
  11900. parser.accept('id', 'inclusive');
  11901. if (parser.accept('id', 'step')) {
  11902. if (parser.accept('(')) {
  11903. while (!parser.match(')')) {
  11904. parser.expect('%');
  11905. if (!parser.accept(',')) {
  11906. break;
  11907. }
  11908. }
  11909. parser.expect(')');
  11910. }
  11911. }
  11912. }
  11913. // Parse optional 'collapse(N)'
  11914. if (parser.accept('id', 'collapse')) {
  11915. parser.expect('(');
  11916. const value = parser.expect('int');
  11917. op.attributes.push({ name: 'collapse_num_loops', value: parseInt(value, 10) });
  11918. parser.expect(')');
  11919. }
  11920. // Parse optional 'tiles(N, ...)'
  11921. if (parser.accept('id', 'tiles')) {
  11922. parser.expect('(');
  11923. const tiles = [];
  11924. while (!parser.match(')')) {
  11925. tiles.push(parseInt(parser.expect('int'), 10));
  11926. if (!parser.accept(',')) {
  11927. break;
  11928. }
  11929. }
  11930. parser.expect(')');
  11931. op.attributes.push({ name: 'tile_sizes', value: tiles });
  11932. }
  11933. // Parse region BEFORE attr-dict (matches reference impl)
  11934. if (parser.match('{')) {
  11935. const region = {};
  11936. parser.parseRegion(region);
  11937. op.regions.push(region);
  11938. }
  11939. // Parse optional attr-dict AFTER region (matches reference impl)
  11940. parser.parseOptionalAttrDict(op.attributes);
  11941. return true;
  11942. }
  11943. _parseDataSharingClauseTypeAttr(parser) {
  11944. if (parser.accept('{')) {
  11945. parser.expect('id', 'type');
  11946. parser.expect('=');
  11947. const value = parser.expect('id');
  11948. parser.expect('}');
  11949. return { value };
  11950. }
  11951. return null;
  11952. }
  11953. };
  11954. mlir.LLVMDialect = class extends mlir.Dialect {
  11955. constructor(operations) {
  11956. super('llvm', operations);
  11957. this.registerCustomDirective('GEPIndices', this._parseGEPIndices.bind(this));
  11958. this.registerCustomDirective('IndirectBrOpSucessors', this._parseIndirectBrOpSucessors.bind(this));
  11959. this.registerCustomDirective('InsertExtractValueElementType', this._parseInsertExtractValueElementType.bind(this));
  11960. this.registerCustomDirective('LLVMLinkage', this._parseLLVMLinkage.bind(this));
  11961. this.registerCustomDirective('OpBundles', this._parseOpBundles.bind(this));
  11962. this.registerCustomDirective('ShuffleType', this._parseShuffleType.bind(this));
  11963. this.registerCustomDirective('SwitchOpCases', this._parseSwitchOpCases.bind(this));
  11964. this.registerCustomAttribute('LLVM_IntegerOverflowFlagsProp', this._parseLLVMIntegerOverflowFlagsProp.bind(this));
  11965. this.registerCustomAttribute('GEPNoWrapFlagsProp', this._parseGEPNoWrapFlagsProp.bind(this));
  11966. this.registerCustomAttribute('LLVM_BlockAddressAttr', this._parseLLVMBlockAddressAttr.bind(this));
  11967. this.registerCustomAttribute('LLVM_BlockTagAttr', this._parseLLVMBlockTagAttr.bind(this));
  11968. this.registerCustomType('LLVM_AnyPointer', this._parseLLVMPointerType.bind(this));
  11969. this.registerCustomType('LLVM_PointerInAddressSpace', this._parseLLVMPointerType.bind(this));
  11970. }
  11971. _parseLLVMIntegerOverflowFlagsProp(parser) {
  11972. if (parser.accept('id', 'overflow')) {
  11973. return this._parseEnumFlagsAngleBracketComma(parser, { values: ['wrap', 'nuw', 'nsw'] });
  11974. }
  11975. return null;
  11976. }
  11977. _parseGEPNoWrapFlagsProp(parser, type) {
  11978. if (type.values.includes(parser.getToken().value)) {
  11979. return this._parseEnumFlags(parser, type, '|');
  11980. }
  11981. return null;
  11982. }
  11983. _parseLLVMBlockAddressAttr(parser) {
  11984. // Parse: <function = @fn, tag = <id = N>>
  11985. if (!parser.match('<')) {
  11986. return null;
  11987. }
  11988. const content = parser.skip('<', '>');
  11989. return { blockaddress: content };
  11990. }
  11991. _parseLLVMBlockTagAttr(parser) {
  11992. // Parse: <id = N>
  11993. if (!parser.match('<')) {
  11994. return null;
  11995. }
  11996. const content = parser.skip('<', '>');
  11997. return { blocktag: content };
  11998. }
  11999. _parseLLVMPointerType(parser) {
  12000. // Try parsing shorthand syntax first: <addressSpace>
  12001. if (parser.match('<')) {
  12002. const content = parser.skip('<', '>');
  12003. // content includes delimiters like "<1>", extract the inner value
  12004. const inner = content.startsWith('<') && content.endsWith('>') ? content.slice(1, -1) : content;
  12005. // If inner content is a number, it's the address space
  12006. if (/^\d+$/.test(inner)) {
  12007. return new mlir.Type(`!llvm.ptr<${inner}>`);
  12008. }
  12009. // Otherwise, it might be something else - fall through to standard parsing
  12010. }
  12011. // Fall back to standard type parsing (!llvm.ptr or !llvm.ptr<addressSpace>)
  12012. return parser.parseType();
  12013. }
  12014. _parseInsertExtractValueElementType(/* parser, op, args */) {
  12015. }
  12016. _parseLLVMLinkage(parser, op /*, args */) {
  12017. if (parser.match('id')) {
  12018. const linkage = parser.expect('id');
  12019. op.attributes.push({ name: 'linkage', value: linkage });
  12020. }
  12021. }
  12022. _parseOpBundles(parser, op /*, args */) {
  12023. // Parse operation bundles: [] or ["tag"()] or ["tag"(%0, %1 : i32, i32), ...]
  12024. // Returns: null if not present, true if success, throws on failure
  12025. // args[0] = $op_bundle_operands - operands for bundles
  12026. // args[1] = type($op_bundle_operands) - types
  12027. // args[2] = $op_bundle_tags - tags attribute
  12028. // Check if '[' is present - if not, optional is not present
  12029. if (!parser.accept('[')) {
  12030. return null; // Not present (equivalent to std::nullopt)
  12031. }
  12032. // Empty bundle list
  12033. if (parser.accept(']')) {
  12034. return true; // Success
  12035. }
  12036. const opBundles = [];
  12037. do {
  12038. const tag = parser.expect('string');
  12039. parser.expect('(');
  12040. const bundleOperands = [];
  12041. if (!parser.match(')')) {
  12042. do {
  12043. bundleOperands.push(parser.parseAttribute());
  12044. } while (parser.accept(','));
  12045. parser.expect(':');
  12046. // Parse types for bundle operands
  12047. do {
  12048. parser.parseType();
  12049. } while (parser.accept(','));
  12050. }
  12051. parser.expect(')');
  12052. opBundles.push({ tag, operands: bundleOperands });
  12053. } while (parser.accept(','));
  12054. parser.expect(']');
  12055. if (opBundles.length > 0) {
  12056. op.attributes.push({ name: 'op_bundle_tags', value: opBundles });
  12057. }
  12058. return true; // Success
  12059. }
  12060. _parseShuffleType(/* parser, op, args */) {
  12061. // custom<ShuffleType>(ref(type($v1)), type($res), ref($mask))
  12062. // This directive doesn't parse anything - it computes the result type
  12063. // based on the input vector type and mask length.
  12064. // args[0] = ref(type($v1)) - input type
  12065. // args[1] = type($res) - result type to populate
  12066. // args[2] = ref($mask) - mask attribute
  12067. // The result type has the same element type as input, but length = mask.size
  12068. // Since we can't easily compute this in JS without full type info,
  12069. // we do nothing here and let the standard assembly format handle it.
  12070. // The reference impl computes: getVectorType(v1Type.elementType, mask.size())
  12071. }
  12072. // Parse switch operation cases
  12073. // Format: `[` (case (`,` case )* )? `]`
  12074. // Where case: integer `:` bb-id (`(` ssa-use-and-type-list `)`)?
  12075. _parseSwitchOpCases(parser, op /*, args */) {
  12076. // args[0] is ref(type($value)) - the flag type
  12077. // args[1] is $case_values - attribute to populate
  12078. // args[2] is $caseDestinations - successors array
  12079. // args[3] is $caseOperands - operands for each case
  12080. // args[4] is type($caseOperands) - types for case operands
  12081. if (!parser.accept('[')) {
  12082. return;
  12083. }
  12084. // Check for empty case list
  12085. if (parser.accept(']')) {
  12086. return;
  12087. }
  12088. const caseValues = [];
  12089. const caseDestinations = [];
  12090. const caseOperands = [];
  12091. while (!parser.match(']') && !parser.match('eof')) {
  12092. // Handle negative case values: -1, -2, etc.
  12093. let sign = 1;
  12094. if (parser.accept('keyword', '-')) {
  12095. sign = -1;
  12096. }
  12097. if (!parser.match('int') && !parser.match('number')) {
  12098. throw new mlir.Error(`Expected integer case value at ${parser.location()}`);
  12099. }
  12100. const value = sign * parseInt(parser.expect(), 10);
  12101. caseValues.push(value);
  12102. // Parse colon
  12103. parser.expect(':');
  12104. // Parse successor block (starts with ^)
  12105. const successor = parser.expect('^');
  12106. caseDestinations.push(successor);
  12107. // Parse optional operands with types: (%operand : type, ...)
  12108. if (parser.accept('(')) {
  12109. const operands = [];
  12110. while (!parser.match(')') && !parser.match(':') && !parser.match('eof')) {
  12111. if (parser.match('%')) {
  12112. const operand = parser.expect('%');
  12113. operands.push({ name: operand });
  12114. if (!parser.accept(',')) {
  12115. break;
  12116. }
  12117. } else {
  12118. break;
  12119. }
  12120. }
  12121. // Parse types after colon if present
  12122. if (parser.accept(':')) {
  12123. let idx = 0;
  12124. while (!parser.match(')') && idx < operands.length) {
  12125. const type = parser.parseType();
  12126. if (operands[idx]) {
  12127. operands[idx].type = type;
  12128. }
  12129. idx++;
  12130. parser.accept(',');
  12131. }
  12132. }
  12133. parser.expect(')');
  12134. caseOperands.push(operands);
  12135. } else {
  12136. caseOperands.push([]);
  12137. }
  12138. // Check for comma or end of list
  12139. if (!parser.accept(',')) {
  12140. break;
  12141. }
  12142. }
  12143. parser.expect(']');
  12144. // Populate operation with parsed data
  12145. if (caseValues.length > 0) {
  12146. op.attributes.push({
  12147. name: 'case_values',
  12148. value: caseValues
  12149. });
  12150. }
  12151. if (caseDestinations.length > 0) {
  12152. if (!op.successors) {
  12153. op.successors = [];
  12154. }
  12155. // Add case destinations (default destination is already added)
  12156. for (const dest of caseDestinations) {
  12157. op.successors.push({ name: dest });
  12158. }
  12159. }
  12160. // Note: caseOperands handling would require more complex logic
  12161. // to properly associate operands with their successors
  12162. }
  12163. parseType(parser, dialectName) {
  12164. const typeName = parser.parseKeyword();
  12165. if (!typeName) {
  12166. return null;
  12167. }
  12168. let type = `!${dialectName}.${typeName}`;
  12169. if (parser.match('<')) {
  12170. const content = parser.skip('<', '>');
  12171. type += content;
  12172. }
  12173. return new mlir.Type(type);
  12174. }
  12175. parseOperation(parser, opName, op) {
  12176. if (opName === 'llvm.func') {
  12177. return this._parseLLVMFuncOp(parser, op);
  12178. }
  12179. if (opName === 'llvm.mlir.global') {
  12180. return this._parseLLVMGlobalOp(parser, op);
  12181. }
  12182. if (opName === 'llvm.mlir.alias') {
  12183. return this._parseLLVMAliasOp(parser, op);
  12184. }
  12185. if (opName === 'llvm.alloca') {
  12186. return this._parseLLVMAllocaOp(parser, op);
  12187. }
  12188. if (opName === 'llvm.call') {
  12189. return this._parseLLVMCallOp(parser, op);
  12190. }
  12191. if (opName === 'llvm.call_intrinsic') {
  12192. return this._parseLLVMCallIntrinsicOp(parser, op);
  12193. }
  12194. if (opName === 'llvm.invoke') {
  12195. return this._parseLLVMInvokeOp(parser, op);
  12196. }
  12197. if (opName === 'llvm.landingpad') {
  12198. return this._parseLLVMLandingpadOp(parser, op);
  12199. }
  12200. if (opName === 'llvm.icmp' || opName === 'llvm.fcmp') {
  12201. return this._parseLLVMCmpOp(parser, op);
  12202. }
  12203. if (opName.startsWith('llvm.intr.')) {
  12204. // Check if this intrinsic has assembly format - if so, use standard parsing
  12205. if (this.hasAssemblyFormat(opName)) {
  12206. return super.parseOperation(parser, opName, op);
  12207. }
  12208. return this._parseLLVMIntrinsicOp(parser, op);
  12209. }
  12210. return super.parseOperation(parser, opName, op);
  12211. }
  12212. _parseLLVMGlobalOp(parser, op) {
  12213. const linkageKeywords = ['external', 'available_externally', 'linkonce', 'linkonce_odr', 'weak', 'weak_odr', 'appending', 'internal', 'private', 'extern_weak', 'common'];
  12214. if (parser.match('id') && linkageKeywords.includes(parser.getToken().value)) {
  12215. op.attributes.push({ name: 'linkage', value: parser.expect('id') });
  12216. }
  12217. const visibilityKeywords = ['default', 'hidden', 'protected'];
  12218. if (parser.match('id') && visibilityKeywords.includes(parser.getToken().value)) {
  12219. op.attributes.push({ name: 'visibility_', value: parser.expect('id') });
  12220. }
  12221. if (parser.accept('id', 'thread_local')) {
  12222. op.attributes.push({ name: 'thread_local_', value: true });
  12223. }
  12224. const unnamedAddrKeywords = ['unnamed_addr', 'local_unnamed_addr'];
  12225. if (parser.match('id') && unnamedAddrKeywords.includes(parser.getToken().value)) {
  12226. op.attributes.push({ name: 'unnamed_addr', value: parser.expect('id') });
  12227. }
  12228. if (parser.accept('id', 'constant')) {
  12229. op.attributes.push({ name: 'constant', value: true });
  12230. }
  12231. if (parser.match('@')) {
  12232. const symbol = parser.expect('@');
  12233. op.attributes.push({ name: 'sym_name', value: symbol });
  12234. }
  12235. parser.expect('(');
  12236. if (!parser.match(')')) {
  12237. const value = parser.parseAttribute();
  12238. if (parser.accept(':')) {
  12239. parser.parseType();
  12240. }
  12241. op.attributes.push({ name: 'value', value });
  12242. }
  12243. parser.expect(')');
  12244. if (parser.accept('id', 'comdat')) {
  12245. parser.expect('(');
  12246. const comdat = parser.expect('@');
  12247. parser.expect(')');
  12248. op.attributes.push({ name: 'comdat', value: comdat });
  12249. }
  12250. if (parser.match('{')) {
  12251. parser.parseAttributeDict(op.attributes);
  12252. }
  12253. if (parser.accept(':')) {
  12254. const type = parser.parseType();
  12255. op.results = [{ type }];
  12256. }
  12257. if (parser.match('{')) {
  12258. const region = {};
  12259. parser.parseRegion(region);
  12260. op.regions.push(region);
  12261. }
  12262. return true;
  12263. }
  12264. _parseLLVMAliasOp(parser, op) {
  12265. const linkageKeywords = ['external', 'available_externally', 'linkonce', 'linkonce_odr', 'weak', 'weak_odr', 'internal', 'private'];
  12266. if (parser.match('id') && linkageKeywords.includes(parser.getToken().value)) {
  12267. op.attributes.push({ name: 'linkage', value: parser.expect('id') });
  12268. }
  12269. const visibilityKeywords = ['default', 'hidden', 'protected'];
  12270. if (parser.match('id') && visibilityKeywords.includes(parser.getToken().value)) {
  12271. op.attributes.push({ name: 'visibility_', value: parser.expect('id') });
  12272. }
  12273. if (parser.accept('id', 'thread_local')) {
  12274. op.attributes.push({ name: 'thread_local_', value: true });
  12275. }
  12276. const unnamedAddrKeywords = ['unnamed_addr', 'local_unnamed_addr'];
  12277. if (parser.match('id') && unnamedAddrKeywords.includes(parser.getToken().value)) {
  12278. op.attributes.push({ name: 'unnamed_addr', value: parser.expect('id') });
  12279. }
  12280. if (parser.match('@')) {
  12281. const symbol = parser.expect('@');
  12282. op.attributes.push({ name: 'sym_name', value: symbol });
  12283. }
  12284. if (parser.match('{')) {
  12285. parser.parseAttributeDict(op.attributes);
  12286. }
  12287. if (parser.accept(':')) {
  12288. const type = parser.parseType();
  12289. op.attributes.push({ name: 'alias_type', value: type });
  12290. }
  12291. if (parser.match('{')) {
  12292. const region = {};
  12293. parser.parseRegion(region);
  12294. op.regions.push(region);
  12295. }
  12296. return true;
  12297. }
  12298. _parseGEPIndices(parser, op) {
  12299. // Reference: LLVMDialect.cpp:750 parseGEPIndices uses parseCommaSeparatedList
  12300. // Note: the reference uses 'none' delimiter with TableGen handling brackets,
  12301. // but mlir.js expects '[' already consumed and needs to handle ']' terminator
  12302. const rawConstantIndices = [];
  12303. while (!parser.match(']')) {
  12304. if (parser.match('int')) {
  12305. const constIndex = parser.expect('int');
  12306. rawConstantIndices.push(constIndex);
  12307. } else {
  12308. const operand = parser.parseAttribute();
  12309. op.operands.push(operand);
  12310. rawConstantIndices.push(-2147483648);
  12311. }
  12312. parser.accept(',');
  12313. }
  12314. if (rawConstantIndices.length > 0) {
  12315. op.attributes.push({ name: 'rawConstantIndices', value: rawConstantIndices });
  12316. }
  12317. }
  12318. _parseIndirectBrOpSucessors(parser, op /*, args */) {
  12319. parser.expect('[');
  12320. const segmentSizes = [];
  12321. if (!parser.match(']')) {
  12322. do {
  12323. const successor = parser.expect('^');
  12324. if (!op.successors) {
  12325. op.successors = [];
  12326. }
  12327. op.successors.push({ name: successor });
  12328. let operandCount = 0;
  12329. if (parser.accept('(')) {
  12330. if (!parser.match(')')) {
  12331. do {
  12332. const operand = parser.parseAttribute();
  12333. op.operands.push(operand);
  12334. operandCount++;
  12335. parser.accept(':');
  12336. parser.parseType();
  12337. } while (parser.accept(','));
  12338. }
  12339. parser.expect(')');
  12340. }
  12341. segmentSizes.push(operandCount);
  12342. } while (parser.accept(','));
  12343. }
  12344. parser.expect(']');
  12345. if (segmentSizes.length > 0) {
  12346. op.attributes.push({ name: 'indbr_operand_segments', value: segmentSizes });
  12347. }
  12348. }
  12349. _parseLLVMAllocaOp(parser, op) {
  12350. if (parser.accept('id', 'inalloca')) {
  12351. op.attributes.push({ name: 'inalloca', value: true });
  12352. }
  12353. const arraySize = parser.parseAttribute();
  12354. op.operands.push(arraySize);
  12355. parser.expect('id', 'x');
  12356. const elemType = parser.parseType();
  12357. op.attributes.push({ name: 'elem_type', value: elemType });
  12358. if (parser.match('{')) {
  12359. parser.parseAttributeDict(op.attributes);
  12360. }
  12361. // Reference: parseColonTypeList (mandatory)
  12362. const types = parser.parseColonTypeList();
  12363. parser.resolveOperands(op.operands, types);
  12364. if (parser.accept('->')) {
  12365. const resultType = parser.parseType();
  12366. op.results = [{ type: resultType }];
  12367. }
  12368. return true;
  12369. }
  12370. _parseLLVMCallOp(parser, op) {
  12371. const cconvKeywords = ['ccc', 'fastcc', 'coldcc', 'cc', 'webkit_jscc', 'anyregcc', 'preserve_mostcc', 'preserve_allcc', 'preserve_nonecc', 'cxx_fast_tlscc', 'tailcc', 'swiftcc', 'swifttailcc', 'cfguard_checkcc', 'ghccc'];
  12372. if (parser.match('id')) {
  12373. const value = parser.getToken().value;
  12374. if (cconvKeywords.includes(value) || /^cc_\d+$/.test(value)) {
  12375. op.attributes.push({ name: 'CConv', value: parser.expect('id') });
  12376. }
  12377. }
  12378. const tailcallKeywords = ['none', 'tail', 'musttail', 'notail'];
  12379. if (parser.match('id') && tailcallKeywords.includes(parser.getToken().value)) {
  12380. op.attributes.push({ name: 'TailCallKind', value: parser.expect('id') });
  12381. }
  12382. let isDirect = false;
  12383. if (parser.match('@')) {
  12384. const callee = parser.expect('@');
  12385. op.attributes.push({ name: 'callee', value: callee });
  12386. isDirect = true;
  12387. } else if (parser.match('%')) {
  12388. const calleePtr = parser.parseAttribute();
  12389. op.operands.push(calleePtr);
  12390. }
  12391. parser.expect('(');
  12392. while (!parser.match(')')) {
  12393. const arg = parser.parseAttribute();
  12394. op.operands.push(arg);
  12395. parser.accept(',');
  12396. }
  12397. parser.expect(')');
  12398. if (parser.accept('id', 'vararg')) {
  12399. parser.expect('(');
  12400. const varCalleeType = parser.parseType();
  12401. op.attributes.push({ name: 'var_callee_type', value: varCalleeType });
  12402. parser.expect(')');
  12403. }
  12404. if (parser.accept('[')) {
  12405. if (!parser.accept(']')) {
  12406. const opBundles = [];
  12407. do {
  12408. const tag = parser.expect('string');
  12409. parser.expect('(');
  12410. const bundleOperands = [];
  12411. if (!parser.match(')')) {
  12412. do {
  12413. bundleOperands.push(parser.parseAttribute());
  12414. } while (parser.accept(','));
  12415. parser.expect(':');
  12416. // Parse types for bundle operands
  12417. do {
  12418. parser.parseType();
  12419. } while (parser.accept(','));
  12420. }
  12421. parser.expect(')');
  12422. opBundles.push({ tag, operands: bundleOperands });
  12423. } while (parser.accept(','));
  12424. parser.expect(']');
  12425. if (opBundles.length > 0) {
  12426. op.attributes.push({ name: 'op_bundle_tags', value: opBundles });
  12427. }
  12428. }
  12429. }
  12430. if (parser.match('{')) {
  12431. parser.parseAttributeDict(op.attributes);
  12432. }
  12433. parser.expect(':');
  12434. if (!isDirect) {
  12435. parser.parseType();
  12436. parser.expect(',');
  12437. }
  12438. const sig = parser.parseFunctionSignature(op.operands);
  12439. for (let i = 0; i < sig.argTypes.length && i < op.operands.length; i++) {
  12440. op.operands[i].type = sig.argTypes[i].toString();
  12441. }
  12442. // Set result types
  12443. if (sig.resultTypes.length > 0) {
  12444. op.results = sig.resultTypes.map((t) => ({ type: t.toString() }));
  12445. }
  12446. return true;
  12447. }
  12448. _parseLLVMCallIntrinsicOp(parser, op) {
  12449. // Format: llvm.call_intrinsic "intrinsic.name"(%args) ["op_bundles"] : (arg_types) -> result_type
  12450. const intrinName = parser.expect('string');
  12451. op.attributes.push({ name: 'intrin', value: intrinName });
  12452. parser.expect('(');
  12453. while (!parser.match(')')) {
  12454. const arg = parser.parseAttribute();
  12455. op.operands.push(arg);
  12456. parser.accept(',');
  12457. }
  12458. parser.expect(')');
  12459. // Parse operation bundles: [] or ["tag"()] or ["tag"(%0, %1 : i32, i32), ...]
  12460. if (parser.accept('[')) {
  12461. if (!parser.accept(']')) {
  12462. const opBundles = [];
  12463. do {
  12464. const tag = parser.expect('string');
  12465. parser.expect('(');
  12466. const bundleOperands = [];
  12467. if (!parser.match(')')) {
  12468. do {
  12469. bundleOperands.push(parser.parseAttribute());
  12470. } while (parser.accept(','));
  12471. parser.expect(':');
  12472. // Parse types for bundle operands
  12473. do {
  12474. parser.parseType();
  12475. } while (parser.accept(','));
  12476. }
  12477. parser.expect(')');
  12478. opBundles.push({ tag, operands: bundleOperands });
  12479. } while (parser.accept(','));
  12480. parser.expect(']');
  12481. if (opBundles.length > 0) {
  12482. op.attributes.push({ name: 'op_bundle_tags', value: opBundles });
  12483. }
  12484. }
  12485. }
  12486. if (parser.match('{')) {
  12487. parser.parseAttributeDict(op.attributes);
  12488. }
  12489. parser.expect(':');
  12490. // Parse function signature: (arg_types {attrs}) -> (result_types {attrs})
  12491. // Matches call_interface_impl::parseFunctionSignature
  12492. const sig = parser.parseFunctionSignature(op.operands);
  12493. // Set operand types
  12494. for (let i = 0; i < sig.argTypes.length && i < op.operands.length; i++) {
  12495. op.operands[i].type = sig.argTypes[i].toString();
  12496. }
  12497. // Set result types
  12498. if (sig.resultTypes.length > 0) {
  12499. op.results = sig.resultTypes.map((t) => ({ type: t.toString() }));
  12500. }
  12501. return true;
  12502. }
  12503. _parseLLVMCmpOp(parser, op) {
  12504. const predicate = parser.expect('string');
  12505. op.attributes.push({ name: 'predicate', value: predicate });
  12506. const lhs = parser.parseAttribute();
  12507. op.operands.push(lhs);
  12508. parser.expect(',');
  12509. const rhs = parser.parseAttribute();
  12510. op.operands.push(rhs);
  12511. if (parser.match('{')) {
  12512. parser.parseAttributeDict(op.attributes);
  12513. }
  12514. parser.expect(':');
  12515. const type = parser.parseType();
  12516. for (const operand of op.operands) {
  12517. operand.type = type;
  12518. }
  12519. return true;
  12520. }
  12521. _parseLLVMIntrinsicOp(parser, op) {
  12522. parser.expect('(');
  12523. while (!parser.match(')')) {
  12524. const operand = parser.parseAttribute();
  12525. op.operands.push(operand);
  12526. parser.accept(',');
  12527. }
  12528. parser.expect(')');
  12529. if (parser.match('{')) {
  12530. parser.parseAttributeDict(op.attributes);
  12531. }
  12532. // Reference: parseColonTypeList (mandatory)
  12533. const types = parser.parseColonTypeList();
  12534. parser.resolveOperands(op.operands, types);
  12535. if (parser.accept('->')) {
  12536. const resultType = parser.parseType();
  12537. op.results = [{ type: resultType }];
  12538. }
  12539. return true;
  12540. }
  12541. _parseLLVMInvokeOp(parser, op) {
  12542. // Format: [cconv] (@callee | %funcptr) (args) to ^normalDest unwind ^unwindDest : [callee_type,] (arg_types) -> result_type
  12543. const cconvKeywords = ['ccc', 'fastcc', 'coldcc', 'cc', 'webkit_jscc', 'anyregcc', 'preserve_mostcc', 'preserve_allcc', 'preserve_nonecc', 'cxx_fast_tlscc', 'tailcc', 'swiftcc', 'swifttailcc', 'cfguard_checkcc', 'ghccc'];
  12544. if (parser.match('id')) {
  12545. const value = parser.getToken().value;
  12546. if (cconvKeywords.includes(value) || /^cc_\d+$/.test(value)) {
  12547. op.attributes.push({ name: 'CConv', value: parser.expect('id') });
  12548. }
  12549. }
  12550. let isDirect = false;
  12551. if (parser.match('@')) {
  12552. isDirect = true;
  12553. const callee = parser.expect('@');
  12554. op.attributes.push({ name: 'callee', value: callee });
  12555. } else if (parser.match('%')) {
  12556. const funcPtr = parser.parseAttribute();
  12557. op.operands.push(funcPtr);
  12558. }
  12559. parser.expect('(');
  12560. while (!parser.match(')')) {
  12561. const operand = parser.parseAttribute();
  12562. op.operands.push(operand);
  12563. parser.accept(',');
  12564. }
  12565. parser.expect(')');
  12566. parser.expect('id', 'to');
  12567. const normalDest = parser.expect('^');
  12568. op.successors = op.successors || [];
  12569. const normalSucc = { label: normalDest };
  12570. // Parse optional successor operands: ^bb1(%operand : type)
  12571. if (parser.accept('(')) {
  12572. normalSucc.operands = [];
  12573. while (!parser.match(')')) {
  12574. const operand = parser.parseAttribute();
  12575. normalSucc.operands.push(operand);
  12576. if (parser.accept(':')) {
  12577. parser.parseType();
  12578. }
  12579. parser.accept(',');
  12580. }
  12581. parser.expect(')');
  12582. }
  12583. op.successors.push(normalSucc);
  12584. parser.expect('id', 'unwind');
  12585. const unwindDest = parser.expect('^');
  12586. const unwindSucc = { label: unwindDest };
  12587. if (parser.accept('(')) {
  12588. unwindSucc.operands = [];
  12589. while (!parser.match(')')) {
  12590. const operand = parser.parseAttribute();
  12591. unwindSucc.operands.push(operand);
  12592. if (parser.accept(':')) {
  12593. parser.parseType();
  12594. }
  12595. parser.accept(',');
  12596. }
  12597. parser.expect(')');
  12598. }
  12599. op.successors.push(unwindSucc);
  12600. if (parser.accept('id', 'vararg')) {
  12601. parser.expect('(');
  12602. const varargType = parser.parseType();
  12603. op.attributes.push({ name: 'var_callee_type', value: varargType });
  12604. parser.expect(')');
  12605. }
  12606. if (parser.accept('[')) {
  12607. if (!parser.accept(']')) {
  12608. const opBundles = [];
  12609. do {
  12610. const tag = parser.expect('string');
  12611. parser.expect('(');
  12612. const bundleOperands = [];
  12613. if (!parser.match(')')) {
  12614. do {
  12615. bundleOperands.push(parser.parseAttribute());
  12616. } while (parser.accept(','));
  12617. parser.expect(':');
  12618. // Parse types for bundle operands
  12619. do {
  12620. parser.parseType();
  12621. } while (parser.accept(','));
  12622. }
  12623. parser.expect(')');
  12624. opBundles.push({ tag, operands: bundleOperands });
  12625. } while (parser.accept(','));
  12626. parser.expect(']');
  12627. if (opBundles.length > 0) {
  12628. op.attributes.push({ name: 'op_bundle_tags', value: opBundles });
  12629. }
  12630. }
  12631. }
  12632. if (parser.match('{')) {
  12633. parser.parseAttributeDict(op.attributes);
  12634. }
  12635. parser.expect(':');
  12636. if (!isDirect) {
  12637. const calleeType = parser.parseType();
  12638. if (op.operands.length > 0) {
  12639. op.operands[0].type = calleeType.toString();
  12640. }
  12641. parser.expect(',');
  12642. }
  12643. const callArgOperands = isDirect ? op.operands : op.operands.slice(1);
  12644. const sig = parser.parseFunctionSignature(callArgOperands);
  12645. for (let i = 0; i < sig.argTypes.length && i < callArgOperands.length; i++) {
  12646. callArgOperands[i].type = sig.argTypes[i].toString();
  12647. }
  12648. if (sig.resultTypes.length > 0) {
  12649. op.results = sig.resultTypes.map((t) => ({ type: t.toString() }));
  12650. }
  12651. return true;
  12652. }
  12653. _parseLLVMLandingpadOp(parser, op) {
  12654. // Format: cleanup? (catch|filter operand : type)* : result_type
  12655. // Parse optional cleanup
  12656. if (parser.accept('id', 'cleanup')) {
  12657. op.attributes.push({ name: 'cleanup', value: true });
  12658. }
  12659. // Parse clauses
  12660. while (parser.match('(')) {
  12661. parser.expect('(');
  12662. parser.expect('id'); // 'catch' or 'filter'
  12663. const operand = parser.parseAttribute();
  12664. op.operands.push(operand);
  12665. parser.expect(':');
  12666. const type = parser.parseType();
  12667. operand.type = type.toString();
  12668. parser.expect(')');
  12669. }
  12670. // Parse result type
  12671. parser.expect(':');
  12672. const resultType = parser.parseType();
  12673. op.results = [{ type: resultType }];
  12674. return true;
  12675. }
  12676. _parseLLVMFuncOp(parser, op) {
  12677. const linkageKeywords = ['external', 'available_externally', 'linkonce', 'linkonce_odr', 'weak', 'weak_odr', 'appending', 'internal', 'private', 'extern_weak', 'common'];
  12678. if (parser.match('id') && linkageKeywords.includes(parser.getToken().value)) {
  12679. op.attributes.push({ name: 'linkage', value: parser.expect('id') });
  12680. }
  12681. const visibilityKeywords = ['default', 'hidden', 'protected'];
  12682. if (parser.match('id') && visibilityKeywords.includes(parser.getToken().value)) {
  12683. op.attributes.push({ name: 'visibility_', value: parser.expect('id') });
  12684. }
  12685. const unnamedAddrKeywords = ['unnamed_addr', 'local_unnamed_addr'];
  12686. if (parser.match('id') && unnamedAddrKeywords.includes(parser.getToken().value)) {
  12687. op.attributes.push({ name: 'unnamed_addr', value: parser.expect('id') });
  12688. }
  12689. const cconvKeywords = ['ccc', 'fastcc', 'coldcc', 'cc', 'webkit_jscc', 'anyregcc', 'preserve_mostcc', 'preserve_allcc', 'preserve_nonecc', 'cxx_fast_tlscc', 'tailcc', 'swiftcc', 'swifttailcc', 'cfguard_checkcc', 'ghccc', 'arm_apcscc', 'arm_aapcscc', 'arm_aapcs_vfpcc', 'aarch64_vector_pcs', 'aarch64_sve_vector_pcs', 'aarch64_sme_preservemost_from_x0', 'aarch64_sme_preservemost_from_x2', 'msp430_intrcc', 'avr_intrcc', 'avr_signalcc', 'ptx_kernel', 'ptx_device', 'spir_func', 'spir_kernel', 'intel_ocl_bicc', 'x86_64_sysvcc', 'win64cc', 'x86_fastcallcc', 'x86_stdcallcc', 'x86_thiscallcc', 'x86_vectorcallcc', 'x86_intrcc', 'amdgpu_vs', 'amdgpu_gs', 'amdgpu_ps', 'amdgpu_cs', 'amdgpu_kernel', 'x86_regcallcc', 'amdgpu_hs', 'msp430_builtincc', 'amdgpu_ls', 'amdgpu_es', 'aarch64_vfpcc', 'aarch64_sve_vfpcc', 'wasm_emscripten_invokecc', 'amdgpu_gfx', 'm68k_intrcc'];
  12690. if (parser.match('id')) {
  12691. const value = parser.getToken().value;
  12692. if (cconvKeywords.includes(value) || /^cc_\d+$/.test(value)) {
  12693. op.attributes.push({ name: 'CConv', value: parser.expect('id') });
  12694. }
  12695. }
  12696. parser.parseSymbolName('sym_name', op.attributes);
  12697. const argResult = parser.parseFunctionArgumentList(true);
  12698. const params = argResult.arguments.map((a) => a.type);
  12699. const results = [];
  12700. const resultAttrs = [];
  12701. if (parser.accept('->')) {
  12702. parser.parseFunctionResultList(results, resultAttrs);
  12703. }
  12704. const returnType = results.length > 0 ? results[0] : null;
  12705. const type = new mlir.LLVMFunctionType(returnType, params, argResult.isVariadic);
  12706. op.attributes.push({ name: 'function_type', value: type });
  12707. if (parser.accept('id', 'vscale_range')) {
  12708. parser.expect('(');
  12709. const minRange = parser.expect();
  12710. parser.expect(',');
  12711. const maxRange = parser.expect();
  12712. parser.expect(')');
  12713. op.attributes.push({ name: 'vscale_range', value: `(${minRange}, ${maxRange})` });
  12714. }
  12715. if (parser.accept('id', 'comdat')) {
  12716. parser.expect('(');
  12717. const comdat = parser.expect('@');
  12718. parser.expect(')');
  12719. op.attributes.push({ name: 'comdat', value: comdat });
  12720. }
  12721. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  12722. if (parser.match('{')) {
  12723. const region = {};
  12724. parser.parseRegion(region);
  12725. op.regions.push(region);
  12726. }
  12727. return true;
  12728. }
  12729. };
  12730. mlir.ROCDLDialect = class extends mlir.LLVMDialect {
  12731. constructor(operations) {
  12732. super(operations);
  12733. this._name = 'rocdl';
  12734. // Load rocdl-specific operations from metadata
  12735. for (const metadata of operations.get('rocdl') || []) {
  12736. const op = { metadata };
  12737. if (metadata.assemblyFormat) {
  12738. const parser = new mlir.AssemblyFormatParser(metadata);
  12739. op.directives = parser.parse();
  12740. }
  12741. this._operations.set(metadata.name, op);
  12742. }
  12743. }
  12744. };
  12745. mlir.StdxDialect = class extends mlir.Dialect {
  12746. constructor(operations) {
  12747. super('stdx', operations);
  12748. }
  12749. parseOperation(parser, opName, op) {
  12750. if (opName === 'stdx.closure') {
  12751. return this._parseClosureOp(parser, op);
  12752. }
  12753. return super.parseOperation(parser, opName, op);
  12754. }
  12755. _parseClosureOp(parser, op) {
  12756. const sig = parser.parseFunctionSignatureWithArguments(false);
  12757. const argTypes = sig.arguments.map((a) => a.type);
  12758. const type = { inputs: argTypes, results: sig.resultTypes };
  12759. op.attributes.push({ name: 'type', value: type });
  12760. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  12761. if (parser.match('{')) {
  12762. const region = {};
  12763. parser.parseRegion(region, sig.arguments);
  12764. op.regions.push(region);
  12765. }
  12766. return true;
  12767. }
  12768. };
  12769. mlir.VMDialect = class extends mlir.Dialect {
  12770. constructor(operations) {
  12771. super('vm', operations);
  12772. }
  12773. parseOperation(parser, opName, op) {
  12774. if (opName === 'vm.func') {
  12775. parser.parseFunctionOp(op, false);
  12776. return true;
  12777. }
  12778. if (opName === 'vm.import') {
  12779. parser.parseOptionalVisibilityKeyword(op.attributes);
  12780. parser.parseSymbolName('sym_name', op.attributes);
  12781. const type = {};
  12782. if (parser.match('(')) {
  12783. parser.skip('(', ')');
  12784. }
  12785. type.inputs = [];
  12786. type.results = [];
  12787. const resultAttrs = [];
  12788. if (parser.accept('->')) {
  12789. parser.parseFunctionResultList(type.results, resultAttrs);
  12790. }
  12791. op.attributes.push({ name: 'function_type', value: type });
  12792. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  12793. return true;
  12794. }
  12795. if (opName === 'vm.export') {
  12796. const functionRef = parser.expect('@');
  12797. op.attributes.push({ name: 'function_ref', value: functionRef });
  12798. if (parser.accept('id', 'as')) {
  12799. parser.expect('(');
  12800. const exportName = parser.expect('string');
  12801. op.attributes.push({ name: 'export_name', value: exportName });
  12802. parser.expect(')');
  12803. } else {
  12804. op.attributes.push({ name: 'export_name', value: functionRef });
  12805. }
  12806. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  12807. return true;
  12808. }
  12809. // Handle vm.global.* declarations (but not store/load operations)
  12810. if (opName.startsWith('vm.global.') && !opName.startsWith('vm.global.store.') && !opName.startsWith('vm.global.load.')) {
  12811. this.getOperation(opName).hasParseOperation = false; // compatibility?
  12812. parser.parseOptionalVisibilityKeyword(op.attributes);
  12813. if (parser.match('id', 'mutable')) {
  12814. const mutable = parser.expect('id');
  12815. op.attributes.push({ name: 'is_mutable', value: mutable });
  12816. }
  12817. parser.parseSymbolName('sym_name', op.attributes);
  12818. parser.parseOptionalAttrDict(op.attributes);
  12819. if (parser.accept('=')) {
  12820. const initialValue = parser.parseAttribute();
  12821. op.attributes.push({ name: 'initial_value', value: initialValue });
  12822. }
  12823. if (parser.accept(':')) {
  12824. const type = parser.parseType();
  12825. op.attributes.push({ name: 'type', value: type });
  12826. }
  12827. return true;
  12828. }
  12829. if (opName === 'vm.initializer') {
  12830. parser.parseOptionalVisibilityKeyword(op.attributes);
  12831. if (parser.match('@')) {
  12832. parser.parseSymbolName('sym_name', op.attributes);
  12833. }
  12834. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  12835. if (parser.match('{')) {
  12836. const region = {};
  12837. parser.parseRegion(region);
  12838. op.regions.push(region);
  12839. }
  12840. return true;
  12841. }
  12842. if (opName === 'vm.rodata.inline') {
  12843. this.getOperation(opName).hasParseOperation = false; // compatibility?
  12844. // Optional name (string)
  12845. if (parser.match('string')) {
  12846. const name = parser.expect('string');
  12847. op.attributes.push({ name: 'name', value: name });
  12848. }
  12849. // Attr-dict
  12850. parser.parseOptionalAttrDict(op.attributes);
  12851. // : type = value
  12852. // Reference: parseOptionalColonTypeList
  12853. parser.resolveOperands(op.results, parser.parseOptionalColonTypeList());
  12854. if (parser.accept('=')) {
  12855. const value = parser.parseAttribute();
  12856. // Handle type annotation after the value (e.g., dense<...> : vector<21xi8>)
  12857. if (parser.accept(':')) {
  12858. const valueType = parser.parseType();
  12859. value.type = valueType;
  12860. }
  12861. op.attributes.push({ name: 'value', value });
  12862. }
  12863. return true;
  12864. }
  12865. // Handle vm.const.* operations (e.g., vm.const.i32.zero : i32, vm.const.i32 1 : i32, vm.const.ref.rodata @symbol : !vm.buffer)
  12866. if (opName.startsWith('vm.const.') &&
  12867. opName !== 'vm.const.i32' &&
  12868. opName !== 'vm.const.ref.rodata' && opName !== 'vm.const.ref.zero') {
  12869. if (opName === 'vm.const.i32.zero') {
  12870. this.getOperation(opName).hasParseOperation = false; // compatibility?
  12871. }
  12872. // Optional value or symbol reference
  12873. if (parser.match('int') || parser.match('float') || parser.match('string')) {
  12874. const value = parser.parseAttribute();
  12875. op.attributes.push({ name: 'value', value: value.value === undefined ? value : value.value });
  12876. } else if (parser.match('@')) {
  12877. // Handle symbol reference (e.g., @symbol_name)
  12878. const symbol = parser.expect('@');
  12879. op.attributes.push({ name: 'rodata', value: symbol });
  12880. }
  12881. parser.parseOptionalAttrDict(op.attributes);
  12882. // Reference: parseOptionalColonTypeList
  12883. parser.resolveOperands(op.results, parser.parseOptionalColonTypeList());
  12884. return true;
  12885. }
  12886. // Handle vm.call and vm.call.variadic
  12887. // Format: @callee(operands) {attrs} : (types) -> results
  12888. // Variadic has complex syntax like: @callee(op1, op2, [(tuple1), (tuple2)])
  12889. if (opName === 'vm.call' || opName === 'vm.call.variadic') {
  12890. this.getOperation(opName).hasParseOperation = false; // compatibility?
  12891. // Parse callee
  12892. if (parser.match('@')) {
  12893. const callee = parser.expect('@');
  12894. op.attributes.push({ name: 'callee', value: callee });
  12895. }
  12896. // Parse operands - use skip for complex nested structures
  12897. if (parser.accept('(')) {
  12898. while (!parser.match(')')) {
  12899. if (parser.match('[')) {
  12900. // Skip complex nested structures in variadic calls
  12901. parser.skip('[', ']');
  12902. parser.accept(','); // consume trailing comma if present
  12903. } else if (parser.match('%')) {
  12904. const operand = parser.expect('%');
  12905. op.operands.push({ value: operand });
  12906. parser.accept(','); // consume trailing comma if present
  12907. } else {
  12908. // Unexpected token, break to avoid infinite loop
  12909. break;
  12910. }
  12911. }
  12912. parser.expect(')');
  12913. }
  12914. // Parse attributes
  12915. parser.parseOptionalAttrDict(op.attributes);
  12916. // Parse types - vm.call.variadic has special syntax with '...' ellipsis
  12917. if (parser.accept(':')) {
  12918. // Skip the entire type section for variadic calls due to '...' syntax
  12919. if (opName === 'vm.call.variadic') {
  12920. parser.skip('(', ')');
  12921. if (parser.accept('->')) {
  12922. const resultTypes = parser.parseFunctionResultTypes();
  12923. parser.resolveOperands(op.results, resultTypes);
  12924. }
  12925. } else {
  12926. // Regular vm.call - Reference: uses functional-type(operands, results)
  12927. const type = parser.parseType();
  12928. if (type instanceof mlir.FunctionType) {
  12929. parser.resolveOperands(op.operands, type.inputs);
  12930. parser.resolveOperands(op.results, type.results);
  12931. }
  12932. }
  12933. }
  12934. return true;
  12935. }
  12936. return super.parseOperation(parser, opName, op);
  12937. }
  12938. };
  12939. mlir.MathDialect = class extends mlir.Dialect {
  12940. constructor(operations) {
  12941. super('math', operations);
  12942. this.registerCustomAttribute('Arith_FastMathAttr', this._parseEnumFlagsAngleBracketComma.bind(this));
  12943. }
  12944. };
  12945. mlir.TMTensorDialect = class extends mlir.Dialect {
  12946. constructor(operations) {
  12947. super('tm_tensor', operations);
  12948. }
  12949. };
  12950. mlir.MLProgramDialect = class extends mlir.Dialect {
  12951. constructor(operations) {
  12952. super('ml_program', operations);
  12953. this.registerCustomDirective('TypedInitialValue', this._parseTypedInitialValue.bind(this));
  12954. }
  12955. _parseTypedInitialValue(parser, op, args) {
  12956. const typeArg = args[0].replace('$', '');
  12957. const valueArg = args[1].replace('$', '');
  12958. if (parser.accept('(')) {
  12959. const attr = parser.parseAttribute();
  12960. if (parser.accept(':')) {
  12961. attr.type = parser.parseType();
  12962. }
  12963. parser.expect(')');
  12964. op.attributes.push({ name: valueArg, value: attr.value === undefined ? attr : attr.value });
  12965. }
  12966. parser.expect(':');
  12967. const type = parser.parseType();
  12968. op.attributes.push({ name: typeArg, value: type });
  12969. }
  12970. };
  12971. mlir.IREEGPUDialect = class extends mlir.Dialect {
  12972. constructor(operations) {
  12973. super('iree_gpu', operations);
  12974. }
  12975. };
  12976. mlir.TFDeviceDialect = class extends mlir.Dialect {
  12977. constructor(operations) {
  12978. super('tf_device', operations);
  12979. }
  12980. parseOperation(parser, opName, op) {
  12981. if (opName === 'tf_device.replicate') {
  12982. return this._parseReplicateOp(parser, op);
  12983. }
  12984. return super.parseOperation(parser, opName, op);
  12985. }
  12986. _parseReplicateOp(parser, op) {
  12987. if (!parser.accept('(')) {
  12988. parser.parseOptionalAttrDict(op.attributes);
  12989. if (parser.match('{')) {
  12990. const region = {};
  12991. parser.parseRegion(region);
  12992. op.regions.push(region);
  12993. }
  12994. return true;
  12995. }
  12996. if (parser.match(')')) {
  12997. parser.expect(')');
  12998. parser.parseOptionalAttrDict(op.attributes);
  12999. if (parser.match('{')) {
  13000. const region = {};
  13001. parser.parseRegion(region);
  13002. op.regions.push(region);
  13003. }
  13004. return true;
  13005. }
  13006. do {
  13007. if (parser.match('[')) {
  13008. const replicatedInputs = [];
  13009. parser.expect('[');
  13010. while (!parser.accept(']')) {
  13011. const value = parser.expect('%');
  13012. replicatedInputs.push({ value });
  13013. if (!parser.accept(',')) {
  13014. parser.expect(']');
  13015. break;
  13016. }
  13017. }
  13018. parser.expect('id', 'as');
  13019. const blockArg = parser.expect('%');
  13020. parser.expect(':');
  13021. const type = parser.parseType();
  13022. op.operands.push({ name: 'replicated_inputs', value: replicatedInputs, blockArg, type });
  13023. } else if (parser.match('%')) {
  13024. const value = parser.expect('%');
  13025. parser.expect('id', 'as');
  13026. const blockArg = parser.expect('%');
  13027. parser.expect(':');
  13028. const type = parser.parseType();
  13029. op.operands.push({ name: 'packed_inputs', value, blockArg, type });
  13030. } else {
  13031. break;
  13032. }
  13033. } while (parser.accept(','));
  13034. parser.expect(')');
  13035. parser.parseOptionalAttrDict(op.attributes);
  13036. if (parser.match('{')) {
  13037. const region = {};
  13038. parser.parseRegion(region);
  13039. op.regions.push(region);
  13040. }
  13041. return true;
  13042. }
  13043. };
  13044. mlir.TFExecutorDialect = class extends mlir.Dialect {
  13045. constructor(operations) {
  13046. super('tf_executor', operations);
  13047. }
  13048. parseType(parser, dialectName) {
  13049. const typeName = parser.parseKeyword();
  13050. if (!typeName) {
  13051. return null;
  13052. }
  13053. const type = `!${dialectName}.${typeName}`;
  13054. if (typeName === 'control' || typeName === 'token') {
  13055. return new mlir.Type(type);
  13056. }
  13057. return null;
  13058. }
  13059. parseOperation(parser, opName, op) {
  13060. if (opName === 'tf_executor.graph') {
  13061. return this._parseGraphOp(parser, op);
  13062. }
  13063. if (opName === 'tf_executor.island') {
  13064. return this._parseIslandOp(parser, op);
  13065. }
  13066. if (opName === 'tf_executor.Enter') {
  13067. return this._parseEnterOp(parser, op);
  13068. }
  13069. if (opName === 'tf_executor.Switch' || opName === 'tf_executor.Merge' ||
  13070. opName === 'tf_executor.LoopCond' || opName === 'tf_executor.Exit') {
  13071. // These ops have hasCustomAssemblyFormat: true but no assemblyFormat in metadata
  13072. op.operands = parser.parseArguments();
  13073. if (parser.accept(':')) {
  13074. const type = parser.parseType();
  13075. if (type instanceof mlir.FunctionType) {
  13076. for (let i = 0; i < op.operands.length; i++) {
  13077. const inputType = type.inputs[i];
  13078. if (inputType) {
  13079. op.operands[i].type = inputType;
  13080. }
  13081. }
  13082. for (let i = 0; i < type.results.length; i++) {
  13083. const outputType = type.results[i];
  13084. if (outputType) {
  13085. op.results.push({ type: outputType });
  13086. }
  13087. }
  13088. } else {
  13089. const typeStr = type.toString();
  13090. for (const operand of op.operands) {
  13091. operand.type = typeStr;
  13092. }
  13093. op.results.push({ type: typeStr });
  13094. op.results.push({ type: '!tf_executor.control' });
  13095. }
  13096. }
  13097. parser.parseOptionalAttrDict(op.attributes);
  13098. return true;
  13099. }
  13100. return super.parseOperation(parser, opName, op);
  13101. }
  13102. _parseEnterOp(parser, op) {
  13103. // Reference: TFExecutorOps.td - syntax is: $data frame $frame_name ...
  13104. // Parse the data operand explicitly to avoid consuming 'frame' keyword
  13105. if (parser.match('%')) {
  13106. const operand = parser.expect('%');
  13107. op.operands.push({ value: operand });
  13108. }
  13109. parser.expect('id', 'frame');
  13110. const frameName = parser.expect('string');
  13111. op.attributes.push({ name: 'frame_name', value: frameName });
  13112. if (parser.accept('id', 'parallel_iterations')) {
  13113. const parallelIterations = parser.expect('int');
  13114. op.attributes.push({ name: 'parallel_iterations', value: parseInt(parallelIterations, 10) });
  13115. } else {
  13116. op.attributes.push({ name: 'parallel_iterations', value: 10 });
  13117. }
  13118. const isConstant = parser.accept('id', 'constant');
  13119. op.attributes.push({ name: 'is_constant', value: isConstant });
  13120. parser.expect(':');
  13121. const type = parser.parseType();
  13122. if (type instanceof mlir.FunctionType) {
  13123. for (let i = 0; i < op.operands.length; i++) {
  13124. const inputType = type.inputs[i];
  13125. if (inputType) {
  13126. op.operands[i].type = inputType;
  13127. }
  13128. }
  13129. for (const outputType of type.results) {
  13130. op.results.push({ type: outputType });
  13131. }
  13132. } else {
  13133. const typeStr = type.toString();
  13134. if (op.operands.length > 0) {
  13135. op.operands[0].type = typeStr;
  13136. }
  13137. for (let i = 1; i < op.operands.length; i++) {
  13138. op.operands[i].type = '!tf_executor.control';
  13139. }
  13140. op.results.push({ type: typeStr });
  13141. op.results.push({ type: '!tf_executor.control' });
  13142. }
  13143. parser.parseOptionalAttrDict(op.attributes);
  13144. return true;
  13145. }
  13146. _parseGraphOp(parser, op) {
  13147. if (parser.match('{')) {
  13148. const region = {};
  13149. parser.parseRegion(region);
  13150. op.regions.push(region);
  13151. if (region.blocks && region.blocks.length > 0) {
  13152. const [block] = region.blocks;
  13153. if (block.operations && block.operations.length > 0) {
  13154. const lastOp = block.operations[block.operations.length - 1];
  13155. if (lastOp.name === 'tf_executor.fetch' && lastOp.operands) {
  13156. for (const operand of lastOp.operands) {
  13157. if (operand.type && operand.type !== '!tf_executor.control') {
  13158. op.results.push({ type: operand.type });
  13159. }
  13160. }
  13161. }
  13162. }
  13163. }
  13164. }
  13165. parser.parseOptionalAttrDict(op.attributes);
  13166. return true;
  13167. }
  13168. _parseIslandOp(parser, op) {
  13169. // Parse: tf_executor.island wraps "tf.SomeOp"(...) {...} : (...) -> (...)
  13170. // or: tf_executor.island {...}
  13171. // or: tf_executor.island(%control_inputs) {...}
  13172. if (parser.match('(')) {
  13173. op.operands = parser.parseArguments();
  13174. }
  13175. if (parser.accept('id', 'wraps')) {
  13176. // Parse the wrapped operation
  13177. const wrappedOp = parser.parseGenericOperation();
  13178. op.attributes.push({ name: 'wrappedOp', value: wrappedOp });
  13179. // Note: The island's results are already set by parseOperation from the LHS
  13180. // We just need to ensure there's a control token type for the last result
  13181. // The wrapped operation's result types should match the island's first N-1 results
  13182. } else if (parser.match('{')) {
  13183. // Parse region-based island
  13184. const region = {};
  13185. parser.parseRegion(region);
  13186. op.regions.push(region);
  13187. }
  13188. parser.parseOptionalAttrDict(op.attributes);
  13189. return true;
  13190. }
  13191. };
  13192. mlir.TFFrameworkDialect = class extends mlir.Dialect {
  13193. constructor(operations) {
  13194. super('tf_framework', operations);
  13195. }
  13196. };
  13197. mlir.TFRDialect = class extends mlir.Dialect {
  13198. constructor(operations) {
  13199. super('tfr', operations);
  13200. }
  13201. parseOperation(parser, opName, op) {
  13202. if (opName === 'tfr.func') {
  13203. parser.parseFunctionOp(op, false);
  13204. return true;
  13205. }
  13206. return super.parseOperation(parser, opName, op);
  13207. }
  13208. };
  13209. mlir.CoreRTDialect = class extends mlir.Dialect {
  13210. constructor(operations) {
  13211. super('corert', operations);
  13212. }
  13213. parseOperation(parser, opName, op) {
  13214. const opInfo = this.getOperation(opName);
  13215. if (!opInfo) {
  13216. return false;
  13217. }
  13218. if (opName === 'corert.executeop' || opName === 'corert.executeop.seq') {
  13219. const opHandler = parser.parseArguments();
  13220. op.operands.push(...opHandler);
  13221. const opNameAttr = parser.expect('string');
  13222. op.attributes.push({ name: 'op_name', value: opNameAttr });
  13223. const operands = parser.parseArguments();
  13224. op.operands.push(...operands);
  13225. if (parser.match('{')) {
  13226. parser.parseAttributeDict(op.attributes);
  13227. }
  13228. if (parser.accept(':')) {
  13229. const resultCount = parser.expect();
  13230. op.attributes.push({ name: 'result_count', value: parseInt(resultCount, 10) });
  13231. }
  13232. return true;
  13233. }
  13234. return super.parseOperation(parser, opName, op);
  13235. }
  13236. };
  13237. mlir.TFRTDialect = class extends mlir.Dialect {
  13238. constructor(operations) {
  13239. super('tfrt', operations);
  13240. }
  13241. parseType(parser, dialectName) {
  13242. const typeName = parser.parseKeyword();
  13243. if (!typeName) {
  13244. return null;
  13245. }
  13246. let type = `!${dialectName}.${typeName}`;
  13247. const simpleTypes = ['chain', 'string', 'dist_context'];
  13248. if (simpleTypes.includes(typeName)) {
  13249. return new mlir.Type(type);
  13250. }
  13251. if (typeName === 'tensor') {
  13252. if (parser.match('<')) {
  13253. const content = parser.skip('<', '>');
  13254. type += content;
  13255. }
  13256. return new mlir.Type(type);
  13257. }
  13258. return null;
  13259. }
  13260. parseOperation(parser, opName, op) {
  13261. const opInfo = this.getOperation(opName);
  13262. if (!opInfo) {
  13263. return false;
  13264. }
  13265. if (opInfo.metadata?.assemblyFormat === 'operands attr-dict') {
  13266. while (parser.match('%')) {
  13267. op.operands.push({ value: parser.expect() });
  13268. if (!parser.accept(',')) {
  13269. break;
  13270. }
  13271. }
  13272. if (parser.match('{')) {
  13273. parser.parseAttributeDict(op.attributes);
  13274. }
  13275. return true;
  13276. }
  13277. if (opName === 'tfrt.call') {
  13278. parser.parseSymbolName('callee', op.attributes);
  13279. op.operands = parser.parseArguments();
  13280. parser.parseOptionalAttrDict(op.attributes);
  13281. if (parser.accept(':')) {
  13282. const type = parser.parseFunctionType();
  13283. if (type && type.results) {
  13284. type.results.forEach((resultType) => {
  13285. op.results.push({ type: resultType });
  13286. });
  13287. }
  13288. }
  13289. return true;
  13290. }
  13291. if (opName === 'tfrt.return') {
  13292. if (!parser.match('keyword', 'loc') && !parser.match('eof')) {
  13293. op.operands = parser.parseArguments();
  13294. // Reference: parseOptionalColonTypeList
  13295. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  13296. }
  13297. return true;
  13298. }
  13299. if (opName === 'tfrt.repeat.i32') {
  13300. if (parser.match('%')) {
  13301. op.operands = parser.parseArguments();
  13302. }
  13303. if (parser.accept(':')) {
  13304. while (!parser.match('{') && !parser.match('eof')) {
  13305. parser.expect();
  13306. }
  13307. }
  13308. if (parser.match('{')) {
  13309. const region = {};
  13310. parser.parseRegion(region);
  13311. op.regions.push(region);
  13312. }
  13313. return true;
  13314. }
  13315. if (opName === 'tfrt.if') {
  13316. op.operands = parser.parseArguments();
  13317. if (parser.accept('id', 'attributes')) {
  13318. parser.parseOptionalAttrDict(op.attributes);
  13319. }
  13320. if (parser.accept(':')) {
  13321. const funcType = parser.parseFunctionType();
  13322. if (funcType && funcType.results) {
  13323. for (const resultType of funcType.results) {
  13324. op.results.push({ type: resultType });
  13325. }
  13326. }
  13327. }
  13328. if (parser.match('{')) {
  13329. const thenRegion = {};
  13330. parser.parseRegion(thenRegion);
  13331. op.regions.push(thenRegion);
  13332. }
  13333. if (parser.accept('id', 'else')) {
  13334. if (parser.match('{')) {
  13335. const elseRegion = {};
  13336. parser.parseRegion(elseRegion);
  13337. op.regions.push(elseRegion);
  13338. }
  13339. }
  13340. return true;
  13341. }
  13342. return super.parseOperation(parser, opName, op);
  13343. }
  13344. };
  13345. mlir.TFRTFallbackAsyncDialect = class extends mlir.Dialect {
  13346. constructor(operations) {
  13347. super('tfrt_fallback_async', operations);
  13348. }
  13349. parseOperation(parser, opName, op) {
  13350. const opInfo = this.getOperation(opName);
  13351. if (!opInfo) {
  13352. return false;
  13353. }
  13354. if (opName === 'tfrt_fallback_async.createop' || opName.startsWith('tfrt_fallback_async.executeop')) {
  13355. const isCreateOp = opName === 'tfrt_fallback_async.createop';
  13356. const hasChain = isCreateOp || opName.includes('.seq');
  13357. const hasAllocator = opName.includes('.allocator');
  13358. if ((hasChain || hasAllocator) && parser.match('(')) {
  13359. const chainOperands = parser.parseArguments();
  13360. op.operands.push(...chainOperands);
  13361. }
  13362. while (!parser.match(':') && !parser.match('{')) {
  13363. if (parser.match('id')) {
  13364. const key = parser.expect('id');
  13365. if (parser.accept('(')) {
  13366. const value = parser.expect();
  13367. parser.expect(')');
  13368. op.attributes.push({ name: key, value });
  13369. }
  13370. } else if (parser.match('string')) {
  13371. const opNameAttr = parser.expect('string');
  13372. op.attributes.push({ name: 'op_name', value: opNameAttr });
  13373. const operands = parser.parseArguments();
  13374. op.operands.push(...operands);
  13375. break;
  13376. } else {
  13377. break;
  13378. }
  13379. }
  13380. if (parser.match('{')) {
  13381. parser.parseAttributeDict(op.attributes);
  13382. if (parser.match('{')) {
  13383. parser.parseAttributeDict(op.attributes);
  13384. }
  13385. }
  13386. if (isCreateOp) {
  13387. if (parser.match('id', 'num_args')) {
  13388. parser.expect('id');
  13389. parser.expect('(');
  13390. const numArgs = parser.expect();
  13391. parser.expect(')');
  13392. op.attributes.push({ name: 'num_args', value: parseInt(numArgs, 10) });
  13393. }
  13394. } else if (parser.accept(':')) {
  13395. const resultCount = parser.expect();
  13396. op.attributes.push({ name: 'result_count', value: parseInt(resultCount, 10) });
  13397. }
  13398. return true;
  13399. }
  13400. return super.parseOperation(parser, opName, op);
  13401. }
  13402. };
  13403. mlir.TileDialect = class extends mlir.Dialect {
  13404. constructor(operations) {
  13405. super('tile', operations);
  13406. }
  13407. parseOperation(parser, opName, op) {
  13408. // tile.contract has format: tile.contract agg, combo, operands... attributes : types -> result
  13409. // Example: %1 = tile.contract add, mul, %0, %arg0, %arg1 {sink = #map0, srcs = [#map1, #map2]} : tensor<f32>, tensor<1x256xf32>, tensor<256x512xf32> -> tensor<1x512xf32>
  13410. if (opName === 'tile.contract') {
  13411. // Parse aggregation kind (add, mul, etc.)
  13412. if (parser.match('id')) {
  13413. const agg = parser.expect('id');
  13414. op.attributes.push({ name: 'agg', value: agg });
  13415. }
  13416. parser.accept(',');
  13417. // Parse combination kind (add, mul, etc.)
  13418. if (parser.match('id')) {
  13419. const combo = parser.expect('id');
  13420. op.attributes.push({ name: 'combo', value: combo });
  13421. }
  13422. parser.accept(',');
  13423. // Parse operands
  13424. op.operands = parser.parseArguments();
  13425. // Parse attributes
  13426. if (parser.match('{')) {
  13427. parser.parseAttributeDict(op.attributes);
  13428. }
  13429. // Parse types
  13430. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  13431. if (parser.accept('->')) {
  13432. const resultTypes = parser.parseFunctionResultTypes();
  13433. parser.resolveOperands(op.results, resultTypes);
  13434. }
  13435. return true;
  13436. }
  13437. return super.parseOperation(parser, opName, op);
  13438. }
  13439. };
  13440. mlir.PXADialect = class extends mlir.Dialect {
  13441. constructor(operations) {
  13442. super('pxa', operations);
  13443. }
  13444. parseOperation(parser, opName, op) {
  13445. if (opName === 'pxa.reduce' || opName === 'pxa.vector_reduce') {
  13446. const agg = parser.expect('id');
  13447. op.attributes.push({ name: 'agg', value: agg });
  13448. const val = { value: parser.expect('%') };
  13449. op.operands.push(val);
  13450. parser.accept(',');
  13451. const memref = { value: parser.expect('%') };
  13452. op.operands.push(memref);
  13453. parser.skip('[', ']');
  13454. parser.parseOptionalAttrDict(op.attributes);
  13455. if (parser.accept(':')) {
  13456. const type = parser.parseType();
  13457. memref.type = type;
  13458. op.results.push({ type });
  13459. if (opName === 'pxa.vector_reduce' && parser.accept(',')) {
  13460. const vectorType = parser.parseType();
  13461. val.type = vectorType;
  13462. }
  13463. }
  13464. return true;
  13465. }
  13466. if (opName === 'pxa.load' || opName === 'pxa.vector_load') {
  13467. const memref = { value: parser.expect('%') };
  13468. op.operands.push(memref);
  13469. parser.skip('[', ']');
  13470. parser.parseOptionalAttrDict(op.attributes);
  13471. if (parser.accept(':')) {
  13472. const type = parser.parseType();
  13473. memref.type = type;
  13474. if (opName === 'pxa.vector_load' && parser.accept(',')) {
  13475. const vectorType = parser.parseType();
  13476. op.results.push({ type: vectorType });
  13477. }
  13478. }
  13479. return true;
  13480. }
  13481. if (opName === 'pxa.generic') {
  13482. if (parser.accept('(')) {
  13483. while (!parser.match(')')) {
  13484. const operand = { value: parser.expect('%') };
  13485. op.operands.push(operand);
  13486. if (parser.match('[')) {
  13487. parser.skip('[', ']');
  13488. }
  13489. if (parser.accept(':')) {
  13490. parser.expect('#'); // Skip affine map reference
  13491. }
  13492. if (!parser.accept(',')) {
  13493. break;
  13494. }
  13495. }
  13496. parser.expect(')');
  13497. }
  13498. if (parser.accept('<')) {
  13499. const reduction = parser.expect('id');
  13500. op.attributes.push({ name: 'reduction', value: reduction });
  13501. parser.expect('>');
  13502. }
  13503. if (parser.match('@')) {
  13504. op.attributes.push({ name: 'kernel', value: parser.expect('@') });
  13505. }
  13506. if (parser.accept('(')) {
  13507. while (!parser.match(')')) {
  13508. const operand = { value: parser.expect('%') };
  13509. op.operands.push(operand);
  13510. if (parser.match('[')) {
  13511. parser.skip('[', ']');
  13512. }
  13513. if (parser.accept(':')) {
  13514. parser.expect('#'); // Skip affine map reference
  13515. }
  13516. if (!parser.accept(',')) {
  13517. break;
  13518. }
  13519. }
  13520. parser.expect(')');
  13521. }
  13522. if (parser.accept('id', 'tile')) {
  13523. parser.expect(':');
  13524. const tile = parser.skip('[', ']');
  13525. op.attributes.push({ name: 'tile', value: tile });
  13526. }
  13527. parser.parseOptionalAttrDict(op.attributes);
  13528. if (parser.accept(':')) {
  13529. const funcType = parser.parseFunctionType();
  13530. if (funcType && funcType.results) {
  13531. for (const resultType of funcType.results) {
  13532. op.results.push({ type: resultType });
  13533. }
  13534. }
  13535. }
  13536. return true;
  13537. }
  13538. return super.parseOperation(parser, opName, op);
  13539. }
  13540. };
  13541. mlir.ToyDialect = class extends mlir.Dialect {
  13542. constructor(operations) {
  13543. super('toy', operations);
  13544. }
  13545. parseOperation(parser, opName, op) {
  13546. if (opName === 'toy.func') {
  13547. parser.parseFunctionOp(op, false);
  13548. return true;
  13549. }
  13550. if (opName === 'toy.constant') {
  13551. const value = parser.parseAttribute();
  13552. op.attributes.push({ name: 'value', value: value.value === undefined ? value : value.value });
  13553. // Reference: parseOptionalColonTypeList
  13554. parser.resolveOperands(op.results, parser.parseOptionalColonTypeList());
  13555. return true;
  13556. }
  13557. if (opName === 'toy.mul' || opName === 'toy.add') {
  13558. op.operands = parser.parseArguments();
  13559. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13560. if (parser.accept(':')) {
  13561. // The type signature can be either:
  13562. // 1. Simple: `: tensor<*xf64>` - just the result type
  13563. // 2. Function-style: `: (tensor<*xf64>, tensor<*xf64>) -> tensor<*xf64>`
  13564. const type = parser.parseType();
  13565. if (type instanceof mlir.FunctionType) {
  13566. // Function-style type signature
  13567. for (let i = 0; i < op.operands.length; i++) {
  13568. const inputType = type.getInput(i);
  13569. if (inputType) {
  13570. op.operands[i].type = inputType;
  13571. }
  13572. }
  13573. // Add result type to existing result (which already has SSA name)
  13574. if (op.results.length > 0) {
  13575. const resultType = type.getResult(0);
  13576. if (resultType) {
  13577. op.results[0].type = resultType;
  13578. }
  13579. }
  13580. } else {
  13581. // Simple type signature - type applies to both operands and result
  13582. const typeStr = type.toString();
  13583. for (const operand of op.operands) {
  13584. operand.type = typeStr;
  13585. }
  13586. if (op.results.length > 0) {
  13587. op.results[0].type = typeStr;
  13588. }
  13589. }
  13590. }
  13591. return true;
  13592. }
  13593. return super.parseOperation(parser, opName, op);
  13594. }
  13595. };
  13596. mlir.SdfgDialect = class extends mlir.Dialect {
  13597. constructor(operations) {
  13598. super('sdfg', operations);
  13599. }
  13600. parseType(parser, dialectName) {
  13601. const typeName = parser.parseKeyword();
  13602. if (!typeName) {
  13603. return null;
  13604. }
  13605. let type = `!${dialectName}.${typeName}`;
  13606. if (typeName === 'stream' && parser.match('_')) {
  13607. parser.expect('_');
  13608. const suffix = parser.expect('id');
  13609. if (suffix === 'array') {
  13610. type += `_${suffix}`;
  13611. }
  13612. }
  13613. if (typeName === 'array' || typeName === 'stream' || typeName === 'memlet' || type.endsWith('stream_array')) {
  13614. if (parser.match('<')) {
  13615. const content = parser.skip('<', '>');
  13616. type += content;
  13617. }
  13618. return new mlir.Type(type);
  13619. }
  13620. return null;
  13621. }
  13622. parseOperation(parser, opName, op) {
  13623. if (opName === 'sdfg.sdfg' || opName === 'sdfg.nested_sdfg' || opName === 'sdir.sdfg') {
  13624. parser.parseOptionalAttrDict(op.attributes);
  13625. const type = {};
  13626. const inputResult = parser.parseFunctionArgumentList();
  13627. type.inputs = inputResult.arguments.map((a) => a.type);
  13628. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13629. type.results = [];
  13630. if (parser.accept('->')) {
  13631. const outputResult = parser.parseFunctionArgumentList();
  13632. type.results = outputResult.arguments.map((a) => a.type);
  13633. }
  13634. op.attributes.push({ name: 'function_type', value: type });
  13635. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13636. if (parser.match('{')) {
  13637. const region = {};
  13638. parser.parseRegion(region);
  13639. op.regions.push(region);
  13640. }
  13641. return true;
  13642. }
  13643. if (opName === 'sdfg.tasklet' || opName === 'sdir.tasklet') {
  13644. parser.parseOptionalAttrDict(op.attributes);
  13645. op.sym_name = parser.parseOptionalSymbolName();
  13646. if (parser.match('(')) {
  13647. op.operands = parser.parseArguments();
  13648. }
  13649. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13650. if (parser.accept('->')) {
  13651. if (parser.accept('(')) {
  13652. while (!parser.accept(')')) {
  13653. const type = parser.parseType();
  13654. op.results.push({ type });
  13655. parser.accept(',');
  13656. }
  13657. } else {
  13658. const type = parser.parseType();
  13659. op.results.push({ type });
  13660. }
  13661. }
  13662. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13663. if (parser.match('{')) {
  13664. const region = {};
  13665. parser.parseRegion(region);
  13666. op.regions.push(region);
  13667. }
  13668. return true;
  13669. }
  13670. if (opName === 'sdfg.consume') {
  13671. parser.parseOptionalAttrDict(op.attributes);
  13672. if (parser.match('(')) {
  13673. op.operands = parser.parseArguments();
  13674. }
  13675. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13676. if (parser.accept('->')) {
  13677. if (parser.accept('(')) {
  13678. while (!parser.accept(')')) {
  13679. if (parser.match('id')) {
  13680. const name = parser.expect('id');
  13681. if (parser.accept(':')) {
  13682. const value = parser.expect('%');
  13683. op.results.push({ name, value });
  13684. }
  13685. } else if (parser.match('%') || parser.match(')')) {
  13686. break;
  13687. } else {
  13688. throw new mlir.Error(`Expected named result in sdfg.consume but got '${parser.getToken().value}' ${parser.location()}`);
  13689. }
  13690. parser.accept(',');
  13691. }
  13692. }
  13693. }
  13694. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13695. if (parser.match('{')) {
  13696. const region = {};
  13697. parser.parseRegion(region);
  13698. op.regions.push(region);
  13699. }
  13700. return true;
  13701. }
  13702. if (opName === 'sdfg.state' || opName === 'sdir.state') {
  13703. parser.parseOptionalAttrDict(op.attributes);
  13704. op.sym_name = parser.parseOptionalSymbolName();
  13705. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13706. const region = {};
  13707. parser.parseRegion(region);
  13708. op.regions.push(region);
  13709. return true;
  13710. }
  13711. if (opName === 'sdfg.alloc' || opName === 'sdir.alloc' || opName === 'sdir.alloc_transient' || opName === 'sdir.alloc_stream') {
  13712. parser.parseOptionalAttrDict(op.attributes);
  13713. if (parser.match('(')) {
  13714. op.operands = parser.parseArguments();
  13715. }
  13716. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13717. if (parser.accept(':')) {
  13718. const type = parser.parseType();
  13719. op.results.push({ type });
  13720. }
  13721. return true;
  13722. }
  13723. if (opName === 'sdfg.store' || opName === 'sdir.store') {
  13724. parser.parseOptionalAttrDict(op.attributes);
  13725. const value = parser.expect('%');
  13726. op.operands.push({ value });
  13727. parser.accept(',');
  13728. const array = parser.expect('%');
  13729. op.operands.push({ value: array });
  13730. if (parser.accept('[')) {
  13731. while (!parser.match(']')) {
  13732. if (parser.match('%')) {
  13733. const idx = parser.expect('%');
  13734. op.operands.push({ value: idx });
  13735. } else {
  13736. parser.expect();
  13737. }
  13738. if (parser.match(',')) {
  13739. parser.accept(',');
  13740. }
  13741. }
  13742. parser.accept(']');
  13743. }
  13744. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13745. if (parser.accept(':')) {
  13746. const valueType = parser.parseType();
  13747. parser.accept('->');
  13748. const arrayType = parser.parseType();
  13749. if (op.operands.length > 0) {
  13750. op.operands[0].type = valueType;
  13751. }
  13752. if (op.operands.length > 1) {
  13753. op.operands[1].type = arrayType;
  13754. }
  13755. }
  13756. return true;
  13757. }
  13758. if (opName === 'sdfg.load' || opName === 'sdir.load') {
  13759. parser.parseOptionalAttrDict(op.attributes);
  13760. const array = parser.expect('%');
  13761. op.operands.push({ value: array });
  13762. if (parser.accept('[')) {
  13763. while (!parser.match(']')) {
  13764. if (parser.match('%')) {
  13765. const idx = parser.expect('%');
  13766. op.operands.push({ value: idx });
  13767. } else {
  13768. parser.expect();
  13769. }
  13770. if (parser.match(',')) {
  13771. parser.accept(',');
  13772. }
  13773. }
  13774. parser.accept(']');
  13775. }
  13776. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13777. if (parser.accept(':')) {
  13778. const arrayType = parser.parseType();
  13779. parser.accept('->');
  13780. const resultType = parser.parseType();
  13781. if (op.operands.length > 0) {
  13782. op.operands[0].type = arrayType;
  13783. }
  13784. op.results.push({ type: resultType });
  13785. }
  13786. return true;
  13787. }
  13788. if (opName === 'sdfg.map' || opName === 'sdir.map') {
  13789. parser.parseOptionalAttrDict(op.attributes);
  13790. const params = [];
  13791. if (parser.accept('(')) {
  13792. while (!parser.accept(')')) {
  13793. if (parser.match('%')) {
  13794. const param = parser.expect('%');
  13795. params.push(param);
  13796. }
  13797. if (parser.match(',')) {
  13798. parser.accept(',');
  13799. }
  13800. }
  13801. }
  13802. if (parser.accept('=')) {
  13803. parser.skip('(', ')');
  13804. }
  13805. if (parser.match('id', 'to')) {
  13806. parser.accept('id', 'to');
  13807. parser.skip('(', ')');
  13808. }
  13809. if (parser.match('id', 'step')) {
  13810. parser.accept('id', 'step');
  13811. parser.skip('(', ')');
  13812. }
  13813. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13814. if (parser.match('{')) {
  13815. const region = {};
  13816. parser.parseRegion(region);
  13817. op.regions.push(region);
  13818. }
  13819. return true;
  13820. }
  13821. if (opName === 'sdfg.consume' || opName === 'sdir.consume') {
  13822. parser.parseOptionalAttrDict(op.attributes);
  13823. if (parser.accept('(')) {
  13824. op.operands = parser.parseArguments();
  13825. }
  13826. if (parser.accept('->')) {
  13827. if (parser.accept('(')) {
  13828. while (!parser.accept(')')) {
  13829. parser.expect();
  13830. }
  13831. }
  13832. }
  13833. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13834. if (parser.match('{')) {
  13835. const region = {};
  13836. parser.parseRegion(region);
  13837. op.regions.push(region);
  13838. }
  13839. return true;
  13840. }
  13841. if (opName === 'sdfg.edge' || opName === 'sdir.edge') {
  13842. parser.parseOptionalAttrDict(op.attributes);
  13843. if (parser.match('(')) {
  13844. op.operands = parser.parseArguments();
  13845. }
  13846. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13847. if (parser.match('@')) {
  13848. const src = parser.expect('@');
  13849. op.attributes.push({ name: 'src', value: src });
  13850. }
  13851. parser.accept('->');
  13852. if (parser.match('@')) {
  13853. const dst = parser.expect('@');
  13854. op.attributes.push({ name: 'dst', value: dst });
  13855. }
  13856. return true;
  13857. }
  13858. if (opName === 'sdfg.sym' || opName === 'sdir.sym') {
  13859. if (parser.accept('(')) {
  13860. const expr = parser.expect('string');
  13861. op.attributes.push({ name: 'expr', value: expr });
  13862. parser.accept(')');
  13863. }
  13864. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13865. if (parser.accept(':')) {
  13866. const type = parser.parseType();
  13867. op.results.push({ type });
  13868. }
  13869. return true;
  13870. }
  13871. if (opName === 'sdfg.copy' || opName === 'sdir.copy') {
  13872. parser.parseOptionalAttrDict(op.attributes);
  13873. op.operands = parser.parseArguments();
  13874. if (parser.accept('->')) {
  13875. const dst = parser.parseArguments();
  13876. op.operands.push(...dst);
  13877. }
  13878. if (parser.accept(':')) {
  13879. const type = parser.parseType();
  13880. for (const operand of op.operands) {
  13881. if (!operand.type) {
  13882. operand.type = type;
  13883. }
  13884. }
  13885. }
  13886. return true;
  13887. }
  13888. if (opName === 'sdfg.libcall' || opName === 'sdir.libcall') {
  13889. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13890. if (parser.match('string')) {
  13891. const libname = parser.expect('string');
  13892. op.attributes.push({ name: 'libname', value: libname });
  13893. }
  13894. op.operands = parser.parseArguments();
  13895. if (parser.accept(':')) {
  13896. if (parser.accept('(')) {
  13897. while (!parser.accept(')')) {
  13898. parser.parseType();
  13899. parser.accept(',');
  13900. }
  13901. }
  13902. if (parser.accept('->')) {
  13903. const resultType = parser.parseType();
  13904. op.results.push({ type: resultType });
  13905. }
  13906. }
  13907. return true;
  13908. }
  13909. if (opName === 'sdfg.get_access' || opName === 'sdir.get_access') {
  13910. if (parser.match('%')) {
  13911. const value = parser.expect();
  13912. op.operands.push({ value });
  13913. }
  13914. if (parser.accept(':')) {
  13915. const inputType = parser.parseType();
  13916. if (op.operands.length > 0) {
  13917. op.operands[0].type = inputType;
  13918. }
  13919. if (parser.accept('->')) {
  13920. const resultType = parser.parseType();
  13921. op.results.push({ type: resultType });
  13922. }
  13923. }
  13924. return true;
  13925. }
  13926. if (opName === 'sdir.call') {
  13927. const callee = parser.parseOptionalSymbolName();
  13928. if (callee) {
  13929. op.attributes.push({ name: 'callee', value: callee });
  13930. }
  13931. if (parser.match('(')) {
  13932. op.operands = parser.parseArguments();
  13933. }
  13934. if (parser.accept(':')) {
  13935. if (parser.accept('(')) {
  13936. while (!parser.accept(')')) {
  13937. parser.parseType();
  13938. parser.accept(',');
  13939. }
  13940. }
  13941. if (parser.accept('->')) {
  13942. const resultType = parser.parseType();
  13943. op.results.push({ type: resultType });
  13944. }
  13945. }
  13946. return true;
  13947. }
  13948. if (opName === 'sdfg.alloc_symbol' || opName === 'sdir.alloc_symbol') {
  13949. if (parser.accept('(')) {
  13950. const sym = parser.expect('string');
  13951. op.attributes.push({ name: 'sym', value: sym });
  13952. parser.accept(')');
  13953. }
  13954. return true;
  13955. }
  13956. if (opName === 'sdfg.return') {
  13957. if (parser.match('%')) {
  13958. op.operands = parser.parseArguments();
  13959. // Reference: parseOptionalColonTypeList
  13960. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  13961. }
  13962. return true;
  13963. }
  13964. if (opName === 'sdfg.stream_push' || opName === 'sdir.stream_push') {
  13965. parser.parseOptionalAttrDict(op.attributes);
  13966. const value = parser.expect('%');
  13967. op.operands.push({ value });
  13968. parser.accept(',');
  13969. const stream = parser.expect('%');
  13970. op.operands.push({ value: stream });
  13971. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13972. if (parser.accept(':')) {
  13973. const valueType = parser.parseType();
  13974. parser.accept('->');
  13975. const streamType = parser.parseType();
  13976. if (op.operands.length > 0) {
  13977. op.operands[0].type = valueType;
  13978. }
  13979. if (op.operands.length > 1) {
  13980. op.operands[1].type = streamType;
  13981. }
  13982. }
  13983. return true;
  13984. }
  13985. if (opName === 'sdfg.stream_pop' || opName === 'sdir.stream_pop') {
  13986. parser.parseOptionalAttrDict(op.attributes);
  13987. const stream = parser.expect('%');
  13988. op.operands.push({ value: stream });
  13989. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  13990. if (parser.accept(':')) {
  13991. const streamType = parser.parseType();
  13992. parser.accept('->');
  13993. const resultType = parser.parseType();
  13994. if (op.operands.length > 0) {
  13995. op.operands[0].type = streamType;
  13996. }
  13997. op.results.push({ type: resultType });
  13998. }
  13999. return true;
  14000. }
  14001. if (opName === 'sdfg.stream_length' || opName === 'sdir.stream_length') {
  14002. parser.parseOptionalAttrDict(op.attributes);
  14003. const stream = parser.expect('%');
  14004. op.operands.push({ value: stream });
  14005. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  14006. if (parser.accept(':')) {
  14007. const streamType = parser.parseType();
  14008. parser.accept('->');
  14009. const resultType = parser.parseType();
  14010. if (op.operands.length > 0) {
  14011. op.operands[0].type = streamType;
  14012. }
  14013. op.results.push({ type: resultType });
  14014. }
  14015. return true;
  14016. }
  14017. if (opName === 'sdfg.view_cast' || opName === 'sdir.view_cast') {
  14018. parser.parseOptionalAttrDict(op.attributes);
  14019. const input = parser.expect('%');
  14020. op.operands.push({ value: input });
  14021. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  14022. if (parser.accept(':')) {
  14023. const inputType = parser.parseType();
  14024. parser.accept('->');
  14025. const resultType = parser.parseType();
  14026. if (op.operands.length > 0) {
  14027. op.operands[0].type = inputType;
  14028. }
  14029. op.results.push({ type: resultType });
  14030. }
  14031. return true;
  14032. }
  14033. if (opName === 'sdfg.subview' || opName === 'sdir.subview') {
  14034. parser.parseOptionalAttrDict(op.attributes);
  14035. const input = parser.expect('%');
  14036. op.operands.push({ value: input });
  14037. while (parser.accept('[')) {
  14038. while (!parser.accept(']')) {
  14039. parser.expect();
  14040. }
  14041. }
  14042. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  14043. if (parser.accept(':')) {
  14044. const inputType = parser.parseType();
  14045. parser.accept('->');
  14046. const resultType = parser.parseType();
  14047. if (op.operands.length > 0) {
  14048. op.operands[0].type = inputType;
  14049. }
  14050. op.results.push({ type: resultType });
  14051. }
  14052. return true;
  14053. }
  14054. return super.parseOperation(parser, opName, op);
  14055. }
  14056. };
  14057. mlir.TFLDialect = class extends mlir.Dialect {
  14058. constructor(operations) {
  14059. super('tfl', operations);
  14060. // Operations that use parseOneResultSameOperandTypeOp in tfl_ops.cc
  14061. // Format: operands attr-dict : single-type
  14062. this._binaryOps = new Set([
  14063. 'add', 'sub', 'mul', 'div', 'floor_div', 'pow', 'squared_difference',
  14064. 'less', 'less_equal', 'greater', 'greater_equal', 'not_equal',
  14065. 'logical_and', 'logical_or'
  14066. ]);
  14067. }
  14068. parseOperation(parser, opName, op) {
  14069. const opKind = opName.substring('tfl.'.length);
  14070. if (opKind === 'control_node') {
  14071. if (parser.accept('(')) {
  14072. parser.parseOptionalSSAUseList(op.operands);
  14073. parser.expect(')');
  14074. }
  14075. if (parser.accept('id', 'controls')) {
  14076. const region = { blocks: [{ operations: [] }] };
  14077. const innerOp = parser.parseGenericOperation();
  14078. region.blocks[0].operations.push(innerOp);
  14079. op.regions.push(region);
  14080. } else if (parser.match('{')) {
  14081. const region = {};
  14082. parser.parseRegion(region);
  14083. op.regions.push(region);
  14084. }
  14085. parser.parseOptionalAttrDict(op.attributes);
  14086. return true;
  14087. }
  14088. if (this._binaryOps.has(opKind)) {
  14089. // Parse: operands attr-dict : type (compact form)
  14090. // Or: (operands) <properties> : fn-type (generic form)
  14091. if (parser.match('(')) {
  14092. parser.expect('(');
  14093. parser.parseOptionalSSAUseList(op.operands);
  14094. parser.expect(')');
  14095. parser.parsePropertyDict(op.attributes);
  14096. parser.parseOptionalAttrDict(op.attributes);
  14097. if (parser.accept(':')) {
  14098. const fnType = parser.parseType();
  14099. if (fnType instanceof mlir.FunctionType) {
  14100. for (let i = 0; i < fnType.inputs.length && i < op.operands.length; i++) {
  14101. op.operands[i].type = fnType.inputs[i].toString();
  14102. }
  14103. for (let i = 0; i < fnType.results.length; i++) {
  14104. op.results.push({ type: fnType.results[i].toString() });
  14105. }
  14106. } else {
  14107. for (const operand of op.operands) {
  14108. operand.type = fnType;
  14109. }
  14110. op.results.push({ type: fnType });
  14111. }
  14112. }
  14113. return true;
  14114. }
  14115. op.operands = parser.parseArguments();
  14116. parser.parseOptionalAttrDict(op.attributes);
  14117. if (parser.accept(':')) {
  14118. const type = parser.parseType();
  14119. for (const operand of op.operands) {
  14120. operand.type = type;
  14121. }
  14122. if (op.results.length > 0) {
  14123. op.results[0].type = type;
  14124. }
  14125. }
  14126. return true;
  14127. }
  14128. return super.parseOperation(parser, opName, op);
  14129. }
  14130. };
  14131. mlir.TFDialect = class extends mlir.Dialect {
  14132. constructor(operations) {
  14133. super('tf', operations);
  14134. }
  14135. parseType(parser, dialectName) {
  14136. const typeName = parser.parseKeyword();
  14137. if (!typeName) {
  14138. return null;
  14139. }
  14140. let type = `!${dialectName}.${typeName}`;
  14141. if (typeName === 'resource' || typeName === 'variant') {
  14142. if (parser.match('<')) {
  14143. const content = parser.skip('<', '>');
  14144. type += content;
  14145. }
  14146. return new mlir.Type(type);
  14147. }
  14148. if (typeName === 'string' || typeName === 'control') {
  14149. return new mlir.Type(type);
  14150. }
  14151. return null;
  14152. }
  14153. };
  14154. mlir.TFTypeDialect = class extends mlir.Dialect {
  14155. constructor(operations) {
  14156. super('tf_type', operations);
  14157. this.simpleTypes = new Set([
  14158. 'string', 'qint8', 'qint16', 'qint32', 'quint8', 'quint16',
  14159. 'f32ref', 'f64ref', 'uint4ref', 'int4ref', 'uint8ref', 'int8ref',
  14160. 'uint16ref', 'int16ref', 'uint32ref', 'int32ref', 'uint64ref', 'int64ref',
  14161. 'stringref', 'boolref', 'quint8ref', 'qint8ref', 'quint16ref', 'qint16ref',
  14162. 'qint32ref', 'bfloat16ref', 'complex64ref', 'complex128ref', 'halfref',
  14163. 'resourceref', 'variantref',
  14164. 'float8e4m3fnref', 'float8e5m2ref', 'float8e4m3fnuzref',
  14165. 'float8e4m3b11fnuzref', 'float8e5m2fnuzref'
  14166. ]);
  14167. }
  14168. parseType(parser, dialectName) {
  14169. const typeName = parser.parseKeyword();
  14170. if (!typeName) {
  14171. return null;
  14172. }
  14173. const type = `!${dialectName}.${typeName}`;
  14174. if (typeName === 'resource' || typeName === 'variant') {
  14175. if (parser.accept('<')) {
  14176. const subtypes = [];
  14177. while (!parser.match('>')) {
  14178. subtypes.push(parser.parseType());
  14179. parser.accept(',');
  14180. }
  14181. parser.expect('>');
  14182. return `${type}<${subtypes.join(', ')}>`;
  14183. }
  14184. return new mlir.Type(type);
  14185. }
  14186. if (this.simpleTypes.has(typeName)) {
  14187. return new mlir.Type(type);
  14188. }
  14189. return null;
  14190. }
  14191. };
  14192. mlir.CheckDialect = class extends mlir.Dialect {
  14193. constructor(operations) {
  14194. super('check', operations);
  14195. }
  14196. };
  14197. mlir.TransformDialect = class extends mlir.Dialect {
  14198. constructor(operations) {
  14199. super('transform', operations);
  14200. this.registerCustomDirective('PackedOrDynamicIndexList', this._parseDynamicIndexList.bind(this));
  14201. this.registerCustomDirective('SemiFunctionType', this._parseSemiFunctionType.bind(this));
  14202. this.registerCustomDirective('SequenceOpOperands', this._parseSequenceOpOperands.bind(this));
  14203. this.registerCustomDirective('ForeachMatchSymbols', this._parseForeachMatchSymbols.bind(this));
  14204. this.registerCustomDirective('TransformMatchDims', this._parseTransformMatchDims.bind(this));
  14205. }
  14206. parseOperation(parser, opName, op) {
  14207. if (opName === 'transform.named_sequence') {
  14208. return this._parseNamedSequenceOp(parser, op);
  14209. }
  14210. // C++-only operation: transform.test_transform_op ["message"]
  14211. // Defined in mlir/test/lib/Dialect/Transform/TestTransformDialectExtension.cpp
  14212. if (opName === 'transform.test_transform_op') {
  14213. if (parser.match('string')) {
  14214. const message = parser.expect('string');
  14215. op.attributes.push({ name: 'message', value: message });
  14216. }
  14217. return true;
  14218. }
  14219. // C++-only operation: transform.iree.register_match_callbacks
  14220. // Used in IREE tests for registering pattern matching callbacks
  14221. if (opName === 'transform.iree.register_match_callbacks') {
  14222. // No operands or attributes
  14223. return true;
  14224. }
  14225. // C++-only operation: transform.iree.match_callback failures(propagate) "name"(%op) : (types) -> (types)
  14226. if (opName === 'transform.iree.match_callback') {
  14227. // Parse optional failures(propagate)
  14228. if (parser.accept('id', 'failures')) {
  14229. parser.expect('(');
  14230. parser.expect('id'); // propagate, suppress, etc.
  14231. parser.expect(')');
  14232. }
  14233. // Parse callback name
  14234. if (parser.match('string')) {
  14235. const callbackName = parser.expect('string');
  14236. op.attributes.push({ name: 'callback_name', value: callbackName });
  14237. }
  14238. // Parse operands
  14239. if (parser.accept('(')) {
  14240. while (!parser.match(')')) {
  14241. if (parser.match('%')) {
  14242. op.operands.push({ value: parser.expect('%') });
  14243. }
  14244. if (!parser.accept(',')) {
  14245. break;
  14246. }
  14247. }
  14248. parser.expect(')');
  14249. }
  14250. // Parse : (input_types) -> (result_types)
  14251. if (parser.accept(':')) {
  14252. parser.expect('(');
  14253. while (!parser.match(')')) {
  14254. parser.parseType();
  14255. if (!parser.accept(',')) {
  14256. break;
  14257. }
  14258. }
  14259. parser.expect(')');
  14260. if (parser.accept('->')) {
  14261. parser.expect('(');
  14262. const resultTypes = [];
  14263. while (!parser.match(')')) {
  14264. resultTypes.push(parser.parseType());
  14265. if (!parser.accept(',')) {
  14266. break;
  14267. }
  14268. }
  14269. parser.expect(')');
  14270. for (const type of resultTypes) {
  14271. op.results.push({ type });
  14272. }
  14273. }
  14274. }
  14275. return true;
  14276. }
  14277. // C++-only operation: transform.iree.take_first %op1, %op2 : (types) -> (types)
  14278. if (opName === 'transform.iree.take_first') {
  14279. // Parse operands
  14280. while (parser.match('%')) {
  14281. op.operands.push({ value: parser.expect('%') });
  14282. if (!parser.accept(',')) {
  14283. break;
  14284. }
  14285. }
  14286. // Parse : (input_types) -> (result_types)
  14287. if (parser.accept(':')) {
  14288. parser.expect('(');
  14289. while (!parser.match(')')) {
  14290. parser.parseType();
  14291. if (!parser.accept(',')) {
  14292. break;
  14293. }
  14294. }
  14295. parser.expect(')');
  14296. if (parser.accept('->')) {
  14297. parser.expect('(');
  14298. const resultTypes = [];
  14299. while (!parser.match(')')) {
  14300. resultTypes.push(parser.parseType());
  14301. if (!parser.accept(',')) {
  14302. break;
  14303. }
  14304. }
  14305. parser.expect(')');
  14306. for (const type of resultTypes) {
  14307. op.results.push({ type });
  14308. }
  14309. }
  14310. }
  14311. return true;
  14312. }
  14313. return super.parseOperation(parser, opName, op);
  14314. }
  14315. _parseSequenceOpOperands(parser, op /*, args */) {
  14316. if (parser.match('%')) {
  14317. const rootOperand = parser.expect('%');
  14318. op.operands.push({ value: rootOperand });
  14319. if (parser.accept(',')) {
  14320. while (parser.match('%')) {
  14321. const extraOperand = parser.expect('%');
  14322. op.operands.push({ value: extraOperand });
  14323. if (!parser.accept(',')) {
  14324. break;
  14325. }
  14326. }
  14327. }
  14328. }
  14329. if (parser.accept(':')) {
  14330. parser.accept('(');
  14331. const types = parser.parseTypeListNoParens();
  14332. parser.resolveOperands(op.operands, types);
  14333. parser.accept(')');
  14334. }
  14335. }
  14336. _parseForeachMatchSymbols(parser, op, args) {
  14337. const matchers = [];
  14338. const actions = [];
  14339. do {
  14340. const matcher = parser.expect('@');
  14341. parser.expect('->');
  14342. const action = parser.expect('@');
  14343. matchers.push(matcher);
  14344. actions.push(action);
  14345. } while (parser.accept(','));
  14346. const matchersAttr = args[0].replace('$', '');
  14347. const actionsAttr = args[1].replace('$', '');
  14348. op.attributes.push({ name: matchersAttr, value: matchers });
  14349. op.attributes.push({ name: actionsAttr, value: actions });
  14350. }
  14351. _parseTransformMatchDims(parser, op, args) {
  14352. if (parser.accept('id', 'all')) {
  14353. const allAttr = args[2].replace('$', '');
  14354. op.attributes.push({ name: allAttr, value: true });
  14355. return;
  14356. }
  14357. const isInverted = parser.accept('id', 'except');
  14358. if (isInverted) {
  14359. parser.expect('(');
  14360. }
  14361. const dims = [];
  14362. do {
  14363. if (parser.match('int')) {
  14364. dims.push(parser.parseInteger());
  14365. }
  14366. } while (parser.accept(','));
  14367. if (isInverted) {
  14368. parser.expect(')');
  14369. const invertedAttr = args[1].replace('$', '');
  14370. op.attributes.push({ name: invertedAttr, value: true });
  14371. }
  14372. const dimsAttr = args[0].replace('$', '');
  14373. op.attributes.push({ name: dimsAttr, value: dims });
  14374. }
  14375. parseType(parser, dialectName) {
  14376. const typeName = parser.parseKeyword();
  14377. if (!typeName) {
  14378. return null;
  14379. }
  14380. let type = `!${dialectName}.${typeName}`;
  14381. if (typeName === 'any' && parser.match('_')) {
  14382. parser.expect('_');
  14383. const suffix = parser.expect('id');
  14384. type += `_${suffix}`;
  14385. }
  14386. if (parser.match('<')) {
  14387. const content = parser.skip('<', '>');
  14388. type += content;
  14389. }
  14390. return new mlir.Type(type);
  14391. }
  14392. _parseNamedSequenceOp(parser, op) {
  14393. parser.parseOptionalVisibilityKeyword(op.attributes);
  14394. parser.parseSymbolName('sym_name', op.attributes);
  14395. const type = {};
  14396. const argResult = parser.parseFunctionArgumentList();
  14397. type.inputs = argResult.arguments.map((a) => a.type);
  14398. type.results = [];
  14399. const resultAttrs = [];
  14400. if (parser.accept('->')) {
  14401. parser.parseFunctionResultList(type.results, resultAttrs);
  14402. }
  14403. op.attributes.push({ name: 'function_type', value: type });
  14404. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  14405. if (parser.match('{')) {
  14406. const region = {};
  14407. parser.parseRegion(region);
  14408. op.regions.push(region);
  14409. }
  14410. return true;
  14411. }
  14412. _parseSemiFunctionType(parser, op /* , args */) {
  14413. // Reference: Syntax.cpp parseSemiFunctionType
  14414. // Format: type OR (type) -> result_types
  14415. const hasLParen = parser.accept('(');
  14416. // Parse the argument type (first operand type)
  14417. const argType = parser.parseType();
  14418. if (op.operands.length > 0) {
  14419. op.operands[0].type = argType;
  14420. }
  14421. if (!hasLParen) {
  14422. return;
  14423. }
  14424. // Had '(' so expect ')' -> result_types
  14425. parser.expect(')');
  14426. parser.expect('->');
  14427. // Handle both single type and parenthesized type list
  14428. if (parser.accept('(')) {
  14429. let idx = 0;
  14430. while (!parser.match(')')) {
  14431. const type = parser.parseType();
  14432. if (idx < op.results.length) {
  14433. op.results[idx].type = type;
  14434. } else {
  14435. op.results.push({ type });
  14436. }
  14437. idx++;
  14438. if (!parser.accept(',')) {
  14439. break;
  14440. }
  14441. }
  14442. parser.expect(')');
  14443. } else {
  14444. const type = parser.parseType();
  14445. if (op.results.length > 0) {
  14446. op.results[0].type = type;
  14447. } else {
  14448. op.results.push({ type });
  14449. }
  14450. }
  14451. }
  14452. };
  14453. mlir.TestDialect = class extends mlir.Dialect {
  14454. constructor(operations) {
  14455. super('test', operations);
  14456. this.registerCustomAttribute('TestBitEnumProp', this._parseTestBitEnumProp.bind(this));
  14457. }
  14458. parseOperation(parser, opName, op) {
  14459. // test.conversion_func_op is a function-like operation with FunctionOpInterface
  14460. // Parse it like func.func to handle argument and result attributes properly
  14461. if (opName === 'test.conversion_func_op') {
  14462. parser.parseFunctionOp(op, false);
  14463. return true;
  14464. }
  14465. // test.call_on_device has assembly format: $callee `(` $forwarded_operands `)` `,` $device_operand attr-dict `:` functional-type(operands, results)
  14466. // This is not in metadata, so parse it manually to match reference implementation.
  14467. // Reference: mlir/test/lib/Dialect/Test/TestOps.td
  14468. if (opName === 'test.call_on_device') {
  14469. if (parser.match('@')) {
  14470. const callee = parser.expect('@');
  14471. op.attributes.push({ name: 'callee', value: callee });
  14472. }
  14473. if (parser.accept('(')) {
  14474. while (!parser.match(')')) {
  14475. if (parser.match('%')) {
  14476. const operand = parser.parseAttribute();
  14477. op.operands.push(operand);
  14478. if (!parser.accept(',')) {
  14479. break;
  14480. }
  14481. } else {
  14482. break;
  14483. }
  14484. }
  14485. parser.expect(')');
  14486. }
  14487. if (parser.accept(',')) {
  14488. if (parser.match('%')) {
  14489. const deviceOperand = parser.parseAttribute();
  14490. op.operands.push(deviceOperand);
  14491. }
  14492. }
  14493. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  14494. parser.resolveOperands(op.operands, parser.parseOptionalColonTypeList());
  14495. if (parser.accept('->')) {
  14496. const resultTypes = parser.parseFunctionResultTypes();
  14497. parser.resolveOperands(op.results, resultTypes);
  14498. }
  14499. return true;
  14500. }
  14501. // test.region_if has custom assembly format
  14502. if (opName === 'test.region_if') {
  14503. // Parse: $operands : type($operands) -> (type($results)) then $thenRegion else $elseRegion join $joinRegion
  14504. while (parser.match('%')) {
  14505. op.operands.push({ value: parser.expect('%') });
  14506. if (!parser.accept(',')) {
  14507. break;
  14508. }
  14509. }
  14510. parser.expect(':');
  14511. const inputTypes = parser.parseTypeList();
  14512. parser.resolveOperands(op.operands, inputTypes);
  14513. parser.expect('->');
  14514. const outputTypes = parser.parseTypeListParens();
  14515. for (const t of outputTypes) {
  14516. op.results.push({ type: t.toString() });
  14517. }
  14518. parser.expect('id', 'then');
  14519. const thenRegion = {};
  14520. parser.parseRegion(thenRegion);
  14521. op.regions.push(thenRegion);
  14522. parser.expect('id', 'else');
  14523. const elseRegion = {};
  14524. parser.parseRegion(elseRegion);
  14525. op.regions.push(elseRegion);
  14526. parser.expect('id', 'join');
  14527. const joinRegion = {};
  14528. parser.parseRegion(joinRegion);
  14529. op.regions.push(joinRegion);
  14530. return true;
  14531. }
  14532. return super.parseOperation(parser, opName, op);
  14533. }
  14534. _parseTestBitEnumProp(parser, type) {
  14535. if (type.values.includes(parser.getToken().value)) {
  14536. return this._parseEnumFlags(parser, type, ',');
  14537. }
  14538. return null;
  14539. }
  14540. };
  14541. mlir.TritonDialect = class extends mlir.Dialect {
  14542. constructor(operations) {
  14543. super('tt', operations);
  14544. this.registerCustomType('TT_Ptr', this._parsePtr.bind(this));
  14545. this.registerCustomType('TT_TensorDescType', this._parseTensorDescType.bind(this));
  14546. this.registerCustomType('TT_TensorPtr', this._parseTensorPtr.bind(this));
  14547. }
  14548. parseType(parser, dialectName) {
  14549. const typeName = parser.parseKeyword();
  14550. if (!typeName) {
  14551. return null;
  14552. }
  14553. let type = `!${dialectName}.${typeName}`;
  14554. if (parser.match('<')) {
  14555. const content = parser.skip('<', '>');
  14556. type += content;
  14557. }
  14558. return new mlir.Type(type);
  14559. }
  14560. parseOperation(parser, opName, op) {
  14561. if (opName === 'tt.func') {
  14562. parser.parseFunctionOp(op, false);
  14563. return true;
  14564. }
  14565. return super.parseOperation(parser, opName, op);
  14566. }
  14567. _parseTensorPtr(parser) {
  14568. if (parser.match('<')) {
  14569. const content = parser.skip('<', '>');
  14570. return new mlir.Type(`!tt.ptr${content}`);
  14571. }
  14572. return null;
  14573. }
  14574. _parsePtr(parser) {
  14575. if (parser.match('<')) {
  14576. const content = parser.skip('<', '>');
  14577. return new mlir.Type(`!tt.ptr${content}`);
  14578. }
  14579. return null;
  14580. }
  14581. _parseTensorDescType(parser) {
  14582. if (parser.match('<')) {
  14583. const content = parser.skip('<', '>');
  14584. return new mlir.Type(`!tt.tensor_desc${content}`);
  14585. }
  14586. return null;
  14587. }
  14588. };
  14589. mlir.TritonGPUDialect = class extends mlir.Dialect {
  14590. constructor(operations) {
  14591. super('ttg', operations);
  14592. // Register custom type parser for MemDescType shorthand notation
  14593. this.registerCustomType('TTG_MemDescType', this._parseMemDescType.bind(this));
  14594. }
  14595. _parseMemDescType(parser) {
  14596. // Handle shorthand MemDescType notation: <dims x elementType, attributes...>
  14597. // Full notation would be: !ttg.memdesc<dims x elementType, attributes...>
  14598. if (!parser.match('<')) {
  14599. return null;
  14600. }
  14601. const content = parser.skip('<', '>');
  14602. return new mlir.Type(`!ttg.memdesc<${content}>`);
  14603. }
  14604. parseOperation(parser, opName, op) {
  14605. if (opName === 'ttg.warp_specialize') {
  14606. parser.expect('(');
  14607. while (!parser.match(')')) {
  14608. const operand = {};
  14609. operand.name = parser.expect('%');
  14610. op.operands.push(operand);
  14611. if (!parser.match(')')) {
  14612. parser.expect(',');
  14613. }
  14614. }
  14615. parser.expect(')');
  14616. parser.parseOptionalAttrDictWithKeyword(op.attributes);
  14617. parser.expect('id', 'default');
  14618. const defaultRegion = {};
  14619. parser.parseRegion(defaultRegion);
  14620. op.regions.push(defaultRegion);
  14621. const partitionNumWarps = [];
  14622. let partitionIndex = 0;
  14623. while (parser.match('id', `partition${partitionIndex}`)) {
  14624. parser.expect('id', `partition${partitionIndex}`);
  14625. const argResult = parser.parseFunctionArgumentList();
  14626. parser.expect('id', 'num_warps');
  14627. parser.expect('(');
  14628. const numWarps = parser.expect();
  14629. partitionNumWarps.push(parseInt(numWarps, 10));
  14630. parser.expect(')');
  14631. const partitionRegion = {};
  14632. partitionRegion.arguments = argResult.arguments;
  14633. parser.parseRegion(partitionRegion);
  14634. if (!op.regions[1]) {
  14635. op.regions[1] = { blocks: [{ operations: [] }] };
  14636. }
  14637. partitionIndex++;
  14638. }
  14639. parser.expect(':');
  14640. const type = {};
  14641. type.inputs = [];
  14642. type.results = [];
  14643. parser.expect('(');
  14644. while (!parser.match(')')) {
  14645. type.inputs.push(parser.parseType());
  14646. if (!parser.match(')')) {
  14647. parser.expect(',');
  14648. }
  14649. }
  14650. parser.expect(')');
  14651. parser.expect('->');
  14652. parser.expect('(');
  14653. while (!parser.match(')')) {
  14654. type.results.push(parser.parseType());
  14655. if (!parser.match(')')) {
  14656. parser.expect(',');
  14657. }
  14658. }
  14659. parser.expect(')');
  14660. op.attributes.push({ name: 'function_type', value: type });
  14661. if (partitionNumWarps.length > 0) {
  14662. op.attributes.push({
  14663. name: 'partitionNumWarps',
  14664. value: { type: 'array', element_type: 'i32', value: partitionNumWarps }
  14665. });
  14666. }
  14667. return true;
  14668. }
  14669. return super.parseOperation(parser, opName, op);
  14670. }
  14671. parseType(parser, dialectName) {
  14672. const typeName = parser.parseKeyword();
  14673. if (!typeName) {
  14674. return null;
  14675. }
  14676. let type = `!${dialectName}.${typeName}`;
  14677. if (parser.match('<')) {
  14678. const content = parser.skip('<', '>');
  14679. type += content;
  14680. }
  14681. return new mlir.Type(type);
  14682. }
  14683. };
  14684. mlir.GluonDialect = class extends mlir.Dialect {
  14685. constructor(operations) {
  14686. super('gluon', operations);
  14687. }
  14688. };
  14689. mlir.TritonNvidiaGPUDialect = class extends mlir.Dialect {
  14690. constructor(operations) {
  14691. super('ttng', operations);
  14692. this.registerCustomDirective('Token', this._parseToken.bind(this));
  14693. this.registerCustomDirective('BarriersAndPreds', this._parseBarriersAndPreds.bind(this));
  14694. }
  14695. _parseToken(parser, op, args) {
  14696. if (!parser.accept('[')) {
  14697. return;
  14698. }
  14699. if (args && args.length >= 2) {
  14700. op.attributes.push({ name: args[1].replace(/^\$/, ''), value: '!ttng.async.token' });
  14701. }
  14702. if (parser.match(']')) {
  14703. parser.expect(']');
  14704. return;
  14705. }
  14706. if (parser.match('%')) {
  14707. const dep = parser.expect('%');
  14708. if (args && args.length > 0) {
  14709. op.operands.push({ value: dep });
  14710. }
  14711. }
  14712. parser.expect(']');
  14713. }
  14714. _parseBarriersAndPreds(parser, op, args) {
  14715. while (parser.accept(',')) {
  14716. if (parser.match('%')) {
  14717. const barrier = parser.expect('%');
  14718. if (args && args.length > 0) {
  14719. op.operands.push({ value: barrier });
  14720. }
  14721. if (parser.accept('[')) {
  14722. if (parser.match('%')) {
  14723. const pred = parser.expect('%');
  14724. if (args && args.length > 1) {
  14725. op.operands.push({ value: pred });
  14726. }
  14727. }
  14728. parser.expect(']');
  14729. }
  14730. }
  14731. }
  14732. }
  14733. parseType(parser, dialectName) {
  14734. const typeName = parser.parseKeyword();
  14735. if (!typeName) {
  14736. return null;
  14737. }
  14738. let type = `!${dialectName}.${typeName}`;
  14739. if (parser.match('<')) {
  14740. const content = parser.skip('<', '>');
  14741. type += content;
  14742. }
  14743. return new mlir.Type(type);
  14744. }
  14745. };
  14746. mlir.TritonAMDGPUDialect = class extends mlir.Dialect {
  14747. constructor(operations) {
  14748. super('amdg', operations);
  14749. this.registerCustomType('TT_Ptr', 'tt.ptr');
  14750. this.registerCustomType('TT_TensorPtr', 'tt.ptr');
  14751. this.registerCustomType('TTG_MemDescType', 'ttg.memdesc');
  14752. }
  14753. parseType(parser, dialectName) {
  14754. const typeName = parser.parseKeyword();
  14755. if (!typeName) {
  14756. return null;
  14757. }
  14758. let type = `!${dialectName}.${typeName}`;
  14759. if (parser.match('<')) {
  14760. const content = parser.skip('<', '>');
  14761. type += content;
  14762. }
  14763. return new mlir.Type(type);
  14764. }
  14765. };
  14766. mlir.ProtonDialect = class extends mlir.Dialect {
  14767. constructor(operations) {
  14768. super('proton', operations);
  14769. }
  14770. };
  14771. mlir.MichelsonDialect = class extends mlir.Dialect {
  14772. constructor(operations) {
  14773. super('michelson', operations);
  14774. }
  14775. parseType(parser, dialectName) {
  14776. const typeName = parser.parseKeyword();
  14777. if (!typeName) {
  14778. return null;
  14779. }
  14780. let type = `!${dialectName}.${typeName}`;
  14781. if ((typeName === 'big' || typeName === 'chain' || typeName === 'key') && parser.match('_')) {
  14782. parser.expect('_');
  14783. const suffix = parser.expect('id');
  14784. type += `_${suffix}`;
  14785. }
  14786. const simpleTypes = ['int', 'bytes', 'operation', 'nat', 'string', 'unit', 'bool', 'mutez', 'timestamp', 'address', 'key', 'signature', 'chain_id', 'key_hash'];
  14787. if (simpleTypes.includes(type.substring(11))) { // Remove "!michelson." prefix
  14788. return new mlir.Type(type);
  14789. }
  14790. const typesWithParams = ['pair', 'list', 'option', 'or', 'map', 'big_map', 'set', 'contract', 'lambda'];
  14791. if (typesWithParams.includes(type.substring(11))) {
  14792. if (parser.match('<')) {
  14793. const content = parser.skip('<', '>');
  14794. type += content;
  14795. }
  14796. return new mlir.Type(type);
  14797. }
  14798. return null;
  14799. }
  14800. };
  14801. mlir.PlanDialect = class extends mlir.Dialect {
  14802. constructor(operations) {
  14803. super('plan', operations);
  14804. this.registerCustomDirective('WithValuesTypes', this._parseWithValuesTypes.bind(this));
  14805. }
  14806. // Reference: PlanOps.cpp parseWithValuesTypes
  14807. // Parse: type($result) - just a single type, element types are inferred
  14808. _parseWithValuesTypes(parser, op /*, args */) {
  14809. const resultType = parser.parseType();
  14810. if (op.results.length === 0) {
  14811. op.results.push({ type: resultType });
  14812. } else {
  14813. op.results[0].type = resultType;
  14814. }
  14815. }
  14816. };
  14817. mlir.KernelDialect = class extends mlir.Dialect {
  14818. constructor(operations) {
  14819. super('kernel', operations);
  14820. this.registerCustomDirective('KernelFunctionalType', this._parseKernelFunctionalType.bind(this));
  14821. }
  14822. // Parse: (types) -> (types)
  14823. _parseKernelFunctionalType(parser /*, op, args */) {
  14824. parser.expect('(');
  14825. if (!parser.match(')')) {
  14826. do {
  14827. parser.parseType();
  14828. } while (parser.accept(','));
  14829. }
  14830. parser.expect(')');
  14831. parser.expect('->');
  14832. if (parser.accept('(')) {
  14833. if (!parser.match(')')) {
  14834. do {
  14835. parser.parseType();
  14836. } while (parser.accept(','));
  14837. }
  14838. parser.expect(')');
  14839. } else {
  14840. parser.parseType();
  14841. }
  14842. }
  14843. };
  14844. mlir.TensorRTDialect = class extends mlir.Dialect {
  14845. constructor(operations) {
  14846. super('tensorrt', operations);
  14847. this.registerCustomAttribute('TensorRT_TopKOperationAttr', this._parseEnumAttrBracket.bind(this));
  14848. this.registerCustomAttribute('TensorRT_ScatterModeAttr', this._parseEnumAttrBracket.bind(this));
  14849. this.registerCustomAttribute('TensorRT_ResizeSelectorAttr', this._parseEnumAttrBracket.bind(this));
  14850. this.registerCustomAttribute('TensorRT_ResizeRoundModeAttr', this._parseEnumAttrBracket.bind(this));
  14851. this.registerCustomAttribute('TensorRT_ResizeModeAttr', this._parseEnumAttrBracket.bind(this));
  14852. this.registerCustomAttribute('TensorRT_ResizeCoordinateTransformationAttr', this._parseEnumAttrBracket.bind(this));
  14853. this.registerCustomAttribute('TensorRT_ReduceOperationAttr', this._parseEnumAttrBracket.bind(this));
  14854. this.registerCustomAttribute('TensorRT_PaddingModeAttr', this._parseEnumAttrBracket.bind(this));
  14855. this.registerCustomAttribute('TensorRT_MatrixOperationAttr', this._parseEnumAttrBracket.bind(this));
  14856. this.registerCustomAttribute('TensorRT_LoopOutputAttr', this._parseEnumAttrBracket.bind(this));
  14857. this.registerCustomAttribute('TensorRT_GatherModeAttr', this._parseEnumAttrBracket.bind(this));
  14858. this.registerCustomAttribute('TensorRT_FillOperationAttr', this._parseEnumAttrBracket.bind(this));
  14859. this.registerCustomAttribute('TensorRT_ElementWiseOperationAttr', this._parseEnumAttrBracket.bind(this));
  14860. this.registerCustomAttribute('TensorRT_ActivationTypeAttr', this._parseEnumAttrBracket.bind(this));
  14861. this.registerCustomAttribute('TensorRT_UnaryOperationAttr', this._parseEnumAttrBracket.bind(this));
  14862. this.registerCustomAttribute('TensorRT_TripLimitAttr', this._parseEnumAttrBracket.bind(this));
  14863. this.registerCustomAttribute('TensorRT_PoolingTypeAttr', this._parseEnumAttrBracket.bind(this));
  14864. this.registerCustomDirective('StaticIndexI64Array', this._parseStaticIndexI64Array.bind(this));
  14865. this.registerCustomDirective('StaticIndexI32Array', this._parseStaticIndexI32Array.bind(this));
  14866. }
  14867. _parseEnumAttrBracket(parser) {
  14868. if (parser.match('<')) {
  14869. parser.expect('<');
  14870. const value = parser.expect('id');
  14871. parser.expect('>');
  14872. return { value };
  14873. }
  14874. return null;
  14875. }
  14876. _parseStaticIndexI64Array(parser, op, args) {
  14877. const values = [];
  14878. do {
  14879. if (parser.match('int')) {
  14880. const value = parser.expect('int');
  14881. values.push(parseInt(value, 10));
  14882. } else if (parser.match('-')) {
  14883. parser.expect('-');
  14884. const value = parser.expect('int');
  14885. values.push(-parseInt(value, 10));
  14886. } else {
  14887. break;
  14888. }
  14889. } while (parser.accept(','));
  14890. const name = args && args[0] ? args[0].replace(/^\$/, '') : 'broadcast_dims';
  14891. op.attributes.push({ name, value: values });
  14892. }
  14893. _parseStaticIndexI32Array(parser, op, args) {
  14894. const values = [];
  14895. do {
  14896. if (parser.match('int')) {
  14897. const value = parser.expect('int');
  14898. values.push(parseInt(value, 10));
  14899. } else if (parser.match('-')) {
  14900. parser.expect('-');
  14901. const value = parser.expect('int');
  14902. values.push(-parseInt(value, 10));
  14903. } else {
  14904. break;
  14905. }
  14906. } while (parser.accept(','));
  14907. const name = args && args[0] ? args[0].replace(/^\$/, '') : 'static_values';
  14908. op.attributes.push({ name, value: values });
  14909. }
  14910. };
  14911. mlir.ExecutorDialect = class extends mlir.Dialect {
  14912. constructor(operations) {
  14913. super('executor', operations);
  14914. this.registerCustomType('Executor_Table', this._parseTable.bind(this));
  14915. this.registerCustomDirective('ExecutorMixedIndices', this._parseExecutorMixedIndices.bind(this));
  14916. }
  14917. parseOperation(parser, opName, op) {
  14918. if (opName === 'executor.func') {
  14919. parser.parseFunctionOp(op, true);
  14920. return true;
  14921. }
  14922. return super.parseOperation(parser, opName, op);
  14923. }
  14924. _parseTable(parser) {
  14925. if (parser.match('<')) {
  14926. const content = parser.skip('<', '>');
  14927. return new mlir.Type(`!executor.table${content}`);
  14928. }
  14929. return null;
  14930. }
  14931. // Parse: [dynamicIndices, staticIndices] mixed format
  14932. _parseExecutorMixedIndices(parser, op /*, args */) {
  14933. do {
  14934. if (parser.match('%')) {
  14935. const operand = parser.expect('%');
  14936. op.operands.push({ value: operand });
  14937. } else {
  14938. parser.parseAttribute();
  14939. }
  14940. } while (parser.accept(','));
  14941. }
  14942. };
  14943. mlir.TFRTTestDialect = class extends mlir.Dialect {
  14944. constructor(operations) {
  14945. super('tfrt_test', operations);
  14946. }
  14947. parseOperation(parser, opName, op) {
  14948. const opInfo = this.getOperation(opName);
  14949. if (!opInfo) {
  14950. return false;
  14951. }
  14952. if (opInfo.metadata?.assemblyFormat === 'operands attr-dict') {
  14953. while (parser.match('%')) {
  14954. op.operands.push({ value: parser.expect() });
  14955. if (!parser.accept(',')) {
  14956. break;
  14957. }
  14958. }
  14959. if (parser.match('{')) {
  14960. parser.parseAttributeDict(op.attributes);
  14961. }
  14962. return true;
  14963. }
  14964. if (opName === 'tfrt_test.do.async') {
  14965. if (parser.match('%')) {
  14966. op.operands = parser.parseArguments();
  14967. }
  14968. if (parser.accept(':')) {
  14969. const type = parser.parseFunctionType();
  14970. if (type && type.results) {
  14971. type.results.forEach((resultType) => {
  14972. op.results.push({ type: resultType });
  14973. });
  14974. }
  14975. }
  14976. if (parser.match('{')) {
  14977. const region = {};
  14978. parser.parseRegion(region);
  14979. op.regions.push(region);
  14980. }
  14981. return true;
  14982. }
  14983. if (opName === 'tfrt_test.benchmark') {
  14984. if (parser.match('string')) {
  14985. const name = parser.expect('string');
  14986. op.attributes.push({ name: 'name', value: name });
  14987. }
  14988. parser.expect('(');
  14989. while (parser.match('%')) {
  14990. const operand = { value: parser.expect('%') };
  14991. if (parser.accept(':')) {
  14992. operand.type = parser.parseType().toString();
  14993. }
  14994. op.operands.push(operand);
  14995. if (!parser.accept(',')) {
  14996. break;
  14997. }
  14998. }
  14999. parser.expect(')');
  15000. while (parser.match('id') && !parser.match('{')) {
  15001. const name = parser.expect('id');
  15002. parser.expect('=');
  15003. let value = null;
  15004. if (parser.match('int')) {
  15005. value = parser.parseInteger();
  15006. } else if (parser.match('string')) {
  15007. value = parser.expect('string');
  15008. } else {
  15009. value = parser.expect('id');
  15010. }
  15011. op.attributes.push({ name, value });
  15012. parser.accept(',');
  15013. }
  15014. if (parser.match('{')) {
  15015. const region = {};
  15016. parser.parseRegion(region);
  15017. op.regions.push(region);
  15018. }
  15019. return true;
  15020. }
  15021. return super.parseOperation(parser, opName, op);
  15022. }
  15023. };
  15024. mlir.XeVMDialect = class extends mlir.Dialect {
  15025. constructor(operations) {
  15026. super('xevm', operations);
  15027. }
  15028. };
  15029. mlir.VMVXDialect = class extends mlir.Dialect {
  15030. constructor(operations) {
  15031. super('vmvx', operations);
  15032. }
  15033. };
  15034. mlir.MLRTDialect = class extends mlir.Dialect {
  15035. constructor(operations) {
  15036. super('mlrt', operations);
  15037. }
  15038. };
  15039. mlir.TFRTTensorDialect = class extends mlir.Dialect {
  15040. constructor(operations) {
  15041. super('tfrt_tensor', operations);
  15042. }
  15043. };
  15044. mlir.TFRTDHTDialect = class extends mlir.Dialect {
  15045. constructor(operations) {
  15046. super('tfrt_dht', operations);
  15047. }
  15048. };
  15049. mlir.TFDDialect = class extends mlir.Dialect {
  15050. constructor(operations) {
  15051. super('tfd', operations);
  15052. }
  15053. };
  15054. mlir.ACCDialect = class extends mlir.Dialect {
  15055. constructor(operations) {
  15056. super('acc', operations);
  15057. this.registerCustomDirective('Var', this._parseVar.bind(this));
  15058. this.registerCustomDirective('AccVar', this._parseAccVar.bind(this));
  15059. this.registerCustomDirective('VarPtrType', this._parseVarPtrType.bind(this));
  15060. this.registerCustomDirective('DeviceTypeOperandsWithKeywordOnly', this._parseDeviceTypeOperandsWithKeywordOnly.bind(this));
  15061. }
  15062. _parseVar(parser, op) {
  15063. if (!parser.accept('id', 'varPtr')) {
  15064. parser.expect('id', 'var');
  15065. }
  15066. parser.expect('(');
  15067. const operand = parser.parseOperand();
  15068. op.operands.push(operand);
  15069. }
  15070. _parseAccVar(parser, op) {
  15071. if (!parser.accept('id', 'accPtr')) {
  15072. parser.expect('id', 'accVar');
  15073. }
  15074. parser.expect('(');
  15075. const operand = parser.parseOperand();
  15076. op.operands.push(operand);
  15077. parser.expect(':');
  15078. operand.type = parser.parseType();
  15079. parser.expect(')');
  15080. }
  15081. _parseVarPtrType(parser, op) {
  15082. const type = parser.parseType();
  15083. if (op.operands.length > 0) {
  15084. op.operands[op.operands.length - 1].type = type;
  15085. }
  15086. parser.expect(')');
  15087. if (parser.accept('id', 'varType')) {
  15088. parser.expect('(');
  15089. const varType = parser.parseType();
  15090. op.attributes.push({ name: 'varType', value: varType });
  15091. parser.expect(')');
  15092. }
  15093. }
  15094. _parseDeviceTypeOperandsWithKeywordOnly() {
  15095. }
  15096. };
  15097. mlir.SMTDialect = class extends mlir.Dialect {
  15098. constructor(operations) {
  15099. super('smt', operations);
  15100. }
  15101. parseOperation(parser, opName, op) {
  15102. if (opName === 'smt.eq' || opName === 'smt.distinct') {
  15103. return this._parseSameOperandTypeVariadicToBoolOp(parser, op);
  15104. }
  15105. if (opName === 'smt.bv.repeat') {
  15106. return this._parseRepeatOp(parser, op);
  15107. }
  15108. if (opName === 'smt.int.constant') {
  15109. return this._parseIntConstantOp(parser, op);
  15110. }
  15111. return super.parseOperation(parser, opName, op);
  15112. }
  15113. _parseSameOperandTypeVariadicToBoolOp(parser, op) {
  15114. const operands = parser.parseOperandList();
  15115. op.operands = operands;
  15116. parser.parseOptionalAttrDict(op.attributes);
  15117. parser.expect(':');
  15118. const type = parser.parseType();
  15119. for (const operand of op.operands) {
  15120. operand.type = type;
  15121. }
  15122. return true;
  15123. }
  15124. _parseRepeatOp(parser, op) {
  15125. const count = parser.parseInteger();
  15126. op.attributes.push({ name: 'count', value: count });
  15127. parser.expect('id', 'times');
  15128. const operand = {};
  15129. operand.value = parser.expect('%');
  15130. op.operands.push(operand);
  15131. parser.parseOptionalAttrDict(op.attributes);
  15132. parser.expect(':');
  15133. const inputType = parser.parseType();
  15134. op.operands[0].type = inputType;
  15135. return true;
  15136. }
  15137. _parseIntConstantOp(parser, op) {
  15138. const value = parser.parseInteger();
  15139. op.attributes.push({ name: 'value', value });
  15140. parser.parseOptionalAttrDict(op.attributes);
  15141. return true;
  15142. }
  15143. };
  15144. mlir.Metadata = class {
  15145. static async open(context) {
  15146. if (!mlir.Metadata._metadata) {
  15147. const data = await context.request('mlir-metadata.json');
  15148. mlir.Metadata._metadata = new mlir.Metadata(data);
  15149. }
  15150. return mlir.Metadata._metadata;
  15151. }
  15152. constructor(data) {
  15153. this.operations = new Map();
  15154. if (data) {
  15155. const operations = JSON.parse(data);
  15156. for (const op of operations) {
  15157. const [dialectName] = op.name.split('.');
  15158. if (!this.operations.has(dialectName)) {
  15159. this.operations.set(dialectName, []);
  15160. }
  15161. this.operations.get(dialectName).push(op);
  15162. }
  15163. }
  15164. }
  15165. type(name) {
  15166. const [dialectName] = name.split('.');
  15167. const operations = this.operations.get(dialectName);
  15168. if (operations) {
  15169. const op = operations.find((op) => op.name === name);
  15170. if (op) {
  15171. return op;
  15172. }
  15173. }
  15174. return { name };
  15175. }
  15176. };
  15177. mlir.Error = class extends Error {
  15178. constructor(message) {
  15179. super(message);
  15180. this.name = 'Error loading MLIR model.';
  15181. }
  15182. };
  15183. export const ModelFactory = mlir.ModelFactory;