RISCVISelLowering.cpp 555 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257
  1. //===-- RISCVISelLowering.cpp - RISCV DAG Lowering Implementation --------===//
  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. // This file defines the interfaces that RISCV uses to lower LLVM code into a
  10. // selection DAG.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "RISCVISelLowering.h"
  14. #include "MCTargetDesc/RISCVMatInt.h"
  15. #include "RISCV.h"
  16. #include "RISCVMachineFunctionInfo.h"
  17. #include "RISCVRegisterInfo.h"
  18. #include "RISCVSubtarget.h"
  19. #include "RISCVTargetMachine.h"
  20. #include "llvm/ADT/SmallSet.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/Analysis/MemoryLocation.h"
  23. #include "llvm/CodeGen/MachineFrameInfo.h"
  24. #include "llvm/CodeGen/MachineFunction.h"
  25. #include "llvm/CodeGen/MachineInstrBuilder.h"
  26. #include "llvm/CodeGen/MachineJumpTableInfo.h"
  27. #include "llvm/CodeGen/MachineRegisterInfo.h"
  28. #include "llvm/CodeGen/TargetLoweringObjectFileImpl.h"
  29. #include "llvm/CodeGen/ValueTypes.h"
  30. #include "llvm/IR/DiagnosticInfo.h"
  31. #include "llvm/IR/DiagnosticPrinter.h"
  32. #include "llvm/IR/IRBuilder.h"
  33. #include "llvm/IR/IntrinsicsRISCV.h"
  34. #include "llvm/IR/PatternMatch.h"
  35. #include "llvm/Support/CommandLine.h"
  36. #include "llvm/Support/Debug.h"
  37. #include "llvm/Support/ErrorHandling.h"
  38. #include "llvm/Support/KnownBits.h"
  39. #include "llvm/Support/MathExtras.h"
  40. #include "llvm/Support/raw_ostream.h"
  41. #include <optional>
  42. using namespace llvm;
  43. #define DEBUG_TYPE "riscv-lower"
  44. STATISTIC(NumTailCalls, "Number of tail calls");
  45. static cl::opt<unsigned> ExtensionMaxWebSize(
  46. DEBUG_TYPE "-ext-max-web-size", cl::Hidden,
  47. cl::desc("Give the maximum size (in number of nodes) of the web of "
  48. "instructions that we will consider for VW expansion"),
  49. cl::init(18));
  50. static cl::opt<bool>
  51. AllowSplatInVW_W(DEBUG_TYPE "-form-vw-w-with-splat", cl::Hidden,
  52. cl::desc("Allow the formation of VW_W operations (e.g., "
  53. "VWADD_W) with splat constants"),
  54. cl::init(false));
  55. static cl::opt<unsigned> NumRepeatedDivisors(
  56. DEBUG_TYPE "-fp-repeated-divisors", cl::Hidden,
  57. cl::desc("Set the minimum number of repetitions of a divisor to allow "
  58. "transformation to multiplications by the reciprocal"),
  59. cl::init(2));
  60. RISCVTargetLowering::RISCVTargetLowering(const TargetMachine &TM,
  61. const RISCVSubtarget &STI)
  62. : TargetLowering(TM), Subtarget(STI) {
  63. if (Subtarget.isRV32E())
  64. report_fatal_error("Codegen not yet implemented for RV32E");
  65. RISCVABI::ABI ABI = Subtarget.getTargetABI();
  66. assert(ABI != RISCVABI::ABI_Unknown && "Improperly initialised target ABI");
  67. if ((ABI == RISCVABI::ABI_ILP32F || ABI == RISCVABI::ABI_LP64F) &&
  68. !Subtarget.hasStdExtF()) {
  69. errs() << "Hard-float 'f' ABI can't be used for a target that "
  70. "doesn't support the F instruction set extension (ignoring "
  71. "target-abi)\n";
  72. ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
  73. } else if ((ABI == RISCVABI::ABI_ILP32D || ABI == RISCVABI::ABI_LP64D) &&
  74. !Subtarget.hasStdExtD()) {
  75. errs() << "Hard-float 'd' ABI can't be used for a target that "
  76. "doesn't support the D instruction set extension (ignoring "
  77. "target-abi)\n";
  78. ABI = Subtarget.is64Bit() ? RISCVABI::ABI_LP64 : RISCVABI::ABI_ILP32;
  79. }
  80. switch (ABI) {
  81. default:
  82. report_fatal_error("Don't know how to lower this ABI");
  83. case RISCVABI::ABI_ILP32:
  84. case RISCVABI::ABI_ILP32F:
  85. case RISCVABI::ABI_ILP32D:
  86. case RISCVABI::ABI_LP64:
  87. case RISCVABI::ABI_LP64F:
  88. case RISCVABI::ABI_LP64D:
  89. break;
  90. }
  91. MVT XLenVT = Subtarget.getXLenVT();
  92. // Set up the register classes.
  93. addRegisterClass(XLenVT, &RISCV::GPRRegClass);
  94. if (Subtarget.hasStdExtZfhOrZfhmin())
  95. addRegisterClass(MVT::f16, &RISCV::FPR16RegClass);
  96. if (Subtarget.hasStdExtF())
  97. addRegisterClass(MVT::f32, &RISCV::FPR32RegClass);
  98. if (Subtarget.hasStdExtD())
  99. addRegisterClass(MVT::f64, &RISCV::FPR64RegClass);
  100. static const MVT::SimpleValueType BoolVecVTs[] = {
  101. MVT::nxv1i1, MVT::nxv2i1, MVT::nxv4i1, MVT::nxv8i1,
  102. MVT::nxv16i1, MVT::nxv32i1, MVT::nxv64i1};
  103. static const MVT::SimpleValueType IntVecVTs[] = {
  104. MVT::nxv1i8, MVT::nxv2i8, MVT::nxv4i8, MVT::nxv8i8, MVT::nxv16i8,
  105. MVT::nxv32i8, MVT::nxv64i8, MVT::nxv1i16, MVT::nxv2i16, MVT::nxv4i16,
  106. MVT::nxv8i16, MVT::nxv16i16, MVT::nxv32i16, MVT::nxv1i32, MVT::nxv2i32,
  107. MVT::nxv4i32, MVT::nxv8i32, MVT::nxv16i32, MVT::nxv1i64, MVT::nxv2i64,
  108. MVT::nxv4i64, MVT::nxv8i64};
  109. static const MVT::SimpleValueType F16VecVTs[] = {
  110. MVT::nxv1f16, MVT::nxv2f16, MVT::nxv4f16,
  111. MVT::nxv8f16, MVT::nxv16f16, MVT::nxv32f16};
  112. static const MVT::SimpleValueType F32VecVTs[] = {
  113. MVT::nxv1f32, MVT::nxv2f32, MVT::nxv4f32, MVT::nxv8f32, MVT::nxv16f32};
  114. static const MVT::SimpleValueType F64VecVTs[] = {
  115. MVT::nxv1f64, MVT::nxv2f64, MVT::nxv4f64, MVT::nxv8f64};
  116. if (Subtarget.hasVInstructions()) {
  117. auto addRegClassForRVV = [this](MVT VT) {
  118. // Disable the smallest fractional LMUL types if ELEN is less than
  119. // RVVBitsPerBlock.
  120. unsigned MinElts = RISCV::RVVBitsPerBlock / Subtarget.getELEN();
  121. if (VT.getVectorMinNumElements() < MinElts)
  122. return;
  123. unsigned Size = VT.getSizeInBits().getKnownMinValue();
  124. const TargetRegisterClass *RC;
  125. if (Size <= RISCV::RVVBitsPerBlock)
  126. RC = &RISCV::VRRegClass;
  127. else if (Size == 2 * RISCV::RVVBitsPerBlock)
  128. RC = &RISCV::VRM2RegClass;
  129. else if (Size == 4 * RISCV::RVVBitsPerBlock)
  130. RC = &RISCV::VRM4RegClass;
  131. else if (Size == 8 * RISCV::RVVBitsPerBlock)
  132. RC = &RISCV::VRM8RegClass;
  133. else
  134. llvm_unreachable("Unexpected size");
  135. addRegisterClass(VT, RC);
  136. };
  137. for (MVT VT : BoolVecVTs)
  138. addRegClassForRVV(VT);
  139. for (MVT VT : IntVecVTs) {
  140. if (VT.getVectorElementType() == MVT::i64 &&
  141. !Subtarget.hasVInstructionsI64())
  142. continue;
  143. addRegClassForRVV(VT);
  144. }
  145. if (Subtarget.hasVInstructionsF16())
  146. for (MVT VT : F16VecVTs)
  147. addRegClassForRVV(VT);
  148. if (Subtarget.hasVInstructionsF32())
  149. for (MVT VT : F32VecVTs)
  150. addRegClassForRVV(VT);
  151. if (Subtarget.hasVInstructionsF64())
  152. for (MVT VT : F64VecVTs)
  153. addRegClassForRVV(VT);
  154. if (Subtarget.useRVVForFixedLengthVectors()) {
  155. auto addRegClassForFixedVectors = [this](MVT VT) {
  156. MVT ContainerVT = getContainerForFixedLengthVector(VT);
  157. unsigned RCID = getRegClassIDForVecVT(ContainerVT);
  158. const RISCVRegisterInfo &TRI = *Subtarget.getRegisterInfo();
  159. addRegisterClass(VT, TRI.getRegClass(RCID));
  160. };
  161. for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
  162. if (useRVVForFixedLengthVectorVT(VT))
  163. addRegClassForFixedVectors(VT);
  164. for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
  165. if (useRVVForFixedLengthVectorVT(VT))
  166. addRegClassForFixedVectors(VT);
  167. }
  168. }
  169. // Compute derived properties from the register classes.
  170. computeRegisterProperties(STI.getRegisterInfo());
  171. setStackPointerRegisterToSaveRestore(RISCV::X2);
  172. setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, XLenVT,
  173. MVT::i1, Promote);
  174. // DAGCombiner can call isLoadExtLegal for types that aren't legal.
  175. setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, MVT::i32,
  176. MVT::i1, Promote);
  177. // TODO: add all necessary setOperationAction calls.
  178. setOperationAction(ISD::DYNAMIC_STACKALLOC, XLenVT, Expand);
  179. setOperationAction(ISD::BR_JT, MVT::Other, Expand);
  180. setOperationAction(ISD::BR_CC, XLenVT, Expand);
  181. setOperationAction(ISD::BRCOND, MVT::Other, Custom);
  182. setOperationAction(ISD::SELECT_CC, XLenVT, Expand);
  183. setCondCodeAction(ISD::SETLE, XLenVT, Expand);
  184. setCondCodeAction(ISD::SETGT, XLenVT, Custom);
  185. setCondCodeAction(ISD::SETGE, XLenVT, Expand);
  186. setCondCodeAction(ISD::SETULE, XLenVT, Expand);
  187. setCondCodeAction(ISD::SETUGT, XLenVT, Custom);
  188. setCondCodeAction(ISD::SETUGE, XLenVT, Expand);
  189. setOperationAction({ISD::STACKSAVE, ISD::STACKRESTORE}, MVT::Other, Expand);
  190. setOperationAction(ISD::VASTART, MVT::Other, Custom);
  191. setOperationAction({ISD::VAARG, ISD::VACOPY, ISD::VAEND}, MVT::Other, Expand);
  192. setOperationAction(ISD::SIGN_EXTEND_INREG, MVT::i1, Expand);
  193. setOperationAction(ISD::EH_DWARF_CFA, MVT::i32, Custom);
  194. if (!Subtarget.hasStdExtZbb())
  195. setOperationAction(ISD::SIGN_EXTEND_INREG, {MVT::i8, MVT::i16}, Expand);
  196. if (Subtarget.is64Bit()) {
  197. setOperationAction(ISD::EH_DWARF_CFA, MVT::i64, Custom);
  198. setOperationAction(ISD::LOAD, MVT::i32, Custom);
  199. setOperationAction({ISD::ADD, ISD::SUB, ISD::SHL, ISD::SRA, ISD::SRL},
  200. MVT::i32, Custom);
  201. setOperationAction({ISD::UADDO, ISD::USUBO, ISD::UADDSAT, ISD::USUBSAT},
  202. MVT::i32, Custom);
  203. } else {
  204. setLibcallName(
  205. {RTLIB::SHL_I128, RTLIB::SRL_I128, RTLIB::SRA_I128, RTLIB::MUL_I128},
  206. nullptr);
  207. setLibcallName(RTLIB::MULO_I64, nullptr);
  208. }
  209. if (!Subtarget.hasStdExtM() && !Subtarget.hasStdExtZmmul()) {
  210. setOperationAction({ISD::MUL, ISD::MULHS, ISD::MULHU}, XLenVT, Expand);
  211. } else {
  212. if (Subtarget.is64Bit()) {
  213. setOperationAction(ISD::MUL, {MVT::i32, MVT::i128}, Custom);
  214. } else {
  215. setOperationAction(ISD::MUL, MVT::i64, Custom);
  216. }
  217. }
  218. if (!Subtarget.hasStdExtM()) {
  219. setOperationAction({ISD::SDIV, ISD::UDIV, ISD::SREM, ISD::UREM},
  220. XLenVT, Expand);
  221. } else {
  222. if (Subtarget.is64Bit()) {
  223. setOperationAction({ISD::SDIV, ISD::UDIV, ISD::UREM},
  224. {MVT::i8, MVT::i16, MVT::i32}, Custom);
  225. }
  226. }
  227. setOperationAction(
  228. {ISD::SDIVREM, ISD::UDIVREM, ISD::SMUL_LOHI, ISD::UMUL_LOHI}, XLenVT,
  229. Expand);
  230. setOperationAction({ISD::SHL_PARTS, ISD::SRL_PARTS, ISD::SRA_PARTS}, XLenVT,
  231. Custom);
  232. if (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) {
  233. if (Subtarget.is64Bit())
  234. setOperationAction({ISD::ROTL, ISD::ROTR}, MVT::i32, Custom);
  235. } else {
  236. setOperationAction({ISD::ROTL, ISD::ROTR}, XLenVT, Expand);
  237. }
  238. // With Zbb we have an XLen rev8 instruction, but not GREVI. So we'll
  239. // pattern match it directly in isel.
  240. setOperationAction(ISD::BSWAP, XLenVT,
  241. (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb())
  242. ? Legal
  243. : Expand);
  244. // Zbkb can use rev8+brev8 to implement bitreverse.
  245. setOperationAction(ISD::BITREVERSE, XLenVT,
  246. Subtarget.hasStdExtZbkb() ? Custom : Expand);
  247. if (Subtarget.hasStdExtZbb()) {
  248. setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, XLenVT,
  249. Legal);
  250. if (Subtarget.is64Bit())
  251. setOperationAction(
  252. {ISD::CTTZ, ISD::CTTZ_ZERO_UNDEF, ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF},
  253. MVT::i32, Custom);
  254. } else {
  255. setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, XLenVT, Expand);
  256. }
  257. if (Subtarget.is64Bit())
  258. setOperationAction(ISD::ABS, MVT::i32, Custom);
  259. if (!Subtarget.hasVendorXVentanaCondOps())
  260. setOperationAction(ISD::SELECT, XLenVT, Custom);
  261. static const unsigned FPLegalNodeTypes[] = {
  262. ISD::FMINNUM, ISD::FMAXNUM, ISD::LRINT,
  263. ISD::LLRINT, ISD::LROUND, ISD::LLROUND,
  264. ISD::STRICT_LRINT, ISD::STRICT_LLRINT, ISD::STRICT_LROUND,
  265. ISD::STRICT_LLROUND, ISD::STRICT_FMA, ISD::STRICT_FADD,
  266. ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV,
  267. ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS};
  268. static const ISD::CondCode FPCCToExpand[] = {
  269. ISD::SETOGT, ISD::SETOGE, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
  270. ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUNE, ISD::SETGT,
  271. ISD::SETGE, ISD::SETNE, ISD::SETO, ISD::SETUO};
  272. static const unsigned FPOpToExpand[] = {
  273. ISD::FSIN, ISD::FCOS, ISD::FSINCOS, ISD::FPOW,
  274. ISD::FREM, ISD::FP16_TO_FP, ISD::FP_TO_FP16};
  275. static const unsigned FPRndMode[] = {
  276. ISD::FCEIL, ISD::FFLOOR, ISD::FTRUNC, ISD::FRINT, ISD::FROUND,
  277. ISD::FROUNDEVEN};
  278. if (Subtarget.hasStdExtZfhOrZfhmin())
  279. setOperationAction(ISD::BITCAST, MVT::i16, Custom);
  280. if (Subtarget.hasStdExtZfhOrZfhmin()) {
  281. if (Subtarget.hasStdExtZfh()) {
  282. setOperationAction(FPLegalNodeTypes, MVT::f16, Legal);
  283. setOperationAction(FPRndMode, MVT::f16, Custom);
  284. setOperationAction(ISD::SELECT, MVT::f16, Custom);
  285. } else {
  286. static const unsigned ZfhminPromoteOps[] = {
  287. ISD::FMINNUM, ISD::FMAXNUM, ISD::FADD,
  288. ISD::FSUB, ISD::FMUL, ISD::FMA,
  289. ISD::FDIV, ISD::FSQRT, ISD::FABS,
  290. ISD::FNEG, ISD::STRICT_FMA, ISD::STRICT_FADD,
  291. ISD::STRICT_FSUB, ISD::STRICT_FMUL, ISD::STRICT_FDIV,
  292. ISD::STRICT_FSQRT, ISD::STRICT_FSETCC, ISD::STRICT_FSETCCS,
  293. ISD::SETCC, ISD::FCEIL, ISD::FFLOOR,
  294. ISD::FTRUNC, ISD::FRINT, ISD::FROUND,
  295. ISD::FROUNDEVEN, ISD::SELECT};
  296. setOperationAction(ZfhminPromoteOps, MVT::f16, Promote);
  297. setOperationAction({ISD::STRICT_LRINT, ISD::STRICT_LLRINT,
  298. ISD::STRICT_LROUND, ISD::STRICT_LLROUND},
  299. MVT::f16, Legal);
  300. // FIXME: Need to promote f16 FCOPYSIGN to f32, but the
  301. // DAGCombiner::visitFP_ROUND probably needs improvements first.
  302. setOperationAction(ISD::FCOPYSIGN, MVT::f16, Expand);
  303. }
  304. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Legal);
  305. setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f32, Legal);
  306. setCondCodeAction(FPCCToExpand, MVT::f16, Expand);
  307. setOperationAction(ISD::SELECT_CC, MVT::f16, Expand);
  308. setOperationAction(ISD::BR_CC, MVT::f16, Expand);
  309. setOperationAction({ISD::FREM, ISD::FNEARBYINT, ISD::FPOW, ISD::FPOWI,
  310. ISD::FCOS, ISD::FSIN, ISD::FSINCOS, ISD::FEXP,
  311. ISD::FEXP2, ISD::FLOG, ISD::FLOG2, ISD::FLOG10},
  312. MVT::f16, Promote);
  313. // FIXME: Need to promote f16 STRICT_* to f32 libcalls, but we don't have
  314. // complete support for all operations in LegalizeDAG.
  315. setOperationAction({ISD::STRICT_FCEIL, ISD::STRICT_FFLOOR,
  316. ISD::STRICT_FNEARBYINT, ISD::STRICT_FRINT,
  317. ISD::STRICT_FROUND, ISD::STRICT_FROUNDEVEN,
  318. ISD::STRICT_FTRUNC},
  319. MVT::f16, Promote);
  320. // We need to custom promote this.
  321. if (Subtarget.is64Bit())
  322. setOperationAction(ISD::FPOWI, MVT::i32, Custom);
  323. }
  324. if (Subtarget.hasStdExtF()) {
  325. setOperationAction(FPLegalNodeTypes, MVT::f32, Legal);
  326. setOperationAction(FPRndMode, MVT::f32, Custom);
  327. setCondCodeAction(FPCCToExpand, MVT::f32, Expand);
  328. setOperationAction(ISD::SELECT_CC, MVT::f32, Expand);
  329. setOperationAction(ISD::SELECT, MVT::f32, Custom);
  330. setOperationAction(ISD::BR_CC, MVT::f32, Expand);
  331. setOperationAction(FPOpToExpand, MVT::f32, Expand);
  332. setLoadExtAction(ISD::EXTLOAD, MVT::f32, MVT::f16, Expand);
  333. setTruncStoreAction(MVT::f32, MVT::f16, Expand);
  334. }
  335. if (Subtarget.hasStdExtF() && Subtarget.is64Bit())
  336. setOperationAction(ISD::BITCAST, MVT::i32, Custom);
  337. if (Subtarget.hasStdExtD()) {
  338. setOperationAction(FPLegalNodeTypes, MVT::f64, Legal);
  339. if (Subtarget.is64Bit()) {
  340. setOperationAction(FPRndMode, MVT::f64, Custom);
  341. }
  342. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Legal);
  343. setOperationAction(ISD::STRICT_FP_EXTEND, MVT::f64, Legal);
  344. setCondCodeAction(FPCCToExpand, MVT::f64, Expand);
  345. setOperationAction(ISD::SELECT_CC, MVT::f64, Expand);
  346. setOperationAction(ISD::SELECT, MVT::f64, Custom);
  347. setOperationAction(ISD::BR_CC, MVT::f64, Expand);
  348. setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f32, Expand);
  349. setTruncStoreAction(MVT::f64, MVT::f32, Expand);
  350. setOperationAction(FPOpToExpand, MVT::f64, Expand);
  351. setLoadExtAction(ISD::EXTLOAD, MVT::f64, MVT::f16, Expand);
  352. setTruncStoreAction(MVT::f64, MVT::f16, Expand);
  353. }
  354. if (Subtarget.is64Bit())
  355. setOperationAction({ISD::FP_TO_UINT, ISD::FP_TO_SINT,
  356. ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT},
  357. MVT::i32, Custom);
  358. if (Subtarget.hasStdExtF()) {
  359. setOperationAction({ISD::FP_TO_UINT_SAT, ISD::FP_TO_SINT_SAT}, XLenVT,
  360. Custom);
  361. setOperationAction({ISD::STRICT_FP_TO_UINT, ISD::STRICT_FP_TO_SINT,
  362. ISD::STRICT_UINT_TO_FP, ISD::STRICT_SINT_TO_FP},
  363. XLenVT, Legal);
  364. setOperationAction(ISD::GET_ROUNDING, XLenVT, Custom);
  365. setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
  366. }
  367. setOperationAction({ISD::GlobalAddress, ISD::BlockAddress, ISD::ConstantPool,
  368. ISD::JumpTable},
  369. XLenVT, Custom);
  370. setOperationAction(ISD::GlobalTLSAddress, XLenVT, Custom);
  371. if (Subtarget.is64Bit())
  372. setOperationAction(ISD::Constant, MVT::i64, Custom);
  373. // TODO: On M-mode only targets, the cycle[h] CSR may not be present.
  374. // Unfortunately this can't be determined just from the ISA naming string.
  375. setOperationAction(ISD::READCYCLECOUNTER, MVT::i64,
  376. Subtarget.is64Bit() ? Legal : Custom);
  377. setOperationAction({ISD::TRAP, ISD::DEBUGTRAP}, MVT::Other, Legal);
  378. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
  379. if (Subtarget.is64Bit())
  380. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i32, Custom);
  381. if (Subtarget.hasStdExtA()) {
  382. setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
  383. setMinCmpXchgSizeInBits(32);
  384. } else if (Subtarget.hasForcedAtomics()) {
  385. setMaxAtomicSizeInBitsSupported(Subtarget.getXLen());
  386. } else {
  387. setMaxAtomicSizeInBitsSupported(0);
  388. }
  389. setOperationAction(ISD::ATOMIC_FENCE, MVT::Other, Custom);
  390. setBooleanContents(ZeroOrOneBooleanContent);
  391. if (Subtarget.hasVInstructions()) {
  392. setBooleanVectorContents(ZeroOrOneBooleanContent);
  393. setOperationAction(ISD::VSCALE, XLenVT, Custom);
  394. // RVV intrinsics may have illegal operands.
  395. // We also need to custom legalize vmv.x.s.
  396. setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
  397. {MVT::i8, MVT::i16}, Custom);
  398. if (Subtarget.is64Bit())
  399. setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i32, Custom);
  400. else
  401. setOperationAction({ISD::INTRINSIC_WO_CHAIN, ISD::INTRINSIC_W_CHAIN},
  402. MVT::i64, Custom);
  403. setOperationAction({ISD::INTRINSIC_W_CHAIN, ISD::INTRINSIC_VOID},
  404. MVT::Other, Custom);
  405. static const unsigned IntegerVPOps[] = {
  406. ISD::VP_ADD, ISD::VP_SUB, ISD::VP_MUL,
  407. ISD::VP_SDIV, ISD::VP_UDIV, ISD::VP_SREM,
  408. ISD::VP_UREM, ISD::VP_AND, ISD::VP_OR,
  409. ISD::VP_XOR, ISD::VP_ASHR, ISD::VP_LSHR,
  410. ISD::VP_SHL, ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
  411. ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR, ISD::VP_REDUCE_SMAX,
  412. ISD::VP_REDUCE_SMIN, ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN,
  413. ISD::VP_MERGE, ISD::VP_SELECT, ISD::VP_FP_TO_SINT,
  414. ISD::VP_FP_TO_UINT, ISD::VP_SETCC, ISD::VP_SIGN_EXTEND,
  415. ISD::VP_ZERO_EXTEND, ISD::VP_TRUNCATE, ISD::VP_SMIN,
  416. ISD::VP_SMAX, ISD::VP_UMIN, ISD::VP_UMAX,
  417. ISD::VP_ABS};
  418. static const unsigned FloatingPointVPOps[] = {
  419. ISD::VP_FADD, ISD::VP_FSUB, ISD::VP_FMUL,
  420. ISD::VP_FDIV, ISD::VP_FNEG, ISD::VP_FABS,
  421. ISD::VP_FMA, ISD::VP_REDUCE_FADD, ISD::VP_REDUCE_SEQ_FADD,
  422. ISD::VP_REDUCE_FMIN, ISD::VP_REDUCE_FMAX, ISD::VP_MERGE,
  423. ISD::VP_SELECT, ISD::VP_SINT_TO_FP, ISD::VP_UINT_TO_FP,
  424. ISD::VP_SETCC, ISD::VP_FP_ROUND, ISD::VP_FP_EXTEND,
  425. ISD::VP_SQRT, ISD::VP_FMINNUM, ISD::VP_FMAXNUM,
  426. ISD::VP_FCEIL, ISD::VP_FFLOOR, ISD::VP_FROUND,
  427. ISD::VP_FROUNDEVEN, ISD::VP_FCOPYSIGN, ISD::VP_FROUNDTOZERO,
  428. ISD::VP_FRINT, ISD::VP_FNEARBYINT};
  429. static const unsigned IntegerVecReduceOps[] = {
  430. ISD::VECREDUCE_ADD, ISD::VECREDUCE_AND, ISD::VECREDUCE_OR,
  431. ISD::VECREDUCE_XOR, ISD::VECREDUCE_SMAX, ISD::VECREDUCE_SMIN,
  432. ISD::VECREDUCE_UMAX, ISD::VECREDUCE_UMIN};
  433. static const unsigned FloatingPointVecReduceOps[] = {
  434. ISD::VECREDUCE_FADD, ISD::VECREDUCE_SEQ_FADD, ISD::VECREDUCE_FMIN,
  435. ISD::VECREDUCE_FMAX};
  436. if (!Subtarget.is64Bit()) {
  437. // We must custom-lower certain vXi64 operations on RV32 due to the vector
  438. // element type being illegal.
  439. setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
  440. MVT::i64, Custom);
  441. setOperationAction(IntegerVecReduceOps, MVT::i64, Custom);
  442. setOperationAction({ISD::VP_REDUCE_ADD, ISD::VP_REDUCE_AND,
  443. ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR,
  444. ISD::VP_REDUCE_SMAX, ISD::VP_REDUCE_SMIN,
  445. ISD::VP_REDUCE_UMAX, ISD::VP_REDUCE_UMIN},
  446. MVT::i64, Custom);
  447. }
  448. for (MVT VT : BoolVecVTs) {
  449. if (!isTypeLegal(VT))
  450. continue;
  451. setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
  452. // Mask VTs are custom-expanded into a series of standard nodes
  453. setOperationAction({ISD::TRUNCATE, ISD::CONCAT_VECTORS,
  454. ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
  455. VT, Custom);
  456. setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
  457. Custom);
  458. setOperationAction(ISD::SELECT, VT, Custom);
  459. setOperationAction(
  460. {ISD::SELECT_CC, ISD::VSELECT, ISD::VP_MERGE, ISD::VP_SELECT}, VT,
  461. Expand);
  462. setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR}, VT, Custom);
  463. setOperationAction(
  464. {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
  465. Custom);
  466. setOperationAction(
  467. {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
  468. Custom);
  469. // RVV has native int->float & float->int conversions where the
  470. // element type sizes are within one power-of-two of each other. Any
  471. // wider distances between type sizes have to be lowered as sequences
  472. // which progressively narrow the gap in stages.
  473. setOperationAction(
  474. {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
  475. VT, Custom);
  476. setOperationAction({ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}, VT,
  477. Custom);
  478. // Expand all extending loads to types larger than this, and truncating
  479. // stores from types larger than this.
  480. for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
  481. setTruncStoreAction(OtherVT, VT, Expand);
  482. setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
  483. VT, Expand);
  484. }
  485. setOperationAction({ISD::VP_FP_TO_SINT, ISD::VP_FP_TO_UINT,
  486. ISD::VP_TRUNCATE, ISD::VP_SETCC},
  487. VT, Custom);
  488. setOperationAction(ISD::VECTOR_REVERSE, VT, Custom);
  489. setOperationPromotedToType(
  490. ISD::VECTOR_SPLICE, VT,
  491. MVT::getVectorVT(MVT::i8, VT.getVectorElementCount()));
  492. }
  493. for (MVT VT : IntVecVTs) {
  494. if (!isTypeLegal(VT))
  495. continue;
  496. setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
  497. setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
  498. // Vectors implement MULHS/MULHU.
  499. setOperationAction({ISD::SMUL_LOHI, ISD::UMUL_LOHI}, VT, Expand);
  500. // nxvXi64 MULHS/MULHU requires the V extension instead of Zve64*.
  501. if (VT.getVectorElementType() == MVT::i64 && !Subtarget.hasStdExtV())
  502. setOperationAction({ISD::MULHU, ISD::MULHS}, VT, Expand);
  503. setOperationAction({ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX}, VT,
  504. Legal);
  505. setOperationAction({ISD::ROTL, ISD::ROTR}, VT, Expand);
  506. setOperationAction({ISD::CTTZ, ISD::CTLZ, ISD::CTPOP}, VT, Expand);
  507. setOperationAction(ISD::BSWAP, VT, Expand);
  508. setOperationAction({ISD::VP_BSWAP, ISD::VP_BITREVERSE}, VT, Expand);
  509. setOperationAction({ISD::VP_FSHL, ISD::VP_FSHR}, VT, Expand);
  510. setOperationAction({ISD::VP_CTLZ, ISD::VP_CTLZ_ZERO_UNDEF, ISD::VP_CTTZ,
  511. ISD::VP_CTTZ_ZERO_UNDEF, ISD::VP_CTPOP},
  512. VT, Expand);
  513. // Custom-lower extensions and truncations from/to mask types.
  514. setOperationAction({ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND},
  515. VT, Custom);
  516. // RVV has native int->float & float->int conversions where the
  517. // element type sizes are within one power-of-two of each other. Any
  518. // wider distances between type sizes have to be lowered as sequences
  519. // which progressively narrow the gap in stages.
  520. setOperationAction(
  521. {ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT, ISD::FP_TO_UINT},
  522. VT, Custom);
  523. setOperationAction({ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}, VT,
  524. Custom);
  525. setOperationAction(
  526. {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT, Legal);
  527. // Integer VTs are lowered as a series of "RISCVISD::TRUNCATE_VECTOR_VL"
  528. // nodes which truncate by one power of two at a time.
  529. setOperationAction(ISD::TRUNCATE, VT, Custom);
  530. // Custom-lower insert/extract operations to simplify patterns.
  531. setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
  532. Custom);
  533. // Custom-lower reduction operations to set up the corresponding custom
  534. // nodes' operands.
  535. setOperationAction(IntegerVecReduceOps, VT, Custom);
  536. setOperationAction(IntegerVPOps, VT, Custom);
  537. setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
  538. setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
  539. VT, Custom);
  540. setOperationAction(
  541. {ISD::VP_LOAD, ISD::VP_STORE, ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
  542. ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER, ISD::VP_SCATTER},
  543. VT, Custom);
  544. setOperationAction(
  545. {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
  546. VT, Custom);
  547. setOperationAction(ISD::SELECT, VT, Custom);
  548. setOperationAction(ISD::SELECT_CC, VT, Expand);
  549. setOperationAction({ISD::STEP_VECTOR, ISD::VECTOR_REVERSE}, VT, Custom);
  550. for (MVT OtherVT : MVT::integer_scalable_vector_valuetypes()) {
  551. setTruncStoreAction(VT, OtherVT, Expand);
  552. setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD}, OtherVT,
  553. VT, Expand);
  554. }
  555. // Splice
  556. setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
  557. // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if element of VT in the range
  558. // of f32.
  559. EVT FloatVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
  560. if (isTypeLegal(FloatVT)) {
  561. setOperationAction(
  562. {ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
  563. Custom);
  564. }
  565. }
  566. // Expand various CCs to best match the RVV ISA, which natively supports UNE
  567. // but no other unordered comparisons, and supports all ordered comparisons
  568. // except ONE. Additionally, we expand GT,OGT,GE,OGE for optimization
  569. // purposes; they are expanded to their swapped-operand CCs (LT,OLT,LE,OLE),
  570. // and we pattern-match those back to the "original", swapping operands once
  571. // more. This way we catch both operations and both "vf" and "fv" forms with
  572. // fewer patterns.
  573. static const ISD::CondCode VFPCCToExpand[] = {
  574. ISD::SETO, ISD::SETONE, ISD::SETUEQ, ISD::SETUGT,
  575. ISD::SETUGE, ISD::SETULT, ISD::SETULE, ISD::SETUO,
  576. ISD::SETGT, ISD::SETOGT, ISD::SETGE, ISD::SETOGE,
  577. };
  578. // Sets common operation actions on RVV floating-point vector types.
  579. const auto SetCommonVFPActions = [&](MVT VT) {
  580. setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
  581. // RVV has native FP_ROUND & FP_EXTEND conversions where the element type
  582. // sizes are within one power-of-two of each other. Therefore conversions
  583. // between vXf16 and vXf64 must be lowered as sequences which convert via
  584. // vXf32.
  585. setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
  586. // Custom-lower insert/extract operations to simplify patterns.
  587. setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT}, VT,
  588. Custom);
  589. // Expand various condition codes (explained above).
  590. setCondCodeAction(VFPCCToExpand, VT, Expand);
  591. setOperationAction({ISD::FMINNUM, ISD::FMAXNUM}, VT, Legal);
  592. setOperationAction(
  593. {ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND, ISD::FROUNDEVEN},
  594. VT, Custom);
  595. setOperationAction(FloatingPointVecReduceOps, VT, Custom);
  596. // Expand FP operations that need libcalls.
  597. setOperationAction(ISD::FREM, VT, Expand);
  598. setOperationAction(ISD::FPOW, VT, Expand);
  599. setOperationAction(ISD::FCOS, VT, Expand);
  600. setOperationAction(ISD::FSIN, VT, Expand);
  601. setOperationAction(ISD::FSINCOS, VT, Expand);
  602. setOperationAction(ISD::FEXP, VT, Expand);
  603. setOperationAction(ISD::FEXP2, VT, Expand);
  604. setOperationAction(ISD::FLOG, VT, Expand);
  605. setOperationAction(ISD::FLOG2, VT, Expand);
  606. setOperationAction(ISD::FLOG10, VT, Expand);
  607. setOperationAction(ISD::FRINT, VT, Expand);
  608. setOperationAction(ISD::FNEARBYINT, VT, Expand);
  609. setOperationAction(ISD::FCOPYSIGN, VT, Legal);
  610. setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
  611. setOperationAction({ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER},
  612. VT, Custom);
  613. setOperationAction(
  614. {ISD::VP_LOAD, ISD::VP_STORE, ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
  615. ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER, ISD::VP_SCATTER},
  616. VT, Custom);
  617. setOperationAction(ISD::SELECT, VT, Custom);
  618. setOperationAction(ISD::SELECT_CC, VT, Expand);
  619. setOperationAction(
  620. {ISD::CONCAT_VECTORS, ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR},
  621. VT, Custom);
  622. setOperationAction({ISD::VECTOR_REVERSE, ISD::VECTOR_SPLICE}, VT, Custom);
  623. setOperationAction(FloatingPointVPOps, VT, Custom);
  624. };
  625. // Sets common extload/truncstore actions on RVV floating-point vector
  626. // types.
  627. const auto SetCommonVFPExtLoadTruncStoreActions =
  628. [&](MVT VT, ArrayRef<MVT::SimpleValueType> SmallerVTs) {
  629. for (auto SmallVT : SmallerVTs) {
  630. setTruncStoreAction(VT, SmallVT, Expand);
  631. setLoadExtAction(ISD::EXTLOAD, VT, SmallVT, Expand);
  632. }
  633. };
  634. if (Subtarget.hasVInstructionsF16()) {
  635. for (MVT VT : F16VecVTs) {
  636. if (!isTypeLegal(VT))
  637. continue;
  638. SetCommonVFPActions(VT);
  639. }
  640. }
  641. if (Subtarget.hasVInstructionsF32()) {
  642. for (MVT VT : F32VecVTs) {
  643. if (!isTypeLegal(VT))
  644. continue;
  645. SetCommonVFPActions(VT);
  646. SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
  647. }
  648. }
  649. if (Subtarget.hasVInstructionsF64()) {
  650. for (MVT VT : F64VecVTs) {
  651. if (!isTypeLegal(VT))
  652. continue;
  653. SetCommonVFPActions(VT);
  654. SetCommonVFPExtLoadTruncStoreActions(VT, F16VecVTs);
  655. SetCommonVFPExtLoadTruncStoreActions(VT, F32VecVTs);
  656. }
  657. }
  658. if (Subtarget.useRVVForFixedLengthVectors()) {
  659. for (MVT VT : MVT::integer_fixedlen_vector_valuetypes()) {
  660. if (!useRVVForFixedLengthVectorVT(VT))
  661. continue;
  662. // By default everything must be expanded.
  663. for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
  664. setOperationAction(Op, VT, Expand);
  665. for (MVT OtherVT : MVT::integer_fixedlen_vector_valuetypes()) {
  666. setTruncStoreAction(VT, OtherVT, Expand);
  667. setLoadExtAction({ISD::EXTLOAD, ISD::SEXTLOAD, ISD::ZEXTLOAD},
  668. OtherVT, VT, Expand);
  669. }
  670. // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
  671. setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
  672. Custom);
  673. setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS}, VT,
  674. Custom);
  675. setOperationAction({ISD::INSERT_VECTOR_ELT, ISD::EXTRACT_VECTOR_ELT},
  676. VT, Custom);
  677. setOperationAction({ISD::LOAD, ISD::STORE}, VT, Custom);
  678. setOperationAction(ISD::SETCC, VT, Custom);
  679. setOperationAction(ISD::SELECT, VT, Custom);
  680. setOperationAction(ISD::TRUNCATE, VT, Custom);
  681. setOperationAction(ISD::BITCAST, VT, Custom);
  682. setOperationAction(
  683. {ISD::VECREDUCE_AND, ISD::VECREDUCE_OR, ISD::VECREDUCE_XOR}, VT,
  684. Custom);
  685. setOperationAction(
  686. {ISD::VP_REDUCE_AND, ISD::VP_REDUCE_OR, ISD::VP_REDUCE_XOR}, VT,
  687. Custom);
  688. setOperationAction({ISD::SINT_TO_FP, ISD::UINT_TO_FP, ISD::FP_TO_SINT,
  689. ISD::FP_TO_UINT},
  690. VT, Custom);
  691. setOperationAction({ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT}, VT,
  692. Custom);
  693. // Operations below are different for between masks and other vectors.
  694. if (VT.getVectorElementType() == MVT::i1) {
  695. setOperationAction({ISD::VP_AND, ISD::VP_OR, ISD::VP_XOR, ISD::AND,
  696. ISD::OR, ISD::XOR},
  697. VT, Custom);
  698. setOperationAction({ISD::VP_FP_TO_SINT, ISD::VP_FP_TO_UINT,
  699. ISD::VP_SETCC, ISD::VP_TRUNCATE},
  700. VT, Custom);
  701. continue;
  702. }
  703. // Make SPLAT_VECTOR Legal so DAGCombine will convert splat vectors to
  704. // it before type legalization for i64 vectors on RV32. It will then be
  705. // type legalized to SPLAT_VECTOR_PARTS which we need to Custom handle.
  706. // FIXME: Use SPLAT_VECTOR for all types? DAGCombine probably needs
  707. // improvements first.
  708. if (!Subtarget.is64Bit() && VT.getVectorElementType() == MVT::i64) {
  709. setOperationAction(ISD::SPLAT_VECTOR, VT, Legal);
  710. setOperationAction(ISD::SPLAT_VECTOR_PARTS, VT, Custom);
  711. }
  712. setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
  713. setOperationAction(
  714. {ISD::MLOAD, ISD::MSTORE, ISD::MGATHER, ISD::MSCATTER}, VT, Custom);
  715. setOperationAction({ISD::VP_LOAD, ISD::VP_STORE,
  716. ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
  717. ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER,
  718. ISD::VP_SCATTER},
  719. VT, Custom);
  720. setOperationAction({ISD::ADD, ISD::MUL, ISD::SUB, ISD::AND, ISD::OR,
  721. ISD::XOR, ISD::SDIV, ISD::SREM, ISD::UDIV,
  722. ISD::UREM, ISD::SHL, ISD::SRA, ISD::SRL},
  723. VT, Custom);
  724. setOperationAction(
  725. {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX, ISD::ABS}, VT, Custom);
  726. // vXi64 MULHS/MULHU requires the V extension instead of Zve64*.
  727. if (VT.getVectorElementType() != MVT::i64 || Subtarget.hasStdExtV())
  728. setOperationAction({ISD::MULHS, ISD::MULHU}, VT, Custom);
  729. setOperationAction(
  730. {ISD::SADDSAT, ISD::UADDSAT, ISD::SSUBSAT, ISD::USUBSAT}, VT,
  731. Custom);
  732. setOperationAction(ISD::VSELECT, VT, Custom);
  733. setOperationAction(ISD::SELECT_CC, VT, Expand);
  734. setOperationAction(
  735. {ISD::ANY_EXTEND, ISD::SIGN_EXTEND, ISD::ZERO_EXTEND}, VT, Custom);
  736. // Custom-lower reduction operations to set up the corresponding custom
  737. // nodes' operands.
  738. setOperationAction({ISD::VECREDUCE_ADD, ISD::VECREDUCE_SMAX,
  739. ISD::VECREDUCE_SMIN, ISD::VECREDUCE_UMAX,
  740. ISD::VECREDUCE_UMIN},
  741. VT, Custom);
  742. setOperationAction(IntegerVPOps, VT, Custom);
  743. // Lower CTLZ_ZERO_UNDEF and CTTZ_ZERO_UNDEF if element of VT in the
  744. // range of f32.
  745. EVT FloatVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
  746. if (isTypeLegal(FloatVT))
  747. setOperationAction(
  748. {ISD::CTLZ, ISD::CTLZ_ZERO_UNDEF, ISD::CTTZ_ZERO_UNDEF}, VT,
  749. Custom);
  750. }
  751. for (MVT VT : MVT::fp_fixedlen_vector_valuetypes()) {
  752. if (!useRVVForFixedLengthVectorVT(VT))
  753. continue;
  754. // By default everything must be expanded.
  755. for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
  756. setOperationAction(Op, VT, Expand);
  757. for (MVT OtherVT : MVT::fp_fixedlen_vector_valuetypes()) {
  758. setLoadExtAction(ISD::EXTLOAD, OtherVT, VT, Expand);
  759. setTruncStoreAction(VT, OtherVT, Expand);
  760. }
  761. // We use EXTRACT_SUBVECTOR as a "cast" from scalable to fixed.
  762. setOperationAction({ISD::INSERT_SUBVECTOR, ISD::EXTRACT_SUBVECTOR}, VT,
  763. Custom);
  764. setOperationAction({ISD::BUILD_VECTOR, ISD::CONCAT_VECTORS,
  765. ISD::VECTOR_SHUFFLE, ISD::INSERT_VECTOR_ELT,
  766. ISD::EXTRACT_VECTOR_ELT},
  767. VT, Custom);
  768. setOperationAction({ISD::LOAD, ISD::STORE, ISD::MLOAD, ISD::MSTORE,
  769. ISD::MGATHER, ISD::MSCATTER},
  770. VT, Custom);
  771. setOperationAction({ISD::VP_LOAD, ISD::VP_STORE,
  772. ISD::EXPERIMENTAL_VP_STRIDED_LOAD,
  773. ISD::EXPERIMENTAL_VP_STRIDED_STORE, ISD::VP_GATHER,
  774. ISD::VP_SCATTER},
  775. VT, Custom);
  776. setOperationAction({ISD::FADD, ISD::FSUB, ISD::FMUL, ISD::FDIV,
  777. ISD::FNEG, ISD::FABS, ISD::FCOPYSIGN, ISD::FSQRT,
  778. ISD::FMA, ISD::FMINNUM, ISD::FMAXNUM},
  779. VT, Custom);
  780. setOperationAction({ISD::FP_ROUND, ISD::FP_EXTEND}, VT, Custom);
  781. setOperationAction({ISD::FTRUNC, ISD::FCEIL, ISD::FFLOOR, ISD::FROUND,
  782. ISD::FROUNDEVEN},
  783. VT, Custom);
  784. setCondCodeAction(VFPCCToExpand, VT, Expand);
  785. setOperationAction({ISD::VSELECT, ISD::SELECT}, VT, Custom);
  786. setOperationAction(ISD::SELECT_CC, VT, Expand);
  787. setOperationAction(ISD::BITCAST, VT, Custom);
  788. setOperationAction(FloatingPointVecReduceOps, VT, Custom);
  789. setOperationAction(FloatingPointVPOps, VT, Custom);
  790. }
  791. // Custom-legalize bitcasts from fixed-length vectors to scalar types.
  792. setOperationAction(ISD::BITCAST, {MVT::i8, MVT::i16, MVT::i32, MVT::i64},
  793. Custom);
  794. if (Subtarget.hasStdExtZfhOrZfhmin())
  795. setOperationAction(ISD::BITCAST, MVT::f16, Custom);
  796. if (Subtarget.hasStdExtF())
  797. setOperationAction(ISD::BITCAST, MVT::f32, Custom);
  798. if (Subtarget.hasStdExtD())
  799. setOperationAction(ISD::BITCAST, MVT::f64, Custom);
  800. }
  801. }
  802. if (Subtarget.hasForcedAtomics()) {
  803. // Set atomic rmw/cas operations to expand to force __sync libcalls.
  804. setOperationAction(
  805. {ISD::ATOMIC_CMP_SWAP, ISD::ATOMIC_SWAP, ISD::ATOMIC_LOAD_ADD,
  806. ISD::ATOMIC_LOAD_SUB, ISD::ATOMIC_LOAD_AND, ISD::ATOMIC_LOAD_OR,
  807. ISD::ATOMIC_LOAD_XOR, ISD::ATOMIC_LOAD_NAND, ISD::ATOMIC_LOAD_MIN,
  808. ISD::ATOMIC_LOAD_MAX, ISD::ATOMIC_LOAD_UMIN, ISD::ATOMIC_LOAD_UMAX},
  809. XLenVT, Expand);
  810. }
  811. // Function alignments.
  812. const Align FunctionAlignment(Subtarget.hasStdExtCOrZca() ? 2 : 4);
  813. setMinFunctionAlignment(FunctionAlignment);
  814. setPrefFunctionAlignment(FunctionAlignment);
  815. setMinimumJumpTableEntries(5);
  816. // Jumps are expensive, compared to logic
  817. setJumpIsExpensive();
  818. setTargetDAGCombine({ISD::INTRINSIC_WO_CHAIN, ISD::ADD, ISD::SUB, ISD::AND,
  819. ISD::OR, ISD::XOR, ISD::SETCC, ISD::SELECT});
  820. if (Subtarget.is64Bit())
  821. setTargetDAGCombine(ISD::SRA);
  822. if (Subtarget.hasStdExtF())
  823. setTargetDAGCombine({ISD::FADD, ISD::FMAXNUM, ISD::FMINNUM});
  824. if (Subtarget.hasStdExtZbb())
  825. setTargetDAGCombine({ISD::UMAX, ISD::UMIN, ISD::SMAX, ISD::SMIN});
  826. if (Subtarget.hasStdExtZbs() && Subtarget.is64Bit())
  827. setTargetDAGCombine(ISD::TRUNCATE);
  828. if (Subtarget.hasStdExtZbkb())
  829. setTargetDAGCombine(ISD::BITREVERSE);
  830. if (Subtarget.hasStdExtZfhOrZfhmin())
  831. setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
  832. if (Subtarget.hasStdExtF())
  833. setTargetDAGCombine({ISD::ZERO_EXTEND, ISD::FP_TO_SINT, ISD::FP_TO_UINT,
  834. ISD::FP_TO_SINT_SAT, ISD::FP_TO_UINT_SAT});
  835. if (Subtarget.hasVInstructions())
  836. setTargetDAGCombine({ISD::FCOPYSIGN, ISD::MGATHER, ISD::MSCATTER,
  837. ISD::VP_GATHER, ISD::VP_SCATTER, ISD::SRA, ISD::SRL,
  838. ISD::SHL, ISD::STORE, ISD::SPLAT_VECTOR});
  839. if (Subtarget.useRVVForFixedLengthVectors())
  840. setTargetDAGCombine(ISD::BITCAST);
  841. setLibcallName(RTLIB::FPEXT_F16_F32, "__extendhfsf2");
  842. setLibcallName(RTLIB::FPROUND_F32_F16, "__truncsfhf2");
  843. }
  844. EVT RISCVTargetLowering::getSetCCResultType(const DataLayout &DL,
  845. LLVMContext &Context,
  846. EVT VT) const {
  847. if (!VT.isVector())
  848. return getPointerTy(DL);
  849. if (Subtarget.hasVInstructions() &&
  850. (VT.isScalableVector() || Subtarget.useRVVForFixedLengthVectors()))
  851. return EVT::getVectorVT(Context, MVT::i1, VT.getVectorElementCount());
  852. return VT.changeVectorElementTypeToInteger();
  853. }
  854. MVT RISCVTargetLowering::getVPExplicitVectorLengthTy() const {
  855. return Subtarget.getXLenVT();
  856. }
  857. bool RISCVTargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
  858. const CallInst &I,
  859. MachineFunction &MF,
  860. unsigned Intrinsic) const {
  861. auto &DL = I.getModule()->getDataLayout();
  862. switch (Intrinsic) {
  863. default:
  864. return false;
  865. case Intrinsic::riscv_masked_atomicrmw_xchg_i32:
  866. case Intrinsic::riscv_masked_atomicrmw_add_i32:
  867. case Intrinsic::riscv_masked_atomicrmw_sub_i32:
  868. case Intrinsic::riscv_masked_atomicrmw_nand_i32:
  869. case Intrinsic::riscv_masked_atomicrmw_max_i32:
  870. case Intrinsic::riscv_masked_atomicrmw_min_i32:
  871. case Intrinsic::riscv_masked_atomicrmw_umax_i32:
  872. case Intrinsic::riscv_masked_atomicrmw_umin_i32:
  873. case Intrinsic::riscv_masked_cmpxchg_i32:
  874. Info.opc = ISD::INTRINSIC_W_CHAIN;
  875. Info.memVT = MVT::i32;
  876. Info.ptrVal = I.getArgOperand(0);
  877. Info.offset = 0;
  878. Info.align = Align(4);
  879. Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOStore |
  880. MachineMemOperand::MOVolatile;
  881. return true;
  882. case Intrinsic::riscv_masked_strided_load:
  883. Info.opc = ISD::INTRINSIC_W_CHAIN;
  884. Info.ptrVal = I.getArgOperand(1);
  885. Info.memVT = getValueType(DL, I.getType()->getScalarType());
  886. Info.align = Align(DL.getTypeSizeInBits(I.getType()->getScalarType()) / 8);
  887. Info.size = MemoryLocation::UnknownSize;
  888. Info.flags |= MachineMemOperand::MOLoad;
  889. return true;
  890. case Intrinsic::riscv_masked_strided_store:
  891. Info.opc = ISD::INTRINSIC_VOID;
  892. Info.ptrVal = I.getArgOperand(1);
  893. Info.memVT =
  894. getValueType(DL, I.getArgOperand(0)->getType()->getScalarType());
  895. Info.align = Align(
  896. DL.getTypeSizeInBits(I.getArgOperand(0)->getType()->getScalarType()) /
  897. 8);
  898. Info.size = MemoryLocation::UnknownSize;
  899. Info.flags |= MachineMemOperand::MOStore;
  900. return true;
  901. case Intrinsic::riscv_seg2_load:
  902. case Intrinsic::riscv_seg3_load:
  903. case Intrinsic::riscv_seg4_load:
  904. case Intrinsic::riscv_seg5_load:
  905. case Intrinsic::riscv_seg6_load:
  906. case Intrinsic::riscv_seg7_load:
  907. case Intrinsic::riscv_seg8_load:
  908. Info.opc = ISD::INTRINSIC_W_CHAIN;
  909. Info.ptrVal = I.getArgOperand(0);
  910. Info.memVT =
  911. getValueType(DL, I.getType()->getStructElementType(0)->getScalarType());
  912. Info.align =
  913. Align(DL.getTypeSizeInBits(
  914. I.getType()->getStructElementType(0)->getScalarType()) /
  915. 8);
  916. Info.size = MemoryLocation::UnknownSize;
  917. Info.flags |= MachineMemOperand::MOLoad;
  918. return true;
  919. }
  920. }
  921. bool RISCVTargetLowering::isLegalAddressingMode(const DataLayout &DL,
  922. const AddrMode &AM, Type *Ty,
  923. unsigned AS,
  924. Instruction *I) const {
  925. // No global is ever allowed as a base.
  926. if (AM.BaseGV)
  927. return false;
  928. // RVV instructions only support register addressing.
  929. if (Subtarget.hasVInstructions() && isa<VectorType>(Ty))
  930. return AM.HasBaseReg && AM.Scale == 0 && !AM.BaseOffs;
  931. // Require a 12-bit signed offset.
  932. if (!isInt<12>(AM.BaseOffs))
  933. return false;
  934. switch (AM.Scale) {
  935. case 0: // "r+i" or just "i", depending on HasBaseReg.
  936. break;
  937. case 1:
  938. if (!AM.HasBaseReg) // allow "r+i".
  939. break;
  940. return false; // disallow "r+r" or "r+r+i".
  941. default:
  942. return false;
  943. }
  944. return true;
  945. }
  946. bool RISCVTargetLowering::isLegalICmpImmediate(int64_t Imm) const {
  947. return isInt<12>(Imm);
  948. }
  949. bool RISCVTargetLowering::isLegalAddImmediate(int64_t Imm) const {
  950. return isInt<12>(Imm);
  951. }
  952. // On RV32, 64-bit integers are split into their high and low parts and held
  953. // in two different registers, so the trunc is free since the low register can
  954. // just be used.
  955. // FIXME: Should we consider i64->i32 free on RV64 to match the EVT version of
  956. // isTruncateFree?
  957. bool RISCVTargetLowering::isTruncateFree(Type *SrcTy, Type *DstTy) const {
  958. if (Subtarget.is64Bit() || !SrcTy->isIntegerTy() || !DstTy->isIntegerTy())
  959. return false;
  960. unsigned SrcBits = SrcTy->getPrimitiveSizeInBits();
  961. unsigned DestBits = DstTy->getPrimitiveSizeInBits();
  962. return (SrcBits == 64 && DestBits == 32);
  963. }
  964. bool RISCVTargetLowering::isTruncateFree(EVT SrcVT, EVT DstVT) const {
  965. // We consider i64->i32 free on RV64 since we have good selection of W
  966. // instructions that make promoting operations back to i64 free in many cases.
  967. if (SrcVT.isVector() || DstVT.isVector() || !SrcVT.isInteger() ||
  968. !DstVT.isInteger())
  969. return false;
  970. unsigned SrcBits = SrcVT.getSizeInBits();
  971. unsigned DestBits = DstVT.getSizeInBits();
  972. return (SrcBits == 64 && DestBits == 32);
  973. }
  974. bool RISCVTargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
  975. // Zexts are free if they can be combined with a load.
  976. // Don't advertise i32->i64 zextload as being free for RV64. It interacts
  977. // poorly with type legalization of compares preferring sext.
  978. if (auto *LD = dyn_cast<LoadSDNode>(Val)) {
  979. EVT MemVT = LD->getMemoryVT();
  980. if ((MemVT == MVT::i8 || MemVT == MVT::i16) &&
  981. (LD->getExtensionType() == ISD::NON_EXTLOAD ||
  982. LD->getExtensionType() == ISD::ZEXTLOAD))
  983. return true;
  984. }
  985. return TargetLowering::isZExtFree(Val, VT2);
  986. }
  987. bool RISCVTargetLowering::isSExtCheaperThanZExt(EVT SrcVT, EVT DstVT) const {
  988. return Subtarget.is64Bit() && SrcVT == MVT::i32 && DstVT == MVT::i64;
  989. }
  990. bool RISCVTargetLowering::signExtendConstant(const ConstantInt *CI) const {
  991. return Subtarget.is64Bit() && CI->getType()->isIntegerTy(32);
  992. }
  993. bool RISCVTargetLowering::isCheapToSpeculateCttz(Type *Ty) const {
  994. return Subtarget.hasStdExtZbb();
  995. }
  996. bool RISCVTargetLowering::isCheapToSpeculateCtlz(Type *Ty) const {
  997. return Subtarget.hasStdExtZbb();
  998. }
  999. bool RISCVTargetLowering::isMaskAndCmp0FoldingBeneficial(
  1000. const Instruction &AndI) const {
  1001. // We expect to be able to match a bit extraction instruction if the Zbs
  1002. // extension is supported and the mask is a power of two. However, we
  1003. // conservatively return false if the mask would fit in an ANDI instruction,
  1004. // on the basis that it's possible the sinking+duplication of the AND in
  1005. // CodeGenPrepare triggered by this hook wouldn't decrease the instruction
  1006. // count and would increase code size (e.g. ANDI+BNEZ => BEXTI+BNEZ).
  1007. if (!Subtarget.hasStdExtZbs())
  1008. return false;
  1009. ConstantInt *Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
  1010. if (!Mask)
  1011. return false;
  1012. return !Mask->getValue().isSignedIntN(12) && Mask->getValue().isPowerOf2();
  1013. }
  1014. bool RISCVTargetLowering::hasAndNotCompare(SDValue Y) const {
  1015. EVT VT = Y.getValueType();
  1016. // FIXME: Support vectors once we have tests.
  1017. if (VT.isVector())
  1018. return false;
  1019. return (Subtarget.hasStdExtZbb() || Subtarget.hasStdExtZbkb()) &&
  1020. !isa<ConstantSDNode>(Y);
  1021. }
  1022. bool RISCVTargetLowering::hasBitTest(SDValue X, SDValue Y) const {
  1023. // Zbs provides BEXT[_I], which can be used with SEQZ/SNEZ as a bit test.
  1024. if (Subtarget.hasStdExtZbs())
  1025. return X.getValueType().isScalarInteger();
  1026. // We can use ANDI+SEQZ/SNEZ as a bit test. Y contains the bit position.
  1027. auto *C = dyn_cast<ConstantSDNode>(Y);
  1028. return C && C->getAPIntValue().ule(10);
  1029. }
  1030. bool RISCVTargetLowering::shouldFoldSelectWithIdentityConstant(unsigned Opcode,
  1031. EVT VT) const {
  1032. // Only enable for rvv.
  1033. if (!VT.isVector() || !Subtarget.hasVInstructions())
  1034. return false;
  1035. if (VT.isFixedLengthVector() && !isTypeLegal(VT))
  1036. return false;
  1037. return true;
  1038. }
  1039. bool RISCVTargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
  1040. Type *Ty) const {
  1041. assert(Ty->isIntegerTy());
  1042. unsigned BitSize = Ty->getIntegerBitWidth();
  1043. if (BitSize > Subtarget.getXLen())
  1044. return false;
  1045. // Fast path, assume 32-bit immediates are cheap.
  1046. int64_t Val = Imm.getSExtValue();
  1047. if (isInt<32>(Val))
  1048. return true;
  1049. // A constant pool entry may be more aligned thant he load we're trying to
  1050. // replace. If we don't support unaligned scalar mem, prefer the constant
  1051. // pool.
  1052. // TODO: Can the caller pass down the alignment?
  1053. if (!Subtarget.enableUnalignedScalarMem())
  1054. return true;
  1055. // Prefer to keep the load if it would require many instructions.
  1056. // This uses the same threshold we use for constant pools but doesn't
  1057. // check useConstantPoolForLargeInts.
  1058. // TODO: Should we keep the load only when we're definitely going to emit a
  1059. // constant pool?
  1060. RISCVMatInt::InstSeq Seq =
  1061. RISCVMatInt::generateInstSeq(Val, Subtarget.getFeatureBits());
  1062. return Seq.size() <= Subtarget.getMaxBuildIntsCost();
  1063. }
  1064. bool RISCVTargetLowering::
  1065. shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
  1066. SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
  1067. unsigned OldShiftOpcode, unsigned NewShiftOpcode,
  1068. SelectionDAG &DAG) const {
  1069. // One interesting pattern that we'd want to form is 'bit extract':
  1070. // ((1 >> Y) & 1) ==/!= 0
  1071. // But we also need to be careful not to try to reverse that fold.
  1072. // Is this '((1 >> Y) & 1)'?
  1073. if (XC && OldShiftOpcode == ISD::SRL && XC->isOne())
  1074. return false; // Keep the 'bit extract' pattern.
  1075. // Will this be '((1 >> Y) & 1)' after the transform?
  1076. if (NewShiftOpcode == ISD::SRL && CC->isOne())
  1077. return true; // Do form the 'bit extract' pattern.
  1078. // If 'X' is a constant, and we transform, then we will immediately
  1079. // try to undo the fold, thus causing endless combine loop.
  1080. // So only do the transform if X is not a constant. This matches the default
  1081. // implementation of this function.
  1082. return !XC;
  1083. }
  1084. bool RISCVTargetLowering::canSplatOperand(unsigned Opcode, int Operand) const {
  1085. switch (Opcode) {
  1086. case Instruction::Add:
  1087. case Instruction::Sub:
  1088. case Instruction::Mul:
  1089. case Instruction::And:
  1090. case Instruction::Or:
  1091. case Instruction::Xor:
  1092. case Instruction::FAdd:
  1093. case Instruction::FSub:
  1094. case Instruction::FMul:
  1095. case Instruction::FDiv:
  1096. case Instruction::ICmp:
  1097. case Instruction::FCmp:
  1098. return true;
  1099. case Instruction::Shl:
  1100. case Instruction::LShr:
  1101. case Instruction::AShr:
  1102. case Instruction::UDiv:
  1103. case Instruction::SDiv:
  1104. case Instruction::URem:
  1105. case Instruction::SRem:
  1106. return Operand == 1;
  1107. default:
  1108. return false;
  1109. }
  1110. }
  1111. bool RISCVTargetLowering::canSplatOperand(Instruction *I, int Operand) const {
  1112. if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
  1113. return false;
  1114. if (canSplatOperand(I->getOpcode(), Operand))
  1115. return true;
  1116. auto *II = dyn_cast<IntrinsicInst>(I);
  1117. if (!II)
  1118. return false;
  1119. switch (II->getIntrinsicID()) {
  1120. case Intrinsic::fma:
  1121. case Intrinsic::vp_fma:
  1122. return Operand == 0 || Operand == 1;
  1123. case Intrinsic::vp_shl:
  1124. case Intrinsic::vp_lshr:
  1125. case Intrinsic::vp_ashr:
  1126. case Intrinsic::vp_udiv:
  1127. case Intrinsic::vp_sdiv:
  1128. case Intrinsic::vp_urem:
  1129. case Intrinsic::vp_srem:
  1130. return Operand == 1;
  1131. // These intrinsics are commutative.
  1132. case Intrinsic::vp_add:
  1133. case Intrinsic::vp_mul:
  1134. case Intrinsic::vp_and:
  1135. case Intrinsic::vp_or:
  1136. case Intrinsic::vp_xor:
  1137. case Intrinsic::vp_fadd:
  1138. case Intrinsic::vp_fmul:
  1139. // These intrinsics have 'vr' versions.
  1140. case Intrinsic::vp_sub:
  1141. case Intrinsic::vp_fsub:
  1142. case Intrinsic::vp_fdiv:
  1143. return Operand == 0 || Operand == 1;
  1144. default:
  1145. return false;
  1146. }
  1147. }
  1148. /// Check if sinking \p I's operands to I's basic block is profitable, because
  1149. /// the operands can be folded into a target instruction, e.g.
  1150. /// splats of scalars can fold into vector instructions.
  1151. bool RISCVTargetLowering::shouldSinkOperands(
  1152. Instruction *I, SmallVectorImpl<Use *> &Ops) const {
  1153. using namespace llvm::PatternMatch;
  1154. if (!I->getType()->isVectorTy() || !Subtarget.hasVInstructions())
  1155. return false;
  1156. for (auto OpIdx : enumerate(I->operands())) {
  1157. if (!canSplatOperand(I, OpIdx.index()))
  1158. continue;
  1159. Instruction *Op = dyn_cast<Instruction>(OpIdx.value().get());
  1160. // Make sure we are not already sinking this operand
  1161. if (!Op || any_of(Ops, [&](Use *U) { return U->get() == Op; }))
  1162. continue;
  1163. // We are looking for a splat that can be sunk.
  1164. if (!match(Op, m_Shuffle(m_InsertElt(m_Undef(), m_Value(), m_ZeroInt()),
  1165. m_Undef(), m_ZeroMask())))
  1166. continue;
  1167. // All uses of the shuffle should be sunk to avoid duplicating it across gpr
  1168. // and vector registers
  1169. for (Use &U : Op->uses()) {
  1170. Instruction *Insn = cast<Instruction>(U.getUser());
  1171. if (!canSplatOperand(Insn, U.getOperandNo()))
  1172. return false;
  1173. }
  1174. Ops.push_back(&Op->getOperandUse(0));
  1175. Ops.push_back(&OpIdx.value());
  1176. }
  1177. return true;
  1178. }
  1179. bool RISCVTargetLowering::shouldScalarizeBinop(SDValue VecOp) const {
  1180. unsigned Opc = VecOp.getOpcode();
  1181. // Assume target opcodes can't be scalarized.
  1182. // TODO - do we have any exceptions?
  1183. if (Opc >= ISD::BUILTIN_OP_END)
  1184. return false;
  1185. // If the vector op is not supported, try to convert to scalar.
  1186. EVT VecVT = VecOp.getValueType();
  1187. if (!isOperationLegalOrCustomOrPromote(Opc, VecVT))
  1188. return true;
  1189. // If the vector op is supported, but the scalar op is not, the transform may
  1190. // not be worthwhile.
  1191. EVT ScalarVT = VecVT.getScalarType();
  1192. return isOperationLegalOrCustomOrPromote(Opc, ScalarVT);
  1193. }
  1194. bool RISCVTargetLowering::isOffsetFoldingLegal(
  1195. const GlobalAddressSDNode *GA) const {
  1196. // In order to maximise the opportunity for common subexpression elimination,
  1197. // keep a separate ADD node for the global address offset instead of folding
  1198. // it in the global address node. Later peephole optimisations may choose to
  1199. // fold it back in when profitable.
  1200. return false;
  1201. }
  1202. bool RISCVTargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
  1203. bool ForCodeSize) const {
  1204. if (VT == MVT::f16 && !Subtarget.hasStdExtZfhOrZfhmin())
  1205. return false;
  1206. if (VT == MVT::f32 && !Subtarget.hasStdExtF())
  1207. return false;
  1208. if (VT == MVT::f64 && !Subtarget.hasStdExtD())
  1209. return false;
  1210. return Imm.isZero();
  1211. }
  1212. // TODO: This is very conservative.
  1213. bool RISCVTargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
  1214. unsigned Index) const {
  1215. if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
  1216. return false;
  1217. // Only support extracting a fixed from a fixed vector for now.
  1218. if (ResVT.isScalableVector() || SrcVT.isScalableVector())
  1219. return false;
  1220. unsigned ResElts = ResVT.getVectorNumElements();
  1221. unsigned SrcElts = SrcVT.getVectorNumElements();
  1222. // Convervatively only handle extracting half of a vector.
  1223. // TODO: Relax this.
  1224. if ((ResElts * 2) != SrcElts)
  1225. return false;
  1226. // The smallest type we can slide is i8.
  1227. // TODO: We can extract index 0 from a mask vector without a slide.
  1228. if (ResVT.getVectorElementType() == MVT::i1)
  1229. return false;
  1230. // Slide can support arbitrary index, but we only treat vslidedown.vi as
  1231. // cheap.
  1232. if (Index >= 32)
  1233. return false;
  1234. // TODO: We can do arbitrary slidedowns, but for now only support extracting
  1235. // the upper half of a vector until we have more test coverage.
  1236. return Index == 0 || Index == ResElts;
  1237. }
  1238. bool RISCVTargetLowering::hasBitPreservingFPLogic(EVT VT) const {
  1239. return (VT == MVT::f16 && Subtarget.hasStdExtZfhOrZfhmin()) ||
  1240. (VT == MVT::f32 && Subtarget.hasStdExtF()) ||
  1241. (VT == MVT::f64 && Subtarget.hasStdExtD());
  1242. }
  1243. MVT RISCVTargetLowering::getRegisterTypeForCallingConv(LLVMContext &Context,
  1244. CallingConv::ID CC,
  1245. EVT VT) const {
  1246. // Use f32 to pass f16 if it is legal and Zfh/Zfhmin is not enabled.
  1247. // We might still end up using a GPR but that will be decided based on ABI.
  1248. if (VT == MVT::f16 && Subtarget.hasStdExtF() &&
  1249. !Subtarget.hasStdExtZfhOrZfhmin())
  1250. return MVT::f32;
  1251. return TargetLowering::getRegisterTypeForCallingConv(Context, CC, VT);
  1252. }
  1253. unsigned RISCVTargetLowering::getNumRegistersForCallingConv(LLVMContext &Context,
  1254. CallingConv::ID CC,
  1255. EVT VT) const {
  1256. // Use f32 to pass f16 if it is legal and Zfh/Zfhmin is not enabled.
  1257. // We might still end up using a GPR but that will be decided based on ABI.
  1258. if (VT == MVT::f16 && Subtarget.hasStdExtF() &&
  1259. !Subtarget.hasStdExtZfhOrZfhmin())
  1260. return 1;
  1261. return TargetLowering::getNumRegistersForCallingConv(Context, CC, VT);
  1262. }
  1263. // Changes the condition code and swaps operands if necessary, so the SetCC
  1264. // operation matches one of the comparisons supported directly by branches
  1265. // in the RISC-V ISA. May adjust compares to favor compare with 0 over compare
  1266. // with 1/-1.
  1267. static void translateSetCCForBranch(const SDLoc &DL, SDValue &LHS, SDValue &RHS,
  1268. ISD::CondCode &CC, SelectionDAG &DAG) {
  1269. // If this is a single bit test that can't be handled by ANDI, shift the
  1270. // bit to be tested to the MSB and perform a signed compare with 0.
  1271. if (isIntEqualitySetCC(CC) && isNullConstant(RHS) &&
  1272. LHS.getOpcode() == ISD::AND && LHS.hasOneUse() &&
  1273. isa<ConstantSDNode>(LHS.getOperand(1))) {
  1274. uint64_t Mask = LHS.getConstantOperandVal(1);
  1275. if ((isPowerOf2_64(Mask) || isMask_64(Mask)) && !isInt<12>(Mask)) {
  1276. unsigned ShAmt = 0;
  1277. if (isPowerOf2_64(Mask)) {
  1278. CC = CC == ISD::SETEQ ? ISD::SETGE : ISD::SETLT;
  1279. ShAmt = LHS.getValueSizeInBits() - 1 - Log2_64(Mask);
  1280. } else {
  1281. ShAmt = LHS.getValueSizeInBits() - llvm::bit_width(Mask);
  1282. }
  1283. LHS = LHS.getOperand(0);
  1284. if (ShAmt != 0)
  1285. LHS = DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS,
  1286. DAG.getConstant(ShAmt, DL, LHS.getValueType()));
  1287. return;
  1288. }
  1289. }
  1290. if (auto *RHSC = dyn_cast<ConstantSDNode>(RHS)) {
  1291. int64_t C = RHSC->getSExtValue();
  1292. switch (CC) {
  1293. default: break;
  1294. case ISD::SETGT:
  1295. // Convert X > -1 to X >= 0.
  1296. if (C == -1) {
  1297. RHS = DAG.getConstant(0, DL, RHS.getValueType());
  1298. CC = ISD::SETGE;
  1299. return;
  1300. }
  1301. break;
  1302. case ISD::SETLT:
  1303. // Convert X < 1 to 0 <= X.
  1304. if (C == 1) {
  1305. RHS = LHS;
  1306. LHS = DAG.getConstant(0, DL, RHS.getValueType());
  1307. CC = ISD::SETGE;
  1308. return;
  1309. }
  1310. break;
  1311. }
  1312. }
  1313. switch (CC) {
  1314. default:
  1315. break;
  1316. case ISD::SETGT:
  1317. case ISD::SETLE:
  1318. case ISD::SETUGT:
  1319. case ISD::SETULE:
  1320. CC = ISD::getSetCCSwappedOperands(CC);
  1321. std::swap(LHS, RHS);
  1322. break;
  1323. }
  1324. }
  1325. RISCVII::VLMUL RISCVTargetLowering::getLMUL(MVT VT) {
  1326. assert(VT.isScalableVector() && "Expecting a scalable vector type");
  1327. unsigned KnownSize = VT.getSizeInBits().getKnownMinValue();
  1328. if (VT.getVectorElementType() == MVT::i1)
  1329. KnownSize *= 8;
  1330. switch (KnownSize) {
  1331. default:
  1332. llvm_unreachable("Invalid LMUL.");
  1333. case 8:
  1334. return RISCVII::VLMUL::LMUL_F8;
  1335. case 16:
  1336. return RISCVII::VLMUL::LMUL_F4;
  1337. case 32:
  1338. return RISCVII::VLMUL::LMUL_F2;
  1339. case 64:
  1340. return RISCVII::VLMUL::LMUL_1;
  1341. case 128:
  1342. return RISCVII::VLMUL::LMUL_2;
  1343. case 256:
  1344. return RISCVII::VLMUL::LMUL_4;
  1345. case 512:
  1346. return RISCVII::VLMUL::LMUL_8;
  1347. }
  1348. }
  1349. unsigned RISCVTargetLowering::getRegClassIDForLMUL(RISCVII::VLMUL LMul) {
  1350. switch (LMul) {
  1351. default:
  1352. llvm_unreachable("Invalid LMUL.");
  1353. case RISCVII::VLMUL::LMUL_F8:
  1354. case RISCVII::VLMUL::LMUL_F4:
  1355. case RISCVII::VLMUL::LMUL_F2:
  1356. case RISCVII::VLMUL::LMUL_1:
  1357. return RISCV::VRRegClassID;
  1358. case RISCVII::VLMUL::LMUL_2:
  1359. return RISCV::VRM2RegClassID;
  1360. case RISCVII::VLMUL::LMUL_4:
  1361. return RISCV::VRM4RegClassID;
  1362. case RISCVII::VLMUL::LMUL_8:
  1363. return RISCV::VRM8RegClassID;
  1364. }
  1365. }
  1366. unsigned RISCVTargetLowering::getSubregIndexByMVT(MVT VT, unsigned Index) {
  1367. RISCVII::VLMUL LMUL = getLMUL(VT);
  1368. if (LMUL == RISCVII::VLMUL::LMUL_F8 ||
  1369. LMUL == RISCVII::VLMUL::LMUL_F4 ||
  1370. LMUL == RISCVII::VLMUL::LMUL_F2 ||
  1371. LMUL == RISCVII::VLMUL::LMUL_1) {
  1372. static_assert(RISCV::sub_vrm1_7 == RISCV::sub_vrm1_0 + 7,
  1373. "Unexpected subreg numbering");
  1374. return RISCV::sub_vrm1_0 + Index;
  1375. }
  1376. if (LMUL == RISCVII::VLMUL::LMUL_2) {
  1377. static_assert(RISCV::sub_vrm2_3 == RISCV::sub_vrm2_0 + 3,
  1378. "Unexpected subreg numbering");
  1379. return RISCV::sub_vrm2_0 + Index;
  1380. }
  1381. if (LMUL == RISCVII::VLMUL::LMUL_4) {
  1382. static_assert(RISCV::sub_vrm4_1 == RISCV::sub_vrm4_0 + 1,
  1383. "Unexpected subreg numbering");
  1384. return RISCV::sub_vrm4_0 + Index;
  1385. }
  1386. llvm_unreachable("Invalid vector type.");
  1387. }
  1388. unsigned RISCVTargetLowering::getRegClassIDForVecVT(MVT VT) {
  1389. if (VT.getVectorElementType() == MVT::i1)
  1390. return RISCV::VRRegClassID;
  1391. return getRegClassIDForLMUL(getLMUL(VT));
  1392. }
  1393. // Attempt to decompose a subvector insert/extract between VecVT and
  1394. // SubVecVT via subregister indices. Returns the subregister index that
  1395. // can perform the subvector insert/extract with the given element index, as
  1396. // well as the index corresponding to any leftover subvectors that must be
  1397. // further inserted/extracted within the register class for SubVecVT.
  1398. std::pair<unsigned, unsigned>
  1399. RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
  1400. MVT VecVT, MVT SubVecVT, unsigned InsertExtractIdx,
  1401. const RISCVRegisterInfo *TRI) {
  1402. static_assert((RISCV::VRM8RegClassID > RISCV::VRM4RegClassID &&
  1403. RISCV::VRM4RegClassID > RISCV::VRM2RegClassID &&
  1404. RISCV::VRM2RegClassID > RISCV::VRRegClassID),
  1405. "Register classes not ordered");
  1406. unsigned VecRegClassID = getRegClassIDForVecVT(VecVT);
  1407. unsigned SubRegClassID = getRegClassIDForVecVT(SubVecVT);
  1408. // Try to compose a subregister index that takes us from the incoming
  1409. // LMUL>1 register class down to the outgoing one. At each step we half
  1410. // the LMUL:
  1411. // nxv16i32@12 -> nxv2i32: sub_vrm4_1_then_sub_vrm2_1_then_sub_vrm1_0
  1412. // Note that this is not guaranteed to find a subregister index, such as
  1413. // when we are extracting from one VR type to another.
  1414. unsigned SubRegIdx = RISCV::NoSubRegister;
  1415. for (const unsigned RCID :
  1416. {RISCV::VRM4RegClassID, RISCV::VRM2RegClassID, RISCV::VRRegClassID})
  1417. if (VecRegClassID > RCID && SubRegClassID <= RCID) {
  1418. VecVT = VecVT.getHalfNumVectorElementsVT();
  1419. bool IsHi =
  1420. InsertExtractIdx >= VecVT.getVectorElementCount().getKnownMinValue();
  1421. SubRegIdx = TRI->composeSubRegIndices(SubRegIdx,
  1422. getSubregIndexByMVT(VecVT, IsHi));
  1423. if (IsHi)
  1424. InsertExtractIdx -= VecVT.getVectorElementCount().getKnownMinValue();
  1425. }
  1426. return {SubRegIdx, InsertExtractIdx};
  1427. }
  1428. // Permit combining of mask vectors as BUILD_VECTOR never expands to scalar
  1429. // stores for those types.
  1430. bool RISCVTargetLowering::mergeStoresAfterLegalization(EVT VT) const {
  1431. return !Subtarget.useRVVForFixedLengthVectors() ||
  1432. (VT.isFixedLengthVector() && VT.getVectorElementType() == MVT::i1);
  1433. }
  1434. bool RISCVTargetLowering::isLegalElementTypeForRVV(Type *ScalarTy) const {
  1435. if (ScalarTy->isPointerTy())
  1436. return true;
  1437. if (ScalarTy->isIntegerTy(8) || ScalarTy->isIntegerTy(16) ||
  1438. ScalarTy->isIntegerTy(32))
  1439. return true;
  1440. if (ScalarTy->isIntegerTy(64))
  1441. return Subtarget.hasVInstructionsI64();
  1442. if (ScalarTy->isHalfTy())
  1443. return Subtarget.hasVInstructionsF16();
  1444. if (ScalarTy->isFloatTy())
  1445. return Subtarget.hasVInstructionsF32();
  1446. if (ScalarTy->isDoubleTy())
  1447. return Subtarget.hasVInstructionsF64();
  1448. return false;
  1449. }
  1450. unsigned RISCVTargetLowering::combineRepeatedFPDivisors() const {
  1451. return NumRepeatedDivisors;
  1452. }
  1453. static SDValue getVLOperand(SDValue Op) {
  1454. assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
  1455. Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
  1456. "Unexpected opcode");
  1457. bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
  1458. unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
  1459. const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
  1460. RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
  1461. if (!II)
  1462. return SDValue();
  1463. return Op.getOperand(II->VLOperand + 1 + HasChain);
  1464. }
  1465. static bool useRVVForFixedLengthVectorVT(MVT VT,
  1466. const RISCVSubtarget &Subtarget) {
  1467. assert(VT.isFixedLengthVector() && "Expected a fixed length vector type!");
  1468. if (!Subtarget.useRVVForFixedLengthVectors())
  1469. return false;
  1470. // We only support a set of vector types with a consistent maximum fixed size
  1471. // across all supported vector element types to avoid legalization issues.
  1472. // Therefore -- since the largest is v1024i8/v512i16/etc -- the largest
  1473. // fixed-length vector type we support is 1024 bytes.
  1474. if (VT.getFixedSizeInBits() > 1024 * 8)
  1475. return false;
  1476. unsigned MinVLen = Subtarget.getRealMinVLen();
  1477. MVT EltVT = VT.getVectorElementType();
  1478. // Don't use RVV for vectors we cannot scalarize if required.
  1479. switch (EltVT.SimpleTy) {
  1480. // i1 is supported but has different rules.
  1481. default:
  1482. return false;
  1483. case MVT::i1:
  1484. // Masks can only use a single register.
  1485. if (VT.getVectorNumElements() > MinVLen)
  1486. return false;
  1487. MinVLen /= 8;
  1488. break;
  1489. case MVT::i8:
  1490. case MVT::i16:
  1491. case MVT::i32:
  1492. break;
  1493. case MVT::i64:
  1494. if (!Subtarget.hasVInstructionsI64())
  1495. return false;
  1496. break;
  1497. case MVT::f16:
  1498. if (!Subtarget.hasVInstructionsF16())
  1499. return false;
  1500. break;
  1501. case MVT::f32:
  1502. if (!Subtarget.hasVInstructionsF32())
  1503. return false;
  1504. break;
  1505. case MVT::f64:
  1506. if (!Subtarget.hasVInstructionsF64())
  1507. return false;
  1508. break;
  1509. }
  1510. // Reject elements larger than ELEN.
  1511. if (EltVT.getSizeInBits() > Subtarget.getELEN())
  1512. return false;
  1513. unsigned LMul = divideCeil(VT.getSizeInBits(), MinVLen);
  1514. // Don't use RVV for types that don't fit.
  1515. if (LMul > Subtarget.getMaxLMULForFixedLengthVectors())
  1516. return false;
  1517. // TODO: Perhaps an artificial restriction, but worth having whilst getting
  1518. // the base fixed length RVV support in place.
  1519. if (!VT.isPow2VectorType())
  1520. return false;
  1521. return true;
  1522. }
  1523. bool RISCVTargetLowering::useRVVForFixedLengthVectorVT(MVT VT) const {
  1524. return ::useRVVForFixedLengthVectorVT(VT, Subtarget);
  1525. }
  1526. // Return the largest legal scalable vector type that matches VT's element type.
  1527. static MVT getContainerForFixedLengthVector(const TargetLowering &TLI, MVT VT,
  1528. const RISCVSubtarget &Subtarget) {
  1529. // This may be called before legal types are setup.
  1530. assert(((VT.isFixedLengthVector() && TLI.isTypeLegal(VT)) ||
  1531. useRVVForFixedLengthVectorVT(VT, Subtarget)) &&
  1532. "Expected legal fixed length vector!");
  1533. unsigned MinVLen = Subtarget.getRealMinVLen();
  1534. unsigned MaxELen = Subtarget.getELEN();
  1535. MVT EltVT = VT.getVectorElementType();
  1536. switch (EltVT.SimpleTy) {
  1537. default:
  1538. llvm_unreachable("unexpected element type for RVV container");
  1539. case MVT::i1:
  1540. case MVT::i8:
  1541. case MVT::i16:
  1542. case MVT::i32:
  1543. case MVT::i64:
  1544. case MVT::f16:
  1545. case MVT::f32:
  1546. case MVT::f64: {
  1547. // We prefer to use LMUL=1 for VLEN sized types. Use fractional lmuls for
  1548. // narrower types. The smallest fractional LMUL we support is 8/ELEN. Within
  1549. // each fractional LMUL we support SEW between 8 and LMUL*ELEN.
  1550. unsigned NumElts =
  1551. (VT.getVectorNumElements() * RISCV::RVVBitsPerBlock) / MinVLen;
  1552. NumElts = std::max(NumElts, RISCV::RVVBitsPerBlock / MaxELen);
  1553. assert(isPowerOf2_32(NumElts) && "Expected power of 2 NumElts");
  1554. return MVT::getScalableVectorVT(EltVT, NumElts);
  1555. }
  1556. }
  1557. }
  1558. static MVT getContainerForFixedLengthVector(SelectionDAG &DAG, MVT VT,
  1559. const RISCVSubtarget &Subtarget) {
  1560. return getContainerForFixedLengthVector(DAG.getTargetLoweringInfo(), VT,
  1561. Subtarget);
  1562. }
  1563. MVT RISCVTargetLowering::getContainerForFixedLengthVector(MVT VT) const {
  1564. return ::getContainerForFixedLengthVector(*this, VT, getSubtarget());
  1565. }
  1566. // Grow V to consume an entire RVV register.
  1567. static SDValue convertToScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
  1568. const RISCVSubtarget &Subtarget) {
  1569. assert(VT.isScalableVector() &&
  1570. "Expected to convert into a scalable vector!");
  1571. assert(V.getValueType().isFixedLengthVector() &&
  1572. "Expected a fixed length vector operand!");
  1573. SDLoc DL(V);
  1574. SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
  1575. return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
  1576. }
  1577. // Shrink V so it's just big enough to maintain a VT's worth of data.
  1578. static SDValue convertFromScalableVector(EVT VT, SDValue V, SelectionDAG &DAG,
  1579. const RISCVSubtarget &Subtarget) {
  1580. assert(VT.isFixedLengthVector() &&
  1581. "Expected to convert into a fixed length vector!");
  1582. assert(V.getValueType().isScalableVector() &&
  1583. "Expected a scalable vector operand!");
  1584. SDLoc DL(V);
  1585. SDValue Zero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
  1586. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
  1587. }
  1588. /// Return the type of the mask type suitable for masking the provided
  1589. /// vector type. This is simply an i1 element type vector of the same
  1590. /// (possibly scalable) length.
  1591. static MVT getMaskTypeFor(MVT VecVT) {
  1592. assert(VecVT.isVector());
  1593. ElementCount EC = VecVT.getVectorElementCount();
  1594. return MVT::getVectorVT(MVT::i1, EC);
  1595. }
  1596. /// Creates an all ones mask suitable for masking a vector of type VecTy with
  1597. /// vector length VL. .
  1598. static SDValue getAllOnesMask(MVT VecVT, SDValue VL, SDLoc DL,
  1599. SelectionDAG &DAG) {
  1600. MVT MaskVT = getMaskTypeFor(VecVT);
  1601. return DAG.getNode(RISCVISD::VMSET_VL, DL, MaskVT, VL);
  1602. }
  1603. static SDValue getVLOp(uint64_t NumElts, SDLoc DL, SelectionDAG &DAG,
  1604. const RISCVSubtarget &Subtarget) {
  1605. return DAG.getConstant(NumElts, DL, Subtarget.getXLenVT());
  1606. }
  1607. static std::pair<SDValue, SDValue>
  1608. getDefaultVLOps(uint64_t NumElts, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
  1609. const RISCVSubtarget &Subtarget) {
  1610. assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
  1611. SDValue VL = getVLOp(NumElts, DL, DAG, Subtarget);
  1612. SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
  1613. return {Mask, VL};
  1614. }
  1615. // Gets the two common "VL" operands: an all-ones mask and the vector length.
  1616. // VecVT is a vector type, either fixed-length or scalable, and ContainerVT is
  1617. // the vector type that the fixed-length vector is contained in. Otherwise if
  1618. // VecVT is scalable, then ContainerVT should be the same as VecVT.
  1619. static std::pair<SDValue, SDValue>
  1620. getDefaultVLOps(MVT VecVT, MVT ContainerVT, SDLoc DL, SelectionDAG &DAG,
  1621. const RISCVSubtarget &Subtarget) {
  1622. if (VecVT.isFixedLengthVector())
  1623. return getDefaultVLOps(VecVT.getVectorNumElements(), ContainerVT, DL, DAG,
  1624. Subtarget);
  1625. assert(ContainerVT.isScalableVector() && "Expecting scalable container type");
  1626. MVT XLenVT = Subtarget.getXLenVT();
  1627. SDValue VL = DAG.getRegister(RISCV::X0, XLenVT);
  1628. SDValue Mask = getAllOnesMask(ContainerVT, VL, DL, DAG);
  1629. return {Mask, VL};
  1630. }
  1631. // As above but assuming the given type is a scalable vector type.
  1632. static std::pair<SDValue, SDValue>
  1633. getDefaultScalableVLOps(MVT VecVT, SDLoc DL, SelectionDAG &DAG,
  1634. const RISCVSubtarget &Subtarget) {
  1635. assert(VecVT.isScalableVector() && "Expecting a scalable vector");
  1636. return getDefaultVLOps(VecVT, VecVT, DL, DAG, Subtarget);
  1637. }
  1638. // The state of RVV BUILD_VECTOR and VECTOR_SHUFFLE lowering is that very few
  1639. // of either is (currently) supported. This can get us into an infinite loop
  1640. // where we try to lower a BUILD_VECTOR as a VECTOR_SHUFFLE as a BUILD_VECTOR
  1641. // as a ..., etc.
  1642. // Until either (or both) of these can reliably lower any node, reporting that
  1643. // we don't want to expand BUILD_VECTORs via VECTOR_SHUFFLEs at least breaks
  1644. // the infinite loop. Note that this lowers BUILD_VECTOR through the stack,
  1645. // which is not desirable.
  1646. bool RISCVTargetLowering::shouldExpandBuildVectorWithShuffles(
  1647. EVT VT, unsigned DefinedValues) const {
  1648. return false;
  1649. }
  1650. static SDValue lowerFP_TO_INT_SAT(SDValue Op, SelectionDAG &DAG,
  1651. const RISCVSubtarget &Subtarget) {
  1652. // RISCV FP-to-int conversions saturate to the destination register size, but
  1653. // don't produce 0 for nan. We can use a conversion instruction and fix the
  1654. // nan case with a compare and a select.
  1655. SDValue Src = Op.getOperand(0);
  1656. MVT DstVT = Op.getSimpleValueType();
  1657. EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  1658. bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT_SAT;
  1659. if (!DstVT.isVector()) {
  1660. // In absense of Zfh, promote f16 to f32, then saturate the result.
  1661. if (Src.getSimpleValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) {
  1662. Src = DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), MVT::f32, Src);
  1663. }
  1664. unsigned Opc;
  1665. if (SatVT == DstVT)
  1666. Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
  1667. else if (DstVT == MVT::i64 && SatVT == MVT::i32)
  1668. Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
  1669. else
  1670. return SDValue();
  1671. // FIXME: Support other SatVTs by clamping before or after the conversion.
  1672. SDLoc DL(Op);
  1673. SDValue FpToInt = DAG.getNode(
  1674. Opc, DL, DstVT, Src,
  1675. DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT()));
  1676. if (Opc == RISCVISD::FCVT_WU_RV64)
  1677. FpToInt = DAG.getZeroExtendInReg(FpToInt, DL, MVT::i32);
  1678. SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
  1679. return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt,
  1680. ISD::CondCode::SETUO);
  1681. }
  1682. // Vectors.
  1683. MVT DstEltVT = DstVT.getVectorElementType();
  1684. MVT SrcVT = Src.getSimpleValueType();
  1685. MVT SrcEltVT = SrcVT.getVectorElementType();
  1686. unsigned SrcEltSize = SrcEltVT.getSizeInBits();
  1687. unsigned DstEltSize = DstEltVT.getSizeInBits();
  1688. // Only handle saturating to the destination type.
  1689. if (SatVT != DstEltVT)
  1690. return SDValue();
  1691. // FIXME: Don't support narrowing by more than 1 steps for now.
  1692. if (SrcEltSize > (2 * DstEltSize))
  1693. return SDValue();
  1694. MVT DstContainerVT = DstVT;
  1695. MVT SrcContainerVT = SrcVT;
  1696. if (DstVT.isFixedLengthVector()) {
  1697. DstContainerVT = getContainerForFixedLengthVector(DAG, DstVT, Subtarget);
  1698. SrcContainerVT = getContainerForFixedLengthVector(DAG, SrcVT, Subtarget);
  1699. assert(DstContainerVT.getVectorElementCount() ==
  1700. SrcContainerVT.getVectorElementCount() &&
  1701. "Expected same element count");
  1702. Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
  1703. }
  1704. SDLoc DL(Op);
  1705. auto [Mask, VL] = getDefaultVLOps(DstVT, DstContainerVT, DL, DAG, Subtarget);
  1706. SDValue IsNan = DAG.getNode(RISCVISD::SETCC_VL, DL, Mask.getValueType(),
  1707. {Src, Src, DAG.getCondCode(ISD::SETNE),
  1708. DAG.getUNDEF(Mask.getValueType()), Mask, VL});
  1709. // Need to widen by more than 1 step, promote the FP type, then do a widening
  1710. // convert.
  1711. if (DstEltSize > (2 * SrcEltSize)) {
  1712. assert(SrcContainerVT.getVectorElementType() == MVT::f16 && "Unexpected VT!");
  1713. MVT InterVT = SrcContainerVT.changeVectorElementType(MVT::f32);
  1714. Src = DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterVT, Src, Mask, VL);
  1715. }
  1716. unsigned RVVOpc =
  1717. IsSigned ? RISCVISD::VFCVT_RTZ_X_F_VL : RISCVISD::VFCVT_RTZ_XU_F_VL;
  1718. SDValue Res = DAG.getNode(RVVOpc, DL, DstContainerVT, Src, Mask, VL);
  1719. SDValue SplatZero = DAG.getNode(
  1720. RISCVISD::VMV_V_X_VL, DL, DstContainerVT, DAG.getUNDEF(DstContainerVT),
  1721. DAG.getConstant(0, DL, Subtarget.getXLenVT()), VL);
  1722. Res = DAG.getNode(RISCVISD::VSELECT_VL, DL, DstContainerVT, IsNan, SplatZero,
  1723. Res, VL);
  1724. if (DstVT.isFixedLengthVector())
  1725. Res = convertFromScalableVector(DstVT, Res, DAG, Subtarget);
  1726. return Res;
  1727. }
  1728. static RISCVFPRndMode::RoundingMode matchRoundingOp(unsigned Opc) {
  1729. switch (Opc) {
  1730. case ISD::FROUNDEVEN:
  1731. case ISD::VP_FROUNDEVEN:
  1732. return RISCVFPRndMode::RNE;
  1733. case ISD::FTRUNC:
  1734. case ISD::VP_FROUNDTOZERO:
  1735. return RISCVFPRndMode::RTZ;
  1736. case ISD::FFLOOR:
  1737. case ISD::VP_FFLOOR:
  1738. return RISCVFPRndMode::RDN;
  1739. case ISD::FCEIL:
  1740. case ISD::VP_FCEIL:
  1741. return RISCVFPRndMode::RUP;
  1742. case ISD::FROUND:
  1743. case ISD::VP_FROUND:
  1744. return RISCVFPRndMode::RMM;
  1745. case ISD::FRINT:
  1746. return RISCVFPRndMode::DYN;
  1747. }
  1748. return RISCVFPRndMode::Invalid;
  1749. }
  1750. // Expand vector FTRUNC, FCEIL, FFLOOR, FROUND, VP_FCEIL, VP_FFLOOR, VP_FROUND
  1751. // VP_FROUNDEVEN, VP_FROUNDTOZERO, VP_FRINT and VP_FNEARBYINT by converting to
  1752. // the integer domain and back. Taking care to avoid converting values that are
  1753. // nan or already correct.
  1754. static SDValue
  1755. lowerVectorFTRUNC_FCEIL_FFLOOR_FROUND(SDValue Op, SelectionDAG &DAG,
  1756. const RISCVSubtarget &Subtarget) {
  1757. MVT VT = Op.getSimpleValueType();
  1758. assert(VT.isVector() && "Unexpected type");
  1759. SDLoc DL(Op);
  1760. SDValue Src = Op.getOperand(0);
  1761. MVT ContainerVT = VT;
  1762. if (VT.isFixedLengthVector()) {
  1763. ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
  1764. Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
  1765. }
  1766. SDValue Mask, VL;
  1767. if (Op->isVPOpcode()) {
  1768. Mask = Op.getOperand(1);
  1769. VL = Op.getOperand(2);
  1770. } else {
  1771. std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
  1772. }
  1773. // Freeze the source since we are increasing the number of uses.
  1774. Src = DAG.getFreeze(Src);
  1775. // We do the conversion on the absolute value and fix the sign at the end.
  1776. SDValue Abs = DAG.getNode(RISCVISD::FABS_VL, DL, ContainerVT, Src, Mask, VL);
  1777. // Determine the largest integer that can be represented exactly. This and
  1778. // values larger than it don't have any fractional bits so don't need to
  1779. // be converted.
  1780. const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(ContainerVT);
  1781. unsigned Precision = APFloat::semanticsPrecision(FltSem);
  1782. APFloat MaxVal = APFloat(FltSem);
  1783. MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
  1784. /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
  1785. SDValue MaxValNode =
  1786. DAG.getConstantFP(MaxVal, DL, ContainerVT.getVectorElementType());
  1787. SDValue MaxValSplat = DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, ContainerVT,
  1788. DAG.getUNDEF(ContainerVT), MaxValNode, VL);
  1789. // If abs(Src) was larger than MaxVal or nan, keep it.
  1790. MVT SetccVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
  1791. Mask =
  1792. DAG.getNode(RISCVISD::SETCC_VL, DL, SetccVT,
  1793. {Abs, MaxValSplat, DAG.getCondCode(ISD::SETOLT),
  1794. Mask, Mask, VL});
  1795. // Truncate to integer and convert back to FP.
  1796. MVT IntVT = ContainerVT.changeVectorElementTypeToInteger();
  1797. MVT XLenVT = Subtarget.getXLenVT();
  1798. SDValue Truncated;
  1799. switch (Op.getOpcode()) {
  1800. default:
  1801. llvm_unreachable("Unexpected opcode");
  1802. case ISD::FCEIL:
  1803. case ISD::VP_FCEIL:
  1804. case ISD::FFLOOR:
  1805. case ISD::VP_FFLOOR:
  1806. case ISD::FROUND:
  1807. case ISD::FROUNDEVEN:
  1808. case ISD::VP_FROUND:
  1809. case ISD::VP_FROUNDEVEN:
  1810. case ISD::VP_FROUNDTOZERO: {
  1811. RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Op.getOpcode());
  1812. assert(FRM != RISCVFPRndMode::Invalid);
  1813. Truncated = DAG.getNode(RISCVISD::VFCVT_RM_X_F_VL, DL, IntVT, Src, Mask,
  1814. DAG.getTargetConstant(FRM, DL, XLenVT), VL);
  1815. break;
  1816. }
  1817. case ISD::FTRUNC:
  1818. Truncated = DAG.getNode(RISCVISD::VFCVT_RTZ_X_F_VL, DL, IntVT, Src,
  1819. Mask, VL);
  1820. break;
  1821. case ISD::VP_FRINT:
  1822. Truncated = DAG.getNode(RISCVISD::VFCVT_X_F_VL, DL, IntVT, Src, Mask, VL);
  1823. break;
  1824. case ISD::VP_FNEARBYINT:
  1825. Truncated = DAG.getNode(RISCVISD::VFROUND_NOEXCEPT_VL, DL, ContainerVT, Src,
  1826. Mask, VL);
  1827. break;
  1828. }
  1829. // VFROUND_NOEXCEPT_VL includes SINT_TO_FP_VL.
  1830. if (Op.getOpcode() != ISD::VP_FNEARBYINT)
  1831. Truncated = DAG.getNode(RISCVISD::SINT_TO_FP_VL, DL, ContainerVT, Truncated,
  1832. Mask, VL);
  1833. // Restore the original sign so that -0.0 is preserved.
  1834. Truncated = DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Truncated,
  1835. Src, Src, Mask, VL);
  1836. if (!VT.isFixedLengthVector())
  1837. return Truncated;
  1838. return convertFromScalableVector(VT, Truncated, DAG, Subtarget);
  1839. }
  1840. static SDValue
  1841. lowerFTRUNC_FCEIL_FFLOOR_FROUND(SDValue Op, SelectionDAG &DAG,
  1842. const RISCVSubtarget &Subtarget) {
  1843. MVT VT = Op.getSimpleValueType();
  1844. if (VT.isVector())
  1845. return lowerVectorFTRUNC_FCEIL_FFLOOR_FROUND(Op, DAG, Subtarget);
  1846. if (DAG.shouldOptForSize())
  1847. return SDValue();
  1848. SDLoc DL(Op);
  1849. SDValue Src = Op.getOperand(0);
  1850. // Create an integer the size of the mantissa with the MSB set. This and all
  1851. // values larger than it don't have any fractional bits so don't need to be
  1852. // converted.
  1853. const fltSemantics &FltSem = DAG.EVTToAPFloatSemantics(VT);
  1854. unsigned Precision = APFloat::semanticsPrecision(FltSem);
  1855. APFloat MaxVal = APFloat(FltSem);
  1856. MaxVal.convertFromAPInt(APInt::getOneBitSet(Precision, Precision - 1),
  1857. /*IsSigned*/ false, APFloat::rmNearestTiesToEven);
  1858. SDValue MaxValNode = DAG.getConstantFP(MaxVal, DL, VT);
  1859. RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Op.getOpcode());
  1860. return DAG.getNode(RISCVISD::FROUND, DL, VT, Src, MaxValNode,
  1861. DAG.getTargetConstant(FRM, DL, Subtarget.getXLenVT()));
  1862. }
  1863. struct VIDSequence {
  1864. int64_t StepNumerator;
  1865. unsigned StepDenominator;
  1866. int64_t Addend;
  1867. };
  1868. static std::optional<uint64_t> getExactInteger(const APFloat &APF,
  1869. uint32_t BitWidth) {
  1870. APSInt ValInt(BitWidth, !APF.isNegative());
  1871. // We use an arbitrary rounding mode here. If a floating-point is an exact
  1872. // integer (e.g., 1.0), the rounding mode does not affect the output value. If
  1873. // the rounding mode changes the output value, then it is not an exact
  1874. // integer.
  1875. RoundingMode ArbitraryRM = RoundingMode::TowardZero;
  1876. bool IsExact;
  1877. // If it is out of signed integer range, it will return an invalid operation.
  1878. // If it is not an exact integer, IsExact is false.
  1879. if ((APF.convertToInteger(ValInt, ArbitraryRM, &IsExact) ==
  1880. APFloatBase::opInvalidOp) ||
  1881. !IsExact)
  1882. return std::nullopt;
  1883. return ValInt.extractBitsAsZExtValue(BitWidth, 0);
  1884. }
  1885. // Try to match an arithmetic-sequence BUILD_VECTOR [X,X+S,X+2*S,...,X+(N-1)*S]
  1886. // to the (non-zero) step S and start value X. This can be then lowered as the
  1887. // RVV sequence (VID * S) + X, for example.
  1888. // The step S is represented as an integer numerator divided by a positive
  1889. // denominator. Note that the implementation currently only identifies
  1890. // sequences in which either the numerator is +/- 1 or the denominator is 1. It
  1891. // cannot detect 2/3, for example.
  1892. // Note that this method will also match potentially unappealing index
  1893. // sequences, like <i32 0, i32 50939494>, however it is left to the caller to
  1894. // determine whether this is worth generating code for.
  1895. static std::optional<VIDSequence> isSimpleVIDSequence(SDValue Op) {
  1896. unsigned NumElts = Op.getNumOperands();
  1897. assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unexpected BUILD_VECTOR");
  1898. bool IsInteger = Op.getValueType().isInteger();
  1899. std::optional<unsigned> SeqStepDenom;
  1900. std::optional<int64_t> SeqStepNum, SeqAddend;
  1901. std::optional<std::pair<uint64_t, unsigned>> PrevElt;
  1902. unsigned EltSizeInBits = Op.getValueType().getScalarSizeInBits();
  1903. for (unsigned Idx = 0; Idx < NumElts; Idx++) {
  1904. // Assume undef elements match the sequence; we just have to be careful
  1905. // when interpolating across them.
  1906. if (Op.getOperand(Idx).isUndef())
  1907. continue;
  1908. uint64_t Val;
  1909. if (IsInteger) {
  1910. // The BUILD_VECTOR must be all constants.
  1911. if (!isa<ConstantSDNode>(Op.getOperand(Idx)))
  1912. return std::nullopt;
  1913. Val = Op.getConstantOperandVal(Idx) &
  1914. maskTrailingOnes<uint64_t>(EltSizeInBits);
  1915. } else {
  1916. // The BUILD_VECTOR must be all constants.
  1917. if (!isa<ConstantFPSDNode>(Op.getOperand(Idx)))
  1918. return std::nullopt;
  1919. if (auto ExactInteger = getExactInteger(
  1920. cast<ConstantFPSDNode>(Op.getOperand(Idx))->getValueAPF(),
  1921. EltSizeInBits))
  1922. Val = *ExactInteger;
  1923. else
  1924. return std::nullopt;
  1925. }
  1926. if (PrevElt) {
  1927. // Calculate the step since the last non-undef element, and ensure
  1928. // it's consistent across the entire sequence.
  1929. unsigned IdxDiff = Idx - PrevElt->second;
  1930. int64_t ValDiff = SignExtend64(Val - PrevElt->first, EltSizeInBits);
  1931. // A zero-value value difference means that we're somewhere in the middle
  1932. // of a fractional step, e.g. <0,0,0*,0,1,1,1,1>. Wait until we notice a
  1933. // step change before evaluating the sequence.
  1934. if (ValDiff == 0)
  1935. continue;
  1936. int64_t Remainder = ValDiff % IdxDiff;
  1937. // Normalize the step if it's greater than 1.
  1938. if (Remainder != ValDiff) {
  1939. // The difference must cleanly divide the element span.
  1940. if (Remainder != 0)
  1941. return std::nullopt;
  1942. ValDiff /= IdxDiff;
  1943. IdxDiff = 1;
  1944. }
  1945. if (!SeqStepNum)
  1946. SeqStepNum = ValDiff;
  1947. else if (ValDiff != SeqStepNum)
  1948. return std::nullopt;
  1949. if (!SeqStepDenom)
  1950. SeqStepDenom = IdxDiff;
  1951. else if (IdxDiff != *SeqStepDenom)
  1952. return std::nullopt;
  1953. }
  1954. // Record this non-undef element for later.
  1955. if (!PrevElt || PrevElt->first != Val)
  1956. PrevElt = std::make_pair(Val, Idx);
  1957. }
  1958. // We need to have logged a step for this to count as a legal index sequence.
  1959. if (!SeqStepNum || !SeqStepDenom)
  1960. return std::nullopt;
  1961. // Loop back through the sequence and validate elements we might have skipped
  1962. // while waiting for a valid step. While doing this, log any sequence addend.
  1963. for (unsigned Idx = 0; Idx < NumElts; Idx++) {
  1964. if (Op.getOperand(Idx).isUndef())
  1965. continue;
  1966. uint64_t Val;
  1967. if (IsInteger) {
  1968. Val = Op.getConstantOperandVal(Idx) &
  1969. maskTrailingOnes<uint64_t>(EltSizeInBits);
  1970. } else {
  1971. Val = *getExactInteger(
  1972. cast<ConstantFPSDNode>(Op.getOperand(Idx))->getValueAPF(),
  1973. EltSizeInBits);
  1974. }
  1975. uint64_t ExpectedVal =
  1976. (int64_t)(Idx * (uint64_t)*SeqStepNum) / *SeqStepDenom;
  1977. int64_t Addend = SignExtend64(Val - ExpectedVal, EltSizeInBits);
  1978. if (!SeqAddend)
  1979. SeqAddend = Addend;
  1980. else if (Addend != SeqAddend)
  1981. return std::nullopt;
  1982. }
  1983. assert(SeqAddend && "Must have an addend if we have a step");
  1984. return VIDSequence{*SeqStepNum, *SeqStepDenom, *SeqAddend};
  1985. }
  1986. // Match a splatted value (SPLAT_VECTOR/BUILD_VECTOR) of an EXTRACT_VECTOR_ELT
  1987. // and lower it as a VRGATHER_VX_VL from the source vector.
  1988. static SDValue matchSplatAsGather(SDValue SplatVal, MVT VT, const SDLoc &DL,
  1989. SelectionDAG &DAG,
  1990. const RISCVSubtarget &Subtarget) {
  1991. if (SplatVal.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
  1992. return SDValue();
  1993. SDValue Vec = SplatVal.getOperand(0);
  1994. // Only perform this optimization on vectors of the same size for simplicity.
  1995. // Don't perform this optimization for i1 vectors.
  1996. // FIXME: Support i1 vectors, maybe by promoting to i8?
  1997. if (Vec.getValueType() != VT || VT.getVectorElementType() == MVT::i1)
  1998. return SDValue();
  1999. SDValue Idx = SplatVal.getOperand(1);
  2000. // The index must be a legal type.
  2001. if (Idx.getValueType() != Subtarget.getXLenVT())
  2002. return SDValue();
  2003. MVT ContainerVT = VT;
  2004. if (VT.isFixedLengthVector()) {
  2005. ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
  2006. Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
  2007. }
  2008. auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
  2009. SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT, Vec,
  2010. Idx, DAG.getUNDEF(ContainerVT), Mask, VL);
  2011. if (!VT.isFixedLengthVector())
  2012. return Gather;
  2013. return convertFromScalableVector(VT, Gather, DAG, Subtarget);
  2014. }
  2015. static SDValue lowerBUILD_VECTOR(SDValue Op, SelectionDAG &DAG,
  2016. const RISCVSubtarget &Subtarget) {
  2017. MVT VT = Op.getSimpleValueType();
  2018. assert(VT.isFixedLengthVector() && "Unexpected vector!");
  2019. MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
  2020. SDLoc DL(Op);
  2021. auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
  2022. MVT XLenVT = Subtarget.getXLenVT();
  2023. unsigned NumElts = Op.getNumOperands();
  2024. if (VT.getVectorElementType() == MVT::i1) {
  2025. if (ISD::isBuildVectorAllZeros(Op.getNode())) {
  2026. SDValue VMClr = DAG.getNode(RISCVISD::VMCLR_VL, DL, ContainerVT, VL);
  2027. return convertFromScalableVector(VT, VMClr, DAG, Subtarget);
  2028. }
  2029. if (ISD::isBuildVectorAllOnes(Op.getNode())) {
  2030. SDValue VMSet = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
  2031. return convertFromScalableVector(VT, VMSet, DAG, Subtarget);
  2032. }
  2033. // Lower constant mask BUILD_VECTORs via an integer vector type, in
  2034. // scalar integer chunks whose bit-width depends on the number of mask
  2035. // bits and XLEN.
  2036. // First, determine the most appropriate scalar integer type to use. This
  2037. // is at most XLenVT, but may be shrunk to a smaller vector element type
  2038. // according to the size of the final vector - use i8 chunks rather than
  2039. // XLenVT if we're producing a v8i1. This results in more consistent
  2040. // codegen across RV32 and RV64.
  2041. unsigned NumViaIntegerBits =
  2042. std::min(std::max(NumElts, 8u), Subtarget.getXLen());
  2043. NumViaIntegerBits = std::min(NumViaIntegerBits, Subtarget.getELEN());
  2044. if (ISD::isBuildVectorOfConstantSDNodes(Op.getNode())) {
  2045. // If we have to use more than one INSERT_VECTOR_ELT then this
  2046. // optimization is likely to increase code size; avoid peforming it in
  2047. // such a case. We can use a load from a constant pool in this case.
  2048. if (DAG.shouldOptForSize() && NumElts > NumViaIntegerBits)
  2049. return SDValue();
  2050. // Now we can create our integer vector type. Note that it may be larger
  2051. // than the resulting mask type: v4i1 would use v1i8 as its integer type.
  2052. MVT IntegerViaVecVT =
  2053. MVT::getVectorVT(MVT::getIntegerVT(NumViaIntegerBits),
  2054. divideCeil(NumElts, NumViaIntegerBits));
  2055. uint64_t Bits = 0;
  2056. unsigned BitPos = 0, IntegerEltIdx = 0;
  2057. SDValue Vec = DAG.getUNDEF(IntegerViaVecVT);
  2058. for (unsigned I = 0; I < NumElts; I++, BitPos++) {
  2059. // Once we accumulate enough bits to fill our scalar type, insert into
  2060. // our vector and clear our accumulated data.
  2061. if (I != 0 && I % NumViaIntegerBits == 0) {
  2062. if (NumViaIntegerBits <= 32)
  2063. Bits = SignExtend64<32>(Bits);
  2064. SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
  2065. Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec,
  2066. Elt, DAG.getConstant(IntegerEltIdx, DL, XLenVT));
  2067. Bits = 0;
  2068. BitPos = 0;
  2069. IntegerEltIdx++;
  2070. }
  2071. SDValue V = Op.getOperand(I);
  2072. bool BitValue = !V.isUndef() && cast<ConstantSDNode>(V)->getZExtValue();
  2073. Bits |= ((uint64_t)BitValue << BitPos);
  2074. }
  2075. // Insert the (remaining) scalar value into position in our integer
  2076. // vector type.
  2077. if (NumViaIntegerBits <= 32)
  2078. Bits = SignExtend64<32>(Bits);
  2079. SDValue Elt = DAG.getConstant(Bits, DL, XLenVT);
  2080. Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, IntegerViaVecVT, Vec, Elt,
  2081. DAG.getConstant(IntegerEltIdx, DL, XLenVT));
  2082. if (NumElts < NumViaIntegerBits) {
  2083. // If we're producing a smaller vector than our minimum legal integer
  2084. // type, bitcast to the equivalent (known-legal) mask type, and extract
  2085. // our final mask.
  2086. assert(IntegerViaVecVT == MVT::v1i8 && "Unexpected mask vector type");
  2087. Vec = DAG.getBitcast(MVT::v8i1, Vec);
  2088. Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Vec,
  2089. DAG.getConstant(0, DL, XLenVT));
  2090. } else {
  2091. // Else we must have produced an integer type with the same size as the
  2092. // mask type; bitcast for the final result.
  2093. assert(VT.getSizeInBits() == IntegerViaVecVT.getSizeInBits());
  2094. Vec = DAG.getBitcast(VT, Vec);
  2095. }
  2096. return Vec;
  2097. }
  2098. // A BUILD_VECTOR can be lowered as a SETCC. For each fixed-length mask
  2099. // vector type, we have a legal equivalently-sized i8 type, so we can use
  2100. // that.
  2101. MVT WideVecVT = VT.changeVectorElementType(MVT::i8);
  2102. SDValue VecZero = DAG.getConstant(0, DL, WideVecVT);
  2103. SDValue WideVec;
  2104. if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
  2105. // For a splat, perform a scalar truncate before creating the wider
  2106. // vector.
  2107. assert(Splat.getValueType() == XLenVT &&
  2108. "Unexpected type for i1 splat value");
  2109. Splat = DAG.getNode(ISD::AND, DL, XLenVT, Splat,
  2110. DAG.getConstant(1, DL, XLenVT));
  2111. WideVec = DAG.getSplatBuildVector(WideVecVT, DL, Splat);
  2112. } else {
  2113. SmallVector<SDValue, 8> Ops(Op->op_values());
  2114. WideVec = DAG.getBuildVector(WideVecVT, DL, Ops);
  2115. SDValue VecOne = DAG.getConstant(1, DL, WideVecVT);
  2116. WideVec = DAG.getNode(ISD::AND, DL, WideVecVT, WideVec, VecOne);
  2117. }
  2118. return DAG.getSetCC(DL, VT, WideVec, VecZero, ISD::SETNE);
  2119. }
  2120. if (SDValue Splat = cast<BuildVectorSDNode>(Op)->getSplatValue()) {
  2121. if (auto Gather = matchSplatAsGather(Splat, VT, DL, DAG, Subtarget))
  2122. return Gather;
  2123. unsigned Opc = VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL
  2124. : RISCVISD::VMV_V_X_VL;
  2125. Splat =
  2126. DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), Splat, VL);
  2127. return convertFromScalableVector(VT, Splat, DAG, Subtarget);
  2128. }
  2129. // Try and match index sequences, which we can lower to the vid instruction
  2130. // with optional modifications. An all-undef vector is matched by
  2131. // getSplatValue, above.
  2132. if (auto SimpleVID = isSimpleVIDSequence(Op)) {
  2133. int64_t StepNumerator = SimpleVID->StepNumerator;
  2134. unsigned StepDenominator = SimpleVID->StepDenominator;
  2135. int64_t Addend = SimpleVID->Addend;
  2136. assert(StepNumerator != 0 && "Invalid step");
  2137. bool Negate = false;
  2138. int64_t SplatStepVal = StepNumerator;
  2139. unsigned StepOpcode = ISD::MUL;
  2140. if (StepNumerator != 1) {
  2141. if (isPowerOf2_64(std::abs(StepNumerator))) {
  2142. Negate = StepNumerator < 0;
  2143. StepOpcode = ISD::SHL;
  2144. SplatStepVal = Log2_64(std::abs(StepNumerator));
  2145. }
  2146. }
  2147. // Only emit VIDs with suitably-small steps/addends. We use imm5 is a
  2148. // threshold since it's the immediate value many RVV instructions accept.
  2149. // There is no vmul.vi instruction so ensure multiply constant can fit in
  2150. // a single addi instruction.
  2151. if (((StepOpcode == ISD::MUL && isInt<12>(SplatStepVal)) ||
  2152. (StepOpcode == ISD::SHL && isUInt<5>(SplatStepVal))) &&
  2153. isPowerOf2_32(StepDenominator) &&
  2154. (SplatStepVal >= 0 || StepDenominator == 1) && isInt<5>(Addend)) {
  2155. MVT VIDVT =
  2156. VT.isFloatingPoint() ? VT.changeVectorElementTypeToInteger() : VT;
  2157. MVT VIDContainerVT =
  2158. getContainerForFixedLengthVector(DAG, VIDVT, Subtarget);
  2159. SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VIDContainerVT, Mask, VL);
  2160. // Convert right out of the scalable type so we can use standard ISD
  2161. // nodes for the rest of the computation. If we used scalable types with
  2162. // these, we'd lose the fixed-length vector info and generate worse
  2163. // vsetvli code.
  2164. VID = convertFromScalableVector(VIDVT, VID, DAG, Subtarget);
  2165. if ((StepOpcode == ISD::MUL && SplatStepVal != 1) ||
  2166. (StepOpcode == ISD::SHL && SplatStepVal != 0)) {
  2167. SDValue SplatStep = DAG.getSplatBuildVector(
  2168. VIDVT, DL, DAG.getConstant(SplatStepVal, DL, XLenVT));
  2169. VID = DAG.getNode(StepOpcode, DL, VIDVT, VID, SplatStep);
  2170. }
  2171. if (StepDenominator != 1) {
  2172. SDValue SplatStep = DAG.getSplatBuildVector(
  2173. VIDVT, DL, DAG.getConstant(Log2_64(StepDenominator), DL, XLenVT));
  2174. VID = DAG.getNode(ISD::SRL, DL, VIDVT, VID, SplatStep);
  2175. }
  2176. if (Addend != 0 || Negate) {
  2177. SDValue SplatAddend = DAG.getSplatBuildVector(
  2178. VIDVT, DL, DAG.getConstant(Addend, DL, XLenVT));
  2179. VID = DAG.getNode(Negate ? ISD::SUB : ISD::ADD, DL, VIDVT, SplatAddend,
  2180. VID);
  2181. }
  2182. if (VT.isFloatingPoint()) {
  2183. // TODO: Use vfwcvt to reduce register pressure.
  2184. VID = DAG.getNode(ISD::SINT_TO_FP, DL, VT, VID);
  2185. }
  2186. return VID;
  2187. }
  2188. }
  2189. // Attempt to detect "hidden" splats, which only reveal themselves as splats
  2190. // when re-interpreted as a vector with a larger element type. For example,
  2191. // v4i16 = build_vector i16 0, i16 1, i16 0, i16 1
  2192. // could be instead splat as
  2193. // v2i32 = build_vector i32 0x00010000, i32 0x00010000
  2194. // TODO: This optimization could also work on non-constant splats, but it
  2195. // would require bit-manipulation instructions to construct the splat value.
  2196. SmallVector<SDValue> Sequence;
  2197. unsigned EltBitSize = VT.getScalarSizeInBits();
  2198. const auto *BV = cast<BuildVectorSDNode>(Op);
  2199. if (VT.isInteger() && EltBitSize < 64 &&
  2200. ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) &&
  2201. BV->getRepeatedSequence(Sequence) &&
  2202. (Sequence.size() * EltBitSize) <= 64) {
  2203. unsigned SeqLen = Sequence.size();
  2204. MVT ViaIntVT = MVT::getIntegerVT(EltBitSize * SeqLen);
  2205. MVT ViaVecVT = MVT::getVectorVT(ViaIntVT, NumElts / SeqLen);
  2206. assert((ViaIntVT == MVT::i16 || ViaIntVT == MVT::i32 ||
  2207. ViaIntVT == MVT::i64) &&
  2208. "Unexpected sequence type");
  2209. unsigned EltIdx = 0;
  2210. uint64_t EltMask = maskTrailingOnes<uint64_t>(EltBitSize);
  2211. uint64_t SplatValue = 0;
  2212. // Construct the amalgamated value which can be splatted as this larger
  2213. // vector type.
  2214. for (const auto &SeqV : Sequence) {
  2215. if (!SeqV.isUndef())
  2216. SplatValue |= ((cast<ConstantSDNode>(SeqV)->getZExtValue() & EltMask)
  2217. << (EltIdx * EltBitSize));
  2218. EltIdx++;
  2219. }
  2220. // On RV64, sign-extend from 32 to 64 bits where possible in order to
  2221. // achieve better constant materializion.
  2222. if (Subtarget.is64Bit() && ViaIntVT == MVT::i32)
  2223. SplatValue = SignExtend64<32>(SplatValue);
  2224. // Since we can't introduce illegal i64 types at this stage, we can only
  2225. // perform an i64 splat on RV32 if it is its own sign-extended value. That
  2226. // way we can use RVV instructions to splat.
  2227. assert((ViaIntVT.bitsLE(XLenVT) ||
  2228. (!Subtarget.is64Bit() && ViaIntVT == MVT::i64)) &&
  2229. "Unexpected bitcast sequence");
  2230. if (ViaIntVT.bitsLE(XLenVT) || isInt<32>(SplatValue)) {
  2231. SDValue ViaVL =
  2232. DAG.getConstant(ViaVecVT.getVectorNumElements(), DL, XLenVT);
  2233. MVT ViaContainerVT =
  2234. getContainerForFixedLengthVector(DAG, ViaVecVT, Subtarget);
  2235. SDValue Splat =
  2236. DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ViaContainerVT,
  2237. DAG.getUNDEF(ViaContainerVT),
  2238. DAG.getConstant(SplatValue, DL, XLenVT), ViaVL);
  2239. Splat = convertFromScalableVector(ViaVecVT, Splat, DAG, Subtarget);
  2240. return DAG.getBitcast(VT, Splat);
  2241. }
  2242. }
  2243. // Try and optimize BUILD_VECTORs with "dominant values" - these are values
  2244. // which constitute a large proportion of the elements. In such cases we can
  2245. // splat a vector with the dominant element and make up the shortfall with
  2246. // INSERT_VECTOR_ELTs.
  2247. // Note that this includes vectors of 2 elements by association. The
  2248. // upper-most element is the "dominant" one, allowing us to use a splat to
  2249. // "insert" the upper element, and an insert of the lower element at position
  2250. // 0, which improves codegen.
  2251. SDValue DominantValue;
  2252. unsigned MostCommonCount = 0;
  2253. DenseMap<SDValue, unsigned> ValueCounts;
  2254. unsigned NumUndefElts =
  2255. count_if(Op->op_values(), [](const SDValue &V) { return V.isUndef(); });
  2256. // Track the number of scalar loads we know we'd be inserting, estimated as
  2257. // any non-zero floating-point constant. Other kinds of element are either
  2258. // already in registers or are materialized on demand. The threshold at which
  2259. // a vector load is more desirable than several scalar materializion and
  2260. // vector-insertion instructions is not known.
  2261. unsigned NumScalarLoads = 0;
  2262. for (SDValue V : Op->op_values()) {
  2263. if (V.isUndef())
  2264. continue;
  2265. ValueCounts.insert(std::make_pair(V, 0));
  2266. unsigned &Count = ValueCounts[V];
  2267. if (auto *CFP = dyn_cast<ConstantFPSDNode>(V))
  2268. NumScalarLoads += !CFP->isExactlyValue(+0.0);
  2269. // Is this value dominant? In case of a tie, prefer the highest element as
  2270. // it's cheaper to insert near the beginning of a vector than it is at the
  2271. // end.
  2272. if (++Count >= MostCommonCount) {
  2273. DominantValue = V;
  2274. MostCommonCount = Count;
  2275. }
  2276. }
  2277. assert(DominantValue && "Not expecting an all-undef BUILD_VECTOR");
  2278. unsigned NumDefElts = NumElts - NumUndefElts;
  2279. unsigned DominantValueCountThreshold = NumDefElts <= 2 ? 0 : NumDefElts - 2;
  2280. // Don't perform this optimization when optimizing for size, since
  2281. // materializing elements and inserting them tends to cause code bloat.
  2282. if (!DAG.shouldOptForSize() && NumScalarLoads < NumElts &&
  2283. ((MostCommonCount > DominantValueCountThreshold) ||
  2284. (ValueCounts.size() <= Log2_32(NumDefElts)))) {
  2285. // Start by splatting the most common element.
  2286. SDValue Vec = DAG.getSplatBuildVector(VT, DL, DominantValue);
  2287. DenseSet<SDValue> Processed{DominantValue};
  2288. MVT SelMaskTy = VT.changeVectorElementType(MVT::i1);
  2289. for (const auto &OpIdx : enumerate(Op->ops())) {
  2290. const SDValue &V = OpIdx.value();
  2291. if (V.isUndef() || !Processed.insert(V).second)
  2292. continue;
  2293. if (ValueCounts[V] == 1) {
  2294. Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT, Vec, V,
  2295. DAG.getConstant(OpIdx.index(), DL, XLenVT));
  2296. } else {
  2297. // Blend in all instances of this value using a VSELECT, using a
  2298. // mask where each bit signals whether that element is the one
  2299. // we're after.
  2300. SmallVector<SDValue> Ops;
  2301. transform(Op->op_values(), std::back_inserter(Ops), [&](SDValue V1) {
  2302. return DAG.getConstant(V == V1, DL, XLenVT);
  2303. });
  2304. Vec = DAG.getNode(ISD::VSELECT, DL, VT,
  2305. DAG.getBuildVector(SelMaskTy, DL, Ops),
  2306. DAG.getSplatBuildVector(VT, DL, V), Vec);
  2307. }
  2308. }
  2309. return Vec;
  2310. }
  2311. return SDValue();
  2312. }
  2313. static SDValue splatPartsI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
  2314. SDValue Lo, SDValue Hi, SDValue VL,
  2315. SelectionDAG &DAG) {
  2316. if (!Passthru)
  2317. Passthru = DAG.getUNDEF(VT);
  2318. if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
  2319. int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
  2320. int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
  2321. // If Hi constant is all the same sign bit as Lo, lower this as a custom
  2322. // node in order to try and match RVV vector/scalar instructions.
  2323. if ((LoC >> 31) == HiC)
  2324. return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Lo, VL);
  2325. // If vl is equal to XLEN_MAX and Hi constant is equal to Lo, we could use
  2326. // vmv.v.x whose EEW = 32 to lower it.
  2327. auto *Const = dyn_cast<ConstantSDNode>(VL);
  2328. if (LoC == HiC && Const && Const->isAllOnesValue()) {
  2329. MVT InterVT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
  2330. // TODO: if vl <= min(VLMAX), we can also do this. But we could not
  2331. // access the subtarget here now.
  2332. auto InterVec = DAG.getNode(
  2333. RISCVISD::VMV_V_X_VL, DL, InterVT, DAG.getUNDEF(InterVT), Lo,
  2334. DAG.getRegister(RISCV::X0, MVT::i32));
  2335. return DAG.getNode(ISD::BITCAST, DL, VT, InterVec);
  2336. }
  2337. }
  2338. // Fall back to a stack store and stride x0 vector load.
  2339. return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VT, Passthru, Lo,
  2340. Hi, VL);
  2341. }
  2342. // Called by type legalization to handle splat of i64 on RV32.
  2343. // FIXME: We can optimize this when the type has sign or zero bits in one
  2344. // of the halves.
  2345. static SDValue splatSplitI64WithVL(const SDLoc &DL, MVT VT, SDValue Passthru,
  2346. SDValue Scalar, SDValue VL,
  2347. SelectionDAG &DAG) {
  2348. assert(Scalar.getValueType() == MVT::i64 && "Unexpected VT!");
  2349. SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
  2350. DAG.getConstant(0, DL, MVT::i32));
  2351. SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Scalar,
  2352. DAG.getConstant(1, DL, MVT::i32));
  2353. return splatPartsI64WithVL(DL, VT, Passthru, Lo, Hi, VL, DAG);
  2354. }
  2355. // This function lowers a splat of a scalar operand Splat with the vector
  2356. // length VL. It ensures the final sequence is type legal, which is useful when
  2357. // lowering a splat after type legalization.
  2358. static SDValue lowerScalarSplat(SDValue Passthru, SDValue Scalar, SDValue VL,
  2359. MVT VT, SDLoc DL, SelectionDAG &DAG,
  2360. const RISCVSubtarget &Subtarget) {
  2361. bool HasPassthru = Passthru && !Passthru.isUndef();
  2362. if (!HasPassthru && !Passthru)
  2363. Passthru = DAG.getUNDEF(VT);
  2364. if (VT.isFloatingPoint()) {
  2365. // If VL is 1, we could use vfmv.s.f.
  2366. if (isOneConstant(VL))
  2367. return DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, VT, Passthru, Scalar, VL);
  2368. return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, VT, Passthru, Scalar, VL);
  2369. }
  2370. MVT XLenVT = Subtarget.getXLenVT();
  2371. // Simplest case is that the operand needs to be promoted to XLenVT.
  2372. if (Scalar.getValueType().bitsLE(XLenVT)) {
  2373. // If the operand is a constant, sign extend to increase our chances
  2374. // of being able to use a .vi instruction. ANY_EXTEND would become a
  2375. // a zero extend and the simm5 check in isel would fail.
  2376. // FIXME: Should we ignore the upper bits in isel instead?
  2377. unsigned ExtOpc =
  2378. isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
  2379. Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
  2380. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar);
  2381. // If VL is 1 and the scalar value won't benefit from immediate, we could
  2382. // use vmv.s.x.
  2383. if (isOneConstant(VL) &&
  2384. (!Const || isNullConstant(Scalar) || !isInt<5>(Const->getSExtValue())))
  2385. return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru, Scalar, VL);
  2386. return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
  2387. }
  2388. assert(XLenVT == MVT::i32 && Scalar.getValueType() == MVT::i64 &&
  2389. "Unexpected scalar for splat lowering!");
  2390. if (isOneConstant(VL) && isNullConstant(Scalar))
  2391. return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, VT, Passthru,
  2392. DAG.getConstant(0, DL, XLenVT), VL);
  2393. // Otherwise use the more complicated splatting algorithm.
  2394. return splatSplitI64WithVL(DL, VT, Passthru, Scalar, VL, DAG);
  2395. }
  2396. static MVT getLMUL1VT(MVT VT) {
  2397. assert(VT.getVectorElementType().getSizeInBits() <= 64 &&
  2398. "Unexpected vector MVT");
  2399. return MVT::getScalableVectorVT(
  2400. VT.getVectorElementType(),
  2401. RISCV::RVVBitsPerBlock / VT.getVectorElementType().getSizeInBits());
  2402. }
  2403. // This function lowers an insert of a scalar operand Scalar into lane
  2404. // 0 of the vector regardless of the value of VL. The contents of the
  2405. // remaining lanes of the result vector are unspecified. VL is assumed
  2406. // to be non-zero.
  2407. static SDValue lowerScalarInsert(SDValue Scalar, SDValue VL,
  2408. MVT VT, SDLoc DL, SelectionDAG &DAG,
  2409. const RISCVSubtarget &Subtarget) {
  2410. const MVT XLenVT = Subtarget.getXLenVT();
  2411. SDValue Passthru = DAG.getUNDEF(VT);
  2412. if (VT.isFloatingPoint()) {
  2413. // TODO: Use vmv.v.i for appropriate constants
  2414. // Use M1 or smaller to avoid over constraining register allocation
  2415. const MVT M1VT = getLMUL1VT(VT);
  2416. auto InnerVT = VT.bitsLE(M1VT) ? VT : M1VT;
  2417. SDValue Result = DAG.getNode(RISCVISD::VFMV_S_F_VL, DL, InnerVT,
  2418. DAG.getUNDEF(InnerVT), Scalar, VL);
  2419. if (VT != InnerVT)
  2420. Result = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
  2421. DAG.getUNDEF(VT),
  2422. Result, DAG.getConstant(0, DL, XLenVT));
  2423. return Result;
  2424. }
  2425. // Avoid the tricky legalization cases by falling back to using the
  2426. // splat code which already handles it gracefully.
  2427. if (!Scalar.getValueType().bitsLE(XLenVT))
  2428. return lowerScalarSplat(DAG.getUNDEF(VT), Scalar,
  2429. DAG.getConstant(1, DL, XLenVT),
  2430. VT, DL, DAG, Subtarget);
  2431. // If the operand is a constant, sign extend to increase our chances
  2432. // of being able to use a .vi instruction. ANY_EXTEND would become a
  2433. // a zero extend and the simm5 check in isel would fail.
  2434. // FIXME: Should we ignore the upper bits in isel instead?
  2435. unsigned ExtOpc =
  2436. isa<ConstantSDNode>(Scalar) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
  2437. Scalar = DAG.getNode(ExtOpc, DL, XLenVT, Scalar);
  2438. // We use a vmv.v.i if possible. We limit this to LMUL1. LMUL2 or
  2439. // higher would involve overly constraining the register allocator for
  2440. // no purpose.
  2441. if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Scalar)) {
  2442. if (!isNullConstant(Scalar) && isInt<5>(Const->getSExtValue()) &&
  2443. VT.bitsLE(getLMUL1VT(VT)))
  2444. return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, Passthru, Scalar, VL);
  2445. }
  2446. // Use M1 or smaller to avoid over constraining register allocation
  2447. const MVT M1VT = getLMUL1VT(VT);
  2448. auto InnerVT = VT.bitsLE(M1VT) ? VT : M1VT;
  2449. SDValue Result = DAG.getNode(RISCVISD::VMV_S_X_VL, DL, InnerVT,
  2450. DAG.getUNDEF(InnerVT), Scalar, VL);
  2451. if (VT != InnerVT)
  2452. Result = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
  2453. DAG.getUNDEF(VT),
  2454. Result, DAG.getConstant(0, DL, XLenVT));
  2455. return Result;
  2456. }
  2457. static bool isInterleaveShuffle(ArrayRef<int> Mask, MVT VT, bool &SwapSources,
  2458. const RISCVSubtarget &Subtarget) {
  2459. // We need to be able to widen elements to the next larger integer type.
  2460. if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
  2461. return false;
  2462. int Size = Mask.size();
  2463. assert(Size == (int)VT.getVectorNumElements() && "Unexpected mask size");
  2464. int Srcs[] = {-1, -1};
  2465. for (int i = 0; i != Size; ++i) {
  2466. // Ignore undef elements.
  2467. if (Mask[i] < 0)
  2468. continue;
  2469. // Is this an even or odd element.
  2470. int Pol = i % 2;
  2471. // Ensure we consistently use the same source for this element polarity.
  2472. int Src = Mask[i] / Size;
  2473. if (Srcs[Pol] < 0)
  2474. Srcs[Pol] = Src;
  2475. if (Srcs[Pol] != Src)
  2476. return false;
  2477. // Make sure the element within the source is appropriate for this element
  2478. // in the destination.
  2479. int Elt = Mask[i] % Size;
  2480. if (Elt != i / 2)
  2481. return false;
  2482. }
  2483. // We need to find a source for each polarity and they can't be the same.
  2484. if (Srcs[0] < 0 || Srcs[1] < 0 || Srcs[0] == Srcs[1])
  2485. return false;
  2486. // Swap the sources if the second source was in the even polarity.
  2487. SwapSources = Srcs[0] > Srcs[1];
  2488. return true;
  2489. }
  2490. /// Match shuffles that concatenate two vectors, rotate the concatenation,
  2491. /// and then extract the original number of elements from the rotated result.
  2492. /// This is equivalent to vector.splice or X86's PALIGNR instruction. The
  2493. /// returned rotation amount is for a rotate right, where elements move from
  2494. /// higher elements to lower elements. \p LoSrc indicates the first source
  2495. /// vector of the rotate or -1 for undef. \p HiSrc indicates the second vector
  2496. /// of the rotate or -1 for undef. At least one of \p LoSrc and \p HiSrc will be
  2497. /// 0 or 1 if a rotation is found.
  2498. ///
  2499. /// NOTE: We talk about rotate to the right which matches how bit shift and
  2500. /// rotate instructions are described where LSBs are on the right, but LLVM IR
  2501. /// and the table below write vectors with the lowest elements on the left.
  2502. static int isElementRotate(int &LoSrc, int &HiSrc, ArrayRef<int> Mask) {
  2503. int Size = Mask.size();
  2504. // We need to detect various ways of spelling a rotation:
  2505. // [11, 12, 13, 14, 15, 0, 1, 2]
  2506. // [-1, 12, 13, 14, -1, -1, 1, -1]
  2507. // [-1, -1, -1, -1, -1, -1, 1, 2]
  2508. // [ 3, 4, 5, 6, 7, 8, 9, 10]
  2509. // [-1, 4, 5, 6, -1, -1, 9, -1]
  2510. // [-1, 4, 5, 6, -1, -1, -1, -1]
  2511. int Rotation = 0;
  2512. LoSrc = -1;
  2513. HiSrc = -1;
  2514. for (int i = 0; i != Size; ++i) {
  2515. int M = Mask[i];
  2516. if (M < 0)
  2517. continue;
  2518. // Determine where a rotate vector would have started.
  2519. int StartIdx = i - (M % Size);
  2520. // The identity rotation isn't interesting, stop.
  2521. if (StartIdx == 0)
  2522. return -1;
  2523. // If we found the tail of a vector the rotation must be the missing
  2524. // front. If we found the head of a vector, it must be how much of the
  2525. // head.
  2526. int CandidateRotation = StartIdx < 0 ? -StartIdx : Size - StartIdx;
  2527. if (Rotation == 0)
  2528. Rotation = CandidateRotation;
  2529. else if (Rotation != CandidateRotation)
  2530. // The rotations don't match, so we can't match this mask.
  2531. return -1;
  2532. // Compute which value this mask is pointing at.
  2533. int MaskSrc = M < Size ? 0 : 1;
  2534. // Compute which of the two target values this index should be assigned to.
  2535. // This reflects whether the high elements are remaining or the low elemnts
  2536. // are remaining.
  2537. int &TargetSrc = StartIdx < 0 ? HiSrc : LoSrc;
  2538. // Either set up this value if we've not encountered it before, or check
  2539. // that it remains consistent.
  2540. if (TargetSrc < 0)
  2541. TargetSrc = MaskSrc;
  2542. else if (TargetSrc != MaskSrc)
  2543. // This may be a rotation, but it pulls from the inputs in some
  2544. // unsupported interleaving.
  2545. return -1;
  2546. }
  2547. // Check that we successfully analyzed the mask, and normalize the results.
  2548. assert(Rotation != 0 && "Failed to locate a viable rotation!");
  2549. assert((LoSrc >= 0 || HiSrc >= 0) &&
  2550. "Failed to find a rotated input vector!");
  2551. return Rotation;
  2552. }
  2553. // Lower the following shuffles to vnsrl.
  2554. // t34: v8i8 = extract_subvector t11, Constant:i64<0>
  2555. // t33: v8i8 = extract_subvector t11, Constant:i64<8>
  2556. // a) t35: v8i8 = vector_shuffle<0,2,4,6,8,10,12,14> t34, t33
  2557. // b) t35: v8i8 = vector_shuffle<1,3,5,7,9,11,13,15> t34, t33
  2558. static SDValue lowerVECTOR_SHUFFLEAsVNSRL(const SDLoc &DL, MVT VT,
  2559. MVT ContainerVT, SDValue V1,
  2560. SDValue V2, SDValue TrueMask,
  2561. SDValue VL, ArrayRef<int> Mask,
  2562. const RISCVSubtarget &Subtarget,
  2563. SelectionDAG &DAG) {
  2564. // Need to be able to widen the vector.
  2565. if (VT.getScalarSizeInBits() >= Subtarget.getELEN())
  2566. return SDValue();
  2567. // Both input must be extracts.
  2568. if (V1.getOpcode() != ISD::EXTRACT_SUBVECTOR ||
  2569. V2.getOpcode() != ISD::EXTRACT_SUBVECTOR)
  2570. return SDValue();
  2571. // Extracting from the same source.
  2572. SDValue Src = V1.getOperand(0);
  2573. if (Src != V2.getOperand(0))
  2574. return SDValue();
  2575. // Src needs to have twice the number of elements.
  2576. if (Src.getValueType().getVectorNumElements() != (Mask.size() * 2))
  2577. return SDValue();
  2578. // The extracts must extract the two halves of the source.
  2579. if (V1.getConstantOperandVal(1) != 0 ||
  2580. V2.getConstantOperandVal(1) != Mask.size())
  2581. return SDValue();
  2582. // First index must be the first even or odd element from V1.
  2583. if (Mask[0] != 0 && Mask[0] != 1)
  2584. return SDValue();
  2585. // The others must increase by 2 each time.
  2586. // TODO: Support undef elements?
  2587. for (unsigned i = 1; i != Mask.size(); ++i)
  2588. if (Mask[i] != Mask[i - 1] + 2)
  2589. return SDValue();
  2590. // Convert the source using a container type with twice the elements. Since
  2591. // source VT is legal and twice this VT, we know VT isn't LMUL=8 so it is
  2592. // safe to double.
  2593. MVT DoubleContainerVT =
  2594. MVT::getVectorVT(ContainerVT.getVectorElementType(),
  2595. ContainerVT.getVectorElementCount() * 2);
  2596. Src = convertToScalableVector(DoubleContainerVT, Src, DAG, Subtarget);
  2597. // Convert the vector to a wider integer type with the original element
  2598. // count. This also converts FP to int.
  2599. unsigned EltBits = ContainerVT.getScalarSizeInBits();
  2600. MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
  2601. MVT WideIntContainerVT =
  2602. MVT::getVectorVT(WideIntEltVT, ContainerVT.getVectorElementCount());
  2603. Src = DAG.getBitcast(WideIntContainerVT, Src);
  2604. // Convert to the integer version of the container type.
  2605. MVT IntEltVT = MVT::getIntegerVT(EltBits);
  2606. MVT IntContainerVT =
  2607. MVT::getVectorVT(IntEltVT, ContainerVT.getVectorElementCount());
  2608. // If we want even elements, then the shift amount is 0. Otherwise, shift by
  2609. // the original element size.
  2610. unsigned Shift = Mask[0] == 0 ? 0 : EltBits;
  2611. SDValue SplatShift = DAG.getNode(
  2612. RISCVISD::VMV_V_X_VL, DL, IntContainerVT, DAG.getUNDEF(ContainerVT),
  2613. DAG.getConstant(Shift, DL, Subtarget.getXLenVT()), VL);
  2614. SDValue Res =
  2615. DAG.getNode(RISCVISD::VNSRL_VL, DL, IntContainerVT, Src, SplatShift,
  2616. DAG.getUNDEF(IntContainerVT), TrueMask, VL);
  2617. // Cast back to FP if needed.
  2618. Res = DAG.getBitcast(ContainerVT, Res);
  2619. return convertFromScalableVector(VT, Res, DAG, Subtarget);
  2620. }
  2621. static SDValue
  2622. getVSlidedown(SelectionDAG &DAG, const RISCVSubtarget &Subtarget, SDLoc DL,
  2623. EVT VT, SDValue Merge, SDValue Op, SDValue Offset, SDValue Mask,
  2624. SDValue VL,
  2625. unsigned Policy = RISCVII::TAIL_UNDISTURBED_MASK_UNDISTURBED) {
  2626. if (Merge.isUndef())
  2627. Policy = RISCVII::TAIL_AGNOSTIC | RISCVII::MASK_AGNOSTIC;
  2628. SDValue PolicyOp = DAG.getTargetConstant(Policy, DL, Subtarget.getXLenVT());
  2629. SDValue Ops[] = {Merge, Op, Offset, Mask, VL, PolicyOp};
  2630. return DAG.getNode(RISCVISD::VSLIDEDOWN_VL, DL, VT, Ops);
  2631. }
  2632. static SDValue
  2633. getVSlideup(SelectionDAG &DAG, const RISCVSubtarget &Subtarget, SDLoc DL,
  2634. EVT VT, SDValue Merge, SDValue Op, SDValue Offset, SDValue Mask,
  2635. SDValue VL,
  2636. unsigned Policy = RISCVII::TAIL_UNDISTURBED_MASK_UNDISTURBED) {
  2637. if (Merge.isUndef())
  2638. Policy = RISCVII::TAIL_AGNOSTIC | RISCVII::MASK_AGNOSTIC;
  2639. SDValue PolicyOp = DAG.getTargetConstant(Policy, DL, Subtarget.getXLenVT());
  2640. SDValue Ops[] = {Merge, Op, Offset, Mask, VL, PolicyOp};
  2641. return DAG.getNode(RISCVISD::VSLIDEUP_VL, DL, VT, Ops);
  2642. }
  2643. // Lower the following shuffle to vslidedown.
  2644. // a)
  2645. // t49: v8i8 = extract_subvector t13, Constant:i64<0>
  2646. // t109: v8i8 = extract_subvector t13, Constant:i64<8>
  2647. // t108: v8i8 = vector_shuffle<1,2,3,4,5,6,7,8> t49, t106
  2648. // b)
  2649. // t69: v16i16 = extract_subvector t68, Constant:i64<0>
  2650. // t23: v8i16 = extract_subvector t69, Constant:i64<0>
  2651. // t29: v4i16 = extract_subvector t23, Constant:i64<4>
  2652. // t26: v8i16 = extract_subvector t69, Constant:i64<8>
  2653. // t30: v4i16 = extract_subvector t26, Constant:i64<0>
  2654. // t54: v4i16 = vector_shuffle<1,2,3,4> t29, t30
  2655. static SDValue lowerVECTOR_SHUFFLEAsVSlidedown(const SDLoc &DL, MVT VT,
  2656. SDValue V1, SDValue V2,
  2657. ArrayRef<int> Mask,
  2658. const RISCVSubtarget &Subtarget,
  2659. SelectionDAG &DAG) {
  2660. auto findNonEXTRACT_SUBVECTORParent =
  2661. [](SDValue Parent) -> std::pair<SDValue, uint64_t> {
  2662. uint64_t Offset = 0;
  2663. while (Parent.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  2664. // EXTRACT_SUBVECTOR can be used to extract a fixed-width vector from
  2665. // a scalable vector. But we don't want to match the case.
  2666. Parent.getOperand(0).getSimpleValueType().isFixedLengthVector()) {
  2667. Offset += Parent.getConstantOperandVal(1);
  2668. Parent = Parent.getOperand(0);
  2669. }
  2670. return std::make_pair(Parent, Offset);
  2671. };
  2672. auto [V1Src, V1IndexOffset] = findNonEXTRACT_SUBVECTORParent(V1);
  2673. auto [V2Src, V2IndexOffset] = findNonEXTRACT_SUBVECTORParent(V2);
  2674. // Extracting from the same source.
  2675. SDValue Src = V1Src;
  2676. if (Src != V2Src)
  2677. return SDValue();
  2678. // Rebuild mask because Src may be from multiple EXTRACT_SUBVECTORs.
  2679. SmallVector<int, 16> NewMask(Mask);
  2680. for (size_t i = 0; i != NewMask.size(); ++i) {
  2681. if (NewMask[i] == -1)
  2682. continue;
  2683. if (static_cast<size_t>(NewMask[i]) < NewMask.size()) {
  2684. NewMask[i] = NewMask[i] + V1IndexOffset;
  2685. } else {
  2686. // Minus NewMask.size() is needed. Otherwise, the b case would be
  2687. // <5,6,7,12> instead of <5,6,7,8>.
  2688. NewMask[i] = NewMask[i] - NewMask.size() + V2IndexOffset;
  2689. }
  2690. }
  2691. // First index must be known and non-zero. It will be used as the slidedown
  2692. // amount.
  2693. if (NewMask[0] <= 0)
  2694. return SDValue();
  2695. // NewMask is also continuous.
  2696. for (unsigned i = 1; i != NewMask.size(); ++i)
  2697. if (NewMask[i - 1] + 1 != NewMask[i])
  2698. return SDValue();
  2699. MVT XLenVT = Subtarget.getXLenVT();
  2700. MVT SrcVT = Src.getSimpleValueType();
  2701. MVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT, Subtarget);
  2702. auto [TrueMask, VL] = getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
  2703. SDValue Slidedown =
  2704. getVSlidedown(DAG, Subtarget, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
  2705. convertToScalableVector(ContainerVT, Src, DAG, Subtarget),
  2706. DAG.getConstant(NewMask[0], DL, XLenVT), TrueMask, VL);
  2707. return DAG.getNode(
  2708. ISD::EXTRACT_SUBVECTOR, DL, VT,
  2709. convertFromScalableVector(SrcVT, Slidedown, DAG, Subtarget),
  2710. DAG.getConstant(0, DL, XLenVT));
  2711. }
  2712. static SDValue lowerVECTOR_SHUFFLE(SDValue Op, SelectionDAG &DAG,
  2713. const RISCVSubtarget &Subtarget) {
  2714. SDValue V1 = Op.getOperand(0);
  2715. SDValue V2 = Op.getOperand(1);
  2716. SDLoc DL(Op);
  2717. MVT XLenVT = Subtarget.getXLenVT();
  2718. MVT VT = Op.getSimpleValueType();
  2719. unsigned NumElts = VT.getVectorNumElements();
  2720. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
  2721. MVT ContainerVT = getContainerForFixedLengthVector(DAG, VT, Subtarget);
  2722. auto [TrueMask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
  2723. if (SVN->isSplat()) {
  2724. const int Lane = SVN->getSplatIndex();
  2725. if (Lane >= 0) {
  2726. MVT SVT = VT.getVectorElementType();
  2727. // Turn splatted vector load into a strided load with an X0 stride.
  2728. SDValue V = V1;
  2729. // Peek through CONCAT_VECTORS as VectorCombine can concat a vector
  2730. // with undef.
  2731. // FIXME: Peek through INSERT_SUBVECTOR, EXTRACT_SUBVECTOR, bitcasts?
  2732. int Offset = Lane;
  2733. if (V.getOpcode() == ISD::CONCAT_VECTORS) {
  2734. int OpElements =
  2735. V.getOperand(0).getSimpleValueType().getVectorNumElements();
  2736. V = V.getOperand(Offset / OpElements);
  2737. Offset %= OpElements;
  2738. }
  2739. // We need to ensure the load isn't atomic or volatile.
  2740. if (ISD::isNormalLoad(V.getNode()) && cast<LoadSDNode>(V)->isSimple()) {
  2741. auto *Ld = cast<LoadSDNode>(V);
  2742. Offset *= SVT.getStoreSize();
  2743. SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(),
  2744. TypeSize::Fixed(Offset), DL);
  2745. // If this is SEW=64 on RV32, use a strided load with a stride of x0.
  2746. if (SVT.isInteger() && SVT.bitsGT(XLenVT)) {
  2747. SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
  2748. SDValue IntID =
  2749. DAG.getTargetConstant(Intrinsic::riscv_vlse, DL, XLenVT);
  2750. SDValue Ops[] = {Ld->getChain(),
  2751. IntID,
  2752. DAG.getUNDEF(ContainerVT),
  2753. NewAddr,
  2754. DAG.getRegister(RISCV::X0, XLenVT),
  2755. VL};
  2756. SDValue NewLoad = DAG.getMemIntrinsicNode(
  2757. ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, SVT,
  2758. DAG.getMachineFunction().getMachineMemOperand(
  2759. Ld->getMemOperand(), Offset, SVT.getStoreSize()));
  2760. DAG.makeEquivalentMemoryOrdering(Ld, NewLoad);
  2761. return convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
  2762. }
  2763. // Otherwise use a scalar load and splat. This will give the best
  2764. // opportunity to fold a splat into the operation. ISel can turn it into
  2765. // the x0 strided load if we aren't able to fold away the select.
  2766. if (SVT.isFloatingPoint())
  2767. V = DAG.getLoad(SVT, DL, Ld->getChain(), NewAddr,
  2768. Ld->getPointerInfo().getWithOffset(Offset),
  2769. Ld->getOriginalAlign(),
  2770. Ld->getMemOperand()->getFlags());
  2771. else
  2772. V = DAG.getExtLoad(ISD::SEXTLOAD, DL, XLenVT, Ld->getChain(), NewAddr,
  2773. Ld->getPointerInfo().getWithOffset(Offset), SVT,
  2774. Ld->getOriginalAlign(),
  2775. Ld->getMemOperand()->getFlags());
  2776. DAG.makeEquivalentMemoryOrdering(Ld, V);
  2777. unsigned Opc =
  2778. VT.isFloatingPoint() ? RISCVISD::VFMV_V_F_VL : RISCVISD::VMV_V_X_VL;
  2779. SDValue Splat =
  2780. DAG.getNode(Opc, DL, ContainerVT, DAG.getUNDEF(ContainerVT), V, VL);
  2781. return convertFromScalableVector(VT, Splat, DAG, Subtarget);
  2782. }
  2783. V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
  2784. assert(Lane < (int)NumElts && "Unexpected lane!");
  2785. SDValue Gather = DAG.getNode(RISCVISD::VRGATHER_VX_VL, DL, ContainerVT,
  2786. V1, DAG.getConstant(Lane, DL, XLenVT),
  2787. DAG.getUNDEF(ContainerVT), TrueMask, VL);
  2788. return convertFromScalableVector(VT, Gather, DAG, Subtarget);
  2789. }
  2790. }
  2791. ArrayRef<int> Mask = SVN->getMask();
  2792. if (SDValue V =
  2793. lowerVECTOR_SHUFFLEAsVSlidedown(DL, VT, V1, V2, Mask, Subtarget, DAG))
  2794. return V;
  2795. // Lower rotations to a SLIDEDOWN and a SLIDEUP. One of the source vectors may
  2796. // be undef which can be handled with a single SLIDEDOWN/UP.
  2797. int LoSrc, HiSrc;
  2798. int Rotation = isElementRotate(LoSrc, HiSrc, Mask);
  2799. if (Rotation > 0) {
  2800. SDValue LoV, HiV;
  2801. if (LoSrc >= 0) {
  2802. LoV = LoSrc == 0 ? V1 : V2;
  2803. LoV = convertToScalableVector(ContainerVT, LoV, DAG, Subtarget);
  2804. }
  2805. if (HiSrc >= 0) {
  2806. HiV = HiSrc == 0 ? V1 : V2;
  2807. HiV = convertToScalableVector(ContainerVT, HiV, DAG, Subtarget);
  2808. }
  2809. // We found a rotation. We need to slide HiV down by Rotation. Then we need
  2810. // to slide LoV up by (NumElts - Rotation).
  2811. unsigned InvRotate = NumElts - Rotation;
  2812. SDValue Res = DAG.getUNDEF(ContainerVT);
  2813. if (HiV) {
  2814. // If we are doing a SLIDEDOWN+SLIDEUP, reduce the VL for the SLIDEDOWN.
  2815. // FIXME: If we are only doing a SLIDEDOWN, don't reduce the VL as it
  2816. // causes multiple vsetvlis in some test cases such as lowering
  2817. // reduce.mul
  2818. SDValue DownVL = VL;
  2819. if (LoV)
  2820. DownVL = DAG.getConstant(InvRotate, DL, XLenVT);
  2821. Res = getVSlidedown(DAG, Subtarget, DL, ContainerVT, Res, HiV,
  2822. DAG.getConstant(Rotation, DL, XLenVT), TrueMask,
  2823. DownVL);
  2824. }
  2825. if (LoV)
  2826. Res = getVSlideup(DAG, Subtarget, DL, ContainerVT, Res, LoV,
  2827. DAG.getConstant(InvRotate, DL, XLenVT), TrueMask, VL,
  2828. RISCVII::TAIL_AGNOSTIC);
  2829. return convertFromScalableVector(VT, Res, DAG, Subtarget);
  2830. }
  2831. if (SDValue V = lowerVECTOR_SHUFFLEAsVNSRL(
  2832. DL, VT, ContainerVT, V1, V2, TrueMask, VL, Mask, Subtarget, DAG))
  2833. return V;
  2834. // Detect an interleave shuffle and lower to
  2835. // (vmaccu.vx (vwaddu.vx lohalf(V1), lohalf(V2)), lohalf(V2), (2^eltbits - 1))
  2836. bool SwapSources;
  2837. if (isInterleaveShuffle(Mask, VT, SwapSources, Subtarget)) {
  2838. // Swap sources if needed.
  2839. if (SwapSources)
  2840. std::swap(V1, V2);
  2841. // Extract the lower half of the vectors.
  2842. MVT HalfVT = VT.getHalfNumVectorElementsVT();
  2843. V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V1,
  2844. DAG.getConstant(0, DL, XLenVT));
  2845. V2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, V2,
  2846. DAG.getConstant(0, DL, XLenVT));
  2847. // Double the element width and halve the number of elements in an int type.
  2848. unsigned EltBits = VT.getScalarSizeInBits();
  2849. MVT WideIntEltVT = MVT::getIntegerVT(EltBits * 2);
  2850. MVT WideIntVT =
  2851. MVT::getVectorVT(WideIntEltVT, VT.getVectorNumElements() / 2);
  2852. // Convert this to a scalable vector. We need to base this on the
  2853. // destination size to ensure there's always a type with a smaller LMUL.
  2854. MVT WideIntContainerVT =
  2855. getContainerForFixedLengthVector(DAG, WideIntVT, Subtarget);
  2856. // Convert sources to scalable vectors with the same element count as the
  2857. // larger type.
  2858. MVT HalfContainerVT = MVT::getVectorVT(
  2859. VT.getVectorElementType(), WideIntContainerVT.getVectorElementCount());
  2860. V1 = convertToScalableVector(HalfContainerVT, V1, DAG, Subtarget);
  2861. V2 = convertToScalableVector(HalfContainerVT, V2, DAG, Subtarget);
  2862. // Cast sources to integer.
  2863. MVT IntEltVT = MVT::getIntegerVT(EltBits);
  2864. MVT IntHalfVT =
  2865. MVT::getVectorVT(IntEltVT, HalfContainerVT.getVectorElementCount());
  2866. V1 = DAG.getBitcast(IntHalfVT, V1);
  2867. V2 = DAG.getBitcast(IntHalfVT, V2);
  2868. // Freeze V2 since we use it twice and we need to be sure that the add and
  2869. // multiply see the same value.
  2870. V2 = DAG.getFreeze(V2);
  2871. // Recreate TrueMask using the widened type's element count.
  2872. TrueMask = getAllOnesMask(HalfContainerVT, VL, DL, DAG);
  2873. // Widen V1 and V2 with 0s and add one copy of V2 to V1.
  2874. SDValue Add =
  2875. DAG.getNode(RISCVISD::VWADDU_VL, DL, WideIntContainerVT, V1, V2,
  2876. DAG.getUNDEF(WideIntContainerVT), TrueMask, VL);
  2877. // Create 2^eltbits - 1 copies of V2 by multiplying by the largest integer.
  2878. SDValue Multiplier = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntHalfVT,
  2879. DAG.getUNDEF(IntHalfVT),
  2880. DAG.getAllOnesConstant(DL, XLenVT), VL);
  2881. SDValue WidenMul =
  2882. DAG.getNode(RISCVISD::VWMULU_VL, DL, WideIntContainerVT, V2, Multiplier,
  2883. DAG.getUNDEF(WideIntContainerVT), TrueMask, VL);
  2884. // Add the new copies to our previous addition giving us 2^eltbits copies of
  2885. // V2. This is equivalent to shifting V2 left by eltbits. This should
  2886. // combine with the vwmulu.vv above to form vwmaccu.vv.
  2887. Add = DAG.getNode(RISCVISD::ADD_VL, DL, WideIntContainerVT, Add, WidenMul,
  2888. DAG.getUNDEF(WideIntContainerVT), TrueMask, VL);
  2889. // Cast back to ContainerVT. We need to re-create a new ContainerVT in case
  2890. // WideIntContainerVT is a larger fractional LMUL than implied by the fixed
  2891. // vector VT.
  2892. ContainerVT =
  2893. MVT::getVectorVT(VT.getVectorElementType(),
  2894. WideIntContainerVT.getVectorElementCount() * 2);
  2895. Add = DAG.getBitcast(ContainerVT, Add);
  2896. return convertFromScalableVector(VT, Add, DAG, Subtarget);
  2897. }
  2898. // Detect shuffles which can be re-expressed as vector selects; these are
  2899. // shuffles in which each element in the destination is taken from an element
  2900. // at the corresponding index in either source vectors.
  2901. bool IsSelect = all_of(enumerate(Mask), [&](const auto &MaskIdx) {
  2902. int MaskIndex = MaskIdx.value();
  2903. return MaskIndex < 0 || MaskIdx.index() == (unsigned)MaskIndex % NumElts;
  2904. });
  2905. assert(!V1.isUndef() && "Unexpected shuffle canonicalization");
  2906. SmallVector<SDValue> MaskVals;
  2907. // As a backup, shuffles can be lowered via a vrgather instruction, possibly
  2908. // merged with a second vrgather.
  2909. SmallVector<SDValue> GatherIndicesLHS, GatherIndicesRHS;
  2910. // By default we preserve the original operand order, and use a mask to
  2911. // select LHS as true and RHS as false. However, since RVV vector selects may
  2912. // feature splats but only on the LHS, we may choose to invert our mask and
  2913. // instead select between RHS and LHS.
  2914. bool SwapOps = DAG.isSplatValue(V2) && !DAG.isSplatValue(V1);
  2915. bool InvertMask = IsSelect == SwapOps;
  2916. // Keep a track of which non-undef indices are used by each LHS/RHS shuffle
  2917. // half.
  2918. DenseMap<int, unsigned> LHSIndexCounts, RHSIndexCounts;
  2919. // Now construct the mask that will be used by the vselect or blended
  2920. // vrgather operation. For vrgathers, construct the appropriate indices into
  2921. // each vector.
  2922. for (int MaskIndex : Mask) {
  2923. bool SelectMaskVal = (MaskIndex < (int)NumElts) ^ InvertMask;
  2924. MaskVals.push_back(DAG.getConstant(SelectMaskVal, DL, XLenVT));
  2925. if (!IsSelect) {
  2926. bool IsLHSOrUndefIndex = MaskIndex < (int)NumElts;
  2927. GatherIndicesLHS.push_back(IsLHSOrUndefIndex && MaskIndex >= 0
  2928. ? DAG.getConstant(MaskIndex, DL, XLenVT)
  2929. : DAG.getUNDEF(XLenVT));
  2930. GatherIndicesRHS.push_back(
  2931. IsLHSOrUndefIndex ? DAG.getUNDEF(XLenVT)
  2932. : DAG.getConstant(MaskIndex - NumElts, DL, XLenVT));
  2933. if (IsLHSOrUndefIndex && MaskIndex >= 0)
  2934. ++LHSIndexCounts[MaskIndex];
  2935. if (!IsLHSOrUndefIndex)
  2936. ++RHSIndexCounts[MaskIndex - NumElts];
  2937. }
  2938. }
  2939. if (SwapOps) {
  2940. std::swap(V1, V2);
  2941. std::swap(GatherIndicesLHS, GatherIndicesRHS);
  2942. }
  2943. assert(MaskVals.size() == NumElts && "Unexpected select-like shuffle");
  2944. MVT MaskVT = MVT::getVectorVT(MVT::i1, NumElts);
  2945. SDValue SelectMask = DAG.getBuildVector(MaskVT, DL, MaskVals);
  2946. if (IsSelect)
  2947. return DAG.getNode(ISD::VSELECT, DL, VT, SelectMask, V1, V2);
  2948. if (VT.getScalarSizeInBits() == 8 && VT.getVectorNumElements() > 256) {
  2949. // On such a large vector we're unable to use i8 as the index type.
  2950. // FIXME: We could promote the index to i16 and use vrgatherei16, but that
  2951. // may involve vector splitting if we're already at LMUL=8, or our
  2952. // user-supplied maximum fixed-length LMUL.
  2953. return SDValue();
  2954. }
  2955. unsigned GatherVXOpc = RISCVISD::VRGATHER_VX_VL;
  2956. unsigned GatherVVOpc = RISCVISD::VRGATHER_VV_VL;
  2957. MVT IndexVT = VT.changeTypeToInteger();
  2958. // Since we can't introduce illegal index types at this stage, use i16 and
  2959. // vrgatherei16 if the corresponding index type for plain vrgather is greater
  2960. // than XLenVT.
  2961. if (IndexVT.getScalarType().bitsGT(XLenVT)) {
  2962. GatherVVOpc = RISCVISD::VRGATHEREI16_VV_VL;
  2963. IndexVT = IndexVT.changeVectorElementType(MVT::i16);
  2964. }
  2965. MVT IndexContainerVT =
  2966. ContainerVT.changeVectorElementType(IndexVT.getScalarType());
  2967. SDValue Gather;
  2968. // TODO: This doesn't trigger for i64 vectors on RV32, since there we
  2969. // encounter a bitcasted BUILD_VECTOR with low/high i32 values.
  2970. if (SDValue SplatValue = DAG.getSplatValue(V1, /*LegalTypes*/ true)) {
  2971. Gather = lowerScalarSplat(SDValue(), SplatValue, VL, ContainerVT, DL, DAG,
  2972. Subtarget);
  2973. } else {
  2974. V1 = convertToScalableVector(ContainerVT, V1, DAG, Subtarget);
  2975. // If only one index is used, we can use a "splat" vrgather.
  2976. // TODO: We can splat the most-common index and fix-up any stragglers, if
  2977. // that's beneficial.
  2978. if (LHSIndexCounts.size() == 1) {
  2979. int SplatIndex = LHSIndexCounts.begin()->getFirst();
  2980. Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V1,
  2981. DAG.getConstant(SplatIndex, DL, XLenVT),
  2982. DAG.getUNDEF(ContainerVT), TrueMask, VL);
  2983. } else {
  2984. SDValue LHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesLHS);
  2985. LHSIndices =
  2986. convertToScalableVector(IndexContainerVT, LHSIndices, DAG, Subtarget);
  2987. Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V1, LHSIndices,
  2988. DAG.getUNDEF(ContainerVT), TrueMask, VL);
  2989. }
  2990. }
  2991. // If a second vector operand is used by this shuffle, blend it in with an
  2992. // additional vrgather.
  2993. if (!V2.isUndef()) {
  2994. V2 = convertToScalableVector(ContainerVT, V2, DAG, Subtarget);
  2995. MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
  2996. SelectMask =
  2997. convertToScalableVector(MaskContainerVT, SelectMask, DAG, Subtarget);
  2998. // If only one index is used, we can use a "splat" vrgather.
  2999. // TODO: We can splat the most-common index and fix-up any stragglers, if
  3000. // that's beneficial.
  3001. if (RHSIndexCounts.size() == 1) {
  3002. int SplatIndex = RHSIndexCounts.begin()->getFirst();
  3003. Gather = DAG.getNode(GatherVXOpc, DL, ContainerVT, V2,
  3004. DAG.getConstant(SplatIndex, DL, XLenVT), Gather,
  3005. SelectMask, VL);
  3006. } else {
  3007. SDValue RHSIndices = DAG.getBuildVector(IndexVT, DL, GatherIndicesRHS);
  3008. RHSIndices =
  3009. convertToScalableVector(IndexContainerVT, RHSIndices, DAG, Subtarget);
  3010. Gather = DAG.getNode(GatherVVOpc, DL, ContainerVT, V2, RHSIndices, Gather,
  3011. SelectMask, VL);
  3012. }
  3013. }
  3014. return convertFromScalableVector(VT, Gather, DAG, Subtarget);
  3015. }
  3016. bool RISCVTargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
  3017. // Support splats for any type. These should type legalize well.
  3018. if (ShuffleVectorSDNode::isSplatMask(M.data(), VT))
  3019. return true;
  3020. // Only support legal VTs for other shuffles for now.
  3021. if (!isTypeLegal(VT))
  3022. return false;
  3023. MVT SVT = VT.getSimpleVT();
  3024. bool SwapSources;
  3025. int LoSrc, HiSrc;
  3026. return (isElementRotate(LoSrc, HiSrc, M) > 0) ||
  3027. isInterleaveShuffle(M, SVT, SwapSources, Subtarget);
  3028. }
  3029. // Lower CTLZ_ZERO_UNDEF or CTTZ_ZERO_UNDEF by converting to FP and extracting
  3030. // the exponent.
  3031. SDValue
  3032. RISCVTargetLowering::lowerCTLZ_CTTZ_ZERO_UNDEF(SDValue Op,
  3033. SelectionDAG &DAG) const {
  3034. MVT VT = Op.getSimpleValueType();
  3035. unsigned EltSize = VT.getScalarSizeInBits();
  3036. SDValue Src = Op.getOperand(0);
  3037. SDLoc DL(Op);
  3038. // We choose FP type that can represent the value if possible. Otherwise, we
  3039. // use rounding to zero conversion for correct exponent of the result.
  3040. // TODO: Use f16 for i8 when possible?
  3041. MVT FloatEltVT = (EltSize >= 32) ? MVT::f64 : MVT::f32;
  3042. if (!isTypeLegal(MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount())))
  3043. FloatEltVT = MVT::f32;
  3044. MVT FloatVT = MVT::getVectorVT(FloatEltVT, VT.getVectorElementCount());
  3045. // Legal types should have been checked in the RISCVTargetLowering
  3046. // constructor.
  3047. // TODO: Splitting may make sense in some cases.
  3048. assert(DAG.getTargetLoweringInfo().isTypeLegal(FloatVT) &&
  3049. "Expected legal float type!");
  3050. // For CTTZ_ZERO_UNDEF, we need to extract the lowest set bit using X & -X.
  3051. // The trailing zero count is equal to log2 of this single bit value.
  3052. if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF) {
  3053. SDValue Neg = DAG.getNegative(Src, DL, VT);
  3054. Src = DAG.getNode(ISD::AND, DL, VT, Src, Neg);
  3055. }
  3056. // We have a legal FP type, convert to it.
  3057. SDValue FloatVal;
  3058. if (FloatVT.bitsGT(VT)) {
  3059. FloatVal = DAG.getNode(ISD::UINT_TO_FP, DL, FloatVT, Src);
  3060. } else {
  3061. // Use RTZ to avoid rounding influencing exponent of FloatVal.
  3062. MVT ContainerVT = VT;
  3063. if (VT.isFixedLengthVector()) {
  3064. ContainerVT = getContainerForFixedLengthVector(VT);
  3065. Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
  3066. }
  3067. auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
  3068. SDValue RTZRM =
  3069. DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, Subtarget.getXLenVT());
  3070. MVT ContainerFloatVT =
  3071. MVT::getVectorVT(FloatEltVT, ContainerVT.getVectorElementCount());
  3072. FloatVal = DAG.getNode(RISCVISD::VFCVT_RM_F_XU_VL, DL, ContainerFloatVT,
  3073. Src, Mask, RTZRM, VL);
  3074. if (VT.isFixedLengthVector())
  3075. FloatVal = convertFromScalableVector(FloatVT, FloatVal, DAG, Subtarget);
  3076. }
  3077. // Bitcast to integer and shift the exponent to the LSB.
  3078. EVT IntVT = FloatVT.changeVectorElementTypeToInteger();
  3079. SDValue Bitcast = DAG.getBitcast(IntVT, FloatVal);
  3080. unsigned ShiftAmt = FloatEltVT == MVT::f64 ? 52 : 23;
  3081. SDValue Exp = DAG.getNode(ISD::SRL, DL, IntVT, Bitcast,
  3082. DAG.getConstant(ShiftAmt, DL, IntVT));
  3083. // Restore back to original type. Truncation after SRL is to generate vnsrl.
  3084. if (IntVT.bitsLT(VT))
  3085. Exp = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Exp);
  3086. else if (IntVT.bitsGT(VT))
  3087. Exp = DAG.getNode(ISD::TRUNCATE, DL, VT, Exp);
  3088. // The exponent contains log2 of the value in biased form.
  3089. unsigned ExponentBias = FloatEltVT == MVT::f64 ? 1023 : 127;
  3090. // For trailing zeros, we just need to subtract the bias.
  3091. if (Op.getOpcode() == ISD::CTTZ_ZERO_UNDEF)
  3092. return DAG.getNode(ISD::SUB, DL, VT, Exp,
  3093. DAG.getConstant(ExponentBias, DL, VT));
  3094. // For leading zeros, we need to remove the bias and convert from log2 to
  3095. // leading zeros. We can do this by subtracting from (Bias + (EltSize - 1)).
  3096. unsigned Adjust = ExponentBias + (EltSize - 1);
  3097. SDValue Res =
  3098. DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(Adjust, DL, VT), Exp);
  3099. // The above result with zero input equals to Adjust which is greater than
  3100. // EltSize. Hence, we can do min(Res, EltSize) for CTLZ.
  3101. if (Op.getOpcode() == ISD::CTLZ)
  3102. Res = DAG.getNode(ISD::UMIN, DL, VT, Res, DAG.getConstant(EltSize, DL, VT));
  3103. return Res;
  3104. }
  3105. // While RVV has alignment restrictions, we should always be able to load as a
  3106. // legal equivalently-sized byte-typed vector instead. This method is
  3107. // responsible for re-expressing a ISD::LOAD via a correctly-aligned type. If
  3108. // the load is already correctly-aligned, it returns SDValue().
  3109. SDValue RISCVTargetLowering::expandUnalignedRVVLoad(SDValue Op,
  3110. SelectionDAG &DAG) const {
  3111. auto *Load = cast<LoadSDNode>(Op);
  3112. assert(Load && Load->getMemoryVT().isVector() && "Expected vector load");
  3113. if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
  3114. Load->getMemoryVT(),
  3115. *Load->getMemOperand()))
  3116. return SDValue();
  3117. SDLoc DL(Op);
  3118. MVT VT = Op.getSimpleValueType();
  3119. unsigned EltSizeBits = VT.getScalarSizeInBits();
  3120. assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
  3121. "Unexpected unaligned RVV load type");
  3122. MVT NewVT =
  3123. MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
  3124. assert(NewVT.isValid() &&
  3125. "Expecting equally-sized RVV vector types to be legal");
  3126. SDValue L = DAG.getLoad(NewVT, DL, Load->getChain(), Load->getBasePtr(),
  3127. Load->getPointerInfo(), Load->getOriginalAlign(),
  3128. Load->getMemOperand()->getFlags());
  3129. return DAG.getMergeValues({DAG.getBitcast(VT, L), L.getValue(1)}, DL);
  3130. }
  3131. // While RVV has alignment restrictions, we should always be able to store as a
  3132. // legal equivalently-sized byte-typed vector instead. This method is
  3133. // responsible for re-expressing a ISD::STORE via a correctly-aligned type. It
  3134. // returns SDValue() if the store is already correctly aligned.
  3135. SDValue RISCVTargetLowering::expandUnalignedRVVStore(SDValue Op,
  3136. SelectionDAG &DAG) const {
  3137. auto *Store = cast<StoreSDNode>(Op);
  3138. assert(Store && Store->getValue().getValueType().isVector() &&
  3139. "Expected vector store");
  3140. if (allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
  3141. Store->getMemoryVT(),
  3142. *Store->getMemOperand()))
  3143. return SDValue();
  3144. SDLoc DL(Op);
  3145. SDValue StoredVal = Store->getValue();
  3146. MVT VT = StoredVal.getSimpleValueType();
  3147. unsigned EltSizeBits = VT.getScalarSizeInBits();
  3148. assert((EltSizeBits == 16 || EltSizeBits == 32 || EltSizeBits == 64) &&
  3149. "Unexpected unaligned RVV store type");
  3150. MVT NewVT =
  3151. MVT::getVectorVT(MVT::i8, VT.getVectorElementCount() * (EltSizeBits / 8));
  3152. assert(NewVT.isValid() &&
  3153. "Expecting equally-sized RVV vector types to be legal");
  3154. StoredVal = DAG.getBitcast(NewVT, StoredVal);
  3155. return DAG.getStore(Store->getChain(), DL, StoredVal, Store->getBasePtr(),
  3156. Store->getPointerInfo(), Store->getOriginalAlign(),
  3157. Store->getMemOperand()->getFlags());
  3158. }
  3159. static SDValue lowerConstant(SDValue Op, SelectionDAG &DAG,
  3160. const RISCVSubtarget &Subtarget) {
  3161. assert(Op.getValueType() == MVT::i64 && "Unexpected VT");
  3162. int64_t Imm = cast<ConstantSDNode>(Op)->getSExtValue();
  3163. // All simm32 constants should be handled by isel.
  3164. // NOTE: The getMaxBuildIntsCost call below should return a value >= 2 making
  3165. // this check redundant, but small immediates are common so this check
  3166. // should have better compile time.
  3167. if (isInt<32>(Imm))
  3168. return Op;
  3169. // We only need to cost the immediate, if constant pool lowering is enabled.
  3170. if (!Subtarget.useConstantPoolForLargeInts())
  3171. return Op;
  3172. RISCVMatInt::InstSeq Seq =
  3173. RISCVMatInt::generateInstSeq(Imm, Subtarget.getFeatureBits());
  3174. if (Seq.size() <= Subtarget.getMaxBuildIntsCost())
  3175. return Op;
  3176. // Expand to a constant pool using the default expansion code.
  3177. return SDValue();
  3178. }
  3179. static SDValue LowerATOMIC_FENCE(SDValue Op, SelectionDAG &DAG) {
  3180. SDLoc dl(Op);
  3181. SyncScope::ID FenceSSID =
  3182. static_cast<SyncScope::ID>(Op.getConstantOperandVal(2));
  3183. // singlethread fences only synchronize with signal handlers on the same
  3184. // thread and thus only need to preserve instruction order, not actually
  3185. // enforce memory ordering.
  3186. if (FenceSSID == SyncScope::SingleThread)
  3187. // MEMBARRIER is a compiler barrier; it codegens to a no-op.
  3188. return DAG.getNode(ISD::MEMBARRIER, dl, MVT::Other, Op.getOperand(0));
  3189. return Op;
  3190. }
  3191. SDValue RISCVTargetLowering::LowerOperation(SDValue Op,
  3192. SelectionDAG &DAG) const {
  3193. switch (Op.getOpcode()) {
  3194. default:
  3195. report_fatal_error("unimplemented operand");
  3196. case ISD::ATOMIC_FENCE:
  3197. return LowerATOMIC_FENCE(Op, DAG);
  3198. case ISD::GlobalAddress:
  3199. return lowerGlobalAddress(Op, DAG);
  3200. case ISD::BlockAddress:
  3201. return lowerBlockAddress(Op, DAG);
  3202. case ISD::ConstantPool:
  3203. return lowerConstantPool(Op, DAG);
  3204. case ISD::JumpTable:
  3205. return lowerJumpTable(Op, DAG);
  3206. case ISD::GlobalTLSAddress:
  3207. return lowerGlobalTLSAddress(Op, DAG);
  3208. case ISD::Constant:
  3209. return lowerConstant(Op, DAG, Subtarget);
  3210. case ISD::SELECT:
  3211. return lowerSELECT(Op, DAG);
  3212. case ISD::BRCOND:
  3213. return lowerBRCOND(Op, DAG);
  3214. case ISD::VASTART:
  3215. return lowerVASTART(Op, DAG);
  3216. case ISD::FRAMEADDR:
  3217. return lowerFRAMEADDR(Op, DAG);
  3218. case ISD::RETURNADDR:
  3219. return lowerRETURNADDR(Op, DAG);
  3220. case ISD::SHL_PARTS:
  3221. return lowerShiftLeftParts(Op, DAG);
  3222. case ISD::SRA_PARTS:
  3223. return lowerShiftRightParts(Op, DAG, true);
  3224. case ISD::SRL_PARTS:
  3225. return lowerShiftRightParts(Op, DAG, false);
  3226. case ISD::BITCAST: {
  3227. SDLoc DL(Op);
  3228. EVT VT = Op.getValueType();
  3229. SDValue Op0 = Op.getOperand(0);
  3230. EVT Op0VT = Op0.getValueType();
  3231. MVT XLenVT = Subtarget.getXLenVT();
  3232. if (VT == MVT::f16 && Op0VT == MVT::i16 &&
  3233. Subtarget.hasStdExtZfhOrZfhmin()) {
  3234. SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Op0);
  3235. SDValue FPConv = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, NewOp0);
  3236. return FPConv;
  3237. }
  3238. if (VT == MVT::f32 && Op0VT == MVT::i32 && Subtarget.is64Bit() &&
  3239. Subtarget.hasStdExtF()) {
  3240. SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, Op0);
  3241. SDValue FPConv =
  3242. DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, NewOp0);
  3243. return FPConv;
  3244. }
  3245. // Consider other scalar<->scalar casts as legal if the types are legal.
  3246. // Otherwise expand them.
  3247. if (!VT.isVector() && !Op0VT.isVector()) {
  3248. if (isTypeLegal(VT) && isTypeLegal(Op0VT))
  3249. return Op;
  3250. return SDValue();
  3251. }
  3252. assert(!VT.isScalableVector() && !Op0VT.isScalableVector() &&
  3253. "Unexpected types");
  3254. if (VT.isFixedLengthVector()) {
  3255. // We can handle fixed length vector bitcasts with a simple replacement
  3256. // in isel.
  3257. if (Op0VT.isFixedLengthVector())
  3258. return Op;
  3259. // When bitcasting from scalar to fixed-length vector, insert the scalar
  3260. // into a one-element vector of the result type, and perform a vector
  3261. // bitcast.
  3262. if (!Op0VT.isVector()) {
  3263. EVT BVT = EVT::getVectorVT(*DAG.getContext(), Op0VT, 1);
  3264. if (!isTypeLegal(BVT))
  3265. return SDValue();
  3266. return DAG.getBitcast(VT, DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, BVT,
  3267. DAG.getUNDEF(BVT), Op0,
  3268. DAG.getConstant(0, DL, XLenVT)));
  3269. }
  3270. return SDValue();
  3271. }
  3272. // Custom-legalize bitcasts from fixed-length vector types to scalar types
  3273. // thus: bitcast the vector to a one-element vector type whose element type
  3274. // is the same as the result type, and extract the first element.
  3275. if (!VT.isVector() && Op0VT.isFixedLengthVector()) {
  3276. EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
  3277. if (!isTypeLegal(BVT))
  3278. return SDValue();
  3279. SDValue BVec = DAG.getBitcast(BVT, Op0);
  3280. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
  3281. DAG.getConstant(0, DL, XLenVT));
  3282. }
  3283. return SDValue();
  3284. }
  3285. case ISD::INTRINSIC_WO_CHAIN:
  3286. return LowerINTRINSIC_WO_CHAIN(Op, DAG);
  3287. case ISD::INTRINSIC_W_CHAIN:
  3288. return LowerINTRINSIC_W_CHAIN(Op, DAG);
  3289. case ISD::INTRINSIC_VOID:
  3290. return LowerINTRINSIC_VOID(Op, DAG);
  3291. case ISD::BITREVERSE: {
  3292. MVT VT = Op.getSimpleValueType();
  3293. SDLoc DL(Op);
  3294. assert(Subtarget.hasStdExtZbkb() && "Unexpected custom legalization");
  3295. assert(Op.getOpcode() == ISD::BITREVERSE && "Unexpected opcode");
  3296. // Expand bitreverse to a bswap(rev8) followed by brev8.
  3297. SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Op.getOperand(0));
  3298. return DAG.getNode(RISCVISD::BREV8, DL, VT, BSwap);
  3299. }
  3300. case ISD::TRUNCATE:
  3301. // Only custom-lower vector truncates
  3302. if (!Op.getSimpleValueType().isVector())
  3303. return Op;
  3304. return lowerVectorTruncLike(Op, DAG);
  3305. case ISD::ANY_EXTEND:
  3306. case ISD::ZERO_EXTEND:
  3307. if (Op.getOperand(0).getValueType().isVector() &&
  3308. Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
  3309. return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ 1);
  3310. return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VZEXT_VL);
  3311. case ISD::SIGN_EXTEND:
  3312. if (Op.getOperand(0).getValueType().isVector() &&
  3313. Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
  3314. return lowerVectorMaskExt(Op, DAG, /*ExtVal*/ -1);
  3315. return lowerFixedLengthVectorExtendToRVV(Op, DAG, RISCVISD::VSEXT_VL);
  3316. case ISD::SPLAT_VECTOR_PARTS:
  3317. return lowerSPLAT_VECTOR_PARTS(Op, DAG);
  3318. case ISD::INSERT_VECTOR_ELT:
  3319. return lowerINSERT_VECTOR_ELT(Op, DAG);
  3320. case ISD::EXTRACT_VECTOR_ELT:
  3321. return lowerEXTRACT_VECTOR_ELT(Op, DAG);
  3322. case ISD::VSCALE: {
  3323. MVT VT = Op.getSimpleValueType();
  3324. SDLoc DL(Op);
  3325. SDValue VLENB = DAG.getNode(RISCVISD::READ_VLENB, DL, VT);
  3326. // We define our scalable vector types for lmul=1 to use a 64 bit known
  3327. // minimum size. e.g. <vscale x 2 x i32>. VLENB is in bytes so we calculate
  3328. // vscale as VLENB / 8.
  3329. static_assert(RISCV::RVVBitsPerBlock == 64, "Unexpected bits per block!");
  3330. if (Subtarget.getRealMinVLen() < RISCV::RVVBitsPerBlock)
  3331. report_fatal_error("Support for VLEN==32 is incomplete.");
  3332. // We assume VLENB is a multiple of 8. We manually choose the best shift
  3333. // here because SimplifyDemandedBits isn't always able to simplify it.
  3334. uint64_t Val = Op.getConstantOperandVal(0);
  3335. if (isPowerOf2_64(Val)) {
  3336. uint64_t Log2 = Log2_64(Val);
  3337. if (Log2 < 3)
  3338. return DAG.getNode(ISD::SRL, DL, VT, VLENB,
  3339. DAG.getConstant(3 - Log2, DL, VT));
  3340. if (Log2 > 3)
  3341. return DAG.getNode(ISD::SHL, DL, VT, VLENB,
  3342. DAG.getConstant(Log2 - 3, DL, VT));
  3343. return VLENB;
  3344. }
  3345. // If the multiplier is a multiple of 8, scale it down to avoid needing
  3346. // to shift the VLENB value.
  3347. if ((Val % 8) == 0)
  3348. return DAG.getNode(ISD::MUL, DL, VT, VLENB,
  3349. DAG.getConstant(Val / 8, DL, VT));
  3350. SDValue VScale = DAG.getNode(ISD::SRL, DL, VT, VLENB,
  3351. DAG.getConstant(3, DL, VT));
  3352. return DAG.getNode(ISD::MUL, DL, VT, VScale, Op.getOperand(0));
  3353. }
  3354. case ISD::FPOWI: {
  3355. // Custom promote f16 powi with illegal i32 integer type on RV64. Once
  3356. // promoted this will be legalized into a libcall by LegalizeIntegerTypes.
  3357. if (Op.getValueType() == MVT::f16 && Subtarget.is64Bit() &&
  3358. Op.getOperand(1).getValueType() == MVT::i32) {
  3359. SDLoc DL(Op);
  3360. SDValue Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op.getOperand(0));
  3361. SDValue Powi =
  3362. DAG.getNode(ISD::FPOWI, DL, MVT::f32, Op0, Op.getOperand(1));
  3363. return DAG.getNode(ISD::FP_ROUND, DL, MVT::f16, Powi,
  3364. DAG.getIntPtrConstant(0, DL, /*isTarget=*/true));
  3365. }
  3366. return SDValue();
  3367. }
  3368. case ISD::FP_EXTEND:
  3369. case ISD::FP_ROUND:
  3370. if (!Op.getValueType().isVector())
  3371. return Op;
  3372. return lowerVectorFPExtendOrRoundLike(Op, DAG);
  3373. case ISD::FP_TO_SINT:
  3374. case ISD::FP_TO_UINT:
  3375. case ISD::SINT_TO_FP:
  3376. case ISD::UINT_TO_FP: {
  3377. // RVV can only do fp<->int conversions to types half/double the size as
  3378. // the source. We custom-lower any conversions that do two hops into
  3379. // sequences.
  3380. MVT VT = Op.getSimpleValueType();
  3381. if (!VT.isVector())
  3382. return Op;
  3383. SDLoc DL(Op);
  3384. SDValue Src = Op.getOperand(0);
  3385. MVT EltVT = VT.getVectorElementType();
  3386. MVT SrcVT = Src.getSimpleValueType();
  3387. MVT SrcEltVT = SrcVT.getVectorElementType();
  3388. unsigned EltSize = EltVT.getSizeInBits();
  3389. unsigned SrcEltSize = SrcEltVT.getSizeInBits();
  3390. assert(isPowerOf2_32(EltSize) && isPowerOf2_32(SrcEltSize) &&
  3391. "Unexpected vector element types");
  3392. bool IsInt2FP = SrcEltVT.isInteger();
  3393. // Widening conversions
  3394. if (EltSize > (2 * SrcEltSize)) {
  3395. if (IsInt2FP) {
  3396. // Do a regular integer sign/zero extension then convert to float.
  3397. MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize / 2),
  3398. VT.getVectorElementCount());
  3399. unsigned ExtOpcode = Op.getOpcode() == ISD::UINT_TO_FP
  3400. ? ISD::ZERO_EXTEND
  3401. : ISD::SIGN_EXTEND;
  3402. SDValue Ext = DAG.getNode(ExtOpcode, DL, IVecVT, Src);
  3403. return DAG.getNode(Op.getOpcode(), DL, VT, Ext);
  3404. }
  3405. // FP2Int
  3406. assert(SrcEltVT == MVT::f16 && "Unexpected FP_TO_[US]INT lowering");
  3407. // Do one doubling fp_extend then complete the operation by converting
  3408. // to int.
  3409. MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
  3410. SDValue FExt = DAG.getFPExtendOrRound(Src, DL, InterimFVT);
  3411. return DAG.getNode(Op.getOpcode(), DL, VT, FExt);
  3412. }
  3413. // Narrowing conversions
  3414. if (SrcEltSize > (2 * EltSize)) {
  3415. if (IsInt2FP) {
  3416. // One narrowing int_to_fp, then an fp_round.
  3417. assert(EltVT == MVT::f16 && "Unexpected [US]_TO_FP lowering");
  3418. MVT InterimFVT = MVT::getVectorVT(MVT::f32, VT.getVectorElementCount());
  3419. SDValue Int2FP = DAG.getNode(Op.getOpcode(), DL, InterimFVT, Src);
  3420. return DAG.getFPExtendOrRound(Int2FP, DL, VT);
  3421. }
  3422. // FP2Int
  3423. // One narrowing fp_to_int, then truncate the integer. If the float isn't
  3424. // representable by the integer, the result is poison.
  3425. MVT IVecVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
  3426. VT.getVectorElementCount());
  3427. SDValue FP2Int = DAG.getNode(Op.getOpcode(), DL, IVecVT, Src);
  3428. return DAG.getNode(ISD::TRUNCATE, DL, VT, FP2Int);
  3429. }
  3430. // Scalable vectors can exit here. Patterns will handle equally-sized
  3431. // conversions halving/doubling ones.
  3432. if (!VT.isFixedLengthVector())
  3433. return Op;
  3434. // For fixed-length vectors we lower to a custom "VL" node.
  3435. unsigned RVVOpc = 0;
  3436. switch (Op.getOpcode()) {
  3437. default:
  3438. llvm_unreachable("Impossible opcode");
  3439. case ISD::FP_TO_SINT:
  3440. RVVOpc = RISCVISD::VFCVT_RTZ_X_F_VL;
  3441. break;
  3442. case ISD::FP_TO_UINT:
  3443. RVVOpc = RISCVISD::VFCVT_RTZ_XU_F_VL;
  3444. break;
  3445. case ISD::SINT_TO_FP:
  3446. RVVOpc = RISCVISD::SINT_TO_FP_VL;
  3447. break;
  3448. case ISD::UINT_TO_FP:
  3449. RVVOpc = RISCVISD::UINT_TO_FP_VL;
  3450. break;
  3451. }
  3452. MVT ContainerVT = getContainerForFixedLengthVector(VT);
  3453. MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
  3454. assert(ContainerVT.getVectorElementCount() == SrcContainerVT.getVectorElementCount() &&
  3455. "Expected same element count");
  3456. auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
  3457. Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
  3458. Src = DAG.getNode(RVVOpc, DL, ContainerVT, Src, Mask, VL);
  3459. return convertFromScalableVector(VT, Src, DAG, Subtarget);
  3460. }
  3461. case ISD::FP_TO_SINT_SAT:
  3462. case ISD::FP_TO_UINT_SAT:
  3463. return lowerFP_TO_INT_SAT(Op, DAG, Subtarget);
  3464. case ISD::FTRUNC:
  3465. case ISD::FCEIL:
  3466. case ISD::FFLOOR:
  3467. case ISD::FRINT:
  3468. case ISD::FROUND:
  3469. case ISD::FROUNDEVEN:
  3470. return lowerFTRUNC_FCEIL_FFLOOR_FROUND(Op, DAG, Subtarget);
  3471. case ISD::VECREDUCE_ADD:
  3472. case ISD::VECREDUCE_UMAX:
  3473. case ISD::VECREDUCE_SMAX:
  3474. case ISD::VECREDUCE_UMIN:
  3475. case ISD::VECREDUCE_SMIN:
  3476. return lowerVECREDUCE(Op, DAG);
  3477. case ISD::VECREDUCE_AND:
  3478. case ISD::VECREDUCE_OR:
  3479. case ISD::VECREDUCE_XOR:
  3480. if (Op.getOperand(0).getValueType().getVectorElementType() == MVT::i1)
  3481. return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ false);
  3482. return lowerVECREDUCE(Op, DAG);
  3483. case ISD::VECREDUCE_FADD:
  3484. case ISD::VECREDUCE_SEQ_FADD:
  3485. case ISD::VECREDUCE_FMIN:
  3486. case ISD::VECREDUCE_FMAX:
  3487. return lowerFPVECREDUCE(Op, DAG);
  3488. case ISD::VP_REDUCE_ADD:
  3489. case ISD::VP_REDUCE_UMAX:
  3490. case ISD::VP_REDUCE_SMAX:
  3491. case ISD::VP_REDUCE_UMIN:
  3492. case ISD::VP_REDUCE_SMIN:
  3493. case ISD::VP_REDUCE_FADD:
  3494. case ISD::VP_REDUCE_SEQ_FADD:
  3495. case ISD::VP_REDUCE_FMIN:
  3496. case ISD::VP_REDUCE_FMAX:
  3497. return lowerVPREDUCE(Op, DAG);
  3498. case ISD::VP_REDUCE_AND:
  3499. case ISD::VP_REDUCE_OR:
  3500. case ISD::VP_REDUCE_XOR:
  3501. if (Op.getOperand(1).getValueType().getVectorElementType() == MVT::i1)
  3502. return lowerVectorMaskVecReduction(Op, DAG, /*IsVP*/ true);
  3503. return lowerVPREDUCE(Op, DAG);
  3504. case ISD::INSERT_SUBVECTOR:
  3505. return lowerINSERT_SUBVECTOR(Op, DAG);
  3506. case ISD::EXTRACT_SUBVECTOR:
  3507. return lowerEXTRACT_SUBVECTOR(Op, DAG);
  3508. case ISD::STEP_VECTOR:
  3509. return lowerSTEP_VECTOR(Op, DAG);
  3510. case ISD::VECTOR_REVERSE:
  3511. return lowerVECTOR_REVERSE(Op, DAG);
  3512. case ISD::VECTOR_SPLICE:
  3513. return lowerVECTOR_SPLICE(Op, DAG);
  3514. case ISD::BUILD_VECTOR:
  3515. return lowerBUILD_VECTOR(Op, DAG, Subtarget);
  3516. case ISD::SPLAT_VECTOR:
  3517. if (Op.getValueType().getVectorElementType() == MVT::i1)
  3518. return lowerVectorMaskSplat(Op, DAG);
  3519. return SDValue();
  3520. case ISD::VECTOR_SHUFFLE:
  3521. return lowerVECTOR_SHUFFLE(Op, DAG, Subtarget);
  3522. case ISD::CONCAT_VECTORS: {
  3523. // Split CONCAT_VECTORS into a series of INSERT_SUBVECTOR nodes. This is
  3524. // better than going through the stack, as the default expansion does.
  3525. SDLoc DL(Op);
  3526. MVT VT = Op.getSimpleValueType();
  3527. unsigned NumOpElts =
  3528. Op.getOperand(0).getSimpleValueType().getVectorMinNumElements();
  3529. SDValue Vec = DAG.getUNDEF(VT);
  3530. for (const auto &OpIdx : enumerate(Op->ops())) {
  3531. SDValue SubVec = OpIdx.value();
  3532. // Don't insert undef subvectors.
  3533. if (SubVec.isUndef())
  3534. continue;
  3535. Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, Vec, SubVec,
  3536. DAG.getIntPtrConstant(OpIdx.index() * NumOpElts, DL));
  3537. }
  3538. return Vec;
  3539. }
  3540. case ISD::LOAD:
  3541. if (auto V = expandUnalignedRVVLoad(Op, DAG))
  3542. return V;
  3543. if (Op.getValueType().isFixedLengthVector())
  3544. return lowerFixedLengthVectorLoadToRVV(Op, DAG);
  3545. return Op;
  3546. case ISD::STORE:
  3547. if (auto V = expandUnalignedRVVStore(Op, DAG))
  3548. return V;
  3549. if (Op.getOperand(1).getValueType().isFixedLengthVector())
  3550. return lowerFixedLengthVectorStoreToRVV(Op, DAG);
  3551. return Op;
  3552. case ISD::MLOAD:
  3553. case ISD::VP_LOAD:
  3554. return lowerMaskedLoad(Op, DAG);
  3555. case ISD::MSTORE:
  3556. case ISD::VP_STORE:
  3557. return lowerMaskedStore(Op, DAG);
  3558. case ISD::SELECT_CC: {
  3559. // This occurs because we custom legalize SETGT and SETUGT for setcc. That
  3560. // causes LegalizeDAG to think we need to custom legalize select_cc. Expand
  3561. // into separate SETCC+SELECT_CC just like LegalizeDAG.
  3562. SDValue Tmp1 = Op.getOperand(0);
  3563. SDValue Tmp2 = Op.getOperand(1);
  3564. SDValue True = Op.getOperand(2);
  3565. SDValue False = Op.getOperand(3);
  3566. EVT VT = Op.getValueType();
  3567. SDValue CC = Op.getOperand(4);
  3568. EVT CmpVT = Tmp1.getValueType();
  3569. EVT CCVT =
  3570. getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), CmpVT);
  3571. SDLoc DL(Op);
  3572. SDValue Cond =
  3573. DAG.getNode(ISD::SETCC, DL, CCVT, Tmp1, Tmp2, CC, Op->getFlags());
  3574. return DAG.getSelect(DL, VT, Cond, True, False);
  3575. }
  3576. case ISD::SETCC: {
  3577. MVT OpVT = Op.getOperand(0).getSimpleValueType();
  3578. if (OpVT.isScalarInteger()) {
  3579. MVT VT = Op.getSimpleValueType();
  3580. SDValue LHS = Op.getOperand(0);
  3581. SDValue RHS = Op.getOperand(1);
  3582. ISD::CondCode CCVal = cast<CondCodeSDNode>(Op.getOperand(2))->get();
  3583. assert((CCVal == ISD::SETGT || CCVal == ISD::SETUGT) &&
  3584. "Unexpected CondCode");
  3585. SDLoc DL(Op);
  3586. // If the RHS is a constant in the range [-2049, 0) or (0, 2046], we can
  3587. // convert this to the equivalent of (set(u)ge X, C+1) by using
  3588. // (xori (slti(u) X, C+1), 1). This avoids materializing a small constant
  3589. // in a register.
  3590. if (isa<ConstantSDNode>(RHS)) {
  3591. int64_t Imm = cast<ConstantSDNode>(RHS)->getSExtValue();
  3592. if (Imm != 0 && isInt<12>((uint64_t)Imm + 1)) {
  3593. // X > -1 should have been replaced with false.
  3594. assert((CCVal != ISD::SETUGT || Imm != -1) &&
  3595. "Missing canonicalization");
  3596. // Using getSetCCSwappedOperands will convert SET(U)GT->SET(U)LT.
  3597. CCVal = ISD::getSetCCSwappedOperands(CCVal);
  3598. SDValue SetCC = DAG.getSetCC(
  3599. DL, VT, LHS, DAG.getConstant(Imm + 1, DL, OpVT), CCVal);
  3600. return DAG.getLogicalNOT(DL, SetCC, VT);
  3601. }
  3602. }
  3603. // Not a constant we could handle, swap the operands and condition code to
  3604. // SETLT/SETULT.
  3605. CCVal = ISD::getSetCCSwappedOperands(CCVal);
  3606. return DAG.getSetCC(DL, VT, RHS, LHS, CCVal);
  3607. }
  3608. return lowerFixedLengthVectorSetccToRVV(Op, DAG);
  3609. }
  3610. case ISD::ADD:
  3611. return lowerToScalableOp(Op, DAG, RISCVISD::ADD_VL, /*HasMergeOp*/ true);
  3612. case ISD::SUB:
  3613. return lowerToScalableOp(Op, DAG, RISCVISD::SUB_VL, /*HasMergeOp*/ true);
  3614. case ISD::MUL:
  3615. return lowerToScalableOp(Op, DAG, RISCVISD::MUL_VL, /*HasMergeOp*/ true);
  3616. case ISD::MULHS:
  3617. return lowerToScalableOp(Op, DAG, RISCVISD::MULHS_VL, /*HasMergeOp*/ true);
  3618. case ISD::MULHU:
  3619. return lowerToScalableOp(Op, DAG, RISCVISD::MULHU_VL, /*HasMergeOp*/ true);
  3620. case ISD::AND:
  3621. return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMAND_VL,
  3622. RISCVISD::AND_VL);
  3623. case ISD::OR:
  3624. return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMOR_VL,
  3625. RISCVISD::OR_VL);
  3626. case ISD::XOR:
  3627. return lowerFixedLengthVectorLogicOpToRVV(Op, DAG, RISCVISD::VMXOR_VL,
  3628. RISCVISD::XOR_VL);
  3629. case ISD::SDIV:
  3630. return lowerToScalableOp(Op, DAG, RISCVISD::SDIV_VL, /*HasMergeOp*/ true);
  3631. case ISD::SREM:
  3632. return lowerToScalableOp(Op, DAG, RISCVISD::SREM_VL, /*HasMergeOp*/ true);
  3633. case ISD::UDIV:
  3634. return lowerToScalableOp(Op, DAG, RISCVISD::UDIV_VL, /*HasMergeOp*/ true);
  3635. case ISD::UREM:
  3636. return lowerToScalableOp(Op, DAG, RISCVISD::UREM_VL, /*HasMergeOp*/ true);
  3637. case ISD::SHL:
  3638. case ISD::SRA:
  3639. case ISD::SRL:
  3640. if (Op.getSimpleValueType().isFixedLengthVector())
  3641. return lowerFixedLengthVectorShiftToRVV(Op, DAG);
  3642. // This can be called for an i32 shift amount that needs to be promoted.
  3643. assert(Op.getOperand(1).getValueType() == MVT::i32 && Subtarget.is64Bit() &&
  3644. "Unexpected custom legalisation");
  3645. return SDValue();
  3646. case ISD::SADDSAT:
  3647. return lowerToScalableOp(Op, DAG, RISCVISD::SADDSAT_VL,
  3648. /*HasMergeOp*/ true);
  3649. case ISD::UADDSAT:
  3650. return lowerToScalableOp(Op, DAG, RISCVISD::UADDSAT_VL,
  3651. /*HasMergeOp*/ true);
  3652. case ISD::SSUBSAT:
  3653. return lowerToScalableOp(Op, DAG, RISCVISD::SSUBSAT_VL,
  3654. /*HasMergeOp*/ true);
  3655. case ISD::USUBSAT:
  3656. return lowerToScalableOp(Op, DAG, RISCVISD::USUBSAT_VL,
  3657. /*HasMergeOp*/ true);
  3658. case ISD::FADD:
  3659. return lowerToScalableOp(Op, DAG, RISCVISD::FADD_VL, /*HasMergeOp*/ true);
  3660. case ISD::FSUB:
  3661. return lowerToScalableOp(Op, DAG, RISCVISD::FSUB_VL, /*HasMergeOp*/ true);
  3662. case ISD::FMUL:
  3663. return lowerToScalableOp(Op, DAG, RISCVISD::FMUL_VL, /*HasMergeOp*/ true);
  3664. case ISD::FDIV:
  3665. return lowerToScalableOp(Op, DAG, RISCVISD::FDIV_VL, /*HasMergeOp*/ true);
  3666. case ISD::FNEG:
  3667. return lowerToScalableOp(Op, DAG, RISCVISD::FNEG_VL);
  3668. case ISD::FABS:
  3669. return lowerToScalableOp(Op, DAG, RISCVISD::FABS_VL);
  3670. case ISD::FSQRT:
  3671. return lowerToScalableOp(Op, DAG, RISCVISD::FSQRT_VL);
  3672. case ISD::FMA:
  3673. return lowerToScalableOp(Op, DAG, RISCVISD::VFMADD_VL);
  3674. case ISD::SMIN:
  3675. return lowerToScalableOp(Op, DAG, RISCVISD::SMIN_VL, /*HasMergeOp*/ true);
  3676. case ISD::SMAX:
  3677. return lowerToScalableOp(Op, DAG, RISCVISD::SMAX_VL, /*HasMergeOp*/ true);
  3678. case ISD::UMIN:
  3679. return lowerToScalableOp(Op, DAG, RISCVISD::UMIN_VL, /*HasMergeOp*/ true);
  3680. case ISD::UMAX:
  3681. return lowerToScalableOp(Op, DAG, RISCVISD::UMAX_VL, /*HasMergeOp*/ true);
  3682. case ISD::FMINNUM:
  3683. return lowerToScalableOp(Op, DAG, RISCVISD::FMINNUM_VL,
  3684. /*HasMergeOp*/ true);
  3685. case ISD::FMAXNUM:
  3686. return lowerToScalableOp(Op, DAG, RISCVISD::FMAXNUM_VL,
  3687. /*HasMergeOp*/ true);
  3688. case ISD::ABS:
  3689. case ISD::VP_ABS:
  3690. return lowerABS(Op, DAG);
  3691. case ISD::CTLZ:
  3692. case ISD::CTLZ_ZERO_UNDEF:
  3693. case ISD::CTTZ_ZERO_UNDEF:
  3694. return lowerCTLZ_CTTZ_ZERO_UNDEF(Op, DAG);
  3695. case ISD::VSELECT:
  3696. return lowerFixedLengthVectorSelectToRVV(Op, DAG);
  3697. case ISD::FCOPYSIGN:
  3698. return lowerFixedLengthVectorFCOPYSIGNToRVV(Op, DAG);
  3699. case ISD::MGATHER:
  3700. case ISD::VP_GATHER:
  3701. return lowerMaskedGather(Op, DAG);
  3702. case ISD::MSCATTER:
  3703. case ISD::VP_SCATTER:
  3704. return lowerMaskedScatter(Op, DAG);
  3705. case ISD::GET_ROUNDING:
  3706. return lowerGET_ROUNDING(Op, DAG);
  3707. case ISD::SET_ROUNDING:
  3708. return lowerSET_ROUNDING(Op, DAG);
  3709. case ISD::EH_DWARF_CFA:
  3710. return lowerEH_DWARF_CFA(Op, DAG);
  3711. case ISD::VP_SELECT:
  3712. return lowerVPOp(Op, DAG, RISCVISD::VSELECT_VL);
  3713. case ISD::VP_MERGE:
  3714. return lowerVPOp(Op, DAG, RISCVISD::VP_MERGE_VL);
  3715. case ISD::VP_ADD:
  3716. return lowerVPOp(Op, DAG, RISCVISD::ADD_VL, /*HasMergeOp*/ true);
  3717. case ISD::VP_SUB:
  3718. return lowerVPOp(Op, DAG, RISCVISD::SUB_VL, /*HasMergeOp*/ true);
  3719. case ISD::VP_MUL:
  3720. return lowerVPOp(Op, DAG, RISCVISD::MUL_VL, /*HasMergeOp*/ true);
  3721. case ISD::VP_SDIV:
  3722. return lowerVPOp(Op, DAG, RISCVISD::SDIV_VL, /*HasMergeOp*/ true);
  3723. case ISD::VP_UDIV:
  3724. return lowerVPOp(Op, DAG, RISCVISD::UDIV_VL, /*HasMergeOp*/ true);
  3725. case ISD::VP_SREM:
  3726. return lowerVPOp(Op, DAG, RISCVISD::SREM_VL, /*HasMergeOp*/ true);
  3727. case ISD::VP_UREM:
  3728. return lowerVPOp(Op, DAG, RISCVISD::UREM_VL, /*HasMergeOp*/ true);
  3729. case ISD::VP_AND:
  3730. return lowerLogicVPOp(Op, DAG, RISCVISD::VMAND_VL, RISCVISD::AND_VL);
  3731. case ISD::VP_OR:
  3732. return lowerLogicVPOp(Op, DAG, RISCVISD::VMOR_VL, RISCVISD::OR_VL);
  3733. case ISD::VP_XOR:
  3734. return lowerLogicVPOp(Op, DAG, RISCVISD::VMXOR_VL, RISCVISD::XOR_VL);
  3735. case ISD::VP_ASHR:
  3736. return lowerVPOp(Op, DAG, RISCVISD::SRA_VL, /*HasMergeOp*/ true);
  3737. case ISD::VP_LSHR:
  3738. return lowerVPOp(Op, DAG, RISCVISD::SRL_VL, /*HasMergeOp*/ true);
  3739. case ISD::VP_SHL:
  3740. return lowerVPOp(Op, DAG, RISCVISD::SHL_VL, /*HasMergeOp*/ true);
  3741. case ISD::VP_FADD:
  3742. return lowerVPOp(Op, DAG, RISCVISD::FADD_VL, /*HasMergeOp*/ true);
  3743. case ISD::VP_FSUB:
  3744. return lowerVPOp(Op, DAG, RISCVISD::FSUB_VL, /*HasMergeOp*/ true);
  3745. case ISD::VP_FMUL:
  3746. return lowerVPOp(Op, DAG, RISCVISD::FMUL_VL, /*HasMergeOp*/ true);
  3747. case ISD::VP_FDIV:
  3748. return lowerVPOp(Op, DAG, RISCVISD::FDIV_VL, /*HasMergeOp*/ true);
  3749. case ISD::VP_FNEG:
  3750. return lowerVPOp(Op, DAG, RISCVISD::FNEG_VL);
  3751. case ISD::VP_FABS:
  3752. return lowerVPOp(Op, DAG, RISCVISD::FABS_VL);
  3753. case ISD::VP_SQRT:
  3754. return lowerVPOp(Op, DAG, RISCVISD::FSQRT_VL);
  3755. case ISD::VP_FMA:
  3756. return lowerVPOp(Op, DAG, RISCVISD::VFMADD_VL);
  3757. case ISD::VP_FMINNUM:
  3758. return lowerVPOp(Op, DAG, RISCVISD::FMINNUM_VL, /*HasMergeOp*/ true);
  3759. case ISD::VP_FMAXNUM:
  3760. return lowerVPOp(Op, DAG, RISCVISD::FMAXNUM_VL, /*HasMergeOp*/ true);
  3761. case ISD::VP_FCOPYSIGN:
  3762. return lowerVPOp(Op, DAG, RISCVISD::FCOPYSIGN_VL, /*HasMergeOp*/ true);
  3763. case ISD::VP_SIGN_EXTEND:
  3764. case ISD::VP_ZERO_EXTEND:
  3765. if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
  3766. return lowerVPExtMaskOp(Op, DAG);
  3767. return lowerVPOp(Op, DAG,
  3768. Op.getOpcode() == ISD::VP_SIGN_EXTEND
  3769. ? RISCVISD::VSEXT_VL
  3770. : RISCVISD::VZEXT_VL);
  3771. case ISD::VP_TRUNCATE:
  3772. return lowerVectorTruncLike(Op, DAG);
  3773. case ISD::VP_FP_EXTEND:
  3774. case ISD::VP_FP_ROUND:
  3775. return lowerVectorFPExtendOrRoundLike(Op, DAG);
  3776. case ISD::VP_FP_TO_SINT:
  3777. return lowerVPFPIntConvOp(Op, DAG, RISCVISD::VFCVT_RTZ_X_F_VL);
  3778. case ISD::VP_FP_TO_UINT:
  3779. return lowerVPFPIntConvOp(Op, DAG, RISCVISD::VFCVT_RTZ_XU_F_VL);
  3780. case ISD::VP_SINT_TO_FP:
  3781. return lowerVPFPIntConvOp(Op, DAG, RISCVISD::SINT_TO_FP_VL);
  3782. case ISD::VP_UINT_TO_FP:
  3783. return lowerVPFPIntConvOp(Op, DAG, RISCVISD::UINT_TO_FP_VL);
  3784. case ISD::VP_SETCC:
  3785. if (Op.getOperand(0).getSimpleValueType().getVectorElementType() == MVT::i1)
  3786. return lowerVPSetCCMaskOp(Op, DAG);
  3787. return lowerVPOp(Op, DAG, RISCVISD::SETCC_VL, /*HasMergeOp*/ true);
  3788. case ISD::VP_SMIN:
  3789. return lowerVPOp(Op, DAG, RISCVISD::SMIN_VL, /*HasMergeOp*/ true);
  3790. case ISD::VP_SMAX:
  3791. return lowerVPOp(Op, DAG, RISCVISD::SMAX_VL, /*HasMergeOp*/ true);
  3792. case ISD::VP_UMIN:
  3793. return lowerVPOp(Op, DAG, RISCVISD::UMIN_VL, /*HasMergeOp*/ true);
  3794. case ISD::VP_UMAX:
  3795. return lowerVPOp(Op, DAG, RISCVISD::UMAX_VL, /*HasMergeOp*/ true);
  3796. case ISD::EXPERIMENTAL_VP_STRIDED_LOAD:
  3797. return lowerVPStridedLoad(Op, DAG);
  3798. case ISD::EXPERIMENTAL_VP_STRIDED_STORE:
  3799. return lowerVPStridedStore(Op, DAG);
  3800. case ISD::VP_FCEIL:
  3801. case ISD::VP_FFLOOR:
  3802. case ISD::VP_FRINT:
  3803. case ISD::VP_FNEARBYINT:
  3804. case ISD::VP_FROUND:
  3805. case ISD::VP_FROUNDEVEN:
  3806. case ISD::VP_FROUNDTOZERO:
  3807. return lowerVectorFTRUNC_FCEIL_FFLOOR_FROUND(Op, DAG, Subtarget);
  3808. }
  3809. }
  3810. static SDValue getTargetNode(GlobalAddressSDNode *N, SDLoc DL, EVT Ty,
  3811. SelectionDAG &DAG, unsigned Flags) {
  3812. return DAG.getTargetGlobalAddress(N->getGlobal(), DL, Ty, 0, Flags);
  3813. }
  3814. static SDValue getTargetNode(BlockAddressSDNode *N, SDLoc DL, EVT Ty,
  3815. SelectionDAG &DAG, unsigned Flags) {
  3816. return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, N->getOffset(),
  3817. Flags);
  3818. }
  3819. static SDValue getTargetNode(ConstantPoolSDNode *N, SDLoc DL, EVT Ty,
  3820. SelectionDAG &DAG, unsigned Flags) {
  3821. return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
  3822. N->getOffset(), Flags);
  3823. }
  3824. static SDValue getTargetNode(JumpTableSDNode *N, SDLoc DL, EVT Ty,
  3825. SelectionDAG &DAG, unsigned Flags) {
  3826. return DAG.getTargetJumpTable(N->getIndex(), Ty, Flags);
  3827. }
  3828. template <class NodeTy>
  3829. SDValue RISCVTargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
  3830. bool IsLocal) const {
  3831. SDLoc DL(N);
  3832. EVT Ty = getPointerTy(DAG.getDataLayout());
  3833. // When HWASAN is used and tagging of global variables is enabled
  3834. // they should be accessed via the GOT, since the tagged address of a global
  3835. // is incompatible with existing code models. This also applies to non-pic
  3836. // mode.
  3837. if (isPositionIndependent() || Subtarget.allowTaggedGlobals()) {
  3838. SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
  3839. if (IsLocal && !Subtarget.allowTaggedGlobals())
  3840. // Use PC-relative addressing to access the symbol. This generates the
  3841. // pattern (PseudoLLA sym), which expands to (addi (auipc %pcrel_hi(sym))
  3842. // %pcrel_lo(auipc)).
  3843. return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
  3844. // Use PC-relative addressing to access the GOT for this symbol, then load
  3845. // the address from the GOT. This generates the pattern (PseudoLA sym),
  3846. // which expands to (ld (addi (auipc %got_pcrel_hi(sym)) %pcrel_lo(auipc))).
  3847. MachineFunction &MF = DAG.getMachineFunction();
  3848. MachineMemOperand *MemOp = MF.getMachineMemOperand(
  3849. MachinePointerInfo::getGOT(MF),
  3850. MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
  3851. MachineMemOperand::MOInvariant,
  3852. LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
  3853. SDValue Load =
  3854. DAG.getMemIntrinsicNode(RISCVISD::LA, DL, DAG.getVTList(Ty, MVT::Other),
  3855. {DAG.getEntryNode(), Addr}, Ty, MemOp);
  3856. return Load;
  3857. }
  3858. switch (getTargetMachine().getCodeModel()) {
  3859. default:
  3860. report_fatal_error("Unsupported code model for lowering");
  3861. case CodeModel::Small: {
  3862. // Generate a sequence for accessing addresses within the first 2 GiB of
  3863. // address space. This generates the pattern (addi (lui %hi(sym)) %lo(sym)).
  3864. SDValue AddrHi = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_HI);
  3865. SDValue AddrLo = getTargetNode(N, DL, Ty, DAG, RISCVII::MO_LO);
  3866. SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
  3867. return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNHi, AddrLo);
  3868. }
  3869. case CodeModel::Medium: {
  3870. // Generate a sequence for accessing addresses within any 2GiB range within
  3871. // the address space. This generates the pattern (PseudoLLA sym), which
  3872. // expands to (addi (auipc %pcrel_hi(sym)) %pcrel_lo(auipc)).
  3873. SDValue Addr = getTargetNode(N, DL, Ty, DAG, 0);
  3874. return DAG.getNode(RISCVISD::LLA, DL, Ty, Addr);
  3875. }
  3876. }
  3877. }
  3878. SDValue RISCVTargetLowering::lowerGlobalAddress(SDValue Op,
  3879. SelectionDAG &DAG) const {
  3880. GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
  3881. assert(N->getOffset() == 0 && "unexpected offset in global node");
  3882. return getAddr(N, DAG, N->getGlobal()->isDSOLocal());
  3883. }
  3884. SDValue RISCVTargetLowering::lowerBlockAddress(SDValue Op,
  3885. SelectionDAG &DAG) const {
  3886. BlockAddressSDNode *N = cast<BlockAddressSDNode>(Op);
  3887. return getAddr(N, DAG);
  3888. }
  3889. SDValue RISCVTargetLowering::lowerConstantPool(SDValue Op,
  3890. SelectionDAG &DAG) const {
  3891. ConstantPoolSDNode *N = cast<ConstantPoolSDNode>(Op);
  3892. return getAddr(N, DAG);
  3893. }
  3894. SDValue RISCVTargetLowering::lowerJumpTable(SDValue Op,
  3895. SelectionDAG &DAG) const {
  3896. JumpTableSDNode *N = cast<JumpTableSDNode>(Op);
  3897. return getAddr(N, DAG);
  3898. }
  3899. SDValue RISCVTargetLowering::getStaticTLSAddr(GlobalAddressSDNode *N,
  3900. SelectionDAG &DAG,
  3901. bool UseGOT) const {
  3902. SDLoc DL(N);
  3903. EVT Ty = getPointerTy(DAG.getDataLayout());
  3904. const GlobalValue *GV = N->getGlobal();
  3905. MVT XLenVT = Subtarget.getXLenVT();
  3906. if (UseGOT) {
  3907. // Use PC-relative addressing to access the GOT for this TLS symbol, then
  3908. // load the address from the GOT and add the thread pointer. This generates
  3909. // the pattern (PseudoLA_TLS_IE sym), which expands to
  3910. // (ld (auipc %tls_ie_pcrel_hi(sym)) %pcrel_lo(auipc)).
  3911. SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
  3912. MachineFunction &MF = DAG.getMachineFunction();
  3913. MachineMemOperand *MemOp = MF.getMachineMemOperand(
  3914. MachinePointerInfo::getGOT(MF),
  3915. MachineMemOperand::MOLoad | MachineMemOperand::MODereferenceable |
  3916. MachineMemOperand::MOInvariant,
  3917. LLT(Ty.getSimpleVT()), Align(Ty.getFixedSizeInBits() / 8));
  3918. SDValue Load = DAG.getMemIntrinsicNode(
  3919. RISCVISD::LA_TLS_IE, DL, DAG.getVTList(Ty, MVT::Other),
  3920. {DAG.getEntryNode(), Addr}, Ty, MemOp);
  3921. // Add the thread pointer.
  3922. SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
  3923. return DAG.getNode(ISD::ADD, DL, Ty, Load, TPReg);
  3924. }
  3925. // Generate a sequence for accessing the address relative to the thread
  3926. // pointer, with the appropriate adjustment for the thread pointer offset.
  3927. // This generates the pattern
  3928. // (add (add_tprel (lui %tprel_hi(sym)) tp %tprel_add(sym)) %tprel_lo(sym))
  3929. SDValue AddrHi =
  3930. DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_HI);
  3931. SDValue AddrAdd =
  3932. DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_ADD);
  3933. SDValue AddrLo =
  3934. DAG.getTargetGlobalAddress(GV, DL, Ty, 0, RISCVII::MO_TPREL_LO);
  3935. SDValue MNHi = DAG.getNode(RISCVISD::HI, DL, Ty, AddrHi);
  3936. SDValue TPReg = DAG.getRegister(RISCV::X4, XLenVT);
  3937. SDValue MNAdd =
  3938. DAG.getNode(RISCVISD::ADD_TPREL, DL, Ty, MNHi, TPReg, AddrAdd);
  3939. return DAG.getNode(RISCVISD::ADD_LO, DL, Ty, MNAdd, AddrLo);
  3940. }
  3941. SDValue RISCVTargetLowering::getDynamicTLSAddr(GlobalAddressSDNode *N,
  3942. SelectionDAG &DAG) const {
  3943. SDLoc DL(N);
  3944. EVT Ty = getPointerTy(DAG.getDataLayout());
  3945. IntegerType *CallTy = Type::getIntNTy(*DAG.getContext(), Ty.getSizeInBits());
  3946. const GlobalValue *GV = N->getGlobal();
  3947. // Use a PC-relative addressing mode to access the global dynamic GOT address.
  3948. // This generates the pattern (PseudoLA_TLS_GD sym), which expands to
  3949. // (addi (auipc %tls_gd_pcrel_hi(sym)) %pcrel_lo(auipc)).
  3950. SDValue Addr = DAG.getTargetGlobalAddress(GV, DL, Ty, 0, 0);
  3951. SDValue Load = DAG.getNode(RISCVISD::LA_TLS_GD, DL, Ty, Addr);
  3952. // Prepare argument list to generate call.
  3953. ArgListTy Args;
  3954. ArgListEntry Entry;
  3955. Entry.Node = Load;
  3956. Entry.Ty = CallTy;
  3957. Args.push_back(Entry);
  3958. // Setup call to __tls_get_addr.
  3959. TargetLowering::CallLoweringInfo CLI(DAG);
  3960. CLI.setDebugLoc(DL)
  3961. .setChain(DAG.getEntryNode())
  3962. .setLibCallee(CallingConv::C, CallTy,
  3963. DAG.getExternalSymbol("__tls_get_addr", Ty),
  3964. std::move(Args));
  3965. return LowerCallTo(CLI).first;
  3966. }
  3967. SDValue RISCVTargetLowering::lowerGlobalTLSAddress(SDValue Op,
  3968. SelectionDAG &DAG) const {
  3969. GlobalAddressSDNode *N = cast<GlobalAddressSDNode>(Op);
  3970. assert(N->getOffset() == 0 && "unexpected offset in global node");
  3971. TLSModel::Model Model = getTargetMachine().getTLSModel(N->getGlobal());
  3972. if (DAG.getMachineFunction().getFunction().getCallingConv() ==
  3973. CallingConv::GHC)
  3974. report_fatal_error("In GHC calling convention TLS is not supported");
  3975. SDValue Addr;
  3976. switch (Model) {
  3977. case TLSModel::LocalExec:
  3978. Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/false);
  3979. break;
  3980. case TLSModel::InitialExec:
  3981. Addr = getStaticTLSAddr(N, DAG, /*UseGOT=*/true);
  3982. break;
  3983. case TLSModel::LocalDynamic:
  3984. case TLSModel::GeneralDynamic:
  3985. Addr = getDynamicTLSAddr(N, DAG);
  3986. break;
  3987. }
  3988. return Addr;
  3989. }
  3990. SDValue RISCVTargetLowering::lowerSELECT(SDValue Op, SelectionDAG &DAG) const {
  3991. SDValue CondV = Op.getOperand(0);
  3992. SDValue TrueV = Op.getOperand(1);
  3993. SDValue FalseV = Op.getOperand(2);
  3994. SDLoc DL(Op);
  3995. MVT VT = Op.getSimpleValueType();
  3996. MVT XLenVT = Subtarget.getXLenVT();
  3997. // Lower vector SELECTs to VSELECTs by splatting the condition.
  3998. if (VT.isVector()) {
  3999. MVT SplatCondVT = VT.changeVectorElementType(MVT::i1);
  4000. SDValue CondSplat = DAG.getSplat(SplatCondVT, DL, CondV);
  4001. return DAG.getNode(ISD::VSELECT, DL, VT, CondSplat, TrueV, FalseV);
  4002. }
  4003. if (!Subtarget.hasShortForwardBranchOpt()) {
  4004. // (select c, -1, y) -> -c | y
  4005. if (isAllOnesConstant(TrueV)) {
  4006. SDValue Neg = DAG.getNegative(CondV, DL, VT);
  4007. return DAG.getNode(ISD::OR, DL, VT, Neg, FalseV);
  4008. }
  4009. // (select c, y, -1) -> (c-1) | y
  4010. if (isAllOnesConstant(FalseV)) {
  4011. SDValue Neg = DAG.getNode(ISD::ADD, DL, VT, CondV,
  4012. DAG.getAllOnesConstant(DL, VT));
  4013. return DAG.getNode(ISD::OR, DL, VT, Neg, TrueV);
  4014. }
  4015. // (select c, 0, y) -> (c-1) & y
  4016. if (isNullConstant(TrueV)) {
  4017. SDValue Neg = DAG.getNode(ISD::ADD, DL, VT, CondV,
  4018. DAG.getAllOnesConstant(DL, VT));
  4019. return DAG.getNode(ISD::AND, DL, VT, Neg, FalseV);
  4020. }
  4021. // (select c, y, 0) -> -c & y
  4022. if (isNullConstant(FalseV)) {
  4023. SDValue Neg = DAG.getNegative(CondV, DL, VT);
  4024. return DAG.getNode(ISD::AND, DL, VT, Neg, TrueV);
  4025. }
  4026. }
  4027. // If the condition is not an integer SETCC which operates on XLenVT, we need
  4028. // to emit a RISCVISD::SELECT_CC comparing the condition to zero. i.e.:
  4029. // (select condv, truev, falsev)
  4030. // -> (riscvisd::select_cc condv, zero, setne, truev, falsev)
  4031. if (CondV.getOpcode() != ISD::SETCC ||
  4032. CondV.getOperand(0).getSimpleValueType() != XLenVT) {
  4033. SDValue Zero = DAG.getConstant(0, DL, XLenVT);
  4034. SDValue SetNE = DAG.getCondCode(ISD::SETNE);
  4035. SDValue Ops[] = {CondV, Zero, SetNE, TrueV, FalseV};
  4036. return DAG.getNode(RISCVISD::SELECT_CC, DL, VT, Ops);
  4037. }
  4038. // If the CondV is the output of a SETCC node which operates on XLenVT inputs,
  4039. // then merge the SETCC node into the lowered RISCVISD::SELECT_CC to take
  4040. // advantage of the integer compare+branch instructions. i.e.:
  4041. // (select (setcc lhs, rhs, cc), truev, falsev)
  4042. // -> (riscvisd::select_cc lhs, rhs, cc, truev, falsev)
  4043. SDValue LHS = CondV.getOperand(0);
  4044. SDValue RHS = CondV.getOperand(1);
  4045. ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
  4046. // Special case for a select of 2 constants that have a diffence of 1.
  4047. // Normally this is done by DAGCombine, but if the select is introduced by
  4048. // type legalization or op legalization, we miss it. Restricting to SETLT
  4049. // case for now because that is what signed saturating add/sub need.
  4050. // FIXME: We don't need the condition to be SETLT or even a SETCC,
  4051. // but we would probably want to swap the true/false values if the condition
  4052. // is SETGE/SETLE to avoid an XORI.
  4053. if (isa<ConstantSDNode>(TrueV) && isa<ConstantSDNode>(FalseV) &&
  4054. CCVal == ISD::SETLT) {
  4055. const APInt &TrueVal = cast<ConstantSDNode>(TrueV)->getAPIntValue();
  4056. const APInt &FalseVal = cast<ConstantSDNode>(FalseV)->getAPIntValue();
  4057. if (TrueVal - 1 == FalseVal)
  4058. return DAG.getNode(ISD::ADD, DL, VT, CondV, FalseV);
  4059. if (TrueVal + 1 == FalseVal)
  4060. return DAG.getNode(ISD::SUB, DL, VT, FalseV, CondV);
  4061. }
  4062. translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
  4063. // 1 < x ? x : 1 -> 0 < x ? x : 1
  4064. if (isOneConstant(LHS) && (CCVal == ISD::SETLT || CCVal == ISD::SETULT) &&
  4065. RHS == TrueV && LHS == FalseV) {
  4066. LHS = DAG.getConstant(0, DL, VT);
  4067. // 0 <u x is the same as x != 0.
  4068. if (CCVal == ISD::SETULT) {
  4069. std::swap(LHS, RHS);
  4070. CCVal = ISD::SETNE;
  4071. }
  4072. }
  4073. // x <s -1 ? x : -1 -> x <s 0 ? x : -1
  4074. if (isAllOnesConstant(RHS) && CCVal == ISD::SETLT && LHS == TrueV &&
  4075. RHS == FalseV) {
  4076. RHS = DAG.getConstant(0, DL, VT);
  4077. }
  4078. SDValue TargetCC = DAG.getCondCode(CCVal);
  4079. if (isa<ConstantSDNode>(TrueV) && !isa<ConstantSDNode>(FalseV)) {
  4080. // (select (setcc lhs, rhs, CC), constant, falsev)
  4081. // -> (select (setcc lhs, rhs, InverseCC), falsev, constant)
  4082. std::swap(TrueV, FalseV);
  4083. TargetCC = DAG.getCondCode(ISD::getSetCCInverse(CCVal, LHS.getValueType()));
  4084. }
  4085. SDValue Ops[] = {LHS, RHS, TargetCC, TrueV, FalseV};
  4086. return DAG.getNode(RISCVISD::SELECT_CC, DL, VT, Ops);
  4087. }
  4088. SDValue RISCVTargetLowering::lowerBRCOND(SDValue Op, SelectionDAG &DAG) const {
  4089. SDValue CondV = Op.getOperand(1);
  4090. SDLoc DL(Op);
  4091. MVT XLenVT = Subtarget.getXLenVT();
  4092. if (CondV.getOpcode() == ISD::SETCC &&
  4093. CondV.getOperand(0).getValueType() == XLenVT) {
  4094. SDValue LHS = CondV.getOperand(0);
  4095. SDValue RHS = CondV.getOperand(1);
  4096. ISD::CondCode CCVal = cast<CondCodeSDNode>(CondV.getOperand(2))->get();
  4097. translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
  4098. SDValue TargetCC = DAG.getCondCode(CCVal);
  4099. return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
  4100. LHS, RHS, TargetCC, Op.getOperand(2));
  4101. }
  4102. return DAG.getNode(RISCVISD::BR_CC, DL, Op.getValueType(), Op.getOperand(0),
  4103. CondV, DAG.getConstant(0, DL, XLenVT),
  4104. DAG.getCondCode(ISD::SETNE), Op.getOperand(2));
  4105. }
  4106. SDValue RISCVTargetLowering::lowerVASTART(SDValue Op, SelectionDAG &DAG) const {
  4107. MachineFunction &MF = DAG.getMachineFunction();
  4108. RISCVMachineFunctionInfo *FuncInfo = MF.getInfo<RISCVMachineFunctionInfo>();
  4109. SDLoc DL(Op);
  4110. SDValue FI = DAG.getFrameIndex(FuncInfo->getVarArgsFrameIndex(),
  4111. getPointerTy(MF.getDataLayout()));
  4112. // vastart just stores the address of the VarArgsFrameIndex slot into the
  4113. // memory location argument.
  4114. const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  4115. return DAG.getStore(Op.getOperand(0), DL, FI, Op.getOperand(1),
  4116. MachinePointerInfo(SV));
  4117. }
  4118. SDValue RISCVTargetLowering::lowerFRAMEADDR(SDValue Op,
  4119. SelectionDAG &DAG) const {
  4120. const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
  4121. MachineFunction &MF = DAG.getMachineFunction();
  4122. MachineFrameInfo &MFI = MF.getFrameInfo();
  4123. MFI.setFrameAddressIsTaken(true);
  4124. Register FrameReg = RI.getFrameRegister(MF);
  4125. int XLenInBytes = Subtarget.getXLen() / 8;
  4126. EVT VT = Op.getValueType();
  4127. SDLoc DL(Op);
  4128. SDValue FrameAddr = DAG.getCopyFromReg(DAG.getEntryNode(), DL, FrameReg, VT);
  4129. unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  4130. while (Depth--) {
  4131. int Offset = -(XLenInBytes * 2);
  4132. SDValue Ptr = DAG.getNode(ISD::ADD, DL, VT, FrameAddr,
  4133. DAG.getIntPtrConstant(Offset, DL));
  4134. FrameAddr =
  4135. DAG.getLoad(VT, DL, DAG.getEntryNode(), Ptr, MachinePointerInfo());
  4136. }
  4137. return FrameAddr;
  4138. }
  4139. SDValue RISCVTargetLowering::lowerRETURNADDR(SDValue Op,
  4140. SelectionDAG &DAG) const {
  4141. const RISCVRegisterInfo &RI = *Subtarget.getRegisterInfo();
  4142. MachineFunction &MF = DAG.getMachineFunction();
  4143. MachineFrameInfo &MFI = MF.getFrameInfo();
  4144. MFI.setReturnAddressIsTaken(true);
  4145. MVT XLenVT = Subtarget.getXLenVT();
  4146. int XLenInBytes = Subtarget.getXLen() / 8;
  4147. if (verifyReturnAddressArgumentIsConstant(Op, DAG))
  4148. return SDValue();
  4149. EVT VT = Op.getValueType();
  4150. SDLoc DL(Op);
  4151. unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  4152. if (Depth) {
  4153. int Off = -XLenInBytes;
  4154. SDValue FrameAddr = lowerFRAMEADDR(Op, DAG);
  4155. SDValue Offset = DAG.getConstant(Off, DL, VT);
  4156. return DAG.getLoad(VT, DL, DAG.getEntryNode(),
  4157. DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset),
  4158. MachinePointerInfo());
  4159. }
  4160. // Return the value of the return address register, marking it an implicit
  4161. // live-in.
  4162. Register Reg = MF.addLiveIn(RI.getRARegister(), getRegClassFor(XLenVT));
  4163. return DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, XLenVT);
  4164. }
  4165. SDValue RISCVTargetLowering::lowerShiftLeftParts(SDValue Op,
  4166. SelectionDAG &DAG) const {
  4167. SDLoc DL(Op);
  4168. SDValue Lo = Op.getOperand(0);
  4169. SDValue Hi = Op.getOperand(1);
  4170. SDValue Shamt = Op.getOperand(2);
  4171. EVT VT = Lo.getValueType();
  4172. // if Shamt-XLEN < 0: // Shamt < XLEN
  4173. // Lo = Lo << Shamt
  4174. // Hi = (Hi << Shamt) | ((Lo >>u 1) >>u (XLEN-1 ^ Shamt))
  4175. // else:
  4176. // Lo = 0
  4177. // Hi = Lo << (Shamt-XLEN)
  4178. SDValue Zero = DAG.getConstant(0, DL, VT);
  4179. SDValue One = DAG.getConstant(1, DL, VT);
  4180. SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
  4181. SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
  4182. SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
  4183. SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
  4184. SDValue LoTrue = DAG.getNode(ISD::SHL, DL, VT, Lo, Shamt);
  4185. SDValue ShiftRight1Lo = DAG.getNode(ISD::SRL, DL, VT, Lo, One);
  4186. SDValue ShiftRightLo =
  4187. DAG.getNode(ISD::SRL, DL, VT, ShiftRight1Lo, XLenMinus1Shamt);
  4188. SDValue ShiftLeftHi = DAG.getNode(ISD::SHL, DL, VT, Hi, Shamt);
  4189. SDValue HiTrue = DAG.getNode(ISD::OR, DL, VT, ShiftLeftHi, ShiftRightLo);
  4190. SDValue HiFalse = DAG.getNode(ISD::SHL, DL, VT, Lo, ShamtMinusXLen);
  4191. SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
  4192. Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, Zero);
  4193. Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
  4194. SDValue Parts[2] = {Lo, Hi};
  4195. return DAG.getMergeValues(Parts, DL);
  4196. }
  4197. SDValue RISCVTargetLowering::lowerShiftRightParts(SDValue Op, SelectionDAG &DAG,
  4198. bool IsSRA) const {
  4199. SDLoc DL(Op);
  4200. SDValue Lo = Op.getOperand(0);
  4201. SDValue Hi = Op.getOperand(1);
  4202. SDValue Shamt = Op.getOperand(2);
  4203. EVT VT = Lo.getValueType();
  4204. // SRA expansion:
  4205. // if Shamt-XLEN < 0: // Shamt < XLEN
  4206. // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
  4207. // Hi = Hi >>s Shamt
  4208. // else:
  4209. // Lo = Hi >>s (Shamt-XLEN);
  4210. // Hi = Hi >>s (XLEN-1)
  4211. //
  4212. // SRL expansion:
  4213. // if Shamt-XLEN < 0: // Shamt < XLEN
  4214. // Lo = (Lo >>u Shamt) | ((Hi << 1) << (ShAmt ^ XLEN-1))
  4215. // Hi = Hi >>u Shamt
  4216. // else:
  4217. // Lo = Hi >>u (Shamt-XLEN);
  4218. // Hi = 0;
  4219. unsigned ShiftRightOp = IsSRA ? ISD::SRA : ISD::SRL;
  4220. SDValue Zero = DAG.getConstant(0, DL, VT);
  4221. SDValue One = DAG.getConstant(1, DL, VT);
  4222. SDValue MinusXLen = DAG.getConstant(-(int)Subtarget.getXLen(), DL, VT);
  4223. SDValue XLenMinus1 = DAG.getConstant(Subtarget.getXLen() - 1, DL, VT);
  4224. SDValue ShamtMinusXLen = DAG.getNode(ISD::ADD, DL, VT, Shamt, MinusXLen);
  4225. SDValue XLenMinus1Shamt = DAG.getNode(ISD::SUB, DL, VT, XLenMinus1, Shamt);
  4226. SDValue ShiftRightLo = DAG.getNode(ISD::SRL, DL, VT, Lo, Shamt);
  4227. SDValue ShiftLeftHi1 = DAG.getNode(ISD::SHL, DL, VT, Hi, One);
  4228. SDValue ShiftLeftHi =
  4229. DAG.getNode(ISD::SHL, DL, VT, ShiftLeftHi1, XLenMinus1Shamt);
  4230. SDValue LoTrue = DAG.getNode(ISD::OR, DL, VT, ShiftRightLo, ShiftLeftHi);
  4231. SDValue HiTrue = DAG.getNode(ShiftRightOp, DL, VT, Hi, Shamt);
  4232. SDValue LoFalse = DAG.getNode(ShiftRightOp, DL, VT, Hi, ShamtMinusXLen);
  4233. SDValue HiFalse =
  4234. IsSRA ? DAG.getNode(ISD::SRA, DL, VT, Hi, XLenMinus1) : Zero;
  4235. SDValue CC = DAG.getSetCC(DL, VT, ShamtMinusXLen, Zero, ISD::SETLT);
  4236. Lo = DAG.getNode(ISD::SELECT, DL, VT, CC, LoTrue, LoFalse);
  4237. Hi = DAG.getNode(ISD::SELECT, DL, VT, CC, HiTrue, HiFalse);
  4238. SDValue Parts[2] = {Lo, Hi};
  4239. return DAG.getMergeValues(Parts, DL);
  4240. }
  4241. // Lower splats of i1 types to SETCC. For each mask vector type, we have a
  4242. // legal equivalently-sized i8 type, so we can use that as a go-between.
  4243. SDValue RISCVTargetLowering::lowerVectorMaskSplat(SDValue Op,
  4244. SelectionDAG &DAG) const {
  4245. SDLoc DL(Op);
  4246. MVT VT = Op.getSimpleValueType();
  4247. SDValue SplatVal = Op.getOperand(0);
  4248. // All-zeros or all-ones splats are handled specially.
  4249. if (ISD::isConstantSplatVectorAllOnes(Op.getNode())) {
  4250. SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
  4251. return DAG.getNode(RISCVISD::VMSET_VL, DL, VT, VL);
  4252. }
  4253. if (ISD::isConstantSplatVectorAllZeros(Op.getNode())) {
  4254. SDValue VL = getDefaultScalableVLOps(VT, DL, DAG, Subtarget).second;
  4255. return DAG.getNode(RISCVISD::VMCLR_VL, DL, VT, VL);
  4256. }
  4257. MVT XLenVT = Subtarget.getXLenVT();
  4258. assert(SplatVal.getValueType() == XLenVT &&
  4259. "Unexpected type for i1 splat value");
  4260. MVT InterVT = VT.changeVectorElementType(MVT::i8);
  4261. SplatVal = DAG.getNode(ISD::AND, DL, XLenVT, SplatVal,
  4262. DAG.getConstant(1, DL, XLenVT));
  4263. SDValue LHS = DAG.getSplatVector(InterVT, DL, SplatVal);
  4264. SDValue Zero = DAG.getConstant(0, DL, InterVT);
  4265. return DAG.getSetCC(DL, VT, LHS, Zero, ISD::SETNE);
  4266. }
  4267. // Custom-lower a SPLAT_VECTOR_PARTS where XLEN<SEW, as the SEW element type is
  4268. // illegal (currently only vXi64 RV32).
  4269. // FIXME: We could also catch non-constant sign-extended i32 values and lower
  4270. // them to VMV_V_X_VL.
  4271. SDValue RISCVTargetLowering::lowerSPLAT_VECTOR_PARTS(SDValue Op,
  4272. SelectionDAG &DAG) const {
  4273. SDLoc DL(Op);
  4274. MVT VecVT = Op.getSimpleValueType();
  4275. assert(!Subtarget.is64Bit() && VecVT.getVectorElementType() == MVT::i64 &&
  4276. "Unexpected SPLAT_VECTOR_PARTS lowering");
  4277. assert(Op.getNumOperands() == 2 && "Unexpected number of operands!");
  4278. SDValue Lo = Op.getOperand(0);
  4279. SDValue Hi = Op.getOperand(1);
  4280. if (VecVT.isFixedLengthVector()) {
  4281. MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
  4282. SDLoc DL(Op);
  4283. auto VL = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).second;
  4284. SDValue Res =
  4285. splatPartsI64WithVL(DL, ContainerVT, SDValue(), Lo, Hi, VL, DAG);
  4286. return convertFromScalableVector(VecVT, Res, DAG, Subtarget);
  4287. }
  4288. if (isa<ConstantSDNode>(Lo) && isa<ConstantSDNode>(Hi)) {
  4289. int32_t LoC = cast<ConstantSDNode>(Lo)->getSExtValue();
  4290. int32_t HiC = cast<ConstantSDNode>(Hi)->getSExtValue();
  4291. // If Hi constant is all the same sign bit as Lo, lower this as a custom
  4292. // node in order to try and match RVV vector/scalar instructions.
  4293. if ((LoC >> 31) == HiC)
  4294. return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
  4295. Lo, DAG.getRegister(RISCV::X0, MVT::i32));
  4296. }
  4297. // Detect cases where Hi is (SRA Lo, 31) which means Hi is Lo sign extended.
  4298. if (Hi.getOpcode() == ISD::SRA && Hi.getOperand(0) == Lo &&
  4299. isa<ConstantSDNode>(Hi.getOperand(1)) &&
  4300. Hi.getConstantOperandVal(1) == 31)
  4301. return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT), Lo,
  4302. DAG.getRegister(RISCV::X0, MVT::i32));
  4303. // Fall back to use a stack store and stride x0 vector load. Use X0 as VL.
  4304. return DAG.getNode(RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL, DL, VecVT,
  4305. DAG.getUNDEF(VecVT), Lo, Hi,
  4306. DAG.getRegister(RISCV::X0, MVT::i32));
  4307. }
  4308. // Custom-lower extensions from mask vectors by using a vselect either with 1
  4309. // for zero/any-extension or -1 for sign-extension:
  4310. // (vXiN = (s|z)ext vXi1:vmask) -> (vXiN = vselect vmask, (-1 or 1), 0)
  4311. // Note that any-extension is lowered identically to zero-extension.
  4312. SDValue RISCVTargetLowering::lowerVectorMaskExt(SDValue Op, SelectionDAG &DAG,
  4313. int64_t ExtTrueVal) const {
  4314. SDLoc DL(Op);
  4315. MVT VecVT = Op.getSimpleValueType();
  4316. SDValue Src = Op.getOperand(0);
  4317. // Only custom-lower extensions from mask types
  4318. assert(Src.getValueType().isVector() &&
  4319. Src.getValueType().getVectorElementType() == MVT::i1);
  4320. if (VecVT.isScalableVector()) {
  4321. SDValue SplatZero = DAG.getConstant(0, DL, VecVT);
  4322. SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, VecVT);
  4323. return DAG.getNode(ISD::VSELECT, DL, VecVT, Src, SplatTrueVal, SplatZero);
  4324. }
  4325. MVT ContainerVT = getContainerForFixedLengthVector(VecVT);
  4326. MVT I1ContainerVT =
  4327. MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
  4328. SDValue CC = convertToScalableVector(I1ContainerVT, Src, DAG, Subtarget);
  4329. SDValue VL = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).second;
  4330. MVT XLenVT = Subtarget.getXLenVT();
  4331. SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
  4332. SDValue SplatTrueVal = DAG.getConstant(ExtTrueVal, DL, XLenVT);
  4333. SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
  4334. DAG.getUNDEF(ContainerVT), SplatZero, VL);
  4335. SplatTrueVal = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
  4336. DAG.getUNDEF(ContainerVT), SplatTrueVal, VL);
  4337. SDValue Select = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC,
  4338. SplatTrueVal, SplatZero, VL);
  4339. return convertFromScalableVector(VecVT, Select, DAG, Subtarget);
  4340. }
  4341. SDValue RISCVTargetLowering::lowerFixedLengthVectorExtendToRVV(
  4342. SDValue Op, SelectionDAG &DAG, unsigned ExtendOpc) const {
  4343. MVT ExtVT = Op.getSimpleValueType();
  4344. // Only custom-lower extensions from fixed-length vector types.
  4345. if (!ExtVT.isFixedLengthVector())
  4346. return Op;
  4347. MVT VT = Op.getOperand(0).getSimpleValueType();
  4348. // Grab the canonical container type for the extended type. Infer the smaller
  4349. // type from that to ensure the same number of vector elements, as we know
  4350. // the LMUL will be sufficient to hold the smaller type.
  4351. MVT ContainerExtVT = getContainerForFixedLengthVector(ExtVT);
  4352. // Get the extended container type manually to ensure the same number of
  4353. // vector elements between source and dest.
  4354. MVT ContainerVT = MVT::getVectorVT(VT.getVectorElementType(),
  4355. ContainerExtVT.getVectorElementCount());
  4356. SDValue Op1 =
  4357. convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
  4358. SDLoc DL(Op);
  4359. auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
  4360. SDValue Ext = DAG.getNode(ExtendOpc, DL, ContainerExtVT, Op1, Mask, VL);
  4361. return convertFromScalableVector(ExtVT, Ext, DAG, Subtarget);
  4362. }
  4363. // Custom-lower truncations from vectors to mask vectors by using a mask and a
  4364. // setcc operation:
  4365. // (vXi1 = trunc vXiN vec) -> (vXi1 = setcc (and vec, 1), 0, ne)
  4366. SDValue RISCVTargetLowering::lowerVectorMaskTruncLike(SDValue Op,
  4367. SelectionDAG &DAG) const {
  4368. bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
  4369. SDLoc DL(Op);
  4370. EVT MaskVT = Op.getValueType();
  4371. // Only expect to custom-lower truncations to mask types
  4372. assert(MaskVT.isVector() && MaskVT.getVectorElementType() == MVT::i1 &&
  4373. "Unexpected type for vector mask lowering");
  4374. SDValue Src = Op.getOperand(0);
  4375. MVT VecVT = Src.getSimpleValueType();
  4376. SDValue Mask, VL;
  4377. if (IsVPTrunc) {
  4378. Mask = Op.getOperand(1);
  4379. VL = Op.getOperand(2);
  4380. }
  4381. // If this is a fixed vector, we need to convert it to a scalable vector.
  4382. MVT ContainerVT = VecVT;
  4383. if (VecVT.isFixedLengthVector()) {
  4384. ContainerVT = getContainerForFixedLengthVector(VecVT);
  4385. Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
  4386. if (IsVPTrunc) {
  4387. MVT MaskContainerVT =
  4388. getContainerForFixedLengthVector(Mask.getSimpleValueType());
  4389. Mask = convertToScalableVector(MaskContainerVT, Mask, DAG, Subtarget);
  4390. }
  4391. }
  4392. if (!IsVPTrunc) {
  4393. std::tie(Mask, VL) =
  4394. getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
  4395. }
  4396. SDValue SplatOne = DAG.getConstant(1, DL, Subtarget.getXLenVT());
  4397. SDValue SplatZero = DAG.getConstant(0, DL, Subtarget.getXLenVT());
  4398. SplatOne = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
  4399. DAG.getUNDEF(ContainerVT), SplatOne, VL);
  4400. SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
  4401. DAG.getUNDEF(ContainerVT), SplatZero, VL);
  4402. MVT MaskContainerVT = ContainerVT.changeVectorElementType(MVT::i1);
  4403. SDValue Trunc = DAG.getNode(RISCVISD::AND_VL, DL, ContainerVT, Src, SplatOne,
  4404. DAG.getUNDEF(ContainerVT), Mask, VL);
  4405. Trunc = DAG.getNode(RISCVISD::SETCC_VL, DL, MaskContainerVT,
  4406. {Trunc, SplatZero, DAG.getCondCode(ISD::SETNE),
  4407. DAG.getUNDEF(MaskContainerVT), Mask, VL});
  4408. if (MaskVT.isFixedLengthVector())
  4409. Trunc = convertFromScalableVector(MaskVT, Trunc, DAG, Subtarget);
  4410. return Trunc;
  4411. }
  4412. SDValue RISCVTargetLowering::lowerVectorTruncLike(SDValue Op,
  4413. SelectionDAG &DAG) const {
  4414. bool IsVPTrunc = Op.getOpcode() == ISD::VP_TRUNCATE;
  4415. SDLoc DL(Op);
  4416. MVT VT = Op.getSimpleValueType();
  4417. // Only custom-lower vector truncates
  4418. assert(VT.isVector() && "Unexpected type for vector truncate lowering");
  4419. // Truncates to mask types are handled differently
  4420. if (VT.getVectorElementType() == MVT::i1)
  4421. return lowerVectorMaskTruncLike(Op, DAG);
  4422. // RVV only has truncates which operate from SEW*2->SEW, so lower arbitrary
  4423. // truncates as a series of "RISCVISD::TRUNCATE_VECTOR_VL" nodes which
  4424. // truncate by one power of two at a time.
  4425. MVT DstEltVT = VT.getVectorElementType();
  4426. SDValue Src = Op.getOperand(0);
  4427. MVT SrcVT = Src.getSimpleValueType();
  4428. MVT SrcEltVT = SrcVT.getVectorElementType();
  4429. assert(DstEltVT.bitsLT(SrcEltVT) && isPowerOf2_64(DstEltVT.getSizeInBits()) &&
  4430. isPowerOf2_64(SrcEltVT.getSizeInBits()) &&
  4431. "Unexpected vector truncate lowering");
  4432. MVT ContainerVT = SrcVT;
  4433. SDValue Mask, VL;
  4434. if (IsVPTrunc) {
  4435. Mask = Op.getOperand(1);
  4436. VL = Op.getOperand(2);
  4437. }
  4438. if (SrcVT.isFixedLengthVector()) {
  4439. ContainerVT = getContainerForFixedLengthVector(SrcVT);
  4440. Src = convertToScalableVector(ContainerVT, Src, DAG, Subtarget);
  4441. if (IsVPTrunc) {
  4442. MVT MaskVT = getMaskTypeFor(ContainerVT);
  4443. Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
  4444. }
  4445. }
  4446. SDValue Result = Src;
  4447. if (!IsVPTrunc) {
  4448. std::tie(Mask, VL) =
  4449. getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
  4450. }
  4451. LLVMContext &Context = *DAG.getContext();
  4452. const ElementCount Count = ContainerVT.getVectorElementCount();
  4453. do {
  4454. SrcEltVT = MVT::getIntegerVT(SrcEltVT.getSizeInBits() / 2);
  4455. EVT ResultVT = EVT::getVectorVT(Context, SrcEltVT, Count);
  4456. Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, ResultVT, Result,
  4457. Mask, VL);
  4458. } while (SrcEltVT != DstEltVT);
  4459. if (SrcVT.isFixedLengthVector())
  4460. Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
  4461. return Result;
  4462. }
  4463. SDValue
  4464. RISCVTargetLowering::lowerVectorFPExtendOrRoundLike(SDValue Op,
  4465. SelectionDAG &DAG) const {
  4466. bool IsVP =
  4467. Op.getOpcode() == ISD::VP_FP_ROUND || Op.getOpcode() == ISD::VP_FP_EXTEND;
  4468. bool IsExtend =
  4469. Op.getOpcode() == ISD::VP_FP_EXTEND || Op.getOpcode() == ISD::FP_EXTEND;
  4470. // RVV can only do truncate fp to types half the size as the source. We
  4471. // custom-lower f64->f16 rounds via RVV's round-to-odd float
  4472. // conversion instruction.
  4473. SDLoc DL(Op);
  4474. MVT VT = Op.getSimpleValueType();
  4475. assert(VT.isVector() && "Unexpected type for vector truncate lowering");
  4476. SDValue Src = Op.getOperand(0);
  4477. MVT SrcVT = Src.getSimpleValueType();
  4478. bool IsDirectExtend = IsExtend && (VT.getVectorElementType() != MVT::f64 ||
  4479. SrcVT.getVectorElementType() != MVT::f16);
  4480. bool IsDirectTrunc = !IsExtend && (VT.getVectorElementType() != MVT::f16 ||
  4481. SrcVT.getVectorElementType() != MVT::f64);
  4482. bool IsDirectConv = IsDirectExtend || IsDirectTrunc;
  4483. // Prepare any fixed-length vector operands.
  4484. MVT ContainerVT = VT;
  4485. SDValue Mask, VL;
  4486. if (IsVP) {
  4487. Mask = Op.getOperand(1);
  4488. VL = Op.getOperand(2);
  4489. }
  4490. if (VT.isFixedLengthVector()) {
  4491. MVT SrcContainerVT = getContainerForFixedLengthVector(SrcVT);
  4492. ContainerVT =
  4493. SrcContainerVT.changeVectorElementType(VT.getVectorElementType());
  4494. Src = convertToScalableVector(SrcContainerVT, Src, DAG, Subtarget);
  4495. if (IsVP) {
  4496. MVT MaskVT = getMaskTypeFor(ContainerVT);
  4497. Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
  4498. }
  4499. }
  4500. if (!IsVP)
  4501. std::tie(Mask, VL) =
  4502. getDefaultVLOps(SrcVT, ContainerVT, DL, DAG, Subtarget);
  4503. unsigned ConvOpc = IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::FP_ROUND_VL;
  4504. if (IsDirectConv) {
  4505. Src = DAG.getNode(ConvOpc, DL, ContainerVT, Src, Mask, VL);
  4506. if (VT.isFixedLengthVector())
  4507. Src = convertFromScalableVector(VT, Src, DAG, Subtarget);
  4508. return Src;
  4509. }
  4510. unsigned InterConvOpc =
  4511. IsExtend ? RISCVISD::FP_EXTEND_VL : RISCVISD::VFNCVT_ROD_VL;
  4512. MVT InterVT = ContainerVT.changeVectorElementType(MVT::f32);
  4513. SDValue IntermediateConv =
  4514. DAG.getNode(InterConvOpc, DL, InterVT, Src, Mask, VL);
  4515. SDValue Result =
  4516. DAG.getNode(ConvOpc, DL, ContainerVT, IntermediateConv, Mask, VL);
  4517. if (VT.isFixedLengthVector())
  4518. return convertFromScalableVector(VT, Result, DAG, Subtarget);
  4519. return Result;
  4520. }
  4521. // Custom-legalize INSERT_VECTOR_ELT so that the value is inserted into the
  4522. // first position of a vector, and that vector is slid up to the insert index.
  4523. // By limiting the active vector length to index+1 and merging with the
  4524. // original vector (with an undisturbed tail policy for elements >= VL), we
  4525. // achieve the desired result of leaving all elements untouched except the one
  4526. // at VL-1, which is replaced with the desired value.
  4527. SDValue RISCVTargetLowering::lowerINSERT_VECTOR_ELT(SDValue Op,
  4528. SelectionDAG &DAG) const {
  4529. SDLoc DL(Op);
  4530. MVT VecVT = Op.getSimpleValueType();
  4531. SDValue Vec = Op.getOperand(0);
  4532. SDValue Val = Op.getOperand(1);
  4533. SDValue Idx = Op.getOperand(2);
  4534. if (VecVT.getVectorElementType() == MVT::i1) {
  4535. // FIXME: For now we just promote to an i8 vector and insert into that,
  4536. // but this is probably not optimal.
  4537. MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
  4538. Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
  4539. Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideVT, Vec, Val, Idx);
  4540. return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Vec);
  4541. }
  4542. MVT ContainerVT = VecVT;
  4543. // If the operand is a fixed-length vector, convert to a scalable one.
  4544. if (VecVT.isFixedLengthVector()) {
  4545. ContainerVT = getContainerForFixedLengthVector(VecVT);
  4546. Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
  4547. }
  4548. MVT XLenVT = Subtarget.getXLenVT();
  4549. SDValue Zero = DAG.getConstant(0, DL, XLenVT);
  4550. bool IsLegalInsert = Subtarget.is64Bit() || Val.getValueType() != MVT::i64;
  4551. // Even i64-element vectors on RV32 can be lowered without scalar
  4552. // legalization if the most-significant 32 bits of the value are not affected
  4553. // by the sign-extension of the lower 32 bits.
  4554. // TODO: We could also catch sign extensions of a 32-bit value.
  4555. if (!IsLegalInsert && isa<ConstantSDNode>(Val)) {
  4556. const auto *CVal = cast<ConstantSDNode>(Val);
  4557. if (isInt<32>(CVal->getSExtValue())) {
  4558. IsLegalInsert = true;
  4559. Val = DAG.getConstant(CVal->getSExtValue(), DL, MVT::i32);
  4560. }
  4561. }
  4562. auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
  4563. SDValue ValInVec;
  4564. if (IsLegalInsert) {
  4565. unsigned Opc =
  4566. VecVT.isFloatingPoint() ? RISCVISD::VFMV_S_F_VL : RISCVISD::VMV_S_X_VL;
  4567. if (isNullConstant(Idx)) {
  4568. Vec = DAG.getNode(Opc, DL, ContainerVT, Vec, Val, VL);
  4569. if (!VecVT.isFixedLengthVector())
  4570. return Vec;
  4571. return convertFromScalableVector(VecVT, Vec, DAG, Subtarget);
  4572. }
  4573. ValInVec = lowerScalarInsert(Val, VL, ContainerVT, DL, DAG, Subtarget);
  4574. } else {
  4575. // On RV32, i64-element vectors must be specially handled to place the
  4576. // value at element 0, by using two vslide1down instructions in sequence on
  4577. // the i32 split lo/hi value. Use an equivalently-sized i32 vector for
  4578. // this.
  4579. SDValue One = DAG.getConstant(1, DL, XLenVT);
  4580. SDValue ValLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, Zero);
  4581. SDValue ValHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, Val, One);
  4582. MVT I32ContainerVT =
  4583. MVT::getVectorVT(MVT::i32, ContainerVT.getVectorElementCount() * 2);
  4584. SDValue I32Mask =
  4585. getDefaultScalableVLOps(I32ContainerVT, DL, DAG, Subtarget).first;
  4586. // Limit the active VL to two.
  4587. SDValue InsertI64VL = DAG.getConstant(2, DL, XLenVT);
  4588. // If the Idx is 0 we can insert directly into the vector.
  4589. if (isNullConstant(Idx)) {
  4590. // First slide in the lo value, then the hi in above it. We use slide1down
  4591. // to avoid the register group overlap constraint of vslide1up.
  4592. ValInVec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32ContainerVT,
  4593. Vec, Vec, ValLo, I32Mask, InsertI64VL);
  4594. // If the source vector is undef don't pass along the tail elements from
  4595. // the previous slide1down.
  4596. SDValue Tail = Vec.isUndef() ? Vec : ValInVec;
  4597. ValInVec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32ContainerVT,
  4598. Tail, ValInVec, ValHi, I32Mask, InsertI64VL);
  4599. // Bitcast back to the right container type.
  4600. ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
  4601. if (!VecVT.isFixedLengthVector())
  4602. return ValInVec;
  4603. return convertFromScalableVector(VecVT, ValInVec, DAG, Subtarget);
  4604. }
  4605. // First slide in the lo value, then the hi in above it. We use slide1down
  4606. // to avoid the register group overlap constraint of vslide1up.
  4607. ValInVec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32ContainerVT,
  4608. DAG.getUNDEF(I32ContainerVT),
  4609. DAG.getUNDEF(I32ContainerVT), ValLo,
  4610. I32Mask, InsertI64VL);
  4611. ValInVec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32ContainerVT,
  4612. DAG.getUNDEF(I32ContainerVT), ValInVec, ValHi,
  4613. I32Mask, InsertI64VL);
  4614. // Bitcast back to the right container type.
  4615. ValInVec = DAG.getBitcast(ContainerVT, ValInVec);
  4616. }
  4617. // Now that the value is in a vector, slide it into position.
  4618. SDValue InsertVL =
  4619. DAG.getNode(ISD::ADD, DL, XLenVT, Idx, DAG.getConstant(1, DL, XLenVT));
  4620. // Use tail agnostic policy if Idx is the last index of Vec.
  4621. unsigned Policy = RISCVII::TAIL_UNDISTURBED_MASK_UNDISTURBED;
  4622. if (VecVT.isFixedLengthVector() && isa<ConstantSDNode>(Idx) &&
  4623. cast<ConstantSDNode>(Idx)->getZExtValue() + 1 ==
  4624. VecVT.getVectorNumElements())
  4625. Policy = RISCVII::TAIL_AGNOSTIC;
  4626. SDValue Slideup = getVSlideup(DAG, Subtarget, DL, ContainerVT, Vec, ValInVec,
  4627. Idx, Mask, InsertVL, Policy);
  4628. if (!VecVT.isFixedLengthVector())
  4629. return Slideup;
  4630. return convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
  4631. }
  4632. // Custom-lower EXTRACT_VECTOR_ELT operations to slide the vector down, then
  4633. // extract the first element: (extractelt (slidedown vec, idx), 0). For integer
  4634. // types this is done using VMV_X_S to allow us to glean information about the
  4635. // sign bits of the result.
  4636. SDValue RISCVTargetLowering::lowerEXTRACT_VECTOR_ELT(SDValue Op,
  4637. SelectionDAG &DAG) const {
  4638. SDLoc DL(Op);
  4639. SDValue Idx = Op.getOperand(1);
  4640. SDValue Vec = Op.getOperand(0);
  4641. EVT EltVT = Op.getValueType();
  4642. MVT VecVT = Vec.getSimpleValueType();
  4643. MVT XLenVT = Subtarget.getXLenVT();
  4644. if (VecVT.getVectorElementType() == MVT::i1) {
  4645. // Use vfirst.m to extract the first bit.
  4646. if (isNullConstant(Idx)) {
  4647. MVT ContainerVT = VecVT;
  4648. if (VecVT.isFixedLengthVector()) {
  4649. ContainerVT = getContainerForFixedLengthVector(VecVT);
  4650. Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
  4651. }
  4652. auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
  4653. SDValue Vfirst =
  4654. DAG.getNode(RISCVISD::VFIRST_VL, DL, XLenVT, Vec, Mask, VL);
  4655. return DAG.getSetCC(DL, XLenVT, Vfirst, DAG.getConstant(0, DL, XLenVT),
  4656. ISD::SETEQ);
  4657. }
  4658. if (VecVT.isFixedLengthVector()) {
  4659. unsigned NumElts = VecVT.getVectorNumElements();
  4660. if (NumElts >= 8) {
  4661. MVT WideEltVT;
  4662. unsigned WidenVecLen;
  4663. SDValue ExtractElementIdx;
  4664. SDValue ExtractBitIdx;
  4665. unsigned MaxEEW = Subtarget.getELEN();
  4666. MVT LargestEltVT = MVT::getIntegerVT(
  4667. std::min(MaxEEW, unsigned(XLenVT.getSizeInBits())));
  4668. if (NumElts <= LargestEltVT.getSizeInBits()) {
  4669. assert(isPowerOf2_32(NumElts) &&
  4670. "the number of elements should be power of 2");
  4671. WideEltVT = MVT::getIntegerVT(NumElts);
  4672. WidenVecLen = 1;
  4673. ExtractElementIdx = DAG.getConstant(0, DL, XLenVT);
  4674. ExtractBitIdx = Idx;
  4675. } else {
  4676. WideEltVT = LargestEltVT;
  4677. WidenVecLen = NumElts / WideEltVT.getSizeInBits();
  4678. // extract element index = index / element width
  4679. ExtractElementIdx = DAG.getNode(
  4680. ISD::SRL, DL, XLenVT, Idx,
  4681. DAG.getConstant(Log2_64(WideEltVT.getSizeInBits()), DL, XLenVT));
  4682. // mask bit index = index % element width
  4683. ExtractBitIdx = DAG.getNode(
  4684. ISD::AND, DL, XLenVT, Idx,
  4685. DAG.getConstant(WideEltVT.getSizeInBits() - 1, DL, XLenVT));
  4686. }
  4687. MVT WideVT = MVT::getVectorVT(WideEltVT, WidenVecLen);
  4688. Vec = DAG.getNode(ISD::BITCAST, DL, WideVT, Vec);
  4689. SDValue ExtractElt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, XLenVT,
  4690. Vec, ExtractElementIdx);
  4691. // Extract the bit from GPR.
  4692. SDValue ShiftRight =
  4693. DAG.getNode(ISD::SRL, DL, XLenVT, ExtractElt, ExtractBitIdx);
  4694. return DAG.getNode(ISD::AND, DL, XLenVT, ShiftRight,
  4695. DAG.getConstant(1, DL, XLenVT));
  4696. }
  4697. }
  4698. // Otherwise, promote to an i8 vector and extract from that.
  4699. MVT WideVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
  4700. Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, WideVT, Vec);
  4701. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec, Idx);
  4702. }
  4703. // If this is a fixed vector, we need to convert it to a scalable vector.
  4704. MVT ContainerVT = VecVT;
  4705. if (VecVT.isFixedLengthVector()) {
  4706. ContainerVT = getContainerForFixedLengthVector(VecVT);
  4707. Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
  4708. }
  4709. // If the index is 0, the vector is already in the right position.
  4710. if (!isNullConstant(Idx)) {
  4711. // Use a VL of 1 to avoid processing more elements than we need.
  4712. auto [Mask, VL] = getDefaultVLOps(1, ContainerVT, DL, DAG, Subtarget);
  4713. Vec = getVSlidedown(DAG, Subtarget, DL, ContainerVT,
  4714. DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
  4715. }
  4716. if (!EltVT.isInteger()) {
  4717. // Floating-point extracts are handled in TableGen.
  4718. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Vec,
  4719. DAG.getConstant(0, DL, XLenVT));
  4720. }
  4721. SDValue Elt0 = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
  4722. return DAG.getNode(ISD::TRUNCATE, DL, EltVT, Elt0);
  4723. }
  4724. // Some RVV intrinsics may claim that they want an integer operand to be
  4725. // promoted or expanded.
  4726. static SDValue lowerVectorIntrinsicScalars(SDValue Op, SelectionDAG &DAG,
  4727. const RISCVSubtarget &Subtarget) {
  4728. assert((Op.getOpcode() == ISD::INTRINSIC_WO_CHAIN ||
  4729. Op.getOpcode() == ISD::INTRINSIC_W_CHAIN) &&
  4730. "Unexpected opcode");
  4731. if (!Subtarget.hasVInstructions())
  4732. return SDValue();
  4733. bool HasChain = Op.getOpcode() == ISD::INTRINSIC_W_CHAIN;
  4734. unsigned IntNo = Op.getConstantOperandVal(HasChain ? 1 : 0);
  4735. SDLoc DL(Op);
  4736. const RISCVVIntrinsicsTable::RISCVVIntrinsicInfo *II =
  4737. RISCVVIntrinsicsTable::getRISCVVIntrinsicInfo(IntNo);
  4738. if (!II || !II->hasScalarOperand())
  4739. return SDValue();
  4740. unsigned SplatOp = II->ScalarOperand + 1 + HasChain;
  4741. assert(SplatOp < Op.getNumOperands());
  4742. SmallVector<SDValue, 8> Operands(Op->op_begin(), Op->op_end());
  4743. SDValue &ScalarOp = Operands[SplatOp];
  4744. MVT OpVT = ScalarOp.getSimpleValueType();
  4745. MVT XLenVT = Subtarget.getXLenVT();
  4746. // If this isn't a scalar, or its type is XLenVT we're done.
  4747. if (!OpVT.isScalarInteger() || OpVT == XLenVT)
  4748. return SDValue();
  4749. // Simplest case is that the operand needs to be promoted to XLenVT.
  4750. if (OpVT.bitsLT(XLenVT)) {
  4751. // If the operand is a constant, sign extend to increase our chances
  4752. // of being able to use a .vi instruction. ANY_EXTEND would become a
  4753. // a zero extend and the simm5 check in isel would fail.
  4754. // FIXME: Should we ignore the upper bits in isel instead?
  4755. unsigned ExtOpc =
  4756. isa<ConstantSDNode>(ScalarOp) ? ISD::SIGN_EXTEND : ISD::ANY_EXTEND;
  4757. ScalarOp = DAG.getNode(ExtOpc, DL, XLenVT, ScalarOp);
  4758. return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
  4759. }
  4760. // Use the previous operand to get the vXi64 VT. The result might be a mask
  4761. // VT for compares. Using the previous operand assumes that the previous
  4762. // operand will never have a smaller element size than a scalar operand and
  4763. // that a widening operation never uses SEW=64.
  4764. // NOTE: If this fails the below assert, we can probably just find the
  4765. // element count from any operand or result and use it to construct the VT.
  4766. assert(II->ScalarOperand > 0 && "Unexpected splat operand!");
  4767. MVT VT = Op.getOperand(SplatOp - 1).getSimpleValueType();
  4768. // The more complex case is when the scalar is larger than XLenVT.
  4769. assert(XLenVT == MVT::i32 && OpVT == MVT::i64 &&
  4770. VT.getVectorElementType() == MVT::i64 && "Unexpected VTs!");
  4771. // If this is a sign-extended 32-bit value, we can truncate it and rely on the
  4772. // instruction to sign-extend since SEW>XLEN.
  4773. if (DAG.ComputeNumSignBits(ScalarOp) > 32) {
  4774. ScalarOp = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, ScalarOp);
  4775. return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
  4776. }
  4777. switch (IntNo) {
  4778. case Intrinsic::riscv_vslide1up:
  4779. case Intrinsic::riscv_vslide1down:
  4780. case Intrinsic::riscv_vslide1up_mask:
  4781. case Intrinsic::riscv_vslide1down_mask: {
  4782. // We need to special case these when the scalar is larger than XLen.
  4783. unsigned NumOps = Op.getNumOperands();
  4784. bool IsMasked = NumOps == 7;
  4785. // Convert the vector source to the equivalent nxvXi32 vector.
  4786. MVT I32VT = MVT::getVectorVT(MVT::i32, VT.getVectorElementCount() * 2);
  4787. SDValue Vec = DAG.getBitcast(I32VT, Operands[2]);
  4788. SDValue ScalarLo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
  4789. DAG.getConstant(0, DL, XLenVT));
  4790. SDValue ScalarHi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i32, ScalarOp,
  4791. DAG.getConstant(1, DL, XLenVT));
  4792. // Double the VL since we halved SEW.
  4793. SDValue AVL = getVLOperand(Op);
  4794. SDValue I32VL;
  4795. // Optimize for constant AVL
  4796. if (isa<ConstantSDNode>(AVL)) {
  4797. unsigned EltSize = VT.getScalarSizeInBits();
  4798. unsigned MinSize = VT.getSizeInBits().getKnownMinValue();
  4799. unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
  4800. unsigned MaxVLMAX =
  4801. RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
  4802. unsigned VectorBitsMin = Subtarget.getRealMinVLen();
  4803. unsigned MinVLMAX =
  4804. RISCVTargetLowering::computeVLMAX(VectorBitsMin, EltSize, MinSize);
  4805. uint64_t AVLInt = cast<ConstantSDNode>(AVL)->getZExtValue();
  4806. if (AVLInt <= MinVLMAX) {
  4807. I32VL = DAG.getConstant(2 * AVLInt, DL, XLenVT);
  4808. } else if (AVLInt >= 2 * MaxVLMAX) {
  4809. // Just set vl to VLMAX in this situation
  4810. RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(I32VT);
  4811. SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
  4812. unsigned Sew = RISCVVType::encodeSEW(I32VT.getScalarSizeInBits());
  4813. SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
  4814. SDValue SETVLMAX = DAG.getTargetConstant(
  4815. Intrinsic::riscv_vsetvlimax_opt, DL, MVT::i32);
  4816. I32VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVLMAX, SEW,
  4817. LMUL);
  4818. } else {
  4819. // For AVL between (MinVLMAX, 2 * MaxVLMAX), the actual working vl
  4820. // is related to the hardware implementation.
  4821. // So let the following code handle
  4822. }
  4823. }
  4824. if (!I32VL) {
  4825. RISCVII::VLMUL Lmul = RISCVTargetLowering::getLMUL(VT);
  4826. SDValue LMUL = DAG.getConstant(Lmul, DL, XLenVT);
  4827. unsigned Sew = RISCVVType::encodeSEW(VT.getScalarSizeInBits());
  4828. SDValue SEW = DAG.getConstant(Sew, DL, XLenVT);
  4829. SDValue SETVL =
  4830. DAG.getTargetConstant(Intrinsic::riscv_vsetvli_opt, DL, MVT::i32);
  4831. // Using vsetvli instruction to get actually used length which related to
  4832. // the hardware implementation
  4833. SDValue VL = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, XLenVT, SETVL, AVL,
  4834. SEW, LMUL);
  4835. I32VL =
  4836. DAG.getNode(ISD::SHL, DL, XLenVT, VL, DAG.getConstant(1, DL, XLenVT));
  4837. }
  4838. SDValue I32Mask = getAllOnesMask(I32VT, I32VL, DL, DAG);
  4839. // Shift the two scalar parts in using SEW=32 slide1up/slide1down
  4840. // instructions.
  4841. SDValue Passthru;
  4842. if (IsMasked)
  4843. Passthru = DAG.getUNDEF(I32VT);
  4844. else
  4845. Passthru = DAG.getBitcast(I32VT, Operands[1]);
  4846. if (IntNo == Intrinsic::riscv_vslide1up ||
  4847. IntNo == Intrinsic::riscv_vslide1up_mask) {
  4848. Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
  4849. ScalarHi, I32Mask, I32VL);
  4850. Vec = DAG.getNode(RISCVISD::VSLIDE1UP_VL, DL, I32VT, Passthru, Vec,
  4851. ScalarLo, I32Mask, I32VL);
  4852. } else {
  4853. Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
  4854. ScalarLo, I32Mask, I32VL);
  4855. Vec = DAG.getNode(RISCVISD::VSLIDE1DOWN_VL, DL, I32VT, Passthru, Vec,
  4856. ScalarHi, I32Mask, I32VL);
  4857. }
  4858. // Convert back to nxvXi64.
  4859. Vec = DAG.getBitcast(VT, Vec);
  4860. if (!IsMasked)
  4861. return Vec;
  4862. // Apply mask after the operation.
  4863. SDValue Mask = Operands[NumOps - 3];
  4864. SDValue MaskedOff = Operands[1];
  4865. // Assume Policy operand is the last operand.
  4866. uint64_t Policy =
  4867. cast<ConstantSDNode>(Operands[NumOps - 1])->getZExtValue();
  4868. // We don't need to select maskedoff if it's undef.
  4869. if (MaskedOff.isUndef())
  4870. return Vec;
  4871. // TAMU
  4872. if (Policy == RISCVII::TAIL_AGNOSTIC)
  4873. return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, Mask, Vec, MaskedOff,
  4874. AVL);
  4875. // TUMA or TUMU: Currently we always emit tumu policy regardless of tuma.
  4876. // It's fine because vmerge does not care mask policy.
  4877. return DAG.getNode(RISCVISD::VP_MERGE_VL, DL, VT, Mask, Vec, MaskedOff,
  4878. AVL);
  4879. }
  4880. }
  4881. // We need to convert the scalar to a splat vector.
  4882. SDValue VL = getVLOperand(Op);
  4883. assert(VL.getValueType() == XLenVT);
  4884. ScalarOp = splatSplitI64WithVL(DL, VT, SDValue(), ScalarOp, VL, DAG);
  4885. return DAG.getNode(Op->getOpcode(), DL, Op->getVTList(), Operands);
  4886. }
  4887. SDValue RISCVTargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
  4888. SelectionDAG &DAG) const {
  4889. unsigned IntNo = Op.getConstantOperandVal(0);
  4890. SDLoc DL(Op);
  4891. MVT XLenVT = Subtarget.getXLenVT();
  4892. switch (IntNo) {
  4893. default:
  4894. break; // Don't custom lower most intrinsics.
  4895. case Intrinsic::thread_pointer: {
  4896. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  4897. return DAG.getRegister(RISCV::X4, PtrVT);
  4898. }
  4899. case Intrinsic::riscv_orc_b:
  4900. case Intrinsic::riscv_brev8: {
  4901. unsigned Opc =
  4902. IntNo == Intrinsic::riscv_brev8 ? RISCVISD::BREV8 : RISCVISD::ORC_B;
  4903. return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1));
  4904. }
  4905. case Intrinsic::riscv_zip:
  4906. case Intrinsic::riscv_unzip: {
  4907. unsigned Opc =
  4908. IntNo == Intrinsic::riscv_zip ? RISCVISD::ZIP : RISCVISD::UNZIP;
  4909. return DAG.getNode(Opc, DL, XLenVT, Op.getOperand(1));
  4910. }
  4911. case Intrinsic::riscv_vmv_x_s:
  4912. assert(Op.getValueType() == XLenVT && "Unexpected VT!");
  4913. return DAG.getNode(RISCVISD::VMV_X_S, DL, Op.getValueType(),
  4914. Op.getOperand(1));
  4915. case Intrinsic::riscv_vfmv_f_s:
  4916. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, Op.getValueType(),
  4917. Op.getOperand(1), DAG.getConstant(0, DL, XLenVT));
  4918. case Intrinsic::riscv_vmv_v_x:
  4919. return lowerScalarSplat(Op.getOperand(1), Op.getOperand(2),
  4920. Op.getOperand(3), Op.getSimpleValueType(), DL, DAG,
  4921. Subtarget);
  4922. case Intrinsic::riscv_vfmv_v_f:
  4923. return DAG.getNode(RISCVISD::VFMV_V_F_VL, DL, Op.getValueType(),
  4924. Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
  4925. case Intrinsic::riscv_vmv_s_x: {
  4926. SDValue Scalar = Op.getOperand(2);
  4927. if (Scalar.getValueType().bitsLE(XLenVT)) {
  4928. Scalar = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, Scalar);
  4929. return DAG.getNode(RISCVISD::VMV_S_X_VL, DL, Op.getValueType(),
  4930. Op.getOperand(1), Scalar, Op.getOperand(3));
  4931. }
  4932. assert(Scalar.getValueType() == MVT::i64 && "Unexpected scalar VT!");
  4933. // This is an i64 value that lives in two scalar registers. We have to
  4934. // insert this in a convoluted way. First we build vXi64 splat containing
  4935. // the two values that we assemble using some bit math. Next we'll use
  4936. // vid.v and vmseq to build a mask with bit 0 set. Then we'll use that mask
  4937. // to merge element 0 from our splat into the source vector.
  4938. // FIXME: This is probably not the best way to do this, but it is
  4939. // consistent with INSERT_VECTOR_ELT lowering so it is a good starting
  4940. // point.
  4941. // sw lo, (a0)
  4942. // sw hi, 4(a0)
  4943. // vlse vX, (a0)
  4944. //
  4945. // vid.v vVid
  4946. // vmseq.vx mMask, vVid, 0
  4947. // vmerge.vvm vDest, vSrc, vVal, mMask
  4948. MVT VT = Op.getSimpleValueType();
  4949. SDValue Vec = Op.getOperand(1);
  4950. SDValue VL = getVLOperand(Op);
  4951. SDValue SplattedVal = splatSplitI64WithVL(DL, VT, SDValue(), Scalar, VL, DAG);
  4952. if (Op.getOperand(1).isUndef())
  4953. return SplattedVal;
  4954. SDValue SplattedIdx =
  4955. DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
  4956. DAG.getConstant(0, DL, MVT::i32), VL);
  4957. MVT MaskVT = getMaskTypeFor(VT);
  4958. SDValue Mask = getAllOnesMask(VT, VL, DL, DAG);
  4959. SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
  4960. SDValue SelectCond =
  4961. DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT,
  4962. {VID, SplattedIdx, DAG.getCondCode(ISD::SETEQ),
  4963. DAG.getUNDEF(MaskVT), Mask, VL});
  4964. return DAG.getNode(RISCVISD::VSELECT_VL, DL, VT, SelectCond, SplattedVal,
  4965. Vec, VL);
  4966. }
  4967. }
  4968. return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
  4969. }
  4970. SDValue RISCVTargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
  4971. SelectionDAG &DAG) const {
  4972. unsigned IntNo = Op.getConstantOperandVal(1);
  4973. switch (IntNo) {
  4974. default:
  4975. break;
  4976. case Intrinsic::riscv_masked_strided_load: {
  4977. SDLoc DL(Op);
  4978. MVT XLenVT = Subtarget.getXLenVT();
  4979. // If the mask is known to be all ones, optimize to an unmasked intrinsic;
  4980. // the selection of the masked intrinsics doesn't do this for us.
  4981. SDValue Mask = Op.getOperand(5);
  4982. bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
  4983. MVT VT = Op->getSimpleValueType(0);
  4984. MVT ContainerVT = VT;
  4985. if (VT.isFixedLengthVector())
  4986. ContainerVT = getContainerForFixedLengthVector(VT);
  4987. SDValue PassThru = Op.getOperand(2);
  4988. if (!IsUnmasked) {
  4989. MVT MaskVT = getMaskTypeFor(ContainerVT);
  4990. if (VT.isFixedLengthVector()) {
  4991. Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
  4992. PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
  4993. }
  4994. }
  4995. auto *Load = cast<MemIntrinsicSDNode>(Op);
  4996. SDValue VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
  4997. SDValue Ptr = Op.getOperand(3);
  4998. SDValue Stride = Op.getOperand(4);
  4999. SDValue Result, Chain;
  5000. // TODO: We restrict this to unmasked loads currently in consideration of
  5001. // the complexity of hanlding all falses masks.
  5002. if (IsUnmasked && isNullConstant(Stride)) {
  5003. MVT ScalarVT = ContainerVT.getVectorElementType();
  5004. SDValue ScalarLoad =
  5005. DAG.getExtLoad(ISD::ZEXTLOAD, DL, XLenVT, Load->getChain(), Ptr,
  5006. ScalarVT, Load->getMemOperand());
  5007. Chain = ScalarLoad.getValue(1);
  5008. Result = lowerScalarSplat(SDValue(), ScalarLoad, VL, ContainerVT, DL, DAG,
  5009. Subtarget);
  5010. } else {
  5011. SDValue IntID = DAG.getTargetConstant(
  5012. IsUnmasked ? Intrinsic::riscv_vlse : Intrinsic::riscv_vlse_mask, DL,
  5013. XLenVT);
  5014. SmallVector<SDValue, 8> Ops{Load->getChain(), IntID};
  5015. if (IsUnmasked)
  5016. Ops.push_back(DAG.getUNDEF(ContainerVT));
  5017. else
  5018. Ops.push_back(PassThru);
  5019. Ops.push_back(Ptr);
  5020. Ops.push_back(Stride);
  5021. if (!IsUnmasked)
  5022. Ops.push_back(Mask);
  5023. Ops.push_back(VL);
  5024. if (!IsUnmasked) {
  5025. SDValue Policy =
  5026. DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
  5027. Ops.push_back(Policy);
  5028. }
  5029. SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
  5030. Result =
  5031. DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
  5032. Load->getMemoryVT(), Load->getMemOperand());
  5033. Chain = Result.getValue(1);
  5034. }
  5035. if (VT.isFixedLengthVector())
  5036. Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
  5037. return DAG.getMergeValues({Result, Chain}, DL);
  5038. }
  5039. case Intrinsic::riscv_seg2_load:
  5040. case Intrinsic::riscv_seg3_load:
  5041. case Intrinsic::riscv_seg4_load:
  5042. case Intrinsic::riscv_seg5_load:
  5043. case Intrinsic::riscv_seg6_load:
  5044. case Intrinsic::riscv_seg7_load:
  5045. case Intrinsic::riscv_seg8_load: {
  5046. SDLoc DL(Op);
  5047. static const Intrinsic::ID VlsegInts[7] = {
  5048. Intrinsic::riscv_vlseg2, Intrinsic::riscv_vlseg3,
  5049. Intrinsic::riscv_vlseg4, Intrinsic::riscv_vlseg5,
  5050. Intrinsic::riscv_vlseg6, Intrinsic::riscv_vlseg7,
  5051. Intrinsic::riscv_vlseg8};
  5052. unsigned NF = Op->getNumValues() - 1;
  5053. assert(NF >= 2 && NF <= 8 && "Unexpected seg number");
  5054. MVT XLenVT = Subtarget.getXLenVT();
  5055. MVT VT = Op->getSimpleValueType(0);
  5056. MVT ContainerVT = getContainerForFixedLengthVector(VT);
  5057. SDValue VL = getVLOp(VT.getVectorNumElements(), DL, DAG, Subtarget);
  5058. SDValue IntID = DAG.getTargetConstant(VlsegInts[NF - 2], DL, XLenVT);
  5059. auto *Load = cast<MemIntrinsicSDNode>(Op);
  5060. SmallVector<EVT, 9> ContainerVTs(NF, ContainerVT);
  5061. ContainerVTs.push_back(MVT::Other);
  5062. SDVTList VTs = DAG.getVTList(ContainerVTs);
  5063. SmallVector<SDValue, 12> Ops = {Load->getChain(), IntID};
  5064. Ops.insert(Ops.end(), NF, DAG.getUNDEF(ContainerVT));
  5065. Ops.push_back(Op.getOperand(2));
  5066. Ops.push_back(VL);
  5067. SDValue Result =
  5068. DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
  5069. Load->getMemoryVT(), Load->getMemOperand());
  5070. SmallVector<SDValue, 9> Results;
  5071. for (unsigned int RetIdx = 0; RetIdx < NF; RetIdx++)
  5072. Results.push_back(convertFromScalableVector(VT, Result.getValue(RetIdx),
  5073. DAG, Subtarget));
  5074. Results.push_back(Result.getValue(NF));
  5075. return DAG.getMergeValues(Results, DL);
  5076. }
  5077. }
  5078. return lowerVectorIntrinsicScalars(Op, DAG, Subtarget);
  5079. }
  5080. SDValue RISCVTargetLowering::LowerINTRINSIC_VOID(SDValue Op,
  5081. SelectionDAG &DAG) const {
  5082. unsigned IntNo = Op.getConstantOperandVal(1);
  5083. switch (IntNo) {
  5084. default:
  5085. break;
  5086. case Intrinsic::riscv_masked_strided_store: {
  5087. SDLoc DL(Op);
  5088. MVT XLenVT = Subtarget.getXLenVT();
  5089. // If the mask is known to be all ones, optimize to an unmasked intrinsic;
  5090. // the selection of the masked intrinsics doesn't do this for us.
  5091. SDValue Mask = Op.getOperand(5);
  5092. bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
  5093. SDValue Val = Op.getOperand(2);
  5094. MVT VT = Val.getSimpleValueType();
  5095. MVT ContainerVT = VT;
  5096. if (VT.isFixedLengthVector()) {
  5097. ContainerVT = getContainerForFixedLengthVector(VT);
  5098. Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
  5099. }
  5100. if (!IsUnmasked) {
  5101. MVT MaskVT = getMaskTypeFor(ContainerVT);
  5102. if (VT.isFixedLengthVector())
  5103. Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
  5104. }
  5105. SDValue VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
  5106. SDValue IntID = DAG.getTargetConstant(
  5107. IsUnmasked ? Intrinsic::riscv_vsse : Intrinsic::riscv_vsse_mask, DL,
  5108. XLenVT);
  5109. auto *Store = cast<MemIntrinsicSDNode>(Op);
  5110. SmallVector<SDValue, 8> Ops{Store->getChain(), IntID};
  5111. Ops.push_back(Val);
  5112. Ops.push_back(Op.getOperand(3)); // Ptr
  5113. Ops.push_back(Op.getOperand(4)); // Stride
  5114. if (!IsUnmasked)
  5115. Ops.push_back(Mask);
  5116. Ops.push_back(VL);
  5117. return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, Store->getVTList(),
  5118. Ops, Store->getMemoryVT(),
  5119. Store->getMemOperand());
  5120. }
  5121. }
  5122. return SDValue();
  5123. }
  5124. static unsigned getRVVReductionOp(unsigned ISDOpcode) {
  5125. switch (ISDOpcode) {
  5126. default:
  5127. llvm_unreachable("Unhandled reduction");
  5128. case ISD::VECREDUCE_ADD:
  5129. return RISCVISD::VECREDUCE_ADD_VL;
  5130. case ISD::VECREDUCE_UMAX:
  5131. return RISCVISD::VECREDUCE_UMAX_VL;
  5132. case ISD::VECREDUCE_SMAX:
  5133. return RISCVISD::VECREDUCE_SMAX_VL;
  5134. case ISD::VECREDUCE_UMIN:
  5135. return RISCVISD::VECREDUCE_UMIN_VL;
  5136. case ISD::VECREDUCE_SMIN:
  5137. return RISCVISD::VECREDUCE_SMIN_VL;
  5138. case ISD::VECREDUCE_AND:
  5139. return RISCVISD::VECREDUCE_AND_VL;
  5140. case ISD::VECREDUCE_OR:
  5141. return RISCVISD::VECREDUCE_OR_VL;
  5142. case ISD::VECREDUCE_XOR:
  5143. return RISCVISD::VECREDUCE_XOR_VL;
  5144. }
  5145. }
  5146. SDValue RISCVTargetLowering::lowerVectorMaskVecReduction(SDValue Op,
  5147. SelectionDAG &DAG,
  5148. bool IsVP) const {
  5149. SDLoc DL(Op);
  5150. SDValue Vec = Op.getOperand(IsVP ? 1 : 0);
  5151. MVT VecVT = Vec.getSimpleValueType();
  5152. assert((Op.getOpcode() == ISD::VECREDUCE_AND ||
  5153. Op.getOpcode() == ISD::VECREDUCE_OR ||
  5154. Op.getOpcode() == ISD::VECREDUCE_XOR ||
  5155. Op.getOpcode() == ISD::VP_REDUCE_AND ||
  5156. Op.getOpcode() == ISD::VP_REDUCE_OR ||
  5157. Op.getOpcode() == ISD::VP_REDUCE_XOR) &&
  5158. "Unexpected reduction lowering");
  5159. MVT XLenVT = Subtarget.getXLenVT();
  5160. assert(Op.getValueType() == XLenVT &&
  5161. "Expected reduction output to be legalized to XLenVT");
  5162. MVT ContainerVT = VecVT;
  5163. if (VecVT.isFixedLengthVector()) {
  5164. ContainerVT = getContainerForFixedLengthVector(VecVT);
  5165. Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
  5166. }
  5167. SDValue Mask, VL;
  5168. if (IsVP) {
  5169. Mask = Op.getOperand(2);
  5170. VL = Op.getOperand(3);
  5171. } else {
  5172. std::tie(Mask, VL) =
  5173. getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
  5174. }
  5175. unsigned BaseOpc;
  5176. ISD::CondCode CC;
  5177. SDValue Zero = DAG.getConstant(0, DL, XLenVT);
  5178. switch (Op.getOpcode()) {
  5179. default:
  5180. llvm_unreachable("Unhandled reduction");
  5181. case ISD::VECREDUCE_AND:
  5182. case ISD::VP_REDUCE_AND: {
  5183. // vcpop ~x == 0
  5184. SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
  5185. Vec = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Vec, TrueMask, VL);
  5186. Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
  5187. CC = ISD::SETEQ;
  5188. BaseOpc = ISD::AND;
  5189. break;
  5190. }
  5191. case ISD::VECREDUCE_OR:
  5192. case ISD::VP_REDUCE_OR:
  5193. // vcpop x != 0
  5194. Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
  5195. CC = ISD::SETNE;
  5196. BaseOpc = ISD::OR;
  5197. break;
  5198. case ISD::VECREDUCE_XOR:
  5199. case ISD::VP_REDUCE_XOR: {
  5200. // ((vcpop x) & 1) != 0
  5201. SDValue One = DAG.getConstant(1, DL, XLenVT);
  5202. Vec = DAG.getNode(RISCVISD::VCPOP_VL, DL, XLenVT, Vec, Mask, VL);
  5203. Vec = DAG.getNode(ISD::AND, DL, XLenVT, Vec, One);
  5204. CC = ISD::SETNE;
  5205. BaseOpc = ISD::XOR;
  5206. break;
  5207. }
  5208. }
  5209. SDValue SetCC = DAG.getSetCC(DL, XLenVT, Vec, Zero, CC);
  5210. if (!IsVP)
  5211. return SetCC;
  5212. // Now include the start value in the operation.
  5213. // Note that we must return the start value when no elements are operated
  5214. // upon. The vcpop instructions we've emitted in each case above will return
  5215. // 0 for an inactive vector, and so we've already received the neutral value:
  5216. // AND gives us (0 == 0) -> 1 and OR/XOR give us (0 != 0) -> 0. Therefore we
  5217. // can simply include the start value.
  5218. return DAG.getNode(BaseOpc, DL, XLenVT, SetCC, Op.getOperand(0));
  5219. }
  5220. static bool hasNonZeroAVL(SDValue AVL) {
  5221. auto *RegisterAVL = dyn_cast<RegisterSDNode>(AVL);
  5222. auto *ImmAVL = dyn_cast<ConstantSDNode>(AVL);
  5223. return (RegisterAVL && RegisterAVL->getReg() == RISCV::X0) ||
  5224. (ImmAVL && ImmAVL->getZExtValue() >= 1);
  5225. }
  5226. /// Helper to lower a reduction sequence of the form:
  5227. /// scalar = reduce_op vec, scalar_start
  5228. static SDValue lowerReductionSeq(unsigned RVVOpcode, MVT ResVT,
  5229. SDValue StartValue, SDValue Vec, SDValue Mask,
  5230. SDValue VL, SDLoc DL, SelectionDAG &DAG,
  5231. const RISCVSubtarget &Subtarget) {
  5232. const MVT VecVT = Vec.getSimpleValueType();
  5233. const MVT M1VT = getLMUL1VT(VecVT);
  5234. const MVT XLenVT = Subtarget.getXLenVT();
  5235. const bool NonZeroAVL = hasNonZeroAVL(VL);
  5236. // The reduction needs an LMUL1 input; do the splat at either LMUL1
  5237. // or the original VT if fractional.
  5238. auto InnerVT = VecVT.bitsLE(M1VT) ? VecVT : M1VT;
  5239. // We reuse the VL of the reduction to reduce vsetvli toggles if we can
  5240. // prove it is non-zero. For the AVL=0 case, we need the scalar to
  5241. // be the result of the reduction operation.
  5242. auto InnerVL = NonZeroAVL ? VL : DAG.getConstant(1, DL, XLenVT);
  5243. SDValue InitialValue = lowerScalarInsert(StartValue, InnerVL, InnerVT, DL,
  5244. DAG, Subtarget);
  5245. if (M1VT != InnerVT)
  5246. InitialValue = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, M1VT,
  5247. DAG.getUNDEF(M1VT),
  5248. InitialValue, DAG.getConstant(0, DL, XLenVT));
  5249. SDValue PassThru = NonZeroAVL ? DAG.getUNDEF(M1VT) : InitialValue;
  5250. SDValue Reduction = DAG.getNode(RVVOpcode, DL, M1VT, PassThru, Vec,
  5251. InitialValue, Mask, VL);
  5252. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Reduction,
  5253. DAG.getConstant(0, DL, XLenVT));
  5254. }
  5255. SDValue RISCVTargetLowering::lowerVECREDUCE(SDValue Op,
  5256. SelectionDAG &DAG) const {
  5257. SDLoc DL(Op);
  5258. SDValue Vec = Op.getOperand(0);
  5259. EVT VecEVT = Vec.getValueType();
  5260. unsigned BaseOpc = ISD::getVecReduceBaseOpcode(Op.getOpcode());
  5261. // Due to ordering in legalize types we may have a vector type that needs to
  5262. // be split. Do that manually so we can get down to a legal type.
  5263. while (getTypeAction(*DAG.getContext(), VecEVT) ==
  5264. TargetLowering::TypeSplitVector) {
  5265. auto [Lo, Hi] = DAG.SplitVector(Vec, DL);
  5266. VecEVT = Lo.getValueType();
  5267. Vec = DAG.getNode(BaseOpc, DL, VecEVT, Lo, Hi);
  5268. }
  5269. // TODO: The type may need to be widened rather than split. Or widened before
  5270. // it can be split.
  5271. if (!isTypeLegal(VecEVT))
  5272. return SDValue();
  5273. MVT VecVT = VecEVT.getSimpleVT();
  5274. MVT VecEltVT = VecVT.getVectorElementType();
  5275. unsigned RVVOpcode = getRVVReductionOp(Op.getOpcode());
  5276. MVT ContainerVT = VecVT;
  5277. if (VecVT.isFixedLengthVector()) {
  5278. ContainerVT = getContainerForFixedLengthVector(VecVT);
  5279. Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
  5280. }
  5281. auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
  5282. SDValue NeutralElem =
  5283. DAG.getNeutralElement(BaseOpc, DL, VecEltVT, SDNodeFlags());
  5284. return lowerReductionSeq(RVVOpcode, Op.getSimpleValueType(), NeutralElem, Vec,
  5285. Mask, VL, DL, DAG, Subtarget);
  5286. }
  5287. // Given a reduction op, this function returns the matching reduction opcode,
  5288. // the vector SDValue and the scalar SDValue required to lower this to a
  5289. // RISCVISD node.
  5290. static std::tuple<unsigned, SDValue, SDValue>
  5291. getRVVFPReductionOpAndOperands(SDValue Op, SelectionDAG &DAG, EVT EltVT) {
  5292. SDLoc DL(Op);
  5293. auto Flags = Op->getFlags();
  5294. unsigned Opcode = Op.getOpcode();
  5295. unsigned BaseOpcode = ISD::getVecReduceBaseOpcode(Opcode);
  5296. switch (Opcode) {
  5297. default:
  5298. llvm_unreachable("Unhandled reduction");
  5299. case ISD::VECREDUCE_FADD: {
  5300. // Use positive zero if we can. It is cheaper to materialize.
  5301. SDValue Zero =
  5302. DAG.getConstantFP(Flags.hasNoSignedZeros() ? 0.0 : -0.0, DL, EltVT);
  5303. return std::make_tuple(RISCVISD::VECREDUCE_FADD_VL, Op.getOperand(0), Zero);
  5304. }
  5305. case ISD::VECREDUCE_SEQ_FADD:
  5306. return std::make_tuple(RISCVISD::VECREDUCE_SEQ_FADD_VL, Op.getOperand(1),
  5307. Op.getOperand(0));
  5308. case ISD::VECREDUCE_FMIN:
  5309. return std::make_tuple(RISCVISD::VECREDUCE_FMIN_VL, Op.getOperand(0),
  5310. DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
  5311. case ISD::VECREDUCE_FMAX:
  5312. return std::make_tuple(RISCVISD::VECREDUCE_FMAX_VL, Op.getOperand(0),
  5313. DAG.getNeutralElement(BaseOpcode, DL, EltVT, Flags));
  5314. }
  5315. }
  5316. SDValue RISCVTargetLowering::lowerFPVECREDUCE(SDValue Op,
  5317. SelectionDAG &DAG) const {
  5318. SDLoc DL(Op);
  5319. MVT VecEltVT = Op.getSimpleValueType();
  5320. unsigned RVVOpcode;
  5321. SDValue VectorVal, ScalarVal;
  5322. std::tie(RVVOpcode, VectorVal, ScalarVal) =
  5323. getRVVFPReductionOpAndOperands(Op, DAG, VecEltVT);
  5324. MVT VecVT = VectorVal.getSimpleValueType();
  5325. MVT ContainerVT = VecVT;
  5326. if (VecVT.isFixedLengthVector()) {
  5327. ContainerVT = getContainerForFixedLengthVector(VecVT);
  5328. VectorVal = convertToScalableVector(ContainerVT, VectorVal, DAG, Subtarget);
  5329. }
  5330. auto [Mask, VL] = getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget);
  5331. return lowerReductionSeq(RVVOpcode, Op.getSimpleValueType(), ScalarVal,
  5332. VectorVal, Mask, VL, DL, DAG, Subtarget);
  5333. }
  5334. static unsigned getRVVVPReductionOp(unsigned ISDOpcode) {
  5335. switch (ISDOpcode) {
  5336. default:
  5337. llvm_unreachable("Unhandled reduction");
  5338. case ISD::VP_REDUCE_ADD:
  5339. return RISCVISD::VECREDUCE_ADD_VL;
  5340. case ISD::VP_REDUCE_UMAX:
  5341. return RISCVISD::VECREDUCE_UMAX_VL;
  5342. case ISD::VP_REDUCE_SMAX:
  5343. return RISCVISD::VECREDUCE_SMAX_VL;
  5344. case ISD::VP_REDUCE_UMIN:
  5345. return RISCVISD::VECREDUCE_UMIN_VL;
  5346. case ISD::VP_REDUCE_SMIN:
  5347. return RISCVISD::VECREDUCE_SMIN_VL;
  5348. case ISD::VP_REDUCE_AND:
  5349. return RISCVISD::VECREDUCE_AND_VL;
  5350. case ISD::VP_REDUCE_OR:
  5351. return RISCVISD::VECREDUCE_OR_VL;
  5352. case ISD::VP_REDUCE_XOR:
  5353. return RISCVISD::VECREDUCE_XOR_VL;
  5354. case ISD::VP_REDUCE_FADD:
  5355. return RISCVISD::VECREDUCE_FADD_VL;
  5356. case ISD::VP_REDUCE_SEQ_FADD:
  5357. return RISCVISD::VECREDUCE_SEQ_FADD_VL;
  5358. case ISD::VP_REDUCE_FMAX:
  5359. return RISCVISD::VECREDUCE_FMAX_VL;
  5360. case ISD::VP_REDUCE_FMIN:
  5361. return RISCVISD::VECREDUCE_FMIN_VL;
  5362. }
  5363. }
  5364. SDValue RISCVTargetLowering::lowerVPREDUCE(SDValue Op,
  5365. SelectionDAG &DAG) const {
  5366. SDLoc DL(Op);
  5367. SDValue Vec = Op.getOperand(1);
  5368. EVT VecEVT = Vec.getValueType();
  5369. // TODO: The type may need to be widened rather than split. Or widened before
  5370. // it can be split.
  5371. if (!isTypeLegal(VecEVT))
  5372. return SDValue();
  5373. MVT VecVT = VecEVT.getSimpleVT();
  5374. unsigned RVVOpcode = getRVVVPReductionOp(Op.getOpcode());
  5375. if (VecVT.isFixedLengthVector()) {
  5376. auto ContainerVT = getContainerForFixedLengthVector(VecVT);
  5377. Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
  5378. }
  5379. SDValue VL = Op.getOperand(3);
  5380. SDValue Mask = Op.getOperand(2);
  5381. return lowerReductionSeq(RVVOpcode, Op.getSimpleValueType(), Op.getOperand(0),
  5382. Vec, Mask, VL, DL, DAG, Subtarget);
  5383. }
  5384. SDValue RISCVTargetLowering::lowerINSERT_SUBVECTOR(SDValue Op,
  5385. SelectionDAG &DAG) const {
  5386. SDValue Vec = Op.getOperand(0);
  5387. SDValue SubVec = Op.getOperand(1);
  5388. MVT VecVT = Vec.getSimpleValueType();
  5389. MVT SubVecVT = SubVec.getSimpleValueType();
  5390. SDLoc DL(Op);
  5391. MVT XLenVT = Subtarget.getXLenVT();
  5392. unsigned OrigIdx = Op.getConstantOperandVal(2);
  5393. const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
  5394. // We don't have the ability to slide mask vectors up indexed by their i1
  5395. // elements; the smallest we can do is i8. Often we are able to bitcast to
  5396. // equivalent i8 vectors. Note that when inserting a fixed-length vector
  5397. // into a scalable one, we might not necessarily have enough scalable
  5398. // elements to safely divide by 8: nxv1i1 = insert nxv1i1, v4i1 is valid.
  5399. if (SubVecVT.getVectorElementType() == MVT::i1 &&
  5400. (OrigIdx != 0 || !Vec.isUndef())) {
  5401. if (VecVT.getVectorMinNumElements() >= 8 &&
  5402. SubVecVT.getVectorMinNumElements() >= 8) {
  5403. assert(OrigIdx % 8 == 0 && "Invalid index");
  5404. assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
  5405. SubVecVT.getVectorMinNumElements() % 8 == 0 &&
  5406. "Unexpected mask vector lowering");
  5407. OrigIdx /= 8;
  5408. SubVecVT =
  5409. MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
  5410. SubVecVT.isScalableVector());
  5411. VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
  5412. VecVT.isScalableVector());
  5413. Vec = DAG.getBitcast(VecVT, Vec);
  5414. SubVec = DAG.getBitcast(SubVecVT, SubVec);
  5415. } else {
  5416. // We can't slide this mask vector up indexed by its i1 elements.
  5417. // This poses a problem when we wish to insert a scalable vector which
  5418. // can't be re-expressed as a larger type. Just choose the slow path and
  5419. // extend to a larger type, then truncate back down.
  5420. MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
  5421. MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
  5422. Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
  5423. SubVec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtSubVecVT, SubVec);
  5424. Vec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ExtVecVT, Vec, SubVec,
  5425. Op.getOperand(2));
  5426. SDValue SplatZero = DAG.getConstant(0, DL, ExtVecVT);
  5427. return DAG.getSetCC(DL, VecVT, Vec, SplatZero, ISD::SETNE);
  5428. }
  5429. }
  5430. // If the subvector vector is a fixed-length type, we cannot use subregister
  5431. // manipulation to simplify the codegen; we don't know which register of a
  5432. // LMUL group contains the specific subvector as we only know the minimum
  5433. // register size. Therefore we must slide the vector group up the full
  5434. // amount.
  5435. if (SubVecVT.isFixedLengthVector()) {
  5436. if (OrigIdx == 0 && Vec.isUndef() && !VecVT.isFixedLengthVector())
  5437. return Op;
  5438. MVT ContainerVT = VecVT;
  5439. if (VecVT.isFixedLengthVector()) {
  5440. ContainerVT = getContainerForFixedLengthVector(VecVT);
  5441. Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
  5442. }
  5443. SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ContainerVT,
  5444. DAG.getUNDEF(ContainerVT), SubVec,
  5445. DAG.getConstant(0, DL, XLenVT));
  5446. if (OrigIdx == 0 && Vec.isUndef() && VecVT.isFixedLengthVector()) {
  5447. SubVec = convertFromScalableVector(VecVT, SubVec, DAG, Subtarget);
  5448. return DAG.getBitcast(Op.getValueType(), SubVec);
  5449. }
  5450. SDValue Mask =
  5451. getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
  5452. // Set the vector length to only the number of elements we care about. Note
  5453. // that for slideup this includes the offset.
  5454. SDValue VL =
  5455. getVLOp(OrigIdx + SubVecVT.getVectorNumElements(), DL, DAG, Subtarget);
  5456. SDValue SlideupAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
  5457. // Use tail agnostic policy if OrigIdx is the last index of Vec.
  5458. unsigned Policy = RISCVII::TAIL_UNDISTURBED_MASK_UNDISTURBED;
  5459. if (VecVT.isFixedLengthVector() &&
  5460. OrigIdx + 1 == VecVT.getVectorNumElements())
  5461. Policy = RISCVII::TAIL_AGNOSTIC;
  5462. SDValue Slideup = getVSlideup(DAG, Subtarget, DL, ContainerVT, Vec, SubVec,
  5463. SlideupAmt, Mask, VL, Policy);
  5464. if (VecVT.isFixedLengthVector())
  5465. Slideup = convertFromScalableVector(VecVT, Slideup, DAG, Subtarget);
  5466. return DAG.getBitcast(Op.getValueType(), Slideup);
  5467. }
  5468. unsigned SubRegIdx, RemIdx;
  5469. std::tie(SubRegIdx, RemIdx) =
  5470. RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
  5471. VecVT, SubVecVT, OrigIdx, TRI);
  5472. RISCVII::VLMUL SubVecLMUL = RISCVTargetLowering::getLMUL(SubVecVT);
  5473. bool IsSubVecPartReg = SubVecLMUL == RISCVII::VLMUL::LMUL_F2 ||
  5474. SubVecLMUL == RISCVII::VLMUL::LMUL_F4 ||
  5475. SubVecLMUL == RISCVII::VLMUL::LMUL_F8;
  5476. // 1. If the Idx has been completely eliminated and this subvector's size is
  5477. // a vector register or a multiple thereof, or the surrounding elements are
  5478. // undef, then this is a subvector insert which naturally aligns to a vector
  5479. // register. These can easily be handled using subregister manipulation.
  5480. // 2. If the subvector is smaller than a vector register, then the insertion
  5481. // must preserve the undisturbed elements of the register. We do this by
  5482. // lowering to an EXTRACT_SUBVECTOR grabbing the nearest LMUL=1 vector type
  5483. // (which resolves to a subregister copy), performing a VSLIDEUP to place the
  5484. // subvector within the vector register, and an INSERT_SUBVECTOR of that
  5485. // LMUL=1 type back into the larger vector (resolving to another subregister
  5486. // operation). See below for how our VSLIDEUP works. We go via a LMUL=1 type
  5487. // to avoid allocating a large register group to hold our subvector.
  5488. if (RemIdx == 0 && (!IsSubVecPartReg || Vec.isUndef()))
  5489. return Op;
  5490. // VSLIDEUP works by leaving elements 0<i<OFFSET undisturbed, elements
  5491. // OFFSET<=i<VL set to the "subvector" and vl<=i<VLMAX set to the tail policy
  5492. // (in our case undisturbed). This means we can set up a subvector insertion
  5493. // where OFFSET is the insertion offset, and the VL is the OFFSET plus the
  5494. // size of the subvector.
  5495. MVT InterSubVT = VecVT;
  5496. SDValue AlignedExtract = Vec;
  5497. unsigned AlignedIdx = OrigIdx - RemIdx;
  5498. if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
  5499. InterSubVT = getLMUL1VT(VecVT);
  5500. // Extract a subvector equal to the nearest full vector register type. This
  5501. // should resolve to a EXTRACT_SUBREG instruction.
  5502. AlignedExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
  5503. DAG.getConstant(AlignedIdx, DL, XLenVT));
  5504. }
  5505. SDValue SlideupAmt = DAG.getConstant(RemIdx, DL, XLenVT);
  5506. // For scalable vectors this must be further multiplied by vscale.
  5507. SlideupAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlideupAmt);
  5508. auto [Mask, VL] = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
  5509. // Construct the vector length corresponding to RemIdx + length(SubVecVT).
  5510. VL = DAG.getConstant(SubVecVT.getVectorMinNumElements(), DL, XLenVT);
  5511. VL = DAG.getNode(ISD::VSCALE, DL, XLenVT, VL);
  5512. VL = DAG.getNode(ISD::ADD, DL, XLenVT, SlideupAmt, VL);
  5513. SubVec = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InterSubVT,
  5514. DAG.getUNDEF(InterSubVT), SubVec,
  5515. DAG.getConstant(0, DL, XLenVT));
  5516. SDValue Slideup = getVSlideup(DAG, Subtarget, DL, InterSubVT, AlignedExtract,
  5517. SubVec, SlideupAmt, Mask, VL);
  5518. // If required, insert this subvector back into the correct vector register.
  5519. // This should resolve to an INSERT_SUBREG instruction.
  5520. if (VecVT.bitsGT(InterSubVT))
  5521. Slideup = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, Vec, Slideup,
  5522. DAG.getConstant(AlignedIdx, DL, XLenVT));
  5523. // We might have bitcast from a mask type: cast back to the original type if
  5524. // required.
  5525. return DAG.getBitcast(Op.getSimpleValueType(), Slideup);
  5526. }
  5527. SDValue RISCVTargetLowering::lowerEXTRACT_SUBVECTOR(SDValue Op,
  5528. SelectionDAG &DAG) const {
  5529. SDValue Vec = Op.getOperand(0);
  5530. MVT SubVecVT = Op.getSimpleValueType();
  5531. MVT VecVT = Vec.getSimpleValueType();
  5532. SDLoc DL(Op);
  5533. MVT XLenVT = Subtarget.getXLenVT();
  5534. unsigned OrigIdx = Op.getConstantOperandVal(1);
  5535. const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
  5536. // We don't have the ability to slide mask vectors down indexed by their i1
  5537. // elements; the smallest we can do is i8. Often we are able to bitcast to
  5538. // equivalent i8 vectors. Note that when extracting a fixed-length vector
  5539. // from a scalable one, we might not necessarily have enough scalable
  5540. // elements to safely divide by 8: v8i1 = extract nxv1i1 is valid.
  5541. if (SubVecVT.getVectorElementType() == MVT::i1 && OrigIdx != 0) {
  5542. if (VecVT.getVectorMinNumElements() >= 8 &&
  5543. SubVecVT.getVectorMinNumElements() >= 8) {
  5544. assert(OrigIdx % 8 == 0 && "Invalid index");
  5545. assert(VecVT.getVectorMinNumElements() % 8 == 0 &&
  5546. SubVecVT.getVectorMinNumElements() % 8 == 0 &&
  5547. "Unexpected mask vector lowering");
  5548. OrigIdx /= 8;
  5549. SubVecVT =
  5550. MVT::getVectorVT(MVT::i8, SubVecVT.getVectorMinNumElements() / 8,
  5551. SubVecVT.isScalableVector());
  5552. VecVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorMinNumElements() / 8,
  5553. VecVT.isScalableVector());
  5554. Vec = DAG.getBitcast(VecVT, Vec);
  5555. } else {
  5556. // We can't slide this mask vector down, indexed by its i1 elements.
  5557. // This poses a problem when we wish to extract a scalable vector which
  5558. // can't be re-expressed as a larger type. Just choose the slow path and
  5559. // extend to a larger type, then truncate back down.
  5560. // TODO: We could probably improve this when extracting certain fixed
  5561. // from fixed, where we can extract as i8 and shift the correct element
  5562. // right to reach the desired subvector?
  5563. MVT ExtVecVT = VecVT.changeVectorElementType(MVT::i8);
  5564. MVT ExtSubVecVT = SubVecVT.changeVectorElementType(MVT::i8);
  5565. Vec = DAG.getNode(ISD::ZERO_EXTEND, DL, ExtVecVT, Vec);
  5566. Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ExtSubVecVT, Vec,
  5567. Op.getOperand(1));
  5568. SDValue SplatZero = DAG.getConstant(0, DL, ExtSubVecVT);
  5569. return DAG.getSetCC(DL, SubVecVT, Vec, SplatZero, ISD::SETNE);
  5570. }
  5571. }
  5572. // If the subvector vector is a fixed-length type, we cannot use subregister
  5573. // manipulation to simplify the codegen; we don't know which register of a
  5574. // LMUL group contains the specific subvector as we only know the minimum
  5575. // register size. Therefore we must slide the vector group down the full
  5576. // amount.
  5577. if (SubVecVT.isFixedLengthVector()) {
  5578. // With an index of 0 this is a cast-like subvector, which can be performed
  5579. // with subregister operations.
  5580. if (OrigIdx == 0)
  5581. return Op;
  5582. MVT ContainerVT = VecVT;
  5583. if (VecVT.isFixedLengthVector()) {
  5584. ContainerVT = getContainerForFixedLengthVector(VecVT);
  5585. Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
  5586. }
  5587. SDValue Mask =
  5588. getDefaultVLOps(VecVT, ContainerVT, DL, DAG, Subtarget).first;
  5589. // Set the vector length to only the number of elements we care about. This
  5590. // avoids sliding down elements we're going to discard straight away.
  5591. SDValue VL = getVLOp(SubVecVT.getVectorNumElements(), DL, DAG, Subtarget);
  5592. SDValue SlidedownAmt = DAG.getConstant(OrigIdx, DL, XLenVT);
  5593. SDValue Slidedown =
  5594. getVSlidedown(DAG, Subtarget, DL, ContainerVT,
  5595. DAG.getUNDEF(ContainerVT), Vec, SlidedownAmt, Mask, VL);
  5596. // Now we can use a cast-like subvector extract to get the result.
  5597. Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
  5598. DAG.getConstant(0, DL, XLenVT));
  5599. return DAG.getBitcast(Op.getValueType(), Slidedown);
  5600. }
  5601. unsigned SubRegIdx, RemIdx;
  5602. std::tie(SubRegIdx, RemIdx) =
  5603. RISCVTargetLowering::decomposeSubvectorInsertExtractToSubRegs(
  5604. VecVT, SubVecVT, OrigIdx, TRI);
  5605. // If the Idx has been completely eliminated then this is a subvector extract
  5606. // which naturally aligns to a vector register. These can easily be handled
  5607. // using subregister manipulation.
  5608. if (RemIdx == 0)
  5609. return Op;
  5610. // Else we must shift our vector register directly to extract the subvector.
  5611. // Do this using VSLIDEDOWN.
  5612. // If the vector type is an LMUL-group type, extract a subvector equal to the
  5613. // nearest full vector register type. This should resolve to a EXTRACT_SUBREG
  5614. // instruction.
  5615. MVT InterSubVT = VecVT;
  5616. if (VecVT.bitsGT(getLMUL1VT(VecVT))) {
  5617. InterSubVT = getLMUL1VT(VecVT);
  5618. Vec = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InterSubVT, Vec,
  5619. DAG.getConstant(OrigIdx - RemIdx, DL, XLenVT));
  5620. }
  5621. // Slide this vector register down by the desired number of elements in order
  5622. // to place the desired subvector starting at element 0.
  5623. SDValue SlidedownAmt = DAG.getConstant(RemIdx, DL, XLenVT);
  5624. // For scalable vectors this must be further multiplied by vscale.
  5625. SlidedownAmt = DAG.getNode(ISD::VSCALE, DL, XLenVT, SlidedownAmt);
  5626. auto [Mask, VL] = getDefaultScalableVLOps(InterSubVT, DL, DAG, Subtarget);
  5627. SDValue Slidedown =
  5628. getVSlidedown(DAG, Subtarget, DL, InterSubVT, DAG.getUNDEF(InterSubVT),
  5629. Vec, SlidedownAmt, Mask, VL);
  5630. // Now the vector is in the right position, extract our final subvector. This
  5631. // should resolve to a COPY.
  5632. Slidedown = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVecVT, Slidedown,
  5633. DAG.getConstant(0, DL, XLenVT));
  5634. // We might have bitcast from a mask type: cast back to the original type if
  5635. // required.
  5636. return DAG.getBitcast(Op.getSimpleValueType(), Slidedown);
  5637. }
  5638. // Lower step_vector to the vid instruction. Any non-identity step value must
  5639. // be accounted for my manual expansion.
  5640. SDValue RISCVTargetLowering::lowerSTEP_VECTOR(SDValue Op,
  5641. SelectionDAG &DAG) const {
  5642. SDLoc DL(Op);
  5643. MVT VT = Op.getSimpleValueType();
  5644. assert(VT.isScalableVector() && "Expected scalable vector");
  5645. MVT XLenVT = Subtarget.getXLenVT();
  5646. auto [Mask, VL] = getDefaultScalableVLOps(VT, DL, DAG, Subtarget);
  5647. SDValue StepVec = DAG.getNode(RISCVISD::VID_VL, DL, VT, Mask, VL);
  5648. uint64_t StepValImm = Op.getConstantOperandVal(0);
  5649. if (StepValImm != 1) {
  5650. if (isPowerOf2_64(StepValImm)) {
  5651. SDValue StepVal =
  5652. DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
  5653. DAG.getConstant(Log2_64(StepValImm), DL, XLenVT), VL);
  5654. StepVec = DAG.getNode(ISD::SHL, DL, VT, StepVec, StepVal);
  5655. } else {
  5656. SDValue StepVal = lowerScalarSplat(
  5657. SDValue(), DAG.getConstant(StepValImm, DL, VT.getVectorElementType()),
  5658. VL, VT, DL, DAG, Subtarget);
  5659. StepVec = DAG.getNode(ISD::MUL, DL, VT, StepVec, StepVal);
  5660. }
  5661. }
  5662. return StepVec;
  5663. }
  5664. // Implement vector_reverse using vrgather.vv with indices determined by
  5665. // subtracting the id of each element from (VLMAX-1). This will convert
  5666. // the indices like so:
  5667. // (0, 1,..., VLMAX-2, VLMAX-1) -> (VLMAX-1, VLMAX-2,..., 1, 0).
  5668. // TODO: This code assumes VLMAX <= 65536 for LMUL=8 SEW=16.
  5669. SDValue RISCVTargetLowering::lowerVECTOR_REVERSE(SDValue Op,
  5670. SelectionDAG &DAG) const {
  5671. SDLoc DL(Op);
  5672. MVT VecVT = Op.getSimpleValueType();
  5673. if (VecVT.getVectorElementType() == MVT::i1) {
  5674. MVT WidenVT = MVT::getVectorVT(MVT::i8, VecVT.getVectorElementCount());
  5675. SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, WidenVT, Op.getOperand(0));
  5676. SDValue Op2 = DAG.getNode(ISD::VECTOR_REVERSE, DL, WidenVT, Op1);
  5677. return DAG.getNode(ISD::TRUNCATE, DL, VecVT, Op2);
  5678. }
  5679. unsigned EltSize = VecVT.getScalarSizeInBits();
  5680. unsigned MinSize = VecVT.getSizeInBits().getKnownMinValue();
  5681. unsigned VectorBitsMax = Subtarget.getRealMaxVLen();
  5682. unsigned MaxVLMAX =
  5683. RISCVTargetLowering::computeVLMAX(VectorBitsMax, EltSize, MinSize);
  5684. unsigned GatherOpc = RISCVISD::VRGATHER_VV_VL;
  5685. MVT IntVT = VecVT.changeVectorElementTypeToInteger();
  5686. // If this is SEW=8 and VLMAX is potentially more than 256, we need
  5687. // to use vrgatherei16.vv.
  5688. // TODO: It's also possible to use vrgatherei16.vv for other types to
  5689. // decrease register width for the index calculation.
  5690. if (MaxVLMAX > 256 && EltSize == 8) {
  5691. // If this is LMUL=8, we have to split before can use vrgatherei16.vv.
  5692. // Reverse each half, then reassemble them in reverse order.
  5693. // NOTE: It's also possible that after splitting that VLMAX no longer
  5694. // requires vrgatherei16.vv.
  5695. if (MinSize == (8 * RISCV::RVVBitsPerBlock)) {
  5696. auto [Lo, Hi] = DAG.SplitVectorOperand(Op.getNode(), 0);
  5697. auto [LoVT, HiVT] = DAG.GetSplitDestVTs(VecVT);
  5698. Lo = DAG.getNode(ISD::VECTOR_REVERSE, DL, LoVT, Lo);
  5699. Hi = DAG.getNode(ISD::VECTOR_REVERSE, DL, HiVT, Hi);
  5700. // Reassemble the low and high pieces reversed.
  5701. // FIXME: This is a CONCAT_VECTORS.
  5702. SDValue Res =
  5703. DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VecVT, DAG.getUNDEF(VecVT), Hi,
  5704. DAG.getIntPtrConstant(0, DL));
  5705. return DAG.getNode(
  5706. ISD::INSERT_SUBVECTOR, DL, VecVT, Res, Lo,
  5707. DAG.getIntPtrConstant(LoVT.getVectorMinNumElements(), DL));
  5708. }
  5709. // Just promote the int type to i16 which will double the LMUL.
  5710. IntVT = MVT::getVectorVT(MVT::i16, VecVT.getVectorElementCount());
  5711. GatherOpc = RISCVISD::VRGATHEREI16_VV_VL;
  5712. }
  5713. MVT XLenVT = Subtarget.getXLenVT();
  5714. auto [Mask, VL] = getDefaultScalableVLOps(VecVT, DL, DAG, Subtarget);
  5715. // Calculate VLMAX-1 for the desired SEW.
  5716. unsigned MinElts = VecVT.getVectorMinNumElements();
  5717. SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
  5718. getVLOp(MinElts, DL, DAG, Subtarget));
  5719. SDValue VLMinus1 =
  5720. DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DAG.getConstant(1, DL, XLenVT));
  5721. // Splat VLMAX-1 taking care to handle SEW==64 on RV32.
  5722. bool IsRV32E64 =
  5723. !Subtarget.is64Bit() && IntVT.getVectorElementType() == MVT::i64;
  5724. SDValue SplatVL;
  5725. if (!IsRV32E64)
  5726. SplatVL = DAG.getSplatVector(IntVT, DL, VLMinus1);
  5727. else
  5728. SplatVL = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT, DAG.getUNDEF(IntVT),
  5729. VLMinus1, DAG.getRegister(RISCV::X0, XLenVT));
  5730. SDValue VID = DAG.getNode(RISCVISD::VID_VL, DL, IntVT, Mask, VL);
  5731. SDValue Indices = DAG.getNode(RISCVISD::SUB_VL, DL, IntVT, SplatVL, VID,
  5732. DAG.getUNDEF(IntVT), Mask, VL);
  5733. return DAG.getNode(GatherOpc, DL, VecVT, Op.getOperand(0), Indices,
  5734. DAG.getUNDEF(VecVT), Mask, VL);
  5735. }
  5736. SDValue RISCVTargetLowering::lowerVECTOR_SPLICE(SDValue Op,
  5737. SelectionDAG &DAG) const {
  5738. SDLoc DL(Op);
  5739. SDValue V1 = Op.getOperand(0);
  5740. SDValue V2 = Op.getOperand(1);
  5741. MVT XLenVT = Subtarget.getXLenVT();
  5742. MVT VecVT = Op.getSimpleValueType();
  5743. unsigned MinElts = VecVT.getVectorMinNumElements();
  5744. SDValue VLMax = DAG.getNode(ISD::VSCALE, DL, XLenVT,
  5745. getVLOp(MinElts, DL, DAG, Subtarget));
  5746. int64_t ImmValue = cast<ConstantSDNode>(Op.getOperand(2))->getSExtValue();
  5747. SDValue DownOffset, UpOffset;
  5748. if (ImmValue >= 0) {
  5749. // The operand is a TargetConstant, we need to rebuild it as a regular
  5750. // constant.
  5751. DownOffset = DAG.getConstant(ImmValue, DL, XLenVT);
  5752. UpOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, DownOffset);
  5753. } else {
  5754. // The operand is a TargetConstant, we need to rebuild it as a regular
  5755. // constant rather than negating the original operand.
  5756. UpOffset = DAG.getConstant(-ImmValue, DL, XLenVT);
  5757. DownOffset = DAG.getNode(ISD::SUB, DL, XLenVT, VLMax, UpOffset);
  5758. }
  5759. SDValue TrueMask = getAllOnesMask(VecVT, VLMax, DL, DAG);
  5760. SDValue SlideDown =
  5761. getVSlidedown(DAG, Subtarget, DL, VecVT, DAG.getUNDEF(VecVT), V1,
  5762. DownOffset, TrueMask, UpOffset);
  5763. return getVSlideup(DAG, Subtarget, DL, VecVT, SlideDown, V2, UpOffset,
  5764. TrueMask, DAG.getRegister(RISCV::X0, XLenVT),
  5765. RISCVII::TAIL_AGNOSTIC);
  5766. }
  5767. SDValue
  5768. RISCVTargetLowering::lowerFixedLengthVectorLoadToRVV(SDValue Op,
  5769. SelectionDAG &DAG) const {
  5770. SDLoc DL(Op);
  5771. auto *Load = cast<LoadSDNode>(Op);
  5772. assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
  5773. Load->getMemoryVT(),
  5774. *Load->getMemOperand()) &&
  5775. "Expecting a correctly-aligned load");
  5776. MVT VT = Op.getSimpleValueType();
  5777. MVT XLenVT = Subtarget.getXLenVT();
  5778. MVT ContainerVT = getContainerForFixedLengthVector(VT);
  5779. SDValue VL = getVLOp(VT.getVectorNumElements(), DL, DAG, Subtarget);
  5780. bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
  5781. SDValue IntID = DAG.getTargetConstant(
  5782. IsMaskOp ? Intrinsic::riscv_vlm : Intrinsic::riscv_vle, DL, XLenVT);
  5783. SmallVector<SDValue, 4> Ops{Load->getChain(), IntID};
  5784. if (!IsMaskOp)
  5785. Ops.push_back(DAG.getUNDEF(ContainerVT));
  5786. Ops.push_back(Load->getBasePtr());
  5787. Ops.push_back(VL);
  5788. SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
  5789. SDValue NewLoad =
  5790. DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
  5791. Load->getMemoryVT(), Load->getMemOperand());
  5792. SDValue Result = convertFromScalableVector(VT, NewLoad, DAG, Subtarget);
  5793. return DAG.getMergeValues({Result, NewLoad.getValue(1)}, DL);
  5794. }
  5795. SDValue
  5796. RISCVTargetLowering::lowerFixedLengthVectorStoreToRVV(SDValue Op,
  5797. SelectionDAG &DAG) const {
  5798. SDLoc DL(Op);
  5799. auto *Store = cast<StoreSDNode>(Op);
  5800. assert(allowsMemoryAccessForAlignment(*DAG.getContext(), DAG.getDataLayout(),
  5801. Store->getMemoryVT(),
  5802. *Store->getMemOperand()) &&
  5803. "Expecting a correctly-aligned store");
  5804. SDValue StoreVal = Store->getValue();
  5805. MVT VT = StoreVal.getSimpleValueType();
  5806. MVT XLenVT = Subtarget.getXLenVT();
  5807. // If the size less than a byte, we need to pad with zeros to make a byte.
  5808. if (VT.getVectorElementType() == MVT::i1 && VT.getVectorNumElements() < 8) {
  5809. VT = MVT::v8i1;
  5810. StoreVal = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT,
  5811. DAG.getConstant(0, DL, VT), StoreVal,
  5812. DAG.getIntPtrConstant(0, DL));
  5813. }
  5814. MVT ContainerVT = getContainerForFixedLengthVector(VT);
  5815. SDValue VL = getVLOp(VT.getVectorNumElements(), DL, DAG, Subtarget);
  5816. SDValue NewValue =
  5817. convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
  5818. bool IsMaskOp = VT.getVectorElementType() == MVT::i1;
  5819. SDValue IntID = DAG.getTargetConstant(
  5820. IsMaskOp ? Intrinsic::riscv_vsm : Intrinsic::riscv_vse, DL, XLenVT);
  5821. return DAG.getMemIntrinsicNode(
  5822. ISD::INTRINSIC_VOID, DL, DAG.getVTList(MVT::Other),
  5823. {Store->getChain(), IntID, NewValue, Store->getBasePtr(), VL},
  5824. Store->getMemoryVT(), Store->getMemOperand());
  5825. }
  5826. SDValue RISCVTargetLowering::lowerMaskedLoad(SDValue Op,
  5827. SelectionDAG &DAG) const {
  5828. SDLoc DL(Op);
  5829. MVT VT = Op.getSimpleValueType();
  5830. const auto *MemSD = cast<MemSDNode>(Op);
  5831. EVT MemVT = MemSD->getMemoryVT();
  5832. MachineMemOperand *MMO = MemSD->getMemOperand();
  5833. SDValue Chain = MemSD->getChain();
  5834. SDValue BasePtr = MemSD->getBasePtr();
  5835. SDValue Mask, PassThru, VL;
  5836. if (const auto *VPLoad = dyn_cast<VPLoadSDNode>(Op)) {
  5837. Mask = VPLoad->getMask();
  5838. PassThru = DAG.getUNDEF(VT);
  5839. VL = VPLoad->getVectorLength();
  5840. } else {
  5841. const auto *MLoad = cast<MaskedLoadSDNode>(Op);
  5842. Mask = MLoad->getMask();
  5843. PassThru = MLoad->getPassThru();
  5844. }
  5845. bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
  5846. MVT XLenVT = Subtarget.getXLenVT();
  5847. MVT ContainerVT = VT;
  5848. if (VT.isFixedLengthVector()) {
  5849. ContainerVT = getContainerForFixedLengthVector(VT);
  5850. PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
  5851. if (!IsUnmasked) {
  5852. MVT MaskVT = getMaskTypeFor(ContainerVT);
  5853. Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
  5854. }
  5855. }
  5856. if (!VL)
  5857. VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
  5858. unsigned IntID =
  5859. IsUnmasked ? Intrinsic::riscv_vle : Intrinsic::riscv_vle_mask;
  5860. SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
  5861. if (IsUnmasked)
  5862. Ops.push_back(DAG.getUNDEF(ContainerVT));
  5863. else
  5864. Ops.push_back(PassThru);
  5865. Ops.push_back(BasePtr);
  5866. if (!IsUnmasked)
  5867. Ops.push_back(Mask);
  5868. Ops.push_back(VL);
  5869. if (!IsUnmasked)
  5870. Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
  5871. SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
  5872. SDValue Result =
  5873. DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
  5874. Chain = Result.getValue(1);
  5875. if (VT.isFixedLengthVector())
  5876. Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
  5877. return DAG.getMergeValues({Result, Chain}, DL);
  5878. }
  5879. SDValue RISCVTargetLowering::lowerMaskedStore(SDValue Op,
  5880. SelectionDAG &DAG) const {
  5881. SDLoc DL(Op);
  5882. const auto *MemSD = cast<MemSDNode>(Op);
  5883. EVT MemVT = MemSD->getMemoryVT();
  5884. MachineMemOperand *MMO = MemSD->getMemOperand();
  5885. SDValue Chain = MemSD->getChain();
  5886. SDValue BasePtr = MemSD->getBasePtr();
  5887. SDValue Val, Mask, VL;
  5888. if (const auto *VPStore = dyn_cast<VPStoreSDNode>(Op)) {
  5889. Val = VPStore->getValue();
  5890. Mask = VPStore->getMask();
  5891. VL = VPStore->getVectorLength();
  5892. } else {
  5893. const auto *MStore = cast<MaskedStoreSDNode>(Op);
  5894. Val = MStore->getValue();
  5895. Mask = MStore->getMask();
  5896. }
  5897. bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
  5898. MVT VT = Val.getSimpleValueType();
  5899. MVT XLenVT = Subtarget.getXLenVT();
  5900. MVT ContainerVT = VT;
  5901. if (VT.isFixedLengthVector()) {
  5902. ContainerVT = getContainerForFixedLengthVector(VT);
  5903. Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
  5904. if (!IsUnmasked) {
  5905. MVT MaskVT = getMaskTypeFor(ContainerVT);
  5906. Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
  5907. }
  5908. }
  5909. if (!VL)
  5910. VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
  5911. unsigned IntID =
  5912. IsUnmasked ? Intrinsic::riscv_vse : Intrinsic::riscv_vse_mask;
  5913. SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
  5914. Ops.push_back(Val);
  5915. Ops.push_back(BasePtr);
  5916. if (!IsUnmasked)
  5917. Ops.push_back(Mask);
  5918. Ops.push_back(VL);
  5919. return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
  5920. DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
  5921. }
  5922. SDValue
  5923. RISCVTargetLowering::lowerFixedLengthVectorSetccToRVV(SDValue Op,
  5924. SelectionDAG &DAG) const {
  5925. MVT InVT = Op.getOperand(0).getSimpleValueType();
  5926. MVT ContainerVT = getContainerForFixedLengthVector(InVT);
  5927. MVT VT = Op.getSimpleValueType();
  5928. SDValue Op1 =
  5929. convertToScalableVector(ContainerVT, Op.getOperand(0), DAG, Subtarget);
  5930. SDValue Op2 =
  5931. convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
  5932. SDLoc DL(Op);
  5933. auto [Mask, VL] = getDefaultVLOps(VT.getVectorNumElements(), ContainerVT, DL,
  5934. DAG, Subtarget);
  5935. MVT MaskVT = getMaskTypeFor(ContainerVT);
  5936. SDValue Cmp =
  5937. DAG.getNode(RISCVISD::SETCC_VL, DL, MaskVT,
  5938. {Op1, Op2, Op.getOperand(2), DAG.getUNDEF(MaskVT), Mask, VL});
  5939. return convertFromScalableVector(VT, Cmp, DAG, Subtarget);
  5940. }
  5941. SDValue RISCVTargetLowering::lowerFixedLengthVectorLogicOpToRVV(
  5942. SDValue Op, SelectionDAG &DAG, unsigned MaskOpc, unsigned VecOpc) const {
  5943. MVT VT = Op.getSimpleValueType();
  5944. if (VT.getVectorElementType() == MVT::i1)
  5945. return lowerToScalableOp(Op, DAG, MaskOpc, /*HasMergeOp*/ false,
  5946. /*HasMask*/ false);
  5947. return lowerToScalableOp(Op, DAG, VecOpc, /*HasMergeOp*/ true);
  5948. }
  5949. SDValue
  5950. RISCVTargetLowering::lowerFixedLengthVectorShiftToRVV(SDValue Op,
  5951. SelectionDAG &DAG) const {
  5952. unsigned Opc;
  5953. switch (Op.getOpcode()) {
  5954. default: llvm_unreachable("Unexpected opcode!");
  5955. case ISD::SHL: Opc = RISCVISD::SHL_VL; break;
  5956. case ISD::SRA: Opc = RISCVISD::SRA_VL; break;
  5957. case ISD::SRL: Opc = RISCVISD::SRL_VL; break;
  5958. }
  5959. return lowerToScalableOp(Op, DAG, Opc, /*HasMergeOp*/ true);
  5960. }
  5961. // Lower vector ABS to smax(X, sub(0, X)).
  5962. SDValue RISCVTargetLowering::lowerABS(SDValue Op, SelectionDAG &DAG) const {
  5963. SDLoc DL(Op);
  5964. MVT VT = Op.getSimpleValueType();
  5965. SDValue X = Op.getOperand(0);
  5966. assert((Op.getOpcode() == ISD::VP_ABS || VT.isFixedLengthVector()) &&
  5967. "Unexpected type for ISD::ABS");
  5968. MVT ContainerVT = VT;
  5969. if (VT.isFixedLengthVector()) {
  5970. ContainerVT = getContainerForFixedLengthVector(VT);
  5971. X = convertToScalableVector(ContainerVT, X, DAG, Subtarget);
  5972. }
  5973. SDValue Mask, VL;
  5974. if (Op->getOpcode() == ISD::VP_ABS) {
  5975. Mask = Op->getOperand(1);
  5976. VL = Op->getOperand(2);
  5977. } else
  5978. std::tie(Mask, VL) = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
  5979. SDValue SplatZero = DAG.getNode(
  5980. RISCVISD::VMV_V_X_VL, DL, ContainerVT, DAG.getUNDEF(ContainerVT),
  5981. DAG.getConstant(0, DL, Subtarget.getXLenVT()), VL);
  5982. SDValue NegX = DAG.getNode(RISCVISD::SUB_VL, DL, ContainerVT, SplatZero, X,
  5983. DAG.getUNDEF(ContainerVT), Mask, VL);
  5984. SDValue Max = DAG.getNode(RISCVISD::SMAX_VL, DL, ContainerVT, X, NegX,
  5985. DAG.getUNDEF(ContainerVT), Mask, VL);
  5986. if (VT.isFixedLengthVector())
  5987. Max = convertFromScalableVector(VT, Max, DAG, Subtarget);
  5988. return Max;
  5989. }
  5990. SDValue RISCVTargetLowering::lowerFixedLengthVectorFCOPYSIGNToRVV(
  5991. SDValue Op, SelectionDAG &DAG) const {
  5992. SDLoc DL(Op);
  5993. MVT VT = Op.getSimpleValueType();
  5994. SDValue Mag = Op.getOperand(0);
  5995. SDValue Sign = Op.getOperand(1);
  5996. assert(Mag.getValueType() == Sign.getValueType() &&
  5997. "Can only handle COPYSIGN with matching types.");
  5998. MVT ContainerVT = getContainerForFixedLengthVector(VT);
  5999. Mag = convertToScalableVector(ContainerVT, Mag, DAG, Subtarget);
  6000. Sign = convertToScalableVector(ContainerVT, Sign, DAG, Subtarget);
  6001. auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
  6002. SDValue CopySign = DAG.getNode(RISCVISD::FCOPYSIGN_VL, DL, ContainerVT, Mag,
  6003. Sign, DAG.getUNDEF(ContainerVT), Mask, VL);
  6004. return convertFromScalableVector(VT, CopySign, DAG, Subtarget);
  6005. }
  6006. SDValue RISCVTargetLowering::lowerFixedLengthVectorSelectToRVV(
  6007. SDValue Op, SelectionDAG &DAG) const {
  6008. MVT VT = Op.getSimpleValueType();
  6009. MVT ContainerVT = getContainerForFixedLengthVector(VT);
  6010. MVT I1ContainerVT =
  6011. MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
  6012. SDValue CC =
  6013. convertToScalableVector(I1ContainerVT, Op.getOperand(0), DAG, Subtarget);
  6014. SDValue Op1 =
  6015. convertToScalableVector(ContainerVT, Op.getOperand(1), DAG, Subtarget);
  6016. SDValue Op2 =
  6017. convertToScalableVector(ContainerVT, Op.getOperand(2), DAG, Subtarget);
  6018. SDLoc DL(Op);
  6019. SDValue VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
  6020. SDValue Select =
  6021. DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, CC, Op1, Op2, VL);
  6022. return convertFromScalableVector(VT, Select, DAG, Subtarget);
  6023. }
  6024. SDValue RISCVTargetLowering::lowerToScalableOp(SDValue Op, SelectionDAG &DAG,
  6025. unsigned NewOpc, bool HasMergeOp,
  6026. bool HasMask) const {
  6027. MVT VT = Op.getSimpleValueType();
  6028. MVT ContainerVT = getContainerForFixedLengthVector(VT);
  6029. // Create list of operands by converting existing ones to scalable types.
  6030. SmallVector<SDValue, 6> Ops;
  6031. for (const SDValue &V : Op->op_values()) {
  6032. assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
  6033. // Pass through non-vector operands.
  6034. if (!V.getValueType().isVector()) {
  6035. Ops.push_back(V);
  6036. continue;
  6037. }
  6038. // "cast" fixed length vector to a scalable vector.
  6039. assert(useRVVForFixedLengthVectorVT(V.getSimpleValueType()) &&
  6040. "Only fixed length vectors are supported!");
  6041. Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
  6042. }
  6043. SDLoc DL(Op);
  6044. auto [Mask, VL] = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget);
  6045. if (HasMergeOp)
  6046. Ops.push_back(DAG.getUNDEF(ContainerVT));
  6047. if (HasMask)
  6048. Ops.push_back(Mask);
  6049. Ops.push_back(VL);
  6050. SDValue ScalableRes =
  6051. DAG.getNode(NewOpc, DL, ContainerVT, Ops, Op->getFlags());
  6052. return convertFromScalableVector(VT, ScalableRes, DAG, Subtarget);
  6053. }
  6054. // Lower a VP_* ISD node to the corresponding RISCVISD::*_VL node:
  6055. // * Operands of each node are assumed to be in the same order.
  6056. // * The EVL operand is promoted from i32 to i64 on RV64.
  6057. // * Fixed-length vectors are converted to their scalable-vector container
  6058. // types.
  6059. SDValue RISCVTargetLowering::lowerVPOp(SDValue Op, SelectionDAG &DAG,
  6060. unsigned RISCVISDOpc,
  6061. bool HasMergeOp) const {
  6062. SDLoc DL(Op);
  6063. MVT VT = Op.getSimpleValueType();
  6064. SmallVector<SDValue, 4> Ops;
  6065. MVT ContainerVT = VT;
  6066. if (VT.isFixedLengthVector())
  6067. ContainerVT = getContainerForFixedLengthVector(VT);
  6068. for (const auto &OpIdx : enumerate(Op->ops())) {
  6069. SDValue V = OpIdx.value();
  6070. assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
  6071. // Add dummy merge value before the mask.
  6072. if (HasMergeOp && *ISD::getVPMaskIdx(Op.getOpcode()) == OpIdx.index())
  6073. Ops.push_back(DAG.getUNDEF(ContainerVT));
  6074. // Pass through operands which aren't fixed-length vectors.
  6075. if (!V.getValueType().isFixedLengthVector()) {
  6076. Ops.push_back(V);
  6077. continue;
  6078. }
  6079. // "cast" fixed length vector to a scalable vector.
  6080. MVT OpVT = V.getSimpleValueType();
  6081. MVT ContainerVT = getContainerForFixedLengthVector(OpVT);
  6082. assert(useRVVForFixedLengthVectorVT(OpVT) &&
  6083. "Only fixed length vectors are supported!");
  6084. Ops.push_back(convertToScalableVector(ContainerVT, V, DAG, Subtarget));
  6085. }
  6086. if (!VT.isFixedLengthVector())
  6087. return DAG.getNode(RISCVISDOpc, DL, VT, Ops, Op->getFlags());
  6088. SDValue VPOp = DAG.getNode(RISCVISDOpc, DL, ContainerVT, Ops, Op->getFlags());
  6089. return convertFromScalableVector(VT, VPOp, DAG, Subtarget);
  6090. }
  6091. SDValue RISCVTargetLowering::lowerVPExtMaskOp(SDValue Op,
  6092. SelectionDAG &DAG) const {
  6093. SDLoc DL(Op);
  6094. MVT VT = Op.getSimpleValueType();
  6095. SDValue Src = Op.getOperand(0);
  6096. // NOTE: Mask is dropped.
  6097. SDValue VL = Op.getOperand(2);
  6098. MVT ContainerVT = VT;
  6099. if (VT.isFixedLengthVector()) {
  6100. ContainerVT = getContainerForFixedLengthVector(VT);
  6101. MVT SrcVT = MVT::getVectorVT(MVT::i1, ContainerVT.getVectorElementCount());
  6102. Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
  6103. }
  6104. MVT XLenVT = Subtarget.getXLenVT();
  6105. SDValue Zero = DAG.getConstant(0, DL, XLenVT);
  6106. SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
  6107. DAG.getUNDEF(ContainerVT), Zero, VL);
  6108. SDValue SplatValue = DAG.getConstant(
  6109. Op.getOpcode() == ISD::VP_ZERO_EXTEND ? 1 : -1, DL, XLenVT);
  6110. SDValue Splat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
  6111. DAG.getUNDEF(ContainerVT), SplatValue, VL);
  6112. SDValue Result = DAG.getNode(RISCVISD::VSELECT_VL, DL, ContainerVT, Src,
  6113. Splat, ZeroSplat, VL);
  6114. if (!VT.isFixedLengthVector())
  6115. return Result;
  6116. return convertFromScalableVector(VT, Result, DAG, Subtarget);
  6117. }
  6118. SDValue RISCVTargetLowering::lowerVPSetCCMaskOp(SDValue Op,
  6119. SelectionDAG &DAG) const {
  6120. SDLoc DL(Op);
  6121. MVT VT = Op.getSimpleValueType();
  6122. SDValue Op1 = Op.getOperand(0);
  6123. SDValue Op2 = Op.getOperand(1);
  6124. ISD::CondCode Condition = cast<CondCodeSDNode>(Op.getOperand(2))->get();
  6125. // NOTE: Mask is dropped.
  6126. SDValue VL = Op.getOperand(4);
  6127. MVT ContainerVT = VT;
  6128. if (VT.isFixedLengthVector()) {
  6129. ContainerVT = getContainerForFixedLengthVector(VT);
  6130. Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
  6131. Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
  6132. }
  6133. SDValue Result;
  6134. SDValue AllOneMask = DAG.getNode(RISCVISD::VMSET_VL, DL, ContainerVT, VL);
  6135. switch (Condition) {
  6136. default:
  6137. break;
  6138. // X != Y --> (X^Y)
  6139. case ISD::SETNE:
  6140. Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
  6141. break;
  6142. // X == Y --> ~(X^Y)
  6143. case ISD::SETEQ: {
  6144. SDValue Temp =
  6145. DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, Op2, VL);
  6146. Result =
  6147. DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, AllOneMask, VL);
  6148. break;
  6149. }
  6150. // X >s Y --> X == 0 & Y == 1 --> ~X & Y
  6151. // X <u Y --> X == 0 & Y == 1 --> ~X & Y
  6152. case ISD::SETGT:
  6153. case ISD::SETULT: {
  6154. SDValue Temp =
  6155. DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
  6156. Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Temp, Op2, VL);
  6157. break;
  6158. }
  6159. // X <s Y --> X == 1 & Y == 0 --> ~Y & X
  6160. // X >u Y --> X == 1 & Y == 0 --> ~Y & X
  6161. case ISD::SETLT:
  6162. case ISD::SETUGT: {
  6163. SDValue Temp =
  6164. DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
  6165. Result = DAG.getNode(RISCVISD::VMAND_VL, DL, ContainerVT, Op1, Temp, VL);
  6166. break;
  6167. }
  6168. // X >=s Y --> X == 0 | Y == 1 --> ~X | Y
  6169. // X <=u Y --> X == 0 | Y == 1 --> ~X | Y
  6170. case ISD::SETGE:
  6171. case ISD::SETULE: {
  6172. SDValue Temp =
  6173. DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op1, AllOneMask, VL);
  6174. Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op2, VL);
  6175. break;
  6176. }
  6177. // X <=s Y --> X == 1 | Y == 0 --> ~Y | X
  6178. // X >=u Y --> X == 1 | Y == 0 --> ~Y | X
  6179. case ISD::SETLE:
  6180. case ISD::SETUGE: {
  6181. SDValue Temp =
  6182. DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Op2, AllOneMask, VL);
  6183. Result = DAG.getNode(RISCVISD::VMXOR_VL, DL, ContainerVT, Temp, Op1, VL);
  6184. break;
  6185. }
  6186. }
  6187. if (!VT.isFixedLengthVector())
  6188. return Result;
  6189. return convertFromScalableVector(VT, Result, DAG, Subtarget);
  6190. }
  6191. // Lower Floating-Point/Integer Type-Convert VP SDNodes
  6192. SDValue RISCVTargetLowering::lowerVPFPIntConvOp(SDValue Op, SelectionDAG &DAG,
  6193. unsigned RISCVISDOpc) const {
  6194. SDLoc DL(Op);
  6195. SDValue Src = Op.getOperand(0);
  6196. SDValue Mask = Op.getOperand(1);
  6197. SDValue VL = Op.getOperand(2);
  6198. MVT DstVT = Op.getSimpleValueType();
  6199. MVT SrcVT = Src.getSimpleValueType();
  6200. if (DstVT.isFixedLengthVector()) {
  6201. DstVT = getContainerForFixedLengthVector(DstVT);
  6202. SrcVT = getContainerForFixedLengthVector(SrcVT);
  6203. Src = convertToScalableVector(SrcVT, Src, DAG, Subtarget);
  6204. MVT MaskVT = getMaskTypeFor(DstVT);
  6205. Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
  6206. }
  6207. unsigned DstEltSize = DstVT.getScalarSizeInBits();
  6208. unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
  6209. SDValue Result;
  6210. if (DstEltSize >= SrcEltSize) { // Single-width and widening conversion.
  6211. if (SrcVT.isInteger()) {
  6212. assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
  6213. unsigned RISCVISDExtOpc = RISCVISDOpc == RISCVISD::SINT_TO_FP_VL
  6214. ? RISCVISD::VSEXT_VL
  6215. : RISCVISD::VZEXT_VL;
  6216. // Do we need to do any pre-widening before converting?
  6217. if (SrcEltSize == 1) {
  6218. MVT IntVT = DstVT.changeVectorElementTypeToInteger();
  6219. MVT XLenVT = Subtarget.getXLenVT();
  6220. SDValue Zero = DAG.getConstant(0, DL, XLenVT);
  6221. SDValue ZeroSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
  6222. DAG.getUNDEF(IntVT), Zero, VL);
  6223. SDValue One = DAG.getConstant(
  6224. RISCVISDExtOpc == RISCVISD::VZEXT_VL ? 1 : -1, DL, XLenVT);
  6225. SDValue OneSplat = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, IntVT,
  6226. DAG.getUNDEF(IntVT), One, VL);
  6227. Src = DAG.getNode(RISCVISD::VSELECT_VL, DL, IntVT, Src, OneSplat,
  6228. ZeroSplat, VL);
  6229. } else if (DstEltSize > (2 * SrcEltSize)) {
  6230. // Widen before converting.
  6231. MVT IntVT = MVT::getVectorVT(MVT::getIntegerVT(DstEltSize / 2),
  6232. DstVT.getVectorElementCount());
  6233. Src = DAG.getNode(RISCVISDExtOpc, DL, IntVT, Src, Mask, VL);
  6234. }
  6235. Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
  6236. } else {
  6237. assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
  6238. "Wrong input/output vector types");
  6239. // Convert f16 to f32 then convert f32 to i64.
  6240. if (DstEltSize > (2 * SrcEltSize)) {
  6241. assert(SrcVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
  6242. MVT InterimFVT =
  6243. MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
  6244. Src =
  6245. DAG.getNode(RISCVISD::FP_EXTEND_VL, DL, InterimFVT, Src, Mask, VL);
  6246. }
  6247. Result = DAG.getNode(RISCVISDOpc, DL, DstVT, Src, Mask, VL);
  6248. }
  6249. } else { // Narrowing + Conversion
  6250. if (SrcVT.isInteger()) {
  6251. assert(DstVT.isFloatingPoint() && "Wrong input/output vector types");
  6252. // First do a narrowing convert to an FP type half the size, then round
  6253. // the FP type to a small FP type if needed.
  6254. MVT InterimFVT = DstVT;
  6255. if (SrcEltSize > (2 * DstEltSize)) {
  6256. assert(SrcEltSize == (4 * DstEltSize) && "Unexpected types!");
  6257. assert(DstVT.getVectorElementType() == MVT::f16 && "Unexpected type!");
  6258. InterimFVT = MVT::getVectorVT(MVT::f32, DstVT.getVectorElementCount());
  6259. }
  6260. Result = DAG.getNode(RISCVISDOpc, DL, InterimFVT, Src, Mask, VL);
  6261. if (InterimFVT != DstVT) {
  6262. Src = Result;
  6263. Result = DAG.getNode(RISCVISD::FP_ROUND_VL, DL, DstVT, Src, Mask, VL);
  6264. }
  6265. } else {
  6266. assert(SrcVT.isFloatingPoint() && DstVT.isInteger() &&
  6267. "Wrong input/output vector types");
  6268. // First do a narrowing conversion to an integer half the size, then
  6269. // truncate if needed.
  6270. if (DstEltSize == 1) {
  6271. // First convert to the same size integer, then convert to mask using
  6272. // setcc.
  6273. assert(SrcEltSize >= 16 && "Unexpected FP type!");
  6274. MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize),
  6275. DstVT.getVectorElementCount());
  6276. Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
  6277. // Compare the integer result to 0. The integer should be 0 or 1/-1,
  6278. // otherwise the conversion was undefined.
  6279. MVT XLenVT = Subtarget.getXLenVT();
  6280. SDValue SplatZero = DAG.getConstant(0, DL, XLenVT);
  6281. SplatZero = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, InterimIVT,
  6282. DAG.getUNDEF(InterimIVT), SplatZero, VL);
  6283. Result = DAG.getNode(RISCVISD::SETCC_VL, DL, DstVT,
  6284. {Result, SplatZero, DAG.getCondCode(ISD::SETNE),
  6285. DAG.getUNDEF(DstVT), Mask, VL});
  6286. } else {
  6287. MVT InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
  6288. DstVT.getVectorElementCount());
  6289. Result = DAG.getNode(RISCVISDOpc, DL, InterimIVT, Src, Mask, VL);
  6290. while (InterimIVT != DstVT) {
  6291. SrcEltSize /= 2;
  6292. Src = Result;
  6293. InterimIVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize / 2),
  6294. DstVT.getVectorElementCount());
  6295. Result = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, InterimIVT,
  6296. Src, Mask, VL);
  6297. }
  6298. }
  6299. }
  6300. }
  6301. MVT VT = Op.getSimpleValueType();
  6302. if (!VT.isFixedLengthVector())
  6303. return Result;
  6304. return convertFromScalableVector(VT, Result, DAG, Subtarget);
  6305. }
  6306. SDValue RISCVTargetLowering::lowerLogicVPOp(SDValue Op, SelectionDAG &DAG,
  6307. unsigned MaskOpc,
  6308. unsigned VecOpc) const {
  6309. MVT VT = Op.getSimpleValueType();
  6310. if (VT.getVectorElementType() != MVT::i1)
  6311. return lowerVPOp(Op, DAG, VecOpc, true);
  6312. // It is safe to drop mask parameter as masked-off elements are undef.
  6313. SDValue Op1 = Op->getOperand(0);
  6314. SDValue Op2 = Op->getOperand(1);
  6315. SDValue VL = Op->getOperand(3);
  6316. MVT ContainerVT = VT;
  6317. const bool IsFixed = VT.isFixedLengthVector();
  6318. if (IsFixed) {
  6319. ContainerVT = getContainerForFixedLengthVector(VT);
  6320. Op1 = convertToScalableVector(ContainerVT, Op1, DAG, Subtarget);
  6321. Op2 = convertToScalableVector(ContainerVT, Op2, DAG, Subtarget);
  6322. }
  6323. SDLoc DL(Op);
  6324. SDValue Val = DAG.getNode(MaskOpc, DL, ContainerVT, Op1, Op2, VL);
  6325. if (!IsFixed)
  6326. return Val;
  6327. return convertFromScalableVector(VT, Val, DAG, Subtarget);
  6328. }
  6329. SDValue RISCVTargetLowering::lowerVPStridedLoad(SDValue Op,
  6330. SelectionDAG &DAG) const {
  6331. SDLoc DL(Op);
  6332. MVT XLenVT = Subtarget.getXLenVT();
  6333. MVT VT = Op.getSimpleValueType();
  6334. MVT ContainerVT = VT;
  6335. if (VT.isFixedLengthVector())
  6336. ContainerVT = getContainerForFixedLengthVector(VT);
  6337. SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
  6338. auto *VPNode = cast<VPStridedLoadSDNode>(Op);
  6339. // Check if the mask is known to be all ones
  6340. SDValue Mask = VPNode->getMask();
  6341. bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
  6342. SDValue IntID = DAG.getTargetConstant(IsUnmasked ? Intrinsic::riscv_vlse
  6343. : Intrinsic::riscv_vlse_mask,
  6344. DL, XLenVT);
  6345. SmallVector<SDValue, 8> Ops{VPNode->getChain(), IntID,
  6346. DAG.getUNDEF(ContainerVT), VPNode->getBasePtr(),
  6347. VPNode->getStride()};
  6348. if (!IsUnmasked) {
  6349. if (VT.isFixedLengthVector()) {
  6350. MVT MaskVT = ContainerVT.changeVectorElementType(MVT::i1);
  6351. Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
  6352. }
  6353. Ops.push_back(Mask);
  6354. }
  6355. Ops.push_back(VPNode->getVectorLength());
  6356. if (!IsUnmasked) {
  6357. SDValue Policy = DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT);
  6358. Ops.push_back(Policy);
  6359. }
  6360. SDValue Result =
  6361. DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops,
  6362. VPNode->getMemoryVT(), VPNode->getMemOperand());
  6363. SDValue Chain = Result.getValue(1);
  6364. if (VT.isFixedLengthVector())
  6365. Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
  6366. return DAG.getMergeValues({Result, Chain}, DL);
  6367. }
  6368. SDValue RISCVTargetLowering::lowerVPStridedStore(SDValue Op,
  6369. SelectionDAG &DAG) const {
  6370. SDLoc DL(Op);
  6371. MVT XLenVT = Subtarget.getXLenVT();
  6372. auto *VPNode = cast<VPStridedStoreSDNode>(Op);
  6373. SDValue StoreVal = VPNode->getValue();
  6374. MVT VT = StoreVal.getSimpleValueType();
  6375. MVT ContainerVT = VT;
  6376. if (VT.isFixedLengthVector()) {
  6377. ContainerVT = getContainerForFixedLengthVector(VT);
  6378. StoreVal = convertToScalableVector(ContainerVT, StoreVal, DAG, Subtarget);
  6379. }
  6380. // Check if the mask is known to be all ones
  6381. SDValue Mask = VPNode->getMask();
  6382. bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
  6383. SDValue IntID = DAG.getTargetConstant(IsUnmasked ? Intrinsic::riscv_vsse
  6384. : Intrinsic::riscv_vsse_mask,
  6385. DL, XLenVT);
  6386. SmallVector<SDValue, 8> Ops{VPNode->getChain(), IntID, StoreVal,
  6387. VPNode->getBasePtr(), VPNode->getStride()};
  6388. if (!IsUnmasked) {
  6389. if (VT.isFixedLengthVector()) {
  6390. MVT MaskVT = ContainerVT.changeVectorElementType(MVT::i1);
  6391. Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
  6392. }
  6393. Ops.push_back(Mask);
  6394. }
  6395. Ops.push_back(VPNode->getVectorLength());
  6396. return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL, VPNode->getVTList(),
  6397. Ops, VPNode->getMemoryVT(),
  6398. VPNode->getMemOperand());
  6399. }
  6400. // Custom lower MGATHER/VP_GATHER to a legalized form for RVV. It will then be
  6401. // matched to a RVV indexed load. The RVV indexed load instructions only
  6402. // support the "unsigned unscaled" addressing mode; indices are implicitly
  6403. // zero-extended or truncated to XLEN and are treated as byte offsets. Any
  6404. // signed or scaled indexing is extended to the XLEN value type and scaled
  6405. // accordingly.
  6406. SDValue RISCVTargetLowering::lowerMaskedGather(SDValue Op,
  6407. SelectionDAG &DAG) const {
  6408. SDLoc DL(Op);
  6409. MVT VT = Op.getSimpleValueType();
  6410. const auto *MemSD = cast<MemSDNode>(Op.getNode());
  6411. EVT MemVT = MemSD->getMemoryVT();
  6412. MachineMemOperand *MMO = MemSD->getMemOperand();
  6413. SDValue Chain = MemSD->getChain();
  6414. SDValue BasePtr = MemSD->getBasePtr();
  6415. ISD::LoadExtType LoadExtType;
  6416. SDValue Index, Mask, PassThru, VL;
  6417. if (auto *VPGN = dyn_cast<VPGatherSDNode>(Op.getNode())) {
  6418. Index = VPGN->getIndex();
  6419. Mask = VPGN->getMask();
  6420. PassThru = DAG.getUNDEF(VT);
  6421. VL = VPGN->getVectorLength();
  6422. // VP doesn't support extending loads.
  6423. LoadExtType = ISD::NON_EXTLOAD;
  6424. } else {
  6425. // Else it must be a MGATHER.
  6426. auto *MGN = cast<MaskedGatherSDNode>(Op.getNode());
  6427. Index = MGN->getIndex();
  6428. Mask = MGN->getMask();
  6429. PassThru = MGN->getPassThru();
  6430. LoadExtType = MGN->getExtensionType();
  6431. }
  6432. MVT IndexVT = Index.getSimpleValueType();
  6433. MVT XLenVT = Subtarget.getXLenVT();
  6434. assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
  6435. "Unexpected VTs!");
  6436. assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
  6437. // Targets have to explicitly opt-in for extending vector loads.
  6438. assert(LoadExtType == ISD::NON_EXTLOAD &&
  6439. "Unexpected extending MGATHER/VP_GATHER");
  6440. (void)LoadExtType;
  6441. // If the mask is known to be all ones, optimize to an unmasked intrinsic;
  6442. // the selection of the masked intrinsics doesn't do this for us.
  6443. bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
  6444. MVT ContainerVT = VT;
  6445. if (VT.isFixedLengthVector()) {
  6446. ContainerVT = getContainerForFixedLengthVector(VT);
  6447. IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
  6448. ContainerVT.getVectorElementCount());
  6449. Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
  6450. if (!IsUnmasked) {
  6451. MVT MaskVT = getMaskTypeFor(ContainerVT);
  6452. Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
  6453. PassThru = convertToScalableVector(ContainerVT, PassThru, DAG, Subtarget);
  6454. }
  6455. }
  6456. if (!VL)
  6457. VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
  6458. if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
  6459. IndexVT = IndexVT.changeVectorElementType(XLenVT);
  6460. SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
  6461. VL);
  6462. Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
  6463. TrueMask, VL);
  6464. }
  6465. unsigned IntID =
  6466. IsUnmasked ? Intrinsic::riscv_vluxei : Intrinsic::riscv_vluxei_mask;
  6467. SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
  6468. if (IsUnmasked)
  6469. Ops.push_back(DAG.getUNDEF(ContainerVT));
  6470. else
  6471. Ops.push_back(PassThru);
  6472. Ops.push_back(BasePtr);
  6473. Ops.push_back(Index);
  6474. if (!IsUnmasked)
  6475. Ops.push_back(Mask);
  6476. Ops.push_back(VL);
  6477. if (!IsUnmasked)
  6478. Ops.push_back(DAG.getTargetConstant(RISCVII::TAIL_AGNOSTIC, DL, XLenVT));
  6479. SDVTList VTs = DAG.getVTList({ContainerVT, MVT::Other});
  6480. SDValue Result =
  6481. DAG.getMemIntrinsicNode(ISD::INTRINSIC_W_CHAIN, DL, VTs, Ops, MemVT, MMO);
  6482. Chain = Result.getValue(1);
  6483. if (VT.isFixedLengthVector())
  6484. Result = convertFromScalableVector(VT, Result, DAG, Subtarget);
  6485. return DAG.getMergeValues({Result, Chain}, DL);
  6486. }
  6487. // Custom lower MSCATTER/VP_SCATTER to a legalized form for RVV. It will then be
  6488. // matched to a RVV indexed store. The RVV indexed store instructions only
  6489. // support the "unsigned unscaled" addressing mode; indices are implicitly
  6490. // zero-extended or truncated to XLEN and are treated as byte offsets. Any
  6491. // signed or scaled indexing is extended to the XLEN value type and scaled
  6492. // accordingly.
  6493. SDValue RISCVTargetLowering::lowerMaskedScatter(SDValue Op,
  6494. SelectionDAG &DAG) const {
  6495. SDLoc DL(Op);
  6496. const auto *MemSD = cast<MemSDNode>(Op.getNode());
  6497. EVT MemVT = MemSD->getMemoryVT();
  6498. MachineMemOperand *MMO = MemSD->getMemOperand();
  6499. SDValue Chain = MemSD->getChain();
  6500. SDValue BasePtr = MemSD->getBasePtr();
  6501. bool IsTruncatingStore = false;
  6502. SDValue Index, Mask, Val, VL;
  6503. if (auto *VPSN = dyn_cast<VPScatterSDNode>(Op.getNode())) {
  6504. Index = VPSN->getIndex();
  6505. Mask = VPSN->getMask();
  6506. Val = VPSN->getValue();
  6507. VL = VPSN->getVectorLength();
  6508. // VP doesn't support truncating stores.
  6509. IsTruncatingStore = false;
  6510. } else {
  6511. // Else it must be a MSCATTER.
  6512. auto *MSN = cast<MaskedScatterSDNode>(Op.getNode());
  6513. Index = MSN->getIndex();
  6514. Mask = MSN->getMask();
  6515. Val = MSN->getValue();
  6516. IsTruncatingStore = MSN->isTruncatingStore();
  6517. }
  6518. MVT VT = Val.getSimpleValueType();
  6519. MVT IndexVT = Index.getSimpleValueType();
  6520. MVT XLenVT = Subtarget.getXLenVT();
  6521. assert(VT.getVectorElementCount() == IndexVT.getVectorElementCount() &&
  6522. "Unexpected VTs!");
  6523. assert(BasePtr.getSimpleValueType() == XLenVT && "Unexpected pointer type");
  6524. // Targets have to explicitly opt-in for extending vector loads and
  6525. // truncating vector stores.
  6526. assert(!IsTruncatingStore && "Unexpected truncating MSCATTER/VP_SCATTER");
  6527. (void)IsTruncatingStore;
  6528. // If the mask is known to be all ones, optimize to an unmasked intrinsic;
  6529. // the selection of the masked intrinsics doesn't do this for us.
  6530. bool IsUnmasked = ISD::isConstantSplatVectorAllOnes(Mask.getNode());
  6531. MVT ContainerVT = VT;
  6532. if (VT.isFixedLengthVector()) {
  6533. ContainerVT = getContainerForFixedLengthVector(VT);
  6534. IndexVT = MVT::getVectorVT(IndexVT.getVectorElementType(),
  6535. ContainerVT.getVectorElementCount());
  6536. Index = convertToScalableVector(IndexVT, Index, DAG, Subtarget);
  6537. Val = convertToScalableVector(ContainerVT, Val, DAG, Subtarget);
  6538. if (!IsUnmasked) {
  6539. MVT MaskVT = getMaskTypeFor(ContainerVT);
  6540. Mask = convertToScalableVector(MaskVT, Mask, DAG, Subtarget);
  6541. }
  6542. }
  6543. if (!VL)
  6544. VL = getDefaultVLOps(VT, ContainerVT, DL, DAG, Subtarget).second;
  6545. if (XLenVT == MVT::i32 && IndexVT.getVectorElementType().bitsGT(XLenVT)) {
  6546. IndexVT = IndexVT.changeVectorElementType(XLenVT);
  6547. SDValue TrueMask = DAG.getNode(RISCVISD::VMSET_VL, DL, Mask.getValueType(),
  6548. VL);
  6549. Index = DAG.getNode(RISCVISD::TRUNCATE_VECTOR_VL, DL, IndexVT, Index,
  6550. TrueMask, VL);
  6551. }
  6552. unsigned IntID =
  6553. IsUnmasked ? Intrinsic::riscv_vsoxei : Intrinsic::riscv_vsoxei_mask;
  6554. SmallVector<SDValue, 8> Ops{Chain, DAG.getTargetConstant(IntID, DL, XLenVT)};
  6555. Ops.push_back(Val);
  6556. Ops.push_back(BasePtr);
  6557. Ops.push_back(Index);
  6558. if (!IsUnmasked)
  6559. Ops.push_back(Mask);
  6560. Ops.push_back(VL);
  6561. return DAG.getMemIntrinsicNode(ISD::INTRINSIC_VOID, DL,
  6562. DAG.getVTList(MVT::Other), Ops, MemVT, MMO);
  6563. }
  6564. SDValue RISCVTargetLowering::lowerGET_ROUNDING(SDValue Op,
  6565. SelectionDAG &DAG) const {
  6566. const MVT XLenVT = Subtarget.getXLenVT();
  6567. SDLoc DL(Op);
  6568. SDValue Chain = Op->getOperand(0);
  6569. SDValue SysRegNo = DAG.getTargetConstant(
  6570. RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
  6571. SDVTList VTs = DAG.getVTList(XLenVT, MVT::Other);
  6572. SDValue RM = DAG.getNode(RISCVISD::READ_CSR, DL, VTs, Chain, SysRegNo);
  6573. // Encoding used for rounding mode in RISCV differs from that used in
  6574. // FLT_ROUNDS. To convert it the RISCV rounding mode is used as an index in a
  6575. // table, which consists of a sequence of 4-bit fields, each representing
  6576. // corresponding FLT_ROUNDS mode.
  6577. static const int Table =
  6578. (int(RoundingMode::NearestTiesToEven) << 4 * RISCVFPRndMode::RNE) |
  6579. (int(RoundingMode::TowardZero) << 4 * RISCVFPRndMode::RTZ) |
  6580. (int(RoundingMode::TowardNegative) << 4 * RISCVFPRndMode::RDN) |
  6581. (int(RoundingMode::TowardPositive) << 4 * RISCVFPRndMode::RUP) |
  6582. (int(RoundingMode::NearestTiesToAway) << 4 * RISCVFPRndMode::RMM);
  6583. SDValue Shift =
  6584. DAG.getNode(ISD::SHL, DL, XLenVT, RM, DAG.getConstant(2, DL, XLenVT));
  6585. SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
  6586. DAG.getConstant(Table, DL, XLenVT), Shift);
  6587. SDValue Masked = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
  6588. DAG.getConstant(7, DL, XLenVT));
  6589. return DAG.getMergeValues({Masked, Chain}, DL);
  6590. }
  6591. SDValue RISCVTargetLowering::lowerSET_ROUNDING(SDValue Op,
  6592. SelectionDAG &DAG) const {
  6593. const MVT XLenVT = Subtarget.getXLenVT();
  6594. SDLoc DL(Op);
  6595. SDValue Chain = Op->getOperand(0);
  6596. SDValue RMValue = Op->getOperand(1);
  6597. SDValue SysRegNo = DAG.getTargetConstant(
  6598. RISCVSysReg::lookupSysRegByName("FRM")->Encoding, DL, XLenVT);
  6599. // Encoding used for rounding mode in RISCV differs from that used in
  6600. // FLT_ROUNDS. To convert it the C rounding mode is used as an index in
  6601. // a table, which consists of a sequence of 4-bit fields, each representing
  6602. // corresponding RISCV mode.
  6603. static const unsigned Table =
  6604. (RISCVFPRndMode::RNE << 4 * int(RoundingMode::NearestTiesToEven)) |
  6605. (RISCVFPRndMode::RTZ << 4 * int(RoundingMode::TowardZero)) |
  6606. (RISCVFPRndMode::RDN << 4 * int(RoundingMode::TowardNegative)) |
  6607. (RISCVFPRndMode::RUP << 4 * int(RoundingMode::TowardPositive)) |
  6608. (RISCVFPRndMode::RMM << 4 * int(RoundingMode::NearestTiesToAway));
  6609. SDValue Shift = DAG.getNode(ISD::SHL, DL, XLenVT, RMValue,
  6610. DAG.getConstant(2, DL, XLenVT));
  6611. SDValue Shifted = DAG.getNode(ISD::SRL, DL, XLenVT,
  6612. DAG.getConstant(Table, DL, XLenVT), Shift);
  6613. RMValue = DAG.getNode(ISD::AND, DL, XLenVT, Shifted,
  6614. DAG.getConstant(0x7, DL, XLenVT));
  6615. return DAG.getNode(RISCVISD::WRITE_CSR, DL, MVT::Other, Chain, SysRegNo,
  6616. RMValue);
  6617. }
  6618. SDValue RISCVTargetLowering::lowerEH_DWARF_CFA(SDValue Op,
  6619. SelectionDAG &DAG) const {
  6620. MachineFunction &MF = DAG.getMachineFunction();
  6621. bool isRISCV64 = Subtarget.is64Bit();
  6622. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6623. int FI = MF.getFrameInfo().CreateFixedObject(isRISCV64 ? 8 : 4, 0, false);
  6624. return DAG.getFrameIndex(FI, PtrVT);
  6625. }
  6626. // Returns the opcode of the target-specific SDNode that implements the 32-bit
  6627. // form of the given Opcode.
  6628. static RISCVISD::NodeType getRISCVWOpcode(unsigned Opcode) {
  6629. switch (Opcode) {
  6630. default:
  6631. llvm_unreachable("Unexpected opcode");
  6632. case ISD::SHL:
  6633. return RISCVISD::SLLW;
  6634. case ISD::SRA:
  6635. return RISCVISD::SRAW;
  6636. case ISD::SRL:
  6637. return RISCVISD::SRLW;
  6638. case ISD::SDIV:
  6639. return RISCVISD::DIVW;
  6640. case ISD::UDIV:
  6641. return RISCVISD::DIVUW;
  6642. case ISD::UREM:
  6643. return RISCVISD::REMUW;
  6644. case ISD::ROTL:
  6645. return RISCVISD::ROLW;
  6646. case ISD::ROTR:
  6647. return RISCVISD::RORW;
  6648. }
  6649. }
  6650. // Converts the given i8/i16/i32 operation to a target-specific SelectionDAG
  6651. // node. Because i8/i16/i32 isn't a legal type for RV64, these operations would
  6652. // otherwise be promoted to i64, making it difficult to select the
  6653. // SLLW/DIVUW/.../*W later one because the fact the operation was originally of
  6654. // type i8/i16/i32 is lost.
  6655. static SDValue customLegalizeToWOp(SDNode *N, SelectionDAG &DAG,
  6656. unsigned ExtOpc = ISD::ANY_EXTEND) {
  6657. SDLoc DL(N);
  6658. RISCVISD::NodeType WOpcode = getRISCVWOpcode(N->getOpcode());
  6659. SDValue NewOp0 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(0));
  6660. SDValue NewOp1 = DAG.getNode(ExtOpc, DL, MVT::i64, N->getOperand(1));
  6661. SDValue NewRes = DAG.getNode(WOpcode, DL, MVT::i64, NewOp0, NewOp1);
  6662. // ReplaceNodeResults requires we maintain the same type for the return value.
  6663. return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewRes);
  6664. }
  6665. // Converts the given 32-bit operation to a i64 operation with signed extension
  6666. // semantic to reduce the signed extension instructions.
  6667. static SDValue customLegalizeToWOpWithSExt(SDNode *N, SelectionDAG &DAG) {
  6668. SDLoc DL(N);
  6669. SDValue NewOp0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
  6670. SDValue NewOp1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
  6671. SDValue NewWOp = DAG.getNode(N->getOpcode(), DL, MVT::i64, NewOp0, NewOp1);
  6672. SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
  6673. DAG.getValueType(MVT::i32));
  6674. return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes);
  6675. }
  6676. void RISCVTargetLowering::ReplaceNodeResults(SDNode *N,
  6677. SmallVectorImpl<SDValue> &Results,
  6678. SelectionDAG &DAG) const {
  6679. SDLoc DL(N);
  6680. switch (N->getOpcode()) {
  6681. default:
  6682. llvm_unreachable("Don't know how to custom type legalize this operation!");
  6683. case ISD::STRICT_FP_TO_SINT:
  6684. case ISD::STRICT_FP_TO_UINT:
  6685. case ISD::FP_TO_SINT:
  6686. case ISD::FP_TO_UINT: {
  6687. assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
  6688. "Unexpected custom legalisation");
  6689. bool IsStrict = N->isStrictFPOpcode();
  6690. bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT ||
  6691. N->getOpcode() == ISD::STRICT_FP_TO_SINT;
  6692. SDValue Op0 = IsStrict ? N->getOperand(1) : N->getOperand(0);
  6693. if (getTypeAction(*DAG.getContext(), Op0.getValueType()) !=
  6694. TargetLowering::TypeSoftenFloat) {
  6695. if (!isTypeLegal(Op0.getValueType()))
  6696. return;
  6697. if (IsStrict) {
  6698. SDValue Chain = N->getOperand(0);
  6699. // In absense of Zfh, promote f16 to f32, then convert.
  6700. if (Op0.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh()) {
  6701. Op0 = DAG.getNode(ISD::STRICT_FP_EXTEND, DL, {MVT::f32, MVT::Other},
  6702. {Chain, Op0});
  6703. Chain = Op0.getValue(1);
  6704. }
  6705. unsigned Opc = IsSigned ? RISCVISD::STRICT_FCVT_W_RV64
  6706. : RISCVISD::STRICT_FCVT_WU_RV64;
  6707. SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
  6708. SDValue Res = DAG.getNode(
  6709. Opc, DL, VTs, Chain, Op0,
  6710. DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
  6711. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
  6712. Results.push_back(Res.getValue(1));
  6713. return;
  6714. }
  6715. // In absense of Zfh, promote f16 to f32, then convert.
  6716. if (Op0.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
  6717. Op0 = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, Op0);
  6718. unsigned Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
  6719. SDValue Res =
  6720. DAG.getNode(Opc, DL, MVT::i64, Op0,
  6721. DAG.getTargetConstant(RISCVFPRndMode::RTZ, DL, MVT::i64));
  6722. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
  6723. return;
  6724. }
  6725. // If the FP type needs to be softened, emit a library call using the 'si'
  6726. // version. If we left it to default legalization we'd end up with 'di'. If
  6727. // the FP type doesn't need to be softened just let generic type
  6728. // legalization promote the result type.
  6729. RTLIB::Libcall LC;
  6730. if (IsSigned)
  6731. LC = RTLIB::getFPTOSINT(Op0.getValueType(), N->getValueType(0));
  6732. else
  6733. LC = RTLIB::getFPTOUINT(Op0.getValueType(), N->getValueType(0));
  6734. MakeLibCallOptions CallOptions;
  6735. EVT OpVT = Op0.getValueType();
  6736. CallOptions.setTypeListBeforeSoften(OpVT, N->getValueType(0), true);
  6737. SDValue Chain = IsStrict ? N->getOperand(0) : SDValue();
  6738. SDValue Result;
  6739. std::tie(Result, Chain) =
  6740. makeLibCall(DAG, LC, N->getValueType(0), Op0, CallOptions, DL, Chain);
  6741. Results.push_back(Result);
  6742. if (IsStrict)
  6743. Results.push_back(Chain);
  6744. break;
  6745. }
  6746. case ISD::READCYCLECOUNTER: {
  6747. assert(!Subtarget.is64Bit() &&
  6748. "READCYCLECOUNTER only has custom type legalization on riscv32");
  6749. SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32, MVT::Other);
  6750. SDValue RCW =
  6751. DAG.getNode(RISCVISD::READ_CYCLE_WIDE, DL, VTs, N->getOperand(0));
  6752. Results.push_back(
  6753. DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, RCW, RCW.getValue(1)));
  6754. Results.push_back(RCW.getValue(2));
  6755. break;
  6756. }
  6757. case ISD::LOAD: {
  6758. if (!ISD::isNON_EXTLoad(N))
  6759. return;
  6760. // Use a SEXTLOAD instead of the default EXTLOAD. Similar to the
  6761. // sext_inreg we emit for ADD/SUB/MUL/SLLI.
  6762. LoadSDNode *Ld = cast<LoadSDNode>(N);
  6763. SDLoc dl(N);
  6764. SDValue Res = DAG.getExtLoad(ISD::SEXTLOAD, dl, MVT::i64, Ld->getChain(),
  6765. Ld->getBasePtr(), Ld->getMemoryVT(),
  6766. Ld->getMemOperand());
  6767. Results.push_back(DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, Res));
  6768. Results.push_back(Res.getValue(1));
  6769. return;
  6770. }
  6771. case ISD::MUL: {
  6772. unsigned Size = N->getSimpleValueType(0).getSizeInBits();
  6773. unsigned XLen = Subtarget.getXLen();
  6774. // This multiply needs to be expanded, try to use MULHSU+MUL if possible.
  6775. if (Size > XLen) {
  6776. assert(Size == (XLen * 2) && "Unexpected custom legalisation");
  6777. SDValue LHS = N->getOperand(0);
  6778. SDValue RHS = N->getOperand(1);
  6779. APInt HighMask = APInt::getHighBitsSet(Size, XLen);
  6780. bool LHSIsU = DAG.MaskedValueIsZero(LHS, HighMask);
  6781. bool RHSIsU = DAG.MaskedValueIsZero(RHS, HighMask);
  6782. // We need exactly one side to be unsigned.
  6783. if (LHSIsU == RHSIsU)
  6784. return;
  6785. auto MakeMULPair = [&](SDValue S, SDValue U) {
  6786. MVT XLenVT = Subtarget.getXLenVT();
  6787. S = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, S);
  6788. U = DAG.getNode(ISD::TRUNCATE, DL, XLenVT, U);
  6789. SDValue Lo = DAG.getNode(ISD::MUL, DL, XLenVT, S, U);
  6790. SDValue Hi = DAG.getNode(RISCVISD::MULHSU, DL, XLenVT, S, U);
  6791. return DAG.getNode(ISD::BUILD_PAIR, DL, N->getValueType(0), Lo, Hi);
  6792. };
  6793. bool LHSIsS = DAG.ComputeNumSignBits(LHS) > XLen;
  6794. bool RHSIsS = DAG.ComputeNumSignBits(RHS) > XLen;
  6795. // The other operand should be signed, but still prefer MULH when
  6796. // possible.
  6797. if (RHSIsU && LHSIsS && !RHSIsS)
  6798. Results.push_back(MakeMULPair(LHS, RHS));
  6799. else if (LHSIsU && RHSIsS && !LHSIsS)
  6800. Results.push_back(MakeMULPair(RHS, LHS));
  6801. return;
  6802. }
  6803. [[fallthrough]];
  6804. }
  6805. case ISD::ADD:
  6806. case ISD::SUB:
  6807. assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
  6808. "Unexpected custom legalisation");
  6809. Results.push_back(customLegalizeToWOpWithSExt(N, DAG));
  6810. break;
  6811. case ISD::SHL:
  6812. case ISD::SRA:
  6813. case ISD::SRL:
  6814. assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
  6815. "Unexpected custom legalisation");
  6816. if (N->getOperand(1).getOpcode() != ISD::Constant) {
  6817. // If we can use a BSET instruction, allow default promotion to apply.
  6818. if (N->getOpcode() == ISD::SHL && Subtarget.hasStdExtZbs() &&
  6819. isOneConstant(N->getOperand(0)))
  6820. break;
  6821. Results.push_back(customLegalizeToWOp(N, DAG));
  6822. break;
  6823. }
  6824. // Custom legalize ISD::SHL by placing a SIGN_EXTEND_INREG after. This is
  6825. // similar to customLegalizeToWOpWithSExt, but we must zero_extend the
  6826. // shift amount.
  6827. if (N->getOpcode() == ISD::SHL) {
  6828. SDLoc DL(N);
  6829. SDValue NewOp0 =
  6830. DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
  6831. SDValue NewOp1 =
  6832. DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N->getOperand(1));
  6833. SDValue NewWOp = DAG.getNode(ISD::SHL, DL, MVT::i64, NewOp0, NewOp1);
  6834. SDValue NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewWOp,
  6835. DAG.getValueType(MVT::i32));
  6836. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
  6837. }
  6838. break;
  6839. case ISD::ROTL:
  6840. case ISD::ROTR:
  6841. assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
  6842. "Unexpected custom legalisation");
  6843. Results.push_back(customLegalizeToWOp(N, DAG));
  6844. break;
  6845. case ISD::CTTZ:
  6846. case ISD::CTTZ_ZERO_UNDEF:
  6847. case ISD::CTLZ:
  6848. case ISD::CTLZ_ZERO_UNDEF: {
  6849. assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
  6850. "Unexpected custom legalisation");
  6851. SDValue NewOp0 =
  6852. DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
  6853. bool IsCTZ =
  6854. N->getOpcode() == ISD::CTTZ || N->getOpcode() == ISD::CTTZ_ZERO_UNDEF;
  6855. unsigned Opc = IsCTZ ? RISCVISD::CTZW : RISCVISD::CLZW;
  6856. SDValue Res = DAG.getNode(Opc, DL, MVT::i64, NewOp0);
  6857. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
  6858. return;
  6859. }
  6860. case ISD::SDIV:
  6861. case ISD::UDIV:
  6862. case ISD::UREM: {
  6863. MVT VT = N->getSimpleValueType(0);
  6864. assert((VT == MVT::i8 || VT == MVT::i16 || VT == MVT::i32) &&
  6865. Subtarget.is64Bit() && Subtarget.hasStdExtM() &&
  6866. "Unexpected custom legalisation");
  6867. // Don't promote division/remainder by constant since we should expand those
  6868. // to multiply by magic constant.
  6869. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  6870. if (N->getOperand(1).getOpcode() == ISD::Constant &&
  6871. !isIntDivCheap(N->getValueType(0), Attr))
  6872. return;
  6873. // If the input is i32, use ANY_EXTEND since the W instructions don't read
  6874. // the upper 32 bits. For other types we need to sign or zero extend
  6875. // based on the opcode.
  6876. unsigned ExtOpc = ISD::ANY_EXTEND;
  6877. if (VT != MVT::i32)
  6878. ExtOpc = N->getOpcode() == ISD::SDIV ? ISD::SIGN_EXTEND
  6879. : ISD::ZERO_EXTEND;
  6880. Results.push_back(customLegalizeToWOp(N, DAG, ExtOpc));
  6881. break;
  6882. }
  6883. case ISD::UADDO:
  6884. case ISD::USUBO: {
  6885. assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
  6886. "Unexpected custom legalisation");
  6887. bool IsAdd = N->getOpcode() == ISD::UADDO;
  6888. // Create an ADDW or SUBW.
  6889. SDValue LHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
  6890. SDValue RHS = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
  6891. SDValue Res =
  6892. DAG.getNode(IsAdd ? ISD::ADD : ISD::SUB, DL, MVT::i64, LHS, RHS);
  6893. Res = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Res,
  6894. DAG.getValueType(MVT::i32));
  6895. SDValue Overflow;
  6896. if (IsAdd && isOneConstant(RHS)) {
  6897. // Special case uaddo X, 1 overflowed if the addition result is 0.
  6898. // The general case (X + C) < C is not necessarily beneficial. Although we
  6899. // reduce the live range of X, we may introduce the materialization of
  6900. // constant C, especially when the setcc result is used by branch. We have
  6901. // no compare with constant and branch instructions.
  6902. Overflow = DAG.getSetCC(DL, N->getValueType(1), Res,
  6903. DAG.getConstant(0, DL, MVT::i64), ISD::SETEQ);
  6904. } else {
  6905. // Sign extend the LHS and perform an unsigned compare with the ADDW
  6906. // result. Since the inputs are sign extended from i32, this is equivalent
  6907. // to comparing the lower 32 bits.
  6908. LHS = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
  6909. Overflow = DAG.getSetCC(DL, N->getValueType(1), Res, LHS,
  6910. IsAdd ? ISD::SETULT : ISD::SETUGT);
  6911. }
  6912. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
  6913. Results.push_back(Overflow);
  6914. return;
  6915. }
  6916. case ISD::UADDSAT:
  6917. case ISD::USUBSAT: {
  6918. assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
  6919. "Unexpected custom legalisation");
  6920. if (Subtarget.hasStdExtZbb()) {
  6921. // With Zbb we can sign extend and let LegalizeDAG use minu/maxu. Using
  6922. // sign extend allows overflow of the lower 32 bits to be detected on
  6923. // the promoted size.
  6924. SDValue LHS =
  6925. DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(0));
  6926. SDValue RHS =
  6927. DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, N->getOperand(1));
  6928. SDValue Res = DAG.getNode(N->getOpcode(), DL, MVT::i64, LHS, RHS);
  6929. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
  6930. return;
  6931. }
  6932. // Without Zbb, expand to UADDO/USUBO+select which will trigger our custom
  6933. // promotion for UADDO/USUBO.
  6934. Results.push_back(expandAddSubSat(N, DAG));
  6935. return;
  6936. }
  6937. case ISD::ABS: {
  6938. assert(N->getValueType(0) == MVT::i32 && Subtarget.is64Bit() &&
  6939. "Unexpected custom legalisation");
  6940. if (Subtarget.hasStdExtZbb()) {
  6941. // Emit a special ABSW node that will be expanded to NEGW+MAX at isel.
  6942. // This allows us to remember that the result is sign extended. Expanding
  6943. // to NEGW+MAX here requires a Freeze which breaks ComputeNumSignBits.
  6944. SDValue Src = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64,
  6945. N->getOperand(0));
  6946. SDValue Abs = DAG.getNode(RISCVISD::ABSW, DL, MVT::i64, Src);
  6947. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Abs));
  6948. return;
  6949. }
  6950. // Expand abs to Y = (sraiw X, 31); subw(xor(X, Y), Y)
  6951. SDValue Src = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(0));
  6952. // Freeze the source so we can increase it's use count.
  6953. Src = DAG.getFreeze(Src);
  6954. // Copy sign bit to all bits using the sraiw pattern.
  6955. SDValue SignFill = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, Src,
  6956. DAG.getValueType(MVT::i32));
  6957. SignFill = DAG.getNode(ISD::SRA, DL, MVT::i64, SignFill,
  6958. DAG.getConstant(31, DL, MVT::i64));
  6959. SDValue NewRes = DAG.getNode(ISD::XOR, DL, MVT::i64, Src, SignFill);
  6960. NewRes = DAG.getNode(ISD::SUB, DL, MVT::i64, NewRes, SignFill);
  6961. // NOTE: The result is only required to be anyextended, but sext is
  6962. // consistent with type legalization of sub.
  6963. NewRes = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, NewRes,
  6964. DAG.getValueType(MVT::i32));
  6965. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, NewRes));
  6966. return;
  6967. }
  6968. case ISD::BITCAST: {
  6969. EVT VT = N->getValueType(0);
  6970. assert(VT.isInteger() && !VT.isVector() && "Unexpected VT!");
  6971. SDValue Op0 = N->getOperand(0);
  6972. EVT Op0VT = Op0.getValueType();
  6973. MVT XLenVT = Subtarget.getXLenVT();
  6974. if (VT == MVT::i16 && Op0VT == MVT::f16 &&
  6975. Subtarget.hasStdExtZfhOrZfhmin()) {
  6976. SDValue FPConv = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, XLenVT, Op0);
  6977. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, FPConv));
  6978. } else if (VT == MVT::i32 && Op0VT == MVT::f32 && Subtarget.is64Bit() &&
  6979. Subtarget.hasStdExtF()) {
  6980. SDValue FPConv =
  6981. DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Op0);
  6982. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, FPConv));
  6983. } else if (!VT.isVector() && Op0VT.isFixedLengthVector() &&
  6984. isTypeLegal(Op0VT)) {
  6985. // Custom-legalize bitcasts from fixed-length vector types to illegal
  6986. // scalar types in order to improve codegen. Bitcast the vector to a
  6987. // one-element vector type whose element type is the same as the result
  6988. // type, and extract the first element.
  6989. EVT BVT = EVT::getVectorVT(*DAG.getContext(), VT, 1);
  6990. if (isTypeLegal(BVT)) {
  6991. SDValue BVec = DAG.getBitcast(BVT, Op0);
  6992. Results.push_back(DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, BVec,
  6993. DAG.getConstant(0, DL, XLenVT)));
  6994. }
  6995. }
  6996. break;
  6997. }
  6998. case RISCVISD::BREV8: {
  6999. MVT VT = N->getSimpleValueType(0);
  7000. MVT XLenVT = Subtarget.getXLenVT();
  7001. assert((VT == MVT::i16 || (VT == MVT::i32 && Subtarget.is64Bit())) &&
  7002. "Unexpected custom legalisation");
  7003. assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
  7004. SDValue NewOp = DAG.getNode(ISD::ANY_EXTEND, DL, XLenVT, N->getOperand(0));
  7005. SDValue NewRes = DAG.getNode(N->getOpcode(), DL, XLenVT, NewOp);
  7006. // ReplaceNodeResults requires we maintain the same type for the return
  7007. // value.
  7008. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, NewRes));
  7009. break;
  7010. }
  7011. case ISD::EXTRACT_VECTOR_ELT: {
  7012. // Custom-legalize an EXTRACT_VECTOR_ELT where XLEN<SEW, as the SEW element
  7013. // type is illegal (currently only vXi64 RV32).
  7014. // With vmv.x.s, when SEW > XLEN, only the least-significant XLEN bits are
  7015. // transferred to the destination register. We issue two of these from the
  7016. // upper- and lower- halves of the SEW-bit vector element, slid down to the
  7017. // first element.
  7018. SDValue Vec = N->getOperand(0);
  7019. SDValue Idx = N->getOperand(1);
  7020. // The vector type hasn't been legalized yet so we can't issue target
  7021. // specific nodes if it needs legalization.
  7022. // FIXME: We would manually legalize if it's important.
  7023. if (!isTypeLegal(Vec.getValueType()))
  7024. return;
  7025. MVT VecVT = Vec.getSimpleValueType();
  7026. assert(!Subtarget.is64Bit() && N->getValueType(0) == MVT::i64 &&
  7027. VecVT.getVectorElementType() == MVT::i64 &&
  7028. "Unexpected EXTRACT_VECTOR_ELT legalization");
  7029. // If this is a fixed vector, we need to convert it to a scalable vector.
  7030. MVT ContainerVT = VecVT;
  7031. if (VecVT.isFixedLengthVector()) {
  7032. ContainerVT = getContainerForFixedLengthVector(VecVT);
  7033. Vec = convertToScalableVector(ContainerVT, Vec, DAG, Subtarget);
  7034. }
  7035. MVT XLenVT = Subtarget.getXLenVT();
  7036. // Use a VL of 1 to avoid processing more elements than we need.
  7037. auto [Mask, VL] = getDefaultVLOps(1, ContainerVT, DL, DAG, Subtarget);
  7038. // Unless the index is known to be 0, we must slide the vector down to get
  7039. // the desired element into index 0.
  7040. if (!isNullConstant(Idx)) {
  7041. Vec = getVSlidedown(DAG, Subtarget, DL, ContainerVT,
  7042. DAG.getUNDEF(ContainerVT), Vec, Idx, Mask, VL);
  7043. }
  7044. // Extract the lower XLEN bits of the correct vector element.
  7045. SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
  7046. // To extract the upper XLEN bits of the vector element, shift the first
  7047. // element right by 32 bits and re-extract the lower XLEN bits.
  7048. SDValue ThirtyTwoV = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, ContainerVT,
  7049. DAG.getUNDEF(ContainerVT),
  7050. DAG.getConstant(32, DL, XLenVT), VL);
  7051. SDValue LShr32 =
  7052. DAG.getNode(RISCVISD::SRL_VL, DL, ContainerVT, Vec, ThirtyTwoV,
  7053. DAG.getUNDEF(ContainerVT), Mask, VL);
  7054. SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
  7055. Results.push_back(DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
  7056. break;
  7057. }
  7058. case ISD::INTRINSIC_WO_CHAIN: {
  7059. unsigned IntNo = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
  7060. switch (IntNo) {
  7061. default:
  7062. llvm_unreachable(
  7063. "Don't know how to custom type legalize this intrinsic!");
  7064. case Intrinsic::riscv_orc_b: {
  7065. SDValue NewOp =
  7066. DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N->getOperand(1));
  7067. SDValue Res = DAG.getNode(RISCVISD::ORC_B, DL, MVT::i64, NewOp);
  7068. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Res));
  7069. return;
  7070. }
  7071. case Intrinsic::riscv_vmv_x_s: {
  7072. EVT VT = N->getValueType(0);
  7073. MVT XLenVT = Subtarget.getXLenVT();
  7074. if (VT.bitsLT(XLenVT)) {
  7075. // Simple case just extract using vmv.x.s and truncate.
  7076. SDValue Extract = DAG.getNode(RISCVISD::VMV_X_S, DL,
  7077. Subtarget.getXLenVT(), N->getOperand(1));
  7078. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Extract));
  7079. return;
  7080. }
  7081. assert(VT == MVT::i64 && !Subtarget.is64Bit() &&
  7082. "Unexpected custom legalization");
  7083. // We need to do the move in two steps.
  7084. SDValue Vec = N->getOperand(1);
  7085. MVT VecVT = Vec.getSimpleValueType();
  7086. // First extract the lower XLEN bits of the element.
  7087. SDValue EltLo = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, Vec);
  7088. // To extract the upper XLEN bits of the vector element, shift the first
  7089. // element right by 32 bits and re-extract the lower XLEN bits.
  7090. auto [Mask, VL] = getDefaultVLOps(1, VecVT, DL, DAG, Subtarget);
  7091. SDValue ThirtyTwoV =
  7092. DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VecVT, DAG.getUNDEF(VecVT),
  7093. DAG.getConstant(32, DL, XLenVT), VL);
  7094. SDValue LShr32 = DAG.getNode(RISCVISD::SRL_VL, DL, VecVT, Vec, ThirtyTwoV,
  7095. DAG.getUNDEF(VecVT), Mask, VL);
  7096. SDValue EltHi = DAG.getNode(RISCVISD::VMV_X_S, DL, XLenVT, LShr32);
  7097. Results.push_back(
  7098. DAG.getNode(ISD::BUILD_PAIR, DL, MVT::i64, EltLo, EltHi));
  7099. break;
  7100. }
  7101. }
  7102. break;
  7103. }
  7104. case ISD::VECREDUCE_ADD:
  7105. case ISD::VECREDUCE_AND:
  7106. case ISD::VECREDUCE_OR:
  7107. case ISD::VECREDUCE_XOR:
  7108. case ISD::VECREDUCE_SMAX:
  7109. case ISD::VECREDUCE_UMAX:
  7110. case ISD::VECREDUCE_SMIN:
  7111. case ISD::VECREDUCE_UMIN:
  7112. if (SDValue V = lowerVECREDUCE(SDValue(N, 0), DAG))
  7113. Results.push_back(V);
  7114. break;
  7115. case ISD::VP_REDUCE_ADD:
  7116. case ISD::VP_REDUCE_AND:
  7117. case ISD::VP_REDUCE_OR:
  7118. case ISD::VP_REDUCE_XOR:
  7119. case ISD::VP_REDUCE_SMAX:
  7120. case ISD::VP_REDUCE_UMAX:
  7121. case ISD::VP_REDUCE_SMIN:
  7122. case ISD::VP_REDUCE_UMIN:
  7123. if (SDValue V = lowerVPREDUCE(SDValue(N, 0), DAG))
  7124. Results.push_back(V);
  7125. break;
  7126. case ISD::GET_ROUNDING: {
  7127. SDVTList VTs = DAG.getVTList(Subtarget.getXLenVT(), MVT::Other);
  7128. SDValue Res = DAG.getNode(ISD::GET_ROUNDING, DL, VTs, N->getOperand(0));
  7129. Results.push_back(Res.getValue(0));
  7130. Results.push_back(Res.getValue(1));
  7131. break;
  7132. }
  7133. }
  7134. }
  7135. // Try to fold (<bop> x, (reduction.<bop> vec, start))
  7136. static SDValue combineBinOpToReduce(SDNode *N, SelectionDAG &DAG,
  7137. const RISCVSubtarget &Subtarget) {
  7138. auto BinOpToRVVReduce = [](unsigned Opc) {
  7139. switch (Opc) {
  7140. default:
  7141. llvm_unreachable("Unhandled binary to transfrom reduction");
  7142. case ISD::ADD:
  7143. return RISCVISD::VECREDUCE_ADD_VL;
  7144. case ISD::UMAX:
  7145. return RISCVISD::VECREDUCE_UMAX_VL;
  7146. case ISD::SMAX:
  7147. return RISCVISD::VECREDUCE_SMAX_VL;
  7148. case ISD::UMIN:
  7149. return RISCVISD::VECREDUCE_UMIN_VL;
  7150. case ISD::SMIN:
  7151. return RISCVISD::VECREDUCE_SMIN_VL;
  7152. case ISD::AND:
  7153. return RISCVISD::VECREDUCE_AND_VL;
  7154. case ISD::OR:
  7155. return RISCVISD::VECREDUCE_OR_VL;
  7156. case ISD::XOR:
  7157. return RISCVISD::VECREDUCE_XOR_VL;
  7158. case ISD::FADD:
  7159. return RISCVISD::VECREDUCE_FADD_VL;
  7160. case ISD::FMAXNUM:
  7161. return RISCVISD::VECREDUCE_FMAX_VL;
  7162. case ISD::FMINNUM:
  7163. return RISCVISD::VECREDUCE_FMIN_VL;
  7164. }
  7165. };
  7166. auto IsReduction = [&BinOpToRVVReduce](SDValue V, unsigned Opc) {
  7167. return V.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  7168. isNullConstant(V.getOperand(1)) &&
  7169. V.getOperand(0).getOpcode() == BinOpToRVVReduce(Opc);
  7170. };
  7171. unsigned Opc = N->getOpcode();
  7172. unsigned ReduceIdx;
  7173. if (IsReduction(N->getOperand(0), Opc))
  7174. ReduceIdx = 0;
  7175. else if (IsReduction(N->getOperand(1), Opc))
  7176. ReduceIdx = 1;
  7177. else
  7178. return SDValue();
  7179. // Skip if FADD disallows reassociation but the combiner needs.
  7180. if (Opc == ISD::FADD && !N->getFlags().hasAllowReassociation())
  7181. return SDValue();
  7182. SDValue Extract = N->getOperand(ReduceIdx);
  7183. SDValue Reduce = Extract.getOperand(0);
  7184. if (!Reduce.hasOneUse())
  7185. return SDValue();
  7186. SDValue ScalarV = Reduce.getOperand(2);
  7187. EVT ScalarVT = ScalarV.getValueType();
  7188. if (ScalarV.getOpcode() == ISD::INSERT_SUBVECTOR &&
  7189. ScalarV.getOperand(0)->isUndef())
  7190. ScalarV = ScalarV.getOperand(1);
  7191. // Make sure that ScalarV is a splat with VL=1.
  7192. if (ScalarV.getOpcode() != RISCVISD::VFMV_S_F_VL &&
  7193. ScalarV.getOpcode() != RISCVISD::VMV_S_X_VL &&
  7194. ScalarV.getOpcode() != RISCVISD::VMV_V_X_VL)
  7195. return SDValue();
  7196. if (!hasNonZeroAVL(ScalarV.getOperand(2)))
  7197. return SDValue();
  7198. // Check the scalar of ScalarV is neutral element
  7199. // TODO: Deal with value other than neutral element.
  7200. if (!isNeutralConstant(N->getOpcode(), N->getFlags(), ScalarV.getOperand(1),
  7201. 0))
  7202. return SDValue();
  7203. if (!ScalarV.hasOneUse())
  7204. return SDValue();
  7205. SDValue NewStart = N->getOperand(1 - ReduceIdx);
  7206. SDLoc DL(N);
  7207. SDValue NewScalarV =
  7208. lowerScalarInsert(NewStart, ScalarV.getOperand(2),
  7209. ScalarV.getSimpleValueType(), DL, DAG, Subtarget);
  7210. // If we looked through an INSERT_SUBVECTOR we need to restore it.
  7211. if (ScalarVT != ScalarV.getValueType())
  7212. NewScalarV =
  7213. DAG.getNode(ISD::INSERT_SUBVECTOR, DL, ScalarVT, DAG.getUNDEF(ScalarVT),
  7214. NewScalarV, DAG.getConstant(0, DL, Subtarget.getXLenVT()));
  7215. SDValue NewReduce =
  7216. DAG.getNode(Reduce.getOpcode(), DL, Reduce.getValueType(),
  7217. Reduce.getOperand(0), Reduce.getOperand(1), NewScalarV,
  7218. Reduce.getOperand(3), Reduce.getOperand(4));
  7219. return DAG.getNode(Extract.getOpcode(), DL, Extract.getValueType(), NewReduce,
  7220. Extract.getOperand(1));
  7221. }
  7222. // Optimize (add (shl x, c0), (shl y, c1)) ->
  7223. // (SLLI (SH*ADD x, y), c0), if c1-c0 equals to [1|2|3].
  7224. static SDValue transformAddShlImm(SDNode *N, SelectionDAG &DAG,
  7225. const RISCVSubtarget &Subtarget) {
  7226. // Perform this optimization only in the zba extension.
  7227. if (!Subtarget.hasStdExtZba())
  7228. return SDValue();
  7229. // Skip for vector types and larger types.
  7230. EVT VT = N->getValueType(0);
  7231. if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
  7232. return SDValue();
  7233. // The two operand nodes must be SHL and have no other use.
  7234. SDValue N0 = N->getOperand(0);
  7235. SDValue N1 = N->getOperand(1);
  7236. if (N0->getOpcode() != ISD::SHL || N1->getOpcode() != ISD::SHL ||
  7237. !N0->hasOneUse() || !N1->hasOneUse())
  7238. return SDValue();
  7239. // Check c0 and c1.
  7240. auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
  7241. auto *N1C = dyn_cast<ConstantSDNode>(N1->getOperand(1));
  7242. if (!N0C || !N1C)
  7243. return SDValue();
  7244. int64_t C0 = N0C->getSExtValue();
  7245. int64_t C1 = N1C->getSExtValue();
  7246. if (C0 <= 0 || C1 <= 0)
  7247. return SDValue();
  7248. // Skip if SH1ADD/SH2ADD/SH3ADD are not applicable.
  7249. int64_t Bits = std::min(C0, C1);
  7250. int64_t Diff = std::abs(C0 - C1);
  7251. if (Diff != 1 && Diff != 2 && Diff != 3)
  7252. return SDValue();
  7253. // Build nodes.
  7254. SDLoc DL(N);
  7255. SDValue NS = (C0 < C1) ? N0->getOperand(0) : N1->getOperand(0);
  7256. SDValue NL = (C0 > C1) ? N0->getOperand(0) : N1->getOperand(0);
  7257. SDValue NA0 =
  7258. DAG.getNode(ISD::SHL, DL, VT, NL, DAG.getConstant(Diff, DL, VT));
  7259. SDValue NA1 = DAG.getNode(ISD::ADD, DL, VT, NA0, NS);
  7260. return DAG.getNode(ISD::SHL, DL, VT, NA1, DAG.getConstant(Bits, DL, VT));
  7261. }
  7262. // Combine a constant select operand into its use:
  7263. //
  7264. // (and (select cond, -1, c), x)
  7265. // -> (select cond, x, (and x, c)) [AllOnes=1]
  7266. // (or (select cond, 0, c), x)
  7267. // -> (select cond, x, (or x, c)) [AllOnes=0]
  7268. // (xor (select cond, 0, c), x)
  7269. // -> (select cond, x, (xor x, c)) [AllOnes=0]
  7270. // (add (select cond, 0, c), x)
  7271. // -> (select cond, x, (add x, c)) [AllOnes=0]
  7272. // (sub x, (select cond, 0, c))
  7273. // -> (select cond, x, (sub x, c)) [AllOnes=0]
  7274. static SDValue combineSelectAndUse(SDNode *N, SDValue Slct, SDValue OtherOp,
  7275. SelectionDAG &DAG, bool AllOnes,
  7276. const RISCVSubtarget &Subtarget) {
  7277. EVT VT = N->getValueType(0);
  7278. // Skip vectors.
  7279. if (VT.isVector())
  7280. return SDValue();
  7281. if (!Subtarget.hasShortForwardBranchOpt() ||
  7282. (Slct.getOpcode() != ISD::SELECT &&
  7283. Slct.getOpcode() != RISCVISD::SELECT_CC) ||
  7284. !Slct.hasOneUse())
  7285. return SDValue();
  7286. auto isZeroOrAllOnes = [](SDValue N, bool AllOnes) {
  7287. return AllOnes ? isAllOnesConstant(N) : isNullConstant(N);
  7288. };
  7289. bool SwapSelectOps;
  7290. unsigned OpOffset = Slct.getOpcode() == RISCVISD::SELECT_CC ? 2 : 0;
  7291. SDValue TrueVal = Slct.getOperand(1 + OpOffset);
  7292. SDValue FalseVal = Slct.getOperand(2 + OpOffset);
  7293. SDValue NonConstantVal;
  7294. if (isZeroOrAllOnes(TrueVal, AllOnes)) {
  7295. SwapSelectOps = false;
  7296. NonConstantVal = FalseVal;
  7297. } else if (isZeroOrAllOnes(FalseVal, AllOnes)) {
  7298. SwapSelectOps = true;
  7299. NonConstantVal = TrueVal;
  7300. } else
  7301. return SDValue();
  7302. // Slct is now know to be the desired identity constant when CC is true.
  7303. TrueVal = OtherOp;
  7304. FalseVal = DAG.getNode(N->getOpcode(), SDLoc(N), VT, OtherOp, NonConstantVal);
  7305. // Unless SwapSelectOps says the condition should be false.
  7306. if (SwapSelectOps)
  7307. std::swap(TrueVal, FalseVal);
  7308. if (Slct.getOpcode() == RISCVISD::SELECT_CC)
  7309. return DAG.getNode(RISCVISD::SELECT_CC, SDLoc(N), VT,
  7310. {Slct.getOperand(0), Slct.getOperand(1),
  7311. Slct.getOperand(2), TrueVal, FalseVal});
  7312. return DAG.getNode(ISD::SELECT, SDLoc(N), VT,
  7313. {Slct.getOperand(0), TrueVal, FalseVal});
  7314. }
  7315. // Attempt combineSelectAndUse on each operand of a commutative operator N.
  7316. static SDValue combineSelectAndUseCommutative(SDNode *N, SelectionDAG &DAG,
  7317. bool AllOnes,
  7318. const RISCVSubtarget &Subtarget) {
  7319. SDValue N0 = N->getOperand(0);
  7320. SDValue N1 = N->getOperand(1);
  7321. if (SDValue Result = combineSelectAndUse(N, N0, N1, DAG, AllOnes, Subtarget))
  7322. return Result;
  7323. if (SDValue Result = combineSelectAndUse(N, N1, N0, DAG, AllOnes, Subtarget))
  7324. return Result;
  7325. return SDValue();
  7326. }
  7327. // Transform (add (mul x, c0), c1) ->
  7328. // (add (mul (add x, c1/c0), c0), c1%c0).
  7329. // if c1/c0 and c1%c0 are simm12, while c1 is not. A special corner case
  7330. // that should be excluded is when c0*(c1/c0) is simm12, which will lead
  7331. // to an infinite loop in DAGCombine if transformed.
  7332. // Or transform (add (mul x, c0), c1) ->
  7333. // (add (mul (add x, c1/c0+1), c0), c1%c0-c0),
  7334. // if c1/c0+1 and c1%c0-c0 are simm12, while c1 is not. A special corner
  7335. // case that should be excluded is when c0*(c1/c0+1) is simm12, which will
  7336. // lead to an infinite loop in DAGCombine if transformed.
  7337. // Or transform (add (mul x, c0), c1) ->
  7338. // (add (mul (add x, c1/c0-1), c0), c1%c0+c0),
  7339. // if c1/c0-1 and c1%c0+c0 are simm12, while c1 is not. A special corner
  7340. // case that should be excluded is when c0*(c1/c0-1) is simm12, which will
  7341. // lead to an infinite loop in DAGCombine if transformed.
  7342. // Or transform (add (mul x, c0), c1) ->
  7343. // (mul (add x, c1/c0), c0).
  7344. // if c1%c0 is zero, and c1/c0 is simm12 while c1 is not.
  7345. static SDValue transformAddImmMulImm(SDNode *N, SelectionDAG &DAG,
  7346. const RISCVSubtarget &Subtarget) {
  7347. // Skip for vector types and larger types.
  7348. EVT VT = N->getValueType(0);
  7349. if (VT.isVector() || VT.getSizeInBits() > Subtarget.getXLen())
  7350. return SDValue();
  7351. // The first operand node must be a MUL and has no other use.
  7352. SDValue N0 = N->getOperand(0);
  7353. if (!N0->hasOneUse() || N0->getOpcode() != ISD::MUL)
  7354. return SDValue();
  7355. // Check if c0 and c1 match above conditions.
  7356. auto *N0C = dyn_cast<ConstantSDNode>(N0->getOperand(1));
  7357. auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
  7358. if (!N0C || !N1C)
  7359. return SDValue();
  7360. // If N0C has multiple uses it's possible one of the cases in
  7361. // DAGCombiner::isMulAddWithConstProfitable will be true, which would result
  7362. // in an infinite loop.
  7363. if (!N0C->hasOneUse())
  7364. return SDValue();
  7365. int64_t C0 = N0C->getSExtValue();
  7366. int64_t C1 = N1C->getSExtValue();
  7367. int64_t CA, CB;
  7368. if (C0 == -1 || C0 == 0 || C0 == 1 || isInt<12>(C1))
  7369. return SDValue();
  7370. // Search for proper CA (non-zero) and CB that both are simm12.
  7371. if ((C1 / C0) != 0 && isInt<12>(C1 / C0) && isInt<12>(C1 % C0) &&
  7372. !isInt<12>(C0 * (C1 / C0))) {
  7373. CA = C1 / C0;
  7374. CB = C1 % C0;
  7375. } else if ((C1 / C0 + 1) != 0 && isInt<12>(C1 / C0 + 1) &&
  7376. isInt<12>(C1 % C0 - C0) && !isInt<12>(C0 * (C1 / C0 + 1))) {
  7377. CA = C1 / C0 + 1;
  7378. CB = C1 % C0 - C0;
  7379. } else if ((C1 / C0 - 1) != 0 && isInt<12>(C1 / C0 - 1) &&
  7380. isInt<12>(C1 % C0 + C0) && !isInt<12>(C0 * (C1 / C0 - 1))) {
  7381. CA = C1 / C0 - 1;
  7382. CB = C1 % C0 + C0;
  7383. } else
  7384. return SDValue();
  7385. // Build new nodes (add (mul (add x, c1/c0), c0), c1%c0).
  7386. SDLoc DL(N);
  7387. SDValue New0 = DAG.getNode(ISD::ADD, DL, VT, N0->getOperand(0),
  7388. DAG.getConstant(CA, DL, VT));
  7389. SDValue New1 =
  7390. DAG.getNode(ISD::MUL, DL, VT, New0, DAG.getConstant(C0, DL, VT));
  7391. return DAG.getNode(ISD::ADD, DL, VT, New1, DAG.getConstant(CB, DL, VT));
  7392. }
  7393. static SDValue performADDCombine(SDNode *N, SelectionDAG &DAG,
  7394. const RISCVSubtarget &Subtarget) {
  7395. if (SDValue V = transformAddImmMulImm(N, DAG, Subtarget))
  7396. return V;
  7397. if (SDValue V = transformAddShlImm(N, DAG, Subtarget))
  7398. return V;
  7399. if (SDValue V = combineBinOpToReduce(N, DAG, Subtarget))
  7400. return V;
  7401. // fold (add (select lhs, rhs, cc, 0, y), x) ->
  7402. // (select lhs, rhs, cc, x, (add x, y))
  7403. return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false, Subtarget);
  7404. }
  7405. // Try to turn a sub boolean RHS and constant LHS into an addi.
  7406. static SDValue combineSubOfBoolean(SDNode *N, SelectionDAG &DAG) {
  7407. SDValue N0 = N->getOperand(0);
  7408. SDValue N1 = N->getOperand(1);
  7409. EVT VT = N->getValueType(0);
  7410. SDLoc DL(N);
  7411. // Require a constant LHS.
  7412. auto *N0C = dyn_cast<ConstantSDNode>(N0);
  7413. if (!N0C)
  7414. return SDValue();
  7415. // All our optimizations involve subtracting 1 from the immediate and forming
  7416. // an ADDI. Make sure the new immediate is valid for an ADDI.
  7417. APInt ImmValMinus1 = N0C->getAPIntValue() - 1;
  7418. if (!ImmValMinus1.isSignedIntN(12))
  7419. return SDValue();
  7420. SDValue NewLHS;
  7421. if (N1.getOpcode() == ISD::SETCC && N1.hasOneUse()) {
  7422. // (sub constant, (setcc x, y, eq/neq)) ->
  7423. // (add (setcc x, y, neq/eq), constant - 1)
  7424. ISD::CondCode CCVal = cast<CondCodeSDNode>(N1.getOperand(2))->get();
  7425. EVT SetCCOpVT = N1.getOperand(0).getValueType();
  7426. if (!isIntEqualitySetCC(CCVal) || !SetCCOpVT.isInteger())
  7427. return SDValue();
  7428. CCVal = ISD::getSetCCInverse(CCVal, SetCCOpVT);
  7429. NewLHS =
  7430. DAG.getSetCC(SDLoc(N1), VT, N1.getOperand(0), N1.getOperand(1), CCVal);
  7431. } else if (N1.getOpcode() == ISD::XOR && isOneConstant(N1.getOperand(1)) &&
  7432. N1.getOperand(0).getOpcode() == ISD::SETCC) {
  7433. // (sub C, (xor (setcc), 1)) -> (add (setcc), C-1).
  7434. // Since setcc returns a bool the xor is equivalent to 1-setcc.
  7435. NewLHS = N1.getOperand(0);
  7436. } else
  7437. return SDValue();
  7438. SDValue NewRHS = DAG.getConstant(ImmValMinus1, DL, VT);
  7439. return DAG.getNode(ISD::ADD, DL, VT, NewLHS, NewRHS);
  7440. }
  7441. static SDValue performSUBCombine(SDNode *N, SelectionDAG &DAG,
  7442. const RISCVSubtarget &Subtarget) {
  7443. if (SDValue V = combineSubOfBoolean(N, DAG))
  7444. return V;
  7445. // fold (sub x, (select lhs, rhs, cc, 0, y)) ->
  7446. // (select lhs, rhs, cc, x, (sub x, y))
  7447. SDValue N0 = N->getOperand(0);
  7448. SDValue N1 = N->getOperand(1);
  7449. return combineSelectAndUse(N, N1, N0, DAG, /*AllOnes*/ false, Subtarget);
  7450. }
  7451. // Apply DeMorgan's law to (and/or (xor X, 1), (xor Y, 1)) if X and Y are 0/1.
  7452. // Legalizing setcc can introduce xors like this. Doing this transform reduces
  7453. // the number of xors and may allow the xor to fold into a branch condition.
  7454. static SDValue combineDeMorganOfBoolean(SDNode *N, SelectionDAG &DAG) {
  7455. SDValue N0 = N->getOperand(0);
  7456. SDValue N1 = N->getOperand(1);
  7457. bool IsAnd = N->getOpcode() == ISD::AND;
  7458. if (N0.getOpcode() != ISD::XOR || N1.getOpcode() != ISD::XOR)
  7459. return SDValue();
  7460. if (!N0.hasOneUse() || !N1.hasOneUse())
  7461. return SDValue();
  7462. SDValue N01 = N0.getOperand(1);
  7463. SDValue N11 = N1.getOperand(1);
  7464. // For AND, SimplifyDemandedBits may have turned one of the (xor X, 1) into
  7465. // (xor X, -1) based on the upper bits of the other operand being 0. If the
  7466. // operation is And, allow one of the Xors to use -1.
  7467. if (isOneConstant(N01)) {
  7468. if (!isOneConstant(N11) && !(IsAnd && isAllOnesConstant(N11)))
  7469. return SDValue();
  7470. } else if (isOneConstant(N11)) {
  7471. // N01 and N11 being 1 was already handled. Handle N11==1 and N01==-1.
  7472. if (!(IsAnd && isAllOnesConstant(N01)))
  7473. return SDValue();
  7474. } else
  7475. return SDValue();
  7476. EVT VT = N->getValueType(0);
  7477. SDValue N00 = N0.getOperand(0);
  7478. SDValue N10 = N1.getOperand(0);
  7479. // The LHS of the xors needs to be 0/1.
  7480. APInt Mask = APInt::getBitsSetFrom(VT.getSizeInBits(), 1);
  7481. if (!DAG.MaskedValueIsZero(N00, Mask) || !DAG.MaskedValueIsZero(N10, Mask))
  7482. return SDValue();
  7483. // Invert the opcode and insert a new xor.
  7484. SDLoc DL(N);
  7485. unsigned Opc = IsAnd ? ISD::OR : ISD::AND;
  7486. SDValue Logic = DAG.getNode(Opc, DL, VT, N00, N10);
  7487. return DAG.getNode(ISD::XOR, DL, VT, Logic, DAG.getConstant(1, DL, VT));
  7488. }
  7489. static SDValue performTRUNCATECombine(SDNode *N, SelectionDAG &DAG,
  7490. const RISCVSubtarget &Subtarget) {
  7491. SDValue N0 = N->getOperand(0);
  7492. EVT VT = N->getValueType(0);
  7493. // Pre-promote (i1 (truncate (srl X, Y))) on RV64 with Zbs without zero
  7494. // extending X. This is safe since we only need the LSB after the shift and
  7495. // shift amounts larger than 31 would produce poison. If we wait until
  7496. // type legalization, we'll create RISCVISD::SRLW and we can't recover it
  7497. // to use a BEXT instruction.
  7498. if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() && VT == MVT::i1 &&
  7499. N0.getValueType() == MVT::i32 && N0.getOpcode() == ISD::SRL &&
  7500. !isa<ConstantSDNode>(N0.getOperand(1)) && N0.hasOneUse()) {
  7501. SDLoc DL(N0);
  7502. SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0));
  7503. SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1));
  7504. SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1);
  7505. return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Srl);
  7506. }
  7507. return SDValue();
  7508. }
  7509. namespace {
  7510. // Helper class contains information about comparison operation.
  7511. // The first two operands of this operation are compared values and the
  7512. // last one is the operation.
  7513. // Compared values are stored in Ops.
  7514. // Comparison operation is stored in CCode.
  7515. class CmpOpInfo {
  7516. static unsigned constexpr Size = 2u;
  7517. // Type for storing operands of compare operation.
  7518. using OpsArray = std::array<SDValue, Size>;
  7519. OpsArray Ops;
  7520. using const_iterator = OpsArray::const_iterator;
  7521. const_iterator begin() const { return Ops.begin(); }
  7522. const_iterator end() const { return Ops.end(); }
  7523. ISD::CondCode CCode;
  7524. unsigned CommonPos{Size};
  7525. unsigned DifferPos{Size};
  7526. // Sets CommonPos and DifferPos based on incoming position
  7527. // of common operand CPos.
  7528. void setPositions(const_iterator CPos) {
  7529. assert(CPos != Ops.end() && "Common operand has to be in OpsArray.\n");
  7530. CommonPos = CPos == Ops.begin() ? 0 : 1;
  7531. DifferPos = 1 - CommonPos;
  7532. assert((DifferPos == 0 || DifferPos == 1) &&
  7533. "Positions can be only 0 or 1.");
  7534. }
  7535. // Private constructor of comparison info based on comparison operator.
  7536. // It is private because CmpOpInfo only reasonable relative to other
  7537. // comparison operator. Therefore, infos about comparison operation
  7538. // have to be collected simultaneously via CmpOpInfo::getInfoAbout().
  7539. CmpOpInfo(const SDValue &CmpOp)
  7540. : Ops{CmpOp.getOperand(0), CmpOp.getOperand(1)},
  7541. CCode{cast<CondCodeSDNode>(CmpOp.getOperand(2))->get()} {}
  7542. // Finds common operand of Op1 and Op2 and finishes filling CmpOpInfos.
  7543. // Returns true if common operand is found. Otherwise - false.
  7544. static bool establishCorrespondence(CmpOpInfo &Op1, CmpOpInfo &Op2) {
  7545. const auto CommonOpIt1 =
  7546. std::find_first_of(Op1.begin(), Op1.end(), Op2.begin(), Op2.end());
  7547. if (CommonOpIt1 == Op1.end())
  7548. return false;
  7549. const auto CommonOpIt2 = std::find(Op2.begin(), Op2.end(), *CommonOpIt1);
  7550. assert(CommonOpIt2 != Op2.end() &&
  7551. "Cannot find common operand in the second comparison operation.");
  7552. Op1.setPositions(CommonOpIt1);
  7553. Op2.setPositions(CommonOpIt2);
  7554. return true;
  7555. }
  7556. public:
  7557. CmpOpInfo(const CmpOpInfo &) = default;
  7558. CmpOpInfo(CmpOpInfo &&) = default;
  7559. SDValue const &operator[](unsigned Pos) const {
  7560. assert(Pos < Size && "Out of range\n");
  7561. return Ops[Pos];
  7562. }
  7563. // Creates infos about comparison operations CmpOp0 and CmpOp1.
  7564. // If there is no common operand returns None. Otherwise, returns
  7565. // correspondence info about comparison operations.
  7566. static std::optional<std::pair<CmpOpInfo, CmpOpInfo>>
  7567. getInfoAbout(SDValue const &CmpOp0, SDValue const &CmpOp1) {
  7568. CmpOpInfo Op0{CmpOp0};
  7569. CmpOpInfo Op1{CmpOp1};
  7570. if (!establishCorrespondence(Op0, Op1))
  7571. return std::nullopt;
  7572. return std::make_pair(Op0, Op1);
  7573. }
  7574. // Returns position of common operand.
  7575. unsigned getCPos() const { return CommonPos; }
  7576. // Returns position of differ operand.
  7577. unsigned getDPos() const { return DifferPos; }
  7578. // Returns common operand.
  7579. SDValue const &getCOp() const { return operator[](CommonPos); }
  7580. // Returns differ operand.
  7581. SDValue const &getDOp() const { return operator[](DifferPos); }
  7582. // Returns consition code of comparison operation.
  7583. ISD::CondCode getCondCode() const { return CCode; }
  7584. };
  7585. } // namespace
  7586. // Verifies conditions to apply an optimization.
  7587. // Returns Reference comparison code and three operands A, B, C.
  7588. // Conditions for optimization:
  7589. // One operand of the compasions has to be common.
  7590. // This operand is written to C.
  7591. // Two others operands are differend. They are written to A and B.
  7592. // Comparisons has to be similar with respect to common operand C.
  7593. // e.g. A < C; C > B are similar
  7594. // but A < C; B > C are not.
  7595. // Reference comparison code is the comparison code if
  7596. // common operand is right placed.
  7597. // e.g. C > A will be swapped to A < C.
  7598. static std::optional<std::tuple<ISD::CondCode, SDValue, SDValue, SDValue>>
  7599. verifyCompareConds(SDNode *N, SelectionDAG &DAG) {
  7600. LLVM_DEBUG(
  7601. dbgs() << "Checking conditions for comparison operation combining.\n";);
  7602. SDValue V0 = N->getOperand(0);
  7603. SDValue V1 = N->getOperand(1);
  7604. assert(V0.getValueType() == V1.getValueType() &&
  7605. "Operations must have the same value type.");
  7606. // Condition 1. Operations have to be used only in logic operation.
  7607. if (!V0.hasOneUse() || !V1.hasOneUse())
  7608. return std::nullopt;
  7609. // Condition 2. Operands have to be comparison operations.
  7610. if (V0.getOpcode() != ISD::SETCC || V1.getOpcode() != ISD::SETCC)
  7611. return std::nullopt;
  7612. // Condition 3.1. Operations only with integers.
  7613. if (!V0.getOperand(0).getValueType().isInteger())
  7614. return std::nullopt;
  7615. const auto ComparisonInfo = CmpOpInfo::getInfoAbout(V0, V1);
  7616. // Condition 3.2. Common operand has to be in comparison.
  7617. if (!ComparisonInfo)
  7618. return std::nullopt;
  7619. const auto [Op0, Op1] = ComparisonInfo.value();
  7620. LLVM_DEBUG(dbgs() << "Shared operands are on positions: " << Op0.getCPos()
  7621. << " and " << Op1.getCPos() << '\n';);
  7622. // If common operand at the first position then swap operation to convert to
  7623. // strict pattern. Common operand has to be right hand side.
  7624. ISD::CondCode RefCond = Op0.getCondCode();
  7625. ISD::CondCode AssistCode = Op1.getCondCode();
  7626. if (!Op0.getCPos())
  7627. RefCond = ISD::getSetCCSwappedOperands(RefCond);
  7628. if (!Op1.getCPos())
  7629. AssistCode = ISD::getSetCCSwappedOperands(AssistCode);
  7630. LLVM_DEBUG(dbgs() << "Reference condition is: " << RefCond << '\n';);
  7631. // If there are different comparison operations then do not perform an
  7632. // optimization. a < c; c < b -> will be changed to b > c.
  7633. if (RefCond != AssistCode)
  7634. return std::nullopt;
  7635. // Conditions can be only similar to Less or Greater. (>, >=, <, <=)
  7636. // Applying this mask to the operation will determine Less and Greater
  7637. // operations.
  7638. const unsigned CmpMask = 0b110;
  7639. const unsigned MaskedOpcode = CmpMask & RefCond;
  7640. // If masking gave 0b110, then this is an operation NE, O or TRUE.
  7641. if (MaskedOpcode == CmpMask)
  7642. return std::nullopt;
  7643. // If masking gave 00000, then this is an operation E, O or FALSE.
  7644. if (MaskedOpcode == 0)
  7645. return std::nullopt;
  7646. // Everything else is similar to Less or Greater.
  7647. SDValue A = Op0.getDOp();
  7648. SDValue B = Op1.getDOp();
  7649. SDValue C = Op0.getCOp();
  7650. LLVM_DEBUG(
  7651. dbgs() << "The conditions for combining comparisons are satisfied.\n";);
  7652. return std::make_tuple(RefCond, A, B, C);
  7653. }
  7654. static ISD::NodeType getSelectionCode(bool IsUnsigned, bool IsAnd,
  7655. bool IsGreaterOp) {
  7656. // Codes of selection operation. The first index selects signed or unsigned,
  7657. // the second index selects MIN/MAX.
  7658. static constexpr ISD::NodeType SelectionCodes[2][2] = {
  7659. {ISD::SMIN, ISD::SMAX}, {ISD::UMIN, ISD::UMAX}};
  7660. const bool ChooseSelCode = IsAnd ^ IsGreaterOp;
  7661. return SelectionCodes[IsUnsigned][ChooseSelCode];
  7662. }
  7663. // Combines two comparison operation and logic operation to one selection
  7664. // operation(min, max) and logic operation. Returns new constructed Node if
  7665. // conditions for optimization are satisfied.
  7666. static SDValue combineCmpOp(SDNode *N, SelectionDAG &DAG,
  7667. const RISCVSubtarget &Subtarget) {
  7668. if (!Subtarget.hasStdExtZbb())
  7669. return SDValue();
  7670. const unsigned BitOpcode = N->getOpcode();
  7671. assert((BitOpcode == ISD::AND || BitOpcode == ISD::OR) &&
  7672. "This optimization can be used only with AND/OR operations");
  7673. const auto Props = verifyCompareConds(N, DAG);
  7674. // If conditions are invalidated then do not perform an optimization.
  7675. if (!Props)
  7676. return SDValue();
  7677. const auto [RefOpcode, A, B, C] = Props.value();
  7678. const EVT CmpOpVT = A.getValueType();
  7679. const bool IsGreaterOp = RefOpcode & 0b10;
  7680. const bool IsUnsigned = ISD::isUnsignedIntSetCC(RefOpcode);
  7681. assert((IsUnsigned || ISD::isSignedIntSetCC(RefOpcode)) &&
  7682. "Operation neither with signed or unsigned integers.");
  7683. const bool IsAnd = BitOpcode == ISD::AND;
  7684. const ISD::NodeType PickCode =
  7685. getSelectionCode(IsUnsigned, IsAnd, IsGreaterOp);
  7686. SDLoc DL(N);
  7687. SDValue Pick = DAG.getNode(PickCode, DL, CmpOpVT, A, B);
  7688. SDValue Cmp =
  7689. DAG.getSetCC(DL, N->getOperand(0).getValueType(), Pick, C, RefOpcode);
  7690. return Cmp;
  7691. }
  7692. static SDValue performANDCombine(SDNode *N,
  7693. TargetLowering::DAGCombinerInfo &DCI,
  7694. const RISCVSubtarget &Subtarget) {
  7695. SelectionDAG &DAG = DCI.DAG;
  7696. SDValue N0 = N->getOperand(0);
  7697. // Pre-promote (i32 (and (srl X, Y), 1)) on RV64 with Zbs without zero
  7698. // extending X. This is safe since we only need the LSB after the shift and
  7699. // shift amounts larger than 31 would produce poison. If we wait until
  7700. // type legalization, we'll create RISCVISD::SRLW and we can't recover it
  7701. // to use a BEXT instruction.
  7702. if (Subtarget.is64Bit() && Subtarget.hasStdExtZbs() &&
  7703. N->getValueType(0) == MVT::i32 && isOneConstant(N->getOperand(1)) &&
  7704. N0.getOpcode() == ISD::SRL && !isa<ConstantSDNode>(N0.getOperand(1)) &&
  7705. N0.hasOneUse()) {
  7706. SDLoc DL(N);
  7707. SDValue Op0 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i64, N0.getOperand(0));
  7708. SDValue Op1 = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, N0.getOperand(1));
  7709. SDValue Srl = DAG.getNode(ISD::SRL, DL, MVT::i64, Op0, Op1);
  7710. SDValue And = DAG.getNode(ISD::AND, DL, MVT::i64, Srl,
  7711. DAG.getConstant(1, DL, MVT::i64));
  7712. return DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, And);
  7713. }
  7714. if (SDValue V = combineCmpOp(N, DAG, Subtarget))
  7715. return V;
  7716. if (SDValue V = combineBinOpToReduce(N, DAG, Subtarget))
  7717. return V;
  7718. if (DCI.isAfterLegalizeDAG())
  7719. if (SDValue V = combineDeMorganOfBoolean(N, DAG))
  7720. return V;
  7721. // fold (and (select lhs, rhs, cc, -1, y), x) ->
  7722. // (select lhs, rhs, cc, x, (and x, y))
  7723. return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ true, Subtarget);
  7724. }
  7725. static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
  7726. const RISCVSubtarget &Subtarget) {
  7727. SelectionDAG &DAG = DCI.DAG;
  7728. if (SDValue V = combineCmpOp(N, DAG, Subtarget))
  7729. return V;
  7730. if (SDValue V = combineBinOpToReduce(N, DAG, Subtarget))
  7731. return V;
  7732. if (DCI.isAfterLegalizeDAG())
  7733. if (SDValue V = combineDeMorganOfBoolean(N, DAG))
  7734. return V;
  7735. // fold (or (select cond, 0, y), x) ->
  7736. // (select cond, x, (or x, y))
  7737. return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false, Subtarget);
  7738. }
  7739. static SDValue performXORCombine(SDNode *N, SelectionDAG &DAG,
  7740. const RISCVSubtarget &Subtarget) {
  7741. SDValue N0 = N->getOperand(0);
  7742. SDValue N1 = N->getOperand(1);
  7743. // fold (xor (sllw 1, x), -1) -> (rolw ~1, x)
  7744. // NOTE: Assumes ROL being legal means ROLW is legal.
  7745. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  7746. if (N0.getOpcode() == RISCVISD::SLLW &&
  7747. isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0)) &&
  7748. TLI.isOperationLegal(ISD::ROTL, MVT::i64)) {
  7749. SDLoc DL(N);
  7750. return DAG.getNode(RISCVISD::ROLW, DL, MVT::i64,
  7751. DAG.getConstant(~1, DL, MVT::i64), N0.getOperand(1));
  7752. }
  7753. if (SDValue V = combineBinOpToReduce(N, DAG, Subtarget))
  7754. return V;
  7755. // fold (xor (select cond, 0, y), x) ->
  7756. // (select cond, x, (xor x, y))
  7757. return combineSelectAndUseCommutative(N, DAG, /*AllOnes*/ false, Subtarget);
  7758. }
  7759. // Replace (seteq (i64 (and X, 0xffffffff)), C1) with
  7760. // (seteq (i64 (sext_inreg (X, i32)), C1')) where C1' is C1 sign extended from
  7761. // bit 31. Same for setne. C1' may be cheaper to materialize and the sext_inreg
  7762. // can become a sext.w instead of a shift pair.
  7763. static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG,
  7764. const RISCVSubtarget &Subtarget) {
  7765. SDValue N0 = N->getOperand(0);
  7766. SDValue N1 = N->getOperand(1);
  7767. EVT VT = N->getValueType(0);
  7768. EVT OpVT = N0.getValueType();
  7769. if (OpVT != MVT::i64 || !Subtarget.is64Bit())
  7770. return SDValue();
  7771. // RHS needs to be a constant.
  7772. auto *N1C = dyn_cast<ConstantSDNode>(N1);
  7773. if (!N1C)
  7774. return SDValue();
  7775. // LHS needs to be (and X, 0xffffffff).
  7776. if (N0.getOpcode() != ISD::AND || !N0.hasOneUse() ||
  7777. !isa<ConstantSDNode>(N0.getOperand(1)) ||
  7778. N0.getConstantOperandVal(1) != UINT64_C(0xffffffff))
  7779. return SDValue();
  7780. // Looking for an equality compare.
  7781. ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
  7782. if (!isIntEqualitySetCC(Cond))
  7783. return SDValue();
  7784. // Don't do this if the sign bit is provably zero, it will be turned back into
  7785. // an AND.
  7786. APInt SignMask = APInt::getOneBitSet(64, 31);
  7787. if (DAG.MaskedValueIsZero(N0.getOperand(0), SignMask))
  7788. return SDValue();
  7789. const APInt &C1 = N1C->getAPIntValue();
  7790. SDLoc dl(N);
  7791. // If the constant is larger than 2^32 - 1 it is impossible for both sides
  7792. // to be equal.
  7793. if (C1.getActiveBits() > 32)
  7794. return DAG.getBoolConstant(Cond == ISD::SETNE, dl, VT, OpVT);
  7795. SDValue SExtOp = DAG.getNode(ISD::SIGN_EXTEND_INREG, N, OpVT,
  7796. N0.getOperand(0), DAG.getValueType(MVT::i32));
  7797. return DAG.getSetCC(dl, VT, SExtOp, DAG.getConstant(C1.trunc(32).sext(64),
  7798. dl, OpVT), Cond);
  7799. }
  7800. static SDValue
  7801. performSIGN_EXTEND_INREGCombine(SDNode *N, SelectionDAG &DAG,
  7802. const RISCVSubtarget &Subtarget) {
  7803. SDValue Src = N->getOperand(0);
  7804. EVT VT = N->getValueType(0);
  7805. // Fold (sext_inreg (fmv_x_anyexth X), i16) -> (fmv_x_signexth X)
  7806. if (Src.getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
  7807. cast<VTSDNode>(N->getOperand(1))->getVT().bitsGE(MVT::i16))
  7808. return DAG.getNode(RISCVISD::FMV_X_SIGNEXTH, SDLoc(N), VT,
  7809. Src.getOperand(0));
  7810. return SDValue();
  7811. }
  7812. namespace {
  7813. // Forward declaration of the structure holding the necessary information to
  7814. // apply a combine.
  7815. struct CombineResult;
  7816. /// Helper class for folding sign/zero extensions.
  7817. /// In particular, this class is used for the following combines:
  7818. /// add_vl -> vwadd(u) | vwadd(u)_w
  7819. /// sub_vl -> vwsub(u) | vwsub(u)_w
  7820. /// mul_vl -> vwmul(u) | vwmul_su
  7821. ///
  7822. /// An object of this class represents an operand of the operation we want to
  7823. /// combine.
  7824. /// E.g., when trying to combine `mul_vl a, b`, we will have one instance of
  7825. /// NodeExtensionHelper for `a` and one for `b`.
  7826. ///
  7827. /// This class abstracts away how the extension is materialized and
  7828. /// how its Mask, VL, number of users affect the combines.
  7829. ///
  7830. /// In particular:
  7831. /// - VWADD_W is conceptually == add(op0, sext(op1))
  7832. /// - VWADDU_W == add(op0, zext(op1))
  7833. /// - VWSUB_W == sub(op0, sext(op1))
  7834. /// - VWSUBU_W == sub(op0, zext(op1))
  7835. ///
  7836. /// And VMV_V_X_VL, depending on the value, is conceptually equivalent to
  7837. /// zext|sext(smaller_value).
  7838. struct NodeExtensionHelper {
  7839. /// Records if this operand is like being zero extended.
  7840. bool SupportsZExt;
  7841. /// Records if this operand is like being sign extended.
  7842. /// Note: SupportsZExt and SupportsSExt are not mutually exclusive. For
  7843. /// instance, a splat constant (e.g., 3), would support being both sign and
  7844. /// zero extended.
  7845. bool SupportsSExt;
  7846. /// This boolean captures whether we care if this operand would still be
  7847. /// around after the folding happens.
  7848. bool EnforceOneUse;
  7849. /// Records if this operand's mask needs to match the mask of the operation
  7850. /// that it will fold into.
  7851. bool CheckMask;
  7852. /// Value of the Mask for this operand.
  7853. /// It may be SDValue().
  7854. SDValue Mask;
  7855. /// Value of the vector length operand.
  7856. /// It may be SDValue().
  7857. SDValue VL;
  7858. /// Original value that this NodeExtensionHelper represents.
  7859. SDValue OrigOperand;
  7860. /// Get the value feeding the extension or the value itself.
  7861. /// E.g., for zext(a), this would return a.
  7862. SDValue getSource() const {
  7863. switch (OrigOperand.getOpcode()) {
  7864. case RISCVISD::VSEXT_VL:
  7865. case RISCVISD::VZEXT_VL:
  7866. return OrigOperand.getOperand(0);
  7867. default:
  7868. return OrigOperand;
  7869. }
  7870. }
  7871. /// Check if this instance represents a splat.
  7872. bool isSplat() const {
  7873. return OrigOperand.getOpcode() == RISCVISD::VMV_V_X_VL;
  7874. }
  7875. /// Get or create a value that can feed \p Root with the given extension \p
  7876. /// SExt. If \p SExt is None, this returns the source of this operand.
  7877. /// \see ::getSource().
  7878. SDValue getOrCreateExtendedOp(const SDNode *Root, SelectionDAG &DAG,
  7879. std::optional<bool> SExt) const {
  7880. if (!SExt.has_value())
  7881. return OrigOperand;
  7882. MVT NarrowVT = getNarrowType(Root);
  7883. SDValue Source = getSource();
  7884. if (Source.getValueType() == NarrowVT)
  7885. return Source;
  7886. unsigned ExtOpc = *SExt ? RISCVISD::VSEXT_VL : RISCVISD::VZEXT_VL;
  7887. // If we need an extension, we should be changing the type.
  7888. SDLoc DL(Root);
  7889. auto [Mask, VL] = getMaskAndVL(Root);
  7890. switch (OrigOperand.getOpcode()) {
  7891. case RISCVISD::VSEXT_VL:
  7892. case RISCVISD::VZEXT_VL:
  7893. return DAG.getNode(ExtOpc, DL, NarrowVT, Source, Mask, VL);
  7894. case RISCVISD::VMV_V_X_VL:
  7895. return DAG.getNode(RISCVISD::VMV_V_X_VL, DL, NarrowVT,
  7896. DAG.getUNDEF(NarrowVT), Source.getOperand(1), VL);
  7897. default:
  7898. // Other opcodes can only come from the original LHS of VW(ADD|SUB)_W_VL
  7899. // and that operand should already have the right NarrowVT so no
  7900. // extension should be required at this point.
  7901. llvm_unreachable("Unsupported opcode");
  7902. }
  7903. }
  7904. /// Helper function to get the narrow type for \p Root.
  7905. /// The narrow type is the type of \p Root where we divided the size of each
  7906. /// element by 2. E.g., if Root's type <2xi16> -> narrow type <2xi8>.
  7907. /// \pre The size of the type of the elements of Root must be a multiple of 2
  7908. /// and be greater than 16.
  7909. static MVT getNarrowType(const SDNode *Root) {
  7910. MVT VT = Root->getSimpleValueType(0);
  7911. // Determine the narrow size.
  7912. unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
  7913. assert(NarrowSize >= 8 && "Trying to extend something we can't represent");
  7914. MVT NarrowVT = MVT::getVectorVT(MVT::getIntegerVT(NarrowSize),
  7915. VT.getVectorElementCount());
  7916. return NarrowVT;
  7917. }
  7918. /// Return the opcode required to materialize the folding of the sign
  7919. /// extensions (\p IsSExt == true) or zero extensions (IsSExt == false) for
  7920. /// both operands for \p Opcode.
  7921. /// Put differently, get the opcode to materialize:
  7922. /// - ISExt == true: \p Opcode(sext(a), sext(b)) -> newOpcode(a, b)
  7923. /// - ISExt == false: \p Opcode(zext(a), zext(b)) -> newOpcode(a, b)
  7924. /// \pre \p Opcode represents a supported root (\see ::isSupportedRoot()).
  7925. static unsigned getSameExtensionOpcode(unsigned Opcode, bool IsSExt) {
  7926. switch (Opcode) {
  7927. case RISCVISD::ADD_VL:
  7928. case RISCVISD::VWADD_W_VL:
  7929. case RISCVISD::VWADDU_W_VL:
  7930. return IsSExt ? RISCVISD::VWADD_VL : RISCVISD::VWADDU_VL;
  7931. case RISCVISD::MUL_VL:
  7932. return IsSExt ? RISCVISD::VWMUL_VL : RISCVISD::VWMULU_VL;
  7933. case RISCVISD::SUB_VL:
  7934. case RISCVISD::VWSUB_W_VL:
  7935. case RISCVISD::VWSUBU_W_VL:
  7936. return IsSExt ? RISCVISD::VWSUB_VL : RISCVISD::VWSUBU_VL;
  7937. default:
  7938. llvm_unreachable("Unexpected opcode");
  7939. }
  7940. }
  7941. /// Get the opcode to materialize \p Opcode(sext(a), zext(b)) ->
  7942. /// newOpcode(a, b).
  7943. static unsigned getSUOpcode(unsigned Opcode) {
  7944. assert(Opcode == RISCVISD::MUL_VL && "SU is only supported for MUL");
  7945. return RISCVISD::VWMULSU_VL;
  7946. }
  7947. /// Get the opcode to materialize \p Opcode(a, s|zext(b)) ->
  7948. /// newOpcode(a, b).
  7949. static unsigned getWOpcode(unsigned Opcode, bool IsSExt) {
  7950. switch (Opcode) {
  7951. case RISCVISD::ADD_VL:
  7952. return IsSExt ? RISCVISD::VWADD_W_VL : RISCVISD::VWADDU_W_VL;
  7953. case RISCVISD::SUB_VL:
  7954. return IsSExt ? RISCVISD::VWSUB_W_VL : RISCVISD::VWSUBU_W_VL;
  7955. default:
  7956. llvm_unreachable("Unexpected opcode");
  7957. }
  7958. }
  7959. using CombineToTry = std::function<std::optional<CombineResult>(
  7960. SDNode * /*Root*/, const NodeExtensionHelper & /*LHS*/,
  7961. const NodeExtensionHelper & /*RHS*/)>;
  7962. /// Check if this node needs to be fully folded or extended for all users.
  7963. bool needToPromoteOtherUsers() const { return EnforceOneUse; }
  7964. /// Helper method to set the various fields of this struct based on the
  7965. /// type of \p Root.
  7966. void fillUpExtensionSupport(SDNode *Root, SelectionDAG &DAG) {
  7967. SupportsZExt = false;
  7968. SupportsSExt = false;
  7969. EnforceOneUse = true;
  7970. CheckMask = true;
  7971. switch (OrigOperand.getOpcode()) {
  7972. case RISCVISD::VZEXT_VL:
  7973. SupportsZExt = true;
  7974. Mask = OrigOperand.getOperand(1);
  7975. VL = OrigOperand.getOperand(2);
  7976. break;
  7977. case RISCVISD::VSEXT_VL:
  7978. SupportsSExt = true;
  7979. Mask = OrigOperand.getOperand(1);
  7980. VL = OrigOperand.getOperand(2);
  7981. break;
  7982. case RISCVISD::VMV_V_X_VL: {
  7983. // Historically, we didn't care about splat values not disappearing during
  7984. // combines.
  7985. EnforceOneUse = false;
  7986. CheckMask = false;
  7987. VL = OrigOperand.getOperand(2);
  7988. // The operand is a splat of a scalar.
  7989. // The pasthru must be undef for tail agnostic.
  7990. if (!OrigOperand.getOperand(0).isUndef())
  7991. break;
  7992. // Get the scalar value.
  7993. SDValue Op = OrigOperand.getOperand(1);
  7994. // See if we have enough sign bits or zero bits in the scalar to use a
  7995. // widening opcode by splatting to smaller element size.
  7996. MVT VT = Root->getSimpleValueType(0);
  7997. unsigned EltBits = VT.getScalarSizeInBits();
  7998. unsigned ScalarBits = Op.getValueSizeInBits();
  7999. // Make sure we're getting all element bits from the scalar register.
  8000. // FIXME: Support implicit sign extension of vmv.v.x?
  8001. if (ScalarBits < EltBits)
  8002. break;
  8003. unsigned NarrowSize = VT.getScalarSizeInBits() / 2;
  8004. // If the narrow type cannot be expressed with a legal VMV,
  8005. // this is not a valid candidate.
  8006. if (NarrowSize < 8)
  8007. break;
  8008. if (DAG.ComputeMaxSignificantBits(Op) <= NarrowSize)
  8009. SupportsSExt = true;
  8010. if (DAG.MaskedValueIsZero(Op,
  8011. APInt::getBitsSetFrom(ScalarBits, NarrowSize)))
  8012. SupportsZExt = true;
  8013. break;
  8014. }
  8015. default:
  8016. break;
  8017. }
  8018. }
  8019. /// Check if \p Root supports any extension folding combines.
  8020. static bool isSupportedRoot(const SDNode *Root) {
  8021. switch (Root->getOpcode()) {
  8022. case RISCVISD::ADD_VL:
  8023. case RISCVISD::MUL_VL:
  8024. case RISCVISD::VWADD_W_VL:
  8025. case RISCVISD::VWADDU_W_VL:
  8026. case RISCVISD::SUB_VL:
  8027. case RISCVISD::VWSUB_W_VL:
  8028. case RISCVISD::VWSUBU_W_VL:
  8029. return true;
  8030. default:
  8031. return false;
  8032. }
  8033. }
  8034. /// Build a NodeExtensionHelper for \p Root.getOperand(\p OperandIdx).
  8035. NodeExtensionHelper(SDNode *Root, unsigned OperandIdx, SelectionDAG &DAG) {
  8036. assert(isSupportedRoot(Root) && "Trying to build an helper with an "
  8037. "unsupported root");
  8038. assert(OperandIdx < 2 && "Requesting something else than LHS or RHS");
  8039. OrigOperand = Root->getOperand(OperandIdx);
  8040. unsigned Opc = Root->getOpcode();
  8041. switch (Opc) {
  8042. // We consider VW<ADD|SUB>(U)_W(LHS, RHS) as if they were
  8043. // <ADD|SUB>(LHS, S|ZEXT(RHS))
  8044. case RISCVISD::VWADD_W_VL:
  8045. case RISCVISD::VWADDU_W_VL:
  8046. case RISCVISD::VWSUB_W_VL:
  8047. case RISCVISD::VWSUBU_W_VL:
  8048. if (OperandIdx == 1) {
  8049. SupportsZExt =
  8050. Opc == RISCVISD::VWADDU_W_VL || Opc == RISCVISD::VWSUBU_W_VL;
  8051. SupportsSExt = !SupportsZExt;
  8052. std::tie(Mask, VL) = getMaskAndVL(Root);
  8053. CheckMask = true;
  8054. // There's no existing extension here, so we don't have to worry about
  8055. // making sure it gets removed.
  8056. EnforceOneUse = false;
  8057. break;
  8058. }
  8059. [[fallthrough]];
  8060. default:
  8061. fillUpExtensionSupport(Root, DAG);
  8062. break;
  8063. }
  8064. }
  8065. /// Check if this operand is compatible with the given vector length \p VL.
  8066. bool isVLCompatible(SDValue VL) const {
  8067. return this->VL != SDValue() && this->VL == VL;
  8068. }
  8069. /// Check if this operand is compatible with the given \p Mask.
  8070. bool isMaskCompatible(SDValue Mask) const {
  8071. return !CheckMask || (this->Mask != SDValue() && this->Mask == Mask);
  8072. }
  8073. /// Helper function to get the Mask and VL from \p Root.
  8074. static std::pair<SDValue, SDValue> getMaskAndVL(const SDNode *Root) {
  8075. assert(isSupportedRoot(Root) && "Unexpected root");
  8076. return std::make_pair(Root->getOperand(3), Root->getOperand(4));
  8077. }
  8078. /// Check if the Mask and VL of this operand are compatible with \p Root.
  8079. bool areVLAndMaskCompatible(const SDNode *Root) const {
  8080. auto [Mask, VL] = getMaskAndVL(Root);
  8081. return isMaskCompatible(Mask) && isVLCompatible(VL);
  8082. }
  8083. /// Helper function to check if \p N is commutative with respect to the
  8084. /// foldings that are supported by this class.
  8085. static bool isCommutative(const SDNode *N) {
  8086. switch (N->getOpcode()) {
  8087. case RISCVISD::ADD_VL:
  8088. case RISCVISD::MUL_VL:
  8089. case RISCVISD::VWADD_W_VL:
  8090. case RISCVISD::VWADDU_W_VL:
  8091. return true;
  8092. case RISCVISD::SUB_VL:
  8093. case RISCVISD::VWSUB_W_VL:
  8094. case RISCVISD::VWSUBU_W_VL:
  8095. return false;
  8096. default:
  8097. llvm_unreachable("Unexpected opcode");
  8098. }
  8099. }
  8100. /// Get a list of combine to try for folding extensions in \p Root.
  8101. /// Note that each returned CombineToTry function doesn't actually modify
  8102. /// anything. Instead they produce an optional CombineResult that if not None,
  8103. /// need to be materialized for the combine to be applied.
  8104. /// \see CombineResult::materialize.
  8105. /// If the related CombineToTry function returns std::nullopt, that means the
  8106. /// combine didn't match.
  8107. static SmallVector<CombineToTry> getSupportedFoldings(const SDNode *Root);
  8108. };
  8109. /// Helper structure that holds all the necessary information to materialize a
  8110. /// combine that does some extension folding.
  8111. struct CombineResult {
  8112. /// Opcode to be generated when materializing the combine.
  8113. unsigned TargetOpcode;
  8114. // No value means no extension is needed. If extension is needed, the value
  8115. // indicates if it needs to be sign extended.
  8116. std::optional<bool> SExtLHS;
  8117. std::optional<bool> SExtRHS;
  8118. /// Root of the combine.
  8119. SDNode *Root;
  8120. /// LHS of the TargetOpcode.
  8121. NodeExtensionHelper LHS;
  8122. /// RHS of the TargetOpcode.
  8123. NodeExtensionHelper RHS;
  8124. CombineResult(unsigned TargetOpcode, SDNode *Root,
  8125. const NodeExtensionHelper &LHS, std::optional<bool> SExtLHS,
  8126. const NodeExtensionHelper &RHS, std::optional<bool> SExtRHS)
  8127. : TargetOpcode(TargetOpcode), SExtLHS(SExtLHS), SExtRHS(SExtRHS),
  8128. Root(Root), LHS(LHS), RHS(RHS) {}
  8129. /// Return a value that uses TargetOpcode and that can be used to replace
  8130. /// Root.
  8131. /// The actual replacement is *not* done in that method.
  8132. SDValue materialize(SelectionDAG &DAG) const {
  8133. SDValue Mask, VL, Merge;
  8134. std::tie(Mask, VL) = NodeExtensionHelper::getMaskAndVL(Root);
  8135. Merge = Root->getOperand(2);
  8136. return DAG.getNode(TargetOpcode, SDLoc(Root), Root->getValueType(0),
  8137. LHS.getOrCreateExtendedOp(Root, DAG, SExtLHS),
  8138. RHS.getOrCreateExtendedOp(Root, DAG, SExtRHS), Merge,
  8139. Mask, VL);
  8140. }
  8141. };
  8142. /// Check if \p Root follows a pattern Root(ext(LHS), ext(RHS))
  8143. /// where `ext` is the same for both LHS and RHS (i.e., both are sext or both
  8144. /// are zext) and LHS and RHS can be folded into Root.
  8145. /// AllowSExt and AllozZExt define which form `ext` can take in this pattern.
  8146. ///
  8147. /// \note If the pattern can match with both zext and sext, the returned
  8148. /// CombineResult will feature the zext result.
  8149. ///
  8150. /// \returns std::nullopt if the pattern doesn't match or a CombineResult that
  8151. /// can be used to apply the pattern.
  8152. static std::optional<CombineResult>
  8153. canFoldToVWWithSameExtensionImpl(SDNode *Root, const NodeExtensionHelper &LHS,
  8154. const NodeExtensionHelper &RHS, bool AllowSExt,
  8155. bool AllowZExt) {
  8156. assert((AllowSExt || AllowZExt) && "Forgot to set what you want?");
  8157. if (!LHS.areVLAndMaskCompatible(Root) || !RHS.areVLAndMaskCompatible(Root))
  8158. return std::nullopt;
  8159. if (AllowZExt && LHS.SupportsZExt && RHS.SupportsZExt)
  8160. return CombineResult(NodeExtensionHelper::getSameExtensionOpcode(
  8161. Root->getOpcode(), /*IsSExt=*/false),
  8162. Root, LHS, /*SExtLHS=*/false, RHS,
  8163. /*SExtRHS=*/false);
  8164. if (AllowSExt && LHS.SupportsSExt && RHS.SupportsSExt)
  8165. return CombineResult(NodeExtensionHelper::getSameExtensionOpcode(
  8166. Root->getOpcode(), /*IsSExt=*/true),
  8167. Root, LHS, /*SExtLHS=*/true, RHS,
  8168. /*SExtRHS=*/true);
  8169. return std::nullopt;
  8170. }
  8171. /// Check if \p Root follows a pattern Root(ext(LHS), ext(RHS))
  8172. /// where `ext` is the same for both LHS and RHS (i.e., both are sext or both
  8173. /// are zext) and LHS and RHS can be folded into Root.
  8174. ///
  8175. /// \returns std::nullopt if the pattern doesn't match or a CombineResult that
  8176. /// can be used to apply the pattern.
  8177. static std::optional<CombineResult>
  8178. canFoldToVWWithSameExtension(SDNode *Root, const NodeExtensionHelper &LHS,
  8179. const NodeExtensionHelper &RHS) {
  8180. return canFoldToVWWithSameExtensionImpl(Root, LHS, RHS, /*AllowSExt=*/true,
  8181. /*AllowZExt=*/true);
  8182. }
  8183. /// Check if \p Root follows a pattern Root(LHS, ext(RHS))
  8184. ///
  8185. /// \returns std::nullopt if the pattern doesn't match or a CombineResult that
  8186. /// can be used to apply the pattern.
  8187. static std::optional<CombineResult>
  8188. canFoldToVW_W(SDNode *Root, const NodeExtensionHelper &LHS,
  8189. const NodeExtensionHelper &RHS) {
  8190. if (!RHS.areVLAndMaskCompatible(Root))
  8191. return std::nullopt;
  8192. // FIXME: Is it useful to form a vwadd.wx or vwsub.wx if it removes a scalar
  8193. // sext/zext?
  8194. // Control this behavior behind an option (AllowSplatInVW_W) for testing
  8195. // purposes.
  8196. if (RHS.SupportsZExt && (!RHS.isSplat() || AllowSplatInVW_W))
  8197. return CombineResult(
  8198. NodeExtensionHelper::getWOpcode(Root->getOpcode(), /*IsSExt=*/false),
  8199. Root, LHS, /*SExtLHS=*/std::nullopt, RHS, /*SExtRHS=*/false);
  8200. if (RHS.SupportsSExt && (!RHS.isSplat() || AllowSplatInVW_W))
  8201. return CombineResult(
  8202. NodeExtensionHelper::getWOpcode(Root->getOpcode(), /*IsSExt=*/true),
  8203. Root, LHS, /*SExtLHS=*/std::nullopt, RHS, /*SExtRHS=*/true);
  8204. return std::nullopt;
  8205. }
  8206. /// Check if \p Root follows a pattern Root(sext(LHS), sext(RHS))
  8207. ///
  8208. /// \returns std::nullopt if the pattern doesn't match or a CombineResult that
  8209. /// can be used to apply the pattern.
  8210. static std::optional<CombineResult>
  8211. canFoldToVWWithSEXT(SDNode *Root, const NodeExtensionHelper &LHS,
  8212. const NodeExtensionHelper &RHS) {
  8213. return canFoldToVWWithSameExtensionImpl(Root, LHS, RHS, /*AllowSExt=*/true,
  8214. /*AllowZExt=*/false);
  8215. }
  8216. /// Check if \p Root follows a pattern Root(zext(LHS), zext(RHS))
  8217. ///
  8218. /// \returns std::nullopt if the pattern doesn't match or a CombineResult that
  8219. /// can be used to apply the pattern.
  8220. static std::optional<CombineResult>
  8221. canFoldToVWWithZEXT(SDNode *Root, const NodeExtensionHelper &LHS,
  8222. const NodeExtensionHelper &RHS) {
  8223. return canFoldToVWWithSameExtensionImpl(Root, LHS, RHS, /*AllowSExt=*/false,
  8224. /*AllowZExt=*/true);
  8225. }
  8226. /// Check if \p Root follows a pattern Root(sext(LHS), zext(RHS))
  8227. ///
  8228. /// \returns std::nullopt if the pattern doesn't match or a CombineResult that
  8229. /// can be used to apply the pattern.
  8230. static std::optional<CombineResult>
  8231. canFoldToVW_SU(SDNode *Root, const NodeExtensionHelper &LHS,
  8232. const NodeExtensionHelper &RHS) {
  8233. if (!LHS.SupportsSExt || !RHS.SupportsZExt)
  8234. return std::nullopt;
  8235. if (!LHS.areVLAndMaskCompatible(Root) || !RHS.areVLAndMaskCompatible(Root))
  8236. return std::nullopt;
  8237. return CombineResult(NodeExtensionHelper::getSUOpcode(Root->getOpcode()),
  8238. Root, LHS, /*SExtLHS=*/true, RHS, /*SExtRHS=*/false);
  8239. }
  8240. SmallVector<NodeExtensionHelper::CombineToTry>
  8241. NodeExtensionHelper::getSupportedFoldings(const SDNode *Root) {
  8242. SmallVector<CombineToTry> Strategies;
  8243. switch (Root->getOpcode()) {
  8244. case RISCVISD::ADD_VL:
  8245. case RISCVISD::SUB_VL:
  8246. // add|sub -> vwadd(u)|vwsub(u)
  8247. Strategies.push_back(canFoldToVWWithSameExtension);
  8248. // add|sub -> vwadd(u)_w|vwsub(u)_w
  8249. Strategies.push_back(canFoldToVW_W);
  8250. break;
  8251. case RISCVISD::MUL_VL:
  8252. // mul -> vwmul(u)
  8253. Strategies.push_back(canFoldToVWWithSameExtension);
  8254. // mul -> vwmulsu
  8255. Strategies.push_back(canFoldToVW_SU);
  8256. break;
  8257. case RISCVISD::VWADD_W_VL:
  8258. case RISCVISD::VWSUB_W_VL:
  8259. // vwadd_w|vwsub_w -> vwadd|vwsub
  8260. Strategies.push_back(canFoldToVWWithSEXT);
  8261. break;
  8262. case RISCVISD::VWADDU_W_VL:
  8263. case RISCVISD::VWSUBU_W_VL:
  8264. // vwaddu_w|vwsubu_w -> vwaddu|vwsubu
  8265. Strategies.push_back(canFoldToVWWithZEXT);
  8266. break;
  8267. default:
  8268. llvm_unreachable("Unexpected opcode");
  8269. }
  8270. return Strategies;
  8271. }
  8272. } // End anonymous namespace.
  8273. /// Combine a binary operation to its equivalent VW or VW_W form.
  8274. /// The supported combines are:
  8275. /// add_vl -> vwadd(u) | vwadd(u)_w
  8276. /// sub_vl -> vwsub(u) | vwsub(u)_w
  8277. /// mul_vl -> vwmul(u) | vwmul_su
  8278. /// vwadd_w(u) -> vwadd(u)
  8279. /// vwub_w(u) -> vwadd(u)
  8280. static SDValue
  8281. combineBinOp_VLToVWBinOp_VL(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
  8282. SelectionDAG &DAG = DCI.DAG;
  8283. assert(NodeExtensionHelper::isSupportedRoot(N) &&
  8284. "Shouldn't have called this method");
  8285. SmallVector<SDNode *> Worklist;
  8286. SmallSet<SDNode *, 8> Inserted;
  8287. Worklist.push_back(N);
  8288. Inserted.insert(N);
  8289. SmallVector<CombineResult> CombinesToApply;
  8290. while (!Worklist.empty()) {
  8291. SDNode *Root = Worklist.pop_back_val();
  8292. if (!NodeExtensionHelper::isSupportedRoot(Root))
  8293. return SDValue();
  8294. NodeExtensionHelper LHS(N, 0, DAG);
  8295. NodeExtensionHelper RHS(N, 1, DAG);
  8296. auto AppendUsersIfNeeded = [&Worklist,
  8297. &Inserted](const NodeExtensionHelper &Op) {
  8298. if (Op.needToPromoteOtherUsers()) {
  8299. for (SDNode *TheUse : Op.OrigOperand->uses()) {
  8300. if (Inserted.insert(TheUse).second)
  8301. Worklist.push_back(TheUse);
  8302. }
  8303. }
  8304. };
  8305. // Control the compile time by limiting the number of node we look at in
  8306. // total.
  8307. if (Inserted.size() > ExtensionMaxWebSize)
  8308. return SDValue();
  8309. SmallVector<NodeExtensionHelper::CombineToTry> FoldingStrategies =
  8310. NodeExtensionHelper::getSupportedFoldings(N);
  8311. assert(!FoldingStrategies.empty() && "Nothing to be folded");
  8312. bool Matched = false;
  8313. for (int Attempt = 0;
  8314. (Attempt != 1 + NodeExtensionHelper::isCommutative(N)) && !Matched;
  8315. ++Attempt) {
  8316. for (NodeExtensionHelper::CombineToTry FoldingStrategy :
  8317. FoldingStrategies) {
  8318. std::optional<CombineResult> Res = FoldingStrategy(N, LHS, RHS);
  8319. if (Res) {
  8320. Matched = true;
  8321. CombinesToApply.push_back(*Res);
  8322. // All the inputs that are extended need to be folded, otherwise
  8323. // we would be leaving the old input (since it is may still be used),
  8324. // and the new one.
  8325. if (Res->SExtLHS.has_value())
  8326. AppendUsersIfNeeded(LHS);
  8327. if (Res->SExtRHS.has_value())
  8328. AppendUsersIfNeeded(RHS);
  8329. break;
  8330. }
  8331. }
  8332. std::swap(LHS, RHS);
  8333. }
  8334. // Right now we do an all or nothing approach.
  8335. if (!Matched)
  8336. return SDValue();
  8337. }
  8338. // Store the value for the replacement of the input node separately.
  8339. SDValue InputRootReplacement;
  8340. // We do the RAUW after we materialize all the combines, because some replaced
  8341. // nodes may be feeding some of the yet-to-be-replaced nodes. Put differently,
  8342. // some of these nodes may appear in the NodeExtensionHelpers of some of the
  8343. // yet-to-be-visited CombinesToApply roots.
  8344. SmallVector<std::pair<SDValue, SDValue>> ValuesToReplace;
  8345. ValuesToReplace.reserve(CombinesToApply.size());
  8346. for (CombineResult Res : CombinesToApply) {
  8347. SDValue NewValue = Res.materialize(DAG);
  8348. if (!InputRootReplacement) {
  8349. assert(Res.Root == N &&
  8350. "First element is expected to be the current node");
  8351. InputRootReplacement = NewValue;
  8352. } else {
  8353. ValuesToReplace.emplace_back(SDValue(Res.Root, 0), NewValue);
  8354. }
  8355. }
  8356. for (std::pair<SDValue, SDValue> OldNewValues : ValuesToReplace) {
  8357. DAG.ReplaceAllUsesOfValueWith(OldNewValues.first, OldNewValues.second);
  8358. DCI.AddToWorklist(OldNewValues.second.getNode());
  8359. }
  8360. return InputRootReplacement;
  8361. }
  8362. // Fold
  8363. // (fp_to_int (froundeven X)) -> fcvt X, rne
  8364. // (fp_to_int (ftrunc X)) -> fcvt X, rtz
  8365. // (fp_to_int (ffloor X)) -> fcvt X, rdn
  8366. // (fp_to_int (fceil X)) -> fcvt X, rup
  8367. // (fp_to_int (fround X)) -> fcvt X, rmm
  8368. static SDValue performFP_TO_INTCombine(SDNode *N,
  8369. TargetLowering::DAGCombinerInfo &DCI,
  8370. const RISCVSubtarget &Subtarget) {
  8371. SelectionDAG &DAG = DCI.DAG;
  8372. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8373. MVT XLenVT = Subtarget.getXLenVT();
  8374. SDValue Src = N->getOperand(0);
  8375. // Ensure the FP type is legal.
  8376. if (!TLI.isTypeLegal(Src.getValueType()))
  8377. return SDValue();
  8378. // Don't do this for f16 with Zfhmin and not Zfh.
  8379. if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
  8380. return SDValue();
  8381. RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src.getOpcode());
  8382. if (FRM == RISCVFPRndMode::Invalid)
  8383. return SDValue();
  8384. SDLoc DL(N);
  8385. bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
  8386. EVT VT = N->getValueType(0);
  8387. if (VT.isVector() && TLI.isTypeLegal(VT)) {
  8388. MVT SrcVT = Src.getSimpleValueType();
  8389. MVT SrcContainerVT = SrcVT;
  8390. MVT ContainerVT = VT.getSimpleVT();
  8391. SDValue XVal = Src.getOperand(0);
  8392. // For widening and narrowing conversions we just combine it into a
  8393. // VFCVT_..._VL node, as there are no specific VFWCVT/VFNCVT VL nodes. They
  8394. // end up getting lowered to their appropriate pseudo instructions based on
  8395. // their operand types
  8396. if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits() * 2 ||
  8397. VT.getScalarSizeInBits() * 2 < SrcVT.getScalarSizeInBits())
  8398. return SDValue();
  8399. // Make fixed-length vectors scalable first
  8400. if (SrcVT.isFixedLengthVector()) {
  8401. SrcContainerVT = getContainerForFixedLengthVector(DAG, SrcVT, Subtarget);
  8402. XVal = convertToScalableVector(SrcContainerVT, XVal, DAG, Subtarget);
  8403. ContainerVT =
  8404. getContainerForFixedLengthVector(DAG, ContainerVT, Subtarget);
  8405. }
  8406. auto [Mask, VL] =
  8407. getDefaultVLOps(SrcVT, SrcContainerVT, DL, DAG, Subtarget);
  8408. SDValue FpToInt;
  8409. if (FRM == RISCVFPRndMode::RTZ) {
  8410. // Use the dedicated trunc static rounding mode if we're truncating so we
  8411. // don't need to generate calls to fsrmi/fsrm
  8412. unsigned Opc =
  8413. IsSigned ? RISCVISD::VFCVT_RTZ_X_F_VL : RISCVISD::VFCVT_RTZ_XU_F_VL;
  8414. FpToInt = DAG.getNode(Opc, DL, ContainerVT, XVal, Mask, VL);
  8415. } else {
  8416. unsigned Opc =
  8417. IsSigned ? RISCVISD::VFCVT_RM_X_F_VL : RISCVISD::VFCVT_RM_XU_F_VL;
  8418. FpToInt = DAG.getNode(Opc, DL, ContainerVT, XVal, Mask,
  8419. DAG.getTargetConstant(FRM, DL, XLenVT), VL);
  8420. }
  8421. // If converted from fixed-length to scalable, convert back
  8422. if (VT.isFixedLengthVector())
  8423. FpToInt = convertFromScalableVector(VT, FpToInt, DAG, Subtarget);
  8424. return FpToInt;
  8425. }
  8426. // Only handle XLen or i32 types. Other types narrower than XLen will
  8427. // eventually be legalized to XLenVT.
  8428. if (VT != MVT::i32 && VT != XLenVT)
  8429. return SDValue();
  8430. unsigned Opc;
  8431. if (VT == XLenVT)
  8432. Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
  8433. else
  8434. Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
  8435. SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src.getOperand(0),
  8436. DAG.getTargetConstant(FRM, DL, XLenVT));
  8437. return DAG.getNode(ISD::TRUNCATE, DL, VT, FpToInt);
  8438. }
  8439. // Fold
  8440. // (fp_to_int_sat (froundeven X)) -> (select X == nan, 0, (fcvt X, rne))
  8441. // (fp_to_int_sat (ftrunc X)) -> (select X == nan, 0, (fcvt X, rtz))
  8442. // (fp_to_int_sat (ffloor X)) -> (select X == nan, 0, (fcvt X, rdn))
  8443. // (fp_to_int_sat (fceil X)) -> (select X == nan, 0, (fcvt X, rup))
  8444. // (fp_to_int_sat (fround X)) -> (select X == nan, 0, (fcvt X, rmm))
  8445. static SDValue performFP_TO_INT_SATCombine(SDNode *N,
  8446. TargetLowering::DAGCombinerInfo &DCI,
  8447. const RISCVSubtarget &Subtarget) {
  8448. SelectionDAG &DAG = DCI.DAG;
  8449. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8450. MVT XLenVT = Subtarget.getXLenVT();
  8451. // Only handle XLen types. Other types narrower than XLen will eventually be
  8452. // legalized to XLenVT.
  8453. EVT DstVT = N->getValueType(0);
  8454. if (DstVT != XLenVT)
  8455. return SDValue();
  8456. SDValue Src = N->getOperand(0);
  8457. // Ensure the FP type is also legal.
  8458. if (!TLI.isTypeLegal(Src.getValueType()))
  8459. return SDValue();
  8460. // Don't do this for f16 with Zfhmin and not Zfh.
  8461. if (Src.getValueType() == MVT::f16 && !Subtarget.hasStdExtZfh())
  8462. return SDValue();
  8463. EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
  8464. RISCVFPRndMode::RoundingMode FRM = matchRoundingOp(Src.getOpcode());
  8465. if (FRM == RISCVFPRndMode::Invalid)
  8466. return SDValue();
  8467. bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT_SAT;
  8468. unsigned Opc;
  8469. if (SatVT == DstVT)
  8470. Opc = IsSigned ? RISCVISD::FCVT_X : RISCVISD::FCVT_XU;
  8471. else if (DstVT == MVT::i64 && SatVT == MVT::i32)
  8472. Opc = IsSigned ? RISCVISD::FCVT_W_RV64 : RISCVISD::FCVT_WU_RV64;
  8473. else
  8474. return SDValue();
  8475. // FIXME: Support other SatVTs by clamping before or after the conversion.
  8476. Src = Src.getOperand(0);
  8477. SDLoc DL(N);
  8478. SDValue FpToInt = DAG.getNode(Opc, DL, XLenVT, Src,
  8479. DAG.getTargetConstant(FRM, DL, XLenVT));
  8480. // fcvt.wu.* sign extends bit 31 on RV64. FP_TO_UINT_SAT expects to zero
  8481. // extend.
  8482. if (Opc == RISCVISD::FCVT_WU_RV64)
  8483. FpToInt = DAG.getZeroExtendInReg(FpToInt, DL, MVT::i32);
  8484. // RISCV FP-to-int conversions saturate to the destination register size, but
  8485. // don't produce 0 for nan.
  8486. SDValue ZeroInt = DAG.getConstant(0, DL, DstVT);
  8487. return DAG.getSelectCC(DL, Src, Src, ZeroInt, FpToInt, ISD::CondCode::SETUO);
  8488. }
  8489. // Combine (bitreverse (bswap X)) to the BREV8 GREVI encoding if the type is
  8490. // smaller than XLenVT.
  8491. static SDValue performBITREVERSECombine(SDNode *N, SelectionDAG &DAG,
  8492. const RISCVSubtarget &Subtarget) {
  8493. assert(Subtarget.hasStdExtZbkb() && "Unexpected extension");
  8494. SDValue Src = N->getOperand(0);
  8495. if (Src.getOpcode() != ISD::BSWAP)
  8496. return SDValue();
  8497. EVT VT = N->getValueType(0);
  8498. if (!VT.isScalarInteger() || VT.getSizeInBits() >= Subtarget.getXLen() ||
  8499. !isPowerOf2_32(VT.getSizeInBits()))
  8500. return SDValue();
  8501. SDLoc DL(N);
  8502. return DAG.getNode(RISCVISD::BREV8, DL, VT, Src.getOperand(0));
  8503. }
  8504. // Convert from one FMA opcode to another based on whether we are negating the
  8505. // multiply result and/or the accumulator.
  8506. // NOTE: Only supports RVV operations with VL.
  8507. static unsigned negateFMAOpcode(unsigned Opcode, bool NegMul, bool NegAcc) {
  8508. assert((NegMul || NegAcc) && "Not negating anything?");
  8509. // Negating the multiply result changes ADD<->SUB and toggles 'N'.
  8510. if (NegMul) {
  8511. // clang-format off
  8512. switch (Opcode) {
  8513. default: llvm_unreachable("Unexpected opcode");
  8514. case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break;
  8515. case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break;
  8516. case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break;
  8517. case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break;
  8518. }
  8519. // clang-format on
  8520. }
  8521. // Negating the accumulator changes ADD<->SUB.
  8522. if (NegAcc) {
  8523. // clang-format off
  8524. switch (Opcode) {
  8525. default: llvm_unreachable("Unexpected opcode");
  8526. case RISCVISD::VFMADD_VL: Opcode = RISCVISD::VFMSUB_VL; break;
  8527. case RISCVISD::VFMSUB_VL: Opcode = RISCVISD::VFMADD_VL; break;
  8528. case RISCVISD::VFNMADD_VL: Opcode = RISCVISD::VFNMSUB_VL; break;
  8529. case RISCVISD::VFNMSUB_VL: Opcode = RISCVISD::VFNMADD_VL; break;
  8530. }
  8531. // clang-format on
  8532. }
  8533. return Opcode;
  8534. }
  8535. static SDValue performSRACombine(SDNode *N, SelectionDAG &DAG,
  8536. const RISCVSubtarget &Subtarget) {
  8537. assert(N->getOpcode() == ISD::SRA && "Unexpected opcode");
  8538. if (N->getValueType(0) != MVT::i64 || !Subtarget.is64Bit())
  8539. return SDValue();
  8540. if (!isa<ConstantSDNode>(N->getOperand(1)))
  8541. return SDValue();
  8542. uint64_t ShAmt = N->getConstantOperandVal(1);
  8543. if (ShAmt > 32)
  8544. return SDValue();
  8545. SDValue N0 = N->getOperand(0);
  8546. // Combine (sra (sext_inreg (shl X, C1), i32), C2) ->
  8547. // (sra (shl X, C1+32), C2+32) so it gets selected as SLLI+SRAI instead of
  8548. // SLLIW+SRAIW. SLLI+SRAI have compressed forms.
  8549. if (ShAmt < 32 &&
  8550. N0.getOpcode() == ISD::SIGN_EXTEND_INREG && N0.hasOneUse() &&
  8551. cast<VTSDNode>(N0.getOperand(1))->getVT() == MVT::i32 &&
  8552. N0.getOperand(0).getOpcode() == ISD::SHL && N0.getOperand(0).hasOneUse() &&
  8553. isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
  8554. uint64_t LShAmt = N0.getOperand(0).getConstantOperandVal(1);
  8555. if (LShAmt < 32) {
  8556. SDLoc ShlDL(N0.getOperand(0));
  8557. SDValue Shl = DAG.getNode(ISD::SHL, ShlDL, MVT::i64,
  8558. N0.getOperand(0).getOperand(0),
  8559. DAG.getConstant(LShAmt + 32, ShlDL, MVT::i64));
  8560. SDLoc DL(N);
  8561. return DAG.getNode(ISD::SRA, DL, MVT::i64, Shl,
  8562. DAG.getConstant(ShAmt + 32, DL, MVT::i64));
  8563. }
  8564. }
  8565. // Combine (sra (shl X, 32), 32 - C) -> (shl (sext_inreg X, i32), C)
  8566. // FIXME: Should this be a generic combine? There's a similar combine on X86.
  8567. //
  8568. // Also try these folds where an add or sub is in the middle.
  8569. // (sra (add (shl X, 32), C1), 32 - C) -> (shl (sext_inreg (add X, C1), C)
  8570. // (sra (sub C1, (shl X, 32)), 32 - C) -> (shl (sext_inreg (sub C1, X), C)
  8571. SDValue Shl;
  8572. ConstantSDNode *AddC = nullptr;
  8573. // We might have an ADD or SUB between the SRA and SHL.
  8574. bool IsAdd = N0.getOpcode() == ISD::ADD;
  8575. if ((IsAdd || N0.getOpcode() == ISD::SUB)) {
  8576. // Other operand needs to be a constant we can modify.
  8577. AddC = dyn_cast<ConstantSDNode>(N0.getOperand(IsAdd ? 1 : 0));
  8578. if (!AddC)
  8579. return SDValue();
  8580. // AddC needs to have at least 32 trailing zeros.
  8581. if (AddC->getAPIntValue().countTrailingZeros() < 32)
  8582. return SDValue();
  8583. // All users should be a shift by constant less than or equal to 32. This
  8584. // ensures we'll do this optimization for each of them to produce an
  8585. // add/sub+sext_inreg they can all share.
  8586. for (SDNode *U : N0->uses()) {
  8587. if (U->getOpcode() != ISD::SRA ||
  8588. !isa<ConstantSDNode>(U->getOperand(1)) ||
  8589. cast<ConstantSDNode>(U->getOperand(1))->getZExtValue() > 32)
  8590. return SDValue();
  8591. }
  8592. Shl = N0.getOperand(IsAdd ? 0 : 1);
  8593. } else {
  8594. // Not an ADD or SUB.
  8595. Shl = N0;
  8596. }
  8597. // Look for a shift left by 32.
  8598. if (Shl.getOpcode() != ISD::SHL || !isa<ConstantSDNode>(Shl.getOperand(1)) ||
  8599. Shl.getConstantOperandVal(1) != 32)
  8600. return SDValue();
  8601. // We if we didn't look through an add/sub, then the shl should have one use.
  8602. // If we did look through an add/sub, the sext_inreg we create is free so
  8603. // we're only creating 2 new instructions. It's enough to only remove the
  8604. // original sra+add/sub.
  8605. if (!AddC && !Shl.hasOneUse())
  8606. return SDValue();
  8607. SDLoc DL(N);
  8608. SDValue In = Shl.getOperand(0);
  8609. // If we looked through an ADD or SUB, we need to rebuild it with the shifted
  8610. // constant.
  8611. if (AddC) {
  8612. SDValue ShiftedAddC =
  8613. DAG.getConstant(AddC->getAPIntValue().lshr(32), DL, MVT::i64);
  8614. if (IsAdd)
  8615. In = DAG.getNode(ISD::ADD, DL, MVT::i64, In, ShiftedAddC);
  8616. else
  8617. In = DAG.getNode(ISD::SUB, DL, MVT::i64, ShiftedAddC, In);
  8618. }
  8619. SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, MVT::i64, In,
  8620. DAG.getValueType(MVT::i32));
  8621. if (ShAmt == 32)
  8622. return SExt;
  8623. return DAG.getNode(
  8624. ISD::SHL, DL, MVT::i64, SExt,
  8625. DAG.getConstant(32 - ShAmt, DL, MVT::i64));
  8626. }
  8627. // Invert (and/or (set cc X, Y), (xor Z, 1)) to (or/and (set !cc X, Y)), Z) if
  8628. // the result is used as the conditon of a br_cc or select_cc we can invert,
  8629. // inverting the setcc is free, and Z is 0/1. Caller will invert the
  8630. // br_cc/select_cc.
  8631. static SDValue tryDemorganOfBooleanCondition(SDValue Cond, SelectionDAG &DAG) {
  8632. bool IsAnd = Cond.getOpcode() == ISD::AND;
  8633. if (!IsAnd && Cond.getOpcode() != ISD::OR)
  8634. return SDValue();
  8635. if (!Cond.hasOneUse())
  8636. return SDValue();
  8637. SDValue Setcc = Cond.getOperand(0);
  8638. SDValue Xor = Cond.getOperand(1);
  8639. // Canonicalize setcc to LHS.
  8640. if (Setcc.getOpcode() != ISD::SETCC)
  8641. std::swap(Setcc, Xor);
  8642. // LHS should be a setcc and RHS should be an xor.
  8643. if (Setcc.getOpcode() != ISD::SETCC || !Setcc.hasOneUse() ||
  8644. Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse())
  8645. return SDValue();
  8646. // If the condition is an And, SimplifyDemandedBits may have changed
  8647. // (xor Z, 1) to (not Z).
  8648. SDValue Xor1 = Xor.getOperand(1);
  8649. if (!isOneConstant(Xor1) && !(IsAnd && isAllOnesConstant(Xor1)))
  8650. return SDValue();
  8651. EVT VT = Cond.getValueType();
  8652. SDValue Xor0 = Xor.getOperand(0);
  8653. // The LHS of the xor needs to be 0/1.
  8654. APInt Mask = APInt::getBitsSetFrom(VT.getSizeInBits(), 1);
  8655. if (!DAG.MaskedValueIsZero(Xor0, Mask))
  8656. return SDValue();
  8657. // We can only invert integer setccs.
  8658. EVT SetCCOpVT = Setcc.getOperand(0).getValueType();
  8659. if (!SetCCOpVT.isScalarInteger())
  8660. return SDValue();
  8661. ISD::CondCode CCVal = cast<CondCodeSDNode>(Setcc.getOperand(2))->get();
  8662. if (ISD::isIntEqualitySetCC(CCVal)) {
  8663. CCVal = ISD::getSetCCInverse(CCVal, SetCCOpVT);
  8664. Setcc = DAG.getSetCC(SDLoc(Setcc), VT, Setcc.getOperand(0),
  8665. Setcc.getOperand(1), CCVal);
  8666. } else if (CCVal == ISD::SETLT && isNullConstant(Setcc.getOperand(0))) {
  8667. // Invert (setlt 0, X) by converting to (setlt X, 1).
  8668. Setcc = DAG.getSetCC(SDLoc(Setcc), VT, Setcc.getOperand(1),
  8669. DAG.getConstant(1, SDLoc(Setcc), VT), CCVal);
  8670. } else if (CCVal == ISD::SETLT && isOneConstant(Setcc.getOperand(1))) {
  8671. // (setlt X, 1) by converting to (setlt 0, X).
  8672. Setcc = DAG.getSetCC(SDLoc(Setcc), VT,
  8673. DAG.getConstant(0, SDLoc(Setcc), VT),
  8674. Setcc.getOperand(0), CCVal);
  8675. } else
  8676. return SDValue();
  8677. unsigned Opc = IsAnd ? ISD::OR : ISD::AND;
  8678. return DAG.getNode(Opc, SDLoc(Cond), VT, Setcc, Xor.getOperand(0));
  8679. }
  8680. // Perform common combines for BR_CC and SELECT_CC condtions.
  8681. static bool combine_CC(SDValue &LHS, SDValue &RHS, SDValue &CC, const SDLoc &DL,
  8682. SelectionDAG &DAG, const RISCVSubtarget &Subtarget) {
  8683. ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get();
  8684. // As far as arithmetic right shift always saves the sign,
  8685. // shift can be omitted.
  8686. // Fold setlt (sra X, N), 0 -> setlt X, 0 and
  8687. // setge (sra X, N), 0 -> setge X, 0
  8688. if (auto *RHSConst = dyn_cast<ConstantSDNode>(RHS.getNode())) {
  8689. if ((CCVal == ISD::SETGE || CCVal == ISD::SETLT) &&
  8690. LHS.getOpcode() == ISD::SRA && RHSConst->isZero()) {
  8691. LHS = LHS.getOperand(0);
  8692. return true;
  8693. }
  8694. }
  8695. if (!ISD::isIntEqualitySetCC(CCVal))
  8696. return false;
  8697. // Fold ((setlt X, Y), 0, ne) -> (X, Y, lt)
  8698. // Sometimes the setcc is introduced after br_cc/select_cc has been formed.
  8699. if (LHS.getOpcode() == ISD::SETCC && isNullConstant(RHS) &&
  8700. LHS.getOperand(0).getValueType() == Subtarget.getXLenVT()) {
  8701. // If we're looking for eq 0 instead of ne 0, we need to invert the
  8702. // condition.
  8703. bool Invert = CCVal == ISD::SETEQ;
  8704. CCVal = cast<CondCodeSDNode>(LHS.getOperand(2))->get();
  8705. if (Invert)
  8706. CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
  8707. RHS = LHS.getOperand(1);
  8708. LHS = LHS.getOperand(0);
  8709. translateSetCCForBranch(DL, LHS, RHS, CCVal, DAG);
  8710. CC = DAG.getCondCode(CCVal);
  8711. return true;
  8712. }
  8713. // Fold ((xor X, Y), 0, eq/ne) -> (X, Y, eq/ne)
  8714. if (LHS.getOpcode() == ISD::XOR && isNullConstant(RHS)) {
  8715. RHS = LHS.getOperand(1);
  8716. LHS = LHS.getOperand(0);
  8717. return true;
  8718. }
  8719. // Fold ((srl (and X, 1<<C), C), 0, eq/ne) -> ((shl X, XLen-1-C), 0, ge/lt)
  8720. if (isNullConstant(RHS) && LHS.getOpcode() == ISD::SRL && LHS.hasOneUse() &&
  8721. LHS.getOperand(1).getOpcode() == ISD::Constant) {
  8722. SDValue LHS0 = LHS.getOperand(0);
  8723. if (LHS0.getOpcode() == ISD::AND &&
  8724. LHS0.getOperand(1).getOpcode() == ISD::Constant) {
  8725. uint64_t Mask = LHS0.getConstantOperandVal(1);
  8726. uint64_t ShAmt = LHS.getConstantOperandVal(1);
  8727. if (isPowerOf2_64(Mask) && Log2_64(Mask) == ShAmt) {
  8728. CCVal = CCVal == ISD::SETEQ ? ISD::SETGE : ISD::SETLT;
  8729. CC = DAG.getCondCode(CCVal);
  8730. ShAmt = LHS.getValueSizeInBits() - 1 - ShAmt;
  8731. LHS = LHS0.getOperand(0);
  8732. if (ShAmt != 0)
  8733. LHS =
  8734. DAG.getNode(ISD::SHL, DL, LHS.getValueType(), LHS0.getOperand(0),
  8735. DAG.getConstant(ShAmt, DL, LHS.getValueType()));
  8736. return true;
  8737. }
  8738. }
  8739. }
  8740. // (X, 1, setne) -> // (X, 0, seteq) if we can prove X is 0/1.
  8741. // This can occur when legalizing some floating point comparisons.
  8742. APInt Mask = APInt::getBitsSetFrom(LHS.getValueSizeInBits(), 1);
  8743. if (isOneConstant(RHS) && DAG.MaskedValueIsZero(LHS, Mask)) {
  8744. CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
  8745. CC = DAG.getCondCode(CCVal);
  8746. RHS = DAG.getConstant(0, DL, LHS.getValueType());
  8747. return true;
  8748. }
  8749. if (isNullConstant(RHS)) {
  8750. if (SDValue NewCond = tryDemorganOfBooleanCondition(LHS, DAG)) {
  8751. CCVal = ISD::getSetCCInverse(CCVal, LHS.getValueType());
  8752. CC = DAG.getCondCode(CCVal);
  8753. LHS = NewCond;
  8754. return true;
  8755. }
  8756. }
  8757. return false;
  8758. }
  8759. // Fold
  8760. // (select C, (add Y, X), Y) -> (add Y, (select C, X, 0)).
  8761. // (select C, (sub Y, X), Y) -> (sub Y, (select C, X, 0)).
  8762. // (select C, (or Y, X), Y) -> (or Y, (select C, X, 0)).
  8763. // (select C, (xor Y, X), Y) -> (xor Y, (select C, X, 0)).
  8764. static SDValue tryFoldSelectIntoOp(SDNode *N, SelectionDAG &DAG,
  8765. SDValue TrueVal, SDValue FalseVal,
  8766. bool Swapped) {
  8767. bool Commutative = true;
  8768. switch (TrueVal.getOpcode()) {
  8769. default:
  8770. return SDValue();
  8771. case ISD::SUB:
  8772. Commutative = false;
  8773. break;
  8774. case ISD::ADD:
  8775. case ISD::OR:
  8776. case ISD::XOR:
  8777. break;
  8778. }
  8779. if (!TrueVal.hasOneUse() || isa<ConstantSDNode>(FalseVal))
  8780. return SDValue();
  8781. unsigned OpToFold;
  8782. if (FalseVal == TrueVal.getOperand(0))
  8783. OpToFold = 0;
  8784. else if (Commutative && FalseVal == TrueVal.getOperand(1))
  8785. OpToFold = 1;
  8786. else
  8787. return SDValue();
  8788. EVT VT = N->getValueType(0);
  8789. SDLoc DL(N);
  8790. SDValue Zero = DAG.getConstant(0, DL, VT);
  8791. SDValue OtherOp = TrueVal.getOperand(1 - OpToFold);
  8792. if (Swapped)
  8793. std::swap(OtherOp, Zero);
  8794. SDValue NewSel = DAG.getSelect(DL, VT, N->getOperand(0), OtherOp, Zero);
  8795. return DAG.getNode(TrueVal.getOpcode(), DL, VT, FalseVal, NewSel);
  8796. }
  8797. static SDValue performSELECTCombine(SDNode *N, SelectionDAG &DAG,
  8798. const RISCVSubtarget &Subtarget) {
  8799. if (Subtarget.hasShortForwardBranchOpt())
  8800. return SDValue();
  8801. // Only support XLenVT.
  8802. if (N->getValueType(0) != Subtarget.getXLenVT())
  8803. return SDValue();
  8804. SDValue TrueVal = N->getOperand(1);
  8805. SDValue FalseVal = N->getOperand(2);
  8806. if (SDValue V = tryFoldSelectIntoOp(N, DAG, TrueVal, FalseVal, /*Swapped*/false))
  8807. return V;
  8808. return tryFoldSelectIntoOp(N, DAG, FalseVal, TrueVal, /*Swapped*/true);
  8809. }
  8810. SDValue RISCVTargetLowering::PerformDAGCombine(SDNode *N,
  8811. DAGCombinerInfo &DCI) const {
  8812. SelectionDAG &DAG = DCI.DAG;
  8813. // Helper to call SimplifyDemandedBits on an operand of N where only some low
  8814. // bits are demanded. N will be added to the Worklist if it was not deleted.
  8815. // Caller should return SDValue(N, 0) if this returns true.
  8816. auto SimplifyDemandedLowBitsHelper = [&](unsigned OpNo, unsigned LowBits) {
  8817. SDValue Op = N->getOperand(OpNo);
  8818. APInt Mask = APInt::getLowBitsSet(Op.getValueSizeInBits(), LowBits);
  8819. if (!SimplifyDemandedBits(Op, Mask, DCI))
  8820. return false;
  8821. if (N->getOpcode() != ISD::DELETED_NODE)
  8822. DCI.AddToWorklist(N);
  8823. return true;
  8824. };
  8825. switch (N->getOpcode()) {
  8826. default:
  8827. break;
  8828. case RISCVISD::SplitF64: {
  8829. SDValue Op0 = N->getOperand(0);
  8830. // If the input to SplitF64 is just BuildPairF64 then the operation is
  8831. // redundant. Instead, use BuildPairF64's operands directly.
  8832. if (Op0->getOpcode() == RISCVISD::BuildPairF64)
  8833. return DCI.CombineTo(N, Op0.getOperand(0), Op0.getOperand(1));
  8834. if (Op0->isUndef()) {
  8835. SDValue Lo = DAG.getUNDEF(MVT::i32);
  8836. SDValue Hi = DAG.getUNDEF(MVT::i32);
  8837. return DCI.CombineTo(N, Lo, Hi);
  8838. }
  8839. SDLoc DL(N);
  8840. // It's cheaper to materialise two 32-bit integers than to load a double
  8841. // from the constant pool and transfer it to integer registers through the
  8842. // stack.
  8843. if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Op0)) {
  8844. APInt V = C->getValueAPF().bitcastToAPInt();
  8845. SDValue Lo = DAG.getConstant(V.trunc(32), DL, MVT::i32);
  8846. SDValue Hi = DAG.getConstant(V.lshr(32).trunc(32), DL, MVT::i32);
  8847. return DCI.CombineTo(N, Lo, Hi);
  8848. }
  8849. // This is a target-specific version of a DAGCombine performed in
  8850. // DAGCombiner::visitBITCAST. It performs the equivalent of:
  8851. // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
  8852. // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
  8853. if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
  8854. !Op0.getNode()->hasOneUse())
  8855. break;
  8856. SDValue NewSplitF64 =
  8857. DAG.getNode(RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32),
  8858. Op0.getOperand(0));
  8859. SDValue Lo = NewSplitF64.getValue(0);
  8860. SDValue Hi = NewSplitF64.getValue(1);
  8861. APInt SignBit = APInt::getSignMask(32);
  8862. if (Op0.getOpcode() == ISD::FNEG) {
  8863. SDValue NewHi = DAG.getNode(ISD::XOR, DL, MVT::i32, Hi,
  8864. DAG.getConstant(SignBit, DL, MVT::i32));
  8865. return DCI.CombineTo(N, Lo, NewHi);
  8866. }
  8867. assert(Op0.getOpcode() == ISD::FABS);
  8868. SDValue NewHi = DAG.getNode(ISD::AND, DL, MVT::i32, Hi,
  8869. DAG.getConstant(~SignBit, DL, MVT::i32));
  8870. return DCI.CombineTo(N, Lo, NewHi);
  8871. }
  8872. case RISCVISD::SLLW:
  8873. case RISCVISD::SRAW:
  8874. case RISCVISD::SRLW:
  8875. case RISCVISD::RORW:
  8876. case RISCVISD::ROLW: {
  8877. // Only the lower 32 bits of LHS and lower 5 bits of RHS are read.
  8878. if (SimplifyDemandedLowBitsHelper(0, 32) ||
  8879. SimplifyDemandedLowBitsHelper(1, 5))
  8880. return SDValue(N, 0);
  8881. break;
  8882. }
  8883. case RISCVISD::CLZW:
  8884. case RISCVISD::CTZW: {
  8885. // Only the lower 32 bits of the first operand are read
  8886. if (SimplifyDemandedLowBitsHelper(0, 32))
  8887. return SDValue(N, 0);
  8888. break;
  8889. }
  8890. case RISCVISD::FMV_X_ANYEXTH:
  8891. case RISCVISD::FMV_X_ANYEXTW_RV64: {
  8892. SDLoc DL(N);
  8893. SDValue Op0 = N->getOperand(0);
  8894. MVT VT = N->getSimpleValueType(0);
  8895. // If the input to FMV_X_ANYEXTW_RV64 is just FMV_W_X_RV64 then the
  8896. // conversion is unnecessary and can be replaced with the FMV_W_X_RV64
  8897. // operand. Similar for FMV_X_ANYEXTH and FMV_H_X.
  8898. if ((N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 &&
  8899. Op0->getOpcode() == RISCVISD::FMV_W_X_RV64) ||
  8900. (N->getOpcode() == RISCVISD::FMV_X_ANYEXTH &&
  8901. Op0->getOpcode() == RISCVISD::FMV_H_X)) {
  8902. assert(Op0.getOperand(0).getValueType() == VT &&
  8903. "Unexpected value type!");
  8904. return Op0.getOperand(0);
  8905. }
  8906. // This is a target-specific version of a DAGCombine performed in
  8907. // DAGCombiner::visitBITCAST. It performs the equivalent of:
  8908. // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
  8909. // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
  8910. if (!(Op0.getOpcode() == ISD::FNEG || Op0.getOpcode() == ISD::FABS) ||
  8911. !Op0.getNode()->hasOneUse())
  8912. break;
  8913. SDValue NewFMV = DAG.getNode(N->getOpcode(), DL, VT, Op0.getOperand(0));
  8914. unsigned FPBits = N->getOpcode() == RISCVISD::FMV_X_ANYEXTW_RV64 ? 32 : 16;
  8915. APInt SignBit = APInt::getSignMask(FPBits).sext(VT.getSizeInBits());
  8916. if (Op0.getOpcode() == ISD::FNEG)
  8917. return DAG.getNode(ISD::XOR, DL, VT, NewFMV,
  8918. DAG.getConstant(SignBit, DL, VT));
  8919. assert(Op0.getOpcode() == ISD::FABS);
  8920. return DAG.getNode(ISD::AND, DL, VT, NewFMV,
  8921. DAG.getConstant(~SignBit, DL, VT));
  8922. }
  8923. case ISD::ADD:
  8924. return performADDCombine(N, DAG, Subtarget);
  8925. case ISD::SUB:
  8926. return performSUBCombine(N, DAG, Subtarget);
  8927. case ISD::AND:
  8928. return performANDCombine(N, DCI, Subtarget);
  8929. case ISD::OR:
  8930. return performORCombine(N, DCI, Subtarget);
  8931. case ISD::XOR:
  8932. return performXORCombine(N, DAG, Subtarget);
  8933. case ISD::FADD:
  8934. case ISD::UMAX:
  8935. case ISD::UMIN:
  8936. case ISD::SMAX:
  8937. case ISD::SMIN:
  8938. case ISD::FMAXNUM:
  8939. case ISD::FMINNUM:
  8940. return combineBinOpToReduce(N, DAG, Subtarget);
  8941. case ISD::SETCC:
  8942. return performSETCCCombine(N, DAG, Subtarget);
  8943. case ISD::SIGN_EXTEND_INREG:
  8944. return performSIGN_EXTEND_INREGCombine(N, DAG, Subtarget);
  8945. case ISD::ZERO_EXTEND:
  8946. // Fold (zero_extend (fp_to_uint X)) to prevent forming fcvt+zexti32 during
  8947. // type legalization. This is safe because fp_to_uint produces poison if
  8948. // it overflows.
  8949. if (N->getValueType(0) == MVT::i64 && Subtarget.is64Bit()) {
  8950. SDValue Src = N->getOperand(0);
  8951. if (Src.getOpcode() == ISD::FP_TO_UINT &&
  8952. isTypeLegal(Src.getOperand(0).getValueType()))
  8953. return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), MVT::i64,
  8954. Src.getOperand(0));
  8955. if (Src.getOpcode() == ISD::STRICT_FP_TO_UINT && Src.hasOneUse() &&
  8956. isTypeLegal(Src.getOperand(1).getValueType())) {
  8957. SDVTList VTs = DAG.getVTList(MVT::i64, MVT::Other);
  8958. SDValue Res = DAG.getNode(ISD::STRICT_FP_TO_UINT, SDLoc(N), VTs,
  8959. Src.getOperand(0), Src.getOperand(1));
  8960. DCI.CombineTo(N, Res);
  8961. DAG.ReplaceAllUsesOfValueWith(Src.getValue(1), Res.getValue(1));
  8962. DCI.recursivelyDeleteUnusedNodes(Src.getNode());
  8963. return SDValue(N, 0); // Return N so it doesn't get rechecked.
  8964. }
  8965. }
  8966. return SDValue();
  8967. case ISD::TRUNCATE:
  8968. return performTRUNCATECombine(N, DAG, Subtarget);
  8969. case ISD::SELECT:
  8970. return performSELECTCombine(N, DAG, Subtarget);
  8971. case RISCVISD::SELECT_CC: {
  8972. // Transform
  8973. SDValue LHS = N->getOperand(0);
  8974. SDValue RHS = N->getOperand(1);
  8975. SDValue CC = N->getOperand(2);
  8976. ISD::CondCode CCVal = cast<CondCodeSDNode>(CC)->get();
  8977. SDValue TrueV = N->getOperand(3);
  8978. SDValue FalseV = N->getOperand(4);
  8979. SDLoc DL(N);
  8980. EVT VT = N->getValueType(0);
  8981. // If the True and False values are the same, we don't need a select_cc.
  8982. if (TrueV == FalseV)
  8983. return TrueV;
  8984. // (select (x < 0), y, z) -> x >> (XLEN - 1) & (y - z) + z
  8985. // (select (x >= 0), y, z) -> x >> (XLEN - 1) & (z - y) + y
  8986. if (!Subtarget.hasShortForwardBranchOpt() && isa<ConstantSDNode>(TrueV) &&
  8987. isa<ConstantSDNode>(FalseV) && isNullConstant(RHS) &&
  8988. (CCVal == ISD::CondCode::SETLT || CCVal == ISD::CondCode::SETGE)) {
  8989. if (CCVal == ISD::CondCode::SETGE)
  8990. std::swap(TrueV, FalseV);
  8991. int64_t TrueSImm = cast<ConstantSDNode>(TrueV)->getSExtValue();
  8992. int64_t FalseSImm = cast<ConstantSDNode>(FalseV)->getSExtValue();
  8993. // Only handle simm12, if it is not in this range, it can be considered as
  8994. // register.
  8995. if (isInt<12>(TrueSImm) && isInt<12>(FalseSImm) &&
  8996. isInt<12>(TrueSImm - FalseSImm)) {
  8997. SDValue SRA =
  8998. DAG.getNode(ISD::SRA, DL, VT, LHS,
  8999. DAG.getConstant(Subtarget.getXLen() - 1, DL, VT));
  9000. SDValue AND =
  9001. DAG.getNode(ISD::AND, DL, VT, SRA,
  9002. DAG.getConstant(TrueSImm - FalseSImm, DL, VT));
  9003. return DAG.getNode(ISD::ADD, DL, VT, AND, FalseV);
  9004. }
  9005. if (CCVal == ISD::CondCode::SETGE)
  9006. std::swap(TrueV, FalseV);
  9007. }
  9008. if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget))
  9009. return DAG.getNode(RISCVISD::SELECT_CC, DL, N->getValueType(0),
  9010. {LHS, RHS, CC, TrueV, FalseV});
  9011. if (!Subtarget.hasShortForwardBranchOpt()) {
  9012. // (select c, -1, y) -> -c | y
  9013. if (isAllOnesConstant(TrueV)) {
  9014. SDValue C = DAG.getSetCC(DL, VT, LHS, RHS, CCVal);
  9015. SDValue Neg = DAG.getNegative(C, DL, VT);
  9016. return DAG.getNode(ISD::OR, DL, VT, Neg, FalseV);
  9017. }
  9018. // (select c, y, -1) -> -!c | y
  9019. if (isAllOnesConstant(FalseV)) {
  9020. SDValue C =
  9021. DAG.getSetCC(DL, VT, LHS, RHS, ISD::getSetCCInverse(CCVal, VT));
  9022. SDValue Neg = DAG.getNegative(C, DL, VT);
  9023. return DAG.getNode(ISD::OR, DL, VT, Neg, TrueV);
  9024. }
  9025. // (select c, 0, y) -> -!c & y
  9026. if (isNullConstant(TrueV)) {
  9027. SDValue C =
  9028. DAG.getSetCC(DL, VT, LHS, RHS, ISD::getSetCCInverse(CCVal, VT));
  9029. SDValue Neg = DAG.getNegative(C, DL, VT);
  9030. return DAG.getNode(ISD::AND, DL, VT, Neg, FalseV);
  9031. }
  9032. // (select c, y, 0) -> -c & y
  9033. if (isNullConstant(FalseV)) {
  9034. SDValue C = DAG.getSetCC(DL, VT, LHS, RHS, CCVal);
  9035. SDValue Neg = DAG.getNegative(C, DL, VT);
  9036. return DAG.getNode(ISD::AND, DL, VT, Neg, TrueV);
  9037. }
  9038. }
  9039. return SDValue();
  9040. }
  9041. case RISCVISD::BR_CC: {
  9042. SDValue LHS = N->getOperand(1);
  9043. SDValue RHS = N->getOperand(2);
  9044. SDValue CC = N->getOperand(3);
  9045. SDLoc DL(N);
  9046. if (combine_CC(LHS, RHS, CC, DL, DAG, Subtarget))
  9047. return DAG.getNode(RISCVISD::BR_CC, DL, N->getValueType(0),
  9048. N->getOperand(0), LHS, RHS, CC, N->getOperand(4));
  9049. return SDValue();
  9050. }
  9051. case ISD::BITREVERSE:
  9052. return performBITREVERSECombine(N, DAG, Subtarget);
  9053. case ISD::FP_TO_SINT:
  9054. case ISD::FP_TO_UINT:
  9055. return performFP_TO_INTCombine(N, DCI, Subtarget);
  9056. case ISD::FP_TO_SINT_SAT:
  9057. case ISD::FP_TO_UINT_SAT:
  9058. return performFP_TO_INT_SATCombine(N, DCI, Subtarget);
  9059. case ISD::FCOPYSIGN: {
  9060. EVT VT = N->getValueType(0);
  9061. if (!VT.isVector())
  9062. break;
  9063. // There is a form of VFSGNJ which injects the negated sign of its second
  9064. // operand. Try and bubble any FNEG up after the extend/round to produce
  9065. // this optimized pattern. Avoid modifying cases where FP_ROUND and
  9066. // TRUNC=1.
  9067. SDValue In2 = N->getOperand(1);
  9068. // Avoid cases where the extend/round has multiple uses, as duplicating
  9069. // those is typically more expensive than removing a fneg.
  9070. if (!In2.hasOneUse())
  9071. break;
  9072. if (In2.getOpcode() != ISD::FP_EXTEND &&
  9073. (In2.getOpcode() != ISD::FP_ROUND || In2.getConstantOperandVal(1) != 0))
  9074. break;
  9075. In2 = In2.getOperand(0);
  9076. if (In2.getOpcode() != ISD::FNEG)
  9077. break;
  9078. SDLoc DL(N);
  9079. SDValue NewFPExtRound = DAG.getFPExtendOrRound(In2.getOperand(0), DL, VT);
  9080. return DAG.getNode(ISD::FCOPYSIGN, DL, VT, N->getOperand(0),
  9081. DAG.getNode(ISD::FNEG, DL, VT, NewFPExtRound));
  9082. }
  9083. case ISD::MGATHER:
  9084. case ISD::MSCATTER:
  9085. case ISD::VP_GATHER:
  9086. case ISD::VP_SCATTER: {
  9087. if (!DCI.isBeforeLegalize())
  9088. break;
  9089. SDValue Index, ScaleOp;
  9090. bool IsIndexSigned = false;
  9091. if (const auto *VPGSN = dyn_cast<VPGatherScatterSDNode>(N)) {
  9092. Index = VPGSN->getIndex();
  9093. ScaleOp = VPGSN->getScale();
  9094. IsIndexSigned = VPGSN->isIndexSigned();
  9095. assert(!VPGSN->isIndexScaled() &&
  9096. "Scaled gather/scatter should not be formed");
  9097. } else {
  9098. const auto *MGSN = cast<MaskedGatherScatterSDNode>(N);
  9099. Index = MGSN->getIndex();
  9100. ScaleOp = MGSN->getScale();
  9101. IsIndexSigned = MGSN->isIndexSigned();
  9102. assert(!MGSN->isIndexScaled() &&
  9103. "Scaled gather/scatter should not be formed");
  9104. }
  9105. EVT IndexVT = Index.getValueType();
  9106. MVT XLenVT = Subtarget.getXLenVT();
  9107. // RISCV indexed loads only support the "unsigned unscaled" addressing
  9108. // mode, so anything else must be manually legalized.
  9109. bool NeedsIdxLegalization =
  9110. (IsIndexSigned && IndexVT.getVectorElementType().bitsLT(XLenVT));
  9111. if (!NeedsIdxLegalization)
  9112. break;
  9113. SDLoc DL(N);
  9114. // Any index legalization should first promote to XLenVT, so we don't lose
  9115. // bits when scaling. This may create an illegal index type so we let
  9116. // LLVM's legalization take care of the splitting.
  9117. // FIXME: LLVM can't split VP_GATHER or VP_SCATTER yet.
  9118. if (IndexVT.getVectorElementType().bitsLT(XLenVT)) {
  9119. IndexVT = IndexVT.changeVectorElementType(XLenVT);
  9120. Index = DAG.getNode(IsIndexSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
  9121. DL, IndexVT, Index);
  9122. }
  9123. ISD::MemIndexType NewIndexTy = ISD::UNSIGNED_SCALED;
  9124. if (const auto *VPGN = dyn_cast<VPGatherSDNode>(N))
  9125. return DAG.getGatherVP(N->getVTList(), VPGN->getMemoryVT(), DL,
  9126. {VPGN->getChain(), VPGN->getBasePtr(), Index,
  9127. ScaleOp, VPGN->getMask(),
  9128. VPGN->getVectorLength()},
  9129. VPGN->getMemOperand(), NewIndexTy);
  9130. if (const auto *VPSN = dyn_cast<VPScatterSDNode>(N))
  9131. return DAG.getScatterVP(N->getVTList(), VPSN->getMemoryVT(), DL,
  9132. {VPSN->getChain(), VPSN->getValue(),
  9133. VPSN->getBasePtr(), Index, ScaleOp,
  9134. VPSN->getMask(), VPSN->getVectorLength()},
  9135. VPSN->getMemOperand(), NewIndexTy);
  9136. if (const auto *MGN = dyn_cast<MaskedGatherSDNode>(N))
  9137. return DAG.getMaskedGather(
  9138. N->getVTList(), MGN->getMemoryVT(), DL,
  9139. {MGN->getChain(), MGN->getPassThru(), MGN->getMask(),
  9140. MGN->getBasePtr(), Index, ScaleOp},
  9141. MGN->getMemOperand(), NewIndexTy, MGN->getExtensionType());
  9142. const auto *MSN = cast<MaskedScatterSDNode>(N);
  9143. return DAG.getMaskedScatter(
  9144. N->getVTList(), MSN->getMemoryVT(), DL,
  9145. {MSN->getChain(), MSN->getValue(), MSN->getMask(), MSN->getBasePtr(),
  9146. Index, ScaleOp},
  9147. MSN->getMemOperand(), NewIndexTy, MSN->isTruncatingStore());
  9148. }
  9149. case RISCVISD::SRA_VL:
  9150. case RISCVISD::SRL_VL:
  9151. case RISCVISD::SHL_VL: {
  9152. SDValue ShAmt = N->getOperand(1);
  9153. if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
  9154. // We don't need the upper 32 bits of a 64-bit element for a shift amount.
  9155. SDLoc DL(N);
  9156. SDValue VL = N->getOperand(3);
  9157. EVT VT = N->getValueType(0);
  9158. ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
  9159. ShAmt.getOperand(1), VL);
  9160. return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt,
  9161. N->getOperand(2), N->getOperand(3), N->getOperand(4));
  9162. }
  9163. break;
  9164. }
  9165. case ISD::SRA:
  9166. if (SDValue V = performSRACombine(N, DAG, Subtarget))
  9167. return V;
  9168. [[fallthrough]];
  9169. case ISD::SRL:
  9170. case ISD::SHL: {
  9171. SDValue ShAmt = N->getOperand(1);
  9172. if (ShAmt.getOpcode() == RISCVISD::SPLAT_VECTOR_SPLIT_I64_VL) {
  9173. // We don't need the upper 32 bits of a 64-bit element for a shift amount.
  9174. SDLoc DL(N);
  9175. EVT VT = N->getValueType(0);
  9176. ShAmt = DAG.getNode(RISCVISD::VMV_V_X_VL, DL, VT, DAG.getUNDEF(VT),
  9177. ShAmt.getOperand(1),
  9178. DAG.getRegister(RISCV::X0, Subtarget.getXLenVT()));
  9179. return DAG.getNode(N->getOpcode(), DL, VT, N->getOperand(0), ShAmt);
  9180. }
  9181. break;
  9182. }
  9183. case RISCVISD::ADD_VL:
  9184. case RISCVISD::SUB_VL:
  9185. case RISCVISD::VWADD_W_VL:
  9186. case RISCVISD::VWADDU_W_VL:
  9187. case RISCVISD::VWSUB_W_VL:
  9188. case RISCVISD::VWSUBU_W_VL:
  9189. case RISCVISD::MUL_VL:
  9190. return combineBinOp_VLToVWBinOp_VL(N, DCI);
  9191. case RISCVISD::VFMADD_VL:
  9192. case RISCVISD::VFNMADD_VL:
  9193. case RISCVISD::VFMSUB_VL:
  9194. case RISCVISD::VFNMSUB_VL: {
  9195. // Fold FNEG_VL into FMA opcodes.
  9196. SDValue A = N->getOperand(0);
  9197. SDValue B = N->getOperand(1);
  9198. SDValue C = N->getOperand(2);
  9199. SDValue Mask = N->getOperand(3);
  9200. SDValue VL = N->getOperand(4);
  9201. auto invertIfNegative = [&Mask, &VL](SDValue &V) {
  9202. if (V.getOpcode() == RISCVISD::FNEG_VL && V.getOperand(1) == Mask &&
  9203. V.getOperand(2) == VL) {
  9204. // Return the negated input.
  9205. V = V.getOperand(0);
  9206. return true;
  9207. }
  9208. return false;
  9209. };
  9210. bool NegA = invertIfNegative(A);
  9211. bool NegB = invertIfNegative(B);
  9212. bool NegC = invertIfNegative(C);
  9213. // If no operands are negated, we're done.
  9214. if (!NegA && !NegB && !NegC)
  9215. return SDValue();
  9216. unsigned NewOpcode = negateFMAOpcode(N->getOpcode(), NegA != NegB, NegC);
  9217. return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), A, B, C, Mask,
  9218. VL);
  9219. }
  9220. case ISD::STORE: {
  9221. auto *Store = cast<StoreSDNode>(N);
  9222. SDValue Val = Store->getValue();
  9223. // Combine store of vmv.x.s/vfmv.f.s to vse with VL of 1.
  9224. // vfmv.f.s is represented as extract element from 0. Match it late to avoid
  9225. // any illegal types.
  9226. if (Val.getOpcode() == RISCVISD::VMV_X_S ||
  9227. (DCI.isAfterLegalizeDAG() &&
  9228. Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  9229. isNullConstant(Val.getOperand(1)))) {
  9230. SDValue Src = Val.getOperand(0);
  9231. MVT VecVT = Src.getSimpleValueType();
  9232. EVT MemVT = Store->getMemoryVT();
  9233. // VecVT should be scalable and memory VT should match the element type.
  9234. if (VecVT.isScalableVector() &&
  9235. MemVT == VecVT.getVectorElementType()) {
  9236. SDLoc DL(N);
  9237. MVT MaskVT = getMaskTypeFor(VecVT);
  9238. return DAG.getStoreVP(
  9239. Store->getChain(), DL, Src, Store->getBasePtr(), Store->getOffset(),
  9240. DAG.getConstant(1, DL, MaskVT),
  9241. DAG.getConstant(1, DL, Subtarget.getXLenVT()), MemVT,
  9242. Store->getMemOperand(), Store->getAddressingMode(),
  9243. Store->isTruncatingStore(), /*IsCompress*/ false);
  9244. }
  9245. }
  9246. break;
  9247. }
  9248. case ISD::SPLAT_VECTOR: {
  9249. EVT VT = N->getValueType(0);
  9250. // Only perform this combine on legal MVT types.
  9251. if (!isTypeLegal(VT))
  9252. break;
  9253. if (auto Gather = matchSplatAsGather(N->getOperand(0), VT.getSimpleVT(), N,
  9254. DAG, Subtarget))
  9255. return Gather;
  9256. break;
  9257. }
  9258. case RISCVISD::VMV_V_X_VL: {
  9259. // Tail agnostic VMV.V.X only demands the vector element bitwidth from the
  9260. // scalar input.
  9261. unsigned ScalarSize = N->getOperand(1).getValueSizeInBits();
  9262. unsigned EltWidth = N->getValueType(0).getScalarSizeInBits();
  9263. if (ScalarSize > EltWidth && N->getOperand(0).isUndef())
  9264. if (SimplifyDemandedLowBitsHelper(1, EltWidth))
  9265. return SDValue(N, 0);
  9266. break;
  9267. }
  9268. case RISCVISD::VFMV_S_F_VL: {
  9269. SDValue Src = N->getOperand(1);
  9270. // Try to remove vector->scalar->vector if the scalar->vector is inserting
  9271. // into an undef vector.
  9272. // TODO: Could use a vslide or vmv.v.v for non-undef.
  9273. if (N->getOperand(0).isUndef() &&
  9274. Src.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  9275. isNullConstant(Src.getOperand(1)) &&
  9276. Src.getOperand(0).getValueType().isScalableVector()) {
  9277. EVT VT = N->getValueType(0);
  9278. EVT SrcVT = Src.getOperand(0).getValueType();
  9279. assert(SrcVT.getVectorElementType() == VT.getVectorElementType());
  9280. // Widths match, just return the original vector.
  9281. if (SrcVT == VT)
  9282. return Src.getOperand(0);
  9283. // TODO: Use insert_subvector/extract_subvector to change widen/narrow?
  9284. }
  9285. break;
  9286. }
  9287. case ISD::INTRINSIC_WO_CHAIN: {
  9288. unsigned IntNo = N->getConstantOperandVal(0);
  9289. switch (IntNo) {
  9290. // By default we do not combine any intrinsic.
  9291. default:
  9292. return SDValue();
  9293. case Intrinsic::riscv_vcpop:
  9294. case Intrinsic::riscv_vcpop_mask:
  9295. case Intrinsic::riscv_vfirst:
  9296. case Intrinsic::riscv_vfirst_mask: {
  9297. SDValue VL = N->getOperand(2);
  9298. if (IntNo == Intrinsic::riscv_vcpop_mask ||
  9299. IntNo == Intrinsic::riscv_vfirst_mask)
  9300. VL = N->getOperand(3);
  9301. if (!isNullConstant(VL))
  9302. return SDValue();
  9303. // If VL is 0, vcpop -> li 0, vfirst -> li -1.
  9304. SDLoc DL(N);
  9305. EVT VT = N->getValueType(0);
  9306. if (IntNo == Intrinsic::riscv_vfirst ||
  9307. IntNo == Intrinsic::riscv_vfirst_mask)
  9308. return DAG.getConstant(-1, DL, VT);
  9309. return DAG.getConstant(0, DL, VT);
  9310. }
  9311. }
  9312. }
  9313. case ISD::BITCAST: {
  9314. assert(Subtarget.useRVVForFixedLengthVectors());
  9315. SDValue N0 = N->getOperand(0);
  9316. EVT VT = N->getValueType(0);
  9317. EVT SrcVT = N0.getValueType();
  9318. // If this is a bitcast between a MVT::v4i1/v2i1/v1i1 and an illegal integer
  9319. // type, widen both sides to avoid a trip through memory.
  9320. if ((SrcVT == MVT::v1i1 || SrcVT == MVT::v2i1 || SrcVT == MVT::v4i1) &&
  9321. VT.isScalarInteger()) {
  9322. unsigned NumConcats = 8 / SrcVT.getVectorNumElements();
  9323. SmallVector<SDValue, 4> Ops(NumConcats, DAG.getUNDEF(SrcVT));
  9324. Ops[0] = N0;
  9325. SDLoc DL(N);
  9326. N0 = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i1, Ops);
  9327. N0 = DAG.getBitcast(MVT::i8, N0);
  9328. return DAG.getNode(ISD::TRUNCATE, DL, VT, N0);
  9329. }
  9330. return SDValue();
  9331. }
  9332. }
  9333. return SDValue();
  9334. }
  9335. bool RISCVTargetLowering::isDesirableToCommuteWithShift(
  9336. const SDNode *N, CombineLevel Level) const {
  9337. assert((N->getOpcode() == ISD::SHL || N->getOpcode() == ISD::SRA ||
  9338. N->getOpcode() == ISD::SRL) &&
  9339. "Expected shift op");
  9340. // The following folds are only desirable if `(OP _, c1 << c2)` can be
  9341. // materialised in fewer instructions than `(OP _, c1)`:
  9342. //
  9343. // (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
  9344. // (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
  9345. SDValue N0 = N->getOperand(0);
  9346. EVT Ty = N0.getValueType();
  9347. if (Ty.isScalarInteger() &&
  9348. (N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR)) {
  9349. auto *C1 = dyn_cast<ConstantSDNode>(N0->getOperand(1));
  9350. auto *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1));
  9351. if (C1 && C2) {
  9352. const APInt &C1Int = C1->getAPIntValue();
  9353. APInt ShiftedC1Int = C1Int << C2->getAPIntValue();
  9354. // We can materialise `c1 << c2` into an add immediate, so it's "free",
  9355. // and the combine should happen, to potentially allow further combines
  9356. // later.
  9357. if (ShiftedC1Int.getMinSignedBits() <= 64 &&
  9358. isLegalAddImmediate(ShiftedC1Int.getSExtValue()))
  9359. return true;
  9360. // We can materialise `c1` in an add immediate, so it's "free", and the
  9361. // combine should be prevented.
  9362. if (C1Int.getMinSignedBits() <= 64 &&
  9363. isLegalAddImmediate(C1Int.getSExtValue()))
  9364. return false;
  9365. // Neither constant will fit into an immediate, so find materialisation
  9366. // costs.
  9367. int C1Cost = RISCVMatInt::getIntMatCost(C1Int, Ty.getSizeInBits(),
  9368. Subtarget.getFeatureBits(),
  9369. /*CompressionCost*/true);
  9370. int ShiftedC1Cost = RISCVMatInt::getIntMatCost(
  9371. ShiftedC1Int, Ty.getSizeInBits(), Subtarget.getFeatureBits(),
  9372. /*CompressionCost*/true);
  9373. // Materialising `c1` is cheaper than materialising `c1 << c2`, so the
  9374. // combine should be prevented.
  9375. if (C1Cost < ShiftedC1Cost)
  9376. return false;
  9377. }
  9378. }
  9379. return true;
  9380. }
  9381. bool RISCVTargetLowering::targetShrinkDemandedConstant(
  9382. SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
  9383. TargetLoweringOpt &TLO) const {
  9384. // Delay this optimization as late as possible.
  9385. if (!TLO.LegalOps)
  9386. return false;
  9387. EVT VT = Op.getValueType();
  9388. if (VT.isVector())
  9389. return false;
  9390. unsigned Opcode = Op.getOpcode();
  9391. if (Opcode != ISD::AND && Opcode != ISD::OR && Opcode != ISD::XOR)
  9392. return false;
  9393. ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  9394. if (!C)
  9395. return false;
  9396. const APInt &Mask = C->getAPIntValue();
  9397. // Clear all non-demanded bits initially.
  9398. APInt ShrunkMask = Mask & DemandedBits;
  9399. // Try to make a smaller immediate by setting undemanded bits.
  9400. APInt ExpandedMask = Mask | ~DemandedBits;
  9401. auto IsLegalMask = [ShrunkMask, ExpandedMask](const APInt &Mask) -> bool {
  9402. return ShrunkMask.isSubsetOf(Mask) && Mask.isSubsetOf(ExpandedMask);
  9403. };
  9404. auto UseMask = [Mask, Op, &TLO](const APInt &NewMask) -> bool {
  9405. if (NewMask == Mask)
  9406. return true;
  9407. SDLoc DL(Op);
  9408. SDValue NewC = TLO.DAG.getConstant(NewMask, DL, Op.getValueType());
  9409. SDValue NewOp = TLO.DAG.getNode(Op.getOpcode(), DL, Op.getValueType(),
  9410. Op.getOperand(0), NewC);
  9411. return TLO.CombineTo(Op, NewOp);
  9412. };
  9413. // If the shrunk mask fits in sign extended 12 bits, let the target
  9414. // independent code apply it.
  9415. if (ShrunkMask.isSignedIntN(12))
  9416. return false;
  9417. // And has a few special cases for zext.
  9418. if (Opcode == ISD::AND) {
  9419. // Preserve (and X, 0xffff), if zext.h exists use zext.h,
  9420. // otherwise use SLLI + SRLI.
  9421. APInt NewMask = APInt(Mask.getBitWidth(), 0xffff);
  9422. if (IsLegalMask(NewMask))
  9423. return UseMask(NewMask);
  9424. // Try to preserve (and X, 0xffffffff), the (zext_inreg X, i32) pattern.
  9425. if (VT == MVT::i64) {
  9426. APInt NewMask = APInt(64, 0xffffffff);
  9427. if (IsLegalMask(NewMask))
  9428. return UseMask(NewMask);
  9429. }
  9430. }
  9431. // For the remaining optimizations, we need to be able to make a negative
  9432. // number through a combination of mask and undemanded bits.
  9433. if (!ExpandedMask.isNegative())
  9434. return false;
  9435. // What is the fewest number of bits we need to represent the negative number.
  9436. unsigned MinSignedBits = ExpandedMask.getMinSignedBits();
  9437. // Try to make a 12 bit negative immediate. If that fails try to make a 32
  9438. // bit negative immediate unless the shrunk immediate already fits in 32 bits.
  9439. // If we can't create a simm12, we shouldn't change opaque constants.
  9440. APInt NewMask = ShrunkMask;
  9441. if (MinSignedBits <= 12)
  9442. NewMask.setBitsFrom(11);
  9443. else if (!C->isOpaque() && MinSignedBits <= 32 && !ShrunkMask.isSignedIntN(32))
  9444. NewMask.setBitsFrom(31);
  9445. else
  9446. return false;
  9447. // Check that our new mask is a subset of the demanded mask.
  9448. assert(IsLegalMask(NewMask));
  9449. return UseMask(NewMask);
  9450. }
  9451. static uint64_t computeGREVOrGORC(uint64_t x, unsigned ShAmt, bool IsGORC) {
  9452. static const uint64_t GREVMasks[] = {
  9453. 0x5555555555555555ULL, 0x3333333333333333ULL, 0x0F0F0F0F0F0F0F0FULL,
  9454. 0x00FF00FF00FF00FFULL, 0x0000FFFF0000FFFFULL, 0x00000000FFFFFFFFULL};
  9455. for (unsigned Stage = 0; Stage != 6; ++Stage) {
  9456. unsigned Shift = 1 << Stage;
  9457. if (ShAmt & Shift) {
  9458. uint64_t Mask = GREVMasks[Stage];
  9459. uint64_t Res = ((x & Mask) << Shift) | ((x >> Shift) & Mask);
  9460. if (IsGORC)
  9461. Res |= x;
  9462. x = Res;
  9463. }
  9464. }
  9465. return x;
  9466. }
  9467. void RISCVTargetLowering::computeKnownBitsForTargetNode(const SDValue Op,
  9468. KnownBits &Known,
  9469. const APInt &DemandedElts,
  9470. const SelectionDAG &DAG,
  9471. unsigned Depth) const {
  9472. unsigned BitWidth = Known.getBitWidth();
  9473. unsigned Opc = Op.getOpcode();
  9474. assert((Opc >= ISD::BUILTIN_OP_END ||
  9475. Opc == ISD::INTRINSIC_WO_CHAIN ||
  9476. Opc == ISD::INTRINSIC_W_CHAIN ||
  9477. Opc == ISD::INTRINSIC_VOID) &&
  9478. "Should use MaskedValueIsZero if you don't know whether Op"
  9479. " is a target node!");
  9480. Known.resetAll();
  9481. switch (Opc) {
  9482. default: break;
  9483. case RISCVISD::SELECT_CC: {
  9484. Known = DAG.computeKnownBits(Op.getOperand(4), Depth + 1);
  9485. // If we don't know any bits, early out.
  9486. if (Known.isUnknown())
  9487. break;
  9488. KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(3), Depth + 1);
  9489. // Only known if known in both the LHS and RHS.
  9490. Known = KnownBits::commonBits(Known, Known2);
  9491. break;
  9492. }
  9493. case RISCVISD::REMUW: {
  9494. KnownBits Known2;
  9495. Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  9496. Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  9497. // We only care about the lower 32 bits.
  9498. Known = KnownBits::urem(Known.trunc(32), Known2.trunc(32));
  9499. // Restore the original width by sign extending.
  9500. Known = Known.sext(BitWidth);
  9501. break;
  9502. }
  9503. case RISCVISD::DIVUW: {
  9504. KnownBits Known2;
  9505. Known = DAG.computeKnownBits(Op.getOperand(0), DemandedElts, Depth + 1);
  9506. Known2 = DAG.computeKnownBits(Op.getOperand(1), DemandedElts, Depth + 1);
  9507. // We only care about the lower 32 bits.
  9508. Known = KnownBits::udiv(Known.trunc(32), Known2.trunc(32));
  9509. // Restore the original width by sign extending.
  9510. Known = Known.sext(BitWidth);
  9511. break;
  9512. }
  9513. case RISCVISD::CTZW: {
  9514. KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
  9515. unsigned PossibleTZ = Known2.trunc(32).countMaxTrailingZeros();
  9516. unsigned LowBits = llvm::bit_width(PossibleTZ);
  9517. Known.Zero.setBitsFrom(LowBits);
  9518. break;
  9519. }
  9520. case RISCVISD::CLZW: {
  9521. KnownBits Known2 = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
  9522. unsigned PossibleLZ = Known2.trunc(32).countMaxLeadingZeros();
  9523. unsigned LowBits = llvm::bit_width(PossibleLZ);
  9524. Known.Zero.setBitsFrom(LowBits);
  9525. break;
  9526. }
  9527. case RISCVISD::BREV8:
  9528. case RISCVISD::ORC_B: {
  9529. // FIXME: This is based on the non-ratified Zbp GREV and GORC where a
  9530. // control value of 7 is equivalent to brev8 and orc.b.
  9531. Known = DAG.computeKnownBits(Op.getOperand(0), Depth + 1);
  9532. bool IsGORC = Op.getOpcode() == RISCVISD::ORC_B;
  9533. // To compute zeros, we need to invert the value and invert it back after.
  9534. Known.Zero =
  9535. ~computeGREVOrGORC(~Known.Zero.getZExtValue(), 7, IsGORC);
  9536. Known.One = computeGREVOrGORC(Known.One.getZExtValue(), 7, IsGORC);
  9537. break;
  9538. }
  9539. case RISCVISD::READ_VLENB: {
  9540. // We can use the minimum and maximum VLEN values to bound VLENB. We
  9541. // know VLEN must be a power of two.
  9542. const unsigned MinVLenB = Subtarget.getRealMinVLen() / 8;
  9543. const unsigned MaxVLenB = Subtarget.getRealMaxVLen() / 8;
  9544. assert(MinVLenB > 0 && "READ_VLENB without vector extension enabled?");
  9545. Known.Zero.setLowBits(Log2_32(MinVLenB));
  9546. Known.Zero.setBitsFrom(Log2_32(MaxVLenB)+1);
  9547. if (MaxVLenB == MinVLenB)
  9548. Known.One.setBit(Log2_32(MinVLenB));
  9549. break;
  9550. }
  9551. case ISD::INTRINSIC_W_CHAIN:
  9552. case ISD::INTRINSIC_WO_CHAIN: {
  9553. unsigned IntNo =
  9554. Op.getConstantOperandVal(Opc == ISD::INTRINSIC_WO_CHAIN ? 0 : 1);
  9555. switch (IntNo) {
  9556. default:
  9557. // We can't do anything for most intrinsics.
  9558. break;
  9559. case Intrinsic::riscv_vsetvli:
  9560. case Intrinsic::riscv_vsetvlimax:
  9561. case Intrinsic::riscv_vsetvli_opt:
  9562. case Intrinsic::riscv_vsetvlimax_opt:
  9563. // Assume that VL output is positive and would fit in an int32_t.
  9564. // TODO: VLEN might be capped at 16 bits in a future V spec update.
  9565. if (BitWidth >= 32)
  9566. Known.Zero.setBitsFrom(31);
  9567. break;
  9568. }
  9569. break;
  9570. }
  9571. }
  9572. }
  9573. unsigned RISCVTargetLowering::ComputeNumSignBitsForTargetNode(
  9574. SDValue Op, const APInt &DemandedElts, const SelectionDAG &DAG,
  9575. unsigned Depth) const {
  9576. switch (Op.getOpcode()) {
  9577. default:
  9578. break;
  9579. case RISCVISD::SELECT_CC: {
  9580. unsigned Tmp =
  9581. DAG.ComputeNumSignBits(Op.getOperand(3), DemandedElts, Depth + 1);
  9582. if (Tmp == 1) return 1; // Early out.
  9583. unsigned Tmp2 =
  9584. DAG.ComputeNumSignBits(Op.getOperand(4), DemandedElts, Depth + 1);
  9585. return std::min(Tmp, Tmp2);
  9586. }
  9587. case RISCVISD::ABSW: {
  9588. // We expand this at isel to negw+max. The result will have 33 sign bits
  9589. // if the input has at least 33 sign bits.
  9590. unsigned Tmp =
  9591. DAG.ComputeNumSignBits(Op.getOperand(0), DemandedElts, Depth + 1);
  9592. if (Tmp < 33) return 1;
  9593. return 33;
  9594. }
  9595. case RISCVISD::SLLW:
  9596. case RISCVISD::SRAW:
  9597. case RISCVISD::SRLW:
  9598. case RISCVISD::DIVW:
  9599. case RISCVISD::DIVUW:
  9600. case RISCVISD::REMUW:
  9601. case RISCVISD::ROLW:
  9602. case RISCVISD::RORW:
  9603. case RISCVISD::FCVT_W_RV64:
  9604. case RISCVISD::FCVT_WU_RV64:
  9605. case RISCVISD::STRICT_FCVT_W_RV64:
  9606. case RISCVISD::STRICT_FCVT_WU_RV64:
  9607. // TODO: As the result is sign-extended, this is conservatively correct. A
  9608. // more precise answer could be calculated for SRAW depending on known
  9609. // bits in the shift amount.
  9610. return 33;
  9611. case RISCVISD::VMV_X_S: {
  9612. // The number of sign bits of the scalar result is computed by obtaining the
  9613. // element type of the input vector operand, subtracting its width from the
  9614. // XLEN, and then adding one (sign bit within the element type). If the
  9615. // element type is wider than XLen, the least-significant XLEN bits are
  9616. // taken.
  9617. unsigned XLen = Subtarget.getXLen();
  9618. unsigned EltBits = Op.getOperand(0).getScalarValueSizeInBits();
  9619. if (EltBits <= XLen)
  9620. return XLen - EltBits + 1;
  9621. break;
  9622. }
  9623. case ISD::INTRINSIC_W_CHAIN: {
  9624. unsigned IntNo = Op.getConstantOperandVal(1);
  9625. switch (IntNo) {
  9626. default:
  9627. break;
  9628. case Intrinsic::riscv_masked_atomicrmw_xchg_i64:
  9629. case Intrinsic::riscv_masked_atomicrmw_add_i64:
  9630. case Intrinsic::riscv_masked_atomicrmw_sub_i64:
  9631. case Intrinsic::riscv_masked_atomicrmw_nand_i64:
  9632. case Intrinsic::riscv_masked_atomicrmw_max_i64:
  9633. case Intrinsic::riscv_masked_atomicrmw_min_i64:
  9634. case Intrinsic::riscv_masked_atomicrmw_umax_i64:
  9635. case Intrinsic::riscv_masked_atomicrmw_umin_i64:
  9636. case Intrinsic::riscv_masked_cmpxchg_i64:
  9637. // riscv_masked_{atomicrmw_*,cmpxchg} intrinsics represent an emulated
  9638. // narrow atomic operation. These are implemented using atomic
  9639. // operations at the minimum supported atomicrmw/cmpxchg width whose
  9640. // result is then sign extended to XLEN. With +A, the minimum width is
  9641. // 32 for both 64 and 32.
  9642. assert(Subtarget.getXLen() == 64);
  9643. assert(getMinCmpXchgSizeInBits() == 32);
  9644. assert(Subtarget.hasStdExtA());
  9645. return 33;
  9646. }
  9647. }
  9648. }
  9649. return 1;
  9650. }
  9651. const Constant *
  9652. RISCVTargetLowering::getTargetConstantFromLoad(LoadSDNode *Ld) const {
  9653. assert(Ld && "Unexpected null LoadSDNode");
  9654. if (!ISD::isNormalLoad(Ld))
  9655. return nullptr;
  9656. SDValue Ptr = Ld->getBasePtr();
  9657. // Only constant pools with no offset are supported.
  9658. auto GetSupportedConstantPool = [](SDValue Ptr) -> ConstantPoolSDNode * {
  9659. auto *CNode = dyn_cast<ConstantPoolSDNode>(Ptr);
  9660. if (!CNode || CNode->isMachineConstantPoolEntry() ||
  9661. CNode->getOffset() != 0)
  9662. return nullptr;
  9663. return CNode;
  9664. };
  9665. // Simple case, LLA.
  9666. if (Ptr.getOpcode() == RISCVISD::LLA) {
  9667. auto *CNode = GetSupportedConstantPool(Ptr);
  9668. if (!CNode || CNode->getTargetFlags() != 0)
  9669. return nullptr;
  9670. return CNode->getConstVal();
  9671. }
  9672. // Look for a HI and ADD_LO pair.
  9673. if (Ptr.getOpcode() != RISCVISD::ADD_LO ||
  9674. Ptr.getOperand(0).getOpcode() != RISCVISD::HI)
  9675. return nullptr;
  9676. auto *CNodeLo = GetSupportedConstantPool(Ptr.getOperand(1));
  9677. auto *CNodeHi = GetSupportedConstantPool(Ptr.getOperand(0).getOperand(0));
  9678. if (!CNodeLo || CNodeLo->getTargetFlags() != RISCVII::MO_LO ||
  9679. !CNodeHi || CNodeHi->getTargetFlags() != RISCVII::MO_HI)
  9680. return nullptr;
  9681. if (CNodeLo->getConstVal() != CNodeHi->getConstVal())
  9682. return nullptr;
  9683. return CNodeLo->getConstVal();
  9684. }
  9685. static MachineBasicBlock *emitReadCycleWidePseudo(MachineInstr &MI,
  9686. MachineBasicBlock *BB) {
  9687. assert(MI.getOpcode() == RISCV::ReadCycleWide && "Unexpected instruction");
  9688. // To read the 64-bit cycle CSR on a 32-bit target, we read the two halves.
  9689. // Should the count have wrapped while it was being read, we need to try
  9690. // again.
  9691. // ...
  9692. // read:
  9693. // rdcycleh x3 # load high word of cycle
  9694. // rdcycle x2 # load low word of cycle
  9695. // rdcycleh x4 # load high word of cycle
  9696. // bne x3, x4, read # check if high word reads match, otherwise try again
  9697. // ...
  9698. MachineFunction &MF = *BB->getParent();
  9699. const BasicBlock *LLVM_BB = BB->getBasicBlock();
  9700. MachineFunction::iterator It = ++BB->getIterator();
  9701. MachineBasicBlock *LoopMBB = MF.CreateMachineBasicBlock(LLVM_BB);
  9702. MF.insert(It, LoopMBB);
  9703. MachineBasicBlock *DoneMBB = MF.CreateMachineBasicBlock(LLVM_BB);
  9704. MF.insert(It, DoneMBB);
  9705. // Transfer the remainder of BB and its successor edges to DoneMBB.
  9706. DoneMBB->splice(DoneMBB->begin(), BB,
  9707. std::next(MachineBasicBlock::iterator(MI)), BB->end());
  9708. DoneMBB->transferSuccessorsAndUpdatePHIs(BB);
  9709. BB->addSuccessor(LoopMBB);
  9710. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  9711. Register ReadAgainReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
  9712. Register LoReg = MI.getOperand(0).getReg();
  9713. Register HiReg = MI.getOperand(1).getReg();
  9714. DebugLoc DL = MI.getDebugLoc();
  9715. const TargetInstrInfo *TII = MF.getSubtarget().getInstrInfo();
  9716. BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), HiReg)
  9717. .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
  9718. .addReg(RISCV::X0);
  9719. BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), LoReg)
  9720. .addImm(RISCVSysReg::lookupSysRegByName("CYCLE")->Encoding)
  9721. .addReg(RISCV::X0);
  9722. BuildMI(LoopMBB, DL, TII->get(RISCV::CSRRS), ReadAgainReg)
  9723. .addImm(RISCVSysReg::lookupSysRegByName("CYCLEH")->Encoding)
  9724. .addReg(RISCV::X0);
  9725. BuildMI(LoopMBB, DL, TII->get(RISCV::BNE))
  9726. .addReg(HiReg)
  9727. .addReg(ReadAgainReg)
  9728. .addMBB(LoopMBB);
  9729. LoopMBB->addSuccessor(LoopMBB);
  9730. LoopMBB->addSuccessor(DoneMBB);
  9731. MI.eraseFromParent();
  9732. return DoneMBB;
  9733. }
  9734. static MachineBasicBlock *emitSplitF64Pseudo(MachineInstr &MI,
  9735. MachineBasicBlock *BB) {
  9736. assert(MI.getOpcode() == RISCV::SplitF64Pseudo && "Unexpected instruction");
  9737. MachineFunction &MF = *BB->getParent();
  9738. DebugLoc DL = MI.getDebugLoc();
  9739. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  9740. const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
  9741. Register LoReg = MI.getOperand(0).getReg();
  9742. Register HiReg = MI.getOperand(1).getReg();
  9743. Register SrcReg = MI.getOperand(2).getReg();
  9744. const TargetRegisterClass *SrcRC = &RISCV::FPR64RegClass;
  9745. int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
  9746. TII.storeRegToStackSlot(*BB, MI, SrcReg, MI.getOperand(2).isKill(), FI, SrcRC,
  9747. RI, Register());
  9748. MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
  9749. MachineMemOperand *MMOLo =
  9750. MF.getMachineMemOperand(MPI, MachineMemOperand::MOLoad, 4, Align(8));
  9751. MachineMemOperand *MMOHi = MF.getMachineMemOperand(
  9752. MPI.getWithOffset(4), MachineMemOperand::MOLoad, 4, Align(8));
  9753. BuildMI(*BB, MI, DL, TII.get(RISCV::LW), LoReg)
  9754. .addFrameIndex(FI)
  9755. .addImm(0)
  9756. .addMemOperand(MMOLo);
  9757. BuildMI(*BB, MI, DL, TII.get(RISCV::LW), HiReg)
  9758. .addFrameIndex(FI)
  9759. .addImm(4)
  9760. .addMemOperand(MMOHi);
  9761. MI.eraseFromParent(); // The pseudo instruction is gone now.
  9762. return BB;
  9763. }
  9764. static MachineBasicBlock *emitBuildPairF64Pseudo(MachineInstr &MI,
  9765. MachineBasicBlock *BB) {
  9766. assert(MI.getOpcode() == RISCV::BuildPairF64Pseudo &&
  9767. "Unexpected instruction");
  9768. MachineFunction &MF = *BB->getParent();
  9769. DebugLoc DL = MI.getDebugLoc();
  9770. const TargetInstrInfo &TII = *MF.getSubtarget().getInstrInfo();
  9771. const TargetRegisterInfo *RI = MF.getSubtarget().getRegisterInfo();
  9772. Register DstReg = MI.getOperand(0).getReg();
  9773. Register LoReg = MI.getOperand(1).getReg();
  9774. Register HiReg = MI.getOperand(2).getReg();
  9775. const TargetRegisterClass *DstRC = &RISCV::FPR64RegClass;
  9776. int FI = MF.getInfo<RISCVMachineFunctionInfo>()->getMoveF64FrameIndex(MF);
  9777. MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
  9778. MachineMemOperand *MMOLo =
  9779. MF.getMachineMemOperand(MPI, MachineMemOperand::MOStore, 4, Align(8));
  9780. MachineMemOperand *MMOHi = MF.getMachineMemOperand(
  9781. MPI.getWithOffset(4), MachineMemOperand::MOStore, 4, Align(8));
  9782. BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
  9783. .addReg(LoReg, getKillRegState(MI.getOperand(1).isKill()))
  9784. .addFrameIndex(FI)
  9785. .addImm(0)
  9786. .addMemOperand(MMOLo);
  9787. BuildMI(*BB, MI, DL, TII.get(RISCV::SW))
  9788. .addReg(HiReg, getKillRegState(MI.getOperand(2).isKill()))
  9789. .addFrameIndex(FI)
  9790. .addImm(4)
  9791. .addMemOperand(MMOHi);
  9792. TII.loadRegFromStackSlot(*BB, MI, DstReg, FI, DstRC, RI, Register());
  9793. MI.eraseFromParent(); // The pseudo instruction is gone now.
  9794. return BB;
  9795. }
  9796. static bool isSelectPseudo(MachineInstr &MI) {
  9797. switch (MI.getOpcode()) {
  9798. default:
  9799. return false;
  9800. case RISCV::Select_GPR_Using_CC_GPR:
  9801. case RISCV::Select_FPR16_Using_CC_GPR:
  9802. case RISCV::Select_FPR32_Using_CC_GPR:
  9803. case RISCV::Select_FPR64_Using_CC_GPR:
  9804. return true;
  9805. }
  9806. }
  9807. static MachineBasicBlock *emitQuietFCMP(MachineInstr &MI, MachineBasicBlock *BB,
  9808. unsigned RelOpcode, unsigned EqOpcode,
  9809. const RISCVSubtarget &Subtarget) {
  9810. DebugLoc DL = MI.getDebugLoc();
  9811. Register DstReg = MI.getOperand(0).getReg();
  9812. Register Src1Reg = MI.getOperand(1).getReg();
  9813. Register Src2Reg = MI.getOperand(2).getReg();
  9814. MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
  9815. Register SavedFFlags = MRI.createVirtualRegister(&RISCV::GPRRegClass);
  9816. const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
  9817. // Save the current FFLAGS.
  9818. BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFlags);
  9819. auto MIB = BuildMI(*BB, MI, DL, TII.get(RelOpcode), DstReg)
  9820. .addReg(Src1Reg)
  9821. .addReg(Src2Reg);
  9822. if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
  9823. MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
  9824. // Restore the FFLAGS.
  9825. BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
  9826. .addReg(SavedFFlags, RegState::Kill);
  9827. // Issue a dummy FEQ opcode to raise exception for signaling NaNs.
  9828. auto MIB2 = BuildMI(*BB, MI, DL, TII.get(EqOpcode), RISCV::X0)
  9829. .addReg(Src1Reg, getKillRegState(MI.getOperand(1).isKill()))
  9830. .addReg(Src2Reg, getKillRegState(MI.getOperand(2).isKill()));
  9831. if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
  9832. MIB2->setFlag(MachineInstr::MIFlag::NoFPExcept);
  9833. // Erase the pseudoinstruction.
  9834. MI.eraseFromParent();
  9835. return BB;
  9836. }
  9837. static MachineBasicBlock *
  9838. EmitLoweredCascadedSelect(MachineInstr &First, MachineInstr &Second,
  9839. MachineBasicBlock *ThisMBB,
  9840. const RISCVSubtarget &Subtarget) {
  9841. // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5)
  9842. // Without this, custom-inserter would have generated:
  9843. //
  9844. // A
  9845. // | \
  9846. // | B
  9847. // | /
  9848. // C
  9849. // | \
  9850. // | D
  9851. // | /
  9852. // E
  9853. //
  9854. // A: X = ...; Y = ...
  9855. // B: empty
  9856. // C: Z = PHI [X, A], [Y, B]
  9857. // D: empty
  9858. // E: PHI [X, C], [Z, D]
  9859. //
  9860. // If we lower both Select_FPRX_ in a single step, we can instead generate:
  9861. //
  9862. // A
  9863. // | \
  9864. // | C
  9865. // | /|
  9866. // |/ |
  9867. // | |
  9868. // | D
  9869. // | /
  9870. // E
  9871. //
  9872. // A: X = ...; Y = ...
  9873. // D: empty
  9874. // E: PHI [X, A], [X, C], [Y, D]
  9875. const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
  9876. const DebugLoc &DL = First.getDebugLoc();
  9877. const BasicBlock *LLVM_BB = ThisMBB->getBasicBlock();
  9878. MachineFunction *F = ThisMBB->getParent();
  9879. MachineBasicBlock *FirstMBB = F->CreateMachineBasicBlock(LLVM_BB);
  9880. MachineBasicBlock *SecondMBB = F->CreateMachineBasicBlock(LLVM_BB);
  9881. MachineBasicBlock *SinkMBB = F->CreateMachineBasicBlock(LLVM_BB);
  9882. MachineFunction::iterator It = ++ThisMBB->getIterator();
  9883. F->insert(It, FirstMBB);
  9884. F->insert(It, SecondMBB);
  9885. F->insert(It, SinkMBB);
  9886. // Transfer the remainder of ThisMBB and its successor edges to SinkMBB.
  9887. SinkMBB->splice(SinkMBB->begin(), ThisMBB,
  9888. std::next(MachineBasicBlock::iterator(First)),
  9889. ThisMBB->end());
  9890. SinkMBB->transferSuccessorsAndUpdatePHIs(ThisMBB);
  9891. // Fallthrough block for ThisMBB.
  9892. ThisMBB->addSuccessor(FirstMBB);
  9893. // Fallthrough block for FirstMBB.
  9894. FirstMBB->addSuccessor(SecondMBB);
  9895. ThisMBB->addSuccessor(SinkMBB);
  9896. FirstMBB->addSuccessor(SinkMBB);
  9897. // This is fallthrough.
  9898. SecondMBB->addSuccessor(SinkMBB);
  9899. auto FirstCC = static_cast<RISCVCC::CondCode>(First.getOperand(3).getImm());
  9900. Register FLHS = First.getOperand(1).getReg();
  9901. Register FRHS = First.getOperand(2).getReg();
  9902. // Insert appropriate branch.
  9903. BuildMI(FirstMBB, DL, TII.getBrCond(FirstCC))
  9904. .addReg(FLHS)
  9905. .addReg(FRHS)
  9906. .addMBB(SinkMBB);
  9907. Register SLHS = Second.getOperand(1).getReg();
  9908. Register SRHS = Second.getOperand(2).getReg();
  9909. Register Op1Reg4 = First.getOperand(4).getReg();
  9910. Register Op1Reg5 = First.getOperand(5).getReg();
  9911. auto SecondCC = static_cast<RISCVCC::CondCode>(Second.getOperand(3).getImm());
  9912. // Insert appropriate branch.
  9913. BuildMI(ThisMBB, DL, TII.getBrCond(SecondCC))
  9914. .addReg(SLHS)
  9915. .addReg(SRHS)
  9916. .addMBB(SinkMBB);
  9917. Register DestReg = Second.getOperand(0).getReg();
  9918. Register Op2Reg4 = Second.getOperand(4).getReg();
  9919. BuildMI(*SinkMBB, SinkMBB->begin(), DL, TII.get(RISCV::PHI), DestReg)
  9920. .addReg(Op2Reg4)
  9921. .addMBB(ThisMBB)
  9922. .addReg(Op1Reg4)
  9923. .addMBB(FirstMBB)
  9924. .addReg(Op1Reg5)
  9925. .addMBB(SecondMBB);
  9926. // Now remove the Select_FPRX_s.
  9927. First.eraseFromParent();
  9928. Second.eraseFromParent();
  9929. return SinkMBB;
  9930. }
  9931. static MachineBasicBlock *emitSelectPseudo(MachineInstr &MI,
  9932. MachineBasicBlock *BB,
  9933. const RISCVSubtarget &Subtarget) {
  9934. // To "insert" Select_* instructions, we actually have to insert the triangle
  9935. // control-flow pattern. The incoming instructions know the destination vreg
  9936. // to set, the condition code register to branch on, the true/false values to
  9937. // select between, and the condcode to use to select the appropriate branch.
  9938. //
  9939. // We produce the following control flow:
  9940. // HeadMBB
  9941. // | \
  9942. // | IfFalseMBB
  9943. // | /
  9944. // TailMBB
  9945. //
  9946. // When we find a sequence of selects we attempt to optimize their emission
  9947. // by sharing the control flow. Currently we only handle cases where we have
  9948. // multiple selects with the exact same condition (same LHS, RHS and CC).
  9949. // The selects may be interleaved with other instructions if the other
  9950. // instructions meet some requirements we deem safe:
  9951. // - They are not pseudo instructions.
  9952. // - They are debug instructions. Otherwise,
  9953. // - They do not have side-effects, do not access memory and their inputs do
  9954. // not depend on the results of the select pseudo-instructions.
  9955. // The TrueV/FalseV operands of the selects cannot depend on the result of
  9956. // previous selects in the sequence.
  9957. // These conditions could be further relaxed. See the X86 target for a
  9958. // related approach and more information.
  9959. //
  9960. // Select_FPRX_ (rs1, rs2, imm, rs4, (Select_FPRX_ rs1, rs2, imm, rs4, rs5))
  9961. // is checked here and handled by a separate function -
  9962. // EmitLoweredCascadedSelect.
  9963. Register LHS = MI.getOperand(1).getReg();
  9964. Register RHS = MI.getOperand(2).getReg();
  9965. auto CC = static_cast<RISCVCC::CondCode>(MI.getOperand(3).getImm());
  9966. SmallVector<MachineInstr *, 4> SelectDebugValues;
  9967. SmallSet<Register, 4> SelectDests;
  9968. SelectDests.insert(MI.getOperand(0).getReg());
  9969. MachineInstr *LastSelectPseudo = &MI;
  9970. auto Next = next_nodbg(MI.getIterator(), BB->instr_end());
  9971. if (MI.getOpcode() != RISCV::Select_GPR_Using_CC_GPR && Next != BB->end() &&
  9972. Next->getOpcode() == MI.getOpcode() &&
  9973. Next->getOperand(5).getReg() == MI.getOperand(0).getReg() &&
  9974. Next->getOperand(5).isKill()) {
  9975. return EmitLoweredCascadedSelect(MI, *Next, BB, Subtarget);
  9976. }
  9977. for (auto E = BB->end(), SequenceMBBI = MachineBasicBlock::iterator(MI);
  9978. SequenceMBBI != E; ++SequenceMBBI) {
  9979. if (SequenceMBBI->isDebugInstr())
  9980. continue;
  9981. if (isSelectPseudo(*SequenceMBBI)) {
  9982. if (SequenceMBBI->getOperand(1).getReg() != LHS ||
  9983. SequenceMBBI->getOperand(2).getReg() != RHS ||
  9984. SequenceMBBI->getOperand(3).getImm() != CC ||
  9985. SelectDests.count(SequenceMBBI->getOperand(4).getReg()) ||
  9986. SelectDests.count(SequenceMBBI->getOperand(5).getReg()))
  9987. break;
  9988. LastSelectPseudo = &*SequenceMBBI;
  9989. SequenceMBBI->collectDebugValues(SelectDebugValues);
  9990. SelectDests.insert(SequenceMBBI->getOperand(0).getReg());
  9991. continue;
  9992. }
  9993. if (SequenceMBBI->hasUnmodeledSideEffects() ||
  9994. SequenceMBBI->mayLoadOrStore() ||
  9995. SequenceMBBI->usesCustomInsertionHook())
  9996. break;
  9997. if (llvm::any_of(SequenceMBBI->operands(), [&](MachineOperand &MO) {
  9998. return MO.isReg() && MO.isUse() && SelectDests.count(MO.getReg());
  9999. }))
  10000. break;
  10001. }
  10002. const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
  10003. const BasicBlock *LLVM_BB = BB->getBasicBlock();
  10004. DebugLoc DL = MI.getDebugLoc();
  10005. MachineFunction::iterator I = ++BB->getIterator();
  10006. MachineBasicBlock *HeadMBB = BB;
  10007. MachineFunction *F = BB->getParent();
  10008. MachineBasicBlock *TailMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10009. MachineBasicBlock *IfFalseMBB = F->CreateMachineBasicBlock(LLVM_BB);
  10010. F->insert(I, IfFalseMBB);
  10011. F->insert(I, TailMBB);
  10012. // Transfer debug instructions associated with the selects to TailMBB.
  10013. for (MachineInstr *DebugInstr : SelectDebugValues) {
  10014. TailMBB->push_back(DebugInstr->removeFromParent());
  10015. }
  10016. // Move all instructions after the sequence to TailMBB.
  10017. TailMBB->splice(TailMBB->end(), HeadMBB,
  10018. std::next(LastSelectPseudo->getIterator()), HeadMBB->end());
  10019. // Update machine-CFG edges by transferring all successors of the current
  10020. // block to the new block which will contain the Phi nodes for the selects.
  10021. TailMBB->transferSuccessorsAndUpdatePHIs(HeadMBB);
  10022. // Set the successors for HeadMBB.
  10023. HeadMBB->addSuccessor(IfFalseMBB);
  10024. HeadMBB->addSuccessor(TailMBB);
  10025. // Insert appropriate branch.
  10026. BuildMI(HeadMBB, DL, TII.getBrCond(CC))
  10027. .addReg(LHS)
  10028. .addReg(RHS)
  10029. .addMBB(TailMBB);
  10030. // IfFalseMBB just falls through to TailMBB.
  10031. IfFalseMBB->addSuccessor(TailMBB);
  10032. // Create PHIs for all of the select pseudo-instructions.
  10033. auto SelectMBBI = MI.getIterator();
  10034. auto SelectEnd = std::next(LastSelectPseudo->getIterator());
  10035. auto InsertionPoint = TailMBB->begin();
  10036. while (SelectMBBI != SelectEnd) {
  10037. auto Next = std::next(SelectMBBI);
  10038. if (isSelectPseudo(*SelectMBBI)) {
  10039. // %Result = phi [ %TrueValue, HeadMBB ], [ %FalseValue, IfFalseMBB ]
  10040. BuildMI(*TailMBB, InsertionPoint, SelectMBBI->getDebugLoc(),
  10041. TII.get(RISCV::PHI), SelectMBBI->getOperand(0).getReg())
  10042. .addReg(SelectMBBI->getOperand(4).getReg())
  10043. .addMBB(HeadMBB)
  10044. .addReg(SelectMBBI->getOperand(5).getReg())
  10045. .addMBB(IfFalseMBB);
  10046. SelectMBBI->eraseFromParent();
  10047. }
  10048. SelectMBBI = Next;
  10049. }
  10050. F->getProperties().reset(MachineFunctionProperties::Property::NoPHIs);
  10051. return TailMBB;
  10052. }
  10053. static MachineBasicBlock *
  10054. emitVFCVT_RM_MASK(MachineInstr &MI, MachineBasicBlock *BB, unsigned Opcode) {
  10055. DebugLoc DL = MI.getDebugLoc();
  10056. const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
  10057. MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
  10058. Register SavedFRM = MRI.createVirtualRegister(&RISCV::GPRRegClass);
  10059. // Update FRM and save the old value.
  10060. BuildMI(*BB, MI, DL, TII.get(RISCV::SwapFRMImm), SavedFRM)
  10061. .addImm(MI.getOperand(4).getImm());
  10062. // Emit an VFCVT without the FRM operand.
  10063. assert(MI.getNumOperands() == 8);
  10064. auto MIB = BuildMI(*BB, MI, DL, TII.get(Opcode))
  10065. .add(MI.getOperand(0))
  10066. .add(MI.getOperand(1))
  10067. .add(MI.getOperand(2))
  10068. .add(MI.getOperand(3))
  10069. .add(MI.getOperand(5))
  10070. .add(MI.getOperand(6))
  10071. .add(MI.getOperand(7));
  10072. if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
  10073. MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
  10074. // Restore FRM.
  10075. BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFRM))
  10076. .addReg(SavedFRM, RegState::Kill);
  10077. // Erase the pseudoinstruction.
  10078. MI.eraseFromParent();
  10079. return BB;
  10080. }
  10081. static MachineBasicBlock *emitVFROUND_NOEXCEPT_MASK(MachineInstr &MI,
  10082. MachineBasicBlock *BB,
  10083. unsigned CVTXOpc,
  10084. unsigned CVTFOpc) {
  10085. DebugLoc DL = MI.getDebugLoc();
  10086. const TargetInstrInfo &TII = *BB->getParent()->getSubtarget().getInstrInfo();
  10087. MachineRegisterInfo &MRI = BB->getParent()->getRegInfo();
  10088. Register SavedFFLAGS = MRI.createVirtualRegister(&RISCV::GPRRegClass);
  10089. // Save the old value of FFLAGS.
  10090. BuildMI(*BB, MI, DL, TII.get(RISCV::ReadFFLAGS), SavedFFLAGS);
  10091. assert(MI.getNumOperands() == 7);
  10092. // Emit a VFCVT_X_F
  10093. const TargetRegisterInfo *TRI =
  10094. BB->getParent()->getSubtarget().getRegisterInfo();
  10095. const TargetRegisterClass *RC = MI.getRegClassConstraint(0, &TII, TRI);
  10096. Register Tmp = MRI.createVirtualRegister(RC);
  10097. BuildMI(*BB, MI, DL, TII.get(CVTXOpc), Tmp)
  10098. .add(MI.getOperand(1))
  10099. .add(MI.getOperand(2))
  10100. .add(MI.getOperand(3))
  10101. .add(MI.getOperand(4))
  10102. .add(MI.getOperand(5))
  10103. .add(MI.getOperand(6));
  10104. // Emit a VFCVT_F_X
  10105. BuildMI(*BB, MI, DL, TII.get(CVTFOpc))
  10106. .add(MI.getOperand(0))
  10107. .add(MI.getOperand(1))
  10108. .addReg(Tmp)
  10109. .add(MI.getOperand(3))
  10110. .add(MI.getOperand(4))
  10111. .add(MI.getOperand(5))
  10112. .add(MI.getOperand(6));
  10113. // Restore FFLAGS.
  10114. BuildMI(*BB, MI, DL, TII.get(RISCV::WriteFFLAGS))
  10115. .addReg(SavedFFLAGS, RegState::Kill);
  10116. // Erase the pseudoinstruction.
  10117. MI.eraseFromParent();
  10118. return BB;
  10119. }
  10120. static MachineBasicBlock *emitFROUND(MachineInstr &MI, MachineBasicBlock *MBB,
  10121. const RISCVSubtarget &Subtarget) {
  10122. unsigned CmpOpc, F2IOpc, I2FOpc, FSGNJOpc, FSGNJXOpc;
  10123. const TargetRegisterClass *RC;
  10124. switch (MI.getOpcode()) {
  10125. default:
  10126. llvm_unreachable("Unexpected opcode");
  10127. case RISCV::PseudoFROUND_H:
  10128. CmpOpc = RISCV::FLT_H;
  10129. F2IOpc = RISCV::FCVT_W_H;
  10130. I2FOpc = RISCV::FCVT_H_W;
  10131. FSGNJOpc = RISCV::FSGNJ_H;
  10132. FSGNJXOpc = RISCV::FSGNJX_H;
  10133. RC = &RISCV::FPR16RegClass;
  10134. break;
  10135. case RISCV::PseudoFROUND_S:
  10136. CmpOpc = RISCV::FLT_S;
  10137. F2IOpc = RISCV::FCVT_W_S;
  10138. I2FOpc = RISCV::FCVT_S_W;
  10139. FSGNJOpc = RISCV::FSGNJ_S;
  10140. FSGNJXOpc = RISCV::FSGNJX_S;
  10141. RC = &RISCV::FPR32RegClass;
  10142. break;
  10143. case RISCV::PseudoFROUND_D:
  10144. assert(Subtarget.is64Bit() && "Expected 64-bit GPR.");
  10145. CmpOpc = RISCV::FLT_D;
  10146. F2IOpc = RISCV::FCVT_L_D;
  10147. I2FOpc = RISCV::FCVT_D_L;
  10148. FSGNJOpc = RISCV::FSGNJ_D;
  10149. FSGNJXOpc = RISCV::FSGNJX_D;
  10150. RC = &RISCV::FPR64RegClass;
  10151. break;
  10152. }
  10153. const BasicBlock *BB = MBB->getBasicBlock();
  10154. DebugLoc DL = MI.getDebugLoc();
  10155. MachineFunction::iterator I = ++MBB->getIterator();
  10156. MachineFunction *F = MBB->getParent();
  10157. MachineBasicBlock *CvtMBB = F->CreateMachineBasicBlock(BB);
  10158. MachineBasicBlock *DoneMBB = F->CreateMachineBasicBlock(BB);
  10159. F->insert(I, CvtMBB);
  10160. F->insert(I, DoneMBB);
  10161. // Move all instructions after the sequence to DoneMBB.
  10162. DoneMBB->splice(DoneMBB->end(), MBB, MachineBasicBlock::iterator(MI),
  10163. MBB->end());
  10164. // Update machine-CFG edges by transferring all successors of the current
  10165. // block to the new block which will contain the Phi nodes for the selects.
  10166. DoneMBB->transferSuccessorsAndUpdatePHIs(MBB);
  10167. // Set the successors for MBB.
  10168. MBB->addSuccessor(CvtMBB);
  10169. MBB->addSuccessor(DoneMBB);
  10170. Register DstReg = MI.getOperand(0).getReg();
  10171. Register SrcReg = MI.getOperand(1).getReg();
  10172. Register MaxReg = MI.getOperand(2).getReg();
  10173. int64_t FRM = MI.getOperand(3).getImm();
  10174. const RISCVInstrInfo &TII = *Subtarget.getInstrInfo();
  10175. MachineRegisterInfo &MRI = MBB->getParent()->getRegInfo();
  10176. Register FabsReg = MRI.createVirtualRegister(RC);
  10177. BuildMI(MBB, DL, TII.get(FSGNJXOpc), FabsReg).addReg(SrcReg).addReg(SrcReg);
  10178. // Compare the FP value to the max value.
  10179. Register CmpReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
  10180. auto MIB =
  10181. BuildMI(MBB, DL, TII.get(CmpOpc), CmpReg).addReg(FabsReg).addReg(MaxReg);
  10182. if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
  10183. MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
  10184. // Insert branch.
  10185. BuildMI(MBB, DL, TII.get(RISCV::BEQ))
  10186. .addReg(CmpReg)
  10187. .addReg(RISCV::X0)
  10188. .addMBB(DoneMBB);
  10189. CvtMBB->addSuccessor(DoneMBB);
  10190. // Convert to integer.
  10191. Register F2IReg = MRI.createVirtualRegister(&RISCV::GPRRegClass);
  10192. MIB = BuildMI(CvtMBB, DL, TII.get(F2IOpc), F2IReg).addReg(SrcReg).addImm(FRM);
  10193. if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
  10194. MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
  10195. // Convert back to FP.
  10196. Register I2FReg = MRI.createVirtualRegister(RC);
  10197. MIB = BuildMI(CvtMBB, DL, TII.get(I2FOpc), I2FReg).addReg(F2IReg).addImm(FRM);
  10198. if (MI.getFlag(MachineInstr::MIFlag::NoFPExcept))
  10199. MIB->setFlag(MachineInstr::MIFlag::NoFPExcept);
  10200. // Restore the sign bit.
  10201. Register CvtReg = MRI.createVirtualRegister(RC);
  10202. BuildMI(CvtMBB, DL, TII.get(FSGNJOpc), CvtReg).addReg(I2FReg).addReg(SrcReg);
  10203. // Merge the results.
  10204. BuildMI(*DoneMBB, DoneMBB->begin(), DL, TII.get(RISCV::PHI), DstReg)
  10205. .addReg(SrcReg)
  10206. .addMBB(MBB)
  10207. .addReg(CvtReg)
  10208. .addMBB(CvtMBB);
  10209. MI.eraseFromParent();
  10210. return DoneMBB;
  10211. }
  10212. MachineBasicBlock *
  10213. RISCVTargetLowering::EmitInstrWithCustomInserter(MachineInstr &MI,
  10214. MachineBasicBlock *BB) const {
  10215. switch (MI.getOpcode()) {
  10216. default:
  10217. llvm_unreachable("Unexpected instr type to insert");
  10218. case RISCV::ReadCycleWide:
  10219. assert(!Subtarget.is64Bit() &&
  10220. "ReadCycleWrite is only to be used on riscv32");
  10221. return emitReadCycleWidePseudo(MI, BB);
  10222. case RISCV::Select_GPR_Using_CC_GPR:
  10223. case RISCV::Select_FPR16_Using_CC_GPR:
  10224. case RISCV::Select_FPR32_Using_CC_GPR:
  10225. case RISCV::Select_FPR64_Using_CC_GPR:
  10226. return emitSelectPseudo(MI, BB, Subtarget);
  10227. case RISCV::BuildPairF64Pseudo:
  10228. return emitBuildPairF64Pseudo(MI, BB);
  10229. case RISCV::SplitF64Pseudo:
  10230. return emitSplitF64Pseudo(MI, BB);
  10231. case RISCV::PseudoQuietFLE_H:
  10232. return emitQuietFCMP(MI, BB, RISCV::FLE_H, RISCV::FEQ_H, Subtarget);
  10233. case RISCV::PseudoQuietFLT_H:
  10234. return emitQuietFCMP(MI, BB, RISCV::FLT_H, RISCV::FEQ_H, Subtarget);
  10235. case RISCV::PseudoQuietFLE_S:
  10236. return emitQuietFCMP(MI, BB, RISCV::FLE_S, RISCV::FEQ_S, Subtarget);
  10237. case RISCV::PseudoQuietFLT_S:
  10238. return emitQuietFCMP(MI, BB, RISCV::FLT_S, RISCV::FEQ_S, Subtarget);
  10239. case RISCV::PseudoQuietFLE_D:
  10240. return emitQuietFCMP(MI, BB, RISCV::FLE_D, RISCV::FEQ_D, Subtarget);
  10241. case RISCV::PseudoQuietFLT_D:
  10242. return emitQuietFCMP(MI, BB, RISCV::FLT_D, RISCV::FEQ_D, Subtarget);
  10243. // =========================================================================
  10244. // VFCVT
  10245. // =========================================================================
  10246. case RISCV::PseudoVFCVT_RM_X_F_V_M1_MASK:
  10247. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M1_MASK);
  10248. case RISCV::PseudoVFCVT_RM_X_F_V_M2_MASK:
  10249. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M2_MASK);
  10250. case RISCV::PseudoVFCVT_RM_X_F_V_M4_MASK:
  10251. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M4_MASK);
  10252. case RISCV::PseudoVFCVT_RM_X_F_V_M8_MASK:
  10253. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M8_MASK);
  10254. case RISCV::PseudoVFCVT_RM_X_F_V_MF2_MASK:
  10255. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_MF2_MASK);
  10256. case RISCV::PseudoVFCVT_RM_X_F_V_MF4_MASK:
  10257. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_MF4_MASK);
  10258. case RISCV::PseudoVFCVT_RM_XU_F_V_M1_MASK:
  10259. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_XU_F_V_M1_MASK);
  10260. case RISCV::PseudoVFCVT_RM_XU_F_V_M2_MASK:
  10261. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_XU_F_V_M2_MASK);
  10262. case RISCV::PseudoVFCVT_RM_XU_F_V_M4_MASK:
  10263. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_XU_F_V_M4_MASK);
  10264. case RISCV::PseudoVFCVT_RM_XU_F_V_M8_MASK:
  10265. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_XU_F_V_M8_MASK);
  10266. case RISCV::PseudoVFCVT_RM_XU_F_V_MF2_MASK:
  10267. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_XU_F_V_MF2_MASK);
  10268. case RISCV::PseudoVFCVT_RM_XU_F_V_MF4_MASK:
  10269. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_XU_F_V_MF4_MASK);
  10270. case RISCV::PseudoVFCVT_RM_F_XU_V_M1_MASK:
  10271. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_XU_V_M1_MASK);
  10272. case RISCV::PseudoVFCVT_RM_F_XU_V_M2_MASK:
  10273. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_XU_V_M2_MASK);
  10274. case RISCV::PseudoVFCVT_RM_F_XU_V_M4_MASK:
  10275. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_XU_V_M4_MASK);
  10276. case RISCV::PseudoVFCVT_RM_F_XU_V_M8_MASK:
  10277. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_XU_V_M8_MASK);
  10278. case RISCV::PseudoVFCVT_RM_F_XU_V_MF2_MASK:
  10279. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_XU_V_MF2_MASK);
  10280. case RISCV::PseudoVFCVT_RM_F_XU_V_MF4_MASK:
  10281. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_XU_V_MF4_MASK);
  10282. case RISCV::PseudoVFCVT_RM_F_X_V_M1_MASK:
  10283. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_X_V_M1_MASK);
  10284. case RISCV::PseudoVFCVT_RM_F_X_V_M2_MASK:
  10285. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_X_V_M2_MASK);
  10286. case RISCV::PseudoVFCVT_RM_F_X_V_M4_MASK:
  10287. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_X_V_M4_MASK);
  10288. case RISCV::PseudoVFCVT_RM_F_X_V_M8_MASK:
  10289. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_X_V_M8_MASK);
  10290. case RISCV::PseudoVFCVT_RM_F_X_V_MF2_MASK:
  10291. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_X_V_MF2_MASK);
  10292. case RISCV::PseudoVFCVT_RM_F_X_V_MF4_MASK:
  10293. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFCVT_F_X_V_MF4_MASK);
  10294. // =========================================================================
  10295. // VFWCVT
  10296. // =========================================================================
  10297. case RISCV::PseudoVFWCVT_RM_XU_F_V_M1_MASK:
  10298. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_M1_MASK);
  10299. case RISCV::PseudoVFWCVT_RM_XU_F_V_M2_MASK:
  10300. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_M2_MASK);
  10301. case RISCV::PseudoVFWCVT_RM_XU_F_V_M4_MASK:
  10302. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_M4_MASK);
  10303. case RISCV::PseudoVFWCVT_RM_XU_F_V_MF2_MASK:
  10304. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_MF2_MASK);
  10305. case RISCV::PseudoVFWCVT_RM_XU_F_V_MF4_MASK:
  10306. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_MF4_MASK);
  10307. case RISCV::PseudoVFWCVT_RM_X_F_V_M1_MASK:
  10308. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_M1_MASK);
  10309. case RISCV::PseudoVFWCVT_RM_X_F_V_M2_MASK:
  10310. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_M2_MASK);
  10311. case RISCV::PseudoVFWCVT_RM_X_F_V_M4_MASK:
  10312. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_M4_MASK);
  10313. case RISCV::PseudoVFWCVT_RM_X_F_V_MF2_MASK:
  10314. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_MF2_MASK);
  10315. case RISCV::PseudoVFWCVT_RM_X_F_V_MF4_MASK:
  10316. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_X_F_V_MF4_MASK);
  10317. case RISCV::PseudoVFWCVT_RM_F_XU_V_M1_MASK:
  10318. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_M1_MASK);
  10319. case RISCV::PseudoVFWCVT_RM_F_XU_V_M2_MASK:
  10320. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_M2_MASK);
  10321. case RISCV::PseudoVFWCVT_RM_F_XU_V_M4_MASK:
  10322. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_M4_MASK);
  10323. case RISCV::PseudoVFWCVT_RM_F_XU_V_MF2_MASK:
  10324. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_MF2_MASK);
  10325. case RISCV::PseudoVFWCVT_RM_F_XU_V_MF4_MASK:
  10326. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_MF4_MASK);
  10327. case RISCV::PseudoVFWCVT_RM_F_XU_V_MF8_MASK:
  10328. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_MF8_MASK);
  10329. case RISCV::PseudoVFWCVT_RM_F_X_V_M1_MASK:
  10330. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_M1_MASK);
  10331. case RISCV::PseudoVFWCVT_RM_F_X_V_M2_MASK:
  10332. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_M2_MASK);
  10333. case RISCV::PseudoVFWCVT_RM_F_X_V_M4_MASK:
  10334. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_M4_MASK);
  10335. case RISCV::PseudoVFWCVT_RM_F_X_V_MF2_MASK:
  10336. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_MF2_MASK);
  10337. case RISCV::PseudoVFWCVT_RM_F_X_V_MF4_MASK:
  10338. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_MF4_MASK);
  10339. case RISCV::PseudoVFWCVT_RM_F_X_V_MF8_MASK:
  10340. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFWCVT_F_XU_V_MF8_MASK);
  10341. // =========================================================================
  10342. // VFNCVT
  10343. // =========================================================================
  10344. case RISCV::PseudoVFNCVT_RM_XU_F_W_M1_MASK:
  10345. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_M1_MASK);
  10346. case RISCV::PseudoVFNCVT_RM_XU_F_W_M2_MASK:
  10347. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_M2_MASK);
  10348. case RISCV::PseudoVFNCVT_RM_XU_F_W_M4_MASK:
  10349. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_M4_MASK);
  10350. case RISCV::PseudoVFNCVT_RM_XU_F_W_MF2_MASK:
  10351. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_MF2_MASK);
  10352. case RISCV::PseudoVFNCVT_RM_XU_F_W_MF4_MASK:
  10353. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_MF4_MASK);
  10354. case RISCV::PseudoVFNCVT_RM_XU_F_W_MF8_MASK:
  10355. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_XU_F_W_MF8_MASK);
  10356. case RISCV::PseudoVFNCVT_RM_X_F_W_M1_MASK:
  10357. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_M1_MASK);
  10358. case RISCV::PseudoVFNCVT_RM_X_F_W_M2_MASK:
  10359. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_M2_MASK);
  10360. case RISCV::PseudoVFNCVT_RM_X_F_W_M4_MASK:
  10361. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_M4_MASK);
  10362. case RISCV::PseudoVFNCVT_RM_X_F_W_MF2_MASK:
  10363. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_MF2_MASK);
  10364. case RISCV::PseudoVFNCVT_RM_X_F_W_MF4_MASK:
  10365. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_MF4_MASK);
  10366. case RISCV::PseudoVFNCVT_RM_X_F_W_MF8_MASK:
  10367. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_X_F_W_MF8_MASK);
  10368. case RISCV::PseudoVFNCVT_RM_F_XU_W_M1_MASK:
  10369. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_M1_MASK);
  10370. case RISCV::PseudoVFNCVT_RM_F_XU_W_M2_MASK:
  10371. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_M2_MASK);
  10372. case RISCV::PseudoVFNCVT_RM_F_XU_W_M4_MASK:
  10373. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_M4_MASK);
  10374. case RISCV::PseudoVFNCVT_RM_F_XU_W_MF2_MASK:
  10375. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_MF2_MASK);
  10376. case RISCV::PseudoVFNCVT_RM_F_XU_W_MF4_MASK:
  10377. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_MF4_MASK);
  10378. case RISCV::PseudoVFNCVT_RM_F_X_W_M1_MASK:
  10379. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_M1_MASK);
  10380. case RISCV::PseudoVFNCVT_RM_F_X_W_M2_MASK:
  10381. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_M2_MASK);
  10382. case RISCV::PseudoVFNCVT_RM_F_X_W_M4_MASK:
  10383. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_M4_MASK);
  10384. case RISCV::PseudoVFNCVT_RM_F_X_W_MF2_MASK:
  10385. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_MF2_MASK);
  10386. case RISCV::PseudoVFNCVT_RM_F_X_W_MF4_MASK:
  10387. return emitVFCVT_RM_MASK(MI, BB, RISCV::PseudoVFNCVT_F_XU_W_MF4_MASK);
  10388. case RISCV::PseudoVFROUND_NOEXCEPT_V_M1_MASK:
  10389. return emitVFROUND_NOEXCEPT_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M1_MASK,
  10390. RISCV::PseudoVFCVT_F_X_V_M1_MASK);
  10391. case RISCV::PseudoVFROUND_NOEXCEPT_V_M2_MASK:
  10392. return emitVFROUND_NOEXCEPT_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M2_MASK,
  10393. RISCV::PseudoVFCVT_F_X_V_M2_MASK);
  10394. case RISCV::PseudoVFROUND_NOEXCEPT_V_M4_MASK:
  10395. return emitVFROUND_NOEXCEPT_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M4_MASK,
  10396. RISCV::PseudoVFCVT_F_X_V_M4_MASK);
  10397. case RISCV::PseudoVFROUND_NOEXCEPT_V_M8_MASK:
  10398. return emitVFROUND_NOEXCEPT_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_M8_MASK,
  10399. RISCV::PseudoVFCVT_F_X_V_M8_MASK);
  10400. case RISCV::PseudoVFROUND_NOEXCEPT_V_MF2_MASK:
  10401. return emitVFROUND_NOEXCEPT_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_MF2_MASK,
  10402. RISCV::PseudoVFCVT_F_X_V_MF2_MASK);
  10403. case RISCV::PseudoVFROUND_NOEXCEPT_V_MF4_MASK:
  10404. return emitVFROUND_NOEXCEPT_MASK(MI, BB, RISCV::PseudoVFCVT_X_F_V_MF4_MASK,
  10405. RISCV::PseudoVFCVT_F_X_V_MF4_MASK);
  10406. case RISCV::PseudoFROUND_H:
  10407. case RISCV::PseudoFROUND_S:
  10408. case RISCV::PseudoFROUND_D:
  10409. return emitFROUND(MI, BB, Subtarget);
  10410. }
  10411. }
  10412. void RISCVTargetLowering::AdjustInstrPostInstrSelection(MachineInstr &MI,
  10413. SDNode *Node) const {
  10414. // Add FRM dependency to any instructions with dynamic rounding mode.
  10415. unsigned Opc = MI.getOpcode();
  10416. auto Idx = RISCV::getNamedOperandIdx(Opc, RISCV::OpName::frm);
  10417. if (Idx < 0)
  10418. return;
  10419. if (MI.getOperand(Idx).getImm() != RISCVFPRndMode::DYN)
  10420. return;
  10421. // If the instruction already reads FRM, don't add another read.
  10422. if (MI.readsRegister(RISCV::FRM))
  10423. return;
  10424. MI.addOperand(
  10425. MachineOperand::CreateReg(RISCV::FRM, /*isDef*/ false, /*isImp*/ true));
  10426. }
  10427. // Calling Convention Implementation.
  10428. // The expectations for frontend ABI lowering vary from target to target.
  10429. // Ideally, an LLVM frontend would be able to avoid worrying about many ABI
  10430. // details, but this is a longer term goal. For now, we simply try to keep the
  10431. // role of the frontend as simple and well-defined as possible. The rules can
  10432. // be summarised as:
  10433. // * Never split up large scalar arguments. We handle them here.
  10434. // * If a hardfloat calling convention is being used, and the struct may be
  10435. // passed in a pair of registers (fp+fp, int+fp), and both registers are
  10436. // available, then pass as two separate arguments. If either the GPRs or FPRs
  10437. // are exhausted, then pass according to the rule below.
  10438. // * If a struct could never be passed in registers or directly in a stack
  10439. // slot (as it is larger than 2*XLEN and the floating point rules don't
  10440. // apply), then pass it using a pointer with the byval attribute.
  10441. // * If a struct is less than 2*XLEN, then coerce to either a two-element
  10442. // word-sized array or a 2*XLEN scalar (depending on alignment).
  10443. // * The frontend can determine whether a struct is returned by reference or
  10444. // not based on its size and fields. If it will be returned by reference, the
  10445. // frontend must modify the prototype so a pointer with the sret annotation is
  10446. // passed as the first argument. This is not necessary for large scalar
  10447. // returns.
  10448. // * Struct return values and varargs should be coerced to structs containing
  10449. // register-size fields in the same situations they would be for fixed
  10450. // arguments.
  10451. static const MCPhysReg ArgGPRs[] = {
  10452. RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13,
  10453. RISCV::X14, RISCV::X15, RISCV::X16, RISCV::X17
  10454. };
  10455. static const MCPhysReg ArgFPR16s[] = {
  10456. RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H,
  10457. RISCV::F14_H, RISCV::F15_H, RISCV::F16_H, RISCV::F17_H
  10458. };
  10459. static const MCPhysReg ArgFPR32s[] = {
  10460. RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F,
  10461. RISCV::F14_F, RISCV::F15_F, RISCV::F16_F, RISCV::F17_F
  10462. };
  10463. static const MCPhysReg ArgFPR64s[] = {
  10464. RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D,
  10465. RISCV::F14_D, RISCV::F15_D, RISCV::F16_D, RISCV::F17_D
  10466. };
  10467. // This is an interim calling convention and it may be changed in the future.
  10468. static const MCPhysReg ArgVRs[] = {
  10469. RISCV::V8, RISCV::V9, RISCV::V10, RISCV::V11, RISCV::V12, RISCV::V13,
  10470. RISCV::V14, RISCV::V15, RISCV::V16, RISCV::V17, RISCV::V18, RISCV::V19,
  10471. RISCV::V20, RISCV::V21, RISCV::V22, RISCV::V23};
  10472. static const MCPhysReg ArgVRM2s[] = {RISCV::V8M2, RISCV::V10M2, RISCV::V12M2,
  10473. RISCV::V14M2, RISCV::V16M2, RISCV::V18M2,
  10474. RISCV::V20M2, RISCV::V22M2};
  10475. static const MCPhysReg ArgVRM4s[] = {RISCV::V8M4, RISCV::V12M4, RISCV::V16M4,
  10476. RISCV::V20M4};
  10477. static const MCPhysReg ArgVRM8s[] = {RISCV::V8M8, RISCV::V16M8};
  10478. // Pass a 2*XLEN argument that has been split into two XLEN values through
  10479. // registers or the stack as necessary.
  10480. static bool CC_RISCVAssign2XLen(unsigned XLen, CCState &State, CCValAssign VA1,
  10481. ISD::ArgFlagsTy ArgFlags1, unsigned ValNo2,
  10482. MVT ValVT2, MVT LocVT2,
  10483. ISD::ArgFlagsTy ArgFlags2) {
  10484. unsigned XLenInBytes = XLen / 8;
  10485. if (Register Reg = State.AllocateReg(ArgGPRs)) {
  10486. // At least one half can be passed via register.
  10487. State.addLoc(CCValAssign::getReg(VA1.getValNo(), VA1.getValVT(), Reg,
  10488. VA1.getLocVT(), CCValAssign::Full));
  10489. } else {
  10490. // Both halves must be passed on the stack, with proper alignment.
  10491. Align StackAlign =
  10492. std::max(Align(XLenInBytes), ArgFlags1.getNonZeroOrigAlign());
  10493. State.addLoc(
  10494. CCValAssign::getMem(VA1.getValNo(), VA1.getValVT(),
  10495. State.AllocateStack(XLenInBytes, StackAlign),
  10496. VA1.getLocVT(), CCValAssign::Full));
  10497. State.addLoc(CCValAssign::getMem(
  10498. ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
  10499. LocVT2, CCValAssign::Full));
  10500. return false;
  10501. }
  10502. if (Register Reg = State.AllocateReg(ArgGPRs)) {
  10503. // The second half can also be passed via register.
  10504. State.addLoc(
  10505. CCValAssign::getReg(ValNo2, ValVT2, Reg, LocVT2, CCValAssign::Full));
  10506. } else {
  10507. // The second half is passed via the stack, without additional alignment.
  10508. State.addLoc(CCValAssign::getMem(
  10509. ValNo2, ValVT2, State.AllocateStack(XLenInBytes, Align(XLenInBytes)),
  10510. LocVT2, CCValAssign::Full));
  10511. }
  10512. return false;
  10513. }
  10514. static unsigned allocateRVVReg(MVT ValVT, unsigned ValNo,
  10515. std::optional<unsigned> FirstMaskArgument,
  10516. CCState &State, const RISCVTargetLowering &TLI) {
  10517. const TargetRegisterClass *RC = TLI.getRegClassFor(ValVT);
  10518. if (RC == &RISCV::VRRegClass) {
  10519. // Assign the first mask argument to V0.
  10520. // This is an interim calling convention and it may be changed in the
  10521. // future.
  10522. if (FirstMaskArgument && ValNo == *FirstMaskArgument)
  10523. return State.AllocateReg(RISCV::V0);
  10524. return State.AllocateReg(ArgVRs);
  10525. }
  10526. if (RC == &RISCV::VRM2RegClass)
  10527. return State.AllocateReg(ArgVRM2s);
  10528. if (RC == &RISCV::VRM4RegClass)
  10529. return State.AllocateReg(ArgVRM4s);
  10530. if (RC == &RISCV::VRM8RegClass)
  10531. return State.AllocateReg(ArgVRM8s);
  10532. llvm_unreachable("Unhandled register class for ValueType");
  10533. }
  10534. // Implements the RISC-V calling convention. Returns true upon failure.
  10535. static bool CC_RISCV(const DataLayout &DL, RISCVABI::ABI ABI, unsigned ValNo,
  10536. MVT ValVT, MVT LocVT, CCValAssign::LocInfo LocInfo,
  10537. ISD::ArgFlagsTy ArgFlags, CCState &State, bool IsFixed,
  10538. bool IsRet, Type *OrigTy, const RISCVTargetLowering &TLI,
  10539. std::optional<unsigned> FirstMaskArgument) {
  10540. unsigned XLen = DL.getLargestLegalIntTypeSizeInBits();
  10541. assert(XLen == 32 || XLen == 64);
  10542. MVT XLenVT = XLen == 32 ? MVT::i32 : MVT::i64;
  10543. // Static chain parameter must not be passed in normal argument registers,
  10544. // so we assign t2 for it as done in GCC's __builtin_call_with_static_chain
  10545. if (ArgFlags.isNest()) {
  10546. if (unsigned Reg = State.AllocateReg(RISCV::X7)) {
  10547. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
  10548. return false;
  10549. }
  10550. }
  10551. // Any return value split in to more than two values can't be returned
  10552. // directly. Vectors are returned via the available vector registers.
  10553. if (!LocVT.isVector() && IsRet && ValNo > 1)
  10554. return true;
  10555. // UseGPRForF16_F32 if targeting one of the soft-float ABIs, if passing a
  10556. // variadic argument, or if no F16/F32 argument registers are available.
  10557. bool UseGPRForF16_F32 = true;
  10558. // UseGPRForF64 if targeting soft-float ABIs or an FLEN=32 ABI, if passing a
  10559. // variadic argument, or if no F64 argument registers are available.
  10560. bool UseGPRForF64 = true;
  10561. switch (ABI) {
  10562. default:
  10563. llvm_unreachable("Unexpected ABI");
  10564. case RISCVABI::ABI_ILP32:
  10565. case RISCVABI::ABI_LP64:
  10566. break;
  10567. case RISCVABI::ABI_ILP32F:
  10568. case RISCVABI::ABI_LP64F:
  10569. UseGPRForF16_F32 = !IsFixed;
  10570. break;
  10571. case RISCVABI::ABI_ILP32D:
  10572. case RISCVABI::ABI_LP64D:
  10573. UseGPRForF16_F32 = !IsFixed;
  10574. UseGPRForF64 = !IsFixed;
  10575. break;
  10576. }
  10577. // FPR16, FPR32, and FPR64 alias each other.
  10578. if (State.getFirstUnallocated(ArgFPR32s) == std::size(ArgFPR32s)) {
  10579. UseGPRForF16_F32 = true;
  10580. UseGPRForF64 = true;
  10581. }
  10582. // From this point on, rely on UseGPRForF16_F32, UseGPRForF64 and
  10583. // similar local variables rather than directly checking against the target
  10584. // ABI.
  10585. if (UseGPRForF16_F32 && (ValVT == MVT::f16 || ValVT == MVT::f32)) {
  10586. LocVT = XLenVT;
  10587. LocInfo = CCValAssign::BCvt;
  10588. } else if (UseGPRForF64 && XLen == 64 && ValVT == MVT::f64) {
  10589. LocVT = MVT::i64;
  10590. LocInfo = CCValAssign::BCvt;
  10591. }
  10592. // If this is a variadic argument, the RISC-V calling convention requires
  10593. // that it is assigned an 'even' or 'aligned' register if it has 8-byte
  10594. // alignment (RV32) or 16-byte alignment (RV64). An aligned register should
  10595. // be used regardless of whether the original argument was split during
  10596. // legalisation or not. The argument will not be passed by registers if the
  10597. // original type is larger than 2*XLEN, so the register alignment rule does
  10598. // not apply.
  10599. unsigned TwoXLenInBytes = (2 * XLen) / 8;
  10600. if (!IsFixed && ArgFlags.getNonZeroOrigAlign() == TwoXLenInBytes &&
  10601. DL.getTypeAllocSize(OrigTy) == TwoXLenInBytes) {
  10602. unsigned RegIdx = State.getFirstUnallocated(ArgGPRs);
  10603. // Skip 'odd' register if necessary.
  10604. if (RegIdx != std::size(ArgGPRs) && RegIdx % 2 == 1)
  10605. State.AllocateReg(ArgGPRs);
  10606. }
  10607. SmallVectorImpl<CCValAssign> &PendingLocs = State.getPendingLocs();
  10608. SmallVectorImpl<ISD::ArgFlagsTy> &PendingArgFlags =
  10609. State.getPendingArgFlags();
  10610. assert(PendingLocs.size() == PendingArgFlags.size() &&
  10611. "PendingLocs and PendingArgFlags out of sync");
  10612. // Handle passing f64 on RV32D with a soft float ABI or when floating point
  10613. // registers are exhausted.
  10614. if (UseGPRForF64 && XLen == 32 && ValVT == MVT::f64) {
  10615. assert(!ArgFlags.isSplit() && PendingLocs.empty() &&
  10616. "Can't lower f64 if it is split");
  10617. // Depending on available argument GPRS, f64 may be passed in a pair of
  10618. // GPRs, split between a GPR and the stack, or passed completely on the
  10619. // stack. LowerCall/LowerFormalArguments/LowerReturn must recognise these
  10620. // cases.
  10621. Register Reg = State.AllocateReg(ArgGPRs);
  10622. LocVT = MVT::i32;
  10623. if (!Reg) {
  10624. unsigned StackOffset = State.AllocateStack(8, Align(8));
  10625. State.addLoc(
  10626. CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
  10627. return false;
  10628. }
  10629. if (!State.AllocateReg(ArgGPRs))
  10630. State.AllocateStack(4, Align(4));
  10631. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
  10632. return false;
  10633. }
  10634. // Fixed-length vectors are located in the corresponding scalable-vector
  10635. // container types.
  10636. if (ValVT.isFixedLengthVector())
  10637. LocVT = TLI.getContainerForFixedLengthVector(LocVT);
  10638. // Split arguments might be passed indirectly, so keep track of the pending
  10639. // values. Split vectors are passed via a mix of registers and indirectly, so
  10640. // treat them as we would any other argument.
  10641. if (ValVT.isScalarInteger() && (ArgFlags.isSplit() || !PendingLocs.empty())) {
  10642. LocVT = XLenVT;
  10643. LocInfo = CCValAssign::Indirect;
  10644. PendingLocs.push_back(
  10645. CCValAssign::getPending(ValNo, ValVT, LocVT, LocInfo));
  10646. PendingArgFlags.push_back(ArgFlags);
  10647. if (!ArgFlags.isSplitEnd()) {
  10648. return false;
  10649. }
  10650. }
  10651. // If the split argument only had two elements, it should be passed directly
  10652. // in registers or on the stack.
  10653. if (ValVT.isScalarInteger() && ArgFlags.isSplitEnd() &&
  10654. PendingLocs.size() <= 2) {
  10655. assert(PendingLocs.size() == 2 && "Unexpected PendingLocs.size()");
  10656. // Apply the normal calling convention rules to the first half of the
  10657. // split argument.
  10658. CCValAssign VA = PendingLocs[0];
  10659. ISD::ArgFlagsTy AF = PendingArgFlags[0];
  10660. PendingLocs.clear();
  10661. PendingArgFlags.clear();
  10662. return CC_RISCVAssign2XLen(XLen, State, VA, AF, ValNo, ValVT, LocVT,
  10663. ArgFlags);
  10664. }
  10665. // Allocate to a register if possible, or else a stack slot.
  10666. Register Reg;
  10667. unsigned StoreSizeBytes = XLen / 8;
  10668. Align StackAlign = Align(XLen / 8);
  10669. if (ValVT == MVT::f16 && !UseGPRForF16_F32)
  10670. Reg = State.AllocateReg(ArgFPR16s);
  10671. else if (ValVT == MVT::f32 && !UseGPRForF16_F32)
  10672. Reg = State.AllocateReg(ArgFPR32s);
  10673. else if (ValVT == MVT::f64 && !UseGPRForF64)
  10674. Reg = State.AllocateReg(ArgFPR64s);
  10675. else if (ValVT.isVector()) {
  10676. Reg = allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI);
  10677. if (!Reg) {
  10678. // For return values, the vector must be passed fully via registers or
  10679. // via the stack.
  10680. // FIXME: The proposed vector ABI only mandates v8-v15 for return values,
  10681. // but we're using all of them.
  10682. if (IsRet)
  10683. return true;
  10684. // Try using a GPR to pass the address
  10685. if ((Reg = State.AllocateReg(ArgGPRs))) {
  10686. LocVT = XLenVT;
  10687. LocInfo = CCValAssign::Indirect;
  10688. } else if (ValVT.isScalableVector()) {
  10689. LocVT = XLenVT;
  10690. LocInfo = CCValAssign::Indirect;
  10691. } else {
  10692. // Pass fixed-length vectors on the stack.
  10693. LocVT = ValVT;
  10694. StoreSizeBytes = ValVT.getStoreSize();
  10695. // Align vectors to their element sizes, being careful for vXi1
  10696. // vectors.
  10697. StackAlign = MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
  10698. }
  10699. }
  10700. } else {
  10701. Reg = State.AllocateReg(ArgGPRs);
  10702. }
  10703. unsigned StackOffset =
  10704. Reg ? 0 : State.AllocateStack(StoreSizeBytes, StackAlign);
  10705. // If we reach this point and PendingLocs is non-empty, we must be at the
  10706. // end of a split argument that must be passed indirectly.
  10707. if (!PendingLocs.empty()) {
  10708. assert(ArgFlags.isSplitEnd() && "Expected ArgFlags.isSplitEnd()");
  10709. assert(PendingLocs.size() > 2 && "Unexpected PendingLocs.size()");
  10710. for (auto &It : PendingLocs) {
  10711. if (Reg)
  10712. It.convertToReg(Reg);
  10713. else
  10714. It.convertToMem(StackOffset);
  10715. State.addLoc(It);
  10716. }
  10717. PendingLocs.clear();
  10718. PendingArgFlags.clear();
  10719. return false;
  10720. }
  10721. assert((!UseGPRForF16_F32 || !UseGPRForF64 || LocVT == XLenVT ||
  10722. (TLI.getSubtarget().hasVInstructions() && ValVT.isVector())) &&
  10723. "Expected an XLenVT or vector types at this stage");
  10724. if (Reg) {
  10725. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
  10726. return false;
  10727. }
  10728. // When a floating-point value is passed on the stack, no bit-conversion is
  10729. // needed.
  10730. if (ValVT.isFloatingPoint()) {
  10731. LocVT = ValVT;
  10732. LocInfo = CCValAssign::Full;
  10733. }
  10734. State.addLoc(CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
  10735. return false;
  10736. }
  10737. template <typename ArgTy>
  10738. static std::optional<unsigned> preAssignMask(const ArgTy &Args) {
  10739. for (const auto &ArgIdx : enumerate(Args)) {
  10740. MVT ArgVT = ArgIdx.value().VT;
  10741. if (ArgVT.isVector() && ArgVT.getVectorElementType() == MVT::i1)
  10742. return ArgIdx.index();
  10743. }
  10744. return std::nullopt;
  10745. }
  10746. void RISCVTargetLowering::analyzeInputArgs(
  10747. MachineFunction &MF, CCState &CCInfo,
  10748. const SmallVectorImpl<ISD::InputArg> &Ins, bool IsRet,
  10749. RISCVCCAssignFn Fn) const {
  10750. unsigned NumArgs = Ins.size();
  10751. FunctionType *FType = MF.getFunction().getFunctionType();
  10752. std::optional<unsigned> FirstMaskArgument;
  10753. if (Subtarget.hasVInstructions())
  10754. FirstMaskArgument = preAssignMask(Ins);
  10755. for (unsigned i = 0; i != NumArgs; ++i) {
  10756. MVT ArgVT = Ins[i].VT;
  10757. ISD::ArgFlagsTy ArgFlags = Ins[i].Flags;
  10758. Type *ArgTy = nullptr;
  10759. if (IsRet)
  10760. ArgTy = FType->getReturnType();
  10761. else if (Ins[i].isOrigArg())
  10762. ArgTy = FType->getParamType(Ins[i].getOrigArgIndex());
  10763. RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
  10764. if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
  10765. ArgFlags, CCInfo, /*IsFixed=*/true, IsRet, ArgTy, *this,
  10766. FirstMaskArgument)) {
  10767. LLVM_DEBUG(dbgs() << "InputArg #" << i << " has unhandled type "
  10768. << EVT(ArgVT).getEVTString() << '\n');
  10769. llvm_unreachable(nullptr);
  10770. }
  10771. }
  10772. }
  10773. void RISCVTargetLowering::analyzeOutputArgs(
  10774. MachineFunction &MF, CCState &CCInfo,
  10775. const SmallVectorImpl<ISD::OutputArg> &Outs, bool IsRet,
  10776. CallLoweringInfo *CLI, RISCVCCAssignFn Fn) const {
  10777. unsigned NumArgs = Outs.size();
  10778. std::optional<unsigned> FirstMaskArgument;
  10779. if (Subtarget.hasVInstructions())
  10780. FirstMaskArgument = preAssignMask(Outs);
  10781. for (unsigned i = 0; i != NumArgs; i++) {
  10782. MVT ArgVT = Outs[i].VT;
  10783. ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
  10784. Type *OrigTy = CLI ? CLI->getArgs()[Outs[i].OrigArgIndex].Ty : nullptr;
  10785. RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
  10786. if (Fn(MF.getDataLayout(), ABI, i, ArgVT, ArgVT, CCValAssign::Full,
  10787. ArgFlags, CCInfo, Outs[i].IsFixed, IsRet, OrigTy, *this,
  10788. FirstMaskArgument)) {
  10789. LLVM_DEBUG(dbgs() << "OutputArg #" << i << " has unhandled type "
  10790. << EVT(ArgVT).getEVTString() << "\n");
  10791. llvm_unreachable(nullptr);
  10792. }
  10793. }
  10794. }
  10795. // Convert Val to a ValVT. Should not be called for CCValAssign::Indirect
  10796. // values.
  10797. static SDValue convertLocVTToValVT(SelectionDAG &DAG, SDValue Val,
  10798. const CCValAssign &VA, const SDLoc &DL,
  10799. const RISCVSubtarget &Subtarget) {
  10800. switch (VA.getLocInfo()) {
  10801. default:
  10802. llvm_unreachable("Unexpected CCValAssign::LocInfo");
  10803. case CCValAssign::Full:
  10804. if (VA.getValVT().isFixedLengthVector() && VA.getLocVT().isScalableVector())
  10805. Val = convertFromScalableVector(VA.getValVT(), Val, DAG, Subtarget);
  10806. break;
  10807. case CCValAssign::BCvt:
  10808. if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
  10809. Val = DAG.getNode(RISCVISD::FMV_H_X, DL, MVT::f16, Val);
  10810. else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
  10811. Val = DAG.getNode(RISCVISD::FMV_W_X_RV64, DL, MVT::f32, Val);
  10812. else
  10813. Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
  10814. break;
  10815. }
  10816. return Val;
  10817. }
  10818. // The caller is responsible for loading the full value if the argument is
  10819. // passed with CCValAssign::Indirect.
  10820. static SDValue unpackFromRegLoc(SelectionDAG &DAG, SDValue Chain,
  10821. const CCValAssign &VA, const SDLoc &DL,
  10822. const ISD::InputArg &In,
  10823. const RISCVTargetLowering &TLI) {
  10824. MachineFunction &MF = DAG.getMachineFunction();
  10825. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  10826. EVT LocVT = VA.getLocVT();
  10827. SDValue Val;
  10828. const TargetRegisterClass *RC = TLI.getRegClassFor(LocVT.getSimpleVT());
  10829. Register VReg = RegInfo.createVirtualRegister(RC);
  10830. RegInfo.addLiveIn(VA.getLocReg(), VReg);
  10831. Val = DAG.getCopyFromReg(Chain, DL, VReg, LocVT);
  10832. // If input is sign extended from 32 bits, note it for the SExtWRemoval pass.
  10833. if (In.isOrigArg()) {
  10834. Argument *OrigArg = MF.getFunction().getArg(In.getOrigArgIndex());
  10835. if (OrigArg->getType()->isIntegerTy()) {
  10836. unsigned BitWidth = OrigArg->getType()->getIntegerBitWidth();
  10837. // An input zero extended from i31 can also be considered sign extended.
  10838. if ((BitWidth <= 32 && In.Flags.isSExt()) ||
  10839. (BitWidth < 32 && In.Flags.isZExt())) {
  10840. RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
  10841. RVFI->addSExt32Register(VReg);
  10842. }
  10843. }
  10844. }
  10845. if (VA.getLocInfo() == CCValAssign::Indirect)
  10846. return Val;
  10847. return convertLocVTToValVT(DAG, Val, VA, DL, TLI.getSubtarget());
  10848. }
  10849. static SDValue convertValVTToLocVT(SelectionDAG &DAG, SDValue Val,
  10850. const CCValAssign &VA, const SDLoc &DL,
  10851. const RISCVSubtarget &Subtarget) {
  10852. EVT LocVT = VA.getLocVT();
  10853. switch (VA.getLocInfo()) {
  10854. default:
  10855. llvm_unreachable("Unexpected CCValAssign::LocInfo");
  10856. case CCValAssign::Full:
  10857. if (VA.getValVT().isFixedLengthVector() && LocVT.isScalableVector())
  10858. Val = convertToScalableVector(LocVT, Val, DAG, Subtarget);
  10859. break;
  10860. case CCValAssign::BCvt:
  10861. if (VA.getLocVT().isInteger() && VA.getValVT() == MVT::f16)
  10862. Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTH, DL, VA.getLocVT(), Val);
  10863. else if (VA.getLocVT() == MVT::i64 && VA.getValVT() == MVT::f32)
  10864. Val = DAG.getNode(RISCVISD::FMV_X_ANYEXTW_RV64, DL, MVT::i64, Val);
  10865. else
  10866. Val = DAG.getNode(ISD::BITCAST, DL, LocVT, Val);
  10867. break;
  10868. }
  10869. return Val;
  10870. }
  10871. // The caller is responsible for loading the full value if the argument is
  10872. // passed with CCValAssign::Indirect.
  10873. static SDValue unpackFromMemLoc(SelectionDAG &DAG, SDValue Chain,
  10874. const CCValAssign &VA, const SDLoc &DL) {
  10875. MachineFunction &MF = DAG.getMachineFunction();
  10876. MachineFrameInfo &MFI = MF.getFrameInfo();
  10877. EVT LocVT = VA.getLocVT();
  10878. EVT ValVT = VA.getValVT();
  10879. EVT PtrVT = MVT::getIntegerVT(DAG.getDataLayout().getPointerSizeInBits(0));
  10880. if (ValVT.isScalableVector()) {
  10881. // When the value is a scalable vector, we save the pointer which points to
  10882. // the scalable vector value in the stack. The ValVT will be the pointer
  10883. // type, instead of the scalable vector type.
  10884. ValVT = LocVT;
  10885. }
  10886. int FI = MFI.CreateFixedObject(ValVT.getStoreSize(), VA.getLocMemOffset(),
  10887. /*IsImmutable=*/true);
  10888. SDValue FIN = DAG.getFrameIndex(FI, PtrVT);
  10889. SDValue Val;
  10890. ISD::LoadExtType ExtType;
  10891. switch (VA.getLocInfo()) {
  10892. default:
  10893. llvm_unreachable("Unexpected CCValAssign::LocInfo");
  10894. case CCValAssign::Full:
  10895. case CCValAssign::Indirect:
  10896. case CCValAssign::BCvt:
  10897. ExtType = ISD::NON_EXTLOAD;
  10898. break;
  10899. }
  10900. Val = DAG.getExtLoad(
  10901. ExtType, DL, LocVT, Chain, FIN,
  10902. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI), ValVT);
  10903. return Val;
  10904. }
  10905. static SDValue unpackF64OnRV32DSoftABI(SelectionDAG &DAG, SDValue Chain,
  10906. const CCValAssign &VA, const SDLoc &DL) {
  10907. assert(VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64 &&
  10908. "Unexpected VA");
  10909. MachineFunction &MF = DAG.getMachineFunction();
  10910. MachineFrameInfo &MFI = MF.getFrameInfo();
  10911. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  10912. if (VA.isMemLoc()) {
  10913. // f64 is passed on the stack.
  10914. int FI =
  10915. MFI.CreateFixedObject(8, VA.getLocMemOffset(), /*IsImmutable=*/true);
  10916. SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
  10917. return DAG.getLoad(MVT::f64, DL, Chain, FIN,
  10918. MachinePointerInfo::getFixedStack(MF, FI));
  10919. }
  10920. assert(VA.isRegLoc() && "Expected register VA assignment");
  10921. Register LoVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
  10922. RegInfo.addLiveIn(VA.getLocReg(), LoVReg);
  10923. SDValue Lo = DAG.getCopyFromReg(Chain, DL, LoVReg, MVT::i32);
  10924. SDValue Hi;
  10925. if (VA.getLocReg() == RISCV::X17) {
  10926. // Second half of f64 is passed on the stack.
  10927. int FI = MFI.CreateFixedObject(4, 0, /*IsImmutable=*/true);
  10928. SDValue FIN = DAG.getFrameIndex(FI, MVT::i32);
  10929. Hi = DAG.getLoad(MVT::i32, DL, Chain, FIN,
  10930. MachinePointerInfo::getFixedStack(MF, FI));
  10931. } else {
  10932. // Second half of f64 is passed in another GPR.
  10933. Register HiVReg = RegInfo.createVirtualRegister(&RISCV::GPRRegClass);
  10934. RegInfo.addLiveIn(VA.getLocReg() + 1, HiVReg);
  10935. Hi = DAG.getCopyFromReg(Chain, DL, HiVReg, MVT::i32);
  10936. }
  10937. return DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, Lo, Hi);
  10938. }
  10939. // FastCC has less than 1% performance improvement for some particular
  10940. // benchmark. But theoretically, it may has benenfit for some cases.
  10941. static bool CC_RISCV_FastCC(const DataLayout &DL, RISCVABI::ABI ABI,
  10942. unsigned ValNo, MVT ValVT, MVT LocVT,
  10943. CCValAssign::LocInfo LocInfo,
  10944. ISD::ArgFlagsTy ArgFlags, CCState &State,
  10945. bool IsFixed, bool IsRet, Type *OrigTy,
  10946. const RISCVTargetLowering &TLI,
  10947. std::optional<unsigned> FirstMaskArgument) {
  10948. // X5 and X6 might be used for save-restore libcall.
  10949. static const MCPhysReg GPRList[] = {
  10950. RISCV::X10, RISCV::X11, RISCV::X12, RISCV::X13, RISCV::X14,
  10951. RISCV::X15, RISCV::X16, RISCV::X17, RISCV::X7, RISCV::X28,
  10952. RISCV::X29, RISCV::X30, RISCV::X31};
  10953. if (LocVT == MVT::i32 || LocVT == MVT::i64) {
  10954. if (unsigned Reg = State.AllocateReg(GPRList)) {
  10955. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
  10956. return false;
  10957. }
  10958. }
  10959. if (LocVT == MVT::f16) {
  10960. static const MCPhysReg FPR16List[] = {
  10961. RISCV::F10_H, RISCV::F11_H, RISCV::F12_H, RISCV::F13_H, RISCV::F14_H,
  10962. RISCV::F15_H, RISCV::F16_H, RISCV::F17_H, RISCV::F0_H, RISCV::F1_H,
  10963. RISCV::F2_H, RISCV::F3_H, RISCV::F4_H, RISCV::F5_H, RISCV::F6_H,
  10964. RISCV::F7_H, RISCV::F28_H, RISCV::F29_H, RISCV::F30_H, RISCV::F31_H};
  10965. if (unsigned Reg = State.AllocateReg(FPR16List)) {
  10966. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
  10967. return false;
  10968. }
  10969. }
  10970. if (LocVT == MVT::f32) {
  10971. static const MCPhysReg FPR32List[] = {
  10972. RISCV::F10_F, RISCV::F11_F, RISCV::F12_F, RISCV::F13_F, RISCV::F14_F,
  10973. RISCV::F15_F, RISCV::F16_F, RISCV::F17_F, RISCV::F0_F, RISCV::F1_F,
  10974. RISCV::F2_F, RISCV::F3_F, RISCV::F4_F, RISCV::F5_F, RISCV::F6_F,
  10975. RISCV::F7_F, RISCV::F28_F, RISCV::F29_F, RISCV::F30_F, RISCV::F31_F};
  10976. if (unsigned Reg = State.AllocateReg(FPR32List)) {
  10977. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
  10978. return false;
  10979. }
  10980. }
  10981. if (LocVT == MVT::f64) {
  10982. static const MCPhysReg FPR64List[] = {
  10983. RISCV::F10_D, RISCV::F11_D, RISCV::F12_D, RISCV::F13_D, RISCV::F14_D,
  10984. RISCV::F15_D, RISCV::F16_D, RISCV::F17_D, RISCV::F0_D, RISCV::F1_D,
  10985. RISCV::F2_D, RISCV::F3_D, RISCV::F4_D, RISCV::F5_D, RISCV::F6_D,
  10986. RISCV::F7_D, RISCV::F28_D, RISCV::F29_D, RISCV::F30_D, RISCV::F31_D};
  10987. if (unsigned Reg = State.AllocateReg(FPR64List)) {
  10988. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
  10989. return false;
  10990. }
  10991. }
  10992. if (LocVT == MVT::i32 || LocVT == MVT::f32) {
  10993. unsigned Offset4 = State.AllocateStack(4, Align(4));
  10994. State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset4, LocVT, LocInfo));
  10995. return false;
  10996. }
  10997. if (LocVT == MVT::i64 || LocVT == MVT::f64) {
  10998. unsigned Offset5 = State.AllocateStack(8, Align(8));
  10999. State.addLoc(CCValAssign::getMem(ValNo, ValVT, Offset5, LocVT, LocInfo));
  11000. return false;
  11001. }
  11002. if (LocVT.isVector()) {
  11003. if (unsigned Reg =
  11004. allocateRVVReg(ValVT, ValNo, FirstMaskArgument, State, TLI)) {
  11005. // Fixed-length vectors are located in the corresponding scalable-vector
  11006. // container types.
  11007. if (ValVT.isFixedLengthVector())
  11008. LocVT = TLI.getContainerForFixedLengthVector(LocVT);
  11009. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
  11010. } else {
  11011. // Try and pass the address via a "fast" GPR.
  11012. if (unsigned GPRReg = State.AllocateReg(GPRList)) {
  11013. LocInfo = CCValAssign::Indirect;
  11014. LocVT = TLI.getSubtarget().getXLenVT();
  11015. State.addLoc(CCValAssign::getReg(ValNo, ValVT, GPRReg, LocVT, LocInfo));
  11016. } else if (ValVT.isFixedLengthVector()) {
  11017. auto StackAlign =
  11018. MaybeAlign(ValVT.getScalarSizeInBits() / 8).valueOrOne();
  11019. unsigned StackOffset =
  11020. State.AllocateStack(ValVT.getStoreSize(), StackAlign);
  11021. State.addLoc(
  11022. CCValAssign::getMem(ValNo, ValVT, StackOffset, LocVT, LocInfo));
  11023. } else {
  11024. // Can't pass scalable vectors on the stack.
  11025. return true;
  11026. }
  11027. }
  11028. return false;
  11029. }
  11030. return true; // CC didn't match.
  11031. }
  11032. static bool CC_RISCV_GHC(unsigned ValNo, MVT ValVT, MVT LocVT,
  11033. CCValAssign::LocInfo LocInfo,
  11034. ISD::ArgFlagsTy ArgFlags, CCState &State) {
  11035. if (ArgFlags.isNest()) {
  11036. report_fatal_error(
  11037. "Attribute 'nest' is not supported in GHC calling convention");
  11038. }
  11039. if (LocVT == MVT::i32 || LocVT == MVT::i64) {
  11040. // Pass in STG registers: Base, Sp, Hp, R1, R2, R3, R4, R5, R6, R7, SpLim
  11041. // s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11
  11042. static const MCPhysReg GPRList[] = {
  11043. RISCV::X9, RISCV::X18, RISCV::X19, RISCV::X20, RISCV::X21, RISCV::X22,
  11044. RISCV::X23, RISCV::X24, RISCV::X25, RISCV::X26, RISCV::X27};
  11045. if (unsigned Reg = State.AllocateReg(GPRList)) {
  11046. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
  11047. return false;
  11048. }
  11049. }
  11050. if (LocVT == MVT::f32) {
  11051. // Pass in STG registers: F1, ..., F6
  11052. // fs0 ... fs5
  11053. static const MCPhysReg FPR32List[] = {RISCV::F8_F, RISCV::F9_F,
  11054. RISCV::F18_F, RISCV::F19_F,
  11055. RISCV::F20_F, RISCV::F21_F};
  11056. if (unsigned Reg = State.AllocateReg(FPR32List)) {
  11057. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
  11058. return false;
  11059. }
  11060. }
  11061. if (LocVT == MVT::f64) {
  11062. // Pass in STG registers: D1, ..., D6
  11063. // fs6 ... fs11
  11064. static const MCPhysReg FPR64List[] = {RISCV::F22_D, RISCV::F23_D,
  11065. RISCV::F24_D, RISCV::F25_D,
  11066. RISCV::F26_D, RISCV::F27_D};
  11067. if (unsigned Reg = State.AllocateReg(FPR64List)) {
  11068. State.addLoc(CCValAssign::getReg(ValNo, ValVT, Reg, LocVT, LocInfo));
  11069. return false;
  11070. }
  11071. }
  11072. report_fatal_error("No registers left in GHC calling convention");
  11073. return true;
  11074. }
  11075. // Transform physical registers into virtual registers.
  11076. SDValue RISCVTargetLowering::LowerFormalArguments(
  11077. SDValue Chain, CallingConv::ID CallConv, bool IsVarArg,
  11078. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
  11079. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  11080. MachineFunction &MF = DAG.getMachineFunction();
  11081. switch (CallConv) {
  11082. default:
  11083. report_fatal_error("Unsupported calling convention");
  11084. case CallingConv::C:
  11085. case CallingConv::Fast:
  11086. break;
  11087. case CallingConv::GHC:
  11088. if (!MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtF] ||
  11089. !MF.getSubtarget().getFeatureBits()[RISCV::FeatureStdExtD])
  11090. report_fatal_error(
  11091. "GHC calling convention requires the F and D instruction set extensions");
  11092. }
  11093. const Function &Func = MF.getFunction();
  11094. if (Func.hasFnAttribute("interrupt")) {
  11095. if (!Func.arg_empty())
  11096. report_fatal_error(
  11097. "Functions with the interrupt attribute cannot have arguments!");
  11098. StringRef Kind =
  11099. MF.getFunction().getFnAttribute("interrupt").getValueAsString();
  11100. if (!(Kind == "user" || Kind == "supervisor" || Kind == "machine"))
  11101. report_fatal_error(
  11102. "Function interrupt attribute argument not supported!");
  11103. }
  11104. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  11105. MVT XLenVT = Subtarget.getXLenVT();
  11106. unsigned XLenInBytes = Subtarget.getXLen() / 8;
  11107. // Used with vargs to acumulate store chains.
  11108. std::vector<SDValue> OutChains;
  11109. // Assign locations to all of the incoming arguments.
  11110. SmallVector<CCValAssign, 16> ArgLocs;
  11111. CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
  11112. if (CallConv == CallingConv::GHC)
  11113. CCInfo.AnalyzeFormalArguments(Ins, CC_RISCV_GHC);
  11114. else
  11115. analyzeInputArgs(MF, CCInfo, Ins, /*IsRet=*/false,
  11116. CallConv == CallingConv::Fast ? CC_RISCV_FastCC
  11117. : CC_RISCV);
  11118. for (unsigned i = 0, e = ArgLocs.size(); i != e; ++i) {
  11119. CCValAssign &VA = ArgLocs[i];
  11120. SDValue ArgValue;
  11121. // Passing f64 on RV32D with a soft float ABI must be handled as a special
  11122. // case.
  11123. if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64)
  11124. ArgValue = unpackF64OnRV32DSoftABI(DAG, Chain, VA, DL);
  11125. else if (VA.isRegLoc())
  11126. ArgValue = unpackFromRegLoc(DAG, Chain, VA, DL, Ins[i], *this);
  11127. else
  11128. ArgValue = unpackFromMemLoc(DAG, Chain, VA, DL);
  11129. if (VA.getLocInfo() == CCValAssign::Indirect) {
  11130. // If the original argument was split and passed by reference (e.g. i128
  11131. // on RV32), we need to load all parts of it here (using the same
  11132. // address). Vectors may be partly split to registers and partly to the
  11133. // stack, in which case the base address is partly offset and subsequent
  11134. // stores are relative to that.
  11135. InVals.push_back(DAG.getLoad(VA.getValVT(), DL, Chain, ArgValue,
  11136. MachinePointerInfo()));
  11137. unsigned ArgIndex = Ins[i].OrigArgIndex;
  11138. unsigned ArgPartOffset = Ins[i].PartOffset;
  11139. assert(VA.getValVT().isVector() || ArgPartOffset == 0);
  11140. while (i + 1 != e && Ins[i + 1].OrigArgIndex == ArgIndex) {
  11141. CCValAssign &PartVA = ArgLocs[i + 1];
  11142. unsigned PartOffset = Ins[i + 1].PartOffset - ArgPartOffset;
  11143. SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
  11144. if (PartVA.getValVT().isScalableVector())
  11145. Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
  11146. SDValue Address = DAG.getNode(ISD::ADD, DL, PtrVT, ArgValue, Offset);
  11147. InVals.push_back(DAG.getLoad(PartVA.getValVT(), DL, Chain, Address,
  11148. MachinePointerInfo()));
  11149. ++i;
  11150. }
  11151. continue;
  11152. }
  11153. InVals.push_back(ArgValue);
  11154. }
  11155. if (any_of(ArgLocs,
  11156. [](CCValAssign &VA) { return VA.getLocVT().isScalableVector(); }))
  11157. MF.getInfo<RISCVMachineFunctionInfo>()->setIsVectorCall();
  11158. if (IsVarArg) {
  11159. ArrayRef<MCPhysReg> ArgRegs = ArrayRef(ArgGPRs);
  11160. unsigned Idx = CCInfo.getFirstUnallocated(ArgRegs);
  11161. const TargetRegisterClass *RC = &RISCV::GPRRegClass;
  11162. MachineFrameInfo &MFI = MF.getFrameInfo();
  11163. MachineRegisterInfo &RegInfo = MF.getRegInfo();
  11164. RISCVMachineFunctionInfo *RVFI = MF.getInfo<RISCVMachineFunctionInfo>();
  11165. // Offset of the first variable argument from stack pointer, and size of
  11166. // the vararg save area. For now, the varargs save area is either zero or
  11167. // large enough to hold a0-a7.
  11168. int VaArgOffset, VarArgsSaveSize;
  11169. // If all registers are allocated, then all varargs must be passed on the
  11170. // stack and we don't need to save any argregs.
  11171. if (ArgRegs.size() == Idx) {
  11172. VaArgOffset = CCInfo.getNextStackOffset();
  11173. VarArgsSaveSize = 0;
  11174. } else {
  11175. VarArgsSaveSize = XLenInBytes * (ArgRegs.size() - Idx);
  11176. VaArgOffset = -VarArgsSaveSize;
  11177. }
  11178. // Record the frame index of the first variable argument
  11179. // which is a value necessary to VASTART.
  11180. int FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
  11181. RVFI->setVarArgsFrameIndex(FI);
  11182. // If saving an odd number of registers then create an extra stack slot to
  11183. // ensure that the frame pointer is 2*XLEN-aligned, which in turn ensures
  11184. // offsets to even-numbered registered remain 2*XLEN-aligned.
  11185. if (Idx % 2) {
  11186. MFI.CreateFixedObject(XLenInBytes, VaArgOffset - (int)XLenInBytes, true);
  11187. VarArgsSaveSize += XLenInBytes;
  11188. }
  11189. // Copy the integer registers that may have been used for passing varargs
  11190. // to the vararg save area.
  11191. for (unsigned I = Idx; I < ArgRegs.size();
  11192. ++I, VaArgOffset += XLenInBytes) {
  11193. const Register Reg = RegInfo.createVirtualRegister(RC);
  11194. RegInfo.addLiveIn(ArgRegs[I], Reg);
  11195. SDValue ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, XLenVT);
  11196. FI = MFI.CreateFixedObject(XLenInBytes, VaArgOffset, true);
  11197. SDValue PtrOff = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
  11198. SDValue Store = DAG.getStore(Chain, DL, ArgValue, PtrOff,
  11199. MachinePointerInfo::getFixedStack(MF, FI));
  11200. cast<StoreSDNode>(Store.getNode())
  11201. ->getMemOperand()
  11202. ->setValue((Value *)nullptr);
  11203. OutChains.push_back(Store);
  11204. }
  11205. RVFI->setVarArgsSaveSize(VarArgsSaveSize);
  11206. }
  11207. // All stores are grouped in one node to allow the matching between
  11208. // the size of Ins and InVals. This only happens for vararg functions.
  11209. if (!OutChains.empty()) {
  11210. OutChains.push_back(Chain);
  11211. Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, OutChains);
  11212. }
  11213. return Chain;
  11214. }
  11215. /// isEligibleForTailCallOptimization - Check whether the call is eligible
  11216. /// for tail call optimization.
  11217. /// Note: This is modelled after ARM's IsEligibleForTailCallOptimization.
  11218. bool RISCVTargetLowering::isEligibleForTailCallOptimization(
  11219. CCState &CCInfo, CallLoweringInfo &CLI, MachineFunction &MF,
  11220. const SmallVector<CCValAssign, 16> &ArgLocs) const {
  11221. auto &Callee = CLI.Callee;
  11222. auto CalleeCC = CLI.CallConv;
  11223. auto &Outs = CLI.Outs;
  11224. auto &Caller = MF.getFunction();
  11225. auto CallerCC = Caller.getCallingConv();
  11226. // Exception-handling functions need a special set of instructions to
  11227. // indicate a return to the hardware. Tail-calling another function would
  11228. // probably break this.
  11229. // TODO: The "interrupt" attribute isn't currently defined by RISC-V. This
  11230. // should be expanded as new function attributes are introduced.
  11231. if (Caller.hasFnAttribute("interrupt"))
  11232. return false;
  11233. // Do not tail call opt if the stack is used to pass parameters.
  11234. if (CCInfo.getNextStackOffset() != 0)
  11235. return false;
  11236. // Do not tail call opt if any parameters need to be passed indirectly.
  11237. // Since long doubles (fp128) and i128 are larger than 2*XLEN, they are
  11238. // passed indirectly. So the address of the value will be passed in a
  11239. // register, or if not available, then the address is put on the stack. In
  11240. // order to pass indirectly, space on the stack often needs to be allocated
  11241. // in order to store the value. In this case the CCInfo.getNextStackOffset()
  11242. // != 0 check is not enough and we need to check if any CCValAssign ArgsLocs
  11243. // are passed CCValAssign::Indirect.
  11244. for (auto &VA : ArgLocs)
  11245. if (VA.getLocInfo() == CCValAssign::Indirect)
  11246. return false;
  11247. // Do not tail call opt if either caller or callee uses struct return
  11248. // semantics.
  11249. auto IsCallerStructRet = Caller.hasStructRetAttr();
  11250. auto IsCalleeStructRet = Outs.empty() ? false : Outs[0].Flags.isSRet();
  11251. if (IsCallerStructRet || IsCalleeStructRet)
  11252. return false;
  11253. // Externally-defined functions with weak linkage should not be
  11254. // tail-called. The behaviour of branch instructions in this situation (as
  11255. // used for tail calls) is implementation-defined, so we cannot rely on the
  11256. // linker replacing the tail call with a return.
  11257. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
  11258. const GlobalValue *GV = G->getGlobal();
  11259. if (GV->hasExternalWeakLinkage())
  11260. return false;
  11261. }
  11262. // The callee has to preserve all registers the caller needs to preserve.
  11263. const RISCVRegisterInfo *TRI = Subtarget.getRegisterInfo();
  11264. const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
  11265. if (CalleeCC != CallerCC) {
  11266. const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
  11267. if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
  11268. return false;
  11269. }
  11270. // Byval parameters hand the function a pointer directly into the stack area
  11271. // we want to reuse during a tail call. Working around this *is* possible
  11272. // but less efficient and uglier in LowerCall.
  11273. for (auto &Arg : Outs)
  11274. if (Arg.Flags.isByVal())
  11275. return false;
  11276. return true;
  11277. }
  11278. static Align getPrefTypeAlign(EVT VT, SelectionDAG &DAG) {
  11279. return DAG.getDataLayout().getPrefTypeAlign(
  11280. VT.getTypeForEVT(*DAG.getContext()));
  11281. }
  11282. // Lower a call to a callseq_start + CALL + callseq_end chain, and add input
  11283. // and output parameter nodes.
  11284. SDValue RISCVTargetLowering::LowerCall(CallLoweringInfo &CLI,
  11285. SmallVectorImpl<SDValue> &InVals) const {
  11286. SelectionDAG &DAG = CLI.DAG;
  11287. SDLoc &DL = CLI.DL;
  11288. SmallVectorImpl<ISD::OutputArg> &Outs = CLI.Outs;
  11289. SmallVectorImpl<SDValue> &OutVals = CLI.OutVals;
  11290. SmallVectorImpl<ISD::InputArg> &Ins = CLI.Ins;
  11291. SDValue Chain = CLI.Chain;
  11292. SDValue Callee = CLI.Callee;
  11293. bool &IsTailCall = CLI.IsTailCall;
  11294. CallingConv::ID CallConv = CLI.CallConv;
  11295. bool IsVarArg = CLI.IsVarArg;
  11296. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  11297. MVT XLenVT = Subtarget.getXLenVT();
  11298. MachineFunction &MF = DAG.getMachineFunction();
  11299. // Analyze the operands of the call, assigning locations to each operand.
  11300. SmallVector<CCValAssign, 16> ArgLocs;
  11301. CCState ArgCCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
  11302. if (CallConv == CallingConv::GHC)
  11303. ArgCCInfo.AnalyzeCallOperands(Outs, CC_RISCV_GHC);
  11304. else
  11305. analyzeOutputArgs(MF, ArgCCInfo, Outs, /*IsRet=*/false, &CLI,
  11306. CallConv == CallingConv::Fast ? CC_RISCV_FastCC
  11307. : CC_RISCV);
  11308. // Check if it's really possible to do a tail call.
  11309. if (IsTailCall)
  11310. IsTailCall = isEligibleForTailCallOptimization(ArgCCInfo, CLI, MF, ArgLocs);
  11311. if (IsTailCall)
  11312. ++NumTailCalls;
  11313. else if (CLI.CB && CLI.CB->isMustTailCall())
  11314. report_fatal_error("failed to perform tail call elimination on a call "
  11315. "site marked musttail");
  11316. // Get a count of how many bytes are to be pushed on the stack.
  11317. unsigned NumBytes = ArgCCInfo.getNextStackOffset();
  11318. // Create local copies for byval args
  11319. SmallVector<SDValue, 8> ByValArgs;
  11320. for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
  11321. ISD::ArgFlagsTy Flags = Outs[i].Flags;
  11322. if (!Flags.isByVal())
  11323. continue;
  11324. SDValue Arg = OutVals[i];
  11325. unsigned Size = Flags.getByValSize();
  11326. Align Alignment = Flags.getNonZeroByValAlign();
  11327. int FI =
  11328. MF.getFrameInfo().CreateStackObject(Size, Alignment, /*isSS=*/false);
  11329. SDValue FIPtr = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
  11330. SDValue SizeNode = DAG.getConstant(Size, DL, XLenVT);
  11331. Chain = DAG.getMemcpy(Chain, DL, FIPtr, Arg, SizeNode, Alignment,
  11332. /*IsVolatile=*/false,
  11333. /*AlwaysInline=*/false, IsTailCall,
  11334. MachinePointerInfo(), MachinePointerInfo());
  11335. ByValArgs.push_back(FIPtr);
  11336. }
  11337. if (!IsTailCall)
  11338. Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, CLI.DL);
  11339. // Copy argument values to their designated locations.
  11340. SmallVector<std::pair<Register, SDValue>, 8> RegsToPass;
  11341. SmallVector<SDValue, 8> MemOpChains;
  11342. SDValue StackPtr;
  11343. for (unsigned i = 0, j = 0, e = ArgLocs.size(); i != e; ++i) {
  11344. CCValAssign &VA = ArgLocs[i];
  11345. SDValue ArgValue = OutVals[i];
  11346. ISD::ArgFlagsTy Flags = Outs[i].Flags;
  11347. // Handle passing f64 on RV32D with a soft float ABI as a special case.
  11348. bool IsF64OnRV32DSoftABI =
  11349. VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64;
  11350. if (IsF64OnRV32DSoftABI && VA.isRegLoc()) {
  11351. SDValue SplitF64 = DAG.getNode(
  11352. RISCVISD::SplitF64, DL, DAG.getVTList(MVT::i32, MVT::i32), ArgValue);
  11353. SDValue Lo = SplitF64.getValue(0);
  11354. SDValue Hi = SplitF64.getValue(1);
  11355. Register RegLo = VA.getLocReg();
  11356. RegsToPass.push_back(std::make_pair(RegLo, Lo));
  11357. if (RegLo == RISCV::X17) {
  11358. // Second half of f64 is passed on the stack.
  11359. // Work out the address of the stack slot.
  11360. if (!StackPtr.getNode())
  11361. StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
  11362. // Emit the store.
  11363. MemOpChains.push_back(
  11364. DAG.getStore(Chain, DL, Hi, StackPtr, MachinePointerInfo()));
  11365. } else {
  11366. // Second half of f64 is passed in another GPR.
  11367. assert(RegLo < RISCV::X31 && "Invalid register pair");
  11368. Register RegHigh = RegLo + 1;
  11369. RegsToPass.push_back(std::make_pair(RegHigh, Hi));
  11370. }
  11371. continue;
  11372. }
  11373. // IsF64OnRV32DSoftABI && VA.isMemLoc() is handled below in the same way
  11374. // as any other MemLoc.
  11375. // Promote the value if needed.
  11376. // For now, only handle fully promoted and indirect arguments.
  11377. if (VA.getLocInfo() == CCValAssign::Indirect) {
  11378. // Store the argument in a stack slot and pass its address.
  11379. Align StackAlign =
  11380. std::max(getPrefTypeAlign(Outs[i].ArgVT, DAG),
  11381. getPrefTypeAlign(ArgValue.getValueType(), DAG));
  11382. TypeSize StoredSize = ArgValue.getValueType().getStoreSize();
  11383. // If the original argument was split (e.g. i128), we need
  11384. // to store the required parts of it here (and pass just one address).
  11385. // Vectors may be partly split to registers and partly to the stack, in
  11386. // which case the base address is partly offset and subsequent stores are
  11387. // relative to that.
  11388. unsigned ArgIndex = Outs[i].OrigArgIndex;
  11389. unsigned ArgPartOffset = Outs[i].PartOffset;
  11390. assert(VA.getValVT().isVector() || ArgPartOffset == 0);
  11391. // Calculate the total size to store. We don't have access to what we're
  11392. // actually storing other than performing the loop and collecting the
  11393. // info.
  11394. SmallVector<std::pair<SDValue, SDValue>> Parts;
  11395. while (i + 1 != e && Outs[i + 1].OrigArgIndex == ArgIndex) {
  11396. SDValue PartValue = OutVals[i + 1];
  11397. unsigned PartOffset = Outs[i + 1].PartOffset - ArgPartOffset;
  11398. SDValue Offset = DAG.getIntPtrConstant(PartOffset, DL);
  11399. EVT PartVT = PartValue.getValueType();
  11400. if (PartVT.isScalableVector())
  11401. Offset = DAG.getNode(ISD::VSCALE, DL, XLenVT, Offset);
  11402. StoredSize += PartVT.getStoreSize();
  11403. StackAlign = std::max(StackAlign, getPrefTypeAlign(PartVT, DAG));
  11404. Parts.push_back(std::make_pair(PartValue, Offset));
  11405. ++i;
  11406. }
  11407. SDValue SpillSlot = DAG.CreateStackTemporary(StoredSize, StackAlign);
  11408. int FI = cast<FrameIndexSDNode>(SpillSlot)->getIndex();
  11409. MemOpChains.push_back(
  11410. DAG.getStore(Chain, DL, ArgValue, SpillSlot,
  11411. MachinePointerInfo::getFixedStack(MF, FI)));
  11412. for (const auto &Part : Parts) {
  11413. SDValue PartValue = Part.first;
  11414. SDValue PartOffset = Part.second;
  11415. SDValue Address =
  11416. DAG.getNode(ISD::ADD, DL, PtrVT, SpillSlot, PartOffset);
  11417. MemOpChains.push_back(
  11418. DAG.getStore(Chain, DL, PartValue, Address,
  11419. MachinePointerInfo::getFixedStack(MF, FI)));
  11420. }
  11421. ArgValue = SpillSlot;
  11422. } else {
  11423. ArgValue = convertValVTToLocVT(DAG, ArgValue, VA, DL, Subtarget);
  11424. }
  11425. // Use local copy if it is a byval arg.
  11426. if (Flags.isByVal())
  11427. ArgValue = ByValArgs[j++];
  11428. if (VA.isRegLoc()) {
  11429. // Queue up the argument copies and emit them at the end.
  11430. RegsToPass.push_back(std::make_pair(VA.getLocReg(), ArgValue));
  11431. } else {
  11432. assert(VA.isMemLoc() && "Argument not register or memory");
  11433. assert(!IsTailCall && "Tail call not allowed if stack is used "
  11434. "for passing parameters");
  11435. // Work out the address of the stack slot.
  11436. if (!StackPtr.getNode())
  11437. StackPtr = DAG.getCopyFromReg(Chain, DL, RISCV::X2, PtrVT);
  11438. SDValue Address =
  11439. DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr,
  11440. DAG.getIntPtrConstant(VA.getLocMemOffset(), DL));
  11441. // Emit the store.
  11442. MemOpChains.push_back(
  11443. DAG.getStore(Chain, DL, ArgValue, Address, MachinePointerInfo()));
  11444. }
  11445. }
  11446. // Join the stores, which are independent of one another.
  11447. if (!MemOpChains.empty())
  11448. Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
  11449. SDValue Glue;
  11450. // Build a sequence of copy-to-reg nodes, chained and glued together.
  11451. for (auto &Reg : RegsToPass) {
  11452. Chain = DAG.getCopyToReg(Chain, DL, Reg.first, Reg.second, Glue);
  11453. Glue = Chain.getValue(1);
  11454. }
  11455. // Validate that none of the argument registers have been marked as
  11456. // reserved, if so report an error. Do the same for the return address if this
  11457. // is not a tailcall.
  11458. validateCCReservedRegs(RegsToPass, MF);
  11459. if (!IsTailCall &&
  11460. MF.getSubtarget<RISCVSubtarget>().isRegisterReservedByUser(RISCV::X1))
  11461. MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
  11462. MF.getFunction(),
  11463. "Return address register required, but has been reserved."});
  11464. // If the callee is a GlobalAddress/ExternalSymbol node, turn it into a
  11465. // TargetGlobalAddress/TargetExternalSymbol node so that legalize won't
  11466. // split it and then direct call can be matched by PseudoCALL.
  11467. if (GlobalAddressSDNode *S = dyn_cast<GlobalAddressSDNode>(Callee)) {
  11468. const GlobalValue *GV = S->getGlobal();
  11469. unsigned OpFlags = RISCVII::MO_CALL;
  11470. if (!getTargetMachine().shouldAssumeDSOLocal(*GV->getParent(), GV))
  11471. OpFlags = RISCVII::MO_PLT;
  11472. Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
  11473. } else if (ExternalSymbolSDNode *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
  11474. unsigned OpFlags = RISCVII::MO_CALL;
  11475. if (!getTargetMachine().shouldAssumeDSOLocal(*MF.getFunction().getParent(),
  11476. nullptr))
  11477. OpFlags = RISCVII::MO_PLT;
  11478. Callee = DAG.getTargetExternalSymbol(S->getSymbol(), PtrVT, OpFlags);
  11479. }
  11480. // The first call operand is the chain and the second is the target address.
  11481. SmallVector<SDValue, 8> Ops;
  11482. Ops.push_back(Chain);
  11483. Ops.push_back(Callee);
  11484. // Add argument registers to the end of the list so that they are
  11485. // known live into the call.
  11486. for (auto &Reg : RegsToPass)
  11487. Ops.push_back(DAG.getRegister(Reg.first, Reg.second.getValueType()));
  11488. if (!IsTailCall) {
  11489. // Add a register mask operand representing the call-preserved registers.
  11490. const TargetRegisterInfo *TRI = Subtarget.getRegisterInfo();
  11491. const uint32_t *Mask = TRI->getCallPreservedMask(MF, CallConv);
  11492. assert(Mask && "Missing call preserved mask for calling convention");
  11493. Ops.push_back(DAG.getRegisterMask(Mask));
  11494. }
  11495. // Glue the call to the argument copies, if any.
  11496. if (Glue.getNode())
  11497. Ops.push_back(Glue);
  11498. // Emit the call.
  11499. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  11500. if (IsTailCall) {
  11501. MF.getFrameInfo().setHasTailCall();
  11502. return DAG.getNode(RISCVISD::TAIL, DL, NodeTys, Ops);
  11503. }
  11504. Chain = DAG.getNode(RISCVISD::CALL, DL, NodeTys, Ops);
  11505. DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
  11506. Glue = Chain.getValue(1);
  11507. // Mark the end of the call, which is glued to the call itself.
  11508. Chain = DAG.getCALLSEQ_END(Chain, NumBytes, 0, Glue, DL);
  11509. Glue = Chain.getValue(1);
  11510. // Assign locations to each value returned by this call.
  11511. SmallVector<CCValAssign, 16> RVLocs;
  11512. CCState RetCCInfo(CallConv, IsVarArg, MF, RVLocs, *DAG.getContext());
  11513. analyzeInputArgs(MF, RetCCInfo, Ins, /*IsRet=*/true, CC_RISCV);
  11514. // Copy all of the result registers out of their specified physreg.
  11515. for (auto &VA : RVLocs) {
  11516. // Copy the value out
  11517. SDValue RetValue =
  11518. DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), Glue);
  11519. // Glue the RetValue to the end of the call sequence
  11520. Chain = RetValue.getValue(1);
  11521. Glue = RetValue.getValue(2);
  11522. if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
  11523. assert(VA.getLocReg() == ArgGPRs[0] && "Unexpected reg assignment");
  11524. SDValue RetValue2 =
  11525. DAG.getCopyFromReg(Chain, DL, ArgGPRs[1], MVT::i32, Glue);
  11526. Chain = RetValue2.getValue(1);
  11527. Glue = RetValue2.getValue(2);
  11528. RetValue = DAG.getNode(RISCVISD::BuildPairF64, DL, MVT::f64, RetValue,
  11529. RetValue2);
  11530. }
  11531. RetValue = convertLocVTToValVT(DAG, RetValue, VA, DL, Subtarget);
  11532. InVals.push_back(RetValue);
  11533. }
  11534. return Chain;
  11535. }
  11536. bool RISCVTargetLowering::CanLowerReturn(
  11537. CallingConv::ID CallConv, MachineFunction &MF, bool IsVarArg,
  11538. const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
  11539. SmallVector<CCValAssign, 16> RVLocs;
  11540. CCState CCInfo(CallConv, IsVarArg, MF, RVLocs, Context);
  11541. std::optional<unsigned> FirstMaskArgument;
  11542. if (Subtarget.hasVInstructions())
  11543. FirstMaskArgument = preAssignMask(Outs);
  11544. for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
  11545. MVT VT = Outs[i].VT;
  11546. ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
  11547. RISCVABI::ABI ABI = MF.getSubtarget<RISCVSubtarget>().getTargetABI();
  11548. if (CC_RISCV(MF.getDataLayout(), ABI, i, VT, VT, CCValAssign::Full,
  11549. ArgFlags, CCInfo, /*IsFixed=*/true, /*IsRet=*/true, nullptr,
  11550. *this, FirstMaskArgument))
  11551. return false;
  11552. }
  11553. return true;
  11554. }
  11555. SDValue
  11556. RISCVTargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
  11557. bool IsVarArg,
  11558. const SmallVectorImpl<ISD::OutputArg> &Outs,
  11559. const SmallVectorImpl<SDValue> &OutVals,
  11560. const SDLoc &DL, SelectionDAG &DAG) const {
  11561. MachineFunction &MF = DAG.getMachineFunction();
  11562. const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
  11563. // Stores the assignment of the return value to a location.
  11564. SmallVector<CCValAssign, 16> RVLocs;
  11565. // Info about the registers and stack slot.
  11566. CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), RVLocs,
  11567. *DAG.getContext());
  11568. analyzeOutputArgs(DAG.getMachineFunction(), CCInfo, Outs, /*IsRet=*/true,
  11569. nullptr, CC_RISCV);
  11570. if (CallConv == CallingConv::GHC && !RVLocs.empty())
  11571. report_fatal_error("GHC functions return void only");
  11572. SDValue Glue;
  11573. SmallVector<SDValue, 4> RetOps(1, Chain);
  11574. // Copy the result values into the output registers.
  11575. for (unsigned i = 0, e = RVLocs.size(); i < e; ++i) {
  11576. SDValue Val = OutVals[i];
  11577. CCValAssign &VA = RVLocs[i];
  11578. assert(VA.isRegLoc() && "Can only return in registers!");
  11579. if (VA.getLocVT() == MVT::i32 && VA.getValVT() == MVT::f64) {
  11580. // Handle returning f64 on RV32D with a soft float ABI.
  11581. assert(VA.isRegLoc() && "Expected return via registers");
  11582. SDValue SplitF64 = DAG.getNode(RISCVISD::SplitF64, DL,
  11583. DAG.getVTList(MVT::i32, MVT::i32), Val);
  11584. SDValue Lo = SplitF64.getValue(0);
  11585. SDValue Hi = SplitF64.getValue(1);
  11586. Register RegLo = VA.getLocReg();
  11587. assert(RegLo < RISCV::X31 && "Invalid register pair");
  11588. Register RegHi = RegLo + 1;
  11589. if (STI.isRegisterReservedByUser(RegLo) ||
  11590. STI.isRegisterReservedByUser(RegHi))
  11591. MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
  11592. MF.getFunction(),
  11593. "Return value register required, but has been reserved."});
  11594. Chain = DAG.getCopyToReg(Chain, DL, RegLo, Lo, Glue);
  11595. Glue = Chain.getValue(1);
  11596. RetOps.push_back(DAG.getRegister(RegLo, MVT::i32));
  11597. Chain = DAG.getCopyToReg(Chain, DL, RegHi, Hi, Glue);
  11598. Glue = Chain.getValue(1);
  11599. RetOps.push_back(DAG.getRegister(RegHi, MVT::i32));
  11600. } else {
  11601. // Handle a 'normal' return.
  11602. Val = convertValVTToLocVT(DAG, Val, VA, DL, Subtarget);
  11603. Chain = DAG.getCopyToReg(Chain, DL, VA.getLocReg(), Val, Glue);
  11604. if (STI.isRegisterReservedByUser(VA.getLocReg()))
  11605. MF.getFunction().getContext().diagnose(DiagnosticInfoUnsupported{
  11606. MF.getFunction(),
  11607. "Return value register required, but has been reserved."});
  11608. // Guarantee that all emitted copies are stuck together.
  11609. Glue = Chain.getValue(1);
  11610. RetOps.push_back(DAG.getRegister(VA.getLocReg(), VA.getLocVT()));
  11611. }
  11612. }
  11613. RetOps[0] = Chain; // Update chain.
  11614. // Add the glue node if we have it.
  11615. if (Glue.getNode()) {
  11616. RetOps.push_back(Glue);
  11617. }
  11618. if (any_of(RVLocs,
  11619. [](CCValAssign &VA) { return VA.getLocVT().isScalableVector(); }))
  11620. MF.getInfo<RISCVMachineFunctionInfo>()->setIsVectorCall();
  11621. unsigned RetOpc = RISCVISD::RET_FLAG;
  11622. // Interrupt service routines use different return instructions.
  11623. const Function &Func = DAG.getMachineFunction().getFunction();
  11624. if (Func.hasFnAttribute("interrupt")) {
  11625. if (!Func.getReturnType()->isVoidTy())
  11626. report_fatal_error(
  11627. "Functions with the interrupt attribute must have void return type!");
  11628. MachineFunction &MF = DAG.getMachineFunction();
  11629. StringRef Kind =
  11630. MF.getFunction().getFnAttribute("interrupt").getValueAsString();
  11631. if (Kind == "user")
  11632. RetOpc = RISCVISD::URET_FLAG;
  11633. else if (Kind == "supervisor")
  11634. RetOpc = RISCVISD::SRET_FLAG;
  11635. else
  11636. RetOpc = RISCVISD::MRET_FLAG;
  11637. }
  11638. return DAG.getNode(RetOpc, DL, MVT::Other, RetOps);
  11639. }
  11640. void RISCVTargetLowering::validateCCReservedRegs(
  11641. const SmallVectorImpl<std::pair<llvm::Register, llvm::SDValue>> &Regs,
  11642. MachineFunction &MF) const {
  11643. const Function &F = MF.getFunction();
  11644. const RISCVSubtarget &STI = MF.getSubtarget<RISCVSubtarget>();
  11645. if (llvm::any_of(Regs, [&STI](auto Reg) {
  11646. return STI.isRegisterReservedByUser(Reg.first);
  11647. }))
  11648. F.getContext().diagnose(DiagnosticInfoUnsupported{
  11649. F, "Argument register required, but has been reserved."});
  11650. }
  11651. // Check if the result of the node is only used as a return value, as
  11652. // otherwise we can't perform a tail-call.
  11653. bool RISCVTargetLowering::isUsedByReturnOnly(SDNode *N, SDValue &Chain) const {
  11654. if (N->getNumValues() != 1)
  11655. return false;
  11656. if (!N->hasNUsesOfValue(1, 0))
  11657. return false;
  11658. SDNode *Copy = *N->use_begin();
  11659. // TODO: Handle additional opcodes in order to support tail-calling libcalls
  11660. // with soft float ABIs.
  11661. if (Copy->getOpcode() != ISD::CopyToReg) {
  11662. return false;
  11663. }
  11664. // If the ISD::CopyToReg has a glue operand, we conservatively assume it
  11665. // isn't safe to perform a tail call.
  11666. if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() == MVT::Glue)
  11667. return false;
  11668. // The copy must be used by a RISCVISD::RET_FLAG, and nothing else.
  11669. bool HasRet = false;
  11670. for (SDNode *Node : Copy->uses()) {
  11671. if (Node->getOpcode() != RISCVISD::RET_FLAG)
  11672. return false;
  11673. HasRet = true;
  11674. }
  11675. if (!HasRet)
  11676. return false;
  11677. Chain = Copy->getOperand(0);
  11678. return true;
  11679. }
  11680. bool RISCVTargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
  11681. return CI->isTailCall();
  11682. }
  11683. const char *RISCVTargetLowering::getTargetNodeName(unsigned Opcode) const {
  11684. #define NODE_NAME_CASE(NODE) \
  11685. case RISCVISD::NODE: \
  11686. return "RISCVISD::" #NODE;
  11687. // clang-format off
  11688. switch ((RISCVISD::NodeType)Opcode) {
  11689. case RISCVISD::FIRST_NUMBER:
  11690. break;
  11691. NODE_NAME_CASE(RET_FLAG)
  11692. NODE_NAME_CASE(URET_FLAG)
  11693. NODE_NAME_CASE(SRET_FLAG)
  11694. NODE_NAME_CASE(MRET_FLAG)
  11695. NODE_NAME_CASE(CALL)
  11696. NODE_NAME_CASE(SELECT_CC)
  11697. NODE_NAME_CASE(BR_CC)
  11698. NODE_NAME_CASE(BuildPairF64)
  11699. NODE_NAME_CASE(SplitF64)
  11700. NODE_NAME_CASE(TAIL)
  11701. NODE_NAME_CASE(ADD_LO)
  11702. NODE_NAME_CASE(HI)
  11703. NODE_NAME_CASE(LLA)
  11704. NODE_NAME_CASE(ADD_TPREL)
  11705. NODE_NAME_CASE(LA)
  11706. NODE_NAME_CASE(LA_TLS_IE)
  11707. NODE_NAME_CASE(LA_TLS_GD)
  11708. NODE_NAME_CASE(MULHSU)
  11709. NODE_NAME_CASE(SLLW)
  11710. NODE_NAME_CASE(SRAW)
  11711. NODE_NAME_CASE(SRLW)
  11712. NODE_NAME_CASE(DIVW)
  11713. NODE_NAME_CASE(DIVUW)
  11714. NODE_NAME_CASE(REMUW)
  11715. NODE_NAME_CASE(ROLW)
  11716. NODE_NAME_CASE(RORW)
  11717. NODE_NAME_CASE(CLZW)
  11718. NODE_NAME_CASE(CTZW)
  11719. NODE_NAME_CASE(ABSW)
  11720. NODE_NAME_CASE(FMV_H_X)
  11721. NODE_NAME_CASE(FMV_X_ANYEXTH)
  11722. NODE_NAME_CASE(FMV_X_SIGNEXTH)
  11723. NODE_NAME_CASE(FMV_W_X_RV64)
  11724. NODE_NAME_CASE(FMV_X_ANYEXTW_RV64)
  11725. NODE_NAME_CASE(FCVT_X)
  11726. NODE_NAME_CASE(FCVT_XU)
  11727. NODE_NAME_CASE(FCVT_W_RV64)
  11728. NODE_NAME_CASE(FCVT_WU_RV64)
  11729. NODE_NAME_CASE(STRICT_FCVT_W_RV64)
  11730. NODE_NAME_CASE(STRICT_FCVT_WU_RV64)
  11731. NODE_NAME_CASE(FROUND)
  11732. NODE_NAME_CASE(READ_CYCLE_WIDE)
  11733. NODE_NAME_CASE(BREV8)
  11734. NODE_NAME_CASE(ORC_B)
  11735. NODE_NAME_CASE(ZIP)
  11736. NODE_NAME_CASE(UNZIP)
  11737. NODE_NAME_CASE(VMV_V_X_VL)
  11738. NODE_NAME_CASE(VFMV_V_F_VL)
  11739. NODE_NAME_CASE(VMV_X_S)
  11740. NODE_NAME_CASE(VMV_S_X_VL)
  11741. NODE_NAME_CASE(VFMV_S_F_VL)
  11742. NODE_NAME_CASE(SPLAT_VECTOR_SPLIT_I64_VL)
  11743. NODE_NAME_CASE(READ_VLENB)
  11744. NODE_NAME_CASE(TRUNCATE_VECTOR_VL)
  11745. NODE_NAME_CASE(VSLIDEUP_VL)
  11746. NODE_NAME_CASE(VSLIDE1UP_VL)
  11747. NODE_NAME_CASE(VSLIDEDOWN_VL)
  11748. NODE_NAME_CASE(VSLIDE1DOWN_VL)
  11749. NODE_NAME_CASE(VID_VL)
  11750. NODE_NAME_CASE(VFNCVT_ROD_VL)
  11751. NODE_NAME_CASE(VECREDUCE_ADD_VL)
  11752. NODE_NAME_CASE(VECREDUCE_UMAX_VL)
  11753. NODE_NAME_CASE(VECREDUCE_SMAX_VL)
  11754. NODE_NAME_CASE(VECREDUCE_UMIN_VL)
  11755. NODE_NAME_CASE(VECREDUCE_SMIN_VL)
  11756. NODE_NAME_CASE(VECREDUCE_AND_VL)
  11757. NODE_NAME_CASE(VECREDUCE_OR_VL)
  11758. NODE_NAME_CASE(VECREDUCE_XOR_VL)
  11759. NODE_NAME_CASE(VECREDUCE_FADD_VL)
  11760. NODE_NAME_CASE(VECREDUCE_SEQ_FADD_VL)
  11761. NODE_NAME_CASE(VECREDUCE_FMIN_VL)
  11762. NODE_NAME_CASE(VECREDUCE_FMAX_VL)
  11763. NODE_NAME_CASE(ADD_VL)
  11764. NODE_NAME_CASE(AND_VL)
  11765. NODE_NAME_CASE(MUL_VL)
  11766. NODE_NAME_CASE(OR_VL)
  11767. NODE_NAME_CASE(SDIV_VL)
  11768. NODE_NAME_CASE(SHL_VL)
  11769. NODE_NAME_CASE(SREM_VL)
  11770. NODE_NAME_CASE(SRA_VL)
  11771. NODE_NAME_CASE(SRL_VL)
  11772. NODE_NAME_CASE(SUB_VL)
  11773. NODE_NAME_CASE(UDIV_VL)
  11774. NODE_NAME_CASE(UREM_VL)
  11775. NODE_NAME_CASE(XOR_VL)
  11776. NODE_NAME_CASE(SADDSAT_VL)
  11777. NODE_NAME_CASE(UADDSAT_VL)
  11778. NODE_NAME_CASE(SSUBSAT_VL)
  11779. NODE_NAME_CASE(USUBSAT_VL)
  11780. NODE_NAME_CASE(FADD_VL)
  11781. NODE_NAME_CASE(FSUB_VL)
  11782. NODE_NAME_CASE(FMUL_VL)
  11783. NODE_NAME_CASE(FDIV_VL)
  11784. NODE_NAME_CASE(FNEG_VL)
  11785. NODE_NAME_CASE(FABS_VL)
  11786. NODE_NAME_CASE(FSQRT_VL)
  11787. NODE_NAME_CASE(VFMADD_VL)
  11788. NODE_NAME_CASE(VFNMADD_VL)
  11789. NODE_NAME_CASE(VFMSUB_VL)
  11790. NODE_NAME_CASE(VFNMSUB_VL)
  11791. NODE_NAME_CASE(FCOPYSIGN_VL)
  11792. NODE_NAME_CASE(SMIN_VL)
  11793. NODE_NAME_CASE(SMAX_VL)
  11794. NODE_NAME_CASE(UMIN_VL)
  11795. NODE_NAME_CASE(UMAX_VL)
  11796. NODE_NAME_CASE(FMINNUM_VL)
  11797. NODE_NAME_CASE(FMAXNUM_VL)
  11798. NODE_NAME_CASE(MULHS_VL)
  11799. NODE_NAME_CASE(MULHU_VL)
  11800. NODE_NAME_CASE(VFCVT_RTZ_X_F_VL)
  11801. NODE_NAME_CASE(VFCVT_RTZ_XU_F_VL)
  11802. NODE_NAME_CASE(VFCVT_RM_X_F_VL)
  11803. NODE_NAME_CASE(VFCVT_RM_XU_F_VL)
  11804. NODE_NAME_CASE(VFCVT_X_F_VL)
  11805. NODE_NAME_CASE(VFCVT_XU_F_VL)
  11806. NODE_NAME_CASE(VFROUND_NOEXCEPT_VL)
  11807. NODE_NAME_CASE(SINT_TO_FP_VL)
  11808. NODE_NAME_CASE(UINT_TO_FP_VL)
  11809. NODE_NAME_CASE(VFCVT_RM_F_XU_VL)
  11810. NODE_NAME_CASE(VFCVT_RM_F_X_VL)
  11811. NODE_NAME_CASE(FP_EXTEND_VL)
  11812. NODE_NAME_CASE(FP_ROUND_VL)
  11813. NODE_NAME_CASE(VWMUL_VL)
  11814. NODE_NAME_CASE(VWMULU_VL)
  11815. NODE_NAME_CASE(VWMULSU_VL)
  11816. NODE_NAME_CASE(VWADD_VL)
  11817. NODE_NAME_CASE(VWADDU_VL)
  11818. NODE_NAME_CASE(VWSUB_VL)
  11819. NODE_NAME_CASE(VWSUBU_VL)
  11820. NODE_NAME_CASE(VWADD_W_VL)
  11821. NODE_NAME_CASE(VWADDU_W_VL)
  11822. NODE_NAME_CASE(VWSUB_W_VL)
  11823. NODE_NAME_CASE(VWSUBU_W_VL)
  11824. NODE_NAME_CASE(VNSRL_VL)
  11825. NODE_NAME_CASE(SETCC_VL)
  11826. NODE_NAME_CASE(VSELECT_VL)
  11827. NODE_NAME_CASE(VP_MERGE_VL)
  11828. NODE_NAME_CASE(VMAND_VL)
  11829. NODE_NAME_CASE(VMOR_VL)
  11830. NODE_NAME_CASE(VMXOR_VL)
  11831. NODE_NAME_CASE(VMCLR_VL)
  11832. NODE_NAME_CASE(VMSET_VL)
  11833. NODE_NAME_CASE(VRGATHER_VX_VL)
  11834. NODE_NAME_CASE(VRGATHER_VV_VL)
  11835. NODE_NAME_CASE(VRGATHEREI16_VV_VL)
  11836. NODE_NAME_CASE(VSEXT_VL)
  11837. NODE_NAME_CASE(VZEXT_VL)
  11838. NODE_NAME_CASE(VCPOP_VL)
  11839. NODE_NAME_CASE(VFIRST_VL)
  11840. NODE_NAME_CASE(READ_CSR)
  11841. NODE_NAME_CASE(WRITE_CSR)
  11842. NODE_NAME_CASE(SWAP_CSR)
  11843. }
  11844. // clang-format on
  11845. return nullptr;
  11846. #undef NODE_NAME_CASE
  11847. }
  11848. /// getConstraintType - Given a constraint letter, return the type of
  11849. /// constraint it is for this target.
  11850. RISCVTargetLowering::ConstraintType
  11851. RISCVTargetLowering::getConstraintType(StringRef Constraint) const {
  11852. if (Constraint.size() == 1) {
  11853. switch (Constraint[0]) {
  11854. default:
  11855. break;
  11856. case 'f':
  11857. return C_RegisterClass;
  11858. case 'I':
  11859. case 'J':
  11860. case 'K':
  11861. return C_Immediate;
  11862. case 'A':
  11863. return C_Memory;
  11864. case 'S': // A symbolic address
  11865. return C_Other;
  11866. }
  11867. } else {
  11868. if (Constraint == "vr" || Constraint == "vm")
  11869. return C_RegisterClass;
  11870. }
  11871. return TargetLowering::getConstraintType(Constraint);
  11872. }
  11873. std::pair<unsigned, const TargetRegisterClass *>
  11874. RISCVTargetLowering::getRegForInlineAsmConstraint(const TargetRegisterInfo *TRI,
  11875. StringRef Constraint,
  11876. MVT VT) const {
  11877. // First, see if this is a constraint that directly corresponds to a
  11878. // RISCV register class.
  11879. if (Constraint.size() == 1) {
  11880. switch (Constraint[0]) {
  11881. case 'r':
  11882. // TODO: Support fixed vectors up to XLen for P extension?
  11883. if (VT.isVector())
  11884. break;
  11885. return std::make_pair(0U, &RISCV::GPRRegClass);
  11886. case 'f':
  11887. if (Subtarget.hasStdExtZfhOrZfhmin() && VT == MVT::f16)
  11888. return std::make_pair(0U, &RISCV::FPR16RegClass);
  11889. if (Subtarget.hasStdExtF() && VT == MVT::f32)
  11890. return std::make_pair(0U, &RISCV::FPR32RegClass);
  11891. if (Subtarget.hasStdExtD() && VT == MVT::f64)
  11892. return std::make_pair(0U, &RISCV::FPR64RegClass);
  11893. break;
  11894. default:
  11895. break;
  11896. }
  11897. } else if (Constraint == "vr") {
  11898. for (const auto *RC : {&RISCV::VRRegClass, &RISCV::VRM2RegClass,
  11899. &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
  11900. if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy))
  11901. return std::make_pair(0U, RC);
  11902. }
  11903. } else if (Constraint == "vm") {
  11904. if (TRI->isTypeLegalForClass(RISCV::VMV0RegClass, VT.SimpleTy))
  11905. return std::make_pair(0U, &RISCV::VMV0RegClass);
  11906. }
  11907. // Clang will correctly decode the usage of register name aliases into their
  11908. // official names. However, other frontends like `rustc` do not. This allows
  11909. // users of these frontends to use the ABI names for registers in LLVM-style
  11910. // register constraints.
  11911. unsigned XRegFromAlias = StringSwitch<unsigned>(Constraint.lower())
  11912. .Case("{zero}", RISCV::X0)
  11913. .Case("{ra}", RISCV::X1)
  11914. .Case("{sp}", RISCV::X2)
  11915. .Case("{gp}", RISCV::X3)
  11916. .Case("{tp}", RISCV::X4)
  11917. .Case("{t0}", RISCV::X5)
  11918. .Case("{t1}", RISCV::X6)
  11919. .Case("{t2}", RISCV::X7)
  11920. .Cases("{s0}", "{fp}", RISCV::X8)
  11921. .Case("{s1}", RISCV::X9)
  11922. .Case("{a0}", RISCV::X10)
  11923. .Case("{a1}", RISCV::X11)
  11924. .Case("{a2}", RISCV::X12)
  11925. .Case("{a3}", RISCV::X13)
  11926. .Case("{a4}", RISCV::X14)
  11927. .Case("{a5}", RISCV::X15)
  11928. .Case("{a6}", RISCV::X16)
  11929. .Case("{a7}", RISCV::X17)
  11930. .Case("{s2}", RISCV::X18)
  11931. .Case("{s3}", RISCV::X19)
  11932. .Case("{s4}", RISCV::X20)
  11933. .Case("{s5}", RISCV::X21)
  11934. .Case("{s6}", RISCV::X22)
  11935. .Case("{s7}", RISCV::X23)
  11936. .Case("{s8}", RISCV::X24)
  11937. .Case("{s9}", RISCV::X25)
  11938. .Case("{s10}", RISCV::X26)
  11939. .Case("{s11}", RISCV::X27)
  11940. .Case("{t3}", RISCV::X28)
  11941. .Case("{t4}", RISCV::X29)
  11942. .Case("{t5}", RISCV::X30)
  11943. .Case("{t6}", RISCV::X31)
  11944. .Default(RISCV::NoRegister);
  11945. if (XRegFromAlias != RISCV::NoRegister)
  11946. return std::make_pair(XRegFromAlias, &RISCV::GPRRegClass);
  11947. // Since TargetLowering::getRegForInlineAsmConstraint uses the name of the
  11948. // TableGen record rather than the AsmName to choose registers for InlineAsm
  11949. // constraints, plus we want to match those names to the widest floating point
  11950. // register type available, manually select floating point registers here.
  11951. //
  11952. // The second case is the ABI name of the register, so that frontends can also
  11953. // use the ABI names in register constraint lists.
  11954. if (Subtarget.hasStdExtF()) {
  11955. unsigned FReg = StringSwitch<unsigned>(Constraint.lower())
  11956. .Cases("{f0}", "{ft0}", RISCV::F0_F)
  11957. .Cases("{f1}", "{ft1}", RISCV::F1_F)
  11958. .Cases("{f2}", "{ft2}", RISCV::F2_F)
  11959. .Cases("{f3}", "{ft3}", RISCV::F3_F)
  11960. .Cases("{f4}", "{ft4}", RISCV::F4_F)
  11961. .Cases("{f5}", "{ft5}", RISCV::F5_F)
  11962. .Cases("{f6}", "{ft6}", RISCV::F6_F)
  11963. .Cases("{f7}", "{ft7}", RISCV::F7_F)
  11964. .Cases("{f8}", "{fs0}", RISCV::F8_F)
  11965. .Cases("{f9}", "{fs1}", RISCV::F9_F)
  11966. .Cases("{f10}", "{fa0}", RISCV::F10_F)
  11967. .Cases("{f11}", "{fa1}", RISCV::F11_F)
  11968. .Cases("{f12}", "{fa2}", RISCV::F12_F)
  11969. .Cases("{f13}", "{fa3}", RISCV::F13_F)
  11970. .Cases("{f14}", "{fa4}", RISCV::F14_F)
  11971. .Cases("{f15}", "{fa5}", RISCV::F15_F)
  11972. .Cases("{f16}", "{fa6}", RISCV::F16_F)
  11973. .Cases("{f17}", "{fa7}", RISCV::F17_F)
  11974. .Cases("{f18}", "{fs2}", RISCV::F18_F)
  11975. .Cases("{f19}", "{fs3}", RISCV::F19_F)
  11976. .Cases("{f20}", "{fs4}", RISCV::F20_F)
  11977. .Cases("{f21}", "{fs5}", RISCV::F21_F)
  11978. .Cases("{f22}", "{fs6}", RISCV::F22_F)
  11979. .Cases("{f23}", "{fs7}", RISCV::F23_F)
  11980. .Cases("{f24}", "{fs8}", RISCV::F24_F)
  11981. .Cases("{f25}", "{fs9}", RISCV::F25_F)
  11982. .Cases("{f26}", "{fs10}", RISCV::F26_F)
  11983. .Cases("{f27}", "{fs11}", RISCV::F27_F)
  11984. .Cases("{f28}", "{ft8}", RISCV::F28_F)
  11985. .Cases("{f29}", "{ft9}", RISCV::F29_F)
  11986. .Cases("{f30}", "{ft10}", RISCV::F30_F)
  11987. .Cases("{f31}", "{ft11}", RISCV::F31_F)
  11988. .Default(RISCV::NoRegister);
  11989. if (FReg != RISCV::NoRegister) {
  11990. assert(RISCV::F0_F <= FReg && FReg <= RISCV::F31_F && "Unknown fp-reg");
  11991. if (Subtarget.hasStdExtD() && (VT == MVT::f64 || VT == MVT::Other)) {
  11992. unsigned RegNo = FReg - RISCV::F0_F;
  11993. unsigned DReg = RISCV::F0_D + RegNo;
  11994. return std::make_pair(DReg, &RISCV::FPR64RegClass);
  11995. }
  11996. if (VT == MVT::f32 || VT == MVT::Other)
  11997. return std::make_pair(FReg, &RISCV::FPR32RegClass);
  11998. if (Subtarget.hasStdExtZfhOrZfhmin() && VT == MVT::f16) {
  11999. unsigned RegNo = FReg - RISCV::F0_F;
  12000. unsigned HReg = RISCV::F0_H + RegNo;
  12001. return std::make_pair(HReg, &RISCV::FPR16RegClass);
  12002. }
  12003. }
  12004. }
  12005. if (Subtarget.hasVInstructions()) {
  12006. Register VReg = StringSwitch<Register>(Constraint.lower())
  12007. .Case("{v0}", RISCV::V0)
  12008. .Case("{v1}", RISCV::V1)
  12009. .Case("{v2}", RISCV::V2)
  12010. .Case("{v3}", RISCV::V3)
  12011. .Case("{v4}", RISCV::V4)
  12012. .Case("{v5}", RISCV::V5)
  12013. .Case("{v6}", RISCV::V6)
  12014. .Case("{v7}", RISCV::V7)
  12015. .Case("{v8}", RISCV::V8)
  12016. .Case("{v9}", RISCV::V9)
  12017. .Case("{v10}", RISCV::V10)
  12018. .Case("{v11}", RISCV::V11)
  12019. .Case("{v12}", RISCV::V12)
  12020. .Case("{v13}", RISCV::V13)
  12021. .Case("{v14}", RISCV::V14)
  12022. .Case("{v15}", RISCV::V15)
  12023. .Case("{v16}", RISCV::V16)
  12024. .Case("{v17}", RISCV::V17)
  12025. .Case("{v18}", RISCV::V18)
  12026. .Case("{v19}", RISCV::V19)
  12027. .Case("{v20}", RISCV::V20)
  12028. .Case("{v21}", RISCV::V21)
  12029. .Case("{v22}", RISCV::V22)
  12030. .Case("{v23}", RISCV::V23)
  12031. .Case("{v24}", RISCV::V24)
  12032. .Case("{v25}", RISCV::V25)
  12033. .Case("{v26}", RISCV::V26)
  12034. .Case("{v27}", RISCV::V27)
  12035. .Case("{v28}", RISCV::V28)
  12036. .Case("{v29}", RISCV::V29)
  12037. .Case("{v30}", RISCV::V30)
  12038. .Case("{v31}", RISCV::V31)
  12039. .Default(RISCV::NoRegister);
  12040. if (VReg != RISCV::NoRegister) {
  12041. if (TRI->isTypeLegalForClass(RISCV::VMRegClass, VT.SimpleTy))
  12042. return std::make_pair(VReg, &RISCV::VMRegClass);
  12043. if (TRI->isTypeLegalForClass(RISCV::VRRegClass, VT.SimpleTy))
  12044. return std::make_pair(VReg, &RISCV::VRRegClass);
  12045. for (const auto *RC :
  12046. {&RISCV::VRM2RegClass, &RISCV::VRM4RegClass, &RISCV::VRM8RegClass}) {
  12047. if (TRI->isTypeLegalForClass(*RC, VT.SimpleTy)) {
  12048. VReg = TRI->getMatchingSuperReg(VReg, RISCV::sub_vrm1_0, RC);
  12049. return std::make_pair(VReg, RC);
  12050. }
  12051. }
  12052. }
  12053. }
  12054. std::pair<Register, const TargetRegisterClass *> Res =
  12055. TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
  12056. // If we picked one of the Zfinx register classes, remap it to the GPR class.
  12057. // FIXME: When Zfinx is supported in CodeGen this will need to take the
  12058. // Subtarget into account.
  12059. if (Res.second == &RISCV::GPRF16RegClass ||
  12060. Res.second == &RISCV::GPRF32RegClass ||
  12061. Res.second == &RISCV::GPRF64RegClass)
  12062. return std::make_pair(Res.first, &RISCV::GPRRegClass);
  12063. return Res;
  12064. }
  12065. unsigned
  12066. RISCVTargetLowering::getInlineAsmMemConstraint(StringRef ConstraintCode) const {
  12067. // Currently only support length 1 constraints.
  12068. if (ConstraintCode.size() == 1) {
  12069. switch (ConstraintCode[0]) {
  12070. case 'A':
  12071. return InlineAsm::Constraint_A;
  12072. default:
  12073. break;
  12074. }
  12075. }
  12076. return TargetLowering::getInlineAsmMemConstraint(ConstraintCode);
  12077. }
  12078. void RISCVTargetLowering::LowerAsmOperandForConstraint(
  12079. SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
  12080. SelectionDAG &DAG) const {
  12081. // Currently only support length 1 constraints.
  12082. if (Constraint.length() == 1) {
  12083. switch (Constraint[0]) {
  12084. case 'I':
  12085. // Validate & create a 12-bit signed immediate operand.
  12086. if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
  12087. uint64_t CVal = C->getSExtValue();
  12088. if (isInt<12>(CVal))
  12089. Ops.push_back(
  12090. DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
  12091. }
  12092. return;
  12093. case 'J':
  12094. // Validate & create an integer zero operand.
  12095. if (auto *C = dyn_cast<ConstantSDNode>(Op))
  12096. if (C->getZExtValue() == 0)
  12097. Ops.push_back(
  12098. DAG.getTargetConstant(0, SDLoc(Op), Subtarget.getXLenVT()));
  12099. return;
  12100. case 'K':
  12101. // Validate & create a 5-bit unsigned immediate operand.
  12102. if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
  12103. uint64_t CVal = C->getZExtValue();
  12104. if (isUInt<5>(CVal))
  12105. Ops.push_back(
  12106. DAG.getTargetConstant(CVal, SDLoc(Op), Subtarget.getXLenVT()));
  12107. }
  12108. return;
  12109. case 'S':
  12110. if (const auto *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
  12111. Ops.push_back(DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
  12112. GA->getValueType(0)));
  12113. } else if (const auto *BA = dyn_cast<BlockAddressSDNode>(Op)) {
  12114. Ops.push_back(DAG.getTargetBlockAddress(BA->getBlockAddress(),
  12115. BA->getValueType(0)));
  12116. }
  12117. return;
  12118. default:
  12119. break;
  12120. }
  12121. }
  12122. TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
  12123. }
  12124. Instruction *RISCVTargetLowering::emitLeadingFence(IRBuilderBase &Builder,
  12125. Instruction *Inst,
  12126. AtomicOrdering Ord) const {
  12127. if (isa<LoadInst>(Inst) && Ord == AtomicOrdering::SequentiallyConsistent)
  12128. return Builder.CreateFence(Ord);
  12129. if (isa<StoreInst>(Inst) && isReleaseOrStronger(Ord))
  12130. return Builder.CreateFence(AtomicOrdering::Release);
  12131. return nullptr;
  12132. }
  12133. Instruction *RISCVTargetLowering::emitTrailingFence(IRBuilderBase &Builder,
  12134. Instruction *Inst,
  12135. AtomicOrdering Ord) const {
  12136. if (isa<LoadInst>(Inst) && isAcquireOrStronger(Ord))
  12137. return Builder.CreateFence(AtomicOrdering::Acquire);
  12138. return nullptr;
  12139. }
  12140. TargetLowering::AtomicExpansionKind
  12141. RISCVTargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
  12142. // atomicrmw {fadd,fsub} must be expanded to use compare-exchange, as floating
  12143. // point operations can't be used in an lr/sc sequence without breaking the
  12144. // forward-progress guarantee.
  12145. if (AI->isFloatingPointOperation() ||
  12146. AI->getOperation() == AtomicRMWInst::UIncWrap ||
  12147. AI->getOperation() == AtomicRMWInst::UDecWrap)
  12148. return AtomicExpansionKind::CmpXChg;
  12149. // Don't expand forced atomics, we want to have __sync libcalls instead.
  12150. if (Subtarget.hasForcedAtomics())
  12151. return AtomicExpansionKind::None;
  12152. unsigned Size = AI->getType()->getPrimitiveSizeInBits();
  12153. if (Size == 8 || Size == 16)
  12154. return AtomicExpansionKind::MaskedIntrinsic;
  12155. return AtomicExpansionKind::None;
  12156. }
  12157. static Intrinsic::ID
  12158. getIntrinsicForMaskedAtomicRMWBinOp(unsigned XLen, AtomicRMWInst::BinOp BinOp) {
  12159. if (XLen == 32) {
  12160. switch (BinOp) {
  12161. default:
  12162. llvm_unreachable("Unexpected AtomicRMW BinOp");
  12163. case AtomicRMWInst::Xchg:
  12164. return Intrinsic::riscv_masked_atomicrmw_xchg_i32;
  12165. case AtomicRMWInst::Add:
  12166. return Intrinsic::riscv_masked_atomicrmw_add_i32;
  12167. case AtomicRMWInst::Sub:
  12168. return Intrinsic::riscv_masked_atomicrmw_sub_i32;
  12169. case AtomicRMWInst::Nand:
  12170. return Intrinsic::riscv_masked_atomicrmw_nand_i32;
  12171. case AtomicRMWInst::Max:
  12172. return Intrinsic::riscv_masked_atomicrmw_max_i32;
  12173. case AtomicRMWInst::Min:
  12174. return Intrinsic::riscv_masked_atomicrmw_min_i32;
  12175. case AtomicRMWInst::UMax:
  12176. return Intrinsic::riscv_masked_atomicrmw_umax_i32;
  12177. case AtomicRMWInst::UMin:
  12178. return Intrinsic::riscv_masked_atomicrmw_umin_i32;
  12179. }
  12180. }
  12181. if (XLen == 64) {
  12182. switch (BinOp) {
  12183. default:
  12184. llvm_unreachable("Unexpected AtomicRMW BinOp");
  12185. case AtomicRMWInst::Xchg:
  12186. return Intrinsic::riscv_masked_atomicrmw_xchg_i64;
  12187. case AtomicRMWInst::Add:
  12188. return Intrinsic::riscv_masked_atomicrmw_add_i64;
  12189. case AtomicRMWInst::Sub:
  12190. return Intrinsic::riscv_masked_atomicrmw_sub_i64;
  12191. case AtomicRMWInst::Nand:
  12192. return Intrinsic::riscv_masked_atomicrmw_nand_i64;
  12193. case AtomicRMWInst::Max:
  12194. return Intrinsic::riscv_masked_atomicrmw_max_i64;
  12195. case AtomicRMWInst::Min:
  12196. return Intrinsic::riscv_masked_atomicrmw_min_i64;
  12197. case AtomicRMWInst::UMax:
  12198. return Intrinsic::riscv_masked_atomicrmw_umax_i64;
  12199. case AtomicRMWInst::UMin:
  12200. return Intrinsic::riscv_masked_atomicrmw_umin_i64;
  12201. }
  12202. }
  12203. llvm_unreachable("Unexpected XLen\n");
  12204. }
  12205. Value *RISCVTargetLowering::emitMaskedAtomicRMWIntrinsic(
  12206. IRBuilderBase &Builder, AtomicRMWInst *AI, Value *AlignedAddr, Value *Incr,
  12207. Value *Mask, Value *ShiftAmt, AtomicOrdering Ord) const {
  12208. unsigned XLen = Subtarget.getXLen();
  12209. Value *Ordering =
  12210. Builder.getIntN(XLen, static_cast<uint64_t>(AI->getOrdering()));
  12211. Type *Tys[] = {AlignedAddr->getType()};
  12212. Function *LrwOpScwLoop = Intrinsic::getDeclaration(
  12213. AI->getModule(),
  12214. getIntrinsicForMaskedAtomicRMWBinOp(XLen, AI->getOperation()), Tys);
  12215. if (XLen == 64) {
  12216. Incr = Builder.CreateSExt(Incr, Builder.getInt64Ty());
  12217. Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
  12218. ShiftAmt = Builder.CreateSExt(ShiftAmt, Builder.getInt64Ty());
  12219. }
  12220. Value *Result;
  12221. // Must pass the shift amount needed to sign extend the loaded value prior
  12222. // to performing a signed comparison for min/max. ShiftAmt is the number of
  12223. // bits to shift the value into position. Pass XLen-ShiftAmt-ValWidth, which
  12224. // is the number of bits to left+right shift the value in order to
  12225. // sign-extend.
  12226. if (AI->getOperation() == AtomicRMWInst::Min ||
  12227. AI->getOperation() == AtomicRMWInst::Max) {
  12228. const DataLayout &DL = AI->getModule()->getDataLayout();
  12229. unsigned ValWidth =
  12230. DL.getTypeStoreSizeInBits(AI->getValOperand()->getType());
  12231. Value *SextShamt =
  12232. Builder.CreateSub(Builder.getIntN(XLen, XLen - ValWidth), ShiftAmt);
  12233. Result = Builder.CreateCall(LrwOpScwLoop,
  12234. {AlignedAddr, Incr, Mask, SextShamt, Ordering});
  12235. } else {
  12236. Result =
  12237. Builder.CreateCall(LrwOpScwLoop, {AlignedAddr, Incr, Mask, Ordering});
  12238. }
  12239. if (XLen == 64)
  12240. Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
  12241. return Result;
  12242. }
  12243. TargetLowering::AtomicExpansionKind
  12244. RISCVTargetLowering::shouldExpandAtomicCmpXchgInIR(
  12245. AtomicCmpXchgInst *CI) const {
  12246. // Don't expand forced atomics, we want to have __sync libcalls instead.
  12247. if (Subtarget.hasForcedAtomics())
  12248. return AtomicExpansionKind::None;
  12249. unsigned Size = CI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
  12250. if (Size == 8 || Size == 16)
  12251. return AtomicExpansionKind::MaskedIntrinsic;
  12252. return AtomicExpansionKind::None;
  12253. }
  12254. Value *RISCVTargetLowering::emitMaskedAtomicCmpXchgIntrinsic(
  12255. IRBuilderBase &Builder, AtomicCmpXchgInst *CI, Value *AlignedAddr,
  12256. Value *CmpVal, Value *NewVal, Value *Mask, AtomicOrdering Ord) const {
  12257. unsigned XLen = Subtarget.getXLen();
  12258. Value *Ordering = Builder.getIntN(XLen, static_cast<uint64_t>(Ord));
  12259. Intrinsic::ID CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i32;
  12260. if (XLen == 64) {
  12261. CmpVal = Builder.CreateSExt(CmpVal, Builder.getInt64Ty());
  12262. NewVal = Builder.CreateSExt(NewVal, Builder.getInt64Ty());
  12263. Mask = Builder.CreateSExt(Mask, Builder.getInt64Ty());
  12264. CmpXchgIntrID = Intrinsic::riscv_masked_cmpxchg_i64;
  12265. }
  12266. Type *Tys[] = {AlignedAddr->getType()};
  12267. Function *MaskedCmpXchg =
  12268. Intrinsic::getDeclaration(CI->getModule(), CmpXchgIntrID, Tys);
  12269. Value *Result = Builder.CreateCall(
  12270. MaskedCmpXchg, {AlignedAddr, CmpVal, NewVal, Mask, Ordering});
  12271. if (XLen == 64)
  12272. Result = Builder.CreateTrunc(Result, Builder.getInt32Ty());
  12273. return Result;
  12274. }
  12275. bool RISCVTargetLowering::shouldRemoveExtendFromGSIndex(EVT IndexVT,
  12276. EVT DataVT) const {
  12277. return false;
  12278. }
  12279. bool RISCVTargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
  12280. EVT VT) const {
  12281. if (!isOperationLegalOrCustom(Op, VT) || !FPVT.isSimple())
  12282. return false;
  12283. switch (FPVT.getSimpleVT().SimpleTy) {
  12284. case MVT::f16:
  12285. return Subtarget.hasStdExtZfhOrZfhmin();
  12286. case MVT::f32:
  12287. return Subtarget.hasStdExtF();
  12288. case MVT::f64:
  12289. return Subtarget.hasStdExtD();
  12290. default:
  12291. return false;
  12292. }
  12293. }
  12294. unsigned RISCVTargetLowering::getJumpTableEncoding() const {
  12295. // If we are using the small code model, we can reduce size of jump table
  12296. // entry to 4 bytes.
  12297. if (Subtarget.is64Bit() && !isPositionIndependent() &&
  12298. getTargetMachine().getCodeModel() == CodeModel::Small) {
  12299. return MachineJumpTableInfo::EK_Custom32;
  12300. }
  12301. return TargetLowering::getJumpTableEncoding();
  12302. }
  12303. const MCExpr *RISCVTargetLowering::LowerCustomJumpTableEntry(
  12304. const MachineJumpTableInfo *MJTI, const MachineBasicBlock *MBB,
  12305. unsigned uid, MCContext &Ctx) const {
  12306. assert(Subtarget.is64Bit() && !isPositionIndependent() &&
  12307. getTargetMachine().getCodeModel() == CodeModel::Small);
  12308. return MCSymbolRefExpr::create(MBB->getSymbol(), Ctx);
  12309. }
  12310. bool RISCVTargetLowering::isVScaleKnownToBeAPowerOfTwo() const {
  12311. // We define vscale to be VLEN/RVVBitsPerBlock. VLEN is always a power
  12312. // of two >= 64, and RVVBitsPerBlock is 64. Thus, vscale must be
  12313. // a power of two as well.
  12314. // FIXME: This doesn't work for zve32, but that's already broken
  12315. // elsewhere for the same reason.
  12316. assert(Subtarget.getRealMinVLen() >= 64 && "zve32* unsupported");
  12317. static_assert(RISCV::RVVBitsPerBlock == 64,
  12318. "RVVBitsPerBlock changed, audit needed");
  12319. return true;
  12320. }
  12321. bool RISCVTargetLowering::isFMAFasterThanFMulAndFAdd(const MachineFunction &MF,
  12322. EVT VT) const {
  12323. EVT SVT = VT.getScalarType();
  12324. if (!SVT.isSimple())
  12325. return false;
  12326. switch (SVT.getSimpleVT().SimpleTy) {
  12327. case MVT::f16:
  12328. return VT.isVector() ? Subtarget.hasVInstructionsF16()
  12329. : Subtarget.hasStdExtZfh();
  12330. case MVT::f32:
  12331. return Subtarget.hasStdExtF();
  12332. case MVT::f64:
  12333. return Subtarget.hasStdExtD();
  12334. default:
  12335. break;
  12336. }
  12337. return false;
  12338. }
  12339. Register RISCVTargetLowering::getExceptionPointerRegister(
  12340. const Constant *PersonalityFn) const {
  12341. return RISCV::X10;
  12342. }
  12343. Register RISCVTargetLowering::getExceptionSelectorRegister(
  12344. const Constant *PersonalityFn) const {
  12345. return RISCV::X11;
  12346. }
  12347. bool RISCVTargetLowering::shouldExtendTypeInLibCall(EVT Type) const {
  12348. // Return false to suppress the unnecessary extensions if the LibCall
  12349. // arguments or return value is f32 type for LP64 ABI.
  12350. RISCVABI::ABI ABI = Subtarget.getTargetABI();
  12351. if (ABI == RISCVABI::ABI_LP64 && (Type == MVT::f32))
  12352. return false;
  12353. return true;
  12354. }
  12355. bool RISCVTargetLowering::shouldSignExtendTypeInLibCall(EVT Type, bool IsSigned) const {
  12356. if (Subtarget.is64Bit() && Type == MVT::i32)
  12357. return true;
  12358. return IsSigned;
  12359. }
  12360. bool RISCVTargetLowering::decomposeMulByConstant(LLVMContext &Context, EVT VT,
  12361. SDValue C) const {
  12362. // Check integral scalar types.
  12363. const bool HasExtMOrZmmul =
  12364. Subtarget.hasStdExtM() || Subtarget.hasStdExtZmmul();
  12365. if (VT.isScalarInteger()) {
  12366. // Omit the optimization if the sub target has the M extension and the data
  12367. // size exceeds XLen.
  12368. if (HasExtMOrZmmul && VT.getSizeInBits() > Subtarget.getXLen())
  12369. return false;
  12370. if (auto *ConstNode = dyn_cast<ConstantSDNode>(C.getNode())) {
  12371. // Break the MUL to a SLLI and an ADD/SUB.
  12372. const APInt &Imm = ConstNode->getAPIntValue();
  12373. if ((Imm + 1).isPowerOf2() || (Imm - 1).isPowerOf2() ||
  12374. (1 - Imm).isPowerOf2() || (-1 - Imm).isPowerOf2())
  12375. return true;
  12376. // Optimize the MUL to (SH*ADD x, (SLLI x, bits)) if Imm is not simm12.
  12377. if (Subtarget.hasStdExtZba() && !Imm.isSignedIntN(12) &&
  12378. ((Imm - 2).isPowerOf2() || (Imm - 4).isPowerOf2() ||
  12379. (Imm - 8).isPowerOf2()))
  12380. return true;
  12381. // Omit the following optimization if the sub target has the M extension
  12382. // and the data size >= XLen.
  12383. if (HasExtMOrZmmul && VT.getSizeInBits() >= Subtarget.getXLen())
  12384. return false;
  12385. // Break the MUL to two SLLI instructions and an ADD/SUB, if Imm needs
  12386. // a pair of LUI/ADDI.
  12387. if (!Imm.isSignedIntN(12) && Imm.countTrailingZeros() < 12) {
  12388. APInt ImmS = Imm.ashr(Imm.countTrailingZeros());
  12389. if ((ImmS + 1).isPowerOf2() || (ImmS - 1).isPowerOf2() ||
  12390. (1 - ImmS).isPowerOf2())
  12391. return true;
  12392. }
  12393. }
  12394. }
  12395. return false;
  12396. }
  12397. bool RISCVTargetLowering::isMulAddWithConstProfitable(SDValue AddNode,
  12398. SDValue ConstNode) const {
  12399. // Let the DAGCombiner decide for vectors.
  12400. EVT VT = AddNode.getValueType();
  12401. if (VT.isVector())
  12402. return true;
  12403. // Let the DAGCombiner decide for larger types.
  12404. if (VT.getScalarSizeInBits() > Subtarget.getXLen())
  12405. return true;
  12406. // It is worse if c1 is simm12 while c1*c2 is not.
  12407. ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
  12408. ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
  12409. const APInt &C1 = C1Node->getAPIntValue();
  12410. const APInt &C2 = C2Node->getAPIntValue();
  12411. if (C1.isSignedIntN(12) && !(C1 * C2).isSignedIntN(12))
  12412. return false;
  12413. // Default to true and let the DAGCombiner decide.
  12414. return true;
  12415. }
  12416. bool RISCVTargetLowering::allowsMisalignedMemoryAccesses(
  12417. EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
  12418. unsigned *Fast) const {
  12419. if (!VT.isVector()) {
  12420. if (Fast)
  12421. *Fast = 0;
  12422. return Subtarget.enableUnalignedScalarMem();
  12423. }
  12424. // All vector implementations must support element alignment
  12425. EVT ElemVT = VT.getVectorElementType();
  12426. if (Alignment >= ElemVT.getStoreSize()) {
  12427. if (Fast)
  12428. *Fast = 1;
  12429. return true;
  12430. }
  12431. return false;
  12432. }
  12433. bool RISCVTargetLowering::splitValueIntoRegisterParts(
  12434. SelectionDAG &DAG, const SDLoc &DL, SDValue Val, SDValue *Parts,
  12435. unsigned NumParts, MVT PartVT, std::optional<CallingConv::ID> CC) const {
  12436. bool IsABIRegCopy = CC.has_value();
  12437. EVT ValueVT = Val.getValueType();
  12438. if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
  12439. // Cast the f16 to i16, extend to i32, pad with ones to make a float nan,
  12440. // and cast to f32.
  12441. Val = DAG.getNode(ISD::BITCAST, DL, MVT::i16, Val);
  12442. Val = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Val);
  12443. Val = DAG.getNode(ISD::OR, DL, MVT::i32, Val,
  12444. DAG.getConstant(0xFFFF0000, DL, MVT::i32));
  12445. Val = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Val);
  12446. Parts[0] = Val;
  12447. return true;
  12448. }
  12449. if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
  12450. LLVMContext &Context = *DAG.getContext();
  12451. EVT ValueEltVT = ValueVT.getVectorElementType();
  12452. EVT PartEltVT = PartVT.getVectorElementType();
  12453. unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinValue();
  12454. unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinValue();
  12455. if (PartVTBitSize % ValueVTBitSize == 0) {
  12456. assert(PartVTBitSize >= ValueVTBitSize);
  12457. // If the element types are different, bitcast to the same element type of
  12458. // PartVT first.
  12459. // Give an example here, we want copy a <vscale x 1 x i8> value to
  12460. // <vscale x 4 x i16>.
  12461. // We need to convert <vscale x 1 x i8> to <vscale x 8 x i8> by insert
  12462. // subvector, then we can bitcast to <vscale x 4 x i16>.
  12463. if (ValueEltVT != PartEltVT) {
  12464. if (PartVTBitSize > ValueVTBitSize) {
  12465. unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
  12466. assert(Count != 0 && "The number of element should not be zero.");
  12467. EVT SameEltTypeVT =
  12468. EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
  12469. Val = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, SameEltTypeVT,
  12470. DAG.getUNDEF(SameEltTypeVT), Val,
  12471. DAG.getVectorIdxConstant(0, DL));
  12472. }
  12473. Val = DAG.getNode(ISD::BITCAST, DL, PartVT, Val);
  12474. } else {
  12475. Val =
  12476. DAG.getNode(ISD::INSERT_SUBVECTOR, DL, PartVT, DAG.getUNDEF(PartVT),
  12477. Val, DAG.getVectorIdxConstant(0, DL));
  12478. }
  12479. Parts[0] = Val;
  12480. return true;
  12481. }
  12482. }
  12483. return false;
  12484. }
  12485. SDValue RISCVTargetLowering::joinRegisterPartsIntoValue(
  12486. SelectionDAG &DAG, const SDLoc &DL, const SDValue *Parts, unsigned NumParts,
  12487. MVT PartVT, EVT ValueVT, std::optional<CallingConv::ID> CC) const {
  12488. bool IsABIRegCopy = CC.has_value();
  12489. if (IsABIRegCopy && ValueVT == MVT::f16 && PartVT == MVT::f32) {
  12490. SDValue Val = Parts[0];
  12491. // Cast the f32 to i32, truncate to i16, and cast back to f16.
  12492. Val = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Val);
  12493. Val = DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Val);
  12494. Val = DAG.getNode(ISD::BITCAST, DL, MVT::f16, Val);
  12495. return Val;
  12496. }
  12497. if (ValueVT.isScalableVector() && PartVT.isScalableVector()) {
  12498. LLVMContext &Context = *DAG.getContext();
  12499. SDValue Val = Parts[0];
  12500. EVT ValueEltVT = ValueVT.getVectorElementType();
  12501. EVT PartEltVT = PartVT.getVectorElementType();
  12502. unsigned ValueVTBitSize = ValueVT.getSizeInBits().getKnownMinValue();
  12503. unsigned PartVTBitSize = PartVT.getSizeInBits().getKnownMinValue();
  12504. if (PartVTBitSize % ValueVTBitSize == 0) {
  12505. assert(PartVTBitSize >= ValueVTBitSize);
  12506. EVT SameEltTypeVT = ValueVT;
  12507. // If the element types are different, convert it to the same element type
  12508. // of PartVT.
  12509. // Give an example here, we want copy a <vscale x 1 x i8> value from
  12510. // <vscale x 4 x i16>.
  12511. // We need to convert <vscale x 4 x i16> to <vscale x 8 x i8> first,
  12512. // then we can extract <vscale x 1 x i8>.
  12513. if (ValueEltVT != PartEltVT) {
  12514. unsigned Count = PartVTBitSize / ValueEltVT.getFixedSizeInBits();
  12515. assert(Count != 0 && "The number of element should not be zero.");
  12516. SameEltTypeVT =
  12517. EVT::getVectorVT(Context, ValueEltVT, Count, /*IsScalable=*/true);
  12518. Val = DAG.getNode(ISD::BITCAST, DL, SameEltTypeVT, Val);
  12519. }
  12520. Val = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ValueVT, Val,
  12521. DAG.getVectorIdxConstant(0, DL));
  12522. return Val;
  12523. }
  12524. }
  12525. return SDValue();
  12526. }
  12527. bool RISCVTargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
  12528. // When aggressively optimizing for code size, we prefer to use a div
  12529. // instruction, as it is usually smaller than the alternative sequence.
  12530. // TODO: Add vector division?
  12531. bool OptSize = Attr.hasFnAttr(Attribute::MinSize);
  12532. return OptSize && !VT.isVector();
  12533. }
  12534. bool RISCVTargetLowering::preferScalarizeSplat(unsigned Opc) const {
  12535. // Scalarize zero_ext and sign_ext might stop match to widening instruction in
  12536. // some situation.
  12537. if (Opc == ISD::ZERO_EXTEND || Opc == ISD::SIGN_EXTEND)
  12538. return false;
  12539. return true;
  12540. }
  12541. static Value *useTpOffset(IRBuilderBase &IRB, unsigned Offset) {
  12542. Module *M = IRB.GetInsertBlock()->getParent()->getParent();
  12543. Function *ThreadPointerFunc =
  12544. Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
  12545. return IRB.CreatePointerCast(
  12546. IRB.CreateConstGEP1_32(IRB.getInt8Ty(),
  12547. IRB.CreateCall(ThreadPointerFunc), Offset),
  12548. IRB.getInt8PtrTy()->getPointerTo(0));
  12549. }
  12550. Value *RISCVTargetLowering::getIRStackGuard(IRBuilderBase &IRB) const {
  12551. // Fuchsia provides a fixed TLS slot for the stack cookie.
  12552. // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
  12553. if (Subtarget.isTargetFuchsia())
  12554. return useTpOffset(IRB, -0x10);
  12555. return TargetLowering::getIRStackGuard(IRB);
  12556. }
  12557. #define GET_REGISTER_MATCHER
  12558. #include "RISCVGenAsmMatcher.inc"
  12559. Register
  12560. RISCVTargetLowering::getRegisterByName(const char *RegName, LLT VT,
  12561. const MachineFunction &MF) const {
  12562. Register Reg = MatchRegisterAltName(RegName);
  12563. if (Reg == RISCV::NoRegister)
  12564. Reg = MatchRegisterName(RegName);
  12565. if (Reg == RISCV::NoRegister)
  12566. report_fatal_error(
  12567. Twine("Invalid register name \"" + StringRef(RegName) + "\"."));
  12568. BitVector ReservedRegs = Subtarget.getRegisterInfo()->getReservedRegs(MF);
  12569. if (!ReservedRegs.test(Reg) && !Subtarget.isRegisterReservedByUser(Reg))
  12570. report_fatal_error(Twine("Trying to obtain non-reserved register \"" +
  12571. StringRef(RegName) + "\"."));
  12572. return Reg;
  12573. }
  12574. namespace llvm::RISCVVIntrinsicsTable {
  12575. #define GET_RISCVVIntrinsicsTable_IMPL
  12576. #include "RISCVGenSearchableTables.inc"
  12577. } // namespace llvm::RISCVVIntrinsicsTable