AArch64ISelLowering.cpp 766 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042
  1. //===-- AArch64ISelLowering.cpp - AArch64 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 implements the AArch64TargetLowering class.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "AArch64ISelLowering.h"
  13. #include "AArch64CallingConvention.h"
  14. #include "AArch64ExpandImm.h"
  15. #include "AArch64MachineFunctionInfo.h"
  16. #include "AArch64PerfectShuffle.h"
  17. #include "AArch64RegisterInfo.h"
  18. #include "AArch64Subtarget.h"
  19. #include "MCTargetDesc/AArch64AddressingModes.h"
  20. #include "Utils/AArch64BaseInfo.h"
  21. #include "llvm/ADT/APFloat.h"
  22. #include "llvm/ADT/APInt.h"
  23. #include "llvm/ADT/ArrayRef.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/SmallSet.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include "llvm/ADT/Statistic.h"
  28. #include "llvm/ADT/StringRef.h"
  29. #include "llvm/ADT/Triple.h"
  30. #include "llvm/ADT/Twine.h"
  31. #include "llvm/Analysis/MemoryLocation.h"
  32. #include "llvm/Analysis/ObjCARCUtil.h"
  33. #include "llvm/Analysis/VectorUtils.h"
  34. #include "llvm/CodeGen/Analysis.h"
  35. #include "llvm/CodeGen/CallingConvLower.h"
  36. #include "llvm/CodeGen/ISDOpcodes.h"
  37. #include "llvm/CodeGen/MachineBasicBlock.h"
  38. #include "llvm/CodeGen/MachineFrameInfo.h"
  39. #include "llvm/CodeGen/MachineFunction.h"
  40. #include "llvm/CodeGen/MachineInstr.h"
  41. #include "llvm/CodeGen/MachineInstrBuilder.h"
  42. #include "llvm/CodeGen/MachineMemOperand.h"
  43. #include "llvm/CodeGen/MachineRegisterInfo.h"
  44. #include "llvm/CodeGen/RuntimeLibcalls.h"
  45. #include "llvm/CodeGen/SelectionDAG.h"
  46. #include "llvm/CodeGen/SelectionDAGNodes.h"
  47. #include "llvm/CodeGen/TargetCallingConv.h"
  48. #include "llvm/CodeGen/TargetInstrInfo.h"
  49. #include "llvm/CodeGen/ValueTypes.h"
  50. #include "llvm/IR/Attributes.h"
  51. #include "llvm/IR/Constants.h"
  52. #include "llvm/IR/DataLayout.h"
  53. #include "llvm/IR/DebugLoc.h"
  54. #include "llvm/IR/DerivedTypes.h"
  55. #include "llvm/IR/Function.h"
  56. #include "llvm/IR/GetElementPtrTypeIterator.h"
  57. #include "llvm/IR/GlobalValue.h"
  58. #include "llvm/IR/IRBuilder.h"
  59. #include "llvm/IR/Instruction.h"
  60. #include "llvm/IR/Instructions.h"
  61. #include "llvm/IR/IntrinsicInst.h"
  62. #include "llvm/IR/Intrinsics.h"
  63. #include "llvm/IR/IntrinsicsAArch64.h"
  64. #include "llvm/IR/Module.h"
  65. #include "llvm/IR/OperandTraits.h"
  66. #include "llvm/IR/PatternMatch.h"
  67. #include "llvm/IR/Type.h"
  68. #include "llvm/IR/Use.h"
  69. #include "llvm/IR/Value.h"
  70. #include "llvm/MC/MCRegisterInfo.h"
  71. #include "llvm/Support/Casting.h"
  72. #include "llvm/Support/CodeGen.h"
  73. #include "llvm/Support/CommandLine.h"
  74. #include "llvm/Support/Compiler.h"
  75. #include "llvm/Support/Debug.h"
  76. #include "llvm/Support/ErrorHandling.h"
  77. #include "llvm/Support/KnownBits.h"
  78. #include "llvm/Support/MachineValueType.h"
  79. #include "llvm/Support/MathExtras.h"
  80. #include "llvm/Support/raw_ostream.h"
  81. #include "llvm/Target/TargetMachine.h"
  82. #include "llvm/Target/TargetOptions.h"
  83. #include <algorithm>
  84. #include <bitset>
  85. #include <cassert>
  86. #include <cctype>
  87. #include <cstdint>
  88. #include <cstdlib>
  89. #include <iterator>
  90. #include <limits>
  91. #include <tuple>
  92. #include <utility>
  93. #include <vector>
  94. using namespace llvm;
  95. using namespace llvm::PatternMatch;
  96. #define DEBUG_TYPE "aarch64-lower"
  97. STATISTIC(NumTailCalls, "Number of tail calls");
  98. STATISTIC(NumShiftInserts, "Number of vector shift inserts");
  99. STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
  100. // FIXME: The necessary dtprel relocations don't seem to be supported
  101. // well in the GNU bfd and gold linkers at the moment. Therefore, by
  102. // default, for now, fall back to GeneralDynamic code generation.
  103. cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
  104. "aarch64-elf-ldtls-generation", cl::Hidden,
  105. cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
  106. cl::init(false));
  107. static cl::opt<bool>
  108. EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
  109. cl::desc("Enable AArch64 logical imm instruction "
  110. "optimization"),
  111. cl::init(true));
  112. // Temporary option added for the purpose of testing functionality added
  113. // to DAGCombiner.cpp in D92230. It is expected that this can be removed
  114. // in future when both implementations will be based off MGATHER rather
  115. // than the GLD1 nodes added for the SVE gather load intrinsics.
  116. static cl::opt<bool>
  117. EnableCombineMGatherIntrinsics("aarch64-enable-mgather-combine", cl::Hidden,
  118. cl::desc("Combine extends of AArch64 masked "
  119. "gather intrinsics"),
  120. cl::init(true));
  121. /// Value type used for condition codes.
  122. static const MVT MVT_CC = MVT::i32;
  123. static inline EVT getPackedSVEVectorVT(EVT VT) {
  124. switch (VT.getSimpleVT().SimpleTy) {
  125. default:
  126. llvm_unreachable("unexpected element type for vector");
  127. case MVT::i8:
  128. return MVT::nxv16i8;
  129. case MVT::i16:
  130. return MVT::nxv8i16;
  131. case MVT::i32:
  132. return MVT::nxv4i32;
  133. case MVT::i64:
  134. return MVT::nxv2i64;
  135. case MVT::f16:
  136. return MVT::nxv8f16;
  137. case MVT::f32:
  138. return MVT::nxv4f32;
  139. case MVT::f64:
  140. return MVT::nxv2f64;
  141. case MVT::bf16:
  142. return MVT::nxv8bf16;
  143. }
  144. }
  145. // NOTE: Currently there's only a need to return integer vector types. If this
  146. // changes then just add an extra "type" parameter.
  147. static inline EVT getPackedSVEVectorVT(ElementCount EC) {
  148. switch (EC.getKnownMinValue()) {
  149. default:
  150. llvm_unreachable("unexpected element count for vector");
  151. case 16:
  152. return MVT::nxv16i8;
  153. case 8:
  154. return MVT::nxv8i16;
  155. case 4:
  156. return MVT::nxv4i32;
  157. case 2:
  158. return MVT::nxv2i64;
  159. }
  160. }
  161. static inline EVT getPromotedVTForPredicate(EVT VT) {
  162. assert(VT.isScalableVector() && (VT.getVectorElementType() == MVT::i1) &&
  163. "Expected scalable predicate vector type!");
  164. switch (VT.getVectorMinNumElements()) {
  165. default:
  166. llvm_unreachable("unexpected element count for vector");
  167. case 2:
  168. return MVT::nxv2i64;
  169. case 4:
  170. return MVT::nxv4i32;
  171. case 8:
  172. return MVT::nxv8i16;
  173. case 16:
  174. return MVT::nxv16i8;
  175. }
  176. }
  177. /// Returns true if VT's elements occupy the lowest bit positions of its
  178. /// associated register class without any intervening space.
  179. ///
  180. /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the
  181. /// same register class, but only nxv8f16 can be treated as a packed vector.
  182. static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) {
  183. assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
  184. "Expected legal vector type!");
  185. return VT.isFixedLengthVector() ||
  186. VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock;
  187. }
  188. // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading
  189. // predicate and end with a passthru value matching the result type.
  190. static bool isMergePassthruOpcode(unsigned Opc) {
  191. switch (Opc) {
  192. default:
  193. return false;
  194. case AArch64ISD::BITREVERSE_MERGE_PASSTHRU:
  195. case AArch64ISD::BSWAP_MERGE_PASSTHRU:
  196. case AArch64ISD::REVH_MERGE_PASSTHRU:
  197. case AArch64ISD::REVW_MERGE_PASSTHRU:
  198. case AArch64ISD::CTLZ_MERGE_PASSTHRU:
  199. case AArch64ISD::CTPOP_MERGE_PASSTHRU:
  200. case AArch64ISD::DUP_MERGE_PASSTHRU:
  201. case AArch64ISD::ABS_MERGE_PASSTHRU:
  202. case AArch64ISD::NEG_MERGE_PASSTHRU:
  203. case AArch64ISD::FNEG_MERGE_PASSTHRU:
  204. case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU:
  205. case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU:
  206. case AArch64ISD::FCEIL_MERGE_PASSTHRU:
  207. case AArch64ISD::FFLOOR_MERGE_PASSTHRU:
  208. case AArch64ISD::FNEARBYINT_MERGE_PASSTHRU:
  209. case AArch64ISD::FRINT_MERGE_PASSTHRU:
  210. case AArch64ISD::FROUND_MERGE_PASSTHRU:
  211. case AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU:
  212. case AArch64ISD::FTRUNC_MERGE_PASSTHRU:
  213. case AArch64ISD::FP_ROUND_MERGE_PASSTHRU:
  214. case AArch64ISD::FP_EXTEND_MERGE_PASSTHRU:
  215. case AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU:
  216. case AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU:
  217. case AArch64ISD::FCVTZU_MERGE_PASSTHRU:
  218. case AArch64ISD::FCVTZS_MERGE_PASSTHRU:
  219. case AArch64ISD::FSQRT_MERGE_PASSTHRU:
  220. case AArch64ISD::FRECPX_MERGE_PASSTHRU:
  221. case AArch64ISD::FABS_MERGE_PASSTHRU:
  222. return true;
  223. }
  224. }
  225. AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
  226. const AArch64Subtarget &STI)
  227. : TargetLowering(TM), Subtarget(&STI) {
  228. // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
  229. // we have to make something up. Arbitrarily, choose ZeroOrOne.
  230. setBooleanContents(ZeroOrOneBooleanContent);
  231. // When comparing vectors the result sets the different elements in the
  232. // vector to all-one or all-zero.
  233. setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
  234. // Set up the register classes.
  235. addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
  236. addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
  237. if (Subtarget->hasLS64()) {
  238. addRegisterClass(MVT::i64x8, &AArch64::GPR64x8ClassRegClass);
  239. setOperationAction(ISD::LOAD, MVT::i64x8, Custom);
  240. setOperationAction(ISD::STORE, MVT::i64x8, Custom);
  241. }
  242. if (Subtarget->hasFPARMv8()) {
  243. addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
  244. addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
  245. addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
  246. addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
  247. addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
  248. }
  249. if (Subtarget->hasNEON()) {
  250. addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
  251. addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
  252. // Someone set us up the NEON.
  253. addDRTypeForNEON(MVT::v2f32);
  254. addDRTypeForNEON(MVT::v8i8);
  255. addDRTypeForNEON(MVT::v4i16);
  256. addDRTypeForNEON(MVT::v2i32);
  257. addDRTypeForNEON(MVT::v1i64);
  258. addDRTypeForNEON(MVT::v1f64);
  259. addDRTypeForNEON(MVT::v4f16);
  260. if (Subtarget->hasBF16())
  261. addDRTypeForNEON(MVT::v4bf16);
  262. addQRTypeForNEON(MVT::v4f32);
  263. addQRTypeForNEON(MVT::v2f64);
  264. addQRTypeForNEON(MVT::v16i8);
  265. addQRTypeForNEON(MVT::v8i16);
  266. addQRTypeForNEON(MVT::v4i32);
  267. addQRTypeForNEON(MVT::v2i64);
  268. addQRTypeForNEON(MVT::v8f16);
  269. if (Subtarget->hasBF16())
  270. addQRTypeForNEON(MVT::v8bf16);
  271. }
  272. if (Subtarget->hasSVE()) {
  273. // Add legal sve predicate types
  274. addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
  275. addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
  276. addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
  277. addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
  278. // Add legal sve data types
  279. addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
  280. addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
  281. addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
  282. addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
  283. addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
  284. addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
  285. addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
  286. addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
  287. addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
  288. addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
  289. if (Subtarget->hasBF16()) {
  290. addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
  291. addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
  292. addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
  293. }
  294. if (Subtarget->useSVEForFixedLengthVectors()) {
  295. for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
  296. if (useSVEForFixedLengthVectorVT(VT))
  297. addRegisterClass(VT, &AArch64::ZPRRegClass);
  298. for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
  299. if (useSVEForFixedLengthVectorVT(VT))
  300. addRegisterClass(VT, &AArch64::ZPRRegClass);
  301. }
  302. for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
  303. setOperationAction(ISD::SADDSAT, VT, Legal);
  304. setOperationAction(ISD::UADDSAT, VT, Legal);
  305. setOperationAction(ISD::SSUBSAT, VT, Legal);
  306. setOperationAction(ISD::USUBSAT, VT, Legal);
  307. setOperationAction(ISD::UREM, VT, Expand);
  308. setOperationAction(ISD::SREM, VT, Expand);
  309. setOperationAction(ISD::SDIVREM, VT, Expand);
  310. setOperationAction(ISD::UDIVREM, VT, Expand);
  311. }
  312. for (auto VT :
  313. { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
  314. MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
  315. setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
  316. for (auto VT :
  317. { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
  318. MVT::nxv2f64 }) {
  319. setCondCodeAction(ISD::SETO, VT, Expand);
  320. setCondCodeAction(ISD::SETOLT, VT, Expand);
  321. setCondCodeAction(ISD::SETLT, VT, Expand);
  322. setCondCodeAction(ISD::SETOLE, VT, Expand);
  323. setCondCodeAction(ISD::SETLE, VT, Expand);
  324. setCondCodeAction(ISD::SETULT, VT, Expand);
  325. setCondCodeAction(ISD::SETULE, VT, Expand);
  326. setCondCodeAction(ISD::SETUGE, VT, Expand);
  327. setCondCodeAction(ISD::SETUGT, VT, Expand);
  328. setCondCodeAction(ISD::SETUEQ, VT, Expand);
  329. setCondCodeAction(ISD::SETUNE, VT, Expand);
  330. setOperationAction(ISD::FREM, VT, Expand);
  331. setOperationAction(ISD::FPOW, VT, Expand);
  332. setOperationAction(ISD::FPOWI, VT, Expand);
  333. setOperationAction(ISD::FCOS, VT, Expand);
  334. setOperationAction(ISD::FSIN, VT, Expand);
  335. setOperationAction(ISD::FSINCOS, VT, Expand);
  336. setOperationAction(ISD::FEXP, VT, Expand);
  337. setOperationAction(ISD::FEXP2, VT, Expand);
  338. setOperationAction(ISD::FLOG, VT, Expand);
  339. setOperationAction(ISD::FLOG2, VT, Expand);
  340. setOperationAction(ISD::FLOG10, VT, Expand);
  341. }
  342. }
  343. // Compute derived properties from the register classes
  344. computeRegisterProperties(Subtarget->getRegisterInfo());
  345. // Provide all sorts of operation actions
  346. setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
  347. setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
  348. setOperationAction(ISD::SETCC, MVT::i32, Custom);
  349. setOperationAction(ISD::SETCC, MVT::i64, Custom);
  350. setOperationAction(ISD::SETCC, MVT::f16, Custom);
  351. setOperationAction(ISD::SETCC, MVT::f32, Custom);
  352. setOperationAction(ISD::SETCC, MVT::f64, Custom);
  353. setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
  354. setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
  355. setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
  356. setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
  357. setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
  358. setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
  359. setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
  360. setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
  361. setOperationAction(ISD::BRCOND, MVT::Other, Expand);
  362. setOperationAction(ISD::BR_CC, MVT::i32, Custom);
  363. setOperationAction(ISD::BR_CC, MVT::i64, Custom);
  364. setOperationAction(ISD::BR_CC, MVT::f16, Custom);
  365. setOperationAction(ISD::BR_CC, MVT::f32, Custom);
  366. setOperationAction(ISD::BR_CC, MVT::f64, Custom);
  367. setOperationAction(ISD::SELECT, MVT::i32, Custom);
  368. setOperationAction(ISD::SELECT, MVT::i64, Custom);
  369. setOperationAction(ISD::SELECT, MVT::f16, Custom);
  370. setOperationAction(ISD::SELECT, MVT::f32, Custom);
  371. setOperationAction(ISD::SELECT, MVT::f64, Custom);
  372. setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
  373. setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
  374. setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
  375. setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
  376. setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
  377. setOperationAction(ISD::BR_JT, MVT::Other, Custom);
  378. setOperationAction(ISD::JumpTable, MVT::i64, Custom);
  379. setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
  380. setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
  381. setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
  382. setOperationAction(ISD::FREM, MVT::f32, Expand);
  383. setOperationAction(ISD::FREM, MVT::f64, Expand);
  384. setOperationAction(ISD::FREM, MVT::f80, Expand);
  385. setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
  386. // Custom lowering hooks are needed for XOR
  387. // to fold it into CSINC/CSINV.
  388. setOperationAction(ISD::XOR, MVT::i32, Custom);
  389. setOperationAction(ISD::XOR, MVT::i64, Custom);
  390. // Virtually no operation on f128 is legal, but LLVM can't expand them when
  391. // there's a valid register class, so we need custom operations in most cases.
  392. setOperationAction(ISD::FABS, MVT::f128, Expand);
  393. setOperationAction(ISD::FADD, MVT::f128, LibCall);
  394. setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
  395. setOperationAction(ISD::FCOS, MVT::f128, Expand);
  396. setOperationAction(ISD::FDIV, MVT::f128, LibCall);
  397. setOperationAction(ISD::FMA, MVT::f128, Expand);
  398. setOperationAction(ISD::FMUL, MVT::f128, LibCall);
  399. setOperationAction(ISD::FNEG, MVT::f128, Expand);
  400. setOperationAction(ISD::FPOW, MVT::f128, Expand);
  401. setOperationAction(ISD::FREM, MVT::f128, Expand);
  402. setOperationAction(ISD::FRINT, MVT::f128, Expand);
  403. setOperationAction(ISD::FSIN, MVT::f128, Expand);
  404. setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
  405. setOperationAction(ISD::FSQRT, MVT::f128, Expand);
  406. setOperationAction(ISD::FSUB, MVT::f128, LibCall);
  407. setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
  408. setOperationAction(ISD::SETCC, MVT::f128, Custom);
  409. setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
  410. setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
  411. setOperationAction(ISD::BR_CC, MVT::f128, Custom);
  412. setOperationAction(ISD::SELECT, MVT::f128, Custom);
  413. setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
  414. setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
  415. // Lowering for many of the conversions is actually specified by the non-f128
  416. // type. The LowerXXX function will be trivial when f128 isn't involved.
  417. setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
  418. setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
  419. setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
  420. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
  421. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
  422. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
  423. setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
  424. setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
  425. setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
  426. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
  427. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
  428. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
  429. setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
  430. setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
  431. setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
  432. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
  433. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
  434. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
  435. setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
  436. setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
  437. setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
  438. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
  439. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
  440. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
  441. setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
  442. setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
  443. setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
  444. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
  445. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
  446. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
  447. setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i32, Custom);
  448. setOperationAction(ISD::FP_TO_UINT_SAT, MVT::i64, Custom);
  449. setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i32, Custom);
  450. setOperationAction(ISD::FP_TO_SINT_SAT, MVT::i64, Custom);
  451. // Variable arguments.
  452. setOperationAction(ISD::VASTART, MVT::Other, Custom);
  453. setOperationAction(ISD::VAARG, MVT::Other, Custom);
  454. setOperationAction(ISD::VACOPY, MVT::Other, Custom);
  455. setOperationAction(ISD::VAEND, MVT::Other, Expand);
  456. // Variable-sized objects.
  457. setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
  458. setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
  459. if (Subtarget->isTargetWindows())
  460. setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
  461. else
  462. setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
  463. // Constant pool entries
  464. setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
  465. // BlockAddress
  466. setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
  467. // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
  468. setOperationAction(ISD::ADDC, MVT::i32, Custom);
  469. setOperationAction(ISD::ADDE, MVT::i32, Custom);
  470. setOperationAction(ISD::SUBC, MVT::i32, Custom);
  471. setOperationAction(ISD::SUBE, MVT::i32, Custom);
  472. setOperationAction(ISD::ADDC, MVT::i64, Custom);
  473. setOperationAction(ISD::ADDE, MVT::i64, Custom);
  474. setOperationAction(ISD::SUBC, MVT::i64, Custom);
  475. setOperationAction(ISD::SUBE, MVT::i64, Custom);
  476. // AArch64 lacks both left-rotate and popcount instructions.
  477. setOperationAction(ISD::ROTL, MVT::i32, Expand);
  478. setOperationAction(ISD::ROTL, MVT::i64, Expand);
  479. for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
  480. setOperationAction(ISD::ROTL, VT, Expand);
  481. setOperationAction(ISD::ROTR, VT, Expand);
  482. }
  483. // AArch64 doesn't have i32 MULH{S|U}.
  484. setOperationAction(ISD::MULHU, MVT::i32, Expand);
  485. setOperationAction(ISD::MULHS, MVT::i32, Expand);
  486. // AArch64 doesn't have {U|S}MUL_LOHI.
  487. setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
  488. setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
  489. setOperationAction(ISD::CTPOP, MVT::i32, Custom);
  490. setOperationAction(ISD::CTPOP, MVT::i64, Custom);
  491. setOperationAction(ISD::CTPOP, MVT::i128, Custom);
  492. setOperationAction(ISD::ABS, MVT::i32, Custom);
  493. setOperationAction(ISD::ABS, MVT::i64, Custom);
  494. setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
  495. setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
  496. for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
  497. setOperationAction(ISD::SDIVREM, VT, Expand);
  498. setOperationAction(ISD::UDIVREM, VT, Expand);
  499. }
  500. setOperationAction(ISD::SREM, MVT::i32, Expand);
  501. setOperationAction(ISD::SREM, MVT::i64, Expand);
  502. setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
  503. setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
  504. setOperationAction(ISD::UREM, MVT::i32, Expand);
  505. setOperationAction(ISD::UREM, MVT::i64, Expand);
  506. // Custom lower Add/Sub/Mul with overflow.
  507. setOperationAction(ISD::SADDO, MVT::i32, Custom);
  508. setOperationAction(ISD::SADDO, MVT::i64, Custom);
  509. setOperationAction(ISD::UADDO, MVT::i32, Custom);
  510. setOperationAction(ISD::UADDO, MVT::i64, Custom);
  511. setOperationAction(ISD::SSUBO, MVT::i32, Custom);
  512. setOperationAction(ISD::SSUBO, MVT::i64, Custom);
  513. setOperationAction(ISD::USUBO, MVT::i32, Custom);
  514. setOperationAction(ISD::USUBO, MVT::i64, Custom);
  515. setOperationAction(ISD::SMULO, MVT::i32, Custom);
  516. setOperationAction(ISD::SMULO, MVT::i64, Custom);
  517. setOperationAction(ISD::UMULO, MVT::i32, Custom);
  518. setOperationAction(ISD::UMULO, MVT::i64, Custom);
  519. setOperationAction(ISD::FSIN, MVT::f32, Expand);
  520. setOperationAction(ISD::FSIN, MVT::f64, Expand);
  521. setOperationAction(ISD::FCOS, MVT::f32, Expand);
  522. setOperationAction(ISD::FCOS, MVT::f64, Expand);
  523. setOperationAction(ISD::FPOW, MVT::f32, Expand);
  524. setOperationAction(ISD::FPOW, MVT::f64, Expand);
  525. setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
  526. setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
  527. if (Subtarget->hasFullFP16())
  528. setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
  529. else
  530. setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
  531. setOperationAction(ISD::FREM, MVT::f16, Promote);
  532. setOperationAction(ISD::FREM, MVT::v4f16, Expand);
  533. setOperationAction(ISD::FREM, MVT::v8f16, Expand);
  534. setOperationAction(ISD::FPOW, MVT::f16, Promote);
  535. setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
  536. setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
  537. setOperationAction(ISD::FPOWI, MVT::f16, Promote);
  538. setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
  539. setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
  540. setOperationAction(ISD::FCOS, MVT::f16, Promote);
  541. setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
  542. setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
  543. setOperationAction(ISD::FSIN, MVT::f16, Promote);
  544. setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
  545. setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
  546. setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
  547. setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
  548. setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
  549. setOperationAction(ISD::FEXP, MVT::f16, Promote);
  550. setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
  551. setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
  552. setOperationAction(ISD::FEXP2, MVT::f16, Promote);
  553. setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
  554. setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
  555. setOperationAction(ISD::FLOG, MVT::f16, Promote);
  556. setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
  557. setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
  558. setOperationAction(ISD::FLOG2, MVT::f16, Promote);
  559. setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
  560. setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
  561. setOperationAction(ISD::FLOG10, MVT::f16, Promote);
  562. setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
  563. setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
  564. if (!Subtarget->hasFullFP16()) {
  565. setOperationAction(ISD::SELECT, MVT::f16, Promote);
  566. setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
  567. setOperationAction(ISD::SETCC, MVT::f16, Promote);
  568. setOperationAction(ISD::BR_CC, MVT::f16, Promote);
  569. setOperationAction(ISD::FADD, MVT::f16, Promote);
  570. setOperationAction(ISD::FSUB, MVT::f16, Promote);
  571. setOperationAction(ISD::FMUL, MVT::f16, Promote);
  572. setOperationAction(ISD::FDIV, MVT::f16, Promote);
  573. setOperationAction(ISD::FMA, MVT::f16, Promote);
  574. setOperationAction(ISD::FNEG, MVT::f16, Promote);
  575. setOperationAction(ISD::FABS, MVT::f16, Promote);
  576. setOperationAction(ISD::FCEIL, MVT::f16, Promote);
  577. setOperationAction(ISD::FSQRT, MVT::f16, Promote);
  578. setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
  579. setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
  580. setOperationAction(ISD::FRINT, MVT::f16, Promote);
  581. setOperationAction(ISD::FROUND, MVT::f16, Promote);
  582. setOperationAction(ISD::FROUNDEVEN, MVT::f16, Promote);
  583. setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
  584. setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
  585. setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
  586. setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
  587. setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
  588. // promote v4f16 to v4f32 when that is known to be safe.
  589. setOperationAction(ISD::FADD, MVT::v4f16, Promote);
  590. setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
  591. setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
  592. setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
  593. AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
  594. AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
  595. AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
  596. AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
  597. setOperationAction(ISD::FABS, MVT::v4f16, Expand);
  598. setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
  599. setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
  600. setOperationAction(ISD::FROUNDEVEN, MVT::v4f16, Expand);
  601. setOperationAction(ISD::FMA, MVT::v4f16, Expand);
  602. setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
  603. setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
  604. setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
  605. setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
  606. setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
  607. setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
  608. setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
  609. setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
  610. setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
  611. setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
  612. setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
  613. setOperationAction(ISD::FABS, MVT::v8f16, Expand);
  614. setOperationAction(ISD::FADD, MVT::v8f16, Expand);
  615. setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
  616. setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
  617. setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
  618. setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
  619. setOperationAction(ISD::FMA, MVT::v8f16, Expand);
  620. setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
  621. setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
  622. setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
  623. setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
  624. setOperationAction(ISD::FROUNDEVEN, MVT::v8f16, Expand);
  625. setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
  626. setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
  627. setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
  628. setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
  629. setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
  630. setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
  631. setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
  632. setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
  633. setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
  634. }
  635. // AArch64 has implementations of a lot of rounding-like FP operations.
  636. for (MVT Ty : {MVT::f32, MVT::f64}) {
  637. setOperationAction(ISD::FFLOOR, Ty, Legal);
  638. setOperationAction(ISD::FNEARBYINT, Ty, Legal);
  639. setOperationAction(ISD::FCEIL, Ty, Legal);
  640. setOperationAction(ISD::FRINT, Ty, Legal);
  641. setOperationAction(ISD::FTRUNC, Ty, Legal);
  642. setOperationAction(ISD::FROUND, Ty, Legal);
  643. setOperationAction(ISD::FROUNDEVEN, Ty, Legal);
  644. setOperationAction(ISD::FMINNUM, Ty, Legal);
  645. setOperationAction(ISD::FMAXNUM, Ty, Legal);
  646. setOperationAction(ISD::FMINIMUM, Ty, Legal);
  647. setOperationAction(ISD::FMAXIMUM, Ty, Legal);
  648. setOperationAction(ISD::LROUND, Ty, Legal);
  649. setOperationAction(ISD::LLROUND, Ty, Legal);
  650. setOperationAction(ISD::LRINT, Ty, Legal);
  651. setOperationAction(ISD::LLRINT, Ty, Legal);
  652. }
  653. if (Subtarget->hasFullFP16()) {
  654. setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
  655. setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
  656. setOperationAction(ISD::FCEIL, MVT::f16, Legal);
  657. setOperationAction(ISD::FRINT, MVT::f16, Legal);
  658. setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
  659. setOperationAction(ISD::FROUND, MVT::f16, Legal);
  660. setOperationAction(ISD::FROUNDEVEN, MVT::f16, Legal);
  661. setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
  662. setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
  663. setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
  664. setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
  665. }
  666. setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
  667. setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
  668. setOperationAction(ISD::SET_ROUNDING, MVT::Other, Custom);
  669. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
  670. setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
  671. setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
  672. setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
  673. setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
  674. // Generate outline atomics library calls only if LSE was not specified for
  675. // subtarget
  676. if (Subtarget->outlineAtomics() && !Subtarget->hasLSE()) {
  677. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, LibCall);
  678. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, LibCall);
  679. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, LibCall);
  680. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, LibCall);
  681. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, LibCall);
  682. setOperationAction(ISD::ATOMIC_SWAP, MVT::i8, LibCall);
  683. setOperationAction(ISD::ATOMIC_SWAP, MVT::i16, LibCall);
  684. setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, LibCall);
  685. setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, LibCall);
  686. setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i8, LibCall);
  687. setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i16, LibCall);
  688. setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, LibCall);
  689. setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, LibCall);
  690. setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i8, LibCall);
  691. setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i16, LibCall);
  692. setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, LibCall);
  693. setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, LibCall);
  694. setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i8, LibCall);
  695. setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i16, LibCall);
  696. setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i32, LibCall);
  697. setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i64, LibCall);
  698. setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i8, LibCall);
  699. setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i16, LibCall);
  700. setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, LibCall);
  701. setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, LibCall);
  702. #define LCALLNAMES(A, B, N) \
  703. setLibcallName(A##N##_RELAX, #B #N "_relax"); \
  704. setLibcallName(A##N##_ACQ, #B #N "_acq"); \
  705. setLibcallName(A##N##_REL, #B #N "_rel"); \
  706. setLibcallName(A##N##_ACQ_REL, #B #N "_acq_rel");
  707. #define LCALLNAME4(A, B) \
  708. LCALLNAMES(A, B, 1) \
  709. LCALLNAMES(A, B, 2) LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8)
  710. #define LCALLNAME5(A, B) \
  711. LCALLNAMES(A, B, 1) \
  712. LCALLNAMES(A, B, 2) \
  713. LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) LCALLNAMES(A, B, 16)
  714. LCALLNAME5(RTLIB::OUTLINE_ATOMIC_CAS, __aarch64_cas)
  715. LCALLNAME4(RTLIB::OUTLINE_ATOMIC_SWP, __aarch64_swp)
  716. LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDADD, __aarch64_ldadd)
  717. LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDSET, __aarch64_ldset)
  718. LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDCLR, __aarch64_ldclr)
  719. LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDEOR, __aarch64_ldeor)
  720. #undef LCALLNAMES
  721. #undef LCALLNAME4
  722. #undef LCALLNAME5
  723. }
  724. // 128-bit loads and stores can be done without expanding
  725. setOperationAction(ISD::LOAD, MVT::i128, Custom);
  726. setOperationAction(ISD::STORE, MVT::i128, Custom);
  727. // Aligned 128-bit loads and stores are single-copy atomic according to the
  728. // v8.4a spec.
  729. if (Subtarget->hasLSE2()) {
  730. setOperationAction(ISD::ATOMIC_LOAD, MVT::i128, Custom);
  731. setOperationAction(ISD::ATOMIC_STORE, MVT::i128, Custom);
  732. }
  733. // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
  734. // custom lowering, as there are no un-paired non-temporal stores and
  735. // legalization will break up 256 bit inputs.
  736. setOperationAction(ISD::STORE, MVT::v32i8, Custom);
  737. setOperationAction(ISD::STORE, MVT::v16i16, Custom);
  738. setOperationAction(ISD::STORE, MVT::v16f16, Custom);
  739. setOperationAction(ISD::STORE, MVT::v8i32, Custom);
  740. setOperationAction(ISD::STORE, MVT::v8f32, Custom);
  741. setOperationAction(ISD::STORE, MVT::v4f64, Custom);
  742. setOperationAction(ISD::STORE, MVT::v4i64, Custom);
  743. // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
  744. // This requires the Performance Monitors extension.
  745. if (Subtarget->hasPerfMon())
  746. setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
  747. if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
  748. getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
  749. // Issue __sincos_stret if available.
  750. setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
  751. setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
  752. } else {
  753. setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
  754. setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
  755. }
  756. if (Subtarget->getTargetTriple().isOSMSVCRT()) {
  757. // MSVCRT doesn't have powi; fall back to pow
  758. setLibcallName(RTLIB::POWI_F32, nullptr);
  759. setLibcallName(RTLIB::POWI_F64, nullptr);
  760. }
  761. // Make floating-point constants legal for the large code model, so they don't
  762. // become loads from the constant pool.
  763. if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
  764. setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
  765. setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
  766. }
  767. // AArch64 does not have floating-point extending loads, i1 sign-extending
  768. // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
  769. for (MVT VT : MVT::fp_valuetypes()) {
  770. setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
  771. setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
  772. setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
  773. setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
  774. }
  775. for (MVT VT : MVT::integer_valuetypes())
  776. setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
  777. setTruncStoreAction(MVT::f32, MVT::f16, Expand);
  778. setTruncStoreAction(MVT::f64, MVT::f32, Expand);
  779. setTruncStoreAction(MVT::f64, MVT::f16, Expand);
  780. setTruncStoreAction(MVT::f128, MVT::f80, Expand);
  781. setTruncStoreAction(MVT::f128, MVT::f64, Expand);
  782. setTruncStoreAction(MVT::f128, MVT::f32, Expand);
  783. setTruncStoreAction(MVT::f128, MVT::f16, Expand);
  784. setOperationAction(ISD::BITCAST, MVT::i16, Custom);
  785. setOperationAction(ISD::BITCAST, MVT::f16, Custom);
  786. setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
  787. // Indexed loads and stores are supported.
  788. for (unsigned im = (unsigned)ISD::PRE_INC;
  789. im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
  790. setIndexedLoadAction(im, MVT::i8, Legal);
  791. setIndexedLoadAction(im, MVT::i16, Legal);
  792. setIndexedLoadAction(im, MVT::i32, Legal);
  793. setIndexedLoadAction(im, MVT::i64, Legal);
  794. setIndexedLoadAction(im, MVT::f64, Legal);
  795. setIndexedLoadAction(im, MVT::f32, Legal);
  796. setIndexedLoadAction(im, MVT::f16, Legal);
  797. setIndexedLoadAction(im, MVT::bf16, Legal);
  798. setIndexedStoreAction(im, MVT::i8, Legal);
  799. setIndexedStoreAction(im, MVT::i16, Legal);
  800. setIndexedStoreAction(im, MVT::i32, Legal);
  801. setIndexedStoreAction(im, MVT::i64, Legal);
  802. setIndexedStoreAction(im, MVT::f64, Legal);
  803. setIndexedStoreAction(im, MVT::f32, Legal);
  804. setIndexedStoreAction(im, MVT::f16, Legal);
  805. setIndexedStoreAction(im, MVT::bf16, Legal);
  806. }
  807. // Trap.
  808. setOperationAction(ISD::TRAP, MVT::Other, Legal);
  809. setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
  810. setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
  811. // We combine OR nodes for bitfield operations.
  812. setTargetDAGCombine(ISD::OR);
  813. // Try to create BICs for vector ANDs.
  814. setTargetDAGCombine(ISD::AND);
  815. // Vector add and sub nodes may conceal a high-half opportunity.
  816. // Also, try to fold ADD into CSINC/CSINV..
  817. setTargetDAGCombine(ISD::ADD);
  818. setTargetDAGCombine(ISD::ABS);
  819. setTargetDAGCombine(ISD::SUB);
  820. setTargetDAGCombine(ISD::XOR);
  821. setTargetDAGCombine(ISD::SINT_TO_FP);
  822. setTargetDAGCombine(ISD::UINT_TO_FP);
  823. setTargetDAGCombine(ISD::FP_TO_SINT);
  824. setTargetDAGCombine(ISD::FP_TO_UINT);
  825. setTargetDAGCombine(ISD::FP_TO_SINT_SAT);
  826. setTargetDAGCombine(ISD::FP_TO_UINT_SAT);
  827. setTargetDAGCombine(ISD::FDIV);
  828. // Try and combine setcc with csel
  829. setTargetDAGCombine(ISD::SETCC);
  830. setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
  831. setTargetDAGCombine(ISD::ANY_EXTEND);
  832. setTargetDAGCombine(ISD::ZERO_EXTEND);
  833. setTargetDAGCombine(ISD::SIGN_EXTEND);
  834. setTargetDAGCombine(ISD::VECTOR_SPLICE);
  835. setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
  836. setTargetDAGCombine(ISD::TRUNCATE);
  837. setTargetDAGCombine(ISD::CONCAT_VECTORS);
  838. setTargetDAGCombine(ISD::INSERT_SUBVECTOR);
  839. setTargetDAGCombine(ISD::STORE);
  840. if (Subtarget->supportsAddressTopByteIgnored())
  841. setTargetDAGCombine(ISD::LOAD);
  842. setTargetDAGCombine(ISD::MUL);
  843. setTargetDAGCombine(ISD::SELECT);
  844. setTargetDAGCombine(ISD::VSELECT);
  845. setTargetDAGCombine(ISD::INTRINSIC_VOID);
  846. setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
  847. setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
  848. setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
  849. setTargetDAGCombine(ISD::VECREDUCE_ADD);
  850. setTargetDAGCombine(ISD::STEP_VECTOR);
  851. setTargetDAGCombine(ISD::FP_EXTEND);
  852. setTargetDAGCombine(ISD::GlobalAddress);
  853. // In case of strict alignment, avoid an excessive number of byte wide stores.
  854. MaxStoresPerMemsetOptSize = 8;
  855. MaxStoresPerMemset =
  856. Subtarget->requiresStrictAlign() ? MaxStoresPerMemsetOptSize : 32;
  857. MaxGluedStoresPerMemcpy = 4;
  858. MaxStoresPerMemcpyOptSize = 4;
  859. MaxStoresPerMemcpy =
  860. Subtarget->requiresStrictAlign() ? MaxStoresPerMemcpyOptSize : 16;
  861. MaxStoresPerMemmoveOptSize = 4;
  862. MaxStoresPerMemmove = 4;
  863. MaxLoadsPerMemcmpOptSize = 4;
  864. MaxLoadsPerMemcmp =
  865. Subtarget->requiresStrictAlign() ? MaxLoadsPerMemcmpOptSize : 8;
  866. setStackPointerRegisterToSaveRestore(AArch64::SP);
  867. setSchedulingPreference(Sched::Hybrid);
  868. EnableExtLdPromotion = true;
  869. // Set required alignment.
  870. setMinFunctionAlignment(Align(4));
  871. // Set preferred alignments.
  872. setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
  873. setMaxBytesForAlignment(STI.getMaxBytesForLoopAlignment());
  874. setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
  875. // Only change the limit for entries in a jump table if specified by
  876. // the sub target, but not at the command line.
  877. unsigned MaxJT = STI.getMaximumJumpTableSize();
  878. if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
  879. setMaximumJumpTableSize(MaxJT);
  880. setHasExtractBitsInsn(true);
  881. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
  882. if (Subtarget->hasNEON()) {
  883. // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
  884. // silliness like this:
  885. setOperationAction(ISD::FABS, MVT::v1f64, Expand);
  886. setOperationAction(ISD::FADD, MVT::v1f64, Expand);
  887. setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
  888. setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
  889. setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
  890. setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
  891. setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
  892. setOperationAction(ISD::FMA, MVT::v1f64, Expand);
  893. setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
  894. setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
  895. setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
  896. setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
  897. setOperationAction(ISD::FREM, MVT::v1f64, Expand);
  898. setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
  899. setOperationAction(ISD::FROUNDEVEN, MVT::v1f64, Expand);
  900. setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
  901. setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
  902. setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
  903. setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
  904. setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
  905. setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
  906. setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
  907. setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
  908. setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
  909. setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
  910. setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
  911. setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
  912. setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
  913. setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
  914. setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
  915. setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
  916. setOperationAction(ISD::FP_TO_SINT_SAT, MVT::v1i64, Expand);
  917. setOperationAction(ISD::FP_TO_UINT_SAT, MVT::v1i64, Expand);
  918. setOperationAction(ISD::MUL, MVT::v1i64, Expand);
  919. // AArch64 doesn't have a direct vector ->f32 conversion instructions for
  920. // elements smaller than i32, so promote the input to i32 first.
  921. setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
  922. setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
  923. // Similarly, there is no direct i32 -> f64 vector conversion instruction.
  924. setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
  925. setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
  926. setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
  927. setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
  928. // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
  929. // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
  930. setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
  931. setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
  932. if (Subtarget->hasFullFP16()) {
  933. setOperationAction(ISD::SINT_TO_FP, MVT::v8i8, Custom);
  934. setOperationAction(ISD::UINT_TO_FP, MVT::v8i8, Custom);
  935. setOperationAction(ISD::SINT_TO_FP, MVT::v16i8, Custom);
  936. setOperationAction(ISD::UINT_TO_FP, MVT::v16i8, Custom);
  937. setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
  938. setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
  939. setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
  940. setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
  941. } else {
  942. // when AArch64 doesn't have fullfp16 support, promote the input
  943. // to i32 first.
  944. setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
  945. setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
  946. setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v16i8, MVT::v16i32);
  947. setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v16i8, MVT::v16i32);
  948. setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
  949. setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
  950. setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
  951. setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
  952. }
  953. setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
  954. setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
  955. setOperationAction(ISD::BITREVERSE, MVT::v8i8, Legal);
  956. setOperationAction(ISD::BITREVERSE, MVT::v16i8, Legal);
  957. setOperationAction(ISD::BITREVERSE, MVT::v2i32, Custom);
  958. setOperationAction(ISD::BITREVERSE, MVT::v4i32, Custom);
  959. setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom);
  960. setOperationAction(ISD::BITREVERSE, MVT::v2i64, Custom);
  961. for (auto VT : {MVT::v1i64, MVT::v2i64}) {
  962. setOperationAction(ISD::UMAX, VT, Custom);
  963. setOperationAction(ISD::SMAX, VT, Custom);
  964. setOperationAction(ISD::UMIN, VT, Custom);
  965. setOperationAction(ISD::SMIN, VT, Custom);
  966. }
  967. // AArch64 doesn't have MUL.2d:
  968. setOperationAction(ISD::MUL, MVT::v2i64, Expand);
  969. // Custom handling for some quad-vector types to detect MULL.
  970. setOperationAction(ISD::MUL, MVT::v8i16, Custom);
  971. setOperationAction(ISD::MUL, MVT::v4i32, Custom);
  972. setOperationAction(ISD::MUL, MVT::v2i64, Custom);
  973. // Saturates
  974. for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
  975. MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
  976. setOperationAction(ISD::SADDSAT, VT, Legal);
  977. setOperationAction(ISD::UADDSAT, VT, Legal);
  978. setOperationAction(ISD::SSUBSAT, VT, Legal);
  979. setOperationAction(ISD::USUBSAT, VT, Legal);
  980. }
  981. for (MVT VT : {MVT::v8i8, MVT::v4i16, MVT::v2i32, MVT::v16i8, MVT::v8i16,
  982. MVT::v4i32}) {
  983. setOperationAction(ISD::ABDS, VT, Legal);
  984. setOperationAction(ISD::ABDU, VT, Legal);
  985. }
  986. // Vector reductions
  987. for (MVT VT : { MVT::v4f16, MVT::v2f32,
  988. MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
  989. if (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()) {
  990. setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
  991. setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
  992. setOperationAction(ISD::VECREDUCE_FADD, VT, Legal);
  993. }
  994. }
  995. for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
  996. MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
  997. setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
  998. setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
  999. setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
  1000. setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
  1001. setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
  1002. }
  1003. setOperationAction(ISD::VECREDUCE_ADD, MVT::v2i64, Custom);
  1004. setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
  1005. setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
  1006. // Likewise, narrowing and extending vector loads/stores aren't handled
  1007. // directly.
  1008. for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
  1009. setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
  1010. if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
  1011. setOperationAction(ISD::MULHS, VT, Legal);
  1012. setOperationAction(ISD::MULHU, VT, Legal);
  1013. } else {
  1014. setOperationAction(ISD::MULHS, VT, Expand);
  1015. setOperationAction(ISD::MULHU, VT, Expand);
  1016. }
  1017. setOperationAction(ISD::SMUL_LOHI, VT, Expand);
  1018. setOperationAction(ISD::UMUL_LOHI, VT, Expand);
  1019. setOperationAction(ISD::BSWAP, VT, Expand);
  1020. setOperationAction(ISD::CTTZ, VT, Expand);
  1021. for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
  1022. setTruncStoreAction(VT, InnerVT, Expand);
  1023. setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
  1024. setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
  1025. setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
  1026. }
  1027. }
  1028. // AArch64 has implementations of a lot of rounding-like FP operations.
  1029. for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
  1030. setOperationAction(ISD::FFLOOR, Ty, Legal);
  1031. setOperationAction(ISD::FNEARBYINT, Ty, Legal);
  1032. setOperationAction(ISD::FCEIL, Ty, Legal);
  1033. setOperationAction(ISD::FRINT, Ty, Legal);
  1034. setOperationAction(ISD::FTRUNC, Ty, Legal);
  1035. setOperationAction(ISD::FROUND, Ty, Legal);
  1036. setOperationAction(ISD::FROUNDEVEN, Ty, Legal);
  1037. }
  1038. if (Subtarget->hasFullFP16()) {
  1039. for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
  1040. setOperationAction(ISD::FFLOOR, Ty, Legal);
  1041. setOperationAction(ISD::FNEARBYINT, Ty, Legal);
  1042. setOperationAction(ISD::FCEIL, Ty, Legal);
  1043. setOperationAction(ISD::FRINT, Ty, Legal);
  1044. setOperationAction(ISD::FTRUNC, Ty, Legal);
  1045. setOperationAction(ISD::FROUND, Ty, Legal);
  1046. setOperationAction(ISD::FROUNDEVEN, Ty, Legal);
  1047. }
  1048. }
  1049. if (Subtarget->hasSVE())
  1050. setOperationAction(ISD::VSCALE, MVT::i32, Custom);
  1051. setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
  1052. setLoadExtAction(ISD::EXTLOAD, MVT::v4i16, MVT::v4i8, Custom);
  1053. setLoadExtAction(ISD::SEXTLOAD, MVT::v4i16, MVT::v4i8, Custom);
  1054. setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i16, MVT::v4i8, Custom);
  1055. setLoadExtAction(ISD::EXTLOAD, MVT::v4i32, MVT::v4i8, Custom);
  1056. setLoadExtAction(ISD::SEXTLOAD, MVT::v4i32, MVT::v4i8, Custom);
  1057. setLoadExtAction(ISD::ZEXTLOAD, MVT::v4i32, MVT::v4i8, Custom);
  1058. }
  1059. if (Subtarget->hasSVE()) {
  1060. for (auto VT : {MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64}) {
  1061. setOperationAction(ISD::BITREVERSE, VT, Custom);
  1062. setOperationAction(ISD::BSWAP, VT, Custom);
  1063. setOperationAction(ISD::CTLZ, VT, Custom);
  1064. setOperationAction(ISD::CTPOP, VT, Custom);
  1065. setOperationAction(ISD::CTTZ, VT, Custom);
  1066. setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
  1067. setOperationAction(ISD::UINT_TO_FP, VT, Custom);
  1068. setOperationAction(ISD::SINT_TO_FP, VT, Custom);
  1069. setOperationAction(ISD::FP_TO_UINT, VT, Custom);
  1070. setOperationAction(ISD::FP_TO_SINT, VT, Custom);
  1071. setOperationAction(ISD::MGATHER, VT, Custom);
  1072. setOperationAction(ISD::MSCATTER, VT, Custom);
  1073. setOperationAction(ISD::MLOAD, VT, Custom);
  1074. setOperationAction(ISD::MUL, VT, Custom);
  1075. setOperationAction(ISD::MULHS, VT, Custom);
  1076. setOperationAction(ISD::MULHU, VT, Custom);
  1077. setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
  1078. setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
  1079. setOperationAction(ISD::SELECT, VT, Custom);
  1080. setOperationAction(ISD::SETCC, VT, Custom);
  1081. setOperationAction(ISD::SDIV, VT, Custom);
  1082. setOperationAction(ISD::UDIV, VT, Custom);
  1083. setOperationAction(ISD::SMIN, VT, Custom);
  1084. setOperationAction(ISD::UMIN, VT, Custom);
  1085. setOperationAction(ISD::SMAX, VT, Custom);
  1086. setOperationAction(ISD::UMAX, VT, Custom);
  1087. setOperationAction(ISD::SHL, VT, Custom);
  1088. setOperationAction(ISD::SRL, VT, Custom);
  1089. setOperationAction(ISD::SRA, VT, Custom);
  1090. setOperationAction(ISD::ABS, VT, Custom);
  1091. setOperationAction(ISD::ABDS, VT, Custom);
  1092. setOperationAction(ISD::ABDU, VT, Custom);
  1093. setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
  1094. setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
  1095. setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
  1096. setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
  1097. setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
  1098. setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
  1099. setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
  1100. setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
  1101. setOperationAction(ISD::UMUL_LOHI, VT, Expand);
  1102. setOperationAction(ISD::SMUL_LOHI, VT, Expand);
  1103. setOperationAction(ISD::SELECT_CC, VT, Expand);
  1104. setOperationAction(ISD::ROTL, VT, Expand);
  1105. setOperationAction(ISD::ROTR, VT, Expand);
  1106. }
  1107. // Illegal unpacked integer vector types.
  1108. for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32}) {
  1109. setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
  1110. setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
  1111. }
  1112. // Legalize unpacked bitcasts to REINTERPRET_CAST.
  1113. for (auto VT : {MVT::nxv2i16, MVT::nxv4i16, MVT::nxv2i32, MVT::nxv2bf16,
  1114. MVT::nxv2f16, MVT::nxv4f16, MVT::nxv2f32})
  1115. setOperationAction(ISD::BITCAST, VT, Custom);
  1116. for (auto VT : {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1}) {
  1117. setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
  1118. setOperationAction(ISD::SELECT, VT, Custom);
  1119. setOperationAction(ISD::SETCC, VT, Custom);
  1120. setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
  1121. setOperationAction(ISD::TRUNCATE, VT, Custom);
  1122. setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
  1123. setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
  1124. setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
  1125. setOperationAction(ISD::SELECT_CC, VT, Expand);
  1126. setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
  1127. setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
  1128. setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
  1129. // There are no legal MVT::nxv16f## based types.
  1130. if (VT != MVT::nxv16i1) {
  1131. setOperationAction(ISD::SINT_TO_FP, VT, Custom);
  1132. setOperationAction(ISD::UINT_TO_FP, VT, Custom);
  1133. }
  1134. }
  1135. // NEON doesn't support masked loads/stores/gathers/scatters, but SVE does
  1136. for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32, MVT::v1f64,
  1137. MVT::v2f64, MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
  1138. MVT::v2i32, MVT::v4i32, MVT::v1i64, MVT::v2i64}) {
  1139. setOperationAction(ISD::MLOAD, VT, Custom);
  1140. setOperationAction(ISD::MSTORE, VT, Custom);
  1141. setOperationAction(ISD::MGATHER, VT, Custom);
  1142. setOperationAction(ISD::MSCATTER, VT, Custom);
  1143. }
  1144. for (MVT VT : MVT::fp_scalable_vector_valuetypes()) {
  1145. for (MVT InnerVT : MVT::fp_scalable_vector_valuetypes()) {
  1146. // Avoid marking truncating FP stores as legal to prevent the
  1147. // DAGCombiner from creating unsupported truncating stores.
  1148. setTruncStoreAction(VT, InnerVT, Expand);
  1149. // SVE does not have floating-point extending loads.
  1150. setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
  1151. setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
  1152. setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
  1153. }
  1154. }
  1155. // SVE supports truncating stores of 64 and 128-bit vectors
  1156. setTruncStoreAction(MVT::v2i64, MVT::v2i8, Custom);
  1157. setTruncStoreAction(MVT::v2i64, MVT::v2i16, Custom);
  1158. setTruncStoreAction(MVT::v2i64, MVT::v2i32, Custom);
  1159. setTruncStoreAction(MVT::v2i32, MVT::v2i8, Custom);
  1160. setTruncStoreAction(MVT::v2i32, MVT::v2i16, Custom);
  1161. for (auto VT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32,
  1162. MVT::nxv4f32, MVT::nxv2f64}) {
  1163. setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
  1164. setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
  1165. setOperationAction(ISD::MGATHER, VT, Custom);
  1166. setOperationAction(ISD::MSCATTER, VT, Custom);
  1167. setOperationAction(ISD::MLOAD, VT, Custom);
  1168. setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
  1169. setOperationAction(ISD::SELECT, VT, Custom);
  1170. setOperationAction(ISD::FADD, VT, Custom);
  1171. setOperationAction(ISD::FCOPYSIGN, VT, Custom);
  1172. setOperationAction(ISD::FDIV, VT, Custom);
  1173. setOperationAction(ISD::FMA, VT, Custom);
  1174. setOperationAction(ISD::FMAXIMUM, VT, Custom);
  1175. setOperationAction(ISD::FMAXNUM, VT, Custom);
  1176. setOperationAction(ISD::FMINIMUM, VT, Custom);
  1177. setOperationAction(ISD::FMINNUM, VT, Custom);
  1178. setOperationAction(ISD::FMUL, VT, Custom);
  1179. setOperationAction(ISD::FNEG, VT, Custom);
  1180. setOperationAction(ISD::FSUB, VT, Custom);
  1181. setOperationAction(ISD::FCEIL, VT, Custom);
  1182. setOperationAction(ISD::FFLOOR, VT, Custom);
  1183. setOperationAction(ISD::FNEARBYINT, VT, Custom);
  1184. setOperationAction(ISD::FRINT, VT, Custom);
  1185. setOperationAction(ISD::FROUND, VT, Custom);
  1186. setOperationAction(ISD::FROUNDEVEN, VT, Custom);
  1187. setOperationAction(ISD::FTRUNC, VT, Custom);
  1188. setOperationAction(ISD::FSQRT, VT, Custom);
  1189. setOperationAction(ISD::FABS, VT, Custom);
  1190. setOperationAction(ISD::FP_EXTEND, VT, Custom);
  1191. setOperationAction(ISD::FP_ROUND, VT, Custom);
  1192. setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
  1193. setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
  1194. setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
  1195. setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
  1196. setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
  1197. setOperationAction(ISD::SELECT_CC, VT, Expand);
  1198. }
  1199. for (auto VT : {MVT::nxv2bf16, MVT::nxv4bf16, MVT::nxv8bf16}) {
  1200. setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
  1201. setOperationAction(ISD::MGATHER, VT, Custom);
  1202. setOperationAction(ISD::MSCATTER, VT, Custom);
  1203. setOperationAction(ISD::MLOAD, VT, Custom);
  1204. setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
  1205. }
  1206. setOperationAction(ISD::SPLAT_VECTOR, MVT::nxv8bf16, Custom);
  1207. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
  1208. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
  1209. // NOTE: Currently this has to happen after computeRegisterProperties rather
  1210. // than the preferred option of combining it with the addRegisterClass call.
  1211. if (Subtarget->useSVEForFixedLengthVectors()) {
  1212. for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
  1213. if (useSVEForFixedLengthVectorVT(VT))
  1214. addTypeForFixedLengthSVE(VT);
  1215. for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
  1216. if (useSVEForFixedLengthVectorVT(VT))
  1217. addTypeForFixedLengthSVE(VT);
  1218. // 64bit results can mean a bigger than NEON input.
  1219. for (auto VT : {MVT::v8i8, MVT::v4i16})
  1220. setOperationAction(ISD::TRUNCATE, VT, Custom);
  1221. setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
  1222. // 128bit results imply a bigger than NEON input.
  1223. for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
  1224. setOperationAction(ISD::TRUNCATE, VT, Custom);
  1225. for (auto VT : {MVT::v8f16, MVT::v4f32})
  1226. setOperationAction(ISD::FP_ROUND, VT, Custom);
  1227. // These operations are not supported on NEON but SVE can do them.
  1228. setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom);
  1229. setOperationAction(ISD::CTLZ, MVT::v1i64, Custom);
  1230. setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
  1231. setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
  1232. setOperationAction(ISD::MUL, MVT::v1i64, Custom);
  1233. setOperationAction(ISD::MUL, MVT::v2i64, Custom);
  1234. setOperationAction(ISD::MULHS, MVT::v1i64, Custom);
  1235. setOperationAction(ISD::MULHS, MVT::v2i64, Custom);
  1236. setOperationAction(ISD::MULHU, MVT::v1i64, Custom);
  1237. setOperationAction(ISD::MULHU, MVT::v2i64, Custom);
  1238. setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
  1239. setOperationAction(ISD::SDIV, MVT::v16i8, Custom);
  1240. setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
  1241. setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
  1242. setOperationAction(ISD::SDIV, MVT::v2i32, Custom);
  1243. setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
  1244. setOperationAction(ISD::SDIV, MVT::v1i64, Custom);
  1245. setOperationAction(ISD::SDIV, MVT::v2i64, Custom);
  1246. setOperationAction(ISD::SMAX, MVT::v1i64, Custom);
  1247. setOperationAction(ISD::SMAX, MVT::v2i64, Custom);
  1248. setOperationAction(ISD::SMIN, MVT::v1i64, Custom);
  1249. setOperationAction(ISD::SMIN, MVT::v2i64, Custom);
  1250. setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
  1251. setOperationAction(ISD::UDIV, MVT::v16i8, Custom);
  1252. setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
  1253. setOperationAction(ISD::UDIV, MVT::v8i16, Custom);
  1254. setOperationAction(ISD::UDIV, MVT::v2i32, Custom);
  1255. setOperationAction(ISD::UDIV, MVT::v4i32, Custom);
  1256. setOperationAction(ISD::UDIV, MVT::v1i64, Custom);
  1257. setOperationAction(ISD::UDIV, MVT::v2i64, Custom);
  1258. setOperationAction(ISD::UMAX, MVT::v1i64, Custom);
  1259. setOperationAction(ISD::UMAX, MVT::v2i64, Custom);
  1260. setOperationAction(ISD::UMIN, MVT::v1i64, Custom);
  1261. setOperationAction(ISD::UMIN, MVT::v2i64, Custom);
  1262. setOperationAction(ISD::VECREDUCE_SMAX, MVT::v2i64, Custom);
  1263. setOperationAction(ISD::VECREDUCE_SMIN, MVT::v2i64, Custom);
  1264. setOperationAction(ISD::VECREDUCE_UMAX, MVT::v2i64, Custom);
  1265. setOperationAction(ISD::VECREDUCE_UMIN, MVT::v2i64, Custom);
  1266. // Int operations with no NEON support.
  1267. for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
  1268. MVT::v2i32, MVT::v4i32, MVT::v2i64}) {
  1269. setOperationAction(ISD::BITREVERSE, VT, Custom);
  1270. setOperationAction(ISD::CTTZ, VT, Custom);
  1271. setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
  1272. setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
  1273. setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
  1274. }
  1275. // FP operations with no NEON support.
  1276. for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32,
  1277. MVT::v1f64, MVT::v2f64})
  1278. setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
  1279. // Use SVE for vectors with more than 2 elements.
  1280. for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v4f32})
  1281. setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
  1282. }
  1283. setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv2i1, MVT::nxv2i64);
  1284. setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv4i1, MVT::nxv4i32);
  1285. setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv8i1, MVT::nxv8i16);
  1286. setOperationPromotedToType(ISD::VECTOR_SPLICE, MVT::nxv16i1, MVT::nxv16i8);
  1287. }
  1288. if (Subtarget->hasMOPS() && Subtarget->hasMTE()) {
  1289. // Only required for llvm.aarch64.mops.memset.tag
  1290. setOperationAction(ISD::INTRINSIC_W_CHAIN, MVT::i8, Custom);
  1291. }
  1292. PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
  1293. }
  1294. void AArch64TargetLowering::addTypeForNEON(MVT VT) {
  1295. assert(VT.isVector() && "VT should be a vector type");
  1296. if (VT.isFloatingPoint()) {
  1297. MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
  1298. setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
  1299. setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
  1300. }
  1301. // Mark vector float intrinsics as expand.
  1302. if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
  1303. setOperationAction(ISD::FSIN, VT, Expand);
  1304. setOperationAction(ISD::FCOS, VT, Expand);
  1305. setOperationAction(ISD::FPOW, VT, Expand);
  1306. setOperationAction(ISD::FLOG, VT, Expand);
  1307. setOperationAction(ISD::FLOG2, VT, Expand);
  1308. setOperationAction(ISD::FLOG10, VT, Expand);
  1309. setOperationAction(ISD::FEXP, VT, Expand);
  1310. setOperationAction(ISD::FEXP2, VT, Expand);
  1311. }
  1312. // But we do support custom-lowering for FCOPYSIGN.
  1313. if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
  1314. ((VT == MVT::v4f16 || VT == MVT::v8f16) && Subtarget->hasFullFP16()))
  1315. setOperationAction(ISD::FCOPYSIGN, VT, Custom);
  1316. setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
  1317. setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
  1318. setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
  1319. setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
  1320. setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
  1321. setOperationAction(ISD::SRA, VT, Custom);
  1322. setOperationAction(ISD::SRL, VT, Custom);
  1323. setOperationAction(ISD::SHL, VT, Custom);
  1324. setOperationAction(ISD::OR, VT, Custom);
  1325. setOperationAction(ISD::SETCC, VT, Custom);
  1326. setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
  1327. setOperationAction(ISD::SELECT, VT, Expand);
  1328. setOperationAction(ISD::SELECT_CC, VT, Expand);
  1329. setOperationAction(ISD::VSELECT, VT, Expand);
  1330. for (MVT InnerVT : MVT::all_valuetypes())
  1331. setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
  1332. // CNT supports only B element sizes, then use UADDLP to widen.
  1333. if (VT != MVT::v8i8 && VT != MVT::v16i8)
  1334. setOperationAction(ISD::CTPOP, VT, Custom);
  1335. setOperationAction(ISD::UDIV, VT, Expand);
  1336. setOperationAction(ISD::SDIV, VT, Expand);
  1337. setOperationAction(ISD::UREM, VT, Expand);
  1338. setOperationAction(ISD::SREM, VT, Expand);
  1339. setOperationAction(ISD::FREM, VT, Expand);
  1340. setOperationAction(ISD::FP_TO_SINT, VT, Custom);
  1341. setOperationAction(ISD::FP_TO_UINT, VT, Custom);
  1342. setOperationAction(ISD::FP_TO_SINT_SAT, VT, Custom);
  1343. setOperationAction(ISD::FP_TO_UINT_SAT, VT, Custom);
  1344. if (!VT.isFloatingPoint())
  1345. setOperationAction(ISD::ABS, VT, Legal);
  1346. // [SU][MIN|MAX] are available for all NEON types apart from i64.
  1347. if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
  1348. for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
  1349. setOperationAction(Opcode, VT, Legal);
  1350. // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
  1351. if (VT.isFloatingPoint() &&
  1352. VT.getVectorElementType() != MVT::bf16 &&
  1353. (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
  1354. for (unsigned Opcode :
  1355. {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
  1356. setOperationAction(Opcode, VT, Legal);
  1357. if (Subtarget->isLittleEndian()) {
  1358. for (unsigned im = (unsigned)ISD::PRE_INC;
  1359. im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
  1360. setIndexedLoadAction(im, VT, Legal);
  1361. setIndexedStoreAction(im, VT, Legal);
  1362. }
  1363. }
  1364. }
  1365. bool AArch64TargetLowering::shouldExpandGetActiveLaneMask(EVT ResVT,
  1366. EVT OpVT) const {
  1367. // Only SVE has a 1:1 mapping from intrinsic -> instruction (whilelo).
  1368. if (!Subtarget->hasSVE())
  1369. return true;
  1370. // We can only support legal predicate result types.
  1371. if (ResVT != MVT::nxv2i1 && ResVT != MVT::nxv4i1 && ResVT != MVT::nxv8i1 &&
  1372. ResVT != MVT::nxv16i1)
  1373. return true;
  1374. // The whilelo instruction only works with i32 or i64 scalar inputs.
  1375. if (OpVT != MVT::i32 && OpVT != MVT::i64)
  1376. return true;
  1377. return false;
  1378. }
  1379. void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) {
  1380. assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
  1381. // By default everything must be expanded.
  1382. for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
  1383. setOperationAction(Op, VT, Expand);
  1384. // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one.
  1385. setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
  1386. if (VT.isFloatingPoint()) {
  1387. setCondCodeAction(ISD::SETO, VT, Expand);
  1388. setCondCodeAction(ISD::SETOLT, VT, Expand);
  1389. setCondCodeAction(ISD::SETLT, VT, Expand);
  1390. setCondCodeAction(ISD::SETOLE, VT, Expand);
  1391. setCondCodeAction(ISD::SETLE, VT, Expand);
  1392. setCondCodeAction(ISD::SETULT, VT, Expand);
  1393. setCondCodeAction(ISD::SETULE, VT, Expand);
  1394. setCondCodeAction(ISD::SETUGE, VT, Expand);
  1395. setCondCodeAction(ISD::SETUGT, VT, Expand);
  1396. setCondCodeAction(ISD::SETUEQ, VT, Expand);
  1397. setCondCodeAction(ISD::SETUNE, VT, Expand);
  1398. }
  1399. // Mark integer truncating stores/extending loads as having custom lowering
  1400. if (VT.isInteger()) {
  1401. MVT InnerVT = VT.changeVectorElementType(MVT::i8);
  1402. while (InnerVT != VT) {
  1403. setTruncStoreAction(VT, InnerVT, Custom);
  1404. setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Custom);
  1405. setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Custom);
  1406. InnerVT = InnerVT.changeVectorElementType(
  1407. MVT::getIntegerVT(2 * InnerVT.getScalarSizeInBits()));
  1408. }
  1409. }
  1410. // Mark floating-point truncating stores/extending loads as having custom
  1411. // lowering
  1412. if (VT.isFloatingPoint()) {
  1413. MVT InnerVT = VT.changeVectorElementType(MVT::f16);
  1414. while (InnerVT != VT) {
  1415. setTruncStoreAction(VT, InnerVT, Custom);
  1416. setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Custom);
  1417. InnerVT = InnerVT.changeVectorElementType(
  1418. MVT::getFloatingPointVT(2 * InnerVT.getScalarSizeInBits()));
  1419. }
  1420. }
  1421. // Lower fixed length vector operations to scalable equivalents.
  1422. setOperationAction(ISD::ABS, VT, Custom);
  1423. setOperationAction(ISD::ADD, VT, Custom);
  1424. setOperationAction(ISD::AND, VT, Custom);
  1425. setOperationAction(ISD::ANY_EXTEND, VT, Custom);
  1426. setOperationAction(ISD::BITCAST, VT, Custom);
  1427. setOperationAction(ISD::BITREVERSE, VT, Custom);
  1428. setOperationAction(ISD::BSWAP, VT, Custom);
  1429. setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
  1430. setOperationAction(ISD::CTLZ, VT, Custom);
  1431. setOperationAction(ISD::CTPOP, VT, Custom);
  1432. setOperationAction(ISD::CTTZ, VT, Custom);
  1433. setOperationAction(ISD::FABS, VT, Custom);
  1434. setOperationAction(ISD::FADD, VT, Custom);
  1435. setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
  1436. setOperationAction(ISD::FCEIL, VT, Custom);
  1437. setOperationAction(ISD::FDIV, VT, Custom);
  1438. setOperationAction(ISD::FFLOOR, VT, Custom);
  1439. setOperationAction(ISD::FMA, VT, Custom);
  1440. setOperationAction(ISD::FMAXIMUM, VT, Custom);
  1441. setOperationAction(ISD::FMAXNUM, VT, Custom);
  1442. setOperationAction(ISD::FMINIMUM, VT, Custom);
  1443. setOperationAction(ISD::FMINNUM, VT, Custom);
  1444. setOperationAction(ISD::FMUL, VT, Custom);
  1445. setOperationAction(ISD::FNEARBYINT, VT, Custom);
  1446. setOperationAction(ISD::FNEG, VT, Custom);
  1447. setOperationAction(ISD::FP_EXTEND, VT, Custom);
  1448. setOperationAction(ISD::FP_ROUND, VT, Custom);
  1449. setOperationAction(ISD::FP_TO_SINT, VT, Custom);
  1450. setOperationAction(ISD::FP_TO_UINT, VT, Custom);
  1451. setOperationAction(ISD::FRINT, VT, Custom);
  1452. setOperationAction(ISD::FROUND, VT, Custom);
  1453. setOperationAction(ISD::FROUNDEVEN, VT, Custom);
  1454. setOperationAction(ISD::FSQRT, VT, Custom);
  1455. setOperationAction(ISD::FSUB, VT, Custom);
  1456. setOperationAction(ISD::FTRUNC, VT, Custom);
  1457. setOperationAction(ISD::LOAD, VT, Custom);
  1458. setOperationAction(ISD::MGATHER, VT, Custom);
  1459. setOperationAction(ISD::MLOAD, VT, Custom);
  1460. setOperationAction(ISD::MSCATTER, VT, Custom);
  1461. setOperationAction(ISD::MSTORE, VT, Custom);
  1462. setOperationAction(ISD::MUL, VT, Custom);
  1463. setOperationAction(ISD::MULHS, VT, Custom);
  1464. setOperationAction(ISD::MULHU, VT, Custom);
  1465. setOperationAction(ISD::OR, VT, Custom);
  1466. setOperationAction(ISD::SDIV, VT, Custom);
  1467. setOperationAction(ISD::SELECT, VT, Custom);
  1468. setOperationAction(ISD::SETCC, VT, Custom);
  1469. setOperationAction(ISD::SHL, VT, Custom);
  1470. setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
  1471. setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
  1472. setOperationAction(ISD::SINT_TO_FP, VT, Custom);
  1473. setOperationAction(ISD::SMAX, VT, Custom);
  1474. setOperationAction(ISD::SMIN, VT, Custom);
  1475. setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
  1476. setOperationAction(ISD::VECTOR_SPLICE, VT, Custom);
  1477. setOperationAction(ISD::SRA, VT, Custom);
  1478. setOperationAction(ISD::SRL, VT, Custom);
  1479. setOperationAction(ISD::STORE, VT, Custom);
  1480. setOperationAction(ISD::SUB, VT, Custom);
  1481. setOperationAction(ISD::TRUNCATE, VT, Custom);
  1482. setOperationAction(ISD::UDIV, VT, Custom);
  1483. setOperationAction(ISD::UINT_TO_FP, VT, Custom);
  1484. setOperationAction(ISD::UMAX, VT, Custom);
  1485. setOperationAction(ISD::UMIN, VT, Custom);
  1486. setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
  1487. setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
  1488. setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
  1489. setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
  1490. setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
  1491. setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
  1492. setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
  1493. setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
  1494. setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
  1495. setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
  1496. setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
  1497. setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
  1498. setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
  1499. setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
  1500. setOperationAction(ISD::VSELECT, VT, Custom);
  1501. setOperationAction(ISD::XOR, VT, Custom);
  1502. setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
  1503. }
  1504. void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
  1505. addRegisterClass(VT, &AArch64::FPR64RegClass);
  1506. addTypeForNEON(VT);
  1507. }
  1508. void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
  1509. addRegisterClass(VT, &AArch64::FPR128RegClass);
  1510. addTypeForNEON(VT);
  1511. }
  1512. EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
  1513. LLVMContext &C, EVT VT) const {
  1514. if (!VT.isVector())
  1515. return MVT::i32;
  1516. if (VT.isScalableVector())
  1517. return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
  1518. return VT.changeVectorElementTypeToInteger();
  1519. }
  1520. static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
  1521. const APInt &Demanded,
  1522. TargetLowering::TargetLoweringOpt &TLO,
  1523. unsigned NewOpc) {
  1524. uint64_t OldImm = Imm, NewImm, Enc;
  1525. uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
  1526. // Return if the immediate is already all zeros, all ones, a bimm32 or a
  1527. // bimm64.
  1528. if (Imm == 0 || Imm == Mask ||
  1529. AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
  1530. return false;
  1531. unsigned EltSize = Size;
  1532. uint64_t DemandedBits = Demanded.getZExtValue();
  1533. // Clear bits that are not demanded.
  1534. Imm &= DemandedBits;
  1535. while (true) {
  1536. // The goal here is to set the non-demanded bits in a way that minimizes
  1537. // the number of switching between 0 and 1. In order to achieve this goal,
  1538. // we set the non-demanded bits to the value of the preceding demanded bits.
  1539. // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
  1540. // non-demanded bit), we copy bit0 (1) to the least significant 'x',
  1541. // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
  1542. // The final result is 0b11000011.
  1543. uint64_t NonDemandedBits = ~DemandedBits;
  1544. uint64_t InvertedImm = ~Imm & DemandedBits;
  1545. uint64_t RotatedImm =
  1546. ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
  1547. NonDemandedBits;
  1548. uint64_t Sum = RotatedImm + NonDemandedBits;
  1549. bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
  1550. uint64_t Ones = (Sum + Carry) & NonDemandedBits;
  1551. NewImm = (Imm | Ones) & Mask;
  1552. // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
  1553. // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
  1554. // we halve the element size and continue the search.
  1555. if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
  1556. break;
  1557. // We cannot shrink the element size any further if it is 2-bits.
  1558. if (EltSize == 2)
  1559. return false;
  1560. EltSize /= 2;
  1561. Mask >>= EltSize;
  1562. uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
  1563. // Return if there is mismatch in any of the demanded bits of Imm and Hi.
  1564. if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
  1565. return false;
  1566. // Merge the upper and lower halves of Imm and DemandedBits.
  1567. Imm |= Hi;
  1568. DemandedBits |= DemandedBitsHi;
  1569. }
  1570. ++NumOptimizedImms;
  1571. // Replicate the element across the register width.
  1572. while (EltSize < Size) {
  1573. NewImm |= NewImm << EltSize;
  1574. EltSize *= 2;
  1575. }
  1576. (void)OldImm;
  1577. assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
  1578. "demanded bits should never be altered");
  1579. assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
  1580. // Create the new constant immediate node.
  1581. EVT VT = Op.getValueType();
  1582. SDLoc DL(Op);
  1583. SDValue New;
  1584. // If the new constant immediate is all-zeros or all-ones, let the target
  1585. // independent DAG combine optimize this node.
  1586. if (NewImm == 0 || NewImm == OrigMask) {
  1587. New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
  1588. TLO.DAG.getConstant(NewImm, DL, VT));
  1589. // Otherwise, create a machine node so that target independent DAG combine
  1590. // doesn't undo this optimization.
  1591. } else {
  1592. Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
  1593. SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
  1594. New = SDValue(
  1595. TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
  1596. }
  1597. return TLO.CombineTo(Op, New);
  1598. }
  1599. bool AArch64TargetLowering::targetShrinkDemandedConstant(
  1600. SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
  1601. TargetLoweringOpt &TLO) const {
  1602. // Delay this optimization to as late as possible.
  1603. if (!TLO.LegalOps)
  1604. return false;
  1605. if (!EnableOptimizeLogicalImm)
  1606. return false;
  1607. EVT VT = Op.getValueType();
  1608. if (VT.isVector())
  1609. return false;
  1610. unsigned Size = VT.getSizeInBits();
  1611. assert((Size == 32 || Size == 64) &&
  1612. "i32 or i64 is expected after legalization.");
  1613. // Exit early if we demand all bits.
  1614. if (DemandedBits.countPopulation() == Size)
  1615. return false;
  1616. unsigned NewOpc;
  1617. switch (Op.getOpcode()) {
  1618. default:
  1619. return false;
  1620. case ISD::AND:
  1621. NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
  1622. break;
  1623. case ISD::OR:
  1624. NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
  1625. break;
  1626. case ISD::XOR:
  1627. NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
  1628. break;
  1629. }
  1630. ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  1631. if (!C)
  1632. return false;
  1633. uint64_t Imm = C->getZExtValue();
  1634. return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
  1635. }
  1636. /// computeKnownBitsForTargetNode - Determine which of the bits specified in
  1637. /// Mask are known to be either zero or one and return them Known.
  1638. void AArch64TargetLowering::computeKnownBitsForTargetNode(
  1639. const SDValue Op, KnownBits &Known,
  1640. const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
  1641. switch (Op.getOpcode()) {
  1642. default:
  1643. break;
  1644. case AArch64ISD::CSEL: {
  1645. KnownBits Known2;
  1646. Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
  1647. Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
  1648. Known = KnownBits::commonBits(Known, Known2);
  1649. break;
  1650. }
  1651. case AArch64ISD::BICi: {
  1652. // Compute the bit cleared value.
  1653. uint64_t Mask =
  1654. ~(Op->getConstantOperandVal(1) << Op->getConstantOperandVal(2));
  1655. Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
  1656. Known &= KnownBits::makeConstant(APInt(Known.getBitWidth(), Mask));
  1657. break;
  1658. }
  1659. case AArch64ISD::VLSHR: {
  1660. KnownBits Known2;
  1661. Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
  1662. Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
  1663. Known = KnownBits::lshr(Known, Known2);
  1664. break;
  1665. }
  1666. case AArch64ISD::VASHR: {
  1667. KnownBits Known2;
  1668. Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
  1669. Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
  1670. Known = KnownBits::ashr(Known, Known2);
  1671. break;
  1672. }
  1673. case AArch64ISD::LOADgot:
  1674. case AArch64ISD::ADDlow: {
  1675. if (!Subtarget->isTargetILP32())
  1676. break;
  1677. // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
  1678. Known.Zero = APInt::getHighBitsSet(64, 32);
  1679. break;
  1680. }
  1681. case AArch64ISD::ASSERT_ZEXT_BOOL: {
  1682. Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
  1683. Known.Zero |= APInt(Known.getBitWidth(), 0xFE);
  1684. break;
  1685. }
  1686. case ISD::INTRINSIC_W_CHAIN: {
  1687. ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
  1688. Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
  1689. switch (IntID) {
  1690. default: return;
  1691. case Intrinsic::aarch64_ldaxr:
  1692. case Intrinsic::aarch64_ldxr: {
  1693. unsigned BitWidth = Known.getBitWidth();
  1694. EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
  1695. unsigned MemBits = VT.getScalarSizeInBits();
  1696. Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
  1697. return;
  1698. }
  1699. }
  1700. break;
  1701. }
  1702. case ISD::INTRINSIC_WO_CHAIN:
  1703. case ISD::INTRINSIC_VOID: {
  1704. unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  1705. switch (IntNo) {
  1706. default:
  1707. break;
  1708. case Intrinsic::aarch64_neon_umaxv:
  1709. case Intrinsic::aarch64_neon_uminv: {
  1710. // Figure out the datatype of the vector operand. The UMINV instruction
  1711. // will zero extend the result, so we can mark as known zero all the
  1712. // bits larger than the element datatype. 32-bit or larget doesn't need
  1713. // this as those are legal types and will be handled by isel directly.
  1714. MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
  1715. unsigned BitWidth = Known.getBitWidth();
  1716. if (VT == MVT::v8i8 || VT == MVT::v16i8) {
  1717. assert(BitWidth >= 8 && "Unexpected width!");
  1718. APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
  1719. Known.Zero |= Mask;
  1720. } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
  1721. assert(BitWidth >= 16 && "Unexpected width!");
  1722. APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
  1723. Known.Zero |= Mask;
  1724. }
  1725. break;
  1726. } break;
  1727. }
  1728. }
  1729. }
  1730. }
  1731. MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
  1732. EVT) const {
  1733. return MVT::i64;
  1734. }
  1735. bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
  1736. EVT VT, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
  1737. bool *Fast) const {
  1738. if (Subtarget->requiresStrictAlign())
  1739. return false;
  1740. if (Fast) {
  1741. // Some CPUs are fine with unaligned stores except for 128-bit ones.
  1742. *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
  1743. // See comments in performSTORECombine() for more details about
  1744. // these conditions.
  1745. // Code that uses clang vector extensions can mark that it
  1746. // wants unaligned accesses to be treated as fast by
  1747. // underspecifying alignment to be 1 or 2.
  1748. Alignment <= 2 ||
  1749. // Disregard v2i64. Memcpy lowering produces those and splitting
  1750. // them regresses performance on micro-benchmarks and olden/bh.
  1751. VT == MVT::v2i64;
  1752. }
  1753. return true;
  1754. }
  1755. // Same as above but handling LLTs instead.
  1756. bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
  1757. LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
  1758. bool *Fast) const {
  1759. if (Subtarget->requiresStrictAlign())
  1760. return false;
  1761. if (Fast) {
  1762. // Some CPUs are fine with unaligned stores except for 128-bit ones.
  1763. *Fast = !Subtarget->isMisaligned128StoreSlow() ||
  1764. Ty.getSizeInBytes() != 16 ||
  1765. // See comments in performSTORECombine() for more details about
  1766. // these conditions.
  1767. // Code that uses clang vector extensions can mark that it
  1768. // wants unaligned accesses to be treated as fast by
  1769. // underspecifying alignment to be 1 or 2.
  1770. Alignment <= 2 ||
  1771. // Disregard v2i64. Memcpy lowering produces those and splitting
  1772. // them regresses performance on micro-benchmarks and olden/bh.
  1773. Ty == LLT::fixed_vector(2, 64);
  1774. }
  1775. return true;
  1776. }
  1777. FastISel *
  1778. AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
  1779. const TargetLibraryInfo *libInfo) const {
  1780. return AArch64::createFastISel(funcInfo, libInfo);
  1781. }
  1782. const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
  1783. #define MAKE_CASE(V) \
  1784. case V: \
  1785. return #V;
  1786. switch ((AArch64ISD::NodeType)Opcode) {
  1787. case AArch64ISD::FIRST_NUMBER:
  1788. break;
  1789. MAKE_CASE(AArch64ISD::CALL)
  1790. MAKE_CASE(AArch64ISD::ADRP)
  1791. MAKE_CASE(AArch64ISD::ADR)
  1792. MAKE_CASE(AArch64ISD::ADDlow)
  1793. MAKE_CASE(AArch64ISD::LOADgot)
  1794. MAKE_CASE(AArch64ISD::RET_FLAG)
  1795. MAKE_CASE(AArch64ISD::BRCOND)
  1796. MAKE_CASE(AArch64ISD::CSEL)
  1797. MAKE_CASE(AArch64ISD::CSINV)
  1798. MAKE_CASE(AArch64ISD::CSNEG)
  1799. MAKE_CASE(AArch64ISD::CSINC)
  1800. MAKE_CASE(AArch64ISD::THREAD_POINTER)
  1801. MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
  1802. MAKE_CASE(AArch64ISD::ABDS_PRED)
  1803. MAKE_CASE(AArch64ISD::ABDU_PRED)
  1804. MAKE_CASE(AArch64ISD::ADD_PRED)
  1805. MAKE_CASE(AArch64ISD::MUL_PRED)
  1806. MAKE_CASE(AArch64ISD::MULHS_PRED)
  1807. MAKE_CASE(AArch64ISD::MULHU_PRED)
  1808. MAKE_CASE(AArch64ISD::SDIV_PRED)
  1809. MAKE_CASE(AArch64ISD::SHL_PRED)
  1810. MAKE_CASE(AArch64ISD::SMAX_PRED)
  1811. MAKE_CASE(AArch64ISD::SMIN_PRED)
  1812. MAKE_CASE(AArch64ISD::SRA_PRED)
  1813. MAKE_CASE(AArch64ISD::SRL_PRED)
  1814. MAKE_CASE(AArch64ISD::SUB_PRED)
  1815. MAKE_CASE(AArch64ISD::UDIV_PRED)
  1816. MAKE_CASE(AArch64ISD::UMAX_PRED)
  1817. MAKE_CASE(AArch64ISD::UMIN_PRED)
  1818. MAKE_CASE(AArch64ISD::SRAD_MERGE_OP1)
  1819. MAKE_CASE(AArch64ISD::FNEG_MERGE_PASSTHRU)
  1820. MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU)
  1821. MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU)
  1822. MAKE_CASE(AArch64ISD::FCEIL_MERGE_PASSTHRU)
  1823. MAKE_CASE(AArch64ISD::FFLOOR_MERGE_PASSTHRU)
  1824. MAKE_CASE(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU)
  1825. MAKE_CASE(AArch64ISD::FRINT_MERGE_PASSTHRU)
  1826. MAKE_CASE(AArch64ISD::FROUND_MERGE_PASSTHRU)
  1827. MAKE_CASE(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU)
  1828. MAKE_CASE(AArch64ISD::FTRUNC_MERGE_PASSTHRU)
  1829. MAKE_CASE(AArch64ISD::FP_ROUND_MERGE_PASSTHRU)
  1830. MAKE_CASE(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU)
  1831. MAKE_CASE(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU)
  1832. MAKE_CASE(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU)
  1833. MAKE_CASE(AArch64ISD::FCVTZU_MERGE_PASSTHRU)
  1834. MAKE_CASE(AArch64ISD::FCVTZS_MERGE_PASSTHRU)
  1835. MAKE_CASE(AArch64ISD::FSQRT_MERGE_PASSTHRU)
  1836. MAKE_CASE(AArch64ISD::FRECPX_MERGE_PASSTHRU)
  1837. MAKE_CASE(AArch64ISD::FABS_MERGE_PASSTHRU)
  1838. MAKE_CASE(AArch64ISD::ABS_MERGE_PASSTHRU)
  1839. MAKE_CASE(AArch64ISD::NEG_MERGE_PASSTHRU)
  1840. MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
  1841. MAKE_CASE(AArch64ISD::ADC)
  1842. MAKE_CASE(AArch64ISD::SBC)
  1843. MAKE_CASE(AArch64ISD::ADDS)
  1844. MAKE_CASE(AArch64ISD::SUBS)
  1845. MAKE_CASE(AArch64ISD::ADCS)
  1846. MAKE_CASE(AArch64ISD::SBCS)
  1847. MAKE_CASE(AArch64ISD::ANDS)
  1848. MAKE_CASE(AArch64ISD::CCMP)
  1849. MAKE_CASE(AArch64ISD::CCMN)
  1850. MAKE_CASE(AArch64ISD::FCCMP)
  1851. MAKE_CASE(AArch64ISD::FCMP)
  1852. MAKE_CASE(AArch64ISD::STRICT_FCMP)
  1853. MAKE_CASE(AArch64ISD::STRICT_FCMPE)
  1854. MAKE_CASE(AArch64ISD::DUP)
  1855. MAKE_CASE(AArch64ISD::DUPLANE8)
  1856. MAKE_CASE(AArch64ISD::DUPLANE16)
  1857. MAKE_CASE(AArch64ISD::DUPLANE32)
  1858. MAKE_CASE(AArch64ISD::DUPLANE64)
  1859. MAKE_CASE(AArch64ISD::MOVI)
  1860. MAKE_CASE(AArch64ISD::MOVIshift)
  1861. MAKE_CASE(AArch64ISD::MOVIedit)
  1862. MAKE_CASE(AArch64ISD::MOVImsl)
  1863. MAKE_CASE(AArch64ISD::FMOV)
  1864. MAKE_CASE(AArch64ISD::MVNIshift)
  1865. MAKE_CASE(AArch64ISD::MVNImsl)
  1866. MAKE_CASE(AArch64ISD::BICi)
  1867. MAKE_CASE(AArch64ISD::ORRi)
  1868. MAKE_CASE(AArch64ISD::BSP)
  1869. MAKE_CASE(AArch64ISD::EXTR)
  1870. MAKE_CASE(AArch64ISD::ZIP1)
  1871. MAKE_CASE(AArch64ISD::ZIP2)
  1872. MAKE_CASE(AArch64ISD::UZP1)
  1873. MAKE_CASE(AArch64ISD::UZP2)
  1874. MAKE_CASE(AArch64ISD::TRN1)
  1875. MAKE_CASE(AArch64ISD::TRN2)
  1876. MAKE_CASE(AArch64ISD::REV16)
  1877. MAKE_CASE(AArch64ISD::REV32)
  1878. MAKE_CASE(AArch64ISD::REV64)
  1879. MAKE_CASE(AArch64ISD::EXT)
  1880. MAKE_CASE(AArch64ISD::SPLICE)
  1881. MAKE_CASE(AArch64ISD::VSHL)
  1882. MAKE_CASE(AArch64ISD::VLSHR)
  1883. MAKE_CASE(AArch64ISD::VASHR)
  1884. MAKE_CASE(AArch64ISD::VSLI)
  1885. MAKE_CASE(AArch64ISD::VSRI)
  1886. MAKE_CASE(AArch64ISD::CMEQ)
  1887. MAKE_CASE(AArch64ISD::CMGE)
  1888. MAKE_CASE(AArch64ISD::CMGT)
  1889. MAKE_CASE(AArch64ISD::CMHI)
  1890. MAKE_CASE(AArch64ISD::CMHS)
  1891. MAKE_CASE(AArch64ISD::FCMEQ)
  1892. MAKE_CASE(AArch64ISD::FCMGE)
  1893. MAKE_CASE(AArch64ISD::FCMGT)
  1894. MAKE_CASE(AArch64ISD::CMEQz)
  1895. MAKE_CASE(AArch64ISD::CMGEz)
  1896. MAKE_CASE(AArch64ISD::CMGTz)
  1897. MAKE_CASE(AArch64ISD::CMLEz)
  1898. MAKE_CASE(AArch64ISD::CMLTz)
  1899. MAKE_CASE(AArch64ISD::FCMEQz)
  1900. MAKE_CASE(AArch64ISD::FCMGEz)
  1901. MAKE_CASE(AArch64ISD::FCMGTz)
  1902. MAKE_CASE(AArch64ISD::FCMLEz)
  1903. MAKE_CASE(AArch64ISD::FCMLTz)
  1904. MAKE_CASE(AArch64ISD::SADDV)
  1905. MAKE_CASE(AArch64ISD::UADDV)
  1906. MAKE_CASE(AArch64ISD::SRHADD)
  1907. MAKE_CASE(AArch64ISD::URHADD)
  1908. MAKE_CASE(AArch64ISD::SHADD)
  1909. MAKE_CASE(AArch64ISD::UHADD)
  1910. MAKE_CASE(AArch64ISD::SDOT)
  1911. MAKE_CASE(AArch64ISD::UDOT)
  1912. MAKE_CASE(AArch64ISD::SMINV)
  1913. MAKE_CASE(AArch64ISD::UMINV)
  1914. MAKE_CASE(AArch64ISD::SMAXV)
  1915. MAKE_CASE(AArch64ISD::UMAXV)
  1916. MAKE_CASE(AArch64ISD::SADDV_PRED)
  1917. MAKE_CASE(AArch64ISD::UADDV_PRED)
  1918. MAKE_CASE(AArch64ISD::SMAXV_PRED)
  1919. MAKE_CASE(AArch64ISD::UMAXV_PRED)
  1920. MAKE_CASE(AArch64ISD::SMINV_PRED)
  1921. MAKE_CASE(AArch64ISD::UMINV_PRED)
  1922. MAKE_CASE(AArch64ISD::ORV_PRED)
  1923. MAKE_CASE(AArch64ISD::EORV_PRED)
  1924. MAKE_CASE(AArch64ISD::ANDV_PRED)
  1925. MAKE_CASE(AArch64ISD::CLASTA_N)
  1926. MAKE_CASE(AArch64ISD::CLASTB_N)
  1927. MAKE_CASE(AArch64ISD::LASTA)
  1928. MAKE_CASE(AArch64ISD::LASTB)
  1929. MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
  1930. MAKE_CASE(AArch64ISD::LS64_BUILD)
  1931. MAKE_CASE(AArch64ISD::LS64_EXTRACT)
  1932. MAKE_CASE(AArch64ISD::TBL)
  1933. MAKE_CASE(AArch64ISD::FADD_PRED)
  1934. MAKE_CASE(AArch64ISD::FADDA_PRED)
  1935. MAKE_CASE(AArch64ISD::FADDV_PRED)
  1936. MAKE_CASE(AArch64ISD::FDIV_PRED)
  1937. MAKE_CASE(AArch64ISD::FMA_PRED)
  1938. MAKE_CASE(AArch64ISD::FMAX_PRED)
  1939. MAKE_CASE(AArch64ISD::FMAXV_PRED)
  1940. MAKE_CASE(AArch64ISD::FMAXNM_PRED)
  1941. MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
  1942. MAKE_CASE(AArch64ISD::FMIN_PRED)
  1943. MAKE_CASE(AArch64ISD::FMINV_PRED)
  1944. MAKE_CASE(AArch64ISD::FMINNM_PRED)
  1945. MAKE_CASE(AArch64ISD::FMINNMV_PRED)
  1946. MAKE_CASE(AArch64ISD::FMUL_PRED)
  1947. MAKE_CASE(AArch64ISD::FSUB_PRED)
  1948. MAKE_CASE(AArch64ISD::BIC)
  1949. MAKE_CASE(AArch64ISD::BIT)
  1950. MAKE_CASE(AArch64ISD::CBZ)
  1951. MAKE_CASE(AArch64ISD::CBNZ)
  1952. MAKE_CASE(AArch64ISD::TBZ)
  1953. MAKE_CASE(AArch64ISD::TBNZ)
  1954. MAKE_CASE(AArch64ISD::TC_RETURN)
  1955. MAKE_CASE(AArch64ISD::PREFETCH)
  1956. MAKE_CASE(AArch64ISD::SITOF)
  1957. MAKE_CASE(AArch64ISD::UITOF)
  1958. MAKE_CASE(AArch64ISD::NVCAST)
  1959. MAKE_CASE(AArch64ISD::MRS)
  1960. MAKE_CASE(AArch64ISD::SQSHL_I)
  1961. MAKE_CASE(AArch64ISD::UQSHL_I)
  1962. MAKE_CASE(AArch64ISD::SRSHR_I)
  1963. MAKE_CASE(AArch64ISD::URSHR_I)
  1964. MAKE_CASE(AArch64ISD::SQSHLU_I)
  1965. MAKE_CASE(AArch64ISD::WrapperLarge)
  1966. MAKE_CASE(AArch64ISD::LD2post)
  1967. MAKE_CASE(AArch64ISD::LD3post)
  1968. MAKE_CASE(AArch64ISD::LD4post)
  1969. MAKE_CASE(AArch64ISD::ST2post)
  1970. MAKE_CASE(AArch64ISD::ST3post)
  1971. MAKE_CASE(AArch64ISD::ST4post)
  1972. MAKE_CASE(AArch64ISD::LD1x2post)
  1973. MAKE_CASE(AArch64ISD::LD1x3post)
  1974. MAKE_CASE(AArch64ISD::LD1x4post)
  1975. MAKE_CASE(AArch64ISD::ST1x2post)
  1976. MAKE_CASE(AArch64ISD::ST1x3post)
  1977. MAKE_CASE(AArch64ISD::ST1x4post)
  1978. MAKE_CASE(AArch64ISD::LD1DUPpost)
  1979. MAKE_CASE(AArch64ISD::LD2DUPpost)
  1980. MAKE_CASE(AArch64ISD::LD3DUPpost)
  1981. MAKE_CASE(AArch64ISD::LD4DUPpost)
  1982. MAKE_CASE(AArch64ISD::LD1LANEpost)
  1983. MAKE_CASE(AArch64ISD::LD2LANEpost)
  1984. MAKE_CASE(AArch64ISD::LD3LANEpost)
  1985. MAKE_CASE(AArch64ISD::LD4LANEpost)
  1986. MAKE_CASE(AArch64ISD::ST2LANEpost)
  1987. MAKE_CASE(AArch64ISD::ST3LANEpost)
  1988. MAKE_CASE(AArch64ISD::ST4LANEpost)
  1989. MAKE_CASE(AArch64ISD::SMULL)
  1990. MAKE_CASE(AArch64ISD::UMULL)
  1991. MAKE_CASE(AArch64ISD::FRECPE)
  1992. MAKE_CASE(AArch64ISD::FRECPS)
  1993. MAKE_CASE(AArch64ISD::FRSQRTE)
  1994. MAKE_CASE(AArch64ISD::FRSQRTS)
  1995. MAKE_CASE(AArch64ISD::STG)
  1996. MAKE_CASE(AArch64ISD::STZG)
  1997. MAKE_CASE(AArch64ISD::ST2G)
  1998. MAKE_CASE(AArch64ISD::STZ2G)
  1999. MAKE_CASE(AArch64ISD::SUNPKHI)
  2000. MAKE_CASE(AArch64ISD::SUNPKLO)
  2001. MAKE_CASE(AArch64ISD::UUNPKHI)
  2002. MAKE_CASE(AArch64ISD::UUNPKLO)
  2003. MAKE_CASE(AArch64ISD::INSR)
  2004. MAKE_CASE(AArch64ISD::PTEST)
  2005. MAKE_CASE(AArch64ISD::PTRUE)
  2006. MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
  2007. MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
  2008. MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
  2009. MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
  2010. MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
  2011. MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
  2012. MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
  2013. MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
  2014. MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
  2015. MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
  2016. MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
  2017. MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
  2018. MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
  2019. MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
  2020. MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
  2021. MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
  2022. MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
  2023. MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
  2024. MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
  2025. MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
  2026. MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
  2027. MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
  2028. MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
  2029. MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
  2030. MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
  2031. MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
  2032. MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
  2033. MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
  2034. MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
  2035. MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
  2036. MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
  2037. MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
  2038. MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
  2039. MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
  2040. MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
  2041. MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
  2042. MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
  2043. MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
  2044. MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
  2045. MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
  2046. MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
  2047. MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
  2048. MAKE_CASE(AArch64ISD::ST1_PRED)
  2049. MAKE_CASE(AArch64ISD::SST1_PRED)
  2050. MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
  2051. MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
  2052. MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
  2053. MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
  2054. MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
  2055. MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
  2056. MAKE_CASE(AArch64ISD::SSTNT1_PRED)
  2057. MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
  2058. MAKE_CASE(AArch64ISD::LDP)
  2059. MAKE_CASE(AArch64ISD::STP)
  2060. MAKE_CASE(AArch64ISD::STNP)
  2061. MAKE_CASE(AArch64ISD::BITREVERSE_MERGE_PASSTHRU)
  2062. MAKE_CASE(AArch64ISD::BSWAP_MERGE_PASSTHRU)
  2063. MAKE_CASE(AArch64ISD::REVH_MERGE_PASSTHRU)
  2064. MAKE_CASE(AArch64ISD::REVW_MERGE_PASSTHRU)
  2065. MAKE_CASE(AArch64ISD::CTLZ_MERGE_PASSTHRU)
  2066. MAKE_CASE(AArch64ISD::CTPOP_MERGE_PASSTHRU)
  2067. MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
  2068. MAKE_CASE(AArch64ISD::INDEX_VECTOR)
  2069. MAKE_CASE(AArch64ISD::UADDLP)
  2070. MAKE_CASE(AArch64ISD::CALL_RVMARKER)
  2071. MAKE_CASE(AArch64ISD::ASSERT_ZEXT_BOOL)
  2072. MAKE_CASE(AArch64ISD::MOPS_MEMSET)
  2073. MAKE_CASE(AArch64ISD::MOPS_MEMSET_TAGGING)
  2074. MAKE_CASE(AArch64ISD::MOPS_MEMCOPY)
  2075. MAKE_CASE(AArch64ISD::MOPS_MEMMOVE)
  2076. MAKE_CASE(AArch64ISD::CALL_BTI)
  2077. }
  2078. #undef MAKE_CASE
  2079. return nullptr;
  2080. }
  2081. MachineBasicBlock *
  2082. AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
  2083. MachineBasicBlock *MBB) const {
  2084. // We materialise the F128CSEL pseudo-instruction as some control flow and a
  2085. // phi node:
  2086. // OrigBB:
  2087. // [... previous instrs leading to comparison ...]
  2088. // b.ne TrueBB
  2089. // b EndBB
  2090. // TrueBB:
  2091. // ; Fallthrough
  2092. // EndBB:
  2093. // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
  2094. MachineFunction *MF = MBB->getParent();
  2095. const TargetInstrInfo *TII = Subtarget->getInstrInfo();
  2096. const BasicBlock *LLVM_BB = MBB->getBasicBlock();
  2097. DebugLoc DL = MI.getDebugLoc();
  2098. MachineFunction::iterator It = ++MBB->getIterator();
  2099. Register DestReg = MI.getOperand(0).getReg();
  2100. Register IfTrueReg = MI.getOperand(1).getReg();
  2101. Register IfFalseReg = MI.getOperand(2).getReg();
  2102. unsigned CondCode = MI.getOperand(3).getImm();
  2103. bool NZCVKilled = MI.getOperand(4).isKill();
  2104. MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
  2105. MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
  2106. MF->insert(It, TrueBB);
  2107. MF->insert(It, EndBB);
  2108. // Transfer rest of current basic-block to EndBB
  2109. EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
  2110. MBB->end());
  2111. EndBB->transferSuccessorsAndUpdatePHIs(MBB);
  2112. BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
  2113. BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
  2114. MBB->addSuccessor(TrueBB);
  2115. MBB->addSuccessor(EndBB);
  2116. // TrueBB falls through to the end.
  2117. TrueBB->addSuccessor(EndBB);
  2118. if (!NZCVKilled) {
  2119. TrueBB->addLiveIn(AArch64::NZCV);
  2120. EndBB->addLiveIn(AArch64::NZCV);
  2121. }
  2122. BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
  2123. .addReg(IfTrueReg)
  2124. .addMBB(TrueBB)
  2125. .addReg(IfFalseReg)
  2126. .addMBB(MBB);
  2127. MI.eraseFromParent();
  2128. return EndBB;
  2129. }
  2130. MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
  2131. MachineInstr &MI, MachineBasicBlock *BB) const {
  2132. assert(!isAsynchronousEHPersonality(classifyEHPersonality(
  2133. BB->getParent()->getFunction().getPersonalityFn())) &&
  2134. "SEH does not use catchret!");
  2135. return BB;
  2136. }
  2137. MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
  2138. MachineInstr &MI, MachineBasicBlock *BB) const {
  2139. switch (MI.getOpcode()) {
  2140. default:
  2141. #ifndef NDEBUG
  2142. MI.dump();
  2143. #endif
  2144. llvm_unreachable("Unexpected instruction for custom inserter!");
  2145. case AArch64::F128CSEL:
  2146. return EmitF128CSEL(MI, BB);
  2147. case TargetOpcode::STATEPOINT:
  2148. // STATEPOINT is a pseudo instruction which has no implicit defs/uses
  2149. // while bl call instruction (where statepoint will be lowered at the end)
  2150. // has implicit def. Add this implicit dead def here as a workaround.
  2151. MI.addOperand(*MI.getMF(), MachineOperand::CreateReg(AArch64::LR, true,
  2152. true, false, true));
  2153. LLVM_FALLTHROUGH;
  2154. case TargetOpcode::STACKMAP:
  2155. case TargetOpcode::PATCHPOINT:
  2156. return emitPatchPoint(MI, BB);
  2157. case AArch64::CATCHRET:
  2158. return EmitLoweredCatchRet(MI, BB);
  2159. }
  2160. }
  2161. //===----------------------------------------------------------------------===//
  2162. // AArch64 Lowering private implementation.
  2163. //===----------------------------------------------------------------------===//
  2164. //===----------------------------------------------------------------------===//
  2165. // Lowering Code
  2166. //===----------------------------------------------------------------------===//
  2167. // Forward declarations of SVE fixed length lowering helpers
  2168. static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT);
  2169. static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V);
  2170. static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V);
  2171. static SDValue convertFixedMaskToScalableVector(SDValue Mask,
  2172. SelectionDAG &DAG);
  2173. static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
  2174. EVT VT);
  2175. /// isZerosVector - Check whether SDNode N is a zero-filled vector.
  2176. static bool isZerosVector(const SDNode *N) {
  2177. // Look through a bit convert.
  2178. while (N->getOpcode() == ISD::BITCAST)
  2179. N = N->getOperand(0).getNode();
  2180. if (ISD::isConstantSplatVectorAllZeros(N))
  2181. return true;
  2182. if (N->getOpcode() != AArch64ISD::DUP)
  2183. return false;
  2184. auto Opnd0 = N->getOperand(0);
  2185. auto *CINT = dyn_cast<ConstantSDNode>(Opnd0);
  2186. auto *CFP = dyn_cast<ConstantFPSDNode>(Opnd0);
  2187. return (CINT && CINT->isZero()) || (CFP && CFP->isZero());
  2188. }
  2189. /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
  2190. /// CC
  2191. static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
  2192. switch (CC) {
  2193. default:
  2194. llvm_unreachable("Unknown condition code!");
  2195. case ISD::SETNE:
  2196. return AArch64CC::NE;
  2197. case ISD::SETEQ:
  2198. return AArch64CC::EQ;
  2199. case ISD::SETGT:
  2200. return AArch64CC::GT;
  2201. case ISD::SETGE:
  2202. return AArch64CC::GE;
  2203. case ISD::SETLT:
  2204. return AArch64CC::LT;
  2205. case ISD::SETLE:
  2206. return AArch64CC::LE;
  2207. case ISD::SETUGT:
  2208. return AArch64CC::HI;
  2209. case ISD::SETUGE:
  2210. return AArch64CC::HS;
  2211. case ISD::SETULT:
  2212. return AArch64CC::LO;
  2213. case ISD::SETULE:
  2214. return AArch64CC::LS;
  2215. }
  2216. }
  2217. /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
  2218. static void changeFPCCToAArch64CC(ISD::CondCode CC,
  2219. AArch64CC::CondCode &CondCode,
  2220. AArch64CC::CondCode &CondCode2) {
  2221. CondCode2 = AArch64CC::AL;
  2222. switch (CC) {
  2223. default:
  2224. llvm_unreachable("Unknown FP condition!");
  2225. case ISD::SETEQ:
  2226. case ISD::SETOEQ:
  2227. CondCode = AArch64CC::EQ;
  2228. break;
  2229. case ISD::SETGT:
  2230. case ISD::SETOGT:
  2231. CondCode = AArch64CC::GT;
  2232. break;
  2233. case ISD::SETGE:
  2234. case ISD::SETOGE:
  2235. CondCode = AArch64CC::GE;
  2236. break;
  2237. case ISD::SETOLT:
  2238. CondCode = AArch64CC::MI;
  2239. break;
  2240. case ISD::SETOLE:
  2241. CondCode = AArch64CC::LS;
  2242. break;
  2243. case ISD::SETONE:
  2244. CondCode = AArch64CC::MI;
  2245. CondCode2 = AArch64CC::GT;
  2246. break;
  2247. case ISD::SETO:
  2248. CondCode = AArch64CC::VC;
  2249. break;
  2250. case ISD::SETUO:
  2251. CondCode = AArch64CC::VS;
  2252. break;
  2253. case ISD::SETUEQ:
  2254. CondCode = AArch64CC::EQ;
  2255. CondCode2 = AArch64CC::VS;
  2256. break;
  2257. case ISD::SETUGT:
  2258. CondCode = AArch64CC::HI;
  2259. break;
  2260. case ISD::SETUGE:
  2261. CondCode = AArch64CC::PL;
  2262. break;
  2263. case ISD::SETLT:
  2264. case ISD::SETULT:
  2265. CondCode = AArch64CC::LT;
  2266. break;
  2267. case ISD::SETLE:
  2268. case ISD::SETULE:
  2269. CondCode = AArch64CC::LE;
  2270. break;
  2271. case ISD::SETNE:
  2272. case ISD::SETUNE:
  2273. CondCode = AArch64CC::NE;
  2274. break;
  2275. }
  2276. }
  2277. /// Convert a DAG fp condition code to an AArch64 CC.
  2278. /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
  2279. /// should be AND'ed instead of OR'ed.
  2280. static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
  2281. AArch64CC::CondCode &CondCode,
  2282. AArch64CC::CondCode &CondCode2) {
  2283. CondCode2 = AArch64CC::AL;
  2284. switch (CC) {
  2285. default:
  2286. changeFPCCToAArch64CC(CC, CondCode, CondCode2);
  2287. assert(CondCode2 == AArch64CC::AL);
  2288. break;
  2289. case ISD::SETONE:
  2290. // (a one b)
  2291. // == ((a olt b) || (a ogt b))
  2292. // == ((a ord b) && (a une b))
  2293. CondCode = AArch64CC::VC;
  2294. CondCode2 = AArch64CC::NE;
  2295. break;
  2296. case ISD::SETUEQ:
  2297. // (a ueq b)
  2298. // == ((a uno b) || (a oeq b))
  2299. // == ((a ule b) && (a uge b))
  2300. CondCode = AArch64CC::PL;
  2301. CondCode2 = AArch64CC::LE;
  2302. break;
  2303. }
  2304. }
  2305. /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
  2306. /// CC usable with the vector instructions. Fewer operations are available
  2307. /// without a real NZCV register, so we have to use less efficient combinations
  2308. /// to get the same effect.
  2309. static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
  2310. AArch64CC::CondCode &CondCode,
  2311. AArch64CC::CondCode &CondCode2,
  2312. bool &Invert) {
  2313. Invert = false;
  2314. switch (CC) {
  2315. default:
  2316. // Mostly the scalar mappings work fine.
  2317. changeFPCCToAArch64CC(CC, CondCode, CondCode2);
  2318. break;
  2319. case ISD::SETUO:
  2320. Invert = true;
  2321. LLVM_FALLTHROUGH;
  2322. case ISD::SETO:
  2323. CondCode = AArch64CC::MI;
  2324. CondCode2 = AArch64CC::GE;
  2325. break;
  2326. case ISD::SETUEQ:
  2327. case ISD::SETULT:
  2328. case ISD::SETULE:
  2329. case ISD::SETUGT:
  2330. case ISD::SETUGE:
  2331. // All of the compare-mask comparisons are ordered, but we can switch
  2332. // between the two by a double inversion. E.g. ULE == !OGT.
  2333. Invert = true;
  2334. changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
  2335. CondCode, CondCode2);
  2336. break;
  2337. }
  2338. }
  2339. static bool isLegalArithImmed(uint64_t C) {
  2340. // Matches AArch64DAGToDAGISel::SelectArithImmed().
  2341. bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
  2342. LLVM_DEBUG(dbgs() << "Is imm " << C
  2343. << " legal: " << (IsLegal ? "yes\n" : "no\n"));
  2344. return IsLegal;
  2345. }
  2346. // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
  2347. // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
  2348. // can be set differently by this operation. It comes down to whether
  2349. // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
  2350. // everything is fine. If not then the optimization is wrong. Thus general
  2351. // comparisons are only valid if op2 != 0.
  2352. //
  2353. // So, finally, the only LLVM-native comparisons that don't mention C and V
  2354. // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
  2355. // the absence of information about op2.
  2356. static bool isCMN(SDValue Op, ISD::CondCode CC) {
  2357. return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
  2358. (CC == ISD::SETEQ || CC == ISD::SETNE);
  2359. }
  2360. static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
  2361. SelectionDAG &DAG, SDValue Chain,
  2362. bool IsSignaling) {
  2363. EVT VT = LHS.getValueType();
  2364. assert(VT != MVT::f128);
  2365. assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
  2366. unsigned Opcode =
  2367. IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
  2368. return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
  2369. }
  2370. static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
  2371. const SDLoc &dl, SelectionDAG &DAG) {
  2372. EVT VT = LHS.getValueType();
  2373. const bool FullFP16 =
  2374. static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
  2375. if (VT.isFloatingPoint()) {
  2376. assert(VT != MVT::f128);
  2377. if (VT == MVT::f16 && !FullFP16) {
  2378. LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
  2379. RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
  2380. VT = MVT::f32;
  2381. }
  2382. return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
  2383. }
  2384. // The CMP instruction is just an alias for SUBS, and representing it as
  2385. // SUBS means that it's possible to get CSE with subtract operations.
  2386. // A later phase can perform the optimization of setting the destination
  2387. // register to WZR/XZR if it ends up being unused.
  2388. unsigned Opcode = AArch64ISD::SUBS;
  2389. if (isCMN(RHS, CC)) {
  2390. // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
  2391. Opcode = AArch64ISD::ADDS;
  2392. RHS = RHS.getOperand(1);
  2393. } else if (isCMN(LHS, CC)) {
  2394. // As we are looking for EQ/NE compares, the operands can be commuted ; can
  2395. // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
  2396. Opcode = AArch64ISD::ADDS;
  2397. LHS = LHS.getOperand(1);
  2398. } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
  2399. if (LHS.getOpcode() == ISD::AND) {
  2400. // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
  2401. // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
  2402. // of the signed comparisons.
  2403. const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
  2404. DAG.getVTList(VT, MVT_CC),
  2405. LHS.getOperand(0),
  2406. LHS.getOperand(1));
  2407. // Replace all users of (and X, Y) with newly generated (ands X, Y)
  2408. DAG.ReplaceAllUsesWith(LHS, ANDSNode);
  2409. return ANDSNode.getValue(1);
  2410. } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
  2411. // Use result of ANDS
  2412. return LHS.getValue(1);
  2413. }
  2414. }
  2415. return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
  2416. .getValue(1);
  2417. }
  2418. /// \defgroup AArch64CCMP CMP;CCMP matching
  2419. ///
  2420. /// These functions deal with the formation of CMP;CCMP;... sequences.
  2421. /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
  2422. /// a comparison. They set the NZCV flags to a predefined value if their
  2423. /// predicate is false. This allows to express arbitrary conjunctions, for
  2424. /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
  2425. /// expressed as:
  2426. /// cmp A
  2427. /// ccmp B, inv(CB), CA
  2428. /// check for CB flags
  2429. ///
  2430. /// This naturally lets us implement chains of AND operations with SETCC
  2431. /// operands. And we can even implement some other situations by transforming
  2432. /// them:
  2433. /// - We can implement (NEG SETCC) i.e. negating a single comparison by
  2434. /// negating the flags used in a CCMP/FCCMP operations.
  2435. /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
  2436. /// by negating the flags we test for afterwards. i.e.
  2437. /// NEG (CMP CCMP CCCMP ...) can be implemented.
  2438. /// - Note that we can only ever negate all previously processed results.
  2439. /// What we can not implement by flipping the flags to test is a negation
  2440. /// of two sub-trees (because the negation affects all sub-trees emitted so
  2441. /// far, so the 2nd sub-tree we emit would also affect the first).
  2442. /// With those tools we can implement some OR operations:
  2443. /// - (OR (SETCC A) (SETCC B)) can be implemented via:
  2444. /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
  2445. /// - After transforming OR to NEG/AND combinations we may be able to use NEG
  2446. /// elimination rules from earlier to implement the whole thing as a
  2447. /// CCMP/FCCMP chain.
  2448. ///
  2449. /// As complete example:
  2450. /// or (or (setCA (cmp A)) (setCB (cmp B)))
  2451. /// (and (setCC (cmp C)) (setCD (cmp D)))"
  2452. /// can be reassociated to:
  2453. /// or (and (setCC (cmp C)) setCD (cmp D))
  2454. // (or (setCA (cmp A)) (setCB (cmp B)))
  2455. /// can be transformed to:
  2456. /// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
  2457. /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
  2458. /// which can be implemented as:
  2459. /// cmp C
  2460. /// ccmp D, inv(CD), CC
  2461. /// ccmp A, CA, inv(CD)
  2462. /// ccmp B, CB, inv(CA)
  2463. /// check for CB flags
  2464. ///
  2465. /// A counterexample is "or (and A B) (and C D)" which translates to
  2466. /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
  2467. /// can only implement 1 of the inner (not) operations, but not both!
  2468. /// @{
  2469. /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
  2470. static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
  2471. ISD::CondCode CC, SDValue CCOp,
  2472. AArch64CC::CondCode Predicate,
  2473. AArch64CC::CondCode OutCC,
  2474. const SDLoc &DL, SelectionDAG &DAG) {
  2475. unsigned Opcode = 0;
  2476. const bool FullFP16 =
  2477. static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
  2478. if (LHS.getValueType().isFloatingPoint()) {
  2479. assert(LHS.getValueType() != MVT::f128);
  2480. if (LHS.getValueType() == MVT::f16 && !FullFP16) {
  2481. LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
  2482. RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
  2483. }
  2484. Opcode = AArch64ISD::FCCMP;
  2485. } else if (RHS.getOpcode() == ISD::SUB) {
  2486. SDValue SubOp0 = RHS.getOperand(0);
  2487. if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
  2488. // See emitComparison() on why we can only do this for SETEQ and SETNE.
  2489. Opcode = AArch64ISD::CCMN;
  2490. RHS = RHS.getOperand(1);
  2491. }
  2492. }
  2493. if (Opcode == 0)
  2494. Opcode = AArch64ISD::CCMP;
  2495. SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
  2496. AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
  2497. unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
  2498. SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
  2499. return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
  2500. }
  2501. /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
  2502. /// expressed as a conjunction. See \ref AArch64CCMP.
  2503. /// \param CanNegate Set to true if we can negate the whole sub-tree just by
  2504. /// changing the conditions on the SETCC tests.
  2505. /// (this means we can call emitConjunctionRec() with
  2506. /// Negate==true on this sub-tree)
  2507. /// \param MustBeFirst Set to true if this subtree needs to be negated and we
  2508. /// cannot do the negation naturally. We are required to
  2509. /// emit the subtree first in this case.
  2510. /// \param WillNegate Is true if are called when the result of this
  2511. /// subexpression must be negated. This happens when the
  2512. /// outer expression is an OR. We can use this fact to know
  2513. /// that we have a double negation (or (or ...) ...) that
  2514. /// can be implemented for free.
  2515. static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
  2516. bool &MustBeFirst, bool WillNegate,
  2517. unsigned Depth = 0) {
  2518. if (!Val.hasOneUse())
  2519. return false;
  2520. unsigned Opcode = Val->getOpcode();
  2521. if (Opcode == ISD::SETCC) {
  2522. if (Val->getOperand(0).getValueType() == MVT::f128)
  2523. return false;
  2524. CanNegate = true;
  2525. MustBeFirst = false;
  2526. return true;
  2527. }
  2528. // Protect against exponential runtime and stack overflow.
  2529. if (Depth > 6)
  2530. return false;
  2531. if (Opcode == ISD::AND || Opcode == ISD::OR) {
  2532. bool IsOR = Opcode == ISD::OR;
  2533. SDValue O0 = Val->getOperand(0);
  2534. SDValue O1 = Val->getOperand(1);
  2535. bool CanNegateL;
  2536. bool MustBeFirstL;
  2537. if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
  2538. return false;
  2539. bool CanNegateR;
  2540. bool MustBeFirstR;
  2541. if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
  2542. return false;
  2543. if (MustBeFirstL && MustBeFirstR)
  2544. return false;
  2545. if (IsOR) {
  2546. // For an OR expression we need to be able to naturally negate at least
  2547. // one side or we cannot do the transformation at all.
  2548. if (!CanNegateL && !CanNegateR)
  2549. return false;
  2550. // If we the result of the OR will be negated and we can naturally negate
  2551. // the leafs, then this sub-tree as a whole negates naturally.
  2552. CanNegate = WillNegate && CanNegateL && CanNegateR;
  2553. // If we cannot naturally negate the whole sub-tree, then this must be
  2554. // emitted first.
  2555. MustBeFirst = !CanNegate;
  2556. } else {
  2557. assert(Opcode == ISD::AND && "Must be OR or AND");
  2558. // We cannot naturally negate an AND operation.
  2559. CanNegate = false;
  2560. MustBeFirst = MustBeFirstL || MustBeFirstR;
  2561. }
  2562. return true;
  2563. }
  2564. return false;
  2565. }
  2566. /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
  2567. /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
  2568. /// Tries to transform the given i1 producing node @p Val to a series compare
  2569. /// and conditional compare operations. @returns an NZCV flags producing node
  2570. /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
  2571. /// transformation was not possible.
  2572. /// \p Negate is true if we want this sub-tree being negated just by changing
  2573. /// SETCC conditions.
  2574. static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
  2575. AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
  2576. AArch64CC::CondCode Predicate) {
  2577. // We're at a tree leaf, produce a conditional comparison operation.
  2578. unsigned Opcode = Val->getOpcode();
  2579. if (Opcode == ISD::SETCC) {
  2580. SDValue LHS = Val->getOperand(0);
  2581. SDValue RHS = Val->getOperand(1);
  2582. ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
  2583. bool isInteger = LHS.getValueType().isInteger();
  2584. if (Negate)
  2585. CC = getSetCCInverse(CC, LHS.getValueType());
  2586. SDLoc DL(Val);
  2587. // Determine OutCC and handle FP special case.
  2588. if (isInteger) {
  2589. OutCC = changeIntCCToAArch64CC(CC);
  2590. } else {
  2591. assert(LHS.getValueType().isFloatingPoint());
  2592. AArch64CC::CondCode ExtraCC;
  2593. changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
  2594. // Some floating point conditions can't be tested with a single condition
  2595. // code. Construct an additional comparison in this case.
  2596. if (ExtraCC != AArch64CC::AL) {
  2597. SDValue ExtraCmp;
  2598. if (!CCOp.getNode())
  2599. ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
  2600. else
  2601. ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
  2602. ExtraCC, DL, DAG);
  2603. CCOp = ExtraCmp;
  2604. Predicate = ExtraCC;
  2605. }
  2606. }
  2607. // Produce a normal comparison if we are first in the chain
  2608. if (!CCOp)
  2609. return emitComparison(LHS, RHS, CC, DL, DAG);
  2610. // Otherwise produce a ccmp.
  2611. return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
  2612. DAG);
  2613. }
  2614. assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
  2615. bool IsOR = Opcode == ISD::OR;
  2616. SDValue LHS = Val->getOperand(0);
  2617. bool CanNegateL;
  2618. bool MustBeFirstL;
  2619. bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
  2620. assert(ValidL && "Valid conjunction/disjunction tree");
  2621. (void)ValidL;
  2622. SDValue RHS = Val->getOperand(1);
  2623. bool CanNegateR;
  2624. bool MustBeFirstR;
  2625. bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
  2626. assert(ValidR && "Valid conjunction/disjunction tree");
  2627. (void)ValidR;
  2628. // Swap sub-tree that must come first to the right side.
  2629. if (MustBeFirstL) {
  2630. assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
  2631. std::swap(LHS, RHS);
  2632. std::swap(CanNegateL, CanNegateR);
  2633. std::swap(MustBeFirstL, MustBeFirstR);
  2634. }
  2635. bool NegateR;
  2636. bool NegateAfterR;
  2637. bool NegateL;
  2638. bool NegateAfterAll;
  2639. if (Opcode == ISD::OR) {
  2640. // Swap the sub-tree that we can negate naturally to the left.
  2641. if (!CanNegateL) {
  2642. assert(CanNegateR && "at least one side must be negatable");
  2643. assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
  2644. assert(!Negate);
  2645. std::swap(LHS, RHS);
  2646. NegateR = false;
  2647. NegateAfterR = true;
  2648. } else {
  2649. // Negate the left sub-tree if possible, otherwise negate the result.
  2650. NegateR = CanNegateR;
  2651. NegateAfterR = !CanNegateR;
  2652. }
  2653. NegateL = true;
  2654. NegateAfterAll = !Negate;
  2655. } else {
  2656. assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
  2657. assert(!Negate && "Valid conjunction/disjunction tree");
  2658. NegateL = false;
  2659. NegateR = false;
  2660. NegateAfterR = false;
  2661. NegateAfterAll = false;
  2662. }
  2663. // Emit sub-trees.
  2664. AArch64CC::CondCode RHSCC;
  2665. SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
  2666. if (NegateAfterR)
  2667. RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
  2668. SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
  2669. if (NegateAfterAll)
  2670. OutCC = AArch64CC::getInvertedCondCode(OutCC);
  2671. return CmpL;
  2672. }
  2673. /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
  2674. /// In some cases this is even possible with OR operations in the expression.
  2675. /// See \ref AArch64CCMP.
  2676. /// \see emitConjunctionRec().
  2677. static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
  2678. AArch64CC::CondCode &OutCC) {
  2679. bool DummyCanNegate;
  2680. bool DummyMustBeFirst;
  2681. if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
  2682. return SDValue();
  2683. return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
  2684. }
  2685. /// @}
  2686. /// Returns how profitable it is to fold a comparison's operand's shift and/or
  2687. /// extension operations.
  2688. static unsigned getCmpOperandFoldingProfit(SDValue Op) {
  2689. auto isSupportedExtend = [&](SDValue V) {
  2690. if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
  2691. return true;
  2692. if (V.getOpcode() == ISD::AND)
  2693. if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
  2694. uint64_t Mask = MaskCst->getZExtValue();
  2695. return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
  2696. }
  2697. return false;
  2698. };
  2699. if (!Op.hasOneUse())
  2700. return 0;
  2701. if (isSupportedExtend(Op))
  2702. return 1;
  2703. unsigned Opc = Op.getOpcode();
  2704. if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
  2705. if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
  2706. uint64_t Shift = ShiftCst->getZExtValue();
  2707. if (isSupportedExtend(Op.getOperand(0)))
  2708. return (Shift <= 4) ? 2 : 1;
  2709. EVT VT = Op.getValueType();
  2710. if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
  2711. return 1;
  2712. }
  2713. return 0;
  2714. }
  2715. static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
  2716. SDValue &AArch64cc, SelectionDAG &DAG,
  2717. const SDLoc &dl) {
  2718. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
  2719. EVT VT = RHS.getValueType();
  2720. uint64_t C = RHSC->getZExtValue();
  2721. if (!isLegalArithImmed(C)) {
  2722. // Constant does not fit, try adjusting it by one?
  2723. switch (CC) {
  2724. default:
  2725. break;
  2726. case ISD::SETLT:
  2727. case ISD::SETGE:
  2728. if ((VT == MVT::i32 && C != 0x80000000 &&
  2729. isLegalArithImmed((uint32_t)(C - 1))) ||
  2730. (VT == MVT::i64 && C != 0x80000000ULL &&
  2731. isLegalArithImmed(C - 1ULL))) {
  2732. CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
  2733. C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
  2734. RHS = DAG.getConstant(C, dl, VT);
  2735. }
  2736. break;
  2737. case ISD::SETULT:
  2738. case ISD::SETUGE:
  2739. if ((VT == MVT::i32 && C != 0 &&
  2740. isLegalArithImmed((uint32_t)(C - 1))) ||
  2741. (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
  2742. CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
  2743. C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
  2744. RHS = DAG.getConstant(C, dl, VT);
  2745. }
  2746. break;
  2747. case ISD::SETLE:
  2748. case ISD::SETGT:
  2749. if ((VT == MVT::i32 && C != INT32_MAX &&
  2750. isLegalArithImmed((uint32_t)(C + 1))) ||
  2751. (VT == MVT::i64 && C != INT64_MAX &&
  2752. isLegalArithImmed(C + 1ULL))) {
  2753. CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
  2754. C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
  2755. RHS = DAG.getConstant(C, dl, VT);
  2756. }
  2757. break;
  2758. case ISD::SETULE:
  2759. case ISD::SETUGT:
  2760. if ((VT == MVT::i32 && C != UINT32_MAX &&
  2761. isLegalArithImmed((uint32_t)(C + 1))) ||
  2762. (VT == MVT::i64 && C != UINT64_MAX &&
  2763. isLegalArithImmed(C + 1ULL))) {
  2764. CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
  2765. C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
  2766. RHS = DAG.getConstant(C, dl, VT);
  2767. }
  2768. break;
  2769. }
  2770. }
  2771. }
  2772. // Comparisons are canonicalized so that the RHS operand is simpler than the
  2773. // LHS one, the extreme case being when RHS is an immediate. However, AArch64
  2774. // can fold some shift+extend operations on the RHS operand, so swap the
  2775. // operands if that can be done.
  2776. //
  2777. // For example:
  2778. // lsl w13, w11, #1
  2779. // cmp w13, w12
  2780. // can be turned into:
  2781. // cmp w12, w11, lsl #1
  2782. if (!isa<ConstantSDNode>(RHS) ||
  2783. !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
  2784. SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
  2785. if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
  2786. std::swap(LHS, RHS);
  2787. CC = ISD::getSetCCSwappedOperands(CC);
  2788. }
  2789. }
  2790. SDValue Cmp;
  2791. AArch64CC::CondCode AArch64CC;
  2792. if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
  2793. const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
  2794. // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
  2795. // For the i8 operand, the largest immediate is 255, so this can be easily
  2796. // encoded in the compare instruction. For the i16 operand, however, the
  2797. // largest immediate cannot be encoded in the compare.
  2798. // Therefore, use a sign extending load and cmn to avoid materializing the
  2799. // -1 constant. For example,
  2800. // movz w1, #65535
  2801. // ldrh w0, [x0, #0]
  2802. // cmp w0, w1
  2803. // >
  2804. // ldrsh w0, [x0, #0]
  2805. // cmn w0, #1
  2806. // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
  2807. // if and only if (sext LHS) == (sext RHS). The checks are in place to
  2808. // ensure both the LHS and RHS are truly zero extended and to make sure the
  2809. // transformation is profitable.
  2810. if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
  2811. cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
  2812. cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
  2813. LHS.getNode()->hasNUsesOfValue(1, 0)) {
  2814. int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
  2815. if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
  2816. SDValue SExt =
  2817. DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
  2818. DAG.getValueType(MVT::i16));
  2819. Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
  2820. RHS.getValueType()),
  2821. CC, dl, DAG);
  2822. AArch64CC = changeIntCCToAArch64CC(CC);
  2823. }
  2824. }
  2825. if (!Cmp && (RHSC->isZero() || RHSC->isOne())) {
  2826. if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
  2827. if ((CC == ISD::SETNE) ^ RHSC->isZero())
  2828. AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
  2829. }
  2830. }
  2831. }
  2832. if (!Cmp) {
  2833. Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
  2834. AArch64CC = changeIntCCToAArch64CC(CC);
  2835. }
  2836. AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
  2837. return Cmp;
  2838. }
  2839. static std::pair<SDValue, SDValue>
  2840. getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
  2841. assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
  2842. "Unsupported value type");
  2843. SDValue Value, Overflow;
  2844. SDLoc DL(Op);
  2845. SDValue LHS = Op.getOperand(0);
  2846. SDValue RHS = Op.getOperand(1);
  2847. unsigned Opc = 0;
  2848. switch (Op.getOpcode()) {
  2849. default:
  2850. llvm_unreachable("Unknown overflow instruction!");
  2851. case ISD::SADDO:
  2852. Opc = AArch64ISD::ADDS;
  2853. CC = AArch64CC::VS;
  2854. break;
  2855. case ISD::UADDO:
  2856. Opc = AArch64ISD::ADDS;
  2857. CC = AArch64CC::HS;
  2858. break;
  2859. case ISD::SSUBO:
  2860. Opc = AArch64ISD::SUBS;
  2861. CC = AArch64CC::VS;
  2862. break;
  2863. case ISD::USUBO:
  2864. Opc = AArch64ISD::SUBS;
  2865. CC = AArch64CC::LO;
  2866. break;
  2867. // Multiply needs a little bit extra work.
  2868. case ISD::SMULO:
  2869. case ISD::UMULO: {
  2870. CC = AArch64CC::NE;
  2871. bool IsSigned = Op.getOpcode() == ISD::SMULO;
  2872. if (Op.getValueType() == MVT::i32) {
  2873. // Extend to 64-bits, then perform a 64-bit multiply.
  2874. unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  2875. LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
  2876. RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
  2877. SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
  2878. Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Mul);
  2879. // Check that the result fits into a 32-bit integer.
  2880. SDVTList VTs = DAG.getVTList(MVT::i64, MVT_CC);
  2881. if (IsSigned) {
  2882. // cmp xreg, wreg, sxtw
  2883. SDValue SExtMul = DAG.getNode(ISD::SIGN_EXTEND, DL, MVT::i64, Value);
  2884. Overflow =
  2885. DAG.getNode(AArch64ISD::SUBS, DL, VTs, Mul, SExtMul).getValue(1);
  2886. } else {
  2887. // tst xreg, #0xffffffff00000000
  2888. SDValue UpperBits = DAG.getConstant(0xFFFFFFFF00000000, DL, MVT::i64);
  2889. Overflow =
  2890. DAG.getNode(AArch64ISD::ANDS, DL, VTs, Mul, UpperBits).getValue(1);
  2891. }
  2892. break;
  2893. }
  2894. assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
  2895. // For the 64 bit multiply
  2896. Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
  2897. if (IsSigned) {
  2898. SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
  2899. SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
  2900. DAG.getConstant(63, DL, MVT::i64));
  2901. // It is important that LowerBits is last, otherwise the arithmetic
  2902. // shift will not be folded into the compare (SUBS).
  2903. SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
  2904. Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
  2905. .getValue(1);
  2906. } else {
  2907. SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
  2908. SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
  2909. Overflow =
  2910. DAG.getNode(AArch64ISD::SUBS, DL, VTs,
  2911. DAG.getConstant(0, DL, MVT::i64),
  2912. UpperBits).getValue(1);
  2913. }
  2914. break;
  2915. }
  2916. } // switch (...)
  2917. if (Opc) {
  2918. SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
  2919. // Emit the AArch64 operation with overflow check.
  2920. Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
  2921. Overflow = Value.getValue(1);
  2922. }
  2923. return std::make_pair(Value, Overflow);
  2924. }
  2925. SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const {
  2926. if (useSVEForFixedLengthVectorVT(Op.getValueType()))
  2927. return LowerToScalableOp(Op, DAG);
  2928. SDValue Sel = Op.getOperand(0);
  2929. SDValue Other = Op.getOperand(1);
  2930. SDLoc dl(Sel);
  2931. // If the operand is an overflow checking operation, invert the condition
  2932. // code and kill the Not operation. I.e., transform:
  2933. // (xor (overflow_op_bool, 1))
  2934. // -->
  2935. // (csel 1, 0, invert(cc), overflow_op_bool)
  2936. // ... which later gets transformed to just a cset instruction with an
  2937. // inverted condition code, rather than a cset + eor sequence.
  2938. if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
  2939. // Only lower legal XALUO ops.
  2940. if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
  2941. return SDValue();
  2942. SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
  2943. SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
  2944. AArch64CC::CondCode CC;
  2945. SDValue Value, Overflow;
  2946. std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
  2947. SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
  2948. return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
  2949. CCVal, Overflow);
  2950. }
  2951. // If neither operand is a SELECT_CC, give up.
  2952. if (Sel.getOpcode() != ISD::SELECT_CC)
  2953. std::swap(Sel, Other);
  2954. if (Sel.getOpcode() != ISD::SELECT_CC)
  2955. return Op;
  2956. // The folding we want to perform is:
  2957. // (xor x, (select_cc a, b, cc, 0, -1) )
  2958. // -->
  2959. // (csel x, (xor x, -1), cc ...)
  2960. //
  2961. // The latter will get matched to a CSINV instruction.
  2962. ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
  2963. SDValue LHS = Sel.getOperand(0);
  2964. SDValue RHS = Sel.getOperand(1);
  2965. SDValue TVal = Sel.getOperand(2);
  2966. SDValue FVal = Sel.getOperand(3);
  2967. // FIXME: This could be generalized to non-integer comparisons.
  2968. if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
  2969. return Op;
  2970. ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
  2971. ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
  2972. // The values aren't constants, this isn't the pattern we're looking for.
  2973. if (!CFVal || !CTVal)
  2974. return Op;
  2975. // We can commute the SELECT_CC by inverting the condition. This
  2976. // might be needed to make this fit into a CSINV pattern.
  2977. if (CTVal->isAllOnes() && CFVal->isZero()) {
  2978. std::swap(TVal, FVal);
  2979. std::swap(CTVal, CFVal);
  2980. CC = ISD::getSetCCInverse(CC, LHS.getValueType());
  2981. }
  2982. // If the constants line up, perform the transform!
  2983. if (CTVal->isZero() && CFVal->isAllOnes()) {
  2984. SDValue CCVal;
  2985. SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
  2986. FVal = Other;
  2987. TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
  2988. DAG.getConstant(-1ULL, dl, Other.getValueType()));
  2989. return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
  2990. CCVal, Cmp);
  2991. }
  2992. return Op;
  2993. }
  2994. static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
  2995. EVT VT = Op.getValueType();
  2996. // Let legalize expand this if it isn't a legal type yet.
  2997. if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
  2998. return SDValue();
  2999. SDVTList VTs = DAG.getVTList(VT, MVT::i32);
  3000. unsigned Opc;
  3001. bool ExtraOp = false;
  3002. switch (Op.getOpcode()) {
  3003. default:
  3004. llvm_unreachable("Invalid code");
  3005. case ISD::ADDC:
  3006. Opc = AArch64ISD::ADDS;
  3007. break;
  3008. case ISD::SUBC:
  3009. Opc = AArch64ISD::SUBS;
  3010. break;
  3011. case ISD::ADDE:
  3012. Opc = AArch64ISD::ADCS;
  3013. ExtraOp = true;
  3014. break;
  3015. case ISD::SUBE:
  3016. Opc = AArch64ISD::SBCS;
  3017. ExtraOp = true;
  3018. break;
  3019. }
  3020. if (!ExtraOp)
  3021. return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
  3022. return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
  3023. Op.getOperand(2));
  3024. }
  3025. static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
  3026. // Let legalize expand this if it isn't a legal type yet.
  3027. if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
  3028. return SDValue();
  3029. SDLoc dl(Op);
  3030. AArch64CC::CondCode CC;
  3031. // The actual operation that sets the overflow or carry flag.
  3032. SDValue Value, Overflow;
  3033. std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
  3034. // We use 0 and 1 as false and true values.
  3035. SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
  3036. SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
  3037. // We use an inverted condition, because the conditional select is inverted
  3038. // too. This will allow it to be selected to a single instruction:
  3039. // CSINC Wd, WZR, WZR, invert(cond).
  3040. SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
  3041. Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
  3042. CCVal, Overflow);
  3043. SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
  3044. return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
  3045. }
  3046. // Prefetch operands are:
  3047. // 1: Address to prefetch
  3048. // 2: bool isWrite
  3049. // 3: int locality (0 = no locality ... 3 = extreme locality)
  3050. // 4: bool isDataCache
  3051. static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
  3052. SDLoc DL(Op);
  3053. unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
  3054. unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
  3055. unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
  3056. bool IsStream = !Locality;
  3057. // When the locality number is set
  3058. if (Locality) {
  3059. // The front-end should have filtered out the out-of-range values
  3060. assert(Locality <= 3 && "Prefetch locality out-of-range");
  3061. // The locality degree is the opposite of the cache speed.
  3062. // Put the number the other way around.
  3063. // The encoding starts at 0 for level 1
  3064. Locality = 3 - Locality;
  3065. }
  3066. // built the mask value encoding the expected behavior.
  3067. unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
  3068. (!IsData << 3) | // IsDataCache bit
  3069. (Locality << 1) | // Cache level bits
  3070. (unsigned)IsStream; // Stream bit
  3071. return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
  3072. DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
  3073. }
  3074. SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
  3075. SelectionDAG &DAG) const {
  3076. EVT VT = Op.getValueType();
  3077. if (VT.isScalableVector())
  3078. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_EXTEND_MERGE_PASSTHRU);
  3079. if (useSVEForFixedLengthVectorVT(VT))
  3080. return LowerFixedLengthFPExtendToSVE(Op, DAG);
  3081. assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
  3082. return SDValue();
  3083. }
  3084. SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
  3085. SelectionDAG &DAG) const {
  3086. if (Op.getValueType().isScalableVector())
  3087. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_ROUND_MERGE_PASSTHRU);
  3088. bool IsStrict = Op->isStrictFPOpcode();
  3089. SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
  3090. EVT SrcVT = SrcVal.getValueType();
  3091. if (useSVEForFixedLengthVectorVT(SrcVT))
  3092. return LowerFixedLengthFPRoundToSVE(Op, DAG);
  3093. if (SrcVT != MVT::f128) {
  3094. // Expand cases where the input is a vector bigger than NEON.
  3095. if (useSVEForFixedLengthVectorVT(SrcVT))
  3096. return SDValue();
  3097. // It's legal except when f128 is involved
  3098. return Op;
  3099. }
  3100. return SDValue();
  3101. }
  3102. SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
  3103. SelectionDAG &DAG) const {
  3104. // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
  3105. // Any additional optimization in this function should be recorded
  3106. // in the cost tables.
  3107. EVT InVT = Op.getOperand(0).getValueType();
  3108. EVT VT = Op.getValueType();
  3109. if (VT.isScalableVector()) {
  3110. unsigned Opcode = Op.getOpcode() == ISD::FP_TO_UINT
  3111. ? AArch64ISD::FCVTZU_MERGE_PASSTHRU
  3112. : AArch64ISD::FCVTZS_MERGE_PASSTHRU;
  3113. return LowerToPredicatedOp(Op, DAG, Opcode);
  3114. }
  3115. if (useSVEForFixedLengthVectorVT(VT) || useSVEForFixedLengthVectorVT(InVT))
  3116. return LowerFixedLengthFPToIntToSVE(Op, DAG);
  3117. unsigned NumElts = InVT.getVectorNumElements();
  3118. // f16 conversions are promoted to f32 when full fp16 is not supported.
  3119. if (InVT.getVectorElementType() == MVT::f16 &&
  3120. !Subtarget->hasFullFP16()) {
  3121. MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
  3122. SDLoc dl(Op);
  3123. return DAG.getNode(
  3124. Op.getOpcode(), dl, Op.getValueType(),
  3125. DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
  3126. }
  3127. uint64_t VTSize = VT.getFixedSizeInBits();
  3128. uint64_t InVTSize = InVT.getFixedSizeInBits();
  3129. if (VTSize < InVTSize) {
  3130. SDLoc dl(Op);
  3131. SDValue Cv =
  3132. DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
  3133. Op.getOperand(0));
  3134. return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
  3135. }
  3136. if (VTSize > InVTSize) {
  3137. SDLoc dl(Op);
  3138. MVT ExtVT =
  3139. MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
  3140. VT.getVectorNumElements());
  3141. SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
  3142. return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
  3143. }
  3144. // Type changing conversions are illegal.
  3145. return Op;
  3146. }
  3147. SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
  3148. SelectionDAG &DAG) const {
  3149. bool IsStrict = Op->isStrictFPOpcode();
  3150. SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
  3151. if (SrcVal.getValueType().isVector())
  3152. return LowerVectorFP_TO_INT(Op, DAG);
  3153. // f16 conversions are promoted to f32 when full fp16 is not supported.
  3154. if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
  3155. assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
  3156. SDLoc dl(Op);
  3157. return DAG.getNode(
  3158. Op.getOpcode(), dl, Op.getValueType(),
  3159. DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
  3160. }
  3161. if (SrcVal.getValueType() != MVT::f128) {
  3162. // It's legal except when f128 is involved
  3163. return Op;
  3164. }
  3165. return SDValue();
  3166. }
  3167. SDValue
  3168. AArch64TargetLowering::LowerVectorFP_TO_INT_SAT(SDValue Op,
  3169. SelectionDAG &DAG) const {
  3170. // AArch64 FP-to-int conversions saturate to the destination element size, so
  3171. // we can lower common saturating conversions to simple instructions.
  3172. SDValue SrcVal = Op.getOperand(0);
  3173. EVT SrcVT = SrcVal.getValueType();
  3174. EVT DstVT = Op.getValueType();
  3175. EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  3176. uint64_t SrcElementWidth = SrcVT.getScalarSizeInBits();
  3177. uint64_t DstElementWidth = DstVT.getScalarSizeInBits();
  3178. uint64_t SatWidth = SatVT.getScalarSizeInBits();
  3179. assert(SatWidth <= DstElementWidth &&
  3180. "Saturation width cannot exceed result width");
  3181. // TODO: Consider lowering to SVE operations, as in LowerVectorFP_TO_INT.
  3182. // Currently, the `llvm.fpto[su]i.sat.*` instrinsics don't accept scalable
  3183. // types, so this is hard to reach.
  3184. if (DstVT.isScalableVector())
  3185. return SDValue();
  3186. EVT SrcElementVT = SrcVT.getVectorElementType();
  3187. // In the absence of FP16 support, promote f16 to f32 and saturate the result.
  3188. if (SrcElementVT == MVT::f16 &&
  3189. (!Subtarget->hasFullFP16() || DstElementWidth > 16)) {
  3190. MVT F32VT = MVT::getVectorVT(MVT::f32, SrcVT.getVectorNumElements());
  3191. SrcVal = DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), F32VT, SrcVal);
  3192. SrcVT = F32VT;
  3193. SrcElementVT = MVT::f32;
  3194. SrcElementWidth = 32;
  3195. } else if (SrcElementVT != MVT::f64 && SrcElementVT != MVT::f32 &&
  3196. SrcElementVT != MVT::f16)
  3197. return SDValue();
  3198. SDLoc DL(Op);
  3199. // Cases that we can emit directly.
  3200. if (SrcElementWidth == DstElementWidth && SrcElementWidth == SatWidth)
  3201. return DAG.getNode(Op.getOpcode(), DL, DstVT, SrcVal,
  3202. DAG.getValueType(DstVT.getScalarType()));
  3203. // Otherwise we emit a cvt that saturates to a higher BW, and saturate the
  3204. // result. This is only valid if the legal cvt is larger than the saturate
  3205. // width. For double, as we don't have MIN/MAX, it can be simpler to scalarize
  3206. // (at least until sqxtn is selected).
  3207. if (SrcElementWidth < SatWidth || SrcElementVT == MVT::f64)
  3208. return SDValue();
  3209. EVT IntVT = SrcVT.changeVectorElementTypeToInteger();
  3210. SDValue NativeCvt = DAG.getNode(Op.getOpcode(), DL, IntVT, SrcVal,
  3211. DAG.getValueType(IntVT.getScalarType()));
  3212. SDValue Sat;
  3213. if (Op.getOpcode() == ISD::FP_TO_SINT_SAT) {
  3214. SDValue MinC = DAG.getConstant(
  3215. APInt::getSignedMaxValue(SatWidth).sextOrSelf(SrcElementWidth), DL,
  3216. IntVT);
  3217. SDValue Min = DAG.getNode(ISD::SMIN, DL, IntVT, NativeCvt, MinC);
  3218. SDValue MaxC = DAG.getConstant(
  3219. APInt::getSignedMinValue(SatWidth).sextOrSelf(SrcElementWidth), DL,
  3220. IntVT);
  3221. Sat = DAG.getNode(ISD::SMAX, DL, IntVT, Min, MaxC);
  3222. } else {
  3223. SDValue MinC = DAG.getConstant(
  3224. APInt::getAllOnesValue(SatWidth).zextOrSelf(SrcElementWidth), DL,
  3225. IntVT);
  3226. Sat = DAG.getNode(ISD::UMIN, DL, IntVT, NativeCvt, MinC);
  3227. }
  3228. return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Sat);
  3229. }
  3230. SDValue AArch64TargetLowering::LowerFP_TO_INT_SAT(SDValue Op,
  3231. SelectionDAG &DAG) const {
  3232. // AArch64 FP-to-int conversions saturate to the destination register size, so
  3233. // we can lower common saturating conversions to simple instructions.
  3234. SDValue SrcVal = Op.getOperand(0);
  3235. EVT SrcVT = SrcVal.getValueType();
  3236. if (SrcVT.isVector())
  3237. return LowerVectorFP_TO_INT_SAT(Op, DAG);
  3238. EVT DstVT = Op.getValueType();
  3239. EVT SatVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  3240. uint64_t SatWidth = SatVT.getScalarSizeInBits();
  3241. uint64_t DstWidth = DstVT.getScalarSizeInBits();
  3242. assert(SatWidth <= DstWidth && "Saturation width cannot exceed result width");
  3243. // In the absence of FP16 support, promote f16 to f32 and saturate the result.
  3244. if (SrcVT == MVT::f16 && !Subtarget->hasFullFP16()) {
  3245. SrcVal = DAG.getNode(ISD::FP_EXTEND, SDLoc(Op), MVT::f32, SrcVal);
  3246. SrcVT = MVT::f32;
  3247. } else if (SrcVT != MVT::f64 && SrcVT != MVT::f32 && SrcVT != MVT::f16)
  3248. return SDValue();
  3249. SDLoc DL(Op);
  3250. // Cases that we can emit directly.
  3251. if ((SrcVT == MVT::f64 || SrcVT == MVT::f32 ||
  3252. (SrcVT == MVT::f16 && Subtarget->hasFullFP16())) &&
  3253. DstVT == SatVT && (DstVT == MVT::i64 || DstVT == MVT::i32))
  3254. return DAG.getNode(Op.getOpcode(), DL, DstVT, SrcVal,
  3255. DAG.getValueType(DstVT));
  3256. // Otherwise we emit a cvt that saturates to a higher BW, and saturate the
  3257. // result. This is only valid if the legal cvt is larger than the saturate
  3258. // width.
  3259. if (DstWidth < SatWidth)
  3260. return SDValue();
  3261. SDValue NativeCvt =
  3262. DAG.getNode(Op.getOpcode(), DL, DstVT, SrcVal, DAG.getValueType(DstVT));
  3263. SDValue Sat;
  3264. if (Op.getOpcode() == ISD::FP_TO_SINT_SAT) {
  3265. SDValue MinC = DAG.getConstant(
  3266. APInt::getSignedMaxValue(SatWidth).sextOrSelf(DstWidth), DL, DstVT);
  3267. SDValue Min = DAG.getNode(ISD::SMIN, DL, DstVT, NativeCvt, MinC);
  3268. SDValue MaxC = DAG.getConstant(
  3269. APInt::getSignedMinValue(SatWidth).sextOrSelf(DstWidth), DL, DstVT);
  3270. Sat = DAG.getNode(ISD::SMAX, DL, DstVT, Min, MaxC);
  3271. } else {
  3272. SDValue MinC = DAG.getConstant(
  3273. APInt::getAllOnesValue(SatWidth).zextOrSelf(DstWidth), DL, DstVT);
  3274. Sat = DAG.getNode(ISD::UMIN, DL, DstVT, NativeCvt, MinC);
  3275. }
  3276. return DAG.getNode(ISD::TRUNCATE, DL, DstVT, Sat);
  3277. }
  3278. SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op,
  3279. SelectionDAG &DAG) const {
  3280. // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
  3281. // Any additional optimization in this function should be recorded
  3282. // in the cost tables.
  3283. EVT VT = Op.getValueType();
  3284. SDLoc dl(Op);
  3285. SDValue In = Op.getOperand(0);
  3286. EVT InVT = In.getValueType();
  3287. unsigned Opc = Op.getOpcode();
  3288. bool IsSigned = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
  3289. if (VT.isScalableVector()) {
  3290. if (InVT.getVectorElementType() == MVT::i1) {
  3291. // We can't directly extend an SVE predicate; extend it first.
  3292. unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  3293. EVT CastVT = getPromotedVTForPredicate(InVT);
  3294. In = DAG.getNode(CastOpc, dl, CastVT, In);
  3295. return DAG.getNode(Opc, dl, VT, In);
  3296. }
  3297. unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU
  3298. : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU;
  3299. return LowerToPredicatedOp(Op, DAG, Opcode);
  3300. }
  3301. if (useSVEForFixedLengthVectorVT(VT) || useSVEForFixedLengthVectorVT(InVT))
  3302. return LowerFixedLengthIntToFPToSVE(Op, DAG);
  3303. uint64_t VTSize = VT.getFixedSizeInBits();
  3304. uint64_t InVTSize = InVT.getFixedSizeInBits();
  3305. if (VTSize < InVTSize) {
  3306. MVT CastVT =
  3307. MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
  3308. InVT.getVectorNumElements());
  3309. In = DAG.getNode(Opc, dl, CastVT, In);
  3310. return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
  3311. }
  3312. if (VTSize > InVTSize) {
  3313. unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  3314. EVT CastVT = VT.changeVectorElementTypeToInteger();
  3315. In = DAG.getNode(CastOpc, dl, CastVT, In);
  3316. return DAG.getNode(Opc, dl, VT, In);
  3317. }
  3318. return Op;
  3319. }
  3320. SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
  3321. SelectionDAG &DAG) const {
  3322. if (Op.getValueType().isVector())
  3323. return LowerVectorINT_TO_FP(Op, DAG);
  3324. bool IsStrict = Op->isStrictFPOpcode();
  3325. SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
  3326. // f16 conversions are promoted to f32 when full fp16 is not supported.
  3327. if (Op.getValueType() == MVT::f16 &&
  3328. !Subtarget->hasFullFP16()) {
  3329. assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
  3330. SDLoc dl(Op);
  3331. return DAG.getNode(
  3332. ISD::FP_ROUND, dl, MVT::f16,
  3333. DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
  3334. DAG.getIntPtrConstant(0, dl));
  3335. }
  3336. // i128 conversions are libcalls.
  3337. if (SrcVal.getValueType() == MVT::i128)
  3338. return SDValue();
  3339. // Other conversions are legal, unless it's to the completely software-based
  3340. // fp128.
  3341. if (Op.getValueType() != MVT::f128)
  3342. return Op;
  3343. return SDValue();
  3344. }
  3345. SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
  3346. SelectionDAG &DAG) const {
  3347. // For iOS, we want to call an alternative entry point: __sincos_stret,
  3348. // which returns the values in two S / D registers.
  3349. SDLoc dl(Op);
  3350. SDValue Arg = Op.getOperand(0);
  3351. EVT ArgVT = Arg.getValueType();
  3352. Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
  3353. ArgListTy Args;
  3354. ArgListEntry Entry;
  3355. Entry.Node = Arg;
  3356. Entry.Ty = ArgTy;
  3357. Entry.IsSExt = false;
  3358. Entry.IsZExt = false;
  3359. Args.push_back(Entry);
  3360. RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
  3361. : RTLIB::SINCOS_STRET_F32;
  3362. const char *LibcallName = getLibcallName(LC);
  3363. SDValue Callee =
  3364. DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
  3365. StructType *RetTy = StructType::get(ArgTy, ArgTy);
  3366. TargetLowering::CallLoweringInfo CLI(DAG);
  3367. CLI.setDebugLoc(dl)
  3368. .setChain(DAG.getEntryNode())
  3369. .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
  3370. std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
  3371. return CallResult.first;
  3372. }
  3373. static MVT getSVEContainerType(EVT ContentTy);
  3374. SDValue AArch64TargetLowering::LowerBITCAST(SDValue Op,
  3375. SelectionDAG &DAG) const {
  3376. EVT OpVT = Op.getValueType();
  3377. EVT ArgVT = Op.getOperand(0).getValueType();
  3378. if (useSVEForFixedLengthVectorVT(OpVT))
  3379. return LowerFixedLengthBitcastToSVE(Op, DAG);
  3380. if (OpVT.isScalableVector()) {
  3381. if (isTypeLegal(OpVT) && !isTypeLegal(ArgVT)) {
  3382. assert(OpVT.isFloatingPoint() && !ArgVT.isFloatingPoint() &&
  3383. "Expected int->fp bitcast!");
  3384. SDValue ExtResult =
  3385. DAG.getNode(ISD::ANY_EXTEND, SDLoc(Op), getSVEContainerType(ArgVT),
  3386. Op.getOperand(0));
  3387. return getSVESafeBitCast(OpVT, ExtResult, DAG);
  3388. }
  3389. return getSVESafeBitCast(OpVT, Op.getOperand(0), DAG);
  3390. }
  3391. if (OpVT != MVT::f16 && OpVT != MVT::bf16)
  3392. return SDValue();
  3393. // Bitcasts between f16 and bf16 are legal.
  3394. if (ArgVT == MVT::f16 || ArgVT == MVT::bf16)
  3395. return Op;
  3396. assert(ArgVT == MVT::i16);
  3397. SDLoc DL(Op);
  3398. Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
  3399. Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
  3400. return SDValue(
  3401. DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
  3402. DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
  3403. 0);
  3404. }
  3405. static EVT getExtensionTo64Bits(const EVT &OrigVT) {
  3406. if (OrigVT.getSizeInBits() >= 64)
  3407. return OrigVT;
  3408. assert(OrigVT.isSimple() && "Expecting a simple value type");
  3409. MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
  3410. switch (OrigSimpleTy) {
  3411. default: llvm_unreachable("Unexpected Vector Type");
  3412. case MVT::v2i8:
  3413. case MVT::v2i16:
  3414. return MVT::v2i32;
  3415. case MVT::v4i8:
  3416. return MVT::v4i16;
  3417. }
  3418. }
  3419. static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
  3420. const EVT &OrigTy,
  3421. const EVT &ExtTy,
  3422. unsigned ExtOpcode) {
  3423. // The vector originally had a size of OrigTy. It was then extended to ExtTy.
  3424. // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
  3425. // 64-bits we need to insert a new extension so that it will be 64-bits.
  3426. assert(ExtTy.is128BitVector() && "Unexpected extension size");
  3427. if (OrigTy.getSizeInBits() >= 64)
  3428. return N;
  3429. // Must extend size to at least 64 bits to be used as an operand for VMULL.
  3430. EVT NewVT = getExtensionTo64Bits(OrigTy);
  3431. return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
  3432. }
  3433. static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
  3434. bool isSigned) {
  3435. EVT VT = N->getValueType(0);
  3436. if (N->getOpcode() != ISD::BUILD_VECTOR)
  3437. return false;
  3438. for (const SDValue &Elt : N->op_values()) {
  3439. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
  3440. unsigned EltSize = VT.getScalarSizeInBits();
  3441. unsigned HalfSize = EltSize / 2;
  3442. if (isSigned) {
  3443. if (!isIntN(HalfSize, C->getSExtValue()))
  3444. return false;
  3445. } else {
  3446. if (!isUIntN(HalfSize, C->getZExtValue()))
  3447. return false;
  3448. }
  3449. continue;
  3450. }
  3451. return false;
  3452. }
  3453. return true;
  3454. }
  3455. static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
  3456. if (N->getOpcode() == ISD::SIGN_EXTEND ||
  3457. N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
  3458. return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
  3459. N->getOperand(0)->getValueType(0),
  3460. N->getValueType(0),
  3461. N->getOpcode());
  3462. assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
  3463. EVT VT = N->getValueType(0);
  3464. SDLoc dl(N);
  3465. unsigned EltSize = VT.getScalarSizeInBits() / 2;
  3466. unsigned NumElts = VT.getVectorNumElements();
  3467. MVT TruncVT = MVT::getIntegerVT(EltSize);
  3468. SmallVector<SDValue, 8> Ops;
  3469. for (unsigned i = 0; i != NumElts; ++i) {
  3470. ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
  3471. const APInt &CInt = C->getAPIntValue();
  3472. // Element types smaller than 32 bits are not legal, so use i32 elements.
  3473. // The values are implicitly truncated so sext vs. zext doesn't matter.
  3474. Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
  3475. }
  3476. return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
  3477. }
  3478. static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
  3479. return N->getOpcode() == ISD::SIGN_EXTEND ||
  3480. N->getOpcode() == ISD::ANY_EXTEND ||
  3481. isExtendedBUILD_VECTOR(N, DAG, true);
  3482. }
  3483. static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
  3484. return N->getOpcode() == ISD::ZERO_EXTEND ||
  3485. N->getOpcode() == ISD::ANY_EXTEND ||
  3486. isExtendedBUILD_VECTOR(N, DAG, false);
  3487. }
  3488. static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
  3489. unsigned Opcode = N->getOpcode();
  3490. if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
  3491. SDNode *N0 = N->getOperand(0).getNode();
  3492. SDNode *N1 = N->getOperand(1).getNode();
  3493. return N0->hasOneUse() && N1->hasOneUse() &&
  3494. isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
  3495. }
  3496. return false;
  3497. }
  3498. static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
  3499. unsigned Opcode = N->getOpcode();
  3500. if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
  3501. SDNode *N0 = N->getOperand(0).getNode();
  3502. SDNode *N1 = N->getOperand(1).getNode();
  3503. return N0->hasOneUse() && N1->hasOneUse() &&
  3504. isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
  3505. }
  3506. return false;
  3507. }
  3508. SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
  3509. SelectionDAG &DAG) const {
  3510. // The rounding mode is in bits 23:22 of the FPSCR.
  3511. // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
  3512. // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
  3513. // so that the shift + and get folded into a bitfield extract.
  3514. SDLoc dl(Op);
  3515. SDValue Chain = Op.getOperand(0);
  3516. SDValue FPCR_64 = DAG.getNode(
  3517. ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
  3518. {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
  3519. Chain = FPCR_64.getValue(1);
  3520. SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
  3521. SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
  3522. DAG.getConstant(1U << 22, dl, MVT::i32));
  3523. SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
  3524. DAG.getConstant(22, dl, MVT::i32));
  3525. SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
  3526. DAG.getConstant(3, dl, MVT::i32));
  3527. return DAG.getMergeValues({AND, Chain}, dl);
  3528. }
  3529. SDValue AArch64TargetLowering::LowerSET_ROUNDING(SDValue Op,
  3530. SelectionDAG &DAG) const {
  3531. SDLoc DL(Op);
  3532. SDValue Chain = Op->getOperand(0);
  3533. SDValue RMValue = Op->getOperand(1);
  3534. // The rounding mode is in bits 23:22 of the FPCR.
  3535. // The llvm.set.rounding argument value to the rounding mode in FPCR mapping
  3536. // is 0->3, 1->0, 2->1, 3->2. The formula we use to implement this is
  3537. // ((arg - 1) & 3) << 22).
  3538. //
  3539. // The argument of llvm.set.rounding must be within the segment [0, 3], so
  3540. // NearestTiesToAway (4) is not handled here. It is responsibility of the code
  3541. // generated llvm.set.rounding to ensure this condition.
  3542. // Calculate new value of FPCR[23:22].
  3543. RMValue = DAG.getNode(ISD::SUB, DL, MVT::i32, RMValue,
  3544. DAG.getConstant(1, DL, MVT::i32));
  3545. RMValue = DAG.getNode(ISD::AND, DL, MVT::i32, RMValue,
  3546. DAG.getConstant(0x3, DL, MVT::i32));
  3547. RMValue =
  3548. DAG.getNode(ISD::SHL, DL, MVT::i32, RMValue,
  3549. DAG.getConstant(AArch64::RoundingBitsPos, DL, MVT::i32));
  3550. RMValue = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, RMValue);
  3551. // Get current value of FPCR.
  3552. SDValue Ops[] = {
  3553. Chain, DAG.getTargetConstant(Intrinsic::aarch64_get_fpcr, DL, MVT::i64)};
  3554. SDValue FPCR =
  3555. DAG.getNode(ISD::INTRINSIC_W_CHAIN, DL, {MVT::i64, MVT::Other}, Ops);
  3556. Chain = FPCR.getValue(1);
  3557. FPCR = FPCR.getValue(0);
  3558. // Put new rounding mode into FPSCR[23:22].
  3559. const int RMMask = ~(AArch64::Rounding::rmMask << AArch64::RoundingBitsPos);
  3560. FPCR = DAG.getNode(ISD::AND, DL, MVT::i64, FPCR,
  3561. DAG.getConstant(RMMask, DL, MVT::i64));
  3562. FPCR = DAG.getNode(ISD::OR, DL, MVT::i64, FPCR, RMValue);
  3563. SDValue Ops2[] = {
  3564. Chain, DAG.getTargetConstant(Intrinsic::aarch64_set_fpcr, DL, MVT::i64),
  3565. FPCR};
  3566. return DAG.getNode(ISD::INTRINSIC_VOID, DL, MVT::Other, Ops2);
  3567. }
  3568. SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
  3569. EVT VT = Op.getValueType();
  3570. // If SVE is available then i64 vector multiplications can also be made legal.
  3571. bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64;
  3572. if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON))
  3573. return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON);
  3574. // Multiplications are only custom-lowered for 128-bit vectors so that
  3575. // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
  3576. assert(VT.is128BitVector() && VT.isInteger() &&
  3577. "unexpected type for custom-lowering ISD::MUL");
  3578. SDNode *N0 = Op.getOperand(0).getNode();
  3579. SDNode *N1 = Op.getOperand(1).getNode();
  3580. unsigned NewOpc = 0;
  3581. bool isMLA = false;
  3582. bool isN0SExt = isSignExtended(N0, DAG);
  3583. bool isN1SExt = isSignExtended(N1, DAG);
  3584. if (isN0SExt && isN1SExt)
  3585. NewOpc = AArch64ISD::SMULL;
  3586. else {
  3587. bool isN0ZExt = isZeroExtended(N0, DAG);
  3588. bool isN1ZExt = isZeroExtended(N1, DAG);
  3589. if (isN0ZExt && isN1ZExt)
  3590. NewOpc = AArch64ISD::UMULL;
  3591. else if (isN1SExt || isN1ZExt) {
  3592. // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
  3593. // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
  3594. if (isN1SExt && isAddSubSExt(N0, DAG)) {
  3595. NewOpc = AArch64ISD::SMULL;
  3596. isMLA = true;
  3597. } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
  3598. NewOpc = AArch64ISD::UMULL;
  3599. isMLA = true;
  3600. } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
  3601. std::swap(N0, N1);
  3602. NewOpc = AArch64ISD::UMULL;
  3603. isMLA = true;
  3604. }
  3605. }
  3606. if (!NewOpc) {
  3607. if (VT == MVT::v2i64)
  3608. // Fall through to expand this. It is not legal.
  3609. return SDValue();
  3610. else
  3611. // Other vector multiplications are legal.
  3612. return Op;
  3613. }
  3614. }
  3615. // Legalize to a S/UMULL instruction
  3616. SDLoc DL(Op);
  3617. SDValue Op0;
  3618. SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
  3619. if (!isMLA) {
  3620. Op0 = skipExtensionForVectorMULL(N0, DAG);
  3621. assert(Op0.getValueType().is64BitVector() &&
  3622. Op1.getValueType().is64BitVector() &&
  3623. "unexpected types for extended operands to VMULL");
  3624. return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
  3625. }
  3626. // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
  3627. // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
  3628. // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
  3629. SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
  3630. SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
  3631. EVT Op1VT = Op1.getValueType();
  3632. return DAG.getNode(N0->getOpcode(), DL, VT,
  3633. DAG.getNode(NewOpc, DL, VT,
  3634. DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
  3635. DAG.getNode(NewOpc, DL, VT,
  3636. DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
  3637. }
  3638. static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
  3639. int Pattern) {
  3640. return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
  3641. DAG.getTargetConstant(Pattern, DL, MVT::i32));
  3642. }
  3643. static SDValue lowerConvertToSVBool(SDValue Op, SelectionDAG &DAG) {
  3644. SDLoc DL(Op);
  3645. EVT OutVT = Op.getValueType();
  3646. SDValue InOp = Op.getOperand(1);
  3647. EVT InVT = InOp.getValueType();
  3648. // Return the operand if the cast isn't changing type,
  3649. // i.e. <n x 16 x i1> -> <n x 16 x i1>
  3650. if (InVT == OutVT)
  3651. return InOp;
  3652. SDValue Reinterpret =
  3653. DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, OutVT, InOp);
  3654. // If the argument converted to an svbool is a ptrue or a comparison, the
  3655. // lanes introduced by the widening are zero by construction.
  3656. switch (InOp.getOpcode()) {
  3657. case AArch64ISD::SETCC_MERGE_ZERO:
  3658. return Reinterpret;
  3659. case ISD::INTRINSIC_WO_CHAIN:
  3660. if (InOp.getConstantOperandVal(0) == Intrinsic::aarch64_sve_ptrue)
  3661. return Reinterpret;
  3662. }
  3663. // Otherwise, zero the newly introduced lanes.
  3664. SDValue Mask = getPTrue(DAG, DL, InVT, AArch64SVEPredPattern::all);
  3665. SDValue MaskReinterpret =
  3666. DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, OutVT, Mask);
  3667. return DAG.getNode(ISD::AND, DL, OutVT, Reinterpret, MaskReinterpret);
  3668. }
  3669. SDValue AArch64TargetLowering::LowerINTRINSIC_W_CHAIN(SDValue Op,
  3670. SelectionDAG &DAG) const {
  3671. unsigned IntNo = Op.getConstantOperandVal(1);
  3672. switch (IntNo) {
  3673. default:
  3674. return SDValue(); // Don't custom lower most intrinsics.
  3675. case Intrinsic::aarch64_mops_memset_tag: {
  3676. auto Node = cast<MemIntrinsicSDNode>(Op.getNode());
  3677. SDLoc DL(Op);
  3678. SDValue Chain = Node->getChain();
  3679. SDValue Dst = Op.getOperand(2);
  3680. SDValue Val = Op.getOperand(3);
  3681. Val = DAG.getAnyExtOrTrunc(Val, DL, MVT::i64);
  3682. SDValue Size = Op.getOperand(4);
  3683. auto Alignment = Node->getMemOperand()->getAlign();
  3684. bool IsVol = Node->isVolatile();
  3685. auto DstPtrInfo = Node->getPointerInfo();
  3686. const auto &SDI =
  3687. static_cast<const AArch64SelectionDAGInfo &>(DAG.getSelectionDAGInfo());
  3688. SDValue MS =
  3689. SDI.EmitMOPS(AArch64ISD::MOPS_MEMSET_TAGGING, DAG, DL, Chain, Dst, Val,
  3690. Size, Alignment, IsVol, DstPtrInfo, MachinePointerInfo{});
  3691. // MOPS_MEMSET_TAGGING has 3 results (DstWb, SizeWb, Chain) whereas the
  3692. // intrinsic has 2. So hide SizeWb using MERGE_VALUES. Otherwise
  3693. // LowerOperationWrapper will complain that the number of results has
  3694. // changed.
  3695. return DAG.getMergeValues({MS.getValue(0), MS.getValue(2)}, DL);
  3696. }
  3697. }
  3698. }
  3699. SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
  3700. SelectionDAG &DAG) const {
  3701. unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  3702. SDLoc dl(Op);
  3703. switch (IntNo) {
  3704. default: return SDValue(); // Don't custom lower most intrinsics.
  3705. case Intrinsic::thread_pointer: {
  3706. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  3707. return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
  3708. }
  3709. case Intrinsic::aarch64_neon_abs: {
  3710. EVT Ty = Op.getValueType();
  3711. if (Ty == MVT::i64) {
  3712. SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
  3713. Op.getOperand(1));
  3714. Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
  3715. return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
  3716. } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
  3717. return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
  3718. } else {
  3719. report_fatal_error("Unexpected type for AArch64 NEON intrinic");
  3720. }
  3721. }
  3722. case Intrinsic::aarch64_neon_smax:
  3723. return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
  3724. Op.getOperand(1), Op.getOperand(2));
  3725. case Intrinsic::aarch64_neon_umax:
  3726. return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
  3727. Op.getOperand(1), Op.getOperand(2));
  3728. case Intrinsic::aarch64_neon_smin:
  3729. return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
  3730. Op.getOperand(1), Op.getOperand(2));
  3731. case Intrinsic::aarch64_neon_umin:
  3732. return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
  3733. Op.getOperand(1), Op.getOperand(2));
  3734. case Intrinsic::aarch64_sve_sunpkhi:
  3735. return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
  3736. Op.getOperand(1));
  3737. case Intrinsic::aarch64_sve_sunpklo:
  3738. return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
  3739. Op.getOperand(1));
  3740. case Intrinsic::aarch64_sve_uunpkhi:
  3741. return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
  3742. Op.getOperand(1));
  3743. case Intrinsic::aarch64_sve_uunpklo:
  3744. return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
  3745. Op.getOperand(1));
  3746. case Intrinsic::aarch64_sve_clasta_n:
  3747. return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
  3748. Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
  3749. case Intrinsic::aarch64_sve_clastb_n:
  3750. return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
  3751. Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
  3752. case Intrinsic::aarch64_sve_lasta:
  3753. return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
  3754. Op.getOperand(1), Op.getOperand(2));
  3755. case Intrinsic::aarch64_sve_lastb:
  3756. return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
  3757. Op.getOperand(1), Op.getOperand(2));
  3758. case Intrinsic::aarch64_sve_rev:
  3759. return DAG.getNode(ISD::VECTOR_REVERSE, dl, Op.getValueType(),
  3760. Op.getOperand(1));
  3761. case Intrinsic::aarch64_sve_tbl:
  3762. return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
  3763. Op.getOperand(1), Op.getOperand(2));
  3764. case Intrinsic::aarch64_sve_trn1:
  3765. return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
  3766. Op.getOperand(1), Op.getOperand(2));
  3767. case Intrinsic::aarch64_sve_trn2:
  3768. return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
  3769. Op.getOperand(1), Op.getOperand(2));
  3770. case Intrinsic::aarch64_sve_uzp1:
  3771. return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
  3772. Op.getOperand(1), Op.getOperand(2));
  3773. case Intrinsic::aarch64_sve_uzp2:
  3774. return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
  3775. Op.getOperand(1), Op.getOperand(2));
  3776. case Intrinsic::aarch64_sve_zip1:
  3777. return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
  3778. Op.getOperand(1), Op.getOperand(2));
  3779. case Intrinsic::aarch64_sve_zip2:
  3780. return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
  3781. Op.getOperand(1), Op.getOperand(2));
  3782. case Intrinsic::aarch64_sve_splice:
  3783. return DAG.getNode(AArch64ISD::SPLICE, dl, Op.getValueType(),
  3784. Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
  3785. case Intrinsic::aarch64_sve_ptrue:
  3786. return getPTrue(DAG, dl, Op.getValueType(),
  3787. cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue());
  3788. case Intrinsic::aarch64_sve_clz:
  3789. return DAG.getNode(AArch64ISD::CTLZ_MERGE_PASSTHRU, dl, Op.getValueType(),
  3790. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3791. case Intrinsic::aarch64_sve_cnt: {
  3792. SDValue Data = Op.getOperand(3);
  3793. // CTPOP only supports integer operands.
  3794. if (Data.getValueType().isFloatingPoint())
  3795. Data = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Data);
  3796. return DAG.getNode(AArch64ISD::CTPOP_MERGE_PASSTHRU, dl, Op.getValueType(),
  3797. Op.getOperand(2), Data, Op.getOperand(1));
  3798. }
  3799. case Intrinsic::aarch64_sve_dupq_lane:
  3800. return LowerDUPQLane(Op, DAG);
  3801. case Intrinsic::aarch64_sve_convert_from_svbool:
  3802. return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
  3803. Op.getOperand(1));
  3804. case Intrinsic::aarch64_sve_convert_to_svbool:
  3805. return lowerConvertToSVBool(Op, DAG);
  3806. case Intrinsic::aarch64_sve_fneg:
  3807. return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3808. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3809. case Intrinsic::aarch64_sve_frintp:
  3810. return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(),
  3811. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3812. case Intrinsic::aarch64_sve_frintm:
  3813. return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(),
  3814. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3815. case Intrinsic::aarch64_sve_frinti:
  3816. return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(),
  3817. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3818. case Intrinsic::aarch64_sve_frintx:
  3819. return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(),
  3820. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3821. case Intrinsic::aarch64_sve_frinta:
  3822. return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(),
  3823. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3824. case Intrinsic::aarch64_sve_frintn:
  3825. return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(),
  3826. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3827. case Intrinsic::aarch64_sve_frintz:
  3828. return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(),
  3829. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3830. case Intrinsic::aarch64_sve_ucvtf:
  3831. return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl,
  3832. Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
  3833. Op.getOperand(1));
  3834. case Intrinsic::aarch64_sve_scvtf:
  3835. return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl,
  3836. Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
  3837. Op.getOperand(1));
  3838. case Intrinsic::aarch64_sve_fcvtzu:
  3839. return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl,
  3840. Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
  3841. Op.getOperand(1));
  3842. case Intrinsic::aarch64_sve_fcvtzs:
  3843. return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl,
  3844. Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
  3845. Op.getOperand(1));
  3846. case Intrinsic::aarch64_sve_fsqrt:
  3847. return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(),
  3848. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3849. case Intrinsic::aarch64_sve_frecpx:
  3850. return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(),
  3851. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3852. case Intrinsic::aarch64_sve_frecpe_x:
  3853. return DAG.getNode(AArch64ISD::FRECPE, dl, Op.getValueType(),
  3854. Op.getOperand(1));
  3855. case Intrinsic::aarch64_sve_frecps_x:
  3856. return DAG.getNode(AArch64ISD::FRECPS, dl, Op.getValueType(),
  3857. Op.getOperand(1), Op.getOperand(2));
  3858. case Intrinsic::aarch64_sve_frsqrte_x:
  3859. return DAG.getNode(AArch64ISD::FRSQRTE, dl, Op.getValueType(),
  3860. Op.getOperand(1));
  3861. case Intrinsic::aarch64_sve_frsqrts_x:
  3862. return DAG.getNode(AArch64ISD::FRSQRTS, dl, Op.getValueType(),
  3863. Op.getOperand(1), Op.getOperand(2));
  3864. case Intrinsic::aarch64_sve_fabs:
  3865. return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(),
  3866. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3867. case Intrinsic::aarch64_sve_abs:
  3868. return DAG.getNode(AArch64ISD::ABS_MERGE_PASSTHRU, dl, Op.getValueType(),
  3869. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3870. case Intrinsic::aarch64_sve_neg:
  3871. return DAG.getNode(AArch64ISD::NEG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3872. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3873. case Intrinsic::aarch64_sve_insr: {
  3874. SDValue Scalar = Op.getOperand(2);
  3875. EVT ScalarTy = Scalar.getValueType();
  3876. if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
  3877. Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
  3878. return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
  3879. Op.getOperand(1), Scalar);
  3880. }
  3881. case Intrinsic::aarch64_sve_rbit:
  3882. return DAG.getNode(AArch64ISD::BITREVERSE_MERGE_PASSTHRU, dl,
  3883. Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
  3884. Op.getOperand(1));
  3885. case Intrinsic::aarch64_sve_revb:
  3886. return DAG.getNode(AArch64ISD::BSWAP_MERGE_PASSTHRU, dl, Op.getValueType(),
  3887. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3888. case Intrinsic::aarch64_sve_revh:
  3889. return DAG.getNode(AArch64ISD::REVH_MERGE_PASSTHRU, dl, Op.getValueType(),
  3890. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3891. case Intrinsic::aarch64_sve_revw:
  3892. return DAG.getNode(AArch64ISD::REVW_MERGE_PASSTHRU, dl, Op.getValueType(),
  3893. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3894. case Intrinsic::aarch64_sve_sxtb:
  3895. return DAG.getNode(
  3896. AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3897. Op.getOperand(2), Op.getOperand(3),
  3898. DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
  3899. Op.getOperand(1));
  3900. case Intrinsic::aarch64_sve_sxth:
  3901. return DAG.getNode(
  3902. AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3903. Op.getOperand(2), Op.getOperand(3),
  3904. DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
  3905. Op.getOperand(1));
  3906. case Intrinsic::aarch64_sve_sxtw:
  3907. return DAG.getNode(
  3908. AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3909. Op.getOperand(2), Op.getOperand(3),
  3910. DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
  3911. Op.getOperand(1));
  3912. case Intrinsic::aarch64_sve_uxtb:
  3913. return DAG.getNode(
  3914. AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3915. Op.getOperand(2), Op.getOperand(3),
  3916. DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
  3917. Op.getOperand(1));
  3918. case Intrinsic::aarch64_sve_uxth:
  3919. return DAG.getNode(
  3920. AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3921. Op.getOperand(2), Op.getOperand(3),
  3922. DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
  3923. Op.getOperand(1));
  3924. case Intrinsic::aarch64_sve_uxtw:
  3925. return DAG.getNode(
  3926. AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3927. Op.getOperand(2), Op.getOperand(3),
  3928. DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
  3929. Op.getOperand(1));
  3930. case Intrinsic::localaddress: {
  3931. const auto &MF = DAG.getMachineFunction();
  3932. const auto *RegInfo = Subtarget->getRegisterInfo();
  3933. unsigned Reg = RegInfo->getLocalAddressRegister(MF);
  3934. return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
  3935. Op.getSimpleValueType());
  3936. }
  3937. case Intrinsic::eh_recoverfp: {
  3938. // FIXME: This needs to be implemented to correctly handle highly aligned
  3939. // stack objects. For now we simply return the incoming FP. Refer D53541
  3940. // for more details.
  3941. SDValue FnOp = Op.getOperand(1);
  3942. SDValue IncomingFPOp = Op.getOperand(2);
  3943. GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
  3944. auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
  3945. if (!Fn)
  3946. report_fatal_error(
  3947. "llvm.eh.recoverfp must take a function as the first argument");
  3948. return IncomingFPOp;
  3949. }
  3950. case Intrinsic::aarch64_neon_vsri:
  3951. case Intrinsic::aarch64_neon_vsli: {
  3952. EVT Ty = Op.getValueType();
  3953. if (!Ty.isVector())
  3954. report_fatal_error("Unexpected type for aarch64_neon_vsli");
  3955. assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
  3956. bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
  3957. unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
  3958. return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
  3959. Op.getOperand(3));
  3960. }
  3961. case Intrinsic::aarch64_neon_srhadd:
  3962. case Intrinsic::aarch64_neon_urhadd:
  3963. case Intrinsic::aarch64_neon_shadd:
  3964. case Intrinsic::aarch64_neon_uhadd: {
  3965. bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
  3966. IntNo == Intrinsic::aarch64_neon_shadd);
  3967. bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
  3968. IntNo == Intrinsic::aarch64_neon_urhadd);
  3969. unsigned Opcode =
  3970. IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
  3971. : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD);
  3972. return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
  3973. Op.getOperand(2));
  3974. }
  3975. case Intrinsic::aarch64_neon_sabd:
  3976. case Intrinsic::aarch64_neon_uabd: {
  3977. unsigned Opcode = IntNo == Intrinsic::aarch64_neon_uabd ? ISD::ABDU
  3978. : ISD::ABDS;
  3979. return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
  3980. Op.getOperand(2));
  3981. }
  3982. case Intrinsic::aarch64_neon_uaddlp: {
  3983. unsigned Opcode = AArch64ISD::UADDLP;
  3984. return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1));
  3985. }
  3986. case Intrinsic::aarch64_neon_sdot:
  3987. case Intrinsic::aarch64_neon_udot:
  3988. case Intrinsic::aarch64_sve_sdot:
  3989. case Intrinsic::aarch64_sve_udot: {
  3990. unsigned Opcode = (IntNo == Intrinsic::aarch64_neon_udot ||
  3991. IntNo == Intrinsic::aarch64_sve_udot)
  3992. ? AArch64ISD::UDOT
  3993. : AArch64ISD::SDOT;
  3994. return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
  3995. Op.getOperand(2), Op.getOperand(3));
  3996. }
  3997. case Intrinsic::get_active_lane_mask: {
  3998. SDValue ID =
  3999. DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl, MVT::i64);
  4000. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(), ID,
  4001. Op.getOperand(1), Op.getOperand(2));
  4002. }
  4003. }
  4004. }
  4005. bool AArch64TargetLowering::shouldExtendGSIndex(EVT VT, EVT &EltTy) const {
  4006. if (VT.getVectorElementType() == MVT::i8 ||
  4007. VT.getVectorElementType() == MVT::i16) {
  4008. EltTy = MVT::i32;
  4009. return true;
  4010. }
  4011. return false;
  4012. }
  4013. bool AArch64TargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
  4014. if (VT.getVectorElementType() == MVT::i32 &&
  4015. VT.getVectorElementCount().getKnownMinValue() >= 4 &&
  4016. !VT.isFixedLengthVector())
  4017. return true;
  4018. return false;
  4019. }
  4020. bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
  4021. return ExtVal.getValueType().isScalableVector() ||
  4022. useSVEForFixedLengthVectorVT(ExtVal.getValueType(),
  4023. /*OverrideNEON=*/true);
  4024. }
  4025. unsigned getGatherVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
  4026. std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
  4027. {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
  4028. AArch64ISD::GLD1_MERGE_ZERO},
  4029. {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
  4030. AArch64ISD::GLD1_UXTW_MERGE_ZERO},
  4031. {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
  4032. AArch64ISD::GLD1_MERGE_ZERO},
  4033. {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
  4034. AArch64ISD::GLD1_SXTW_MERGE_ZERO},
  4035. {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
  4036. AArch64ISD::GLD1_SCALED_MERGE_ZERO},
  4037. {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
  4038. AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO},
  4039. {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
  4040. AArch64ISD::GLD1_SCALED_MERGE_ZERO},
  4041. {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
  4042. AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO},
  4043. };
  4044. auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
  4045. return AddrModes.find(Key)->second;
  4046. }
  4047. unsigned getScatterVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
  4048. std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
  4049. {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
  4050. AArch64ISD::SST1_PRED},
  4051. {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
  4052. AArch64ISD::SST1_UXTW_PRED},
  4053. {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
  4054. AArch64ISD::SST1_PRED},
  4055. {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
  4056. AArch64ISD::SST1_SXTW_PRED},
  4057. {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
  4058. AArch64ISD::SST1_SCALED_PRED},
  4059. {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
  4060. AArch64ISD::SST1_UXTW_SCALED_PRED},
  4061. {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
  4062. AArch64ISD::SST1_SCALED_PRED},
  4063. {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
  4064. AArch64ISD::SST1_SXTW_SCALED_PRED},
  4065. };
  4066. auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
  4067. return AddrModes.find(Key)->second;
  4068. }
  4069. unsigned getSignExtendedGatherOpcode(unsigned Opcode) {
  4070. switch (Opcode) {
  4071. default:
  4072. llvm_unreachable("unimplemented opcode");
  4073. return Opcode;
  4074. case AArch64ISD::GLD1_MERGE_ZERO:
  4075. return AArch64ISD::GLD1S_MERGE_ZERO;
  4076. case AArch64ISD::GLD1_IMM_MERGE_ZERO:
  4077. return AArch64ISD::GLD1S_IMM_MERGE_ZERO;
  4078. case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
  4079. return AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
  4080. case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
  4081. return AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
  4082. case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
  4083. return AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
  4084. case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
  4085. return AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
  4086. case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
  4087. return AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
  4088. }
  4089. }
  4090. bool getGatherScatterIndexIsExtended(SDValue Index) {
  4091. unsigned Opcode = Index.getOpcode();
  4092. if (Opcode == ISD::SIGN_EXTEND_INREG)
  4093. return true;
  4094. if (Opcode == ISD::AND) {
  4095. SDValue Splat = Index.getOperand(1);
  4096. if (Splat.getOpcode() != ISD::SPLAT_VECTOR)
  4097. return false;
  4098. ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Splat.getOperand(0));
  4099. if (!Mask || Mask->getZExtValue() != 0xFFFFFFFF)
  4100. return false;
  4101. return true;
  4102. }
  4103. return false;
  4104. }
  4105. // If the base pointer of a masked gather or scatter is null, we
  4106. // may be able to swap BasePtr & Index and use the vector + register
  4107. // or vector + immediate addressing mode, e.g.
  4108. // VECTOR + REGISTER:
  4109. // getelementptr nullptr, <vscale x N x T> (splat(%offset)) + %indices)
  4110. // -> getelementptr %offset, <vscale x N x T> %indices
  4111. // VECTOR + IMMEDIATE:
  4112. // getelementptr nullptr, <vscale x N x T> (splat(#x)) + %indices)
  4113. // -> getelementptr #x, <vscale x N x T> %indices
  4114. void selectGatherScatterAddrMode(SDValue &BasePtr, SDValue &Index, EVT MemVT,
  4115. unsigned &Opcode, bool IsGather,
  4116. SelectionDAG &DAG) {
  4117. if (!isNullConstant(BasePtr))
  4118. return;
  4119. // FIXME: This will not match for fixed vector type codegen as the nodes in
  4120. // question will have fixed<->scalable conversions around them. This should be
  4121. // moved to a DAG combine or complex pattern so that is executes after all of
  4122. // the fixed vector insert and extracts have been removed. This deficiency
  4123. // will result in a sub-optimal addressing mode being used, i.e. an ADD not
  4124. // being folded into the scatter/gather.
  4125. ConstantSDNode *Offset = nullptr;
  4126. if (Index.getOpcode() == ISD::ADD)
  4127. if (auto SplatVal = DAG.getSplatValue(Index.getOperand(1))) {
  4128. if (isa<ConstantSDNode>(SplatVal))
  4129. Offset = cast<ConstantSDNode>(SplatVal);
  4130. else {
  4131. BasePtr = SplatVal;
  4132. Index = Index->getOperand(0);
  4133. return;
  4134. }
  4135. }
  4136. unsigned NewOp =
  4137. IsGather ? AArch64ISD::GLD1_IMM_MERGE_ZERO : AArch64ISD::SST1_IMM_PRED;
  4138. if (!Offset) {
  4139. std::swap(BasePtr, Index);
  4140. Opcode = NewOp;
  4141. return;
  4142. }
  4143. uint64_t OffsetVal = Offset->getZExtValue();
  4144. unsigned ScalarSizeInBytes = MemVT.getScalarSizeInBits() / 8;
  4145. auto ConstOffset = DAG.getConstant(OffsetVal, SDLoc(Index), MVT::i64);
  4146. if (OffsetVal % ScalarSizeInBytes || OffsetVal / ScalarSizeInBytes > 31) {
  4147. // Index is out of range for the immediate addressing mode
  4148. BasePtr = ConstOffset;
  4149. Index = Index->getOperand(0);
  4150. return;
  4151. }
  4152. // Immediate is in range
  4153. Opcode = NewOp;
  4154. BasePtr = Index->getOperand(0);
  4155. Index = ConstOffset;
  4156. }
  4157. SDValue AArch64TargetLowering::LowerMGATHER(SDValue Op,
  4158. SelectionDAG &DAG) const {
  4159. SDLoc DL(Op);
  4160. MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(Op);
  4161. assert(MGT && "Can only custom lower gather load nodes");
  4162. bool IsFixedLength = MGT->getMemoryVT().isFixedLengthVector();
  4163. SDValue Index = MGT->getIndex();
  4164. SDValue Chain = MGT->getChain();
  4165. SDValue PassThru = MGT->getPassThru();
  4166. SDValue Mask = MGT->getMask();
  4167. SDValue BasePtr = MGT->getBasePtr();
  4168. ISD::LoadExtType ExtTy = MGT->getExtensionType();
  4169. ISD::MemIndexType IndexType = MGT->getIndexType();
  4170. bool IsScaled =
  4171. IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
  4172. bool IsSigned =
  4173. IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
  4174. bool IdxNeedsExtend =
  4175. getGatherScatterIndexIsExtended(Index) ||
  4176. Index.getSimpleValueType().getVectorElementType() == MVT::i32;
  4177. bool ResNeedsSignExtend = ExtTy == ISD::EXTLOAD || ExtTy == ISD::SEXTLOAD;
  4178. EVT VT = PassThru.getSimpleValueType();
  4179. EVT IndexVT = Index.getSimpleValueType();
  4180. EVT MemVT = MGT->getMemoryVT();
  4181. SDValue InputVT = DAG.getValueType(MemVT);
  4182. if (VT.getVectorElementType() == MVT::bf16 &&
  4183. !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
  4184. return SDValue();
  4185. if (IsFixedLength) {
  4186. assert(Subtarget->useSVEForFixedLengthVectors() &&
  4187. "Cannot lower when not using SVE for fixed vectors");
  4188. if (MemVT.getScalarSizeInBits() <= IndexVT.getScalarSizeInBits()) {
  4189. IndexVT = getContainerForFixedLengthVector(DAG, IndexVT);
  4190. MemVT = IndexVT.changeVectorElementType(MemVT.getVectorElementType());
  4191. } else {
  4192. MemVT = getContainerForFixedLengthVector(DAG, MemVT);
  4193. IndexVT = MemVT.changeTypeToInteger();
  4194. }
  4195. InputVT = DAG.getValueType(MemVT.changeTypeToInteger());
  4196. Mask = DAG.getNode(
  4197. ISD::SIGN_EXTEND, DL,
  4198. VT.changeVectorElementType(IndexVT.getVectorElementType()), Mask);
  4199. }
  4200. if (PassThru->isUndef() || isZerosVector(PassThru.getNode()))
  4201. PassThru = SDValue();
  4202. if (VT.isFloatingPoint() && !IsFixedLength) {
  4203. // Handle FP data by using an integer gather and casting the result.
  4204. if (PassThru) {
  4205. EVT PassThruVT = getPackedSVEVectorVT(VT.getVectorElementCount());
  4206. PassThru = getSVESafeBitCast(PassThruVT, PassThru, DAG);
  4207. }
  4208. InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
  4209. }
  4210. SDVTList VTs = DAG.getVTList(IndexVT, MVT::Other);
  4211. if (getGatherScatterIndexIsExtended(Index))
  4212. Index = Index.getOperand(0);
  4213. unsigned Opcode = getGatherVecOpcode(IsScaled, IsSigned, IdxNeedsExtend);
  4214. selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode,
  4215. /*isGather=*/true, DAG);
  4216. if (ResNeedsSignExtend)
  4217. Opcode = getSignExtendedGatherOpcode(Opcode);
  4218. if (IsFixedLength) {
  4219. if (Index.getSimpleValueType().isFixedLengthVector())
  4220. Index = convertToScalableVector(DAG, IndexVT, Index);
  4221. if (BasePtr.getSimpleValueType().isFixedLengthVector())
  4222. BasePtr = convertToScalableVector(DAG, IndexVT, BasePtr);
  4223. Mask = convertFixedMaskToScalableVector(Mask, DAG);
  4224. }
  4225. SDValue Ops[] = {Chain, Mask, BasePtr, Index, InputVT};
  4226. SDValue Result = DAG.getNode(Opcode, DL, VTs, Ops);
  4227. Chain = Result.getValue(1);
  4228. if (IsFixedLength) {
  4229. Result = convertFromScalableVector(
  4230. DAG, VT.changeVectorElementType(IndexVT.getVectorElementType()),
  4231. Result);
  4232. Result = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Result);
  4233. Result = DAG.getNode(ISD::BITCAST, DL, VT, Result);
  4234. if (PassThru)
  4235. Result = DAG.getSelect(DL, VT, MGT->getMask(), Result, PassThru);
  4236. } else {
  4237. if (PassThru)
  4238. Result = DAG.getSelect(DL, IndexVT, Mask, Result, PassThru);
  4239. if (VT.isFloatingPoint())
  4240. Result = getSVESafeBitCast(VT, Result, DAG);
  4241. }
  4242. return DAG.getMergeValues({Result, Chain}, DL);
  4243. }
  4244. SDValue AArch64TargetLowering::LowerMSCATTER(SDValue Op,
  4245. SelectionDAG &DAG) const {
  4246. SDLoc DL(Op);
  4247. MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(Op);
  4248. assert(MSC && "Can only custom lower scatter store nodes");
  4249. bool IsFixedLength = MSC->getMemoryVT().isFixedLengthVector();
  4250. SDValue Index = MSC->getIndex();
  4251. SDValue Chain = MSC->getChain();
  4252. SDValue StoreVal = MSC->getValue();
  4253. SDValue Mask = MSC->getMask();
  4254. SDValue BasePtr = MSC->getBasePtr();
  4255. ISD::MemIndexType IndexType = MSC->getIndexType();
  4256. bool IsScaled =
  4257. IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
  4258. bool IsSigned =
  4259. IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
  4260. bool NeedsExtend =
  4261. getGatherScatterIndexIsExtended(Index) ||
  4262. Index.getSimpleValueType().getVectorElementType() == MVT::i32;
  4263. EVT VT = StoreVal.getSimpleValueType();
  4264. EVT IndexVT = Index.getSimpleValueType();
  4265. SDVTList VTs = DAG.getVTList(MVT::Other);
  4266. EVT MemVT = MSC->getMemoryVT();
  4267. SDValue InputVT = DAG.getValueType(MemVT);
  4268. if (VT.getVectorElementType() == MVT::bf16 &&
  4269. !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
  4270. return SDValue();
  4271. if (IsFixedLength) {
  4272. assert(Subtarget->useSVEForFixedLengthVectors() &&
  4273. "Cannot lower when not using SVE for fixed vectors");
  4274. if (MemVT.getScalarSizeInBits() <= IndexVT.getScalarSizeInBits()) {
  4275. IndexVT = getContainerForFixedLengthVector(DAG, IndexVT);
  4276. MemVT = IndexVT.changeVectorElementType(MemVT.getVectorElementType());
  4277. } else {
  4278. MemVT = getContainerForFixedLengthVector(DAG, MemVT);
  4279. IndexVT = MemVT.changeTypeToInteger();
  4280. }
  4281. InputVT = DAG.getValueType(MemVT.changeTypeToInteger());
  4282. StoreVal =
  4283. DAG.getNode(ISD::BITCAST, DL, VT.changeTypeToInteger(), StoreVal);
  4284. StoreVal = DAG.getNode(
  4285. ISD::ANY_EXTEND, DL,
  4286. VT.changeVectorElementType(IndexVT.getVectorElementType()), StoreVal);
  4287. StoreVal = convertToScalableVector(DAG, IndexVT, StoreVal);
  4288. Mask = DAG.getNode(
  4289. ISD::SIGN_EXTEND, DL,
  4290. VT.changeVectorElementType(IndexVT.getVectorElementType()), Mask);
  4291. } else if (VT.isFloatingPoint()) {
  4292. // Handle FP data by casting the data so an integer scatter can be used.
  4293. EVT StoreValVT = getPackedSVEVectorVT(VT.getVectorElementCount());
  4294. StoreVal = getSVESafeBitCast(StoreValVT, StoreVal, DAG);
  4295. InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
  4296. }
  4297. if (getGatherScatterIndexIsExtended(Index))
  4298. Index = Index.getOperand(0);
  4299. unsigned Opcode = getScatterVecOpcode(IsScaled, IsSigned, NeedsExtend);
  4300. selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode,
  4301. /*isGather=*/false, DAG);
  4302. if (IsFixedLength) {
  4303. if (Index.getSimpleValueType().isFixedLengthVector())
  4304. Index = convertToScalableVector(DAG, IndexVT, Index);
  4305. if (BasePtr.getSimpleValueType().isFixedLengthVector())
  4306. BasePtr = convertToScalableVector(DAG, IndexVT, BasePtr);
  4307. Mask = convertFixedMaskToScalableVector(Mask, DAG);
  4308. }
  4309. SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, InputVT};
  4310. return DAG.getNode(Opcode, DL, VTs, Ops);
  4311. }
  4312. SDValue AArch64TargetLowering::LowerMLOAD(SDValue Op, SelectionDAG &DAG) const {
  4313. SDLoc DL(Op);
  4314. MaskedLoadSDNode *LoadNode = cast<MaskedLoadSDNode>(Op);
  4315. assert(LoadNode && "Expected custom lowering of a masked load node");
  4316. EVT VT = Op->getValueType(0);
  4317. if (useSVEForFixedLengthVectorVT(VT, true))
  4318. return LowerFixedLengthVectorMLoadToSVE(Op, DAG);
  4319. SDValue PassThru = LoadNode->getPassThru();
  4320. SDValue Mask = LoadNode->getMask();
  4321. if (PassThru->isUndef() || isZerosVector(PassThru.getNode()))
  4322. return Op;
  4323. SDValue Load = DAG.getMaskedLoad(
  4324. VT, DL, LoadNode->getChain(), LoadNode->getBasePtr(),
  4325. LoadNode->getOffset(), Mask, DAG.getUNDEF(VT), LoadNode->getMemoryVT(),
  4326. LoadNode->getMemOperand(), LoadNode->getAddressingMode(),
  4327. LoadNode->getExtensionType());
  4328. SDValue Result = DAG.getSelect(DL, VT, Mask, Load, PassThru);
  4329. return DAG.getMergeValues({Result, Load.getValue(1)}, DL);
  4330. }
  4331. // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
  4332. static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
  4333. EVT VT, EVT MemVT,
  4334. SelectionDAG &DAG) {
  4335. assert(VT.isVector() && "VT should be a vector type");
  4336. assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
  4337. SDValue Value = ST->getValue();
  4338. // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
  4339. // the word lane which represent the v4i8 subvector. It optimizes the store
  4340. // to:
  4341. //
  4342. // xtn v0.8b, v0.8h
  4343. // str s0, [x0]
  4344. SDValue Undef = DAG.getUNDEF(MVT::i16);
  4345. SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
  4346. {Undef, Undef, Undef, Undef});
  4347. SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
  4348. Value, UndefVec);
  4349. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
  4350. Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
  4351. SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
  4352. Trunc, DAG.getConstant(0, DL, MVT::i64));
  4353. return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
  4354. ST->getBasePtr(), ST->getMemOperand());
  4355. }
  4356. // Custom lowering for any store, vector or scalar and/or default or with
  4357. // a truncate operations. Currently only custom lower truncate operation
  4358. // from vector v4i16 to v4i8 or volatile stores of i128.
  4359. SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
  4360. SelectionDAG &DAG) const {
  4361. SDLoc Dl(Op);
  4362. StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
  4363. assert (StoreNode && "Can only custom lower store nodes");
  4364. SDValue Value = StoreNode->getValue();
  4365. EVT VT = Value.getValueType();
  4366. EVT MemVT = StoreNode->getMemoryVT();
  4367. if (VT.isVector()) {
  4368. if (useSVEForFixedLengthVectorVT(VT, true))
  4369. return LowerFixedLengthVectorStoreToSVE(Op, DAG);
  4370. unsigned AS = StoreNode->getAddressSpace();
  4371. Align Alignment = StoreNode->getAlign();
  4372. if (Alignment < MemVT.getStoreSize() &&
  4373. !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment,
  4374. StoreNode->getMemOperand()->getFlags(),
  4375. nullptr)) {
  4376. return scalarizeVectorStore(StoreNode, DAG);
  4377. }
  4378. if (StoreNode->isTruncatingStore() && VT == MVT::v4i16 &&
  4379. MemVT == MVT::v4i8) {
  4380. return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
  4381. }
  4382. // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
  4383. // the custom lowering, as there are no un-paired non-temporal stores and
  4384. // legalization will break up 256 bit inputs.
  4385. ElementCount EC = MemVT.getVectorElementCount();
  4386. if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
  4387. EC.isKnownEven() &&
  4388. ((MemVT.getScalarSizeInBits() == 8u ||
  4389. MemVT.getScalarSizeInBits() == 16u ||
  4390. MemVT.getScalarSizeInBits() == 32u ||
  4391. MemVT.getScalarSizeInBits() == 64u))) {
  4392. SDValue Lo =
  4393. DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
  4394. MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
  4395. StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
  4396. SDValue Hi =
  4397. DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
  4398. MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
  4399. StoreNode->getValue(),
  4400. DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64));
  4401. SDValue Result = DAG.getMemIntrinsicNode(
  4402. AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
  4403. {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
  4404. StoreNode->getMemoryVT(), StoreNode->getMemOperand());
  4405. return Result;
  4406. }
  4407. } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
  4408. return LowerStore128(Op, DAG);
  4409. } else if (MemVT == MVT::i64x8) {
  4410. SDValue Value = StoreNode->getValue();
  4411. assert(Value->getValueType(0) == MVT::i64x8);
  4412. SDValue Chain = StoreNode->getChain();
  4413. SDValue Base = StoreNode->getBasePtr();
  4414. EVT PtrVT = Base.getValueType();
  4415. for (unsigned i = 0; i < 8; i++) {
  4416. SDValue Part = DAG.getNode(AArch64ISD::LS64_EXTRACT, Dl, MVT::i64,
  4417. Value, DAG.getConstant(i, Dl, MVT::i32));
  4418. SDValue Ptr = DAG.getNode(ISD::ADD, Dl, PtrVT, Base,
  4419. DAG.getConstant(i * 8, Dl, PtrVT));
  4420. Chain = DAG.getStore(Chain, Dl, Part, Ptr, StoreNode->getPointerInfo(),
  4421. StoreNode->getOriginalAlign());
  4422. }
  4423. return Chain;
  4424. }
  4425. return SDValue();
  4426. }
  4427. /// Lower atomic or volatile 128-bit stores to a single STP instruction.
  4428. SDValue AArch64TargetLowering::LowerStore128(SDValue Op,
  4429. SelectionDAG &DAG) const {
  4430. MemSDNode *StoreNode = cast<MemSDNode>(Op);
  4431. assert(StoreNode->getMemoryVT() == MVT::i128);
  4432. assert(StoreNode->isVolatile() || StoreNode->isAtomic());
  4433. assert(!StoreNode->isAtomic() ||
  4434. StoreNode->getMergedOrdering() == AtomicOrdering::Unordered ||
  4435. StoreNode->getMergedOrdering() == AtomicOrdering::Monotonic);
  4436. SDValue Value = StoreNode->getOpcode() == ISD::STORE
  4437. ? StoreNode->getOperand(1)
  4438. : StoreNode->getOperand(2);
  4439. SDLoc DL(Op);
  4440. SDValue Lo = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, Value,
  4441. DAG.getConstant(0, DL, MVT::i64));
  4442. SDValue Hi = DAG.getNode(ISD::EXTRACT_ELEMENT, DL, MVT::i64, Value,
  4443. DAG.getConstant(1, DL, MVT::i64));
  4444. SDValue Result = DAG.getMemIntrinsicNode(
  4445. AArch64ISD::STP, DL, DAG.getVTList(MVT::Other),
  4446. {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
  4447. StoreNode->getMemoryVT(), StoreNode->getMemOperand());
  4448. return Result;
  4449. }
  4450. SDValue AArch64TargetLowering::LowerLOAD(SDValue Op,
  4451. SelectionDAG &DAG) const {
  4452. SDLoc DL(Op);
  4453. LoadSDNode *LoadNode = cast<LoadSDNode>(Op);
  4454. assert(LoadNode && "Expected custom lowering of a load node");
  4455. if (LoadNode->getMemoryVT() == MVT::i64x8) {
  4456. SmallVector<SDValue, 8> Ops;
  4457. SDValue Base = LoadNode->getBasePtr();
  4458. SDValue Chain = LoadNode->getChain();
  4459. EVT PtrVT = Base.getValueType();
  4460. for (unsigned i = 0; i < 8; i++) {
  4461. SDValue Ptr = DAG.getNode(ISD::ADD, DL, PtrVT, Base,
  4462. DAG.getConstant(i * 8, DL, PtrVT));
  4463. SDValue Part = DAG.getLoad(MVT::i64, DL, Chain, Ptr,
  4464. LoadNode->getPointerInfo(),
  4465. LoadNode->getOriginalAlign());
  4466. Ops.push_back(Part);
  4467. Chain = SDValue(Part.getNode(), 1);
  4468. }
  4469. SDValue Loaded = DAG.getNode(AArch64ISD::LS64_BUILD, DL, MVT::i64x8, Ops);
  4470. return DAG.getMergeValues({Loaded, Chain}, DL);
  4471. }
  4472. // Custom lowering for extending v4i8 vector loads.
  4473. EVT VT = Op->getValueType(0);
  4474. assert((VT == MVT::v4i16 || VT == MVT::v4i32) && "Expected v4i16 or v4i32");
  4475. if (LoadNode->getMemoryVT() != MVT::v4i8)
  4476. return SDValue();
  4477. unsigned ExtType;
  4478. if (LoadNode->getExtensionType() == ISD::SEXTLOAD)
  4479. ExtType = ISD::SIGN_EXTEND;
  4480. else if (LoadNode->getExtensionType() == ISD::ZEXTLOAD ||
  4481. LoadNode->getExtensionType() == ISD::EXTLOAD)
  4482. ExtType = ISD::ZERO_EXTEND;
  4483. else
  4484. return SDValue();
  4485. SDValue Load = DAG.getLoad(MVT::f32, DL, LoadNode->getChain(),
  4486. LoadNode->getBasePtr(), MachinePointerInfo());
  4487. SDValue Chain = Load.getValue(1);
  4488. SDValue Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, MVT::v2f32, Load);
  4489. SDValue BC = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Vec);
  4490. SDValue Ext = DAG.getNode(ExtType, DL, MVT::v8i16, BC);
  4491. Ext = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v4i16, Ext,
  4492. DAG.getConstant(0, DL, MVT::i64));
  4493. if (VT == MVT::v4i32)
  4494. Ext = DAG.getNode(ExtType, DL, MVT::v4i32, Ext);
  4495. return DAG.getMergeValues({Ext, Chain}, DL);
  4496. }
  4497. // Generate SUBS and CSEL for integer abs.
  4498. SDValue AArch64TargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
  4499. MVT VT = Op.getSimpleValueType();
  4500. if (VT.isVector())
  4501. return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABS_MERGE_PASSTHRU);
  4502. SDLoc DL(Op);
  4503. SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
  4504. Op.getOperand(0));
  4505. // Generate SUBS & CSEL.
  4506. SDValue Cmp =
  4507. DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
  4508. Op.getOperand(0), DAG.getConstant(0, DL, VT));
  4509. return DAG.getNode(AArch64ISD::CSEL, DL, VT, Op.getOperand(0), Neg,
  4510. DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
  4511. Cmp.getValue(1));
  4512. }
  4513. SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
  4514. SelectionDAG &DAG) const {
  4515. LLVM_DEBUG(dbgs() << "Custom lowering: ");
  4516. LLVM_DEBUG(Op.dump());
  4517. switch (Op.getOpcode()) {
  4518. default:
  4519. llvm_unreachable("unimplemented operand");
  4520. return SDValue();
  4521. case ISD::BITCAST:
  4522. return LowerBITCAST(Op, DAG);
  4523. case ISD::GlobalAddress:
  4524. return LowerGlobalAddress(Op, DAG);
  4525. case ISD::GlobalTLSAddress:
  4526. return LowerGlobalTLSAddress(Op, DAG);
  4527. case ISD::SETCC:
  4528. case ISD::STRICT_FSETCC:
  4529. case ISD::STRICT_FSETCCS:
  4530. return LowerSETCC(Op, DAG);
  4531. case ISD::BR_CC:
  4532. return LowerBR_CC(Op, DAG);
  4533. case ISD::SELECT:
  4534. return LowerSELECT(Op, DAG);
  4535. case ISD::SELECT_CC:
  4536. return LowerSELECT_CC(Op, DAG);
  4537. case ISD::JumpTable:
  4538. return LowerJumpTable(Op, DAG);
  4539. case ISD::BR_JT:
  4540. return LowerBR_JT(Op, DAG);
  4541. case ISD::ConstantPool:
  4542. return LowerConstantPool(Op, DAG);
  4543. case ISD::BlockAddress:
  4544. return LowerBlockAddress(Op, DAG);
  4545. case ISD::VASTART:
  4546. return LowerVASTART(Op, DAG);
  4547. case ISD::VACOPY:
  4548. return LowerVACOPY(Op, DAG);
  4549. case ISD::VAARG:
  4550. return LowerVAARG(Op, DAG);
  4551. case ISD::ADDC:
  4552. case ISD::ADDE:
  4553. case ISD::SUBC:
  4554. case ISD::SUBE:
  4555. return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
  4556. case ISD::SADDO:
  4557. case ISD::UADDO:
  4558. case ISD::SSUBO:
  4559. case ISD::USUBO:
  4560. case ISD::SMULO:
  4561. case ISD::UMULO:
  4562. return LowerXALUO(Op, DAG);
  4563. case ISD::FADD:
  4564. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
  4565. case ISD::FSUB:
  4566. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED);
  4567. case ISD::FMUL:
  4568. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED);
  4569. case ISD::FMA:
  4570. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
  4571. case ISD::FDIV:
  4572. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED);
  4573. case ISD::FNEG:
  4574. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU);
  4575. case ISD::FCEIL:
  4576. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU);
  4577. case ISD::FFLOOR:
  4578. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU);
  4579. case ISD::FNEARBYINT:
  4580. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU);
  4581. case ISD::FRINT:
  4582. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU);
  4583. case ISD::FROUND:
  4584. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU);
  4585. case ISD::FROUNDEVEN:
  4586. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU);
  4587. case ISD::FTRUNC:
  4588. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU);
  4589. case ISD::FSQRT:
  4590. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU);
  4591. case ISD::FABS:
  4592. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU);
  4593. case ISD::FP_ROUND:
  4594. case ISD::STRICT_FP_ROUND:
  4595. return LowerFP_ROUND(Op, DAG);
  4596. case ISD::FP_EXTEND:
  4597. return LowerFP_EXTEND(Op, DAG);
  4598. case ISD::FRAMEADDR:
  4599. return LowerFRAMEADDR(Op, DAG);
  4600. case ISD::SPONENTRY:
  4601. return LowerSPONENTRY(Op, DAG);
  4602. case ISD::RETURNADDR:
  4603. return LowerRETURNADDR(Op, DAG);
  4604. case ISD::ADDROFRETURNADDR:
  4605. return LowerADDROFRETURNADDR(Op, DAG);
  4606. case ISD::CONCAT_VECTORS:
  4607. return LowerCONCAT_VECTORS(Op, DAG);
  4608. case ISD::INSERT_VECTOR_ELT:
  4609. return LowerINSERT_VECTOR_ELT(Op, DAG);
  4610. case ISD::EXTRACT_VECTOR_ELT:
  4611. return LowerEXTRACT_VECTOR_ELT(Op, DAG);
  4612. case ISD::BUILD_VECTOR:
  4613. return LowerBUILD_VECTOR(Op, DAG);
  4614. case ISD::VECTOR_SHUFFLE:
  4615. return LowerVECTOR_SHUFFLE(Op, DAG);
  4616. case ISD::SPLAT_VECTOR:
  4617. return LowerSPLAT_VECTOR(Op, DAG);
  4618. case ISD::EXTRACT_SUBVECTOR:
  4619. return LowerEXTRACT_SUBVECTOR(Op, DAG);
  4620. case ISD::INSERT_SUBVECTOR:
  4621. return LowerINSERT_SUBVECTOR(Op, DAG);
  4622. case ISD::SDIV:
  4623. case ISD::UDIV:
  4624. return LowerDIV(Op, DAG);
  4625. case ISD::SMIN:
  4626. case ISD::UMIN:
  4627. case ISD::SMAX:
  4628. case ISD::UMAX:
  4629. return LowerMinMax(Op, DAG);
  4630. case ISD::SRA:
  4631. case ISD::SRL:
  4632. case ISD::SHL:
  4633. return LowerVectorSRA_SRL_SHL(Op, DAG);
  4634. case ISD::SHL_PARTS:
  4635. case ISD::SRL_PARTS:
  4636. case ISD::SRA_PARTS:
  4637. return LowerShiftParts(Op, DAG);
  4638. case ISD::CTPOP:
  4639. return LowerCTPOP(Op, DAG);
  4640. case ISD::FCOPYSIGN:
  4641. return LowerFCOPYSIGN(Op, DAG);
  4642. case ISD::OR:
  4643. return LowerVectorOR(Op, DAG);
  4644. case ISD::XOR:
  4645. return LowerXOR(Op, DAG);
  4646. case ISD::PREFETCH:
  4647. return LowerPREFETCH(Op, DAG);
  4648. case ISD::SINT_TO_FP:
  4649. case ISD::UINT_TO_FP:
  4650. case ISD::STRICT_SINT_TO_FP:
  4651. case ISD::STRICT_UINT_TO_FP:
  4652. return LowerINT_TO_FP(Op, DAG);
  4653. case ISD::FP_TO_SINT:
  4654. case ISD::FP_TO_UINT:
  4655. case ISD::STRICT_FP_TO_SINT:
  4656. case ISD::STRICT_FP_TO_UINT:
  4657. return LowerFP_TO_INT(Op, DAG);
  4658. case ISD::FP_TO_SINT_SAT:
  4659. case ISD::FP_TO_UINT_SAT:
  4660. return LowerFP_TO_INT_SAT(Op, DAG);
  4661. case ISD::FSINCOS:
  4662. return LowerFSINCOS(Op, DAG);
  4663. case ISD::FLT_ROUNDS_:
  4664. return LowerFLT_ROUNDS_(Op, DAG);
  4665. case ISD::SET_ROUNDING:
  4666. return LowerSET_ROUNDING(Op, DAG);
  4667. case ISD::MUL:
  4668. return LowerMUL(Op, DAG);
  4669. case ISD::MULHS:
  4670. return LowerToPredicatedOp(Op, DAG, AArch64ISD::MULHS_PRED,
  4671. /*OverrideNEON=*/true);
  4672. case ISD::MULHU:
  4673. return LowerToPredicatedOp(Op, DAG, AArch64ISD::MULHU_PRED,
  4674. /*OverrideNEON=*/true);
  4675. case ISD::INTRINSIC_W_CHAIN:
  4676. return LowerINTRINSIC_W_CHAIN(Op, DAG);
  4677. case ISD::INTRINSIC_WO_CHAIN:
  4678. return LowerINTRINSIC_WO_CHAIN(Op, DAG);
  4679. case ISD::ATOMIC_STORE:
  4680. if (cast<MemSDNode>(Op)->getMemoryVT() == MVT::i128) {
  4681. assert(Subtarget->hasLSE2());
  4682. return LowerStore128(Op, DAG);
  4683. }
  4684. return SDValue();
  4685. case ISD::STORE:
  4686. return LowerSTORE(Op, DAG);
  4687. case ISD::MSTORE:
  4688. return LowerFixedLengthVectorMStoreToSVE(Op, DAG);
  4689. case ISD::MGATHER:
  4690. return LowerMGATHER(Op, DAG);
  4691. case ISD::MSCATTER:
  4692. return LowerMSCATTER(Op, DAG);
  4693. case ISD::VECREDUCE_SEQ_FADD:
  4694. return LowerVECREDUCE_SEQ_FADD(Op, DAG);
  4695. case ISD::VECREDUCE_ADD:
  4696. case ISD::VECREDUCE_AND:
  4697. case ISD::VECREDUCE_OR:
  4698. case ISD::VECREDUCE_XOR:
  4699. case ISD::VECREDUCE_SMAX:
  4700. case ISD::VECREDUCE_SMIN:
  4701. case ISD::VECREDUCE_UMAX:
  4702. case ISD::VECREDUCE_UMIN:
  4703. case ISD::VECREDUCE_FADD:
  4704. case ISD::VECREDUCE_FMAX:
  4705. case ISD::VECREDUCE_FMIN:
  4706. return LowerVECREDUCE(Op, DAG);
  4707. case ISD::ATOMIC_LOAD_SUB:
  4708. return LowerATOMIC_LOAD_SUB(Op, DAG);
  4709. case ISD::ATOMIC_LOAD_AND:
  4710. return LowerATOMIC_LOAD_AND(Op, DAG);
  4711. case ISD::DYNAMIC_STACKALLOC:
  4712. return LowerDYNAMIC_STACKALLOC(Op, DAG);
  4713. case ISD::VSCALE:
  4714. return LowerVSCALE(Op, DAG);
  4715. case ISD::ANY_EXTEND:
  4716. case ISD::SIGN_EXTEND:
  4717. case ISD::ZERO_EXTEND:
  4718. return LowerFixedLengthVectorIntExtendToSVE(Op, DAG);
  4719. case ISD::SIGN_EXTEND_INREG: {
  4720. // Only custom lower when ExtraVT has a legal byte based element type.
  4721. EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  4722. EVT ExtraEltVT = ExtraVT.getVectorElementType();
  4723. if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) &&
  4724. (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64))
  4725. return SDValue();
  4726. return LowerToPredicatedOp(Op, DAG,
  4727. AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU);
  4728. }
  4729. case ISD::TRUNCATE:
  4730. return LowerTRUNCATE(Op, DAG);
  4731. case ISD::MLOAD:
  4732. return LowerMLOAD(Op, DAG);
  4733. case ISD::LOAD:
  4734. if (useSVEForFixedLengthVectorVT(Op.getValueType()))
  4735. return LowerFixedLengthVectorLoadToSVE(Op, DAG);
  4736. return LowerLOAD(Op, DAG);
  4737. case ISD::ADD:
  4738. return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
  4739. case ISD::AND:
  4740. return LowerToScalableOp(Op, DAG);
  4741. case ISD::SUB:
  4742. return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED);
  4743. case ISD::FMAXIMUM:
  4744. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAX_PRED);
  4745. case ISD::FMAXNUM:
  4746. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED);
  4747. case ISD::FMINIMUM:
  4748. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMIN_PRED);
  4749. case ISD::FMINNUM:
  4750. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED);
  4751. case ISD::VSELECT:
  4752. return LowerFixedLengthVectorSelectToSVE(Op, DAG);
  4753. case ISD::ABS:
  4754. return LowerABS(Op, DAG);
  4755. case ISD::ABDS:
  4756. return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABDS_PRED);
  4757. case ISD::ABDU:
  4758. return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABDU_PRED);
  4759. case ISD::BITREVERSE:
  4760. return LowerBitreverse(Op, DAG);
  4761. case ISD::BSWAP:
  4762. return LowerToPredicatedOp(Op, DAG, AArch64ISD::BSWAP_MERGE_PASSTHRU);
  4763. case ISD::CTLZ:
  4764. return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTLZ_MERGE_PASSTHRU,
  4765. /*OverrideNEON=*/true);
  4766. case ISD::CTTZ:
  4767. return LowerCTTZ(Op, DAG);
  4768. case ISD::VECTOR_SPLICE:
  4769. return LowerVECTOR_SPLICE(Op, DAG);
  4770. }
  4771. }
  4772. bool AArch64TargetLowering::mergeStoresAfterLegalization(EVT VT) const {
  4773. return !Subtarget->useSVEForFixedLengthVectors();
  4774. }
  4775. bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(
  4776. EVT VT, bool OverrideNEON) const {
  4777. if (!Subtarget->useSVEForFixedLengthVectors())
  4778. return false;
  4779. if (!VT.isFixedLengthVector())
  4780. return false;
  4781. // Don't use SVE for vectors we cannot scalarize if required.
  4782. switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
  4783. // Fixed length predicates should be promoted to i8.
  4784. // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
  4785. case MVT::i1:
  4786. default:
  4787. return false;
  4788. case MVT::i8:
  4789. case MVT::i16:
  4790. case MVT::i32:
  4791. case MVT::i64:
  4792. case MVT::f16:
  4793. case MVT::f32:
  4794. case MVT::f64:
  4795. break;
  4796. }
  4797. // All SVE implementations support NEON sized vectors.
  4798. if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector()))
  4799. return true;
  4800. // Ensure NEON MVTs only belong to a single register class.
  4801. if (VT.getFixedSizeInBits() <= 128)
  4802. return false;
  4803. // Don't use SVE for types that don't fit.
  4804. if (VT.getFixedSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
  4805. return false;
  4806. // TODO: Perhaps an artificial restriction, but worth having whilst getting
  4807. // the base fixed length SVE support in place.
  4808. if (!VT.isPow2VectorType())
  4809. return false;
  4810. return true;
  4811. }
  4812. //===----------------------------------------------------------------------===//
  4813. // Calling Convention Implementation
  4814. //===----------------------------------------------------------------------===//
  4815. /// Selects the correct CCAssignFn for a given CallingConvention value.
  4816. CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
  4817. bool IsVarArg) const {
  4818. switch (CC) {
  4819. default:
  4820. report_fatal_error("Unsupported calling convention.");
  4821. case CallingConv::WebKit_JS:
  4822. return CC_AArch64_WebKit_JS;
  4823. case CallingConv::GHC:
  4824. return CC_AArch64_GHC;
  4825. case CallingConv::C:
  4826. case CallingConv::Fast:
  4827. case CallingConv::PreserveMost:
  4828. case CallingConv::CXX_FAST_TLS:
  4829. case CallingConv::Swift:
  4830. case CallingConv::SwiftTail:
  4831. case CallingConv::Tail:
  4832. if (Subtarget->isTargetWindows() && IsVarArg)
  4833. return CC_AArch64_Win64_VarArg;
  4834. if (!Subtarget->isTargetDarwin())
  4835. return CC_AArch64_AAPCS;
  4836. if (!IsVarArg)
  4837. return CC_AArch64_DarwinPCS;
  4838. return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
  4839. : CC_AArch64_DarwinPCS_VarArg;
  4840. case CallingConv::Win64:
  4841. return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
  4842. case CallingConv::CFGuard_Check:
  4843. return CC_AArch64_Win64_CFGuard_Check;
  4844. case CallingConv::AArch64_VectorCall:
  4845. case CallingConv::AArch64_SVE_VectorCall:
  4846. return CC_AArch64_AAPCS;
  4847. }
  4848. }
  4849. CCAssignFn *
  4850. AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
  4851. return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
  4852. : RetCC_AArch64_AAPCS;
  4853. }
  4854. SDValue AArch64TargetLowering::LowerFormalArguments(
  4855. SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
  4856. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
  4857. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  4858. MachineFunction &MF = DAG.getMachineFunction();
  4859. MachineFrameInfo &MFI = MF.getFrameInfo();
  4860. bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
  4861. // Assign locations to all of the incoming arguments.
  4862. SmallVector<CCValAssign, 16> ArgLocs;
  4863. DenseMap<unsigned, SDValue> CopiedRegs;
  4864. CCState CCInfo(CallConv, isVarArg, MF, ArgLocs, *DAG.getContext());
  4865. // At this point, Ins[].VT may already be promoted to i32. To correctly
  4866. // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
  4867. // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
  4868. // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
  4869. // we use a special version of AnalyzeFormalArguments to pass in ValVT and
  4870. // LocVT.
  4871. unsigned NumArgs = Ins.size();
  4872. Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
  4873. unsigned CurArgIdx = 0;
  4874. for (unsigned i = 0; i != NumArgs; ++i) {
  4875. MVT ValVT = Ins[i].VT;
  4876. if (Ins[i].isOrigArg()) {
  4877. std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
  4878. CurArgIdx = Ins[i].getOrigArgIndex();
  4879. // Get type of the original argument.
  4880. EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
  4881. /*AllowUnknown*/ true);
  4882. MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
  4883. // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
  4884. if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
  4885. ValVT = MVT::i8;
  4886. else if (ActualMVT == MVT::i16)
  4887. ValVT = MVT::i16;
  4888. }
  4889. bool UseVarArgCC = false;
  4890. if (IsWin64)
  4891. UseVarArgCC = isVarArg;
  4892. CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, UseVarArgCC);
  4893. bool Res =
  4894. AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
  4895. assert(!Res && "Call operand has unhandled type");
  4896. (void)Res;
  4897. }
  4898. SmallVector<SDValue, 16> ArgValues;
  4899. unsigned ExtraArgLocs = 0;
  4900. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  4901. CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
  4902. if (Ins[i].Flags.isByVal()) {
  4903. // Byval is used for HFAs in the PCS, but the system should work in a
  4904. // non-compliant manner for larger structs.
  4905. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  4906. int Size = Ins[i].Flags.getByValSize();
  4907. unsigned NumRegs = (Size + 7) / 8;
  4908. // FIXME: This works on big-endian for composite byvals, which are the common
  4909. // case. It should also work for fundamental types too.
  4910. unsigned FrameIdx =
  4911. MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
  4912. SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
  4913. InVals.push_back(FrameIdxN);
  4914. continue;
  4915. }
  4916. if (Ins[i].Flags.isSwiftAsync())
  4917. MF.getInfo<AArch64FunctionInfo>()->setHasSwiftAsyncContext(true);
  4918. SDValue ArgValue;
  4919. if (VA.isRegLoc()) {
  4920. // Arguments stored in registers.
  4921. EVT RegVT = VA.getLocVT();
  4922. const TargetRegisterClass *RC;
  4923. if (RegVT == MVT::i32)
  4924. RC = &AArch64::GPR32RegClass;
  4925. else if (RegVT == MVT::i64)
  4926. RC = &AArch64::GPR64RegClass;
  4927. else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
  4928. RC = &AArch64::FPR16RegClass;
  4929. else if (RegVT == MVT::f32)
  4930. RC = &AArch64::FPR32RegClass;
  4931. else if (RegVT == MVT::f64 || RegVT.is64BitVector())
  4932. RC = &AArch64::FPR64RegClass;
  4933. else if (RegVT == MVT::f128 || RegVT.is128BitVector())
  4934. RC = &AArch64::FPR128RegClass;
  4935. else if (RegVT.isScalableVector() &&
  4936. RegVT.getVectorElementType() == MVT::i1)
  4937. RC = &AArch64::PPRRegClass;
  4938. else if (RegVT.isScalableVector())
  4939. RC = &AArch64::ZPRRegClass;
  4940. else
  4941. llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
  4942. // Transform the arguments in physical registers into virtual ones.
  4943. Register Reg = MF.addLiveIn(VA.getLocReg(), RC);
  4944. ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
  4945. // If this is an 8, 16 or 32-bit value, it is really passed promoted
  4946. // to 64 bits. Insert an assert[sz]ext to capture this, then
  4947. // truncate to the right size.
  4948. switch (VA.getLocInfo()) {
  4949. default:
  4950. llvm_unreachable("Unknown loc info!");
  4951. case CCValAssign::Full:
  4952. break;
  4953. case CCValAssign::Indirect:
  4954. assert(VA.getValVT().isScalableVector() &&
  4955. "Only scalable vectors can be passed indirectly");
  4956. break;
  4957. case CCValAssign::BCvt:
  4958. ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
  4959. break;
  4960. case CCValAssign::AExt:
  4961. case CCValAssign::SExt:
  4962. case CCValAssign::ZExt:
  4963. break;
  4964. case CCValAssign::AExtUpper:
  4965. ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
  4966. DAG.getConstant(32, DL, RegVT));
  4967. ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
  4968. break;
  4969. }
  4970. } else { // VA.isRegLoc()
  4971. assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
  4972. unsigned ArgOffset = VA.getLocMemOffset();
  4973. unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
  4974. ? VA.getLocVT().getSizeInBits()
  4975. : VA.getValVT().getSizeInBits()) / 8;
  4976. uint32_t BEAlign = 0;
  4977. if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
  4978. !Ins[i].Flags.isInConsecutiveRegs())
  4979. BEAlign = 8 - ArgSize;
  4980. int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
  4981. // Create load nodes to retrieve arguments from the stack.
  4982. SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
  4983. // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
  4984. ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
  4985. MVT MemVT = VA.getValVT();
  4986. switch (VA.getLocInfo()) {
  4987. default:
  4988. break;
  4989. case CCValAssign::Trunc:
  4990. case CCValAssign::BCvt:
  4991. MemVT = VA.getLocVT();
  4992. break;
  4993. case CCValAssign::Indirect:
  4994. assert(VA.getValVT().isScalableVector() &&
  4995. "Only scalable vectors can be passed indirectly");
  4996. MemVT = VA.getLocVT();
  4997. break;
  4998. case CCValAssign::SExt:
  4999. ExtType = ISD::SEXTLOAD;
  5000. break;
  5001. case CCValAssign::ZExt:
  5002. ExtType = ISD::ZEXTLOAD;
  5003. break;
  5004. case CCValAssign::AExt:
  5005. ExtType = ISD::EXTLOAD;
  5006. break;
  5007. }
  5008. ArgValue =
  5009. DAG.getExtLoad(ExtType, DL, VA.getLocVT(), Chain, FIN,
  5010. MachinePointerInfo::getFixedStack(MF, FI), MemVT);
  5011. }
  5012. if (VA.getLocInfo() == CCValAssign::Indirect) {
  5013. assert(VA.getValVT().isScalableVector() &&
  5014. "Only scalable vectors can be passed indirectly");
  5015. uint64_t PartSize = VA.getValVT().getStoreSize().getKnownMinSize();
  5016. unsigned NumParts = 1;
  5017. if (Ins[i].Flags.isInConsecutiveRegs()) {
  5018. assert(!Ins[i].Flags.isInConsecutiveRegsLast());
  5019. while (!Ins[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
  5020. ++NumParts;
  5021. }
  5022. MVT PartLoad = VA.getValVT();
  5023. SDValue Ptr = ArgValue;
  5024. // Ensure we generate all loads for each tuple part, whilst updating the
  5025. // pointer after each load correctly using vscale.
  5026. while (NumParts > 0) {
  5027. ArgValue = DAG.getLoad(PartLoad, DL, Chain, Ptr, MachinePointerInfo());
  5028. InVals.push_back(ArgValue);
  5029. NumParts--;
  5030. if (NumParts > 0) {
  5031. SDValue BytesIncrement = DAG.getVScale(
  5032. DL, Ptr.getValueType(),
  5033. APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize));
  5034. SDNodeFlags Flags;
  5035. Flags.setNoUnsignedWrap(true);
  5036. Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
  5037. BytesIncrement, Flags);
  5038. ExtraArgLocs++;
  5039. i++;
  5040. }
  5041. }
  5042. } else {
  5043. if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
  5044. ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
  5045. ArgValue, DAG.getValueType(MVT::i32));
  5046. // i1 arguments are zero-extended to i8 by the caller. Emit a
  5047. // hint to reflect this.
  5048. if (Ins[i].isOrigArg()) {
  5049. Argument *OrigArg = MF.getFunction().getArg(Ins[i].getOrigArgIndex());
  5050. if (OrigArg->getType()->isIntegerTy(1)) {
  5051. if (!Ins[i].Flags.isZExt()) {
  5052. ArgValue = DAG.getNode(AArch64ISD::ASSERT_ZEXT_BOOL, DL,
  5053. ArgValue.getValueType(), ArgValue);
  5054. }
  5055. }
  5056. }
  5057. InVals.push_back(ArgValue);
  5058. }
  5059. }
  5060. assert((ArgLocs.size() + ExtraArgLocs) == Ins.size());
  5061. // varargs
  5062. AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  5063. if (isVarArg) {
  5064. if (!Subtarget->isTargetDarwin() || IsWin64) {
  5065. // The AAPCS variadic function ABI is identical to the non-variadic
  5066. // one. As a result there may be more arguments in registers and we should
  5067. // save them for future reference.
  5068. // Win64 variadic functions also pass arguments in registers, but all float
  5069. // arguments are passed in integer registers.
  5070. saveVarArgRegisters(CCInfo, DAG, DL, Chain);
  5071. }
  5072. // This will point to the next argument passed via stack.
  5073. unsigned StackOffset = CCInfo.getNextStackOffset();
  5074. // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
  5075. StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
  5076. FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
  5077. if (MFI.hasMustTailInVarArgFunc()) {
  5078. SmallVector<MVT, 2> RegParmTypes;
  5079. RegParmTypes.push_back(MVT::i64);
  5080. RegParmTypes.push_back(MVT::f128);
  5081. // Compute the set of forwarded registers. The rest are scratch.
  5082. SmallVectorImpl<ForwardedRegister> &Forwards =
  5083. FuncInfo->getForwardedMustTailRegParms();
  5084. CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
  5085. CC_AArch64_AAPCS);
  5086. // Conservatively forward X8, since it might be used for aggregate return.
  5087. if (!CCInfo.isAllocated(AArch64::X8)) {
  5088. Register X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
  5089. Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
  5090. }
  5091. }
  5092. }
  5093. // On Windows, InReg pointers must be returned, so record the pointer in a
  5094. // virtual register at the start of the function so it can be returned in the
  5095. // epilogue.
  5096. if (IsWin64) {
  5097. for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
  5098. if (Ins[I].Flags.isInReg()) {
  5099. assert(!FuncInfo->getSRetReturnReg());
  5100. MVT PtrTy = getPointerTy(DAG.getDataLayout());
  5101. Register Reg =
  5102. MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
  5103. FuncInfo->setSRetReturnReg(Reg);
  5104. SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
  5105. Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
  5106. break;
  5107. }
  5108. }
  5109. }
  5110. unsigned StackArgSize = CCInfo.getNextStackOffset();
  5111. bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
  5112. if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
  5113. // This is a non-standard ABI so by fiat I say we're allowed to make full
  5114. // use of the stack area to be popped, which must be aligned to 16 bytes in
  5115. // any case:
  5116. StackArgSize = alignTo(StackArgSize, 16);
  5117. // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
  5118. // a multiple of 16.
  5119. FuncInfo->setArgumentStackToRestore(StackArgSize);
  5120. // This realignment carries over to the available bytes below. Our own
  5121. // callers will guarantee the space is free by giving an aligned value to
  5122. // CALLSEQ_START.
  5123. }
  5124. // Even if we're not expected to free up the space, it's useful to know how
  5125. // much is there while considering tail calls (because we can reuse it).
  5126. FuncInfo->setBytesInStackArgArea(StackArgSize);
  5127. if (Subtarget->hasCustomCallingConv())
  5128. Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
  5129. return Chain;
  5130. }
  5131. void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
  5132. SelectionDAG &DAG,
  5133. const SDLoc &DL,
  5134. SDValue &Chain) const {
  5135. MachineFunction &MF = DAG.getMachineFunction();
  5136. MachineFrameInfo &MFI = MF.getFrameInfo();
  5137. AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  5138. auto PtrVT = getPointerTy(DAG.getDataLayout());
  5139. bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
  5140. SmallVector<SDValue, 8> MemOps;
  5141. static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
  5142. AArch64::X3, AArch64::X4, AArch64::X5,
  5143. AArch64::X6, AArch64::X7 };
  5144. static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
  5145. unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
  5146. unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
  5147. int GPRIdx = 0;
  5148. if (GPRSaveSize != 0) {
  5149. if (IsWin64) {
  5150. GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
  5151. if (GPRSaveSize & 15)
  5152. // The extra size here, if triggered, will always be 8.
  5153. MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
  5154. } else
  5155. GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
  5156. SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
  5157. for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
  5158. Register VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
  5159. SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
  5160. SDValue Store =
  5161. DAG.getStore(Val.getValue(1), DL, Val, FIN,
  5162. IsWin64 ? MachinePointerInfo::getFixedStack(
  5163. MF, GPRIdx, (i - FirstVariadicGPR) * 8)
  5164. : MachinePointerInfo::getStack(MF, i * 8));
  5165. MemOps.push_back(Store);
  5166. FIN =
  5167. DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
  5168. }
  5169. }
  5170. FuncInfo->setVarArgsGPRIndex(GPRIdx);
  5171. FuncInfo->setVarArgsGPRSize(GPRSaveSize);
  5172. if (Subtarget->hasFPARMv8() && !IsWin64) {
  5173. static const MCPhysReg FPRArgRegs[] = {
  5174. AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
  5175. AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
  5176. static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
  5177. unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
  5178. unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
  5179. int FPRIdx = 0;
  5180. if (FPRSaveSize != 0) {
  5181. FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
  5182. SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
  5183. for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
  5184. Register VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
  5185. SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
  5186. SDValue Store = DAG.getStore(Val.getValue(1), DL, Val, FIN,
  5187. MachinePointerInfo::getStack(MF, i * 16));
  5188. MemOps.push_back(Store);
  5189. FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
  5190. DAG.getConstant(16, DL, PtrVT));
  5191. }
  5192. }
  5193. FuncInfo->setVarArgsFPRIndex(FPRIdx);
  5194. FuncInfo->setVarArgsFPRSize(FPRSaveSize);
  5195. }
  5196. if (!MemOps.empty()) {
  5197. Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
  5198. }
  5199. }
  5200. /// LowerCallResult - Lower the result values of a call into the
  5201. /// appropriate copies out of appropriate physical registers.
  5202. SDValue AArch64TargetLowering::LowerCallResult(
  5203. SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
  5204. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
  5205. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
  5206. SDValue ThisVal) const {
  5207. CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
  5208. // Assign locations to each value returned by this call.
  5209. SmallVector<CCValAssign, 16> RVLocs;
  5210. DenseMap<unsigned, SDValue> CopiedRegs;
  5211. CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
  5212. *DAG.getContext());
  5213. CCInfo.AnalyzeCallResult(Ins, RetCC);
  5214. // Copy all of the result registers out of their specified physreg.
  5215. for (unsigned i = 0; i != RVLocs.size(); ++i) {
  5216. CCValAssign VA = RVLocs[i];
  5217. // Pass 'this' value directly from the argument to return value, to avoid
  5218. // reg unit interference
  5219. if (i == 0 && isThisReturn) {
  5220. assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
  5221. "unexpected return calling convention register assignment");
  5222. InVals.push_back(ThisVal);
  5223. continue;
  5224. }
  5225. // Avoid copying a physreg twice since RegAllocFast is incompetent and only
  5226. // allows one use of a physreg per block.
  5227. SDValue Val = CopiedRegs.lookup(VA.getLocReg());
  5228. if (!Val) {
  5229. Val =
  5230. DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
  5231. Chain = Val.getValue(1);
  5232. InFlag = Val.getValue(2);
  5233. CopiedRegs[VA.getLocReg()] = Val;
  5234. }
  5235. switch (VA.getLocInfo()) {
  5236. default:
  5237. llvm_unreachable("Unknown loc info!");
  5238. case CCValAssign::Full:
  5239. break;
  5240. case CCValAssign::BCvt:
  5241. Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
  5242. break;
  5243. case CCValAssign::AExtUpper:
  5244. Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
  5245. DAG.getConstant(32, DL, VA.getLocVT()));
  5246. LLVM_FALLTHROUGH;
  5247. case CCValAssign::AExt:
  5248. LLVM_FALLTHROUGH;
  5249. case CCValAssign::ZExt:
  5250. Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
  5251. break;
  5252. }
  5253. InVals.push_back(Val);
  5254. }
  5255. return Chain;
  5256. }
  5257. /// Return true if the calling convention is one that we can guarantee TCO for.
  5258. static bool canGuaranteeTCO(CallingConv::ID CC, bool GuaranteeTailCalls) {
  5259. return (CC == CallingConv::Fast && GuaranteeTailCalls) ||
  5260. CC == CallingConv::Tail || CC == CallingConv::SwiftTail;
  5261. }
  5262. /// Return true if we might ever do TCO for calls with this calling convention.
  5263. static bool mayTailCallThisCC(CallingConv::ID CC) {
  5264. switch (CC) {
  5265. case CallingConv::C:
  5266. case CallingConv::AArch64_SVE_VectorCall:
  5267. case CallingConv::PreserveMost:
  5268. case CallingConv::Swift:
  5269. case CallingConv::SwiftTail:
  5270. case CallingConv::Tail:
  5271. case CallingConv::Fast:
  5272. return true;
  5273. default:
  5274. return false;
  5275. }
  5276. }
  5277. static void analyzeCallOperands(const AArch64TargetLowering &TLI,
  5278. const AArch64Subtarget *Subtarget,
  5279. const TargetLowering::CallLoweringInfo &CLI,
  5280. CCState &CCInfo) {
  5281. const SelectionDAG &DAG = CLI.DAG;
  5282. CallingConv::ID CalleeCC = CLI.CallConv;
  5283. bool IsVarArg = CLI.IsVarArg;
  5284. const SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
  5285. bool IsCalleeWin64 = Subtarget->isCallingConvWin64(CalleeCC);
  5286. unsigned NumArgs = Outs.size();
  5287. for (unsigned i = 0; i != NumArgs; ++i) {
  5288. MVT ArgVT = Outs[i].VT;
  5289. ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
  5290. bool UseVarArgCC = false;
  5291. if (IsVarArg) {
  5292. // On Windows, the fixed arguments in a vararg call are passed in GPRs
  5293. // too, so use the vararg CC to force them to integer registers.
  5294. if (IsCalleeWin64) {
  5295. UseVarArgCC = true;
  5296. } else {
  5297. UseVarArgCC = !Outs[i].IsFixed;
  5298. }
  5299. } else {
  5300. // Get type of the original argument.
  5301. EVT ActualVT =
  5302. TLI.getValueType(DAG.getDataLayout(), CLI.Args[Outs[i].OrigArgIndex].Ty,
  5303. /*AllowUnknown*/ true);
  5304. MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ArgVT;
  5305. // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
  5306. if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
  5307. ArgVT = MVT::i8;
  5308. else if (ActualMVT == MVT::i16)
  5309. ArgVT = MVT::i16;
  5310. }
  5311. CCAssignFn *AssignFn = TLI.CCAssignFnForCall(CalleeCC, UseVarArgCC);
  5312. bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
  5313. assert(!Res && "Call operand has unhandled type");
  5314. (void)Res;
  5315. }
  5316. }
  5317. bool AArch64TargetLowering::isEligibleForTailCallOptimization(
  5318. const CallLoweringInfo &CLI) const {
  5319. CallingConv::ID CalleeCC = CLI.CallConv;
  5320. if (!mayTailCallThisCC(CalleeCC))
  5321. return false;
  5322. SDValue Callee = CLI.Callee;
  5323. bool IsVarArg = CLI.IsVarArg;
  5324. const SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
  5325. const SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
  5326. const SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
  5327. const SelectionDAG &DAG = CLI.DAG;
  5328. MachineFunction &MF = DAG.getMachineFunction();
  5329. const Function &CallerF = MF.getFunction();
  5330. CallingConv::ID CallerCC = CallerF.getCallingConv();
  5331. // Functions using the C or Fast calling convention that have an SVE signature
  5332. // preserve more registers and should assume the SVE_VectorCall CC.
  5333. // The check for matching callee-saved regs will determine whether it is
  5334. // eligible for TCO.
  5335. if ((CallerCC == CallingConv::C || CallerCC == CallingConv::Fast) &&
  5336. AArch64RegisterInfo::hasSVEArgsOrReturn(&MF))
  5337. CallerCC = CallingConv::AArch64_SVE_VectorCall;
  5338. bool CCMatch = CallerCC == CalleeCC;
  5339. // When using the Windows calling convention on a non-windows OS, we want
  5340. // to back up and restore X18 in such functions; we can't do a tail call
  5341. // from those functions.
  5342. if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
  5343. CalleeCC != CallingConv::Win64)
  5344. return false;
  5345. // Byval parameters hand the function a pointer directly into the stack area
  5346. // we want to reuse during a tail call. Working around this *is* possible (see
  5347. // X86) but less efficient and uglier in LowerCall.
  5348. for (Function::const_arg_iterator i = CallerF.arg_begin(),
  5349. e = CallerF.arg_end();
  5350. i != e; ++i) {
  5351. if (i->hasByValAttr())
  5352. return false;
  5353. // On Windows, "inreg" attributes signify non-aggregate indirect returns.
  5354. // In this case, it is necessary to save/restore X0 in the callee. Tail
  5355. // call opt interferes with this. So we disable tail call opt when the
  5356. // caller has an argument with "inreg" attribute.
  5357. // FIXME: Check whether the callee also has an "inreg" argument.
  5358. if (i->hasInRegAttr())
  5359. return false;
  5360. }
  5361. if (canGuaranteeTCO(CalleeCC, getTargetMachine().Options.GuaranteedTailCallOpt))
  5362. return CCMatch;
  5363. // Externally-defined functions with weak linkage should not be
  5364. // tail-called on AArch64 when the OS does not support dynamic
  5365. // pre-emption of symbols, as the AAELF spec requires normal calls
  5366. // to undefined weak functions to be replaced with a NOP or jump to the
  5367. // next instruction. The behaviour of branch instructions in this
  5368. // situation (as used for tail calls) is implementation-defined, so we
  5369. // cannot rely on the linker replacing the tail call with a return.
  5370. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
  5371. const GlobalValue *GV = G->getGlobal();
  5372. const Triple &TT = getTargetMachine().getTargetTriple();
  5373. if (GV->hasExternalWeakLinkage() &&
  5374. (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
  5375. return false;
  5376. }
  5377. // Now we search for cases where we can use a tail call without changing the
  5378. // ABI. Sibcall is used in some places (particularly gcc) to refer to this
  5379. // concept.
  5380. // I want anyone implementing a new calling convention to think long and hard
  5381. // about this assert.
  5382. assert((!IsVarArg || CalleeCC == CallingConv::C) &&
  5383. "Unexpected variadic calling convention");
  5384. LLVMContext &C = *DAG.getContext();
  5385. // Check that the call results are passed in the same way.
  5386. if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
  5387. CCAssignFnForCall(CalleeCC, IsVarArg),
  5388. CCAssignFnForCall(CallerCC, IsVarArg)))
  5389. return false;
  5390. // The callee has to preserve all registers the caller needs to preserve.
  5391. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
  5392. const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
  5393. if (!CCMatch) {
  5394. const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
  5395. if (Subtarget->hasCustomCallingConv()) {
  5396. TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
  5397. TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
  5398. }
  5399. if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
  5400. return false;
  5401. }
  5402. // Nothing more to check if the callee is taking no arguments
  5403. if (Outs.empty())
  5404. return true;
  5405. SmallVector<CCValAssign, 16> ArgLocs;
  5406. CCState CCInfo(CalleeCC, IsVarArg, MF, ArgLocs, C);
  5407. analyzeCallOperands(*this, Subtarget, CLI, CCInfo);
  5408. if (IsVarArg && !(CLI.CB && CLI.CB->isMustTailCall())) {
  5409. // When we are musttail, additional checks have been done and we can safely ignore this check
  5410. // At least two cases here: if caller is fastcc then we can't have any
  5411. // memory arguments (we'd be expected to clean up the stack afterwards). If
  5412. // caller is C then we could potentially use its argument area.
  5413. // FIXME: for now we take the most conservative of these in both cases:
  5414. // disallow all variadic memory operands.
  5415. for (const CCValAssign &ArgLoc : ArgLocs)
  5416. if (!ArgLoc.isRegLoc())
  5417. return false;
  5418. }
  5419. const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  5420. // If any of the arguments is passed indirectly, it must be SVE, so the
  5421. // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
  5422. // allocate space on the stack. That is why we determine this explicitly here
  5423. // the call cannot be a tailcall.
  5424. if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
  5425. assert((A.getLocInfo() != CCValAssign::Indirect ||
  5426. A.getValVT().isScalableVector()) &&
  5427. "Expected value to be scalable");
  5428. return A.getLocInfo() == CCValAssign::Indirect;
  5429. }))
  5430. return false;
  5431. // If the stack arguments for this call do not fit into our own save area then
  5432. // the call cannot be made tail.
  5433. if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
  5434. return false;
  5435. const MachineRegisterInfo &MRI = MF.getRegInfo();
  5436. if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
  5437. return false;
  5438. return true;
  5439. }
  5440. SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
  5441. SelectionDAG &DAG,
  5442. MachineFrameInfo &MFI,
  5443. int ClobberedFI) const {
  5444. SmallVector<SDValue, 8> ArgChains;
  5445. int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
  5446. int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
  5447. // Include the original chain at the beginning of the list. When this is
  5448. // used by target LowerCall hooks, this helps legalize find the
  5449. // CALLSEQ_BEGIN node.
  5450. ArgChains.push_back(Chain);
  5451. // Add a chain value for each stack argument corresponding
  5452. for (SDNode *U : DAG.getEntryNode().getNode()->uses())
  5453. if (LoadSDNode *L = dyn_cast<LoadSDNode>(U))
  5454. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
  5455. if (FI->getIndex() < 0) {
  5456. int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
  5457. int64_t InLastByte = InFirstByte;
  5458. InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
  5459. if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
  5460. (FirstByte <= InFirstByte && InFirstByte <= LastByte))
  5461. ArgChains.push_back(SDValue(L, 1));
  5462. }
  5463. // Build a tokenfactor for all the chains.
  5464. return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
  5465. }
  5466. bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
  5467. bool TailCallOpt) const {
  5468. return (CallCC == CallingConv::Fast && TailCallOpt) ||
  5469. CallCC == CallingConv::Tail || CallCC == CallingConv::SwiftTail;
  5470. }
  5471. // Check if the value is zero-extended from i1 to i8
  5472. static bool checkZExtBool(SDValue Arg, const SelectionDAG &DAG) {
  5473. unsigned SizeInBits = Arg.getValueType().getSizeInBits();
  5474. if (SizeInBits < 8)
  5475. return false;
  5476. APInt LowBits(SizeInBits, 0xFF);
  5477. APInt RequredZero(SizeInBits, 0xFE);
  5478. KnownBits Bits = DAG.computeKnownBits(Arg, LowBits, 4);
  5479. bool ZExtBool = (Bits.Zero & RequredZero) == RequredZero;
  5480. return ZExtBool;
  5481. }
  5482. /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
  5483. /// and add input and output parameter nodes.
  5484. SDValue
  5485. AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
  5486. SmallVectorImpl<SDValue> &InVals) const {
  5487. SelectionDAG &DAG = CLI.DAG;
  5488. SDLoc &DL = CLI.DL;
  5489. SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
  5490. SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
  5491. SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
  5492. SDValue Chain = CLI.Chain;
  5493. SDValue Callee = CLI.Callee;
  5494. bool &IsTailCall = CLI.IsTailCall;
  5495. CallingConv::ID &CallConv = CLI.CallConv;
  5496. bool IsVarArg = CLI.IsVarArg;
  5497. MachineFunction &MF = DAG.getMachineFunction();
  5498. MachineFunction::CallSiteInfo CSInfo;
  5499. bool IsThisReturn = false;
  5500. AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  5501. bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
  5502. bool IsSibCall = false;
  5503. bool GuardWithBTI = false;
  5504. if (CLI.CB && CLI.CB->getAttributes().hasFnAttr(Attribute::ReturnsTwice) &&
  5505. !Subtarget->noBTIAtReturnTwice()) {
  5506. GuardWithBTI = FuncInfo->branchTargetEnforcement();
  5507. }
  5508. // Check callee args/returns for SVE registers and set calling convention
  5509. // accordingly.
  5510. if (CallConv == CallingConv::C || CallConv == CallingConv::Fast) {
  5511. bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
  5512. return Out.VT.isScalableVector();
  5513. });
  5514. bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
  5515. return In.VT.isScalableVector();
  5516. });
  5517. if (CalleeInSVE || CalleeOutSVE)
  5518. CallConv = CallingConv::AArch64_SVE_VectorCall;
  5519. }
  5520. if (IsTailCall) {
  5521. // Check if it's really possible to do a tail call.
  5522. IsTailCall = isEligibleForTailCallOptimization(CLI);
  5523. // A sibling call is one where we're under the usual C ABI and not planning
  5524. // to change that but can still do a tail call:
  5525. if (!TailCallOpt && IsTailCall && CallConv != CallingConv::Tail &&
  5526. CallConv != CallingConv::SwiftTail)
  5527. IsSibCall = true;
  5528. if (IsTailCall)
  5529. ++NumTailCalls;
  5530. }
  5531. if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
  5532. report_fatal_error("failed to perform tail call elimination on a call "
  5533. "site marked musttail");
  5534. // Analyze operands of the call, assigning locations to each operand.
  5535. SmallVector<CCValAssign, 16> ArgLocs;
  5536. CCState CCInfo(CallConv, IsVarArg, MF, ArgLocs, *DAG.getContext());
  5537. if (IsVarArg) {
  5538. unsigned NumArgs = Outs.size();
  5539. for (unsigned i = 0; i != NumArgs; ++i) {
  5540. if (!Outs[i].IsFixed && Outs[i].VT.isScalableVector())
  5541. report_fatal_error("Passing SVE types to variadic functions is "
  5542. "currently not supported");
  5543. }
  5544. }
  5545. analyzeCallOperands(*this, Subtarget, CLI, CCInfo);
  5546. // Get a count of how many bytes are to be pushed on the stack.
  5547. unsigned NumBytes = CCInfo.getNextStackOffset();
  5548. if (IsSibCall) {
  5549. // Since we're not changing the ABI to make this a tail call, the memory
  5550. // operands are already available in the caller's incoming argument space.
  5551. NumBytes = 0;
  5552. }
  5553. // FPDiff is the byte offset of the call's argument area from the callee's.
  5554. // Stores to callee stack arguments will be placed in FixedStackSlots offset
  5555. // by this amount for a tail call. In a sibling call it must be 0 because the
  5556. // caller will deallocate the entire stack and the callee still expects its
  5557. // arguments to begin at SP+0. Completely unused for non-tail calls.
  5558. int FPDiff = 0;
  5559. if (IsTailCall && !IsSibCall) {
  5560. unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
  5561. // Since callee will pop argument stack as a tail call, we must keep the
  5562. // popped size 16-byte aligned.
  5563. NumBytes = alignTo(NumBytes, 16);
  5564. // FPDiff will be negative if this tail call requires more space than we
  5565. // would automatically have in our incoming argument space. Positive if we
  5566. // can actually shrink the stack.
  5567. FPDiff = NumReusableBytes - NumBytes;
  5568. // Update the required reserved area if this is the tail call requiring the
  5569. // most argument stack space.
  5570. if (FPDiff < 0 && FuncInfo->getTailCallReservedStack() < (unsigned)-FPDiff)
  5571. FuncInfo->setTailCallReservedStack(-FPDiff);
  5572. // The stack pointer must be 16-byte aligned at all times it's used for a
  5573. // memory operation, which in practice means at *all* times and in
  5574. // particular across call boundaries. Therefore our own arguments started at
  5575. // a 16-byte aligned SP and the delta applied for the tail call should
  5576. // satisfy the same constraint.
  5577. assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
  5578. }
  5579. // Adjust the stack pointer for the new arguments...
  5580. // These operations are automatically eliminated by the prolog/epilog pass
  5581. if (!IsSibCall)
  5582. Chain = DAG.getCALLSEQ_START(Chain, IsTailCall ? 0 : NumBytes, 0, DL);
  5583. SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
  5584. getPointerTy(DAG.getDataLayout()));
  5585. SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
  5586. SmallSet<unsigned, 8> RegsUsed;
  5587. SmallVector<SDValue, 8> MemOpChains;
  5588. auto PtrVT = getPointerTy(DAG.getDataLayout());
  5589. if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
  5590. const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
  5591. for (const auto &F : Forwards) {
  5592. SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
  5593. RegsToPass.emplace_back(F.PReg, Val);
  5594. }
  5595. }
  5596. // Walk the register/memloc assignments, inserting copies/loads.
  5597. unsigned ExtraArgLocs = 0;
  5598. for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
  5599. CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
  5600. SDValue Arg = OutVals[i];
  5601. ISD::ArgFlagsTy Flags = Outs[i].Flags;
  5602. // Promote the value if needed.
  5603. switch (VA.getLocInfo()) {
  5604. default:
  5605. llvm_unreachable("Unknown loc info!");
  5606. case CCValAssign::Full:
  5607. break;
  5608. case CCValAssign::SExt:
  5609. Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
  5610. break;
  5611. case CCValAssign::ZExt:
  5612. Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
  5613. break;
  5614. case CCValAssign::AExt:
  5615. if (Outs[i].ArgVT == MVT::i1) {
  5616. // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
  5617. //
  5618. // Check if we actually have to do this, because the value may
  5619. // already be zero-extended.
  5620. //
  5621. // We cannot just emit a (zext i8 (trunc (assert-zext i8)))
  5622. // and rely on DAGCombiner to fold this, because the following
  5623. // (anyext i32) is combined with (zext i8) in DAG.getNode:
  5624. //
  5625. // (ext (zext x)) -> (zext x)
  5626. //
  5627. // This will give us (zext i32), which we cannot remove, so
  5628. // try to check this beforehand.
  5629. if (!checkZExtBool(Arg, DAG)) {
  5630. Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
  5631. Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
  5632. }
  5633. }
  5634. Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
  5635. break;
  5636. case CCValAssign::AExtUpper:
  5637. assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
  5638. Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
  5639. Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
  5640. DAG.getConstant(32, DL, VA.getLocVT()));
  5641. break;
  5642. case CCValAssign::BCvt:
  5643. Arg = DAG.getBitcast(VA.getLocVT(), Arg);
  5644. break;
  5645. case CCValAssign::Trunc:
  5646. Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
  5647. break;
  5648. case CCValAssign::FPExt:
  5649. Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
  5650. break;
  5651. case CCValAssign::Indirect:
  5652. assert(VA.getValVT().isScalableVector() &&
  5653. "Only scalable vectors can be passed indirectly");
  5654. uint64_t StoreSize = VA.getValVT().getStoreSize().getKnownMinSize();
  5655. uint64_t PartSize = StoreSize;
  5656. unsigned NumParts = 1;
  5657. if (Outs[i].Flags.isInConsecutiveRegs()) {
  5658. assert(!Outs[i].Flags.isInConsecutiveRegsLast());
  5659. while (!Outs[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
  5660. ++NumParts;
  5661. StoreSize *= NumParts;
  5662. }
  5663. MachineFrameInfo &MFI = MF.getFrameInfo();
  5664. Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
  5665. Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
  5666. int FI = MFI.CreateStackObject(StoreSize, Alignment, false);
  5667. MFI.setStackID(FI, TargetStackID::ScalableVector);
  5668. MachinePointerInfo MPI = MachinePointerInfo::getFixedStack(MF, FI);
  5669. SDValue Ptr = DAG.getFrameIndex(
  5670. FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
  5671. SDValue SpillSlot = Ptr;
  5672. // Ensure we generate all stores for each tuple part, whilst updating the
  5673. // pointer after each store correctly using vscale.
  5674. while (NumParts) {
  5675. Chain = DAG.getStore(Chain, DL, OutVals[i], Ptr, MPI);
  5676. NumParts--;
  5677. if (NumParts > 0) {
  5678. SDValue BytesIncrement = DAG.getVScale(
  5679. DL, Ptr.getValueType(),
  5680. APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize));
  5681. SDNodeFlags Flags;
  5682. Flags.setNoUnsignedWrap(true);
  5683. MPI = MachinePointerInfo(MPI.getAddrSpace());
  5684. Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
  5685. BytesIncrement, Flags);
  5686. ExtraArgLocs++;
  5687. i++;
  5688. }
  5689. }
  5690. Arg = SpillSlot;
  5691. break;
  5692. }
  5693. if (VA.isRegLoc()) {
  5694. if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
  5695. Outs[0].VT == MVT::i64) {
  5696. assert(VA.getLocVT() == MVT::i64 &&
  5697. "unexpected calling convention register assignment");
  5698. assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
  5699. "unexpected use of 'returned'");
  5700. IsThisReturn = true;
  5701. }
  5702. if (RegsUsed.count(VA.getLocReg())) {
  5703. // If this register has already been used then we're trying to pack
  5704. // parts of an [N x i32] into an X-register. The extension type will
  5705. // take care of putting the two halves in the right place but we have to
  5706. // combine them.
  5707. SDValue &Bits =
  5708. llvm::find_if(RegsToPass,
  5709. [=](const std::pair<unsigned, SDValue> &Elt) {
  5710. return Elt.first == VA.getLocReg();
  5711. })
  5712. ->second;
  5713. Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
  5714. // Call site info is used for function's parameter entry value
  5715. // tracking. For now we track only simple cases when parameter
  5716. // is transferred through whole register.
  5717. llvm::erase_if(CSInfo, [&VA](MachineFunction::ArgRegPair ArgReg) {
  5718. return ArgReg.Reg == VA.getLocReg();
  5719. });
  5720. } else {
  5721. RegsToPass.emplace_back(VA.getLocReg(), Arg);
  5722. RegsUsed.insert(VA.getLocReg());
  5723. const TargetOptions &Options = DAG.getTarget().Options;
  5724. if (Options.EmitCallSiteInfo)
  5725. CSInfo.emplace_back(VA.getLocReg(), i);
  5726. }
  5727. } else {
  5728. assert(VA.isMemLoc());
  5729. SDValue DstAddr;
  5730. MachinePointerInfo DstInfo;
  5731. // FIXME: This works on big-endian for composite byvals, which are the
  5732. // common case. It should also work for fundamental types too.
  5733. uint32_t BEAlign = 0;
  5734. unsigned OpSize;
  5735. if (VA.getLocInfo() == CCValAssign::Indirect ||
  5736. VA.getLocInfo() == CCValAssign::Trunc)
  5737. OpSize = VA.getLocVT().getFixedSizeInBits();
  5738. else
  5739. OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
  5740. : VA.getValVT().getSizeInBits();
  5741. OpSize = (OpSize + 7) / 8;
  5742. if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
  5743. !Flags.isInConsecutiveRegs()) {
  5744. if (OpSize < 8)
  5745. BEAlign = 8 - OpSize;
  5746. }
  5747. unsigned LocMemOffset = VA.getLocMemOffset();
  5748. int32_t Offset = LocMemOffset + BEAlign;
  5749. SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
  5750. PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
  5751. if (IsTailCall) {
  5752. Offset = Offset + FPDiff;
  5753. int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
  5754. DstAddr = DAG.getFrameIndex(FI, PtrVT);
  5755. DstInfo = MachinePointerInfo::getFixedStack(MF, FI);
  5756. // Make sure any stack arguments overlapping with where we're storing
  5757. // are loaded before this eventual operation. Otherwise they'll be
  5758. // clobbered.
  5759. Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
  5760. } else {
  5761. SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
  5762. DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
  5763. DstInfo = MachinePointerInfo::getStack(MF, LocMemOffset);
  5764. }
  5765. if (Outs[i].Flags.isByVal()) {
  5766. SDValue SizeNode =
  5767. DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
  5768. SDValue Cpy = DAG.getMemcpy(
  5769. Chain, DL, DstAddr, Arg, SizeNode,
  5770. Outs[i].Flags.getNonZeroByValAlign(),
  5771. /*isVol = */ false, /*AlwaysInline = */ false,
  5772. /*isTailCall = */ false, DstInfo, MachinePointerInfo());
  5773. MemOpChains.push_back(Cpy);
  5774. } else {
  5775. // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
  5776. // promoted to a legal register type i32, we should truncate Arg back to
  5777. // i1/i8/i16.
  5778. if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
  5779. VA.getValVT() == MVT::i16)
  5780. Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
  5781. SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
  5782. MemOpChains.push_back(Store);
  5783. }
  5784. }
  5785. }
  5786. if (!MemOpChains.empty())
  5787. Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
  5788. // Build a sequence of copy-to-reg nodes chained together with token chain
  5789. // and flag operands which copy the outgoing args into the appropriate regs.
  5790. SDValue InFlag;
  5791. for (auto &RegToPass : RegsToPass) {
  5792. Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
  5793. RegToPass.second, InFlag);
  5794. InFlag = Chain.getValue(1);
  5795. }
  5796. // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
  5797. // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
  5798. // node so that legalize doesn't hack it.
  5799. if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
  5800. auto GV = G->getGlobal();
  5801. unsigned OpFlags =
  5802. Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
  5803. if (OpFlags & AArch64II::MO_GOT) {
  5804. Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
  5805. Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
  5806. } else {
  5807. const GlobalValue *GV = G->getGlobal();
  5808. Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
  5809. }
  5810. } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
  5811. if (getTargetMachine().getCodeModel() == CodeModel::Large &&
  5812. Subtarget->isTargetMachO()) {
  5813. const char *Sym = S->getSymbol();
  5814. Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
  5815. Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
  5816. } else {
  5817. const char *Sym = S->getSymbol();
  5818. Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
  5819. }
  5820. }
  5821. // We don't usually want to end the call-sequence here because we would tidy
  5822. // the frame up *after* the call, however in the ABI-changing tail-call case
  5823. // we've carefully laid out the parameters so that when sp is reset they'll be
  5824. // in the correct location.
  5825. if (IsTailCall && !IsSibCall) {
  5826. Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, DL, true),
  5827. DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
  5828. InFlag = Chain.getValue(1);
  5829. }
  5830. std::vector<SDValue> Ops;
  5831. Ops.push_back(Chain);
  5832. Ops.push_back(Callee);
  5833. if (IsTailCall) {
  5834. // Each tail call may have to adjust the stack by a different amount, so
  5835. // this information must travel along with the operation for eventual
  5836. // consumption by emitEpilogue.
  5837. Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
  5838. }
  5839. // Add argument registers to the end of the list so that they are known live
  5840. // into the call.
  5841. for (auto &RegToPass : RegsToPass)
  5842. Ops.push_back(DAG.getRegister(RegToPass.first,
  5843. RegToPass.second.getValueType()));
  5844. // Add a register mask operand representing the call-preserved registers.
  5845. const uint32_t *Mask;
  5846. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
  5847. if (IsThisReturn) {
  5848. // For 'this' returns, use the X0-preserving mask if applicable
  5849. Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
  5850. if (!Mask) {
  5851. IsThisReturn = false;
  5852. Mask = TRI->getCallPreservedMask(MF, CallConv);
  5853. }
  5854. } else
  5855. Mask = TRI->getCallPreservedMask(MF, CallConv);
  5856. if (Subtarget->hasCustomCallingConv())
  5857. TRI->UpdateCustomCallPreservedMask(MF, &Mask);
  5858. if (TRI->isAnyArgRegReserved(MF))
  5859. TRI->emitReservedArgRegCallError(MF);
  5860. assert(Mask && "Missing call preserved mask for calling convention");
  5861. Ops.push_back(DAG.getRegisterMask(Mask));
  5862. if (InFlag.getNode())
  5863. Ops.push_back(InFlag);
  5864. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5865. // If we're doing a tall call, use a TC_RETURN here rather than an
  5866. // actual call instruction.
  5867. if (IsTailCall) {
  5868. MF.getFrameInfo().setHasTailCall();
  5869. SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
  5870. DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
  5871. return Ret;
  5872. }
  5873. unsigned CallOpc = AArch64ISD::CALL;
  5874. // Calls with operand bundle "clang.arc.attachedcall" are special. They should
  5875. // be expanded to the call, directly followed by a special marker sequence and
  5876. // a call to an ObjC library function. Use CALL_RVMARKER to do that.
  5877. if (CLI.CB && objcarc::hasAttachedCallOpBundle(CLI.CB)) {
  5878. assert(!IsTailCall &&
  5879. "tail calls cannot be marked with clang.arc.attachedcall");
  5880. CallOpc = AArch64ISD::CALL_RVMARKER;
  5881. // Add a target global address for the retainRV/claimRV runtime function
  5882. // just before the call target.
  5883. Function *ARCFn = *objcarc::getAttachedARCFunction(CLI.CB);
  5884. auto GA = DAG.getTargetGlobalAddress(ARCFn, DL, PtrVT);
  5885. Ops.insert(Ops.begin() + 1, GA);
  5886. } else if (GuardWithBTI)
  5887. CallOpc = AArch64ISD::CALL_BTI;
  5888. // Returns a chain and a flag for retval copy to use.
  5889. Chain = DAG.getNode(CallOpc, DL, NodeTys, Ops);
  5890. DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
  5891. InFlag = Chain.getValue(1);
  5892. DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
  5893. uint64_t CalleePopBytes =
  5894. DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
  5895. Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
  5896. DAG.getIntPtrConstant(CalleePopBytes, DL, true),
  5897. InFlag, DL);
  5898. if (!Ins.empty())
  5899. InFlag = Chain.getValue(1);
  5900. // Handle result values, copying them out of physregs into vregs that we
  5901. // return.
  5902. return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
  5903. InVals, IsThisReturn,
  5904. IsThisReturn ? OutVals[0] : SDValue());
  5905. }
  5906. bool AArch64TargetLowering::CanLowerReturn(
  5907. CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
  5908. const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
  5909. CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
  5910. SmallVector<CCValAssign, 16> RVLocs;
  5911. CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
  5912. return CCInfo.CheckReturn(Outs, RetCC);
  5913. }
  5914. SDValue
  5915. AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
  5916. bool isVarArg,
  5917. const SmallVectorImpl<ISD::OutputArg> &Outs,
  5918. const SmallVectorImpl<SDValue> &OutVals,
  5919. const SDLoc &DL, SelectionDAG &DAG) const {
  5920. auto &MF = DAG.getMachineFunction();
  5921. auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  5922. CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
  5923. SmallVector<CCValAssign, 16> RVLocs;
  5924. CCState CCInfo(CallConv, isVarArg, MF, RVLocs, *DAG.getContext());
  5925. CCInfo.AnalyzeReturn(Outs, RetCC);
  5926. // Copy the result values into the output registers.
  5927. SDValue Flag;
  5928. SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
  5929. SmallSet<unsigned, 4> RegsUsed;
  5930. for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
  5931. ++i, ++realRVLocIdx) {
  5932. CCValAssign &VA = RVLocs[i];
  5933. assert(VA.isRegLoc() && "Can only return in registers!");
  5934. SDValue Arg = OutVals[realRVLocIdx];
  5935. switch (VA.getLocInfo()) {
  5936. default:
  5937. llvm_unreachable("Unknown loc info!");
  5938. case CCValAssign::Full:
  5939. if (Outs[i].ArgVT == MVT::i1) {
  5940. // AAPCS requires i1 to be zero-extended to i8 by the producer of the
  5941. // value. This is strictly redundant on Darwin (which uses "zeroext
  5942. // i1"), but will be optimised out before ISel.
  5943. Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
  5944. Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
  5945. }
  5946. break;
  5947. case CCValAssign::BCvt:
  5948. Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
  5949. break;
  5950. case CCValAssign::AExt:
  5951. case CCValAssign::ZExt:
  5952. Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
  5953. break;
  5954. case CCValAssign::AExtUpper:
  5955. assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
  5956. Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
  5957. Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
  5958. DAG.getConstant(32, DL, VA.getLocVT()));
  5959. break;
  5960. }
  5961. if (RegsUsed.count(VA.getLocReg())) {
  5962. SDValue &Bits =
  5963. llvm::find_if(RetVals, [=](const std::pair<unsigned, SDValue> &Elt) {
  5964. return Elt.first == VA.getLocReg();
  5965. })->second;
  5966. Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
  5967. } else {
  5968. RetVals.emplace_back(VA.getLocReg(), Arg);
  5969. RegsUsed.insert(VA.getLocReg());
  5970. }
  5971. }
  5972. SmallVector<SDValue, 4> RetOps(1, Chain);
  5973. for (auto &RetVal : RetVals) {
  5974. Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
  5975. Flag = Chain.getValue(1);
  5976. RetOps.push_back(
  5977. DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
  5978. }
  5979. // Windows AArch64 ABIs require that for returning structs by value we copy
  5980. // the sret argument into X0 for the return.
  5981. // We saved the argument into a virtual register in the entry block,
  5982. // so now we copy the value out and into X0.
  5983. if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
  5984. SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
  5985. getPointerTy(MF.getDataLayout()));
  5986. unsigned RetValReg = AArch64::X0;
  5987. Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
  5988. Flag = Chain.getValue(1);
  5989. RetOps.push_back(
  5990. DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
  5991. }
  5992. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
  5993. const MCPhysReg *I = TRI->getCalleeSavedRegsViaCopy(&MF);
  5994. if (I) {
  5995. for (; *I; ++I) {
  5996. if (AArch64::GPR64RegClass.contains(*I))
  5997. RetOps.push_back(DAG.getRegister(*I, MVT::i64));
  5998. else if (AArch64::FPR64RegClass.contains(*I))
  5999. RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
  6000. else
  6001. llvm_unreachable("Unexpected register class in CSRsViaCopy!");
  6002. }
  6003. }
  6004. RetOps[0] = Chain; // Update chain.
  6005. // Add the flag if we have it.
  6006. if (Flag.getNode())
  6007. RetOps.push_back(Flag);
  6008. return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
  6009. }
  6010. //===----------------------------------------------------------------------===//
  6011. // Other Lowering Code
  6012. //===----------------------------------------------------------------------===//
  6013. SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
  6014. SelectionDAG &DAG,
  6015. unsigned Flag) const {
  6016. return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
  6017. N->getOffset(), Flag);
  6018. }
  6019. SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
  6020. SelectionDAG &DAG,
  6021. unsigned Flag) const {
  6022. return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
  6023. }
  6024. SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
  6025. SelectionDAG &DAG,
  6026. unsigned Flag) const {
  6027. return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
  6028. N->getOffset(), Flag);
  6029. }
  6030. SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
  6031. SelectionDAG &DAG,
  6032. unsigned Flag) const {
  6033. return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
  6034. }
  6035. // (loadGOT sym)
  6036. template <class NodeTy>
  6037. SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
  6038. unsigned Flags) const {
  6039. LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
  6040. SDLoc DL(N);
  6041. EVT Ty = getPointerTy(DAG.getDataLayout());
  6042. SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
  6043. // FIXME: Once remat is capable of dealing with instructions with register
  6044. // operands, expand this into two nodes instead of using a wrapper node.
  6045. return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
  6046. }
  6047. // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
  6048. template <class NodeTy>
  6049. SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
  6050. unsigned Flags) const {
  6051. LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
  6052. SDLoc DL(N);
  6053. EVT Ty = getPointerTy(DAG.getDataLayout());
  6054. const unsigned char MO_NC = AArch64II::MO_NC;
  6055. return DAG.getNode(
  6056. AArch64ISD::WrapperLarge, DL, Ty,
  6057. getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
  6058. getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
  6059. getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
  6060. getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
  6061. }
  6062. // (addlow (adrp %hi(sym)) %lo(sym))
  6063. template <class NodeTy>
  6064. SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
  6065. unsigned Flags) const {
  6066. LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
  6067. SDLoc DL(N);
  6068. EVT Ty = getPointerTy(DAG.getDataLayout());
  6069. SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
  6070. SDValue Lo = getTargetNode(N, Ty, DAG,
  6071. AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
  6072. SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
  6073. return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
  6074. }
  6075. // (adr sym)
  6076. template <class NodeTy>
  6077. SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
  6078. unsigned Flags) const {
  6079. LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
  6080. SDLoc DL(N);
  6081. EVT Ty = getPointerTy(DAG.getDataLayout());
  6082. SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
  6083. return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
  6084. }
  6085. SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
  6086. SelectionDAG &DAG) const {
  6087. GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
  6088. const GlobalValue *GV = GN->getGlobal();
  6089. unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
  6090. if (OpFlags != AArch64II::MO_NO_FLAG)
  6091. assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
  6092. "unexpected offset in global node");
  6093. // This also catches the large code model case for Darwin, and tiny code
  6094. // model with got relocations.
  6095. if ((OpFlags & AArch64II::MO_GOT) != 0) {
  6096. return getGOT(GN, DAG, OpFlags);
  6097. }
  6098. SDValue Result;
  6099. if (getTargetMachine().getCodeModel() == CodeModel::Large) {
  6100. Result = getAddrLarge(GN, DAG, OpFlags);
  6101. } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
  6102. Result = getAddrTiny(GN, DAG, OpFlags);
  6103. } else {
  6104. Result = getAddr(GN, DAG, OpFlags);
  6105. }
  6106. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6107. SDLoc DL(GN);
  6108. if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
  6109. Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
  6110. MachinePointerInfo::getGOT(DAG.getMachineFunction()));
  6111. return Result;
  6112. }
  6113. /// Convert a TLS address reference into the correct sequence of loads
  6114. /// and calls to compute the variable's address (for Darwin, currently) and
  6115. /// return an SDValue containing the final node.
  6116. /// Darwin only has one TLS scheme which must be capable of dealing with the
  6117. /// fully general situation, in the worst case. This means:
  6118. /// + "extern __thread" declaration.
  6119. /// + Defined in a possibly unknown dynamic library.
  6120. ///
  6121. /// The general system is that each __thread variable has a [3 x i64] descriptor
  6122. /// which contains information used by the runtime to calculate the address. The
  6123. /// only part of this the compiler needs to know about is the first xword, which
  6124. /// contains a function pointer that must be called with the address of the
  6125. /// entire descriptor in "x0".
  6126. ///
  6127. /// Since this descriptor may be in a different unit, in general even the
  6128. /// descriptor must be accessed via an indirect load. The "ideal" code sequence
  6129. /// is:
  6130. /// adrp x0, _var@TLVPPAGE
  6131. /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
  6132. /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
  6133. /// ; the function pointer
  6134. /// blr x1 ; Uses descriptor address in x0
  6135. /// ; Address of _var is now in x0.
  6136. ///
  6137. /// If the address of _var's descriptor *is* known to the linker, then it can
  6138. /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
  6139. /// a slight efficiency gain.
  6140. SDValue
  6141. AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
  6142. SelectionDAG &DAG) const {
  6143. assert(Subtarget->isTargetDarwin() &&
  6144. "This function expects a Darwin target");
  6145. SDLoc DL(Op);
  6146. MVT PtrVT = getPointerTy(DAG.getDataLayout());
  6147. MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
  6148. const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
  6149. SDValue TLVPAddr =
  6150. DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
  6151. SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
  6152. // The first entry in the descriptor is a function pointer that we must call
  6153. // to obtain the address of the variable.
  6154. SDValue Chain = DAG.getEntryNode();
  6155. SDValue FuncTLVGet = DAG.getLoad(
  6156. PtrMemVT, DL, Chain, DescAddr,
  6157. MachinePointerInfo::getGOT(DAG.getMachineFunction()),
  6158. Align(PtrMemVT.getSizeInBits() / 8),
  6159. MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
  6160. Chain = FuncTLVGet.getValue(1);
  6161. // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
  6162. FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
  6163. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  6164. MFI.setAdjustsStack(true);
  6165. // TLS calls preserve all registers except those that absolutely must be
  6166. // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
  6167. // silly).
  6168. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
  6169. const uint32_t *Mask = TRI->getTLSCallPreservedMask();
  6170. if (Subtarget->hasCustomCallingConv())
  6171. TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
  6172. // Finally, we can make the call. This is just a degenerate version of a
  6173. // normal AArch64 call node: x0 takes the address of the descriptor, and
  6174. // returns the address of the variable in this thread.
  6175. Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
  6176. Chain =
  6177. DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
  6178. Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
  6179. DAG.getRegisterMask(Mask), Chain.getValue(1));
  6180. return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
  6181. }
  6182. /// Convert a thread-local variable reference into a sequence of instructions to
  6183. /// compute the variable's address for the local exec TLS model of ELF targets.
  6184. /// The sequence depends on the maximum TLS area size.
  6185. SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
  6186. SDValue ThreadBase,
  6187. const SDLoc &DL,
  6188. SelectionDAG &DAG) const {
  6189. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6190. SDValue TPOff, Addr;
  6191. switch (DAG.getTarget().Options.TLSSize) {
  6192. default:
  6193. llvm_unreachable("Unexpected TLS size");
  6194. case 12: {
  6195. // mrs x0, TPIDR_EL0
  6196. // add x0, x0, :tprel_lo12:a
  6197. SDValue Var = DAG.getTargetGlobalAddress(
  6198. GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
  6199. return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
  6200. Var,
  6201. DAG.getTargetConstant(0, DL, MVT::i32)),
  6202. 0);
  6203. }
  6204. case 24: {
  6205. // mrs x0, TPIDR_EL0
  6206. // add x0, x0, :tprel_hi12:a
  6207. // add x0, x0, :tprel_lo12_nc:a
  6208. SDValue HiVar = DAG.getTargetGlobalAddress(
  6209. GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
  6210. SDValue LoVar = DAG.getTargetGlobalAddress(
  6211. GV, DL, PtrVT, 0,
  6212. AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  6213. Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
  6214. HiVar,
  6215. DAG.getTargetConstant(0, DL, MVT::i32)),
  6216. 0);
  6217. return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
  6218. LoVar,
  6219. DAG.getTargetConstant(0, DL, MVT::i32)),
  6220. 0);
  6221. }
  6222. case 32: {
  6223. // mrs x1, TPIDR_EL0
  6224. // movz x0, #:tprel_g1:a
  6225. // movk x0, #:tprel_g0_nc:a
  6226. // add x0, x1, x0
  6227. SDValue HiVar = DAG.getTargetGlobalAddress(
  6228. GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
  6229. SDValue LoVar = DAG.getTargetGlobalAddress(
  6230. GV, DL, PtrVT, 0,
  6231. AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
  6232. TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
  6233. DAG.getTargetConstant(16, DL, MVT::i32)),
  6234. 0);
  6235. TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
  6236. DAG.getTargetConstant(0, DL, MVT::i32)),
  6237. 0);
  6238. return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
  6239. }
  6240. case 48: {
  6241. // mrs x1, TPIDR_EL0
  6242. // movz x0, #:tprel_g2:a
  6243. // movk x0, #:tprel_g1_nc:a
  6244. // movk x0, #:tprel_g0_nc:a
  6245. // add x0, x1, x0
  6246. SDValue HiVar = DAG.getTargetGlobalAddress(
  6247. GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
  6248. SDValue MiVar = DAG.getTargetGlobalAddress(
  6249. GV, DL, PtrVT, 0,
  6250. AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
  6251. SDValue LoVar = DAG.getTargetGlobalAddress(
  6252. GV, DL, PtrVT, 0,
  6253. AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
  6254. TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
  6255. DAG.getTargetConstant(32, DL, MVT::i32)),
  6256. 0);
  6257. TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
  6258. DAG.getTargetConstant(16, DL, MVT::i32)),
  6259. 0);
  6260. TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
  6261. DAG.getTargetConstant(0, DL, MVT::i32)),
  6262. 0);
  6263. return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
  6264. }
  6265. }
  6266. }
  6267. /// When accessing thread-local variables under either the general-dynamic or
  6268. /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
  6269. /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
  6270. /// is a function pointer to carry out the resolution.
  6271. ///
  6272. /// The sequence is:
  6273. /// adrp x0, :tlsdesc:var
  6274. /// ldr x1, [x0, #:tlsdesc_lo12:var]
  6275. /// add x0, x0, #:tlsdesc_lo12:var
  6276. /// .tlsdesccall var
  6277. /// blr x1
  6278. /// (TPIDR_EL0 offset now in x0)
  6279. ///
  6280. /// The above sequence must be produced unscheduled, to enable the linker to
  6281. /// optimize/relax this sequence.
  6282. /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
  6283. /// above sequence, and expanded really late in the compilation flow, to ensure
  6284. /// the sequence is produced as per above.
  6285. SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
  6286. const SDLoc &DL,
  6287. SelectionDAG &DAG) const {
  6288. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6289. SDValue Chain = DAG.getEntryNode();
  6290. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  6291. Chain =
  6292. DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
  6293. SDValue Glue = Chain.getValue(1);
  6294. return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
  6295. }
  6296. SDValue
  6297. AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
  6298. SelectionDAG &DAG) const {
  6299. assert(Subtarget->isTargetELF() && "This function expects an ELF target");
  6300. const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
  6301. TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
  6302. if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
  6303. if (Model == TLSModel::LocalDynamic)
  6304. Model = TLSModel::GeneralDynamic;
  6305. }
  6306. if (getTargetMachine().getCodeModel() == CodeModel::Large &&
  6307. Model != TLSModel::LocalExec)
  6308. report_fatal_error("ELF TLS only supported in small memory model or "
  6309. "in local exec TLS model");
  6310. // Different choices can be made for the maximum size of the TLS area for a
  6311. // module. For the small address model, the default TLS size is 16MiB and the
  6312. // maximum TLS size is 4GiB.
  6313. // FIXME: add tiny and large code model support for TLS access models other
  6314. // than local exec. We currently generate the same code as small for tiny,
  6315. // which may be larger than needed.
  6316. SDValue TPOff;
  6317. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6318. SDLoc DL(Op);
  6319. const GlobalValue *GV = GA->getGlobal();
  6320. SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
  6321. if (Model == TLSModel::LocalExec) {
  6322. return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
  6323. } else if (Model == TLSModel::InitialExec) {
  6324. TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
  6325. TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
  6326. } else if (Model == TLSModel::LocalDynamic) {
  6327. // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
  6328. // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
  6329. // the beginning of the module's TLS region, followed by a DTPREL offset
  6330. // calculation.
  6331. // These accesses will need deduplicating if there's more than one.
  6332. AArch64FunctionInfo *MFI =
  6333. DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
  6334. MFI->incNumLocalDynamicTLSAccesses();
  6335. // The call needs a relocation too for linker relaxation. It doesn't make
  6336. // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
  6337. // the address.
  6338. SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
  6339. AArch64II::MO_TLS);
  6340. // Now we can calculate the offset from TPIDR_EL0 to this module's
  6341. // thread-local area.
  6342. TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
  6343. // Now use :dtprel_whatever: operations to calculate this variable's offset
  6344. // in its thread-storage area.
  6345. SDValue HiVar = DAG.getTargetGlobalAddress(
  6346. GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
  6347. SDValue LoVar = DAG.getTargetGlobalAddress(
  6348. GV, DL, MVT::i64, 0,
  6349. AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  6350. TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
  6351. DAG.getTargetConstant(0, DL, MVT::i32)),
  6352. 0);
  6353. TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
  6354. DAG.getTargetConstant(0, DL, MVT::i32)),
  6355. 0);
  6356. } else if (Model == TLSModel::GeneralDynamic) {
  6357. // The call needs a relocation too for linker relaxation. It doesn't make
  6358. // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
  6359. // the address.
  6360. SDValue SymAddr =
  6361. DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
  6362. // Finally we can make a call to calculate the offset from tpidr_el0.
  6363. TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
  6364. } else
  6365. llvm_unreachable("Unsupported ELF TLS access model");
  6366. return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
  6367. }
  6368. SDValue
  6369. AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
  6370. SelectionDAG &DAG) const {
  6371. assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
  6372. SDValue Chain = DAG.getEntryNode();
  6373. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  6374. SDLoc DL(Op);
  6375. SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
  6376. // Load the ThreadLocalStoragePointer from the TEB
  6377. // A pointer to the TLS array is located at offset 0x58 from the TEB.
  6378. SDValue TLSArray =
  6379. DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
  6380. TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
  6381. Chain = TLSArray.getValue(1);
  6382. // Load the TLS index from the C runtime;
  6383. // This does the same as getAddr(), but without having a GlobalAddressSDNode.
  6384. // This also does the same as LOADgot, but using a generic i32 load,
  6385. // while LOADgot only loads i64.
  6386. SDValue TLSIndexHi =
  6387. DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
  6388. SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
  6389. "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  6390. SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
  6391. SDValue TLSIndex =
  6392. DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
  6393. TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
  6394. Chain = TLSIndex.getValue(1);
  6395. // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
  6396. // offset into the TLSArray.
  6397. TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
  6398. SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
  6399. DAG.getConstant(3, DL, PtrVT));
  6400. SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
  6401. DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
  6402. MachinePointerInfo());
  6403. Chain = TLS.getValue(1);
  6404. const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
  6405. const GlobalValue *GV = GA->getGlobal();
  6406. SDValue TGAHi = DAG.getTargetGlobalAddress(
  6407. GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
  6408. SDValue TGALo = DAG.getTargetGlobalAddress(
  6409. GV, DL, PtrVT, 0,
  6410. AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  6411. // Add the offset from the start of the .tls section (section base).
  6412. SDValue Addr =
  6413. SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
  6414. DAG.getTargetConstant(0, DL, MVT::i32)),
  6415. 0);
  6416. Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
  6417. return Addr;
  6418. }
  6419. SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
  6420. SelectionDAG &DAG) const {
  6421. const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
  6422. if (DAG.getTarget().useEmulatedTLS())
  6423. return LowerToTLSEmulatedModel(GA, DAG);
  6424. if (Subtarget->isTargetDarwin())
  6425. return LowerDarwinGlobalTLSAddress(Op, DAG);
  6426. if (Subtarget->isTargetELF())
  6427. return LowerELFGlobalTLSAddress(Op, DAG);
  6428. if (Subtarget->isTargetWindows())
  6429. return LowerWindowsGlobalTLSAddress(Op, DAG);
  6430. llvm_unreachable("Unexpected platform trying to use TLS");
  6431. }
  6432. // Looks through \param Val to determine the bit that can be used to
  6433. // check the sign of the value. It returns the unextended value and
  6434. // the sign bit position.
  6435. std::pair<SDValue, uint64_t> lookThroughSignExtension(SDValue Val) {
  6436. if (Val.getOpcode() == ISD::SIGN_EXTEND_INREG)
  6437. return {Val.getOperand(0),
  6438. cast<VTSDNode>(Val.getOperand(1))->getVT().getFixedSizeInBits() -
  6439. 1};
  6440. if (Val.getOpcode() == ISD::SIGN_EXTEND)
  6441. return {Val.getOperand(0),
  6442. Val.getOperand(0)->getValueType(0).getFixedSizeInBits() - 1};
  6443. return {Val, Val.getValueSizeInBits() - 1};
  6444. }
  6445. SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
  6446. SDValue Chain = Op.getOperand(0);
  6447. ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
  6448. SDValue LHS = Op.getOperand(2);
  6449. SDValue RHS = Op.getOperand(3);
  6450. SDValue Dest = Op.getOperand(4);
  6451. SDLoc dl(Op);
  6452. MachineFunction &MF = DAG.getMachineFunction();
  6453. // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
  6454. // will not be produced, as they are conditional branch instructions that do
  6455. // not set flags.
  6456. bool ProduceNonFlagSettingCondBr =
  6457. !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
  6458. // Handle f128 first, since lowering it will result in comparing the return
  6459. // value of a libcall against zero, which is just what the rest of LowerBR_CC
  6460. // is expecting to deal with.
  6461. if (LHS.getValueType() == MVT::f128) {
  6462. softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
  6463. // If softenSetCCOperands returned a scalar, we need to compare the result
  6464. // against zero to select between true and false values.
  6465. if (!RHS.getNode()) {
  6466. RHS = DAG.getConstant(0, dl, LHS.getValueType());
  6467. CC = ISD::SETNE;
  6468. }
  6469. }
  6470. // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
  6471. // instruction.
  6472. if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
  6473. (CC == ISD::SETEQ || CC == ISD::SETNE)) {
  6474. // Only lower legal XALUO ops.
  6475. if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
  6476. return SDValue();
  6477. // The actual operation with overflow check.
  6478. AArch64CC::CondCode OFCC;
  6479. SDValue Value, Overflow;
  6480. std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
  6481. if (CC == ISD::SETNE)
  6482. OFCC = getInvertedCondCode(OFCC);
  6483. SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
  6484. return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
  6485. Overflow);
  6486. }
  6487. if (LHS.getValueType().isInteger()) {
  6488. assert((LHS.getValueType() == RHS.getValueType()) &&
  6489. (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
  6490. // If the RHS of the comparison is zero, we can potentially fold this
  6491. // to a specialized branch.
  6492. const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
  6493. if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
  6494. if (CC == ISD::SETEQ) {
  6495. // See if we can use a TBZ to fold in an AND as well.
  6496. // TBZ has a smaller branch displacement than CBZ. If the offset is
  6497. // out of bounds, a late MI-layer pass rewrites branches.
  6498. // 403.gcc is an example that hits this case.
  6499. if (LHS.getOpcode() == ISD::AND &&
  6500. isa<ConstantSDNode>(LHS.getOperand(1)) &&
  6501. isPowerOf2_64(LHS.getConstantOperandVal(1))) {
  6502. SDValue Test = LHS.getOperand(0);
  6503. uint64_t Mask = LHS.getConstantOperandVal(1);
  6504. return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
  6505. DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
  6506. Dest);
  6507. }
  6508. return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
  6509. } else if (CC == ISD::SETNE) {
  6510. // See if we can use a TBZ to fold in an AND as well.
  6511. // TBZ has a smaller branch displacement than CBZ. If the offset is
  6512. // out of bounds, a late MI-layer pass rewrites branches.
  6513. // 403.gcc is an example that hits this case.
  6514. if (LHS.getOpcode() == ISD::AND &&
  6515. isa<ConstantSDNode>(LHS.getOperand(1)) &&
  6516. isPowerOf2_64(LHS.getConstantOperandVal(1))) {
  6517. SDValue Test = LHS.getOperand(0);
  6518. uint64_t Mask = LHS.getConstantOperandVal(1);
  6519. return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
  6520. DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
  6521. Dest);
  6522. }
  6523. return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
  6524. } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
  6525. // Don't combine AND since emitComparison converts the AND to an ANDS
  6526. // (a.k.a. TST) and the test in the test bit and branch instruction
  6527. // becomes redundant. This would also increase register pressure.
  6528. uint64_t SignBitPos;
  6529. std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
  6530. return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
  6531. DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
  6532. }
  6533. }
  6534. if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
  6535. LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
  6536. // Don't combine AND since emitComparison converts the AND to an ANDS
  6537. // (a.k.a. TST) and the test in the test bit and branch instruction
  6538. // becomes redundant. This would also increase register pressure.
  6539. uint64_t SignBitPos;
  6540. std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
  6541. return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
  6542. DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
  6543. }
  6544. SDValue CCVal;
  6545. SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
  6546. return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
  6547. Cmp);
  6548. }
  6549. assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
  6550. LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
  6551. // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
  6552. // clean. Some of them require two branches to implement.
  6553. SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
  6554. AArch64CC::CondCode CC1, CC2;
  6555. changeFPCCToAArch64CC(CC, CC1, CC2);
  6556. SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
  6557. SDValue BR1 =
  6558. DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
  6559. if (CC2 != AArch64CC::AL) {
  6560. SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
  6561. return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
  6562. Cmp);
  6563. }
  6564. return BR1;
  6565. }
  6566. SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
  6567. SelectionDAG &DAG) const {
  6568. EVT VT = Op.getValueType();
  6569. SDLoc DL(Op);
  6570. SDValue In1 = Op.getOperand(0);
  6571. SDValue In2 = Op.getOperand(1);
  6572. EVT SrcVT = In2.getValueType();
  6573. if (VT.isScalableVector()) {
  6574. if (VT != SrcVT)
  6575. return SDValue();
  6576. // copysign(x,y) -> (y & SIGN_MASK) | (x & ~SIGN_MASK)
  6577. //
  6578. // A possible alternative sequence involves using FNEG_MERGE_PASSTHRU;
  6579. // maybe useful for copysign operations with mismatched VTs.
  6580. //
  6581. // IntVT here is chosen so it's a legal type with the same element width
  6582. // as the input.
  6583. EVT IntVT =
  6584. getPackedSVEVectorVT(VT.getVectorElementType().changeTypeToInteger());
  6585. unsigned NumBits = VT.getScalarSizeInBits();
  6586. SDValue SignMask = DAG.getConstant(APInt::getSignMask(NumBits), DL, IntVT);
  6587. SDValue InvSignMask = DAG.getNOT(DL, SignMask, IntVT);
  6588. SDValue Sign = DAG.getNode(ISD::AND, DL, IntVT, SignMask,
  6589. getSVESafeBitCast(IntVT, In2, DAG));
  6590. SDValue Magnitude = DAG.getNode(ISD::AND, DL, IntVT, InvSignMask,
  6591. getSVESafeBitCast(IntVT, In1, DAG));
  6592. SDValue IntResult = DAG.getNode(ISD::OR, DL, IntVT, Sign, Magnitude);
  6593. return getSVESafeBitCast(VT, IntResult, DAG);
  6594. }
  6595. if (!Subtarget->hasNEON())
  6596. return SDValue();
  6597. if (SrcVT.bitsLT(VT))
  6598. In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
  6599. else if (SrcVT.bitsGT(VT))
  6600. In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
  6601. EVT VecVT;
  6602. uint64_t EltMask;
  6603. SDValue VecVal1, VecVal2;
  6604. auto setVecVal = [&] (int Idx) {
  6605. if (!VT.isVector()) {
  6606. VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
  6607. DAG.getUNDEF(VecVT), In1);
  6608. VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
  6609. DAG.getUNDEF(VecVT), In2);
  6610. } else {
  6611. VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
  6612. VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
  6613. }
  6614. };
  6615. if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
  6616. VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
  6617. EltMask = 0x80000000ULL;
  6618. setVecVal(AArch64::ssub);
  6619. } else if (VT == MVT::f64 || VT == MVT::v2f64) {
  6620. VecVT = MVT::v2i64;
  6621. // We want to materialize a mask with the high bit set, but the AdvSIMD
  6622. // immediate moves cannot materialize that in a single instruction for
  6623. // 64-bit elements. Instead, materialize zero and then negate it.
  6624. EltMask = 0;
  6625. setVecVal(AArch64::dsub);
  6626. } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
  6627. VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
  6628. EltMask = 0x8000ULL;
  6629. setVecVal(AArch64::hsub);
  6630. } else {
  6631. llvm_unreachable("Invalid type for copysign!");
  6632. }
  6633. SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
  6634. // If we couldn't materialize the mask above, then the mask vector will be
  6635. // the zero vector, and we need to negate it here.
  6636. if (VT == MVT::f64 || VT == MVT::v2f64) {
  6637. BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
  6638. BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
  6639. BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
  6640. }
  6641. SDValue Sel =
  6642. DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
  6643. if (VT == MVT::f16)
  6644. return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
  6645. if (VT == MVT::f32)
  6646. return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
  6647. else if (VT == MVT::f64)
  6648. return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
  6649. else
  6650. return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
  6651. }
  6652. SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
  6653. if (DAG.getMachineFunction().getFunction().hasFnAttribute(
  6654. Attribute::NoImplicitFloat))
  6655. return SDValue();
  6656. if (!Subtarget->hasNEON())
  6657. return SDValue();
  6658. // While there is no integer popcount instruction, it can
  6659. // be more efficiently lowered to the following sequence that uses
  6660. // AdvSIMD registers/instructions as long as the copies to/from
  6661. // the AdvSIMD registers are cheap.
  6662. // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
  6663. // CNT V0.8B, V0.8B // 8xbyte pop-counts
  6664. // ADDV B0, V0.8B // sum 8xbyte pop-counts
  6665. // UMOV X0, V0.B[0] // copy byte result back to integer reg
  6666. SDValue Val = Op.getOperand(0);
  6667. SDLoc DL(Op);
  6668. EVT VT = Op.getValueType();
  6669. if (VT == MVT::i32 || VT == MVT::i64) {
  6670. if (VT == MVT::i32)
  6671. Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
  6672. Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
  6673. SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
  6674. SDValue UaddLV = DAG.getNode(
  6675. ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
  6676. DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
  6677. if (VT == MVT::i64)
  6678. UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
  6679. return UaddLV;
  6680. } else if (VT == MVT::i128) {
  6681. Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
  6682. SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
  6683. SDValue UaddLV = DAG.getNode(
  6684. ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
  6685. DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
  6686. return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
  6687. }
  6688. if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
  6689. return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTPOP_MERGE_PASSTHRU);
  6690. assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
  6691. VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
  6692. "Unexpected type for custom ctpop lowering");
  6693. EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
  6694. Val = DAG.getBitcast(VT8Bit, Val);
  6695. Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
  6696. // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
  6697. unsigned EltSize = 8;
  6698. unsigned NumElts = VT.is64BitVector() ? 8 : 16;
  6699. while (EltSize != VT.getScalarSizeInBits()) {
  6700. EltSize *= 2;
  6701. NumElts /= 2;
  6702. MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
  6703. Val = DAG.getNode(
  6704. ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
  6705. DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
  6706. }
  6707. return Val;
  6708. }
  6709. SDValue AArch64TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
  6710. EVT VT = Op.getValueType();
  6711. assert(VT.isScalableVector() ||
  6712. useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true));
  6713. SDLoc DL(Op);
  6714. SDValue RBIT = DAG.getNode(ISD::BITREVERSE, DL, VT, Op.getOperand(0));
  6715. return DAG.getNode(ISD::CTLZ, DL, VT, RBIT);
  6716. }
  6717. SDValue AArch64TargetLowering::LowerMinMax(SDValue Op,
  6718. SelectionDAG &DAG) const {
  6719. EVT VT = Op.getValueType();
  6720. SDLoc DL(Op);
  6721. unsigned Opcode = Op.getOpcode();
  6722. ISD::CondCode CC;
  6723. switch (Opcode) {
  6724. default:
  6725. llvm_unreachable("Wrong instruction");
  6726. case ISD::SMAX:
  6727. CC = ISD::SETGT;
  6728. break;
  6729. case ISD::SMIN:
  6730. CC = ISD::SETLT;
  6731. break;
  6732. case ISD::UMAX:
  6733. CC = ISD::SETUGT;
  6734. break;
  6735. case ISD::UMIN:
  6736. CC = ISD::SETULT;
  6737. break;
  6738. }
  6739. if (VT.isScalableVector() ||
  6740. useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true)) {
  6741. switch (Opcode) {
  6742. default:
  6743. llvm_unreachable("Wrong instruction");
  6744. case ISD::SMAX:
  6745. return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED,
  6746. /*OverrideNEON=*/true);
  6747. case ISD::SMIN:
  6748. return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED,
  6749. /*OverrideNEON=*/true);
  6750. case ISD::UMAX:
  6751. return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED,
  6752. /*OverrideNEON=*/true);
  6753. case ISD::UMIN:
  6754. return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED,
  6755. /*OverrideNEON=*/true);
  6756. }
  6757. }
  6758. SDValue Op0 = Op.getOperand(0);
  6759. SDValue Op1 = Op.getOperand(1);
  6760. SDValue Cond = DAG.getSetCC(DL, VT, Op0, Op1, CC);
  6761. return DAG.getSelect(DL, VT, Cond, Op0, Op1);
  6762. }
  6763. SDValue AArch64TargetLowering::LowerBitreverse(SDValue Op,
  6764. SelectionDAG &DAG) const {
  6765. EVT VT = Op.getValueType();
  6766. if (VT.isScalableVector() ||
  6767. useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
  6768. return LowerToPredicatedOp(Op, DAG, AArch64ISD::BITREVERSE_MERGE_PASSTHRU,
  6769. true);
  6770. SDLoc DL(Op);
  6771. SDValue REVB;
  6772. MVT VST;
  6773. switch (VT.getSimpleVT().SimpleTy) {
  6774. default:
  6775. llvm_unreachable("Invalid type for bitreverse!");
  6776. case MVT::v2i32: {
  6777. VST = MVT::v8i8;
  6778. REVB = DAG.getNode(AArch64ISD::REV32, DL, VST, Op.getOperand(0));
  6779. break;
  6780. }
  6781. case MVT::v4i32: {
  6782. VST = MVT::v16i8;
  6783. REVB = DAG.getNode(AArch64ISD::REV32, DL, VST, Op.getOperand(0));
  6784. break;
  6785. }
  6786. case MVT::v1i64: {
  6787. VST = MVT::v8i8;
  6788. REVB = DAG.getNode(AArch64ISD::REV64, DL, VST, Op.getOperand(0));
  6789. break;
  6790. }
  6791. case MVT::v2i64: {
  6792. VST = MVT::v16i8;
  6793. REVB = DAG.getNode(AArch64ISD::REV64, DL, VST, Op.getOperand(0));
  6794. break;
  6795. }
  6796. }
  6797. return DAG.getNode(AArch64ISD::NVCAST, DL, VT,
  6798. DAG.getNode(ISD::BITREVERSE, DL, VST, REVB));
  6799. }
  6800. SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
  6801. if (Op.getValueType().isVector())
  6802. return LowerVSETCC(Op, DAG);
  6803. bool IsStrict = Op->isStrictFPOpcode();
  6804. bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
  6805. unsigned OpNo = IsStrict ? 1 : 0;
  6806. SDValue Chain;
  6807. if (IsStrict)
  6808. Chain = Op.getOperand(0);
  6809. SDValue LHS = Op.getOperand(OpNo + 0);
  6810. SDValue RHS = Op.getOperand(OpNo + 1);
  6811. ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
  6812. SDLoc dl(Op);
  6813. // We chose ZeroOrOneBooleanContents, so use zero and one.
  6814. EVT VT = Op.getValueType();
  6815. SDValue TVal = DAG.getConstant(1, dl, VT);
  6816. SDValue FVal = DAG.getConstant(0, dl, VT);
  6817. // Handle f128 first, since one possible outcome is a normal integer
  6818. // comparison which gets picked up by the next if statement.
  6819. if (LHS.getValueType() == MVT::f128) {
  6820. softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
  6821. IsSignaling);
  6822. // If softenSetCCOperands returned a scalar, use it.
  6823. if (!RHS.getNode()) {
  6824. assert(LHS.getValueType() == Op.getValueType() &&
  6825. "Unexpected setcc expansion!");
  6826. return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
  6827. }
  6828. }
  6829. if (LHS.getValueType().isInteger()) {
  6830. SDValue CCVal;
  6831. SDValue Cmp = getAArch64Cmp(
  6832. LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
  6833. // Note that we inverted the condition above, so we reverse the order of
  6834. // the true and false operands here. This will allow the setcc to be
  6835. // matched to a single CSINC instruction.
  6836. SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
  6837. return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
  6838. }
  6839. // Now we know we're dealing with FP values.
  6840. assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
  6841. LHS.getValueType() == MVT::f64);
  6842. // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
  6843. // and do the comparison.
  6844. SDValue Cmp;
  6845. if (IsStrict)
  6846. Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
  6847. else
  6848. Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
  6849. AArch64CC::CondCode CC1, CC2;
  6850. changeFPCCToAArch64CC(CC, CC1, CC2);
  6851. SDValue Res;
  6852. if (CC2 == AArch64CC::AL) {
  6853. changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
  6854. CC2);
  6855. SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
  6856. // Note that we inverted the condition above, so we reverse the order of
  6857. // the true and false operands here. This will allow the setcc to be
  6858. // matched to a single CSINC instruction.
  6859. Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
  6860. } else {
  6861. // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
  6862. // totally clean. Some of them require two CSELs to implement. As is in
  6863. // this case, we emit the first CSEL and then emit a second using the output
  6864. // of the first as the RHS. We're effectively OR'ing the two CC's together.
  6865. // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
  6866. SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
  6867. SDValue CS1 =
  6868. DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
  6869. SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
  6870. Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
  6871. }
  6872. return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
  6873. }
  6874. SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
  6875. SDValue RHS, SDValue TVal,
  6876. SDValue FVal, const SDLoc &dl,
  6877. SelectionDAG &DAG) const {
  6878. // Handle f128 first, because it will result in a comparison of some RTLIB
  6879. // call result against zero.
  6880. if (LHS.getValueType() == MVT::f128) {
  6881. softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
  6882. // If softenSetCCOperands returned a scalar, we need to compare the result
  6883. // against zero to select between true and false values.
  6884. if (!RHS.getNode()) {
  6885. RHS = DAG.getConstant(0, dl, LHS.getValueType());
  6886. CC = ISD::SETNE;
  6887. }
  6888. }
  6889. // Also handle f16, for which we need to do a f32 comparison.
  6890. if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
  6891. LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
  6892. RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
  6893. }
  6894. // Next, handle integers.
  6895. if (LHS.getValueType().isInteger()) {
  6896. assert((LHS.getValueType() == RHS.getValueType()) &&
  6897. (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
  6898. ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
  6899. ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
  6900. ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
  6901. // Check for sign pattern (SELECT_CC setgt, iN lhs, -1, 1, -1) and transform
  6902. // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
  6903. // supported types.
  6904. if (CC == ISD::SETGT && RHSC && RHSC->isAllOnes() && CTVal && CFVal &&
  6905. CTVal->isOne() && CFVal->isAllOnes() &&
  6906. LHS.getValueType() == TVal.getValueType()) {
  6907. EVT VT = LHS.getValueType();
  6908. SDValue Shift =
  6909. DAG.getNode(ISD::SRA, dl, VT, LHS,
  6910. DAG.getConstant(VT.getSizeInBits() - 1, dl, VT));
  6911. return DAG.getNode(ISD::OR, dl, VT, Shift, DAG.getConstant(1, dl, VT));
  6912. }
  6913. unsigned Opcode = AArch64ISD::CSEL;
  6914. // If both the TVal and the FVal are constants, see if we can swap them in
  6915. // order to for a CSINV or CSINC out of them.
  6916. if (CTVal && CFVal && CTVal->isAllOnes() && CFVal->isZero()) {
  6917. std::swap(TVal, FVal);
  6918. std::swap(CTVal, CFVal);
  6919. CC = ISD::getSetCCInverse(CC, LHS.getValueType());
  6920. } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isZero()) {
  6921. std::swap(TVal, FVal);
  6922. std::swap(CTVal, CFVal);
  6923. CC = ISD::getSetCCInverse(CC, LHS.getValueType());
  6924. } else if (TVal.getOpcode() == ISD::XOR) {
  6925. // If TVal is a NOT we want to swap TVal and FVal so that we can match
  6926. // with a CSINV rather than a CSEL.
  6927. if (isAllOnesConstant(TVal.getOperand(1))) {
  6928. std::swap(TVal, FVal);
  6929. std::swap(CTVal, CFVal);
  6930. CC = ISD::getSetCCInverse(CC, LHS.getValueType());
  6931. }
  6932. } else if (TVal.getOpcode() == ISD::SUB) {
  6933. // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
  6934. // that we can match with a CSNEG rather than a CSEL.
  6935. if (isNullConstant(TVal.getOperand(0))) {
  6936. std::swap(TVal, FVal);
  6937. std::swap(CTVal, CFVal);
  6938. CC = ISD::getSetCCInverse(CC, LHS.getValueType());
  6939. }
  6940. } else if (CTVal && CFVal) {
  6941. const int64_t TrueVal = CTVal->getSExtValue();
  6942. const int64_t FalseVal = CFVal->getSExtValue();
  6943. bool Swap = false;
  6944. // If both TVal and FVal are constants, see if FVal is the
  6945. // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
  6946. // instead of a CSEL in that case.
  6947. if (TrueVal == ~FalseVal) {
  6948. Opcode = AArch64ISD::CSINV;
  6949. } else if (FalseVal > std::numeric_limits<int64_t>::min() &&
  6950. TrueVal == -FalseVal) {
  6951. Opcode = AArch64ISD::CSNEG;
  6952. } else if (TVal.getValueType() == MVT::i32) {
  6953. // If our operands are only 32-bit wide, make sure we use 32-bit
  6954. // arithmetic for the check whether we can use CSINC. This ensures that
  6955. // the addition in the check will wrap around properly in case there is
  6956. // an overflow (which would not be the case if we do the check with
  6957. // 64-bit arithmetic).
  6958. const uint32_t TrueVal32 = CTVal->getZExtValue();
  6959. const uint32_t FalseVal32 = CFVal->getZExtValue();
  6960. if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
  6961. Opcode = AArch64ISD::CSINC;
  6962. if (TrueVal32 > FalseVal32) {
  6963. Swap = true;
  6964. }
  6965. }
  6966. // 64-bit check whether we can use CSINC.
  6967. } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
  6968. Opcode = AArch64ISD::CSINC;
  6969. if (TrueVal > FalseVal) {
  6970. Swap = true;
  6971. }
  6972. }
  6973. // Swap TVal and FVal if necessary.
  6974. if (Swap) {
  6975. std::swap(TVal, FVal);
  6976. std::swap(CTVal, CFVal);
  6977. CC = ISD::getSetCCInverse(CC, LHS.getValueType());
  6978. }
  6979. if (Opcode != AArch64ISD::CSEL) {
  6980. // Drop FVal since we can get its value by simply inverting/negating
  6981. // TVal.
  6982. FVal = TVal;
  6983. }
  6984. }
  6985. // Avoid materializing a constant when possible by reusing a known value in
  6986. // a register. However, don't perform this optimization if the known value
  6987. // is one, zero or negative one in the case of a CSEL. We can always
  6988. // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
  6989. // FVal, respectively.
  6990. ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
  6991. if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
  6992. !RHSVal->isZero() && !RHSVal->isAllOnes()) {
  6993. AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
  6994. // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
  6995. // "a != C ? x : a" to avoid materializing C.
  6996. if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
  6997. TVal = LHS;
  6998. else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
  6999. FVal = LHS;
  7000. } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
  7001. assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
  7002. // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
  7003. // avoid materializing C.
  7004. AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
  7005. if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
  7006. Opcode = AArch64ISD::CSINV;
  7007. TVal = LHS;
  7008. FVal = DAG.getConstant(0, dl, FVal.getValueType());
  7009. }
  7010. }
  7011. SDValue CCVal;
  7012. SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
  7013. EVT VT = TVal.getValueType();
  7014. return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
  7015. }
  7016. // Now we know we're dealing with FP values.
  7017. assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
  7018. LHS.getValueType() == MVT::f64);
  7019. assert(LHS.getValueType() == RHS.getValueType());
  7020. EVT VT = TVal.getValueType();
  7021. SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
  7022. // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
  7023. // clean. Some of them require two CSELs to implement.
  7024. AArch64CC::CondCode CC1, CC2;
  7025. changeFPCCToAArch64CC(CC, CC1, CC2);
  7026. if (DAG.getTarget().Options.UnsafeFPMath) {
  7027. // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
  7028. // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
  7029. ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
  7030. if (RHSVal && RHSVal->isZero()) {
  7031. ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
  7032. ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
  7033. if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
  7034. CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
  7035. TVal = LHS;
  7036. else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
  7037. CFVal && CFVal->isZero() &&
  7038. FVal.getValueType() == LHS.getValueType())
  7039. FVal = LHS;
  7040. }
  7041. }
  7042. // Emit first, and possibly only, CSEL.
  7043. SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
  7044. SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
  7045. // If we need a second CSEL, emit it, using the output of the first as the
  7046. // RHS. We're effectively OR'ing the two CC's together.
  7047. if (CC2 != AArch64CC::AL) {
  7048. SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
  7049. return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
  7050. }
  7051. // Otherwise, return the output of the first CSEL.
  7052. return CS1;
  7053. }
  7054. SDValue AArch64TargetLowering::LowerVECTOR_SPLICE(SDValue Op,
  7055. SelectionDAG &DAG) const {
  7056. EVT Ty = Op.getValueType();
  7057. auto Idx = Op.getConstantOperandAPInt(2);
  7058. int64_t IdxVal = Idx.getSExtValue();
  7059. assert(Ty.isScalableVector() &&
  7060. "Only expect scalable vectors for custom lowering of VECTOR_SPLICE");
  7061. // We can use the splice instruction for certain index values where we are
  7062. // able to efficiently generate the correct predicate. The index will be
  7063. // inverted and used directly as the input to the ptrue instruction, i.e.
  7064. // -1 -> vl1, -2 -> vl2, etc. The predicate will then be reversed to get the
  7065. // splice predicate. However, we can only do this if we can guarantee that
  7066. // there are enough elements in the vector, hence we check the index <= min
  7067. // number of elements.
  7068. Optional<unsigned> PredPattern;
  7069. if (Ty.isScalableVector() && IdxVal < 0 &&
  7070. (PredPattern = getSVEPredPatternFromNumElements(std::abs(IdxVal))) !=
  7071. None) {
  7072. SDLoc DL(Op);
  7073. // Create a predicate where all but the last -IdxVal elements are false.
  7074. EVT PredVT = Ty.changeVectorElementType(MVT::i1);
  7075. SDValue Pred = getPTrue(DAG, DL, PredVT, *PredPattern);
  7076. Pred = DAG.getNode(ISD::VECTOR_REVERSE, DL, PredVT, Pred);
  7077. // Now splice the two inputs together using the predicate.
  7078. return DAG.getNode(AArch64ISD::SPLICE, DL, Ty, Pred, Op.getOperand(0),
  7079. Op.getOperand(1));
  7080. }
  7081. // This will select to an EXT instruction, which has a maximum immediate
  7082. // value of 255, hence 2048-bits is the maximum value we can lower.
  7083. if (IdxVal >= 0 &&
  7084. IdxVal < int64_t(2048 / Ty.getVectorElementType().getSizeInBits()))
  7085. return Op;
  7086. return SDValue();
  7087. }
  7088. SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
  7089. SelectionDAG &DAG) const {
  7090. ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
  7091. SDValue LHS = Op.getOperand(0);
  7092. SDValue RHS = Op.getOperand(1);
  7093. SDValue TVal = Op.getOperand(2);
  7094. SDValue FVal = Op.getOperand(3);
  7095. SDLoc DL(Op);
  7096. return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
  7097. }
  7098. SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
  7099. SelectionDAG &DAG) const {
  7100. SDValue CCVal = Op->getOperand(0);
  7101. SDValue TVal = Op->getOperand(1);
  7102. SDValue FVal = Op->getOperand(2);
  7103. SDLoc DL(Op);
  7104. EVT Ty = Op.getValueType();
  7105. if (Ty.isScalableVector()) {
  7106. SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
  7107. MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
  7108. SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
  7109. return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
  7110. }
  7111. if (useSVEForFixedLengthVectorVT(Ty)) {
  7112. // FIXME: Ideally this would be the same as above using i1 types, however
  7113. // for the moment we can't deal with fixed i1 vector types properly, so
  7114. // instead extend the predicate to a result type sized integer vector.
  7115. MVT SplatValVT = MVT::getIntegerVT(Ty.getScalarSizeInBits());
  7116. MVT PredVT = MVT::getVectorVT(SplatValVT, Ty.getVectorElementCount());
  7117. SDValue SplatVal = DAG.getSExtOrTrunc(CCVal, DL, SplatValVT);
  7118. SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, SplatVal);
  7119. return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
  7120. }
  7121. // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
  7122. // instruction.
  7123. if (ISD::isOverflowIntrOpRes(CCVal)) {
  7124. // Only lower legal XALUO ops.
  7125. if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
  7126. return SDValue();
  7127. AArch64CC::CondCode OFCC;
  7128. SDValue Value, Overflow;
  7129. std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
  7130. SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
  7131. return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
  7132. CCVal, Overflow);
  7133. }
  7134. // Lower it the same way as we would lower a SELECT_CC node.
  7135. ISD::CondCode CC;
  7136. SDValue LHS, RHS;
  7137. if (CCVal.getOpcode() == ISD::SETCC) {
  7138. LHS = CCVal.getOperand(0);
  7139. RHS = CCVal.getOperand(1);
  7140. CC = cast<CondCodeSDNode>(CCVal.getOperand(2))->get();
  7141. } else {
  7142. LHS = CCVal;
  7143. RHS = DAG.getConstant(0, DL, CCVal.getValueType());
  7144. CC = ISD::SETNE;
  7145. }
  7146. return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
  7147. }
  7148. SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
  7149. SelectionDAG &DAG) const {
  7150. // Jump table entries as PC relative offsets. No additional tweaking
  7151. // is necessary here. Just get the address of the jump table.
  7152. JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
  7153. if (getTargetMachine().getCodeModel() == CodeModel::Large &&
  7154. !Subtarget->isTargetMachO()) {
  7155. return getAddrLarge(JT, DAG);
  7156. } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
  7157. return getAddrTiny(JT, DAG);
  7158. }
  7159. return getAddr(JT, DAG);
  7160. }
  7161. SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
  7162. SelectionDAG &DAG) const {
  7163. // Jump table entries as PC relative offsets. No additional tweaking
  7164. // is necessary here. Just get the address of the jump table.
  7165. SDLoc DL(Op);
  7166. SDValue JT = Op.getOperand(1);
  7167. SDValue Entry = Op.getOperand(2);
  7168. int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
  7169. auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
  7170. AFI->setJumpTableEntryInfo(JTI, 4, nullptr);
  7171. SDNode *Dest =
  7172. DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
  7173. Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
  7174. return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
  7175. SDValue(Dest, 0));
  7176. }
  7177. SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
  7178. SelectionDAG &DAG) const {
  7179. ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
  7180. if (getTargetMachine().getCodeModel() == CodeModel::Large) {
  7181. // Use the GOT for the large code model on iOS.
  7182. if (Subtarget->isTargetMachO()) {
  7183. return getGOT(CP, DAG);
  7184. }
  7185. return getAddrLarge(CP, DAG);
  7186. } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
  7187. return getAddrTiny(CP, DAG);
  7188. } else {
  7189. return getAddr(CP, DAG);
  7190. }
  7191. }
  7192. SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
  7193. SelectionDAG &DAG) const {
  7194. BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
  7195. if (getTargetMachine().getCodeModel() == CodeModel::Large &&
  7196. !Subtarget->isTargetMachO()) {
  7197. return getAddrLarge(BA, DAG);
  7198. } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
  7199. return getAddrTiny(BA, DAG);
  7200. }
  7201. return getAddr(BA, DAG);
  7202. }
  7203. SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
  7204. SelectionDAG &DAG) const {
  7205. AArch64FunctionInfo *FuncInfo =
  7206. DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
  7207. SDLoc DL(Op);
  7208. SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
  7209. getPointerTy(DAG.getDataLayout()));
  7210. FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
  7211. const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  7212. return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
  7213. MachinePointerInfo(SV));
  7214. }
  7215. SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
  7216. SelectionDAG &DAG) const {
  7217. AArch64FunctionInfo *FuncInfo =
  7218. DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
  7219. SDLoc DL(Op);
  7220. SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
  7221. ? FuncInfo->getVarArgsGPRIndex()
  7222. : FuncInfo->getVarArgsStackIndex(),
  7223. getPointerTy(DAG.getDataLayout()));
  7224. const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  7225. return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
  7226. MachinePointerInfo(SV));
  7227. }
  7228. SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
  7229. SelectionDAG &DAG) const {
  7230. // The layout of the va_list struct is specified in the AArch64 Procedure Call
  7231. // Standard, section B.3.
  7232. MachineFunction &MF = DAG.getMachineFunction();
  7233. AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  7234. unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
  7235. auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
  7236. auto PtrVT = getPointerTy(DAG.getDataLayout());
  7237. SDLoc DL(Op);
  7238. SDValue Chain = Op.getOperand(0);
  7239. SDValue VAList = Op.getOperand(1);
  7240. const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  7241. SmallVector<SDValue, 4> MemOps;
  7242. // void *__stack at offset 0
  7243. unsigned Offset = 0;
  7244. SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
  7245. Stack = DAG.getZExtOrTrunc(Stack, DL, PtrMemVT);
  7246. MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
  7247. MachinePointerInfo(SV), Align(PtrSize)));
  7248. // void *__gr_top at offset 8 (4 on ILP32)
  7249. Offset += PtrSize;
  7250. int GPRSize = FuncInfo->getVarArgsGPRSize();
  7251. if (GPRSize > 0) {
  7252. SDValue GRTop, GRTopAddr;
  7253. GRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
  7254. DAG.getConstant(Offset, DL, PtrVT));
  7255. GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
  7256. GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
  7257. DAG.getConstant(GPRSize, DL, PtrVT));
  7258. GRTop = DAG.getZExtOrTrunc(GRTop, DL, PtrMemVT);
  7259. MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
  7260. MachinePointerInfo(SV, Offset),
  7261. Align(PtrSize)));
  7262. }
  7263. // void *__vr_top at offset 16 (8 on ILP32)
  7264. Offset += PtrSize;
  7265. int FPRSize = FuncInfo->getVarArgsFPRSize();
  7266. if (FPRSize > 0) {
  7267. SDValue VRTop, VRTopAddr;
  7268. VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
  7269. DAG.getConstant(Offset, DL, PtrVT));
  7270. VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
  7271. VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
  7272. DAG.getConstant(FPRSize, DL, PtrVT));
  7273. VRTop = DAG.getZExtOrTrunc(VRTop, DL, PtrMemVT);
  7274. MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
  7275. MachinePointerInfo(SV, Offset),
  7276. Align(PtrSize)));
  7277. }
  7278. // int __gr_offs at offset 24 (12 on ILP32)
  7279. Offset += PtrSize;
  7280. SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
  7281. DAG.getConstant(Offset, DL, PtrVT));
  7282. MemOps.push_back(
  7283. DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32),
  7284. GROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
  7285. // int __vr_offs at offset 28 (16 on ILP32)
  7286. Offset += 4;
  7287. SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
  7288. DAG.getConstant(Offset, DL, PtrVT));
  7289. MemOps.push_back(
  7290. DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32),
  7291. VROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
  7292. return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
  7293. }
  7294. SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
  7295. SelectionDAG &DAG) const {
  7296. MachineFunction &MF = DAG.getMachineFunction();
  7297. if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
  7298. return LowerWin64_VASTART(Op, DAG);
  7299. else if (Subtarget->isTargetDarwin())
  7300. return LowerDarwin_VASTART(Op, DAG);
  7301. else
  7302. return LowerAAPCS_VASTART(Op, DAG);
  7303. }
  7304. SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
  7305. SelectionDAG &DAG) const {
  7306. // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
  7307. // pointer.
  7308. SDLoc DL(Op);
  7309. unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
  7310. unsigned VaListSize =
  7311. (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
  7312. ? PtrSize
  7313. : Subtarget->isTargetILP32() ? 20 : 32;
  7314. const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
  7315. const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
  7316. return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
  7317. DAG.getConstant(VaListSize, DL, MVT::i32),
  7318. Align(PtrSize), false, false, false,
  7319. MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
  7320. }
  7321. SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
  7322. assert(Subtarget->isTargetDarwin() &&
  7323. "automatic va_arg instruction only works on Darwin");
  7324. const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  7325. EVT VT = Op.getValueType();
  7326. SDLoc DL(Op);
  7327. SDValue Chain = Op.getOperand(0);
  7328. SDValue Addr = Op.getOperand(1);
  7329. MaybeAlign Align(Op.getConstantOperandVal(3));
  7330. unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
  7331. auto PtrVT = getPointerTy(DAG.getDataLayout());
  7332. auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
  7333. SDValue VAList =
  7334. DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
  7335. Chain = VAList.getValue(1);
  7336. VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
  7337. if (VT.isScalableVector())
  7338. report_fatal_error("Passing SVE types to variadic functions is "
  7339. "currently not supported");
  7340. if (Align && *Align > MinSlotSize) {
  7341. VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
  7342. DAG.getConstant(Align->value() - 1, DL, PtrVT));
  7343. VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
  7344. DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
  7345. }
  7346. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  7347. unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
  7348. // Scalar integer and FP values smaller than 64 bits are implicitly extended
  7349. // up to 64 bits. At the very least, we have to increase the striding of the
  7350. // vaargs list to match this, and for FP values we need to introduce
  7351. // FP_ROUND nodes as well.
  7352. if (VT.isInteger() && !VT.isVector())
  7353. ArgSize = std::max(ArgSize, MinSlotSize);
  7354. bool NeedFPTrunc = false;
  7355. if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
  7356. ArgSize = 8;
  7357. NeedFPTrunc = true;
  7358. }
  7359. // Increment the pointer, VAList, to the next vaarg
  7360. SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
  7361. DAG.getConstant(ArgSize, DL, PtrVT));
  7362. VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
  7363. // Store the incremented VAList to the legalized pointer
  7364. SDValue APStore =
  7365. DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
  7366. // Load the actual argument out of the pointer VAList
  7367. if (NeedFPTrunc) {
  7368. // Load the value as an f64.
  7369. SDValue WideFP =
  7370. DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
  7371. // Round the value down to an f32.
  7372. SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
  7373. DAG.getIntPtrConstant(1, DL));
  7374. SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
  7375. // Merge the rounded value with the chain output of the load.
  7376. return DAG.getMergeValues(Ops, DL);
  7377. }
  7378. return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
  7379. }
  7380. SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
  7381. SelectionDAG &DAG) const {
  7382. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  7383. MFI.setFrameAddressIsTaken(true);
  7384. EVT VT = Op.getValueType();
  7385. SDLoc DL(Op);
  7386. unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  7387. SDValue FrameAddr =
  7388. DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
  7389. while (Depth--)
  7390. FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
  7391. MachinePointerInfo());
  7392. if (Subtarget->isTargetILP32())
  7393. FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
  7394. DAG.getValueType(VT));
  7395. return FrameAddr;
  7396. }
  7397. SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
  7398. SelectionDAG &DAG) const {
  7399. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  7400. EVT VT = getPointerTy(DAG.getDataLayout());
  7401. SDLoc DL(Op);
  7402. int FI = MFI.CreateFixedObject(4, 0, false);
  7403. return DAG.getFrameIndex(FI, VT);
  7404. }
  7405. #define GET_REGISTER_MATCHER
  7406. #include "AArch64GenAsmMatcher.inc"
  7407. // FIXME? Maybe this could be a TableGen attribute on some registers and
  7408. // this table could be generated automatically from RegInfo.
  7409. Register AArch64TargetLowering::
  7410. getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
  7411. Register Reg = MatchRegisterName(RegName);
  7412. if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
  7413. const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
  7414. unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
  7415. if (!Subtarget->isXRegisterReserved(DwarfRegNum))
  7416. Reg = 0;
  7417. }
  7418. if (Reg)
  7419. return Reg;
  7420. report_fatal_error(Twine("Invalid register name \""
  7421. + StringRef(RegName) + "\"."));
  7422. }
  7423. SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
  7424. SelectionDAG &DAG) const {
  7425. DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
  7426. EVT VT = Op.getValueType();
  7427. SDLoc DL(Op);
  7428. SDValue FrameAddr =
  7429. DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
  7430. SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
  7431. return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
  7432. }
  7433. SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
  7434. SelectionDAG &DAG) const {
  7435. MachineFunction &MF = DAG.getMachineFunction();
  7436. MachineFrameInfo &MFI = MF.getFrameInfo();
  7437. MFI.setReturnAddressIsTaken(true);
  7438. EVT VT = Op.getValueType();
  7439. SDLoc DL(Op);
  7440. unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  7441. SDValue ReturnAddress;
  7442. if (Depth) {
  7443. SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
  7444. SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
  7445. ReturnAddress = DAG.getLoad(
  7446. VT, DL, DAG.getEntryNode(),
  7447. DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo());
  7448. } else {
  7449. // Return LR, which contains the return address. Mark it an implicit
  7450. // live-in.
  7451. Register Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
  7452. ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
  7453. }
  7454. // The XPACLRI instruction assembles to a hint-space instruction before
  7455. // Armv8.3-A therefore this instruction can be safely used for any pre
  7456. // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use
  7457. // that instead.
  7458. SDNode *St;
  7459. if (Subtarget->hasPAuth()) {
  7460. St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress);
  7461. } else {
  7462. // XPACLRI operates on LR therefore we must move the operand accordingly.
  7463. SDValue Chain =
  7464. DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress);
  7465. St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain);
  7466. }
  7467. return SDValue(St, 0);
  7468. }
  7469. /// LowerShiftParts - Lower SHL_PARTS/SRA_PARTS/SRL_PARTS, which returns two
  7470. /// i32 values and take a 2 x i32 value to shift plus a shift amount.
  7471. SDValue AArch64TargetLowering::LowerShiftParts(SDValue Op,
  7472. SelectionDAG &DAG) const {
  7473. SDValue Lo, Hi;
  7474. expandShiftParts(Op.getNode(), Lo, Hi, DAG);
  7475. return DAG.getMergeValues({Lo, Hi}, SDLoc(Op));
  7476. }
  7477. bool AArch64TargetLowering::isOffsetFoldingLegal(
  7478. const GlobalAddressSDNode *GA) const {
  7479. // Offsets are folded in the DAG combine rather than here so that we can
  7480. // intelligently choose an offset based on the uses.
  7481. return false;
  7482. }
  7483. bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
  7484. bool OptForSize) const {
  7485. bool IsLegal = false;
  7486. // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
  7487. // 16-bit case when target has full fp16 support.
  7488. // FIXME: We should be able to handle f128 as well with a clever lowering.
  7489. const APInt ImmInt = Imm.bitcastToAPInt();
  7490. if (VT == MVT::f64)
  7491. IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
  7492. else if (VT == MVT::f32)
  7493. IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
  7494. else if (VT == MVT::f16 && Subtarget->hasFullFP16())
  7495. IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
  7496. // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
  7497. // generate that fmov.
  7498. // If we can not materialize in immediate field for fmov, check if the
  7499. // value can be encoded as the immediate operand of a logical instruction.
  7500. // The immediate value will be created with either MOVZ, MOVN, or ORR.
  7501. if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
  7502. // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
  7503. // however the mov+fmov sequence is always better because of the reduced
  7504. // cache pressure. The timings are still the same if you consider
  7505. // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
  7506. // movw+movk is fused). So we limit up to 2 instrdduction at most.
  7507. SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
  7508. AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
  7509. Insn);
  7510. unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
  7511. IsLegal = Insn.size() <= Limit;
  7512. }
  7513. LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
  7514. << " imm value: "; Imm.dump(););
  7515. return IsLegal;
  7516. }
  7517. //===----------------------------------------------------------------------===//
  7518. // AArch64 Optimization Hooks
  7519. //===----------------------------------------------------------------------===//
  7520. static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
  7521. SDValue Operand, SelectionDAG &DAG,
  7522. int &ExtraSteps) {
  7523. EVT VT = Operand.getValueType();
  7524. if ((ST->hasNEON() &&
  7525. (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
  7526. VT == MVT::f32 || VT == MVT::v1f32 || VT == MVT::v2f32 ||
  7527. VT == MVT::v4f32)) ||
  7528. (ST->hasSVE() &&
  7529. (VT == MVT::nxv8f16 || VT == MVT::nxv4f32 || VT == MVT::nxv2f64))) {
  7530. if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
  7531. // For the reciprocal estimates, convergence is quadratic, so the number
  7532. // of digits is doubled after each iteration. In ARMv8, the accuracy of
  7533. // the initial estimate is 2^-8. Thus the number of extra steps to refine
  7534. // the result for float (23 mantissa bits) is 2 and for double (52
  7535. // mantissa bits) is 3.
  7536. ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
  7537. return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
  7538. }
  7539. return SDValue();
  7540. }
  7541. SDValue
  7542. AArch64TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
  7543. const DenormalMode &Mode) const {
  7544. SDLoc DL(Op);
  7545. EVT VT = Op.getValueType();
  7546. EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
  7547. SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
  7548. return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
  7549. }
  7550. SDValue
  7551. AArch64TargetLowering::getSqrtResultForDenormInput(SDValue Op,
  7552. SelectionDAG &DAG) const {
  7553. return Op;
  7554. }
  7555. SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
  7556. SelectionDAG &DAG, int Enabled,
  7557. int &ExtraSteps,
  7558. bool &UseOneConst,
  7559. bool Reciprocal) const {
  7560. if (Enabled == ReciprocalEstimate::Enabled ||
  7561. (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
  7562. if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
  7563. DAG, ExtraSteps)) {
  7564. SDLoc DL(Operand);
  7565. EVT VT = Operand.getValueType();
  7566. SDNodeFlags Flags;
  7567. Flags.setAllowReassociation(true);
  7568. // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
  7569. // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
  7570. for (int i = ExtraSteps; i > 0; --i) {
  7571. SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
  7572. Flags);
  7573. Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
  7574. Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
  7575. }
  7576. if (!Reciprocal)
  7577. Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
  7578. ExtraSteps = 0;
  7579. return Estimate;
  7580. }
  7581. return SDValue();
  7582. }
  7583. SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
  7584. SelectionDAG &DAG, int Enabled,
  7585. int &ExtraSteps) const {
  7586. if (Enabled == ReciprocalEstimate::Enabled)
  7587. if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
  7588. DAG, ExtraSteps)) {
  7589. SDLoc DL(Operand);
  7590. EVT VT = Operand.getValueType();
  7591. SDNodeFlags Flags;
  7592. Flags.setAllowReassociation(true);
  7593. // Newton reciprocal iteration: E * (2 - X * E)
  7594. // AArch64 reciprocal iteration instruction: (2 - M * N)
  7595. for (int i = ExtraSteps; i > 0; --i) {
  7596. SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
  7597. Estimate, Flags);
  7598. Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
  7599. }
  7600. ExtraSteps = 0;
  7601. return Estimate;
  7602. }
  7603. return SDValue();
  7604. }
  7605. //===----------------------------------------------------------------------===//
  7606. // AArch64 Inline Assembly Support
  7607. //===----------------------------------------------------------------------===//
  7608. // Table of Constraints
  7609. // TODO: This is the current set of constraints supported by ARM for the
  7610. // compiler, not all of them may make sense.
  7611. //
  7612. // r - A general register
  7613. // w - An FP/SIMD register of some size in the range v0-v31
  7614. // x - An FP/SIMD register of some size in the range v0-v15
  7615. // I - Constant that can be used with an ADD instruction
  7616. // J - Constant that can be used with a SUB instruction
  7617. // K - Constant that can be used with a 32-bit logical instruction
  7618. // L - Constant that can be used with a 64-bit logical instruction
  7619. // M - Constant that can be used as a 32-bit MOV immediate
  7620. // N - Constant that can be used as a 64-bit MOV immediate
  7621. // Q - A memory reference with base register and no offset
  7622. // S - A symbolic address
  7623. // Y - Floating point constant zero
  7624. // Z - Integer constant zero
  7625. //
  7626. // Note that general register operands will be output using their 64-bit x
  7627. // register name, whatever the size of the variable, unless the asm operand
  7628. // is prefixed by the %w modifier. Floating-point and SIMD register operands
  7629. // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
  7630. // %q modifier.
  7631. const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
  7632. // At this point, we have to lower this constraint to something else, so we
  7633. // lower it to an "r" or "w". However, by doing this we will force the result
  7634. // to be in register, while the X constraint is much more permissive.
  7635. //
  7636. // Although we are correct (we are free to emit anything, without
  7637. // constraints), we might break use cases that would expect us to be more
  7638. // efficient and emit something else.
  7639. if (!Subtarget->hasFPARMv8())
  7640. return "r";
  7641. if (ConstraintVT.isFloatingPoint())
  7642. return "w";
  7643. if (ConstraintVT.isVector() &&
  7644. (ConstraintVT.getSizeInBits() == 64 ||
  7645. ConstraintVT.getSizeInBits() == 128))
  7646. return "w";
  7647. return "r";
  7648. }
  7649. enum PredicateConstraint {
  7650. Upl,
  7651. Upa,
  7652. Invalid
  7653. };
  7654. static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
  7655. PredicateConstraint P = PredicateConstraint::Invalid;
  7656. if (Constraint == "Upa")
  7657. P = PredicateConstraint::Upa;
  7658. if (Constraint == "Upl")
  7659. P = PredicateConstraint::Upl;
  7660. return P;
  7661. }
  7662. /// getConstraintType - Given a constraint letter, return the type of
  7663. /// constraint it is for this target.
  7664. AArch64TargetLowering::ConstraintType
  7665. AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
  7666. if (Constraint.size() == 1) {
  7667. switch (Constraint[0]) {
  7668. default:
  7669. break;
  7670. case 'x':
  7671. case 'w':
  7672. case 'y':
  7673. return C_RegisterClass;
  7674. // An address with a single base register. Due to the way we
  7675. // currently handle addresses it is the same as 'r'.
  7676. case 'Q':
  7677. return C_Memory;
  7678. case 'I':
  7679. case 'J':
  7680. case 'K':
  7681. case 'L':
  7682. case 'M':
  7683. case 'N':
  7684. case 'Y':
  7685. case 'Z':
  7686. return C_Immediate;
  7687. case 'z':
  7688. case 'S': // A symbolic address
  7689. return C_Other;
  7690. }
  7691. } else if (parsePredicateConstraint(Constraint) !=
  7692. PredicateConstraint::Invalid)
  7693. return C_RegisterClass;
  7694. return TargetLowering::getConstraintType(Constraint);
  7695. }
  7696. /// Examine constraint type and operand type and determine a weight value.
  7697. /// This object must already have been set up with the operand type
  7698. /// and the current alternative constraint selected.
  7699. TargetLowering::ConstraintWeight
  7700. AArch64TargetLowering::getSingleConstraintMatchWeight(
  7701. AsmOperandInfo &info, const char *constraint) const {
  7702. ConstraintWeight weight = CW_Invalid;
  7703. Value *CallOperandVal = info.CallOperandVal;
  7704. // If we don't have a value, we can't do a match,
  7705. // but allow it at the lowest weight.
  7706. if (!CallOperandVal)
  7707. return CW_Default;
  7708. Type *type = CallOperandVal->getType();
  7709. // Look at the constraint type.
  7710. switch (*constraint) {
  7711. default:
  7712. weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
  7713. break;
  7714. case 'x':
  7715. case 'w':
  7716. case 'y':
  7717. if (type->isFloatingPointTy() || type->isVectorTy())
  7718. weight = CW_Register;
  7719. break;
  7720. case 'z':
  7721. weight = CW_Constant;
  7722. break;
  7723. case 'U':
  7724. if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
  7725. weight = CW_Register;
  7726. break;
  7727. }
  7728. return weight;
  7729. }
  7730. std::pair<unsigned, const TargetRegisterClass *>
  7731. AArch64TargetLowering::getRegForInlineAsmConstraint(
  7732. const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
  7733. if (Constraint.size() == 1) {
  7734. switch (Constraint[0]) {
  7735. case 'r':
  7736. if (VT.isScalableVector())
  7737. return std::make_pair(0U, nullptr);
  7738. if (Subtarget->hasLS64() && VT.getSizeInBits() == 512)
  7739. return std::make_pair(0U, &AArch64::GPR64x8ClassRegClass);
  7740. if (VT.getFixedSizeInBits() == 64)
  7741. return std::make_pair(0U, &AArch64::GPR64commonRegClass);
  7742. return std::make_pair(0U, &AArch64::GPR32commonRegClass);
  7743. case 'w': {
  7744. if (!Subtarget->hasFPARMv8())
  7745. break;
  7746. if (VT.isScalableVector()) {
  7747. if (VT.getVectorElementType() != MVT::i1)
  7748. return std::make_pair(0U, &AArch64::ZPRRegClass);
  7749. return std::make_pair(0U, nullptr);
  7750. }
  7751. uint64_t VTSize = VT.getFixedSizeInBits();
  7752. if (VTSize == 16)
  7753. return std::make_pair(0U, &AArch64::FPR16RegClass);
  7754. if (VTSize == 32)
  7755. return std::make_pair(0U, &AArch64::FPR32RegClass);
  7756. if (VTSize == 64)
  7757. return std::make_pair(0U, &AArch64::FPR64RegClass);
  7758. if (VTSize == 128)
  7759. return std::make_pair(0U, &AArch64::FPR128RegClass);
  7760. break;
  7761. }
  7762. // The instructions that this constraint is designed for can
  7763. // only take 128-bit registers so just use that regclass.
  7764. case 'x':
  7765. if (!Subtarget->hasFPARMv8())
  7766. break;
  7767. if (VT.isScalableVector())
  7768. return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
  7769. if (VT.getSizeInBits() == 128)
  7770. return std::make_pair(0U, &AArch64::FPR128_loRegClass);
  7771. break;
  7772. case 'y':
  7773. if (!Subtarget->hasFPARMv8())
  7774. break;
  7775. if (VT.isScalableVector())
  7776. return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
  7777. break;
  7778. }
  7779. } else {
  7780. PredicateConstraint PC = parsePredicateConstraint(Constraint);
  7781. if (PC != PredicateConstraint::Invalid) {
  7782. if (!VT.isScalableVector() || VT.getVectorElementType() != MVT::i1)
  7783. return std::make_pair(0U, nullptr);
  7784. bool restricted = (PC == PredicateConstraint::Upl);
  7785. return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
  7786. : std::make_pair(0U, &AArch64::PPRRegClass);
  7787. }
  7788. }
  7789. if (StringRef("{cc}").equals_insensitive(Constraint))
  7790. return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
  7791. // Use the default implementation in TargetLowering to convert the register
  7792. // constraint into a member of a register class.
  7793. std::pair<unsigned, const TargetRegisterClass *> Res;
  7794. Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
  7795. // Not found as a standard register?
  7796. if (!Res.second) {
  7797. unsigned Size = Constraint.size();
  7798. if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
  7799. tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
  7800. int RegNo;
  7801. bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
  7802. if (!Failed && RegNo >= 0 && RegNo <= 31) {
  7803. // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
  7804. // By default we'll emit v0-v31 for this unless there's a modifier where
  7805. // we'll emit the correct register as well.
  7806. if (VT != MVT::Other && VT.getSizeInBits() == 64) {
  7807. Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
  7808. Res.second = &AArch64::FPR64RegClass;
  7809. } else {
  7810. Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
  7811. Res.second = &AArch64::FPR128RegClass;
  7812. }
  7813. }
  7814. }
  7815. }
  7816. if (Res.second && !Subtarget->hasFPARMv8() &&
  7817. !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
  7818. !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
  7819. return std::make_pair(0U, nullptr);
  7820. return Res;
  7821. }
  7822. EVT AArch64TargetLowering::getAsmOperandValueType(const DataLayout &DL,
  7823. llvm::Type *Ty,
  7824. bool AllowUnknown) const {
  7825. if (Subtarget->hasLS64() && Ty->isIntegerTy(512))
  7826. return EVT(MVT::i64x8);
  7827. return TargetLowering::getAsmOperandValueType(DL, Ty, AllowUnknown);
  7828. }
  7829. /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
  7830. /// vector. If it is invalid, don't add anything to Ops.
  7831. void AArch64TargetLowering::LowerAsmOperandForConstraint(
  7832. SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
  7833. SelectionDAG &DAG) const {
  7834. SDValue Result;
  7835. // Currently only support length 1 constraints.
  7836. if (Constraint.length() != 1)
  7837. return;
  7838. char ConstraintLetter = Constraint[0];
  7839. switch (ConstraintLetter) {
  7840. default:
  7841. break;
  7842. // This set of constraints deal with valid constants for various instructions.
  7843. // Validate and return a target constant for them if we can.
  7844. case 'z': {
  7845. // 'z' maps to xzr or wzr so it needs an input of 0.
  7846. if (!isNullConstant(Op))
  7847. return;
  7848. if (Op.getValueType() == MVT::i64)
  7849. Result = DAG.getRegister(AArch64::XZR, MVT::i64);
  7850. else
  7851. Result = DAG.getRegister(AArch64::WZR, MVT::i32);
  7852. break;
  7853. }
  7854. case 'S': {
  7855. // An absolute symbolic address or label reference.
  7856. if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
  7857. Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
  7858. GA->getValueType(0));
  7859. } else if (const BlockAddressSDNode *BA =
  7860. dyn_cast<BlockAddressSDNode>(Op)) {
  7861. Result =
  7862. DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
  7863. } else
  7864. return;
  7865. break;
  7866. }
  7867. case 'I':
  7868. case 'J':
  7869. case 'K':
  7870. case 'L':
  7871. case 'M':
  7872. case 'N':
  7873. ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
  7874. if (!C)
  7875. return;
  7876. // Grab the value and do some validation.
  7877. uint64_t CVal = C->getZExtValue();
  7878. switch (ConstraintLetter) {
  7879. // The I constraint applies only to simple ADD or SUB immediate operands:
  7880. // i.e. 0 to 4095 with optional shift by 12
  7881. // The J constraint applies only to ADD or SUB immediates that would be
  7882. // valid when negated, i.e. if [an add pattern] were to be output as a SUB
  7883. // instruction [or vice versa], in other words -1 to -4095 with optional
  7884. // left shift by 12.
  7885. case 'I':
  7886. if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
  7887. break;
  7888. return;
  7889. case 'J': {
  7890. uint64_t NVal = -C->getSExtValue();
  7891. if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
  7892. CVal = C->getSExtValue();
  7893. break;
  7894. }
  7895. return;
  7896. }
  7897. // The K and L constraints apply *only* to logical immediates, including
  7898. // what used to be the MOVI alias for ORR (though the MOVI alias has now
  7899. // been removed and MOV should be used). So these constraints have to
  7900. // distinguish between bit patterns that are valid 32-bit or 64-bit
  7901. // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
  7902. // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
  7903. // versa.
  7904. case 'K':
  7905. if (AArch64_AM::isLogicalImmediate(CVal, 32))
  7906. break;
  7907. return;
  7908. case 'L':
  7909. if (AArch64_AM::isLogicalImmediate(CVal, 64))
  7910. break;
  7911. return;
  7912. // The M and N constraints are a superset of K and L respectively, for use
  7913. // with the MOV (immediate) alias. As well as the logical immediates they
  7914. // also match 32 or 64-bit immediates that can be loaded either using a
  7915. // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
  7916. // (M) or 64-bit 0x1234000000000000 (N) etc.
  7917. // As a note some of this code is liberally stolen from the asm parser.
  7918. case 'M': {
  7919. if (!isUInt<32>(CVal))
  7920. return;
  7921. if (AArch64_AM::isLogicalImmediate(CVal, 32))
  7922. break;
  7923. if ((CVal & 0xFFFF) == CVal)
  7924. break;
  7925. if ((CVal & 0xFFFF0000ULL) == CVal)
  7926. break;
  7927. uint64_t NCVal = ~(uint32_t)CVal;
  7928. if ((NCVal & 0xFFFFULL) == NCVal)
  7929. break;
  7930. if ((NCVal & 0xFFFF0000ULL) == NCVal)
  7931. break;
  7932. return;
  7933. }
  7934. case 'N': {
  7935. if (AArch64_AM::isLogicalImmediate(CVal, 64))
  7936. break;
  7937. if ((CVal & 0xFFFFULL) == CVal)
  7938. break;
  7939. if ((CVal & 0xFFFF0000ULL) == CVal)
  7940. break;
  7941. if ((CVal & 0xFFFF00000000ULL) == CVal)
  7942. break;
  7943. if ((CVal & 0xFFFF000000000000ULL) == CVal)
  7944. break;
  7945. uint64_t NCVal = ~CVal;
  7946. if ((NCVal & 0xFFFFULL) == NCVal)
  7947. break;
  7948. if ((NCVal & 0xFFFF0000ULL) == NCVal)
  7949. break;
  7950. if ((NCVal & 0xFFFF00000000ULL) == NCVal)
  7951. break;
  7952. if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
  7953. break;
  7954. return;
  7955. }
  7956. default:
  7957. return;
  7958. }
  7959. // All assembler immediates are 64-bit integers.
  7960. Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
  7961. break;
  7962. }
  7963. if (Result.getNode()) {
  7964. Ops.push_back(Result);
  7965. return;
  7966. }
  7967. return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
  7968. }
  7969. //===----------------------------------------------------------------------===//
  7970. // AArch64 Advanced SIMD Support
  7971. //===----------------------------------------------------------------------===//
  7972. /// WidenVector - Given a value in the V64 register class, produce the
  7973. /// equivalent value in the V128 register class.
  7974. static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
  7975. EVT VT = V64Reg.getValueType();
  7976. unsigned NarrowSize = VT.getVectorNumElements();
  7977. MVT EltTy = VT.getVectorElementType().getSimpleVT();
  7978. MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
  7979. SDLoc DL(V64Reg);
  7980. return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
  7981. V64Reg, DAG.getConstant(0, DL, MVT::i64));
  7982. }
  7983. /// getExtFactor - Determine the adjustment factor for the position when
  7984. /// generating an "extract from vector registers" instruction.
  7985. static unsigned getExtFactor(SDValue &V) {
  7986. EVT EltType = V.getValueType().getVectorElementType();
  7987. return EltType.getSizeInBits() / 8;
  7988. }
  7989. /// NarrowVector - Given a value in the V128 register class, produce the
  7990. /// equivalent value in the V64 register class.
  7991. static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
  7992. EVT VT = V128Reg.getValueType();
  7993. unsigned WideSize = VT.getVectorNumElements();
  7994. MVT EltTy = VT.getVectorElementType().getSimpleVT();
  7995. MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
  7996. SDLoc DL(V128Reg);
  7997. return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
  7998. }
  7999. // Gather data to see if the operation can be modelled as a
  8000. // shuffle in combination with VEXTs.
  8001. SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
  8002. SelectionDAG &DAG) const {
  8003. assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
  8004. LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
  8005. SDLoc dl(Op);
  8006. EVT VT = Op.getValueType();
  8007. assert(!VT.isScalableVector() &&
  8008. "Scalable vectors cannot be used with ISD::BUILD_VECTOR");
  8009. unsigned NumElts = VT.getVectorNumElements();
  8010. struct ShuffleSourceInfo {
  8011. SDValue Vec;
  8012. unsigned MinElt;
  8013. unsigned MaxElt;
  8014. // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
  8015. // be compatible with the shuffle we intend to construct. As a result
  8016. // ShuffleVec will be some sliding window into the original Vec.
  8017. SDValue ShuffleVec;
  8018. // Code should guarantee that element i in Vec starts at element "WindowBase
  8019. // + i * WindowScale in ShuffleVec".
  8020. int WindowBase;
  8021. int WindowScale;
  8022. ShuffleSourceInfo(SDValue Vec)
  8023. : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
  8024. ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
  8025. bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
  8026. };
  8027. // First gather all vectors used as an immediate source for this BUILD_VECTOR
  8028. // node.
  8029. SmallVector<ShuffleSourceInfo, 2> Sources;
  8030. for (unsigned i = 0; i < NumElts; ++i) {
  8031. SDValue V = Op.getOperand(i);
  8032. if (V.isUndef())
  8033. continue;
  8034. else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  8035. !isa<ConstantSDNode>(V.getOperand(1)) ||
  8036. V.getOperand(0).getValueType().isScalableVector()) {
  8037. LLVM_DEBUG(
  8038. dbgs() << "Reshuffle failed: "
  8039. "a shuffle can only come from building a vector from "
  8040. "various elements of other fixed-width vectors, provided "
  8041. "their indices are constant\n");
  8042. return SDValue();
  8043. }
  8044. // Add this element source to the list if it's not already there.
  8045. SDValue SourceVec = V.getOperand(0);
  8046. auto Source = find(Sources, SourceVec);
  8047. if (Source == Sources.end())
  8048. Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
  8049. // Update the minimum and maximum lane number seen.
  8050. unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
  8051. Source->MinElt = std::min(Source->MinElt, EltNo);
  8052. Source->MaxElt = std::max(Source->MaxElt, EltNo);
  8053. }
  8054. if (Sources.size() > 2) {
  8055. LLVM_DEBUG(
  8056. dbgs() << "Reshuffle failed: currently only do something sane when at "
  8057. "most two source vectors are involved\n");
  8058. return SDValue();
  8059. }
  8060. // Find out the smallest element size among result and two sources, and use
  8061. // it as element size to build the shuffle_vector.
  8062. EVT SmallestEltTy = VT.getVectorElementType();
  8063. for (auto &Source : Sources) {
  8064. EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
  8065. if (SrcEltTy.bitsLT(SmallestEltTy)) {
  8066. SmallestEltTy = SrcEltTy;
  8067. }
  8068. }
  8069. unsigned ResMultiplier =
  8070. VT.getScalarSizeInBits() / SmallestEltTy.getFixedSizeInBits();
  8071. uint64_t VTSize = VT.getFixedSizeInBits();
  8072. NumElts = VTSize / SmallestEltTy.getFixedSizeInBits();
  8073. EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
  8074. // If the source vector is too wide or too narrow, we may nevertheless be able
  8075. // to construct a compatible shuffle either by concatenating it with UNDEF or
  8076. // extracting a suitable range of elements.
  8077. for (auto &Src : Sources) {
  8078. EVT SrcVT = Src.ShuffleVec.getValueType();
  8079. TypeSize SrcVTSize = SrcVT.getSizeInBits();
  8080. if (SrcVTSize == TypeSize::Fixed(VTSize))
  8081. continue;
  8082. // This stage of the search produces a source with the same element type as
  8083. // the original, but with a total width matching the BUILD_VECTOR output.
  8084. EVT EltVT = SrcVT.getVectorElementType();
  8085. unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
  8086. EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
  8087. if (SrcVTSize.getFixedValue() < VTSize) {
  8088. assert(2 * SrcVTSize == VTSize);
  8089. // We can pad out the smaller vector for free, so if it's part of a
  8090. // shuffle...
  8091. Src.ShuffleVec =
  8092. DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
  8093. DAG.getUNDEF(Src.ShuffleVec.getValueType()));
  8094. continue;
  8095. }
  8096. if (SrcVTSize.getFixedValue() != 2 * VTSize) {
  8097. LLVM_DEBUG(
  8098. dbgs() << "Reshuffle failed: result vector too small to extract\n");
  8099. return SDValue();
  8100. }
  8101. if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
  8102. LLVM_DEBUG(
  8103. dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
  8104. return SDValue();
  8105. }
  8106. if (Src.MinElt >= NumSrcElts) {
  8107. // The extraction can just take the second half
  8108. Src.ShuffleVec =
  8109. DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
  8110. DAG.getConstant(NumSrcElts, dl, MVT::i64));
  8111. Src.WindowBase = -NumSrcElts;
  8112. } else if (Src.MaxElt < NumSrcElts) {
  8113. // The extraction can just take the first half
  8114. Src.ShuffleVec =
  8115. DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
  8116. DAG.getConstant(0, dl, MVT::i64));
  8117. } else {
  8118. // An actual VEXT is needed
  8119. SDValue VEXTSrc1 =
  8120. DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
  8121. DAG.getConstant(0, dl, MVT::i64));
  8122. SDValue VEXTSrc2 =
  8123. DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
  8124. DAG.getConstant(NumSrcElts, dl, MVT::i64));
  8125. unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
  8126. if (!SrcVT.is64BitVector()) {
  8127. LLVM_DEBUG(
  8128. dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT "
  8129. "for SVE vectors.");
  8130. return SDValue();
  8131. }
  8132. Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
  8133. VEXTSrc2,
  8134. DAG.getConstant(Imm, dl, MVT::i32));
  8135. Src.WindowBase = -Src.MinElt;
  8136. }
  8137. }
  8138. // Another possible incompatibility occurs from the vector element types. We
  8139. // can fix this by bitcasting the source vectors to the same type we intend
  8140. // for the shuffle.
  8141. for (auto &Src : Sources) {
  8142. EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
  8143. if (SrcEltTy == SmallestEltTy)
  8144. continue;
  8145. assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
  8146. Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
  8147. Src.WindowScale =
  8148. SrcEltTy.getFixedSizeInBits() / SmallestEltTy.getFixedSizeInBits();
  8149. Src.WindowBase *= Src.WindowScale;
  8150. }
  8151. // Final check before we try to actually produce a shuffle.
  8152. LLVM_DEBUG(for (auto Src
  8153. : Sources)
  8154. assert(Src.ShuffleVec.getValueType() == ShuffleVT););
  8155. // The stars all align, our next step is to produce the mask for the shuffle.
  8156. SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
  8157. int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
  8158. for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
  8159. SDValue Entry = Op.getOperand(i);
  8160. if (Entry.isUndef())
  8161. continue;
  8162. auto Src = find(Sources, Entry.getOperand(0));
  8163. int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
  8164. // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
  8165. // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
  8166. // segment.
  8167. EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
  8168. int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
  8169. VT.getScalarSizeInBits());
  8170. int LanesDefined = BitsDefined / BitsPerShuffleLane;
  8171. // This source is expected to fill ResMultiplier lanes of the final shuffle,
  8172. // starting at the appropriate offset.
  8173. int *LaneMask = &Mask[i * ResMultiplier];
  8174. int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
  8175. ExtractBase += NumElts * (Src - Sources.begin());
  8176. for (int j = 0; j < LanesDefined; ++j)
  8177. LaneMask[j] = ExtractBase + j;
  8178. }
  8179. // Final check before we try to produce nonsense...
  8180. if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
  8181. LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
  8182. return SDValue();
  8183. }
  8184. SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
  8185. for (unsigned i = 0; i < Sources.size(); ++i)
  8186. ShuffleOps[i] = Sources[i].ShuffleVec;
  8187. SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
  8188. ShuffleOps[1], Mask);
  8189. SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
  8190. LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
  8191. dbgs() << "Reshuffle, creating node: "; V.dump(););
  8192. return V;
  8193. }
  8194. // check if an EXT instruction can handle the shuffle mask when the
  8195. // vector sources of the shuffle are the same.
  8196. static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
  8197. unsigned NumElts = VT.getVectorNumElements();
  8198. // Assume that the first shuffle index is not UNDEF. Fail if it is.
  8199. if (M[0] < 0)
  8200. return false;
  8201. Imm = M[0];
  8202. // If this is a VEXT shuffle, the immediate value is the index of the first
  8203. // element. The other shuffle indices must be the successive elements after
  8204. // the first one.
  8205. unsigned ExpectedElt = Imm;
  8206. for (unsigned i = 1; i < NumElts; ++i) {
  8207. // Increment the expected index. If it wraps around, just follow it
  8208. // back to index zero and keep going.
  8209. ++ExpectedElt;
  8210. if (ExpectedElt == NumElts)
  8211. ExpectedElt = 0;
  8212. if (M[i] < 0)
  8213. continue; // ignore UNDEF indices
  8214. if (ExpectedElt != static_cast<unsigned>(M[i]))
  8215. return false;
  8216. }
  8217. return true;
  8218. }
  8219. /// Check if a vector shuffle corresponds to a DUP instructions with a larger
  8220. /// element width than the vector lane type. If that is the case the function
  8221. /// returns true and writes the value of the DUP instruction lane operand into
  8222. /// DupLaneOp
  8223. static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize,
  8224. unsigned &DupLaneOp) {
  8225. assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
  8226. "Only possible block sizes for wide DUP are: 16, 32, 64");
  8227. if (BlockSize <= VT.getScalarSizeInBits())
  8228. return false;
  8229. if (BlockSize % VT.getScalarSizeInBits() != 0)
  8230. return false;
  8231. if (VT.getSizeInBits() % BlockSize != 0)
  8232. return false;
  8233. size_t SingleVecNumElements = VT.getVectorNumElements();
  8234. size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits();
  8235. size_t NumBlocks = VT.getSizeInBits() / BlockSize;
  8236. // We are looking for masks like
  8237. // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element
  8238. // might be replaced by 'undefined'. BlockIndices will eventually contain
  8239. // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7]
  8240. // for the above examples)
  8241. SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1);
  8242. for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++)
  8243. for (size_t I = 0; I < NumEltsPerBlock; I++) {
  8244. int Elt = M[BlockIndex * NumEltsPerBlock + I];
  8245. if (Elt < 0)
  8246. continue;
  8247. // For now we don't support shuffles that use the second operand
  8248. if ((unsigned)Elt >= SingleVecNumElements)
  8249. return false;
  8250. if (BlockElts[I] < 0)
  8251. BlockElts[I] = Elt;
  8252. else if (BlockElts[I] != Elt)
  8253. return false;
  8254. }
  8255. // We found a candidate block (possibly with some undefs). It must be a
  8256. // sequence of consecutive integers starting with a value divisible by
  8257. // NumEltsPerBlock with some values possibly replaced by undef-s.
  8258. // Find first non-undef element
  8259. auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; });
  8260. assert(FirstRealEltIter != BlockElts.end() &&
  8261. "Shuffle with all-undefs must have been caught by previous cases, "
  8262. "e.g. isSplat()");
  8263. if (FirstRealEltIter == BlockElts.end()) {
  8264. DupLaneOp = 0;
  8265. return true;
  8266. }
  8267. // Index of FirstRealElt in BlockElts
  8268. size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin();
  8269. if ((unsigned)*FirstRealEltIter < FirstRealIndex)
  8270. return false;
  8271. // BlockElts[0] must have the following value if it isn't undef:
  8272. size_t Elt0 = *FirstRealEltIter - FirstRealIndex;
  8273. // Check the first element
  8274. if (Elt0 % NumEltsPerBlock != 0)
  8275. return false;
  8276. // Check that the sequence indeed consists of consecutive integers (modulo
  8277. // undefs)
  8278. for (size_t I = 0; I < NumEltsPerBlock; I++)
  8279. if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I)
  8280. return false;
  8281. DupLaneOp = Elt0 / NumEltsPerBlock;
  8282. return true;
  8283. }
  8284. // check if an EXT instruction can handle the shuffle mask when the
  8285. // vector sources of the shuffle are different.
  8286. static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
  8287. unsigned &Imm) {
  8288. // Look for the first non-undef element.
  8289. const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
  8290. // Benefit form APInt to handle overflow when calculating expected element.
  8291. unsigned NumElts = VT.getVectorNumElements();
  8292. unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
  8293. APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
  8294. // The following shuffle indices must be the successive elements after the
  8295. // first real element.
  8296. const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
  8297. [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
  8298. if (FirstWrongElt != M.end())
  8299. return false;
  8300. // The index of an EXT is the first element if it is not UNDEF.
  8301. // Watch out for the beginning UNDEFs. The EXT index should be the expected
  8302. // value of the first element. E.g.
  8303. // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
  8304. // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
  8305. // ExpectedElt is the last mask index plus 1.
  8306. Imm = ExpectedElt.getZExtValue();
  8307. // There are two difference cases requiring to reverse input vectors.
  8308. // For example, for vector <4 x i32> we have the following cases,
  8309. // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
  8310. // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
  8311. // For both cases, we finally use mask <5, 6, 7, 0>, which requires
  8312. // to reverse two input vectors.
  8313. if (Imm < NumElts)
  8314. ReverseEXT = true;
  8315. else
  8316. Imm -= NumElts;
  8317. return true;
  8318. }
  8319. /// isREVMask - Check if a vector shuffle corresponds to a REV
  8320. /// instruction with the specified blocksize. (The order of the elements
  8321. /// within each block of the vector is reversed.)
  8322. static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
  8323. assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
  8324. "Only possible block sizes for REV are: 16, 32, 64");
  8325. unsigned EltSz = VT.getScalarSizeInBits();
  8326. if (EltSz == 64)
  8327. return false;
  8328. unsigned NumElts = VT.getVectorNumElements();
  8329. unsigned BlockElts = M[0] + 1;
  8330. // If the first shuffle index is UNDEF, be optimistic.
  8331. if (M[0] < 0)
  8332. BlockElts = BlockSize / EltSz;
  8333. if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
  8334. return false;
  8335. for (unsigned i = 0; i < NumElts; ++i) {
  8336. if (M[i] < 0)
  8337. continue; // ignore UNDEF indices
  8338. if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
  8339. return false;
  8340. }
  8341. return true;
  8342. }
  8343. static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
  8344. unsigned NumElts = VT.getVectorNumElements();
  8345. if (NumElts % 2 != 0)
  8346. return false;
  8347. WhichResult = (M[0] == 0 ? 0 : 1);
  8348. unsigned Idx = WhichResult * NumElts / 2;
  8349. for (unsigned i = 0; i != NumElts; i += 2) {
  8350. if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
  8351. (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
  8352. return false;
  8353. Idx += 1;
  8354. }
  8355. return true;
  8356. }
  8357. static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
  8358. unsigned NumElts = VT.getVectorNumElements();
  8359. WhichResult = (M[0] == 0 ? 0 : 1);
  8360. for (unsigned i = 0; i != NumElts; ++i) {
  8361. if (M[i] < 0)
  8362. continue; // ignore UNDEF indices
  8363. if ((unsigned)M[i] != 2 * i + WhichResult)
  8364. return false;
  8365. }
  8366. return true;
  8367. }
  8368. static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
  8369. unsigned NumElts = VT.getVectorNumElements();
  8370. if (NumElts % 2 != 0)
  8371. return false;
  8372. WhichResult = (M[0] == 0 ? 0 : 1);
  8373. for (unsigned i = 0; i < NumElts; i += 2) {
  8374. if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
  8375. (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
  8376. return false;
  8377. }
  8378. return true;
  8379. }
  8380. /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
  8381. /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
  8382. /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
  8383. static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
  8384. unsigned NumElts = VT.getVectorNumElements();
  8385. if (NumElts % 2 != 0)
  8386. return false;
  8387. WhichResult = (M[0] == 0 ? 0 : 1);
  8388. unsigned Idx = WhichResult * NumElts / 2;
  8389. for (unsigned i = 0; i != NumElts; i += 2) {
  8390. if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
  8391. (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
  8392. return false;
  8393. Idx += 1;
  8394. }
  8395. return true;
  8396. }
  8397. /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
  8398. /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
  8399. /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
  8400. static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
  8401. unsigned Half = VT.getVectorNumElements() / 2;
  8402. WhichResult = (M[0] == 0 ? 0 : 1);
  8403. for (unsigned j = 0; j != 2; ++j) {
  8404. unsigned Idx = WhichResult;
  8405. for (unsigned i = 0; i != Half; ++i) {
  8406. int MIdx = M[i + j * Half];
  8407. if (MIdx >= 0 && (unsigned)MIdx != Idx)
  8408. return false;
  8409. Idx += 2;
  8410. }
  8411. }
  8412. return true;
  8413. }
  8414. /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
  8415. /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
  8416. /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
  8417. static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
  8418. unsigned NumElts = VT.getVectorNumElements();
  8419. if (NumElts % 2 != 0)
  8420. return false;
  8421. WhichResult = (M[0] == 0 ? 0 : 1);
  8422. for (unsigned i = 0; i < NumElts; i += 2) {
  8423. if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
  8424. (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
  8425. return false;
  8426. }
  8427. return true;
  8428. }
  8429. static bool isINSMask(ArrayRef<int> M, int NumInputElements,
  8430. bool &DstIsLeft, int &Anomaly) {
  8431. if (M.size() != static_cast<size_t>(NumInputElements))
  8432. return false;
  8433. int NumLHSMatch = 0, NumRHSMatch = 0;
  8434. int LastLHSMismatch = -1, LastRHSMismatch = -1;
  8435. for (int i = 0; i < NumInputElements; ++i) {
  8436. if (M[i] == -1) {
  8437. ++NumLHSMatch;
  8438. ++NumRHSMatch;
  8439. continue;
  8440. }
  8441. if (M[i] == i)
  8442. ++NumLHSMatch;
  8443. else
  8444. LastLHSMismatch = i;
  8445. if (M[i] == i + NumInputElements)
  8446. ++NumRHSMatch;
  8447. else
  8448. LastRHSMismatch = i;
  8449. }
  8450. if (NumLHSMatch == NumInputElements - 1) {
  8451. DstIsLeft = true;
  8452. Anomaly = LastLHSMismatch;
  8453. return true;
  8454. } else if (NumRHSMatch == NumInputElements - 1) {
  8455. DstIsLeft = false;
  8456. Anomaly = LastRHSMismatch;
  8457. return true;
  8458. }
  8459. return false;
  8460. }
  8461. static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
  8462. if (VT.getSizeInBits() != 128)
  8463. return false;
  8464. unsigned NumElts = VT.getVectorNumElements();
  8465. for (int I = 0, E = NumElts / 2; I != E; I++) {
  8466. if (Mask[I] != I)
  8467. return false;
  8468. }
  8469. int Offset = NumElts / 2;
  8470. for (int I = NumElts / 2, E = NumElts; I != E; I++) {
  8471. if (Mask[I] != I + SplitLHS * Offset)
  8472. return false;
  8473. }
  8474. return true;
  8475. }
  8476. static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
  8477. SDLoc DL(Op);
  8478. EVT VT = Op.getValueType();
  8479. SDValue V0 = Op.getOperand(0);
  8480. SDValue V1 = Op.getOperand(1);
  8481. ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
  8482. if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
  8483. VT.getVectorElementType() != V1.getValueType().getVectorElementType())
  8484. return SDValue();
  8485. bool SplitV0 = V0.getValueSizeInBits() == 128;
  8486. if (!isConcatMask(Mask, VT, SplitV0))
  8487. return SDValue();
  8488. EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
  8489. if (SplitV0) {
  8490. V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
  8491. DAG.getConstant(0, DL, MVT::i64));
  8492. }
  8493. if (V1.getValueSizeInBits() == 128) {
  8494. V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
  8495. DAG.getConstant(0, DL, MVT::i64));
  8496. }
  8497. return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
  8498. }
  8499. /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
  8500. /// the specified operations to build the shuffle.
  8501. static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
  8502. SDValue RHS, SelectionDAG &DAG,
  8503. const SDLoc &dl) {
  8504. unsigned OpNum = (PFEntry >> 26) & 0x0F;
  8505. unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
  8506. unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
  8507. enum {
  8508. OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
  8509. OP_VREV,
  8510. OP_VDUP0,
  8511. OP_VDUP1,
  8512. OP_VDUP2,
  8513. OP_VDUP3,
  8514. OP_VEXT1,
  8515. OP_VEXT2,
  8516. OP_VEXT3,
  8517. OP_VUZPL, // VUZP, left result
  8518. OP_VUZPR, // VUZP, right result
  8519. OP_VZIPL, // VZIP, left result
  8520. OP_VZIPR, // VZIP, right result
  8521. OP_VTRNL, // VTRN, left result
  8522. OP_VTRNR // VTRN, right result
  8523. };
  8524. if (OpNum == OP_COPY) {
  8525. if (LHSID == (1 * 9 + 2) * 9 + 3)
  8526. return LHS;
  8527. assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
  8528. return RHS;
  8529. }
  8530. SDValue OpLHS, OpRHS;
  8531. OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
  8532. OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
  8533. EVT VT = OpLHS.getValueType();
  8534. switch (OpNum) {
  8535. default:
  8536. llvm_unreachable("Unknown shuffle opcode!");
  8537. case OP_VREV:
  8538. // VREV divides the vector in half and swaps within the half.
  8539. if (VT.getVectorElementType() == MVT::i32 ||
  8540. VT.getVectorElementType() == MVT::f32)
  8541. return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
  8542. // vrev <4 x i16> -> REV32
  8543. if (VT.getVectorElementType() == MVT::i16 ||
  8544. VT.getVectorElementType() == MVT::f16 ||
  8545. VT.getVectorElementType() == MVT::bf16)
  8546. return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
  8547. // vrev <4 x i8> -> REV16
  8548. assert(VT.getVectorElementType() == MVT::i8);
  8549. return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
  8550. case OP_VDUP0:
  8551. case OP_VDUP1:
  8552. case OP_VDUP2:
  8553. case OP_VDUP3: {
  8554. EVT EltTy = VT.getVectorElementType();
  8555. unsigned Opcode;
  8556. if (EltTy == MVT::i8)
  8557. Opcode = AArch64ISD::DUPLANE8;
  8558. else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
  8559. Opcode = AArch64ISD::DUPLANE16;
  8560. else if (EltTy == MVT::i32 || EltTy == MVT::f32)
  8561. Opcode = AArch64ISD::DUPLANE32;
  8562. else if (EltTy == MVT::i64 || EltTy == MVT::f64)
  8563. Opcode = AArch64ISD::DUPLANE64;
  8564. else
  8565. llvm_unreachable("Invalid vector element type?");
  8566. if (VT.getSizeInBits() == 64)
  8567. OpLHS = WidenVector(OpLHS, DAG);
  8568. SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
  8569. return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
  8570. }
  8571. case OP_VEXT1:
  8572. case OP_VEXT2:
  8573. case OP_VEXT3: {
  8574. unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
  8575. return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
  8576. DAG.getConstant(Imm, dl, MVT::i32));
  8577. }
  8578. case OP_VUZPL:
  8579. return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
  8580. OpRHS);
  8581. case OP_VUZPR:
  8582. return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
  8583. OpRHS);
  8584. case OP_VZIPL:
  8585. return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
  8586. OpRHS);
  8587. case OP_VZIPR:
  8588. return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
  8589. OpRHS);
  8590. case OP_VTRNL:
  8591. return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
  8592. OpRHS);
  8593. case OP_VTRNR:
  8594. return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
  8595. OpRHS);
  8596. }
  8597. }
  8598. static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
  8599. SelectionDAG &DAG) {
  8600. // Check to see if we can use the TBL instruction.
  8601. SDValue V1 = Op.getOperand(0);
  8602. SDValue V2 = Op.getOperand(1);
  8603. SDLoc DL(Op);
  8604. EVT EltVT = Op.getValueType().getVectorElementType();
  8605. unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
  8606. SmallVector<SDValue, 8> TBLMask;
  8607. for (int Val : ShuffleMask) {
  8608. for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
  8609. unsigned Offset = Byte + Val * BytesPerElt;
  8610. TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
  8611. }
  8612. }
  8613. MVT IndexVT = MVT::v8i8;
  8614. unsigned IndexLen = 8;
  8615. if (Op.getValueSizeInBits() == 128) {
  8616. IndexVT = MVT::v16i8;
  8617. IndexLen = 16;
  8618. }
  8619. SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
  8620. SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
  8621. SDValue Shuffle;
  8622. if (V2.getNode()->isUndef()) {
  8623. if (IndexLen == 8)
  8624. V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
  8625. Shuffle = DAG.getNode(
  8626. ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
  8627. DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
  8628. DAG.getBuildVector(IndexVT, DL,
  8629. makeArrayRef(TBLMask.data(), IndexLen)));
  8630. } else {
  8631. if (IndexLen == 8) {
  8632. V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
  8633. Shuffle = DAG.getNode(
  8634. ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
  8635. DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
  8636. DAG.getBuildVector(IndexVT, DL,
  8637. makeArrayRef(TBLMask.data(), IndexLen)));
  8638. } else {
  8639. // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
  8640. // cannot currently represent the register constraints on the input
  8641. // table registers.
  8642. // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
  8643. // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
  8644. // IndexLen));
  8645. Shuffle = DAG.getNode(
  8646. ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
  8647. DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
  8648. V2Cst, DAG.getBuildVector(IndexVT, DL,
  8649. makeArrayRef(TBLMask.data(), IndexLen)));
  8650. }
  8651. }
  8652. return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
  8653. }
  8654. static unsigned getDUPLANEOp(EVT EltType) {
  8655. if (EltType == MVT::i8)
  8656. return AArch64ISD::DUPLANE8;
  8657. if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
  8658. return AArch64ISD::DUPLANE16;
  8659. if (EltType == MVT::i32 || EltType == MVT::f32)
  8660. return AArch64ISD::DUPLANE32;
  8661. if (EltType == MVT::i64 || EltType == MVT::f64)
  8662. return AArch64ISD::DUPLANE64;
  8663. llvm_unreachable("Invalid vector element type?");
  8664. }
  8665. static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT,
  8666. unsigned Opcode, SelectionDAG &DAG) {
  8667. // Try to eliminate a bitcasted extract subvector before a DUPLANE.
  8668. auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
  8669. // Match: dup (bitcast (extract_subv X, C)), LaneC
  8670. if (BitCast.getOpcode() != ISD::BITCAST ||
  8671. BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
  8672. return false;
  8673. // The extract index must align in the destination type. That may not
  8674. // happen if the bitcast is from narrow to wide type.
  8675. SDValue Extract = BitCast.getOperand(0);
  8676. unsigned ExtIdx = Extract.getConstantOperandVal(1);
  8677. unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
  8678. unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
  8679. unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
  8680. if (ExtIdxInBits % CastedEltBitWidth != 0)
  8681. return false;
  8682. // Can't handle cases where vector size is not 128-bit
  8683. if (!Extract.getOperand(0).getValueType().is128BitVector())
  8684. return false;
  8685. // Update the lane value by offsetting with the scaled extract index.
  8686. LaneC += ExtIdxInBits / CastedEltBitWidth;
  8687. // Determine the casted vector type of the wide vector input.
  8688. // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
  8689. // Examples:
  8690. // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
  8691. // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
  8692. unsigned SrcVecNumElts =
  8693. Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
  8694. CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
  8695. SrcVecNumElts);
  8696. return true;
  8697. };
  8698. MVT CastVT;
  8699. if (getScaledOffsetDup(V, Lane, CastVT)) {
  8700. V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0));
  8701. } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  8702. V.getOperand(0).getValueType().is128BitVector()) {
  8703. // The lane is incremented by the index of the extract.
  8704. // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
  8705. Lane += V.getConstantOperandVal(1);
  8706. V = V.getOperand(0);
  8707. } else if (V.getOpcode() == ISD::CONCAT_VECTORS) {
  8708. // The lane is decremented if we are splatting from the 2nd operand.
  8709. // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
  8710. unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
  8711. Lane -= Idx * VT.getVectorNumElements() / 2;
  8712. V = WidenVector(V.getOperand(Idx), DAG);
  8713. } else if (VT.getSizeInBits() == 64) {
  8714. // Widen the operand to 128-bit register with undef.
  8715. V = WidenVector(V, DAG);
  8716. }
  8717. return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64));
  8718. }
  8719. // Return true if we can get a new shuffle mask by checking the parameter mask
  8720. // array to test whether every two adjacent mask values are continuous and
  8721. // starting from an even number.
  8722. static bool isWideTypeMask(ArrayRef<int> M, EVT VT,
  8723. SmallVectorImpl<int> &NewMask) {
  8724. unsigned NumElts = VT.getVectorNumElements();
  8725. if (NumElts % 2 != 0)
  8726. return false;
  8727. NewMask.clear();
  8728. for (unsigned i = 0; i < NumElts; i += 2) {
  8729. int M0 = M[i];
  8730. int M1 = M[i + 1];
  8731. // If both elements are undef, new mask is undef too.
  8732. if (M0 == -1 && M1 == -1) {
  8733. NewMask.push_back(-1);
  8734. continue;
  8735. }
  8736. if (M0 == -1 && M1 != -1 && (M1 % 2) == 1) {
  8737. NewMask.push_back(M1 / 2);
  8738. continue;
  8739. }
  8740. if (M0 != -1 && (M0 % 2) == 0 && ((M0 + 1) == M1 || M1 == -1)) {
  8741. NewMask.push_back(M0 / 2);
  8742. continue;
  8743. }
  8744. NewMask.clear();
  8745. return false;
  8746. }
  8747. assert(NewMask.size() == NumElts / 2 && "Incorrect size for mask!");
  8748. return true;
  8749. }
  8750. // Try to widen element type to get a new mask value for a better permutation
  8751. // sequence, so that we can use NEON shuffle instructions, such as zip1/2,
  8752. // UZP1/2, TRN1/2, REV, INS, etc.
  8753. // For example:
  8754. // shufflevector <4 x i32> %a, <4 x i32> %b,
  8755. // <4 x i32> <i32 6, i32 7, i32 2, i32 3>
  8756. // is equivalent to:
  8757. // shufflevector <2 x i64> %a, <2 x i64> %b, <2 x i32> <i32 3, i32 1>
  8758. // Finally, we can get:
  8759. // mov v0.d[0], v1.d[1]
  8760. static SDValue tryWidenMaskForShuffle(SDValue Op, SelectionDAG &DAG) {
  8761. SDLoc DL(Op);
  8762. EVT VT = Op.getValueType();
  8763. EVT ScalarVT = VT.getVectorElementType();
  8764. unsigned ElementSize = ScalarVT.getFixedSizeInBits();
  8765. SDValue V0 = Op.getOperand(0);
  8766. SDValue V1 = Op.getOperand(1);
  8767. ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
  8768. // If combining adjacent elements, like two i16's -> i32, two i32's -> i64 ...
  8769. // We need to make sure the wider element type is legal. Thus, ElementSize
  8770. // should be not larger than 32 bits, and i1 type should also be excluded.
  8771. if (ElementSize > 32 || ElementSize == 1)
  8772. return SDValue();
  8773. SmallVector<int, 8> NewMask;
  8774. if (isWideTypeMask(Mask, VT, NewMask)) {
  8775. MVT NewEltVT = VT.isFloatingPoint()
  8776. ? MVT::getFloatingPointVT(ElementSize * 2)
  8777. : MVT::getIntegerVT(ElementSize * 2);
  8778. MVT NewVT = MVT::getVectorVT(NewEltVT, VT.getVectorNumElements() / 2);
  8779. if (DAG.getTargetLoweringInfo().isTypeLegal(NewVT)) {
  8780. V0 = DAG.getBitcast(NewVT, V0);
  8781. V1 = DAG.getBitcast(NewVT, V1);
  8782. return DAG.getBitcast(VT,
  8783. DAG.getVectorShuffle(NewVT, DL, V0, V1, NewMask));
  8784. }
  8785. }
  8786. return SDValue();
  8787. }
  8788. SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
  8789. SelectionDAG &DAG) const {
  8790. SDLoc dl(Op);
  8791. EVT VT = Op.getValueType();
  8792. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
  8793. if (useSVEForFixedLengthVectorVT(VT))
  8794. return LowerFixedLengthVECTOR_SHUFFLEToSVE(Op, DAG);
  8795. // Convert shuffles that are directly supported on NEON to target-specific
  8796. // DAG nodes, instead of keeping them as shuffles and matching them again
  8797. // during code selection. This is more efficient and avoids the possibility
  8798. // of inconsistencies between legalization and selection.
  8799. ArrayRef<int> ShuffleMask = SVN->getMask();
  8800. SDValue V1 = Op.getOperand(0);
  8801. SDValue V2 = Op.getOperand(1);
  8802. assert(V1.getValueType() == VT && "Unexpected VECTOR_SHUFFLE type!");
  8803. assert(ShuffleMask.size() == VT.getVectorNumElements() &&
  8804. "Unexpected VECTOR_SHUFFLE mask size!");
  8805. if (SVN->isSplat()) {
  8806. int Lane = SVN->getSplatIndex();
  8807. // If this is undef splat, generate it via "just" vdup, if possible.
  8808. if (Lane == -1)
  8809. Lane = 0;
  8810. if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
  8811. return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
  8812. V1.getOperand(0));
  8813. // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
  8814. // constant. If so, we can just reference the lane's definition directly.
  8815. if (V1.getOpcode() == ISD::BUILD_VECTOR &&
  8816. !isa<ConstantSDNode>(V1.getOperand(Lane)))
  8817. return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
  8818. // Otherwise, duplicate from the lane of the input vector.
  8819. unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
  8820. return constructDup(V1, Lane, dl, VT, Opcode, DAG);
  8821. }
  8822. // Check if the mask matches a DUP for a wider element
  8823. for (unsigned LaneSize : {64U, 32U, 16U}) {
  8824. unsigned Lane = 0;
  8825. if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) {
  8826. unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64
  8827. : LaneSize == 32 ? AArch64ISD::DUPLANE32
  8828. : AArch64ISD::DUPLANE16;
  8829. // Cast V1 to an integer vector with required lane size
  8830. MVT NewEltTy = MVT::getIntegerVT(LaneSize);
  8831. unsigned NewEltCount = VT.getSizeInBits() / LaneSize;
  8832. MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount);
  8833. V1 = DAG.getBitcast(NewVecTy, V1);
  8834. // Constuct the DUP instruction
  8835. V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG);
  8836. // Cast back to the original type
  8837. return DAG.getBitcast(VT, V1);
  8838. }
  8839. }
  8840. if (isREVMask(ShuffleMask, VT, 64))
  8841. return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
  8842. if (isREVMask(ShuffleMask, VT, 32))
  8843. return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
  8844. if (isREVMask(ShuffleMask, VT, 16))
  8845. return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
  8846. if (((VT.getVectorNumElements() == 8 && VT.getScalarSizeInBits() == 16) ||
  8847. (VT.getVectorNumElements() == 16 && VT.getScalarSizeInBits() == 8)) &&
  8848. ShuffleVectorInst::isReverseMask(ShuffleMask)) {
  8849. SDValue Rev = DAG.getNode(AArch64ISD::REV64, dl, VT, V1);
  8850. return DAG.getNode(AArch64ISD::EXT, dl, VT, Rev, Rev,
  8851. DAG.getConstant(8, dl, MVT::i32));
  8852. }
  8853. bool ReverseEXT = false;
  8854. unsigned Imm;
  8855. if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
  8856. if (ReverseEXT)
  8857. std::swap(V1, V2);
  8858. Imm *= getExtFactor(V1);
  8859. return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
  8860. DAG.getConstant(Imm, dl, MVT::i32));
  8861. } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
  8862. Imm *= getExtFactor(V1);
  8863. return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
  8864. DAG.getConstant(Imm, dl, MVT::i32));
  8865. }
  8866. unsigned WhichResult;
  8867. if (isZIPMask(ShuffleMask, VT, WhichResult)) {
  8868. unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
  8869. return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
  8870. }
  8871. if (isUZPMask(ShuffleMask, VT, WhichResult)) {
  8872. unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
  8873. return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
  8874. }
  8875. if (isTRNMask(ShuffleMask, VT, WhichResult)) {
  8876. unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
  8877. return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
  8878. }
  8879. if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
  8880. unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
  8881. return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
  8882. }
  8883. if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
  8884. unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
  8885. return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
  8886. }
  8887. if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
  8888. unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
  8889. return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
  8890. }
  8891. if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
  8892. return Concat;
  8893. bool DstIsLeft;
  8894. int Anomaly;
  8895. int NumInputElements = V1.getValueType().getVectorNumElements();
  8896. if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
  8897. SDValue DstVec = DstIsLeft ? V1 : V2;
  8898. SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
  8899. SDValue SrcVec = V1;
  8900. int SrcLane = ShuffleMask[Anomaly];
  8901. if (SrcLane >= NumInputElements) {
  8902. SrcVec = V2;
  8903. SrcLane -= VT.getVectorNumElements();
  8904. }
  8905. SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
  8906. EVT ScalarVT = VT.getVectorElementType();
  8907. if (ScalarVT.getFixedSizeInBits() < 32 && ScalarVT.isInteger())
  8908. ScalarVT = MVT::i32;
  8909. return DAG.getNode(
  8910. ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
  8911. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
  8912. DstLaneV);
  8913. }
  8914. if (SDValue NewSD = tryWidenMaskForShuffle(Op, DAG))
  8915. return NewSD;
  8916. // If the shuffle is not directly supported and it has 4 elements, use
  8917. // the PerfectShuffle-generated table to synthesize it from other shuffles.
  8918. unsigned NumElts = VT.getVectorNumElements();
  8919. if (NumElts == 4) {
  8920. unsigned PFIndexes[4];
  8921. for (unsigned i = 0; i != 4; ++i) {
  8922. if (ShuffleMask[i] < 0)
  8923. PFIndexes[i] = 8;
  8924. else
  8925. PFIndexes[i] = ShuffleMask[i];
  8926. }
  8927. // Compute the index in the perfect shuffle table.
  8928. unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
  8929. PFIndexes[2] * 9 + PFIndexes[3];
  8930. unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
  8931. unsigned Cost = (PFEntry >> 30);
  8932. if (Cost <= 4)
  8933. return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
  8934. }
  8935. return GenerateTBL(Op, ShuffleMask, DAG);
  8936. }
  8937. SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
  8938. SelectionDAG &DAG) const {
  8939. SDLoc dl(Op);
  8940. EVT VT = Op.getValueType();
  8941. EVT ElemVT = VT.getScalarType();
  8942. SDValue SplatVal = Op.getOperand(0);
  8943. if (useSVEForFixedLengthVectorVT(VT))
  8944. return LowerToScalableOp(Op, DAG);
  8945. // Extend input splat value where needed to fit into a GPR (32b or 64b only)
  8946. // FPRs don't have this restriction.
  8947. switch (ElemVT.getSimpleVT().SimpleTy) {
  8948. case MVT::i1: {
  8949. // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
  8950. // lowering code.
  8951. if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
  8952. // We can hande the zero case during isel.
  8953. if (ConstVal->isZero())
  8954. return Op;
  8955. if (ConstVal->isOne())
  8956. return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
  8957. }
  8958. // The general case of i1. There isn't any natural way to do this,
  8959. // so we use some trickery with whilelo.
  8960. SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
  8961. SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
  8962. DAG.getValueType(MVT::i1));
  8963. SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
  8964. MVT::i64);
  8965. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
  8966. DAG.getConstant(0, dl, MVT::i64), SplatVal);
  8967. }
  8968. case MVT::i8:
  8969. case MVT::i16:
  8970. case MVT::i32:
  8971. SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
  8972. break;
  8973. case MVT::i64:
  8974. SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
  8975. break;
  8976. case MVT::f16:
  8977. case MVT::bf16:
  8978. case MVT::f32:
  8979. case MVT::f64:
  8980. // Fine as is
  8981. break;
  8982. default:
  8983. report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
  8984. }
  8985. return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
  8986. }
  8987. SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
  8988. SelectionDAG &DAG) const {
  8989. SDLoc DL(Op);
  8990. EVT VT = Op.getValueType();
  8991. if (!isTypeLegal(VT) || !VT.isScalableVector())
  8992. return SDValue();
  8993. // Current lowering only supports the SVE-ACLE types.
  8994. if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
  8995. return SDValue();
  8996. // The DUPQ operation is indepedent of element type so normalise to i64s.
  8997. SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
  8998. SDValue Idx128 = Op.getOperand(2);
  8999. // DUPQ can be used when idx is in range.
  9000. auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
  9001. if (CIdx && (CIdx->getZExtValue() <= 3)) {
  9002. SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
  9003. SDNode *DUPQ =
  9004. DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
  9005. return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
  9006. }
  9007. // The ACLE says this must produce the same result as:
  9008. // svtbl(data, svadd_x(svptrue_b64(),
  9009. // svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
  9010. // index * 2))
  9011. SDValue One = DAG.getConstant(1, DL, MVT::i64);
  9012. SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
  9013. // create the vector 0,1,0,1,...
  9014. SDValue SV = DAG.getStepVector(DL, MVT::nxv2i64);
  9015. SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
  9016. // create the vector idx64,idx64+1,idx64,idx64+1,...
  9017. SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
  9018. SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
  9019. SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
  9020. // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
  9021. SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
  9022. return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
  9023. }
  9024. static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
  9025. APInt &UndefBits) {
  9026. EVT VT = BVN->getValueType(0);
  9027. APInt SplatBits, SplatUndef;
  9028. unsigned SplatBitSize;
  9029. bool HasAnyUndefs;
  9030. if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
  9031. unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
  9032. for (unsigned i = 0; i < NumSplats; ++i) {
  9033. CnstBits <<= SplatBitSize;
  9034. UndefBits <<= SplatBitSize;
  9035. CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
  9036. UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
  9037. }
  9038. return true;
  9039. }
  9040. return false;
  9041. }
  9042. // Try 64-bit splatted SIMD immediate.
  9043. static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
  9044. const APInt &Bits) {
  9045. if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
  9046. uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
  9047. EVT VT = Op.getValueType();
  9048. MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
  9049. if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
  9050. Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
  9051. SDLoc dl(Op);
  9052. SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
  9053. DAG.getConstant(Value, dl, MVT::i32));
  9054. return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
  9055. }
  9056. }
  9057. return SDValue();
  9058. }
  9059. // Try 32-bit splatted SIMD immediate.
  9060. static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
  9061. const APInt &Bits,
  9062. const SDValue *LHS = nullptr) {
  9063. if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
  9064. uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
  9065. EVT VT = Op.getValueType();
  9066. MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
  9067. bool isAdvSIMDModImm = false;
  9068. uint64_t Shift;
  9069. if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
  9070. Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
  9071. Shift = 0;
  9072. }
  9073. else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
  9074. Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
  9075. Shift = 8;
  9076. }
  9077. else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
  9078. Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
  9079. Shift = 16;
  9080. }
  9081. else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
  9082. Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
  9083. Shift = 24;
  9084. }
  9085. if (isAdvSIMDModImm) {
  9086. SDLoc dl(Op);
  9087. SDValue Mov;
  9088. if (LHS)
  9089. Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
  9090. DAG.getConstant(Value, dl, MVT::i32),
  9091. DAG.getConstant(Shift, dl, MVT::i32));
  9092. else
  9093. Mov = DAG.getNode(NewOp, dl, MovTy,
  9094. DAG.getConstant(Value, dl, MVT::i32),
  9095. DAG.getConstant(Shift, dl, MVT::i32));
  9096. return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
  9097. }
  9098. }
  9099. return SDValue();
  9100. }
  9101. // Try 16-bit splatted SIMD immediate.
  9102. static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
  9103. const APInt &Bits,
  9104. const SDValue *LHS = nullptr) {
  9105. if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
  9106. uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
  9107. EVT VT = Op.getValueType();
  9108. MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
  9109. bool isAdvSIMDModImm = false;
  9110. uint64_t Shift;
  9111. if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
  9112. Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
  9113. Shift = 0;
  9114. }
  9115. else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
  9116. Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
  9117. Shift = 8;
  9118. }
  9119. if (isAdvSIMDModImm) {
  9120. SDLoc dl(Op);
  9121. SDValue Mov;
  9122. if (LHS)
  9123. Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
  9124. DAG.getConstant(Value, dl, MVT::i32),
  9125. DAG.getConstant(Shift, dl, MVT::i32));
  9126. else
  9127. Mov = DAG.getNode(NewOp, dl, MovTy,
  9128. DAG.getConstant(Value, dl, MVT::i32),
  9129. DAG.getConstant(Shift, dl, MVT::i32));
  9130. return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
  9131. }
  9132. }
  9133. return SDValue();
  9134. }
  9135. // Try 32-bit splatted SIMD immediate with shifted ones.
  9136. static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
  9137. SelectionDAG &DAG, const APInt &Bits) {
  9138. if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
  9139. uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
  9140. EVT VT = Op.getValueType();
  9141. MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
  9142. bool isAdvSIMDModImm = false;
  9143. uint64_t Shift;
  9144. if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
  9145. Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
  9146. Shift = 264;
  9147. }
  9148. else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
  9149. Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
  9150. Shift = 272;
  9151. }
  9152. if (isAdvSIMDModImm) {
  9153. SDLoc dl(Op);
  9154. SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
  9155. DAG.getConstant(Value, dl, MVT::i32),
  9156. DAG.getConstant(Shift, dl, MVT::i32));
  9157. return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
  9158. }
  9159. }
  9160. return SDValue();
  9161. }
  9162. // Try 8-bit splatted SIMD immediate.
  9163. static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
  9164. const APInt &Bits) {
  9165. if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
  9166. uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
  9167. EVT VT = Op.getValueType();
  9168. MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
  9169. if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
  9170. Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
  9171. SDLoc dl(Op);
  9172. SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
  9173. DAG.getConstant(Value, dl, MVT::i32));
  9174. return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
  9175. }
  9176. }
  9177. return SDValue();
  9178. }
  9179. // Try FP splatted SIMD immediate.
  9180. static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
  9181. const APInt &Bits) {
  9182. if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
  9183. uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
  9184. EVT VT = Op.getValueType();
  9185. bool isWide = (VT.getSizeInBits() == 128);
  9186. MVT MovTy;
  9187. bool isAdvSIMDModImm = false;
  9188. if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
  9189. Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
  9190. MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
  9191. }
  9192. else if (isWide &&
  9193. (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
  9194. Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
  9195. MovTy = MVT::v2f64;
  9196. }
  9197. if (isAdvSIMDModImm) {
  9198. SDLoc dl(Op);
  9199. SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
  9200. DAG.getConstant(Value, dl, MVT::i32));
  9201. return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
  9202. }
  9203. }
  9204. return SDValue();
  9205. }
  9206. // Specialized code to quickly find if PotentialBVec is a BuildVector that
  9207. // consists of only the same constant int value, returned in reference arg
  9208. // ConstVal
  9209. static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
  9210. uint64_t &ConstVal) {
  9211. BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
  9212. if (!Bvec)
  9213. return false;
  9214. ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
  9215. if (!FirstElt)
  9216. return false;
  9217. EVT VT = Bvec->getValueType(0);
  9218. unsigned NumElts = VT.getVectorNumElements();
  9219. for (unsigned i = 1; i < NumElts; ++i)
  9220. if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
  9221. return false;
  9222. ConstVal = FirstElt->getZExtValue();
  9223. return true;
  9224. }
  9225. static unsigned getIntrinsicID(const SDNode *N) {
  9226. unsigned Opcode = N->getOpcode();
  9227. switch (Opcode) {
  9228. default:
  9229. return Intrinsic::not_intrinsic;
  9230. case ISD::INTRINSIC_WO_CHAIN: {
  9231. unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
  9232. if (IID < Intrinsic::num_intrinsics)
  9233. return IID;
  9234. return Intrinsic::not_intrinsic;
  9235. }
  9236. }
  9237. }
  9238. // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
  9239. // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
  9240. // BUILD_VECTORs with constant element C1, C2 is a constant, and:
  9241. // - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
  9242. // - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
  9243. // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
  9244. static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
  9245. EVT VT = N->getValueType(0);
  9246. if (!VT.isVector())
  9247. return SDValue();
  9248. SDLoc DL(N);
  9249. SDValue And;
  9250. SDValue Shift;
  9251. SDValue FirstOp = N->getOperand(0);
  9252. unsigned FirstOpc = FirstOp.getOpcode();
  9253. SDValue SecondOp = N->getOperand(1);
  9254. unsigned SecondOpc = SecondOp.getOpcode();
  9255. // Is one of the operands an AND or a BICi? The AND may have been optimised to
  9256. // a BICi in order to use an immediate instead of a register.
  9257. // Is the other operand an shl or lshr? This will have been turned into:
  9258. // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
  9259. if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
  9260. (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
  9261. And = FirstOp;
  9262. Shift = SecondOp;
  9263. } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
  9264. (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
  9265. And = SecondOp;
  9266. Shift = FirstOp;
  9267. } else
  9268. return SDValue();
  9269. bool IsAnd = And.getOpcode() == ISD::AND;
  9270. bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
  9271. // Is the shift amount constant?
  9272. ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
  9273. if (!C2node)
  9274. return SDValue();
  9275. uint64_t C1;
  9276. if (IsAnd) {
  9277. // Is the and mask vector all constant?
  9278. if (!isAllConstantBuildVector(And.getOperand(1), C1))
  9279. return SDValue();
  9280. } else {
  9281. // Reconstruct the corresponding AND immediate from the two BICi immediates.
  9282. ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
  9283. ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
  9284. assert(C1nodeImm && C1nodeShift);
  9285. C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
  9286. }
  9287. // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
  9288. // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
  9289. // how much one can shift elements of a particular size?
  9290. uint64_t C2 = C2node->getZExtValue();
  9291. unsigned ElemSizeInBits = VT.getScalarSizeInBits();
  9292. if (C2 > ElemSizeInBits)
  9293. return SDValue();
  9294. APInt C1AsAPInt(ElemSizeInBits, C1);
  9295. APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
  9296. : APInt::getLowBitsSet(ElemSizeInBits, C2);
  9297. if (C1AsAPInt != RequiredC1)
  9298. return SDValue();
  9299. SDValue X = And.getOperand(0);
  9300. SDValue Y = Shift.getOperand(0);
  9301. unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
  9302. SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
  9303. LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
  9304. LLVM_DEBUG(N->dump(&DAG));
  9305. LLVM_DEBUG(dbgs() << "into: \n");
  9306. LLVM_DEBUG(ResultSLI->dump(&DAG));
  9307. ++NumShiftInserts;
  9308. return ResultSLI;
  9309. }
  9310. SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
  9311. SelectionDAG &DAG) const {
  9312. if (useSVEForFixedLengthVectorVT(Op.getValueType()))
  9313. return LowerToScalableOp(Op, DAG);
  9314. // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
  9315. if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
  9316. return Res;
  9317. EVT VT = Op.getValueType();
  9318. SDValue LHS = Op.getOperand(0);
  9319. BuildVectorSDNode *BVN =
  9320. dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
  9321. if (!BVN) {
  9322. // OR commutes, so try swapping the operands.
  9323. LHS = Op.getOperand(1);
  9324. BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
  9325. }
  9326. if (!BVN)
  9327. return Op;
  9328. APInt DefBits(VT.getSizeInBits(), 0);
  9329. APInt UndefBits(VT.getSizeInBits(), 0);
  9330. if (resolveBuildVector(BVN, DefBits, UndefBits)) {
  9331. SDValue NewOp;
  9332. if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
  9333. DefBits, &LHS)) ||
  9334. (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
  9335. DefBits, &LHS)))
  9336. return NewOp;
  9337. if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
  9338. UndefBits, &LHS)) ||
  9339. (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
  9340. UndefBits, &LHS)))
  9341. return NewOp;
  9342. }
  9343. // We can always fall back to a non-immediate OR.
  9344. return Op;
  9345. }
  9346. // Normalize the operands of BUILD_VECTOR. The value of constant operands will
  9347. // be truncated to fit element width.
  9348. static SDValue NormalizeBuildVector(SDValue Op,
  9349. SelectionDAG &DAG) {
  9350. assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
  9351. SDLoc dl(Op);
  9352. EVT VT = Op.getValueType();
  9353. EVT EltTy= VT.getVectorElementType();
  9354. if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
  9355. return Op;
  9356. SmallVector<SDValue, 16> Ops;
  9357. for (SDValue Lane : Op->ops()) {
  9358. // For integer vectors, type legalization would have promoted the
  9359. // operands already. Otherwise, if Op is a floating-point splat
  9360. // (with operands cast to integers), then the only possibilities
  9361. // are constants and UNDEFs.
  9362. if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
  9363. APInt LowBits(EltTy.getSizeInBits(),
  9364. CstLane->getZExtValue());
  9365. Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
  9366. } else if (Lane.getNode()->isUndef()) {
  9367. Lane = DAG.getUNDEF(MVT::i32);
  9368. } else {
  9369. assert(Lane.getValueType() == MVT::i32 &&
  9370. "Unexpected BUILD_VECTOR operand type");
  9371. }
  9372. Ops.push_back(Lane);
  9373. }
  9374. return DAG.getBuildVector(VT, dl, Ops);
  9375. }
  9376. static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
  9377. EVT VT = Op.getValueType();
  9378. APInt DefBits(VT.getSizeInBits(), 0);
  9379. APInt UndefBits(VT.getSizeInBits(), 0);
  9380. BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
  9381. if (resolveBuildVector(BVN, DefBits, UndefBits)) {
  9382. SDValue NewOp;
  9383. if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
  9384. (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
  9385. (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
  9386. (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
  9387. (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
  9388. (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
  9389. return NewOp;
  9390. DefBits = ~DefBits;
  9391. if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
  9392. (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
  9393. (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
  9394. return NewOp;
  9395. DefBits = UndefBits;
  9396. if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
  9397. (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
  9398. (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
  9399. (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
  9400. (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
  9401. (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
  9402. return NewOp;
  9403. DefBits = ~UndefBits;
  9404. if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
  9405. (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
  9406. (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
  9407. return NewOp;
  9408. }
  9409. return SDValue();
  9410. }
  9411. SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
  9412. SelectionDAG &DAG) const {
  9413. EVT VT = Op.getValueType();
  9414. // Try to build a simple constant vector.
  9415. Op = NormalizeBuildVector(Op, DAG);
  9416. if (VT.isInteger()) {
  9417. // Certain vector constants, used to express things like logical NOT and
  9418. // arithmetic NEG, are passed through unmodified. This allows special
  9419. // patterns for these operations to match, which will lower these constants
  9420. // to whatever is proven necessary.
  9421. BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
  9422. if (BVN->isConstant())
  9423. if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
  9424. unsigned BitSize = VT.getVectorElementType().getSizeInBits();
  9425. APInt Val(BitSize,
  9426. Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
  9427. if (Val.isZero() || Val.isAllOnes())
  9428. return Op;
  9429. }
  9430. }
  9431. if (SDValue V = ConstantBuildVector(Op, DAG))
  9432. return V;
  9433. // Scan through the operands to find some interesting properties we can
  9434. // exploit:
  9435. // 1) If only one value is used, we can use a DUP, or
  9436. // 2) if only the low element is not undef, we can just insert that, or
  9437. // 3) if only one constant value is used (w/ some non-constant lanes),
  9438. // we can splat the constant value into the whole vector then fill
  9439. // in the non-constant lanes.
  9440. // 4) FIXME: If different constant values are used, but we can intelligently
  9441. // select the values we'll be overwriting for the non-constant
  9442. // lanes such that we can directly materialize the vector
  9443. // some other way (MOVI, e.g.), we can be sneaky.
  9444. // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
  9445. SDLoc dl(Op);
  9446. unsigned NumElts = VT.getVectorNumElements();
  9447. bool isOnlyLowElement = true;
  9448. bool usesOnlyOneValue = true;
  9449. bool usesOnlyOneConstantValue = true;
  9450. bool isConstant = true;
  9451. bool AllLanesExtractElt = true;
  9452. unsigned NumConstantLanes = 0;
  9453. unsigned NumDifferentLanes = 0;
  9454. unsigned NumUndefLanes = 0;
  9455. SDValue Value;
  9456. SDValue ConstantValue;
  9457. for (unsigned i = 0; i < NumElts; ++i) {
  9458. SDValue V = Op.getOperand(i);
  9459. if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
  9460. AllLanesExtractElt = false;
  9461. if (V.isUndef()) {
  9462. ++NumUndefLanes;
  9463. continue;
  9464. }
  9465. if (i > 0)
  9466. isOnlyLowElement = false;
  9467. if (!isIntOrFPConstant(V))
  9468. isConstant = false;
  9469. if (isIntOrFPConstant(V)) {
  9470. ++NumConstantLanes;
  9471. if (!ConstantValue.getNode())
  9472. ConstantValue = V;
  9473. else if (ConstantValue != V)
  9474. usesOnlyOneConstantValue = false;
  9475. }
  9476. if (!Value.getNode())
  9477. Value = V;
  9478. else if (V != Value) {
  9479. usesOnlyOneValue = false;
  9480. ++NumDifferentLanes;
  9481. }
  9482. }
  9483. if (!Value.getNode()) {
  9484. LLVM_DEBUG(
  9485. dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
  9486. return DAG.getUNDEF(VT);
  9487. }
  9488. // Convert BUILD_VECTOR where all elements but the lowest are undef into
  9489. // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
  9490. // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
  9491. if (isOnlyLowElement && !(NumElts == 1 && isIntOrFPConstant(Value))) {
  9492. LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
  9493. "SCALAR_TO_VECTOR node\n");
  9494. return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
  9495. }
  9496. if (AllLanesExtractElt) {
  9497. SDNode *Vector = nullptr;
  9498. bool Even = false;
  9499. bool Odd = false;
  9500. // Check whether the extract elements match the Even pattern <0,2,4,...> or
  9501. // the Odd pattern <1,3,5,...>.
  9502. for (unsigned i = 0; i < NumElts; ++i) {
  9503. SDValue V = Op.getOperand(i);
  9504. const SDNode *N = V.getNode();
  9505. if (!isa<ConstantSDNode>(N->getOperand(1)))
  9506. break;
  9507. SDValue N0 = N->getOperand(0);
  9508. // All elements are extracted from the same vector.
  9509. if (!Vector) {
  9510. Vector = N0.getNode();
  9511. // Check that the type of EXTRACT_VECTOR_ELT matches the type of
  9512. // BUILD_VECTOR.
  9513. if (VT.getVectorElementType() !=
  9514. N0.getValueType().getVectorElementType())
  9515. break;
  9516. } else if (Vector != N0.getNode()) {
  9517. Odd = false;
  9518. Even = false;
  9519. break;
  9520. }
  9521. // Extracted values are either at Even indices <0,2,4,...> or at Odd
  9522. // indices <1,3,5,...>.
  9523. uint64_t Val = N->getConstantOperandVal(1);
  9524. if (Val == 2 * i) {
  9525. Even = true;
  9526. continue;
  9527. }
  9528. if (Val - 1 == 2 * i) {
  9529. Odd = true;
  9530. continue;
  9531. }
  9532. // Something does not match: abort.
  9533. Odd = false;
  9534. Even = false;
  9535. break;
  9536. }
  9537. if (Even || Odd) {
  9538. SDValue LHS =
  9539. DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
  9540. DAG.getConstant(0, dl, MVT::i64));
  9541. SDValue RHS =
  9542. DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
  9543. DAG.getConstant(NumElts, dl, MVT::i64));
  9544. if (Even && !Odd)
  9545. return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
  9546. RHS);
  9547. if (Odd && !Even)
  9548. return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
  9549. RHS);
  9550. }
  9551. }
  9552. // Use DUP for non-constant splats. For f32 constant splats, reduce to
  9553. // i32 and try again.
  9554. if (usesOnlyOneValue) {
  9555. if (!isConstant) {
  9556. if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  9557. Value.getValueType() != VT) {
  9558. LLVM_DEBUG(
  9559. dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
  9560. return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
  9561. }
  9562. // This is actually a DUPLANExx operation, which keeps everything vectory.
  9563. SDValue Lane = Value.getOperand(1);
  9564. Value = Value.getOperand(0);
  9565. if (Value.getValueSizeInBits() == 64) {
  9566. LLVM_DEBUG(
  9567. dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
  9568. "widening it\n");
  9569. Value = WidenVector(Value, DAG);
  9570. }
  9571. unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
  9572. return DAG.getNode(Opcode, dl, VT, Value, Lane);
  9573. }
  9574. if (VT.getVectorElementType().isFloatingPoint()) {
  9575. SmallVector<SDValue, 8> Ops;
  9576. EVT EltTy = VT.getVectorElementType();
  9577. assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
  9578. EltTy == MVT::f64) && "Unsupported floating-point vector type");
  9579. LLVM_DEBUG(
  9580. dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
  9581. "BITCASTS, and try again\n");
  9582. MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
  9583. for (unsigned i = 0; i < NumElts; ++i)
  9584. Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
  9585. EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
  9586. SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
  9587. LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
  9588. Val.dump(););
  9589. Val = LowerBUILD_VECTOR(Val, DAG);
  9590. if (Val.getNode())
  9591. return DAG.getNode(ISD::BITCAST, dl, VT, Val);
  9592. }
  9593. }
  9594. // If we need to insert a small number of different non-constant elements and
  9595. // the vector width is sufficiently large, prefer using DUP with the common
  9596. // value and INSERT_VECTOR_ELT for the different lanes. If DUP is preferred,
  9597. // skip the constant lane handling below.
  9598. bool PreferDUPAndInsert =
  9599. !isConstant && NumDifferentLanes >= 1 &&
  9600. NumDifferentLanes < ((NumElts - NumUndefLanes) / 2) &&
  9601. NumDifferentLanes >= NumConstantLanes;
  9602. // If there was only one constant value used and for more than one lane,
  9603. // start by splatting that value, then replace the non-constant lanes. This
  9604. // is better than the default, which will perform a separate initialization
  9605. // for each lane.
  9606. if (!PreferDUPAndInsert && NumConstantLanes > 0 && usesOnlyOneConstantValue) {
  9607. // Firstly, try to materialize the splat constant.
  9608. SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
  9609. Val = ConstantBuildVector(Vec, DAG);
  9610. if (!Val) {
  9611. // Otherwise, materialize the constant and splat it.
  9612. Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
  9613. DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
  9614. }
  9615. // Now insert the non-constant lanes.
  9616. for (unsigned i = 0; i < NumElts; ++i) {
  9617. SDValue V = Op.getOperand(i);
  9618. SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
  9619. if (!isIntOrFPConstant(V))
  9620. // Note that type legalization likely mucked about with the VT of the
  9621. // source operand, so we may have to convert it here before inserting.
  9622. Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
  9623. }
  9624. return Val;
  9625. }
  9626. // This will generate a load from the constant pool.
  9627. if (isConstant) {
  9628. LLVM_DEBUG(
  9629. dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
  9630. "expansion\n");
  9631. return SDValue();
  9632. }
  9633. // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
  9634. if (NumElts >= 4) {
  9635. if (SDValue shuffle = ReconstructShuffle(Op, DAG))
  9636. return shuffle;
  9637. }
  9638. if (PreferDUPAndInsert) {
  9639. // First, build a constant vector with the common element.
  9640. SmallVector<SDValue, 8> Ops(NumElts, Value);
  9641. SDValue NewVector = LowerBUILD_VECTOR(DAG.getBuildVector(VT, dl, Ops), DAG);
  9642. // Next, insert the elements that do not match the common value.
  9643. for (unsigned I = 0; I < NumElts; ++I)
  9644. if (Op.getOperand(I) != Value)
  9645. NewVector =
  9646. DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, NewVector,
  9647. Op.getOperand(I), DAG.getConstant(I, dl, MVT::i64));
  9648. return NewVector;
  9649. }
  9650. // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
  9651. // know the default expansion would otherwise fall back on something even
  9652. // worse. For a vector with one or two non-undef values, that's
  9653. // scalar_to_vector for the elements followed by a shuffle (provided the
  9654. // shuffle is valid for the target) and materialization element by element
  9655. // on the stack followed by a load for everything else.
  9656. if (!isConstant && !usesOnlyOneValue) {
  9657. LLVM_DEBUG(
  9658. dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
  9659. "of INSERT_VECTOR_ELT\n");
  9660. SDValue Vec = DAG.getUNDEF(VT);
  9661. SDValue Op0 = Op.getOperand(0);
  9662. unsigned i = 0;
  9663. // Use SCALAR_TO_VECTOR for lane zero to
  9664. // a) Avoid a RMW dependency on the full vector register, and
  9665. // b) Allow the register coalescer to fold away the copy if the
  9666. // value is already in an S or D register, and we're forced to emit an
  9667. // INSERT_SUBREG that we can't fold anywhere.
  9668. //
  9669. // We also allow types like i8 and i16 which are illegal scalar but legal
  9670. // vector element types. After type-legalization the inserted value is
  9671. // extended (i32) and it is safe to cast them to the vector type by ignoring
  9672. // the upper bits of the lowest lane (e.g. v8i8, v4i16).
  9673. if (!Op0.isUndef()) {
  9674. LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
  9675. Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
  9676. ++i;
  9677. }
  9678. LLVM_DEBUG(if (i < NumElts) dbgs()
  9679. << "Creating nodes for the other vector elements:\n";);
  9680. for (; i < NumElts; ++i) {
  9681. SDValue V = Op.getOperand(i);
  9682. if (V.isUndef())
  9683. continue;
  9684. SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
  9685. Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
  9686. }
  9687. return Vec;
  9688. }
  9689. LLVM_DEBUG(
  9690. dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
  9691. "better alternative\n");
  9692. return SDValue();
  9693. }
  9694. SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op,
  9695. SelectionDAG &DAG) const {
  9696. if (useSVEForFixedLengthVectorVT(Op.getValueType()))
  9697. return LowerFixedLengthConcatVectorsToSVE(Op, DAG);
  9698. assert(Op.getValueType().isScalableVector() &&
  9699. isTypeLegal(Op.getValueType()) &&
  9700. "Expected legal scalable vector type!");
  9701. if (isTypeLegal(Op.getOperand(0).getValueType())) {
  9702. unsigned NumOperands = Op->getNumOperands();
  9703. assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
  9704. "Unexpected number of operands in CONCAT_VECTORS");
  9705. if (NumOperands == 2)
  9706. return Op;
  9707. // Concat each pair of subvectors and pack into the lower half of the array.
  9708. SmallVector<SDValue> ConcatOps(Op->op_begin(), Op->op_end());
  9709. while (ConcatOps.size() > 1) {
  9710. for (unsigned I = 0, E = ConcatOps.size(); I != E; I += 2) {
  9711. SDValue V1 = ConcatOps[I];
  9712. SDValue V2 = ConcatOps[I + 1];
  9713. EVT SubVT = V1.getValueType();
  9714. EVT PairVT = SubVT.getDoubleNumVectorElementsVT(*DAG.getContext());
  9715. ConcatOps[I / 2] =
  9716. DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(Op), PairVT, V1, V2);
  9717. }
  9718. ConcatOps.resize(ConcatOps.size() / 2);
  9719. }
  9720. return ConcatOps[0];
  9721. }
  9722. return SDValue();
  9723. }
  9724. SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
  9725. SelectionDAG &DAG) const {
  9726. assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
  9727. if (useSVEForFixedLengthVectorVT(Op.getValueType()))
  9728. return LowerFixedLengthInsertVectorElt(Op, DAG);
  9729. // Check for non-constant or out of range lane.
  9730. EVT VT = Op.getOperand(0).getValueType();
  9731. if (VT.getScalarType() == MVT::i1) {
  9732. EVT VectorVT = getPromotedVTForPredicate(VT);
  9733. SDLoc DL(Op);
  9734. SDValue ExtendedVector =
  9735. DAG.getAnyExtOrTrunc(Op.getOperand(0), DL, VectorVT);
  9736. SDValue ExtendedValue =
  9737. DAG.getAnyExtOrTrunc(Op.getOperand(1), DL,
  9738. VectorVT.getScalarType().getSizeInBits() < 32
  9739. ? MVT::i32
  9740. : VectorVT.getScalarType());
  9741. ExtendedVector =
  9742. DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VectorVT, ExtendedVector,
  9743. ExtendedValue, Op.getOperand(2));
  9744. return DAG.getAnyExtOrTrunc(ExtendedVector, DL, VT);
  9745. }
  9746. ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
  9747. if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
  9748. return SDValue();
  9749. // Insertion/extraction are legal for V128 types.
  9750. if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
  9751. VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
  9752. VT == MVT::v8f16 || VT == MVT::v8bf16)
  9753. return Op;
  9754. if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
  9755. VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
  9756. VT != MVT::v4bf16)
  9757. return SDValue();
  9758. // For V64 types, we perform insertion by expanding the value
  9759. // to a V128 type and perform the insertion on that.
  9760. SDLoc DL(Op);
  9761. SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
  9762. EVT WideTy = WideVec.getValueType();
  9763. SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
  9764. Op.getOperand(1), Op.getOperand(2));
  9765. // Re-narrow the resultant vector.
  9766. return NarrowVector(Node, DAG);
  9767. }
  9768. SDValue
  9769. AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
  9770. SelectionDAG &DAG) const {
  9771. assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
  9772. EVT VT = Op.getOperand(0).getValueType();
  9773. if (VT.getScalarType() == MVT::i1) {
  9774. // We can't directly extract from an SVE predicate; extend it first.
  9775. // (This isn't the only possible lowering, but it's straightforward.)
  9776. EVT VectorVT = getPromotedVTForPredicate(VT);
  9777. SDLoc DL(Op);
  9778. SDValue Extend =
  9779. DAG.getNode(ISD::ANY_EXTEND, DL, VectorVT, Op.getOperand(0));
  9780. MVT ExtractTy = VectorVT == MVT::nxv2i64 ? MVT::i64 : MVT::i32;
  9781. SDValue Extract = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtractTy,
  9782. Extend, Op.getOperand(1));
  9783. return DAG.getAnyExtOrTrunc(Extract, DL, Op.getValueType());
  9784. }
  9785. if (useSVEForFixedLengthVectorVT(VT))
  9786. return LowerFixedLengthExtractVectorElt(Op, DAG);
  9787. // Check for non-constant or out of range lane.
  9788. ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  9789. if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
  9790. return SDValue();
  9791. // Insertion/extraction are legal for V128 types.
  9792. if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
  9793. VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
  9794. VT == MVT::v8f16 || VT == MVT::v8bf16)
  9795. return Op;
  9796. if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
  9797. VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
  9798. VT != MVT::v4bf16)
  9799. return SDValue();
  9800. // For V64 types, we perform extraction by expanding the value
  9801. // to a V128 type and perform the extraction on that.
  9802. SDLoc DL(Op);
  9803. SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
  9804. EVT WideTy = WideVec.getValueType();
  9805. EVT ExtrTy = WideTy.getVectorElementType();
  9806. if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
  9807. ExtrTy = MVT::i32;
  9808. // For extractions, we just return the result directly.
  9809. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
  9810. Op.getOperand(1));
  9811. }
  9812. SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
  9813. SelectionDAG &DAG) const {
  9814. assert(Op.getValueType().isFixedLengthVector() &&
  9815. "Only cases that extract a fixed length vector are supported!");
  9816. EVT InVT = Op.getOperand(0).getValueType();
  9817. unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
  9818. unsigned Size = Op.getValueSizeInBits();
  9819. // If we don't have legal types yet, do nothing
  9820. if (!DAG.getTargetLoweringInfo().isTypeLegal(InVT))
  9821. return SDValue();
  9822. if (InVT.isScalableVector()) {
  9823. // This will be matched by custom code during ISelDAGToDAG.
  9824. if (Idx == 0 && isPackedVectorType(InVT, DAG))
  9825. return Op;
  9826. return SDValue();
  9827. }
  9828. // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
  9829. if (Idx == 0 && InVT.getSizeInBits() <= 128)
  9830. return Op;
  9831. // If this is extracting the upper 64-bits of a 128-bit vector, we match
  9832. // that directly.
  9833. if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 &&
  9834. InVT.getSizeInBits() == 128)
  9835. return Op;
  9836. if (useSVEForFixedLengthVectorVT(InVT)) {
  9837. SDLoc DL(Op);
  9838. EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
  9839. SDValue NewInVec =
  9840. convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
  9841. SDValue Splice = DAG.getNode(ISD::VECTOR_SPLICE, DL, ContainerVT, NewInVec,
  9842. NewInVec, DAG.getConstant(Idx, DL, MVT::i64));
  9843. return convertFromScalableVector(DAG, Op.getValueType(), Splice);
  9844. }
  9845. return SDValue();
  9846. }
  9847. SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
  9848. SelectionDAG &DAG) const {
  9849. assert(Op.getValueType().isScalableVector() &&
  9850. "Only expect to lower inserts into scalable vectors!");
  9851. EVT InVT = Op.getOperand(1).getValueType();
  9852. unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
  9853. SDValue Vec0 = Op.getOperand(0);
  9854. SDValue Vec1 = Op.getOperand(1);
  9855. SDLoc DL(Op);
  9856. EVT VT = Op.getValueType();
  9857. if (InVT.isScalableVector()) {
  9858. if (!isTypeLegal(VT))
  9859. return SDValue();
  9860. // Break down insert_subvector into simpler parts.
  9861. if (VT.getVectorElementType() == MVT::i1) {
  9862. unsigned NumElts = VT.getVectorMinNumElements();
  9863. EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
  9864. SDValue Lo, Hi;
  9865. Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, Vec0,
  9866. DAG.getVectorIdxConstant(0, DL));
  9867. Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, Vec0,
  9868. DAG.getVectorIdxConstant(NumElts / 2, DL));
  9869. if (Idx < (NumElts / 2)) {
  9870. SDValue NewLo = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, HalfVT, Lo, Vec1,
  9871. DAG.getVectorIdxConstant(Idx, DL));
  9872. return DAG.getNode(AArch64ISD::UZP1, DL, VT, NewLo, Hi);
  9873. } else {
  9874. SDValue NewHi =
  9875. DAG.getNode(ISD::INSERT_SUBVECTOR, DL, HalfVT, Hi, Vec1,
  9876. DAG.getVectorIdxConstant(Idx - (NumElts / 2), DL));
  9877. return DAG.getNode(AArch64ISD::UZP1, DL, VT, Lo, NewHi);
  9878. }
  9879. }
  9880. // Ensure the subvector is half the size of the main vector.
  9881. if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2))
  9882. return SDValue();
  9883. EVT WideVT;
  9884. SDValue ExtVec;
  9885. if (VT.isFloatingPoint()) {
  9886. // The InVT type should be legal. We can safely cast the unpacked
  9887. // subvector from InVT -> VT.
  9888. WideVT = VT;
  9889. ExtVec = getSVESafeBitCast(VT, Vec1, DAG);
  9890. } else {
  9891. // Extend elements of smaller vector...
  9892. WideVT = InVT.widenIntegerVectorElementType(*(DAG.getContext()));
  9893. ExtVec = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1);
  9894. }
  9895. if (Idx == 0) {
  9896. SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0);
  9897. return DAG.getNode(AArch64ISD::UZP1, DL, VT, ExtVec, HiVec0);
  9898. } else if (Idx == InVT.getVectorMinNumElements()) {
  9899. SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0);
  9900. return DAG.getNode(AArch64ISD::UZP1, DL, VT, LoVec0, ExtVec);
  9901. }
  9902. return SDValue();
  9903. }
  9904. if (Idx == 0 && isPackedVectorType(VT, DAG)) {
  9905. // This will be matched by custom code during ISelDAGToDAG.
  9906. if (Vec0.isUndef())
  9907. return Op;
  9908. Optional<unsigned> PredPattern =
  9909. getSVEPredPatternFromNumElements(InVT.getVectorNumElements());
  9910. auto PredTy = VT.changeVectorElementType(MVT::i1);
  9911. SDValue PTrue = getPTrue(DAG, DL, PredTy, *PredPattern);
  9912. SDValue ScalableVec1 = convertToScalableVector(DAG, VT, Vec1);
  9913. return DAG.getNode(ISD::VSELECT, DL, VT, PTrue, ScalableVec1, Vec0);
  9914. }
  9915. return SDValue();
  9916. }
  9917. static bool isPow2Splat(SDValue Op, uint64_t &SplatVal, bool &Negated) {
  9918. if (Op.getOpcode() != AArch64ISD::DUP &&
  9919. Op.getOpcode() != ISD::SPLAT_VECTOR &&
  9920. Op.getOpcode() != ISD::BUILD_VECTOR)
  9921. return false;
  9922. if (Op.getOpcode() == ISD::BUILD_VECTOR &&
  9923. !isAllConstantBuildVector(Op, SplatVal))
  9924. return false;
  9925. if (Op.getOpcode() != ISD::BUILD_VECTOR &&
  9926. !isa<ConstantSDNode>(Op->getOperand(0)))
  9927. return false;
  9928. SplatVal = Op->getConstantOperandVal(0);
  9929. if (Op.getValueType().getVectorElementType() != MVT::i64)
  9930. SplatVal = (int32_t)SplatVal;
  9931. Negated = false;
  9932. if (isPowerOf2_64(SplatVal))
  9933. return true;
  9934. Negated = true;
  9935. if (isPowerOf2_64(-SplatVal)) {
  9936. SplatVal = -SplatVal;
  9937. return true;
  9938. }
  9939. return false;
  9940. }
  9941. SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const {
  9942. EVT VT = Op.getValueType();
  9943. SDLoc dl(Op);
  9944. if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
  9945. return LowerFixedLengthVectorIntDivideToSVE(Op, DAG);
  9946. assert(VT.isScalableVector() && "Expected a scalable vector.");
  9947. bool Signed = Op.getOpcode() == ISD::SDIV;
  9948. unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
  9949. bool Negated;
  9950. uint64_t SplatVal;
  9951. if (Signed && isPow2Splat(Op.getOperand(1), SplatVal, Negated)) {
  9952. SDValue Pg = getPredicateForScalableVector(DAG, dl, VT);
  9953. SDValue Res =
  9954. DAG.getNode(AArch64ISD::SRAD_MERGE_OP1, dl, VT, Pg, Op->getOperand(0),
  9955. DAG.getTargetConstant(Log2_64(SplatVal), dl, MVT::i32));
  9956. if (Negated)
  9957. Res = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), Res);
  9958. return Res;
  9959. }
  9960. if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64)
  9961. return LowerToPredicatedOp(Op, DAG, PredOpcode);
  9962. // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit
  9963. // operations, and truncate the result.
  9964. EVT WidenedVT;
  9965. if (VT == MVT::nxv16i8)
  9966. WidenedVT = MVT::nxv8i16;
  9967. else if (VT == MVT::nxv8i16)
  9968. WidenedVT = MVT::nxv4i32;
  9969. else
  9970. llvm_unreachable("Unexpected Custom DIV operation");
  9971. unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
  9972. unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
  9973. SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0));
  9974. SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1));
  9975. SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0));
  9976. SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1));
  9977. SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo);
  9978. SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi);
  9979. return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi);
  9980. }
  9981. bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
  9982. // Currently no fixed length shuffles that require SVE are legal.
  9983. if (useSVEForFixedLengthVectorVT(VT))
  9984. return false;
  9985. if (VT.getVectorNumElements() == 4 &&
  9986. (VT.is128BitVector() || VT.is64BitVector())) {
  9987. unsigned PFIndexes[4];
  9988. for (unsigned i = 0; i != 4; ++i) {
  9989. if (M[i] < 0)
  9990. PFIndexes[i] = 8;
  9991. else
  9992. PFIndexes[i] = M[i];
  9993. }
  9994. // Compute the index in the perfect shuffle table.
  9995. unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
  9996. PFIndexes[2] * 9 + PFIndexes[3];
  9997. unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
  9998. unsigned Cost = (PFEntry >> 30);
  9999. if (Cost <= 4)
  10000. return true;
  10001. }
  10002. bool DummyBool;
  10003. int DummyInt;
  10004. unsigned DummyUnsigned;
  10005. return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
  10006. isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
  10007. isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
  10008. // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
  10009. isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
  10010. isZIPMask(M, VT, DummyUnsigned) ||
  10011. isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
  10012. isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
  10013. isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
  10014. isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
  10015. isConcatMask(M, VT, VT.getSizeInBits() == 128));
  10016. }
  10017. /// getVShiftImm - Check if this is a valid build_vector for the immediate
  10018. /// operand of a vector shift operation, where all the elements of the
  10019. /// build_vector must have the same constant integer value.
  10020. static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
  10021. // Ignore bit_converts.
  10022. while (Op.getOpcode() == ISD::BITCAST)
  10023. Op = Op.getOperand(0);
  10024. BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
  10025. APInt SplatBits, SplatUndef;
  10026. unsigned SplatBitSize;
  10027. bool HasAnyUndefs;
  10028. if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
  10029. HasAnyUndefs, ElementBits) ||
  10030. SplatBitSize > ElementBits)
  10031. return false;
  10032. Cnt = SplatBits.getSExtValue();
  10033. return true;
  10034. }
  10035. /// isVShiftLImm - Check if this is a valid build_vector for the immediate
  10036. /// operand of a vector shift left operation. That value must be in the range:
  10037. /// 0 <= Value < ElementBits for a left shift; or
  10038. /// 0 <= Value <= ElementBits for a long left shift.
  10039. static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
  10040. assert(VT.isVector() && "vector shift count is not a vector type");
  10041. int64_t ElementBits = VT.getScalarSizeInBits();
  10042. if (!getVShiftImm(Op, ElementBits, Cnt))
  10043. return false;
  10044. return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
  10045. }
  10046. /// isVShiftRImm - Check if this is a valid build_vector for the immediate
  10047. /// operand of a vector shift right operation. The value must be in the range:
  10048. /// 1 <= Value <= ElementBits for a right shift; or
  10049. static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
  10050. assert(VT.isVector() && "vector shift count is not a vector type");
  10051. int64_t ElementBits = VT.getScalarSizeInBits();
  10052. if (!getVShiftImm(Op, ElementBits, Cnt))
  10053. return false;
  10054. return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
  10055. }
  10056. SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
  10057. SelectionDAG &DAG) const {
  10058. EVT VT = Op.getValueType();
  10059. if (VT.getScalarType() == MVT::i1) {
  10060. // Lower i1 truncate to `(x & 1) != 0`.
  10061. SDLoc dl(Op);
  10062. EVT OpVT = Op.getOperand(0).getValueType();
  10063. SDValue Zero = DAG.getConstant(0, dl, OpVT);
  10064. SDValue One = DAG.getConstant(1, dl, OpVT);
  10065. SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
  10066. return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
  10067. }
  10068. if (!VT.isVector() || VT.isScalableVector())
  10069. return SDValue();
  10070. if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
  10071. return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
  10072. return SDValue();
  10073. }
  10074. SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
  10075. SelectionDAG &DAG) const {
  10076. EVT VT = Op.getValueType();
  10077. SDLoc DL(Op);
  10078. int64_t Cnt;
  10079. if (!Op.getOperand(1).getValueType().isVector())
  10080. return Op;
  10081. unsigned EltSize = VT.getScalarSizeInBits();
  10082. switch (Op.getOpcode()) {
  10083. default:
  10084. llvm_unreachable("unexpected shift opcode");
  10085. case ISD::SHL:
  10086. if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
  10087. return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED);
  10088. if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
  10089. return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
  10090. DAG.getConstant(Cnt, DL, MVT::i32));
  10091. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
  10092. DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
  10093. MVT::i32),
  10094. Op.getOperand(0), Op.getOperand(1));
  10095. case ISD::SRA:
  10096. case ISD::SRL:
  10097. if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) {
  10098. unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED
  10099. : AArch64ISD::SRL_PRED;
  10100. return LowerToPredicatedOp(Op, DAG, Opc);
  10101. }
  10102. // Right shift immediate
  10103. if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
  10104. unsigned Opc =
  10105. (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
  10106. return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
  10107. DAG.getConstant(Cnt, DL, MVT::i32));
  10108. }
  10109. // Right shift register. Note, there is not a shift right register
  10110. // instruction, but the shift left register instruction takes a signed
  10111. // value, where negative numbers specify a right shift.
  10112. unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
  10113. : Intrinsic::aarch64_neon_ushl;
  10114. // negate the shift amount
  10115. SDValue NegShift = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
  10116. Op.getOperand(1));
  10117. SDValue NegShiftLeft =
  10118. DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
  10119. DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
  10120. NegShift);
  10121. return NegShiftLeft;
  10122. }
  10123. return SDValue();
  10124. }
  10125. static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
  10126. AArch64CC::CondCode CC, bool NoNans, EVT VT,
  10127. const SDLoc &dl, SelectionDAG &DAG) {
  10128. EVT SrcVT = LHS.getValueType();
  10129. assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
  10130. "function only supposed to emit natural comparisons");
  10131. BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
  10132. APInt CnstBits(VT.getSizeInBits(), 0);
  10133. APInt UndefBits(VT.getSizeInBits(), 0);
  10134. bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
  10135. bool IsZero = IsCnst && (CnstBits == 0);
  10136. if (SrcVT.getVectorElementType().isFloatingPoint()) {
  10137. switch (CC) {
  10138. default:
  10139. return SDValue();
  10140. case AArch64CC::NE: {
  10141. SDValue Fcmeq;
  10142. if (IsZero)
  10143. Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
  10144. else
  10145. Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
  10146. return DAG.getNOT(dl, Fcmeq, VT);
  10147. }
  10148. case AArch64CC::EQ:
  10149. if (IsZero)
  10150. return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
  10151. return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
  10152. case AArch64CC::GE:
  10153. if (IsZero)
  10154. return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
  10155. return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
  10156. case AArch64CC::GT:
  10157. if (IsZero)
  10158. return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
  10159. return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
  10160. case AArch64CC::LS:
  10161. if (IsZero)
  10162. return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
  10163. return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
  10164. case AArch64CC::LT:
  10165. if (!NoNans)
  10166. return SDValue();
  10167. // If we ignore NaNs then we can use to the MI implementation.
  10168. LLVM_FALLTHROUGH;
  10169. case AArch64CC::MI:
  10170. if (IsZero)
  10171. return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
  10172. return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
  10173. }
  10174. }
  10175. switch (CC) {
  10176. default:
  10177. return SDValue();
  10178. case AArch64CC::NE: {
  10179. SDValue Cmeq;
  10180. if (IsZero)
  10181. Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
  10182. else
  10183. Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
  10184. return DAG.getNOT(dl, Cmeq, VT);
  10185. }
  10186. case AArch64CC::EQ:
  10187. if (IsZero)
  10188. return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
  10189. return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
  10190. case AArch64CC::GE:
  10191. if (IsZero)
  10192. return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
  10193. return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
  10194. case AArch64CC::GT:
  10195. if (IsZero)
  10196. return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
  10197. return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
  10198. case AArch64CC::LE:
  10199. if (IsZero)
  10200. return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
  10201. return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
  10202. case AArch64CC::LS:
  10203. return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
  10204. case AArch64CC::LO:
  10205. return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
  10206. case AArch64CC::LT:
  10207. if (IsZero)
  10208. return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
  10209. return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
  10210. case AArch64CC::HI:
  10211. return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
  10212. case AArch64CC::HS:
  10213. return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
  10214. }
  10215. }
  10216. SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
  10217. SelectionDAG &DAG) const {
  10218. if (Op.getValueType().isScalableVector())
  10219. return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
  10220. if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
  10221. return LowerFixedLengthVectorSetccToSVE(Op, DAG);
  10222. ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
  10223. SDValue LHS = Op.getOperand(0);
  10224. SDValue RHS = Op.getOperand(1);
  10225. EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
  10226. SDLoc dl(Op);
  10227. if (LHS.getValueType().getVectorElementType().isInteger()) {
  10228. assert(LHS.getValueType() == RHS.getValueType());
  10229. AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
  10230. SDValue Cmp =
  10231. EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
  10232. return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
  10233. }
  10234. const bool FullFP16 =
  10235. static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
  10236. // Make v4f16 (only) fcmp operations utilise vector instructions
  10237. // v8f16 support will be a litle more complicated
  10238. if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
  10239. if (LHS.getValueType().getVectorNumElements() == 4) {
  10240. LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
  10241. RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
  10242. SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
  10243. DAG.ReplaceAllUsesWith(Op, NewSetcc);
  10244. CmpVT = MVT::v4i32;
  10245. } else
  10246. return SDValue();
  10247. }
  10248. assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
  10249. LHS.getValueType().getVectorElementType() != MVT::f128);
  10250. // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
  10251. // clean. Some of them require two branches to implement.
  10252. AArch64CC::CondCode CC1, CC2;
  10253. bool ShouldInvert;
  10254. changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
  10255. bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
  10256. SDValue Cmp =
  10257. EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
  10258. if (!Cmp.getNode())
  10259. return SDValue();
  10260. if (CC2 != AArch64CC::AL) {
  10261. SDValue Cmp2 =
  10262. EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
  10263. if (!Cmp2.getNode())
  10264. return SDValue();
  10265. Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
  10266. }
  10267. Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
  10268. if (ShouldInvert)
  10269. Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
  10270. return Cmp;
  10271. }
  10272. static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
  10273. SelectionDAG &DAG) {
  10274. SDValue VecOp = ScalarOp.getOperand(0);
  10275. auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
  10276. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
  10277. DAG.getConstant(0, DL, MVT::i64));
  10278. }
  10279. SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
  10280. SelectionDAG &DAG) const {
  10281. SDValue Src = Op.getOperand(0);
  10282. // Try to lower fixed length reductions to SVE.
  10283. EVT SrcVT = Src.getValueType();
  10284. bool OverrideNEON = Op.getOpcode() == ISD::VECREDUCE_AND ||
  10285. Op.getOpcode() == ISD::VECREDUCE_OR ||
  10286. Op.getOpcode() == ISD::VECREDUCE_XOR ||
  10287. Op.getOpcode() == ISD::VECREDUCE_FADD ||
  10288. (Op.getOpcode() != ISD::VECREDUCE_ADD &&
  10289. SrcVT.getVectorElementType() == MVT::i64);
  10290. if (SrcVT.isScalableVector() ||
  10291. useSVEForFixedLengthVectorVT(SrcVT, OverrideNEON)) {
  10292. if (SrcVT.getVectorElementType() == MVT::i1)
  10293. return LowerPredReductionToSVE(Op, DAG);
  10294. switch (Op.getOpcode()) {
  10295. case ISD::VECREDUCE_ADD:
  10296. return LowerReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG);
  10297. case ISD::VECREDUCE_AND:
  10298. return LowerReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG);
  10299. case ISD::VECREDUCE_OR:
  10300. return LowerReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG);
  10301. case ISD::VECREDUCE_SMAX:
  10302. return LowerReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG);
  10303. case ISD::VECREDUCE_SMIN:
  10304. return LowerReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG);
  10305. case ISD::VECREDUCE_UMAX:
  10306. return LowerReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG);
  10307. case ISD::VECREDUCE_UMIN:
  10308. return LowerReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG);
  10309. case ISD::VECREDUCE_XOR:
  10310. return LowerReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG);
  10311. case ISD::VECREDUCE_FADD:
  10312. return LowerReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG);
  10313. case ISD::VECREDUCE_FMAX:
  10314. return LowerReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG);
  10315. case ISD::VECREDUCE_FMIN:
  10316. return LowerReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG);
  10317. default:
  10318. llvm_unreachable("Unhandled fixed length reduction");
  10319. }
  10320. }
  10321. // Lower NEON reductions.
  10322. SDLoc dl(Op);
  10323. switch (Op.getOpcode()) {
  10324. case ISD::VECREDUCE_ADD:
  10325. return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
  10326. case ISD::VECREDUCE_SMAX:
  10327. return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
  10328. case ISD::VECREDUCE_SMIN:
  10329. return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
  10330. case ISD::VECREDUCE_UMAX:
  10331. return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
  10332. case ISD::VECREDUCE_UMIN:
  10333. return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
  10334. case ISD::VECREDUCE_FMAX: {
  10335. return DAG.getNode(
  10336. ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
  10337. DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
  10338. Src);
  10339. }
  10340. case ISD::VECREDUCE_FMIN: {
  10341. return DAG.getNode(
  10342. ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
  10343. DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
  10344. Src);
  10345. }
  10346. default:
  10347. llvm_unreachable("Unhandled reduction");
  10348. }
  10349. }
  10350. SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
  10351. SelectionDAG &DAG) const {
  10352. auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
  10353. if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
  10354. return SDValue();
  10355. // LSE has an atomic load-add instruction, but not a load-sub.
  10356. SDLoc dl(Op);
  10357. MVT VT = Op.getSimpleValueType();
  10358. SDValue RHS = Op.getOperand(2);
  10359. AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
  10360. RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
  10361. return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
  10362. Op.getOperand(0), Op.getOperand(1), RHS,
  10363. AN->getMemOperand());
  10364. }
  10365. SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
  10366. SelectionDAG &DAG) const {
  10367. auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
  10368. if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
  10369. return SDValue();
  10370. // LSE has an atomic load-clear instruction, but not a load-and.
  10371. SDLoc dl(Op);
  10372. MVT VT = Op.getSimpleValueType();
  10373. SDValue RHS = Op.getOperand(2);
  10374. AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
  10375. RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
  10376. return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
  10377. Op.getOperand(0), Op.getOperand(1), RHS,
  10378. AN->getMemOperand());
  10379. }
  10380. SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
  10381. SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
  10382. SDLoc dl(Op);
  10383. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  10384. SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
  10385. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
  10386. const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
  10387. if (Subtarget->hasCustomCallingConv())
  10388. TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
  10389. Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
  10390. DAG.getConstant(4, dl, MVT::i64));
  10391. Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
  10392. Chain =
  10393. DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
  10394. Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
  10395. DAG.getRegisterMask(Mask), Chain.getValue(1));
  10396. // To match the actual intent better, we should read the output from X15 here
  10397. // again (instead of potentially spilling it to the stack), but rereading Size
  10398. // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
  10399. // here.
  10400. Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
  10401. DAG.getConstant(4, dl, MVT::i64));
  10402. return Chain;
  10403. }
  10404. SDValue
  10405. AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
  10406. SelectionDAG &DAG) const {
  10407. assert(Subtarget->isTargetWindows() &&
  10408. "Only Windows alloca probing supported");
  10409. SDLoc dl(Op);
  10410. // Get the inputs.
  10411. SDNode *Node = Op.getNode();
  10412. SDValue Chain = Op.getOperand(0);
  10413. SDValue Size = Op.getOperand(1);
  10414. MaybeAlign Align =
  10415. cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
  10416. EVT VT = Node->getValueType(0);
  10417. if (DAG.getMachineFunction().getFunction().hasFnAttribute(
  10418. "no-stack-arg-probe")) {
  10419. SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
  10420. Chain = SP.getValue(1);
  10421. SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
  10422. if (Align)
  10423. SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
  10424. DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
  10425. Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
  10426. SDValue Ops[2] = {SP, Chain};
  10427. return DAG.getMergeValues(Ops, dl);
  10428. }
  10429. Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
  10430. Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
  10431. SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
  10432. Chain = SP.getValue(1);
  10433. SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
  10434. if (Align)
  10435. SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
  10436. DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
  10437. Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
  10438. Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
  10439. DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
  10440. SDValue Ops[2] = {SP, Chain};
  10441. return DAG.getMergeValues(Ops, dl);
  10442. }
  10443. SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
  10444. SelectionDAG &DAG) const {
  10445. EVT VT = Op.getValueType();
  10446. assert(VT != MVT::i64 && "Expected illegal VSCALE node");
  10447. SDLoc DL(Op);
  10448. APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
  10449. return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
  10450. DL, VT);
  10451. }
  10452. /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
  10453. template <unsigned NumVecs>
  10454. static bool
  10455. setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL,
  10456. AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) {
  10457. Info.opc = ISD::INTRINSIC_VOID;
  10458. // Retrieve EC from first vector argument.
  10459. const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType());
  10460. ElementCount EC = VT.getVectorElementCount();
  10461. #ifndef NDEBUG
  10462. // Check the assumption that all input vectors are the same type.
  10463. for (unsigned I = 0; I < NumVecs; ++I)
  10464. assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) &&
  10465. "Invalid type.");
  10466. #endif
  10467. // memVT is `NumVecs * VT`.
  10468. Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
  10469. EC * NumVecs);
  10470. Info.ptrVal = CI.getArgOperand(CI.arg_size() - 1);
  10471. Info.offset = 0;
  10472. Info.align.reset();
  10473. Info.flags = MachineMemOperand::MOStore;
  10474. return true;
  10475. }
  10476. /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
  10477. /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
  10478. /// specified in the intrinsic calls.
  10479. bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
  10480. const CallInst &I,
  10481. MachineFunction &MF,
  10482. unsigned Intrinsic) const {
  10483. auto &DL = I.getModule()->getDataLayout();
  10484. switch (Intrinsic) {
  10485. case Intrinsic::aarch64_sve_st2:
  10486. return setInfoSVEStN<2>(*this, DL, Info, I);
  10487. case Intrinsic::aarch64_sve_st3:
  10488. return setInfoSVEStN<3>(*this, DL, Info, I);
  10489. case Intrinsic::aarch64_sve_st4:
  10490. return setInfoSVEStN<4>(*this, DL, Info, I);
  10491. case Intrinsic::aarch64_neon_ld2:
  10492. case Intrinsic::aarch64_neon_ld3:
  10493. case Intrinsic::aarch64_neon_ld4:
  10494. case Intrinsic::aarch64_neon_ld1x2:
  10495. case Intrinsic::aarch64_neon_ld1x3:
  10496. case Intrinsic::aarch64_neon_ld1x4:
  10497. case Intrinsic::aarch64_neon_ld2lane:
  10498. case Intrinsic::aarch64_neon_ld3lane:
  10499. case Intrinsic::aarch64_neon_ld4lane:
  10500. case Intrinsic::aarch64_neon_ld2r:
  10501. case Intrinsic::aarch64_neon_ld3r:
  10502. case Intrinsic::aarch64_neon_ld4r: {
  10503. Info.opc = ISD::INTRINSIC_W_CHAIN;
  10504. // Conservatively set memVT to the entire set of vectors loaded.
  10505. uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
  10506. Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
  10507. Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
  10508. Info.offset = 0;
  10509. Info.align.reset();
  10510. // volatile loads with NEON intrinsics not supported
  10511. Info.flags = MachineMemOperand::MOLoad;
  10512. return true;
  10513. }
  10514. case Intrinsic::aarch64_neon_st2:
  10515. case Intrinsic::aarch64_neon_st3:
  10516. case Intrinsic::aarch64_neon_st4:
  10517. case Intrinsic::aarch64_neon_st1x2:
  10518. case Intrinsic::aarch64_neon_st1x3:
  10519. case Intrinsic::aarch64_neon_st1x4:
  10520. case Intrinsic::aarch64_neon_st2lane:
  10521. case Intrinsic::aarch64_neon_st3lane:
  10522. case Intrinsic::aarch64_neon_st4lane: {
  10523. Info.opc = ISD::INTRINSIC_VOID;
  10524. // Conservatively set memVT to the entire set of vectors stored.
  10525. unsigned NumElts = 0;
  10526. for (const Value *Arg : I.args()) {
  10527. Type *ArgTy = Arg->getType();
  10528. if (!ArgTy->isVectorTy())
  10529. break;
  10530. NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
  10531. }
  10532. Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
  10533. Info.ptrVal = I.getArgOperand(I.arg_size() - 1);
  10534. Info.offset = 0;
  10535. Info.align.reset();
  10536. // volatile stores with NEON intrinsics not supported
  10537. Info.flags = MachineMemOperand::MOStore;
  10538. return true;
  10539. }
  10540. case Intrinsic::aarch64_ldaxr:
  10541. case Intrinsic::aarch64_ldxr: {
  10542. PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
  10543. Info.opc = ISD::INTRINSIC_W_CHAIN;
  10544. Info.memVT = MVT::getVT(PtrTy->getPointerElementType());
  10545. Info.ptrVal = I.getArgOperand(0);
  10546. Info.offset = 0;
  10547. Info.align = DL.getABITypeAlign(PtrTy->getPointerElementType());
  10548. Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
  10549. return true;
  10550. }
  10551. case Intrinsic::aarch64_stlxr:
  10552. case Intrinsic::aarch64_stxr: {
  10553. PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
  10554. Info.opc = ISD::INTRINSIC_W_CHAIN;
  10555. Info.memVT = MVT::getVT(PtrTy->getPointerElementType());
  10556. Info.ptrVal = I.getArgOperand(1);
  10557. Info.offset = 0;
  10558. Info.align = DL.getABITypeAlign(PtrTy->getPointerElementType());
  10559. Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
  10560. return true;
  10561. }
  10562. case Intrinsic::aarch64_ldaxp:
  10563. case Intrinsic::aarch64_ldxp:
  10564. Info.opc = ISD::INTRINSIC_W_CHAIN;
  10565. Info.memVT = MVT::i128;
  10566. Info.ptrVal = I.getArgOperand(0);
  10567. Info.offset = 0;
  10568. Info.align = Align(16);
  10569. Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
  10570. return true;
  10571. case Intrinsic::aarch64_stlxp:
  10572. case Intrinsic::aarch64_stxp:
  10573. Info.opc = ISD::INTRINSIC_W_CHAIN;
  10574. Info.memVT = MVT::i128;
  10575. Info.ptrVal = I.getArgOperand(2);
  10576. Info.offset = 0;
  10577. Info.align = Align(16);
  10578. Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
  10579. return true;
  10580. case Intrinsic::aarch64_sve_ldnt1: {
  10581. PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
  10582. Info.opc = ISD::INTRINSIC_W_CHAIN;
  10583. Info.memVT = MVT::getVT(I.getType());
  10584. Info.ptrVal = I.getArgOperand(1);
  10585. Info.offset = 0;
  10586. Info.align = DL.getABITypeAlign(PtrTy->getPointerElementType());
  10587. Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MONonTemporal;
  10588. return true;
  10589. }
  10590. case Intrinsic::aarch64_sve_stnt1: {
  10591. PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
  10592. Info.opc = ISD::INTRINSIC_W_CHAIN;
  10593. Info.memVT = MVT::getVT(I.getOperand(0)->getType());
  10594. Info.ptrVal = I.getArgOperand(2);
  10595. Info.offset = 0;
  10596. Info.align = DL.getABITypeAlign(PtrTy->getPointerElementType());
  10597. Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MONonTemporal;
  10598. return true;
  10599. }
  10600. case Intrinsic::aarch64_mops_memset_tag: {
  10601. Value *Dst = I.getArgOperand(0);
  10602. Value *Val = I.getArgOperand(1);
  10603. Info.opc = ISD::INTRINSIC_W_CHAIN;
  10604. Info.memVT = MVT::getVT(Val->getType());
  10605. Info.ptrVal = Dst;
  10606. Info.offset = 0;
  10607. Info.align = I.getParamAlign(0).valueOrOne();
  10608. Info.flags = MachineMemOperand::MOStore;
  10609. // The size of the memory being operated on is unknown at this point
  10610. Info.size = MemoryLocation::UnknownSize;
  10611. return true;
  10612. }
  10613. default:
  10614. break;
  10615. }
  10616. return false;
  10617. }
  10618. bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
  10619. ISD::LoadExtType ExtTy,
  10620. EVT NewVT) const {
  10621. // TODO: This may be worth removing. Check regression tests for diffs.
  10622. if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
  10623. return false;
  10624. // If we're reducing the load width in order to avoid having to use an extra
  10625. // instruction to do extension then it's probably a good idea.
  10626. if (ExtTy != ISD::NON_EXTLOAD)
  10627. return true;
  10628. // Don't reduce load width if it would prevent us from combining a shift into
  10629. // the offset.
  10630. MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
  10631. assert(Mem);
  10632. const SDValue &Base = Mem->getBasePtr();
  10633. if (Base.getOpcode() == ISD::ADD &&
  10634. Base.getOperand(1).getOpcode() == ISD::SHL &&
  10635. Base.getOperand(1).hasOneUse() &&
  10636. Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
  10637. // It's unknown whether a scalable vector has a power-of-2 bitwidth.
  10638. if (Mem->getMemoryVT().isScalableVector())
  10639. return false;
  10640. // The shift can be combined if it matches the size of the value being
  10641. // loaded (and so reducing the width would make it not match).
  10642. uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
  10643. uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
  10644. if (ShiftAmount == Log2_32(LoadBytes))
  10645. return false;
  10646. }
  10647. // We have no reason to disallow reducing the load width, so allow it.
  10648. return true;
  10649. }
  10650. // Truncations from 64-bit GPR to 32-bit GPR is free.
  10651. bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
  10652. if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
  10653. return false;
  10654. uint64_t NumBits1 = Ty1->getPrimitiveSizeInBits().getFixedSize();
  10655. uint64_t NumBits2 = Ty2->getPrimitiveSizeInBits().getFixedSize();
  10656. return NumBits1 > NumBits2;
  10657. }
  10658. bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
  10659. if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
  10660. return false;
  10661. uint64_t NumBits1 = VT1.getFixedSizeInBits();
  10662. uint64_t NumBits2 = VT2.getFixedSizeInBits();
  10663. return NumBits1 > NumBits2;
  10664. }
  10665. /// Check if it is profitable to hoist instruction in then/else to if.
  10666. /// Not profitable if I and it's user can form a FMA instruction
  10667. /// because we prefer FMSUB/FMADD.
  10668. bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
  10669. if (I->getOpcode() != Instruction::FMul)
  10670. return true;
  10671. if (!I->hasOneUse())
  10672. return true;
  10673. Instruction *User = I->user_back();
  10674. if (User &&
  10675. !(User->getOpcode() == Instruction::FSub ||
  10676. User->getOpcode() == Instruction::FAdd))
  10677. return true;
  10678. const TargetOptions &Options = getTargetMachine().Options;
  10679. const Function *F = I->getFunction();
  10680. const DataLayout &DL = F->getParent()->getDataLayout();
  10681. Type *Ty = User->getOperand(0)->getType();
  10682. return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
  10683. isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
  10684. (Options.AllowFPOpFusion == FPOpFusion::Fast ||
  10685. Options.UnsafeFPMath));
  10686. }
  10687. // All 32-bit GPR operations implicitly zero the high-half of the corresponding
  10688. // 64-bit GPR.
  10689. bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
  10690. if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
  10691. return false;
  10692. unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
  10693. unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
  10694. return NumBits1 == 32 && NumBits2 == 64;
  10695. }
  10696. bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
  10697. if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
  10698. return false;
  10699. unsigned NumBits1 = VT1.getSizeInBits();
  10700. unsigned NumBits2 = VT2.getSizeInBits();
  10701. return NumBits1 == 32 && NumBits2 == 64;
  10702. }
  10703. bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
  10704. EVT VT1 = Val.getValueType();
  10705. if (isZExtFree(VT1, VT2)) {
  10706. return true;
  10707. }
  10708. if (Val.getOpcode() != ISD::LOAD)
  10709. return false;
  10710. // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
  10711. return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
  10712. VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
  10713. VT1.getSizeInBits() <= 32);
  10714. }
  10715. bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
  10716. if (isa<FPExtInst>(Ext))
  10717. return false;
  10718. // Vector types are not free.
  10719. if (Ext->getType()->isVectorTy())
  10720. return false;
  10721. for (const Use &U : Ext->uses()) {
  10722. // The extension is free if we can fold it with a left shift in an
  10723. // addressing mode or an arithmetic operation: add, sub, and cmp.
  10724. // Is there a shift?
  10725. const Instruction *Instr = cast<Instruction>(U.getUser());
  10726. // Is this a constant shift?
  10727. switch (Instr->getOpcode()) {
  10728. case Instruction::Shl:
  10729. if (!isa<ConstantInt>(Instr->getOperand(1)))
  10730. return false;
  10731. break;
  10732. case Instruction::GetElementPtr: {
  10733. gep_type_iterator GTI = gep_type_begin(Instr);
  10734. auto &DL = Ext->getModule()->getDataLayout();
  10735. std::advance(GTI, U.getOperandNo()-1);
  10736. Type *IdxTy = GTI.getIndexedType();
  10737. // This extension will end up with a shift because of the scaling factor.
  10738. // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
  10739. // Get the shift amount based on the scaling factor:
  10740. // log2(sizeof(IdxTy)) - log2(8).
  10741. uint64_t ShiftAmt =
  10742. countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
  10743. // Is the constant foldable in the shift of the addressing mode?
  10744. // I.e., shift amount is between 1 and 4 inclusive.
  10745. if (ShiftAmt == 0 || ShiftAmt > 4)
  10746. return false;
  10747. break;
  10748. }
  10749. case Instruction::Trunc:
  10750. // Check if this is a noop.
  10751. // trunc(sext ty1 to ty2) to ty1.
  10752. if (Instr->getType() == Ext->getOperand(0)->getType())
  10753. continue;
  10754. LLVM_FALLTHROUGH;
  10755. default:
  10756. return false;
  10757. }
  10758. // At this point we can use the bfm family, so this extension is free
  10759. // for that use.
  10760. }
  10761. return true;
  10762. }
  10763. /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
  10764. /// or upper half of the vector elements.
  10765. static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
  10766. auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
  10767. auto *FullTy = FullV->getType();
  10768. auto *HalfTy = HalfV->getType();
  10769. return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
  10770. 2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
  10771. };
  10772. auto extractHalf = [](Value *FullV, Value *HalfV) {
  10773. auto *FullVT = cast<FixedVectorType>(FullV->getType());
  10774. auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
  10775. return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
  10776. };
  10777. ArrayRef<int> M1, M2;
  10778. Value *S1Op1, *S2Op1;
  10779. if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
  10780. !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
  10781. return false;
  10782. // Check that the operands are half as wide as the result and we extract
  10783. // half of the elements of the input vectors.
  10784. if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
  10785. !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
  10786. return false;
  10787. // Check the mask extracts either the lower or upper half of vector
  10788. // elements.
  10789. int M1Start = -1;
  10790. int M2Start = -1;
  10791. int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
  10792. if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
  10793. !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
  10794. M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
  10795. return false;
  10796. return true;
  10797. }
  10798. /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
  10799. /// of the vector elements.
  10800. static bool areExtractExts(Value *Ext1, Value *Ext2) {
  10801. auto areExtDoubled = [](Instruction *Ext) {
  10802. return Ext->getType()->getScalarSizeInBits() ==
  10803. 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
  10804. };
  10805. if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
  10806. !match(Ext2, m_ZExtOrSExt(m_Value())) ||
  10807. !areExtDoubled(cast<Instruction>(Ext1)) ||
  10808. !areExtDoubled(cast<Instruction>(Ext2)))
  10809. return false;
  10810. return true;
  10811. }
  10812. /// Check if Op could be used with vmull_high_p64 intrinsic.
  10813. static bool isOperandOfVmullHighP64(Value *Op) {
  10814. Value *VectorOperand = nullptr;
  10815. ConstantInt *ElementIndex = nullptr;
  10816. return match(Op, m_ExtractElt(m_Value(VectorOperand),
  10817. m_ConstantInt(ElementIndex))) &&
  10818. ElementIndex->getValue() == 1 &&
  10819. isa<FixedVectorType>(VectorOperand->getType()) &&
  10820. cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
  10821. }
  10822. /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
  10823. static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
  10824. return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
  10825. }
  10826. static bool isSplatShuffle(Value *V) {
  10827. if (auto *Shuf = dyn_cast<ShuffleVectorInst>(V))
  10828. return is_splat(Shuf->getShuffleMask());
  10829. return false;
  10830. }
  10831. /// Check if sinking \p I's operands to I's basic block is profitable, because
  10832. /// the operands can be folded into a target instruction, e.g.
  10833. /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
  10834. bool AArch64TargetLowering::shouldSinkOperands(
  10835. Instruction *I, SmallVectorImpl<Use *> &Ops) const {
  10836. if (!I->getType()->isVectorTy())
  10837. return false;
  10838. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  10839. switch (II->getIntrinsicID()) {
  10840. case Intrinsic::aarch64_neon_smull:
  10841. case Intrinsic::aarch64_neon_umull:
  10842. if (areExtractShuffleVectors(II->getOperand(0), II->getOperand(1))) {
  10843. Ops.push_back(&II->getOperandUse(0));
  10844. Ops.push_back(&II->getOperandUse(1));
  10845. return true;
  10846. }
  10847. LLVM_FALLTHROUGH;
  10848. case Intrinsic::aarch64_neon_sqdmull:
  10849. case Intrinsic::aarch64_neon_sqdmulh:
  10850. case Intrinsic::aarch64_neon_sqrdmulh:
  10851. // Sink splats for index lane variants
  10852. if (isSplatShuffle(II->getOperand(0)))
  10853. Ops.push_back(&II->getOperandUse(0));
  10854. if (isSplatShuffle(II->getOperand(1)))
  10855. Ops.push_back(&II->getOperandUse(1));
  10856. return !Ops.empty();
  10857. case Intrinsic::aarch64_neon_pmull64:
  10858. if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
  10859. II->getArgOperand(1)))
  10860. return false;
  10861. Ops.push_back(&II->getArgOperandUse(0));
  10862. Ops.push_back(&II->getArgOperandUse(1));
  10863. return true;
  10864. default:
  10865. return false;
  10866. }
  10867. }
  10868. switch (I->getOpcode()) {
  10869. case Instruction::Sub:
  10870. case Instruction::Add: {
  10871. if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
  10872. return false;
  10873. // If the exts' operands extract either the lower or upper elements, we
  10874. // can sink them too.
  10875. auto Ext1 = cast<Instruction>(I->getOperand(0));
  10876. auto Ext2 = cast<Instruction>(I->getOperand(1));
  10877. if (areExtractShuffleVectors(Ext1->getOperand(0), Ext2->getOperand(0))) {
  10878. Ops.push_back(&Ext1->getOperandUse(0));
  10879. Ops.push_back(&Ext2->getOperandUse(0));
  10880. }
  10881. Ops.push_back(&I->getOperandUse(0));
  10882. Ops.push_back(&I->getOperandUse(1));
  10883. return true;
  10884. }
  10885. case Instruction::Mul: {
  10886. bool IsProfitable = false;
  10887. for (auto &Op : I->operands()) {
  10888. // Make sure we are not already sinking this operand
  10889. if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
  10890. continue;
  10891. ShuffleVectorInst *Shuffle = dyn_cast<ShuffleVectorInst>(Op);
  10892. if (!Shuffle || !Shuffle->isZeroEltSplat())
  10893. continue;
  10894. Value *ShuffleOperand = Shuffle->getOperand(0);
  10895. InsertElementInst *Insert = dyn_cast<InsertElementInst>(ShuffleOperand);
  10896. if (!Insert)
  10897. continue;
  10898. Instruction *OperandInstr = dyn_cast<Instruction>(Insert->getOperand(1));
  10899. if (!OperandInstr)
  10900. continue;
  10901. ConstantInt *ElementConstant =
  10902. dyn_cast<ConstantInt>(Insert->getOperand(2));
  10903. // Check that the insertelement is inserting into element 0
  10904. if (!ElementConstant || ElementConstant->getZExtValue() != 0)
  10905. continue;
  10906. unsigned Opcode = OperandInstr->getOpcode();
  10907. if (Opcode != Instruction::SExt && Opcode != Instruction::ZExt)
  10908. continue;
  10909. Ops.push_back(&Shuffle->getOperandUse(0));
  10910. Ops.push_back(&Op);
  10911. IsProfitable = true;
  10912. }
  10913. return IsProfitable;
  10914. }
  10915. default:
  10916. return false;
  10917. }
  10918. return false;
  10919. }
  10920. bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
  10921. Align &RequiredAligment) const {
  10922. if (!LoadedType.isSimple() ||
  10923. (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
  10924. return false;
  10925. // Cyclone supports unaligned accesses.
  10926. RequiredAligment = Align(1);
  10927. unsigned NumBits = LoadedType.getSizeInBits();
  10928. return NumBits == 32 || NumBits == 64;
  10929. }
  10930. /// A helper function for determining the number of interleaved accesses we
  10931. /// will generate when lowering accesses of the given type.
  10932. unsigned AArch64TargetLowering::getNumInterleavedAccesses(
  10933. VectorType *VecTy, const DataLayout &DL, bool UseScalable) const {
  10934. unsigned VecSize = UseScalable ? Subtarget->getMinSVEVectorSizeInBits() : 128;
  10935. return std::max<unsigned>(1, (DL.getTypeSizeInBits(VecTy) + 127) / VecSize);
  10936. }
  10937. MachineMemOperand::Flags
  10938. AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
  10939. if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
  10940. I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
  10941. return MOStridedAccess;
  10942. return MachineMemOperand::MONone;
  10943. }
  10944. bool AArch64TargetLowering::isLegalInterleavedAccessType(
  10945. VectorType *VecTy, const DataLayout &DL, bool &UseScalable) const {
  10946. unsigned VecSize = DL.getTypeSizeInBits(VecTy);
  10947. unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
  10948. unsigned NumElements = cast<FixedVectorType>(VecTy)->getNumElements();
  10949. UseScalable = false;
  10950. // Ensure the number of vector elements is greater than 1.
  10951. if (NumElements < 2)
  10952. return false;
  10953. // Ensure the element type is legal.
  10954. if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
  10955. return false;
  10956. if (Subtarget->useSVEForFixedLengthVectors() &&
  10957. (VecSize % Subtarget->getMinSVEVectorSizeInBits() == 0 ||
  10958. (VecSize < Subtarget->getMinSVEVectorSizeInBits() &&
  10959. isPowerOf2_32(NumElements) && VecSize > 128))) {
  10960. UseScalable = true;
  10961. return true;
  10962. }
  10963. // Ensure the total vector size is 64 or a multiple of 128. Types larger than
  10964. // 128 will be split into multiple interleaved accesses.
  10965. return VecSize == 64 || VecSize % 128 == 0;
  10966. }
  10967. static ScalableVectorType *getSVEContainerIRType(FixedVectorType *VTy) {
  10968. if (VTy->getElementType() == Type::getDoubleTy(VTy->getContext()))
  10969. return ScalableVectorType::get(VTy->getElementType(), 2);
  10970. if (VTy->getElementType() == Type::getFloatTy(VTy->getContext()))
  10971. return ScalableVectorType::get(VTy->getElementType(), 4);
  10972. if (VTy->getElementType() == Type::getBFloatTy(VTy->getContext()))
  10973. return ScalableVectorType::get(VTy->getElementType(), 8);
  10974. if (VTy->getElementType() == Type::getHalfTy(VTy->getContext()))
  10975. return ScalableVectorType::get(VTy->getElementType(), 8);
  10976. if (VTy->getElementType() == Type::getInt64Ty(VTy->getContext()))
  10977. return ScalableVectorType::get(VTy->getElementType(), 2);
  10978. if (VTy->getElementType() == Type::getInt32Ty(VTy->getContext()))
  10979. return ScalableVectorType::get(VTy->getElementType(), 4);
  10980. if (VTy->getElementType() == Type::getInt16Ty(VTy->getContext()))
  10981. return ScalableVectorType::get(VTy->getElementType(), 8);
  10982. if (VTy->getElementType() == Type::getInt8Ty(VTy->getContext()))
  10983. return ScalableVectorType::get(VTy->getElementType(), 16);
  10984. llvm_unreachable("Cannot handle input vector type");
  10985. }
  10986. /// Lower an interleaved load into a ldN intrinsic.
  10987. ///
  10988. /// E.g. Lower an interleaved load (Factor = 2):
  10989. /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
  10990. /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
  10991. /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
  10992. ///
  10993. /// Into:
  10994. /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
  10995. /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
  10996. /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
  10997. bool AArch64TargetLowering::lowerInterleavedLoad(
  10998. LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
  10999. ArrayRef<unsigned> Indices, unsigned Factor) const {
  11000. assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
  11001. "Invalid interleave factor");
  11002. assert(!Shuffles.empty() && "Empty shufflevector input");
  11003. assert(Shuffles.size() == Indices.size() &&
  11004. "Unmatched number of shufflevectors and indices");
  11005. const DataLayout &DL = LI->getModule()->getDataLayout();
  11006. VectorType *VTy = Shuffles[0]->getType();
  11007. // Skip if we do not have NEON and skip illegal vector types. We can
  11008. // "legalize" wide vector types into multiple interleaved accesses as long as
  11009. // the vector types are divisible by 128.
  11010. bool UseScalable;
  11011. if (!Subtarget->hasNEON() ||
  11012. !isLegalInterleavedAccessType(VTy, DL, UseScalable))
  11013. return false;
  11014. unsigned NumLoads = getNumInterleavedAccesses(VTy, DL, UseScalable);
  11015. auto *FVTy = cast<FixedVectorType>(VTy);
  11016. // A pointer vector can not be the return type of the ldN intrinsics. Need to
  11017. // load integer vectors first and then convert to pointer vectors.
  11018. Type *EltTy = FVTy->getElementType();
  11019. if (EltTy->isPointerTy())
  11020. FVTy =
  11021. FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
  11022. // If we're going to generate more than one load, reset the sub-vector type
  11023. // to something legal.
  11024. FVTy = FixedVectorType::get(FVTy->getElementType(),
  11025. FVTy->getNumElements() / NumLoads);
  11026. auto *LDVTy =
  11027. UseScalable ? cast<VectorType>(getSVEContainerIRType(FVTy)) : FVTy;
  11028. IRBuilder<> Builder(LI);
  11029. // The base address of the load.
  11030. Value *BaseAddr = LI->getPointerOperand();
  11031. if (NumLoads > 1) {
  11032. // We will compute the pointer operand of each load from the original base
  11033. // address using GEPs. Cast the base address to a pointer to the scalar
  11034. // element type.
  11035. BaseAddr = Builder.CreateBitCast(
  11036. BaseAddr,
  11037. LDVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
  11038. }
  11039. Type *PtrTy =
  11040. UseScalable
  11041. ? LDVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace())
  11042. : LDVTy->getPointerTo(LI->getPointerAddressSpace());
  11043. Type *PredTy = VectorType::get(Type::getInt1Ty(LDVTy->getContext()),
  11044. LDVTy->getElementCount());
  11045. static const Intrinsic::ID SVELoadIntrs[3] = {
  11046. Intrinsic::aarch64_sve_ld2_sret, Intrinsic::aarch64_sve_ld3_sret,
  11047. Intrinsic::aarch64_sve_ld4_sret};
  11048. static const Intrinsic::ID NEONLoadIntrs[3] = {Intrinsic::aarch64_neon_ld2,
  11049. Intrinsic::aarch64_neon_ld3,
  11050. Intrinsic::aarch64_neon_ld4};
  11051. Function *LdNFunc;
  11052. if (UseScalable)
  11053. LdNFunc = Intrinsic::getDeclaration(LI->getModule(),
  11054. SVELoadIntrs[Factor - 2], {LDVTy});
  11055. else
  11056. LdNFunc = Intrinsic::getDeclaration(
  11057. LI->getModule(), NEONLoadIntrs[Factor - 2], {LDVTy, PtrTy});
  11058. // Holds sub-vectors extracted from the load intrinsic return values. The
  11059. // sub-vectors are associated with the shufflevector instructions they will
  11060. // replace.
  11061. DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
  11062. Value *PTrue = nullptr;
  11063. if (UseScalable) {
  11064. Optional<unsigned> PgPattern =
  11065. getSVEPredPatternFromNumElements(FVTy->getNumElements());
  11066. if (Subtarget->getMinSVEVectorSizeInBits() ==
  11067. Subtarget->getMaxSVEVectorSizeInBits() &&
  11068. Subtarget->getMinSVEVectorSizeInBits() == DL.getTypeSizeInBits(FVTy))
  11069. PgPattern = AArch64SVEPredPattern::all;
  11070. auto *PTruePat =
  11071. ConstantInt::get(Type::getInt32Ty(LDVTy->getContext()), *PgPattern);
  11072. PTrue = Builder.CreateIntrinsic(Intrinsic::aarch64_sve_ptrue, {PredTy},
  11073. {PTruePat});
  11074. }
  11075. for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
  11076. // If we're generating more than one load, compute the base address of
  11077. // subsequent loads as an offset from the previous.
  11078. if (LoadCount > 0)
  11079. BaseAddr = Builder.CreateConstGEP1_32(LDVTy->getElementType(), BaseAddr,
  11080. FVTy->getNumElements() * Factor);
  11081. CallInst *LdN;
  11082. if (UseScalable)
  11083. LdN = Builder.CreateCall(
  11084. LdNFunc, {PTrue, Builder.CreateBitCast(BaseAddr, PtrTy)}, "ldN");
  11085. else
  11086. LdN = Builder.CreateCall(LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy),
  11087. "ldN");
  11088. // Extract and store the sub-vectors returned by the load intrinsic.
  11089. for (unsigned i = 0; i < Shuffles.size(); i++) {
  11090. ShuffleVectorInst *SVI = Shuffles[i];
  11091. unsigned Index = Indices[i];
  11092. Value *SubVec = Builder.CreateExtractValue(LdN, Index);
  11093. if (UseScalable)
  11094. SubVec = Builder.CreateExtractVector(
  11095. FVTy, SubVec,
  11096. ConstantInt::get(Type::getInt64Ty(VTy->getContext()), 0));
  11097. // Convert the integer vector to pointer vector if the element is pointer.
  11098. if (EltTy->isPointerTy())
  11099. SubVec = Builder.CreateIntToPtr(
  11100. SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
  11101. FVTy->getNumElements()));
  11102. SubVecs[SVI].push_back(SubVec);
  11103. }
  11104. }
  11105. // Replace uses of the shufflevector instructions with the sub-vectors
  11106. // returned by the load intrinsic. If a shufflevector instruction is
  11107. // associated with more than one sub-vector, those sub-vectors will be
  11108. // concatenated into a single wide vector.
  11109. for (ShuffleVectorInst *SVI : Shuffles) {
  11110. auto &SubVec = SubVecs[SVI];
  11111. auto *WideVec =
  11112. SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
  11113. SVI->replaceAllUsesWith(WideVec);
  11114. }
  11115. return true;
  11116. }
  11117. /// Lower an interleaved store into a stN intrinsic.
  11118. ///
  11119. /// E.g. Lower an interleaved store (Factor = 3):
  11120. /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
  11121. /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
  11122. /// store <12 x i32> %i.vec, <12 x i32>* %ptr
  11123. ///
  11124. /// Into:
  11125. /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
  11126. /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
  11127. /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
  11128. /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
  11129. ///
  11130. /// Note that the new shufflevectors will be removed and we'll only generate one
  11131. /// st3 instruction in CodeGen.
  11132. ///
  11133. /// Example for a more general valid mask (Factor 3). Lower:
  11134. /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
  11135. /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
  11136. /// store <12 x i32> %i.vec, <12 x i32>* %ptr
  11137. ///
  11138. /// Into:
  11139. /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
  11140. /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
  11141. /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
  11142. /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
  11143. bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
  11144. ShuffleVectorInst *SVI,
  11145. unsigned Factor) const {
  11146. assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
  11147. "Invalid interleave factor");
  11148. auto *VecTy = cast<FixedVectorType>(SVI->getType());
  11149. assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
  11150. unsigned LaneLen = VecTy->getNumElements() / Factor;
  11151. Type *EltTy = VecTy->getElementType();
  11152. auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
  11153. const DataLayout &DL = SI->getModule()->getDataLayout();
  11154. bool UseScalable;
  11155. // Skip if we do not have NEON and skip illegal vector types. We can
  11156. // "legalize" wide vector types into multiple interleaved accesses as long as
  11157. // the vector types are divisible by 128.
  11158. if (!Subtarget->hasNEON() ||
  11159. !isLegalInterleavedAccessType(SubVecTy, DL, UseScalable))
  11160. return false;
  11161. unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL, UseScalable);
  11162. Value *Op0 = SVI->getOperand(0);
  11163. Value *Op1 = SVI->getOperand(1);
  11164. IRBuilder<> Builder(SI);
  11165. // StN intrinsics don't support pointer vectors as arguments. Convert pointer
  11166. // vectors to integer vectors.
  11167. if (EltTy->isPointerTy()) {
  11168. Type *IntTy = DL.getIntPtrType(EltTy);
  11169. unsigned NumOpElts =
  11170. cast<FixedVectorType>(Op0->getType())->getNumElements();
  11171. // Convert to the corresponding integer vector.
  11172. auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
  11173. Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
  11174. Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
  11175. SubVecTy = FixedVectorType::get(IntTy, LaneLen);
  11176. }
  11177. // If we're going to generate more than one store, reset the lane length
  11178. // and sub-vector type to something legal.
  11179. LaneLen /= NumStores;
  11180. SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
  11181. auto *STVTy = UseScalable ? cast<VectorType>(getSVEContainerIRType(SubVecTy))
  11182. : SubVecTy;
  11183. // The base address of the store.
  11184. Value *BaseAddr = SI->getPointerOperand();
  11185. if (NumStores > 1) {
  11186. // We will compute the pointer operand of each store from the original base
  11187. // address using GEPs. Cast the base address to a pointer to the scalar
  11188. // element type.
  11189. BaseAddr = Builder.CreateBitCast(
  11190. BaseAddr,
  11191. SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
  11192. }
  11193. auto Mask = SVI->getShuffleMask();
  11194. Type *PtrTy =
  11195. UseScalable
  11196. ? STVTy->getElementType()->getPointerTo(SI->getPointerAddressSpace())
  11197. : STVTy->getPointerTo(SI->getPointerAddressSpace());
  11198. Type *PredTy = VectorType::get(Type::getInt1Ty(STVTy->getContext()),
  11199. STVTy->getElementCount());
  11200. static const Intrinsic::ID SVEStoreIntrs[3] = {Intrinsic::aarch64_sve_st2,
  11201. Intrinsic::aarch64_sve_st3,
  11202. Intrinsic::aarch64_sve_st4};
  11203. static const Intrinsic::ID NEONStoreIntrs[3] = {Intrinsic::aarch64_neon_st2,
  11204. Intrinsic::aarch64_neon_st3,
  11205. Intrinsic::aarch64_neon_st4};
  11206. Function *StNFunc;
  11207. if (UseScalable)
  11208. StNFunc = Intrinsic::getDeclaration(SI->getModule(),
  11209. SVEStoreIntrs[Factor - 2], {STVTy});
  11210. else
  11211. StNFunc = Intrinsic::getDeclaration(
  11212. SI->getModule(), NEONStoreIntrs[Factor - 2], {STVTy, PtrTy});
  11213. Value *PTrue = nullptr;
  11214. if (UseScalable) {
  11215. Optional<unsigned> PgPattern =
  11216. getSVEPredPatternFromNumElements(SubVecTy->getNumElements());
  11217. if (Subtarget->getMinSVEVectorSizeInBits() ==
  11218. Subtarget->getMaxSVEVectorSizeInBits() &&
  11219. Subtarget->getMinSVEVectorSizeInBits() ==
  11220. DL.getTypeSizeInBits(SubVecTy))
  11221. PgPattern = AArch64SVEPredPattern::all;
  11222. auto *PTruePat =
  11223. ConstantInt::get(Type::getInt32Ty(STVTy->getContext()), *PgPattern);
  11224. PTrue = Builder.CreateIntrinsic(Intrinsic::aarch64_sve_ptrue, {PredTy},
  11225. {PTruePat});
  11226. }
  11227. for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
  11228. SmallVector<Value *, 5> Ops;
  11229. // Split the shufflevector operands into sub vectors for the new stN call.
  11230. for (unsigned i = 0; i < Factor; i++) {
  11231. Value *Shuffle;
  11232. unsigned IdxI = StoreCount * LaneLen * Factor + i;
  11233. if (Mask[IdxI] >= 0) {
  11234. Shuffle = Builder.CreateShuffleVector(
  11235. Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0));
  11236. } else {
  11237. unsigned StartMask = 0;
  11238. for (unsigned j = 1; j < LaneLen; j++) {
  11239. unsigned IdxJ = StoreCount * LaneLen * Factor + j;
  11240. if (Mask[IdxJ * Factor + IdxI] >= 0) {
  11241. StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
  11242. break;
  11243. }
  11244. }
  11245. // Note: Filling undef gaps with random elements is ok, since
  11246. // those elements were being written anyway (with undefs).
  11247. // In the case of all undefs we're defaulting to using elems from 0
  11248. // Note: StartMask cannot be negative, it's checked in
  11249. // isReInterleaveMask
  11250. Shuffle = Builder.CreateShuffleVector(
  11251. Op0, Op1, createSequentialMask(StartMask, LaneLen, 0));
  11252. }
  11253. if (UseScalable)
  11254. Shuffle = Builder.CreateInsertVector(
  11255. STVTy, UndefValue::get(STVTy), Shuffle,
  11256. ConstantInt::get(Type::getInt64Ty(STVTy->getContext()), 0));
  11257. Ops.push_back(Shuffle);
  11258. }
  11259. if (UseScalable)
  11260. Ops.push_back(PTrue);
  11261. // If we generating more than one store, we compute the base address of
  11262. // subsequent stores as an offset from the previous.
  11263. if (StoreCount > 0)
  11264. BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
  11265. BaseAddr, LaneLen * Factor);
  11266. Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
  11267. Builder.CreateCall(StNFunc, Ops);
  11268. }
  11269. return true;
  11270. }
  11271. // Lower an SVE structured load intrinsic returning a tuple type to target
  11272. // specific intrinsic taking the same input but returning a multi-result value
  11273. // of the split tuple type.
  11274. //
  11275. // E.g. Lowering an LD3:
  11276. //
  11277. // call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
  11278. // <vscale x 4 x i1> %pred,
  11279. // <vscale x 4 x i32>* %addr)
  11280. //
  11281. // Output DAG:
  11282. //
  11283. // t0: ch = EntryToken
  11284. // t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
  11285. // t4: i64,ch = CopyFromReg t0, Register:i64 %1
  11286. // t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
  11287. // t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
  11288. //
  11289. // This is called pre-legalization to avoid widening/splitting issues with
  11290. // non-power-of-2 tuple types used for LD3, such as nxv12i32.
  11291. SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
  11292. ArrayRef<SDValue> LoadOps,
  11293. EVT VT, SelectionDAG &DAG,
  11294. const SDLoc &DL) const {
  11295. assert(VT.isScalableVector() && "Can only lower scalable vectors");
  11296. unsigned N, Opcode;
  11297. static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
  11298. {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
  11299. {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
  11300. {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
  11301. std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
  11302. assert(VT.getVectorElementCount().getKnownMinValue() % N == 0 &&
  11303. "invalid tuple vector type!");
  11304. EVT SplitVT =
  11305. EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
  11306. VT.getVectorElementCount().divideCoefficientBy(N));
  11307. assert(isTypeLegal(SplitVT));
  11308. SmallVector<EVT, 5> VTs(N, SplitVT);
  11309. VTs.push_back(MVT::Other); // Chain
  11310. SDVTList NodeTys = DAG.getVTList(VTs);
  11311. SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
  11312. SmallVector<SDValue, 4> PseudoLoadOps;
  11313. for (unsigned I = 0; I < N; ++I)
  11314. PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
  11315. return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
  11316. }
  11317. EVT AArch64TargetLowering::getOptimalMemOpType(
  11318. const MemOp &Op, const AttributeList &FuncAttributes) const {
  11319. bool CanImplicitFloat = !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat);
  11320. bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
  11321. bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
  11322. // Only use AdvSIMD to implement memset of 32-byte and above. It would have
  11323. // taken one instruction to materialize the v2i64 zero and one store (with
  11324. // restrictive addressing mode). Just do i64 stores.
  11325. bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
  11326. auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
  11327. if (Op.isAligned(AlignCheck))
  11328. return true;
  11329. bool Fast;
  11330. return allowsMisalignedMemoryAccesses(VT, 0, Align(1),
  11331. MachineMemOperand::MONone, &Fast) &&
  11332. Fast;
  11333. };
  11334. if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
  11335. AlignmentIsAcceptable(MVT::v16i8, Align(16)))
  11336. return MVT::v16i8;
  11337. if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
  11338. return MVT::f128;
  11339. if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
  11340. return MVT::i64;
  11341. if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
  11342. return MVT::i32;
  11343. return MVT::Other;
  11344. }
  11345. LLT AArch64TargetLowering::getOptimalMemOpLLT(
  11346. const MemOp &Op, const AttributeList &FuncAttributes) const {
  11347. bool CanImplicitFloat = !FuncAttributes.hasFnAttr(Attribute::NoImplicitFloat);
  11348. bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
  11349. bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
  11350. // Only use AdvSIMD to implement memset of 32-byte and above. It would have
  11351. // taken one instruction to materialize the v2i64 zero and one store (with
  11352. // restrictive addressing mode). Just do i64 stores.
  11353. bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
  11354. auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
  11355. if (Op.isAligned(AlignCheck))
  11356. return true;
  11357. bool Fast;
  11358. return allowsMisalignedMemoryAccesses(VT, 0, Align(1),
  11359. MachineMemOperand::MONone, &Fast) &&
  11360. Fast;
  11361. };
  11362. if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
  11363. AlignmentIsAcceptable(MVT::v2i64, Align(16)))
  11364. return LLT::fixed_vector(2, 64);
  11365. if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
  11366. return LLT::scalar(128);
  11367. if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
  11368. return LLT::scalar(64);
  11369. if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
  11370. return LLT::scalar(32);
  11371. return LLT();
  11372. }
  11373. // 12-bit optionally shifted immediates are legal for adds.
  11374. bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
  11375. if (Immed == std::numeric_limits<int64_t>::min()) {
  11376. LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
  11377. << ": avoid UB for INT64_MIN\n");
  11378. return false;
  11379. }
  11380. // Same encoding for add/sub, just flip the sign.
  11381. Immed = std::abs(Immed);
  11382. bool IsLegal = ((Immed >> 12) == 0 ||
  11383. ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
  11384. LLVM_DEBUG(dbgs() << "Is " << Immed
  11385. << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
  11386. return IsLegal;
  11387. }
  11388. // Return false to prevent folding
  11389. // (mul (add x, c1), c2) -> (add (mul x, c2), c2*c1) in DAGCombine,
  11390. // if the folding leads to worse code.
  11391. bool AArch64TargetLowering::isMulAddWithConstProfitable(
  11392. const SDValue &AddNode, const SDValue &ConstNode) const {
  11393. // Let the DAGCombiner decide for vector types and large types.
  11394. const EVT VT = AddNode.getValueType();
  11395. if (VT.isVector() || VT.getScalarSizeInBits() > 64)
  11396. return true;
  11397. // It is worse if c1 is legal add immediate, while c1*c2 is not
  11398. // and has to be composed by at least two instructions.
  11399. const ConstantSDNode *C1Node = cast<ConstantSDNode>(AddNode.getOperand(1));
  11400. const ConstantSDNode *C2Node = cast<ConstantSDNode>(ConstNode);
  11401. const int64_t C1 = C1Node->getSExtValue();
  11402. const APInt C1C2 = C1Node->getAPIntValue() * C2Node->getAPIntValue();
  11403. if (!isLegalAddImmediate(C1) || isLegalAddImmediate(C1C2.getSExtValue()))
  11404. return true;
  11405. SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
  11406. AArch64_IMM::expandMOVImm(C1C2.getZExtValue(), VT.getSizeInBits(), Insn);
  11407. if (Insn.size() > 1)
  11408. return false;
  11409. // Default to true and let the DAGCombiner decide.
  11410. return true;
  11411. }
  11412. // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
  11413. // immediates is the same as for an add or a sub.
  11414. bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
  11415. return isLegalAddImmediate(Immed);
  11416. }
  11417. /// isLegalAddressingMode - Return true if the addressing mode represented
  11418. /// by AM is legal for this target, for a load/store of the specified type.
  11419. bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
  11420. const AddrMode &AM, Type *Ty,
  11421. unsigned AS, Instruction *I) const {
  11422. // AArch64 has five basic addressing modes:
  11423. // reg
  11424. // reg + 9-bit signed offset
  11425. // reg + SIZE_IN_BYTES * 12-bit unsigned offset
  11426. // reg1 + reg2
  11427. // reg + SIZE_IN_BYTES * reg
  11428. // No global is ever allowed as a base.
  11429. if (AM.BaseGV)
  11430. return false;
  11431. // No reg+reg+imm addressing.
  11432. if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
  11433. return false;
  11434. // FIXME: Update this method to support scalable addressing modes.
  11435. if (isa<ScalableVectorType>(Ty)) {
  11436. uint64_t VecElemNumBytes =
  11437. DL.getTypeSizeInBits(cast<VectorType>(Ty)->getElementType()) / 8;
  11438. return AM.HasBaseReg && !AM.BaseOffs &&
  11439. (AM.Scale == 0 || (uint64_t)AM.Scale == VecElemNumBytes);
  11440. }
  11441. // check reg + imm case:
  11442. // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
  11443. uint64_t NumBytes = 0;
  11444. if (Ty->isSized()) {
  11445. uint64_t NumBits = DL.getTypeSizeInBits(Ty);
  11446. NumBytes = NumBits / 8;
  11447. if (!isPowerOf2_64(NumBits))
  11448. NumBytes = 0;
  11449. }
  11450. if (!AM.Scale) {
  11451. int64_t Offset = AM.BaseOffs;
  11452. // 9-bit signed offset
  11453. if (isInt<9>(Offset))
  11454. return true;
  11455. // 12-bit unsigned offset
  11456. unsigned shift = Log2_64(NumBytes);
  11457. if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
  11458. // Must be a multiple of NumBytes (NumBytes is a power of 2)
  11459. (Offset >> shift) << shift == Offset)
  11460. return true;
  11461. return false;
  11462. }
  11463. // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
  11464. return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
  11465. }
  11466. bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
  11467. // Consider splitting large offset of struct or array.
  11468. return true;
  11469. }
  11470. InstructionCost AArch64TargetLowering::getScalingFactorCost(
  11471. const DataLayout &DL, const AddrMode &AM, Type *Ty, unsigned AS) const {
  11472. // Scaling factors are not free at all.
  11473. // Operands | Rt Latency
  11474. // -------------------------------------------
  11475. // Rt, [Xn, Xm] | 4
  11476. // -------------------------------------------
  11477. // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
  11478. // Rt, [Xn, Wm, <extend> #imm] |
  11479. if (isLegalAddressingMode(DL, AM, Ty, AS))
  11480. // Scale represents reg2 * scale, thus account for 1 if
  11481. // it is not equal to 0 or 1.
  11482. return AM.Scale != 0 && AM.Scale != 1;
  11483. return -1;
  11484. }
  11485. bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
  11486. const MachineFunction &MF, EVT VT) const {
  11487. VT = VT.getScalarType();
  11488. if (!VT.isSimple())
  11489. return false;
  11490. switch (VT.getSimpleVT().SimpleTy) {
  11491. case MVT::f16:
  11492. return Subtarget->hasFullFP16();
  11493. case MVT::f32:
  11494. case MVT::f64:
  11495. return true;
  11496. default:
  11497. break;
  11498. }
  11499. return false;
  11500. }
  11501. bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
  11502. Type *Ty) const {
  11503. switch (Ty->getScalarType()->getTypeID()) {
  11504. case Type::FloatTyID:
  11505. case Type::DoubleTyID:
  11506. return true;
  11507. default:
  11508. return false;
  11509. }
  11510. }
  11511. bool AArch64TargetLowering::generateFMAsInMachineCombiner(
  11512. EVT VT, CodeGenOpt::Level OptLevel) const {
  11513. return (OptLevel >= CodeGenOpt::Aggressive) && !VT.isScalableVector() &&
  11514. !useSVEForFixedLengthVectorVT(VT);
  11515. }
  11516. const MCPhysReg *
  11517. AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
  11518. // LR is a callee-save register, but we must treat it as clobbered by any call
  11519. // site. Hence we include LR in the scratch registers, which are in turn added
  11520. // as implicit-defs for stackmaps and patchpoints.
  11521. static const MCPhysReg ScratchRegs[] = {
  11522. AArch64::X16, AArch64::X17, AArch64::LR, 0
  11523. };
  11524. return ScratchRegs;
  11525. }
  11526. bool
  11527. AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
  11528. CombineLevel Level) const {
  11529. N = N->getOperand(0).getNode();
  11530. EVT VT = N->getValueType(0);
  11531. // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
  11532. // it with shift to let it be lowered to UBFX.
  11533. if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
  11534. isa<ConstantSDNode>(N->getOperand(1))) {
  11535. uint64_t TruncMask = N->getConstantOperandVal(1);
  11536. if (isMask_64(TruncMask) &&
  11537. N->getOperand(0).getOpcode() == ISD::SRL &&
  11538. isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
  11539. return false;
  11540. }
  11541. return true;
  11542. }
  11543. bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
  11544. Type *Ty) const {
  11545. assert(Ty->isIntegerTy());
  11546. unsigned BitSize = Ty->getPrimitiveSizeInBits();
  11547. if (BitSize == 0)
  11548. return false;
  11549. int64_t Val = Imm.getSExtValue();
  11550. if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
  11551. return true;
  11552. if ((int64_t)Val < 0)
  11553. Val = ~Val;
  11554. if (BitSize == 32)
  11555. Val &= (1LL << 32) - 1;
  11556. unsigned LZ = countLeadingZeros((uint64_t)Val);
  11557. unsigned Shift = (63 - LZ) / 16;
  11558. // MOVZ is free so return true for one or fewer MOVK.
  11559. return Shift < 3;
  11560. }
  11561. bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
  11562. unsigned Index) const {
  11563. if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
  11564. return false;
  11565. return (Index == 0 || Index == ResVT.getVectorMinNumElements());
  11566. }
  11567. /// Turn vector tests of the signbit in the form of:
  11568. /// xor (sra X, elt_size(X)-1), -1
  11569. /// into:
  11570. /// cmge X, X, #0
  11571. static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
  11572. const AArch64Subtarget *Subtarget) {
  11573. EVT VT = N->getValueType(0);
  11574. if (!Subtarget->hasNEON() || !VT.isVector())
  11575. return SDValue();
  11576. // There must be a shift right algebraic before the xor, and the xor must be a
  11577. // 'not' operation.
  11578. SDValue Shift = N->getOperand(0);
  11579. SDValue Ones = N->getOperand(1);
  11580. if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
  11581. !ISD::isBuildVectorAllOnes(Ones.getNode()))
  11582. return SDValue();
  11583. // The shift should be smearing the sign bit across each vector element.
  11584. auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
  11585. EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
  11586. if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
  11587. return SDValue();
  11588. return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
  11589. }
  11590. // Given a vecreduce_add node, detect the below pattern and convert it to the
  11591. // node sequence with UABDL, [S|U]ADB and UADDLP.
  11592. //
  11593. // i32 vecreduce_add(
  11594. // v16i32 abs(
  11595. // v16i32 sub(
  11596. // v16i32 [sign|zero]_extend(v16i8 a), v16i32 [sign|zero]_extend(v16i8 b))))
  11597. // =================>
  11598. // i32 vecreduce_add(
  11599. // v4i32 UADDLP(
  11600. // v8i16 add(
  11601. // v8i16 zext(
  11602. // v8i8 [S|U]ABD low8:v16i8 a, low8:v16i8 b
  11603. // v8i16 zext(
  11604. // v8i8 [S|U]ABD high8:v16i8 a, high8:v16i8 b
  11605. static SDValue performVecReduceAddCombineWithUADDLP(SDNode *N,
  11606. SelectionDAG &DAG) {
  11607. // Assumed i32 vecreduce_add
  11608. if (N->getValueType(0) != MVT::i32)
  11609. return SDValue();
  11610. SDValue VecReduceOp0 = N->getOperand(0);
  11611. unsigned Opcode = VecReduceOp0.getOpcode();
  11612. // Assumed v16i32 abs
  11613. if (Opcode != ISD::ABS || VecReduceOp0->getValueType(0) != MVT::v16i32)
  11614. return SDValue();
  11615. SDValue ABS = VecReduceOp0;
  11616. // Assumed v16i32 sub
  11617. if (ABS->getOperand(0)->getOpcode() != ISD::SUB ||
  11618. ABS->getOperand(0)->getValueType(0) != MVT::v16i32)
  11619. return SDValue();
  11620. SDValue SUB = ABS->getOperand(0);
  11621. unsigned Opcode0 = SUB->getOperand(0).getOpcode();
  11622. unsigned Opcode1 = SUB->getOperand(1).getOpcode();
  11623. // Assumed v16i32 type
  11624. if (SUB->getOperand(0)->getValueType(0) != MVT::v16i32 ||
  11625. SUB->getOperand(1)->getValueType(0) != MVT::v16i32)
  11626. return SDValue();
  11627. // Assumed zext or sext
  11628. bool IsZExt = false;
  11629. if (Opcode0 == ISD::ZERO_EXTEND && Opcode1 == ISD::ZERO_EXTEND) {
  11630. IsZExt = true;
  11631. } else if (Opcode0 == ISD::SIGN_EXTEND && Opcode1 == ISD::SIGN_EXTEND) {
  11632. IsZExt = false;
  11633. } else
  11634. return SDValue();
  11635. SDValue EXT0 = SUB->getOperand(0);
  11636. SDValue EXT1 = SUB->getOperand(1);
  11637. // Assumed zext's operand has v16i8 type
  11638. if (EXT0->getOperand(0)->getValueType(0) != MVT::v16i8 ||
  11639. EXT1->getOperand(0)->getValueType(0) != MVT::v16i8)
  11640. return SDValue();
  11641. // Pattern is dectected. Let's convert it to sequence of nodes.
  11642. SDLoc DL(N);
  11643. // First, create the node pattern of UABD/SABD.
  11644. SDValue UABDHigh8Op0 =
  11645. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT0->getOperand(0),
  11646. DAG.getConstant(8, DL, MVT::i64));
  11647. SDValue UABDHigh8Op1 =
  11648. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT1->getOperand(0),
  11649. DAG.getConstant(8, DL, MVT::i64));
  11650. SDValue UABDHigh8 = DAG.getNode(IsZExt ? ISD::ABDU : ISD::ABDS, DL, MVT::v8i8,
  11651. UABDHigh8Op0, UABDHigh8Op1);
  11652. SDValue UABDL = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, UABDHigh8);
  11653. // Second, create the node pattern of UABAL.
  11654. SDValue UABDLo8Op0 =
  11655. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT0->getOperand(0),
  11656. DAG.getConstant(0, DL, MVT::i64));
  11657. SDValue UABDLo8Op1 =
  11658. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, MVT::v8i8, EXT1->getOperand(0),
  11659. DAG.getConstant(0, DL, MVT::i64));
  11660. SDValue UABDLo8 = DAG.getNode(IsZExt ? ISD::ABDU : ISD::ABDS, DL, MVT::v8i8,
  11661. UABDLo8Op0, UABDLo8Op1);
  11662. SDValue ZExtUABD = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::v8i16, UABDLo8);
  11663. SDValue UABAL = DAG.getNode(ISD::ADD, DL, MVT::v8i16, UABDL, ZExtUABD);
  11664. // Third, create the node of UADDLP.
  11665. SDValue UADDLP = DAG.getNode(AArch64ISD::UADDLP, DL, MVT::v4i32, UABAL);
  11666. // Fourth, create the node of VECREDUCE_ADD.
  11667. return DAG.getNode(ISD::VECREDUCE_ADD, DL, MVT::i32, UADDLP);
  11668. }
  11669. // Turn a v8i8/v16i8 extended vecreduce into a udot/sdot and vecreduce
  11670. // vecreduce.add(ext(A)) to vecreduce.add(DOT(zero, A, one))
  11671. // vecreduce.add(mul(ext(A), ext(B))) to vecreduce.add(DOT(zero, A, B))
  11672. static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG,
  11673. const AArch64Subtarget *ST) {
  11674. if (!ST->hasDotProd())
  11675. return performVecReduceAddCombineWithUADDLP(N, DAG);
  11676. SDValue Op0 = N->getOperand(0);
  11677. if (N->getValueType(0) != MVT::i32 ||
  11678. Op0.getValueType().getVectorElementType() != MVT::i32)
  11679. return SDValue();
  11680. unsigned ExtOpcode = Op0.getOpcode();
  11681. SDValue A = Op0;
  11682. SDValue B;
  11683. if (ExtOpcode == ISD::MUL) {
  11684. A = Op0.getOperand(0);
  11685. B = Op0.getOperand(1);
  11686. if (A.getOpcode() != B.getOpcode() ||
  11687. A.getOperand(0).getValueType() != B.getOperand(0).getValueType())
  11688. return SDValue();
  11689. ExtOpcode = A.getOpcode();
  11690. }
  11691. if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND)
  11692. return SDValue();
  11693. EVT Op0VT = A.getOperand(0).getValueType();
  11694. if (Op0VT != MVT::v8i8 && Op0VT != MVT::v16i8)
  11695. return SDValue();
  11696. SDLoc DL(Op0);
  11697. // For non-mla reductions B can be set to 1. For MLA we take the operand of
  11698. // the extend B.
  11699. if (!B)
  11700. B = DAG.getConstant(1, DL, Op0VT);
  11701. else
  11702. B = B.getOperand(0);
  11703. SDValue Zeros =
  11704. DAG.getConstant(0, DL, Op0VT == MVT::v8i8 ? MVT::v2i32 : MVT::v4i32);
  11705. auto DotOpcode =
  11706. (ExtOpcode == ISD::ZERO_EXTEND) ? AArch64ISD::UDOT : AArch64ISD::SDOT;
  11707. SDValue Dot = DAG.getNode(DotOpcode, DL, Zeros.getValueType(), Zeros,
  11708. A.getOperand(0), B);
  11709. return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot);
  11710. }
  11711. static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
  11712. TargetLowering::DAGCombinerInfo &DCI,
  11713. const AArch64Subtarget *Subtarget) {
  11714. if (DCI.isBeforeLegalizeOps())
  11715. return SDValue();
  11716. return foldVectorXorShiftIntoCmp(N, DAG, Subtarget);
  11717. }
  11718. SDValue
  11719. AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
  11720. SelectionDAG &DAG,
  11721. SmallVectorImpl<SDNode *> &Created) const {
  11722. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  11723. if (isIntDivCheap(N->getValueType(0), Attr))
  11724. return SDValue(N,0); // Lower SDIV as SDIV
  11725. EVT VT = N->getValueType(0);
  11726. // For scalable and fixed types, mark them as cheap so we can handle it much
  11727. // later. This allows us to handle larger than legal types.
  11728. if (VT.isScalableVector() || Subtarget->useSVEForFixedLengthVectors())
  11729. return SDValue(N, 0);
  11730. // fold (sdiv X, pow2)
  11731. if ((VT != MVT::i32 && VT != MVT::i64) ||
  11732. !(Divisor.isPowerOf2() || Divisor.isNegatedPowerOf2()))
  11733. return SDValue();
  11734. SDLoc DL(N);
  11735. SDValue N0 = N->getOperand(0);
  11736. unsigned Lg2 = Divisor.countTrailingZeros();
  11737. SDValue Zero = DAG.getConstant(0, DL, VT);
  11738. SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
  11739. // Add (N0 < 0) ? Pow2 - 1 : 0;
  11740. SDValue CCVal;
  11741. SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
  11742. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
  11743. SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
  11744. Created.push_back(Cmp.getNode());
  11745. Created.push_back(Add.getNode());
  11746. Created.push_back(CSel.getNode());
  11747. // Divide by pow2.
  11748. SDValue SRA =
  11749. DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
  11750. // If we're dividing by a positive value, we're done. Otherwise, we must
  11751. // negate the result.
  11752. if (Divisor.isNonNegative())
  11753. return SRA;
  11754. Created.push_back(SRA.getNode());
  11755. return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
  11756. }
  11757. static bool IsSVECntIntrinsic(SDValue S) {
  11758. switch(getIntrinsicID(S.getNode())) {
  11759. default:
  11760. break;
  11761. case Intrinsic::aarch64_sve_cntb:
  11762. case Intrinsic::aarch64_sve_cnth:
  11763. case Intrinsic::aarch64_sve_cntw:
  11764. case Intrinsic::aarch64_sve_cntd:
  11765. return true;
  11766. }
  11767. return false;
  11768. }
  11769. /// Calculates what the pre-extend type is, based on the extension
  11770. /// operation node provided by \p Extend.
  11771. ///
  11772. /// In the case that \p Extend is a SIGN_EXTEND or a ZERO_EXTEND, the
  11773. /// pre-extend type is pulled directly from the operand, while other extend
  11774. /// operations need a bit more inspection to get this information.
  11775. ///
  11776. /// \param Extend The SDNode from the DAG that represents the extend operation
  11777. /// \param DAG The SelectionDAG hosting the \p Extend node
  11778. ///
  11779. /// \returns The type representing the \p Extend source type, or \p MVT::Other
  11780. /// if no valid type can be determined
  11781. static EVT calculatePreExtendType(SDValue Extend, SelectionDAG &DAG) {
  11782. switch (Extend.getOpcode()) {
  11783. case ISD::SIGN_EXTEND:
  11784. case ISD::ZERO_EXTEND:
  11785. return Extend.getOperand(0).getValueType();
  11786. case ISD::AssertSext:
  11787. case ISD::AssertZext:
  11788. case ISD::SIGN_EXTEND_INREG: {
  11789. VTSDNode *TypeNode = dyn_cast<VTSDNode>(Extend.getOperand(1));
  11790. if (!TypeNode)
  11791. return MVT::Other;
  11792. return TypeNode->getVT();
  11793. }
  11794. case ISD::AND: {
  11795. ConstantSDNode *Constant =
  11796. dyn_cast<ConstantSDNode>(Extend.getOperand(1).getNode());
  11797. if (!Constant)
  11798. return MVT::Other;
  11799. uint32_t Mask = Constant->getZExtValue();
  11800. if (Mask == UCHAR_MAX)
  11801. return MVT::i8;
  11802. else if (Mask == USHRT_MAX)
  11803. return MVT::i16;
  11804. else if (Mask == UINT_MAX)
  11805. return MVT::i32;
  11806. return MVT::Other;
  11807. }
  11808. default:
  11809. return MVT::Other;
  11810. }
  11811. llvm_unreachable("Code path unhandled in calculatePreExtendType!");
  11812. }
  11813. /// Combines a dup(sext/zext) node pattern into sext/zext(dup)
  11814. /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
  11815. static SDValue performCommonVectorExtendCombine(SDValue VectorShuffle,
  11816. SelectionDAG &DAG) {
  11817. ShuffleVectorSDNode *ShuffleNode =
  11818. dyn_cast<ShuffleVectorSDNode>(VectorShuffle.getNode());
  11819. if (!ShuffleNode)
  11820. return SDValue();
  11821. // Ensuring the mask is zero before continuing
  11822. if (!ShuffleNode->isSplat() || ShuffleNode->getSplatIndex() != 0)
  11823. return SDValue();
  11824. SDValue InsertVectorElt = VectorShuffle.getOperand(0);
  11825. if (InsertVectorElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
  11826. return SDValue();
  11827. SDValue InsertLane = InsertVectorElt.getOperand(2);
  11828. ConstantSDNode *Constant = dyn_cast<ConstantSDNode>(InsertLane.getNode());
  11829. // Ensures the insert is inserting into lane 0
  11830. if (!Constant || Constant->getZExtValue() != 0)
  11831. return SDValue();
  11832. SDValue Extend = InsertVectorElt.getOperand(1);
  11833. unsigned ExtendOpcode = Extend.getOpcode();
  11834. bool IsSExt = ExtendOpcode == ISD::SIGN_EXTEND ||
  11835. ExtendOpcode == ISD::SIGN_EXTEND_INREG ||
  11836. ExtendOpcode == ISD::AssertSext;
  11837. if (!IsSExt && ExtendOpcode != ISD::ZERO_EXTEND &&
  11838. ExtendOpcode != ISD::AssertZext && ExtendOpcode != ISD::AND)
  11839. return SDValue();
  11840. EVT TargetType = VectorShuffle.getValueType();
  11841. EVT PreExtendType = calculatePreExtendType(Extend, DAG);
  11842. if ((TargetType != MVT::v8i16 && TargetType != MVT::v4i32 &&
  11843. TargetType != MVT::v2i64) ||
  11844. (PreExtendType == MVT::Other))
  11845. return SDValue();
  11846. // Restrict valid pre-extend data type
  11847. if (PreExtendType != MVT::i8 && PreExtendType != MVT::i16 &&
  11848. PreExtendType != MVT::i32)
  11849. return SDValue();
  11850. EVT PreExtendVT = TargetType.changeVectorElementType(PreExtendType);
  11851. if (PreExtendVT.getVectorElementCount() != TargetType.getVectorElementCount())
  11852. return SDValue();
  11853. if (TargetType.getScalarSizeInBits() != PreExtendVT.getScalarSizeInBits() * 2)
  11854. return SDValue();
  11855. SDLoc DL(VectorShuffle);
  11856. SDValue InsertVectorNode = DAG.getNode(
  11857. InsertVectorElt.getOpcode(), DL, PreExtendVT, DAG.getUNDEF(PreExtendVT),
  11858. DAG.getAnyExtOrTrunc(Extend.getOperand(0), DL, PreExtendType),
  11859. DAG.getConstant(0, DL, MVT::i64));
  11860. std::vector<int> ShuffleMask(TargetType.getVectorNumElements());
  11861. SDValue VectorShuffleNode =
  11862. DAG.getVectorShuffle(PreExtendVT, DL, InsertVectorNode,
  11863. DAG.getUNDEF(PreExtendVT), ShuffleMask);
  11864. SDValue ExtendNode = DAG.getNode(IsSExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
  11865. DL, TargetType, VectorShuffleNode);
  11866. return ExtendNode;
  11867. }
  11868. /// Combines a mul(dup(sext/zext)) node pattern into mul(sext/zext(dup))
  11869. /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
  11870. static SDValue performMulVectorExtendCombine(SDNode *Mul, SelectionDAG &DAG) {
  11871. // If the value type isn't a vector, none of the operands are going to be dups
  11872. if (!Mul->getValueType(0).isVector())
  11873. return SDValue();
  11874. SDValue Op0 = performCommonVectorExtendCombine(Mul->getOperand(0), DAG);
  11875. SDValue Op1 = performCommonVectorExtendCombine(Mul->getOperand(1), DAG);
  11876. // Neither operands have been changed, don't make any further changes
  11877. if (!Op0 && !Op1)
  11878. return SDValue();
  11879. SDLoc DL(Mul);
  11880. return DAG.getNode(Mul->getOpcode(), DL, Mul->getValueType(0),
  11881. Op0 ? Op0 : Mul->getOperand(0),
  11882. Op1 ? Op1 : Mul->getOperand(1));
  11883. }
  11884. static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
  11885. TargetLowering::DAGCombinerInfo &DCI,
  11886. const AArch64Subtarget *Subtarget) {
  11887. if (SDValue Ext = performMulVectorExtendCombine(N, DAG))
  11888. return Ext;
  11889. if (DCI.isBeforeLegalizeOps())
  11890. return SDValue();
  11891. // Canonicalize X*(Y+1) -> X*Y+X and (X+1)*Y -> X*Y+Y,
  11892. // and in MachineCombiner pass, add+mul will be combined into madd.
  11893. // Similarly, X*(1-Y) -> X - X*Y and (1-Y)*X -> X - Y*X.
  11894. SDLoc DL(N);
  11895. EVT VT = N->getValueType(0);
  11896. SDValue N0 = N->getOperand(0);
  11897. SDValue N1 = N->getOperand(1);
  11898. SDValue MulOper;
  11899. unsigned AddSubOpc;
  11900. auto IsAddSubWith1 = [&](SDValue V) -> bool {
  11901. AddSubOpc = V->getOpcode();
  11902. if ((AddSubOpc == ISD::ADD || AddSubOpc == ISD::SUB) && V->hasOneUse()) {
  11903. SDValue Opnd = V->getOperand(1);
  11904. MulOper = V->getOperand(0);
  11905. if (AddSubOpc == ISD::SUB)
  11906. std::swap(Opnd, MulOper);
  11907. if (auto C = dyn_cast<ConstantSDNode>(Opnd))
  11908. return C->isOne();
  11909. }
  11910. return false;
  11911. };
  11912. if (IsAddSubWith1(N0)) {
  11913. SDValue MulVal = DAG.getNode(ISD::MUL, DL, VT, N1, MulOper);
  11914. return DAG.getNode(AddSubOpc, DL, VT, N1, MulVal);
  11915. }
  11916. if (IsAddSubWith1(N1)) {
  11917. SDValue MulVal = DAG.getNode(ISD::MUL, DL, VT, N0, MulOper);
  11918. return DAG.getNode(AddSubOpc, DL, VT, N0, MulVal);
  11919. }
  11920. // The below optimizations require a constant RHS.
  11921. if (!isa<ConstantSDNode>(N1))
  11922. return SDValue();
  11923. ConstantSDNode *C = cast<ConstantSDNode>(N1);
  11924. const APInt &ConstValue = C->getAPIntValue();
  11925. // Allow the scaling to be folded into the `cnt` instruction by preventing
  11926. // the scaling to be obscured here. This makes it easier to pattern match.
  11927. if (IsSVECntIntrinsic(N0) ||
  11928. (N0->getOpcode() == ISD::TRUNCATE &&
  11929. (IsSVECntIntrinsic(N0->getOperand(0)))))
  11930. if (ConstValue.sge(1) && ConstValue.sle(16))
  11931. return SDValue();
  11932. // Multiplication of a power of two plus/minus one can be done more
  11933. // cheaply as as shift+add/sub. For now, this is true unilaterally. If
  11934. // future CPUs have a cheaper MADD instruction, this may need to be
  11935. // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
  11936. // 64-bit is 5 cycles, so this is always a win.
  11937. // More aggressively, some multiplications N0 * C can be lowered to
  11938. // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
  11939. // e.g. 6=3*2=(2+1)*2.
  11940. // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
  11941. // which equals to (1+2)*16-(1+2).
  11942. // TrailingZeroes is used to test if the mul can be lowered to
  11943. // shift+add+shift.
  11944. unsigned TrailingZeroes = ConstValue.countTrailingZeros();
  11945. if (TrailingZeroes) {
  11946. // Conservatively do not lower to shift+add+shift if the mul might be
  11947. // folded into smul or umul.
  11948. if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
  11949. isZeroExtended(N0.getNode(), DAG)))
  11950. return SDValue();
  11951. // Conservatively do not lower to shift+add+shift if the mul might be
  11952. // folded into madd or msub.
  11953. if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
  11954. N->use_begin()->getOpcode() == ISD::SUB))
  11955. return SDValue();
  11956. }
  11957. // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
  11958. // and shift+add+shift.
  11959. APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
  11960. unsigned ShiftAmt;
  11961. // Is the shifted value the LHS operand of the add/sub?
  11962. bool ShiftValUseIsN0 = true;
  11963. // Do we need to negate the result?
  11964. bool NegateResult = false;
  11965. if (ConstValue.isNonNegative()) {
  11966. // (mul x, 2^N + 1) => (add (shl x, N), x)
  11967. // (mul x, 2^N - 1) => (sub (shl x, N), x)
  11968. // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
  11969. APInt SCVMinus1 = ShiftedConstValue - 1;
  11970. APInt CVPlus1 = ConstValue + 1;
  11971. if (SCVMinus1.isPowerOf2()) {
  11972. ShiftAmt = SCVMinus1.logBase2();
  11973. AddSubOpc = ISD::ADD;
  11974. } else if (CVPlus1.isPowerOf2()) {
  11975. ShiftAmt = CVPlus1.logBase2();
  11976. AddSubOpc = ISD::SUB;
  11977. } else
  11978. return SDValue();
  11979. } else {
  11980. // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
  11981. // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
  11982. APInt CVNegPlus1 = -ConstValue + 1;
  11983. APInt CVNegMinus1 = -ConstValue - 1;
  11984. if (CVNegPlus1.isPowerOf2()) {
  11985. ShiftAmt = CVNegPlus1.logBase2();
  11986. AddSubOpc = ISD::SUB;
  11987. ShiftValUseIsN0 = false;
  11988. } else if (CVNegMinus1.isPowerOf2()) {
  11989. ShiftAmt = CVNegMinus1.logBase2();
  11990. AddSubOpc = ISD::ADD;
  11991. NegateResult = true;
  11992. } else
  11993. return SDValue();
  11994. }
  11995. SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
  11996. DAG.getConstant(ShiftAmt, DL, MVT::i64));
  11997. SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
  11998. SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
  11999. SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
  12000. assert(!(NegateResult && TrailingZeroes) &&
  12001. "NegateResult and TrailingZeroes cannot both be true for now.");
  12002. // Negate the result.
  12003. if (NegateResult)
  12004. return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
  12005. // Shift the result.
  12006. if (TrailingZeroes)
  12007. return DAG.getNode(ISD::SHL, DL, VT, Res,
  12008. DAG.getConstant(TrailingZeroes, DL, MVT::i64));
  12009. return Res;
  12010. }
  12011. static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
  12012. SelectionDAG &DAG) {
  12013. // Take advantage of vector comparisons producing 0 or -1 in each lane to
  12014. // optimize away operation when it's from a constant.
  12015. //
  12016. // The general transformation is:
  12017. // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
  12018. // AND(VECTOR_CMP(x,y), constant2)
  12019. // constant2 = UNARYOP(constant)
  12020. // Early exit if this isn't a vector operation, the operand of the
  12021. // unary operation isn't a bitwise AND, or if the sizes of the operations
  12022. // aren't the same.
  12023. EVT VT = N->getValueType(0);
  12024. if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
  12025. N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
  12026. VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
  12027. return SDValue();
  12028. // Now check that the other operand of the AND is a constant. We could
  12029. // make the transformation for non-constant splats as well, but it's unclear
  12030. // that would be a benefit as it would not eliminate any operations, just
  12031. // perform one more step in scalar code before moving to the vector unit.
  12032. if (BuildVectorSDNode *BV =
  12033. dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
  12034. // Bail out if the vector isn't a constant.
  12035. if (!BV->isConstant())
  12036. return SDValue();
  12037. // Everything checks out. Build up the new and improved node.
  12038. SDLoc DL(N);
  12039. EVT IntVT = BV->getValueType(0);
  12040. // Create a new constant of the appropriate type for the transformed
  12041. // DAG.
  12042. SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
  12043. // The AND node needs bitcasts to/from an integer vector type around it.
  12044. SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
  12045. SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
  12046. N->getOperand(0)->getOperand(0), MaskConst);
  12047. SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
  12048. return Res;
  12049. }
  12050. return SDValue();
  12051. }
  12052. static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
  12053. const AArch64Subtarget *Subtarget) {
  12054. // First try to optimize away the conversion when it's conditionally from
  12055. // a constant. Vectors only.
  12056. if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
  12057. return Res;
  12058. EVT VT = N->getValueType(0);
  12059. if (VT != MVT::f32 && VT != MVT::f64)
  12060. return SDValue();
  12061. // Only optimize when the source and destination types have the same width.
  12062. if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
  12063. return SDValue();
  12064. // If the result of an integer load is only used by an integer-to-float
  12065. // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
  12066. // This eliminates an "integer-to-vector-move" UOP and improves throughput.
  12067. SDValue N0 = N->getOperand(0);
  12068. if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
  12069. // Do not change the width of a volatile load.
  12070. !cast<LoadSDNode>(N0)->isVolatile()) {
  12071. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  12072. SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
  12073. LN0->getPointerInfo(), LN0->getAlignment(),
  12074. LN0->getMemOperand()->getFlags());
  12075. // Make sure successors of the original load stay after it by updating them
  12076. // to use the new Chain.
  12077. DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
  12078. unsigned Opcode =
  12079. (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
  12080. return DAG.getNode(Opcode, SDLoc(N), VT, Load);
  12081. }
  12082. return SDValue();
  12083. }
  12084. /// Fold a floating-point multiply by power of two into floating-point to
  12085. /// fixed-point conversion.
  12086. static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
  12087. TargetLowering::DAGCombinerInfo &DCI,
  12088. const AArch64Subtarget *Subtarget) {
  12089. if (!Subtarget->hasNEON())
  12090. return SDValue();
  12091. if (!N->getValueType(0).isSimple())
  12092. return SDValue();
  12093. SDValue Op = N->getOperand(0);
  12094. if (!Op.getValueType().isSimple() || Op.getOpcode() != ISD::FMUL)
  12095. return SDValue();
  12096. if (!Op.getValueType().is64BitVector() && !Op.getValueType().is128BitVector())
  12097. return SDValue();
  12098. SDValue ConstVec = Op->getOperand(1);
  12099. if (!isa<BuildVectorSDNode>(ConstVec))
  12100. return SDValue();
  12101. MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
  12102. uint32_t FloatBits = FloatTy.getSizeInBits();
  12103. if (FloatBits != 32 && FloatBits != 64 &&
  12104. (FloatBits != 16 || !Subtarget->hasFullFP16()))
  12105. return SDValue();
  12106. MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
  12107. uint32_t IntBits = IntTy.getSizeInBits();
  12108. if (IntBits != 16 && IntBits != 32 && IntBits != 64)
  12109. return SDValue();
  12110. // Avoid conversions where iN is larger than the float (e.g., float -> i64).
  12111. if (IntBits > FloatBits)
  12112. return SDValue();
  12113. BitVector UndefElements;
  12114. BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
  12115. int32_t Bits = IntBits == 64 ? 64 : 32;
  12116. int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
  12117. if (C == -1 || C == 0 || C > Bits)
  12118. return SDValue();
  12119. EVT ResTy = Op.getValueType().changeVectorElementTypeToInteger();
  12120. if (!DAG.getTargetLoweringInfo().isTypeLegal(ResTy))
  12121. return SDValue();
  12122. if (N->getOpcode() == ISD::FP_TO_SINT_SAT ||
  12123. N->getOpcode() == ISD::FP_TO_UINT_SAT) {
  12124. EVT SatVT = cast<VTSDNode>(N->getOperand(1))->getVT();
  12125. if (SatVT.getScalarSizeInBits() != IntBits)
  12126. return SDValue();
  12127. }
  12128. SDLoc DL(N);
  12129. bool IsSigned = (N->getOpcode() == ISD::FP_TO_SINT ||
  12130. N->getOpcode() == ISD::FP_TO_SINT_SAT);
  12131. unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
  12132. : Intrinsic::aarch64_neon_vcvtfp2fxu;
  12133. SDValue FixConv =
  12134. DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
  12135. DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
  12136. Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
  12137. // We can handle smaller integers by generating an extra trunc.
  12138. if (IntBits < FloatBits)
  12139. FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
  12140. return FixConv;
  12141. }
  12142. /// Fold a floating-point divide by power of two into fixed-point to
  12143. /// floating-point conversion.
  12144. static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
  12145. TargetLowering::DAGCombinerInfo &DCI,
  12146. const AArch64Subtarget *Subtarget) {
  12147. if (!Subtarget->hasNEON())
  12148. return SDValue();
  12149. SDValue Op = N->getOperand(0);
  12150. unsigned Opc = Op->getOpcode();
  12151. if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
  12152. !Op.getOperand(0).getValueType().isSimple() ||
  12153. (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
  12154. return SDValue();
  12155. SDValue ConstVec = N->getOperand(1);
  12156. if (!isa<BuildVectorSDNode>(ConstVec))
  12157. return SDValue();
  12158. MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
  12159. int32_t IntBits = IntTy.getSizeInBits();
  12160. if (IntBits != 16 && IntBits != 32 && IntBits != 64)
  12161. return SDValue();
  12162. MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
  12163. int32_t FloatBits = FloatTy.getSizeInBits();
  12164. if (FloatBits != 32 && FloatBits != 64)
  12165. return SDValue();
  12166. // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
  12167. if (IntBits > FloatBits)
  12168. return SDValue();
  12169. BitVector UndefElements;
  12170. BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
  12171. int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
  12172. if (C == -1 || C == 0 || C > FloatBits)
  12173. return SDValue();
  12174. MVT ResTy;
  12175. unsigned NumLanes = Op.getValueType().getVectorNumElements();
  12176. switch (NumLanes) {
  12177. default:
  12178. return SDValue();
  12179. case 2:
  12180. ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
  12181. break;
  12182. case 4:
  12183. ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
  12184. break;
  12185. }
  12186. if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
  12187. return SDValue();
  12188. SDLoc DL(N);
  12189. SDValue ConvInput = Op.getOperand(0);
  12190. bool IsSigned = Opc == ISD::SINT_TO_FP;
  12191. if (IntBits < FloatBits)
  12192. ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
  12193. ResTy, ConvInput);
  12194. unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
  12195. : Intrinsic::aarch64_neon_vcvtfxu2fp;
  12196. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
  12197. DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
  12198. DAG.getConstant(C, DL, MVT::i32));
  12199. }
  12200. /// An EXTR instruction is made up of two shifts, ORed together. This helper
  12201. /// searches for and classifies those shifts.
  12202. static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
  12203. bool &FromHi) {
  12204. if (N.getOpcode() == ISD::SHL)
  12205. FromHi = false;
  12206. else if (N.getOpcode() == ISD::SRL)
  12207. FromHi = true;
  12208. else
  12209. return false;
  12210. if (!isa<ConstantSDNode>(N.getOperand(1)))
  12211. return false;
  12212. ShiftAmount = N->getConstantOperandVal(1);
  12213. Src = N->getOperand(0);
  12214. return true;
  12215. }
  12216. /// EXTR instruction extracts a contiguous chunk of bits from two existing
  12217. /// registers viewed as a high/low pair. This function looks for the pattern:
  12218. /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
  12219. /// with an EXTR. Can't quite be done in TableGen because the two immediates
  12220. /// aren't independent.
  12221. static SDValue tryCombineToEXTR(SDNode *N,
  12222. TargetLowering::DAGCombinerInfo &DCI) {
  12223. SelectionDAG &DAG = DCI.DAG;
  12224. SDLoc DL(N);
  12225. EVT VT = N->getValueType(0);
  12226. assert(N->getOpcode() == ISD::OR && "Unexpected root");
  12227. if (VT != MVT::i32 && VT != MVT::i64)
  12228. return SDValue();
  12229. SDValue LHS;
  12230. uint32_t ShiftLHS = 0;
  12231. bool LHSFromHi = false;
  12232. if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
  12233. return SDValue();
  12234. SDValue RHS;
  12235. uint32_t ShiftRHS = 0;
  12236. bool RHSFromHi = false;
  12237. if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
  12238. return SDValue();
  12239. // If they're both trying to come from the high part of the register, they're
  12240. // not really an EXTR.
  12241. if (LHSFromHi == RHSFromHi)
  12242. return SDValue();
  12243. if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
  12244. return SDValue();
  12245. if (LHSFromHi) {
  12246. std::swap(LHS, RHS);
  12247. std::swap(ShiftLHS, ShiftRHS);
  12248. }
  12249. return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
  12250. DAG.getConstant(ShiftRHS, DL, MVT::i64));
  12251. }
  12252. static SDValue tryCombineToBSL(SDNode *N,
  12253. TargetLowering::DAGCombinerInfo &DCI) {
  12254. EVT VT = N->getValueType(0);
  12255. SelectionDAG &DAG = DCI.DAG;
  12256. SDLoc DL(N);
  12257. if (!VT.isVector())
  12258. return SDValue();
  12259. // The combining code currently only works for NEON vectors. In particular,
  12260. // it does not work for SVE when dealing with vectors wider than 128 bits.
  12261. if (!VT.is64BitVector() && !VT.is128BitVector())
  12262. return SDValue();
  12263. SDValue N0 = N->getOperand(0);
  12264. if (N0.getOpcode() != ISD::AND)
  12265. return SDValue();
  12266. SDValue N1 = N->getOperand(1);
  12267. if (N1.getOpcode() != ISD::AND)
  12268. return SDValue();
  12269. // InstCombine does (not (neg a)) => (add a -1).
  12270. // Try: (or (and (neg a) b) (and (add a -1) c)) => (bsl (neg a) b c)
  12271. // Loop over all combinations of AND operands.
  12272. for (int i = 1; i >= 0; --i) {
  12273. for (int j = 1; j >= 0; --j) {
  12274. SDValue O0 = N0->getOperand(i);
  12275. SDValue O1 = N1->getOperand(j);
  12276. SDValue Sub, Add, SubSibling, AddSibling;
  12277. // Find a SUB and an ADD operand, one from each AND.
  12278. if (O0.getOpcode() == ISD::SUB && O1.getOpcode() == ISD::ADD) {
  12279. Sub = O0;
  12280. Add = O1;
  12281. SubSibling = N0->getOperand(1 - i);
  12282. AddSibling = N1->getOperand(1 - j);
  12283. } else if (O0.getOpcode() == ISD::ADD && O1.getOpcode() == ISD::SUB) {
  12284. Add = O0;
  12285. Sub = O1;
  12286. AddSibling = N0->getOperand(1 - i);
  12287. SubSibling = N1->getOperand(1 - j);
  12288. } else
  12289. continue;
  12290. if (!ISD::isBuildVectorAllZeros(Sub.getOperand(0).getNode()))
  12291. continue;
  12292. // Constant ones is always righthand operand of the Add.
  12293. if (!ISD::isBuildVectorAllOnes(Add.getOperand(1).getNode()))
  12294. continue;
  12295. if (Sub.getOperand(1) != Add.getOperand(0))
  12296. continue;
  12297. return DAG.getNode(AArch64ISD::BSP, DL, VT, Sub, SubSibling, AddSibling);
  12298. }
  12299. }
  12300. // (or (and a b) (and (not a) c)) => (bsl a b c)
  12301. // We only have to look for constant vectors here since the general, variable
  12302. // case can be handled in TableGen.
  12303. unsigned Bits = VT.getScalarSizeInBits();
  12304. uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
  12305. for (int i = 1; i >= 0; --i)
  12306. for (int j = 1; j >= 0; --j) {
  12307. BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
  12308. BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
  12309. if (!BVN0 || !BVN1)
  12310. continue;
  12311. bool FoundMatch = true;
  12312. for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
  12313. ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
  12314. ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
  12315. if (!CN0 || !CN1 ||
  12316. CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
  12317. FoundMatch = false;
  12318. break;
  12319. }
  12320. }
  12321. if (FoundMatch)
  12322. return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
  12323. N0->getOperand(1 - i), N1->getOperand(1 - j));
  12324. }
  12325. return SDValue();
  12326. }
  12327. static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
  12328. const AArch64Subtarget *Subtarget) {
  12329. // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
  12330. SelectionDAG &DAG = DCI.DAG;
  12331. EVT VT = N->getValueType(0);
  12332. if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
  12333. return SDValue();
  12334. if (SDValue Res = tryCombineToEXTR(N, DCI))
  12335. return Res;
  12336. if (SDValue Res = tryCombineToBSL(N, DCI))
  12337. return Res;
  12338. return SDValue();
  12339. }
  12340. static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
  12341. if (!MemVT.getVectorElementType().isSimple())
  12342. return false;
  12343. uint64_t MaskForTy = 0ull;
  12344. switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
  12345. case MVT::i8:
  12346. MaskForTy = 0xffull;
  12347. break;
  12348. case MVT::i16:
  12349. MaskForTy = 0xffffull;
  12350. break;
  12351. case MVT::i32:
  12352. MaskForTy = 0xffffffffull;
  12353. break;
  12354. default:
  12355. return false;
  12356. break;
  12357. }
  12358. if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
  12359. if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
  12360. return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
  12361. return false;
  12362. }
  12363. static SDValue performSVEAndCombine(SDNode *N,
  12364. TargetLowering::DAGCombinerInfo &DCI) {
  12365. if (DCI.isBeforeLegalizeOps())
  12366. return SDValue();
  12367. SelectionDAG &DAG = DCI.DAG;
  12368. SDValue Src = N->getOperand(0);
  12369. unsigned Opc = Src->getOpcode();
  12370. // Zero/any extend of an unsigned unpack
  12371. if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
  12372. SDValue UnpkOp = Src->getOperand(0);
  12373. SDValue Dup = N->getOperand(1);
  12374. if (Dup.getOpcode() != AArch64ISD::DUP)
  12375. return SDValue();
  12376. SDLoc DL(N);
  12377. ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
  12378. if (!C)
  12379. return SDValue();
  12380. uint64_t ExtVal = C->getZExtValue();
  12381. // If the mask is fully covered by the unpack, we don't need to push
  12382. // a new AND onto the operand
  12383. EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
  12384. if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
  12385. (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
  12386. (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
  12387. return Src;
  12388. // Truncate to prevent a DUP with an over wide constant
  12389. APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
  12390. // Otherwise, make sure we propagate the AND to the operand
  12391. // of the unpack
  12392. Dup = DAG.getNode(AArch64ISD::DUP, DL,
  12393. UnpkOp->getValueType(0),
  12394. DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
  12395. SDValue And = DAG.getNode(ISD::AND, DL,
  12396. UnpkOp->getValueType(0), UnpkOp, Dup);
  12397. return DAG.getNode(Opc, DL, N->getValueType(0), And);
  12398. }
  12399. if (!EnableCombineMGatherIntrinsics)
  12400. return SDValue();
  12401. SDValue Mask = N->getOperand(1);
  12402. if (!Src.hasOneUse())
  12403. return SDValue();
  12404. EVT MemVT;
  12405. // SVE load instructions perform an implicit zero-extend, which makes them
  12406. // perfect candidates for combining.
  12407. switch (Opc) {
  12408. case AArch64ISD::LD1_MERGE_ZERO:
  12409. case AArch64ISD::LDNF1_MERGE_ZERO:
  12410. case AArch64ISD::LDFF1_MERGE_ZERO:
  12411. MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
  12412. break;
  12413. case AArch64ISD::GLD1_MERGE_ZERO:
  12414. case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
  12415. case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
  12416. case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
  12417. case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
  12418. case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
  12419. case AArch64ISD::GLD1_IMM_MERGE_ZERO:
  12420. case AArch64ISD::GLDFF1_MERGE_ZERO:
  12421. case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
  12422. case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
  12423. case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
  12424. case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
  12425. case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
  12426. case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
  12427. case AArch64ISD::GLDNT1_MERGE_ZERO:
  12428. MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
  12429. break;
  12430. default:
  12431. return SDValue();
  12432. }
  12433. if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
  12434. return Src;
  12435. return SDValue();
  12436. }
  12437. static SDValue performANDCombine(SDNode *N,
  12438. TargetLowering::DAGCombinerInfo &DCI) {
  12439. SelectionDAG &DAG = DCI.DAG;
  12440. SDValue LHS = N->getOperand(0);
  12441. EVT VT = N->getValueType(0);
  12442. if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
  12443. return SDValue();
  12444. if (VT.isScalableVector())
  12445. return performSVEAndCombine(N, DCI);
  12446. // The combining code below works only for NEON vectors. In particular, it
  12447. // does not work for SVE when dealing with vectors wider than 128 bits.
  12448. if (!(VT.is64BitVector() || VT.is128BitVector()))
  12449. return SDValue();
  12450. BuildVectorSDNode *BVN =
  12451. dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
  12452. if (!BVN)
  12453. return SDValue();
  12454. // AND does not accept an immediate, so check if we can use a BIC immediate
  12455. // instruction instead. We do this here instead of using a (and x, (mvni imm))
  12456. // pattern in isel, because some immediates may be lowered to the preferred
  12457. // (and x, (movi imm)) form, even though an mvni representation also exists.
  12458. APInt DefBits(VT.getSizeInBits(), 0);
  12459. APInt UndefBits(VT.getSizeInBits(), 0);
  12460. if (resolveBuildVector(BVN, DefBits, UndefBits)) {
  12461. SDValue NewOp;
  12462. DefBits = ~DefBits;
  12463. if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
  12464. DefBits, &LHS)) ||
  12465. (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
  12466. DefBits, &LHS)))
  12467. return NewOp;
  12468. UndefBits = ~UndefBits;
  12469. if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
  12470. UndefBits, &LHS)) ||
  12471. (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
  12472. UndefBits, &LHS)))
  12473. return NewOp;
  12474. }
  12475. return SDValue();
  12476. }
  12477. // Attempt to form urhadd(OpA, OpB) from
  12478. // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1))
  12479. // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)).
  12480. // The original form of the first expression is
  12481. // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the
  12482. // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)).
  12483. // Before this function is called the srl will have been lowered to
  12484. // AArch64ISD::VLSHR.
  12485. // This pass can also recognize signed variants of the patterns that use sign
  12486. // extension instead of zero extension and form a srhadd(OpA, OpB) or a
  12487. // shadd(OpA, OpB) from them.
  12488. static SDValue
  12489. performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
  12490. SelectionDAG &DAG) {
  12491. EVT VT = N->getValueType(0);
  12492. // Since we are looking for a right shift by a constant value of 1 and we are
  12493. // operating on types at least 16 bits in length (sign/zero extended OpA and
  12494. // OpB, which are at least 8 bits), it follows that the truncate will always
  12495. // discard the shifted-in bit and therefore the right shift will be logical
  12496. // regardless of the signedness of OpA and OpB.
  12497. SDValue Shift = N->getOperand(0);
  12498. if (Shift.getOpcode() != AArch64ISD::VLSHR)
  12499. return SDValue();
  12500. // Is the right shift using an immediate value of 1?
  12501. uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
  12502. if (ShiftAmount != 1)
  12503. return SDValue();
  12504. SDValue ExtendOpA, ExtendOpB;
  12505. SDValue ShiftOp0 = Shift.getOperand(0);
  12506. unsigned ShiftOp0Opc = ShiftOp0.getOpcode();
  12507. if (ShiftOp0Opc == ISD::SUB) {
  12508. SDValue Xor = ShiftOp0.getOperand(1);
  12509. if (Xor.getOpcode() != ISD::XOR)
  12510. return SDValue();
  12511. // Is the XOR using a constant amount of all ones in the right hand side?
  12512. uint64_t C;
  12513. if (!isAllConstantBuildVector(Xor.getOperand(1), C))
  12514. return SDValue();
  12515. unsigned ElemSizeInBits = VT.getScalarSizeInBits();
  12516. APInt CAsAPInt(ElemSizeInBits, C);
  12517. if (CAsAPInt != APInt::getAllOnes(ElemSizeInBits))
  12518. return SDValue();
  12519. ExtendOpA = Xor.getOperand(0);
  12520. ExtendOpB = ShiftOp0.getOperand(0);
  12521. } else if (ShiftOp0Opc == ISD::ADD) {
  12522. ExtendOpA = ShiftOp0.getOperand(0);
  12523. ExtendOpB = ShiftOp0.getOperand(1);
  12524. } else
  12525. return SDValue();
  12526. unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
  12527. unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
  12528. if (!(ExtendOpAOpc == ExtendOpBOpc &&
  12529. (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
  12530. return SDValue();
  12531. // Is the result of the right shift being truncated to the same value type as
  12532. // the original operands, OpA and OpB?
  12533. SDValue OpA = ExtendOpA.getOperand(0);
  12534. SDValue OpB = ExtendOpB.getOperand(0);
  12535. EVT OpAVT = OpA.getValueType();
  12536. assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
  12537. if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
  12538. return SDValue();
  12539. SDLoc DL(N);
  12540. bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
  12541. bool IsRHADD = ShiftOp0Opc == ISD::SUB;
  12542. unsigned HADDOpc = IsSignExtend
  12543. ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
  12544. : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD);
  12545. SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB);
  12546. return ResultHADD;
  12547. }
  12548. static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) {
  12549. switch (Opcode) {
  12550. case ISD::FADD:
  12551. return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64;
  12552. case ISD::ADD:
  12553. return VT == MVT::i64;
  12554. default:
  12555. return false;
  12556. }
  12557. }
  12558. static SDValue performExtractVectorEltCombine(SDNode *N, SelectionDAG &DAG) {
  12559. SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
  12560. ConstantSDNode *ConstantN1 = dyn_cast<ConstantSDNode>(N1);
  12561. EVT VT = N->getValueType(0);
  12562. const bool FullFP16 =
  12563. static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
  12564. // Rewrite for pairwise fadd pattern
  12565. // (f32 (extract_vector_elt
  12566. // (fadd (vXf32 Other)
  12567. // (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0))
  12568. // ->
  12569. // (f32 (fadd (extract_vector_elt (vXf32 Other) 0)
  12570. // (extract_vector_elt (vXf32 Other) 1))
  12571. if (ConstantN1 && ConstantN1->getZExtValue() == 0 &&
  12572. hasPairwiseAdd(N0->getOpcode(), VT, FullFP16)) {
  12573. SDLoc DL(N0);
  12574. SDValue N00 = N0->getOperand(0);
  12575. SDValue N01 = N0->getOperand(1);
  12576. ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01);
  12577. SDValue Other = N00;
  12578. // And handle the commutative case.
  12579. if (!Shuffle) {
  12580. Shuffle = dyn_cast<ShuffleVectorSDNode>(N00);
  12581. Other = N01;
  12582. }
  12583. if (Shuffle && Shuffle->getMaskElt(0) == 1 &&
  12584. Other == Shuffle->getOperand(0)) {
  12585. return DAG.getNode(N0->getOpcode(), DL, VT,
  12586. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
  12587. DAG.getConstant(0, DL, MVT::i64)),
  12588. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
  12589. DAG.getConstant(1, DL, MVT::i64)));
  12590. }
  12591. }
  12592. return SDValue();
  12593. }
  12594. static SDValue performConcatVectorsCombine(SDNode *N,
  12595. TargetLowering::DAGCombinerInfo &DCI,
  12596. SelectionDAG &DAG) {
  12597. SDLoc dl(N);
  12598. EVT VT = N->getValueType(0);
  12599. SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
  12600. unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
  12601. if (VT.isScalableVector())
  12602. return SDValue();
  12603. // Optimize concat_vectors of truncated vectors, where the intermediate
  12604. // type is illegal, to avoid said illegality, e.g.,
  12605. // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
  12606. // (v2i16 (truncate (v2i64)))))
  12607. // ->
  12608. // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
  12609. // (v4i32 (bitcast (v2i64))),
  12610. // <0, 2, 4, 6>)))
  12611. // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
  12612. // on both input and result type, so we might generate worse code.
  12613. // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
  12614. if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
  12615. N1Opc == ISD::TRUNCATE) {
  12616. SDValue N00 = N0->getOperand(0);
  12617. SDValue N10 = N1->getOperand(0);
  12618. EVT N00VT = N00.getValueType();
  12619. if (N00VT == N10.getValueType() &&
  12620. (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
  12621. N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
  12622. MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
  12623. SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
  12624. for (size_t i = 0; i < Mask.size(); ++i)
  12625. Mask[i] = i * 2;
  12626. return DAG.getNode(ISD::TRUNCATE, dl, VT,
  12627. DAG.getVectorShuffle(
  12628. MidVT, dl,
  12629. DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
  12630. DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
  12631. }
  12632. }
  12633. // Wait 'til after everything is legalized to try this. That way we have
  12634. // legal vector types and such.
  12635. if (DCI.isBeforeLegalizeOps())
  12636. return SDValue();
  12637. // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted
  12638. // subvectors from the same original vectors. Combine these into a single
  12639. // [us]rhadd or [us]hadd that operates on the two original vectors. Example:
  12640. // (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
  12641. // extract_subvector (v16i8 OpB,
  12642. // <0>))),
  12643. // (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
  12644. // extract_subvector (v16i8 OpB,
  12645. // <8>)))))
  12646. // ->
  12647. // (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
  12648. if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
  12649. (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD ||
  12650. N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) {
  12651. SDValue N00 = N0->getOperand(0);
  12652. SDValue N01 = N0->getOperand(1);
  12653. SDValue N10 = N1->getOperand(0);
  12654. SDValue N11 = N1->getOperand(1);
  12655. EVT N00VT = N00.getValueType();
  12656. EVT N10VT = N10.getValueType();
  12657. if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  12658. N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  12659. N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  12660. N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
  12661. SDValue N00Source = N00->getOperand(0);
  12662. SDValue N01Source = N01->getOperand(0);
  12663. SDValue N10Source = N10->getOperand(0);
  12664. SDValue N11Source = N11->getOperand(0);
  12665. if (N00Source == N10Source && N01Source == N11Source &&
  12666. N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
  12667. assert(N0.getValueType() == N1.getValueType());
  12668. uint64_t N00Index = N00.getConstantOperandVal(1);
  12669. uint64_t N01Index = N01.getConstantOperandVal(1);
  12670. uint64_t N10Index = N10.getConstantOperandVal(1);
  12671. uint64_t N11Index = N11.getConstantOperandVal(1);
  12672. if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
  12673. N10Index == N00VT.getVectorNumElements())
  12674. return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
  12675. }
  12676. }
  12677. }
  12678. // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
  12679. // splat. The indexed instructions are going to be expecting a DUPLANE64, so
  12680. // canonicalise to that.
  12681. if (N->getNumOperands() == 2 && N0 == N1 && VT.getVectorNumElements() == 2) {
  12682. assert(VT.getScalarSizeInBits() == 64);
  12683. return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
  12684. DAG.getConstant(0, dl, MVT::i64));
  12685. }
  12686. // Canonicalise concat_vectors so that the right-hand vector has as few
  12687. // bit-casts as possible before its real operation. The primary matching
  12688. // destination for these operations will be the narrowing "2" instructions,
  12689. // which depend on the operation being performed on this right-hand vector.
  12690. // For example,
  12691. // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
  12692. // becomes
  12693. // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
  12694. if (N->getNumOperands() != 2 || N1Opc != ISD::BITCAST)
  12695. return SDValue();
  12696. SDValue RHS = N1->getOperand(0);
  12697. MVT RHSTy = RHS.getValueType().getSimpleVT();
  12698. // If the RHS is not a vector, this is not the pattern we're looking for.
  12699. if (!RHSTy.isVector())
  12700. return SDValue();
  12701. LLVM_DEBUG(
  12702. dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
  12703. MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
  12704. RHSTy.getVectorNumElements() * 2);
  12705. return DAG.getNode(ISD::BITCAST, dl, VT,
  12706. DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
  12707. DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
  12708. RHS));
  12709. }
  12710. static SDValue
  12711. performInsertSubvectorCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
  12712. SelectionDAG &DAG) {
  12713. SDLoc DL(N);
  12714. SDValue Vec = N->getOperand(0);
  12715. SDValue SubVec = N->getOperand(1);
  12716. uint64_t IdxVal = N->getConstantOperandVal(2);
  12717. EVT VecVT = Vec.getValueType();
  12718. EVT SubVT = SubVec.getValueType();
  12719. // Only do this for legal fixed vector types.
  12720. if (!VecVT.isFixedLengthVector() ||
  12721. !DAG.getTargetLoweringInfo().isTypeLegal(VecVT) ||
  12722. !DAG.getTargetLoweringInfo().isTypeLegal(SubVT))
  12723. return SDValue();
  12724. // Ignore widening patterns.
  12725. if (IdxVal == 0 && Vec.isUndef())
  12726. return SDValue();
  12727. // Subvector must be half the width and an "aligned" insertion.
  12728. unsigned NumSubElts = SubVT.getVectorNumElements();
  12729. if ((SubVT.getSizeInBits() * 2) != VecVT.getSizeInBits() ||
  12730. (IdxVal != 0 && IdxVal != NumSubElts))
  12731. return SDValue();
  12732. // Fold insert_subvector -> concat_vectors
  12733. // insert_subvector(Vec,Sub,lo) -> concat_vectors(Sub,extract(Vec,hi))
  12734. // insert_subvector(Vec,Sub,hi) -> concat_vectors(extract(Vec,lo),Sub)
  12735. SDValue Lo, Hi;
  12736. if (IdxVal == 0) {
  12737. Lo = SubVec;
  12738. Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
  12739. DAG.getVectorIdxConstant(NumSubElts, DL));
  12740. } else {
  12741. Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SubVT, Vec,
  12742. DAG.getVectorIdxConstant(0, DL));
  12743. Hi = SubVec;
  12744. }
  12745. return DAG.getNode(ISD::CONCAT_VECTORS, DL, VecVT, Lo, Hi);
  12746. }
  12747. static SDValue tryCombineFixedPointConvert(SDNode *N,
  12748. TargetLowering::DAGCombinerInfo &DCI,
  12749. SelectionDAG &DAG) {
  12750. // Wait until after everything is legalized to try this. That way we have
  12751. // legal vector types and such.
  12752. if (DCI.isBeforeLegalizeOps())
  12753. return SDValue();
  12754. // Transform a scalar conversion of a value from a lane extract into a
  12755. // lane extract of a vector conversion. E.g., from foo1 to foo2:
  12756. // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
  12757. // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
  12758. //
  12759. // The second form interacts better with instruction selection and the
  12760. // register allocator to avoid cross-class register copies that aren't
  12761. // coalescable due to a lane reference.
  12762. // Check the operand and see if it originates from a lane extract.
  12763. SDValue Op1 = N->getOperand(1);
  12764. if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
  12765. // Yep, no additional predication needed. Perform the transform.
  12766. SDValue IID = N->getOperand(0);
  12767. SDValue Shift = N->getOperand(2);
  12768. SDValue Vec = Op1.getOperand(0);
  12769. SDValue Lane = Op1.getOperand(1);
  12770. EVT ResTy = N->getValueType(0);
  12771. EVT VecResTy;
  12772. SDLoc DL(N);
  12773. // The vector width should be 128 bits by the time we get here, even
  12774. // if it started as 64 bits (the extract_vector handling will have
  12775. // done so).
  12776. assert(Vec.getValueSizeInBits() == 128 &&
  12777. "unexpected vector size on extract_vector_elt!");
  12778. if (Vec.getValueType() == MVT::v4i32)
  12779. VecResTy = MVT::v4f32;
  12780. else if (Vec.getValueType() == MVT::v2i64)
  12781. VecResTy = MVT::v2f64;
  12782. else
  12783. llvm_unreachable("unexpected vector type!");
  12784. SDValue Convert =
  12785. DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
  12786. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
  12787. }
  12788. return SDValue();
  12789. }
  12790. // AArch64 high-vector "long" operations are formed by performing the non-high
  12791. // version on an extract_subvector of each operand which gets the high half:
  12792. //
  12793. // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
  12794. //
  12795. // However, there are cases which don't have an extract_high explicitly, but
  12796. // have another operation that can be made compatible with one for free. For
  12797. // example:
  12798. //
  12799. // (dupv64 scalar) --> (extract_high (dup128 scalar))
  12800. //
  12801. // This routine does the actual conversion of such DUPs, once outer routines
  12802. // have determined that everything else is in order.
  12803. // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
  12804. // similarly here.
  12805. static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
  12806. switch (N.getOpcode()) {
  12807. case AArch64ISD::DUP:
  12808. case AArch64ISD::DUPLANE8:
  12809. case AArch64ISD::DUPLANE16:
  12810. case AArch64ISD::DUPLANE32:
  12811. case AArch64ISD::DUPLANE64:
  12812. case AArch64ISD::MOVI:
  12813. case AArch64ISD::MOVIshift:
  12814. case AArch64ISD::MOVIedit:
  12815. case AArch64ISD::MOVImsl:
  12816. case AArch64ISD::MVNIshift:
  12817. case AArch64ISD::MVNImsl:
  12818. break;
  12819. default:
  12820. // FMOV could be supported, but isn't very useful, as it would only occur
  12821. // if you passed a bitcast' floating point immediate to an eligible long
  12822. // integer op (addl, smull, ...).
  12823. return SDValue();
  12824. }
  12825. MVT NarrowTy = N.getSimpleValueType();
  12826. if (!NarrowTy.is64BitVector())
  12827. return SDValue();
  12828. MVT ElementTy = NarrowTy.getVectorElementType();
  12829. unsigned NumElems = NarrowTy.getVectorNumElements();
  12830. MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
  12831. SDLoc dl(N);
  12832. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
  12833. DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
  12834. DAG.getConstant(NumElems, dl, MVT::i64));
  12835. }
  12836. static bool isEssentiallyExtractHighSubvector(SDValue N) {
  12837. if (N.getOpcode() == ISD::BITCAST)
  12838. N = N.getOperand(0);
  12839. if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
  12840. return false;
  12841. if (N.getOperand(0).getValueType().isScalableVector())
  12842. return false;
  12843. return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
  12844. N.getOperand(0).getValueType().getVectorNumElements() / 2;
  12845. }
  12846. /// Helper structure to keep track of ISD::SET_CC operands.
  12847. struct GenericSetCCInfo {
  12848. const SDValue *Opnd0;
  12849. const SDValue *Opnd1;
  12850. ISD::CondCode CC;
  12851. };
  12852. /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
  12853. struct AArch64SetCCInfo {
  12854. const SDValue *Cmp;
  12855. AArch64CC::CondCode CC;
  12856. };
  12857. /// Helper structure to keep track of SetCC information.
  12858. union SetCCInfo {
  12859. GenericSetCCInfo Generic;
  12860. AArch64SetCCInfo AArch64;
  12861. };
  12862. /// Helper structure to be able to read SetCC information. If set to
  12863. /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
  12864. /// GenericSetCCInfo.
  12865. struct SetCCInfoAndKind {
  12866. SetCCInfo Info;
  12867. bool IsAArch64;
  12868. };
  12869. /// Check whether or not \p Op is a SET_CC operation, either a generic or
  12870. /// an
  12871. /// AArch64 lowered one.
  12872. /// \p SetCCInfo is filled accordingly.
  12873. /// \post SetCCInfo is meanginfull only when this function returns true.
  12874. /// \return True when Op is a kind of SET_CC operation.
  12875. static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
  12876. // If this is a setcc, this is straight forward.
  12877. if (Op.getOpcode() == ISD::SETCC) {
  12878. SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
  12879. SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
  12880. SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
  12881. SetCCInfo.IsAArch64 = false;
  12882. return true;
  12883. }
  12884. // Otherwise, check if this is a matching csel instruction.
  12885. // In other words:
  12886. // - csel 1, 0, cc
  12887. // - csel 0, 1, !cc
  12888. if (Op.getOpcode() != AArch64ISD::CSEL)
  12889. return false;
  12890. // Set the information about the operands.
  12891. // TODO: we want the operands of the Cmp not the csel
  12892. SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
  12893. SetCCInfo.IsAArch64 = true;
  12894. SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
  12895. cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
  12896. // Check that the operands matches the constraints:
  12897. // (1) Both operands must be constants.
  12898. // (2) One must be 1 and the other must be 0.
  12899. ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
  12900. ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  12901. // Check (1).
  12902. if (!TValue || !FValue)
  12903. return false;
  12904. // Check (2).
  12905. if (!TValue->isOne()) {
  12906. // Update the comparison when we are interested in !cc.
  12907. std::swap(TValue, FValue);
  12908. SetCCInfo.Info.AArch64.CC =
  12909. AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
  12910. }
  12911. return TValue->isOne() && FValue->isZero();
  12912. }
  12913. // Returns true if Op is setcc or zext of setcc.
  12914. static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
  12915. if (isSetCC(Op, Info))
  12916. return true;
  12917. return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
  12918. isSetCC(Op->getOperand(0), Info));
  12919. }
  12920. // The folding we want to perform is:
  12921. // (add x, [zext] (setcc cc ...) )
  12922. // -->
  12923. // (csel x, (add x, 1), !cc ...)
  12924. //
  12925. // The latter will get matched to a CSINC instruction.
  12926. static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
  12927. assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
  12928. SDValue LHS = Op->getOperand(0);
  12929. SDValue RHS = Op->getOperand(1);
  12930. SetCCInfoAndKind InfoAndKind;
  12931. // If both operands are a SET_CC, then we don't want to perform this
  12932. // folding and create another csel as this results in more instructions
  12933. // (and higher register usage).
  12934. if (isSetCCOrZExtSetCC(LHS, InfoAndKind) &&
  12935. isSetCCOrZExtSetCC(RHS, InfoAndKind))
  12936. return SDValue();
  12937. // If neither operand is a SET_CC, give up.
  12938. if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
  12939. std::swap(LHS, RHS);
  12940. if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
  12941. return SDValue();
  12942. }
  12943. // FIXME: This could be generatized to work for FP comparisons.
  12944. EVT CmpVT = InfoAndKind.IsAArch64
  12945. ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
  12946. : InfoAndKind.Info.Generic.Opnd0->getValueType();
  12947. if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
  12948. return SDValue();
  12949. SDValue CCVal;
  12950. SDValue Cmp;
  12951. SDLoc dl(Op);
  12952. if (InfoAndKind.IsAArch64) {
  12953. CCVal = DAG.getConstant(
  12954. AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
  12955. MVT::i32);
  12956. Cmp = *InfoAndKind.Info.AArch64.Cmp;
  12957. } else
  12958. Cmp = getAArch64Cmp(
  12959. *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
  12960. ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
  12961. dl);
  12962. EVT VT = Op->getValueType(0);
  12963. LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
  12964. return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
  12965. }
  12966. // ADD(UADDV a, UADDV b) --> UADDV(ADD a, b)
  12967. static SDValue performUADDVCombine(SDNode *N, SelectionDAG &DAG) {
  12968. EVT VT = N->getValueType(0);
  12969. // Only scalar integer and vector types.
  12970. if (N->getOpcode() != ISD::ADD || !VT.isScalarInteger())
  12971. return SDValue();
  12972. SDValue LHS = N->getOperand(0);
  12973. SDValue RHS = N->getOperand(1);
  12974. if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  12975. RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || LHS.getValueType() != VT)
  12976. return SDValue();
  12977. auto *LHSN1 = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
  12978. auto *RHSN1 = dyn_cast<ConstantSDNode>(RHS->getOperand(1));
  12979. if (!LHSN1 || LHSN1 != RHSN1 || !RHSN1->isZero())
  12980. return SDValue();
  12981. SDValue Op1 = LHS->getOperand(0);
  12982. SDValue Op2 = RHS->getOperand(0);
  12983. EVT OpVT1 = Op1.getValueType();
  12984. EVT OpVT2 = Op2.getValueType();
  12985. if (Op1.getOpcode() != AArch64ISD::UADDV || OpVT1 != OpVT2 ||
  12986. Op2.getOpcode() != AArch64ISD::UADDV ||
  12987. OpVT1.getVectorElementType() != VT)
  12988. return SDValue();
  12989. SDValue Val1 = Op1.getOperand(0);
  12990. SDValue Val2 = Op2.getOperand(0);
  12991. EVT ValVT = Val1->getValueType(0);
  12992. SDLoc DL(N);
  12993. SDValue AddVal = DAG.getNode(ISD::ADD, DL, ValVT, Val1, Val2);
  12994. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
  12995. DAG.getNode(AArch64ISD::UADDV, DL, ValVT, AddVal),
  12996. DAG.getConstant(0, DL, MVT::i64));
  12997. }
  12998. // ADD(UDOT(zero, x, y), A) --> UDOT(A, x, y)
  12999. static SDValue performAddDotCombine(SDNode *N, SelectionDAG &DAG) {
  13000. EVT VT = N->getValueType(0);
  13001. if (N->getOpcode() != ISD::ADD)
  13002. return SDValue();
  13003. SDValue Dot = N->getOperand(0);
  13004. SDValue A = N->getOperand(1);
  13005. // Handle commutivity
  13006. auto isZeroDot = [](SDValue Dot) {
  13007. return (Dot.getOpcode() == AArch64ISD::UDOT ||
  13008. Dot.getOpcode() == AArch64ISD::SDOT) &&
  13009. isZerosVector(Dot.getOperand(0).getNode());
  13010. };
  13011. if (!isZeroDot(Dot))
  13012. std::swap(Dot, A);
  13013. if (!isZeroDot(Dot))
  13014. return SDValue();
  13015. return DAG.getNode(Dot.getOpcode(), SDLoc(N), VT, A, Dot.getOperand(1),
  13016. Dot.getOperand(2));
  13017. }
  13018. // The basic add/sub long vector instructions have variants with "2" on the end
  13019. // which act on the high-half of their inputs. They are normally matched by
  13020. // patterns like:
  13021. //
  13022. // (add (zeroext (extract_high LHS)),
  13023. // (zeroext (extract_high RHS)))
  13024. // -> uaddl2 vD, vN, vM
  13025. //
  13026. // However, if one of the extracts is something like a duplicate, this
  13027. // instruction can still be used profitably. This function puts the DAG into a
  13028. // more appropriate form for those patterns to trigger.
  13029. static SDValue performAddSubLongCombine(SDNode *N,
  13030. TargetLowering::DAGCombinerInfo &DCI,
  13031. SelectionDAG &DAG) {
  13032. if (DCI.isBeforeLegalizeOps())
  13033. return SDValue();
  13034. MVT VT = N->getSimpleValueType(0);
  13035. if (!VT.is128BitVector()) {
  13036. if (N->getOpcode() == ISD::ADD)
  13037. return performSetccAddFolding(N, DAG);
  13038. return SDValue();
  13039. }
  13040. // Make sure both branches are extended in the same way.
  13041. SDValue LHS = N->getOperand(0);
  13042. SDValue RHS = N->getOperand(1);
  13043. if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
  13044. LHS.getOpcode() != ISD::SIGN_EXTEND) ||
  13045. LHS.getOpcode() != RHS.getOpcode())
  13046. return SDValue();
  13047. unsigned ExtType = LHS.getOpcode();
  13048. // It's not worth doing if at least one of the inputs isn't already an
  13049. // extract, but we don't know which it'll be so we have to try both.
  13050. if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
  13051. RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
  13052. if (!RHS.getNode())
  13053. return SDValue();
  13054. RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
  13055. } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
  13056. LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
  13057. if (!LHS.getNode())
  13058. return SDValue();
  13059. LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
  13060. }
  13061. return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
  13062. }
  13063. static SDValue performAddSubCombine(SDNode *N,
  13064. TargetLowering::DAGCombinerInfo &DCI,
  13065. SelectionDAG &DAG) {
  13066. // Try to change sum of two reductions.
  13067. if (SDValue Val = performUADDVCombine(N, DAG))
  13068. return Val;
  13069. if (SDValue Val = performAddDotCombine(N, DAG))
  13070. return Val;
  13071. return performAddSubLongCombine(N, DCI, DAG);
  13072. }
  13073. // Massage DAGs which we can use the high-half "long" operations on into
  13074. // something isel will recognize better. E.g.
  13075. //
  13076. // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
  13077. // (aarch64_neon_umull (extract_high (v2i64 vec)))
  13078. // (extract_high (v2i64 (dup128 scalar)))))
  13079. //
  13080. static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
  13081. TargetLowering::DAGCombinerInfo &DCI,
  13082. SelectionDAG &DAG) {
  13083. if (DCI.isBeforeLegalizeOps())
  13084. return SDValue();
  13085. SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1);
  13086. SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2);
  13087. assert(LHS.getValueType().is64BitVector() &&
  13088. RHS.getValueType().is64BitVector() &&
  13089. "unexpected shape for long operation");
  13090. // Either node could be a DUP, but it's not worth doing both of them (you'd
  13091. // just as well use the non-high version) so look for a corresponding extract
  13092. // operation on the other "wing".
  13093. if (isEssentiallyExtractHighSubvector(LHS)) {
  13094. RHS = tryExtendDUPToExtractHigh(RHS, DAG);
  13095. if (!RHS.getNode())
  13096. return SDValue();
  13097. } else if (isEssentiallyExtractHighSubvector(RHS)) {
  13098. LHS = tryExtendDUPToExtractHigh(LHS, DAG);
  13099. if (!LHS.getNode())
  13100. return SDValue();
  13101. }
  13102. if (IID == Intrinsic::not_intrinsic)
  13103. return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS);
  13104. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
  13105. N->getOperand(0), LHS, RHS);
  13106. }
  13107. static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
  13108. MVT ElemTy = N->getSimpleValueType(0).getScalarType();
  13109. unsigned ElemBits = ElemTy.getSizeInBits();
  13110. int64_t ShiftAmount;
  13111. if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
  13112. APInt SplatValue, SplatUndef;
  13113. unsigned SplatBitSize;
  13114. bool HasAnyUndefs;
  13115. if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
  13116. HasAnyUndefs, ElemBits) ||
  13117. SplatBitSize != ElemBits)
  13118. return SDValue();
  13119. ShiftAmount = SplatValue.getSExtValue();
  13120. } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
  13121. ShiftAmount = CVN->getSExtValue();
  13122. } else
  13123. return SDValue();
  13124. unsigned Opcode;
  13125. bool IsRightShift;
  13126. switch (IID) {
  13127. default:
  13128. llvm_unreachable("Unknown shift intrinsic");
  13129. case Intrinsic::aarch64_neon_sqshl:
  13130. Opcode = AArch64ISD::SQSHL_I;
  13131. IsRightShift = false;
  13132. break;
  13133. case Intrinsic::aarch64_neon_uqshl:
  13134. Opcode = AArch64ISD::UQSHL_I;
  13135. IsRightShift = false;
  13136. break;
  13137. case Intrinsic::aarch64_neon_srshl:
  13138. Opcode = AArch64ISD::SRSHR_I;
  13139. IsRightShift = true;
  13140. break;
  13141. case Intrinsic::aarch64_neon_urshl:
  13142. Opcode = AArch64ISD::URSHR_I;
  13143. IsRightShift = true;
  13144. break;
  13145. case Intrinsic::aarch64_neon_sqshlu:
  13146. Opcode = AArch64ISD::SQSHLU_I;
  13147. IsRightShift = false;
  13148. break;
  13149. case Intrinsic::aarch64_neon_sshl:
  13150. case Intrinsic::aarch64_neon_ushl:
  13151. // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
  13152. // left shift for positive shift amounts. Below, we only replace the current
  13153. // node with VSHL, if this condition is met.
  13154. Opcode = AArch64ISD::VSHL;
  13155. IsRightShift = false;
  13156. break;
  13157. }
  13158. if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
  13159. SDLoc dl(N);
  13160. return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
  13161. DAG.getConstant(-ShiftAmount, dl, MVT::i32));
  13162. } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
  13163. SDLoc dl(N);
  13164. return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
  13165. DAG.getConstant(ShiftAmount, dl, MVT::i32));
  13166. }
  13167. return SDValue();
  13168. }
  13169. // The CRC32[BH] instructions ignore the high bits of their data operand. Since
  13170. // the intrinsics must be legal and take an i32, this means there's almost
  13171. // certainly going to be a zext in the DAG which we can eliminate.
  13172. static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
  13173. SDValue AndN = N->getOperand(2);
  13174. if (AndN.getOpcode() != ISD::AND)
  13175. return SDValue();
  13176. ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
  13177. if (!CMask || CMask->getZExtValue() != Mask)
  13178. return SDValue();
  13179. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
  13180. N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
  13181. }
  13182. static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
  13183. SelectionDAG &DAG) {
  13184. SDLoc dl(N);
  13185. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
  13186. DAG.getNode(Opc, dl,
  13187. N->getOperand(1).getSimpleValueType(),
  13188. N->getOperand(1)),
  13189. DAG.getConstant(0, dl, MVT::i64));
  13190. }
  13191. static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
  13192. SDLoc DL(N);
  13193. SDValue Op1 = N->getOperand(1);
  13194. SDValue Op2 = N->getOperand(2);
  13195. EVT ScalarTy = Op2.getValueType();
  13196. if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
  13197. ScalarTy = MVT::i32;
  13198. // Lower index_vector(base, step) to mul(step step_vector(1)) + splat(base).
  13199. SDValue StepVector = DAG.getStepVector(DL, N->getValueType(0));
  13200. SDValue Step = DAG.getNode(ISD::SPLAT_VECTOR, DL, N->getValueType(0), Op2);
  13201. SDValue Mul = DAG.getNode(ISD::MUL, DL, N->getValueType(0), StepVector, Step);
  13202. SDValue Base = DAG.getNode(ISD::SPLAT_VECTOR, DL, N->getValueType(0), Op1);
  13203. return DAG.getNode(ISD::ADD, DL, N->getValueType(0), Mul, Base);
  13204. }
  13205. static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
  13206. SDLoc dl(N);
  13207. SDValue Scalar = N->getOperand(3);
  13208. EVT ScalarTy = Scalar.getValueType();
  13209. if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
  13210. Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
  13211. SDValue Passthru = N->getOperand(1);
  13212. SDValue Pred = N->getOperand(2);
  13213. return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
  13214. Pred, Scalar, Passthru);
  13215. }
  13216. static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
  13217. SDLoc dl(N);
  13218. LLVMContext &Ctx = *DAG.getContext();
  13219. EVT VT = N->getValueType(0);
  13220. assert(VT.isScalableVector() && "Expected a scalable vector.");
  13221. // Current lowering only supports the SVE-ACLE types.
  13222. if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
  13223. return SDValue();
  13224. unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
  13225. unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
  13226. EVT ByteVT =
  13227. EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize));
  13228. // Convert everything to the domain of EXT (i.e bytes).
  13229. SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
  13230. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
  13231. SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
  13232. DAG.getConstant(ElemSize, dl, MVT::i32));
  13233. SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
  13234. return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
  13235. }
  13236. static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
  13237. TargetLowering::DAGCombinerInfo &DCI,
  13238. SelectionDAG &DAG) {
  13239. if (DCI.isBeforeLegalize())
  13240. return SDValue();
  13241. SDValue Comparator = N->getOperand(3);
  13242. if (Comparator.getOpcode() == AArch64ISD::DUP ||
  13243. Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
  13244. unsigned IID = getIntrinsicID(N);
  13245. EVT VT = N->getValueType(0);
  13246. EVT CmpVT = N->getOperand(2).getValueType();
  13247. SDValue Pred = N->getOperand(1);
  13248. SDValue Imm;
  13249. SDLoc DL(N);
  13250. switch (IID) {
  13251. default:
  13252. llvm_unreachable("Called with wrong intrinsic!");
  13253. break;
  13254. // Signed comparisons
  13255. case Intrinsic::aarch64_sve_cmpeq_wide:
  13256. case Intrinsic::aarch64_sve_cmpne_wide:
  13257. case Intrinsic::aarch64_sve_cmpge_wide:
  13258. case Intrinsic::aarch64_sve_cmpgt_wide:
  13259. case Intrinsic::aarch64_sve_cmplt_wide:
  13260. case Intrinsic::aarch64_sve_cmple_wide: {
  13261. if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
  13262. int64_t ImmVal = CN->getSExtValue();
  13263. if (ImmVal >= -16 && ImmVal <= 15)
  13264. Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
  13265. else
  13266. return SDValue();
  13267. }
  13268. break;
  13269. }
  13270. // Unsigned comparisons
  13271. case Intrinsic::aarch64_sve_cmphs_wide:
  13272. case Intrinsic::aarch64_sve_cmphi_wide:
  13273. case Intrinsic::aarch64_sve_cmplo_wide:
  13274. case Intrinsic::aarch64_sve_cmpls_wide: {
  13275. if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
  13276. uint64_t ImmVal = CN->getZExtValue();
  13277. if (ImmVal <= 127)
  13278. Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
  13279. else
  13280. return SDValue();
  13281. }
  13282. break;
  13283. }
  13284. }
  13285. if (!Imm)
  13286. return SDValue();
  13287. SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
  13288. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
  13289. N->getOperand(2), Splat, DAG.getCondCode(CC));
  13290. }
  13291. return SDValue();
  13292. }
  13293. static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
  13294. AArch64CC::CondCode Cond) {
  13295. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  13296. SDLoc DL(Op);
  13297. assert(Op.getValueType().isScalableVector() &&
  13298. TLI.isTypeLegal(Op.getValueType()) &&
  13299. "Expected legal scalable vector type!");
  13300. // Ensure target specific opcodes are using legal type.
  13301. EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
  13302. SDValue TVal = DAG.getConstant(1, DL, OutVT);
  13303. SDValue FVal = DAG.getConstant(0, DL, OutVT);
  13304. // Set condition code (CC) flags.
  13305. SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
  13306. // Convert CC to integer based on requested condition.
  13307. // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
  13308. SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
  13309. SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
  13310. return DAG.getZExtOrTrunc(Res, DL, VT);
  13311. }
  13312. static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc,
  13313. SelectionDAG &DAG) {
  13314. SDLoc DL(N);
  13315. SDValue Pred = N->getOperand(1);
  13316. SDValue VecToReduce = N->getOperand(2);
  13317. // NOTE: The integer reduction's result type is not always linked to the
  13318. // operand's element type so we construct it from the intrinsic's result type.
  13319. EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0));
  13320. SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
  13321. // SVE reductions set the whole vector register with the first element
  13322. // containing the reduction result, which we'll now extract.
  13323. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  13324. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
  13325. Zero);
  13326. }
  13327. static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
  13328. SelectionDAG &DAG) {
  13329. SDLoc DL(N);
  13330. SDValue Pred = N->getOperand(1);
  13331. SDValue VecToReduce = N->getOperand(2);
  13332. EVT ReduceVT = VecToReduce.getValueType();
  13333. SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
  13334. // SVE reductions set the whole vector register with the first element
  13335. // containing the reduction result, which we'll now extract.
  13336. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  13337. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
  13338. Zero);
  13339. }
  13340. static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
  13341. SelectionDAG &DAG) {
  13342. SDLoc DL(N);
  13343. SDValue Pred = N->getOperand(1);
  13344. SDValue InitVal = N->getOperand(2);
  13345. SDValue VecToReduce = N->getOperand(3);
  13346. EVT ReduceVT = VecToReduce.getValueType();
  13347. // Ordered reductions use the first lane of the result vector as the
  13348. // reduction's initial value.
  13349. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  13350. InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
  13351. DAG.getUNDEF(ReduceVT), InitVal, Zero);
  13352. SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
  13353. // SVE reductions set the whole vector register with the first element
  13354. // containing the reduction result, which we'll now extract.
  13355. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
  13356. Zero);
  13357. }
  13358. static bool isAllInactivePredicate(SDValue N) {
  13359. // Look through cast.
  13360. while (N.getOpcode() == AArch64ISD::REINTERPRET_CAST)
  13361. N = N.getOperand(0);
  13362. return ISD::isConstantSplatVectorAllZeros(N.getNode());
  13363. }
  13364. static bool isAllActivePredicate(SelectionDAG &DAG, SDValue N) {
  13365. unsigned NumElts = N.getValueType().getVectorMinNumElements();
  13366. // Look through cast.
  13367. while (N.getOpcode() == AArch64ISD::REINTERPRET_CAST) {
  13368. N = N.getOperand(0);
  13369. // When reinterpreting from a type with fewer elements the "new" elements
  13370. // are not active, so bail if they're likely to be used.
  13371. if (N.getValueType().getVectorMinNumElements() < NumElts)
  13372. return false;
  13373. }
  13374. // "ptrue p.<ty>, all" can be considered all active when <ty> is the same size
  13375. // or smaller than the implicit element type represented by N.
  13376. // NOTE: A larger element count implies a smaller element type.
  13377. if (N.getOpcode() == AArch64ISD::PTRUE &&
  13378. N.getConstantOperandVal(0) == AArch64SVEPredPattern::all)
  13379. return N.getValueType().getVectorMinNumElements() >= NumElts;
  13380. // If we're compiling for a specific vector-length, we can check if the
  13381. // pattern's VL equals that of the scalable vector at runtime.
  13382. if (N.getOpcode() == AArch64ISD::PTRUE) {
  13383. const auto &Subtarget =
  13384. static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
  13385. unsigned MinSVESize = Subtarget.getMinSVEVectorSizeInBits();
  13386. unsigned MaxSVESize = Subtarget.getMaxSVEVectorSizeInBits();
  13387. if (MaxSVESize && MinSVESize == MaxSVESize) {
  13388. unsigned VScale = MaxSVESize / AArch64::SVEBitsPerBlock;
  13389. unsigned PatNumElts =
  13390. getNumElementsFromSVEPredPattern(N.getConstantOperandVal(0));
  13391. return PatNumElts == (NumElts * VScale);
  13392. }
  13393. }
  13394. return false;
  13395. }
  13396. // If a merged operation has no inactive lanes we can relax it to a predicated
  13397. // or unpredicated operation, which potentially allows better isel (perhaps
  13398. // using immediate forms) or relaxing register reuse requirements.
  13399. static SDValue convertMergedOpToPredOp(SDNode *N, unsigned Opc,
  13400. SelectionDAG &DAG, bool UnpredOp = false,
  13401. bool SwapOperands = false) {
  13402. assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!");
  13403. assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!");
  13404. SDValue Pg = N->getOperand(1);
  13405. SDValue Op1 = N->getOperand(SwapOperands ? 3 : 2);
  13406. SDValue Op2 = N->getOperand(SwapOperands ? 2 : 3);
  13407. // ISD way to specify an all active predicate.
  13408. if (isAllActivePredicate(DAG, Pg)) {
  13409. if (UnpredOp)
  13410. return DAG.getNode(Opc, SDLoc(N), N->getValueType(0), Op1, Op2);
  13411. return DAG.getNode(Opc, SDLoc(N), N->getValueType(0), Pg, Op1, Op2);
  13412. }
  13413. // FUTURE: SplatVector(true)
  13414. return SDValue();
  13415. }
  13416. static SDValue performIntrinsicCombine(SDNode *N,
  13417. TargetLowering::DAGCombinerInfo &DCI,
  13418. const AArch64Subtarget *Subtarget) {
  13419. SelectionDAG &DAG = DCI.DAG;
  13420. unsigned IID = getIntrinsicID(N);
  13421. switch (IID) {
  13422. default:
  13423. break;
  13424. case Intrinsic::aarch64_neon_vcvtfxs2fp:
  13425. case Intrinsic::aarch64_neon_vcvtfxu2fp:
  13426. return tryCombineFixedPointConvert(N, DCI, DAG);
  13427. case Intrinsic::aarch64_neon_saddv:
  13428. return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
  13429. case Intrinsic::aarch64_neon_uaddv:
  13430. return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
  13431. case Intrinsic::aarch64_neon_sminv:
  13432. return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
  13433. case Intrinsic::aarch64_neon_uminv:
  13434. return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
  13435. case Intrinsic::aarch64_neon_smaxv:
  13436. return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
  13437. case Intrinsic::aarch64_neon_umaxv:
  13438. return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
  13439. case Intrinsic::aarch64_neon_fmax:
  13440. return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
  13441. N->getOperand(1), N->getOperand(2));
  13442. case Intrinsic::aarch64_neon_fmin:
  13443. return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
  13444. N->getOperand(1), N->getOperand(2));
  13445. case Intrinsic::aarch64_neon_fmaxnm:
  13446. return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
  13447. N->getOperand(1), N->getOperand(2));
  13448. case Intrinsic::aarch64_neon_fminnm:
  13449. return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
  13450. N->getOperand(1), N->getOperand(2));
  13451. case Intrinsic::aarch64_neon_smull:
  13452. case Intrinsic::aarch64_neon_umull:
  13453. case Intrinsic::aarch64_neon_pmull:
  13454. case Intrinsic::aarch64_neon_sqdmull:
  13455. return tryCombineLongOpWithDup(IID, N, DCI, DAG);
  13456. case Intrinsic::aarch64_neon_sqshl:
  13457. case Intrinsic::aarch64_neon_uqshl:
  13458. case Intrinsic::aarch64_neon_sqshlu:
  13459. case Intrinsic::aarch64_neon_srshl:
  13460. case Intrinsic::aarch64_neon_urshl:
  13461. case Intrinsic::aarch64_neon_sshl:
  13462. case Intrinsic::aarch64_neon_ushl:
  13463. return tryCombineShiftImm(IID, N, DAG);
  13464. case Intrinsic::aarch64_crc32b:
  13465. case Intrinsic::aarch64_crc32cb:
  13466. return tryCombineCRC32(0xff, N, DAG);
  13467. case Intrinsic::aarch64_crc32h:
  13468. case Intrinsic::aarch64_crc32ch:
  13469. return tryCombineCRC32(0xffff, N, DAG);
  13470. case Intrinsic::aarch64_sve_saddv:
  13471. // There is no i64 version of SADDV because the sign is irrelevant.
  13472. if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64)
  13473. return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
  13474. else
  13475. return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG);
  13476. case Intrinsic::aarch64_sve_uaddv:
  13477. return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
  13478. case Intrinsic::aarch64_sve_smaxv:
  13479. return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG);
  13480. case Intrinsic::aarch64_sve_umaxv:
  13481. return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG);
  13482. case Intrinsic::aarch64_sve_sminv:
  13483. return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG);
  13484. case Intrinsic::aarch64_sve_uminv:
  13485. return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG);
  13486. case Intrinsic::aarch64_sve_orv:
  13487. return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG);
  13488. case Intrinsic::aarch64_sve_eorv:
  13489. return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG);
  13490. case Intrinsic::aarch64_sve_andv:
  13491. return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG);
  13492. case Intrinsic::aarch64_sve_index:
  13493. return LowerSVEIntrinsicIndex(N, DAG);
  13494. case Intrinsic::aarch64_sve_dup:
  13495. return LowerSVEIntrinsicDUP(N, DAG);
  13496. case Intrinsic::aarch64_sve_dup_x:
  13497. return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
  13498. N->getOperand(1));
  13499. case Intrinsic::aarch64_sve_ext:
  13500. return LowerSVEIntrinsicEXT(N, DAG);
  13501. case Intrinsic::aarch64_sve_mul:
  13502. return convertMergedOpToPredOp(N, AArch64ISD::MUL_PRED, DAG);
  13503. case Intrinsic::aarch64_sve_smulh:
  13504. return convertMergedOpToPredOp(N, AArch64ISD::MULHS_PRED, DAG);
  13505. case Intrinsic::aarch64_sve_umulh:
  13506. return convertMergedOpToPredOp(N, AArch64ISD::MULHU_PRED, DAG);
  13507. case Intrinsic::aarch64_sve_smin:
  13508. return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG);
  13509. case Intrinsic::aarch64_sve_umin:
  13510. return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG);
  13511. case Intrinsic::aarch64_sve_smax:
  13512. return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG);
  13513. case Intrinsic::aarch64_sve_umax:
  13514. return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG);
  13515. case Intrinsic::aarch64_sve_lsl:
  13516. return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG);
  13517. case Intrinsic::aarch64_sve_lsr:
  13518. return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG);
  13519. case Intrinsic::aarch64_sve_asr:
  13520. return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG);
  13521. case Intrinsic::aarch64_sve_fadd:
  13522. return convertMergedOpToPredOp(N, AArch64ISD::FADD_PRED, DAG);
  13523. case Intrinsic::aarch64_sve_fsub:
  13524. return convertMergedOpToPredOp(N, AArch64ISD::FSUB_PRED, DAG);
  13525. case Intrinsic::aarch64_sve_fmul:
  13526. return convertMergedOpToPredOp(N, AArch64ISD::FMUL_PRED, DAG);
  13527. case Intrinsic::aarch64_sve_add:
  13528. return convertMergedOpToPredOp(N, ISD::ADD, DAG, true);
  13529. case Intrinsic::aarch64_sve_sub:
  13530. return convertMergedOpToPredOp(N, ISD::SUB, DAG, true);
  13531. case Intrinsic::aarch64_sve_subr:
  13532. return convertMergedOpToPredOp(N, ISD::SUB, DAG, true, true);
  13533. case Intrinsic::aarch64_sve_and:
  13534. return convertMergedOpToPredOp(N, ISD::AND, DAG, true);
  13535. case Intrinsic::aarch64_sve_bic:
  13536. return convertMergedOpToPredOp(N, AArch64ISD::BIC, DAG, true);
  13537. case Intrinsic::aarch64_sve_eor:
  13538. return convertMergedOpToPredOp(N, ISD::XOR, DAG, true);
  13539. case Intrinsic::aarch64_sve_orr:
  13540. return convertMergedOpToPredOp(N, ISD::OR, DAG, true);
  13541. case Intrinsic::aarch64_sve_sqadd:
  13542. return convertMergedOpToPredOp(N, ISD::SADDSAT, DAG, true);
  13543. case Intrinsic::aarch64_sve_sqsub:
  13544. return convertMergedOpToPredOp(N, ISD::SSUBSAT, DAG, true);
  13545. case Intrinsic::aarch64_sve_uqadd:
  13546. return convertMergedOpToPredOp(N, ISD::UADDSAT, DAG, true);
  13547. case Intrinsic::aarch64_sve_uqsub:
  13548. return convertMergedOpToPredOp(N, ISD::USUBSAT, DAG, true);
  13549. case Intrinsic::aarch64_sve_sqadd_x:
  13550. return DAG.getNode(ISD::SADDSAT, SDLoc(N), N->getValueType(0),
  13551. N->getOperand(1), N->getOperand(2));
  13552. case Intrinsic::aarch64_sve_sqsub_x:
  13553. return DAG.getNode(ISD::SSUBSAT, SDLoc(N), N->getValueType(0),
  13554. N->getOperand(1), N->getOperand(2));
  13555. case Intrinsic::aarch64_sve_uqadd_x:
  13556. return DAG.getNode(ISD::UADDSAT, SDLoc(N), N->getValueType(0),
  13557. N->getOperand(1), N->getOperand(2));
  13558. case Intrinsic::aarch64_sve_uqsub_x:
  13559. return DAG.getNode(ISD::USUBSAT, SDLoc(N), N->getValueType(0),
  13560. N->getOperand(1), N->getOperand(2));
  13561. case Intrinsic::aarch64_sve_asrd:
  13562. return DAG.getNode(AArch64ISD::SRAD_MERGE_OP1, SDLoc(N), N->getValueType(0),
  13563. N->getOperand(1), N->getOperand(2), N->getOperand(3));
  13564. case Intrinsic::aarch64_sve_cmphs:
  13565. if (!N->getOperand(2).getValueType().isFloatingPoint())
  13566. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  13567. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  13568. N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
  13569. break;
  13570. case Intrinsic::aarch64_sve_cmphi:
  13571. if (!N->getOperand(2).getValueType().isFloatingPoint())
  13572. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  13573. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  13574. N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
  13575. break;
  13576. case Intrinsic::aarch64_sve_fcmpge:
  13577. case Intrinsic::aarch64_sve_cmpge:
  13578. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  13579. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  13580. N->getOperand(3), DAG.getCondCode(ISD::SETGE));
  13581. break;
  13582. case Intrinsic::aarch64_sve_fcmpgt:
  13583. case Intrinsic::aarch64_sve_cmpgt:
  13584. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  13585. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  13586. N->getOperand(3), DAG.getCondCode(ISD::SETGT));
  13587. break;
  13588. case Intrinsic::aarch64_sve_fcmpeq:
  13589. case Intrinsic::aarch64_sve_cmpeq:
  13590. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  13591. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  13592. N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
  13593. break;
  13594. case Intrinsic::aarch64_sve_fcmpne:
  13595. case Intrinsic::aarch64_sve_cmpne:
  13596. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  13597. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  13598. N->getOperand(3), DAG.getCondCode(ISD::SETNE));
  13599. break;
  13600. case Intrinsic::aarch64_sve_fcmpuo:
  13601. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  13602. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  13603. N->getOperand(3), DAG.getCondCode(ISD::SETUO));
  13604. break;
  13605. case Intrinsic::aarch64_sve_fadda:
  13606. return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
  13607. case Intrinsic::aarch64_sve_faddv:
  13608. return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
  13609. case Intrinsic::aarch64_sve_fmaxnmv:
  13610. return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
  13611. case Intrinsic::aarch64_sve_fmaxv:
  13612. return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
  13613. case Intrinsic::aarch64_sve_fminnmv:
  13614. return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
  13615. case Intrinsic::aarch64_sve_fminv:
  13616. return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
  13617. case Intrinsic::aarch64_sve_sel:
  13618. return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
  13619. N->getOperand(1), N->getOperand(2), N->getOperand(3));
  13620. case Intrinsic::aarch64_sve_cmpeq_wide:
  13621. return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
  13622. case Intrinsic::aarch64_sve_cmpne_wide:
  13623. return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
  13624. case Intrinsic::aarch64_sve_cmpge_wide:
  13625. return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
  13626. case Intrinsic::aarch64_sve_cmpgt_wide:
  13627. return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
  13628. case Intrinsic::aarch64_sve_cmplt_wide:
  13629. return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
  13630. case Intrinsic::aarch64_sve_cmple_wide:
  13631. return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
  13632. case Intrinsic::aarch64_sve_cmphs_wide:
  13633. return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
  13634. case Intrinsic::aarch64_sve_cmphi_wide:
  13635. return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
  13636. case Intrinsic::aarch64_sve_cmplo_wide:
  13637. return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
  13638. case Intrinsic::aarch64_sve_cmpls_wide:
  13639. return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
  13640. case Intrinsic::aarch64_sve_ptest_any:
  13641. return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
  13642. AArch64CC::ANY_ACTIVE);
  13643. case Intrinsic::aarch64_sve_ptest_first:
  13644. return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
  13645. AArch64CC::FIRST_ACTIVE);
  13646. case Intrinsic::aarch64_sve_ptest_last:
  13647. return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
  13648. AArch64CC::LAST_ACTIVE);
  13649. }
  13650. return SDValue();
  13651. }
  13652. static bool isCheapToExtend(const SDValue &N) {
  13653. unsigned OC = N->getOpcode();
  13654. return OC == ISD::LOAD || OC == ISD::MLOAD ||
  13655. ISD::isConstantSplatVectorAllZeros(N.getNode());
  13656. }
  13657. static SDValue
  13658. performSignExtendSetCCCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
  13659. SelectionDAG &DAG) {
  13660. // If we have (sext (setcc A B)) and A and B are cheap to extend,
  13661. // we can move the sext into the arguments and have the same result. For
  13662. // example, if A and B are both loads, we can make those extending loads and
  13663. // avoid an extra instruction. This pattern appears often in VLS code
  13664. // generation where the inputs to the setcc have a different size to the
  13665. // instruction that wants to use the result of the setcc.
  13666. assert(N->getOpcode() == ISD::SIGN_EXTEND &&
  13667. N->getOperand(0)->getOpcode() == ISD::SETCC);
  13668. const SDValue SetCC = N->getOperand(0);
  13669. const SDValue CCOp0 = SetCC.getOperand(0);
  13670. const SDValue CCOp1 = SetCC.getOperand(1);
  13671. if (!CCOp0->getValueType(0).isInteger() ||
  13672. !CCOp1->getValueType(0).isInteger())
  13673. return SDValue();
  13674. ISD::CondCode Code =
  13675. cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get();
  13676. ISD::NodeType ExtType =
  13677. isSignedIntSetCC(Code) ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  13678. if (isCheapToExtend(SetCC.getOperand(0)) &&
  13679. isCheapToExtend(SetCC.getOperand(1))) {
  13680. const SDValue Ext1 =
  13681. DAG.getNode(ExtType, SDLoc(N), N->getValueType(0), CCOp0);
  13682. const SDValue Ext2 =
  13683. DAG.getNode(ExtType, SDLoc(N), N->getValueType(0), CCOp1);
  13684. return DAG.getSetCC(
  13685. SDLoc(SetCC), N->getValueType(0), Ext1, Ext2,
  13686. cast<CondCodeSDNode>(SetCC->getOperand(2).getNode())->get());
  13687. }
  13688. return SDValue();
  13689. }
  13690. static SDValue performExtendCombine(SDNode *N,
  13691. TargetLowering::DAGCombinerInfo &DCI,
  13692. SelectionDAG &DAG) {
  13693. // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
  13694. // we can convert that DUP into another extract_high (of a bigger DUP), which
  13695. // helps the backend to decide that an sabdl2 would be useful, saving a real
  13696. // extract_high operation.
  13697. if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
  13698. (N->getOperand(0).getOpcode() == ISD::ABDU ||
  13699. N->getOperand(0).getOpcode() == ISD::ABDS)) {
  13700. SDNode *ABDNode = N->getOperand(0).getNode();
  13701. SDValue NewABD =
  13702. tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG);
  13703. if (!NewABD.getNode())
  13704. return SDValue();
  13705. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD);
  13706. }
  13707. if (N->getValueType(0).isFixedLengthVector() &&
  13708. N->getOpcode() == ISD::SIGN_EXTEND &&
  13709. N->getOperand(0)->getOpcode() == ISD::SETCC)
  13710. return performSignExtendSetCCCombine(N, DCI, DAG);
  13711. return SDValue();
  13712. }
  13713. static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
  13714. SDValue SplatVal, unsigned NumVecElts) {
  13715. assert(!St.isTruncatingStore() && "cannot split truncating vector store");
  13716. unsigned OrigAlignment = St.getAlignment();
  13717. unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
  13718. // Create scalar stores. This is at least as good as the code sequence for a
  13719. // split unaligned store which is a dup.s, ext.b, and two stores.
  13720. // Most of the time the three stores should be replaced by store pair
  13721. // instructions (stp).
  13722. SDLoc DL(&St);
  13723. SDValue BasePtr = St.getBasePtr();
  13724. uint64_t BaseOffset = 0;
  13725. const MachinePointerInfo &PtrInfo = St.getPointerInfo();
  13726. SDValue NewST1 =
  13727. DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
  13728. OrigAlignment, St.getMemOperand()->getFlags());
  13729. // As this in ISel, we will not merge this add which may degrade results.
  13730. if (BasePtr->getOpcode() == ISD::ADD &&
  13731. isa<ConstantSDNode>(BasePtr->getOperand(1))) {
  13732. BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
  13733. BasePtr = BasePtr->getOperand(0);
  13734. }
  13735. unsigned Offset = EltOffset;
  13736. while (--NumVecElts) {
  13737. unsigned Alignment = MinAlign(OrigAlignment, Offset);
  13738. SDValue OffsetPtr =
  13739. DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
  13740. DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
  13741. NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
  13742. PtrInfo.getWithOffset(Offset), Alignment,
  13743. St.getMemOperand()->getFlags());
  13744. Offset += EltOffset;
  13745. }
  13746. return NewST1;
  13747. }
  13748. // Returns an SVE type that ContentTy can be trivially sign or zero extended
  13749. // into.
  13750. static MVT getSVEContainerType(EVT ContentTy) {
  13751. assert(ContentTy.isSimple() && "No SVE containers for extended types");
  13752. switch (ContentTy.getSimpleVT().SimpleTy) {
  13753. default:
  13754. llvm_unreachable("No known SVE container for this MVT type");
  13755. case MVT::nxv2i8:
  13756. case MVT::nxv2i16:
  13757. case MVT::nxv2i32:
  13758. case MVT::nxv2i64:
  13759. case MVT::nxv2f32:
  13760. case MVT::nxv2f64:
  13761. return MVT::nxv2i64;
  13762. case MVT::nxv4i8:
  13763. case MVT::nxv4i16:
  13764. case MVT::nxv4i32:
  13765. case MVT::nxv4f32:
  13766. return MVT::nxv4i32;
  13767. case MVT::nxv8i8:
  13768. case MVT::nxv8i16:
  13769. case MVT::nxv8f16:
  13770. case MVT::nxv8bf16:
  13771. return MVT::nxv8i16;
  13772. case MVT::nxv16i8:
  13773. return MVT::nxv16i8;
  13774. }
  13775. }
  13776. static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
  13777. SDLoc DL(N);
  13778. EVT VT = N->getValueType(0);
  13779. if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
  13780. return SDValue();
  13781. EVT ContainerVT = VT;
  13782. if (ContainerVT.isInteger())
  13783. ContainerVT = getSVEContainerType(ContainerVT);
  13784. SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
  13785. SDValue Ops[] = { N->getOperand(0), // Chain
  13786. N->getOperand(2), // Pg
  13787. N->getOperand(3), // Base
  13788. DAG.getValueType(VT) };
  13789. SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
  13790. SDValue LoadChain = SDValue(Load.getNode(), 1);
  13791. if (ContainerVT.isInteger() && (VT != ContainerVT))
  13792. Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
  13793. return DAG.getMergeValues({ Load, LoadChain }, DL);
  13794. }
  13795. static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
  13796. SDLoc DL(N);
  13797. EVT VT = N->getValueType(0);
  13798. EVT PtrTy = N->getOperand(3).getValueType();
  13799. if (VT == MVT::nxv8bf16 &&
  13800. !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
  13801. return SDValue();
  13802. EVT LoadVT = VT;
  13803. if (VT.isFloatingPoint())
  13804. LoadVT = VT.changeTypeToInteger();
  13805. auto *MINode = cast<MemIntrinsicSDNode>(N);
  13806. SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
  13807. SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
  13808. MINode->getOperand(3), DAG.getUNDEF(PtrTy),
  13809. MINode->getOperand(2), PassThru,
  13810. MINode->getMemoryVT(), MINode->getMemOperand(),
  13811. ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
  13812. if (VT.isFloatingPoint()) {
  13813. SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
  13814. return DAG.getMergeValues(Ops, DL);
  13815. }
  13816. return L;
  13817. }
  13818. template <unsigned Opcode>
  13819. static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
  13820. static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
  13821. Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
  13822. "Unsupported opcode.");
  13823. SDLoc DL(N);
  13824. EVT VT = N->getValueType(0);
  13825. if (VT == MVT::nxv8bf16 &&
  13826. !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
  13827. return SDValue();
  13828. EVT LoadVT = VT;
  13829. if (VT.isFloatingPoint())
  13830. LoadVT = VT.changeTypeToInteger();
  13831. SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
  13832. SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
  13833. SDValue LoadChain = SDValue(Load.getNode(), 1);
  13834. if (VT.isFloatingPoint())
  13835. Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
  13836. return DAG.getMergeValues({Load, LoadChain}, DL);
  13837. }
  13838. static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
  13839. SDLoc DL(N);
  13840. SDValue Data = N->getOperand(2);
  13841. EVT DataVT = Data.getValueType();
  13842. EVT HwSrcVt = getSVEContainerType(DataVT);
  13843. SDValue InputVT = DAG.getValueType(DataVT);
  13844. if (DataVT == MVT::nxv8bf16 &&
  13845. !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
  13846. return SDValue();
  13847. if (DataVT.isFloatingPoint())
  13848. InputVT = DAG.getValueType(HwSrcVt);
  13849. SDValue SrcNew;
  13850. if (Data.getValueType().isFloatingPoint())
  13851. SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
  13852. else
  13853. SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
  13854. SDValue Ops[] = { N->getOperand(0), // Chain
  13855. SrcNew,
  13856. N->getOperand(4), // Base
  13857. N->getOperand(3), // Pg
  13858. InputVT
  13859. };
  13860. return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
  13861. }
  13862. static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
  13863. SDLoc DL(N);
  13864. SDValue Data = N->getOperand(2);
  13865. EVT DataVT = Data.getValueType();
  13866. EVT PtrTy = N->getOperand(4).getValueType();
  13867. if (DataVT == MVT::nxv8bf16 &&
  13868. !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
  13869. return SDValue();
  13870. if (DataVT.isFloatingPoint())
  13871. Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
  13872. auto *MINode = cast<MemIntrinsicSDNode>(N);
  13873. return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
  13874. DAG.getUNDEF(PtrTy), MINode->getOperand(3),
  13875. MINode->getMemoryVT(), MINode->getMemOperand(),
  13876. ISD::UNINDEXED, false, false);
  13877. }
  13878. /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
  13879. /// load store optimizer pass will merge them to store pair stores. This should
  13880. /// be better than a movi to create the vector zero followed by a vector store
  13881. /// if the zero constant is not re-used, since one instructions and one register
  13882. /// live range will be removed.
  13883. ///
  13884. /// For example, the final generated code should be:
  13885. ///
  13886. /// stp xzr, xzr, [x0]
  13887. ///
  13888. /// instead of:
  13889. ///
  13890. /// movi v0.2d, #0
  13891. /// str q0, [x0]
  13892. ///
  13893. static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
  13894. SDValue StVal = St.getValue();
  13895. EVT VT = StVal.getValueType();
  13896. // Avoid scalarizing zero splat stores for scalable vectors.
  13897. if (VT.isScalableVector())
  13898. return SDValue();
  13899. // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
  13900. // 2, 3 or 4 i32 elements.
  13901. int NumVecElts = VT.getVectorNumElements();
  13902. if (!(((NumVecElts == 2 || NumVecElts == 3) &&
  13903. VT.getVectorElementType().getSizeInBits() == 64) ||
  13904. ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
  13905. VT.getVectorElementType().getSizeInBits() == 32)))
  13906. return SDValue();
  13907. if (StVal.getOpcode() != ISD::BUILD_VECTOR)
  13908. return SDValue();
  13909. // If the zero constant has more than one use then the vector store could be
  13910. // better since the constant mov will be amortized and stp q instructions
  13911. // should be able to be formed.
  13912. if (!StVal.hasOneUse())
  13913. return SDValue();
  13914. // If the store is truncating then it's going down to i16 or smaller, which
  13915. // means it can be implemented in a single store anyway.
  13916. if (St.isTruncatingStore())
  13917. return SDValue();
  13918. // If the immediate offset of the address operand is too large for the stp
  13919. // instruction, then bail out.
  13920. if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
  13921. int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
  13922. if (Offset < -512 || Offset > 504)
  13923. return SDValue();
  13924. }
  13925. for (int I = 0; I < NumVecElts; ++I) {
  13926. SDValue EltVal = StVal.getOperand(I);
  13927. if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
  13928. return SDValue();
  13929. }
  13930. // Use a CopyFromReg WZR/XZR here to prevent
  13931. // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
  13932. SDLoc DL(&St);
  13933. unsigned ZeroReg;
  13934. EVT ZeroVT;
  13935. if (VT.getVectorElementType().getSizeInBits() == 32) {
  13936. ZeroReg = AArch64::WZR;
  13937. ZeroVT = MVT::i32;
  13938. } else {
  13939. ZeroReg = AArch64::XZR;
  13940. ZeroVT = MVT::i64;
  13941. }
  13942. SDValue SplatVal =
  13943. DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
  13944. return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
  13945. }
  13946. /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
  13947. /// value. The load store optimizer pass will merge them to store pair stores.
  13948. /// This has better performance than a splat of the scalar followed by a split
  13949. /// vector store. Even if the stores are not merged it is four stores vs a dup,
  13950. /// followed by an ext.b and two stores.
  13951. static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
  13952. SDValue StVal = St.getValue();
  13953. EVT VT = StVal.getValueType();
  13954. // Don't replace floating point stores, they possibly won't be transformed to
  13955. // stp because of the store pair suppress pass.
  13956. if (VT.isFloatingPoint())
  13957. return SDValue();
  13958. // We can express a splat as store pair(s) for 2 or 4 elements.
  13959. unsigned NumVecElts = VT.getVectorNumElements();
  13960. if (NumVecElts != 4 && NumVecElts != 2)
  13961. return SDValue();
  13962. // If the store is truncating then it's going down to i16 or smaller, which
  13963. // means it can be implemented in a single store anyway.
  13964. if (St.isTruncatingStore())
  13965. return SDValue();
  13966. // Check that this is a splat.
  13967. // Make sure that each of the relevant vector element locations are inserted
  13968. // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
  13969. std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
  13970. SDValue SplatVal;
  13971. for (unsigned I = 0; I < NumVecElts; ++I) {
  13972. // Check for insert vector elements.
  13973. if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
  13974. return SDValue();
  13975. // Check that same value is inserted at each vector element.
  13976. if (I == 0)
  13977. SplatVal = StVal.getOperand(1);
  13978. else if (StVal.getOperand(1) != SplatVal)
  13979. return SDValue();
  13980. // Check insert element index.
  13981. ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
  13982. if (!CIndex)
  13983. return SDValue();
  13984. uint64_t IndexVal = CIndex->getZExtValue();
  13985. if (IndexVal >= NumVecElts)
  13986. return SDValue();
  13987. IndexNotInserted.reset(IndexVal);
  13988. StVal = StVal.getOperand(0);
  13989. }
  13990. // Check that all vector element locations were inserted to.
  13991. if (IndexNotInserted.any())
  13992. return SDValue();
  13993. return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
  13994. }
  13995. static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
  13996. SelectionDAG &DAG,
  13997. const AArch64Subtarget *Subtarget) {
  13998. StoreSDNode *S = cast<StoreSDNode>(N);
  13999. if (S->isVolatile() || S->isIndexed())
  14000. return SDValue();
  14001. SDValue StVal = S->getValue();
  14002. EVT VT = StVal.getValueType();
  14003. if (!VT.isFixedLengthVector())
  14004. return SDValue();
  14005. // If we get a splat of zeros, convert this vector store to a store of
  14006. // scalars. They will be merged into store pairs of xzr thereby removing one
  14007. // instruction and one register.
  14008. if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
  14009. return ReplacedZeroSplat;
  14010. // FIXME: The logic for deciding if an unaligned store should be split should
  14011. // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
  14012. // a call to that function here.
  14013. if (!Subtarget->isMisaligned128StoreSlow())
  14014. return SDValue();
  14015. // Don't split at -Oz.
  14016. if (DAG.getMachineFunction().getFunction().hasMinSize())
  14017. return SDValue();
  14018. // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
  14019. // those up regresses performance on micro-benchmarks and olden/bh.
  14020. if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
  14021. return SDValue();
  14022. // Split unaligned 16B stores. They are terrible for performance.
  14023. // Don't split stores with alignment of 1 or 2. Code that uses clang vector
  14024. // extensions can use this to mark that it does not want splitting to happen
  14025. // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
  14026. // eliminating alignment hazards is only 1 in 8 for alignment of 2.
  14027. if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
  14028. S->getAlignment() <= 2)
  14029. return SDValue();
  14030. // If we get a splat of a scalar convert this vector store to a store of
  14031. // scalars. They will be merged into store pairs thereby removing two
  14032. // instructions.
  14033. if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
  14034. return ReplacedSplat;
  14035. SDLoc DL(S);
  14036. // Split VT into two.
  14037. EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
  14038. unsigned NumElts = HalfVT.getVectorNumElements();
  14039. SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
  14040. DAG.getConstant(0, DL, MVT::i64));
  14041. SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
  14042. DAG.getConstant(NumElts, DL, MVT::i64));
  14043. SDValue BasePtr = S->getBasePtr();
  14044. SDValue NewST1 =
  14045. DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
  14046. S->getAlignment(), S->getMemOperand()->getFlags());
  14047. SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
  14048. DAG.getConstant(8, DL, MVT::i64));
  14049. return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
  14050. S->getPointerInfo(), S->getAlignment(),
  14051. S->getMemOperand()->getFlags());
  14052. }
  14053. static SDValue performSpliceCombine(SDNode *N, SelectionDAG &DAG) {
  14054. assert(N->getOpcode() == AArch64ISD::SPLICE && "Unexepected Opcode!");
  14055. // splice(pg, op1, undef) -> op1
  14056. if (N->getOperand(2).isUndef())
  14057. return N->getOperand(1);
  14058. return SDValue();
  14059. }
  14060. static SDValue performUnpackCombine(SDNode *N, SelectionDAG &DAG) {
  14061. assert((N->getOpcode() == AArch64ISD::UUNPKHI ||
  14062. N->getOpcode() == AArch64ISD::UUNPKLO) &&
  14063. "Unexpected Opcode!");
  14064. // uunpklo/hi undef -> undef
  14065. if (N->getOperand(0).isUndef())
  14066. return DAG.getUNDEF(N->getValueType(0));
  14067. return SDValue();
  14068. }
  14069. static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) {
  14070. SDLoc DL(N);
  14071. SDValue Op0 = N->getOperand(0);
  14072. SDValue Op1 = N->getOperand(1);
  14073. EVT ResVT = N->getValueType(0);
  14074. // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z)
  14075. if (Op0.getOpcode() == AArch64ISD::UUNPKLO) {
  14076. if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
  14077. SDValue X = Op0.getOperand(0).getOperand(0);
  14078. return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1);
  14079. }
  14080. }
  14081. // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z)
  14082. if (Op1.getOpcode() == AArch64ISD::UUNPKHI) {
  14083. if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
  14084. SDValue Z = Op1.getOperand(0).getOperand(1);
  14085. return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z);
  14086. }
  14087. }
  14088. return SDValue();
  14089. }
  14090. static SDValue performGLD1Combine(SDNode *N, SelectionDAG &DAG) {
  14091. unsigned Opc = N->getOpcode();
  14092. assert(((Opc >= AArch64ISD::GLD1_MERGE_ZERO && // unsigned gather loads
  14093. Opc <= AArch64ISD::GLD1_IMM_MERGE_ZERO) ||
  14094. (Opc >= AArch64ISD::GLD1S_MERGE_ZERO && // signed gather loads
  14095. Opc <= AArch64ISD::GLD1S_IMM_MERGE_ZERO)) &&
  14096. "Invalid opcode.");
  14097. const bool Scaled = Opc == AArch64ISD::GLD1_SCALED_MERGE_ZERO ||
  14098. Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
  14099. const bool Signed = Opc == AArch64ISD::GLD1S_MERGE_ZERO ||
  14100. Opc == AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
  14101. const bool Extended = Opc == AArch64ISD::GLD1_SXTW_MERGE_ZERO ||
  14102. Opc == AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO ||
  14103. Opc == AArch64ISD::GLD1_UXTW_MERGE_ZERO ||
  14104. Opc == AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO;
  14105. SDLoc DL(N);
  14106. SDValue Chain = N->getOperand(0);
  14107. SDValue Pg = N->getOperand(1);
  14108. SDValue Base = N->getOperand(2);
  14109. SDValue Offset = N->getOperand(3);
  14110. SDValue Ty = N->getOperand(4);
  14111. EVT ResVT = N->getValueType(0);
  14112. const auto OffsetOpc = Offset.getOpcode();
  14113. const bool OffsetIsZExt =
  14114. OffsetOpc == AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU;
  14115. const bool OffsetIsSExt =
  14116. OffsetOpc == AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU;
  14117. // Fold sign/zero extensions of vector offsets into GLD1 nodes where possible.
  14118. if (!Extended && (OffsetIsSExt || OffsetIsZExt)) {
  14119. SDValue ExtPg = Offset.getOperand(0);
  14120. VTSDNode *ExtFrom = cast<VTSDNode>(Offset.getOperand(2).getNode());
  14121. EVT ExtFromEVT = ExtFrom->getVT().getVectorElementType();
  14122. // If the predicate for the sign- or zero-extended offset is the
  14123. // same as the predicate used for this load and the sign-/zero-extension
  14124. // was from a 32-bits...
  14125. if (ExtPg == Pg && ExtFromEVT == MVT::i32) {
  14126. SDValue UnextendedOffset = Offset.getOperand(1);
  14127. unsigned NewOpc = getGatherVecOpcode(Scaled, OffsetIsSExt, true);
  14128. if (Signed)
  14129. NewOpc = getSignExtendedGatherOpcode(NewOpc);
  14130. return DAG.getNode(NewOpc, DL, {ResVT, MVT::Other},
  14131. {Chain, Pg, Base, UnextendedOffset, Ty});
  14132. }
  14133. }
  14134. return SDValue();
  14135. }
  14136. /// Optimize a vector shift instruction and its operand if shifted out
  14137. /// bits are not used.
  14138. static SDValue performVectorShiftCombine(SDNode *N,
  14139. const AArch64TargetLowering &TLI,
  14140. TargetLowering::DAGCombinerInfo &DCI) {
  14141. assert(N->getOpcode() == AArch64ISD::VASHR ||
  14142. N->getOpcode() == AArch64ISD::VLSHR);
  14143. SDValue Op = N->getOperand(0);
  14144. unsigned OpScalarSize = Op.getScalarValueSizeInBits();
  14145. unsigned ShiftImm = N->getConstantOperandVal(1);
  14146. assert(OpScalarSize > ShiftImm && "Invalid shift imm");
  14147. APInt ShiftedOutBits = APInt::getLowBitsSet(OpScalarSize, ShiftImm);
  14148. APInt DemandedMask = ~ShiftedOutBits;
  14149. if (TLI.SimplifyDemandedBits(Op, DemandedMask, DCI))
  14150. return SDValue(N, 0);
  14151. return SDValue();
  14152. }
  14153. static SDValue performSunpkloCombine(SDNode *N, SelectionDAG &DAG) {
  14154. // sunpklo(sext(pred)) -> sext(extract_low_half(pred))
  14155. // This transform works in partnership with performSetCCPunpkCombine to
  14156. // remove unnecessary transfer of predicates into standard registers and back
  14157. if (N->getOperand(0).getOpcode() == ISD::SIGN_EXTEND &&
  14158. N->getOperand(0)->getOperand(0)->getValueType(0).getScalarType() ==
  14159. MVT::i1) {
  14160. SDValue CC = N->getOperand(0)->getOperand(0);
  14161. auto VT = CC->getValueType(0).getHalfNumVectorElementsVT(*DAG.getContext());
  14162. SDValue Unpk = DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), VT, CC,
  14163. DAG.getVectorIdxConstant(0, SDLoc(N)));
  14164. return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), N->getValueType(0), Unpk);
  14165. }
  14166. return SDValue();
  14167. }
  14168. /// Target-specific DAG combine function for post-increment LD1 (lane) and
  14169. /// post-increment LD1R.
  14170. static SDValue performPostLD1Combine(SDNode *N,
  14171. TargetLowering::DAGCombinerInfo &DCI,
  14172. bool IsLaneOp) {
  14173. if (DCI.isBeforeLegalizeOps())
  14174. return SDValue();
  14175. SelectionDAG &DAG = DCI.DAG;
  14176. EVT VT = N->getValueType(0);
  14177. if (!VT.is128BitVector() && !VT.is64BitVector())
  14178. return SDValue();
  14179. unsigned LoadIdx = IsLaneOp ? 1 : 0;
  14180. SDNode *LD = N->getOperand(LoadIdx).getNode();
  14181. // If it is not LOAD, can not do such combine.
  14182. if (LD->getOpcode() != ISD::LOAD)
  14183. return SDValue();
  14184. // The vector lane must be a constant in the LD1LANE opcode.
  14185. SDValue Lane;
  14186. if (IsLaneOp) {
  14187. Lane = N->getOperand(2);
  14188. auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
  14189. if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
  14190. return SDValue();
  14191. }
  14192. LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
  14193. EVT MemVT = LoadSDN->getMemoryVT();
  14194. // Check if memory operand is the same type as the vector element.
  14195. if (MemVT != VT.getVectorElementType())
  14196. return SDValue();
  14197. // Check if there are other uses. If so, do not combine as it will introduce
  14198. // an extra load.
  14199. for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
  14200. ++UI) {
  14201. if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
  14202. continue;
  14203. if (*UI != N)
  14204. return SDValue();
  14205. }
  14206. SDValue Addr = LD->getOperand(1);
  14207. SDValue Vector = N->getOperand(0);
  14208. // Search for a use of the address operand that is an increment.
  14209. for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
  14210. Addr.getNode()->use_end(); UI != UE; ++UI) {
  14211. SDNode *User = *UI;
  14212. if (User->getOpcode() != ISD::ADD
  14213. || UI.getUse().getResNo() != Addr.getResNo())
  14214. continue;
  14215. // If the increment is a constant, it must match the memory ref size.
  14216. SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
  14217. if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
  14218. uint32_t IncVal = CInc->getZExtValue();
  14219. unsigned NumBytes = VT.getScalarSizeInBits() / 8;
  14220. if (IncVal != NumBytes)
  14221. continue;
  14222. Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
  14223. }
  14224. // To avoid cycle construction make sure that neither the load nor the add
  14225. // are predecessors to each other or the Vector.
  14226. SmallPtrSet<const SDNode *, 32> Visited;
  14227. SmallVector<const SDNode *, 16> Worklist;
  14228. Visited.insert(Addr.getNode());
  14229. Worklist.push_back(User);
  14230. Worklist.push_back(LD);
  14231. Worklist.push_back(Vector.getNode());
  14232. if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
  14233. SDNode::hasPredecessorHelper(User, Visited, Worklist))
  14234. continue;
  14235. SmallVector<SDValue, 8> Ops;
  14236. Ops.push_back(LD->getOperand(0)); // Chain
  14237. if (IsLaneOp) {
  14238. Ops.push_back(Vector); // The vector to be inserted
  14239. Ops.push_back(Lane); // The lane to be inserted in the vector
  14240. }
  14241. Ops.push_back(Addr);
  14242. Ops.push_back(Inc);
  14243. EVT Tys[3] = { VT, MVT::i64, MVT::Other };
  14244. SDVTList SDTys = DAG.getVTList(Tys);
  14245. unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
  14246. SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
  14247. MemVT,
  14248. LoadSDN->getMemOperand());
  14249. // Update the uses.
  14250. SDValue NewResults[] = {
  14251. SDValue(LD, 0), // The result of load
  14252. SDValue(UpdN.getNode(), 2) // Chain
  14253. };
  14254. DCI.CombineTo(LD, NewResults);
  14255. DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
  14256. DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
  14257. break;
  14258. }
  14259. return SDValue();
  14260. }
  14261. /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
  14262. /// address translation.
  14263. static bool performTBISimplification(SDValue Addr,
  14264. TargetLowering::DAGCombinerInfo &DCI,
  14265. SelectionDAG &DAG) {
  14266. APInt DemandedMask = APInt::getLowBitsSet(64, 56);
  14267. KnownBits Known;
  14268. TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
  14269. !DCI.isBeforeLegalizeOps());
  14270. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  14271. if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
  14272. DCI.CommitTargetLoweringOpt(TLO);
  14273. return true;
  14274. }
  14275. return false;
  14276. }
  14277. static SDValue foldTruncStoreOfExt(SelectionDAG &DAG, SDNode *N) {
  14278. assert((N->getOpcode() == ISD::STORE || N->getOpcode() == ISD::MSTORE) &&
  14279. "Expected STORE dag node in input!");
  14280. if (auto Store = dyn_cast<StoreSDNode>(N)) {
  14281. if (!Store->isTruncatingStore() || Store->isIndexed())
  14282. return SDValue();
  14283. SDValue Ext = Store->getValue();
  14284. auto ExtOpCode = Ext.getOpcode();
  14285. if (ExtOpCode != ISD::ZERO_EXTEND && ExtOpCode != ISD::SIGN_EXTEND &&
  14286. ExtOpCode != ISD::ANY_EXTEND)
  14287. return SDValue();
  14288. SDValue Orig = Ext->getOperand(0);
  14289. if (Store->getMemoryVT() != Orig.getValueType())
  14290. return SDValue();
  14291. return DAG.getStore(Store->getChain(), SDLoc(Store), Orig,
  14292. Store->getBasePtr(), Store->getMemOperand());
  14293. }
  14294. return SDValue();
  14295. }
  14296. static SDValue performSTORECombine(SDNode *N,
  14297. TargetLowering::DAGCombinerInfo &DCI,
  14298. SelectionDAG &DAG,
  14299. const AArch64Subtarget *Subtarget) {
  14300. StoreSDNode *ST = cast<StoreSDNode>(N);
  14301. SDValue Chain = ST->getChain();
  14302. SDValue Value = ST->getValue();
  14303. SDValue Ptr = ST->getBasePtr();
  14304. // If this is an FP_ROUND followed by a store, fold this into a truncating
  14305. // store. We can do this even if this is already a truncstore.
  14306. // We purposefully don't care about legality of the nodes here as we know
  14307. // they can be split down into something legal.
  14308. if (DCI.isBeforeLegalizeOps() && Value.getOpcode() == ISD::FP_ROUND &&
  14309. Value.getNode()->hasOneUse() && ST->isUnindexed() &&
  14310. Subtarget->useSVEForFixedLengthVectors() &&
  14311. Value.getValueType().isFixedLengthVector() &&
  14312. Value.getValueType().getFixedSizeInBits() >=
  14313. Subtarget->getMinSVEVectorSizeInBits())
  14314. return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
  14315. ST->getMemoryVT(), ST->getMemOperand());
  14316. if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
  14317. return Split;
  14318. if (Subtarget->supportsAddressTopByteIgnored() &&
  14319. performTBISimplification(N->getOperand(2), DCI, DAG))
  14320. return SDValue(N, 0);
  14321. if (SDValue Store = foldTruncStoreOfExt(DAG, N))
  14322. return Store;
  14323. return SDValue();
  14324. }
  14325. /// Target-specific DAG combine function for NEON load/store intrinsics
  14326. /// to merge base address updates.
  14327. static SDValue performNEONPostLDSTCombine(SDNode *N,
  14328. TargetLowering::DAGCombinerInfo &DCI,
  14329. SelectionDAG &DAG) {
  14330. if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
  14331. return SDValue();
  14332. unsigned AddrOpIdx = N->getNumOperands() - 1;
  14333. SDValue Addr = N->getOperand(AddrOpIdx);
  14334. // Search for a use of the address operand that is an increment.
  14335. for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
  14336. UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
  14337. SDNode *User = *UI;
  14338. if (User->getOpcode() != ISD::ADD ||
  14339. UI.getUse().getResNo() != Addr.getResNo())
  14340. continue;
  14341. // Check that the add is independent of the load/store. Otherwise, folding
  14342. // it would create a cycle.
  14343. SmallPtrSet<const SDNode *, 32> Visited;
  14344. SmallVector<const SDNode *, 16> Worklist;
  14345. Visited.insert(Addr.getNode());
  14346. Worklist.push_back(N);
  14347. Worklist.push_back(User);
  14348. if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
  14349. SDNode::hasPredecessorHelper(User, Visited, Worklist))
  14350. continue;
  14351. // Find the new opcode for the updating load/store.
  14352. bool IsStore = false;
  14353. bool IsLaneOp = false;
  14354. bool IsDupOp = false;
  14355. unsigned NewOpc = 0;
  14356. unsigned NumVecs = 0;
  14357. unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
  14358. switch (IntNo) {
  14359. default: llvm_unreachable("unexpected intrinsic for Neon base update");
  14360. case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
  14361. NumVecs = 2; break;
  14362. case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
  14363. NumVecs = 3; break;
  14364. case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
  14365. NumVecs = 4; break;
  14366. case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
  14367. NumVecs = 2; IsStore = true; break;
  14368. case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
  14369. NumVecs = 3; IsStore = true; break;
  14370. case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
  14371. NumVecs = 4; IsStore = true; break;
  14372. case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
  14373. NumVecs = 2; break;
  14374. case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
  14375. NumVecs = 3; break;
  14376. case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
  14377. NumVecs = 4; break;
  14378. case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
  14379. NumVecs = 2; IsStore = true; break;
  14380. case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
  14381. NumVecs = 3; IsStore = true; break;
  14382. case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
  14383. NumVecs = 4; IsStore = true; break;
  14384. case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
  14385. NumVecs = 2; IsDupOp = true; break;
  14386. case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
  14387. NumVecs = 3; IsDupOp = true; break;
  14388. case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
  14389. NumVecs = 4; IsDupOp = true; break;
  14390. case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
  14391. NumVecs = 2; IsLaneOp = true; break;
  14392. case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
  14393. NumVecs = 3; IsLaneOp = true; break;
  14394. case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
  14395. NumVecs = 4; IsLaneOp = true; break;
  14396. case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
  14397. NumVecs = 2; IsStore = true; IsLaneOp = true; break;
  14398. case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
  14399. NumVecs = 3; IsStore = true; IsLaneOp = true; break;
  14400. case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
  14401. NumVecs = 4; IsStore = true; IsLaneOp = true; break;
  14402. }
  14403. EVT VecTy;
  14404. if (IsStore)
  14405. VecTy = N->getOperand(2).getValueType();
  14406. else
  14407. VecTy = N->getValueType(0);
  14408. // If the increment is a constant, it must match the memory ref size.
  14409. SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
  14410. if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
  14411. uint32_t IncVal = CInc->getZExtValue();
  14412. unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
  14413. if (IsLaneOp || IsDupOp)
  14414. NumBytes /= VecTy.getVectorNumElements();
  14415. if (IncVal != NumBytes)
  14416. continue;
  14417. Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
  14418. }
  14419. SmallVector<SDValue, 8> Ops;
  14420. Ops.push_back(N->getOperand(0)); // Incoming chain
  14421. // Load lane and store have vector list as input.
  14422. if (IsLaneOp || IsStore)
  14423. for (unsigned i = 2; i < AddrOpIdx; ++i)
  14424. Ops.push_back(N->getOperand(i));
  14425. Ops.push_back(Addr); // Base register
  14426. Ops.push_back(Inc);
  14427. // Return Types.
  14428. EVT Tys[6];
  14429. unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
  14430. unsigned n;
  14431. for (n = 0; n < NumResultVecs; ++n)
  14432. Tys[n] = VecTy;
  14433. Tys[n++] = MVT::i64; // Type of write back register
  14434. Tys[n] = MVT::Other; // Type of the chain
  14435. SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
  14436. MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
  14437. SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
  14438. MemInt->getMemoryVT(),
  14439. MemInt->getMemOperand());
  14440. // Update the uses.
  14441. std::vector<SDValue> NewResults;
  14442. for (unsigned i = 0; i < NumResultVecs; ++i) {
  14443. NewResults.push_back(SDValue(UpdN.getNode(), i));
  14444. }
  14445. NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
  14446. DCI.CombineTo(N, NewResults);
  14447. DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
  14448. break;
  14449. }
  14450. return SDValue();
  14451. }
  14452. // Checks to see if the value is the prescribed width and returns information
  14453. // about its extension mode.
  14454. static
  14455. bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
  14456. ExtType = ISD::NON_EXTLOAD;
  14457. switch(V.getNode()->getOpcode()) {
  14458. default:
  14459. return false;
  14460. case ISD::LOAD: {
  14461. LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
  14462. if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
  14463. || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
  14464. ExtType = LoadNode->getExtensionType();
  14465. return true;
  14466. }
  14467. return false;
  14468. }
  14469. case ISD::AssertSext: {
  14470. VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
  14471. if ((TypeNode->getVT() == MVT::i8 && width == 8)
  14472. || (TypeNode->getVT() == MVT::i16 && width == 16)) {
  14473. ExtType = ISD::SEXTLOAD;
  14474. return true;
  14475. }
  14476. return false;
  14477. }
  14478. case ISD::AssertZext: {
  14479. VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
  14480. if ((TypeNode->getVT() == MVT::i8 && width == 8)
  14481. || (TypeNode->getVT() == MVT::i16 && width == 16)) {
  14482. ExtType = ISD::ZEXTLOAD;
  14483. return true;
  14484. }
  14485. return false;
  14486. }
  14487. case ISD::Constant:
  14488. case ISD::TargetConstant: {
  14489. return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
  14490. 1LL << (width - 1);
  14491. }
  14492. }
  14493. return true;
  14494. }
  14495. // This function does a whole lot of voodoo to determine if the tests are
  14496. // equivalent without and with a mask. Essentially what happens is that given a
  14497. // DAG resembling:
  14498. //
  14499. // +-------------+ +-------------+ +-------------+ +-------------+
  14500. // | Input | | AddConstant | | CompConstant| | CC |
  14501. // +-------------+ +-------------+ +-------------+ +-------------+
  14502. // | | | |
  14503. // V V | +----------+
  14504. // +-------------+ +----+ | |
  14505. // | ADD | |0xff| | |
  14506. // +-------------+ +----+ | |
  14507. // | | | |
  14508. // V V | |
  14509. // +-------------+ | |
  14510. // | AND | | |
  14511. // +-------------+ | |
  14512. // | | |
  14513. // +-----+ | |
  14514. // | | |
  14515. // V V V
  14516. // +-------------+
  14517. // | CMP |
  14518. // +-------------+
  14519. //
  14520. // The AND node may be safely removed for some combinations of inputs. In
  14521. // particular we need to take into account the extension type of the Input,
  14522. // the exact values of AddConstant, CompConstant, and CC, along with the nominal
  14523. // width of the input (this can work for any width inputs, the above graph is
  14524. // specific to 8 bits.
  14525. //
  14526. // The specific equations were worked out by generating output tables for each
  14527. // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
  14528. // problem was simplified by working with 4 bit inputs, which means we only
  14529. // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
  14530. // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
  14531. // patterns present in both extensions (0,7). For every distinct set of
  14532. // AddConstant and CompConstants bit patterns we can consider the masked and
  14533. // unmasked versions to be equivalent if the result of this function is true for
  14534. // all 16 distinct bit patterns of for the current extension type of Input (w0).
  14535. //
  14536. // sub w8, w0, w1
  14537. // and w10, w8, #0x0f
  14538. // cmp w8, w2
  14539. // cset w9, AArch64CC
  14540. // cmp w10, w2
  14541. // cset w11, AArch64CC
  14542. // cmp w9, w11
  14543. // cset w0, eq
  14544. // ret
  14545. //
  14546. // Since the above function shows when the outputs are equivalent it defines
  14547. // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
  14548. // would be expensive to run during compiles. The equations below were written
  14549. // in a test harness that confirmed they gave equivalent outputs to the above
  14550. // for all inputs function, so they can be used determine if the removal is
  14551. // legal instead.
  14552. //
  14553. // isEquivalentMaskless() is the code for testing if the AND can be removed
  14554. // factored out of the DAG recognition as the DAG can take several forms.
  14555. static bool isEquivalentMaskless(unsigned CC, unsigned width,
  14556. ISD::LoadExtType ExtType, int AddConstant,
  14557. int CompConstant) {
  14558. // By being careful about our equations and only writing the in term
  14559. // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
  14560. // make them generally applicable to all bit widths.
  14561. int MaxUInt = (1 << width);
  14562. // For the purposes of these comparisons sign extending the type is
  14563. // equivalent to zero extending the add and displacing it by half the integer
  14564. // width. Provided we are careful and make sure our equations are valid over
  14565. // the whole range we can just adjust the input and avoid writing equations
  14566. // for sign extended inputs.
  14567. if (ExtType == ISD::SEXTLOAD)
  14568. AddConstant -= (1 << (width-1));
  14569. switch(CC) {
  14570. case AArch64CC::LE:
  14571. case AArch64CC::GT:
  14572. if ((AddConstant == 0) ||
  14573. (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
  14574. (AddConstant >= 0 && CompConstant < 0) ||
  14575. (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
  14576. return true;
  14577. break;
  14578. case AArch64CC::LT:
  14579. case AArch64CC::GE:
  14580. if ((AddConstant == 0) ||
  14581. (AddConstant >= 0 && CompConstant <= 0) ||
  14582. (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
  14583. return true;
  14584. break;
  14585. case AArch64CC::HI:
  14586. case AArch64CC::LS:
  14587. if ((AddConstant >= 0 && CompConstant < 0) ||
  14588. (AddConstant <= 0 && CompConstant >= -1 &&
  14589. CompConstant < AddConstant + MaxUInt))
  14590. return true;
  14591. break;
  14592. case AArch64CC::PL:
  14593. case AArch64CC::MI:
  14594. if ((AddConstant == 0) ||
  14595. (AddConstant > 0 && CompConstant <= 0) ||
  14596. (AddConstant < 0 && CompConstant <= AddConstant))
  14597. return true;
  14598. break;
  14599. case AArch64CC::LO:
  14600. case AArch64CC::HS:
  14601. if ((AddConstant >= 0 && CompConstant <= 0) ||
  14602. (AddConstant <= 0 && CompConstant >= 0 &&
  14603. CompConstant <= AddConstant + MaxUInt))
  14604. return true;
  14605. break;
  14606. case AArch64CC::EQ:
  14607. case AArch64CC::NE:
  14608. if ((AddConstant > 0 && CompConstant < 0) ||
  14609. (AddConstant < 0 && CompConstant >= 0 &&
  14610. CompConstant < AddConstant + MaxUInt) ||
  14611. (AddConstant >= 0 && CompConstant >= 0 &&
  14612. CompConstant >= AddConstant) ||
  14613. (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
  14614. return true;
  14615. break;
  14616. case AArch64CC::VS:
  14617. case AArch64CC::VC:
  14618. case AArch64CC::AL:
  14619. case AArch64CC::NV:
  14620. return true;
  14621. case AArch64CC::Invalid:
  14622. break;
  14623. }
  14624. return false;
  14625. }
  14626. static
  14627. SDValue performCONDCombine(SDNode *N,
  14628. TargetLowering::DAGCombinerInfo &DCI,
  14629. SelectionDAG &DAG, unsigned CCIndex,
  14630. unsigned CmpIndex) {
  14631. unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
  14632. SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
  14633. unsigned CondOpcode = SubsNode->getOpcode();
  14634. if (CondOpcode != AArch64ISD::SUBS)
  14635. return SDValue();
  14636. // There is a SUBS feeding this condition. Is it fed by a mask we can
  14637. // use?
  14638. SDNode *AndNode = SubsNode->getOperand(0).getNode();
  14639. unsigned MaskBits = 0;
  14640. if (AndNode->getOpcode() != ISD::AND)
  14641. return SDValue();
  14642. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
  14643. uint32_t CNV = CN->getZExtValue();
  14644. if (CNV == 255)
  14645. MaskBits = 8;
  14646. else if (CNV == 65535)
  14647. MaskBits = 16;
  14648. }
  14649. if (!MaskBits)
  14650. return SDValue();
  14651. SDValue AddValue = AndNode->getOperand(0);
  14652. if (AddValue.getOpcode() != ISD::ADD)
  14653. return SDValue();
  14654. // The basic dag structure is correct, grab the inputs and validate them.
  14655. SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
  14656. SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
  14657. SDValue SubsInputValue = SubsNode->getOperand(1);
  14658. // The mask is present and the provenance of all the values is a smaller type,
  14659. // lets see if the mask is superfluous.
  14660. if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
  14661. !isa<ConstantSDNode>(SubsInputValue.getNode()))
  14662. return SDValue();
  14663. ISD::LoadExtType ExtType;
  14664. if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
  14665. !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
  14666. !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
  14667. return SDValue();
  14668. if(!isEquivalentMaskless(CC, MaskBits, ExtType,
  14669. cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
  14670. cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
  14671. return SDValue();
  14672. // The AND is not necessary, remove it.
  14673. SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
  14674. SubsNode->getValueType(1));
  14675. SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
  14676. SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
  14677. DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
  14678. return SDValue(N, 0);
  14679. }
  14680. // Optimize compare with zero and branch.
  14681. static SDValue performBRCONDCombine(SDNode *N,
  14682. TargetLowering::DAGCombinerInfo &DCI,
  14683. SelectionDAG &DAG) {
  14684. MachineFunction &MF = DAG.getMachineFunction();
  14685. // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
  14686. // will not be produced, as they are conditional branch instructions that do
  14687. // not set flags.
  14688. if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
  14689. return SDValue();
  14690. if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
  14691. N = NV.getNode();
  14692. SDValue Chain = N->getOperand(0);
  14693. SDValue Dest = N->getOperand(1);
  14694. SDValue CCVal = N->getOperand(2);
  14695. SDValue Cmp = N->getOperand(3);
  14696. assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
  14697. unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
  14698. if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
  14699. return SDValue();
  14700. unsigned CmpOpc = Cmp.getOpcode();
  14701. if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
  14702. return SDValue();
  14703. // Only attempt folding if there is only one use of the flag and no use of the
  14704. // value.
  14705. if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
  14706. return SDValue();
  14707. SDValue LHS = Cmp.getOperand(0);
  14708. SDValue RHS = Cmp.getOperand(1);
  14709. assert(LHS.getValueType() == RHS.getValueType() &&
  14710. "Expected the value type to be the same for both operands!");
  14711. if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
  14712. return SDValue();
  14713. if (isNullConstant(LHS))
  14714. std::swap(LHS, RHS);
  14715. if (!isNullConstant(RHS))
  14716. return SDValue();
  14717. if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
  14718. LHS.getOpcode() == ISD::SRL)
  14719. return SDValue();
  14720. // Fold the compare into the branch instruction.
  14721. SDValue BR;
  14722. if (CC == AArch64CC::EQ)
  14723. BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
  14724. else
  14725. BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
  14726. // Do not add new nodes to DAG combiner worklist.
  14727. DCI.CombineTo(N, BR, false);
  14728. return SDValue();
  14729. }
  14730. // Optimize CSEL instructions
  14731. static SDValue performCSELCombine(SDNode *N,
  14732. TargetLowering::DAGCombinerInfo &DCI,
  14733. SelectionDAG &DAG) {
  14734. // CSEL x, x, cc -> x
  14735. if (N->getOperand(0) == N->getOperand(1))
  14736. return N->getOperand(0);
  14737. return performCONDCombine(N, DCI, DAG, 2, 3);
  14738. }
  14739. static SDValue performSETCCCombine(SDNode *N, SelectionDAG &DAG) {
  14740. assert(N->getOpcode() == ISD::SETCC && "Unexpected opcode!");
  14741. SDValue LHS = N->getOperand(0);
  14742. SDValue RHS = N->getOperand(1);
  14743. ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
  14744. // setcc (csel 0, 1, cond, X), 1, ne ==> csel 0, 1, !cond, X
  14745. if (Cond == ISD::SETNE && isOneConstant(RHS) &&
  14746. LHS->getOpcode() == AArch64ISD::CSEL &&
  14747. isNullConstant(LHS->getOperand(0)) && isOneConstant(LHS->getOperand(1)) &&
  14748. LHS->hasOneUse()) {
  14749. SDLoc DL(N);
  14750. // Invert CSEL's condition.
  14751. auto *OpCC = cast<ConstantSDNode>(LHS.getOperand(2));
  14752. auto OldCond = static_cast<AArch64CC::CondCode>(OpCC->getZExtValue());
  14753. auto NewCond = getInvertedCondCode(OldCond);
  14754. // csel 0, 1, !cond, X
  14755. SDValue CSEL =
  14756. DAG.getNode(AArch64ISD::CSEL, DL, LHS.getValueType(), LHS.getOperand(0),
  14757. LHS.getOperand(1), DAG.getConstant(NewCond, DL, MVT::i32),
  14758. LHS.getOperand(3));
  14759. return DAG.getZExtOrTrunc(CSEL, DL, N->getValueType(0));
  14760. }
  14761. return SDValue();
  14762. }
  14763. static SDValue performSetCCPunpkCombine(SDNode *N, SelectionDAG &DAG) {
  14764. // setcc_merge_zero pred
  14765. // (sign_extend (extract_subvector (setcc_merge_zero ... pred ...))), 0, ne
  14766. // => extract_subvector (inner setcc_merge_zero)
  14767. SDValue Pred = N->getOperand(0);
  14768. SDValue LHS = N->getOperand(1);
  14769. SDValue RHS = N->getOperand(2);
  14770. ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(3))->get();
  14771. if (Cond != ISD::SETNE || !isZerosVector(RHS.getNode()) ||
  14772. LHS->getOpcode() != ISD::SIGN_EXTEND)
  14773. return SDValue();
  14774. SDValue Extract = LHS->getOperand(0);
  14775. if (Extract->getOpcode() != ISD::EXTRACT_SUBVECTOR ||
  14776. Extract->getValueType(0) != N->getValueType(0) ||
  14777. Extract->getConstantOperandVal(1) != 0)
  14778. return SDValue();
  14779. SDValue InnerSetCC = Extract->getOperand(0);
  14780. if (InnerSetCC->getOpcode() != AArch64ISD::SETCC_MERGE_ZERO)
  14781. return SDValue();
  14782. // By this point we've effectively got
  14783. // zero_inactive_lanes_and_trunc_i1(sext_i1(A)). If we can prove A's inactive
  14784. // lanes are already zero then the trunc(sext()) sequence is redundant and we
  14785. // can operate on A directly.
  14786. SDValue InnerPred = InnerSetCC.getOperand(0);
  14787. if (Pred.getOpcode() == AArch64ISD::PTRUE &&
  14788. InnerPred.getOpcode() == AArch64ISD::PTRUE &&
  14789. Pred.getConstantOperandVal(0) == InnerPred.getConstantOperandVal(0) &&
  14790. Pred->getConstantOperandVal(0) >= AArch64SVEPredPattern::vl1 &&
  14791. Pred->getConstantOperandVal(0) <= AArch64SVEPredPattern::vl256)
  14792. return Extract;
  14793. return SDValue();
  14794. }
  14795. static SDValue performSetccMergeZeroCombine(SDNode *N, SelectionDAG &DAG) {
  14796. assert(N->getOpcode() == AArch64ISD::SETCC_MERGE_ZERO &&
  14797. "Unexpected opcode!");
  14798. SDValue Pred = N->getOperand(0);
  14799. SDValue LHS = N->getOperand(1);
  14800. SDValue RHS = N->getOperand(2);
  14801. ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(3))->get();
  14802. // setcc_merge_zero pred (sign_extend (setcc_merge_zero ... pred ...)), 0, ne
  14803. // => inner setcc_merge_zero
  14804. if (Cond == ISD::SETNE && isZerosVector(RHS.getNode()) &&
  14805. LHS->getOpcode() == ISD::SIGN_EXTEND &&
  14806. LHS->getOperand(0)->getValueType(0) == N->getValueType(0) &&
  14807. LHS->getOperand(0)->getOpcode() == AArch64ISD::SETCC_MERGE_ZERO &&
  14808. LHS->getOperand(0)->getOperand(0) == Pred)
  14809. return LHS->getOperand(0);
  14810. if (SDValue V = performSetCCPunpkCombine(N, DAG))
  14811. return V;
  14812. return SDValue();
  14813. }
  14814. // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
  14815. // as well as whether the test should be inverted. This code is required to
  14816. // catch these cases (as opposed to standard dag combines) because
  14817. // AArch64ISD::TBZ is matched during legalization.
  14818. static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
  14819. SelectionDAG &DAG) {
  14820. if (!Op->hasOneUse())
  14821. return Op;
  14822. // We don't handle undef/constant-fold cases below, as they should have
  14823. // already been taken care of (e.g. and of 0, test of undefined shifted bits,
  14824. // etc.)
  14825. // (tbz (trunc x), b) -> (tbz x, b)
  14826. // This case is just here to enable more of the below cases to be caught.
  14827. if (Op->getOpcode() == ISD::TRUNCATE &&
  14828. Bit < Op->getValueType(0).getSizeInBits()) {
  14829. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  14830. }
  14831. // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
  14832. if (Op->getOpcode() == ISD::ANY_EXTEND &&
  14833. Bit < Op->getOperand(0).getValueSizeInBits()) {
  14834. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  14835. }
  14836. if (Op->getNumOperands() != 2)
  14837. return Op;
  14838. auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
  14839. if (!C)
  14840. return Op;
  14841. switch (Op->getOpcode()) {
  14842. default:
  14843. return Op;
  14844. // (tbz (and x, m), b) -> (tbz x, b)
  14845. case ISD::AND:
  14846. if ((C->getZExtValue() >> Bit) & 1)
  14847. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  14848. return Op;
  14849. // (tbz (shl x, c), b) -> (tbz x, b-c)
  14850. case ISD::SHL:
  14851. if (C->getZExtValue() <= Bit &&
  14852. (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
  14853. Bit = Bit - C->getZExtValue();
  14854. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  14855. }
  14856. return Op;
  14857. // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
  14858. case ISD::SRA:
  14859. Bit = Bit + C->getZExtValue();
  14860. if (Bit >= Op->getValueType(0).getSizeInBits())
  14861. Bit = Op->getValueType(0).getSizeInBits() - 1;
  14862. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  14863. // (tbz (srl x, c), b) -> (tbz x, b+c)
  14864. case ISD::SRL:
  14865. if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
  14866. Bit = Bit + C->getZExtValue();
  14867. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  14868. }
  14869. return Op;
  14870. // (tbz (xor x, -1), b) -> (tbnz x, b)
  14871. case ISD::XOR:
  14872. if ((C->getZExtValue() >> Bit) & 1)
  14873. Invert = !Invert;
  14874. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  14875. }
  14876. }
  14877. // Optimize test single bit zero/non-zero and branch.
  14878. static SDValue performTBZCombine(SDNode *N,
  14879. TargetLowering::DAGCombinerInfo &DCI,
  14880. SelectionDAG &DAG) {
  14881. unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
  14882. bool Invert = false;
  14883. SDValue TestSrc = N->getOperand(1);
  14884. SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
  14885. if (TestSrc == NewTestSrc)
  14886. return SDValue();
  14887. unsigned NewOpc = N->getOpcode();
  14888. if (Invert) {
  14889. if (NewOpc == AArch64ISD::TBZ)
  14890. NewOpc = AArch64ISD::TBNZ;
  14891. else {
  14892. assert(NewOpc == AArch64ISD::TBNZ);
  14893. NewOpc = AArch64ISD::TBZ;
  14894. }
  14895. }
  14896. SDLoc DL(N);
  14897. return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
  14898. DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
  14899. }
  14900. // vselect (v1i1 setcc) ->
  14901. // vselect (v1iXX setcc) (XX is the size of the compared operand type)
  14902. // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
  14903. // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
  14904. // such VSELECT.
  14905. static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
  14906. SDValue N0 = N->getOperand(0);
  14907. EVT CCVT = N0.getValueType();
  14908. if (isAllActivePredicate(DAG, N0))
  14909. return N->getOperand(1);
  14910. if (isAllInactivePredicate(N0))
  14911. return N->getOperand(2);
  14912. // Check for sign pattern (VSELECT setgt, iN lhs, -1, 1, -1) and transform
  14913. // into (OR (ASR lhs, N-1), 1), which requires less instructions for the
  14914. // supported types.
  14915. SDValue SetCC = N->getOperand(0);
  14916. if (SetCC.getOpcode() == ISD::SETCC &&
  14917. SetCC.getOperand(2) == DAG.getCondCode(ISD::SETGT)) {
  14918. SDValue CmpLHS = SetCC.getOperand(0);
  14919. EVT VT = CmpLHS.getValueType();
  14920. SDNode *CmpRHS = SetCC.getOperand(1).getNode();
  14921. SDNode *SplatLHS = N->getOperand(1).getNode();
  14922. SDNode *SplatRHS = N->getOperand(2).getNode();
  14923. APInt SplatLHSVal;
  14924. if (CmpLHS.getValueType() == N->getOperand(1).getValueType() &&
  14925. VT.isSimple() &&
  14926. is_contained(
  14927. makeArrayRef({MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
  14928. MVT::v2i32, MVT::v4i32, MVT::v2i64}),
  14929. VT.getSimpleVT().SimpleTy) &&
  14930. ISD::isConstantSplatVector(SplatLHS, SplatLHSVal) &&
  14931. SplatLHSVal.isOne() && ISD::isConstantSplatVectorAllOnes(CmpRHS) &&
  14932. ISD::isConstantSplatVectorAllOnes(SplatRHS)) {
  14933. unsigned NumElts = VT.getVectorNumElements();
  14934. SmallVector<SDValue, 8> Ops(
  14935. NumElts, DAG.getConstant(VT.getScalarSizeInBits() - 1, SDLoc(N),
  14936. VT.getScalarType()));
  14937. SDValue Val = DAG.getBuildVector(VT, SDLoc(N), Ops);
  14938. auto Shift = DAG.getNode(ISD::SRA, SDLoc(N), VT, CmpLHS, Val);
  14939. auto Or = DAG.getNode(ISD::OR, SDLoc(N), VT, Shift, N->getOperand(1));
  14940. return Or;
  14941. }
  14942. }
  14943. if (N0.getOpcode() != ISD::SETCC ||
  14944. CCVT.getVectorElementCount() != ElementCount::getFixed(1) ||
  14945. CCVT.getVectorElementType() != MVT::i1)
  14946. return SDValue();
  14947. EVT ResVT = N->getValueType(0);
  14948. EVT CmpVT = N0.getOperand(0).getValueType();
  14949. // Only combine when the result type is of the same size as the compared
  14950. // operands.
  14951. if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
  14952. return SDValue();
  14953. SDValue IfTrue = N->getOperand(1);
  14954. SDValue IfFalse = N->getOperand(2);
  14955. SetCC = DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
  14956. N0.getOperand(0), N0.getOperand(1),
  14957. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  14958. return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
  14959. IfTrue, IfFalse);
  14960. }
  14961. /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
  14962. /// the compare-mask instructions rather than going via NZCV, even if LHS and
  14963. /// RHS are really scalar. This replaces any scalar setcc in the above pattern
  14964. /// with a vector one followed by a DUP shuffle on the result.
  14965. static SDValue performSelectCombine(SDNode *N,
  14966. TargetLowering::DAGCombinerInfo &DCI) {
  14967. SelectionDAG &DAG = DCI.DAG;
  14968. SDValue N0 = N->getOperand(0);
  14969. EVT ResVT = N->getValueType(0);
  14970. if (N0.getOpcode() != ISD::SETCC)
  14971. return SDValue();
  14972. if (ResVT.isScalableVector())
  14973. return SDValue();
  14974. // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
  14975. // scalar SetCCResultType. We also don't expect vectors, because we assume
  14976. // that selects fed by vector SETCCs are canonicalized to VSELECT.
  14977. assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
  14978. "Scalar-SETCC feeding SELECT has unexpected result type!");
  14979. // If NumMaskElts == 0, the comparison is larger than select result. The
  14980. // largest real NEON comparison is 64-bits per lane, which means the result is
  14981. // at most 32-bits and an illegal vector. Just bail out for now.
  14982. EVT SrcVT = N0.getOperand(0).getValueType();
  14983. // Don't try to do this optimization when the setcc itself has i1 operands.
  14984. // There are no legal vectors of i1, so this would be pointless.
  14985. if (SrcVT == MVT::i1)
  14986. return SDValue();
  14987. int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
  14988. if (!ResVT.isVector() || NumMaskElts == 0)
  14989. return SDValue();
  14990. SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
  14991. EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
  14992. // Also bail out if the vector CCVT isn't the same size as ResVT.
  14993. // This can happen if the SETCC operand size doesn't divide the ResVT size
  14994. // (e.g., f64 vs v3f32).
  14995. if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
  14996. return SDValue();
  14997. // Make sure we didn't create illegal types, if we're not supposed to.
  14998. assert(DCI.isBeforeLegalize() ||
  14999. DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
  15000. // First perform a vector comparison, where lane 0 is the one we're interested
  15001. // in.
  15002. SDLoc DL(N0);
  15003. SDValue LHS =
  15004. DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
  15005. SDValue RHS =
  15006. DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
  15007. SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
  15008. // Now duplicate the comparison mask we want across all other lanes.
  15009. SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
  15010. SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
  15011. Mask = DAG.getNode(ISD::BITCAST, DL,
  15012. ResVT.changeVectorElementTypeToInteger(), Mask);
  15013. return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
  15014. }
  15015. /// Get rid of unnecessary NVCASTs (that don't change the type).
  15016. static SDValue performNVCASTCombine(SDNode *N) {
  15017. if (N->getValueType(0) == N->getOperand(0).getValueType())
  15018. return N->getOperand(0);
  15019. return SDValue();
  15020. }
  15021. // If all users of the globaladdr are of the form (globaladdr + constant), find
  15022. // the smallest constant, fold it into the globaladdr's offset and rewrite the
  15023. // globaladdr as (globaladdr + constant) - constant.
  15024. static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
  15025. const AArch64Subtarget *Subtarget,
  15026. const TargetMachine &TM) {
  15027. auto *GN = cast<GlobalAddressSDNode>(N);
  15028. if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
  15029. AArch64II::MO_NO_FLAG)
  15030. return SDValue();
  15031. uint64_t MinOffset = -1ull;
  15032. for (SDNode *N : GN->uses()) {
  15033. if (N->getOpcode() != ISD::ADD)
  15034. return SDValue();
  15035. auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
  15036. if (!C)
  15037. C = dyn_cast<ConstantSDNode>(N->getOperand(1));
  15038. if (!C)
  15039. return SDValue();
  15040. MinOffset = std::min(MinOffset, C->getZExtValue());
  15041. }
  15042. uint64_t Offset = MinOffset + GN->getOffset();
  15043. // Require that the new offset is larger than the existing one. Otherwise, we
  15044. // can end up oscillating between two possible DAGs, for example,
  15045. // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
  15046. if (Offset <= uint64_t(GN->getOffset()))
  15047. return SDValue();
  15048. // Check whether folding this offset is legal. It must not go out of bounds of
  15049. // the referenced object to avoid violating the code model, and must be
  15050. // smaller than 2^20 because this is the largest offset expressible in all
  15051. // object formats. (The IMAGE_REL_ARM64_PAGEBASE_REL21 relocation in COFF
  15052. // stores an immediate signed 21 bit offset.)
  15053. //
  15054. // This check also prevents us from folding negative offsets, which will end
  15055. // up being treated in the same way as large positive ones. They could also
  15056. // cause code model violations, and aren't really common enough to matter.
  15057. if (Offset >= (1 << 20))
  15058. return SDValue();
  15059. const GlobalValue *GV = GN->getGlobal();
  15060. Type *T = GV->getValueType();
  15061. if (!T->isSized() ||
  15062. Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
  15063. return SDValue();
  15064. SDLoc DL(GN);
  15065. SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
  15066. return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
  15067. DAG.getConstant(MinOffset, DL, MVT::i64));
  15068. }
  15069. // Turns the vector of indices into a vector of byte offstes by scaling Offset
  15070. // by (BitWidth / 8).
  15071. static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
  15072. SDLoc DL, unsigned BitWidth) {
  15073. assert(Offset.getValueType().isScalableVector() &&
  15074. "This method is only for scalable vectors of offsets");
  15075. SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
  15076. SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
  15077. return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
  15078. }
  15079. /// Check if the value of \p OffsetInBytes can be used as an immediate for
  15080. /// the gather load/prefetch and scatter store instructions with vector base and
  15081. /// immediate offset addressing mode:
  15082. ///
  15083. /// [<Zn>.[S|D]{, #<imm>}]
  15084. ///
  15085. /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
  15086. inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
  15087. unsigned ScalarSizeInBytes) {
  15088. // The immediate is not a multiple of the scalar size.
  15089. if (OffsetInBytes % ScalarSizeInBytes)
  15090. return false;
  15091. // The immediate is out of range.
  15092. if (OffsetInBytes / ScalarSizeInBytes > 31)
  15093. return false;
  15094. return true;
  15095. }
  15096. /// Check if the value of \p Offset represents a valid immediate for the SVE
  15097. /// gather load/prefetch and scatter store instructiona with vector base and
  15098. /// immediate offset addressing mode:
  15099. ///
  15100. /// [<Zn>.[S|D]{, #<imm>}]
  15101. ///
  15102. /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
  15103. static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
  15104. unsigned ScalarSizeInBytes) {
  15105. ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
  15106. return OffsetConst && isValidImmForSVEVecImmAddrMode(
  15107. OffsetConst->getZExtValue(), ScalarSizeInBytes);
  15108. }
  15109. static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
  15110. unsigned Opcode,
  15111. bool OnlyPackedOffsets = true) {
  15112. const SDValue Src = N->getOperand(2);
  15113. const EVT SrcVT = Src->getValueType(0);
  15114. assert(SrcVT.isScalableVector() &&
  15115. "Scatter stores are only possible for SVE vectors");
  15116. SDLoc DL(N);
  15117. MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
  15118. // Make sure that source data will fit into an SVE register
  15119. if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
  15120. return SDValue();
  15121. // For FPs, ACLE only supports _packed_ single and double precision types.
  15122. if (SrcElVT.isFloatingPoint())
  15123. if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
  15124. return SDValue();
  15125. // Depending on the addressing mode, this is either a pointer or a vector of
  15126. // pointers (that fits into one register)
  15127. SDValue Base = N->getOperand(4);
  15128. // Depending on the addressing mode, this is either a single offset or a
  15129. // vector of offsets (that fits into one register)
  15130. SDValue Offset = N->getOperand(5);
  15131. // For "scalar + vector of indices", just scale the indices. This only
  15132. // applies to non-temporal scatters because there's no instruction that takes
  15133. // indicies.
  15134. if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
  15135. Offset =
  15136. getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
  15137. Opcode = AArch64ISD::SSTNT1_PRED;
  15138. }
  15139. // In the case of non-temporal gather loads there's only one SVE instruction
  15140. // per data-size: "scalar + vector", i.e.
  15141. // * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
  15142. // Since we do have intrinsics that allow the arguments to be in a different
  15143. // order, we may need to swap them to match the spec.
  15144. if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
  15145. std::swap(Base, Offset);
  15146. // SST1_IMM requires that the offset is an immediate that is:
  15147. // * a multiple of #SizeInBytes,
  15148. // * in the range [0, 31 x #SizeInBytes],
  15149. // where #SizeInBytes is the size in bytes of the stored items. For
  15150. // immediates outside that range and non-immediate scalar offsets use SST1 or
  15151. // SST1_UXTW instead.
  15152. if (Opcode == AArch64ISD::SST1_IMM_PRED) {
  15153. if (!isValidImmForSVEVecImmAddrMode(Offset,
  15154. SrcVT.getScalarSizeInBits() / 8)) {
  15155. if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
  15156. Opcode = AArch64ISD::SST1_UXTW_PRED;
  15157. else
  15158. Opcode = AArch64ISD::SST1_PRED;
  15159. std::swap(Base, Offset);
  15160. }
  15161. }
  15162. auto &TLI = DAG.getTargetLoweringInfo();
  15163. if (!TLI.isTypeLegal(Base.getValueType()))
  15164. return SDValue();
  15165. // Some scatter store variants allow unpacked offsets, but only as nxv2i32
  15166. // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
  15167. // nxv2i64. Legalize accordingly.
  15168. if (!OnlyPackedOffsets &&
  15169. Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
  15170. Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
  15171. if (!TLI.isTypeLegal(Offset.getValueType()))
  15172. return SDValue();
  15173. // Source value type that is representable in hardware
  15174. EVT HwSrcVt = getSVEContainerType(SrcVT);
  15175. // Keep the original type of the input data to store - this is needed to be
  15176. // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
  15177. // FP values we want the integer equivalent, so just use HwSrcVt.
  15178. SDValue InputVT = DAG.getValueType(SrcVT);
  15179. if (SrcVT.isFloatingPoint())
  15180. InputVT = DAG.getValueType(HwSrcVt);
  15181. SDVTList VTs = DAG.getVTList(MVT::Other);
  15182. SDValue SrcNew;
  15183. if (Src.getValueType().isFloatingPoint())
  15184. SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
  15185. else
  15186. SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
  15187. SDValue Ops[] = {N->getOperand(0), // Chain
  15188. SrcNew,
  15189. N->getOperand(3), // Pg
  15190. Base,
  15191. Offset,
  15192. InputVT};
  15193. return DAG.getNode(Opcode, DL, VTs, Ops);
  15194. }
  15195. static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
  15196. unsigned Opcode,
  15197. bool OnlyPackedOffsets = true) {
  15198. const EVT RetVT = N->getValueType(0);
  15199. assert(RetVT.isScalableVector() &&
  15200. "Gather loads are only possible for SVE vectors");
  15201. SDLoc DL(N);
  15202. // Make sure that the loaded data will fit into an SVE register
  15203. if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
  15204. return SDValue();
  15205. // Depending on the addressing mode, this is either a pointer or a vector of
  15206. // pointers (that fits into one register)
  15207. SDValue Base = N->getOperand(3);
  15208. // Depending on the addressing mode, this is either a single offset or a
  15209. // vector of offsets (that fits into one register)
  15210. SDValue Offset = N->getOperand(4);
  15211. // For "scalar + vector of indices", just scale the indices. This only
  15212. // applies to non-temporal gathers because there's no instruction that takes
  15213. // indicies.
  15214. if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
  15215. Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
  15216. RetVT.getScalarSizeInBits());
  15217. Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
  15218. }
  15219. // In the case of non-temporal gather loads there's only one SVE instruction
  15220. // per data-size: "scalar + vector", i.e.
  15221. // * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
  15222. // Since we do have intrinsics that allow the arguments to be in a different
  15223. // order, we may need to swap them to match the spec.
  15224. if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
  15225. Offset.getValueType().isVector())
  15226. std::swap(Base, Offset);
  15227. // GLD{FF}1_IMM requires that the offset is an immediate that is:
  15228. // * a multiple of #SizeInBytes,
  15229. // * in the range [0, 31 x #SizeInBytes],
  15230. // where #SizeInBytes is the size in bytes of the loaded items. For
  15231. // immediates outside that range and non-immediate scalar offsets use
  15232. // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
  15233. if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
  15234. Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
  15235. if (!isValidImmForSVEVecImmAddrMode(Offset,
  15236. RetVT.getScalarSizeInBits() / 8)) {
  15237. if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
  15238. Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
  15239. ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
  15240. : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
  15241. else
  15242. Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
  15243. ? AArch64ISD::GLD1_MERGE_ZERO
  15244. : AArch64ISD::GLDFF1_MERGE_ZERO;
  15245. std::swap(Base, Offset);
  15246. }
  15247. }
  15248. auto &TLI = DAG.getTargetLoweringInfo();
  15249. if (!TLI.isTypeLegal(Base.getValueType()))
  15250. return SDValue();
  15251. // Some gather load variants allow unpacked offsets, but only as nxv2i32
  15252. // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
  15253. // nxv2i64. Legalize accordingly.
  15254. if (!OnlyPackedOffsets &&
  15255. Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
  15256. Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
  15257. // Return value type that is representable in hardware
  15258. EVT HwRetVt = getSVEContainerType(RetVT);
  15259. // Keep the original output value type around - this is needed to be able to
  15260. // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
  15261. // values we want the integer equivalent, so just use HwRetVT.
  15262. SDValue OutVT = DAG.getValueType(RetVT);
  15263. if (RetVT.isFloatingPoint())
  15264. OutVT = DAG.getValueType(HwRetVt);
  15265. SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
  15266. SDValue Ops[] = {N->getOperand(0), // Chain
  15267. N->getOperand(2), // Pg
  15268. Base, Offset, OutVT};
  15269. SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
  15270. SDValue LoadChain = SDValue(Load.getNode(), 1);
  15271. if (RetVT.isInteger() && (RetVT != HwRetVt))
  15272. Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
  15273. // If the original return value was FP, bitcast accordingly. Doing it here
  15274. // means that we can avoid adding TableGen patterns for FPs.
  15275. if (RetVT.isFloatingPoint())
  15276. Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
  15277. return DAG.getMergeValues({Load, LoadChain}, DL);
  15278. }
  15279. static SDValue
  15280. performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
  15281. SelectionDAG &DAG) {
  15282. SDLoc DL(N);
  15283. SDValue Src = N->getOperand(0);
  15284. unsigned Opc = Src->getOpcode();
  15285. // Sign extend of an unsigned unpack -> signed unpack
  15286. if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
  15287. unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
  15288. : AArch64ISD::SUNPKLO;
  15289. // Push the sign extend to the operand of the unpack
  15290. // This is necessary where, for example, the operand of the unpack
  15291. // is another unpack:
  15292. // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
  15293. // ->
  15294. // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
  15295. // ->
  15296. // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
  15297. SDValue ExtOp = Src->getOperand(0);
  15298. auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
  15299. EVT EltTy = VT.getVectorElementType();
  15300. (void)EltTy;
  15301. assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
  15302. "Sign extending from an invalid type");
  15303. EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext());
  15304. SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
  15305. ExtOp, DAG.getValueType(ExtVT));
  15306. return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
  15307. }
  15308. if (DCI.isBeforeLegalizeOps())
  15309. return SDValue();
  15310. if (!EnableCombineMGatherIntrinsics)
  15311. return SDValue();
  15312. // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
  15313. // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
  15314. unsigned NewOpc;
  15315. unsigned MemVTOpNum = 4;
  15316. switch (Opc) {
  15317. case AArch64ISD::LD1_MERGE_ZERO:
  15318. NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
  15319. MemVTOpNum = 3;
  15320. break;
  15321. case AArch64ISD::LDNF1_MERGE_ZERO:
  15322. NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
  15323. MemVTOpNum = 3;
  15324. break;
  15325. case AArch64ISD::LDFF1_MERGE_ZERO:
  15326. NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
  15327. MemVTOpNum = 3;
  15328. break;
  15329. case AArch64ISD::GLD1_MERGE_ZERO:
  15330. NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
  15331. break;
  15332. case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
  15333. NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
  15334. break;
  15335. case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
  15336. NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
  15337. break;
  15338. case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
  15339. NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
  15340. break;
  15341. case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
  15342. NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
  15343. break;
  15344. case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
  15345. NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
  15346. break;
  15347. case AArch64ISD::GLD1_IMM_MERGE_ZERO:
  15348. NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
  15349. break;
  15350. case AArch64ISD::GLDFF1_MERGE_ZERO:
  15351. NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
  15352. break;
  15353. case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
  15354. NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
  15355. break;
  15356. case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
  15357. NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
  15358. break;
  15359. case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
  15360. NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
  15361. break;
  15362. case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
  15363. NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
  15364. break;
  15365. case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
  15366. NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
  15367. break;
  15368. case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
  15369. NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
  15370. break;
  15371. case AArch64ISD::GLDNT1_MERGE_ZERO:
  15372. NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
  15373. break;
  15374. default:
  15375. return SDValue();
  15376. }
  15377. EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
  15378. EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
  15379. if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
  15380. return SDValue();
  15381. EVT DstVT = N->getValueType(0);
  15382. SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
  15383. SmallVector<SDValue, 5> Ops;
  15384. for (unsigned I = 0; I < Src->getNumOperands(); ++I)
  15385. Ops.push_back(Src->getOperand(I));
  15386. SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
  15387. DCI.CombineTo(N, ExtLoad);
  15388. DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
  15389. // Return N so it doesn't get rechecked
  15390. return SDValue(N, 0);
  15391. }
  15392. /// Legalize the gather prefetch (scalar + vector addressing mode) when the
  15393. /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
  15394. /// != nxv2i32) do not need legalization.
  15395. static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
  15396. const unsigned OffsetPos = 4;
  15397. SDValue Offset = N->getOperand(OffsetPos);
  15398. // Not an unpacked vector, bail out.
  15399. if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
  15400. return SDValue();
  15401. // Extend the unpacked offset vector to 64-bit lanes.
  15402. SDLoc DL(N);
  15403. Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
  15404. SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
  15405. // Replace the offset operand with the 64-bit one.
  15406. Ops[OffsetPos] = Offset;
  15407. return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
  15408. }
  15409. /// Combines a node carrying the intrinsic
  15410. /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
  15411. /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
  15412. /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
  15413. /// sve gather prefetch instruction with vector plus immediate addressing mode.
  15414. static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
  15415. unsigned ScalarSizeInBytes) {
  15416. const unsigned ImmPos = 4, OffsetPos = 3;
  15417. // No need to combine the node if the immediate is valid...
  15418. if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
  15419. return SDValue();
  15420. // ...otherwise swap the offset base with the offset...
  15421. SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
  15422. std::swap(Ops[ImmPos], Ops[OffsetPos]);
  15423. // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
  15424. // `aarch64_sve_prfb_gather_uxtw_index`.
  15425. SDLoc DL(N);
  15426. Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
  15427. MVT::i64);
  15428. return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
  15429. }
  15430. // Return true if the vector operation can guarantee only the first lane of its
  15431. // result contains data, with all bits in other lanes set to zero.
  15432. static bool isLanes1toNKnownZero(SDValue Op) {
  15433. switch (Op.getOpcode()) {
  15434. default:
  15435. return false;
  15436. case AArch64ISD::ANDV_PRED:
  15437. case AArch64ISD::EORV_PRED:
  15438. case AArch64ISD::FADDA_PRED:
  15439. case AArch64ISD::FADDV_PRED:
  15440. case AArch64ISD::FMAXNMV_PRED:
  15441. case AArch64ISD::FMAXV_PRED:
  15442. case AArch64ISD::FMINNMV_PRED:
  15443. case AArch64ISD::FMINV_PRED:
  15444. case AArch64ISD::ORV_PRED:
  15445. case AArch64ISD::SADDV_PRED:
  15446. case AArch64ISD::SMAXV_PRED:
  15447. case AArch64ISD::SMINV_PRED:
  15448. case AArch64ISD::UADDV_PRED:
  15449. case AArch64ISD::UMAXV_PRED:
  15450. case AArch64ISD::UMINV_PRED:
  15451. return true;
  15452. }
  15453. }
  15454. static SDValue removeRedundantInsertVectorElt(SDNode *N) {
  15455. assert(N->getOpcode() == ISD::INSERT_VECTOR_ELT && "Unexpected node!");
  15456. SDValue InsertVec = N->getOperand(0);
  15457. SDValue InsertElt = N->getOperand(1);
  15458. SDValue InsertIdx = N->getOperand(2);
  15459. // We only care about inserts into the first element...
  15460. if (!isNullConstant(InsertIdx))
  15461. return SDValue();
  15462. // ...of a zero'd vector...
  15463. if (!ISD::isConstantSplatVectorAllZeros(InsertVec.getNode()))
  15464. return SDValue();
  15465. // ...where the inserted data was previously extracted...
  15466. if (InsertElt.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
  15467. return SDValue();
  15468. SDValue ExtractVec = InsertElt.getOperand(0);
  15469. SDValue ExtractIdx = InsertElt.getOperand(1);
  15470. // ...from the first element of a vector.
  15471. if (!isNullConstant(ExtractIdx))
  15472. return SDValue();
  15473. // If we get here we are effectively trying to zero lanes 1-N of a vector.
  15474. // Ensure there's no type conversion going on.
  15475. if (N->getValueType(0) != ExtractVec.getValueType())
  15476. return SDValue();
  15477. if (!isLanes1toNKnownZero(ExtractVec))
  15478. return SDValue();
  15479. // The explicit zeroing is redundant.
  15480. return ExtractVec;
  15481. }
  15482. static SDValue
  15483. performInsertVectorEltCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI) {
  15484. if (SDValue Res = removeRedundantInsertVectorElt(N))
  15485. return Res;
  15486. return performPostLD1Combine(N, DCI, true);
  15487. }
  15488. SDValue performSVESpliceCombine(SDNode *N, SelectionDAG &DAG) {
  15489. EVT Ty = N->getValueType(0);
  15490. if (Ty.isInteger())
  15491. return SDValue();
  15492. EVT IntTy = Ty.changeVectorElementTypeToInteger();
  15493. EVT ExtIntTy = getPackedSVEVectorVT(IntTy.getVectorElementCount());
  15494. if (ExtIntTy.getVectorElementType().getScalarSizeInBits() <
  15495. IntTy.getVectorElementType().getScalarSizeInBits())
  15496. return SDValue();
  15497. SDLoc DL(N);
  15498. SDValue LHS = DAG.getAnyExtOrTrunc(DAG.getBitcast(IntTy, N->getOperand(0)),
  15499. DL, ExtIntTy);
  15500. SDValue RHS = DAG.getAnyExtOrTrunc(DAG.getBitcast(IntTy, N->getOperand(1)),
  15501. DL, ExtIntTy);
  15502. SDValue Idx = N->getOperand(2);
  15503. SDValue Splice = DAG.getNode(ISD::VECTOR_SPLICE, DL, ExtIntTy, LHS, RHS, Idx);
  15504. SDValue Trunc = DAG.getAnyExtOrTrunc(Splice, DL, IntTy);
  15505. return DAG.getBitcast(Ty, Trunc);
  15506. }
  15507. SDValue performFPExtendCombine(SDNode *N, SelectionDAG &DAG,
  15508. TargetLowering::DAGCombinerInfo &DCI,
  15509. const AArch64Subtarget *Subtarget) {
  15510. SDValue N0 = N->getOperand(0);
  15511. EVT VT = N->getValueType(0);
  15512. // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
  15513. if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::FP_ROUND)
  15514. return SDValue();
  15515. // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
  15516. // We purposefully don't care about legality of the nodes here as we know
  15517. // they can be split down into something legal.
  15518. if (DCI.isBeforeLegalizeOps() && ISD::isNormalLoad(N0.getNode()) &&
  15519. N0.hasOneUse() && Subtarget->useSVEForFixedLengthVectors() &&
  15520. VT.isFixedLengthVector() &&
  15521. VT.getFixedSizeInBits() >= Subtarget->getMinSVEVectorSizeInBits()) {
  15522. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  15523. SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
  15524. LN0->getChain(), LN0->getBasePtr(),
  15525. N0.getValueType(), LN0->getMemOperand());
  15526. DCI.CombineTo(N, ExtLoad);
  15527. DCI.CombineTo(N0.getNode(),
  15528. DAG.getNode(ISD::FP_ROUND, SDLoc(N0), N0.getValueType(),
  15529. ExtLoad, DAG.getIntPtrConstant(1, SDLoc(N0))),
  15530. ExtLoad.getValue(1));
  15531. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  15532. }
  15533. return SDValue();
  15534. }
  15535. SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
  15536. DAGCombinerInfo &DCI) const {
  15537. SelectionDAG &DAG = DCI.DAG;
  15538. switch (N->getOpcode()) {
  15539. default:
  15540. LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
  15541. break;
  15542. case ISD::ADD:
  15543. case ISD::SUB:
  15544. return performAddSubCombine(N, DCI, DAG);
  15545. case ISD::XOR:
  15546. return performXorCombine(N, DAG, DCI, Subtarget);
  15547. case ISD::MUL:
  15548. return performMulCombine(N, DAG, DCI, Subtarget);
  15549. case ISD::SINT_TO_FP:
  15550. case ISD::UINT_TO_FP:
  15551. return performIntToFpCombine(N, DAG, Subtarget);
  15552. case ISD::FP_TO_SINT:
  15553. case ISD::FP_TO_UINT:
  15554. case ISD::FP_TO_SINT_SAT:
  15555. case ISD::FP_TO_UINT_SAT:
  15556. return performFpToIntCombine(N, DAG, DCI, Subtarget);
  15557. case ISD::FDIV:
  15558. return performFDivCombine(N, DAG, DCI, Subtarget);
  15559. case ISD::OR:
  15560. return performORCombine(N, DCI, Subtarget);
  15561. case ISD::AND:
  15562. return performANDCombine(N, DCI);
  15563. case ISD::INTRINSIC_WO_CHAIN:
  15564. return performIntrinsicCombine(N, DCI, Subtarget);
  15565. case ISD::ANY_EXTEND:
  15566. case ISD::ZERO_EXTEND:
  15567. case ISD::SIGN_EXTEND:
  15568. return performExtendCombine(N, DCI, DAG);
  15569. case ISD::SIGN_EXTEND_INREG:
  15570. return performSignExtendInRegCombine(N, DCI, DAG);
  15571. case ISD::TRUNCATE:
  15572. return performVectorTruncateCombine(N, DCI, DAG);
  15573. case ISD::CONCAT_VECTORS:
  15574. return performConcatVectorsCombine(N, DCI, DAG);
  15575. case ISD::INSERT_SUBVECTOR:
  15576. return performInsertSubvectorCombine(N, DCI, DAG);
  15577. case ISD::SELECT:
  15578. return performSelectCombine(N, DCI);
  15579. case ISD::VSELECT:
  15580. return performVSelectCombine(N, DCI.DAG);
  15581. case ISD::SETCC:
  15582. return performSETCCCombine(N, DAG);
  15583. case ISD::LOAD:
  15584. if (performTBISimplification(N->getOperand(1), DCI, DAG))
  15585. return SDValue(N, 0);
  15586. break;
  15587. case ISD::STORE:
  15588. return performSTORECombine(N, DCI, DAG, Subtarget);
  15589. case ISD::VECTOR_SPLICE:
  15590. return performSVESpliceCombine(N, DAG);
  15591. case ISD::FP_EXTEND:
  15592. return performFPExtendCombine(N, DAG, DCI, Subtarget);
  15593. case AArch64ISD::BRCOND:
  15594. return performBRCONDCombine(N, DCI, DAG);
  15595. case AArch64ISD::TBNZ:
  15596. case AArch64ISD::TBZ:
  15597. return performTBZCombine(N, DCI, DAG);
  15598. case AArch64ISD::CSEL:
  15599. return performCSELCombine(N, DCI, DAG);
  15600. case AArch64ISD::DUP:
  15601. return performPostLD1Combine(N, DCI, false);
  15602. case AArch64ISD::NVCAST:
  15603. return performNVCASTCombine(N);
  15604. case AArch64ISD::SPLICE:
  15605. return performSpliceCombine(N, DAG);
  15606. case AArch64ISD::UUNPKLO:
  15607. case AArch64ISD::UUNPKHI:
  15608. return performUnpackCombine(N, DAG);
  15609. case AArch64ISD::UZP1:
  15610. return performUzpCombine(N, DAG);
  15611. case AArch64ISD::SETCC_MERGE_ZERO:
  15612. return performSetccMergeZeroCombine(N, DAG);
  15613. case AArch64ISD::GLD1_MERGE_ZERO:
  15614. case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
  15615. case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
  15616. case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
  15617. case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
  15618. case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
  15619. case AArch64ISD::GLD1_IMM_MERGE_ZERO:
  15620. case AArch64ISD::GLD1S_MERGE_ZERO:
  15621. case AArch64ISD::GLD1S_SCALED_MERGE_ZERO:
  15622. case AArch64ISD::GLD1S_UXTW_MERGE_ZERO:
  15623. case AArch64ISD::GLD1S_SXTW_MERGE_ZERO:
  15624. case AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO:
  15625. case AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO:
  15626. case AArch64ISD::GLD1S_IMM_MERGE_ZERO:
  15627. return performGLD1Combine(N, DAG);
  15628. case AArch64ISD::VASHR:
  15629. case AArch64ISD::VLSHR:
  15630. return performVectorShiftCombine(N, *this, DCI);
  15631. case AArch64ISD::SUNPKLO:
  15632. return performSunpkloCombine(N, DAG);
  15633. case ISD::INSERT_VECTOR_ELT:
  15634. return performInsertVectorEltCombine(N, DCI);
  15635. case ISD::EXTRACT_VECTOR_ELT:
  15636. return performExtractVectorEltCombine(N, DAG);
  15637. case ISD::VECREDUCE_ADD:
  15638. return performVecReduceAddCombine(N, DCI.DAG, Subtarget);
  15639. case ISD::INTRINSIC_VOID:
  15640. case ISD::INTRINSIC_W_CHAIN:
  15641. switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
  15642. case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
  15643. return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
  15644. case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
  15645. return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
  15646. case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
  15647. return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
  15648. case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
  15649. return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
  15650. case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
  15651. case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
  15652. case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
  15653. case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
  15654. case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
  15655. case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
  15656. case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
  15657. case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
  15658. return legalizeSVEGatherPrefetchOffsVec(N, DAG);
  15659. case Intrinsic::aarch64_neon_ld2:
  15660. case Intrinsic::aarch64_neon_ld3:
  15661. case Intrinsic::aarch64_neon_ld4:
  15662. case Intrinsic::aarch64_neon_ld1x2:
  15663. case Intrinsic::aarch64_neon_ld1x3:
  15664. case Intrinsic::aarch64_neon_ld1x4:
  15665. case Intrinsic::aarch64_neon_ld2lane:
  15666. case Intrinsic::aarch64_neon_ld3lane:
  15667. case Intrinsic::aarch64_neon_ld4lane:
  15668. case Intrinsic::aarch64_neon_ld2r:
  15669. case Intrinsic::aarch64_neon_ld3r:
  15670. case Intrinsic::aarch64_neon_ld4r:
  15671. case Intrinsic::aarch64_neon_st2:
  15672. case Intrinsic::aarch64_neon_st3:
  15673. case Intrinsic::aarch64_neon_st4:
  15674. case Intrinsic::aarch64_neon_st1x2:
  15675. case Intrinsic::aarch64_neon_st1x3:
  15676. case Intrinsic::aarch64_neon_st1x4:
  15677. case Intrinsic::aarch64_neon_st2lane:
  15678. case Intrinsic::aarch64_neon_st3lane:
  15679. case Intrinsic::aarch64_neon_st4lane:
  15680. return performNEONPostLDSTCombine(N, DCI, DAG);
  15681. case Intrinsic::aarch64_sve_ldnt1:
  15682. return performLDNT1Combine(N, DAG);
  15683. case Intrinsic::aarch64_sve_ld1rq:
  15684. return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
  15685. case Intrinsic::aarch64_sve_ld1ro:
  15686. return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
  15687. case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
  15688. return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
  15689. case Intrinsic::aarch64_sve_ldnt1_gather:
  15690. return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
  15691. case Intrinsic::aarch64_sve_ldnt1_gather_index:
  15692. return performGatherLoadCombine(N, DAG,
  15693. AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
  15694. case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
  15695. return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
  15696. case Intrinsic::aarch64_sve_ld1:
  15697. return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
  15698. case Intrinsic::aarch64_sve_ldnf1:
  15699. return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
  15700. case Intrinsic::aarch64_sve_ldff1:
  15701. return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
  15702. case Intrinsic::aarch64_sve_st1:
  15703. return performST1Combine(N, DAG);
  15704. case Intrinsic::aarch64_sve_stnt1:
  15705. return performSTNT1Combine(N, DAG);
  15706. case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
  15707. return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
  15708. case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
  15709. return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
  15710. case Intrinsic::aarch64_sve_stnt1_scatter:
  15711. return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
  15712. case Intrinsic::aarch64_sve_stnt1_scatter_index:
  15713. return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
  15714. case Intrinsic::aarch64_sve_ld1_gather:
  15715. return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
  15716. case Intrinsic::aarch64_sve_ld1_gather_index:
  15717. return performGatherLoadCombine(N, DAG,
  15718. AArch64ISD::GLD1_SCALED_MERGE_ZERO);
  15719. case Intrinsic::aarch64_sve_ld1_gather_sxtw:
  15720. return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
  15721. /*OnlyPackedOffsets=*/false);
  15722. case Intrinsic::aarch64_sve_ld1_gather_uxtw:
  15723. return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
  15724. /*OnlyPackedOffsets=*/false);
  15725. case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
  15726. return performGatherLoadCombine(N, DAG,
  15727. AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
  15728. /*OnlyPackedOffsets=*/false);
  15729. case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
  15730. return performGatherLoadCombine(N, DAG,
  15731. AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
  15732. /*OnlyPackedOffsets=*/false);
  15733. case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
  15734. return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
  15735. case Intrinsic::aarch64_sve_ldff1_gather:
  15736. return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
  15737. case Intrinsic::aarch64_sve_ldff1_gather_index:
  15738. return performGatherLoadCombine(N, DAG,
  15739. AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
  15740. case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
  15741. return performGatherLoadCombine(N, DAG,
  15742. AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
  15743. /*OnlyPackedOffsets=*/false);
  15744. case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
  15745. return performGatherLoadCombine(N, DAG,
  15746. AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
  15747. /*OnlyPackedOffsets=*/false);
  15748. case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
  15749. return performGatherLoadCombine(N, DAG,
  15750. AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
  15751. /*OnlyPackedOffsets=*/false);
  15752. case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
  15753. return performGatherLoadCombine(N, DAG,
  15754. AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
  15755. /*OnlyPackedOffsets=*/false);
  15756. case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
  15757. return performGatherLoadCombine(N, DAG,
  15758. AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
  15759. case Intrinsic::aarch64_sve_st1_scatter:
  15760. return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
  15761. case Intrinsic::aarch64_sve_st1_scatter_index:
  15762. return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
  15763. case Intrinsic::aarch64_sve_st1_scatter_sxtw:
  15764. return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
  15765. /*OnlyPackedOffsets=*/false);
  15766. case Intrinsic::aarch64_sve_st1_scatter_uxtw:
  15767. return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
  15768. /*OnlyPackedOffsets=*/false);
  15769. case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
  15770. return performScatterStoreCombine(N, DAG,
  15771. AArch64ISD::SST1_SXTW_SCALED_PRED,
  15772. /*OnlyPackedOffsets=*/false);
  15773. case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
  15774. return performScatterStoreCombine(N, DAG,
  15775. AArch64ISD::SST1_UXTW_SCALED_PRED,
  15776. /*OnlyPackedOffsets=*/false);
  15777. case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
  15778. return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
  15779. case Intrinsic::aarch64_sve_tuple_get: {
  15780. SDLoc DL(N);
  15781. SDValue Chain = N->getOperand(0);
  15782. SDValue Src1 = N->getOperand(2);
  15783. SDValue Idx = N->getOperand(3);
  15784. uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
  15785. EVT ResVT = N->getValueType(0);
  15786. uint64_t NumLanes = ResVT.getVectorElementCount().getKnownMinValue();
  15787. SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL);
  15788. SDValue Val =
  15789. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx);
  15790. return DAG.getMergeValues({Val, Chain}, DL);
  15791. }
  15792. case Intrinsic::aarch64_sve_tuple_set: {
  15793. SDLoc DL(N);
  15794. SDValue Chain = N->getOperand(0);
  15795. SDValue Tuple = N->getOperand(2);
  15796. SDValue Idx = N->getOperand(3);
  15797. SDValue Vec = N->getOperand(4);
  15798. EVT TupleVT = Tuple.getValueType();
  15799. uint64_t TupleLanes = TupleVT.getVectorElementCount().getKnownMinValue();
  15800. uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
  15801. uint64_t NumLanes =
  15802. Vec.getValueType().getVectorElementCount().getKnownMinValue();
  15803. if ((TupleLanes % NumLanes) != 0)
  15804. report_fatal_error("invalid tuple vector!");
  15805. uint64_t NumVecs = TupleLanes / NumLanes;
  15806. SmallVector<SDValue, 4> Opnds;
  15807. for (unsigned I = 0; I < NumVecs; ++I) {
  15808. if (I == IdxConst)
  15809. Opnds.push_back(Vec);
  15810. else {
  15811. SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL);
  15812. Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
  15813. Vec.getValueType(), Tuple, ExtIdx));
  15814. }
  15815. }
  15816. SDValue Concat =
  15817. DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
  15818. return DAG.getMergeValues({Concat, Chain}, DL);
  15819. }
  15820. case Intrinsic::aarch64_sve_tuple_create2:
  15821. case Intrinsic::aarch64_sve_tuple_create3:
  15822. case Intrinsic::aarch64_sve_tuple_create4: {
  15823. SDLoc DL(N);
  15824. SDValue Chain = N->getOperand(0);
  15825. SmallVector<SDValue, 4> Opnds;
  15826. for (unsigned I = 2; I < N->getNumOperands(); ++I)
  15827. Opnds.push_back(N->getOperand(I));
  15828. EVT VT = Opnds[0].getValueType();
  15829. EVT EltVT = VT.getVectorElementType();
  15830. EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
  15831. VT.getVectorElementCount() *
  15832. (N->getNumOperands() - 2));
  15833. SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
  15834. return DAG.getMergeValues({Concat, Chain}, DL);
  15835. }
  15836. case Intrinsic::aarch64_sve_ld2:
  15837. case Intrinsic::aarch64_sve_ld3:
  15838. case Intrinsic::aarch64_sve_ld4: {
  15839. SDLoc DL(N);
  15840. SDValue Chain = N->getOperand(0);
  15841. SDValue Mask = N->getOperand(2);
  15842. SDValue BasePtr = N->getOperand(3);
  15843. SDValue LoadOps[] = {Chain, Mask, BasePtr};
  15844. unsigned IntrinsicID =
  15845. cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
  15846. SDValue Result =
  15847. LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
  15848. return DAG.getMergeValues({Result, Chain}, DL);
  15849. }
  15850. case Intrinsic::aarch64_rndr:
  15851. case Intrinsic::aarch64_rndrrs: {
  15852. unsigned IntrinsicID =
  15853. cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
  15854. auto Register =
  15855. (IntrinsicID == Intrinsic::aarch64_rndr ? AArch64SysReg::RNDR
  15856. : AArch64SysReg::RNDRRS);
  15857. SDLoc DL(N);
  15858. SDValue A = DAG.getNode(
  15859. AArch64ISD::MRS, DL, DAG.getVTList(MVT::i64, MVT::Glue, MVT::Other),
  15860. N->getOperand(0), DAG.getConstant(Register, DL, MVT::i64));
  15861. SDValue B = DAG.getNode(
  15862. AArch64ISD::CSINC, DL, MVT::i32, DAG.getConstant(0, DL, MVT::i32),
  15863. DAG.getConstant(0, DL, MVT::i32),
  15864. DAG.getConstant(AArch64CC::NE, DL, MVT::i32), A.getValue(1));
  15865. return DAG.getMergeValues(
  15866. {A, DAG.getZExtOrTrunc(B, DL, MVT::i1), A.getValue(2)}, DL);
  15867. }
  15868. default:
  15869. break;
  15870. }
  15871. break;
  15872. case ISD::GlobalAddress:
  15873. return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
  15874. }
  15875. return SDValue();
  15876. }
  15877. // Check if the return value is used as only a return value, as otherwise
  15878. // we can't perform a tail-call. In particular, we need to check for
  15879. // target ISD nodes that are returns and any other "odd" constructs
  15880. // that the generic analysis code won't necessarily catch.
  15881. bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
  15882. SDValue &Chain) const {
  15883. if (N->getNumValues() != 1)
  15884. return false;
  15885. if (!N->hasNUsesOfValue(1, 0))
  15886. return false;
  15887. SDValue TCChain = Chain;
  15888. SDNode *Copy = *N->use_begin();
  15889. if (Copy->getOpcode() == ISD::CopyToReg) {
  15890. // If the copy has a glue operand, we conservatively assume it isn't safe to
  15891. // perform a tail call.
  15892. if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
  15893. MVT::Glue)
  15894. return false;
  15895. TCChain = Copy->getOperand(0);
  15896. } else if (Copy->getOpcode() != ISD::FP_EXTEND)
  15897. return false;
  15898. bool HasRet = false;
  15899. for (SDNode *Node : Copy->uses()) {
  15900. if (Node->getOpcode() != AArch64ISD::RET_FLAG)
  15901. return false;
  15902. HasRet = true;
  15903. }
  15904. if (!HasRet)
  15905. return false;
  15906. Chain = TCChain;
  15907. return true;
  15908. }
  15909. // Return whether the an instruction can potentially be optimized to a tail
  15910. // call. This will cause the optimizers to attempt to move, or duplicate,
  15911. // return instructions to help enable tail call optimizations for this
  15912. // instruction.
  15913. bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
  15914. return CI->isTailCall();
  15915. }
  15916. bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
  15917. SDValue &Offset,
  15918. ISD::MemIndexedMode &AM,
  15919. bool &IsInc,
  15920. SelectionDAG &DAG) const {
  15921. if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
  15922. return false;
  15923. Base = Op->getOperand(0);
  15924. // All of the indexed addressing mode instructions take a signed
  15925. // 9 bit immediate offset.
  15926. if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
  15927. int64_t RHSC = RHS->getSExtValue();
  15928. if (Op->getOpcode() == ISD::SUB)
  15929. RHSC = -(uint64_t)RHSC;
  15930. if (!isInt<9>(RHSC))
  15931. return false;
  15932. IsInc = (Op->getOpcode() == ISD::ADD);
  15933. Offset = Op->getOperand(1);
  15934. return true;
  15935. }
  15936. return false;
  15937. }
  15938. bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
  15939. SDValue &Offset,
  15940. ISD::MemIndexedMode &AM,
  15941. SelectionDAG &DAG) const {
  15942. EVT VT;
  15943. SDValue Ptr;
  15944. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
  15945. VT = LD->getMemoryVT();
  15946. Ptr = LD->getBasePtr();
  15947. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
  15948. VT = ST->getMemoryVT();
  15949. Ptr = ST->getBasePtr();
  15950. } else
  15951. return false;
  15952. bool IsInc;
  15953. if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
  15954. return false;
  15955. AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
  15956. return true;
  15957. }
  15958. bool AArch64TargetLowering::getPostIndexedAddressParts(
  15959. SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
  15960. ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
  15961. EVT VT;
  15962. SDValue Ptr;
  15963. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
  15964. VT = LD->getMemoryVT();
  15965. Ptr = LD->getBasePtr();
  15966. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
  15967. VT = ST->getMemoryVT();
  15968. Ptr = ST->getBasePtr();
  15969. } else
  15970. return false;
  15971. bool IsInc;
  15972. if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
  15973. return false;
  15974. // Post-indexing updates the base, so it's not a valid transform
  15975. // if that's not the same as the load's pointer.
  15976. if (Ptr != Base)
  15977. return false;
  15978. AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
  15979. return true;
  15980. }
  15981. void AArch64TargetLowering::ReplaceBITCASTResults(
  15982. SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
  15983. SDLoc DL(N);
  15984. SDValue Op = N->getOperand(0);
  15985. EVT VT = N->getValueType(0);
  15986. EVT SrcVT = Op.getValueType();
  15987. if (VT.isScalableVector() && !isTypeLegal(VT) && isTypeLegal(SrcVT)) {
  15988. assert(!VT.isFloatingPoint() && SrcVT.isFloatingPoint() &&
  15989. "Expected fp->int bitcast!");
  15990. SDValue CastResult = getSVESafeBitCast(getSVEContainerType(VT), Op, DAG);
  15991. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, CastResult));
  15992. return;
  15993. }
  15994. if (VT != MVT::i16 || (SrcVT != MVT::f16 && SrcVT != MVT::bf16))
  15995. return;
  15996. Op = SDValue(
  15997. DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
  15998. DAG.getUNDEF(MVT::i32), Op,
  15999. DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
  16000. 0);
  16001. Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
  16002. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
  16003. }
  16004. static void ReplaceReductionResults(SDNode *N,
  16005. SmallVectorImpl<SDValue> &Results,
  16006. SelectionDAG &DAG, unsigned InterOp,
  16007. unsigned AcrossOp) {
  16008. EVT LoVT, HiVT;
  16009. SDValue Lo, Hi;
  16010. SDLoc dl(N);
  16011. std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
  16012. std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
  16013. SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
  16014. SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
  16015. Results.push_back(SplitVal);
  16016. }
  16017. static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
  16018. SDLoc DL(N);
  16019. SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
  16020. SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
  16021. DAG.getNode(ISD::SRL, DL, MVT::i128, N,
  16022. DAG.getConstant(64, DL, MVT::i64)));
  16023. return std::make_pair(Lo, Hi);
  16024. }
  16025. void AArch64TargetLowering::ReplaceExtractSubVectorResults(
  16026. SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
  16027. SDValue In = N->getOperand(0);
  16028. EVT InVT = In.getValueType();
  16029. // Common code will handle these just fine.
  16030. if (!InVT.isScalableVector() || !InVT.isInteger())
  16031. return;
  16032. SDLoc DL(N);
  16033. EVT VT = N->getValueType(0);
  16034. // The following checks bail if this is not a halving operation.
  16035. ElementCount ResEC = VT.getVectorElementCount();
  16036. if (InVT.getVectorElementCount() != (ResEC * 2))
  16037. return;
  16038. auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
  16039. if (!CIndex)
  16040. return;
  16041. unsigned Index = CIndex->getZExtValue();
  16042. if ((Index != 0) && (Index != ResEC.getKnownMinValue()))
  16043. return;
  16044. unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
  16045. EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
  16046. SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
  16047. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
  16048. }
  16049. // Create an even/odd pair of X registers holding integer value V.
  16050. static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
  16051. SDLoc dl(V.getNode());
  16052. SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
  16053. SDValue VHi = DAG.getAnyExtOrTrunc(
  16054. DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
  16055. dl, MVT::i64);
  16056. if (DAG.getDataLayout().isBigEndian())
  16057. std::swap (VLo, VHi);
  16058. SDValue RegClass =
  16059. DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
  16060. SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
  16061. SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
  16062. const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
  16063. return SDValue(
  16064. DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
  16065. }
  16066. static void ReplaceCMP_SWAP_128Results(SDNode *N,
  16067. SmallVectorImpl<SDValue> &Results,
  16068. SelectionDAG &DAG,
  16069. const AArch64Subtarget *Subtarget) {
  16070. assert(N->getValueType(0) == MVT::i128 &&
  16071. "AtomicCmpSwap on types less than 128 should be legal");
  16072. MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
  16073. if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) {
  16074. // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
  16075. // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
  16076. SDValue Ops[] = {
  16077. createGPRPairNode(DAG, N->getOperand(2)), // Compare value
  16078. createGPRPairNode(DAG, N->getOperand(3)), // Store value
  16079. N->getOperand(1), // Ptr
  16080. N->getOperand(0), // Chain in
  16081. };
  16082. unsigned Opcode;
  16083. switch (MemOp->getMergedOrdering()) {
  16084. case AtomicOrdering::Monotonic:
  16085. Opcode = AArch64::CASPX;
  16086. break;
  16087. case AtomicOrdering::Acquire:
  16088. Opcode = AArch64::CASPAX;
  16089. break;
  16090. case AtomicOrdering::Release:
  16091. Opcode = AArch64::CASPLX;
  16092. break;
  16093. case AtomicOrdering::AcquireRelease:
  16094. case AtomicOrdering::SequentiallyConsistent:
  16095. Opcode = AArch64::CASPALX;
  16096. break;
  16097. default:
  16098. llvm_unreachable("Unexpected ordering!");
  16099. }
  16100. MachineSDNode *CmpSwap = DAG.getMachineNode(
  16101. Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
  16102. DAG.setNodeMemRefs(CmpSwap, {MemOp});
  16103. unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
  16104. if (DAG.getDataLayout().isBigEndian())
  16105. std::swap(SubReg1, SubReg2);
  16106. SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
  16107. SDValue(CmpSwap, 0));
  16108. SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
  16109. SDValue(CmpSwap, 0));
  16110. Results.push_back(
  16111. DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
  16112. Results.push_back(SDValue(CmpSwap, 1)); // Chain out
  16113. return;
  16114. }
  16115. unsigned Opcode;
  16116. switch (MemOp->getMergedOrdering()) {
  16117. case AtomicOrdering::Monotonic:
  16118. Opcode = AArch64::CMP_SWAP_128_MONOTONIC;
  16119. break;
  16120. case AtomicOrdering::Acquire:
  16121. Opcode = AArch64::CMP_SWAP_128_ACQUIRE;
  16122. break;
  16123. case AtomicOrdering::Release:
  16124. Opcode = AArch64::CMP_SWAP_128_RELEASE;
  16125. break;
  16126. case AtomicOrdering::AcquireRelease:
  16127. case AtomicOrdering::SequentiallyConsistent:
  16128. Opcode = AArch64::CMP_SWAP_128;
  16129. break;
  16130. default:
  16131. llvm_unreachable("Unexpected ordering!");
  16132. }
  16133. auto Desired = splitInt128(N->getOperand(2), DAG);
  16134. auto New = splitInt128(N->getOperand(3), DAG);
  16135. SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
  16136. New.first, New.second, N->getOperand(0)};
  16137. SDNode *CmpSwap = DAG.getMachineNode(
  16138. Opcode, SDLoc(N), DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other),
  16139. Ops);
  16140. DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
  16141. Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
  16142. SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
  16143. Results.push_back(SDValue(CmpSwap, 3));
  16144. }
  16145. void AArch64TargetLowering::ReplaceNodeResults(
  16146. SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
  16147. switch (N->getOpcode()) {
  16148. default:
  16149. llvm_unreachable("Don't know how to custom expand this");
  16150. case ISD::BITCAST:
  16151. ReplaceBITCASTResults(N, Results, DAG);
  16152. return;
  16153. case ISD::VECREDUCE_ADD:
  16154. case ISD::VECREDUCE_SMAX:
  16155. case ISD::VECREDUCE_SMIN:
  16156. case ISD::VECREDUCE_UMAX:
  16157. case ISD::VECREDUCE_UMIN:
  16158. Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
  16159. return;
  16160. case ISD::CTPOP:
  16161. if (SDValue Result = LowerCTPOP(SDValue(N, 0), DAG))
  16162. Results.push_back(Result);
  16163. return;
  16164. case AArch64ISD::SADDV:
  16165. ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
  16166. return;
  16167. case AArch64ISD::UADDV:
  16168. ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
  16169. return;
  16170. case AArch64ISD::SMINV:
  16171. ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
  16172. return;
  16173. case AArch64ISD::UMINV:
  16174. ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
  16175. return;
  16176. case AArch64ISD::SMAXV:
  16177. ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
  16178. return;
  16179. case AArch64ISD::UMAXV:
  16180. ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
  16181. return;
  16182. case ISD::FP_TO_UINT:
  16183. case ISD::FP_TO_SINT:
  16184. case ISD::STRICT_FP_TO_SINT:
  16185. case ISD::STRICT_FP_TO_UINT:
  16186. assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
  16187. // Let normal code take care of it by not adding anything to Results.
  16188. return;
  16189. case ISD::ATOMIC_CMP_SWAP:
  16190. ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
  16191. return;
  16192. case ISD::ATOMIC_LOAD:
  16193. case ISD::LOAD: {
  16194. assert(SDValue(N, 0).getValueType() == MVT::i128 &&
  16195. "unexpected load's value type");
  16196. MemSDNode *LoadNode = cast<MemSDNode>(N);
  16197. if ((!LoadNode->isVolatile() && !LoadNode->isAtomic()) ||
  16198. LoadNode->getMemoryVT() != MVT::i128) {
  16199. // Non-volatile or atomic loads are optimized later in AArch64's load/store
  16200. // optimizer.
  16201. return;
  16202. }
  16203. SDValue Result = DAG.getMemIntrinsicNode(
  16204. AArch64ISD::LDP, SDLoc(N),
  16205. DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
  16206. {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
  16207. LoadNode->getMemOperand());
  16208. SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
  16209. Result.getValue(0), Result.getValue(1));
  16210. Results.append({Pair, Result.getValue(2) /* Chain */});
  16211. return;
  16212. }
  16213. case ISD::EXTRACT_SUBVECTOR:
  16214. ReplaceExtractSubVectorResults(N, Results, DAG);
  16215. return;
  16216. case ISD::INSERT_SUBVECTOR:
  16217. // Custom lowering has been requested for INSERT_SUBVECTOR -- but delegate
  16218. // to common code for result type legalisation
  16219. return;
  16220. case ISD::INTRINSIC_WO_CHAIN: {
  16221. EVT VT = N->getValueType(0);
  16222. assert((VT == MVT::i8 || VT == MVT::i16) &&
  16223. "custom lowering for unexpected type");
  16224. ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
  16225. Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
  16226. switch (IntID) {
  16227. default:
  16228. return;
  16229. case Intrinsic::aarch64_sve_clasta_n: {
  16230. SDLoc DL(N);
  16231. auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
  16232. auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
  16233. N->getOperand(1), Op2, N->getOperand(3));
  16234. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
  16235. return;
  16236. }
  16237. case Intrinsic::aarch64_sve_clastb_n: {
  16238. SDLoc DL(N);
  16239. auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
  16240. auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
  16241. N->getOperand(1), Op2, N->getOperand(3));
  16242. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
  16243. return;
  16244. }
  16245. case Intrinsic::aarch64_sve_lasta: {
  16246. SDLoc DL(N);
  16247. auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
  16248. N->getOperand(1), N->getOperand(2));
  16249. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
  16250. return;
  16251. }
  16252. case Intrinsic::aarch64_sve_lastb: {
  16253. SDLoc DL(N);
  16254. auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
  16255. N->getOperand(1), N->getOperand(2));
  16256. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
  16257. return;
  16258. }
  16259. }
  16260. }
  16261. }
  16262. }
  16263. bool AArch64TargetLowering::useLoadStackGuardNode() const {
  16264. if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
  16265. return TargetLowering::useLoadStackGuardNode();
  16266. return true;
  16267. }
  16268. unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
  16269. // Combine multiple FDIVs with the same divisor into multiple FMULs by the
  16270. // reciprocal if there are three or more FDIVs.
  16271. return 3;
  16272. }
  16273. TargetLoweringBase::LegalizeTypeAction
  16274. AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
  16275. // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
  16276. // v4i16, v2i32 instead of to promote.
  16277. if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
  16278. VT == MVT::v1f32)
  16279. return TypeWidenVector;
  16280. return TargetLoweringBase::getPreferredVectorAction(VT);
  16281. }
  16282. // In v8.4a, ldp and stp instructions are guaranteed to be single-copy atomic
  16283. // provided the address is 16-byte aligned.
  16284. bool AArch64TargetLowering::isOpSuitableForLDPSTP(const Instruction *I) const {
  16285. if (!Subtarget->hasLSE2())
  16286. return false;
  16287. if (auto LI = dyn_cast<LoadInst>(I))
  16288. return LI->getType()->getPrimitiveSizeInBits() == 128 &&
  16289. LI->getAlignment() >= 16;
  16290. if (auto SI = dyn_cast<StoreInst>(I))
  16291. return SI->getValueOperand()->getType()->getPrimitiveSizeInBits() == 128 &&
  16292. SI->getAlignment() >= 16;
  16293. return false;
  16294. }
  16295. bool AArch64TargetLowering::shouldInsertFencesForAtomic(
  16296. const Instruction *I) const {
  16297. return isOpSuitableForLDPSTP(I);
  16298. }
  16299. // Loads and stores less than 128-bits are already atomic; ones above that
  16300. // are doomed anyway, so defer to the default libcall and blame the OS when
  16301. // things go wrong.
  16302. bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
  16303. unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
  16304. if (Size != 128)
  16305. return false;
  16306. return !isOpSuitableForLDPSTP(SI);
  16307. }
  16308. // Loads and stores less than 128-bits are already atomic; ones above that
  16309. // are doomed anyway, so defer to the default libcall and blame the OS when
  16310. // things go wrong.
  16311. TargetLowering::AtomicExpansionKind
  16312. AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
  16313. unsigned Size = LI->getType()->getPrimitiveSizeInBits();
  16314. if (Size != 128 || isOpSuitableForLDPSTP(LI))
  16315. return AtomicExpansionKind::None;
  16316. // At -O0, fast-regalloc cannot cope with the live vregs necessary to
  16317. // implement atomicrmw without spilling. If the target address is also on the
  16318. // stack and close enough to the spill slot, this can lead to a situation
  16319. // where the monitor always gets cleared and the atomic operation can never
  16320. // succeed. So at -O0 lower this operation to a CAS loop.
  16321. if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
  16322. return AtomicExpansionKind::CmpXChg;
  16323. return AtomicExpansionKind::LLSC;
  16324. }
  16325. // For the real atomic operations, we have ldxr/stxr up to 128 bits,
  16326. TargetLowering::AtomicExpansionKind
  16327. AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
  16328. if (AI->isFloatingPointOperation())
  16329. return AtomicExpansionKind::CmpXChg;
  16330. unsigned Size = AI->getType()->getPrimitiveSizeInBits();
  16331. if (Size > 128) return AtomicExpansionKind::None;
  16332. // Nand is not supported in LSE.
  16333. // Leave 128 bits to LLSC or CmpXChg.
  16334. if (AI->getOperation() != AtomicRMWInst::Nand && Size < 128) {
  16335. if (Subtarget->hasLSE())
  16336. return AtomicExpansionKind::None;
  16337. if (Subtarget->outlineAtomics()) {
  16338. // [U]Min/[U]Max RWM atomics are used in __sync_fetch_ libcalls so far.
  16339. // Don't outline them unless
  16340. // (1) high level <atomic> support approved:
  16341. // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0493r1.pdf
  16342. // (2) low level libgcc and compiler-rt support implemented by:
  16343. // min/max outline atomics helpers
  16344. if (AI->getOperation() != AtomicRMWInst::Min &&
  16345. AI->getOperation() != AtomicRMWInst::Max &&
  16346. AI->getOperation() != AtomicRMWInst::UMin &&
  16347. AI->getOperation() != AtomicRMWInst::UMax) {
  16348. return AtomicExpansionKind::None;
  16349. }
  16350. }
  16351. }
  16352. // At -O0, fast-regalloc cannot cope with the live vregs necessary to
  16353. // implement atomicrmw without spilling. If the target address is also on the
  16354. // stack and close enough to the spill slot, this can lead to a situation
  16355. // where the monitor always gets cleared and the atomic operation can never
  16356. // succeed. So at -O0 lower this operation to a CAS loop.
  16357. if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
  16358. return AtomicExpansionKind::CmpXChg;
  16359. return AtomicExpansionKind::LLSC;
  16360. }
  16361. TargetLowering::AtomicExpansionKind
  16362. AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
  16363. AtomicCmpXchgInst *AI) const {
  16364. // If subtarget has LSE, leave cmpxchg intact for codegen.
  16365. if (Subtarget->hasLSE() || Subtarget->outlineAtomics())
  16366. return AtomicExpansionKind::None;
  16367. // At -O0, fast-regalloc cannot cope with the live vregs necessary to
  16368. // implement cmpxchg without spilling. If the address being exchanged is also
  16369. // on the stack and close enough to the spill slot, this can lead to a
  16370. // situation where the monitor always gets cleared and the atomic operation
  16371. // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
  16372. if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
  16373. return AtomicExpansionKind::None;
  16374. // 128-bit atomic cmpxchg is weird; AtomicExpand doesn't know how to expand
  16375. // it.
  16376. unsigned Size = AI->getCompareOperand()->getType()->getPrimitiveSizeInBits();
  16377. if (Size > 64)
  16378. return AtomicExpansionKind::None;
  16379. return AtomicExpansionKind::LLSC;
  16380. }
  16381. Value *AArch64TargetLowering::emitLoadLinked(IRBuilderBase &Builder,
  16382. Type *ValueTy, Value *Addr,
  16383. AtomicOrdering Ord) const {
  16384. Module *M = Builder.GetInsertBlock()->getParent()->getParent();
  16385. bool IsAcquire = isAcquireOrStronger(Ord);
  16386. // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
  16387. // intrinsic must return {i64, i64} and we have to recombine them into a
  16388. // single i128 here.
  16389. if (ValueTy->getPrimitiveSizeInBits() == 128) {
  16390. Intrinsic::ID Int =
  16391. IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
  16392. Function *Ldxr = Intrinsic::getDeclaration(M, Int);
  16393. Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
  16394. Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
  16395. Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
  16396. Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
  16397. Lo = Builder.CreateZExt(Lo, ValueTy, "lo64");
  16398. Hi = Builder.CreateZExt(Hi, ValueTy, "hi64");
  16399. return Builder.CreateOr(
  16400. Lo, Builder.CreateShl(Hi, ConstantInt::get(ValueTy, 64)), "val64");
  16401. }
  16402. Type *Tys[] = { Addr->getType() };
  16403. Intrinsic::ID Int =
  16404. IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
  16405. Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
  16406. const DataLayout &DL = M->getDataLayout();
  16407. IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(ValueTy));
  16408. Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
  16409. return Builder.CreateBitCast(Trunc, ValueTy);
  16410. }
  16411. void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
  16412. IRBuilderBase &Builder) const {
  16413. Module *M = Builder.GetInsertBlock()->getParent()->getParent();
  16414. Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
  16415. }
  16416. Value *AArch64TargetLowering::emitStoreConditional(IRBuilderBase &Builder,
  16417. Value *Val, Value *Addr,
  16418. AtomicOrdering Ord) const {
  16419. Module *M = Builder.GetInsertBlock()->getParent()->getParent();
  16420. bool IsRelease = isReleaseOrStronger(Ord);
  16421. // Since the intrinsics must have legal type, the i128 intrinsics take two
  16422. // parameters: "i64, i64". We must marshal Val into the appropriate form
  16423. // before the call.
  16424. if (Val->getType()->getPrimitiveSizeInBits() == 128) {
  16425. Intrinsic::ID Int =
  16426. IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
  16427. Function *Stxr = Intrinsic::getDeclaration(M, Int);
  16428. Type *Int64Ty = Type::getInt64Ty(M->getContext());
  16429. Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
  16430. Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
  16431. Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
  16432. return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
  16433. }
  16434. Intrinsic::ID Int =
  16435. IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
  16436. Type *Tys[] = { Addr->getType() };
  16437. Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
  16438. const DataLayout &DL = M->getDataLayout();
  16439. IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
  16440. Val = Builder.CreateBitCast(Val, IntValTy);
  16441. return Builder.CreateCall(Stxr,
  16442. {Builder.CreateZExtOrBitCast(
  16443. Val, Stxr->getFunctionType()->getParamType(0)),
  16444. Addr});
  16445. }
  16446. bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
  16447. Type *Ty, CallingConv::ID CallConv, bool isVarArg,
  16448. const DataLayout &DL) const {
  16449. if (!Ty->isArrayTy()) {
  16450. const TypeSize &TySize = Ty->getPrimitiveSizeInBits();
  16451. return TySize.isScalable() && TySize.getKnownMinSize() > 128;
  16452. }
  16453. // All non aggregate members of the type must have the same type
  16454. SmallVector<EVT> ValueVTs;
  16455. ComputeValueVTs(*this, DL, Ty, ValueVTs);
  16456. return is_splat(ValueVTs);
  16457. }
  16458. bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
  16459. EVT) const {
  16460. return false;
  16461. }
  16462. static Value *UseTlsOffset(IRBuilderBase &IRB, unsigned Offset) {
  16463. Module *M = IRB.GetInsertBlock()->getParent()->getParent();
  16464. Function *ThreadPointerFunc =
  16465. Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
  16466. return IRB.CreatePointerCast(
  16467. IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
  16468. Offset),
  16469. IRB.getInt8PtrTy()->getPointerTo(0));
  16470. }
  16471. Value *AArch64TargetLowering::getIRStackGuard(IRBuilderBase &IRB) const {
  16472. // Android provides a fixed TLS slot for the stack cookie. See the definition
  16473. // of TLS_SLOT_STACK_GUARD in
  16474. // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
  16475. if (Subtarget->isTargetAndroid())
  16476. return UseTlsOffset(IRB, 0x28);
  16477. // Fuchsia is similar.
  16478. // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
  16479. if (Subtarget->isTargetFuchsia())
  16480. return UseTlsOffset(IRB, -0x10);
  16481. return TargetLowering::getIRStackGuard(IRB);
  16482. }
  16483. void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
  16484. // MSVC CRT provides functionalities for stack protection.
  16485. if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
  16486. // MSVC CRT has a global variable holding security cookie.
  16487. M.getOrInsertGlobal("__security_cookie",
  16488. Type::getInt8PtrTy(M.getContext()));
  16489. // MSVC CRT has a function to validate security cookie.
  16490. FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
  16491. "__security_check_cookie", Type::getVoidTy(M.getContext()),
  16492. Type::getInt8PtrTy(M.getContext()));
  16493. if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
  16494. F->setCallingConv(CallingConv::Win64);
  16495. F->addParamAttr(0, Attribute::AttrKind::InReg);
  16496. }
  16497. return;
  16498. }
  16499. TargetLowering::insertSSPDeclarations(M);
  16500. }
  16501. Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
  16502. // MSVC CRT has a global variable holding security cookie.
  16503. if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
  16504. return M.getGlobalVariable("__security_cookie");
  16505. return TargetLowering::getSDagStackGuard(M);
  16506. }
  16507. Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
  16508. // MSVC CRT has a function to validate security cookie.
  16509. if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
  16510. return M.getFunction("__security_check_cookie");
  16511. return TargetLowering::getSSPStackGuardCheck(M);
  16512. }
  16513. Value *
  16514. AArch64TargetLowering::getSafeStackPointerLocation(IRBuilderBase &IRB) const {
  16515. // Android provides a fixed TLS slot for the SafeStack pointer. See the
  16516. // definition of TLS_SLOT_SAFESTACK in
  16517. // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
  16518. if (Subtarget->isTargetAndroid())
  16519. return UseTlsOffset(IRB, 0x48);
  16520. // Fuchsia is similar.
  16521. // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
  16522. if (Subtarget->isTargetFuchsia())
  16523. return UseTlsOffset(IRB, -0x8);
  16524. return TargetLowering::getSafeStackPointerLocation(IRB);
  16525. }
  16526. bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
  16527. const Instruction &AndI) const {
  16528. // Only sink 'and' mask to cmp use block if it is masking a single bit, since
  16529. // this is likely to be fold the and/cmp/br into a single tbz instruction. It
  16530. // may be beneficial to sink in other cases, but we would have to check that
  16531. // the cmp would not get folded into the br to form a cbz for these to be
  16532. // beneficial.
  16533. ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
  16534. if (!Mask)
  16535. return false;
  16536. return Mask->getValue().isPowerOf2();
  16537. }
  16538. bool AArch64TargetLowering::
  16539. shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
  16540. SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
  16541. unsigned OldShiftOpcode, unsigned NewShiftOpcode,
  16542. SelectionDAG &DAG) const {
  16543. // Does baseline recommend not to perform the fold by default?
  16544. if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
  16545. X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
  16546. return false;
  16547. // Else, if this is a vector shift, prefer 'shl'.
  16548. return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
  16549. }
  16550. bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
  16551. SDNode *N) const {
  16552. if (DAG.getMachineFunction().getFunction().hasMinSize() &&
  16553. !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
  16554. return false;
  16555. return true;
  16556. }
  16557. void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
  16558. // Update IsSplitCSR in AArch64unctionInfo.
  16559. AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
  16560. AFI->setIsSplitCSR(true);
  16561. }
  16562. void AArch64TargetLowering::insertCopiesSplitCSR(
  16563. MachineBasicBlock *Entry,
  16564. const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
  16565. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
  16566. const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
  16567. if (!IStart)
  16568. return;
  16569. const TargetInstrInfo *TII = Subtarget->getInstrInfo();
  16570. MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
  16571. MachineBasicBlock::iterator MBBI = Entry->begin();
  16572. for (const MCPhysReg *I = IStart; *I; ++I) {
  16573. const TargetRegisterClass *RC = nullptr;
  16574. if (AArch64::GPR64RegClass.contains(*I))
  16575. RC = &AArch64::GPR64RegClass;
  16576. else if (AArch64::FPR64RegClass.contains(*I))
  16577. RC = &AArch64::FPR64RegClass;
  16578. else
  16579. llvm_unreachable("Unexpected register class in CSRsViaCopy!");
  16580. Register NewVR = MRI->createVirtualRegister(RC);
  16581. // Create copy from CSR to a virtual register.
  16582. // FIXME: this currently does not emit CFI pseudo-instructions, it works
  16583. // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
  16584. // nounwind. If we want to generalize this later, we may need to emit
  16585. // CFI pseudo-instructions.
  16586. assert(Entry->getParent()->getFunction().hasFnAttribute(
  16587. Attribute::NoUnwind) &&
  16588. "Function should be nounwind in insertCopiesSplitCSR!");
  16589. Entry->addLiveIn(*I);
  16590. BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
  16591. .addReg(*I);
  16592. // Insert the copy-back instructions right before the terminator.
  16593. for (auto *Exit : Exits)
  16594. BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
  16595. TII->get(TargetOpcode::COPY), *I)
  16596. .addReg(NewVR);
  16597. }
  16598. }
  16599. bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
  16600. // Integer division on AArch64 is expensive. However, when aggressively
  16601. // optimizing for code size, we prefer to use a div instruction, as it is
  16602. // usually smaller than the alternative sequence.
  16603. // The exception to this is vector division. Since AArch64 doesn't have vector
  16604. // integer division, leaving the division as-is is a loss even in terms of
  16605. // size, because it will have to be scalarized, while the alternative code
  16606. // sequence can be performed in vector form.
  16607. bool OptSize = Attr.hasFnAttr(Attribute::MinSize);
  16608. return OptSize && !VT.isVector();
  16609. }
  16610. bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
  16611. // We want inc-of-add for scalars and sub-of-not for vectors.
  16612. return VT.isScalarInteger();
  16613. }
  16614. bool AArch64TargetLowering::shouldConvertFpToSat(unsigned Op, EVT FPVT,
  16615. EVT VT) const {
  16616. // v8f16 without fp16 need to be extended to v8f32, which is more difficult to
  16617. // legalize.
  16618. if (FPVT == MVT::v8f16 && !Subtarget->hasFullFP16())
  16619. return false;
  16620. return TargetLowering::shouldConvertFpToSat(Op, FPVT, VT);
  16621. }
  16622. bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
  16623. return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
  16624. }
  16625. unsigned
  16626. AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
  16627. if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
  16628. return getPointerTy(DL).getSizeInBits();
  16629. return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
  16630. }
  16631. void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
  16632. MachineFrameInfo &MFI = MF.getFrameInfo();
  16633. // If we have any vulnerable SVE stack objects then the stack protector
  16634. // needs to be placed at the top of the SVE stack area, as the SVE locals
  16635. // are placed above the other locals, so we allocate it as if it were a
  16636. // scalable vector.
  16637. // FIXME: It may be worthwhile having a specific interface for this rather
  16638. // than doing it here in finalizeLowering.
  16639. if (MFI.hasStackProtectorIndex()) {
  16640. for (unsigned int i = 0, e = MFI.getObjectIndexEnd(); i != e; ++i) {
  16641. if (MFI.getStackID(i) == TargetStackID::ScalableVector &&
  16642. MFI.getObjectSSPLayout(i) != MachineFrameInfo::SSPLK_None) {
  16643. MFI.setStackID(MFI.getStackProtectorIndex(),
  16644. TargetStackID::ScalableVector);
  16645. MFI.setObjectAlignment(MFI.getStackProtectorIndex(), Align(16));
  16646. break;
  16647. }
  16648. }
  16649. }
  16650. MFI.computeMaxCallFrameSize(MF);
  16651. TargetLoweringBase::finalizeLowering(MF);
  16652. }
  16653. // Unlike X86, we let frame lowering assign offsets to all catch objects.
  16654. bool AArch64TargetLowering::needsFixedCatchObjects() const {
  16655. return false;
  16656. }
  16657. bool AArch64TargetLowering::shouldLocalize(
  16658. const MachineInstr &MI, const TargetTransformInfo *TTI) const {
  16659. switch (MI.getOpcode()) {
  16660. case TargetOpcode::G_GLOBAL_VALUE: {
  16661. // On Darwin, TLS global vars get selected into function calls, which
  16662. // we don't want localized, as they can get moved into the middle of a
  16663. // another call sequence.
  16664. const GlobalValue &GV = *MI.getOperand(1).getGlobal();
  16665. if (GV.isThreadLocal() && Subtarget->isTargetMachO())
  16666. return false;
  16667. break;
  16668. }
  16669. // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
  16670. // localizable.
  16671. case AArch64::ADRP:
  16672. case AArch64::G_ADD_LOW:
  16673. return true;
  16674. default:
  16675. break;
  16676. }
  16677. return TargetLoweringBase::shouldLocalize(MI, TTI);
  16678. }
  16679. bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
  16680. if (isa<ScalableVectorType>(Inst.getType()))
  16681. return true;
  16682. for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
  16683. if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
  16684. return true;
  16685. if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
  16686. if (isa<ScalableVectorType>(AI->getAllocatedType()))
  16687. return true;
  16688. }
  16689. return false;
  16690. }
  16691. // Return the largest legal scalable vector type that matches VT's element type.
  16692. static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
  16693. assert(VT.isFixedLengthVector() &&
  16694. DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
  16695. "Expected legal fixed length vector!");
  16696. switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
  16697. default:
  16698. llvm_unreachable("unexpected element type for SVE container");
  16699. case MVT::i8:
  16700. return EVT(MVT::nxv16i8);
  16701. case MVT::i16:
  16702. return EVT(MVT::nxv8i16);
  16703. case MVT::i32:
  16704. return EVT(MVT::nxv4i32);
  16705. case MVT::i64:
  16706. return EVT(MVT::nxv2i64);
  16707. case MVT::f16:
  16708. return EVT(MVT::nxv8f16);
  16709. case MVT::f32:
  16710. return EVT(MVT::nxv4f32);
  16711. case MVT::f64:
  16712. return EVT(MVT::nxv2f64);
  16713. }
  16714. }
  16715. // Return a PTRUE with active lanes corresponding to the extent of VT.
  16716. static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
  16717. EVT VT) {
  16718. assert(VT.isFixedLengthVector() &&
  16719. DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
  16720. "Expected legal fixed length vector!");
  16721. Optional<unsigned> PgPattern =
  16722. getSVEPredPatternFromNumElements(VT.getVectorNumElements());
  16723. assert(PgPattern && "Unexpected element count for SVE predicate");
  16724. // For vectors that are exactly getMaxSVEVectorSizeInBits big, we can use
  16725. // AArch64SVEPredPattern::all, which can enable the use of unpredicated
  16726. // variants of instructions when available.
  16727. const auto &Subtarget =
  16728. static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
  16729. unsigned MinSVESize = Subtarget.getMinSVEVectorSizeInBits();
  16730. unsigned MaxSVESize = Subtarget.getMaxSVEVectorSizeInBits();
  16731. if (MaxSVESize && MinSVESize == MaxSVESize &&
  16732. MaxSVESize == VT.getSizeInBits())
  16733. PgPattern = AArch64SVEPredPattern::all;
  16734. MVT MaskVT;
  16735. switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
  16736. default:
  16737. llvm_unreachable("unexpected element type for SVE predicate");
  16738. case MVT::i8:
  16739. MaskVT = MVT::nxv16i1;
  16740. break;
  16741. case MVT::i16:
  16742. case MVT::f16:
  16743. MaskVT = MVT::nxv8i1;
  16744. break;
  16745. case MVT::i32:
  16746. case MVT::f32:
  16747. MaskVT = MVT::nxv4i1;
  16748. break;
  16749. case MVT::i64:
  16750. case MVT::f64:
  16751. MaskVT = MVT::nxv2i1;
  16752. break;
  16753. }
  16754. return getPTrue(DAG, DL, MaskVT, *PgPattern);
  16755. }
  16756. static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
  16757. EVT VT) {
  16758. assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
  16759. "Expected legal scalable vector!");
  16760. auto PredTy = VT.changeVectorElementType(MVT::i1);
  16761. return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
  16762. }
  16763. static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
  16764. if (VT.isFixedLengthVector())
  16765. return getPredicateForFixedLengthVector(DAG, DL, VT);
  16766. return getPredicateForScalableVector(DAG, DL, VT);
  16767. }
  16768. // Grow V to consume an entire SVE register.
  16769. static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
  16770. assert(VT.isScalableVector() &&
  16771. "Expected to convert into a scalable vector!");
  16772. assert(V.getValueType().isFixedLengthVector() &&
  16773. "Expected a fixed length vector operand!");
  16774. SDLoc DL(V);
  16775. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  16776. return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
  16777. }
  16778. // Shrink V so it's just big enough to maintain a VT's worth of data.
  16779. static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
  16780. assert(VT.isFixedLengthVector() &&
  16781. "Expected to convert into a fixed length vector!");
  16782. assert(V.getValueType().isScalableVector() &&
  16783. "Expected a scalable vector operand!");
  16784. SDLoc DL(V);
  16785. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  16786. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
  16787. }
  16788. // Convert all fixed length vector loads larger than NEON to masked_loads.
  16789. SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
  16790. SDValue Op, SelectionDAG &DAG) const {
  16791. auto Load = cast<LoadSDNode>(Op);
  16792. SDLoc DL(Op);
  16793. EVT VT = Op.getValueType();
  16794. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  16795. EVT LoadVT = ContainerVT;
  16796. EVT MemVT = Load->getMemoryVT();
  16797. auto Pg = getPredicateForFixedLengthVector(DAG, DL, VT);
  16798. if (VT.isFloatingPoint() && Load->getExtensionType() == ISD::EXTLOAD) {
  16799. LoadVT = ContainerVT.changeTypeToInteger();
  16800. MemVT = MemVT.changeTypeToInteger();
  16801. }
  16802. auto NewLoad = DAG.getMaskedLoad(
  16803. LoadVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(), Pg,
  16804. DAG.getUNDEF(LoadVT), MemVT, Load->getMemOperand(),
  16805. Load->getAddressingMode(), Load->getExtensionType());
  16806. if (VT.isFloatingPoint() && Load->getExtensionType() == ISD::EXTLOAD) {
  16807. EVT ExtendVT = ContainerVT.changeVectorElementType(
  16808. Load->getMemoryVT().getVectorElementType());
  16809. NewLoad = getSVESafeBitCast(ExtendVT, NewLoad, DAG);
  16810. NewLoad = DAG.getNode(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU, DL, ContainerVT,
  16811. Pg, NewLoad, DAG.getUNDEF(ContainerVT));
  16812. }
  16813. auto Result = convertFromScalableVector(DAG, VT, NewLoad);
  16814. SDValue MergedValues[2] = {Result, Load->getChain()};
  16815. return DAG.getMergeValues(MergedValues, DL);
  16816. }
  16817. static SDValue convertFixedMaskToScalableVector(SDValue Mask,
  16818. SelectionDAG &DAG) {
  16819. SDLoc DL(Mask);
  16820. EVT InVT = Mask.getValueType();
  16821. EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
  16822. auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
  16823. if (ISD::isBuildVectorAllOnes(Mask.getNode()))
  16824. return Pg;
  16825. auto Op1 = convertToScalableVector(DAG, ContainerVT, Mask);
  16826. auto Op2 = DAG.getConstant(0, DL, ContainerVT);
  16827. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, Pg.getValueType(),
  16828. {Pg, Op1, Op2, DAG.getCondCode(ISD::SETNE)});
  16829. }
  16830. // Convert all fixed length vector loads larger than NEON to masked_loads.
  16831. SDValue AArch64TargetLowering::LowerFixedLengthVectorMLoadToSVE(
  16832. SDValue Op, SelectionDAG &DAG) const {
  16833. auto Load = cast<MaskedLoadSDNode>(Op);
  16834. SDLoc DL(Op);
  16835. EVT VT = Op.getValueType();
  16836. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  16837. SDValue Mask = convertFixedMaskToScalableVector(Load->getMask(), DAG);
  16838. SDValue PassThru;
  16839. bool IsPassThruZeroOrUndef = false;
  16840. if (Load->getPassThru()->isUndef()) {
  16841. PassThru = DAG.getUNDEF(ContainerVT);
  16842. IsPassThruZeroOrUndef = true;
  16843. } else {
  16844. if (ContainerVT.isInteger())
  16845. PassThru = DAG.getConstant(0, DL, ContainerVT);
  16846. else
  16847. PassThru = DAG.getConstantFP(0, DL, ContainerVT);
  16848. if (isZerosVector(Load->getPassThru().getNode()))
  16849. IsPassThruZeroOrUndef = true;
  16850. }
  16851. auto NewLoad = DAG.getMaskedLoad(
  16852. ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
  16853. Mask, PassThru, Load->getMemoryVT(), Load->getMemOperand(),
  16854. Load->getAddressingMode(), Load->getExtensionType());
  16855. if (!IsPassThruZeroOrUndef) {
  16856. SDValue OldPassThru =
  16857. convertToScalableVector(DAG, ContainerVT, Load->getPassThru());
  16858. NewLoad = DAG.getSelect(DL, ContainerVT, Mask, NewLoad, OldPassThru);
  16859. }
  16860. auto Result = convertFromScalableVector(DAG, VT, NewLoad);
  16861. SDValue MergedValues[2] = {Result, Load->getChain()};
  16862. return DAG.getMergeValues(MergedValues, DL);
  16863. }
  16864. // Convert all fixed length vector stores larger than NEON to masked_stores.
  16865. SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
  16866. SDValue Op, SelectionDAG &DAG) const {
  16867. auto Store = cast<StoreSDNode>(Op);
  16868. SDLoc DL(Op);
  16869. EVT VT = Store->getValue().getValueType();
  16870. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  16871. EVT MemVT = Store->getMemoryVT();
  16872. auto Pg = getPredicateForFixedLengthVector(DAG, DL, VT);
  16873. auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
  16874. if (VT.isFloatingPoint() && Store->isTruncatingStore()) {
  16875. EVT TruncVT = ContainerVT.changeVectorElementType(
  16876. Store->getMemoryVT().getVectorElementType());
  16877. MemVT = MemVT.changeTypeToInteger();
  16878. NewValue = DAG.getNode(AArch64ISD::FP_ROUND_MERGE_PASSTHRU, DL, TruncVT, Pg,
  16879. NewValue, DAG.getTargetConstant(0, DL, MVT::i64),
  16880. DAG.getUNDEF(TruncVT));
  16881. NewValue =
  16882. getSVESafeBitCast(ContainerVT.changeTypeToInteger(), NewValue, DAG);
  16883. }
  16884. return DAG.getMaskedStore(Store->getChain(), DL, NewValue,
  16885. Store->getBasePtr(), Store->getOffset(), Pg, MemVT,
  16886. Store->getMemOperand(), Store->getAddressingMode(),
  16887. Store->isTruncatingStore());
  16888. }
  16889. SDValue AArch64TargetLowering::LowerFixedLengthVectorMStoreToSVE(
  16890. SDValue Op, SelectionDAG &DAG) const {
  16891. auto *Store = cast<MaskedStoreSDNode>(Op);
  16892. SDLoc DL(Op);
  16893. EVT VT = Store->getValue().getValueType();
  16894. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  16895. auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
  16896. SDValue Mask = convertFixedMaskToScalableVector(Store->getMask(), DAG);
  16897. return DAG.getMaskedStore(
  16898. Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
  16899. Mask, Store->getMemoryVT(), Store->getMemOperand(),
  16900. Store->getAddressingMode(), Store->isTruncatingStore());
  16901. }
  16902. SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE(
  16903. SDValue Op, SelectionDAG &DAG) const {
  16904. SDLoc dl(Op);
  16905. EVT VT = Op.getValueType();
  16906. EVT EltVT = VT.getVectorElementType();
  16907. bool Signed = Op.getOpcode() == ISD::SDIV;
  16908. unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
  16909. bool Negated;
  16910. uint64_t SplatVal;
  16911. if (Signed && isPow2Splat(Op.getOperand(1), SplatVal, Negated)) {
  16912. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  16913. SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
  16914. SDValue Op2 = DAG.getTargetConstant(Log2_64(SplatVal), dl, MVT::i32);
  16915. SDValue Pg = getPredicateForFixedLengthVector(DAG, dl, VT);
  16916. SDValue Res = DAG.getNode(AArch64ISD::SRAD_MERGE_OP1, dl, ContainerVT, Pg, Op1, Op2);
  16917. if (Negated)
  16918. Res = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), Res);
  16919. return convertFromScalableVector(DAG, VT, Res);
  16920. }
  16921. // Scalable vector i32/i64 DIV is supported.
  16922. if (EltVT == MVT::i32 || EltVT == MVT::i64)
  16923. return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true);
  16924. // Scalable vector i8/i16 DIV is not supported. Promote it to i32.
  16925. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  16926. EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
  16927. EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext());
  16928. EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT);
  16929. // If this is not a full vector, extend, div, and truncate it.
  16930. EVT WidenedVT = VT.widenIntegerVectorElementType(*DAG.getContext());
  16931. if (DAG.getTargetLoweringInfo().isTypeLegal(WidenedVT)) {
  16932. unsigned ExtendOpcode = Signed ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  16933. SDValue Op0 = DAG.getNode(ExtendOpcode, dl, WidenedVT, Op.getOperand(0));
  16934. SDValue Op1 = DAG.getNode(ExtendOpcode, dl, WidenedVT, Op.getOperand(1));
  16935. SDValue Div = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0, Op1);
  16936. return DAG.getNode(ISD::TRUNCATE, dl, VT, Div);
  16937. }
  16938. // Convert the operands to scalable vectors.
  16939. SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
  16940. SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
  16941. // Extend the scalable operands.
  16942. unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
  16943. unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
  16944. SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0);
  16945. SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1);
  16946. SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0);
  16947. SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1);
  16948. // Convert back to fixed vectors so the DIV can be further lowered.
  16949. Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo);
  16950. Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo);
  16951. Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi);
  16952. Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi);
  16953. SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
  16954. Op0Lo, Op1Lo);
  16955. SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
  16956. Op0Hi, Op1Hi);
  16957. // Convert again to scalable vectors to truncate.
  16958. ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo);
  16959. ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi);
  16960. SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT,
  16961. ResultLo, ResultHi);
  16962. return convertFromScalableVector(DAG, VT, ScalableResult);
  16963. }
  16964. SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE(
  16965. SDValue Op, SelectionDAG &DAG) const {
  16966. EVT VT = Op.getValueType();
  16967. assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
  16968. SDLoc DL(Op);
  16969. SDValue Val = Op.getOperand(0);
  16970. EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
  16971. Val = convertToScalableVector(DAG, ContainerVT, Val);
  16972. bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND;
  16973. unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
  16974. // Repeatedly unpack Val until the result is of the desired element type.
  16975. switch (ContainerVT.getSimpleVT().SimpleTy) {
  16976. default:
  16977. llvm_unreachable("unimplemented container type");
  16978. case MVT::nxv16i8:
  16979. Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val);
  16980. if (VT.getVectorElementType() == MVT::i16)
  16981. break;
  16982. LLVM_FALLTHROUGH;
  16983. case MVT::nxv8i16:
  16984. Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val);
  16985. if (VT.getVectorElementType() == MVT::i32)
  16986. break;
  16987. LLVM_FALLTHROUGH;
  16988. case MVT::nxv4i32:
  16989. Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val);
  16990. assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!");
  16991. break;
  16992. }
  16993. return convertFromScalableVector(DAG, VT, Val);
  16994. }
  16995. SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
  16996. SDValue Op, SelectionDAG &DAG) const {
  16997. EVT VT = Op.getValueType();
  16998. assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
  16999. SDLoc DL(Op);
  17000. SDValue Val = Op.getOperand(0);
  17001. EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
  17002. Val = convertToScalableVector(DAG, ContainerVT, Val);
  17003. // Repeatedly truncate Val until the result is of the desired element type.
  17004. switch (ContainerVT.getSimpleVT().SimpleTy) {
  17005. default:
  17006. llvm_unreachable("unimplemented container type");
  17007. case MVT::nxv2i64:
  17008. Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
  17009. Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
  17010. if (VT.getVectorElementType() == MVT::i32)
  17011. break;
  17012. LLVM_FALLTHROUGH;
  17013. case MVT::nxv4i32:
  17014. Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
  17015. Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
  17016. if (VT.getVectorElementType() == MVT::i16)
  17017. break;
  17018. LLVM_FALLTHROUGH;
  17019. case MVT::nxv8i16:
  17020. Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
  17021. Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
  17022. assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
  17023. break;
  17024. }
  17025. return convertFromScalableVector(DAG, VT, Val);
  17026. }
  17027. SDValue AArch64TargetLowering::LowerFixedLengthExtractVectorElt(
  17028. SDValue Op, SelectionDAG &DAG) const {
  17029. EVT VT = Op.getValueType();
  17030. EVT InVT = Op.getOperand(0).getValueType();
  17031. assert(InVT.isFixedLengthVector() && "Expected fixed length vector type!");
  17032. SDLoc DL(Op);
  17033. EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
  17034. SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(0));
  17035. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Op.getOperand(1));
  17036. }
  17037. SDValue AArch64TargetLowering::LowerFixedLengthInsertVectorElt(
  17038. SDValue Op, SelectionDAG &DAG) const {
  17039. EVT VT = Op.getValueType();
  17040. assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
  17041. SDLoc DL(Op);
  17042. EVT InVT = Op.getOperand(0).getValueType();
  17043. EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
  17044. SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(0));
  17045. auto ScalableRes = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT, Op0,
  17046. Op.getOperand(1), Op.getOperand(2));
  17047. return convertFromScalableVector(DAG, VT, ScalableRes);
  17048. }
  17049. // Convert vector operation 'Op' to an equivalent predicated operation whereby
  17050. // the original operation's type is used to construct a suitable predicate.
  17051. // NOTE: The results for inactive lanes are undefined.
  17052. SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
  17053. SelectionDAG &DAG,
  17054. unsigned NewOp,
  17055. bool OverrideNEON) const {
  17056. EVT VT = Op.getValueType();
  17057. SDLoc DL(Op);
  17058. auto Pg = getPredicateForVector(DAG, DL, VT);
  17059. if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) {
  17060. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  17061. // Create list of operands by converting existing ones to scalable types.
  17062. SmallVector<SDValue, 4> Operands = {Pg};
  17063. for (const SDValue &V : Op->op_values()) {
  17064. if (isa<CondCodeSDNode>(V)) {
  17065. Operands.push_back(V);
  17066. continue;
  17067. }
  17068. if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) {
  17069. EVT VTArg = VTNode->getVT().getVectorElementType();
  17070. EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg);
  17071. Operands.push_back(DAG.getValueType(NewVTArg));
  17072. continue;
  17073. }
  17074. assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) &&
  17075. "Only fixed length vectors are supported!");
  17076. Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
  17077. }
  17078. if (isMergePassthruOpcode(NewOp))
  17079. Operands.push_back(DAG.getUNDEF(ContainerVT));
  17080. auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
  17081. return convertFromScalableVector(DAG, VT, ScalableRes);
  17082. }
  17083. assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
  17084. SmallVector<SDValue, 4> Operands = {Pg};
  17085. for (const SDValue &V : Op->op_values()) {
  17086. assert((!V.getValueType().isVector() ||
  17087. V.getValueType().isScalableVector()) &&
  17088. "Only scalable vectors are supported!");
  17089. Operands.push_back(V);
  17090. }
  17091. if (isMergePassthruOpcode(NewOp))
  17092. Operands.push_back(DAG.getUNDEF(VT));
  17093. return DAG.getNode(NewOp, DL, VT, Operands, Op->getFlags());
  17094. }
  17095. // If a fixed length vector operation has no side effects when applied to
  17096. // undefined elements, we can safely use scalable vectors to perform the same
  17097. // operation without needing to worry about predication.
  17098. SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op,
  17099. SelectionDAG &DAG) const {
  17100. EVT VT = Op.getValueType();
  17101. assert(useSVEForFixedLengthVectorVT(VT) &&
  17102. "Only expected to lower fixed length vector operation!");
  17103. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  17104. // Create list of operands by converting existing ones to scalable types.
  17105. SmallVector<SDValue, 4> Ops;
  17106. for (const SDValue &V : Op->op_values()) {
  17107. assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
  17108. // Pass through non-vector operands.
  17109. if (!V.getValueType().isVector()) {
  17110. Ops.push_back(V);
  17111. continue;
  17112. }
  17113. // "cast" fixed length vector to a scalable vector.
  17114. assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
  17115. "Only fixed length vectors are supported!");
  17116. Ops.push_back(convertToScalableVector(DAG, ContainerVT, V));
  17117. }
  17118. auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops);
  17119. return convertFromScalableVector(DAG, VT, ScalableRes);
  17120. }
  17121. SDValue AArch64TargetLowering::LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp,
  17122. SelectionDAG &DAG) const {
  17123. SDLoc DL(ScalarOp);
  17124. SDValue AccOp = ScalarOp.getOperand(0);
  17125. SDValue VecOp = ScalarOp.getOperand(1);
  17126. EVT SrcVT = VecOp.getValueType();
  17127. EVT ResVT = SrcVT.getVectorElementType();
  17128. EVT ContainerVT = SrcVT;
  17129. if (SrcVT.isFixedLengthVector()) {
  17130. ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
  17131. VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
  17132. }
  17133. SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
  17134. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  17135. // Convert operands to Scalable.
  17136. AccOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT,
  17137. DAG.getUNDEF(ContainerVT), AccOp, Zero);
  17138. // Perform reduction.
  17139. SDValue Rdx = DAG.getNode(AArch64ISD::FADDA_PRED, DL, ContainerVT,
  17140. Pg, AccOp, VecOp);
  17141. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Rdx, Zero);
  17142. }
  17143. SDValue AArch64TargetLowering::LowerPredReductionToSVE(SDValue ReduceOp,
  17144. SelectionDAG &DAG) const {
  17145. SDLoc DL(ReduceOp);
  17146. SDValue Op = ReduceOp.getOperand(0);
  17147. EVT OpVT = Op.getValueType();
  17148. EVT VT = ReduceOp.getValueType();
  17149. if (!OpVT.isScalableVector() || OpVT.getVectorElementType() != MVT::i1)
  17150. return SDValue();
  17151. SDValue Pg = getPredicateForVector(DAG, DL, OpVT);
  17152. switch (ReduceOp.getOpcode()) {
  17153. default:
  17154. return SDValue();
  17155. case ISD::VECREDUCE_OR:
  17156. if (isAllActivePredicate(DAG, Pg))
  17157. // The predicate can be 'Op' because
  17158. // vecreduce_or(Op & <all true>) <=> vecreduce_or(Op).
  17159. return getPTest(DAG, VT, Op, Op, AArch64CC::ANY_ACTIVE);
  17160. else
  17161. return getPTest(DAG, VT, Pg, Op, AArch64CC::ANY_ACTIVE);
  17162. case ISD::VECREDUCE_AND: {
  17163. Op = DAG.getNode(ISD::XOR, DL, OpVT, Op, Pg);
  17164. return getPTest(DAG, VT, Pg, Op, AArch64CC::NONE_ACTIVE);
  17165. }
  17166. case ISD::VECREDUCE_XOR: {
  17167. SDValue ID =
  17168. DAG.getTargetConstant(Intrinsic::aarch64_sve_cntp, DL, MVT::i64);
  17169. SDValue Cntp =
  17170. DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, ID, Pg, Op);
  17171. return DAG.getAnyExtOrTrunc(Cntp, DL, VT);
  17172. }
  17173. }
  17174. return SDValue();
  17175. }
  17176. SDValue AArch64TargetLowering::LowerReductionToSVE(unsigned Opcode,
  17177. SDValue ScalarOp,
  17178. SelectionDAG &DAG) const {
  17179. SDLoc DL(ScalarOp);
  17180. SDValue VecOp = ScalarOp.getOperand(0);
  17181. EVT SrcVT = VecOp.getValueType();
  17182. if (useSVEForFixedLengthVectorVT(SrcVT, true)) {
  17183. EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
  17184. VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
  17185. }
  17186. // UADDV always returns an i64 result.
  17187. EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 :
  17188. SrcVT.getVectorElementType();
  17189. EVT RdxVT = SrcVT;
  17190. if (SrcVT.isFixedLengthVector() || Opcode == AArch64ISD::UADDV_PRED)
  17191. RdxVT = getPackedSVEVectorVT(ResVT);
  17192. SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
  17193. SDValue Rdx = DAG.getNode(Opcode, DL, RdxVT, Pg, VecOp);
  17194. SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT,
  17195. Rdx, DAG.getConstant(0, DL, MVT::i64));
  17196. // The VEC_REDUCE nodes expect an element size result.
  17197. if (ResVT != ScalarOp.getValueType())
  17198. Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType());
  17199. return Res;
  17200. }
  17201. SDValue
  17202. AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op,
  17203. SelectionDAG &DAG) const {
  17204. EVT VT = Op.getValueType();
  17205. SDLoc DL(Op);
  17206. EVT InVT = Op.getOperand(1).getValueType();
  17207. EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
  17208. SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1));
  17209. SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2));
  17210. // Convert the mask to a predicated (NOTE: We don't need to worry about
  17211. // inactive lanes since VSELECT is safe when given undefined elements).
  17212. EVT MaskVT = Op.getOperand(0).getValueType();
  17213. EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT);
  17214. auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0));
  17215. Mask = DAG.getNode(ISD::TRUNCATE, DL,
  17216. MaskContainerVT.changeVectorElementType(MVT::i1), Mask);
  17217. auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT,
  17218. Mask, Op1, Op2);
  17219. return convertFromScalableVector(DAG, VT, ScalableRes);
  17220. }
  17221. SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE(
  17222. SDValue Op, SelectionDAG &DAG) const {
  17223. SDLoc DL(Op);
  17224. EVT InVT = Op.getOperand(0).getValueType();
  17225. EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
  17226. assert(useSVEForFixedLengthVectorVT(InVT) &&
  17227. "Only expected to lower fixed length vector operation!");
  17228. assert(Op.getValueType() == InVT.changeTypeToInteger() &&
  17229. "Expected integer result of the same bit length as the inputs!");
  17230. auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
  17231. auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
  17232. auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
  17233. EVT CmpVT = Pg.getValueType();
  17234. auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT,
  17235. {Pg, Op1, Op2, Op.getOperand(2)});
  17236. EVT PromoteVT = ContainerVT.changeTypeToInteger();
  17237. auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT);
  17238. return convertFromScalableVector(DAG, Op.getValueType(), Promote);
  17239. }
  17240. SDValue
  17241. AArch64TargetLowering::LowerFixedLengthBitcastToSVE(SDValue Op,
  17242. SelectionDAG &DAG) const {
  17243. SDLoc DL(Op);
  17244. auto SrcOp = Op.getOperand(0);
  17245. EVT VT = Op.getValueType();
  17246. EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
  17247. EVT ContainerSrcVT =
  17248. getContainerForFixedLengthVector(DAG, SrcOp.getValueType());
  17249. SrcOp = convertToScalableVector(DAG, ContainerSrcVT, SrcOp);
  17250. Op = DAG.getNode(ISD::BITCAST, DL, ContainerDstVT, SrcOp);
  17251. return convertFromScalableVector(DAG, VT, Op);
  17252. }
  17253. SDValue AArch64TargetLowering::LowerFixedLengthConcatVectorsToSVE(
  17254. SDValue Op, SelectionDAG &DAG) const {
  17255. SDLoc DL(Op);
  17256. unsigned NumOperands = Op->getNumOperands();
  17257. assert(NumOperands > 1 && isPowerOf2_32(NumOperands) &&
  17258. "Unexpected number of operands in CONCAT_VECTORS");
  17259. auto SrcOp1 = Op.getOperand(0);
  17260. auto SrcOp2 = Op.getOperand(1);
  17261. EVT VT = Op.getValueType();
  17262. EVT SrcVT = SrcOp1.getValueType();
  17263. if (NumOperands > 2) {
  17264. SmallVector<SDValue, 4> Ops;
  17265. EVT PairVT = SrcVT.getDoubleNumVectorElementsVT(*DAG.getContext());
  17266. for (unsigned I = 0; I < NumOperands; I += 2)
  17267. Ops.push_back(DAG.getNode(ISD::CONCAT_VECTORS, DL, PairVT,
  17268. Op->getOperand(I), Op->getOperand(I + 1)));
  17269. return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Ops);
  17270. }
  17271. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  17272. SDValue Pg = getPredicateForFixedLengthVector(DAG, DL, SrcVT);
  17273. SrcOp1 = convertToScalableVector(DAG, ContainerVT, SrcOp1);
  17274. SrcOp2 = convertToScalableVector(DAG, ContainerVT, SrcOp2);
  17275. Op = DAG.getNode(AArch64ISD::SPLICE, DL, ContainerVT, Pg, SrcOp1, SrcOp2);
  17276. return convertFromScalableVector(DAG, VT, Op);
  17277. }
  17278. SDValue
  17279. AArch64TargetLowering::LowerFixedLengthFPExtendToSVE(SDValue Op,
  17280. SelectionDAG &DAG) const {
  17281. EVT VT = Op.getValueType();
  17282. assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
  17283. SDLoc DL(Op);
  17284. SDValue Val = Op.getOperand(0);
  17285. SDValue Pg = getPredicateForVector(DAG, DL, VT);
  17286. EVT SrcVT = Val.getValueType();
  17287. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  17288. EVT ExtendVT = ContainerVT.changeVectorElementType(
  17289. SrcVT.getVectorElementType());
  17290. Val = DAG.getNode(ISD::BITCAST, DL, SrcVT.changeTypeToInteger(), Val);
  17291. Val = DAG.getNode(ISD::ANY_EXTEND, DL, VT.changeTypeToInteger(), Val);
  17292. Val = convertToScalableVector(DAG, ContainerVT.changeTypeToInteger(), Val);
  17293. Val = getSVESafeBitCast(ExtendVT, Val, DAG);
  17294. Val = DAG.getNode(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU, DL, ContainerVT,
  17295. Pg, Val, DAG.getUNDEF(ContainerVT));
  17296. return convertFromScalableVector(DAG, VT, Val);
  17297. }
  17298. SDValue
  17299. AArch64TargetLowering::LowerFixedLengthFPRoundToSVE(SDValue Op,
  17300. SelectionDAG &DAG) const {
  17301. EVT VT = Op.getValueType();
  17302. assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
  17303. SDLoc DL(Op);
  17304. SDValue Val = Op.getOperand(0);
  17305. EVT SrcVT = Val.getValueType();
  17306. EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
  17307. EVT RoundVT = ContainerSrcVT.changeVectorElementType(
  17308. VT.getVectorElementType());
  17309. SDValue Pg = getPredicateForVector(DAG, DL, RoundVT);
  17310. Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
  17311. Val = DAG.getNode(AArch64ISD::FP_ROUND_MERGE_PASSTHRU, DL, RoundVT, Pg, Val,
  17312. Op.getOperand(1), DAG.getUNDEF(RoundVT));
  17313. Val = getSVESafeBitCast(ContainerSrcVT.changeTypeToInteger(), Val, DAG);
  17314. Val = convertFromScalableVector(DAG, SrcVT.changeTypeToInteger(), Val);
  17315. Val = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Val);
  17316. return DAG.getNode(ISD::BITCAST, DL, VT, Val);
  17317. }
  17318. SDValue
  17319. AArch64TargetLowering::LowerFixedLengthIntToFPToSVE(SDValue Op,
  17320. SelectionDAG &DAG) const {
  17321. EVT VT = Op.getValueType();
  17322. assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
  17323. bool IsSigned = Op.getOpcode() == ISD::SINT_TO_FP;
  17324. unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU
  17325. : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU;
  17326. SDLoc DL(Op);
  17327. SDValue Val = Op.getOperand(0);
  17328. EVT SrcVT = Val.getValueType();
  17329. EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
  17330. EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
  17331. if (ContainerSrcVT.getVectorElementType().getSizeInBits() <=
  17332. ContainerDstVT.getVectorElementType().getSizeInBits()) {
  17333. SDValue Pg = getPredicateForVector(DAG, DL, VT);
  17334. Val = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
  17335. VT.changeTypeToInteger(), Val);
  17336. Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
  17337. Val = getSVESafeBitCast(ContainerDstVT.changeTypeToInteger(), Val, DAG);
  17338. // Safe to use a larger than specified operand since we just unpacked the
  17339. // data, hence the upper bits are zero.
  17340. Val = DAG.getNode(Opcode, DL, ContainerDstVT, Pg, Val,
  17341. DAG.getUNDEF(ContainerDstVT));
  17342. return convertFromScalableVector(DAG, VT, Val);
  17343. } else {
  17344. EVT CvtVT = ContainerSrcVT.changeVectorElementType(
  17345. ContainerDstVT.getVectorElementType());
  17346. SDValue Pg = getPredicateForVector(DAG, DL, CvtVT);
  17347. Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
  17348. Val = DAG.getNode(Opcode, DL, CvtVT, Pg, Val, DAG.getUNDEF(CvtVT));
  17349. Val = getSVESafeBitCast(ContainerSrcVT, Val, DAG);
  17350. Val = convertFromScalableVector(DAG, SrcVT, Val);
  17351. Val = DAG.getNode(ISD::TRUNCATE, DL, VT.changeTypeToInteger(), Val);
  17352. return DAG.getNode(ISD::BITCAST, DL, VT, Val);
  17353. }
  17354. }
  17355. SDValue
  17356. AArch64TargetLowering::LowerFixedLengthFPToIntToSVE(SDValue Op,
  17357. SelectionDAG &DAG) const {
  17358. EVT VT = Op.getValueType();
  17359. assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
  17360. bool IsSigned = Op.getOpcode() == ISD::FP_TO_SINT;
  17361. unsigned Opcode = IsSigned ? AArch64ISD::FCVTZS_MERGE_PASSTHRU
  17362. : AArch64ISD::FCVTZU_MERGE_PASSTHRU;
  17363. SDLoc DL(Op);
  17364. SDValue Val = Op.getOperand(0);
  17365. EVT SrcVT = Val.getValueType();
  17366. EVT ContainerDstVT = getContainerForFixedLengthVector(DAG, VT);
  17367. EVT ContainerSrcVT = getContainerForFixedLengthVector(DAG, SrcVT);
  17368. if (ContainerSrcVT.getVectorElementType().getSizeInBits() <=
  17369. ContainerDstVT.getVectorElementType().getSizeInBits()) {
  17370. EVT CvtVT = ContainerDstVT.changeVectorElementType(
  17371. ContainerSrcVT.getVectorElementType());
  17372. SDValue Pg = getPredicateForVector(DAG, DL, VT);
  17373. Val = DAG.getNode(ISD::BITCAST, DL, SrcVT.changeTypeToInteger(), Val);
  17374. Val = DAG.getNode(ISD::ANY_EXTEND, DL, VT, Val);
  17375. Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
  17376. Val = getSVESafeBitCast(CvtVT, Val, DAG);
  17377. Val = DAG.getNode(Opcode, DL, ContainerDstVT, Pg, Val,
  17378. DAG.getUNDEF(ContainerDstVT));
  17379. return convertFromScalableVector(DAG, VT, Val);
  17380. } else {
  17381. EVT CvtVT = ContainerSrcVT.changeTypeToInteger();
  17382. SDValue Pg = getPredicateForVector(DAG, DL, CvtVT);
  17383. // Safe to use a larger than specified result since an fp_to_int where the
  17384. // result doesn't fit into the destination is undefined.
  17385. Val = convertToScalableVector(DAG, ContainerSrcVT, Val);
  17386. Val = DAG.getNode(Opcode, DL, CvtVT, Pg, Val, DAG.getUNDEF(CvtVT));
  17387. Val = convertFromScalableVector(DAG, SrcVT.changeTypeToInteger(), Val);
  17388. return DAG.getNode(ISD::TRUNCATE, DL, VT, Val);
  17389. }
  17390. }
  17391. SDValue AArch64TargetLowering::LowerFixedLengthVECTOR_SHUFFLEToSVE(
  17392. SDValue Op, SelectionDAG &DAG) const {
  17393. EVT VT = Op.getValueType();
  17394. assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
  17395. auto *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
  17396. auto ShuffleMask = SVN->getMask();
  17397. SDLoc DL(Op);
  17398. SDValue Op1 = Op.getOperand(0);
  17399. SDValue Op2 = Op.getOperand(1);
  17400. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  17401. Op1 = convertToScalableVector(DAG, ContainerVT, Op1);
  17402. Op2 = convertToScalableVector(DAG, ContainerVT, Op2);
  17403. bool ReverseEXT = false;
  17404. unsigned Imm;
  17405. if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm) &&
  17406. Imm == VT.getVectorNumElements() - 1) {
  17407. if (ReverseEXT)
  17408. std::swap(Op1, Op2);
  17409. EVT ScalarTy = VT.getVectorElementType();
  17410. if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
  17411. ScalarTy = MVT::i32;
  17412. SDValue Scalar = DAG.getNode(
  17413. ISD::EXTRACT_VECTOR_ELT, DL, ScalarTy, Op1,
  17414. DAG.getConstant(VT.getVectorNumElements() - 1, DL, MVT::i64));
  17415. Op = DAG.getNode(AArch64ISD::INSR, DL, ContainerVT, Op2, Scalar);
  17416. return convertFromScalableVector(DAG, VT, Op);
  17417. }
  17418. for (unsigned LaneSize : {64U, 32U, 16U}) {
  17419. if (isREVMask(ShuffleMask, VT, LaneSize)) {
  17420. EVT NewVT =
  17421. getPackedSVEVectorVT(EVT::getIntegerVT(*DAG.getContext(), LaneSize));
  17422. unsigned RevOp;
  17423. unsigned EltSz = VT.getScalarSizeInBits();
  17424. if (EltSz == 8)
  17425. RevOp = AArch64ISD::BSWAP_MERGE_PASSTHRU;
  17426. else if (EltSz == 16)
  17427. RevOp = AArch64ISD::REVH_MERGE_PASSTHRU;
  17428. else
  17429. RevOp = AArch64ISD::REVW_MERGE_PASSTHRU;
  17430. Op = DAG.getNode(ISD::BITCAST, DL, NewVT, Op1);
  17431. Op = LowerToPredicatedOp(Op, DAG, RevOp);
  17432. Op = DAG.getNode(ISD::BITCAST, DL, ContainerVT, Op);
  17433. return convertFromScalableVector(DAG, VT, Op);
  17434. }
  17435. }
  17436. unsigned WhichResult;
  17437. if (isZIPMask(ShuffleMask, VT, WhichResult) && WhichResult == 0)
  17438. return convertFromScalableVector(
  17439. DAG, VT, DAG.getNode(AArch64ISD::ZIP1, DL, ContainerVT, Op1, Op2));
  17440. if (isTRNMask(ShuffleMask, VT, WhichResult)) {
  17441. unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
  17442. return convertFromScalableVector(
  17443. DAG, VT, DAG.getNode(Opc, DL, ContainerVT, Op1, Op2));
  17444. }
  17445. if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult) && WhichResult == 0)
  17446. return convertFromScalableVector(
  17447. DAG, VT, DAG.getNode(AArch64ISD::ZIP1, DL, ContainerVT, Op1, Op1));
  17448. if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
  17449. unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
  17450. return convertFromScalableVector(
  17451. DAG, VT, DAG.getNode(Opc, DL, ContainerVT, Op1, Op1));
  17452. }
  17453. // Functions like isZIPMask return true when a ISD::VECTOR_SHUFFLE's mask
  17454. // represents the same logical operation as performed by a ZIP instruction. In
  17455. // isolation these functions do not mean the ISD::VECTOR_SHUFFLE is exactly
  17456. // equivalent to an AArch64 instruction. There's the extra component of
  17457. // ISD::VECTOR_SHUFFLE's value type to consider. Prior to SVE these functions
  17458. // only operated on 64/128bit vector types that have a direct mapping to a
  17459. // target register and so an exact mapping is implied.
  17460. // However, when using SVE for fixed length vectors, most legal vector types
  17461. // are actually sub-vectors of a larger SVE register. When mapping
  17462. // ISD::VECTOR_SHUFFLE to an SVE instruction care must be taken to consider
  17463. // how the mask's indices translate. Specifically, when the mapping requires
  17464. // an exact meaning for a specific vector index (e.g. Index X is the last
  17465. // vector element in the register) then such mappings are often only safe when
  17466. // the exact SVE register size is know. The main exception to this is when
  17467. // indices are logically relative to the first element of either
  17468. // ISD::VECTOR_SHUFFLE operand because these relative indices don't change
  17469. // when converting from fixed-length to scalable vector types (i.e. the start
  17470. // of a fixed length vector is always the start of a scalable vector).
  17471. unsigned MinSVESize = Subtarget->getMinSVEVectorSizeInBits();
  17472. unsigned MaxSVESize = Subtarget->getMaxSVEVectorSizeInBits();
  17473. if (MinSVESize == MaxSVESize && MaxSVESize == VT.getSizeInBits()) {
  17474. if (ShuffleVectorInst::isReverseMask(ShuffleMask) && Op2.isUndef()) {
  17475. Op = DAG.getNode(ISD::VECTOR_REVERSE, DL, ContainerVT, Op1);
  17476. return convertFromScalableVector(DAG, VT, Op);
  17477. }
  17478. if (isZIPMask(ShuffleMask, VT, WhichResult) && WhichResult != 0)
  17479. return convertFromScalableVector(
  17480. DAG, VT, DAG.getNode(AArch64ISD::ZIP2, DL, ContainerVT, Op1, Op2));
  17481. if (isUZPMask(ShuffleMask, VT, WhichResult)) {
  17482. unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
  17483. return convertFromScalableVector(
  17484. DAG, VT, DAG.getNode(Opc, DL, ContainerVT, Op1, Op2));
  17485. }
  17486. if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult) && WhichResult != 0)
  17487. return convertFromScalableVector(
  17488. DAG, VT, DAG.getNode(AArch64ISD::ZIP2, DL, ContainerVT, Op1, Op1));
  17489. if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
  17490. unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
  17491. return convertFromScalableVector(
  17492. DAG, VT, DAG.getNode(Opc, DL, ContainerVT, Op1, Op1));
  17493. }
  17494. }
  17495. return SDValue();
  17496. }
  17497. SDValue AArch64TargetLowering::getSVESafeBitCast(EVT VT, SDValue Op,
  17498. SelectionDAG &DAG) const {
  17499. SDLoc DL(Op);
  17500. EVT InVT = Op.getValueType();
  17501. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  17502. (void)TLI;
  17503. assert(VT.isScalableVector() && TLI.isTypeLegal(VT) &&
  17504. InVT.isScalableVector() && TLI.isTypeLegal(InVT) &&
  17505. "Only expect to cast between legal scalable vector types!");
  17506. assert((VT.getVectorElementType() == MVT::i1) ==
  17507. (InVT.getVectorElementType() == MVT::i1) &&
  17508. "Cannot cast between data and predicate scalable vector types!");
  17509. if (InVT == VT)
  17510. return Op;
  17511. if (VT.getVectorElementType() == MVT::i1)
  17512. return DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
  17513. EVT PackedVT = getPackedSVEVectorVT(VT.getVectorElementType());
  17514. EVT PackedInVT = getPackedSVEVectorVT(InVT.getVectorElementType());
  17515. // Pack input if required.
  17516. if (InVT != PackedInVT)
  17517. Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, PackedInVT, Op);
  17518. Op = DAG.getNode(ISD::BITCAST, DL, PackedVT, Op);
  17519. // Unpack result if required.
  17520. if (VT != PackedVT)
  17521. Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
  17522. return Op;
  17523. }
  17524. bool AArch64TargetLowering::isAllActivePredicate(SelectionDAG &DAG,
  17525. SDValue N) const {
  17526. return ::isAllActivePredicate(DAG, N);
  17527. }
  17528. EVT AArch64TargetLowering::getPromotedVTForPredicate(EVT VT) const {
  17529. return ::getPromotedVTForPredicate(VT);
  17530. }
  17531. bool AArch64TargetLowering::SimplifyDemandedBitsForTargetNode(
  17532. SDValue Op, const APInt &OriginalDemandedBits,
  17533. const APInt &OriginalDemandedElts, KnownBits &Known, TargetLoweringOpt &TLO,
  17534. unsigned Depth) const {
  17535. unsigned Opc = Op.getOpcode();
  17536. switch (Opc) {
  17537. case AArch64ISD::VSHL: {
  17538. // Match (VSHL (VLSHR Val X) X)
  17539. SDValue ShiftL = Op;
  17540. SDValue ShiftR = Op->getOperand(0);
  17541. if (ShiftR->getOpcode() != AArch64ISD::VLSHR)
  17542. return false;
  17543. if (!ShiftL.hasOneUse() || !ShiftR.hasOneUse())
  17544. return false;
  17545. unsigned ShiftLBits = ShiftL->getConstantOperandVal(1);
  17546. unsigned ShiftRBits = ShiftR->getConstantOperandVal(1);
  17547. // Other cases can be handled as well, but this is not
  17548. // implemented.
  17549. if (ShiftRBits != ShiftLBits)
  17550. return false;
  17551. unsigned ScalarSize = Op.getScalarValueSizeInBits();
  17552. assert(ScalarSize > ShiftLBits && "Invalid shift imm");
  17553. APInt ZeroBits = APInt::getLowBitsSet(ScalarSize, ShiftLBits);
  17554. APInt UnusedBits = ~OriginalDemandedBits;
  17555. if ((ZeroBits & UnusedBits) != ZeroBits)
  17556. return false;
  17557. // All bits that are zeroed by (VSHL (VLSHR Val X) X) are not
  17558. // used - simplify to just Val.
  17559. return TLO.CombineTo(Op, ShiftR->getOperand(0));
  17560. }
  17561. }
  17562. return TargetLowering::SimplifyDemandedBitsForTargetNode(
  17563. Op, OriginalDemandedBits, OriginalDemandedElts, Known, TLO, Depth);
  17564. }
  17565. bool AArch64TargetLowering::isConstantUnsignedBitfieldExtractLegal(
  17566. unsigned Opc, LLT Ty1, LLT Ty2) const {
  17567. return Ty1 == Ty2 && (Ty1 == LLT::scalar(32) || Ty1 == LLT::scalar(64));
  17568. }