GlobalISelEmitter.cpp 234 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314
  1. //===- GlobalISelEmitter.cpp - Generate an instruction selector -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. /// \file
  10. /// This tablegen backend emits code for use by the GlobalISel instruction
  11. /// selector. See include/llvm/CodeGen/TargetGlobalISel.td.
  12. ///
  13. /// This file analyzes the patterns recognized by the SelectionDAGISel tablegen
  14. /// backend, filters out the ones that are unsupported, maps
  15. /// SelectionDAG-specific constructs to their GlobalISel counterpart
  16. /// (when applicable: MVT to LLT; SDNode to generic Instruction).
  17. ///
  18. /// Not all patterns are supported: pass the tablegen invocation
  19. /// "-warn-on-skipped-patterns" to emit a warning when a pattern is skipped,
  20. /// as well as why.
  21. ///
  22. /// The generated file defines a single method:
  23. /// bool <Target>InstructionSelector::selectImpl(MachineInstr &I) const;
  24. /// intended to be used in InstructionSelector::select as the first-step
  25. /// selector for the patterns that don't require complex C++.
  26. ///
  27. /// FIXME: We'll probably want to eventually define a base
  28. /// "TargetGenInstructionSelector" class.
  29. ///
  30. //===----------------------------------------------------------------------===//
  31. #include "CodeGenDAGPatterns.h"
  32. #include "CodeGenInstruction.h"
  33. #include "SubtargetFeatureInfo.h"
  34. #include "llvm/ADT/Statistic.h"
  35. #include "llvm/Support/CodeGenCoverage.h"
  36. #include "llvm/Support/CommandLine.h"
  37. #include "llvm/Support/Error.h"
  38. #include "llvm/Support/LowLevelTypeImpl.h"
  39. #include "llvm/Support/MachineValueType.h"
  40. #include "llvm/Support/ScopedPrinter.h"
  41. #include "llvm/TableGen/Error.h"
  42. #include "llvm/TableGen/Record.h"
  43. #include "llvm/TableGen/TableGenBackend.h"
  44. #include <numeric>
  45. #include <string>
  46. using namespace llvm;
  47. #define DEBUG_TYPE "gisel-emitter"
  48. STATISTIC(NumPatternTotal, "Total number of patterns");
  49. STATISTIC(NumPatternImported, "Number of patterns imported from SelectionDAG");
  50. STATISTIC(NumPatternImportsSkipped, "Number of SelectionDAG imports skipped");
  51. STATISTIC(NumPatternsTested, "Number of patterns executed according to coverage information");
  52. STATISTIC(NumPatternEmitted, "Number of patterns emitted");
  53. cl::OptionCategory GlobalISelEmitterCat("Options for -gen-global-isel");
  54. static cl::opt<bool> WarnOnSkippedPatterns(
  55. "warn-on-skipped-patterns",
  56. cl::desc("Explain why a pattern was skipped for inclusion "
  57. "in the GlobalISel selector"),
  58. cl::init(false), cl::cat(GlobalISelEmitterCat));
  59. static cl::opt<bool> GenerateCoverage(
  60. "instrument-gisel-coverage",
  61. cl::desc("Generate coverage instrumentation for GlobalISel"),
  62. cl::init(false), cl::cat(GlobalISelEmitterCat));
  63. static cl::opt<std::string> UseCoverageFile(
  64. "gisel-coverage-file", cl::init(""),
  65. cl::desc("Specify file to retrieve coverage information from"),
  66. cl::cat(GlobalISelEmitterCat));
  67. static cl::opt<bool> OptimizeMatchTable(
  68. "optimize-match-table",
  69. cl::desc("Generate an optimized version of the match table"),
  70. cl::init(true), cl::cat(GlobalISelEmitterCat));
  71. namespace {
  72. //===- Helper functions ---------------------------------------------------===//
  73. /// Get the name of the enum value used to number the predicate function.
  74. std::string getEnumNameForPredicate(const TreePredicateFn &Predicate) {
  75. if (Predicate.hasGISelPredicateCode())
  76. return "GIPFP_MI_" + Predicate.getFnName();
  77. return "GIPFP_" + Predicate.getImmTypeIdentifier().str() + "_" +
  78. Predicate.getFnName();
  79. }
  80. /// Get the opcode used to check this predicate.
  81. std::string getMatchOpcodeForImmPredicate(const TreePredicateFn &Predicate) {
  82. return "GIM_Check" + Predicate.getImmTypeIdentifier().str() + "ImmPredicate";
  83. }
  84. /// This class stands in for LLT wherever we want to tablegen-erate an
  85. /// equivalent at compiler run-time.
  86. class LLTCodeGen {
  87. private:
  88. LLT Ty;
  89. public:
  90. LLTCodeGen() = default;
  91. LLTCodeGen(const LLT &Ty) : Ty(Ty) {}
  92. std::string getCxxEnumValue() const {
  93. std::string Str;
  94. raw_string_ostream OS(Str);
  95. emitCxxEnumValue(OS);
  96. return Str;
  97. }
  98. void emitCxxEnumValue(raw_ostream &OS) const {
  99. if (Ty.isScalar()) {
  100. OS << "GILLT_s" << Ty.getSizeInBits();
  101. return;
  102. }
  103. if (Ty.isVector()) {
  104. OS << (Ty.isScalable() ? "GILLT_nxv" : "GILLT_v")
  105. << Ty.getElementCount().getKnownMinValue() << "s"
  106. << Ty.getScalarSizeInBits();
  107. return;
  108. }
  109. if (Ty.isPointer()) {
  110. OS << "GILLT_p" << Ty.getAddressSpace();
  111. if (Ty.getSizeInBits() > 0)
  112. OS << "s" << Ty.getSizeInBits();
  113. return;
  114. }
  115. llvm_unreachable("Unhandled LLT");
  116. }
  117. void emitCxxConstructorCall(raw_ostream &OS) const {
  118. if (Ty.isScalar()) {
  119. OS << "LLT::scalar(" << Ty.getSizeInBits() << ")";
  120. return;
  121. }
  122. if (Ty.isVector()) {
  123. OS << "LLT::vector("
  124. << (Ty.isScalable() ? "ElementCount::getScalable("
  125. : "ElementCount::getFixed(")
  126. << Ty.getElementCount().getKnownMinValue() << "), "
  127. << Ty.getScalarSizeInBits() << ")";
  128. return;
  129. }
  130. if (Ty.isPointer() && Ty.getSizeInBits() > 0) {
  131. OS << "LLT::pointer(" << Ty.getAddressSpace() << ", "
  132. << Ty.getSizeInBits() << ")";
  133. return;
  134. }
  135. llvm_unreachable("Unhandled LLT");
  136. }
  137. const LLT &get() const { return Ty; }
  138. /// This ordering is used for std::unique() and llvm::sort(). There's no
  139. /// particular logic behind the order but either A < B or B < A must be
  140. /// true if A != B.
  141. bool operator<(const LLTCodeGen &Other) const {
  142. if (Ty.isValid() != Other.Ty.isValid())
  143. return Ty.isValid() < Other.Ty.isValid();
  144. if (!Ty.isValid())
  145. return false;
  146. if (Ty.isVector() != Other.Ty.isVector())
  147. return Ty.isVector() < Other.Ty.isVector();
  148. if (Ty.isScalar() != Other.Ty.isScalar())
  149. return Ty.isScalar() < Other.Ty.isScalar();
  150. if (Ty.isPointer() != Other.Ty.isPointer())
  151. return Ty.isPointer() < Other.Ty.isPointer();
  152. if (Ty.isPointer() && Ty.getAddressSpace() != Other.Ty.getAddressSpace())
  153. return Ty.getAddressSpace() < Other.Ty.getAddressSpace();
  154. if (Ty.isVector() && Ty.getElementCount() != Other.Ty.getElementCount())
  155. return std::make_tuple(Ty.isScalable(),
  156. Ty.getElementCount().getKnownMinValue()) <
  157. std::make_tuple(Other.Ty.isScalable(),
  158. Other.Ty.getElementCount().getKnownMinValue());
  159. assert((!Ty.isVector() || Ty.isScalable() == Other.Ty.isScalable()) &&
  160. "Unexpected mismatch of scalable property");
  161. return Ty.isVector()
  162. ? std::make_tuple(Ty.isScalable(),
  163. Ty.getSizeInBits().getKnownMinValue()) <
  164. std::make_tuple(
  165. Other.Ty.isScalable(),
  166. Other.Ty.getSizeInBits().getKnownMinValue())
  167. : Ty.getSizeInBits().getFixedValue() <
  168. Other.Ty.getSizeInBits().getFixedValue();
  169. }
  170. bool operator==(const LLTCodeGen &B) const { return Ty == B.Ty; }
  171. };
  172. // Track all types that are used so we can emit the corresponding enum.
  173. std::set<LLTCodeGen> KnownTypes;
  174. class InstructionMatcher;
  175. /// Convert an MVT to an equivalent LLT if possible, or the invalid LLT() for
  176. /// MVTs that don't map cleanly to an LLT (e.g., iPTR, *any, ...).
  177. static std::optional<LLTCodeGen> MVTToLLT(MVT::SimpleValueType SVT) {
  178. MVT VT(SVT);
  179. if (VT.isVector() && !VT.getVectorElementCount().isScalar())
  180. return LLTCodeGen(
  181. LLT::vector(VT.getVectorElementCount(), VT.getScalarSizeInBits()));
  182. if (VT.isInteger() || VT.isFloatingPoint())
  183. return LLTCodeGen(LLT::scalar(VT.getSizeInBits()));
  184. return std::nullopt;
  185. }
  186. static std::string explainPredicates(const TreePatternNode *N) {
  187. std::string Explanation;
  188. StringRef Separator = "";
  189. for (const TreePredicateCall &Call : N->getPredicateCalls()) {
  190. const TreePredicateFn &P = Call.Fn;
  191. Explanation +=
  192. (Separator + P.getOrigPatFragRecord()->getRecord()->getName()).str();
  193. Separator = ", ";
  194. if (P.isAlwaysTrue())
  195. Explanation += " always-true";
  196. if (P.isImmediatePattern())
  197. Explanation += " immediate";
  198. if (P.isUnindexed())
  199. Explanation += " unindexed";
  200. if (P.isNonExtLoad())
  201. Explanation += " non-extload";
  202. if (P.isAnyExtLoad())
  203. Explanation += " extload";
  204. if (P.isSignExtLoad())
  205. Explanation += " sextload";
  206. if (P.isZeroExtLoad())
  207. Explanation += " zextload";
  208. if (P.isNonTruncStore())
  209. Explanation += " non-truncstore";
  210. if (P.isTruncStore())
  211. Explanation += " truncstore";
  212. if (Record *VT = P.getMemoryVT())
  213. Explanation += (" MemVT=" + VT->getName()).str();
  214. if (Record *VT = P.getScalarMemoryVT())
  215. Explanation += (" ScalarVT(MemVT)=" + VT->getName()).str();
  216. if (ListInit *AddrSpaces = P.getAddressSpaces()) {
  217. raw_string_ostream OS(Explanation);
  218. OS << " AddressSpaces=[";
  219. StringRef AddrSpaceSeparator;
  220. for (Init *Val : AddrSpaces->getValues()) {
  221. IntInit *IntVal = dyn_cast<IntInit>(Val);
  222. if (!IntVal)
  223. continue;
  224. OS << AddrSpaceSeparator << IntVal->getValue();
  225. AddrSpaceSeparator = ", ";
  226. }
  227. OS << ']';
  228. }
  229. int64_t MinAlign = P.getMinAlignment();
  230. if (MinAlign > 0)
  231. Explanation += " MinAlign=" + utostr(MinAlign);
  232. if (P.isAtomicOrderingMonotonic())
  233. Explanation += " monotonic";
  234. if (P.isAtomicOrderingAcquire())
  235. Explanation += " acquire";
  236. if (P.isAtomicOrderingRelease())
  237. Explanation += " release";
  238. if (P.isAtomicOrderingAcquireRelease())
  239. Explanation += " acq_rel";
  240. if (P.isAtomicOrderingSequentiallyConsistent())
  241. Explanation += " seq_cst";
  242. if (P.isAtomicOrderingAcquireOrStronger())
  243. Explanation += " >=acquire";
  244. if (P.isAtomicOrderingWeakerThanAcquire())
  245. Explanation += " <acquire";
  246. if (P.isAtomicOrderingReleaseOrStronger())
  247. Explanation += " >=release";
  248. if (P.isAtomicOrderingWeakerThanRelease())
  249. Explanation += " <release";
  250. }
  251. return Explanation;
  252. }
  253. std::string explainOperator(Record *Operator) {
  254. if (Operator->isSubClassOf("SDNode"))
  255. return (" (" + Operator->getValueAsString("Opcode") + ")").str();
  256. if (Operator->isSubClassOf("Intrinsic"))
  257. return (" (Operator is an Intrinsic, " + Operator->getName() + ")").str();
  258. if (Operator->isSubClassOf("ComplexPattern"))
  259. return (" (Operator is an unmapped ComplexPattern, " + Operator->getName() +
  260. ")")
  261. .str();
  262. if (Operator->isSubClassOf("SDNodeXForm"))
  263. return (" (Operator is an unmapped SDNodeXForm, " + Operator->getName() +
  264. ")")
  265. .str();
  266. return (" (Operator " + Operator->getName() + " not understood)").str();
  267. }
  268. /// Helper function to let the emitter report skip reason error messages.
  269. static Error failedImport(const Twine &Reason) {
  270. return make_error<StringError>(Reason, inconvertibleErrorCode());
  271. }
  272. static Error isTrivialOperatorNode(const TreePatternNode *N) {
  273. std::string Explanation;
  274. std::string Separator;
  275. bool HasUnsupportedPredicate = false;
  276. for (const TreePredicateCall &Call : N->getPredicateCalls()) {
  277. const TreePredicateFn &Predicate = Call.Fn;
  278. if (Predicate.isAlwaysTrue())
  279. continue;
  280. if (Predicate.isImmediatePattern())
  281. continue;
  282. if (Predicate.hasNoUse())
  283. continue;
  284. if (Predicate.isNonExtLoad() || Predicate.isAnyExtLoad() ||
  285. Predicate.isSignExtLoad() || Predicate.isZeroExtLoad())
  286. continue;
  287. if (Predicate.isNonTruncStore() || Predicate.isTruncStore())
  288. continue;
  289. if (Predicate.isLoad() && Predicate.getMemoryVT())
  290. continue;
  291. if (Predicate.isLoad() || Predicate.isStore()) {
  292. if (Predicate.isUnindexed())
  293. continue;
  294. }
  295. if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
  296. const ListInit *AddrSpaces = Predicate.getAddressSpaces();
  297. if (AddrSpaces && !AddrSpaces->empty())
  298. continue;
  299. if (Predicate.getMinAlignment() > 0)
  300. continue;
  301. }
  302. if (Predicate.isAtomic() && Predicate.getMemoryVT())
  303. continue;
  304. if (Predicate.isAtomic() &&
  305. (Predicate.isAtomicOrderingMonotonic() ||
  306. Predicate.isAtomicOrderingAcquire() ||
  307. Predicate.isAtomicOrderingRelease() ||
  308. Predicate.isAtomicOrderingAcquireRelease() ||
  309. Predicate.isAtomicOrderingSequentiallyConsistent() ||
  310. Predicate.isAtomicOrderingAcquireOrStronger() ||
  311. Predicate.isAtomicOrderingWeakerThanAcquire() ||
  312. Predicate.isAtomicOrderingReleaseOrStronger() ||
  313. Predicate.isAtomicOrderingWeakerThanRelease()))
  314. continue;
  315. if (Predicate.hasGISelPredicateCode())
  316. continue;
  317. HasUnsupportedPredicate = true;
  318. Explanation = Separator + "Has a predicate (" + explainPredicates(N) + ")";
  319. Separator = ", ";
  320. Explanation += (Separator + "first-failing:" +
  321. Predicate.getOrigPatFragRecord()->getRecord()->getName())
  322. .str();
  323. break;
  324. }
  325. if (!HasUnsupportedPredicate)
  326. return Error::success();
  327. return failedImport(Explanation);
  328. }
  329. static Record *getInitValueAsRegClass(Init *V) {
  330. if (DefInit *VDefInit = dyn_cast<DefInit>(V)) {
  331. if (VDefInit->getDef()->isSubClassOf("RegisterOperand"))
  332. return VDefInit->getDef()->getValueAsDef("RegClass");
  333. if (VDefInit->getDef()->isSubClassOf("RegisterClass"))
  334. return VDefInit->getDef();
  335. }
  336. return nullptr;
  337. }
  338. std::string
  339. getNameForFeatureBitset(const std::vector<Record *> &FeatureBitset) {
  340. std::string Name = "GIFBS";
  341. for (const auto &Feature : FeatureBitset)
  342. Name += ("_" + Feature->getName()).str();
  343. return Name;
  344. }
  345. static std::string getScopedName(unsigned Scope, const std::string &Name) {
  346. return ("pred:" + Twine(Scope) + ":" + Name).str();
  347. }
  348. //===- MatchTable Helpers -------------------------------------------------===//
  349. class MatchTable;
  350. /// A record to be stored in a MatchTable.
  351. ///
  352. /// This class represents any and all output that may be required to emit the
  353. /// MatchTable. Instances are most often configured to represent an opcode or
  354. /// value that will be emitted to the table with some formatting but it can also
  355. /// represent commas, comments, and other formatting instructions.
  356. struct MatchTableRecord {
  357. enum RecordFlagsBits {
  358. MTRF_None = 0x0,
  359. /// Causes EmitStr to be formatted as comment when emitted.
  360. MTRF_Comment = 0x1,
  361. /// Causes the record value to be followed by a comma when emitted.
  362. MTRF_CommaFollows = 0x2,
  363. /// Causes the record value to be followed by a line break when emitted.
  364. MTRF_LineBreakFollows = 0x4,
  365. /// Indicates that the record defines a label and causes an additional
  366. /// comment to be emitted containing the index of the label.
  367. MTRF_Label = 0x8,
  368. /// Causes the record to be emitted as the index of the label specified by
  369. /// LabelID along with a comment indicating where that label is.
  370. MTRF_JumpTarget = 0x10,
  371. /// Causes the formatter to add a level of indentation before emitting the
  372. /// record.
  373. MTRF_Indent = 0x20,
  374. /// Causes the formatter to remove a level of indentation after emitting the
  375. /// record.
  376. MTRF_Outdent = 0x40,
  377. };
  378. /// When MTRF_Label or MTRF_JumpTarget is used, indicates a label id to
  379. /// reference or define.
  380. unsigned LabelID;
  381. /// The string to emit. Depending on the MTRF_* flags it may be a comment, a
  382. /// value, a label name.
  383. std::string EmitStr;
  384. private:
  385. /// The number of MatchTable elements described by this record. Comments are 0
  386. /// while values are typically 1. Values >1 may occur when we need to emit
  387. /// values that exceed the size of a MatchTable element.
  388. unsigned NumElements;
  389. public:
  390. /// A bitfield of RecordFlagsBits flags.
  391. unsigned Flags;
  392. /// The actual run-time value, if known
  393. int64_t RawValue;
  394. MatchTableRecord(std::optional<unsigned> LabelID_, StringRef EmitStr,
  395. unsigned NumElements, unsigned Flags,
  396. int64_t RawValue = std::numeric_limits<int64_t>::min())
  397. : LabelID(LabelID_.value_or(~0u)), EmitStr(EmitStr),
  398. NumElements(NumElements), Flags(Flags), RawValue(RawValue) {
  399. assert((!LabelID_ || LabelID != ~0u) &&
  400. "This value is reserved for non-labels");
  401. }
  402. MatchTableRecord(const MatchTableRecord &Other) = default;
  403. MatchTableRecord(MatchTableRecord &&Other) = default;
  404. /// Useful if a Match Table Record gets optimized out
  405. void turnIntoComment() {
  406. Flags |= MTRF_Comment;
  407. Flags &= ~MTRF_CommaFollows;
  408. NumElements = 0;
  409. }
  410. /// For Jump Table generation purposes
  411. bool operator<(const MatchTableRecord &Other) const {
  412. return RawValue < Other.RawValue;
  413. }
  414. int64_t getRawValue() const { return RawValue; }
  415. void emit(raw_ostream &OS, bool LineBreakNextAfterThis,
  416. const MatchTable &Table) const;
  417. unsigned size() const { return NumElements; }
  418. };
  419. class Matcher;
  420. /// Holds the contents of a generated MatchTable to enable formatting and the
  421. /// necessary index tracking needed to support GIM_Try.
  422. class MatchTable {
  423. /// An unique identifier for the table. The generated table will be named
  424. /// MatchTable${ID}.
  425. unsigned ID;
  426. /// The records that make up the table. Also includes comments describing the
  427. /// values being emitted and line breaks to format it.
  428. std::vector<MatchTableRecord> Contents;
  429. /// The currently defined labels.
  430. DenseMap<unsigned, unsigned> LabelMap;
  431. /// Tracks the sum of MatchTableRecord::NumElements as the table is built.
  432. unsigned CurrentSize = 0;
  433. /// A unique identifier for a MatchTable label.
  434. unsigned CurrentLabelID = 0;
  435. /// Determines if the table should be instrumented for rule coverage tracking.
  436. bool IsWithCoverage;
  437. public:
  438. static MatchTableRecord LineBreak;
  439. static MatchTableRecord Comment(StringRef Comment) {
  440. return MatchTableRecord(std::nullopt, Comment, 0,
  441. MatchTableRecord::MTRF_Comment);
  442. }
  443. static MatchTableRecord Opcode(StringRef Opcode, int IndentAdjust = 0) {
  444. unsigned ExtraFlags = 0;
  445. if (IndentAdjust > 0)
  446. ExtraFlags |= MatchTableRecord::MTRF_Indent;
  447. if (IndentAdjust < 0)
  448. ExtraFlags |= MatchTableRecord::MTRF_Outdent;
  449. return MatchTableRecord(std::nullopt, Opcode, 1,
  450. MatchTableRecord::MTRF_CommaFollows | ExtraFlags);
  451. }
  452. static MatchTableRecord NamedValue(StringRef NamedValue) {
  453. return MatchTableRecord(std::nullopt, NamedValue, 1,
  454. MatchTableRecord::MTRF_CommaFollows);
  455. }
  456. static MatchTableRecord NamedValue(StringRef NamedValue, int64_t RawValue) {
  457. return MatchTableRecord(std::nullopt, NamedValue, 1,
  458. MatchTableRecord::MTRF_CommaFollows, RawValue);
  459. }
  460. static MatchTableRecord NamedValue(StringRef Namespace,
  461. StringRef NamedValue) {
  462. return MatchTableRecord(std::nullopt, (Namespace + "::" + NamedValue).str(),
  463. 1, MatchTableRecord::MTRF_CommaFollows);
  464. }
  465. static MatchTableRecord NamedValue(StringRef Namespace, StringRef NamedValue,
  466. int64_t RawValue) {
  467. return MatchTableRecord(std::nullopt, (Namespace + "::" + NamedValue).str(),
  468. 1, MatchTableRecord::MTRF_CommaFollows, RawValue);
  469. }
  470. static MatchTableRecord IntValue(int64_t IntValue) {
  471. return MatchTableRecord(std::nullopt, llvm::to_string(IntValue), 1,
  472. MatchTableRecord::MTRF_CommaFollows);
  473. }
  474. static MatchTableRecord Label(unsigned LabelID) {
  475. return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 0,
  476. MatchTableRecord::MTRF_Label |
  477. MatchTableRecord::MTRF_Comment |
  478. MatchTableRecord::MTRF_LineBreakFollows);
  479. }
  480. static MatchTableRecord JumpTarget(unsigned LabelID) {
  481. return MatchTableRecord(LabelID, "Label " + llvm::to_string(LabelID), 1,
  482. MatchTableRecord::MTRF_JumpTarget |
  483. MatchTableRecord::MTRF_Comment |
  484. MatchTableRecord::MTRF_CommaFollows);
  485. }
  486. static MatchTable buildTable(ArrayRef<Matcher *> Rules, bool WithCoverage);
  487. MatchTable(bool WithCoverage, unsigned ID = 0)
  488. : ID(ID), IsWithCoverage(WithCoverage) {}
  489. bool isWithCoverage() const { return IsWithCoverage; }
  490. void push_back(const MatchTableRecord &Value) {
  491. if (Value.Flags & MatchTableRecord::MTRF_Label)
  492. defineLabel(Value.LabelID);
  493. Contents.push_back(Value);
  494. CurrentSize += Value.size();
  495. }
  496. unsigned allocateLabelID() { return CurrentLabelID++; }
  497. void defineLabel(unsigned LabelID) {
  498. LabelMap.insert(std::make_pair(LabelID, CurrentSize));
  499. }
  500. unsigned getLabelIndex(unsigned LabelID) const {
  501. const auto I = LabelMap.find(LabelID);
  502. assert(I != LabelMap.end() && "Use of undeclared label");
  503. return I->second;
  504. }
  505. void emitUse(raw_ostream &OS) const { OS << "MatchTable" << ID; }
  506. void emitDeclaration(raw_ostream &OS) const {
  507. unsigned Indentation = 4;
  508. OS << " constexpr static int64_t MatchTable" << ID << "[] = {";
  509. LineBreak.emit(OS, true, *this);
  510. OS << std::string(Indentation, ' ');
  511. for (auto I = Contents.begin(), E = Contents.end(); I != E;
  512. ++I) {
  513. bool LineBreakIsNext = false;
  514. const auto &NextI = std::next(I);
  515. if (NextI != E) {
  516. if (NextI->EmitStr == "" &&
  517. NextI->Flags == MatchTableRecord::MTRF_LineBreakFollows)
  518. LineBreakIsNext = true;
  519. }
  520. if (I->Flags & MatchTableRecord::MTRF_Indent)
  521. Indentation += 2;
  522. I->emit(OS, LineBreakIsNext, *this);
  523. if (I->Flags & MatchTableRecord::MTRF_LineBreakFollows)
  524. OS << std::string(Indentation, ' ');
  525. if (I->Flags & MatchTableRecord::MTRF_Outdent)
  526. Indentation -= 2;
  527. }
  528. OS << "};\n";
  529. }
  530. };
  531. MatchTableRecord MatchTable::LineBreak = {
  532. std::nullopt, "" /* Emit String */, 0 /* Elements */,
  533. MatchTableRecord::MTRF_LineBreakFollows};
  534. void MatchTableRecord::emit(raw_ostream &OS, bool LineBreakIsNextAfterThis,
  535. const MatchTable &Table) const {
  536. bool UseLineComment =
  537. LineBreakIsNextAfterThis || (Flags & MTRF_LineBreakFollows);
  538. if (Flags & (MTRF_JumpTarget | MTRF_CommaFollows))
  539. UseLineComment = false;
  540. if (Flags & MTRF_Comment)
  541. OS << (UseLineComment ? "// " : "/*");
  542. OS << EmitStr;
  543. if (Flags & MTRF_Label)
  544. OS << ": @" << Table.getLabelIndex(LabelID);
  545. if ((Flags & MTRF_Comment) && !UseLineComment)
  546. OS << "*/";
  547. if (Flags & MTRF_JumpTarget) {
  548. if (Flags & MTRF_Comment)
  549. OS << " ";
  550. OS << Table.getLabelIndex(LabelID);
  551. }
  552. if (Flags & MTRF_CommaFollows) {
  553. OS << ",";
  554. if (!LineBreakIsNextAfterThis && !(Flags & MTRF_LineBreakFollows))
  555. OS << " ";
  556. }
  557. if (Flags & MTRF_LineBreakFollows)
  558. OS << "\n";
  559. }
  560. MatchTable &operator<<(MatchTable &Table, const MatchTableRecord &Value) {
  561. Table.push_back(Value);
  562. return Table;
  563. }
  564. //===- Matchers -----------------------------------------------------------===//
  565. class OperandMatcher;
  566. class MatchAction;
  567. class PredicateMatcher;
  568. class Matcher {
  569. public:
  570. virtual ~Matcher() = default;
  571. virtual void optimize() {}
  572. virtual void emit(MatchTable &Table) = 0;
  573. virtual bool hasFirstCondition() const = 0;
  574. virtual const PredicateMatcher &getFirstCondition() const = 0;
  575. virtual std::unique_ptr<PredicateMatcher> popFirstCondition() = 0;
  576. };
  577. MatchTable MatchTable::buildTable(ArrayRef<Matcher *> Rules,
  578. bool WithCoverage) {
  579. MatchTable Table(WithCoverage);
  580. for (Matcher *Rule : Rules)
  581. Rule->emit(Table);
  582. return Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
  583. }
  584. class GroupMatcher final : public Matcher {
  585. /// Conditions that form a common prefix of all the matchers contained.
  586. SmallVector<std::unique_ptr<PredicateMatcher>, 1> Conditions;
  587. /// All the nested matchers, sharing a common prefix.
  588. std::vector<Matcher *> Matchers;
  589. /// An owning collection for any auxiliary matchers created while optimizing
  590. /// nested matchers contained.
  591. std::vector<std::unique_ptr<Matcher>> MatcherStorage;
  592. public:
  593. /// Add a matcher to the collection of nested matchers if it meets the
  594. /// requirements, and return true. If it doesn't, do nothing and return false.
  595. ///
  596. /// Expected to preserve its argument, so it could be moved out later on.
  597. bool addMatcher(Matcher &Candidate);
  598. /// Mark the matcher as fully-built and ensure any invariants expected by both
  599. /// optimize() and emit(...) methods. Generally, both sequences of calls
  600. /// are expected to lead to a sensible result:
  601. ///
  602. /// addMatcher(...)*; finalize(); optimize(); emit(...); and
  603. /// addMatcher(...)*; finalize(); emit(...);
  604. ///
  605. /// or generally
  606. ///
  607. /// addMatcher(...)*; finalize(); { optimize()*; emit(...); }*
  608. ///
  609. /// Multiple calls to optimize() are expected to be handled gracefully, though
  610. /// optimize() is not expected to be idempotent. Multiple calls to finalize()
  611. /// aren't generally supported. emit(...) is expected to be non-mutating and
  612. /// producing the exact same results upon repeated calls.
  613. ///
  614. /// addMatcher() calls after the finalize() call are not supported.
  615. ///
  616. /// finalize() and optimize() are both allowed to mutate the contained
  617. /// matchers, so moving them out after finalize() is not supported.
  618. void finalize();
  619. void optimize() override;
  620. void emit(MatchTable &Table) override;
  621. /// Could be used to move out the matchers added previously, unless finalize()
  622. /// has been already called. If any of the matchers are moved out, the group
  623. /// becomes safe to destroy, but not safe to re-use for anything else.
  624. iterator_range<std::vector<Matcher *>::iterator> matchers() {
  625. return make_range(Matchers.begin(), Matchers.end());
  626. }
  627. size_t size() const { return Matchers.size(); }
  628. bool empty() const { return Matchers.empty(); }
  629. std::unique_ptr<PredicateMatcher> popFirstCondition() override {
  630. assert(!Conditions.empty() &&
  631. "Trying to pop a condition from a condition-less group");
  632. std::unique_ptr<PredicateMatcher> P = std::move(Conditions.front());
  633. Conditions.erase(Conditions.begin());
  634. return P;
  635. }
  636. const PredicateMatcher &getFirstCondition() const override {
  637. assert(!Conditions.empty() &&
  638. "Trying to get a condition from a condition-less group");
  639. return *Conditions.front();
  640. }
  641. bool hasFirstCondition() const override { return !Conditions.empty(); }
  642. private:
  643. /// See if a candidate matcher could be added to this group solely by
  644. /// analyzing its first condition.
  645. bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
  646. };
  647. class SwitchMatcher : public Matcher {
  648. /// All the nested matchers, representing distinct switch-cases. The first
  649. /// conditions (as Matcher::getFirstCondition() reports) of all the nested
  650. /// matchers must share the same type and path to a value they check, in other
  651. /// words, be isIdenticalDownToValue, but have different values they check
  652. /// against.
  653. std::vector<Matcher *> Matchers;
  654. /// The representative condition, with a type and a path (InsnVarID and OpIdx
  655. /// in most cases) shared by all the matchers contained.
  656. std::unique_ptr<PredicateMatcher> Condition = nullptr;
  657. /// Temporary set used to check that the case values don't repeat within the
  658. /// same switch.
  659. std::set<MatchTableRecord> Values;
  660. /// An owning collection for any auxiliary matchers created while optimizing
  661. /// nested matchers contained.
  662. std::vector<std::unique_ptr<Matcher>> MatcherStorage;
  663. public:
  664. bool addMatcher(Matcher &Candidate);
  665. void finalize();
  666. void emit(MatchTable &Table) override;
  667. iterator_range<std::vector<Matcher *>::iterator> matchers() {
  668. return make_range(Matchers.begin(), Matchers.end());
  669. }
  670. size_t size() const { return Matchers.size(); }
  671. bool empty() const { return Matchers.empty(); }
  672. std::unique_ptr<PredicateMatcher> popFirstCondition() override {
  673. // SwitchMatcher doesn't have a common first condition for its cases, as all
  674. // the cases only share a kind of a value (a type and a path to it) they
  675. // match, but deliberately differ in the actual value they match.
  676. llvm_unreachable("Trying to pop a condition from a condition-less group");
  677. }
  678. const PredicateMatcher &getFirstCondition() const override {
  679. llvm_unreachable("Trying to pop a condition from a condition-less group");
  680. }
  681. bool hasFirstCondition() const override { return false; }
  682. private:
  683. /// See if the predicate type has a Switch-implementation for it.
  684. static bool isSupportedPredicateType(const PredicateMatcher &Predicate);
  685. bool candidateConditionMatches(const PredicateMatcher &Predicate) const;
  686. /// emit()-helper
  687. static void emitPredicateSpecificOpcodes(const PredicateMatcher &P,
  688. MatchTable &Table);
  689. };
  690. /// Generates code to check that a match rule matches.
  691. class RuleMatcher : public Matcher {
  692. public:
  693. using ActionList = std::list<std::unique_ptr<MatchAction>>;
  694. using action_iterator = ActionList::iterator;
  695. protected:
  696. /// A list of matchers that all need to succeed for the current rule to match.
  697. /// FIXME: This currently supports a single match position but could be
  698. /// extended to support multiple positions to support div/rem fusion or
  699. /// load-multiple instructions.
  700. using MatchersTy = std::vector<std::unique_ptr<InstructionMatcher>> ;
  701. MatchersTy Matchers;
  702. /// A list of actions that need to be taken when all predicates in this rule
  703. /// have succeeded.
  704. ActionList Actions;
  705. using DefinedInsnVariablesMap = std::map<InstructionMatcher *, unsigned>;
  706. /// A map of instruction matchers to the local variables
  707. DefinedInsnVariablesMap InsnVariableIDs;
  708. using MutatableInsnSet = SmallPtrSet<InstructionMatcher *, 4>;
  709. // The set of instruction matchers that have not yet been claimed for mutation
  710. // by a BuildMI.
  711. MutatableInsnSet MutatableInsns;
  712. /// A map of named operands defined by the matchers that may be referenced by
  713. /// the renderers.
  714. StringMap<OperandMatcher *> DefinedOperands;
  715. /// A map of anonymous physical register operands defined by the matchers that
  716. /// may be referenced by the renderers.
  717. DenseMap<Record *, OperandMatcher *> PhysRegOperands;
  718. /// ID for the next instruction variable defined with implicitlyDefineInsnVar()
  719. unsigned NextInsnVarID;
  720. /// ID for the next output instruction allocated with allocateOutputInsnID()
  721. unsigned NextOutputInsnID;
  722. /// ID for the next temporary register ID allocated with allocateTempRegID()
  723. unsigned NextTempRegID;
  724. std::vector<Record *> RequiredFeatures;
  725. std::vector<std::unique_ptr<PredicateMatcher>> EpilogueMatchers;
  726. ArrayRef<SMLoc> SrcLoc;
  727. typedef std::tuple<Record *, unsigned, unsigned>
  728. DefinedComplexPatternSubOperand;
  729. typedef StringMap<DefinedComplexPatternSubOperand>
  730. DefinedComplexPatternSubOperandMap;
  731. /// A map of Symbolic Names to ComplexPattern sub-operands.
  732. DefinedComplexPatternSubOperandMap ComplexSubOperands;
  733. /// A map used to for multiple referenced error check of ComplexSubOperand.
  734. /// ComplexSubOperand can't be referenced multiple from different operands,
  735. /// however multiple references from same operand are allowed since that is
  736. /// how 'same operand checks' are generated.
  737. StringMap<std::string> ComplexSubOperandsParentName;
  738. uint64_t RuleID;
  739. static uint64_t NextRuleID;
  740. public:
  741. RuleMatcher(ArrayRef<SMLoc> SrcLoc)
  742. : NextInsnVarID(0), NextOutputInsnID(0), NextTempRegID(0), SrcLoc(SrcLoc),
  743. RuleID(NextRuleID++) {}
  744. RuleMatcher(RuleMatcher &&Other) = default;
  745. RuleMatcher &operator=(RuleMatcher &&Other) = default;
  746. uint64_t getRuleID() const { return RuleID; }
  747. InstructionMatcher &addInstructionMatcher(StringRef SymbolicName);
  748. void addRequiredFeature(Record *Feature);
  749. const std::vector<Record *> &getRequiredFeatures() const;
  750. template <class Kind, class... Args> Kind &addAction(Args &&... args);
  751. template <class Kind, class... Args>
  752. action_iterator insertAction(action_iterator InsertPt, Args &&... args);
  753. /// Define an instruction without emitting any code to do so.
  754. unsigned implicitlyDefineInsnVar(InstructionMatcher &Matcher);
  755. unsigned getInsnVarID(InstructionMatcher &InsnMatcher) const;
  756. DefinedInsnVariablesMap::const_iterator defined_insn_vars_begin() const {
  757. return InsnVariableIDs.begin();
  758. }
  759. DefinedInsnVariablesMap::const_iterator defined_insn_vars_end() const {
  760. return InsnVariableIDs.end();
  761. }
  762. iterator_range<typename DefinedInsnVariablesMap::const_iterator>
  763. defined_insn_vars() const {
  764. return make_range(defined_insn_vars_begin(), defined_insn_vars_end());
  765. }
  766. MutatableInsnSet::const_iterator mutatable_insns_begin() const {
  767. return MutatableInsns.begin();
  768. }
  769. MutatableInsnSet::const_iterator mutatable_insns_end() const {
  770. return MutatableInsns.end();
  771. }
  772. iterator_range<typename MutatableInsnSet::const_iterator>
  773. mutatable_insns() const {
  774. return make_range(mutatable_insns_begin(), mutatable_insns_end());
  775. }
  776. void reserveInsnMatcherForMutation(InstructionMatcher *InsnMatcher) {
  777. bool R = MutatableInsns.erase(InsnMatcher);
  778. assert(R && "Reserving a mutatable insn that isn't available");
  779. (void)R;
  780. }
  781. action_iterator actions_begin() { return Actions.begin(); }
  782. action_iterator actions_end() { return Actions.end(); }
  783. iterator_range<action_iterator> actions() {
  784. return make_range(actions_begin(), actions_end());
  785. }
  786. void defineOperand(StringRef SymbolicName, OperandMatcher &OM);
  787. void definePhysRegOperand(Record *Reg, OperandMatcher &OM);
  788. Error defineComplexSubOperand(StringRef SymbolicName, Record *ComplexPattern,
  789. unsigned RendererID, unsigned SubOperandID,
  790. StringRef ParentSymbolicName) {
  791. std::string ParentName(ParentSymbolicName);
  792. if (ComplexSubOperands.count(SymbolicName)) {
  793. const std::string &RecordedParentName =
  794. ComplexSubOperandsParentName[SymbolicName];
  795. if (RecordedParentName != ParentName)
  796. return failedImport("Error: Complex suboperand " + SymbolicName +
  797. " referenced by different operands: " +
  798. RecordedParentName + " and " + ParentName + ".");
  799. // Complex suboperand referenced more than once from same the operand is
  800. // used to generate 'same operand check'. Emitting of
  801. // GIR_ComplexSubOperandRenderer for them is already handled.
  802. return Error::success();
  803. }
  804. ComplexSubOperands[SymbolicName] =
  805. std::make_tuple(ComplexPattern, RendererID, SubOperandID);
  806. ComplexSubOperandsParentName[SymbolicName] = ParentName;
  807. return Error::success();
  808. }
  809. std::optional<DefinedComplexPatternSubOperand>
  810. getComplexSubOperand(StringRef SymbolicName) const {
  811. const auto &I = ComplexSubOperands.find(SymbolicName);
  812. if (I == ComplexSubOperands.end())
  813. return std::nullopt;
  814. return I->second;
  815. }
  816. InstructionMatcher &getInstructionMatcher(StringRef SymbolicName) const;
  817. const OperandMatcher &getOperandMatcher(StringRef Name) const;
  818. const OperandMatcher &getPhysRegOperandMatcher(Record *) const;
  819. void optimize() override;
  820. void emit(MatchTable &Table) override;
  821. /// Compare the priority of this object and B.
  822. ///
  823. /// Returns true if this object is more important than B.
  824. bool isHigherPriorityThan(const RuleMatcher &B) const;
  825. /// Report the maximum number of temporary operands needed by the rule
  826. /// matcher.
  827. unsigned countRendererFns() const;
  828. std::unique_ptr<PredicateMatcher> popFirstCondition() override;
  829. const PredicateMatcher &getFirstCondition() const override;
  830. LLTCodeGen getFirstConditionAsRootType();
  831. bool hasFirstCondition() const override;
  832. unsigned getNumOperands() const;
  833. StringRef getOpcode() const;
  834. // FIXME: Remove this as soon as possible
  835. InstructionMatcher &insnmatchers_front() const { return *Matchers.front(); }
  836. unsigned allocateOutputInsnID() { return NextOutputInsnID++; }
  837. unsigned allocateTempRegID() { return NextTempRegID++; }
  838. iterator_range<MatchersTy::iterator> insnmatchers() {
  839. return make_range(Matchers.begin(), Matchers.end());
  840. }
  841. bool insnmatchers_empty() const { return Matchers.empty(); }
  842. void insnmatchers_pop_front() { Matchers.erase(Matchers.begin()); }
  843. };
  844. uint64_t RuleMatcher::NextRuleID = 0;
  845. using action_iterator = RuleMatcher::action_iterator;
  846. template <class PredicateTy> class PredicateListMatcher {
  847. private:
  848. /// Template instantiations should specialize this to return a string to use
  849. /// for the comment emitted when there are no predicates.
  850. std::string getNoPredicateComment() const;
  851. protected:
  852. using PredicatesTy = std::deque<std::unique_ptr<PredicateTy>>;
  853. PredicatesTy Predicates;
  854. /// Track if the list of predicates was manipulated by one of the optimization
  855. /// methods.
  856. bool Optimized = false;
  857. public:
  858. typename PredicatesTy::iterator predicates_begin() {
  859. return Predicates.begin();
  860. }
  861. typename PredicatesTy::iterator predicates_end() {
  862. return Predicates.end();
  863. }
  864. iterator_range<typename PredicatesTy::iterator> predicates() {
  865. return make_range(predicates_begin(), predicates_end());
  866. }
  867. typename PredicatesTy::size_type predicates_size() const {
  868. return Predicates.size();
  869. }
  870. bool predicates_empty() const { return Predicates.empty(); }
  871. std::unique_ptr<PredicateTy> predicates_pop_front() {
  872. std::unique_ptr<PredicateTy> Front = std::move(Predicates.front());
  873. Predicates.pop_front();
  874. Optimized = true;
  875. return Front;
  876. }
  877. void prependPredicate(std::unique_ptr<PredicateTy> &&Predicate) {
  878. Predicates.push_front(std::move(Predicate));
  879. }
  880. void eraseNullPredicates() {
  881. const auto NewEnd =
  882. std::stable_partition(Predicates.begin(), Predicates.end(),
  883. std::logical_not<std::unique_ptr<PredicateTy>>());
  884. if (NewEnd != Predicates.begin()) {
  885. Predicates.erase(Predicates.begin(), NewEnd);
  886. Optimized = true;
  887. }
  888. }
  889. /// Emit MatchTable opcodes that tests whether all the predicates are met.
  890. template <class... Args>
  891. void emitPredicateListOpcodes(MatchTable &Table, Args &&... args) {
  892. if (Predicates.empty() && !Optimized) {
  893. Table << MatchTable::Comment(getNoPredicateComment())
  894. << MatchTable::LineBreak;
  895. return;
  896. }
  897. for (const auto &Predicate : predicates())
  898. Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
  899. }
  900. /// Provide a function to avoid emitting certain predicates. This is used to
  901. /// defer some predicate checks until after others
  902. using PredicateFilterFunc = std::function<bool(const PredicateTy&)>;
  903. /// Emit MatchTable opcodes for predicates which satisfy \p
  904. /// ShouldEmitPredicate. This should be called multiple times to ensure all
  905. /// predicates are eventually added to the match table.
  906. template <class... Args>
  907. void emitFilteredPredicateListOpcodes(PredicateFilterFunc ShouldEmitPredicate,
  908. MatchTable &Table, Args &&... args) {
  909. if (Predicates.empty() && !Optimized) {
  910. Table << MatchTable::Comment(getNoPredicateComment())
  911. << MatchTable::LineBreak;
  912. return;
  913. }
  914. for (const auto &Predicate : predicates()) {
  915. if (ShouldEmitPredicate(*Predicate))
  916. Predicate->emitPredicateOpcodes(Table, std::forward<Args>(args)...);
  917. }
  918. }
  919. };
  920. class PredicateMatcher {
  921. public:
  922. /// This enum is used for RTTI and also defines the priority that is given to
  923. /// the predicate when generating the matcher code. Kinds with higher priority
  924. /// must be tested first.
  925. ///
  926. /// The relative priority of OPM_LLT, OPM_RegBank, and OPM_MBB do not matter
  927. /// but OPM_Int must have priority over OPM_RegBank since constant integers
  928. /// are represented by a virtual register defined by a G_CONSTANT instruction.
  929. ///
  930. /// Note: The relative priority between IPM_ and OPM_ does not matter, they
  931. /// are currently not compared between each other.
  932. enum PredicateKind {
  933. IPM_Opcode,
  934. IPM_NumOperands,
  935. IPM_ImmPredicate,
  936. IPM_Imm,
  937. IPM_AtomicOrderingMMO,
  938. IPM_MemoryLLTSize,
  939. IPM_MemoryVsLLTSize,
  940. IPM_MemoryAddressSpace,
  941. IPM_MemoryAlignment,
  942. IPM_VectorSplatImm,
  943. IPM_NoUse,
  944. IPM_GenericPredicate,
  945. OPM_SameOperand,
  946. OPM_ComplexPattern,
  947. OPM_IntrinsicID,
  948. OPM_CmpPredicate,
  949. OPM_Instruction,
  950. OPM_Int,
  951. OPM_LiteralInt,
  952. OPM_LLT,
  953. OPM_PointerToAny,
  954. OPM_RegBank,
  955. OPM_MBB,
  956. OPM_RecordNamedOperand,
  957. };
  958. protected:
  959. PredicateKind Kind;
  960. unsigned InsnVarID;
  961. unsigned OpIdx;
  962. public:
  963. PredicateMatcher(PredicateKind Kind, unsigned InsnVarID, unsigned OpIdx = ~0)
  964. : Kind(Kind), InsnVarID(InsnVarID), OpIdx(OpIdx) {}
  965. unsigned getInsnVarID() const { return InsnVarID; }
  966. unsigned getOpIdx() const { return OpIdx; }
  967. virtual ~PredicateMatcher() = default;
  968. /// Emit MatchTable opcodes that check the predicate for the given operand.
  969. virtual void emitPredicateOpcodes(MatchTable &Table,
  970. RuleMatcher &Rule) const = 0;
  971. PredicateKind getKind() const { return Kind; }
  972. bool dependsOnOperands() const {
  973. // Custom predicates really depend on the context pattern of the
  974. // instruction, not just the individual instruction. This therefore
  975. // implicitly depends on all other pattern constraints.
  976. return Kind == IPM_GenericPredicate;
  977. }
  978. virtual bool isIdentical(const PredicateMatcher &B) const {
  979. return B.getKind() == getKind() && InsnVarID == B.InsnVarID &&
  980. OpIdx == B.OpIdx;
  981. }
  982. virtual bool isIdenticalDownToValue(const PredicateMatcher &B) const {
  983. return hasValue() && PredicateMatcher::isIdentical(B);
  984. }
  985. virtual MatchTableRecord getValue() const {
  986. assert(hasValue() && "Can not get a value of a value-less predicate!");
  987. llvm_unreachable("Not implemented yet");
  988. }
  989. virtual bool hasValue() const { return false; }
  990. /// Report the maximum number of temporary operands needed by the predicate
  991. /// matcher.
  992. virtual unsigned countRendererFns() const { return 0; }
  993. };
  994. /// Generates code to check a predicate of an operand.
  995. ///
  996. /// Typical predicates include:
  997. /// * Operand is a particular register.
  998. /// * Operand is assigned a particular register bank.
  999. /// * Operand is an MBB.
  1000. class OperandPredicateMatcher : public PredicateMatcher {
  1001. public:
  1002. OperandPredicateMatcher(PredicateKind Kind, unsigned InsnVarID,
  1003. unsigned OpIdx)
  1004. : PredicateMatcher(Kind, InsnVarID, OpIdx) {}
  1005. virtual ~OperandPredicateMatcher() {}
  1006. /// Compare the priority of this object and B.
  1007. ///
  1008. /// Returns true if this object is more important than B.
  1009. virtual bool isHigherPriorityThan(const OperandPredicateMatcher &B) const;
  1010. };
  1011. template <>
  1012. std::string
  1013. PredicateListMatcher<OperandPredicateMatcher>::getNoPredicateComment() const {
  1014. return "No operand predicates";
  1015. }
  1016. /// Generates code to check that a register operand is defined by the same exact
  1017. /// one as another.
  1018. class SameOperandMatcher : public OperandPredicateMatcher {
  1019. std::string MatchingName;
  1020. unsigned OrigOpIdx;
  1021. public:
  1022. SameOperandMatcher(unsigned InsnVarID, unsigned OpIdx, StringRef MatchingName,
  1023. unsigned OrigOpIdx)
  1024. : OperandPredicateMatcher(OPM_SameOperand, InsnVarID, OpIdx),
  1025. MatchingName(MatchingName), OrigOpIdx(OrigOpIdx) {}
  1026. static bool classof(const PredicateMatcher *P) {
  1027. return P->getKind() == OPM_SameOperand;
  1028. }
  1029. void emitPredicateOpcodes(MatchTable &Table,
  1030. RuleMatcher &Rule) const override;
  1031. bool isIdentical(const PredicateMatcher &B) const override {
  1032. return OperandPredicateMatcher::isIdentical(B) &&
  1033. OrigOpIdx == cast<SameOperandMatcher>(&B)->OrigOpIdx &&
  1034. MatchingName == cast<SameOperandMatcher>(&B)->MatchingName;
  1035. }
  1036. };
  1037. /// Generates code to check that an operand is a particular LLT.
  1038. class LLTOperandMatcher : public OperandPredicateMatcher {
  1039. protected:
  1040. LLTCodeGen Ty;
  1041. public:
  1042. static std::map<LLTCodeGen, unsigned> TypeIDValues;
  1043. static void initTypeIDValuesMap() {
  1044. TypeIDValues.clear();
  1045. unsigned ID = 0;
  1046. for (const LLTCodeGen &LLTy : KnownTypes)
  1047. TypeIDValues[LLTy] = ID++;
  1048. }
  1049. LLTOperandMatcher(unsigned InsnVarID, unsigned OpIdx, const LLTCodeGen &Ty)
  1050. : OperandPredicateMatcher(OPM_LLT, InsnVarID, OpIdx), Ty(Ty) {
  1051. KnownTypes.insert(Ty);
  1052. }
  1053. static bool classof(const PredicateMatcher *P) {
  1054. return P->getKind() == OPM_LLT;
  1055. }
  1056. bool isIdentical(const PredicateMatcher &B) const override {
  1057. return OperandPredicateMatcher::isIdentical(B) &&
  1058. Ty == cast<LLTOperandMatcher>(&B)->Ty;
  1059. }
  1060. MatchTableRecord getValue() const override {
  1061. const auto VI = TypeIDValues.find(Ty);
  1062. if (VI == TypeIDValues.end())
  1063. return MatchTable::NamedValue(getTy().getCxxEnumValue());
  1064. return MatchTable::NamedValue(getTy().getCxxEnumValue(), VI->second);
  1065. }
  1066. bool hasValue() const override {
  1067. if (TypeIDValues.size() != KnownTypes.size())
  1068. initTypeIDValuesMap();
  1069. return TypeIDValues.count(Ty);
  1070. }
  1071. LLTCodeGen getTy() const { return Ty; }
  1072. void emitPredicateOpcodes(MatchTable &Table,
  1073. RuleMatcher &Rule) const override {
  1074. Table << MatchTable::Opcode("GIM_CheckType") << MatchTable::Comment("MI")
  1075. << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
  1076. << MatchTable::IntValue(OpIdx) << MatchTable::Comment("Type")
  1077. << getValue() << MatchTable::LineBreak;
  1078. }
  1079. };
  1080. std::map<LLTCodeGen, unsigned> LLTOperandMatcher::TypeIDValues;
  1081. /// Generates code to check that an operand is a pointer to any address space.
  1082. ///
  1083. /// In SelectionDAG, the types did not describe pointers or address spaces. As a
  1084. /// result, iN is used to describe a pointer of N bits to any address space and
  1085. /// PatFrag predicates are typically used to constrain the address space. There's
  1086. /// no reliable means to derive the missing type information from the pattern so
  1087. /// imported rules must test the components of a pointer separately.
  1088. ///
  1089. /// If SizeInBits is zero, then the pointer size will be obtained from the
  1090. /// subtarget.
  1091. class PointerToAnyOperandMatcher : public OperandPredicateMatcher {
  1092. protected:
  1093. unsigned SizeInBits;
  1094. public:
  1095. PointerToAnyOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  1096. unsigned SizeInBits)
  1097. : OperandPredicateMatcher(OPM_PointerToAny, InsnVarID, OpIdx),
  1098. SizeInBits(SizeInBits) {}
  1099. static bool classof(const PredicateMatcher *P) {
  1100. return P->getKind() == OPM_PointerToAny;
  1101. }
  1102. bool isIdentical(const PredicateMatcher &B) const override {
  1103. return OperandPredicateMatcher::isIdentical(B) &&
  1104. SizeInBits == cast<PointerToAnyOperandMatcher>(&B)->SizeInBits;
  1105. }
  1106. void emitPredicateOpcodes(MatchTable &Table,
  1107. RuleMatcher &Rule) const override {
  1108. Table << MatchTable::Opcode("GIM_CheckPointerToAny")
  1109. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1110. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1111. << MatchTable::Comment("SizeInBits")
  1112. << MatchTable::IntValue(SizeInBits) << MatchTable::LineBreak;
  1113. }
  1114. };
  1115. /// Generates code to record named operand in RecordedOperands list at StoreIdx.
  1116. /// Predicates with 'let PredicateCodeUsesOperands = 1' get RecordedOperands as
  1117. /// an argument to predicate's c++ code once all operands have been matched.
  1118. class RecordNamedOperandMatcher : public OperandPredicateMatcher {
  1119. protected:
  1120. unsigned StoreIdx;
  1121. std::string Name;
  1122. public:
  1123. RecordNamedOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  1124. unsigned StoreIdx, StringRef Name)
  1125. : OperandPredicateMatcher(OPM_RecordNamedOperand, InsnVarID, OpIdx),
  1126. StoreIdx(StoreIdx), Name(Name) {}
  1127. static bool classof(const PredicateMatcher *P) {
  1128. return P->getKind() == OPM_RecordNamedOperand;
  1129. }
  1130. bool isIdentical(const PredicateMatcher &B) const override {
  1131. return OperandPredicateMatcher::isIdentical(B) &&
  1132. StoreIdx == cast<RecordNamedOperandMatcher>(&B)->StoreIdx &&
  1133. Name == cast<RecordNamedOperandMatcher>(&B)->Name;
  1134. }
  1135. void emitPredicateOpcodes(MatchTable &Table,
  1136. RuleMatcher &Rule) const override {
  1137. Table << MatchTable::Opcode("GIM_RecordNamedOperand")
  1138. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1139. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1140. << MatchTable::Comment("StoreIdx") << MatchTable::IntValue(StoreIdx)
  1141. << MatchTable::Comment("Name : " + Name) << MatchTable::LineBreak;
  1142. }
  1143. };
  1144. /// Generates code to check that an operand is a particular target constant.
  1145. class ComplexPatternOperandMatcher : public OperandPredicateMatcher {
  1146. protected:
  1147. const OperandMatcher &Operand;
  1148. const Record &TheDef;
  1149. unsigned getAllocatedTemporariesBaseID() const;
  1150. public:
  1151. bool isIdentical(const PredicateMatcher &B) const override { return false; }
  1152. ComplexPatternOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  1153. const OperandMatcher &Operand,
  1154. const Record &TheDef)
  1155. : OperandPredicateMatcher(OPM_ComplexPattern, InsnVarID, OpIdx),
  1156. Operand(Operand), TheDef(TheDef) {}
  1157. static bool classof(const PredicateMatcher *P) {
  1158. return P->getKind() == OPM_ComplexPattern;
  1159. }
  1160. void emitPredicateOpcodes(MatchTable &Table,
  1161. RuleMatcher &Rule) const override {
  1162. unsigned ID = getAllocatedTemporariesBaseID();
  1163. Table << MatchTable::Opcode("GIM_CheckComplexPattern")
  1164. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1165. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1166. << MatchTable::Comment("Renderer") << MatchTable::IntValue(ID)
  1167. << MatchTable::NamedValue(("GICP_" + TheDef.getName()).str())
  1168. << MatchTable::LineBreak;
  1169. }
  1170. unsigned countRendererFns() const override {
  1171. return 1;
  1172. }
  1173. };
  1174. /// Generates code to check that an operand is in a particular register bank.
  1175. class RegisterBankOperandMatcher : public OperandPredicateMatcher {
  1176. protected:
  1177. const CodeGenRegisterClass &RC;
  1178. public:
  1179. RegisterBankOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  1180. const CodeGenRegisterClass &RC)
  1181. : OperandPredicateMatcher(OPM_RegBank, InsnVarID, OpIdx), RC(RC) {}
  1182. bool isIdentical(const PredicateMatcher &B) const override {
  1183. return OperandPredicateMatcher::isIdentical(B) &&
  1184. RC.getDef() == cast<RegisterBankOperandMatcher>(&B)->RC.getDef();
  1185. }
  1186. static bool classof(const PredicateMatcher *P) {
  1187. return P->getKind() == OPM_RegBank;
  1188. }
  1189. void emitPredicateOpcodes(MatchTable &Table,
  1190. RuleMatcher &Rule) const override {
  1191. Table << MatchTable::Opcode("GIM_CheckRegBankForClass")
  1192. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1193. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1194. << MatchTable::Comment("RC")
  1195. << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
  1196. << MatchTable::LineBreak;
  1197. }
  1198. };
  1199. /// Generates code to check that an operand is a basic block.
  1200. class MBBOperandMatcher : public OperandPredicateMatcher {
  1201. public:
  1202. MBBOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
  1203. : OperandPredicateMatcher(OPM_MBB, InsnVarID, OpIdx) {}
  1204. static bool classof(const PredicateMatcher *P) {
  1205. return P->getKind() == OPM_MBB;
  1206. }
  1207. void emitPredicateOpcodes(MatchTable &Table,
  1208. RuleMatcher &Rule) const override {
  1209. Table << MatchTable::Opcode("GIM_CheckIsMBB") << MatchTable::Comment("MI")
  1210. << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
  1211. << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
  1212. }
  1213. };
  1214. class ImmOperandMatcher : public OperandPredicateMatcher {
  1215. public:
  1216. ImmOperandMatcher(unsigned InsnVarID, unsigned OpIdx)
  1217. : OperandPredicateMatcher(IPM_Imm, InsnVarID, OpIdx) {}
  1218. static bool classof(const PredicateMatcher *P) {
  1219. return P->getKind() == IPM_Imm;
  1220. }
  1221. void emitPredicateOpcodes(MatchTable &Table,
  1222. RuleMatcher &Rule) const override {
  1223. Table << MatchTable::Opcode("GIM_CheckIsImm") << MatchTable::Comment("MI")
  1224. << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Op")
  1225. << MatchTable::IntValue(OpIdx) << MatchTable::LineBreak;
  1226. }
  1227. };
  1228. /// Generates code to check that an operand is a G_CONSTANT with a particular
  1229. /// int.
  1230. class ConstantIntOperandMatcher : public OperandPredicateMatcher {
  1231. protected:
  1232. int64_t Value;
  1233. public:
  1234. ConstantIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
  1235. : OperandPredicateMatcher(OPM_Int, InsnVarID, OpIdx), Value(Value) {}
  1236. bool isIdentical(const PredicateMatcher &B) const override {
  1237. return OperandPredicateMatcher::isIdentical(B) &&
  1238. Value == cast<ConstantIntOperandMatcher>(&B)->Value;
  1239. }
  1240. static bool classof(const PredicateMatcher *P) {
  1241. return P->getKind() == OPM_Int;
  1242. }
  1243. void emitPredicateOpcodes(MatchTable &Table,
  1244. RuleMatcher &Rule) const override {
  1245. Table << MatchTable::Opcode("GIM_CheckConstantInt")
  1246. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1247. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1248. << MatchTable::IntValue(Value) << MatchTable::LineBreak;
  1249. }
  1250. };
  1251. /// Generates code to check that an operand is a raw int (where MO.isImm() or
  1252. /// MO.isCImm() is true).
  1253. class LiteralIntOperandMatcher : public OperandPredicateMatcher {
  1254. protected:
  1255. int64_t Value;
  1256. public:
  1257. LiteralIntOperandMatcher(unsigned InsnVarID, unsigned OpIdx, int64_t Value)
  1258. : OperandPredicateMatcher(OPM_LiteralInt, InsnVarID, OpIdx),
  1259. Value(Value) {}
  1260. bool isIdentical(const PredicateMatcher &B) const override {
  1261. return OperandPredicateMatcher::isIdentical(B) &&
  1262. Value == cast<LiteralIntOperandMatcher>(&B)->Value;
  1263. }
  1264. static bool classof(const PredicateMatcher *P) {
  1265. return P->getKind() == OPM_LiteralInt;
  1266. }
  1267. void emitPredicateOpcodes(MatchTable &Table,
  1268. RuleMatcher &Rule) const override {
  1269. Table << MatchTable::Opcode("GIM_CheckLiteralInt")
  1270. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1271. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1272. << MatchTable::IntValue(Value) << MatchTable::LineBreak;
  1273. }
  1274. };
  1275. /// Generates code to check that an operand is an CmpInst predicate
  1276. class CmpPredicateOperandMatcher : public OperandPredicateMatcher {
  1277. protected:
  1278. std::string PredName;
  1279. public:
  1280. CmpPredicateOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  1281. std::string P)
  1282. : OperandPredicateMatcher(OPM_CmpPredicate, InsnVarID, OpIdx), PredName(P) {}
  1283. bool isIdentical(const PredicateMatcher &B) const override {
  1284. return OperandPredicateMatcher::isIdentical(B) &&
  1285. PredName == cast<CmpPredicateOperandMatcher>(&B)->PredName;
  1286. }
  1287. static bool classof(const PredicateMatcher *P) {
  1288. return P->getKind() == OPM_CmpPredicate;
  1289. }
  1290. void emitPredicateOpcodes(MatchTable &Table,
  1291. RuleMatcher &Rule) const override {
  1292. Table << MatchTable::Opcode("GIM_CheckCmpPredicate")
  1293. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1294. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1295. << MatchTable::Comment("Predicate")
  1296. << MatchTable::NamedValue("CmpInst", PredName)
  1297. << MatchTable::LineBreak;
  1298. }
  1299. };
  1300. /// Generates code to check that an operand is an intrinsic ID.
  1301. class IntrinsicIDOperandMatcher : public OperandPredicateMatcher {
  1302. protected:
  1303. const CodeGenIntrinsic *II;
  1304. public:
  1305. IntrinsicIDOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  1306. const CodeGenIntrinsic *II)
  1307. : OperandPredicateMatcher(OPM_IntrinsicID, InsnVarID, OpIdx), II(II) {}
  1308. bool isIdentical(const PredicateMatcher &B) const override {
  1309. return OperandPredicateMatcher::isIdentical(B) &&
  1310. II == cast<IntrinsicIDOperandMatcher>(&B)->II;
  1311. }
  1312. static bool classof(const PredicateMatcher *P) {
  1313. return P->getKind() == OPM_IntrinsicID;
  1314. }
  1315. void emitPredicateOpcodes(MatchTable &Table,
  1316. RuleMatcher &Rule) const override {
  1317. Table << MatchTable::Opcode("GIM_CheckIntrinsicID")
  1318. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1319. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  1320. << MatchTable::NamedValue("Intrinsic::" + II->EnumName)
  1321. << MatchTable::LineBreak;
  1322. }
  1323. };
  1324. /// Generates code to check that this operand is an immediate whose value meets
  1325. /// an immediate predicate.
  1326. class OperandImmPredicateMatcher : public OperandPredicateMatcher {
  1327. protected:
  1328. TreePredicateFn Predicate;
  1329. public:
  1330. OperandImmPredicateMatcher(unsigned InsnVarID, unsigned OpIdx,
  1331. const TreePredicateFn &Predicate)
  1332. : OperandPredicateMatcher(IPM_ImmPredicate, InsnVarID, OpIdx),
  1333. Predicate(Predicate) {}
  1334. bool isIdentical(const PredicateMatcher &B) const override {
  1335. return OperandPredicateMatcher::isIdentical(B) &&
  1336. Predicate.getOrigPatFragRecord() ==
  1337. cast<OperandImmPredicateMatcher>(&B)
  1338. ->Predicate.getOrigPatFragRecord();
  1339. }
  1340. static bool classof(const PredicateMatcher *P) {
  1341. return P->getKind() == IPM_ImmPredicate;
  1342. }
  1343. void emitPredicateOpcodes(MatchTable &Table,
  1344. RuleMatcher &Rule) const override {
  1345. Table << MatchTable::Opcode("GIM_CheckImmOperandPredicate")
  1346. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1347. << MatchTable::Comment("MO") << MatchTable::IntValue(OpIdx)
  1348. << MatchTable::Comment("Predicate")
  1349. << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
  1350. << MatchTable::LineBreak;
  1351. }
  1352. };
  1353. /// Generates code to check that a set of predicates match for a particular
  1354. /// operand.
  1355. class OperandMatcher : public PredicateListMatcher<OperandPredicateMatcher> {
  1356. protected:
  1357. InstructionMatcher &Insn;
  1358. unsigned OpIdx;
  1359. std::string SymbolicName;
  1360. /// The index of the first temporary variable allocated to this operand. The
  1361. /// number of allocated temporaries can be found with
  1362. /// countRendererFns().
  1363. unsigned AllocatedTemporariesBaseID;
  1364. public:
  1365. OperandMatcher(InstructionMatcher &Insn, unsigned OpIdx,
  1366. const std::string &SymbolicName,
  1367. unsigned AllocatedTemporariesBaseID)
  1368. : Insn(Insn), OpIdx(OpIdx), SymbolicName(SymbolicName),
  1369. AllocatedTemporariesBaseID(AllocatedTemporariesBaseID) {}
  1370. bool hasSymbolicName() const { return !SymbolicName.empty(); }
  1371. StringRef getSymbolicName() const { return SymbolicName; }
  1372. void setSymbolicName(StringRef Name) {
  1373. assert(SymbolicName.empty() && "Operand already has a symbolic name");
  1374. SymbolicName = std::string(Name);
  1375. }
  1376. /// Construct a new operand predicate and add it to the matcher.
  1377. template <class Kind, class... Args>
  1378. std::optional<Kind *> addPredicate(Args &&...args) {
  1379. if (isSameAsAnotherOperand())
  1380. return std::nullopt;
  1381. Predicates.emplace_back(std::make_unique<Kind>(
  1382. getInsnVarID(), getOpIdx(), std::forward<Args>(args)...));
  1383. return static_cast<Kind *>(Predicates.back().get());
  1384. }
  1385. unsigned getOpIdx() const { return OpIdx; }
  1386. unsigned getInsnVarID() const;
  1387. std::string getOperandExpr(unsigned InsnVarID) const {
  1388. return "State.MIs[" + llvm::to_string(InsnVarID) + "]->getOperand(" +
  1389. llvm::to_string(OpIdx) + ")";
  1390. }
  1391. InstructionMatcher &getInstructionMatcher() const { return Insn; }
  1392. Error addTypeCheckPredicate(const TypeSetByHwMode &VTy,
  1393. bool OperandIsAPointer);
  1394. /// Emit MatchTable opcodes that test whether the instruction named in
  1395. /// InsnVarID matches all the predicates and all the operands.
  1396. void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
  1397. if (!Optimized) {
  1398. std::string Comment;
  1399. raw_string_ostream CommentOS(Comment);
  1400. CommentOS << "MIs[" << getInsnVarID() << "] ";
  1401. if (SymbolicName.empty())
  1402. CommentOS << "Operand " << OpIdx;
  1403. else
  1404. CommentOS << SymbolicName;
  1405. Table << MatchTable::Comment(Comment) << MatchTable::LineBreak;
  1406. }
  1407. emitPredicateListOpcodes(Table, Rule);
  1408. }
  1409. /// Compare the priority of this object and B.
  1410. ///
  1411. /// Returns true if this object is more important than B.
  1412. bool isHigherPriorityThan(OperandMatcher &B) {
  1413. // Operand matchers involving more predicates have higher priority.
  1414. if (predicates_size() > B.predicates_size())
  1415. return true;
  1416. if (predicates_size() < B.predicates_size())
  1417. return false;
  1418. // This assumes that predicates are added in a consistent order.
  1419. for (auto &&Predicate : zip(predicates(), B.predicates())) {
  1420. if (std::get<0>(Predicate)->isHigherPriorityThan(*std::get<1>(Predicate)))
  1421. return true;
  1422. if (std::get<1>(Predicate)->isHigherPriorityThan(*std::get<0>(Predicate)))
  1423. return false;
  1424. }
  1425. return false;
  1426. };
  1427. /// Report the maximum number of temporary operands needed by the operand
  1428. /// matcher.
  1429. unsigned countRendererFns() {
  1430. return std::accumulate(
  1431. predicates().begin(), predicates().end(), 0,
  1432. [](unsigned A,
  1433. const std::unique_ptr<OperandPredicateMatcher> &Predicate) {
  1434. return A + Predicate->countRendererFns();
  1435. });
  1436. }
  1437. unsigned getAllocatedTemporariesBaseID() const {
  1438. return AllocatedTemporariesBaseID;
  1439. }
  1440. bool isSameAsAnotherOperand() {
  1441. for (const auto &Predicate : predicates())
  1442. if (isa<SameOperandMatcher>(Predicate))
  1443. return true;
  1444. return false;
  1445. }
  1446. };
  1447. Error OperandMatcher::addTypeCheckPredicate(const TypeSetByHwMode &VTy,
  1448. bool OperandIsAPointer) {
  1449. if (!VTy.isMachineValueType())
  1450. return failedImport("unsupported typeset");
  1451. if (VTy.getMachineValueType() == MVT::iPTR && OperandIsAPointer) {
  1452. addPredicate<PointerToAnyOperandMatcher>(0);
  1453. return Error::success();
  1454. }
  1455. auto OpTyOrNone = MVTToLLT(VTy.getMachineValueType().SimpleTy);
  1456. if (!OpTyOrNone)
  1457. return failedImport("unsupported type");
  1458. if (OperandIsAPointer)
  1459. addPredicate<PointerToAnyOperandMatcher>(OpTyOrNone->get().getSizeInBits());
  1460. else if (VTy.isPointer())
  1461. addPredicate<LLTOperandMatcher>(LLT::pointer(VTy.getPtrAddrSpace(),
  1462. OpTyOrNone->get().getSizeInBits()));
  1463. else
  1464. addPredicate<LLTOperandMatcher>(*OpTyOrNone);
  1465. return Error::success();
  1466. }
  1467. unsigned ComplexPatternOperandMatcher::getAllocatedTemporariesBaseID() const {
  1468. return Operand.getAllocatedTemporariesBaseID();
  1469. }
  1470. /// Generates code to check a predicate on an instruction.
  1471. ///
  1472. /// Typical predicates include:
  1473. /// * The opcode of the instruction is a particular value.
  1474. /// * The nsw/nuw flag is/isn't set.
  1475. class InstructionPredicateMatcher : public PredicateMatcher {
  1476. public:
  1477. InstructionPredicateMatcher(PredicateKind Kind, unsigned InsnVarID)
  1478. : PredicateMatcher(Kind, InsnVarID) {}
  1479. virtual ~InstructionPredicateMatcher() {}
  1480. /// Compare the priority of this object and B.
  1481. ///
  1482. /// Returns true if this object is more important than B.
  1483. virtual bool
  1484. isHigherPriorityThan(const InstructionPredicateMatcher &B) const {
  1485. return Kind < B.Kind;
  1486. };
  1487. };
  1488. template <>
  1489. std::string
  1490. PredicateListMatcher<PredicateMatcher>::getNoPredicateComment() const {
  1491. return "No instruction predicates";
  1492. }
  1493. /// Generates code to check the opcode of an instruction.
  1494. class InstructionOpcodeMatcher : public InstructionPredicateMatcher {
  1495. protected:
  1496. // Allow matching one to several, similar opcodes that share properties. This
  1497. // is to handle patterns where one SelectionDAG operation maps to multiple
  1498. // GlobalISel ones (e.g. G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC). The first
  1499. // is treated as the canonical opcode.
  1500. SmallVector<const CodeGenInstruction *, 2> Insts;
  1501. static DenseMap<const CodeGenInstruction *, unsigned> OpcodeValues;
  1502. MatchTableRecord getInstValue(const CodeGenInstruction *I) const {
  1503. const auto VI = OpcodeValues.find(I);
  1504. if (VI != OpcodeValues.end())
  1505. return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
  1506. VI->second);
  1507. return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
  1508. }
  1509. public:
  1510. static void initOpcodeValuesMap(const CodeGenTarget &Target) {
  1511. OpcodeValues.clear();
  1512. unsigned OpcodeValue = 0;
  1513. for (const CodeGenInstruction *I : Target.getInstructionsByEnumValue())
  1514. OpcodeValues[I] = OpcodeValue++;
  1515. }
  1516. InstructionOpcodeMatcher(unsigned InsnVarID,
  1517. ArrayRef<const CodeGenInstruction *> I)
  1518. : InstructionPredicateMatcher(IPM_Opcode, InsnVarID),
  1519. Insts(I.begin(), I.end()) {
  1520. assert((Insts.size() == 1 || Insts.size() == 2) &&
  1521. "unexpected number of opcode alternatives");
  1522. }
  1523. static bool classof(const PredicateMatcher *P) {
  1524. return P->getKind() == IPM_Opcode;
  1525. }
  1526. bool isIdentical(const PredicateMatcher &B) const override {
  1527. return InstructionPredicateMatcher::isIdentical(B) &&
  1528. Insts == cast<InstructionOpcodeMatcher>(&B)->Insts;
  1529. }
  1530. bool hasValue() const override {
  1531. return Insts.size() == 1 && OpcodeValues.count(Insts[0]);
  1532. }
  1533. // TODO: This is used for the SwitchMatcher optimization. We should be able to
  1534. // return a list of the opcodes to match.
  1535. MatchTableRecord getValue() const override {
  1536. assert(Insts.size() == 1);
  1537. const CodeGenInstruction *I = Insts[0];
  1538. const auto VI = OpcodeValues.find(I);
  1539. if (VI != OpcodeValues.end())
  1540. return MatchTable::NamedValue(I->Namespace, I->TheDef->getName(),
  1541. VI->second);
  1542. return MatchTable::NamedValue(I->Namespace, I->TheDef->getName());
  1543. }
  1544. void emitPredicateOpcodes(MatchTable &Table,
  1545. RuleMatcher &Rule) const override {
  1546. StringRef CheckType = Insts.size() == 1 ?
  1547. "GIM_CheckOpcode" : "GIM_CheckOpcodeIsEither";
  1548. Table << MatchTable::Opcode(CheckType) << MatchTable::Comment("MI")
  1549. << MatchTable::IntValue(InsnVarID);
  1550. for (const CodeGenInstruction *I : Insts)
  1551. Table << getInstValue(I);
  1552. Table << MatchTable::LineBreak;
  1553. }
  1554. /// Compare the priority of this object and B.
  1555. ///
  1556. /// Returns true if this object is more important than B.
  1557. bool
  1558. isHigherPriorityThan(const InstructionPredicateMatcher &B) const override {
  1559. if (InstructionPredicateMatcher::isHigherPriorityThan(B))
  1560. return true;
  1561. if (B.InstructionPredicateMatcher::isHigherPriorityThan(*this))
  1562. return false;
  1563. // Prioritize opcodes for cosmetic reasons in the generated source. Although
  1564. // this is cosmetic at the moment, we may want to drive a similar ordering
  1565. // using instruction frequency information to improve compile time.
  1566. if (const InstructionOpcodeMatcher *BO =
  1567. dyn_cast<InstructionOpcodeMatcher>(&B))
  1568. return Insts[0]->TheDef->getName() < BO->Insts[0]->TheDef->getName();
  1569. return false;
  1570. };
  1571. bool isConstantInstruction() const {
  1572. return Insts.size() == 1 && Insts[0]->TheDef->getName() == "G_CONSTANT";
  1573. }
  1574. // The first opcode is the canonical opcode, and later are alternatives.
  1575. StringRef getOpcode() const {
  1576. return Insts[0]->TheDef->getName();
  1577. }
  1578. ArrayRef<const CodeGenInstruction *> getAlternativeOpcodes() {
  1579. return Insts;
  1580. }
  1581. bool isVariadicNumOperands() const {
  1582. // If one is variadic, they all should be.
  1583. return Insts[0]->Operands.isVariadic;
  1584. }
  1585. StringRef getOperandType(unsigned OpIdx) const {
  1586. // Types expected to be uniform for all alternatives.
  1587. return Insts[0]->Operands[OpIdx].OperandType;
  1588. }
  1589. };
  1590. DenseMap<const CodeGenInstruction *, unsigned>
  1591. InstructionOpcodeMatcher::OpcodeValues;
  1592. class InstructionNumOperandsMatcher final : public InstructionPredicateMatcher {
  1593. unsigned NumOperands = 0;
  1594. public:
  1595. InstructionNumOperandsMatcher(unsigned InsnVarID, unsigned NumOperands)
  1596. : InstructionPredicateMatcher(IPM_NumOperands, InsnVarID),
  1597. NumOperands(NumOperands) {}
  1598. static bool classof(const PredicateMatcher *P) {
  1599. return P->getKind() == IPM_NumOperands;
  1600. }
  1601. bool isIdentical(const PredicateMatcher &B) const override {
  1602. return InstructionPredicateMatcher::isIdentical(B) &&
  1603. NumOperands == cast<InstructionNumOperandsMatcher>(&B)->NumOperands;
  1604. }
  1605. void emitPredicateOpcodes(MatchTable &Table,
  1606. RuleMatcher &Rule) const override {
  1607. Table << MatchTable::Opcode("GIM_CheckNumOperands")
  1608. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1609. << MatchTable::Comment("Expected")
  1610. << MatchTable::IntValue(NumOperands) << MatchTable::LineBreak;
  1611. }
  1612. };
  1613. /// Generates code to check that this instruction is a constant whose value
  1614. /// meets an immediate predicate.
  1615. ///
  1616. /// Immediates are slightly odd since they are typically used like an operand
  1617. /// but are represented as an operator internally. We typically write simm8:$src
  1618. /// in a tablegen pattern, but this is just syntactic sugar for
  1619. /// (imm:i32)<<P:Predicate_simm8>>:$imm which more directly describes the nodes
  1620. /// that will be matched and the predicate (which is attached to the imm
  1621. /// operator) that will be tested. In SelectionDAG this describes a
  1622. /// ConstantSDNode whose internal value will be tested using the simm8 predicate.
  1623. ///
  1624. /// The corresponding GlobalISel representation is %1 = G_CONSTANT iN Value. In
  1625. /// this representation, the immediate could be tested with an
  1626. /// InstructionMatcher, InstructionOpcodeMatcher, OperandMatcher, and a
  1627. /// OperandPredicateMatcher-subclass to check the Value meets the predicate but
  1628. /// there are two implementation issues with producing that matcher
  1629. /// configuration from the SelectionDAG pattern:
  1630. /// * ImmLeaf is a PatFrag whose root is an InstructionMatcher. This means that
  1631. /// were we to sink the immediate predicate to the operand we would have to
  1632. /// have two partial implementations of PatFrag support, one for immediates
  1633. /// and one for non-immediates.
  1634. /// * At the point we handle the predicate, the OperandMatcher hasn't been
  1635. /// created yet. If we were to sink the predicate to the OperandMatcher we
  1636. /// would also have to complicate (or duplicate) the code that descends and
  1637. /// creates matchers for the subtree.
  1638. /// Overall, it's simpler to handle it in the place it was found.
  1639. class InstructionImmPredicateMatcher : public InstructionPredicateMatcher {
  1640. protected:
  1641. TreePredicateFn Predicate;
  1642. public:
  1643. InstructionImmPredicateMatcher(unsigned InsnVarID,
  1644. const TreePredicateFn &Predicate)
  1645. : InstructionPredicateMatcher(IPM_ImmPredicate, InsnVarID),
  1646. Predicate(Predicate) {}
  1647. bool isIdentical(const PredicateMatcher &B) const override {
  1648. return InstructionPredicateMatcher::isIdentical(B) &&
  1649. Predicate.getOrigPatFragRecord() ==
  1650. cast<InstructionImmPredicateMatcher>(&B)
  1651. ->Predicate.getOrigPatFragRecord();
  1652. }
  1653. static bool classof(const PredicateMatcher *P) {
  1654. return P->getKind() == IPM_ImmPredicate;
  1655. }
  1656. void emitPredicateOpcodes(MatchTable &Table,
  1657. RuleMatcher &Rule) const override {
  1658. Table << MatchTable::Opcode(getMatchOpcodeForImmPredicate(Predicate))
  1659. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1660. << MatchTable::Comment("Predicate")
  1661. << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
  1662. << MatchTable::LineBreak;
  1663. }
  1664. };
  1665. /// Generates code to check that a memory instruction has a atomic ordering
  1666. /// MachineMemoryOperand.
  1667. class AtomicOrderingMMOPredicateMatcher : public InstructionPredicateMatcher {
  1668. public:
  1669. enum AOComparator {
  1670. AO_Exactly,
  1671. AO_OrStronger,
  1672. AO_WeakerThan,
  1673. };
  1674. protected:
  1675. StringRef Order;
  1676. AOComparator Comparator;
  1677. public:
  1678. AtomicOrderingMMOPredicateMatcher(unsigned InsnVarID, StringRef Order,
  1679. AOComparator Comparator = AO_Exactly)
  1680. : InstructionPredicateMatcher(IPM_AtomicOrderingMMO, InsnVarID),
  1681. Order(Order), Comparator(Comparator) {}
  1682. static bool classof(const PredicateMatcher *P) {
  1683. return P->getKind() == IPM_AtomicOrderingMMO;
  1684. }
  1685. bool isIdentical(const PredicateMatcher &B) const override {
  1686. if (!InstructionPredicateMatcher::isIdentical(B))
  1687. return false;
  1688. const auto &R = *cast<AtomicOrderingMMOPredicateMatcher>(&B);
  1689. return Order == R.Order && Comparator == R.Comparator;
  1690. }
  1691. void emitPredicateOpcodes(MatchTable &Table,
  1692. RuleMatcher &Rule) const override {
  1693. StringRef Opcode = "GIM_CheckAtomicOrdering";
  1694. if (Comparator == AO_OrStronger)
  1695. Opcode = "GIM_CheckAtomicOrderingOrStrongerThan";
  1696. if (Comparator == AO_WeakerThan)
  1697. Opcode = "GIM_CheckAtomicOrderingWeakerThan";
  1698. Table << MatchTable::Opcode(Opcode) << MatchTable::Comment("MI")
  1699. << MatchTable::IntValue(InsnVarID) << MatchTable::Comment("Order")
  1700. << MatchTable::NamedValue(("(int64_t)AtomicOrdering::" + Order).str())
  1701. << MatchTable::LineBreak;
  1702. }
  1703. };
  1704. /// Generates code to check that the size of an MMO is exactly N bytes.
  1705. class MemorySizePredicateMatcher : public InstructionPredicateMatcher {
  1706. protected:
  1707. unsigned MMOIdx;
  1708. uint64_t Size;
  1709. public:
  1710. MemorySizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx, unsigned Size)
  1711. : InstructionPredicateMatcher(IPM_MemoryLLTSize, InsnVarID),
  1712. MMOIdx(MMOIdx), Size(Size) {}
  1713. static bool classof(const PredicateMatcher *P) {
  1714. return P->getKind() == IPM_MemoryLLTSize;
  1715. }
  1716. bool isIdentical(const PredicateMatcher &B) const override {
  1717. return InstructionPredicateMatcher::isIdentical(B) &&
  1718. MMOIdx == cast<MemorySizePredicateMatcher>(&B)->MMOIdx &&
  1719. Size == cast<MemorySizePredicateMatcher>(&B)->Size;
  1720. }
  1721. void emitPredicateOpcodes(MatchTable &Table,
  1722. RuleMatcher &Rule) const override {
  1723. Table << MatchTable::Opcode("GIM_CheckMemorySizeEqualTo")
  1724. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1725. << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
  1726. << MatchTable::Comment("Size") << MatchTable::IntValue(Size)
  1727. << MatchTable::LineBreak;
  1728. }
  1729. };
  1730. class MemoryAddressSpacePredicateMatcher : public InstructionPredicateMatcher {
  1731. protected:
  1732. unsigned MMOIdx;
  1733. SmallVector<unsigned, 4> AddrSpaces;
  1734. public:
  1735. MemoryAddressSpacePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
  1736. ArrayRef<unsigned> AddrSpaces)
  1737. : InstructionPredicateMatcher(IPM_MemoryAddressSpace, InsnVarID),
  1738. MMOIdx(MMOIdx), AddrSpaces(AddrSpaces.begin(), AddrSpaces.end()) {}
  1739. static bool classof(const PredicateMatcher *P) {
  1740. return P->getKind() == IPM_MemoryAddressSpace;
  1741. }
  1742. bool isIdentical(const PredicateMatcher &B) const override {
  1743. if (!InstructionPredicateMatcher::isIdentical(B))
  1744. return false;
  1745. auto *Other = cast<MemoryAddressSpacePredicateMatcher>(&B);
  1746. return MMOIdx == Other->MMOIdx && AddrSpaces == Other->AddrSpaces;
  1747. }
  1748. void emitPredicateOpcodes(MatchTable &Table,
  1749. RuleMatcher &Rule) const override {
  1750. Table << MatchTable::Opcode("GIM_CheckMemoryAddressSpace")
  1751. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1752. << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
  1753. // Encode number of address spaces to expect.
  1754. << MatchTable::Comment("NumAddrSpace")
  1755. << MatchTable::IntValue(AddrSpaces.size());
  1756. for (unsigned AS : AddrSpaces)
  1757. Table << MatchTable::Comment("AddrSpace") << MatchTable::IntValue(AS);
  1758. Table << MatchTable::LineBreak;
  1759. }
  1760. };
  1761. class MemoryAlignmentPredicateMatcher : public InstructionPredicateMatcher {
  1762. protected:
  1763. unsigned MMOIdx;
  1764. int MinAlign;
  1765. public:
  1766. MemoryAlignmentPredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
  1767. int MinAlign)
  1768. : InstructionPredicateMatcher(IPM_MemoryAlignment, InsnVarID),
  1769. MMOIdx(MMOIdx), MinAlign(MinAlign) {
  1770. assert(MinAlign > 0);
  1771. }
  1772. static bool classof(const PredicateMatcher *P) {
  1773. return P->getKind() == IPM_MemoryAlignment;
  1774. }
  1775. bool isIdentical(const PredicateMatcher &B) const override {
  1776. if (!InstructionPredicateMatcher::isIdentical(B))
  1777. return false;
  1778. auto *Other = cast<MemoryAlignmentPredicateMatcher>(&B);
  1779. return MMOIdx == Other->MMOIdx && MinAlign == Other->MinAlign;
  1780. }
  1781. void emitPredicateOpcodes(MatchTable &Table,
  1782. RuleMatcher &Rule) const override {
  1783. Table << MatchTable::Opcode("GIM_CheckMemoryAlignment")
  1784. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1785. << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
  1786. << MatchTable::Comment("MinAlign") << MatchTable::IntValue(MinAlign)
  1787. << MatchTable::LineBreak;
  1788. }
  1789. };
  1790. /// Generates code to check that the size of an MMO is less-than, equal-to, or
  1791. /// greater than a given LLT.
  1792. class MemoryVsLLTSizePredicateMatcher : public InstructionPredicateMatcher {
  1793. public:
  1794. enum RelationKind {
  1795. GreaterThan,
  1796. EqualTo,
  1797. LessThan,
  1798. };
  1799. protected:
  1800. unsigned MMOIdx;
  1801. RelationKind Relation;
  1802. unsigned OpIdx;
  1803. public:
  1804. MemoryVsLLTSizePredicateMatcher(unsigned InsnVarID, unsigned MMOIdx,
  1805. enum RelationKind Relation,
  1806. unsigned OpIdx)
  1807. : InstructionPredicateMatcher(IPM_MemoryVsLLTSize, InsnVarID),
  1808. MMOIdx(MMOIdx), Relation(Relation), OpIdx(OpIdx) {}
  1809. static bool classof(const PredicateMatcher *P) {
  1810. return P->getKind() == IPM_MemoryVsLLTSize;
  1811. }
  1812. bool isIdentical(const PredicateMatcher &B) const override {
  1813. return InstructionPredicateMatcher::isIdentical(B) &&
  1814. MMOIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->MMOIdx &&
  1815. Relation == cast<MemoryVsLLTSizePredicateMatcher>(&B)->Relation &&
  1816. OpIdx == cast<MemoryVsLLTSizePredicateMatcher>(&B)->OpIdx;
  1817. }
  1818. void emitPredicateOpcodes(MatchTable &Table,
  1819. RuleMatcher &Rule) const override {
  1820. Table << MatchTable::Opcode(Relation == EqualTo
  1821. ? "GIM_CheckMemorySizeEqualToLLT"
  1822. : Relation == GreaterThan
  1823. ? "GIM_CheckMemorySizeGreaterThanLLT"
  1824. : "GIM_CheckMemorySizeLessThanLLT")
  1825. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1826. << MatchTable::Comment("MMO") << MatchTable::IntValue(MMOIdx)
  1827. << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
  1828. << MatchTable::LineBreak;
  1829. }
  1830. };
  1831. // Matcher for immAllOnesV/immAllZerosV
  1832. class VectorSplatImmPredicateMatcher : public InstructionPredicateMatcher {
  1833. public:
  1834. enum SplatKind {
  1835. AllZeros,
  1836. AllOnes
  1837. };
  1838. private:
  1839. SplatKind Kind;
  1840. public:
  1841. VectorSplatImmPredicateMatcher(unsigned InsnVarID, SplatKind K)
  1842. : InstructionPredicateMatcher(IPM_VectorSplatImm, InsnVarID), Kind(K) {}
  1843. static bool classof(const PredicateMatcher *P) {
  1844. return P->getKind() == IPM_VectorSplatImm;
  1845. }
  1846. bool isIdentical(const PredicateMatcher &B) const override {
  1847. return InstructionPredicateMatcher::isIdentical(B) &&
  1848. Kind == static_cast<const VectorSplatImmPredicateMatcher &>(B).Kind;
  1849. }
  1850. void emitPredicateOpcodes(MatchTable &Table,
  1851. RuleMatcher &Rule) const override {
  1852. if (Kind == AllOnes)
  1853. Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllOnes");
  1854. else
  1855. Table << MatchTable::Opcode("GIM_CheckIsBuildVectorAllZeros");
  1856. Table << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID);
  1857. Table << MatchTable::LineBreak;
  1858. }
  1859. };
  1860. /// Generates code to check an arbitrary C++ instruction predicate.
  1861. class GenericInstructionPredicateMatcher : public InstructionPredicateMatcher {
  1862. protected:
  1863. TreePredicateFn Predicate;
  1864. public:
  1865. GenericInstructionPredicateMatcher(unsigned InsnVarID,
  1866. TreePredicateFn Predicate)
  1867. : InstructionPredicateMatcher(IPM_GenericPredicate, InsnVarID),
  1868. Predicate(Predicate) {}
  1869. static bool classof(const InstructionPredicateMatcher *P) {
  1870. return P->getKind() == IPM_GenericPredicate;
  1871. }
  1872. bool isIdentical(const PredicateMatcher &B) const override {
  1873. return InstructionPredicateMatcher::isIdentical(B) &&
  1874. Predicate ==
  1875. static_cast<const GenericInstructionPredicateMatcher &>(B)
  1876. .Predicate;
  1877. }
  1878. void emitPredicateOpcodes(MatchTable &Table,
  1879. RuleMatcher &Rule) const override {
  1880. Table << MatchTable::Opcode("GIM_CheckCxxInsnPredicate")
  1881. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1882. << MatchTable::Comment("FnId")
  1883. << MatchTable::NamedValue(getEnumNameForPredicate(Predicate))
  1884. << MatchTable::LineBreak;
  1885. }
  1886. };
  1887. /// Generates code to check for the absence of use of the result.
  1888. // TODO? Generalize this to support checking for one use.
  1889. class NoUsePredicateMatcher : public InstructionPredicateMatcher {
  1890. public:
  1891. NoUsePredicateMatcher(unsigned InsnVarID)
  1892. : InstructionPredicateMatcher(IPM_NoUse, InsnVarID) {}
  1893. static bool classof(const PredicateMatcher *P) {
  1894. return P->getKind() == IPM_NoUse;
  1895. }
  1896. bool isIdentical(const PredicateMatcher &B) const override {
  1897. return InstructionPredicateMatcher::isIdentical(B);
  1898. }
  1899. void emitPredicateOpcodes(MatchTable &Table,
  1900. RuleMatcher &Rule) const override {
  1901. Table << MatchTable::Opcode("GIM_CheckHasNoUse")
  1902. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  1903. << MatchTable::LineBreak;
  1904. }
  1905. };
  1906. /// Generates code to check that a set of predicates and operands match for a
  1907. /// particular instruction.
  1908. ///
  1909. /// Typical predicates include:
  1910. /// * Has a specific opcode.
  1911. /// * Has an nsw/nuw flag or doesn't.
  1912. class InstructionMatcher final : public PredicateListMatcher<PredicateMatcher> {
  1913. protected:
  1914. typedef std::vector<std::unique_ptr<OperandMatcher>> OperandVec;
  1915. RuleMatcher &Rule;
  1916. /// The operands to match. All rendered operands must be present even if the
  1917. /// condition is always true.
  1918. OperandVec Operands;
  1919. bool NumOperandsCheck = true;
  1920. std::string SymbolicName;
  1921. unsigned InsnVarID;
  1922. /// PhysRegInputs - List list has an entry for each explicitly specified
  1923. /// physreg input to the pattern. The first elt is the Register node, the
  1924. /// second is the recorded slot number the input pattern match saved it in.
  1925. SmallVector<std::pair<Record *, unsigned>, 2> PhysRegInputs;
  1926. public:
  1927. InstructionMatcher(RuleMatcher &Rule, StringRef SymbolicName,
  1928. bool NumOpsCheck = true)
  1929. : Rule(Rule), NumOperandsCheck(NumOpsCheck), SymbolicName(SymbolicName) {
  1930. // We create a new instruction matcher.
  1931. // Get a new ID for that instruction.
  1932. InsnVarID = Rule.implicitlyDefineInsnVar(*this);
  1933. }
  1934. /// Construct a new instruction predicate and add it to the matcher.
  1935. template <class Kind, class... Args>
  1936. std::optional<Kind *> addPredicate(Args &&...args) {
  1937. Predicates.emplace_back(
  1938. std::make_unique<Kind>(getInsnVarID(), std::forward<Args>(args)...));
  1939. return static_cast<Kind *>(Predicates.back().get());
  1940. }
  1941. RuleMatcher &getRuleMatcher() const { return Rule; }
  1942. unsigned getInsnVarID() const { return InsnVarID; }
  1943. /// Add an operand to the matcher.
  1944. OperandMatcher &addOperand(unsigned OpIdx, const std::string &SymbolicName,
  1945. unsigned AllocatedTemporariesBaseID) {
  1946. Operands.emplace_back(new OperandMatcher(*this, OpIdx, SymbolicName,
  1947. AllocatedTemporariesBaseID));
  1948. if (!SymbolicName.empty())
  1949. Rule.defineOperand(SymbolicName, *Operands.back());
  1950. return *Operands.back();
  1951. }
  1952. OperandMatcher &getOperand(unsigned OpIdx) {
  1953. auto I = llvm::find_if(Operands,
  1954. [&OpIdx](const std::unique_ptr<OperandMatcher> &X) {
  1955. return X->getOpIdx() == OpIdx;
  1956. });
  1957. if (I != Operands.end())
  1958. return **I;
  1959. llvm_unreachable("Failed to lookup operand");
  1960. }
  1961. OperandMatcher &addPhysRegInput(Record *Reg, unsigned OpIdx,
  1962. unsigned TempOpIdx) {
  1963. assert(SymbolicName.empty());
  1964. OperandMatcher *OM = new OperandMatcher(*this, OpIdx, "", TempOpIdx);
  1965. Operands.emplace_back(OM);
  1966. Rule.definePhysRegOperand(Reg, *OM);
  1967. PhysRegInputs.emplace_back(Reg, OpIdx);
  1968. return *OM;
  1969. }
  1970. ArrayRef<std::pair<Record *, unsigned>> getPhysRegInputs() const {
  1971. return PhysRegInputs;
  1972. }
  1973. StringRef getSymbolicName() const { return SymbolicName; }
  1974. unsigned getNumOperands() const { return Operands.size(); }
  1975. OperandVec::iterator operands_begin() { return Operands.begin(); }
  1976. OperandVec::iterator operands_end() { return Operands.end(); }
  1977. iterator_range<OperandVec::iterator> operands() {
  1978. return make_range(operands_begin(), operands_end());
  1979. }
  1980. OperandVec::const_iterator operands_begin() const { return Operands.begin(); }
  1981. OperandVec::const_iterator operands_end() const { return Operands.end(); }
  1982. iterator_range<OperandVec::const_iterator> operands() const {
  1983. return make_range(operands_begin(), operands_end());
  1984. }
  1985. bool operands_empty() const { return Operands.empty(); }
  1986. void pop_front() { Operands.erase(Operands.begin()); }
  1987. void optimize();
  1988. /// Emit MatchTable opcodes that test whether the instruction named in
  1989. /// InsnVarName matches all the predicates and all the operands.
  1990. void emitPredicateOpcodes(MatchTable &Table, RuleMatcher &Rule) {
  1991. if (NumOperandsCheck)
  1992. InstructionNumOperandsMatcher(InsnVarID, getNumOperands())
  1993. .emitPredicateOpcodes(Table, Rule);
  1994. // First emit all instruction level predicates need to be verified before we
  1995. // can verify operands.
  1996. emitFilteredPredicateListOpcodes(
  1997. [](const PredicateMatcher &P) {
  1998. return !P.dependsOnOperands();
  1999. }, Table, Rule);
  2000. // Emit all operand constraints.
  2001. for (const auto &Operand : Operands)
  2002. Operand->emitPredicateOpcodes(Table, Rule);
  2003. // All of the tablegen defined predicates should now be matched. Now emit
  2004. // any custom predicates that rely on all generated checks.
  2005. emitFilteredPredicateListOpcodes(
  2006. [](const PredicateMatcher &P) {
  2007. return P.dependsOnOperands();
  2008. }, Table, Rule);
  2009. }
  2010. /// Compare the priority of this object and B.
  2011. ///
  2012. /// Returns true if this object is more important than B.
  2013. bool isHigherPriorityThan(InstructionMatcher &B) {
  2014. // Instruction matchers involving more operands have higher priority.
  2015. if (Operands.size() > B.Operands.size())
  2016. return true;
  2017. if (Operands.size() < B.Operands.size())
  2018. return false;
  2019. for (auto &&P : zip(predicates(), B.predicates())) {
  2020. auto L = static_cast<InstructionPredicateMatcher *>(std::get<0>(P).get());
  2021. auto R = static_cast<InstructionPredicateMatcher *>(std::get<1>(P).get());
  2022. if (L->isHigherPriorityThan(*R))
  2023. return true;
  2024. if (R->isHigherPriorityThan(*L))
  2025. return false;
  2026. }
  2027. for (auto Operand : zip(Operands, B.Operands)) {
  2028. if (std::get<0>(Operand)->isHigherPriorityThan(*std::get<1>(Operand)))
  2029. return true;
  2030. if (std::get<1>(Operand)->isHigherPriorityThan(*std::get<0>(Operand)))
  2031. return false;
  2032. }
  2033. return false;
  2034. };
  2035. /// Report the maximum number of temporary operands needed by the instruction
  2036. /// matcher.
  2037. unsigned countRendererFns() {
  2038. return std::accumulate(
  2039. predicates().begin(), predicates().end(), 0,
  2040. [](unsigned A,
  2041. const std::unique_ptr<PredicateMatcher> &Predicate) {
  2042. return A + Predicate->countRendererFns();
  2043. }) +
  2044. std::accumulate(
  2045. Operands.begin(), Operands.end(), 0,
  2046. [](unsigned A, const std::unique_ptr<OperandMatcher> &Operand) {
  2047. return A + Operand->countRendererFns();
  2048. });
  2049. }
  2050. InstructionOpcodeMatcher &getOpcodeMatcher() {
  2051. for (auto &P : predicates())
  2052. if (auto *OpMatcher = dyn_cast<InstructionOpcodeMatcher>(P.get()))
  2053. return *OpMatcher;
  2054. llvm_unreachable("Didn't find an opcode matcher");
  2055. }
  2056. bool isConstantInstruction() {
  2057. return getOpcodeMatcher().isConstantInstruction();
  2058. }
  2059. StringRef getOpcode() { return getOpcodeMatcher().getOpcode(); }
  2060. };
  2061. StringRef RuleMatcher::getOpcode() const {
  2062. return Matchers.front()->getOpcode();
  2063. }
  2064. unsigned RuleMatcher::getNumOperands() const {
  2065. return Matchers.front()->getNumOperands();
  2066. }
  2067. LLTCodeGen RuleMatcher::getFirstConditionAsRootType() {
  2068. InstructionMatcher &InsnMatcher = *Matchers.front();
  2069. if (!InsnMatcher.predicates_empty())
  2070. if (const auto *TM =
  2071. dyn_cast<LLTOperandMatcher>(&**InsnMatcher.predicates_begin()))
  2072. if (TM->getInsnVarID() == 0 && TM->getOpIdx() == 0)
  2073. return TM->getTy();
  2074. return {};
  2075. }
  2076. /// Generates code to check that the operand is a register defined by an
  2077. /// instruction that matches the given instruction matcher.
  2078. ///
  2079. /// For example, the pattern:
  2080. /// (set $dst, (G_MUL (G_ADD $src1, $src2), $src3))
  2081. /// would use an InstructionOperandMatcher for operand 1 of the G_MUL to match
  2082. /// the:
  2083. /// (G_ADD $src1, $src2)
  2084. /// subpattern.
  2085. class InstructionOperandMatcher : public OperandPredicateMatcher {
  2086. protected:
  2087. std::unique_ptr<InstructionMatcher> InsnMatcher;
  2088. public:
  2089. InstructionOperandMatcher(unsigned InsnVarID, unsigned OpIdx,
  2090. RuleMatcher &Rule, StringRef SymbolicName,
  2091. bool NumOpsCheck = true)
  2092. : OperandPredicateMatcher(OPM_Instruction, InsnVarID, OpIdx),
  2093. InsnMatcher(new InstructionMatcher(Rule, SymbolicName, NumOpsCheck)) {}
  2094. static bool classof(const PredicateMatcher *P) {
  2095. return P->getKind() == OPM_Instruction;
  2096. }
  2097. InstructionMatcher &getInsnMatcher() const { return *InsnMatcher; }
  2098. void emitCaptureOpcodes(MatchTable &Table, RuleMatcher &Rule) const {
  2099. const unsigned NewInsnVarID = InsnMatcher->getInsnVarID();
  2100. Table << MatchTable::Opcode("GIM_RecordInsn")
  2101. << MatchTable::Comment("DefineMI")
  2102. << MatchTable::IntValue(NewInsnVarID) << MatchTable::Comment("MI")
  2103. << MatchTable::IntValue(getInsnVarID())
  2104. << MatchTable::Comment("OpIdx") << MatchTable::IntValue(getOpIdx())
  2105. << MatchTable::Comment("MIs[" + llvm::to_string(NewInsnVarID) + "]")
  2106. << MatchTable::LineBreak;
  2107. }
  2108. void emitPredicateOpcodes(MatchTable &Table,
  2109. RuleMatcher &Rule) const override {
  2110. emitCaptureOpcodes(Table, Rule);
  2111. InsnMatcher->emitPredicateOpcodes(Table, Rule);
  2112. }
  2113. bool isHigherPriorityThan(const OperandPredicateMatcher &B) const override {
  2114. if (OperandPredicateMatcher::isHigherPriorityThan(B))
  2115. return true;
  2116. if (B.OperandPredicateMatcher::isHigherPriorityThan(*this))
  2117. return false;
  2118. if (const InstructionOperandMatcher *BP =
  2119. dyn_cast<InstructionOperandMatcher>(&B))
  2120. if (InsnMatcher->isHigherPriorityThan(*BP->InsnMatcher))
  2121. return true;
  2122. return false;
  2123. }
  2124. /// Report the maximum number of temporary operands needed by the predicate
  2125. /// matcher.
  2126. unsigned countRendererFns() const override {
  2127. return InsnMatcher->countRendererFns();
  2128. }
  2129. };
  2130. void InstructionMatcher::optimize() {
  2131. SmallVector<std::unique_ptr<PredicateMatcher>, 8> Stash;
  2132. const auto &OpcMatcher = getOpcodeMatcher();
  2133. Stash.push_back(predicates_pop_front());
  2134. if (Stash.back().get() == &OpcMatcher) {
  2135. if (NumOperandsCheck && OpcMatcher.isVariadicNumOperands())
  2136. Stash.emplace_back(
  2137. new InstructionNumOperandsMatcher(InsnVarID, getNumOperands()));
  2138. NumOperandsCheck = false;
  2139. for (auto &OM : Operands)
  2140. for (auto &OP : OM->predicates())
  2141. if (isa<IntrinsicIDOperandMatcher>(OP)) {
  2142. Stash.push_back(std::move(OP));
  2143. OM->eraseNullPredicates();
  2144. break;
  2145. }
  2146. }
  2147. if (InsnVarID > 0) {
  2148. assert(!Operands.empty() && "Nested instruction is expected to def a vreg");
  2149. for (auto &OP : Operands[0]->predicates())
  2150. OP.reset();
  2151. Operands[0]->eraseNullPredicates();
  2152. }
  2153. for (auto &OM : Operands) {
  2154. for (auto &OP : OM->predicates())
  2155. if (isa<LLTOperandMatcher>(OP))
  2156. Stash.push_back(std::move(OP));
  2157. OM->eraseNullPredicates();
  2158. }
  2159. while (!Stash.empty())
  2160. prependPredicate(Stash.pop_back_val());
  2161. }
  2162. //===- Actions ------------------------------------------------------------===//
  2163. class OperandRenderer {
  2164. public:
  2165. enum RendererKind {
  2166. OR_Copy,
  2167. OR_CopyOrAddZeroReg,
  2168. OR_CopySubReg,
  2169. OR_CopyPhysReg,
  2170. OR_CopyConstantAsImm,
  2171. OR_CopyFConstantAsFPImm,
  2172. OR_Imm,
  2173. OR_SubRegIndex,
  2174. OR_Register,
  2175. OR_TempRegister,
  2176. OR_ComplexPattern,
  2177. OR_Custom,
  2178. OR_CustomOperand
  2179. };
  2180. protected:
  2181. RendererKind Kind;
  2182. public:
  2183. OperandRenderer(RendererKind Kind) : Kind(Kind) {}
  2184. virtual ~OperandRenderer() {}
  2185. RendererKind getKind() const { return Kind; }
  2186. virtual void emitRenderOpcodes(MatchTable &Table,
  2187. RuleMatcher &Rule) const = 0;
  2188. };
  2189. /// A CopyRenderer emits code to copy a single operand from an existing
  2190. /// instruction to the one being built.
  2191. class CopyRenderer : public OperandRenderer {
  2192. protected:
  2193. unsigned NewInsnID;
  2194. /// The name of the operand.
  2195. const StringRef SymbolicName;
  2196. public:
  2197. CopyRenderer(unsigned NewInsnID, StringRef SymbolicName)
  2198. : OperandRenderer(OR_Copy), NewInsnID(NewInsnID),
  2199. SymbolicName(SymbolicName) {
  2200. assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
  2201. }
  2202. static bool classof(const OperandRenderer *R) {
  2203. return R->getKind() == OR_Copy;
  2204. }
  2205. StringRef getSymbolicName() const { return SymbolicName; }
  2206. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2207. const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
  2208. unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
  2209. Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
  2210. << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
  2211. << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
  2212. << MatchTable::IntValue(Operand.getOpIdx())
  2213. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2214. }
  2215. };
  2216. /// A CopyRenderer emits code to copy a virtual register to a specific physical
  2217. /// register.
  2218. class CopyPhysRegRenderer : public OperandRenderer {
  2219. protected:
  2220. unsigned NewInsnID;
  2221. Record *PhysReg;
  2222. public:
  2223. CopyPhysRegRenderer(unsigned NewInsnID, Record *Reg)
  2224. : OperandRenderer(OR_CopyPhysReg), NewInsnID(NewInsnID),
  2225. PhysReg(Reg) {
  2226. assert(PhysReg);
  2227. }
  2228. static bool classof(const OperandRenderer *R) {
  2229. return R->getKind() == OR_CopyPhysReg;
  2230. }
  2231. Record *getPhysReg() const { return PhysReg; }
  2232. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2233. const OperandMatcher &Operand = Rule.getPhysRegOperandMatcher(PhysReg);
  2234. unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
  2235. Table << MatchTable::Opcode("GIR_Copy") << MatchTable::Comment("NewInsnID")
  2236. << MatchTable::IntValue(NewInsnID) << MatchTable::Comment("OldInsnID")
  2237. << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
  2238. << MatchTable::IntValue(Operand.getOpIdx())
  2239. << MatchTable::Comment(PhysReg->getName())
  2240. << MatchTable::LineBreak;
  2241. }
  2242. };
  2243. /// A CopyOrAddZeroRegRenderer emits code to copy a single operand from an
  2244. /// existing instruction to the one being built. If the operand turns out to be
  2245. /// a 'G_CONSTANT 0' then it replaces the operand with a zero register.
  2246. class CopyOrAddZeroRegRenderer : public OperandRenderer {
  2247. protected:
  2248. unsigned NewInsnID;
  2249. /// The name of the operand.
  2250. const StringRef SymbolicName;
  2251. const Record *ZeroRegisterDef;
  2252. public:
  2253. CopyOrAddZeroRegRenderer(unsigned NewInsnID,
  2254. StringRef SymbolicName, Record *ZeroRegisterDef)
  2255. : OperandRenderer(OR_CopyOrAddZeroReg), NewInsnID(NewInsnID),
  2256. SymbolicName(SymbolicName), ZeroRegisterDef(ZeroRegisterDef) {
  2257. assert(!SymbolicName.empty() && "Cannot copy from an unspecified source");
  2258. }
  2259. static bool classof(const OperandRenderer *R) {
  2260. return R->getKind() == OR_CopyOrAddZeroReg;
  2261. }
  2262. StringRef getSymbolicName() const { return SymbolicName; }
  2263. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2264. const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
  2265. unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
  2266. Table << MatchTable::Opcode("GIR_CopyOrAddZeroReg")
  2267. << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
  2268. << MatchTable::Comment("OldInsnID")
  2269. << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
  2270. << MatchTable::IntValue(Operand.getOpIdx())
  2271. << MatchTable::NamedValue(
  2272. (ZeroRegisterDef->getValue("Namespace")
  2273. ? ZeroRegisterDef->getValueAsString("Namespace")
  2274. : ""),
  2275. ZeroRegisterDef->getName())
  2276. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2277. }
  2278. };
  2279. /// A CopyConstantAsImmRenderer emits code to render a G_CONSTANT instruction to
  2280. /// an extended immediate operand.
  2281. class CopyConstantAsImmRenderer : public OperandRenderer {
  2282. protected:
  2283. unsigned NewInsnID;
  2284. /// The name of the operand.
  2285. const std::string SymbolicName;
  2286. bool Signed;
  2287. public:
  2288. CopyConstantAsImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
  2289. : OperandRenderer(OR_CopyConstantAsImm), NewInsnID(NewInsnID),
  2290. SymbolicName(SymbolicName), Signed(true) {}
  2291. static bool classof(const OperandRenderer *R) {
  2292. return R->getKind() == OR_CopyConstantAsImm;
  2293. }
  2294. StringRef getSymbolicName() const { return SymbolicName; }
  2295. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2296. InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
  2297. unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
  2298. Table << MatchTable::Opcode(Signed ? "GIR_CopyConstantAsSImm"
  2299. : "GIR_CopyConstantAsUImm")
  2300. << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
  2301. << MatchTable::Comment("OldInsnID")
  2302. << MatchTable::IntValue(OldInsnVarID)
  2303. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2304. }
  2305. };
  2306. /// A CopyFConstantAsFPImmRenderer emits code to render a G_FCONSTANT
  2307. /// instruction to an extended immediate operand.
  2308. class CopyFConstantAsFPImmRenderer : public OperandRenderer {
  2309. protected:
  2310. unsigned NewInsnID;
  2311. /// The name of the operand.
  2312. const std::string SymbolicName;
  2313. public:
  2314. CopyFConstantAsFPImmRenderer(unsigned NewInsnID, StringRef SymbolicName)
  2315. : OperandRenderer(OR_CopyFConstantAsFPImm), NewInsnID(NewInsnID),
  2316. SymbolicName(SymbolicName) {}
  2317. static bool classof(const OperandRenderer *R) {
  2318. return R->getKind() == OR_CopyFConstantAsFPImm;
  2319. }
  2320. StringRef getSymbolicName() const { return SymbolicName; }
  2321. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2322. InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
  2323. unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
  2324. Table << MatchTable::Opcode("GIR_CopyFConstantAsFPImm")
  2325. << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
  2326. << MatchTable::Comment("OldInsnID")
  2327. << MatchTable::IntValue(OldInsnVarID)
  2328. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2329. }
  2330. };
  2331. /// A CopySubRegRenderer emits code to copy a single register operand from an
  2332. /// existing instruction to the one being built and indicate that only a
  2333. /// subregister should be copied.
  2334. class CopySubRegRenderer : public OperandRenderer {
  2335. protected:
  2336. unsigned NewInsnID;
  2337. /// The name of the operand.
  2338. const StringRef SymbolicName;
  2339. /// The subregister to extract.
  2340. const CodeGenSubRegIndex *SubReg;
  2341. public:
  2342. CopySubRegRenderer(unsigned NewInsnID, StringRef SymbolicName,
  2343. const CodeGenSubRegIndex *SubReg)
  2344. : OperandRenderer(OR_CopySubReg), NewInsnID(NewInsnID),
  2345. SymbolicName(SymbolicName), SubReg(SubReg) {}
  2346. static bool classof(const OperandRenderer *R) {
  2347. return R->getKind() == OR_CopySubReg;
  2348. }
  2349. StringRef getSymbolicName() const { return SymbolicName; }
  2350. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2351. const OperandMatcher &Operand = Rule.getOperandMatcher(SymbolicName);
  2352. unsigned OldInsnVarID = Rule.getInsnVarID(Operand.getInstructionMatcher());
  2353. Table << MatchTable::Opcode("GIR_CopySubReg")
  2354. << MatchTable::Comment("NewInsnID") << MatchTable::IntValue(NewInsnID)
  2355. << MatchTable::Comment("OldInsnID")
  2356. << MatchTable::IntValue(OldInsnVarID) << MatchTable::Comment("OpIdx")
  2357. << MatchTable::IntValue(Operand.getOpIdx())
  2358. << MatchTable::Comment("SubRegIdx")
  2359. << MatchTable::IntValue(SubReg->EnumValue)
  2360. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2361. }
  2362. };
  2363. /// Adds a specific physical register to the instruction being built.
  2364. /// This is typically useful for WZR/XZR on AArch64.
  2365. class AddRegisterRenderer : public OperandRenderer {
  2366. protected:
  2367. unsigned InsnID;
  2368. const Record *RegisterDef;
  2369. bool IsDef;
  2370. const CodeGenTarget &Target;
  2371. public:
  2372. AddRegisterRenderer(unsigned InsnID, const CodeGenTarget &Target,
  2373. const Record *RegisterDef, bool IsDef = false)
  2374. : OperandRenderer(OR_Register), InsnID(InsnID), RegisterDef(RegisterDef),
  2375. IsDef(IsDef), Target(Target) {}
  2376. static bool classof(const OperandRenderer *R) {
  2377. return R->getKind() == OR_Register;
  2378. }
  2379. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2380. Table << MatchTable::Opcode("GIR_AddRegister")
  2381. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID);
  2382. if (RegisterDef->getName() != "zero_reg") {
  2383. Table << MatchTable::NamedValue(
  2384. (RegisterDef->getValue("Namespace")
  2385. ? RegisterDef->getValueAsString("Namespace")
  2386. : ""),
  2387. RegisterDef->getName());
  2388. } else {
  2389. Table << MatchTable::NamedValue(Target.getRegNamespace(), "NoRegister");
  2390. }
  2391. Table << MatchTable::Comment("AddRegisterRegFlags");
  2392. // TODO: This is encoded as a 64-bit element, but only 16 or 32-bits are
  2393. // really needed for a physical register reference. We can pack the
  2394. // register and flags in a single field.
  2395. if (IsDef)
  2396. Table << MatchTable::NamedValue("RegState::Define");
  2397. else
  2398. Table << MatchTable::IntValue(0);
  2399. Table << MatchTable::LineBreak;
  2400. }
  2401. };
  2402. /// Adds a specific temporary virtual register to the instruction being built.
  2403. /// This is used to chain instructions together when emitting multiple
  2404. /// instructions.
  2405. class TempRegRenderer : public OperandRenderer {
  2406. protected:
  2407. unsigned InsnID;
  2408. unsigned TempRegID;
  2409. const CodeGenSubRegIndex *SubRegIdx;
  2410. bool IsDef;
  2411. bool IsDead;
  2412. public:
  2413. TempRegRenderer(unsigned InsnID, unsigned TempRegID, bool IsDef = false,
  2414. const CodeGenSubRegIndex *SubReg = nullptr,
  2415. bool IsDead = false)
  2416. : OperandRenderer(OR_Register), InsnID(InsnID), TempRegID(TempRegID),
  2417. SubRegIdx(SubReg), IsDef(IsDef), IsDead(IsDead) {}
  2418. static bool classof(const OperandRenderer *R) {
  2419. return R->getKind() == OR_TempRegister;
  2420. }
  2421. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2422. if (SubRegIdx) {
  2423. assert(!IsDef);
  2424. Table << MatchTable::Opcode("GIR_AddTempSubRegister");
  2425. } else
  2426. Table << MatchTable::Opcode("GIR_AddTempRegister");
  2427. Table << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2428. << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
  2429. << MatchTable::Comment("TempRegFlags");
  2430. if (IsDef) {
  2431. SmallString<32> RegFlags;
  2432. RegFlags += "RegState::Define";
  2433. if (IsDead)
  2434. RegFlags += "|RegState::Dead";
  2435. Table << MatchTable::NamedValue(RegFlags);
  2436. } else
  2437. Table << MatchTable::IntValue(0);
  2438. if (SubRegIdx)
  2439. Table << MatchTable::NamedValue(SubRegIdx->getQualifiedName());
  2440. Table << MatchTable::LineBreak;
  2441. }
  2442. };
  2443. /// Adds a specific immediate to the instruction being built.
  2444. class ImmRenderer : public OperandRenderer {
  2445. protected:
  2446. unsigned InsnID;
  2447. int64_t Imm;
  2448. public:
  2449. ImmRenderer(unsigned InsnID, int64_t Imm)
  2450. : OperandRenderer(OR_Imm), InsnID(InsnID), Imm(Imm) {}
  2451. static bool classof(const OperandRenderer *R) {
  2452. return R->getKind() == OR_Imm;
  2453. }
  2454. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2455. Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
  2456. << MatchTable::IntValue(InsnID) << MatchTable::Comment("Imm")
  2457. << MatchTable::IntValue(Imm) << MatchTable::LineBreak;
  2458. }
  2459. };
  2460. /// Adds an enum value for a subreg index to the instruction being built.
  2461. class SubRegIndexRenderer : public OperandRenderer {
  2462. protected:
  2463. unsigned InsnID;
  2464. const CodeGenSubRegIndex *SubRegIdx;
  2465. public:
  2466. SubRegIndexRenderer(unsigned InsnID, const CodeGenSubRegIndex *SRI)
  2467. : OperandRenderer(OR_SubRegIndex), InsnID(InsnID), SubRegIdx(SRI) {}
  2468. static bool classof(const OperandRenderer *R) {
  2469. return R->getKind() == OR_SubRegIndex;
  2470. }
  2471. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2472. Table << MatchTable::Opcode("GIR_AddImm") << MatchTable::Comment("InsnID")
  2473. << MatchTable::IntValue(InsnID) << MatchTable::Comment("SubRegIndex")
  2474. << MatchTable::IntValue(SubRegIdx->EnumValue)
  2475. << MatchTable::LineBreak;
  2476. }
  2477. };
  2478. /// Adds operands by calling a renderer function supplied by the ComplexPattern
  2479. /// matcher function.
  2480. class RenderComplexPatternOperand : public OperandRenderer {
  2481. private:
  2482. unsigned InsnID;
  2483. const Record &TheDef;
  2484. /// The name of the operand.
  2485. const StringRef SymbolicName;
  2486. /// The renderer number. This must be unique within a rule since it's used to
  2487. /// identify a temporary variable to hold the renderer function.
  2488. unsigned RendererID;
  2489. /// When provided, this is the suboperand of the ComplexPattern operand to
  2490. /// render. Otherwise all the suboperands will be rendered.
  2491. std::optional<unsigned> SubOperand;
  2492. unsigned getNumOperands() const {
  2493. return TheDef.getValueAsDag("Operands")->getNumArgs();
  2494. }
  2495. public:
  2496. RenderComplexPatternOperand(unsigned InsnID, const Record &TheDef,
  2497. StringRef SymbolicName, unsigned RendererID,
  2498. std::optional<unsigned> SubOperand = std::nullopt)
  2499. : OperandRenderer(OR_ComplexPattern), InsnID(InsnID), TheDef(TheDef),
  2500. SymbolicName(SymbolicName), RendererID(RendererID),
  2501. SubOperand(SubOperand) {}
  2502. static bool classof(const OperandRenderer *R) {
  2503. return R->getKind() == OR_ComplexPattern;
  2504. }
  2505. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2506. Table << MatchTable::Opcode(SubOperand ? "GIR_ComplexSubOperandRenderer"
  2507. : "GIR_ComplexRenderer")
  2508. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2509. << MatchTable::Comment("RendererID")
  2510. << MatchTable::IntValue(RendererID);
  2511. if (SubOperand)
  2512. Table << MatchTable::Comment("SubOperand")
  2513. << MatchTable::IntValue(*SubOperand);
  2514. Table << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2515. }
  2516. };
  2517. class CustomRenderer : public OperandRenderer {
  2518. protected:
  2519. unsigned InsnID;
  2520. const Record &Renderer;
  2521. /// The name of the operand.
  2522. const std::string SymbolicName;
  2523. public:
  2524. CustomRenderer(unsigned InsnID, const Record &Renderer,
  2525. StringRef SymbolicName)
  2526. : OperandRenderer(OR_Custom), InsnID(InsnID), Renderer(Renderer),
  2527. SymbolicName(SymbolicName) {}
  2528. static bool classof(const OperandRenderer *R) {
  2529. return R->getKind() == OR_Custom;
  2530. }
  2531. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2532. InstructionMatcher &InsnMatcher = Rule.getInstructionMatcher(SymbolicName);
  2533. unsigned OldInsnVarID = Rule.getInsnVarID(InsnMatcher);
  2534. Table << MatchTable::Opcode("GIR_CustomRenderer")
  2535. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2536. << MatchTable::Comment("OldInsnID")
  2537. << MatchTable::IntValue(OldInsnVarID)
  2538. << MatchTable::Comment("Renderer")
  2539. << MatchTable::NamedValue(
  2540. "GICR_" + Renderer.getValueAsString("RendererFn").str())
  2541. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2542. }
  2543. };
  2544. class CustomOperandRenderer : public OperandRenderer {
  2545. protected:
  2546. unsigned InsnID;
  2547. const Record &Renderer;
  2548. /// The name of the operand.
  2549. const std::string SymbolicName;
  2550. public:
  2551. CustomOperandRenderer(unsigned InsnID, const Record &Renderer,
  2552. StringRef SymbolicName)
  2553. : OperandRenderer(OR_CustomOperand), InsnID(InsnID), Renderer(Renderer),
  2554. SymbolicName(SymbolicName) {}
  2555. static bool classof(const OperandRenderer *R) {
  2556. return R->getKind() == OR_CustomOperand;
  2557. }
  2558. void emitRenderOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2559. const OperandMatcher &OpdMatcher = Rule.getOperandMatcher(SymbolicName);
  2560. Table << MatchTable::Opcode("GIR_CustomOperandRenderer")
  2561. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2562. << MatchTable::Comment("OldInsnID")
  2563. << MatchTable::IntValue(OpdMatcher.getInsnVarID())
  2564. << MatchTable::Comment("OpIdx")
  2565. << MatchTable::IntValue(OpdMatcher.getOpIdx())
  2566. << MatchTable::Comment("OperandRenderer")
  2567. << MatchTable::NamedValue(
  2568. "GICR_" + Renderer.getValueAsString("RendererFn").str())
  2569. << MatchTable::Comment(SymbolicName) << MatchTable::LineBreak;
  2570. }
  2571. };
  2572. /// An action taken when all Matcher predicates succeeded for a parent rule.
  2573. ///
  2574. /// Typical actions include:
  2575. /// * Changing the opcode of an instruction.
  2576. /// * Adding an operand to an instruction.
  2577. class MatchAction {
  2578. public:
  2579. virtual ~MatchAction() {}
  2580. /// Emit the MatchTable opcodes to implement the action.
  2581. virtual void emitActionOpcodes(MatchTable &Table,
  2582. RuleMatcher &Rule) const = 0;
  2583. };
  2584. /// Generates a comment describing the matched rule being acted upon.
  2585. class DebugCommentAction : public MatchAction {
  2586. private:
  2587. std::string S;
  2588. public:
  2589. DebugCommentAction(StringRef S) : S(std::string(S)) {}
  2590. void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2591. Table << MatchTable::Comment(S) << MatchTable::LineBreak;
  2592. }
  2593. };
  2594. /// Generates code to build an instruction or mutate an existing instruction
  2595. /// into the desired instruction when this is possible.
  2596. class BuildMIAction : public MatchAction {
  2597. private:
  2598. unsigned InsnID;
  2599. const CodeGenInstruction *I;
  2600. InstructionMatcher *Matched;
  2601. std::vector<std::unique_ptr<OperandRenderer>> OperandRenderers;
  2602. /// True if the instruction can be built solely by mutating the opcode.
  2603. bool canMutate(RuleMatcher &Rule, const InstructionMatcher *Insn) const {
  2604. if (!Insn)
  2605. return false;
  2606. if (OperandRenderers.size() != Insn->getNumOperands())
  2607. return false;
  2608. for (const auto &Renderer : enumerate(OperandRenderers)) {
  2609. if (const auto *Copy = dyn_cast<CopyRenderer>(&*Renderer.value())) {
  2610. const OperandMatcher &OM = Rule.getOperandMatcher(Copy->getSymbolicName());
  2611. if (Insn != &OM.getInstructionMatcher() ||
  2612. OM.getOpIdx() != Renderer.index())
  2613. return false;
  2614. } else
  2615. return false;
  2616. }
  2617. return true;
  2618. }
  2619. public:
  2620. BuildMIAction(unsigned InsnID, const CodeGenInstruction *I)
  2621. : InsnID(InsnID), I(I), Matched(nullptr) {}
  2622. unsigned getInsnID() const { return InsnID; }
  2623. const CodeGenInstruction *getCGI() const { return I; }
  2624. void chooseInsnToMutate(RuleMatcher &Rule) {
  2625. for (auto *MutateCandidate : Rule.mutatable_insns()) {
  2626. if (canMutate(Rule, MutateCandidate)) {
  2627. // Take the first one we're offered that we're able to mutate.
  2628. Rule.reserveInsnMatcherForMutation(MutateCandidate);
  2629. Matched = MutateCandidate;
  2630. return;
  2631. }
  2632. }
  2633. }
  2634. template <class Kind, class... Args>
  2635. Kind &addRenderer(Args&&... args) {
  2636. OperandRenderers.emplace_back(
  2637. std::make_unique<Kind>(InsnID, std::forward<Args>(args)...));
  2638. return *static_cast<Kind *>(OperandRenderers.back().get());
  2639. }
  2640. void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2641. if (Matched) {
  2642. assert(canMutate(Rule, Matched) &&
  2643. "Arranged to mutate an insn that isn't mutatable");
  2644. unsigned RecycleInsnID = Rule.getInsnVarID(*Matched);
  2645. Table << MatchTable::Opcode("GIR_MutateOpcode")
  2646. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2647. << MatchTable::Comment("RecycleInsnID")
  2648. << MatchTable::IntValue(RecycleInsnID)
  2649. << MatchTable::Comment("Opcode")
  2650. << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
  2651. << MatchTable::LineBreak;
  2652. if (!I->ImplicitDefs.empty() || !I->ImplicitUses.empty()) {
  2653. for (auto *Def : I->ImplicitDefs) {
  2654. auto Namespace = Def->getValue("Namespace")
  2655. ? Def->getValueAsString("Namespace")
  2656. : "";
  2657. Table << MatchTable::Opcode("GIR_AddImplicitDef")
  2658. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2659. << MatchTable::NamedValue(Namespace, Def->getName())
  2660. << MatchTable::LineBreak;
  2661. }
  2662. for (auto *Use : I->ImplicitUses) {
  2663. auto Namespace = Use->getValue("Namespace")
  2664. ? Use->getValueAsString("Namespace")
  2665. : "";
  2666. Table << MatchTable::Opcode("GIR_AddImplicitUse")
  2667. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2668. << MatchTable::NamedValue(Namespace, Use->getName())
  2669. << MatchTable::LineBreak;
  2670. }
  2671. }
  2672. return;
  2673. }
  2674. // TODO: Simple permutation looks like it could be almost as common as
  2675. // mutation due to commutative operations.
  2676. Table << MatchTable::Opcode("GIR_BuildMI") << MatchTable::Comment("InsnID")
  2677. << MatchTable::IntValue(InsnID) << MatchTable::Comment("Opcode")
  2678. << MatchTable::NamedValue(I->Namespace, I->TheDef->getName())
  2679. << MatchTable::LineBreak;
  2680. for (const auto &Renderer : OperandRenderers)
  2681. Renderer->emitRenderOpcodes(Table, Rule);
  2682. if (I->mayLoad || I->mayStore) {
  2683. Table << MatchTable::Opcode("GIR_MergeMemOperands")
  2684. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2685. << MatchTable::Comment("MergeInsnID's");
  2686. // Emit the ID's for all the instructions that are matched by this rule.
  2687. // TODO: Limit this to matched instructions that mayLoad/mayStore or have
  2688. // some other means of having a memoperand. Also limit this to
  2689. // emitted instructions that expect to have a memoperand too. For
  2690. // example, (G_SEXT (G_LOAD x)) that results in separate load and
  2691. // sign-extend instructions shouldn't put the memoperand on the
  2692. // sign-extend since it has no effect there.
  2693. std::vector<unsigned> MergeInsnIDs;
  2694. for (const auto &IDMatcherPair : Rule.defined_insn_vars())
  2695. MergeInsnIDs.push_back(IDMatcherPair.second);
  2696. llvm::sort(MergeInsnIDs);
  2697. for (const auto &MergeInsnID : MergeInsnIDs)
  2698. Table << MatchTable::IntValue(MergeInsnID);
  2699. Table << MatchTable::NamedValue("GIU_MergeMemOperands_EndOfList")
  2700. << MatchTable::LineBreak;
  2701. }
  2702. // FIXME: This is a hack but it's sufficient for ISel. We'll need to do
  2703. // better for combines. Particularly when there are multiple match
  2704. // roots.
  2705. if (InsnID == 0)
  2706. Table << MatchTable::Opcode("GIR_EraseFromParent")
  2707. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2708. << MatchTable::LineBreak;
  2709. }
  2710. };
  2711. /// Generates code to constrain the operands of an output instruction to the
  2712. /// register classes specified by the definition of that instruction.
  2713. class ConstrainOperandsToDefinitionAction : public MatchAction {
  2714. unsigned InsnID;
  2715. public:
  2716. ConstrainOperandsToDefinitionAction(unsigned InsnID) : InsnID(InsnID) {}
  2717. void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2718. Table << MatchTable::Opcode("GIR_ConstrainSelectedInstOperands")
  2719. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2720. << MatchTable::LineBreak;
  2721. }
  2722. };
  2723. /// Generates code to constrain the specified operand of an output instruction
  2724. /// to the specified register class.
  2725. class ConstrainOperandToRegClassAction : public MatchAction {
  2726. unsigned InsnID;
  2727. unsigned OpIdx;
  2728. const CodeGenRegisterClass &RC;
  2729. public:
  2730. ConstrainOperandToRegClassAction(unsigned InsnID, unsigned OpIdx,
  2731. const CodeGenRegisterClass &RC)
  2732. : InsnID(InsnID), OpIdx(OpIdx), RC(RC) {}
  2733. void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2734. Table << MatchTable::Opcode("GIR_ConstrainOperandRC")
  2735. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2736. << MatchTable::Comment("Op") << MatchTable::IntValue(OpIdx)
  2737. << MatchTable::NamedValue(RC.getQualifiedName() + "RegClassID")
  2738. << MatchTable::LineBreak;
  2739. }
  2740. };
  2741. /// Generates code to create a temporary register which can be used to chain
  2742. /// instructions together.
  2743. class MakeTempRegisterAction : public MatchAction {
  2744. private:
  2745. LLTCodeGen Ty;
  2746. unsigned TempRegID;
  2747. public:
  2748. MakeTempRegisterAction(const LLTCodeGen &Ty, unsigned TempRegID)
  2749. : Ty(Ty), TempRegID(TempRegID) {
  2750. KnownTypes.insert(Ty);
  2751. }
  2752. void emitActionOpcodes(MatchTable &Table, RuleMatcher &Rule) const override {
  2753. Table << MatchTable::Opcode("GIR_MakeTempReg")
  2754. << MatchTable::Comment("TempRegID") << MatchTable::IntValue(TempRegID)
  2755. << MatchTable::Comment("TypeID")
  2756. << MatchTable::NamedValue(Ty.getCxxEnumValue())
  2757. << MatchTable::LineBreak;
  2758. }
  2759. };
  2760. InstructionMatcher &RuleMatcher::addInstructionMatcher(StringRef SymbolicName) {
  2761. Matchers.emplace_back(new InstructionMatcher(*this, SymbolicName));
  2762. MutatableInsns.insert(Matchers.back().get());
  2763. return *Matchers.back();
  2764. }
  2765. void RuleMatcher::addRequiredFeature(Record *Feature) {
  2766. RequiredFeatures.push_back(Feature);
  2767. }
  2768. const std::vector<Record *> &RuleMatcher::getRequiredFeatures() const {
  2769. return RequiredFeatures;
  2770. }
  2771. // Emplaces an action of the specified Kind at the end of the action list.
  2772. //
  2773. // Returns a reference to the newly created action.
  2774. //
  2775. // Like std::vector::emplace_back(), may invalidate all iterators if the new
  2776. // size exceeds the capacity. Otherwise, only invalidates the past-the-end
  2777. // iterator.
  2778. template <class Kind, class... Args>
  2779. Kind &RuleMatcher::addAction(Args &&... args) {
  2780. Actions.emplace_back(std::make_unique<Kind>(std::forward<Args>(args)...));
  2781. return *static_cast<Kind *>(Actions.back().get());
  2782. }
  2783. // Emplaces an action of the specified Kind before the given insertion point.
  2784. //
  2785. // Returns an iterator pointing at the newly created instruction.
  2786. //
  2787. // Like std::vector::insert(), may invalidate all iterators if the new size
  2788. // exceeds the capacity. Otherwise, only invalidates the iterators from the
  2789. // insertion point onwards.
  2790. template <class Kind, class... Args>
  2791. action_iterator RuleMatcher::insertAction(action_iterator InsertPt,
  2792. Args &&... args) {
  2793. return Actions.emplace(InsertPt,
  2794. std::make_unique<Kind>(std::forward<Args>(args)...));
  2795. }
  2796. unsigned RuleMatcher::implicitlyDefineInsnVar(InstructionMatcher &Matcher) {
  2797. unsigned NewInsnVarID = NextInsnVarID++;
  2798. InsnVariableIDs[&Matcher] = NewInsnVarID;
  2799. return NewInsnVarID;
  2800. }
  2801. unsigned RuleMatcher::getInsnVarID(InstructionMatcher &InsnMatcher) const {
  2802. const auto &I = InsnVariableIDs.find(&InsnMatcher);
  2803. if (I != InsnVariableIDs.end())
  2804. return I->second;
  2805. llvm_unreachable("Matched Insn was not captured in a local variable");
  2806. }
  2807. void RuleMatcher::defineOperand(StringRef SymbolicName, OperandMatcher &OM) {
  2808. if (DefinedOperands.find(SymbolicName) == DefinedOperands.end()) {
  2809. DefinedOperands[SymbolicName] = &OM;
  2810. return;
  2811. }
  2812. // If the operand is already defined, then we must ensure both references in
  2813. // the matcher have the exact same node.
  2814. OM.addPredicate<SameOperandMatcher>(
  2815. OM.getSymbolicName(), getOperandMatcher(OM.getSymbolicName()).getOpIdx());
  2816. }
  2817. void RuleMatcher::definePhysRegOperand(Record *Reg, OperandMatcher &OM) {
  2818. if (PhysRegOperands.find(Reg) == PhysRegOperands.end()) {
  2819. PhysRegOperands[Reg] = &OM;
  2820. return;
  2821. }
  2822. }
  2823. InstructionMatcher &
  2824. RuleMatcher::getInstructionMatcher(StringRef SymbolicName) const {
  2825. for (const auto &I : InsnVariableIDs)
  2826. if (I.first->getSymbolicName() == SymbolicName)
  2827. return *I.first;
  2828. llvm_unreachable(
  2829. ("Failed to lookup instruction " + SymbolicName).str().c_str());
  2830. }
  2831. const OperandMatcher &
  2832. RuleMatcher::getPhysRegOperandMatcher(Record *Reg) const {
  2833. const auto &I = PhysRegOperands.find(Reg);
  2834. if (I == PhysRegOperands.end()) {
  2835. PrintFatalError(SrcLoc, "Register " + Reg->getName() +
  2836. " was not declared in matcher");
  2837. }
  2838. return *I->second;
  2839. }
  2840. const OperandMatcher &
  2841. RuleMatcher::getOperandMatcher(StringRef Name) const {
  2842. const auto &I = DefinedOperands.find(Name);
  2843. if (I == DefinedOperands.end())
  2844. PrintFatalError(SrcLoc, "Operand " + Name + " was not declared in matcher");
  2845. return *I->second;
  2846. }
  2847. void RuleMatcher::emit(MatchTable &Table) {
  2848. if (Matchers.empty())
  2849. llvm_unreachable("Unexpected empty matcher!");
  2850. // The representation supports rules that require multiple roots such as:
  2851. // %ptr(p0) = ...
  2852. // %elt0(s32) = G_LOAD %ptr
  2853. // %1(p0) = G_ADD %ptr, 4
  2854. // %elt1(s32) = G_LOAD p0 %1
  2855. // which could be usefully folded into:
  2856. // %ptr(p0) = ...
  2857. // %elt0(s32), %elt1(s32) = TGT_LOAD_PAIR %ptr
  2858. // on some targets but we don't need to make use of that yet.
  2859. assert(Matchers.size() == 1 && "Cannot handle multi-root matchers yet");
  2860. unsigned LabelID = Table.allocateLabelID();
  2861. Table << MatchTable::Opcode("GIM_Try", +1)
  2862. << MatchTable::Comment("On fail goto")
  2863. << MatchTable::JumpTarget(LabelID)
  2864. << MatchTable::Comment(("Rule ID " + Twine(RuleID) + " //").str())
  2865. << MatchTable::LineBreak;
  2866. if (!RequiredFeatures.empty()) {
  2867. Table << MatchTable::Opcode("GIM_CheckFeatures")
  2868. << MatchTable::NamedValue(getNameForFeatureBitset(RequiredFeatures))
  2869. << MatchTable::LineBreak;
  2870. }
  2871. Matchers.front()->emitPredicateOpcodes(Table, *this);
  2872. // We must also check if it's safe to fold the matched instructions.
  2873. if (InsnVariableIDs.size() >= 2) {
  2874. // Invert the map to create stable ordering (by var names)
  2875. SmallVector<unsigned, 2> InsnIDs;
  2876. for (const auto &Pair : InsnVariableIDs) {
  2877. // Skip the root node since it isn't moving anywhere. Everything else is
  2878. // sinking to meet it.
  2879. if (Pair.first == Matchers.front().get())
  2880. continue;
  2881. InsnIDs.push_back(Pair.second);
  2882. }
  2883. llvm::sort(InsnIDs);
  2884. for (const auto &InsnID : InsnIDs) {
  2885. // Reject the difficult cases until we have a more accurate check.
  2886. Table << MatchTable::Opcode("GIM_CheckIsSafeToFold")
  2887. << MatchTable::Comment("InsnID") << MatchTable::IntValue(InsnID)
  2888. << MatchTable::LineBreak;
  2889. // FIXME: Emit checks to determine it's _actually_ safe to fold and/or
  2890. // account for unsafe cases.
  2891. //
  2892. // Example:
  2893. // MI1--> %0 = ...
  2894. // %1 = ... %0
  2895. // MI0--> %2 = ... %0
  2896. // It's not safe to erase MI1. We currently handle this by not
  2897. // erasing %0 (even when it's dead).
  2898. //
  2899. // Example:
  2900. // MI1--> %0 = load volatile @a
  2901. // %1 = load volatile @a
  2902. // MI0--> %2 = ... %0
  2903. // It's not safe to sink %0's def past %1. We currently handle
  2904. // this by rejecting all loads.
  2905. //
  2906. // Example:
  2907. // MI1--> %0 = load @a
  2908. // %1 = store @a
  2909. // MI0--> %2 = ... %0
  2910. // It's not safe to sink %0's def past %1. We currently handle
  2911. // this by rejecting all loads.
  2912. //
  2913. // Example:
  2914. // G_CONDBR %cond, @BB1
  2915. // BB0:
  2916. // MI1--> %0 = load @a
  2917. // G_BR @BB1
  2918. // BB1:
  2919. // MI0--> %2 = ... %0
  2920. // It's not always safe to sink %0 across control flow. In this
  2921. // case it may introduce a memory fault. We currentl handle this
  2922. // by rejecting all loads.
  2923. }
  2924. }
  2925. for (const auto &PM : EpilogueMatchers)
  2926. PM->emitPredicateOpcodes(Table, *this);
  2927. for (const auto &MA : Actions)
  2928. MA->emitActionOpcodes(Table, *this);
  2929. if (Table.isWithCoverage())
  2930. Table << MatchTable::Opcode("GIR_Coverage") << MatchTable::IntValue(RuleID)
  2931. << MatchTable::LineBreak;
  2932. else
  2933. Table << MatchTable::Comment(("GIR_Coverage, " + Twine(RuleID) + ",").str())
  2934. << MatchTable::LineBreak;
  2935. Table << MatchTable::Opcode("GIR_Done", -1) << MatchTable::LineBreak
  2936. << MatchTable::Label(LabelID);
  2937. ++NumPatternEmitted;
  2938. }
  2939. bool RuleMatcher::isHigherPriorityThan(const RuleMatcher &B) const {
  2940. // Rules involving more match roots have higher priority.
  2941. if (Matchers.size() > B.Matchers.size())
  2942. return true;
  2943. if (Matchers.size() < B.Matchers.size())
  2944. return false;
  2945. for (auto Matcher : zip(Matchers, B.Matchers)) {
  2946. if (std::get<0>(Matcher)->isHigherPriorityThan(*std::get<1>(Matcher)))
  2947. return true;
  2948. if (std::get<1>(Matcher)->isHigherPriorityThan(*std::get<0>(Matcher)))
  2949. return false;
  2950. }
  2951. return false;
  2952. }
  2953. unsigned RuleMatcher::countRendererFns() const {
  2954. return std::accumulate(
  2955. Matchers.begin(), Matchers.end(), 0,
  2956. [](unsigned A, const std::unique_ptr<InstructionMatcher> &Matcher) {
  2957. return A + Matcher->countRendererFns();
  2958. });
  2959. }
  2960. bool OperandPredicateMatcher::isHigherPriorityThan(
  2961. const OperandPredicateMatcher &B) const {
  2962. // Generally speaking, an instruction is more important than an Int or a
  2963. // LiteralInt because it can cover more nodes but theres an exception to
  2964. // this. G_CONSTANT's are less important than either of those two because they
  2965. // are more permissive.
  2966. const InstructionOperandMatcher *AOM =
  2967. dyn_cast<InstructionOperandMatcher>(this);
  2968. const InstructionOperandMatcher *BOM =
  2969. dyn_cast<InstructionOperandMatcher>(&B);
  2970. bool AIsConstantInsn = AOM && AOM->getInsnMatcher().isConstantInstruction();
  2971. bool BIsConstantInsn = BOM && BOM->getInsnMatcher().isConstantInstruction();
  2972. if (AOM && BOM) {
  2973. // The relative priorities between a G_CONSTANT and any other instruction
  2974. // don't actually matter but this code is needed to ensure a strict weak
  2975. // ordering. This is particularly important on Windows where the rules will
  2976. // be incorrectly sorted without it.
  2977. if (AIsConstantInsn != BIsConstantInsn)
  2978. return AIsConstantInsn < BIsConstantInsn;
  2979. return false;
  2980. }
  2981. if (AOM && AIsConstantInsn && (B.Kind == OPM_Int || B.Kind == OPM_LiteralInt))
  2982. return false;
  2983. if (BOM && BIsConstantInsn && (Kind == OPM_Int || Kind == OPM_LiteralInt))
  2984. return true;
  2985. return Kind < B.Kind;
  2986. }
  2987. void SameOperandMatcher::emitPredicateOpcodes(MatchTable &Table,
  2988. RuleMatcher &Rule) const {
  2989. const OperandMatcher &OtherOM = Rule.getOperandMatcher(MatchingName);
  2990. unsigned OtherInsnVarID = Rule.getInsnVarID(OtherOM.getInstructionMatcher());
  2991. assert(OtherInsnVarID == OtherOM.getInstructionMatcher().getInsnVarID());
  2992. Table << MatchTable::Opcode("GIM_CheckIsSameOperand")
  2993. << MatchTable::Comment("MI") << MatchTable::IntValue(InsnVarID)
  2994. << MatchTable::Comment("OpIdx") << MatchTable::IntValue(OpIdx)
  2995. << MatchTable::Comment("OtherMI")
  2996. << MatchTable::IntValue(OtherInsnVarID)
  2997. << MatchTable::Comment("OtherOpIdx")
  2998. << MatchTable::IntValue(OtherOM.getOpIdx())
  2999. << MatchTable::LineBreak;
  3000. }
  3001. //===- GlobalISelEmitter class --------------------------------------------===//
  3002. static Expected<LLTCodeGen> getInstResultType(const TreePatternNode *Dst) {
  3003. ArrayRef<TypeSetByHwMode> ChildTypes = Dst->getExtTypes();
  3004. if (ChildTypes.size() != 1)
  3005. return failedImport("Dst pattern child has multiple results");
  3006. std::optional<LLTCodeGen> MaybeOpTy;
  3007. if (ChildTypes.front().isMachineValueType()) {
  3008. MaybeOpTy =
  3009. MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
  3010. }
  3011. if (!MaybeOpTy)
  3012. return failedImport("Dst operand has an unsupported type");
  3013. return *MaybeOpTy;
  3014. }
  3015. class GlobalISelEmitter {
  3016. public:
  3017. explicit GlobalISelEmitter(RecordKeeper &RK);
  3018. void run(raw_ostream &OS);
  3019. private:
  3020. const RecordKeeper &RK;
  3021. const CodeGenDAGPatterns CGP;
  3022. const CodeGenTarget &Target;
  3023. CodeGenRegBank &CGRegs;
  3024. /// Keep track of the equivalence between SDNodes and Instruction by mapping
  3025. /// SDNodes to the GINodeEquiv mapping. We need to map to the GINodeEquiv to
  3026. /// check for attributes on the relation such as CheckMMOIsNonAtomic.
  3027. /// This is defined using 'GINodeEquiv' in the target description.
  3028. DenseMap<Record *, Record *> NodeEquivs;
  3029. /// Keep track of the equivalence between ComplexPattern's and
  3030. /// GIComplexOperandMatcher. Map entries are specified by subclassing
  3031. /// GIComplexPatternEquiv.
  3032. DenseMap<const Record *, const Record *> ComplexPatternEquivs;
  3033. /// Keep track of the equivalence between SDNodeXForm's and
  3034. /// GICustomOperandRenderer. Map entries are specified by subclassing
  3035. /// GISDNodeXFormEquiv.
  3036. DenseMap<const Record *, const Record *> SDNodeXFormEquivs;
  3037. /// Keep track of Scores of PatternsToMatch similar to how the DAG does.
  3038. /// This adds compatibility for RuleMatchers to use this for ordering rules.
  3039. DenseMap<uint64_t, int> RuleMatcherScores;
  3040. // Map of predicates to their subtarget features.
  3041. SubtargetFeatureInfoMap SubtargetFeatures;
  3042. // Rule coverage information.
  3043. std::optional<CodeGenCoverage> RuleCoverage;
  3044. /// Variables used to help with collecting of named operands for predicates
  3045. /// with 'let PredicateCodeUsesOperands = 1'. WaitingForNamedOperands is set
  3046. /// to the number of named operands that predicate expects. Store locations in
  3047. /// StoreIdxForName correspond to the order in which operand names appear in
  3048. /// predicate's argument list.
  3049. /// When we visit named leaf operand and WaitingForNamedOperands is not zero,
  3050. /// add matcher that will record operand and decrease counter.
  3051. unsigned WaitingForNamedOperands = 0;
  3052. StringMap<unsigned> StoreIdxForName;
  3053. void gatherOpcodeValues();
  3054. void gatherTypeIDValues();
  3055. void gatherNodeEquivs();
  3056. Record *findNodeEquiv(Record *N) const;
  3057. const CodeGenInstruction *getEquivNode(Record &Equiv,
  3058. const TreePatternNode *N) const;
  3059. Error importRulePredicates(RuleMatcher &M, ArrayRef<Record *> Predicates);
  3060. Expected<InstructionMatcher &>
  3061. createAndImportSelDAGMatcher(RuleMatcher &Rule,
  3062. InstructionMatcher &InsnMatcher,
  3063. const TreePatternNode *Src, unsigned &TempOpIdx);
  3064. Error importComplexPatternOperandMatcher(OperandMatcher &OM, Record *R,
  3065. unsigned &TempOpIdx) const;
  3066. Error importChildMatcher(RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
  3067. const TreePatternNode *SrcChild,
  3068. bool OperandIsAPointer, bool OperandIsImmArg,
  3069. unsigned OpIdx, unsigned &TempOpIdx);
  3070. Expected<BuildMIAction &> createAndImportInstructionRenderer(
  3071. RuleMatcher &M, InstructionMatcher &InsnMatcher,
  3072. const TreePatternNode *Src, const TreePatternNode *Dst);
  3073. Expected<action_iterator> createAndImportSubInstructionRenderer(
  3074. action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
  3075. unsigned TempReg);
  3076. Expected<action_iterator>
  3077. createInstructionRenderer(action_iterator InsertPt, RuleMatcher &M,
  3078. const TreePatternNode *Dst);
  3079. Expected<action_iterator>
  3080. importExplicitDefRenderers(action_iterator InsertPt, RuleMatcher &M,
  3081. BuildMIAction &DstMIBuilder,
  3082. const TreePatternNode *Dst);
  3083. Expected<action_iterator>
  3084. importExplicitUseRenderers(action_iterator InsertPt, RuleMatcher &M,
  3085. BuildMIAction &DstMIBuilder,
  3086. const llvm::TreePatternNode *Dst);
  3087. Expected<action_iterator>
  3088. importExplicitUseRenderer(action_iterator InsertPt, RuleMatcher &Rule,
  3089. BuildMIAction &DstMIBuilder,
  3090. TreePatternNode *DstChild);
  3091. Error importDefaultOperandRenderers(action_iterator InsertPt, RuleMatcher &M,
  3092. BuildMIAction &DstMIBuilder,
  3093. DagInit *DefaultOps) const;
  3094. Error
  3095. importImplicitDefRenderers(BuildMIAction &DstMIBuilder,
  3096. const std::vector<Record *> &ImplicitDefs) const;
  3097. void emitCxxPredicateFns(raw_ostream &OS, StringRef CodeFieldName,
  3098. StringRef TypeIdentifier, StringRef ArgType,
  3099. StringRef ArgName, StringRef AdditionalArgs,
  3100. StringRef AdditionalDeclarations,
  3101. std::function<bool(const Record *R)> Filter);
  3102. void emitImmPredicateFns(raw_ostream &OS, StringRef TypeIdentifier,
  3103. StringRef ArgType,
  3104. std::function<bool(const Record *R)> Filter);
  3105. void emitMIPredicateFns(raw_ostream &OS);
  3106. /// Analyze pattern \p P, returning a matcher for it if possible.
  3107. /// Otherwise, return an Error explaining why we don't support it.
  3108. Expected<RuleMatcher> runOnPattern(const PatternToMatch &P);
  3109. void declareSubtargetFeature(Record *Predicate);
  3110. MatchTable buildMatchTable(MutableArrayRef<RuleMatcher> Rules, bool Optimize,
  3111. bool WithCoverage);
  3112. /// Infer a CodeGenRegisterClass for the type of \p SuperRegNode. The returned
  3113. /// CodeGenRegisterClass will support the CodeGenRegisterClass of
  3114. /// \p SubRegNode, and the subregister index defined by \p SubRegIdxNode.
  3115. /// If no register class is found, return std::nullopt.
  3116. std::optional<const CodeGenRegisterClass *>
  3117. inferSuperRegisterClassForNode(const TypeSetByHwMode &Ty,
  3118. TreePatternNode *SuperRegNode,
  3119. TreePatternNode *SubRegIdxNode);
  3120. std::optional<CodeGenSubRegIndex *>
  3121. inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode);
  3122. /// Infer a CodeGenRegisterClass which suppoorts \p Ty and \p SubRegIdxNode.
  3123. /// Return std::nullopt if no such class exists.
  3124. std::optional<const CodeGenRegisterClass *>
  3125. inferSuperRegisterClass(const TypeSetByHwMode &Ty,
  3126. TreePatternNode *SubRegIdxNode);
  3127. /// Return the CodeGenRegisterClass associated with \p Leaf if it has one.
  3128. std::optional<const CodeGenRegisterClass *>
  3129. getRegClassFromLeaf(TreePatternNode *Leaf);
  3130. /// Return a CodeGenRegisterClass for \p N if one can be found. Return
  3131. /// std::nullopt otherwise.
  3132. std::optional<const CodeGenRegisterClass *>
  3133. inferRegClassFromPattern(TreePatternNode *N);
  3134. /// Return the size of the MemoryVT in this predicate, if possible.
  3135. std::optional<unsigned>
  3136. getMemSizeBitsFromPredicate(const TreePredicateFn &Predicate);
  3137. // Add builtin predicates.
  3138. Expected<InstructionMatcher &>
  3139. addBuiltinPredicates(const Record *SrcGIEquivOrNull,
  3140. const TreePredicateFn &Predicate,
  3141. InstructionMatcher &InsnMatcher, bool &HasAddedMatcher);
  3142. public:
  3143. /// Takes a sequence of \p Rules and group them based on the predicates
  3144. /// they share. \p MatcherStorage is used as a memory container
  3145. /// for the group that are created as part of this process.
  3146. ///
  3147. /// What this optimization does looks like if GroupT = GroupMatcher:
  3148. /// Output without optimization:
  3149. /// \verbatim
  3150. /// # R1
  3151. /// # predicate A
  3152. /// # predicate B
  3153. /// ...
  3154. /// # R2
  3155. /// # predicate A // <-- effectively this is going to be checked twice.
  3156. /// // Once in R1 and once in R2.
  3157. /// # predicate C
  3158. /// \endverbatim
  3159. /// Output with optimization:
  3160. /// \verbatim
  3161. /// # Group1_2
  3162. /// # predicate A // <-- Check is now shared.
  3163. /// # R1
  3164. /// # predicate B
  3165. /// # R2
  3166. /// # predicate C
  3167. /// \endverbatim
  3168. template <class GroupT>
  3169. static std::vector<Matcher *> optimizeRules(
  3170. ArrayRef<Matcher *> Rules,
  3171. std::vector<std::unique_ptr<Matcher>> &MatcherStorage);
  3172. };
  3173. void GlobalISelEmitter::gatherOpcodeValues() {
  3174. InstructionOpcodeMatcher::initOpcodeValuesMap(Target);
  3175. }
  3176. void GlobalISelEmitter::gatherTypeIDValues() {
  3177. LLTOperandMatcher::initTypeIDValuesMap();
  3178. }
  3179. void GlobalISelEmitter::gatherNodeEquivs() {
  3180. assert(NodeEquivs.empty());
  3181. for (Record *Equiv : RK.getAllDerivedDefinitions("GINodeEquiv"))
  3182. NodeEquivs[Equiv->getValueAsDef("Node")] = Equiv;
  3183. assert(ComplexPatternEquivs.empty());
  3184. for (Record *Equiv : RK.getAllDerivedDefinitions("GIComplexPatternEquiv")) {
  3185. Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
  3186. if (!SelDAGEquiv)
  3187. continue;
  3188. ComplexPatternEquivs[SelDAGEquiv] = Equiv;
  3189. }
  3190. assert(SDNodeXFormEquivs.empty());
  3191. for (Record *Equiv : RK.getAllDerivedDefinitions("GISDNodeXFormEquiv")) {
  3192. Record *SelDAGEquiv = Equiv->getValueAsDef("SelDAGEquivalent");
  3193. if (!SelDAGEquiv)
  3194. continue;
  3195. SDNodeXFormEquivs[SelDAGEquiv] = Equiv;
  3196. }
  3197. }
  3198. Record *GlobalISelEmitter::findNodeEquiv(Record *N) const {
  3199. return NodeEquivs.lookup(N);
  3200. }
  3201. const CodeGenInstruction *
  3202. GlobalISelEmitter::getEquivNode(Record &Equiv, const TreePatternNode *N) const {
  3203. if (N->getNumChildren() >= 1) {
  3204. // setcc operation maps to two different G_* instructions based on the type.
  3205. if (!Equiv.isValueUnset("IfFloatingPoint") &&
  3206. MVT(N->getChild(0)->getSimpleType(0)).isFloatingPoint())
  3207. return &Target.getInstruction(Equiv.getValueAsDef("IfFloatingPoint"));
  3208. }
  3209. for (const TreePredicateCall &Call : N->getPredicateCalls()) {
  3210. const TreePredicateFn &Predicate = Call.Fn;
  3211. if (!Equiv.isValueUnset("IfSignExtend") &&
  3212. (Predicate.isLoad() || Predicate.isAtomic()) &&
  3213. Predicate.isSignExtLoad())
  3214. return &Target.getInstruction(Equiv.getValueAsDef("IfSignExtend"));
  3215. if (!Equiv.isValueUnset("IfZeroExtend") &&
  3216. (Predicate.isLoad() || Predicate.isAtomic()) &&
  3217. Predicate.isZeroExtLoad())
  3218. return &Target.getInstruction(Equiv.getValueAsDef("IfZeroExtend"));
  3219. }
  3220. return &Target.getInstruction(Equiv.getValueAsDef("I"));
  3221. }
  3222. GlobalISelEmitter::GlobalISelEmitter(RecordKeeper &RK)
  3223. : RK(RK), CGP(RK), Target(CGP.getTargetInfo()),
  3224. CGRegs(Target.getRegBank()) {}
  3225. //===- Emitter ------------------------------------------------------------===//
  3226. Error GlobalISelEmitter::importRulePredicates(RuleMatcher &M,
  3227. ArrayRef<Record *> Predicates) {
  3228. for (Record *Pred : Predicates) {
  3229. if (Pred->getValueAsString("CondString").empty())
  3230. continue;
  3231. declareSubtargetFeature(Pred);
  3232. M.addRequiredFeature(Pred);
  3233. }
  3234. return Error::success();
  3235. }
  3236. std::optional<unsigned> GlobalISelEmitter::getMemSizeBitsFromPredicate(
  3237. const TreePredicateFn &Predicate) {
  3238. std::optional<LLTCodeGen> MemTyOrNone =
  3239. MVTToLLT(getValueType(Predicate.getMemoryVT()));
  3240. if (!MemTyOrNone)
  3241. return std::nullopt;
  3242. // Align so unusual types like i1 don't get rounded down.
  3243. return llvm::alignTo(
  3244. static_cast<unsigned>(MemTyOrNone->get().getSizeInBits()), 8);
  3245. }
  3246. Expected<InstructionMatcher &> GlobalISelEmitter::addBuiltinPredicates(
  3247. const Record *SrcGIEquivOrNull, const TreePredicateFn &Predicate,
  3248. InstructionMatcher &InsnMatcher, bool &HasAddedMatcher) {
  3249. if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
  3250. if (const ListInit *AddrSpaces = Predicate.getAddressSpaces()) {
  3251. SmallVector<unsigned, 4> ParsedAddrSpaces;
  3252. for (Init *Val : AddrSpaces->getValues()) {
  3253. IntInit *IntVal = dyn_cast<IntInit>(Val);
  3254. if (!IntVal)
  3255. return failedImport("Address space is not an integer");
  3256. ParsedAddrSpaces.push_back(IntVal->getValue());
  3257. }
  3258. if (!ParsedAddrSpaces.empty()) {
  3259. InsnMatcher.addPredicate<MemoryAddressSpacePredicateMatcher>(
  3260. 0, ParsedAddrSpaces);
  3261. return InsnMatcher;
  3262. }
  3263. }
  3264. int64_t MinAlign = Predicate.getMinAlignment();
  3265. if (MinAlign > 0) {
  3266. InsnMatcher.addPredicate<MemoryAlignmentPredicateMatcher>(0, MinAlign);
  3267. return InsnMatcher;
  3268. }
  3269. }
  3270. // G_LOAD is used for both non-extending and any-extending loads.
  3271. if (Predicate.isLoad() && Predicate.isNonExtLoad()) {
  3272. InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
  3273. 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
  3274. return InsnMatcher;
  3275. }
  3276. if (Predicate.isLoad() && Predicate.isAnyExtLoad()) {
  3277. InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
  3278. 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
  3279. return InsnMatcher;
  3280. }
  3281. if (Predicate.isStore()) {
  3282. if (Predicate.isTruncStore()) {
  3283. if (Predicate.getMemoryVT() != nullptr) {
  3284. // FIXME: If MemoryVT is set, we end up with 2 checks for the MMO size.
  3285. auto MemSizeInBits = getMemSizeBitsFromPredicate(Predicate);
  3286. if (!MemSizeInBits)
  3287. return failedImport("MemVT could not be converted to LLT");
  3288. InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0, *MemSizeInBits /
  3289. 8);
  3290. } else {
  3291. InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
  3292. 0, MemoryVsLLTSizePredicateMatcher::LessThan, 0);
  3293. }
  3294. return InsnMatcher;
  3295. }
  3296. if (Predicate.isNonTruncStore()) {
  3297. // We need to check the sizes match here otherwise we could incorrectly
  3298. // match truncating stores with non-truncating ones.
  3299. InsnMatcher.addPredicate<MemoryVsLLTSizePredicateMatcher>(
  3300. 0, MemoryVsLLTSizePredicateMatcher::EqualTo, 0);
  3301. }
  3302. }
  3303. // No check required. We already did it by swapping the opcode.
  3304. if (!SrcGIEquivOrNull->isValueUnset("IfSignExtend") &&
  3305. Predicate.isSignExtLoad())
  3306. return InsnMatcher;
  3307. // No check required. We already did it by swapping the opcode.
  3308. if (!SrcGIEquivOrNull->isValueUnset("IfZeroExtend") &&
  3309. Predicate.isZeroExtLoad())
  3310. return InsnMatcher;
  3311. // No check required. G_STORE by itself is a non-extending store.
  3312. if (Predicate.isNonTruncStore())
  3313. return InsnMatcher;
  3314. if (Predicate.isLoad() || Predicate.isStore() || Predicate.isAtomic()) {
  3315. if (Predicate.getMemoryVT() != nullptr) {
  3316. auto MemSizeInBits = getMemSizeBitsFromPredicate(Predicate);
  3317. if (!MemSizeInBits)
  3318. return failedImport("MemVT could not be converted to LLT");
  3319. InsnMatcher.addPredicate<MemorySizePredicateMatcher>(0,
  3320. *MemSizeInBits / 8);
  3321. return InsnMatcher;
  3322. }
  3323. }
  3324. if (Predicate.isLoad() || Predicate.isStore()) {
  3325. // No check required. A G_LOAD/G_STORE is an unindexed load.
  3326. if (Predicate.isUnindexed())
  3327. return InsnMatcher;
  3328. }
  3329. if (Predicate.isAtomic()) {
  3330. if (Predicate.isAtomicOrderingMonotonic()) {
  3331. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Monotonic");
  3332. return InsnMatcher;
  3333. }
  3334. if (Predicate.isAtomicOrderingAcquire()) {
  3335. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Acquire");
  3336. return InsnMatcher;
  3337. }
  3338. if (Predicate.isAtomicOrderingRelease()) {
  3339. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("Release");
  3340. return InsnMatcher;
  3341. }
  3342. if (Predicate.isAtomicOrderingAcquireRelease()) {
  3343. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3344. "AcquireRelease");
  3345. return InsnMatcher;
  3346. }
  3347. if (Predicate.isAtomicOrderingSequentiallyConsistent()) {
  3348. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3349. "SequentiallyConsistent");
  3350. return InsnMatcher;
  3351. }
  3352. }
  3353. if (Predicate.isAtomicOrderingAcquireOrStronger()) {
  3354. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3355. "Acquire", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
  3356. return InsnMatcher;
  3357. }
  3358. if (Predicate.isAtomicOrderingWeakerThanAcquire()) {
  3359. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3360. "Acquire", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
  3361. return InsnMatcher;
  3362. }
  3363. if (Predicate.isAtomicOrderingReleaseOrStronger()) {
  3364. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3365. "Release", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
  3366. return InsnMatcher;
  3367. }
  3368. if (Predicate.isAtomicOrderingWeakerThanRelease()) {
  3369. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3370. "Release", AtomicOrderingMMOPredicateMatcher::AO_WeakerThan);
  3371. return InsnMatcher;
  3372. }
  3373. HasAddedMatcher = false;
  3374. return InsnMatcher;
  3375. }
  3376. Expected<InstructionMatcher &> GlobalISelEmitter::createAndImportSelDAGMatcher(
  3377. RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
  3378. const TreePatternNode *Src, unsigned &TempOpIdx) {
  3379. Record *SrcGIEquivOrNull = nullptr;
  3380. const CodeGenInstruction *SrcGIOrNull = nullptr;
  3381. // Start with the defined operands (i.e., the results of the root operator).
  3382. if (Src->getExtTypes().size() > 1)
  3383. return failedImport("Src pattern has multiple results");
  3384. if (Src->isLeaf()) {
  3385. Init *SrcInit = Src->getLeafValue();
  3386. if (isa<IntInit>(SrcInit)) {
  3387. InsnMatcher.addPredicate<InstructionOpcodeMatcher>(
  3388. &Target.getInstruction(RK.getDef("G_CONSTANT")));
  3389. } else
  3390. return failedImport(
  3391. "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
  3392. } else {
  3393. SrcGIEquivOrNull = findNodeEquiv(Src->getOperator());
  3394. if (!SrcGIEquivOrNull)
  3395. return failedImport("Pattern operator lacks an equivalent Instruction" +
  3396. explainOperator(Src->getOperator()));
  3397. SrcGIOrNull = getEquivNode(*SrcGIEquivOrNull, Src);
  3398. // The operators look good: match the opcode
  3399. InsnMatcher.addPredicate<InstructionOpcodeMatcher>(SrcGIOrNull);
  3400. }
  3401. unsigned OpIdx = 0;
  3402. for (const TypeSetByHwMode &VTy : Src->getExtTypes()) {
  3403. // Results don't have a name unless they are the root node. The caller will
  3404. // set the name if appropriate.
  3405. const bool OperandIsAPointer =
  3406. SrcGIOrNull && SrcGIOrNull->isOutOperandAPointer(OpIdx);
  3407. OperandMatcher &OM = InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
  3408. if (auto Error = OM.addTypeCheckPredicate(VTy, OperandIsAPointer))
  3409. return failedImport(toString(std::move(Error)) +
  3410. " for result of Src pattern operator");
  3411. }
  3412. for (const TreePredicateCall &Call : Src->getPredicateCalls()) {
  3413. const TreePredicateFn &Predicate = Call.Fn;
  3414. bool HasAddedBuiltinMatcher = true;
  3415. if (Predicate.isAlwaysTrue())
  3416. continue;
  3417. if (Predicate.isImmediatePattern()) {
  3418. InsnMatcher.addPredicate<InstructionImmPredicateMatcher>(Predicate);
  3419. continue;
  3420. }
  3421. auto InsnMatcherOrError = addBuiltinPredicates(
  3422. SrcGIEquivOrNull, Predicate, InsnMatcher, HasAddedBuiltinMatcher);
  3423. if (auto Error = InsnMatcherOrError.takeError())
  3424. return std::move(Error);
  3425. // FIXME: This should be part of addBuiltinPredicates(). If we add this at
  3426. // the start of addBuiltinPredicates() without returning, then there might
  3427. // be cases where we hit the last return before which the
  3428. // HasAddedBuiltinMatcher will be set to false. The predicate could be
  3429. // missed if we add it in the middle or at the end due to return statements
  3430. // after the addPredicate<>() calls.
  3431. if (Predicate.hasNoUse()) {
  3432. InsnMatcher.addPredicate<NoUsePredicateMatcher>();
  3433. HasAddedBuiltinMatcher = true;
  3434. }
  3435. if (Predicate.hasGISelPredicateCode()) {
  3436. if (Predicate.usesOperands()) {
  3437. assert(WaitingForNamedOperands == 0 &&
  3438. "previous predicate didn't find all operands or "
  3439. "nested predicate that uses operands");
  3440. TreePattern *TP = Predicate.getOrigPatFragRecord();
  3441. WaitingForNamedOperands = TP->getNumArgs();
  3442. for (unsigned i = 0; i < WaitingForNamedOperands; ++i)
  3443. StoreIdxForName[getScopedName(Call.Scope, TP->getArgName(i))] = i;
  3444. }
  3445. InsnMatcher.addPredicate<GenericInstructionPredicateMatcher>(Predicate);
  3446. continue;
  3447. }
  3448. if (!HasAddedBuiltinMatcher) {
  3449. return failedImport("Src pattern child has predicate (" +
  3450. explainPredicates(Src) + ")");
  3451. }
  3452. }
  3453. bool IsAtomic = false;
  3454. if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsNonAtomic"))
  3455. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>("NotAtomic");
  3456. else if (SrcGIEquivOrNull && SrcGIEquivOrNull->getValueAsBit("CheckMMOIsAtomic")) {
  3457. IsAtomic = true;
  3458. InsnMatcher.addPredicate<AtomicOrderingMMOPredicateMatcher>(
  3459. "Unordered", AtomicOrderingMMOPredicateMatcher::AO_OrStronger);
  3460. }
  3461. if (Src->isLeaf()) {
  3462. Init *SrcInit = Src->getLeafValue();
  3463. if (IntInit *SrcIntInit = dyn_cast<IntInit>(SrcInit)) {
  3464. OperandMatcher &OM =
  3465. InsnMatcher.addOperand(OpIdx++, Src->getName(), TempOpIdx);
  3466. OM.addPredicate<LiteralIntOperandMatcher>(SrcIntInit->getValue());
  3467. } else
  3468. return failedImport(
  3469. "Unable to deduce gMIR opcode to handle Src (which is a leaf)");
  3470. } else {
  3471. assert(SrcGIOrNull &&
  3472. "Expected to have already found an equivalent Instruction");
  3473. if (SrcGIOrNull->TheDef->getName() == "G_CONSTANT" ||
  3474. SrcGIOrNull->TheDef->getName() == "G_FCONSTANT") {
  3475. // imm/fpimm still have operands but we don't need to do anything with it
  3476. // here since we don't support ImmLeaf predicates yet. However, we still
  3477. // need to note the hidden operand to get GIM_CheckNumOperands correct.
  3478. InsnMatcher.addOperand(OpIdx++, "", TempOpIdx);
  3479. return InsnMatcher;
  3480. }
  3481. // Special case because the operand order is changed from setcc. The
  3482. // predicate operand needs to be swapped from the last operand to the first
  3483. // source.
  3484. unsigned NumChildren = Src->getNumChildren();
  3485. bool IsFCmp = SrcGIOrNull->TheDef->getName() == "G_FCMP";
  3486. if (IsFCmp || SrcGIOrNull->TheDef->getName() == "G_ICMP") {
  3487. TreePatternNode *SrcChild = Src->getChild(NumChildren - 1);
  3488. if (SrcChild->isLeaf()) {
  3489. DefInit *DI = dyn_cast<DefInit>(SrcChild->getLeafValue());
  3490. Record *CCDef = DI ? DI->getDef() : nullptr;
  3491. if (!CCDef || !CCDef->isSubClassOf("CondCode"))
  3492. return failedImport("Unable to handle CondCode");
  3493. OperandMatcher &OM =
  3494. InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
  3495. StringRef PredType = IsFCmp ? CCDef->getValueAsString("FCmpPredicate") :
  3496. CCDef->getValueAsString("ICmpPredicate");
  3497. if (!PredType.empty()) {
  3498. OM.addPredicate<CmpPredicateOperandMatcher>(std::string(PredType));
  3499. // Process the other 2 operands normally.
  3500. --NumChildren;
  3501. }
  3502. }
  3503. }
  3504. // Hack around an unfortunate mistake in how atomic store (and really
  3505. // atomicrmw in general) operands were ordered. A ISD::STORE used the order
  3506. // <stored value>, <pointer> order. ISD::ATOMIC_STORE used the opposite,
  3507. // <pointer>, <stored value>. In GlobalISel there's just the one store
  3508. // opcode, so we need to swap the operands here to get the right type check.
  3509. if (IsAtomic && SrcGIOrNull->TheDef->getName() == "G_STORE") {
  3510. assert(NumChildren == 2 && "wrong operands for atomic store");
  3511. TreePatternNode *PtrChild = Src->getChild(0);
  3512. TreePatternNode *ValueChild = Src->getChild(1);
  3513. if (auto Error = importChildMatcher(Rule, InsnMatcher, PtrChild, true,
  3514. false, 1, TempOpIdx))
  3515. return std::move(Error);
  3516. if (auto Error = importChildMatcher(Rule, InsnMatcher, ValueChild, false,
  3517. false, 0, TempOpIdx))
  3518. return std::move(Error);
  3519. return InsnMatcher;
  3520. }
  3521. // Match the used operands (i.e. the children of the operator).
  3522. bool IsIntrinsic =
  3523. SrcGIOrNull->TheDef->getName() == "G_INTRINSIC" ||
  3524. SrcGIOrNull->TheDef->getName() == "G_INTRINSIC_W_SIDE_EFFECTS";
  3525. const CodeGenIntrinsic *II = Src->getIntrinsicInfo(CGP);
  3526. if (IsIntrinsic && !II)
  3527. return failedImport("Expected IntInit containing intrinsic ID)");
  3528. for (unsigned i = 0; i != NumChildren; ++i) {
  3529. TreePatternNode *SrcChild = Src->getChild(i);
  3530. // We need to determine the meaning of a literal integer based on the
  3531. // context. If this is a field required to be an immediate (such as an
  3532. // immarg intrinsic argument), the required predicates are different than
  3533. // a constant which may be materialized in a register. If we have an
  3534. // argument that is required to be an immediate, we should not emit an LLT
  3535. // type check, and should not be looking for a G_CONSTANT defined
  3536. // register.
  3537. bool OperandIsImmArg = SrcGIOrNull->isInOperandImmArg(i);
  3538. // SelectionDAG allows pointers to be represented with iN since it doesn't
  3539. // distinguish between pointers and integers but they are different types in GlobalISel.
  3540. // Coerce integers to pointers to address space 0 if the context indicates a pointer.
  3541. //
  3542. bool OperandIsAPointer = SrcGIOrNull->isInOperandAPointer(i);
  3543. if (IsIntrinsic) {
  3544. // For G_INTRINSIC/G_INTRINSIC_W_SIDE_EFFECTS, the operand immediately
  3545. // following the defs is an intrinsic ID.
  3546. if (i == 0) {
  3547. OperandMatcher &OM =
  3548. InsnMatcher.addOperand(OpIdx++, SrcChild->getName(), TempOpIdx);
  3549. OM.addPredicate<IntrinsicIDOperandMatcher>(II);
  3550. continue;
  3551. }
  3552. // We have to check intrinsics for llvm_anyptr_ty and immarg parameters.
  3553. //
  3554. // Note that we have to look at the i-1th parameter, because we don't
  3555. // have the intrinsic ID in the intrinsic's parameter list.
  3556. OperandIsAPointer |= II->isParamAPointer(i - 1);
  3557. OperandIsImmArg |= II->isParamImmArg(i - 1);
  3558. }
  3559. if (auto Error =
  3560. importChildMatcher(Rule, InsnMatcher, SrcChild, OperandIsAPointer,
  3561. OperandIsImmArg, OpIdx++, TempOpIdx))
  3562. return std::move(Error);
  3563. }
  3564. }
  3565. return InsnMatcher;
  3566. }
  3567. Error GlobalISelEmitter::importComplexPatternOperandMatcher(
  3568. OperandMatcher &OM, Record *R, unsigned &TempOpIdx) const {
  3569. const auto &ComplexPattern = ComplexPatternEquivs.find(R);
  3570. if (ComplexPattern == ComplexPatternEquivs.end())
  3571. return failedImport("SelectionDAG ComplexPattern (" + R->getName() +
  3572. ") not mapped to GlobalISel");
  3573. OM.addPredicate<ComplexPatternOperandMatcher>(OM, *ComplexPattern->second);
  3574. TempOpIdx++;
  3575. return Error::success();
  3576. }
  3577. // Get the name to use for a pattern operand. For an anonymous physical register
  3578. // input, this should use the register name.
  3579. static StringRef getSrcChildName(const TreePatternNode *SrcChild,
  3580. Record *&PhysReg) {
  3581. StringRef SrcChildName = SrcChild->getName();
  3582. if (SrcChildName.empty() && SrcChild->isLeaf()) {
  3583. if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
  3584. auto *ChildRec = ChildDefInit->getDef();
  3585. if (ChildRec->isSubClassOf("Register")) {
  3586. SrcChildName = ChildRec->getName();
  3587. PhysReg = ChildRec;
  3588. }
  3589. }
  3590. }
  3591. return SrcChildName;
  3592. }
  3593. Error GlobalISelEmitter::importChildMatcher(
  3594. RuleMatcher &Rule, InstructionMatcher &InsnMatcher,
  3595. const TreePatternNode *SrcChild, bool OperandIsAPointer,
  3596. bool OperandIsImmArg, unsigned OpIdx, unsigned &TempOpIdx) {
  3597. Record *PhysReg = nullptr;
  3598. std::string SrcChildName = std::string(getSrcChildName(SrcChild, PhysReg));
  3599. if (!SrcChild->isLeaf() &&
  3600. SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
  3601. // The "name" of a non-leaf complex pattern (MY_PAT $op1, $op2) is
  3602. // "MY_PAT:op1:op2" and the ones with same "name" represent same operand.
  3603. std::string PatternName = std::string(SrcChild->getOperator()->getName());
  3604. for (unsigned i = 0; i < SrcChild->getNumChildren(); ++i) {
  3605. PatternName += ":";
  3606. PatternName += SrcChild->getChild(i)->getName();
  3607. }
  3608. SrcChildName = PatternName;
  3609. }
  3610. OperandMatcher &OM =
  3611. PhysReg ? InsnMatcher.addPhysRegInput(PhysReg, OpIdx, TempOpIdx)
  3612. : InsnMatcher.addOperand(OpIdx, SrcChildName, TempOpIdx);
  3613. if (OM.isSameAsAnotherOperand())
  3614. return Error::success();
  3615. ArrayRef<TypeSetByHwMode> ChildTypes = SrcChild->getExtTypes();
  3616. if (ChildTypes.size() != 1)
  3617. return failedImport("Src pattern child has multiple results");
  3618. // Check MBB's before the type check since they are not a known type.
  3619. if (!SrcChild->isLeaf()) {
  3620. if (SrcChild->getOperator()->isSubClassOf("SDNode")) {
  3621. auto &ChildSDNI = CGP.getSDNodeInfo(SrcChild->getOperator());
  3622. if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
  3623. OM.addPredicate<MBBOperandMatcher>();
  3624. return Error::success();
  3625. }
  3626. if (SrcChild->getOperator()->getName() == "timm") {
  3627. OM.addPredicate<ImmOperandMatcher>();
  3628. // Add predicates, if any
  3629. for (const TreePredicateCall &Call : SrcChild->getPredicateCalls()) {
  3630. const TreePredicateFn &Predicate = Call.Fn;
  3631. // Only handle immediate patterns for now
  3632. if (Predicate.isImmediatePattern()) {
  3633. OM.addPredicate<OperandImmPredicateMatcher>(Predicate);
  3634. }
  3635. }
  3636. return Error::success();
  3637. }
  3638. }
  3639. }
  3640. // Immediate arguments have no meaningful type to check as they don't have
  3641. // registers.
  3642. if (!OperandIsImmArg) {
  3643. if (auto Error =
  3644. OM.addTypeCheckPredicate(ChildTypes.front(), OperandIsAPointer))
  3645. return failedImport(toString(std::move(Error)) + " for Src operand (" +
  3646. to_string(*SrcChild) + ")");
  3647. }
  3648. // Check for nested instructions.
  3649. if (!SrcChild->isLeaf()) {
  3650. if (SrcChild->getOperator()->isSubClassOf("ComplexPattern")) {
  3651. // When a ComplexPattern is used as an operator, it should do the same
  3652. // thing as when used as a leaf. However, the children of the operator
  3653. // name the sub-operands that make up the complex operand and we must
  3654. // prepare to reference them in the renderer too.
  3655. unsigned RendererID = TempOpIdx;
  3656. if (auto Error = importComplexPatternOperandMatcher(
  3657. OM, SrcChild->getOperator(), TempOpIdx))
  3658. return Error;
  3659. for (unsigned i = 0, e = SrcChild->getNumChildren(); i != e; ++i) {
  3660. auto *SubOperand = SrcChild->getChild(i);
  3661. if (!SubOperand->getName().empty()) {
  3662. if (auto Error = Rule.defineComplexSubOperand(
  3663. SubOperand->getName(), SrcChild->getOperator(), RendererID, i,
  3664. SrcChildName))
  3665. return Error;
  3666. }
  3667. }
  3668. return Error::success();
  3669. }
  3670. auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
  3671. InsnMatcher.getRuleMatcher(), SrcChild->getName());
  3672. if (!MaybeInsnOperand) {
  3673. // This isn't strictly true. If the user were to provide exactly the same
  3674. // matchers as the original operand then we could allow it. However, it's
  3675. // simpler to not permit the redundant specification.
  3676. return failedImport("Nested instruction cannot be the same as another operand");
  3677. }
  3678. // Map the node to a gMIR instruction.
  3679. InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
  3680. auto InsnMatcherOrError = createAndImportSelDAGMatcher(
  3681. Rule, InsnOperand.getInsnMatcher(), SrcChild, TempOpIdx);
  3682. if (auto Error = InsnMatcherOrError.takeError())
  3683. return Error;
  3684. return Error::success();
  3685. }
  3686. if (SrcChild->hasAnyPredicate())
  3687. return failedImport("Src pattern child has unsupported predicate");
  3688. // Check for constant immediates.
  3689. if (auto *ChildInt = dyn_cast<IntInit>(SrcChild->getLeafValue())) {
  3690. if (OperandIsImmArg) {
  3691. // Checks for argument directly in operand list
  3692. OM.addPredicate<LiteralIntOperandMatcher>(ChildInt->getValue());
  3693. } else {
  3694. // Checks for materialized constant
  3695. OM.addPredicate<ConstantIntOperandMatcher>(ChildInt->getValue());
  3696. }
  3697. return Error::success();
  3698. }
  3699. // Check for def's like register classes or ComplexPattern's.
  3700. if (auto *ChildDefInit = dyn_cast<DefInit>(SrcChild->getLeafValue())) {
  3701. auto *ChildRec = ChildDefInit->getDef();
  3702. if (WaitingForNamedOperands) {
  3703. auto PA = SrcChild->getNamesAsPredicateArg().begin();
  3704. std::string Name = getScopedName(PA->getScope(), PA->getIdentifier());
  3705. OM.addPredicate<RecordNamedOperandMatcher>(StoreIdxForName[Name], Name);
  3706. --WaitingForNamedOperands;
  3707. }
  3708. // Check for register classes.
  3709. if (ChildRec->isSubClassOf("RegisterClass") ||
  3710. ChildRec->isSubClassOf("RegisterOperand")) {
  3711. OM.addPredicate<RegisterBankOperandMatcher>(
  3712. Target.getRegisterClass(getInitValueAsRegClass(ChildDefInit)));
  3713. return Error::success();
  3714. }
  3715. if (ChildRec->isSubClassOf("Register")) {
  3716. // This just be emitted as a copy to the specific register.
  3717. ValueTypeByHwMode VT = ChildTypes.front().getValueTypeByHwMode();
  3718. const CodeGenRegisterClass *RC
  3719. = CGRegs.getMinimalPhysRegClass(ChildRec, &VT);
  3720. if (!RC) {
  3721. return failedImport(
  3722. "Could not determine physical register class of pattern source");
  3723. }
  3724. OM.addPredicate<RegisterBankOperandMatcher>(*RC);
  3725. return Error::success();
  3726. }
  3727. // Check for ValueType.
  3728. if (ChildRec->isSubClassOf("ValueType")) {
  3729. // We already added a type check as standard practice so this doesn't need
  3730. // to do anything.
  3731. return Error::success();
  3732. }
  3733. // Check for ComplexPattern's.
  3734. if (ChildRec->isSubClassOf("ComplexPattern"))
  3735. return importComplexPatternOperandMatcher(OM, ChildRec, TempOpIdx);
  3736. if (ChildRec->isSubClassOf("ImmLeaf")) {
  3737. return failedImport(
  3738. "Src pattern child def is an unsupported tablegen class (ImmLeaf)");
  3739. }
  3740. // Place holder for SRCVALUE nodes. Nothing to do here.
  3741. if (ChildRec->getName() == "srcvalue")
  3742. return Error::success();
  3743. const bool ImmAllOnesV = ChildRec->getName() == "immAllOnesV";
  3744. if (ImmAllOnesV || ChildRec->getName() == "immAllZerosV") {
  3745. auto MaybeInsnOperand = OM.addPredicate<InstructionOperandMatcher>(
  3746. InsnMatcher.getRuleMatcher(), SrcChild->getName(), false);
  3747. InstructionOperandMatcher &InsnOperand = **MaybeInsnOperand;
  3748. ValueTypeByHwMode VTy = ChildTypes.front().getValueTypeByHwMode();
  3749. const CodeGenInstruction &BuildVector
  3750. = Target.getInstruction(RK.getDef("G_BUILD_VECTOR"));
  3751. const CodeGenInstruction &BuildVectorTrunc
  3752. = Target.getInstruction(RK.getDef("G_BUILD_VECTOR_TRUNC"));
  3753. // Treat G_BUILD_VECTOR as the canonical opcode, and G_BUILD_VECTOR_TRUNC
  3754. // as an alternative.
  3755. InsnOperand.getInsnMatcher().addPredicate<InstructionOpcodeMatcher>(
  3756. ArrayRef({&BuildVector, &BuildVectorTrunc}));
  3757. // TODO: Handle both G_BUILD_VECTOR and G_BUILD_VECTOR_TRUNC We could
  3758. // theoretically not emit any opcode check, but getOpcodeMatcher currently
  3759. // has to succeed.
  3760. OperandMatcher &OM =
  3761. InsnOperand.getInsnMatcher().addOperand(0, "", TempOpIdx);
  3762. if (auto Error =
  3763. OM.addTypeCheckPredicate(VTy, false /* OperandIsAPointer */))
  3764. return failedImport(toString(std::move(Error)) +
  3765. " for result of Src pattern operator");
  3766. InsnOperand.getInsnMatcher().addPredicate<VectorSplatImmPredicateMatcher>(
  3767. ImmAllOnesV ? VectorSplatImmPredicateMatcher::AllOnes
  3768. : VectorSplatImmPredicateMatcher::AllZeros);
  3769. return Error::success();
  3770. }
  3771. return failedImport(
  3772. "Src pattern child def is an unsupported tablegen class");
  3773. }
  3774. return failedImport("Src pattern child is an unsupported kind");
  3775. }
  3776. Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderer(
  3777. action_iterator InsertPt, RuleMatcher &Rule, BuildMIAction &DstMIBuilder,
  3778. TreePatternNode *DstChild) {
  3779. const auto &SubOperand = Rule.getComplexSubOperand(DstChild->getName());
  3780. if (SubOperand) {
  3781. DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
  3782. *std::get<0>(*SubOperand), DstChild->getName(),
  3783. std::get<1>(*SubOperand), std::get<2>(*SubOperand));
  3784. return InsertPt;
  3785. }
  3786. if (!DstChild->isLeaf()) {
  3787. if (DstChild->getOperator()->isSubClassOf("SDNodeXForm")) {
  3788. auto Child = DstChild->getChild(0);
  3789. auto I = SDNodeXFormEquivs.find(DstChild->getOperator());
  3790. if (I != SDNodeXFormEquivs.end()) {
  3791. Record *XFormOpc = DstChild->getOperator()->getValueAsDef("Opcode");
  3792. if (XFormOpc->getName() == "timm") {
  3793. // If this is a TargetConstant, there won't be a corresponding
  3794. // instruction to transform. Instead, this will refer directly to an
  3795. // operand in an instruction's operand list.
  3796. DstMIBuilder.addRenderer<CustomOperandRenderer>(*I->second,
  3797. Child->getName());
  3798. } else {
  3799. DstMIBuilder.addRenderer<CustomRenderer>(*I->second,
  3800. Child->getName());
  3801. }
  3802. return InsertPt;
  3803. }
  3804. return failedImport("SDNodeXForm " + Child->getName() +
  3805. " has no custom renderer");
  3806. }
  3807. // We accept 'bb' here. It's an operator because BasicBlockSDNode isn't
  3808. // inline, but in MI it's just another operand.
  3809. if (DstChild->getOperator()->isSubClassOf("SDNode")) {
  3810. auto &ChildSDNI = CGP.getSDNodeInfo(DstChild->getOperator());
  3811. if (ChildSDNI.getSDClassName() == "BasicBlockSDNode") {
  3812. DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
  3813. return InsertPt;
  3814. }
  3815. }
  3816. // Similarly, imm is an operator in TreePatternNode's view but must be
  3817. // rendered as operands.
  3818. // FIXME: The target should be able to choose sign-extended when appropriate
  3819. // (e.g. on Mips).
  3820. if (DstChild->getOperator()->getName() == "timm") {
  3821. DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
  3822. return InsertPt;
  3823. } else if (DstChild->getOperator()->getName() == "imm") {
  3824. DstMIBuilder.addRenderer<CopyConstantAsImmRenderer>(DstChild->getName());
  3825. return InsertPt;
  3826. } else if (DstChild->getOperator()->getName() == "fpimm") {
  3827. DstMIBuilder.addRenderer<CopyFConstantAsFPImmRenderer>(
  3828. DstChild->getName());
  3829. return InsertPt;
  3830. }
  3831. if (DstChild->getOperator()->isSubClassOf("Instruction")) {
  3832. auto OpTy = getInstResultType(DstChild);
  3833. if (!OpTy)
  3834. return OpTy.takeError();
  3835. unsigned TempRegID = Rule.allocateTempRegID();
  3836. InsertPt = Rule.insertAction<MakeTempRegisterAction>(
  3837. InsertPt, *OpTy, TempRegID);
  3838. DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
  3839. auto InsertPtOrError = createAndImportSubInstructionRenderer(
  3840. ++InsertPt, Rule, DstChild, TempRegID);
  3841. if (auto Error = InsertPtOrError.takeError())
  3842. return std::move(Error);
  3843. return InsertPtOrError.get();
  3844. }
  3845. return failedImport("Dst pattern child isn't a leaf node or an MBB" + llvm::to_string(*DstChild));
  3846. }
  3847. // It could be a specific immediate in which case we should just check for
  3848. // that immediate.
  3849. if (const IntInit *ChildIntInit =
  3850. dyn_cast<IntInit>(DstChild->getLeafValue())) {
  3851. DstMIBuilder.addRenderer<ImmRenderer>(ChildIntInit->getValue());
  3852. return InsertPt;
  3853. }
  3854. // Otherwise, we're looking for a bog-standard RegisterClass operand.
  3855. if (auto *ChildDefInit = dyn_cast<DefInit>(DstChild->getLeafValue())) {
  3856. auto *ChildRec = ChildDefInit->getDef();
  3857. ArrayRef<TypeSetByHwMode> ChildTypes = DstChild->getExtTypes();
  3858. if (ChildTypes.size() != 1)
  3859. return failedImport("Dst pattern child has multiple results");
  3860. std::optional<LLTCodeGen> OpTyOrNone;
  3861. if (ChildTypes.front().isMachineValueType())
  3862. OpTyOrNone = MVTToLLT(ChildTypes.front().getMachineValueType().SimpleTy);
  3863. if (!OpTyOrNone)
  3864. return failedImport("Dst operand has an unsupported type");
  3865. if (ChildRec->isSubClassOf("Register")) {
  3866. DstMIBuilder.addRenderer<AddRegisterRenderer>(Target, ChildRec);
  3867. return InsertPt;
  3868. }
  3869. if (ChildRec->isSubClassOf("RegisterClass") ||
  3870. ChildRec->isSubClassOf("RegisterOperand") ||
  3871. ChildRec->isSubClassOf("ValueType")) {
  3872. if (ChildRec->isSubClassOf("RegisterOperand") &&
  3873. !ChildRec->isValueUnset("GIZeroRegister")) {
  3874. DstMIBuilder.addRenderer<CopyOrAddZeroRegRenderer>(
  3875. DstChild->getName(), ChildRec->getValueAsDef("GIZeroRegister"));
  3876. return InsertPt;
  3877. }
  3878. DstMIBuilder.addRenderer<CopyRenderer>(DstChild->getName());
  3879. return InsertPt;
  3880. }
  3881. if (ChildRec->isSubClassOf("SubRegIndex")) {
  3882. CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(ChildRec);
  3883. DstMIBuilder.addRenderer<ImmRenderer>(SubIdx->EnumValue);
  3884. return InsertPt;
  3885. }
  3886. if (ChildRec->isSubClassOf("ComplexPattern")) {
  3887. const auto &ComplexPattern = ComplexPatternEquivs.find(ChildRec);
  3888. if (ComplexPattern == ComplexPatternEquivs.end())
  3889. return failedImport(
  3890. "SelectionDAG ComplexPattern not mapped to GlobalISel");
  3891. const OperandMatcher &OM = Rule.getOperandMatcher(DstChild->getName());
  3892. DstMIBuilder.addRenderer<RenderComplexPatternOperand>(
  3893. *ComplexPattern->second, DstChild->getName(),
  3894. OM.getAllocatedTemporariesBaseID());
  3895. return InsertPt;
  3896. }
  3897. return failedImport(
  3898. "Dst pattern child def is an unsupported tablegen class");
  3899. }
  3900. return failedImport("Dst pattern child is an unsupported kind");
  3901. }
  3902. Expected<BuildMIAction &> GlobalISelEmitter::createAndImportInstructionRenderer(
  3903. RuleMatcher &M, InstructionMatcher &InsnMatcher, const TreePatternNode *Src,
  3904. const TreePatternNode *Dst) {
  3905. auto InsertPtOrError = createInstructionRenderer(M.actions_end(), M, Dst);
  3906. if (auto Error = InsertPtOrError.takeError())
  3907. return std::move(Error);
  3908. action_iterator InsertPt = InsertPtOrError.get();
  3909. BuildMIAction &DstMIBuilder = *static_cast<BuildMIAction *>(InsertPt->get());
  3910. for (auto PhysInput : InsnMatcher.getPhysRegInputs()) {
  3911. InsertPt = M.insertAction<BuildMIAction>(
  3912. InsertPt, M.allocateOutputInsnID(),
  3913. &Target.getInstruction(RK.getDef("COPY")));
  3914. BuildMIAction &CopyToPhysRegMIBuilder =
  3915. *static_cast<BuildMIAction *>(InsertPt->get());
  3916. CopyToPhysRegMIBuilder.addRenderer<AddRegisterRenderer>(Target,
  3917. PhysInput.first,
  3918. true);
  3919. CopyToPhysRegMIBuilder.addRenderer<CopyPhysRegRenderer>(PhysInput.first);
  3920. }
  3921. if (auto Error = importExplicitDefRenderers(InsertPt, M, DstMIBuilder, Dst)
  3922. .takeError())
  3923. return std::move(Error);
  3924. if (auto Error = importExplicitUseRenderers(InsertPt, M, DstMIBuilder, Dst)
  3925. .takeError())
  3926. return std::move(Error);
  3927. return DstMIBuilder;
  3928. }
  3929. Expected<action_iterator>
  3930. GlobalISelEmitter::createAndImportSubInstructionRenderer(
  3931. const action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst,
  3932. unsigned TempRegID) {
  3933. auto InsertPtOrError = createInstructionRenderer(InsertPt, M, Dst);
  3934. // TODO: Assert there's exactly one result.
  3935. if (auto Error = InsertPtOrError.takeError())
  3936. return std::move(Error);
  3937. BuildMIAction &DstMIBuilder =
  3938. *static_cast<BuildMIAction *>(InsertPtOrError.get()->get());
  3939. // Assign the result to TempReg.
  3940. DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true);
  3941. InsertPtOrError =
  3942. importExplicitUseRenderers(InsertPtOrError.get(), M, DstMIBuilder, Dst);
  3943. if (auto Error = InsertPtOrError.takeError())
  3944. return std::move(Error);
  3945. // We need to make sure that when we import an INSERT_SUBREG as a
  3946. // subinstruction that it ends up being constrained to the correct super
  3947. // register and subregister classes.
  3948. auto OpName = Target.getInstruction(Dst->getOperator()).TheDef->getName();
  3949. if (OpName == "INSERT_SUBREG") {
  3950. auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
  3951. if (!SubClass)
  3952. return failedImport(
  3953. "Cannot infer register class from INSERT_SUBREG operand #1");
  3954. std::optional<const CodeGenRegisterClass *> SuperClass =
  3955. inferSuperRegisterClassForNode(Dst->getExtType(0), Dst->getChild(0),
  3956. Dst->getChild(2));
  3957. if (!SuperClass)
  3958. return failedImport(
  3959. "Cannot infer register class for INSERT_SUBREG operand #0");
  3960. // The destination and the super register source of an INSERT_SUBREG must
  3961. // be the same register class.
  3962. M.insertAction<ConstrainOperandToRegClassAction>(
  3963. InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
  3964. M.insertAction<ConstrainOperandToRegClassAction>(
  3965. InsertPt, DstMIBuilder.getInsnID(), 1, **SuperClass);
  3966. M.insertAction<ConstrainOperandToRegClassAction>(
  3967. InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
  3968. return InsertPtOrError.get();
  3969. }
  3970. if (OpName == "EXTRACT_SUBREG") {
  3971. // EXTRACT_SUBREG selects into a subregister COPY but unlike most
  3972. // instructions, the result register class is controlled by the
  3973. // subregisters of the operand. As a result, we must constrain the result
  3974. // class rather than check that it's already the right one.
  3975. auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
  3976. if (!SuperClass)
  3977. return failedImport(
  3978. "Cannot infer register class from EXTRACT_SUBREG operand #0");
  3979. auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
  3980. if (!SubIdx)
  3981. return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
  3982. const auto SrcRCDstRCPair =
  3983. (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
  3984. assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
  3985. M.insertAction<ConstrainOperandToRegClassAction>(
  3986. InsertPt, DstMIBuilder.getInsnID(), 0, *SrcRCDstRCPair->second);
  3987. M.insertAction<ConstrainOperandToRegClassAction>(
  3988. InsertPt, DstMIBuilder.getInsnID(), 1, *SrcRCDstRCPair->first);
  3989. // We're done with this pattern! It's eligible for GISel emission; return
  3990. // it.
  3991. return InsertPtOrError.get();
  3992. }
  3993. // Similar to INSERT_SUBREG, we also have to handle SUBREG_TO_REG as a
  3994. // subinstruction.
  3995. if (OpName == "SUBREG_TO_REG") {
  3996. auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
  3997. if (!SubClass)
  3998. return failedImport(
  3999. "Cannot infer register class from SUBREG_TO_REG child #1");
  4000. auto SuperClass = inferSuperRegisterClass(Dst->getExtType(0),
  4001. Dst->getChild(2));
  4002. if (!SuperClass)
  4003. return failedImport(
  4004. "Cannot infer register class for SUBREG_TO_REG operand #0");
  4005. M.insertAction<ConstrainOperandToRegClassAction>(
  4006. InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
  4007. M.insertAction<ConstrainOperandToRegClassAction>(
  4008. InsertPt, DstMIBuilder.getInsnID(), 2, **SubClass);
  4009. return InsertPtOrError.get();
  4010. }
  4011. if (OpName == "REG_SEQUENCE") {
  4012. auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
  4013. M.insertAction<ConstrainOperandToRegClassAction>(
  4014. InsertPt, DstMIBuilder.getInsnID(), 0, **SuperClass);
  4015. unsigned Num = Dst->getNumChildren();
  4016. for (unsigned I = 1; I != Num; I += 2) {
  4017. TreePatternNode *SubRegChild = Dst->getChild(I + 1);
  4018. auto SubIdx = inferSubRegIndexForNode(SubRegChild);
  4019. if (!SubIdx)
  4020. return failedImport("REG_SEQUENCE child is not a subreg index");
  4021. const auto SrcRCDstRCPair =
  4022. (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
  4023. assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
  4024. M.insertAction<ConstrainOperandToRegClassAction>(
  4025. InsertPt, DstMIBuilder.getInsnID(), I, *SrcRCDstRCPair->second);
  4026. }
  4027. return InsertPtOrError.get();
  4028. }
  4029. M.insertAction<ConstrainOperandsToDefinitionAction>(InsertPt,
  4030. DstMIBuilder.getInsnID());
  4031. return InsertPtOrError.get();
  4032. }
  4033. Expected<action_iterator> GlobalISelEmitter::createInstructionRenderer(
  4034. action_iterator InsertPt, RuleMatcher &M, const TreePatternNode *Dst) {
  4035. Record *DstOp = Dst->getOperator();
  4036. if (!DstOp->isSubClassOf("Instruction")) {
  4037. if (DstOp->isSubClassOf("ValueType"))
  4038. return failedImport(
  4039. "Pattern operator isn't an instruction (it's a ValueType)");
  4040. return failedImport("Pattern operator isn't an instruction");
  4041. }
  4042. CodeGenInstruction *DstI = &Target.getInstruction(DstOp);
  4043. // COPY_TO_REGCLASS is just a copy with a ConstrainOperandToRegClassAction
  4044. // attached. Similarly for EXTRACT_SUBREG except that's a subregister copy.
  4045. StringRef Name = DstI->TheDef->getName();
  4046. if (Name == "COPY_TO_REGCLASS" || Name == "EXTRACT_SUBREG")
  4047. DstI = &Target.getInstruction(RK.getDef("COPY"));
  4048. return M.insertAction<BuildMIAction>(InsertPt, M.allocateOutputInsnID(),
  4049. DstI);
  4050. }
  4051. Expected<action_iterator> GlobalISelEmitter::importExplicitDefRenderers(
  4052. action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
  4053. const TreePatternNode *Dst) {
  4054. const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
  4055. const unsigned NumDefs = DstI->Operands.NumDefs;
  4056. if (NumDefs == 0)
  4057. return InsertPt;
  4058. DstMIBuilder.addRenderer<CopyRenderer>(DstI->Operands[0].Name);
  4059. // Some instructions have multiple defs, but are missing a type entry
  4060. // (e.g. s_cc_out operands).
  4061. if (Dst->getExtTypes().size() < NumDefs)
  4062. return failedImport("unhandled discarded def");
  4063. // Patterns only handle a single result, so any result after the first is an
  4064. // implicitly dead def.
  4065. for (unsigned I = 1; I < NumDefs; ++I) {
  4066. const TypeSetByHwMode &ExtTy = Dst->getExtType(I);
  4067. if (!ExtTy.isMachineValueType())
  4068. return failedImport("unsupported typeset");
  4069. auto OpTy = MVTToLLT(ExtTy.getMachineValueType().SimpleTy);
  4070. if (!OpTy)
  4071. return failedImport("unsupported type");
  4072. unsigned TempRegID = M.allocateTempRegID();
  4073. InsertPt =
  4074. M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTy, TempRegID);
  4075. DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, true, nullptr, true);
  4076. }
  4077. return InsertPt;
  4078. }
  4079. Expected<action_iterator> GlobalISelEmitter::importExplicitUseRenderers(
  4080. action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
  4081. const llvm::TreePatternNode *Dst) {
  4082. const CodeGenInstruction *DstI = DstMIBuilder.getCGI();
  4083. CodeGenInstruction *OrigDstI = &Target.getInstruction(Dst->getOperator());
  4084. StringRef Name = OrigDstI->TheDef->getName();
  4085. unsigned ExpectedDstINumUses = Dst->getNumChildren();
  4086. // EXTRACT_SUBREG needs to use a subregister COPY.
  4087. if (Name == "EXTRACT_SUBREG") {
  4088. if (!Dst->getChild(1)->isLeaf())
  4089. return failedImport("EXTRACT_SUBREG child #1 is not a leaf");
  4090. DefInit *SubRegInit = dyn_cast<DefInit>(Dst->getChild(1)->getLeafValue());
  4091. if (!SubRegInit)
  4092. return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
  4093. CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
  4094. TreePatternNode *ValChild = Dst->getChild(0);
  4095. if (!ValChild->isLeaf()) {
  4096. // We really have to handle the source instruction, and then insert a
  4097. // copy from the subregister.
  4098. auto ExtractSrcTy = getInstResultType(ValChild);
  4099. if (!ExtractSrcTy)
  4100. return ExtractSrcTy.takeError();
  4101. unsigned TempRegID = M.allocateTempRegID();
  4102. InsertPt = M.insertAction<MakeTempRegisterAction>(
  4103. InsertPt, *ExtractSrcTy, TempRegID);
  4104. auto InsertPtOrError = createAndImportSubInstructionRenderer(
  4105. ++InsertPt, M, ValChild, TempRegID);
  4106. if (auto Error = InsertPtOrError.takeError())
  4107. return std::move(Error);
  4108. DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID, false, SubIdx);
  4109. return InsertPt;
  4110. }
  4111. // If this is a source operand, this is just a subregister copy.
  4112. Record *RCDef = getInitValueAsRegClass(ValChild->getLeafValue());
  4113. if (!RCDef)
  4114. return failedImport("EXTRACT_SUBREG child #0 could not "
  4115. "be coerced to a register class");
  4116. CodeGenRegisterClass *RC = CGRegs.getRegClass(RCDef);
  4117. const auto SrcRCDstRCPair =
  4118. RC->getMatchingSubClassWithSubRegs(CGRegs, SubIdx);
  4119. if (SrcRCDstRCPair) {
  4120. assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
  4121. if (SrcRCDstRCPair->first != RC)
  4122. return failedImport("EXTRACT_SUBREG requires an additional COPY");
  4123. }
  4124. DstMIBuilder.addRenderer<CopySubRegRenderer>(Dst->getChild(0)->getName(),
  4125. SubIdx);
  4126. return InsertPt;
  4127. }
  4128. if (Name == "REG_SEQUENCE") {
  4129. if (!Dst->getChild(0)->isLeaf())
  4130. return failedImport("REG_SEQUENCE child #0 is not a leaf");
  4131. Record *RCDef = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
  4132. if (!RCDef)
  4133. return failedImport("REG_SEQUENCE child #0 could not "
  4134. "be coerced to a register class");
  4135. if ((ExpectedDstINumUses - 1) % 2 != 0)
  4136. return failedImport("Malformed REG_SEQUENCE");
  4137. for (unsigned I = 1; I != ExpectedDstINumUses; I += 2) {
  4138. TreePatternNode *ValChild = Dst->getChild(I);
  4139. TreePatternNode *SubRegChild = Dst->getChild(I + 1);
  4140. if (DefInit *SubRegInit =
  4141. dyn_cast<DefInit>(SubRegChild->getLeafValue())) {
  4142. CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
  4143. auto InsertPtOrError =
  4144. importExplicitUseRenderer(InsertPt, M, DstMIBuilder, ValChild);
  4145. if (auto Error = InsertPtOrError.takeError())
  4146. return std::move(Error);
  4147. InsertPt = InsertPtOrError.get();
  4148. DstMIBuilder.addRenderer<SubRegIndexRenderer>(SubIdx);
  4149. }
  4150. }
  4151. return InsertPt;
  4152. }
  4153. // Render the explicit uses.
  4154. unsigned DstINumUses = OrigDstI->Operands.size() - OrigDstI->Operands.NumDefs;
  4155. if (Name == "COPY_TO_REGCLASS") {
  4156. DstINumUses--; // Ignore the class constraint.
  4157. ExpectedDstINumUses--;
  4158. }
  4159. // NumResults - This is the number of results produced by the instruction in
  4160. // the "outs" list.
  4161. unsigned NumResults = OrigDstI->Operands.NumDefs;
  4162. // Number of operands we know the output instruction must have. If it is
  4163. // variadic, we could have more operands.
  4164. unsigned NumFixedOperands = DstI->Operands.size();
  4165. // Loop over all of the fixed operands of the instruction pattern, emitting
  4166. // code to fill them all in. The node 'N' usually has number children equal to
  4167. // the number of input operands of the instruction. However, in cases where
  4168. // there are predicate operands for an instruction, we need to fill in the
  4169. // 'execute always' values. Match up the node operands to the instruction
  4170. // operands to do this.
  4171. unsigned Child = 0;
  4172. // Similarly to the code in TreePatternNode::ApplyTypeConstraints, count the
  4173. // number of operands at the end of the list which have default values.
  4174. // Those can come from the pattern if it provides enough arguments, or be
  4175. // filled in with the default if the pattern hasn't provided them. But any
  4176. // operand with a default value _before_ the last mandatory one will be
  4177. // filled in with their defaults unconditionally.
  4178. unsigned NonOverridableOperands = NumFixedOperands;
  4179. while (NonOverridableOperands > NumResults &&
  4180. CGP.operandHasDefault(DstI->Operands[NonOverridableOperands - 1].Rec))
  4181. --NonOverridableOperands;
  4182. unsigned NumDefaultOps = 0;
  4183. for (unsigned I = 0; I != DstINumUses; ++I) {
  4184. unsigned InstOpNo = DstI->Operands.NumDefs + I;
  4185. // Determine what to emit for this operand.
  4186. Record *OperandNode = DstI->Operands[InstOpNo].Rec;
  4187. // If the operand has default values, introduce them now.
  4188. if (CGP.operandHasDefault(OperandNode) &&
  4189. (InstOpNo < NonOverridableOperands || Child >= Dst->getNumChildren())) {
  4190. // This is a predicate or optional def operand which the pattern has not
  4191. // overridden, or which we aren't letting it override; emit the 'default
  4192. // ops' operands.
  4193. const CGIOperandList::OperandInfo &DstIOperand = DstI->Operands[InstOpNo];
  4194. DagInit *DefaultOps = DstIOperand.Rec->getValueAsDag("DefaultOps");
  4195. if (auto Error = importDefaultOperandRenderers(
  4196. InsertPt, M, DstMIBuilder, DefaultOps))
  4197. return std::move(Error);
  4198. ++NumDefaultOps;
  4199. continue;
  4200. }
  4201. auto InsertPtOrError = importExplicitUseRenderer(InsertPt, M, DstMIBuilder,
  4202. Dst->getChild(Child));
  4203. if (auto Error = InsertPtOrError.takeError())
  4204. return std::move(Error);
  4205. InsertPt = InsertPtOrError.get();
  4206. ++Child;
  4207. }
  4208. if (NumDefaultOps + ExpectedDstINumUses != DstINumUses)
  4209. return failedImport("Expected " + llvm::to_string(DstINumUses) +
  4210. " used operands but found " +
  4211. llvm::to_string(ExpectedDstINumUses) +
  4212. " explicit ones and " + llvm::to_string(NumDefaultOps) +
  4213. " default ones");
  4214. return InsertPt;
  4215. }
  4216. Error GlobalISelEmitter::importDefaultOperandRenderers(
  4217. action_iterator InsertPt, RuleMatcher &M, BuildMIAction &DstMIBuilder,
  4218. DagInit *DefaultOps) const {
  4219. for (const auto *DefaultOp : DefaultOps->getArgs()) {
  4220. std::optional<LLTCodeGen> OpTyOrNone;
  4221. // Look through ValueType operators.
  4222. if (const DagInit *DefaultDagOp = dyn_cast<DagInit>(DefaultOp)) {
  4223. if (const DefInit *DefaultDagOperator =
  4224. dyn_cast<DefInit>(DefaultDagOp->getOperator())) {
  4225. if (DefaultDagOperator->getDef()->isSubClassOf("ValueType")) {
  4226. OpTyOrNone = MVTToLLT(getValueType(
  4227. DefaultDagOperator->getDef()));
  4228. DefaultOp = DefaultDagOp->getArg(0);
  4229. }
  4230. }
  4231. }
  4232. if (const DefInit *DefaultDefOp = dyn_cast<DefInit>(DefaultOp)) {
  4233. auto Def = DefaultDefOp->getDef();
  4234. if (Def->getName() == "undef_tied_input") {
  4235. unsigned TempRegID = M.allocateTempRegID();
  4236. M.insertAction<MakeTempRegisterAction>(InsertPt, *OpTyOrNone,
  4237. TempRegID);
  4238. InsertPt = M.insertAction<BuildMIAction>(
  4239. InsertPt, M.allocateOutputInsnID(),
  4240. &Target.getInstruction(RK.getDef("IMPLICIT_DEF")));
  4241. BuildMIAction &IDMIBuilder = *static_cast<BuildMIAction *>(
  4242. InsertPt->get());
  4243. IDMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
  4244. DstMIBuilder.addRenderer<TempRegRenderer>(TempRegID);
  4245. } else {
  4246. DstMIBuilder.addRenderer<AddRegisterRenderer>(Target, Def);
  4247. }
  4248. continue;
  4249. }
  4250. if (const IntInit *DefaultIntOp = dyn_cast<IntInit>(DefaultOp)) {
  4251. DstMIBuilder.addRenderer<ImmRenderer>(DefaultIntOp->getValue());
  4252. continue;
  4253. }
  4254. return failedImport("Could not add default op");
  4255. }
  4256. return Error::success();
  4257. }
  4258. Error GlobalISelEmitter::importImplicitDefRenderers(
  4259. BuildMIAction &DstMIBuilder,
  4260. const std::vector<Record *> &ImplicitDefs) const {
  4261. if (!ImplicitDefs.empty())
  4262. return failedImport("Pattern defines a physical register");
  4263. return Error::success();
  4264. }
  4265. std::optional<const CodeGenRegisterClass *>
  4266. GlobalISelEmitter::getRegClassFromLeaf(TreePatternNode *Leaf) {
  4267. assert(Leaf && "Expected node?");
  4268. assert(Leaf->isLeaf() && "Expected leaf?");
  4269. Record *RCRec = getInitValueAsRegClass(Leaf->getLeafValue());
  4270. if (!RCRec)
  4271. return std::nullopt;
  4272. CodeGenRegisterClass *RC = CGRegs.getRegClass(RCRec);
  4273. if (!RC)
  4274. return std::nullopt;
  4275. return RC;
  4276. }
  4277. std::optional<const CodeGenRegisterClass *>
  4278. GlobalISelEmitter::inferRegClassFromPattern(TreePatternNode *N) {
  4279. if (!N)
  4280. return std::nullopt;
  4281. if (N->isLeaf())
  4282. return getRegClassFromLeaf(N);
  4283. // We don't have a leaf node, so we have to try and infer something. Check
  4284. // that we have an instruction that we an infer something from.
  4285. // Only handle things that produce a single type.
  4286. if (N->getNumTypes() != 1)
  4287. return std::nullopt;
  4288. Record *OpRec = N->getOperator();
  4289. // We only want instructions.
  4290. if (!OpRec->isSubClassOf("Instruction"))
  4291. return std::nullopt;
  4292. // Don't want to try and infer things when there could potentially be more
  4293. // than one candidate register class.
  4294. auto &Inst = Target.getInstruction(OpRec);
  4295. if (Inst.Operands.NumDefs > 1)
  4296. return std::nullopt;
  4297. // Handle any special-case instructions which we can safely infer register
  4298. // classes from.
  4299. StringRef InstName = Inst.TheDef->getName();
  4300. bool IsRegSequence = InstName == "REG_SEQUENCE";
  4301. if (IsRegSequence || InstName == "COPY_TO_REGCLASS") {
  4302. // If we have a COPY_TO_REGCLASS, then we need to handle it specially. It
  4303. // has the desired register class as the first child.
  4304. TreePatternNode *RCChild = N->getChild(IsRegSequence ? 0 : 1);
  4305. if (!RCChild->isLeaf())
  4306. return std::nullopt;
  4307. return getRegClassFromLeaf(RCChild);
  4308. }
  4309. if (InstName == "INSERT_SUBREG") {
  4310. TreePatternNode *Child0 = N->getChild(0);
  4311. assert(Child0->getNumTypes() == 1 && "Unexpected number of types!");
  4312. const TypeSetByHwMode &VTy = Child0->getExtType(0);
  4313. return inferSuperRegisterClassForNode(VTy, Child0, N->getChild(2));
  4314. }
  4315. if (InstName == "EXTRACT_SUBREG") {
  4316. assert(N->getNumTypes() == 1 && "Unexpected number of types!");
  4317. const TypeSetByHwMode &VTy = N->getExtType(0);
  4318. return inferSuperRegisterClass(VTy, N->getChild(1));
  4319. }
  4320. // Handle destination record types that we can safely infer a register class
  4321. // from.
  4322. const auto &DstIOperand = Inst.Operands[0];
  4323. Record *DstIOpRec = DstIOperand.Rec;
  4324. if (DstIOpRec->isSubClassOf("RegisterOperand")) {
  4325. DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
  4326. const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
  4327. return &RC;
  4328. }
  4329. if (DstIOpRec->isSubClassOf("RegisterClass")) {
  4330. const CodeGenRegisterClass &RC = Target.getRegisterClass(DstIOpRec);
  4331. return &RC;
  4332. }
  4333. return std::nullopt;
  4334. }
  4335. std::optional<const CodeGenRegisterClass *>
  4336. GlobalISelEmitter::inferSuperRegisterClass(const TypeSetByHwMode &Ty,
  4337. TreePatternNode *SubRegIdxNode) {
  4338. assert(SubRegIdxNode && "Expected subregister index node!");
  4339. // We need a ValueTypeByHwMode for getSuperRegForSubReg.
  4340. if (!Ty.isValueTypeByHwMode(false))
  4341. return std::nullopt;
  4342. if (!SubRegIdxNode->isLeaf())
  4343. return std::nullopt;
  4344. DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
  4345. if (!SubRegInit)
  4346. return std::nullopt;
  4347. CodeGenSubRegIndex *SubIdx = CGRegs.getSubRegIdx(SubRegInit->getDef());
  4348. // Use the information we found above to find a minimal register class which
  4349. // supports the subregister and type we want.
  4350. auto RC =
  4351. Target.getSuperRegForSubReg(Ty.getValueTypeByHwMode(), CGRegs, SubIdx,
  4352. /* MustBeAllocatable */ true);
  4353. if (!RC)
  4354. return std::nullopt;
  4355. return *RC;
  4356. }
  4357. std::optional<const CodeGenRegisterClass *>
  4358. GlobalISelEmitter::inferSuperRegisterClassForNode(
  4359. const TypeSetByHwMode &Ty, TreePatternNode *SuperRegNode,
  4360. TreePatternNode *SubRegIdxNode) {
  4361. assert(SuperRegNode && "Expected super register node!");
  4362. // Check if we already have a defined register class for the super register
  4363. // node. If we do, then we should preserve that rather than inferring anything
  4364. // from the subregister index node. We can assume that whoever wrote the
  4365. // pattern in the first place made sure that the super register and
  4366. // subregister are compatible.
  4367. if (std::optional<const CodeGenRegisterClass *> SuperRegisterClass =
  4368. inferRegClassFromPattern(SuperRegNode))
  4369. return *SuperRegisterClass;
  4370. return inferSuperRegisterClass(Ty, SubRegIdxNode);
  4371. }
  4372. std::optional<CodeGenSubRegIndex *>
  4373. GlobalISelEmitter::inferSubRegIndexForNode(TreePatternNode *SubRegIdxNode) {
  4374. if (!SubRegIdxNode->isLeaf())
  4375. return std::nullopt;
  4376. DefInit *SubRegInit = dyn_cast<DefInit>(SubRegIdxNode->getLeafValue());
  4377. if (!SubRegInit)
  4378. return std::nullopt;
  4379. return CGRegs.getSubRegIdx(SubRegInit->getDef());
  4380. }
  4381. Expected<RuleMatcher> GlobalISelEmitter::runOnPattern(const PatternToMatch &P) {
  4382. // Keep track of the matchers and actions to emit.
  4383. int Score = P.getPatternComplexity(CGP);
  4384. RuleMatcher M(P.getSrcRecord()->getLoc());
  4385. RuleMatcherScores[M.getRuleID()] = Score;
  4386. M.addAction<DebugCommentAction>(llvm::to_string(*P.getSrcPattern()) +
  4387. " => " +
  4388. llvm::to_string(*P.getDstPattern()));
  4389. SmallVector<Record *, 4> Predicates;
  4390. P.getPredicateRecords(Predicates);
  4391. if (auto Error = importRulePredicates(M, Predicates))
  4392. return std::move(Error);
  4393. // Next, analyze the pattern operators.
  4394. TreePatternNode *Src = P.getSrcPattern();
  4395. TreePatternNode *Dst = P.getDstPattern();
  4396. // If the root of either pattern isn't a simple operator, ignore it.
  4397. if (auto Err = isTrivialOperatorNode(Dst))
  4398. return failedImport("Dst pattern root isn't a trivial operator (" +
  4399. toString(std::move(Err)) + ")");
  4400. if (auto Err = isTrivialOperatorNode(Src))
  4401. return failedImport("Src pattern root isn't a trivial operator (" +
  4402. toString(std::move(Err)) + ")");
  4403. // The different predicates and matchers created during
  4404. // addInstructionMatcher use the RuleMatcher M to set up their
  4405. // instruction ID (InsnVarID) that are going to be used when
  4406. // M is going to be emitted.
  4407. // However, the code doing the emission still relies on the IDs
  4408. // returned during that process by the RuleMatcher when issuing
  4409. // the recordInsn opcodes.
  4410. // Because of that:
  4411. // 1. The order in which we created the predicates
  4412. // and such must be the same as the order in which we emit them,
  4413. // and
  4414. // 2. We need to reset the generation of the IDs in M somewhere between
  4415. // addInstructionMatcher and emit
  4416. //
  4417. // FIXME: Long term, we don't want to have to rely on this implicit
  4418. // naming being the same. One possible solution would be to have
  4419. // explicit operator for operation capture and reference those.
  4420. // The plus side is that it would expose opportunities to share
  4421. // the capture accross rules. The downside is that it would
  4422. // introduce a dependency between predicates (captures must happen
  4423. // before their first use.)
  4424. InstructionMatcher &InsnMatcherTemp = M.addInstructionMatcher(Src->getName());
  4425. unsigned TempOpIdx = 0;
  4426. auto InsnMatcherOrError =
  4427. createAndImportSelDAGMatcher(M, InsnMatcherTemp, Src, TempOpIdx);
  4428. if (auto Error = InsnMatcherOrError.takeError())
  4429. return std::move(Error);
  4430. InstructionMatcher &InsnMatcher = InsnMatcherOrError.get();
  4431. if (Dst->isLeaf()) {
  4432. Record *RCDef = getInitValueAsRegClass(Dst->getLeafValue());
  4433. if (RCDef) {
  4434. const CodeGenRegisterClass &RC = Target.getRegisterClass(RCDef);
  4435. // We need to replace the def and all its uses with the specified
  4436. // operand. However, we must also insert COPY's wherever needed.
  4437. // For now, emit a copy and let the register allocator clean up.
  4438. auto &DstI = Target.getInstruction(RK.getDef("COPY"));
  4439. const auto &DstIOperand = DstI.Operands[0];
  4440. OperandMatcher &OM0 = InsnMatcher.getOperand(0);
  4441. OM0.setSymbolicName(DstIOperand.Name);
  4442. M.defineOperand(OM0.getSymbolicName(), OM0);
  4443. OM0.addPredicate<RegisterBankOperandMatcher>(RC);
  4444. auto &DstMIBuilder =
  4445. M.addAction<BuildMIAction>(M.allocateOutputInsnID(), &DstI);
  4446. DstMIBuilder.addRenderer<CopyRenderer>(DstIOperand.Name);
  4447. DstMIBuilder.addRenderer<CopyRenderer>(Dst->getName());
  4448. M.addAction<ConstrainOperandToRegClassAction>(0, 0, RC);
  4449. // We're done with this pattern! It's eligible for GISel emission; return
  4450. // it.
  4451. ++NumPatternImported;
  4452. return std::move(M);
  4453. }
  4454. return failedImport("Dst pattern root isn't a known leaf");
  4455. }
  4456. // Start with the defined operands (i.e., the results of the root operator).
  4457. Record *DstOp = Dst->getOperator();
  4458. if (!DstOp->isSubClassOf("Instruction"))
  4459. return failedImport("Pattern operator isn't an instruction");
  4460. auto &DstI = Target.getInstruction(DstOp);
  4461. StringRef DstIName = DstI.TheDef->getName();
  4462. unsigned DstNumDefs = DstI.Operands.NumDefs,
  4463. SrcNumDefs = Src->getExtTypes().size();
  4464. if (DstNumDefs < SrcNumDefs) {
  4465. if (DstNumDefs != 0)
  4466. return failedImport("Src pattern result has more defs than dst MI (" +
  4467. to_string(SrcNumDefs) + " def(s) vs " +
  4468. to_string(DstNumDefs) + " def(s))");
  4469. bool FoundNoUsePred = false;
  4470. for (const auto &Pred : InsnMatcher.predicates()) {
  4471. if ((FoundNoUsePred = isa<NoUsePredicateMatcher>(Pred.get())))
  4472. break;
  4473. }
  4474. if (!FoundNoUsePred)
  4475. return failedImport("Src pattern result has " + to_string(SrcNumDefs) +
  4476. " def(s) without the HasNoUse predicate set to true "
  4477. "but Dst MI has no def");
  4478. }
  4479. // The root of the match also has constraints on the register bank so that it
  4480. // matches the result instruction.
  4481. unsigned OpIdx = 0;
  4482. unsigned N = std::min(DstNumDefs, SrcNumDefs);
  4483. for (unsigned I = 0; I < N; ++I) {
  4484. const TypeSetByHwMode &VTy = Src->getExtType(I);
  4485. const auto &DstIOperand = DstI.Operands[OpIdx];
  4486. Record *DstIOpRec = DstIOperand.Rec;
  4487. if (DstIName == "COPY_TO_REGCLASS") {
  4488. DstIOpRec = getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
  4489. if (DstIOpRec == nullptr)
  4490. return failedImport(
  4491. "COPY_TO_REGCLASS operand #1 isn't a register class");
  4492. } else if (DstIName == "REG_SEQUENCE") {
  4493. DstIOpRec = getInitValueAsRegClass(Dst->getChild(0)->getLeafValue());
  4494. if (DstIOpRec == nullptr)
  4495. return failedImport("REG_SEQUENCE operand #0 isn't a register class");
  4496. } else if (DstIName == "EXTRACT_SUBREG") {
  4497. auto InferredClass = inferRegClassFromPattern(Dst->getChild(0));
  4498. if (!InferredClass)
  4499. return failedImport("Could not infer class for EXTRACT_SUBREG operand #0");
  4500. // We can assume that a subregister is in the same bank as it's super
  4501. // register.
  4502. DstIOpRec = (*InferredClass)->getDef();
  4503. } else if (DstIName == "INSERT_SUBREG") {
  4504. auto MaybeSuperClass = inferSuperRegisterClassForNode(
  4505. VTy, Dst->getChild(0), Dst->getChild(2));
  4506. if (!MaybeSuperClass)
  4507. return failedImport(
  4508. "Cannot infer register class for INSERT_SUBREG operand #0");
  4509. // Move to the next pattern here, because the register class we found
  4510. // doesn't necessarily have a record associated with it. So, we can't
  4511. // set DstIOpRec using this.
  4512. OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
  4513. OM.setSymbolicName(DstIOperand.Name);
  4514. M.defineOperand(OM.getSymbolicName(), OM);
  4515. OM.addPredicate<RegisterBankOperandMatcher>(**MaybeSuperClass);
  4516. ++OpIdx;
  4517. continue;
  4518. } else if (DstIName == "SUBREG_TO_REG") {
  4519. auto MaybeRegClass = inferSuperRegisterClass(VTy, Dst->getChild(2));
  4520. if (!MaybeRegClass)
  4521. return failedImport(
  4522. "Cannot infer register class for SUBREG_TO_REG operand #0");
  4523. OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
  4524. OM.setSymbolicName(DstIOperand.Name);
  4525. M.defineOperand(OM.getSymbolicName(), OM);
  4526. OM.addPredicate<RegisterBankOperandMatcher>(**MaybeRegClass);
  4527. ++OpIdx;
  4528. continue;
  4529. } else if (DstIOpRec->isSubClassOf("RegisterOperand"))
  4530. DstIOpRec = DstIOpRec->getValueAsDef("RegClass");
  4531. else if (!DstIOpRec->isSubClassOf("RegisterClass"))
  4532. return failedImport("Dst MI def isn't a register class" +
  4533. to_string(*Dst));
  4534. OperandMatcher &OM = InsnMatcher.getOperand(OpIdx);
  4535. OM.setSymbolicName(DstIOperand.Name);
  4536. M.defineOperand(OM.getSymbolicName(), OM);
  4537. OM.addPredicate<RegisterBankOperandMatcher>(
  4538. Target.getRegisterClass(DstIOpRec));
  4539. ++OpIdx;
  4540. }
  4541. auto DstMIBuilderOrError =
  4542. createAndImportInstructionRenderer(M, InsnMatcher, Src, Dst);
  4543. if (auto Error = DstMIBuilderOrError.takeError())
  4544. return std::move(Error);
  4545. BuildMIAction &DstMIBuilder = DstMIBuilderOrError.get();
  4546. // Render the implicit defs.
  4547. // These are only added to the root of the result.
  4548. if (auto Error = importImplicitDefRenderers(DstMIBuilder, P.getDstRegs()))
  4549. return std::move(Error);
  4550. DstMIBuilder.chooseInsnToMutate(M);
  4551. // Constrain the registers to classes. This is normally derived from the
  4552. // emitted instruction but a few instructions require special handling.
  4553. if (DstIName == "COPY_TO_REGCLASS") {
  4554. // COPY_TO_REGCLASS does not provide operand constraints itself but the
  4555. // result is constrained to the class given by the second child.
  4556. Record *DstIOpRec =
  4557. getInitValueAsRegClass(Dst->getChild(1)->getLeafValue());
  4558. if (DstIOpRec == nullptr)
  4559. return failedImport("COPY_TO_REGCLASS operand #1 isn't a register class");
  4560. M.addAction<ConstrainOperandToRegClassAction>(
  4561. 0, 0, Target.getRegisterClass(DstIOpRec));
  4562. // We're done with this pattern! It's eligible for GISel emission; return
  4563. // it.
  4564. ++NumPatternImported;
  4565. return std::move(M);
  4566. }
  4567. if (DstIName == "EXTRACT_SUBREG") {
  4568. auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
  4569. if (!SuperClass)
  4570. return failedImport(
  4571. "Cannot infer register class from EXTRACT_SUBREG operand #0");
  4572. auto SubIdx = inferSubRegIndexForNode(Dst->getChild(1));
  4573. if (!SubIdx)
  4574. return failedImport("EXTRACT_SUBREG child #1 is not a subreg index");
  4575. // It would be nice to leave this constraint implicit but we're required
  4576. // to pick a register class so constrain the result to a register class
  4577. // that can hold the correct MVT.
  4578. //
  4579. // FIXME: This may introduce an extra copy if the chosen class doesn't
  4580. // actually contain the subregisters.
  4581. assert(Src->getExtTypes().size() == 1 &&
  4582. "Expected Src of EXTRACT_SUBREG to have one result type");
  4583. const auto SrcRCDstRCPair =
  4584. (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
  4585. if (!SrcRCDstRCPair) {
  4586. return failedImport("subreg index is incompatible "
  4587. "with inferred reg class");
  4588. }
  4589. assert(SrcRCDstRCPair->second && "Couldn't find a matching subclass");
  4590. M.addAction<ConstrainOperandToRegClassAction>(0, 0, *SrcRCDstRCPair->second);
  4591. M.addAction<ConstrainOperandToRegClassAction>(0, 1, *SrcRCDstRCPair->first);
  4592. // We're done with this pattern! It's eligible for GISel emission; return
  4593. // it.
  4594. ++NumPatternImported;
  4595. return std::move(M);
  4596. }
  4597. if (DstIName == "INSERT_SUBREG") {
  4598. assert(Src->getExtTypes().size() == 1 &&
  4599. "Expected Src of INSERT_SUBREG to have one result type");
  4600. // We need to constrain the destination, a super regsister source, and a
  4601. // subregister source.
  4602. auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
  4603. if (!SubClass)
  4604. return failedImport(
  4605. "Cannot infer register class from INSERT_SUBREG operand #1");
  4606. auto SuperClass = inferSuperRegisterClassForNode(
  4607. Src->getExtType(0), Dst->getChild(0), Dst->getChild(2));
  4608. if (!SuperClass)
  4609. return failedImport(
  4610. "Cannot infer register class for INSERT_SUBREG operand #0");
  4611. M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
  4612. M.addAction<ConstrainOperandToRegClassAction>(0, 1, **SuperClass);
  4613. M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
  4614. ++NumPatternImported;
  4615. return std::move(M);
  4616. }
  4617. if (DstIName == "SUBREG_TO_REG") {
  4618. // We need to constrain the destination and subregister source.
  4619. assert(Src->getExtTypes().size() == 1 &&
  4620. "Expected Src of SUBREG_TO_REG to have one result type");
  4621. // Attempt to infer the subregister source from the first child. If it has
  4622. // an explicitly given register class, we'll use that. Otherwise, we will
  4623. // fail.
  4624. auto SubClass = inferRegClassFromPattern(Dst->getChild(1));
  4625. if (!SubClass)
  4626. return failedImport(
  4627. "Cannot infer register class from SUBREG_TO_REG child #1");
  4628. // We don't have a child to look at that might have a super register node.
  4629. auto SuperClass =
  4630. inferSuperRegisterClass(Src->getExtType(0), Dst->getChild(2));
  4631. if (!SuperClass)
  4632. return failedImport(
  4633. "Cannot infer register class for SUBREG_TO_REG operand #0");
  4634. M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
  4635. M.addAction<ConstrainOperandToRegClassAction>(0, 2, **SubClass);
  4636. ++NumPatternImported;
  4637. return std::move(M);
  4638. }
  4639. if (DstIName == "REG_SEQUENCE") {
  4640. auto SuperClass = inferRegClassFromPattern(Dst->getChild(0));
  4641. M.addAction<ConstrainOperandToRegClassAction>(0, 0, **SuperClass);
  4642. unsigned Num = Dst->getNumChildren();
  4643. for (unsigned I = 1; I != Num; I += 2) {
  4644. TreePatternNode *SubRegChild = Dst->getChild(I + 1);
  4645. auto SubIdx = inferSubRegIndexForNode(SubRegChild);
  4646. if (!SubIdx)
  4647. return failedImport("REG_SEQUENCE child is not a subreg index");
  4648. const auto SrcRCDstRCPair =
  4649. (*SuperClass)->getMatchingSubClassWithSubRegs(CGRegs, *SubIdx);
  4650. M.addAction<ConstrainOperandToRegClassAction>(0, I,
  4651. *SrcRCDstRCPair->second);
  4652. }
  4653. ++NumPatternImported;
  4654. return std::move(M);
  4655. }
  4656. M.addAction<ConstrainOperandsToDefinitionAction>(0);
  4657. // We're done with this pattern! It's eligible for GISel emission; return it.
  4658. ++NumPatternImported;
  4659. return std::move(M);
  4660. }
  4661. // Emit imm predicate table and an enum to reference them with.
  4662. // The 'Predicate_' part of the name is redundant but eliminating it is more
  4663. // trouble than it's worth.
  4664. void GlobalISelEmitter::emitCxxPredicateFns(
  4665. raw_ostream &OS, StringRef CodeFieldName, StringRef TypeIdentifier,
  4666. StringRef ArgType, StringRef ArgName, StringRef AdditionalArgs,
  4667. StringRef AdditionalDeclarations,
  4668. std::function<bool(const Record *R)> Filter) {
  4669. std::vector<const Record *> MatchedRecords;
  4670. const auto &Defs = RK.getAllDerivedDefinitions("PatFrags");
  4671. std::copy_if(Defs.begin(), Defs.end(), std::back_inserter(MatchedRecords),
  4672. [&](Record *Record) {
  4673. return !Record->getValueAsString(CodeFieldName).empty() &&
  4674. Filter(Record);
  4675. });
  4676. if (!MatchedRecords.empty()) {
  4677. OS << "// PatFrag predicates.\n"
  4678. << "enum {\n";
  4679. std::string EnumeratorSeparator =
  4680. (" = GIPFP_" + TypeIdentifier + "_Invalid + 1,\n").str();
  4681. for (const auto *Record : MatchedRecords) {
  4682. OS << " GIPFP_" << TypeIdentifier << "_Predicate_" << Record->getName()
  4683. << EnumeratorSeparator;
  4684. EnumeratorSeparator = ",\n";
  4685. }
  4686. OS << "};\n";
  4687. }
  4688. OS << "bool " << Target.getName() << "InstructionSelector::test" << ArgName
  4689. << "Predicate_" << TypeIdentifier << "(unsigned PredicateID, " << ArgType << " "
  4690. << ArgName << AdditionalArgs <<") const {\n"
  4691. << AdditionalDeclarations;
  4692. if (!AdditionalDeclarations.empty())
  4693. OS << "\n";
  4694. if (!MatchedRecords.empty())
  4695. OS << " switch (PredicateID) {\n";
  4696. for (const auto *Record : MatchedRecords) {
  4697. OS << " case GIPFP_" << TypeIdentifier << "_Predicate_"
  4698. << Record->getName() << ": {\n"
  4699. << " " << Record->getValueAsString(CodeFieldName) << "\n"
  4700. << " llvm_unreachable(\"" << CodeFieldName
  4701. << " should have returned\");\n"
  4702. << " return false;\n"
  4703. << " }\n";
  4704. }
  4705. if (!MatchedRecords.empty())
  4706. OS << " }\n";
  4707. OS << " llvm_unreachable(\"Unknown predicate\");\n"
  4708. << " return false;\n"
  4709. << "}\n";
  4710. }
  4711. void GlobalISelEmitter::emitImmPredicateFns(
  4712. raw_ostream &OS, StringRef TypeIdentifier, StringRef ArgType,
  4713. std::function<bool(const Record *R)> Filter) {
  4714. return emitCxxPredicateFns(OS, "ImmediateCode", TypeIdentifier, ArgType,
  4715. "Imm", "", "", Filter);
  4716. }
  4717. void GlobalISelEmitter::emitMIPredicateFns(raw_ostream &OS) {
  4718. return emitCxxPredicateFns(
  4719. OS, "GISelPredicateCode", "MI", "const MachineInstr &", "MI",
  4720. ", const std::array<const MachineOperand *, 3> &Operands",
  4721. " const MachineFunction &MF = *MI.getParent()->getParent();\n"
  4722. " const MachineRegisterInfo &MRI = MF.getRegInfo();\n"
  4723. " (void)MRI;",
  4724. [](const Record *R) { return true; });
  4725. }
  4726. template <class GroupT>
  4727. std::vector<Matcher *> GlobalISelEmitter::optimizeRules(
  4728. ArrayRef<Matcher *> Rules,
  4729. std::vector<std::unique_ptr<Matcher>> &MatcherStorage) {
  4730. std::vector<Matcher *> OptRules;
  4731. std::unique_ptr<GroupT> CurrentGroup = std::make_unique<GroupT>();
  4732. assert(CurrentGroup->empty() && "Newly created group isn't empty!");
  4733. unsigned NumGroups = 0;
  4734. auto ProcessCurrentGroup = [&]() {
  4735. if (CurrentGroup->empty())
  4736. // An empty group is good to be reused:
  4737. return;
  4738. // If the group isn't large enough to provide any benefit, move all the
  4739. // added rules out of it and make sure to re-create the group to properly
  4740. // re-initialize it:
  4741. if (CurrentGroup->size() < 2)
  4742. append_range(OptRules, CurrentGroup->matchers());
  4743. else {
  4744. CurrentGroup->finalize();
  4745. OptRules.push_back(CurrentGroup.get());
  4746. MatcherStorage.emplace_back(std::move(CurrentGroup));
  4747. ++NumGroups;
  4748. }
  4749. CurrentGroup = std::make_unique<GroupT>();
  4750. };
  4751. for (Matcher *Rule : Rules) {
  4752. // Greedily add as many matchers as possible to the current group:
  4753. if (CurrentGroup->addMatcher(*Rule))
  4754. continue;
  4755. ProcessCurrentGroup();
  4756. assert(CurrentGroup->empty() && "A group wasn't properly re-initialized");
  4757. // Try to add the pending matcher to a newly created empty group:
  4758. if (!CurrentGroup->addMatcher(*Rule))
  4759. // If we couldn't add the matcher to an empty group, that group type
  4760. // doesn't support that kind of matchers at all, so just skip it:
  4761. OptRules.push_back(Rule);
  4762. }
  4763. ProcessCurrentGroup();
  4764. LLVM_DEBUG(dbgs() << "NumGroups: " << NumGroups << "\n");
  4765. (void) NumGroups;
  4766. assert(CurrentGroup->empty() && "The last group wasn't properly processed");
  4767. return OptRules;
  4768. }
  4769. MatchTable
  4770. GlobalISelEmitter::buildMatchTable(MutableArrayRef<RuleMatcher> Rules,
  4771. bool Optimize, bool WithCoverage) {
  4772. std::vector<Matcher *> InputRules;
  4773. for (Matcher &Rule : Rules)
  4774. InputRules.push_back(&Rule);
  4775. if (!Optimize)
  4776. return MatchTable::buildTable(InputRules, WithCoverage);
  4777. unsigned CurrentOrdering = 0;
  4778. StringMap<unsigned> OpcodeOrder;
  4779. for (RuleMatcher &Rule : Rules) {
  4780. const StringRef Opcode = Rule.getOpcode();
  4781. assert(!Opcode.empty() && "Didn't expect an undefined opcode");
  4782. if (OpcodeOrder.count(Opcode) == 0)
  4783. OpcodeOrder[Opcode] = CurrentOrdering++;
  4784. }
  4785. llvm::stable_sort(InputRules, [&OpcodeOrder](const Matcher *A,
  4786. const Matcher *B) {
  4787. auto *L = static_cast<const RuleMatcher *>(A);
  4788. auto *R = static_cast<const RuleMatcher *>(B);
  4789. return std::make_tuple(OpcodeOrder[L->getOpcode()], L->getNumOperands()) <
  4790. std::make_tuple(OpcodeOrder[R->getOpcode()], R->getNumOperands());
  4791. });
  4792. for (Matcher *Rule : InputRules)
  4793. Rule->optimize();
  4794. std::vector<std::unique_ptr<Matcher>> MatcherStorage;
  4795. std::vector<Matcher *> OptRules =
  4796. optimizeRules<GroupMatcher>(InputRules, MatcherStorage);
  4797. for (Matcher *Rule : OptRules)
  4798. Rule->optimize();
  4799. OptRules = optimizeRules<SwitchMatcher>(OptRules, MatcherStorage);
  4800. return MatchTable::buildTable(OptRules, WithCoverage);
  4801. }
  4802. void GroupMatcher::optimize() {
  4803. // Make sure we only sort by a specific predicate within a range of rules that
  4804. // all have that predicate checked against a specific value (not a wildcard):
  4805. auto F = Matchers.begin();
  4806. auto T = F;
  4807. auto E = Matchers.end();
  4808. while (T != E) {
  4809. while (T != E) {
  4810. auto *R = static_cast<RuleMatcher *>(*T);
  4811. if (!R->getFirstConditionAsRootType().get().isValid())
  4812. break;
  4813. ++T;
  4814. }
  4815. std::stable_sort(F, T, [](Matcher *A, Matcher *B) {
  4816. auto *L = static_cast<RuleMatcher *>(A);
  4817. auto *R = static_cast<RuleMatcher *>(B);
  4818. return L->getFirstConditionAsRootType() <
  4819. R->getFirstConditionAsRootType();
  4820. });
  4821. if (T != E)
  4822. F = ++T;
  4823. }
  4824. GlobalISelEmitter::optimizeRules<GroupMatcher>(Matchers, MatcherStorage)
  4825. .swap(Matchers);
  4826. GlobalISelEmitter::optimizeRules<SwitchMatcher>(Matchers, MatcherStorage)
  4827. .swap(Matchers);
  4828. }
  4829. void GlobalISelEmitter::run(raw_ostream &OS) {
  4830. if (!UseCoverageFile.empty()) {
  4831. RuleCoverage = CodeGenCoverage();
  4832. auto RuleCoverageBufOrErr = MemoryBuffer::getFile(UseCoverageFile);
  4833. if (!RuleCoverageBufOrErr) {
  4834. PrintWarning(SMLoc(), "Missing rule coverage data");
  4835. RuleCoverage = std::nullopt;
  4836. } else {
  4837. if (!RuleCoverage->parse(*RuleCoverageBufOrErr.get(), Target.getName())) {
  4838. PrintWarning(SMLoc(), "Ignoring invalid or missing rule coverage data");
  4839. RuleCoverage = std::nullopt;
  4840. }
  4841. }
  4842. }
  4843. // Track the run-time opcode values
  4844. gatherOpcodeValues();
  4845. // Track the run-time LLT ID values
  4846. gatherTypeIDValues();
  4847. // Track the GINodeEquiv definitions.
  4848. gatherNodeEquivs();
  4849. emitSourceFileHeader(("Global Instruction Selector for the " +
  4850. Target.getName() + " target").str(), OS);
  4851. std::vector<RuleMatcher> Rules;
  4852. // Look through the SelectionDAG patterns we found, possibly emitting some.
  4853. for (const PatternToMatch &Pat : CGP.ptms()) {
  4854. ++NumPatternTotal;
  4855. auto MatcherOrErr = runOnPattern(Pat);
  4856. // The pattern analysis can fail, indicating an unsupported pattern.
  4857. // Report that if we've been asked to do so.
  4858. if (auto Err = MatcherOrErr.takeError()) {
  4859. if (WarnOnSkippedPatterns) {
  4860. PrintWarning(Pat.getSrcRecord()->getLoc(),
  4861. "Skipped pattern: " + toString(std::move(Err)));
  4862. } else {
  4863. consumeError(std::move(Err));
  4864. }
  4865. ++NumPatternImportsSkipped;
  4866. continue;
  4867. }
  4868. if (RuleCoverage) {
  4869. if (RuleCoverage->isCovered(MatcherOrErr->getRuleID()))
  4870. ++NumPatternsTested;
  4871. else
  4872. PrintWarning(Pat.getSrcRecord()->getLoc(),
  4873. "Pattern is not covered by a test");
  4874. }
  4875. Rules.push_back(std::move(MatcherOrErr.get()));
  4876. }
  4877. // Comparison function to order records by name.
  4878. auto orderByName = [](const Record *A, const Record *B) {
  4879. return A->getName() < B->getName();
  4880. };
  4881. std::vector<Record *> ComplexPredicates =
  4882. RK.getAllDerivedDefinitions("GIComplexOperandMatcher");
  4883. llvm::sort(ComplexPredicates, orderByName);
  4884. std::vector<StringRef> CustomRendererFns;
  4885. transform(RK.getAllDerivedDefinitions("GICustomOperandRenderer"),
  4886. std::back_inserter(CustomRendererFns), [](const auto &Record) {
  4887. return Record->getValueAsString("RendererFn");
  4888. });
  4889. // Sort and remove duplicates to get a list of unique renderer functions, in
  4890. // case some were mentioned more than once.
  4891. llvm::sort(CustomRendererFns);
  4892. CustomRendererFns.erase(
  4893. std::unique(CustomRendererFns.begin(), CustomRendererFns.end()),
  4894. CustomRendererFns.end());
  4895. unsigned MaxTemporaries = 0;
  4896. for (const auto &Rule : Rules)
  4897. MaxTemporaries = std::max(MaxTemporaries, Rule.countRendererFns());
  4898. OS << "#ifdef GET_GLOBALISEL_PREDICATE_BITSET\n"
  4899. << "const unsigned MAX_SUBTARGET_PREDICATES = " << SubtargetFeatures.size()
  4900. << ";\n"
  4901. << "using PredicateBitset = "
  4902. "llvm::PredicateBitsetImpl<MAX_SUBTARGET_PREDICATES>;\n"
  4903. << "#endif // ifdef GET_GLOBALISEL_PREDICATE_BITSET\n\n";
  4904. OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n"
  4905. << " mutable MatcherState State;\n"
  4906. << " typedef "
  4907. "ComplexRendererFns("
  4908. << Target.getName()
  4909. << "InstructionSelector::*ComplexMatcherMemFn)(MachineOperand &) const;\n"
  4910. << " typedef void(" << Target.getName()
  4911. << "InstructionSelector::*CustomRendererFn)(MachineInstrBuilder &, const "
  4912. "MachineInstr &, int) "
  4913. "const;\n"
  4914. << " const ISelInfoTy<PredicateBitset, ComplexMatcherMemFn, "
  4915. "CustomRendererFn> "
  4916. "ISelInfo;\n";
  4917. OS << " static " << Target.getName()
  4918. << "InstructionSelector::ComplexMatcherMemFn ComplexPredicateFns[];\n"
  4919. << " static " << Target.getName()
  4920. << "InstructionSelector::CustomRendererFn CustomRenderers[];\n"
  4921. << " bool testImmPredicate_I64(unsigned PredicateID, int64_t Imm) const "
  4922. "override;\n"
  4923. << " bool testImmPredicate_APInt(unsigned PredicateID, const APInt &Imm) "
  4924. "const override;\n"
  4925. << " bool testImmPredicate_APFloat(unsigned PredicateID, const APFloat "
  4926. "&Imm) const override;\n"
  4927. << " const int64_t *getMatchTable() const override;\n"
  4928. << " bool testMIPredicate_MI(unsigned PredicateID, const MachineInstr &MI"
  4929. ", const std::array<const MachineOperand *, 3> &Operands) "
  4930. "const override;\n"
  4931. << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_DECL\n\n";
  4932. OS << "#ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n"
  4933. << ", State(" << MaxTemporaries << "),\n"
  4934. << "ISelInfo(TypeObjects, NumTypeObjects, FeatureBitsets"
  4935. << ", ComplexPredicateFns, CustomRenderers)\n"
  4936. << "#endif // ifdef GET_GLOBALISEL_TEMPORARIES_INIT\n\n";
  4937. OS << "#ifdef GET_GLOBALISEL_IMPL\n";
  4938. SubtargetFeatureInfo::emitSubtargetFeatureBitEnumeration(SubtargetFeatures,
  4939. OS);
  4940. // Separate subtarget features by how often they must be recomputed.
  4941. SubtargetFeatureInfoMap ModuleFeatures;
  4942. std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
  4943. std::inserter(ModuleFeatures, ModuleFeatures.end()),
  4944. [](const SubtargetFeatureInfoMap::value_type &X) {
  4945. return !X.second.mustRecomputePerFunction();
  4946. });
  4947. SubtargetFeatureInfoMap FunctionFeatures;
  4948. std::copy_if(SubtargetFeatures.begin(), SubtargetFeatures.end(),
  4949. std::inserter(FunctionFeatures, FunctionFeatures.end()),
  4950. [](const SubtargetFeatureInfoMap::value_type &X) {
  4951. return X.second.mustRecomputePerFunction();
  4952. });
  4953. SubtargetFeatureInfo::emitComputeAvailableFeatures(
  4954. Target.getName(), "InstructionSelector", "computeAvailableModuleFeatures",
  4955. ModuleFeatures, OS);
  4956. OS << "void " << Target.getName() << "InstructionSelector"
  4957. "::setupGeneratedPerFunctionState(MachineFunction &MF) {\n"
  4958. " AvailableFunctionFeatures = computeAvailableFunctionFeatures("
  4959. "(const " << Target.getName() << "Subtarget *)&MF.getSubtarget(), &MF);\n"
  4960. "}\n";
  4961. SubtargetFeatureInfo::emitComputeAvailableFeatures(
  4962. Target.getName(), "InstructionSelector",
  4963. "computeAvailableFunctionFeatures", FunctionFeatures, OS,
  4964. "const MachineFunction *MF");
  4965. // Emit a table containing the LLT objects needed by the matcher and an enum
  4966. // for the matcher to reference them with.
  4967. std::vector<LLTCodeGen> TypeObjects;
  4968. append_range(TypeObjects, KnownTypes);
  4969. llvm::sort(TypeObjects);
  4970. OS << "// LLT Objects.\n"
  4971. << "enum {\n";
  4972. for (const auto &TypeObject : TypeObjects) {
  4973. OS << " ";
  4974. TypeObject.emitCxxEnumValue(OS);
  4975. OS << ",\n";
  4976. }
  4977. OS << "};\n";
  4978. OS << "const static size_t NumTypeObjects = " << TypeObjects.size() << ";\n"
  4979. << "const static LLT TypeObjects[] = {\n";
  4980. for (const auto &TypeObject : TypeObjects) {
  4981. OS << " ";
  4982. TypeObject.emitCxxConstructorCall(OS);
  4983. OS << ",\n";
  4984. }
  4985. OS << "};\n\n";
  4986. // Emit a table containing the PredicateBitsets objects needed by the matcher
  4987. // and an enum for the matcher to reference them with.
  4988. std::vector<std::vector<Record *>> FeatureBitsets;
  4989. FeatureBitsets.reserve(Rules.size());
  4990. for (auto &Rule : Rules)
  4991. FeatureBitsets.push_back(Rule.getRequiredFeatures());
  4992. llvm::sort(FeatureBitsets, [&](const std::vector<Record *> &A,
  4993. const std::vector<Record *> &B) {
  4994. if (A.size() < B.size())
  4995. return true;
  4996. if (A.size() > B.size())
  4997. return false;
  4998. for (auto Pair : zip(A, B)) {
  4999. if (std::get<0>(Pair)->getName() < std::get<1>(Pair)->getName())
  5000. return true;
  5001. if (std::get<0>(Pair)->getName() > std::get<1>(Pair)->getName())
  5002. return false;
  5003. }
  5004. return false;
  5005. });
  5006. FeatureBitsets.erase(
  5007. std::unique(FeatureBitsets.begin(), FeatureBitsets.end()),
  5008. FeatureBitsets.end());
  5009. OS << "// Feature bitsets.\n"
  5010. << "enum {\n"
  5011. << " GIFBS_Invalid,\n";
  5012. for (const auto &FeatureBitset : FeatureBitsets) {
  5013. if (FeatureBitset.empty())
  5014. continue;
  5015. OS << " " << getNameForFeatureBitset(FeatureBitset) << ",\n";
  5016. }
  5017. OS << "};\n"
  5018. << "const static PredicateBitset FeatureBitsets[] {\n"
  5019. << " {}, // GIFBS_Invalid\n";
  5020. for (const auto &FeatureBitset : FeatureBitsets) {
  5021. if (FeatureBitset.empty())
  5022. continue;
  5023. OS << " {";
  5024. for (const auto &Feature : FeatureBitset) {
  5025. const auto &I = SubtargetFeatures.find(Feature);
  5026. assert(I != SubtargetFeatures.end() && "Didn't import predicate?");
  5027. OS << I->second.getEnumBitName() << ", ";
  5028. }
  5029. OS << "},\n";
  5030. }
  5031. OS << "};\n\n";
  5032. // Emit complex predicate table and an enum to reference them with.
  5033. OS << "// ComplexPattern predicates.\n"
  5034. << "enum {\n"
  5035. << " GICP_Invalid,\n";
  5036. for (const auto &Record : ComplexPredicates)
  5037. OS << " GICP_" << Record->getName() << ",\n";
  5038. OS << "};\n"
  5039. << "// See constructor for table contents\n\n";
  5040. emitImmPredicateFns(OS, "I64", "int64_t", [](const Record *R) {
  5041. bool Unset;
  5042. return !R->getValueAsBitOrUnset("IsAPFloat", Unset) &&
  5043. !R->getValueAsBit("IsAPInt");
  5044. });
  5045. emitImmPredicateFns(OS, "APFloat", "const APFloat &", [](const Record *R) {
  5046. bool Unset;
  5047. return R->getValueAsBitOrUnset("IsAPFloat", Unset);
  5048. });
  5049. emitImmPredicateFns(OS, "APInt", "const APInt &", [](const Record *R) {
  5050. return R->getValueAsBit("IsAPInt");
  5051. });
  5052. emitMIPredicateFns(OS);
  5053. OS << "\n";
  5054. OS << Target.getName() << "InstructionSelector::ComplexMatcherMemFn\n"
  5055. << Target.getName() << "InstructionSelector::ComplexPredicateFns[] = {\n"
  5056. << " nullptr, // GICP_Invalid\n";
  5057. for (const auto &Record : ComplexPredicates)
  5058. OS << " &" << Target.getName()
  5059. << "InstructionSelector::" << Record->getValueAsString("MatcherFn")
  5060. << ", // " << Record->getName() << "\n";
  5061. OS << "};\n\n";
  5062. OS << "// Custom renderers.\n"
  5063. << "enum {\n"
  5064. << " GICR_Invalid,\n";
  5065. for (const auto &Fn : CustomRendererFns)
  5066. OS << " GICR_" << Fn << ",\n";
  5067. OS << "};\n";
  5068. OS << Target.getName() << "InstructionSelector::CustomRendererFn\n"
  5069. << Target.getName() << "InstructionSelector::CustomRenderers[] = {\n"
  5070. << " nullptr, // GICR_Invalid\n";
  5071. for (const auto &Fn : CustomRendererFns)
  5072. OS << " &" << Target.getName() << "InstructionSelector::" << Fn << ",\n";
  5073. OS << "};\n\n";
  5074. llvm::stable_sort(Rules, [&](const RuleMatcher &A, const RuleMatcher &B) {
  5075. int ScoreA = RuleMatcherScores[A.getRuleID()];
  5076. int ScoreB = RuleMatcherScores[B.getRuleID()];
  5077. if (ScoreA > ScoreB)
  5078. return true;
  5079. if (ScoreB > ScoreA)
  5080. return false;
  5081. if (A.isHigherPriorityThan(B)) {
  5082. assert(!B.isHigherPriorityThan(A) && "Cannot be more important "
  5083. "and less important at "
  5084. "the same time");
  5085. return true;
  5086. }
  5087. return false;
  5088. });
  5089. OS << "bool " << Target.getName()
  5090. << "InstructionSelector::selectImpl(MachineInstr &I, CodeGenCoverage "
  5091. "&CoverageInfo) const {\n"
  5092. << " MachineFunction &MF = *I.getParent()->getParent();\n"
  5093. << " MachineRegisterInfo &MRI = MF.getRegInfo();\n"
  5094. << " const PredicateBitset AvailableFeatures = getAvailableFeatures();\n"
  5095. << " NewMIVector OutMIs;\n"
  5096. << " State.MIs.clear();\n"
  5097. << " State.MIs.push_back(&I);\n\n"
  5098. << " if (executeMatchTable(*this, OutMIs, State, ISelInfo"
  5099. << ", getMatchTable(), TII, MRI, TRI, RBI, AvailableFeatures"
  5100. << ", CoverageInfo)) {\n"
  5101. << " return true;\n"
  5102. << " }\n\n"
  5103. << " return false;\n"
  5104. << "}\n\n";
  5105. const MatchTable Table =
  5106. buildMatchTable(Rules, OptimizeMatchTable, GenerateCoverage);
  5107. OS << "const int64_t *" << Target.getName()
  5108. << "InstructionSelector::getMatchTable() const {\n";
  5109. Table.emitDeclaration(OS);
  5110. OS << " return ";
  5111. Table.emitUse(OS);
  5112. OS << ";\n}\n";
  5113. OS << "#endif // ifdef GET_GLOBALISEL_IMPL\n";
  5114. OS << "#ifdef GET_GLOBALISEL_PREDICATES_DECL\n"
  5115. << "PredicateBitset AvailableModuleFeatures;\n"
  5116. << "mutable PredicateBitset AvailableFunctionFeatures;\n"
  5117. << "PredicateBitset getAvailableFeatures() const {\n"
  5118. << " return AvailableModuleFeatures | AvailableFunctionFeatures;\n"
  5119. << "}\n"
  5120. << "PredicateBitset\n"
  5121. << "computeAvailableModuleFeatures(const " << Target.getName()
  5122. << "Subtarget *Subtarget) const;\n"
  5123. << "PredicateBitset\n"
  5124. << "computeAvailableFunctionFeatures(const " << Target.getName()
  5125. << "Subtarget *Subtarget,\n"
  5126. << " const MachineFunction *MF) const;\n"
  5127. << "void setupGeneratedPerFunctionState(MachineFunction &MF) override;\n"
  5128. << "#endif // ifdef GET_GLOBALISEL_PREDICATES_DECL\n";
  5129. OS << "#ifdef GET_GLOBALISEL_PREDICATES_INIT\n"
  5130. << "AvailableModuleFeatures(computeAvailableModuleFeatures(&STI)),\n"
  5131. << "AvailableFunctionFeatures()\n"
  5132. << "#endif // ifdef GET_GLOBALISEL_PREDICATES_INIT\n";
  5133. }
  5134. void GlobalISelEmitter::declareSubtargetFeature(Record *Predicate) {
  5135. if (SubtargetFeatures.count(Predicate) == 0)
  5136. SubtargetFeatures.emplace(
  5137. Predicate, SubtargetFeatureInfo(Predicate, SubtargetFeatures.size()));
  5138. }
  5139. void RuleMatcher::optimize() {
  5140. for (auto &Item : InsnVariableIDs) {
  5141. InstructionMatcher &InsnMatcher = *Item.first;
  5142. for (auto &OM : InsnMatcher.operands()) {
  5143. // Complex Patterns are usually expensive and they relatively rarely fail
  5144. // on their own: more often we end up throwing away all the work done by a
  5145. // matching part of a complex pattern because some other part of the
  5146. // enclosing pattern didn't match. All of this makes it beneficial to
  5147. // delay complex patterns until the very end of the rule matching,
  5148. // especially for targets having lots of complex patterns.
  5149. for (auto &OP : OM->predicates())
  5150. if (isa<ComplexPatternOperandMatcher>(OP))
  5151. EpilogueMatchers.emplace_back(std::move(OP));
  5152. OM->eraseNullPredicates();
  5153. }
  5154. InsnMatcher.optimize();
  5155. }
  5156. llvm::sort(EpilogueMatchers, [](const std::unique_ptr<PredicateMatcher> &L,
  5157. const std::unique_ptr<PredicateMatcher> &R) {
  5158. return std::make_tuple(L->getKind(), L->getInsnVarID(), L->getOpIdx()) <
  5159. std::make_tuple(R->getKind(), R->getInsnVarID(), R->getOpIdx());
  5160. });
  5161. }
  5162. bool RuleMatcher::hasFirstCondition() const {
  5163. if (insnmatchers_empty())
  5164. return false;
  5165. InstructionMatcher &Matcher = insnmatchers_front();
  5166. if (!Matcher.predicates_empty())
  5167. return true;
  5168. for (auto &OM : Matcher.operands())
  5169. for (auto &OP : OM->predicates())
  5170. if (!isa<InstructionOperandMatcher>(OP))
  5171. return true;
  5172. return false;
  5173. }
  5174. const PredicateMatcher &RuleMatcher::getFirstCondition() const {
  5175. assert(!insnmatchers_empty() &&
  5176. "Trying to get a condition from an empty RuleMatcher");
  5177. InstructionMatcher &Matcher = insnmatchers_front();
  5178. if (!Matcher.predicates_empty())
  5179. return **Matcher.predicates_begin();
  5180. // If there is no more predicate on the instruction itself, look at its
  5181. // operands.
  5182. for (auto &OM : Matcher.operands())
  5183. for (auto &OP : OM->predicates())
  5184. if (!isa<InstructionOperandMatcher>(OP))
  5185. return *OP;
  5186. llvm_unreachable("Trying to get a condition from an InstructionMatcher with "
  5187. "no conditions");
  5188. }
  5189. std::unique_ptr<PredicateMatcher> RuleMatcher::popFirstCondition() {
  5190. assert(!insnmatchers_empty() &&
  5191. "Trying to pop a condition from an empty RuleMatcher");
  5192. InstructionMatcher &Matcher = insnmatchers_front();
  5193. if (!Matcher.predicates_empty())
  5194. return Matcher.predicates_pop_front();
  5195. // If there is no more predicate on the instruction itself, look at its
  5196. // operands.
  5197. for (auto &OM : Matcher.operands())
  5198. for (auto &OP : OM->predicates())
  5199. if (!isa<InstructionOperandMatcher>(OP)) {
  5200. std::unique_ptr<PredicateMatcher> Result = std::move(OP);
  5201. OM->eraseNullPredicates();
  5202. return Result;
  5203. }
  5204. llvm_unreachable("Trying to pop a condition from an InstructionMatcher with "
  5205. "no conditions");
  5206. }
  5207. bool GroupMatcher::candidateConditionMatches(
  5208. const PredicateMatcher &Predicate) const {
  5209. if (empty()) {
  5210. // Sharing predicates for nested instructions is not supported yet as we
  5211. // currently don't hoist the GIM_RecordInsn's properly, therefore we can
  5212. // only work on the original root instruction (InsnVarID == 0):
  5213. if (Predicate.getInsnVarID() != 0)
  5214. return false;
  5215. // ... otherwise an empty group can handle any predicate with no specific
  5216. // requirements:
  5217. return true;
  5218. }
  5219. const Matcher &Representative = **Matchers.begin();
  5220. const auto &RepresentativeCondition = Representative.getFirstCondition();
  5221. // ... if not empty, the group can only accomodate matchers with the exact
  5222. // same first condition:
  5223. return Predicate.isIdentical(RepresentativeCondition);
  5224. }
  5225. bool GroupMatcher::addMatcher(Matcher &Candidate) {
  5226. if (!Candidate.hasFirstCondition())
  5227. return false;
  5228. const PredicateMatcher &Predicate = Candidate.getFirstCondition();
  5229. if (!candidateConditionMatches(Predicate))
  5230. return false;
  5231. Matchers.push_back(&Candidate);
  5232. return true;
  5233. }
  5234. void GroupMatcher::finalize() {
  5235. assert(Conditions.empty() && "Already finalized?");
  5236. if (empty())
  5237. return;
  5238. Matcher &FirstRule = **Matchers.begin();
  5239. for (;;) {
  5240. // All the checks are expected to succeed during the first iteration:
  5241. for (const auto &Rule : Matchers)
  5242. if (!Rule->hasFirstCondition())
  5243. return;
  5244. const auto &FirstCondition = FirstRule.getFirstCondition();
  5245. for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
  5246. if (!Matchers[I]->getFirstCondition().isIdentical(FirstCondition))
  5247. return;
  5248. Conditions.push_back(FirstRule.popFirstCondition());
  5249. for (unsigned I = 1, E = Matchers.size(); I < E; ++I)
  5250. Matchers[I]->popFirstCondition();
  5251. }
  5252. }
  5253. void GroupMatcher::emit(MatchTable &Table) {
  5254. unsigned LabelID = ~0U;
  5255. if (!Conditions.empty()) {
  5256. LabelID = Table.allocateLabelID();
  5257. Table << MatchTable::Opcode("GIM_Try", +1)
  5258. << MatchTable::Comment("On fail goto")
  5259. << MatchTable::JumpTarget(LabelID) << MatchTable::LineBreak;
  5260. }
  5261. for (auto &Condition : Conditions)
  5262. Condition->emitPredicateOpcodes(
  5263. Table, *static_cast<RuleMatcher *>(*Matchers.begin()));
  5264. for (const auto &M : Matchers)
  5265. M->emit(Table);
  5266. // Exit the group
  5267. if (!Conditions.empty())
  5268. Table << MatchTable::Opcode("GIM_Reject", -1) << MatchTable::LineBreak
  5269. << MatchTable::Label(LabelID);
  5270. }
  5271. bool SwitchMatcher::isSupportedPredicateType(const PredicateMatcher &P) {
  5272. return isa<InstructionOpcodeMatcher>(P) || isa<LLTOperandMatcher>(P);
  5273. }
  5274. bool SwitchMatcher::candidateConditionMatches(
  5275. const PredicateMatcher &Predicate) const {
  5276. if (empty()) {
  5277. // Sharing predicates for nested instructions is not supported yet as we
  5278. // currently don't hoist the GIM_RecordInsn's properly, therefore we can
  5279. // only work on the original root instruction (InsnVarID == 0):
  5280. if (Predicate.getInsnVarID() != 0)
  5281. return false;
  5282. // ... while an attempt to add even a root matcher to an empty SwitchMatcher
  5283. // could fail as not all the types of conditions are supported:
  5284. if (!isSupportedPredicateType(Predicate))
  5285. return false;
  5286. // ... or the condition might not have a proper implementation of
  5287. // getValue() / isIdenticalDownToValue() yet:
  5288. if (!Predicate.hasValue())
  5289. return false;
  5290. // ... otherwise an empty Switch can accomodate the condition with no
  5291. // further requirements:
  5292. return true;
  5293. }
  5294. const Matcher &CaseRepresentative = **Matchers.begin();
  5295. const auto &RepresentativeCondition = CaseRepresentative.getFirstCondition();
  5296. // Switch-cases must share the same kind of condition and path to the value it
  5297. // checks:
  5298. if (!Predicate.isIdenticalDownToValue(RepresentativeCondition))
  5299. return false;
  5300. const auto Value = Predicate.getValue();
  5301. // ... but be unique with respect to the actual value they check:
  5302. return Values.count(Value) == 0;
  5303. }
  5304. bool SwitchMatcher::addMatcher(Matcher &Candidate) {
  5305. if (!Candidate.hasFirstCondition())
  5306. return false;
  5307. const PredicateMatcher &Predicate = Candidate.getFirstCondition();
  5308. if (!candidateConditionMatches(Predicate))
  5309. return false;
  5310. const auto Value = Predicate.getValue();
  5311. Values.insert(Value);
  5312. Matchers.push_back(&Candidate);
  5313. return true;
  5314. }
  5315. void SwitchMatcher::finalize() {
  5316. assert(Condition == nullptr && "Already finalized");
  5317. assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
  5318. if (empty())
  5319. return;
  5320. llvm::stable_sort(Matchers, [](const Matcher *L, const Matcher *R) {
  5321. return L->getFirstCondition().getValue() <
  5322. R->getFirstCondition().getValue();
  5323. });
  5324. Condition = Matchers[0]->popFirstCondition();
  5325. for (unsigned I = 1, E = Values.size(); I < E; ++I)
  5326. Matchers[I]->popFirstCondition();
  5327. }
  5328. void SwitchMatcher::emitPredicateSpecificOpcodes(const PredicateMatcher &P,
  5329. MatchTable &Table) {
  5330. assert(isSupportedPredicateType(P) && "Predicate type is not supported");
  5331. if (const auto *Condition = dyn_cast<InstructionOpcodeMatcher>(&P)) {
  5332. Table << MatchTable::Opcode("GIM_SwitchOpcode") << MatchTable::Comment("MI")
  5333. << MatchTable::IntValue(Condition->getInsnVarID());
  5334. return;
  5335. }
  5336. if (const auto *Condition = dyn_cast<LLTOperandMatcher>(&P)) {
  5337. Table << MatchTable::Opcode("GIM_SwitchType") << MatchTable::Comment("MI")
  5338. << MatchTable::IntValue(Condition->getInsnVarID())
  5339. << MatchTable::Comment("Op")
  5340. << MatchTable::IntValue(Condition->getOpIdx());
  5341. return;
  5342. }
  5343. llvm_unreachable("emitPredicateSpecificOpcodes is broken: can not handle a "
  5344. "predicate type that is claimed to be supported");
  5345. }
  5346. void SwitchMatcher::emit(MatchTable &Table) {
  5347. assert(Values.size() == Matchers.size() && "Broken SwitchMatcher");
  5348. if (empty())
  5349. return;
  5350. assert(Condition != nullptr &&
  5351. "Broken SwitchMatcher, hasn't been finalized?");
  5352. std::vector<unsigned> LabelIDs(Values.size());
  5353. std::generate(LabelIDs.begin(), LabelIDs.end(),
  5354. [&Table]() { return Table.allocateLabelID(); });
  5355. const unsigned Default = Table.allocateLabelID();
  5356. const int64_t LowerBound = Values.begin()->getRawValue();
  5357. const int64_t UpperBound = Values.rbegin()->getRawValue() + 1;
  5358. emitPredicateSpecificOpcodes(*Condition, Table);
  5359. Table << MatchTable::Comment("[") << MatchTable::IntValue(LowerBound)
  5360. << MatchTable::IntValue(UpperBound) << MatchTable::Comment(")")
  5361. << MatchTable::Comment("default:") << MatchTable::JumpTarget(Default);
  5362. int64_t J = LowerBound;
  5363. auto VI = Values.begin();
  5364. for (unsigned I = 0, E = Values.size(); I < E; ++I) {
  5365. auto V = *VI++;
  5366. while (J++ < V.getRawValue())
  5367. Table << MatchTable::IntValue(0);
  5368. V.turnIntoComment();
  5369. Table << MatchTable::LineBreak << V << MatchTable::JumpTarget(LabelIDs[I]);
  5370. }
  5371. Table << MatchTable::LineBreak;
  5372. for (unsigned I = 0, E = Values.size(); I < E; ++I) {
  5373. Table << MatchTable::Label(LabelIDs[I]);
  5374. Matchers[I]->emit(Table);
  5375. Table << MatchTable::Opcode("GIM_Reject") << MatchTable::LineBreak;
  5376. }
  5377. Table << MatchTable::Label(Default);
  5378. }
  5379. unsigned OperandMatcher::getInsnVarID() const { return Insn.getInsnVarID(); }
  5380. } // end anonymous namespace
  5381. //===----------------------------------------------------------------------===//
  5382. namespace llvm {
  5383. void EmitGlobalISel(RecordKeeper &RK, raw_ostream &OS) {
  5384. GlobalISelEmitter(RK).run(OS);
  5385. }
  5386. } // End llvm namespace