AArch64ISelLowering.cpp 661 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277
  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/VectorUtils.h"
  32. #include "llvm/CodeGen/CallingConvLower.h"
  33. #include "llvm/CodeGen/MachineBasicBlock.h"
  34. #include "llvm/CodeGen/MachineFrameInfo.h"
  35. #include "llvm/CodeGen/MachineFunction.h"
  36. #include "llvm/CodeGen/MachineInstr.h"
  37. #include "llvm/CodeGen/MachineInstrBuilder.h"
  38. #include "llvm/CodeGen/MachineMemOperand.h"
  39. #include "llvm/CodeGen/MachineRegisterInfo.h"
  40. #include "llvm/CodeGen/RuntimeLibcalls.h"
  41. #include "llvm/CodeGen/SelectionDAG.h"
  42. #include "llvm/CodeGen/SelectionDAGNodes.h"
  43. #include "llvm/CodeGen/TargetCallingConv.h"
  44. #include "llvm/CodeGen/TargetInstrInfo.h"
  45. #include "llvm/CodeGen/ValueTypes.h"
  46. #include "llvm/IR/Attributes.h"
  47. #include "llvm/IR/Constants.h"
  48. #include "llvm/IR/DataLayout.h"
  49. #include "llvm/IR/DebugLoc.h"
  50. #include "llvm/IR/DerivedTypes.h"
  51. #include "llvm/IR/Function.h"
  52. #include "llvm/IR/GetElementPtrTypeIterator.h"
  53. #include "llvm/IR/GlobalValue.h"
  54. #include "llvm/IR/IRBuilder.h"
  55. #include "llvm/IR/Instruction.h"
  56. #include "llvm/IR/Instructions.h"
  57. #include "llvm/IR/IntrinsicInst.h"
  58. #include "llvm/IR/Intrinsics.h"
  59. #include "llvm/IR/IntrinsicsAArch64.h"
  60. #include "llvm/IR/Module.h"
  61. #include "llvm/IR/OperandTraits.h"
  62. #include "llvm/IR/PatternMatch.h"
  63. #include "llvm/IR/Type.h"
  64. #include "llvm/IR/Use.h"
  65. #include "llvm/IR/Value.h"
  66. #include "llvm/MC/MCRegisterInfo.h"
  67. #include "llvm/Support/Casting.h"
  68. #include "llvm/Support/CodeGen.h"
  69. #include "llvm/Support/CommandLine.h"
  70. #include "llvm/Support/Compiler.h"
  71. #include "llvm/Support/Debug.h"
  72. #include "llvm/Support/ErrorHandling.h"
  73. #include "llvm/Support/KnownBits.h"
  74. #include "llvm/Support/MachineValueType.h"
  75. #include "llvm/Support/MathExtras.h"
  76. #include "llvm/Support/raw_ostream.h"
  77. #include "llvm/Target/TargetMachine.h"
  78. #include "llvm/Target/TargetOptions.h"
  79. #include <algorithm>
  80. #include <bitset>
  81. #include <cassert>
  82. #include <cctype>
  83. #include <cstdint>
  84. #include <cstdlib>
  85. #include <iterator>
  86. #include <limits>
  87. #include <tuple>
  88. #include <utility>
  89. #include <vector>
  90. using namespace llvm;
  91. using namespace llvm::PatternMatch;
  92. #define DEBUG_TYPE "aarch64-lower"
  93. STATISTIC(NumTailCalls, "Number of tail calls");
  94. STATISTIC(NumShiftInserts, "Number of vector shift inserts");
  95. STATISTIC(NumOptimizedImms, "Number of times immediates were optimized");
  96. // FIXME: The necessary dtprel relocations don't seem to be supported
  97. // well in the GNU bfd and gold linkers at the moment. Therefore, by
  98. // default, for now, fall back to GeneralDynamic code generation.
  99. cl::opt<bool> EnableAArch64ELFLocalDynamicTLSGeneration(
  100. "aarch64-elf-ldtls-generation", cl::Hidden,
  101. cl::desc("Allow AArch64 Local Dynamic TLS code generation"),
  102. cl::init(false));
  103. static cl::opt<bool>
  104. EnableOptimizeLogicalImm("aarch64-enable-logical-imm", cl::Hidden,
  105. cl::desc("Enable AArch64 logical imm instruction "
  106. "optimization"),
  107. cl::init(true));
  108. // Temporary option added for the purpose of testing functionality added
  109. // to DAGCombiner.cpp in D92230. It is expected that this can be removed
  110. // in future when both implementations will be based off MGATHER rather
  111. // than the GLD1 nodes added for the SVE gather load intrinsics.
  112. static cl::opt<bool>
  113. EnableCombineMGatherIntrinsics("aarch64-enable-mgather-combine", cl::Hidden,
  114. cl::desc("Combine extends of AArch64 masked "
  115. "gather intrinsics"),
  116. cl::init(true));
  117. /// Value type used for condition codes.
  118. static const MVT MVT_CC = MVT::i32;
  119. static inline EVT getPackedSVEVectorVT(EVT VT) {
  120. switch (VT.getSimpleVT().SimpleTy) {
  121. default:
  122. llvm_unreachable("unexpected element type for vector");
  123. case MVT::i8:
  124. return MVT::nxv16i8;
  125. case MVT::i16:
  126. return MVT::nxv8i16;
  127. case MVT::i32:
  128. return MVT::nxv4i32;
  129. case MVT::i64:
  130. return MVT::nxv2i64;
  131. case MVT::f16:
  132. return MVT::nxv8f16;
  133. case MVT::f32:
  134. return MVT::nxv4f32;
  135. case MVT::f64:
  136. return MVT::nxv2f64;
  137. case MVT::bf16:
  138. return MVT::nxv8bf16;
  139. }
  140. }
  141. // NOTE: Currently there's only a need to return integer vector types. If this
  142. // changes then just add an extra "type" parameter.
  143. static inline EVT getPackedSVEVectorVT(ElementCount EC) {
  144. switch (EC.getKnownMinValue()) {
  145. default:
  146. llvm_unreachable("unexpected element count for vector");
  147. case 16:
  148. return MVT::nxv16i8;
  149. case 8:
  150. return MVT::nxv8i16;
  151. case 4:
  152. return MVT::nxv4i32;
  153. case 2:
  154. return MVT::nxv2i64;
  155. }
  156. }
  157. static inline EVT getPromotedVTForPredicate(EVT VT) {
  158. assert(VT.isScalableVector() && (VT.getVectorElementType() == MVT::i1) &&
  159. "Expected scalable predicate vector type!");
  160. switch (VT.getVectorMinNumElements()) {
  161. default:
  162. llvm_unreachable("unexpected element count for vector");
  163. case 2:
  164. return MVT::nxv2i64;
  165. case 4:
  166. return MVT::nxv4i32;
  167. case 8:
  168. return MVT::nxv8i16;
  169. case 16:
  170. return MVT::nxv16i8;
  171. }
  172. }
  173. /// Returns true if VT's elements occupy the lowest bit positions of its
  174. /// associated register class without any intervening space.
  175. ///
  176. /// For example, nxv2f16, nxv4f16 and nxv8f16 are legal types that belong to the
  177. /// same register class, but only nxv8f16 can be treated as a packed vector.
  178. static inline bool isPackedVectorType(EVT VT, SelectionDAG &DAG) {
  179. assert(VT.isVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
  180. "Expected legal vector type!");
  181. return VT.isFixedLengthVector() ||
  182. VT.getSizeInBits().getKnownMinSize() == AArch64::SVEBitsPerBlock;
  183. }
  184. // Returns true for ####_MERGE_PASSTHRU opcodes, whose operands have a leading
  185. // predicate and end with a passthru value matching the result type.
  186. static bool isMergePassthruOpcode(unsigned Opc) {
  187. switch (Opc) {
  188. default:
  189. return false;
  190. case AArch64ISD::BITREVERSE_MERGE_PASSTHRU:
  191. case AArch64ISD::BSWAP_MERGE_PASSTHRU:
  192. case AArch64ISD::CTLZ_MERGE_PASSTHRU:
  193. case AArch64ISD::CTPOP_MERGE_PASSTHRU:
  194. case AArch64ISD::DUP_MERGE_PASSTHRU:
  195. case AArch64ISD::ABS_MERGE_PASSTHRU:
  196. case AArch64ISD::NEG_MERGE_PASSTHRU:
  197. case AArch64ISD::FNEG_MERGE_PASSTHRU:
  198. case AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU:
  199. case AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU:
  200. case AArch64ISD::FCEIL_MERGE_PASSTHRU:
  201. case AArch64ISD::FFLOOR_MERGE_PASSTHRU:
  202. case AArch64ISD::FNEARBYINT_MERGE_PASSTHRU:
  203. case AArch64ISD::FRINT_MERGE_PASSTHRU:
  204. case AArch64ISD::FROUND_MERGE_PASSTHRU:
  205. case AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU:
  206. case AArch64ISD::FTRUNC_MERGE_PASSTHRU:
  207. case AArch64ISD::FP_ROUND_MERGE_PASSTHRU:
  208. case AArch64ISD::FP_EXTEND_MERGE_PASSTHRU:
  209. case AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU:
  210. case AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU:
  211. case AArch64ISD::FCVTZU_MERGE_PASSTHRU:
  212. case AArch64ISD::FCVTZS_MERGE_PASSTHRU:
  213. case AArch64ISD::FSQRT_MERGE_PASSTHRU:
  214. case AArch64ISD::FRECPX_MERGE_PASSTHRU:
  215. case AArch64ISD::FABS_MERGE_PASSTHRU:
  216. return true;
  217. }
  218. }
  219. AArch64TargetLowering::AArch64TargetLowering(const TargetMachine &TM,
  220. const AArch64Subtarget &STI)
  221. : TargetLowering(TM), Subtarget(&STI) {
  222. // AArch64 doesn't have comparisons which set GPRs or setcc instructions, so
  223. // we have to make something up. Arbitrarily, choose ZeroOrOne.
  224. setBooleanContents(ZeroOrOneBooleanContent);
  225. // When comparing vectors the result sets the different elements in the
  226. // vector to all-one or all-zero.
  227. setBooleanVectorContents(ZeroOrNegativeOneBooleanContent);
  228. // Set up the register classes.
  229. addRegisterClass(MVT::i32, &AArch64::GPR32allRegClass);
  230. addRegisterClass(MVT::i64, &AArch64::GPR64allRegClass);
  231. if (Subtarget->hasFPARMv8()) {
  232. addRegisterClass(MVT::f16, &AArch64::FPR16RegClass);
  233. addRegisterClass(MVT::bf16, &AArch64::FPR16RegClass);
  234. addRegisterClass(MVT::f32, &AArch64::FPR32RegClass);
  235. addRegisterClass(MVT::f64, &AArch64::FPR64RegClass);
  236. addRegisterClass(MVT::f128, &AArch64::FPR128RegClass);
  237. }
  238. if (Subtarget->hasNEON()) {
  239. addRegisterClass(MVT::v16i8, &AArch64::FPR8RegClass);
  240. addRegisterClass(MVT::v8i16, &AArch64::FPR16RegClass);
  241. // Someone set us up the NEON.
  242. addDRTypeForNEON(MVT::v2f32);
  243. addDRTypeForNEON(MVT::v8i8);
  244. addDRTypeForNEON(MVT::v4i16);
  245. addDRTypeForNEON(MVT::v2i32);
  246. addDRTypeForNEON(MVT::v1i64);
  247. addDRTypeForNEON(MVT::v1f64);
  248. addDRTypeForNEON(MVT::v4f16);
  249. if (Subtarget->hasBF16())
  250. addDRTypeForNEON(MVT::v4bf16);
  251. addQRTypeForNEON(MVT::v4f32);
  252. addQRTypeForNEON(MVT::v2f64);
  253. addQRTypeForNEON(MVT::v16i8);
  254. addQRTypeForNEON(MVT::v8i16);
  255. addQRTypeForNEON(MVT::v4i32);
  256. addQRTypeForNEON(MVT::v2i64);
  257. addQRTypeForNEON(MVT::v8f16);
  258. if (Subtarget->hasBF16())
  259. addQRTypeForNEON(MVT::v8bf16);
  260. }
  261. if (Subtarget->hasSVE()) {
  262. // Add legal sve predicate types
  263. addRegisterClass(MVT::nxv2i1, &AArch64::PPRRegClass);
  264. addRegisterClass(MVT::nxv4i1, &AArch64::PPRRegClass);
  265. addRegisterClass(MVT::nxv8i1, &AArch64::PPRRegClass);
  266. addRegisterClass(MVT::nxv16i1, &AArch64::PPRRegClass);
  267. // Add legal sve data types
  268. addRegisterClass(MVT::nxv16i8, &AArch64::ZPRRegClass);
  269. addRegisterClass(MVT::nxv8i16, &AArch64::ZPRRegClass);
  270. addRegisterClass(MVT::nxv4i32, &AArch64::ZPRRegClass);
  271. addRegisterClass(MVT::nxv2i64, &AArch64::ZPRRegClass);
  272. addRegisterClass(MVT::nxv2f16, &AArch64::ZPRRegClass);
  273. addRegisterClass(MVT::nxv4f16, &AArch64::ZPRRegClass);
  274. addRegisterClass(MVT::nxv8f16, &AArch64::ZPRRegClass);
  275. addRegisterClass(MVT::nxv2f32, &AArch64::ZPRRegClass);
  276. addRegisterClass(MVT::nxv4f32, &AArch64::ZPRRegClass);
  277. addRegisterClass(MVT::nxv2f64, &AArch64::ZPRRegClass);
  278. if (Subtarget->hasBF16()) {
  279. addRegisterClass(MVT::nxv2bf16, &AArch64::ZPRRegClass);
  280. addRegisterClass(MVT::nxv4bf16, &AArch64::ZPRRegClass);
  281. addRegisterClass(MVT::nxv8bf16, &AArch64::ZPRRegClass);
  282. }
  283. if (Subtarget->useSVEForFixedLengthVectors()) {
  284. for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
  285. if (useSVEForFixedLengthVectorVT(VT))
  286. addRegisterClass(VT, &AArch64::ZPRRegClass);
  287. for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
  288. if (useSVEForFixedLengthVectorVT(VT))
  289. addRegisterClass(VT, &AArch64::ZPRRegClass);
  290. }
  291. for (auto VT : { MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64 }) {
  292. setOperationAction(ISD::SADDSAT, VT, Legal);
  293. setOperationAction(ISD::UADDSAT, VT, Legal);
  294. setOperationAction(ISD::SSUBSAT, VT, Legal);
  295. setOperationAction(ISD::USUBSAT, VT, Legal);
  296. setOperationAction(ISD::UREM, VT, Expand);
  297. setOperationAction(ISD::SREM, VT, Expand);
  298. setOperationAction(ISD::SDIVREM, VT, Expand);
  299. setOperationAction(ISD::UDIVREM, VT, Expand);
  300. }
  301. for (auto VT :
  302. { MVT::nxv2i8, MVT::nxv2i16, MVT::nxv2i32, MVT::nxv2i64, MVT::nxv4i8,
  303. MVT::nxv4i16, MVT::nxv4i32, MVT::nxv8i8, MVT::nxv8i16 })
  304. setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Legal);
  305. for (auto VT :
  306. { MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32, MVT::nxv4f32,
  307. MVT::nxv2f64 }) {
  308. setCondCodeAction(ISD::SETO, VT, Expand);
  309. setCondCodeAction(ISD::SETOLT, VT, Expand);
  310. setCondCodeAction(ISD::SETLT, VT, Expand);
  311. setCondCodeAction(ISD::SETOLE, VT, Expand);
  312. setCondCodeAction(ISD::SETLE, VT, Expand);
  313. setCondCodeAction(ISD::SETULT, VT, Expand);
  314. setCondCodeAction(ISD::SETULE, VT, Expand);
  315. setCondCodeAction(ISD::SETUGE, VT, Expand);
  316. setCondCodeAction(ISD::SETUGT, VT, Expand);
  317. setCondCodeAction(ISD::SETUEQ, VT, Expand);
  318. setCondCodeAction(ISD::SETUNE, VT, Expand);
  319. }
  320. }
  321. // Compute derived properties from the register classes
  322. computeRegisterProperties(Subtarget->getRegisterInfo());
  323. // Provide all sorts of operation actions
  324. setOperationAction(ISD::GlobalAddress, MVT::i64, Custom);
  325. setOperationAction(ISD::GlobalTLSAddress, MVT::i64, Custom);
  326. setOperationAction(ISD::SETCC, MVT::i32, Custom);
  327. setOperationAction(ISD::SETCC, MVT::i64, Custom);
  328. setOperationAction(ISD::SETCC, MVT::f16, Custom);
  329. setOperationAction(ISD::SETCC, MVT::f32, Custom);
  330. setOperationAction(ISD::SETCC, MVT::f64, Custom);
  331. setOperationAction(ISD::STRICT_FSETCC, MVT::f16, Custom);
  332. setOperationAction(ISD::STRICT_FSETCC, MVT::f32, Custom);
  333. setOperationAction(ISD::STRICT_FSETCC, MVT::f64, Custom);
  334. setOperationAction(ISD::STRICT_FSETCCS, MVT::f16, Custom);
  335. setOperationAction(ISD::STRICT_FSETCCS, MVT::f32, Custom);
  336. setOperationAction(ISD::STRICT_FSETCCS, MVT::f64, Custom);
  337. setOperationAction(ISD::BITREVERSE, MVT::i32, Legal);
  338. setOperationAction(ISD::BITREVERSE, MVT::i64, Legal);
  339. setOperationAction(ISD::BRCOND, MVT::Other, Expand);
  340. setOperationAction(ISD::BR_CC, MVT::i32, Custom);
  341. setOperationAction(ISD::BR_CC, MVT::i64, Custom);
  342. setOperationAction(ISD::BR_CC, MVT::f16, Custom);
  343. setOperationAction(ISD::BR_CC, MVT::f32, Custom);
  344. setOperationAction(ISD::BR_CC, MVT::f64, Custom);
  345. setOperationAction(ISD::SELECT, MVT::i32, Custom);
  346. setOperationAction(ISD::SELECT, MVT::i64, Custom);
  347. setOperationAction(ISD::SELECT, MVT::f16, Custom);
  348. setOperationAction(ISD::SELECT, MVT::f32, Custom);
  349. setOperationAction(ISD::SELECT, MVT::f64, Custom);
  350. setOperationAction(ISD::SELECT_CC, MVT::i32, Custom);
  351. setOperationAction(ISD::SELECT_CC, MVT::i64, Custom);
  352. setOperationAction(ISD::SELECT_CC, MVT::f16, Custom);
  353. setOperationAction(ISD::SELECT_CC, MVT::f32, Custom);
  354. setOperationAction(ISD::SELECT_CC, MVT::f64, Custom);
  355. setOperationAction(ISD::BR_JT, MVT::Other, Custom);
  356. setOperationAction(ISD::JumpTable, MVT::i64, Custom);
  357. setOperationAction(ISD::SHL_PARTS, MVT::i64, Custom);
  358. setOperationAction(ISD::SRA_PARTS, MVT::i64, Custom);
  359. setOperationAction(ISD::SRL_PARTS, MVT::i64, Custom);
  360. setOperationAction(ISD::FREM, MVT::f32, Expand);
  361. setOperationAction(ISD::FREM, MVT::f64, Expand);
  362. setOperationAction(ISD::FREM, MVT::f80, Expand);
  363. setOperationAction(ISD::BUILD_PAIR, MVT::i64, Expand);
  364. // Custom lowering hooks are needed for XOR
  365. // to fold it into CSINC/CSINV.
  366. setOperationAction(ISD::XOR, MVT::i32, Custom);
  367. setOperationAction(ISD::XOR, MVT::i64, Custom);
  368. // Virtually no operation on f128 is legal, but LLVM can't expand them when
  369. // there's a valid register class, so we need custom operations in most cases.
  370. setOperationAction(ISD::FABS, MVT::f128, Expand);
  371. setOperationAction(ISD::FADD, MVT::f128, LibCall);
  372. setOperationAction(ISD::FCOPYSIGN, MVT::f128, Expand);
  373. setOperationAction(ISD::FCOS, MVT::f128, Expand);
  374. setOperationAction(ISD::FDIV, MVT::f128, LibCall);
  375. setOperationAction(ISD::FMA, MVT::f128, Expand);
  376. setOperationAction(ISD::FMUL, MVT::f128, LibCall);
  377. setOperationAction(ISD::FNEG, MVT::f128, Expand);
  378. setOperationAction(ISD::FPOW, MVT::f128, Expand);
  379. setOperationAction(ISD::FREM, MVT::f128, Expand);
  380. setOperationAction(ISD::FRINT, MVT::f128, Expand);
  381. setOperationAction(ISD::FSIN, MVT::f128, Expand);
  382. setOperationAction(ISD::FSINCOS, MVT::f128, Expand);
  383. setOperationAction(ISD::FSQRT, MVT::f128, Expand);
  384. setOperationAction(ISD::FSUB, MVT::f128, LibCall);
  385. setOperationAction(ISD::FTRUNC, MVT::f128, Expand);
  386. setOperationAction(ISD::SETCC, MVT::f128, Custom);
  387. setOperationAction(ISD::STRICT_FSETCC, MVT::f128, Custom);
  388. setOperationAction(ISD::STRICT_FSETCCS, MVT::f128, Custom);
  389. setOperationAction(ISD::BR_CC, MVT::f128, Custom);
  390. setOperationAction(ISD::SELECT, MVT::f128, Custom);
  391. setOperationAction(ISD::SELECT_CC, MVT::f128, Custom);
  392. setOperationAction(ISD::FP_EXTEND, MVT::f128, Custom);
  393. // Lowering for many of the conversions is actually specified by the non-f128
  394. // type. The LowerXXX function will be trivial when f128 isn't involved.
  395. setOperationAction(ISD::FP_TO_SINT, MVT::i32, Custom);
  396. setOperationAction(ISD::FP_TO_SINT, MVT::i64, Custom);
  397. setOperationAction(ISD::FP_TO_SINT, MVT::i128, Custom);
  398. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i32, Custom);
  399. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i64, Custom);
  400. setOperationAction(ISD::STRICT_FP_TO_SINT, MVT::i128, Custom);
  401. setOperationAction(ISD::FP_TO_UINT, MVT::i32, Custom);
  402. setOperationAction(ISD::FP_TO_UINT, MVT::i64, Custom);
  403. setOperationAction(ISD::FP_TO_UINT, MVT::i128, Custom);
  404. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i32, Custom);
  405. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i64, Custom);
  406. setOperationAction(ISD::STRICT_FP_TO_UINT, MVT::i128, Custom);
  407. setOperationAction(ISD::SINT_TO_FP, MVT::i32, Custom);
  408. setOperationAction(ISD::SINT_TO_FP, MVT::i64, Custom);
  409. setOperationAction(ISD::SINT_TO_FP, MVT::i128, Custom);
  410. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i32, Custom);
  411. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i64, Custom);
  412. setOperationAction(ISD::STRICT_SINT_TO_FP, MVT::i128, Custom);
  413. setOperationAction(ISD::UINT_TO_FP, MVT::i32, Custom);
  414. setOperationAction(ISD::UINT_TO_FP, MVT::i64, Custom);
  415. setOperationAction(ISD::UINT_TO_FP, MVT::i128, Custom);
  416. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i32, Custom);
  417. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i64, Custom);
  418. setOperationAction(ISD::STRICT_UINT_TO_FP, MVT::i128, Custom);
  419. setOperationAction(ISD::FP_ROUND, MVT::f16, Custom);
  420. setOperationAction(ISD::FP_ROUND, MVT::f32, Custom);
  421. setOperationAction(ISD::FP_ROUND, MVT::f64, Custom);
  422. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f16, Custom);
  423. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f32, Custom);
  424. setOperationAction(ISD::STRICT_FP_ROUND, MVT::f64, Custom);
  425. // Variable arguments.
  426. setOperationAction(ISD::VASTART, MVT::Other, Custom);
  427. setOperationAction(ISD::VAARG, MVT::Other, Custom);
  428. setOperationAction(ISD::VACOPY, MVT::Other, Custom);
  429. setOperationAction(ISD::VAEND, MVT::Other, Expand);
  430. // Variable-sized objects.
  431. setOperationAction(ISD::STACKSAVE, MVT::Other, Expand);
  432. setOperationAction(ISD::STACKRESTORE, MVT::Other, Expand);
  433. if (Subtarget->isTargetWindows())
  434. setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Custom);
  435. else
  436. setOperationAction(ISD::DYNAMIC_STACKALLOC, MVT::i64, Expand);
  437. // Constant pool entries
  438. setOperationAction(ISD::ConstantPool, MVT::i64, Custom);
  439. // BlockAddress
  440. setOperationAction(ISD::BlockAddress, MVT::i64, Custom);
  441. // Add/Sub overflow ops with MVT::Glues are lowered to NZCV dependences.
  442. setOperationAction(ISD::ADDC, MVT::i32, Custom);
  443. setOperationAction(ISD::ADDE, MVT::i32, Custom);
  444. setOperationAction(ISD::SUBC, MVT::i32, Custom);
  445. setOperationAction(ISD::SUBE, MVT::i32, Custom);
  446. setOperationAction(ISD::ADDC, MVT::i64, Custom);
  447. setOperationAction(ISD::ADDE, MVT::i64, Custom);
  448. setOperationAction(ISD::SUBC, MVT::i64, Custom);
  449. setOperationAction(ISD::SUBE, MVT::i64, Custom);
  450. // AArch64 lacks both left-rotate and popcount instructions.
  451. setOperationAction(ISD::ROTL, MVT::i32, Expand);
  452. setOperationAction(ISD::ROTL, MVT::i64, Expand);
  453. for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
  454. setOperationAction(ISD::ROTL, VT, Expand);
  455. setOperationAction(ISD::ROTR, VT, Expand);
  456. }
  457. // AArch64 doesn't have i32 MULH{S|U}.
  458. setOperationAction(ISD::MULHU, MVT::i32, Expand);
  459. setOperationAction(ISD::MULHS, MVT::i32, Expand);
  460. // AArch64 doesn't have {U|S}MUL_LOHI.
  461. setOperationAction(ISD::UMUL_LOHI, MVT::i64, Expand);
  462. setOperationAction(ISD::SMUL_LOHI, MVT::i64, Expand);
  463. setOperationAction(ISD::CTPOP, MVT::i32, Custom);
  464. setOperationAction(ISD::CTPOP, MVT::i64, Custom);
  465. setOperationAction(ISD::CTPOP, MVT::i128, Custom);
  466. setOperationAction(ISD::ABS, MVT::i32, Custom);
  467. setOperationAction(ISD::ABS, MVT::i64, Custom);
  468. setOperationAction(ISD::SDIVREM, MVT::i32, Expand);
  469. setOperationAction(ISD::SDIVREM, MVT::i64, Expand);
  470. for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
  471. setOperationAction(ISD::SDIVREM, VT, Expand);
  472. setOperationAction(ISD::UDIVREM, VT, Expand);
  473. }
  474. setOperationAction(ISD::SREM, MVT::i32, Expand);
  475. setOperationAction(ISD::SREM, MVT::i64, Expand);
  476. setOperationAction(ISD::UDIVREM, MVT::i32, Expand);
  477. setOperationAction(ISD::UDIVREM, MVT::i64, Expand);
  478. setOperationAction(ISD::UREM, MVT::i32, Expand);
  479. setOperationAction(ISD::UREM, MVT::i64, Expand);
  480. // Custom lower Add/Sub/Mul with overflow.
  481. setOperationAction(ISD::SADDO, MVT::i32, Custom);
  482. setOperationAction(ISD::SADDO, MVT::i64, Custom);
  483. setOperationAction(ISD::UADDO, MVT::i32, Custom);
  484. setOperationAction(ISD::UADDO, MVT::i64, Custom);
  485. setOperationAction(ISD::SSUBO, MVT::i32, Custom);
  486. setOperationAction(ISD::SSUBO, MVT::i64, Custom);
  487. setOperationAction(ISD::USUBO, MVT::i32, Custom);
  488. setOperationAction(ISD::USUBO, MVT::i64, Custom);
  489. setOperationAction(ISD::SMULO, MVT::i32, Custom);
  490. setOperationAction(ISD::SMULO, MVT::i64, Custom);
  491. setOperationAction(ISD::UMULO, MVT::i32, Custom);
  492. setOperationAction(ISD::UMULO, MVT::i64, Custom);
  493. setOperationAction(ISD::FSIN, MVT::f32, Expand);
  494. setOperationAction(ISD::FSIN, MVT::f64, Expand);
  495. setOperationAction(ISD::FCOS, MVT::f32, Expand);
  496. setOperationAction(ISD::FCOS, MVT::f64, Expand);
  497. setOperationAction(ISD::FPOW, MVT::f32, Expand);
  498. setOperationAction(ISD::FPOW, MVT::f64, Expand);
  499. setOperationAction(ISD::FCOPYSIGN, MVT::f64, Custom);
  500. setOperationAction(ISD::FCOPYSIGN, MVT::f32, Custom);
  501. if (Subtarget->hasFullFP16())
  502. setOperationAction(ISD::FCOPYSIGN, MVT::f16, Custom);
  503. else
  504. setOperationAction(ISD::FCOPYSIGN, MVT::f16, Promote);
  505. setOperationAction(ISD::FREM, MVT::f16, Promote);
  506. setOperationAction(ISD::FREM, MVT::v4f16, Expand);
  507. setOperationAction(ISD::FREM, MVT::v8f16, Expand);
  508. setOperationAction(ISD::FPOW, MVT::f16, Promote);
  509. setOperationAction(ISD::FPOW, MVT::v4f16, Expand);
  510. setOperationAction(ISD::FPOW, MVT::v8f16, Expand);
  511. setOperationAction(ISD::FPOWI, MVT::f16, Promote);
  512. setOperationAction(ISD::FPOWI, MVT::v4f16, Expand);
  513. setOperationAction(ISD::FPOWI, MVT::v8f16, Expand);
  514. setOperationAction(ISD::FCOS, MVT::f16, Promote);
  515. setOperationAction(ISD::FCOS, MVT::v4f16, Expand);
  516. setOperationAction(ISD::FCOS, MVT::v8f16, Expand);
  517. setOperationAction(ISD::FSIN, MVT::f16, Promote);
  518. setOperationAction(ISD::FSIN, MVT::v4f16, Expand);
  519. setOperationAction(ISD::FSIN, MVT::v8f16, Expand);
  520. setOperationAction(ISD::FSINCOS, MVT::f16, Promote);
  521. setOperationAction(ISD::FSINCOS, MVT::v4f16, Expand);
  522. setOperationAction(ISD::FSINCOS, MVT::v8f16, Expand);
  523. setOperationAction(ISD::FEXP, MVT::f16, Promote);
  524. setOperationAction(ISD::FEXP, MVT::v4f16, Expand);
  525. setOperationAction(ISD::FEXP, MVT::v8f16, Expand);
  526. setOperationAction(ISD::FEXP2, MVT::f16, Promote);
  527. setOperationAction(ISD::FEXP2, MVT::v4f16, Expand);
  528. setOperationAction(ISD::FEXP2, MVT::v8f16, Expand);
  529. setOperationAction(ISD::FLOG, MVT::f16, Promote);
  530. setOperationAction(ISD::FLOG, MVT::v4f16, Expand);
  531. setOperationAction(ISD::FLOG, MVT::v8f16, Expand);
  532. setOperationAction(ISD::FLOG2, MVT::f16, Promote);
  533. setOperationAction(ISD::FLOG2, MVT::v4f16, Expand);
  534. setOperationAction(ISD::FLOG2, MVT::v8f16, Expand);
  535. setOperationAction(ISD::FLOG10, MVT::f16, Promote);
  536. setOperationAction(ISD::FLOG10, MVT::v4f16, Expand);
  537. setOperationAction(ISD::FLOG10, MVT::v8f16, Expand);
  538. if (!Subtarget->hasFullFP16()) {
  539. setOperationAction(ISD::SELECT, MVT::f16, Promote);
  540. setOperationAction(ISD::SELECT_CC, MVT::f16, Promote);
  541. setOperationAction(ISD::SETCC, MVT::f16, Promote);
  542. setOperationAction(ISD::BR_CC, MVT::f16, Promote);
  543. setOperationAction(ISD::FADD, MVT::f16, Promote);
  544. setOperationAction(ISD::FSUB, MVT::f16, Promote);
  545. setOperationAction(ISD::FMUL, MVT::f16, Promote);
  546. setOperationAction(ISD::FDIV, MVT::f16, Promote);
  547. setOperationAction(ISD::FMA, MVT::f16, Promote);
  548. setOperationAction(ISD::FNEG, MVT::f16, Promote);
  549. setOperationAction(ISD::FABS, MVT::f16, Promote);
  550. setOperationAction(ISD::FCEIL, MVT::f16, Promote);
  551. setOperationAction(ISD::FSQRT, MVT::f16, Promote);
  552. setOperationAction(ISD::FFLOOR, MVT::f16, Promote);
  553. setOperationAction(ISD::FNEARBYINT, MVT::f16, Promote);
  554. setOperationAction(ISD::FRINT, MVT::f16, Promote);
  555. setOperationAction(ISD::FROUND, MVT::f16, Promote);
  556. setOperationAction(ISD::FTRUNC, MVT::f16, Promote);
  557. setOperationAction(ISD::FMINNUM, MVT::f16, Promote);
  558. setOperationAction(ISD::FMAXNUM, MVT::f16, Promote);
  559. setOperationAction(ISD::FMINIMUM, MVT::f16, Promote);
  560. setOperationAction(ISD::FMAXIMUM, MVT::f16, Promote);
  561. // promote v4f16 to v4f32 when that is known to be safe.
  562. setOperationAction(ISD::FADD, MVT::v4f16, Promote);
  563. setOperationAction(ISD::FSUB, MVT::v4f16, Promote);
  564. setOperationAction(ISD::FMUL, MVT::v4f16, Promote);
  565. setOperationAction(ISD::FDIV, MVT::v4f16, Promote);
  566. AddPromotedToType(ISD::FADD, MVT::v4f16, MVT::v4f32);
  567. AddPromotedToType(ISD::FSUB, MVT::v4f16, MVT::v4f32);
  568. AddPromotedToType(ISD::FMUL, MVT::v4f16, MVT::v4f32);
  569. AddPromotedToType(ISD::FDIV, MVT::v4f16, MVT::v4f32);
  570. setOperationAction(ISD::FABS, MVT::v4f16, Expand);
  571. setOperationAction(ISD::FNEG, MVT::v4f16, Expand);
  572. setOperationAction(ISD::FROUND, MVT::v4f16, Expand);
  573. setOperationAction(ISD::FMA, MVT::v4f16, Expand);
  574. setOperationAction(ISD::SETCC, MVT::v4f16, Expand);
  575. setOperationAction(ISD::BR_CC, MVT::v4f16, Expand);
  576. setOperationAction(ISD::SELECT, MVT::v4f16, Expand);
  577. setOperationAction(ISD::SELECT_CC, MVT::v4f16, Expand);
  578. setOperationAction(ISD::FTRUNC, MVT::v4f16, Expand);
  579. setOperationAction(ISD::FCOPYSIGN, MVT::v4f16, Expand);
  580. setOperationAction(ISD::FFLOOR, MVT::v4f16, Expand);
  581. setOperationAction(ISD::FCEIL, MVT::v4f16, Expand);
  582. setOperationAction(ISD::FRINT, MVT::v4f16, Expand);
  583. setOperationAction(ISD::FNEARBYINT, MVT::v4f16, Expand);
  584. setOperationAction(ISD::FSQRT, MVT::v4f16, Expand);
  585. setOperationAction(ISD::FABS, MVT::v8f16, Expand);
  586. setOperationAction(ISD::FADD, MVT::v8f16, Expand);
  587. setOperationAction(ISD::FCEIL, MVT::v8f16, Expand);
  588. setOperationAction(ISD::FCOPYSIGN, MVT::v8f16, Expand);
  589. setOperationAction(ISD::FDIV, MVT::v8f16, Expand);
  590. setOperationAction(ISD::FFLOOR, MVT::v8f16, Expand);
  591. setOperationAction(ISD::FMA, MVT::v8f16, Expand);
  592. setOperationAction(ISD::FMUL, MVT::v8f16, Expand);
  593. setOperationAction(ISD::FNEARBYINT, MVT::v8f16, Expand);
  594. setOperationAction(ISD::FNEG, MVT::v8f16, Expand);
  595. setOperationAction(ISD::FROUND, MVT::v8f16, Expand);
  596. setOperationAction(ISD::FRINT, MVT::v8f16, Expand);
  597. setOperationAction(ISD::FSQRT, MVT::v8f16, Expand);
  598. setOperationAction(ISD::FSUB, MVT::v8f16, Expand);
  599. setOperationAction(ISD::FTRUNC, MVT::v8f16, Expand);
  600. setOperationAction(ISD::SETCC, MVT::v8f16, Expand);
  601. setOperationAction(ISD::BR_CC, MVT::v8f16, Expand);
  602. setOperationAction(ISD::SELECT, MVT::v8f16, Expand);
  603. setOperationAction(ISD::SELECT_CC, MVT::v8f16, Expand);
  604. setOperationAction(ISD::FP_EXTEND, MVT::v8f16, Expand);
  605. }
  606. // AArch64 has implementations of a lot of rounding-like FP operations.
  607. for (MVT Ty : {MVT::f32, MVT::f64}) {
  608. setOperationAction(ISD::FFLOOR, Ty, Legal);
  609. setOperationAction(ISD::FNEARBYINT, Ty, Legal);
  610. setOperationAction(ISD::FCEIL, Ty, Legal);
  611. setOperationAction(ISD::FRINT, Ty, Legal);
  612. setOperationAction(ISD::FTRUNC, Ty, Legal);
  613. setOperationAction(ISD::FROUND, Ty, Legal);
  614. setOperationAction(ISD::FMINNUM, Ty, Legal);
  615. setOperationAction(ISD::FMAXNUM, Ty, Legal);
  616. setOperationAction(ISD::FMINIMUM, Ty, Legal);
  617. setOperationAction(ISD::FMAXIMUM, Ty, Legal);
  618. setOperationAction(ISD::LROUND, Ty, Legal);
  619. setOperationAction(ISD::LLROUND, Ty, Legal);
  620. setOperationAction(ISD::LRINT, Ty, Legal);
  621. setOperationAction(ISD::LLRINT, Ty, Legal);
  622. }
  623. if (Subtarget->hasFullFP16()) {
  624. setOperationAction(ISD::FNEARBYINT, MVT::f16, Legal);
  625. setOperationAction(ISD::FFLOOR, MVT::f16, Legal);
  626. setOperationAction(ISD::FCEIL, MVT::f16, Legal);
  627. setOperationAction(ISD::FRINT, MVT::f16, Legal);
  628. setOperationAction(ISD::FTRUNC, MVT::f16, Legal);
  629. setOperationAction(ISD::FROUND, MVT::f16, Legal);
  630. setOperationAction(ISD::FMINNUM, MVT::f16, Legal);
  631. setOperationAction(ISD::FMAXNUM, MVT::f16, Legal);
  632. setOperationAction(ISD::FMINIMUM, MVT::f16, Legal);
  633. setOperationAction(ISD::FMAXIMUM, MVT::f16, Legal);
  634. }
  635. setOperationAction(ISD::PREFETCH, MVT::Other, Custom);
  636. setOperationAction(ISD::FLT_ROUNDS_, MVT::i32, Custom);
  637. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, Custom);
  638. setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i32, Custom);
  639. setOperationAction(ISD::ATOMIC_LOAD_SUB, MVT::i64, Custom);
  640. setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i32, Custom);
  641. setOperationAction(ISD::ATOMIC_LOAD_AND, MVT::i64, Custom);
  642. // Generate outline atomics library calls only if LSE was not specified for
  643. // subtarget
  644. if (Subtarget->outlineAtomics() && !Subtarget->hasLSE()) {
  645. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i8, LibCall);
  646. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i16, LibCall);
  647. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i32, LibCall);
  648. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i64, LibCall);
  649. setOperationAction(ISD::ATOMIC_CMP_SWAP, MVT::i128, LibCall);
  650. setOperationAction(ISD::ATOMIC_SWAP, MVT::i8, LibCall);
  651. setOperationAction(ISD::ATOMIC_SWAP, MVT::i16, LibCall);
  652. setOperationAction(ISD::ATOMIC_SWAP, MVT::i32, LibCall);
  653. setOperationAction(ISD::ATOMIC_SWAP, MVT::i64, LibCall);
  654. setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i8, LibCall);
  655. setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i16, LibCall);
  656. setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i32, LibCall);
  657. setOperationAction(ISD::ATOMIC_LOAD_ADD, MVT::i64, LibCall);
  658. setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i8, LibCall);
  659. setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i16, LibCall);
  660. setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i32, LibCall);
  661. setOperationAction(ISD::ATOMIC_LOAD_OR, MVT::i64, LibCall);
  662. setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i8, LibCall);
  663. setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i16, LibCall);
  664. setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i32, LibCall);
  665. setOperationAction(ISD::ATOMIC_LOAD_CLR, MVT::i64, LibCall);
  666. setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i8, LibCall);
  667. setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i16, LibCall);
  668. setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i32, LibCall);
  669. setOperationAction(ISD::ATOMIC_LOAD_XOR, MVT::i64, LibCall);
  670. #define LCALLNAMES(A, B, N) \
  671. setLibcallName(A##N##_RELAX, #B #N "_relax"); \
  672. setLibcallName(A##N##_ACQ, #B #N "_acq"); \
  673. setLibcallName(A##N##_REL, #B #N "_rel"); \
  674. setLibcallName(A##N##_ACQ_REL, #B #N "_acq_rel");
  675. #define LCALLNAME4(A, B) \
  676. LCALLNAMES(A, B, 1) \
  677. LCALLNAMES(A, B, 2) LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8)
  678. #define LCALLNAME5(A, B) \
  679. LCALLNAMES(A, B, 1) \
  680. LCALLNAMES(A, B, 2) \
  681. LCALLNAMES(A, B, 4) LCALLNAMES(A, B, 8) LCALLNAMES(A, B, 16)
  682. LCALLNAME5(RTLIB::OUTLINE_ATOMIC_CAS, __aarch64_cas)
  683. LCALLNAME4(RTLIB::OUTLINE_ATOMIC_SWP, __aarch64_swp)
  684. LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDADD, __aarch64_ldadd)
  685. LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDSET, __aarch64_ldset)
  686. LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDCLR, __aarch64_ldclr)
  687. LCALLNAME4(RTLIB::OUTLINE_ATOMIC_LDEOR, __aarch64_ldeor)
  688. #undef LCALLNAMES
  689. #undef LCALLNAME4
  690. #undef LCALLNAME5
  691. }
  692. // 128-bit loads and stores can be done without expanding
  693. setOperationAction(ISD::LOAD, MVT::i128, Custom);
  694. setOperationAction(ISD::STORE, MVT::i128, Custom);
  695. // 256 bit non-temporal stores can be lowered to STNP. Do this as part of the
  696. // custom lowering, as there are no un-paired non-temporal stores and
  697. // legalization will break up 256 bit inputs.
  698. setOperationAction(ISD::STORE, MVT::v32i8, Custom);
  699. setOperationAction(ISD::STORE, MVT::v16i16, Custom);
  700. setOperationAction(ISD::STORE, MVT::v16f16, Custom);
  701. setOperationAction(ISD::STORE, MVT::v8i32, Custom);
  702. setOperationAction(ISD::STORE, MVT::v8f32, Custom);
  703. setOperationAction(ISD::STORE, MVT::v4f64, Custom);
  704. setOperationAction(ISD::STORE, MVT::v4i64, Custom);
  705. // Lower READCYCLECOUNTER using an mrs from PMCCNTR_EL0.
  706. // This requires the Performance Monitors extension.
  707. if (Subtarget->hasPerfMon())
  708. setOperationAction(ISD::READCYCLECOUNTER, MVT::i64, Legal);
  709. if (getLibcallName(RTLIB::SINCOS_STRET_F32) != nullptr &&
  710. getLibcallName(RTLIB::SINCOS_STRET_F64) != nullptr) {
  711. // Issue __sincos_stret if available.
  712. setOperationAction(ISD::FSINCOS, MVT::f64, Custom);
  713. setOperationAction(ISD::FSINCOS, MVT::f32, Custom);
  714. } else {
  715. setOperationAction(ISD::FSINCOS, MVT::f64, Expand);
  716. setOperationAction(ISD::FSINCOS, MVT::f32, Expand);
  717. }
  718. if (Subtarget->getTargetTriple().isOSMSVCRT()) {
  719. // MSVCRT doesn't have powi; fall back to pow
  720. setLibcallName(RTLIB::POWI_F32, nullptr);
  721. setLibcallName(RTLIB::POWI_F64, nullptr);
  722. }
  723. // Make floating-point constants legal for the large code model, so they don't
  724. // become loads from the constant pool.
  725. if (Subtarget->isTargetMachO() && TM.getCodeModel() == CodeModel::Large) {
  726. setOperationAction(ISD::ConstantFP, MVT::f32, Legal);
  727. setOperationAction(ISD::ConstantFP, MVT::f64, Legal);
  728. }
  729. // AArch64 does not have floating-point extending loads, i1 sign-extending
  730. // load, floating-point truncating stores, or v2i32->v2i16 truncating store.
  731. for (MVT VT : MVT::fp_valuetypes()) {
  732. setLoadExtAction(ISD::EXTLOAD, VT, MVT::f16, Expand);
  733. setLoadExtAction(ISD::EXTLOAD, VT, MVT::f32, Expand);
  734. setLoadExtAction(ISD::EXTLOAD, VT, MVT::f64, Expand);
  735. setLoadExtAction(ISD::EXTLOAD, VT, MVT::f80, Expand);
  736. }
  737. for (MVT VT : MVT::integer_valuetypes())
  738. setLoadExtAction(ISD::SEXTLOAD, VT, MVT::i1, Expand);
  739. setTruncStoreAction(MVT::f32, MVT::f16, Expand);
  740. setTruncStoreAction(MVT::f64, MVT::f32, Expand);
  741. setTruncStoreAction(MVT::f64, MVT::f16, Expand);
  742. setTruncStoreAction(MVT::f128, MVT::f80, Expand);
  743. setTruncStoreAction(MVT::f128, MVT::f64, Expand);
  744. setTruncStoreAction(MVT::f128, MVT::f32, Expand);
  745. setTruncStoreAction(MVT::f128, MVT::f16, Expand);
  746. setOperationAction(ISD::BITCAST, MVT::i16, Custom);
  747. setOperationAction(ISD::BITCAST, MVT::f16, Custom);
  748. setOperationAction(ISD::BITCAST, MVT::bf16, Custom);
  749. // Indexed loads and stores are supported.
  750. for (unsigned im = (unsigned)ISD::PRE_INC;
  751. im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
  752. setIndexedLoadAction(im, MVT::i8, Legal);
  753. setIndexedLoadAction(im, MVT::i16, Legal);
  754. setIndexedLoadAction(im, MVT::i32, Legal);
  755. setIndexedLoadAction(im, MVT::i64, Legal);
  756. setIndexedLoadAction(im, MVT::f64, Legal);
  757. setIndexedLoadAction(im, MVT::f32, Legal);
  758. setIndexedLoadAction(im, MVT::f16, Legal);
  759. setIndexedLoadAction(im, MVT::bf16, Legal);
  760. setIndexedStoreAction(im, MVT::i8, Legal);
  761. setIndexedStoreAction(im, MVT::i16, Legal);
  762. setIndexedStoreAction(im, MVT::i32, Legal);
  763. setIndexedStoreAction(im, MVT::i64, Legal);
  764. setIndexedStoreAction(im, MVT::f64, Legal);
  765. setIndexedStoreAction(im, MVT::f32, Legal);
  766. setIndexedStoreAction(im, MVT::f16, Legal);
  767. setIndexedStoreAction(im, MVT::bf16, Legal);
  768. }
  769. // Trap.
  770. setOperationAction(ISD::TRAP, MVT::Other, Legal);
  771. setOperationAction(ISD::DEBUGTRAP, MVT::Other, Legal);
  772. setOperationAction(ISD::UBSANTRAP, MVT::Other, Legal);
  773. // We combine OR nodes for bitfield operations.
  774. setTargetDAGCombine(ISD::OR);
  775. // Try to create BICs for vector ANDs.
  776. setTargetDAGCombine(ISD::AND);
  777. // Vector add and sub nodes may conceal a high-half opportunity.
  778. // Also, try to fold ADD into CSINC/CSINV..
  779. setTargetDAGCombine(ISD::ADD);
  780. setTargetDAGCombine(ISD::ABS);
  781. setTargetDAGCombine(ISD::SUB);
  782. setTargetDAGCombine(ISD::SRL);
  783. setTargetDAGCombine(ISD::XOR);
  784. setTargetDAGCombine(ISD::SINT_TO_FP);
  785. setTargetDAGCombine(ISD::UINT_TO_FP);
  786. setTargetDAGCombine(ISD::FP_TO_SINT);
  787. setTargetDAGCombine(ISD::FP_TO_UINT);
  788. setTargetDAGCombine(ISD::FDIV);
  789. setTargetDAGCombine(ISD::INTRINSIC_WO_CHAIN);
  790. setTargetDAGCombine(ISD::ANY_EXTEND);
  791. setTargetDAGCombine(ISD::ZERO_EXTEND);
  792. setTargetDAGCombine(ISD::SIGN_EXTEND);
  793. setTargetDAGCombine(ISD::SIGN_EXTEND_INREG);
  794. setTargetDAGCombine(ISD::TRUNCATE);
  795. setTargetDAGCombine(ISD::CONCAT_VECTORS);
  796. setTargetDAGCombine(ISD::STORE);
  797. if (Subtarget->supportsAddressTopByteIgnored())
  798. setTargetDAGCombine(ISD::LOAD);
  799. setTargetDAGCombine(ISD::MGATHER);
  800. setTargetDAGCombine(ISD::MSCATTER);
  801. setTargetDAGCombine(ISD::MUL);
  802. setTargetDAGCombine(ISD::SELECT);
  803. setTargetDAGCombine(ISD::VSELECT);
  804. setTargetDAGCombine(ISD::INTRINSIC_VOID);
  805. setTargetDAGCombine(ISD::INTRINSIC_W_CHAIN);
  806. setTargetDAGCombine(ISD::INSERT_VECTOR_ELT);
  807. setTargetDAGCombine(ISD::EXTRACT_VECTOR_ELT);
  808. setTargetDAGCombine(ISD::VECREDUCE_ADD);
  809. setTargetDAGCombine(ISD::GlobalAddress);
  810. // In case of strict alignment, avoid an excessive number of byte wide stores.
  811. MaxStoresPerMemsetOptSize = 8;
  812. MaxStoresPerMemset = Subtarget->requiresStrictAlign()
  813. ? MaxStoresPerMemsetOptSize : 32;
  814. MaxGluedStoresPerMemcpy = 4;
  815. MaxStoresPerMemcpyOptSize = 4;
  816. MaxStoresPerMemcpy = Subtarget->requiresStrictAlign()
  817. ? MaxStoresPerMemcpyOptSize : 16;
  818. MaxStoresPerMemmoveOptSize = MaxStoresPerMemmove = 4;
  819. MaxLoadsPerMemcmpOptSize = 4;
  820. MaxLoadsPerMemcmp = Subtarget->requiresStrictAlign()
  821. ? MaxLoadsPerMemcmpOptSize : 8;
  822. setStackPointerRegisterToSaveRestore(AArch64::SP);
  823. setSchedulingPreference(Sched::Hybrid);
  824. EnableExtLdPromotion = true;
  825. // Set required alignment.
  826. setMinFunctionAlignment(Align(4));
  827. // Set preferred alignments.
  828. setPrefLoopAlignment(Align(1ULL << STI.getPrefLoopLogAlignment()));
  829. setPrefFunctionAlignment(Align(1ULL << STI.getPrefFunctionLogAlignment()));
  830. // Only change the limit for entries in a jump table if specified by
  831. // the sub target, but not at the command line.
  832. unsigned MaxJT = STI.getMaximumJumpTableSize();
  833. if (MaxJT && getMaximumJumpTableSize() == UINT_MAX)
  834. setMaximumJumpTableSize(MaxJT);
  835. setHasExtractBitsInsn(true);
  836. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::Other, Custom);
  837. if (Subtarget->hasNEON()) {
  838. // FIXME: v1f64 shouldn't be legal if we can avoid it, because it leads to
  839. // silliness like this:
  840. setOperationAction(ISD::FABS, MVT::v1f64, Expand);
  841. setOperationAction(ISD::FADD, MVT::v1f64, Expand);
  842. setOperationAction(ISD::FCEIL, MVT::v1f64, Expand);
  843. setOperationAction(ISD::FCOPYSIGN, MVT::v1f64, Expand);
  844. setOperationAction(ISD::FCOS, MVT::v1f64, Expand);
  845. setOperationAction(ISD::FDIV, MVT::v1f64, Expand);
  846. setOperationAction(ISD::FFLOOR, MVT::v1f64, Expand);
  847. setOperationAction(ISD::FMA, MVT::v1f64, Expand);
  848. setOperationAction(ISD::FMUL, MVT::v1f64, Expand);
  849. setOperationAction(ISD::FNEARBYINT, MVT::v1f64, Expand);
  850. setOperationAction(ISD::FNEG, MVT::v1f64, Expand);
  851. setOperationAction(ISD::FPOW, MVT::v1f64, Expand);
  852. setOperationAction(ISD::FREM, MVT::v1f64, Expand);
  853. setOperationAction(ISD::FROUND, MVT::v1f64, Expand);
  854. setOperationAction(ISD::FRINT, MVT::v1f64, Expand);
  855. setOperationAction(ISD::FSIN, MVT::v1f64, Expand);
  856. setOperationAction(ISD::FSINCOS, MVT::v1f64, Expand);
  857. setOperationAction(ISD::FSQRT, MVT::v1f64, Expand);
  858. setOperationAction(ISD::FSUB, MVT::v1f64, Expand);
  859. setOperationAction(ISD::FTRUNC, MVT::v1f64, Expand);
  860. setOperationAction(ISD::SETCC, MVT::v1f64, Expand);
  861. setOperationAction(ISD::BR_CC, MVT::v1f64, Expand);
  862. setOperationAction(ISD::SELECT, MVT::v1f64, Expand);
  863. setOperationAction(ISD::SELECT_CC, MVT::v1f64, Expand);
  864. setOperationAction(ISD::FP_EXTEND, MVT::v1f64, Expand);
  865. setOperationAction(ISD::FP_TO_SINT, MVT::v1i64, Expand);
  866. setOperationAction(ISD::FP_TO_UINT, MVT::v1i64, Expand);
  867. setOperationAction(ISD::SINT_TO_FP, MVT::v1i64, Expand);
  868. setOperationAction(ISD::UINT_TO_FP, MVT::v1i64, Expand);
  869. setOperationAction(ISD::FP_ROUND, MVT::v1f64, Expand);
  870. setOperationAction(ISD::MUL, MVT::v1i64, Expand);
  871. // AArch64 doesn't have a direct vector ->f32 conversion instructions for
  872. // elements smaller than i32, so promote the input to i32 first.
  873. setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i8, MVT::v4i32);
  874. setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i8, MVT::v4i32);
  875. // i8 vector elements also need promotion to i32 for v8i8
  876. setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i8, MVT::v8i32);
  877. setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i8, MVT::v8i32);
  878. // Similarly, there is no direct i32 -> f64 vector conversion instruction.
  879. setOperationAction(ISD::SINT_TO_FP, MVT::v2i32, Custom);
  880. setOperationAction(ISD::UINT_TO_FP, MVT::v2i32, Custom);
  881. setOperationAction(ISD::SINT_TO_FP, MVT::v2i64, Custom);
  882. setOperationAction(ISD::UINT_TO_FP, MVT::v2i64, Custom);
  883. // Or, direct i32 -> f16 vector conversion. Set it so custom, so the
  884. // conversion happens in two steps: v4i32 -> v4f32 -> v4f16
  885. setOperationAction(ISD::SINT_TO_FP, MVT::v4i32, Custom);
  886. setOperationAction(ISD::UINT_TO_FP, MVT::v4i32, Custom);
  887. if (Subtarget->hasFullFP16()) {
  888. setOperationAction(ISD::SINT_TO_FP, MVT::v4i16, Custom);
  889. setOperationAction(ISD::UINT_TO_FP, MVT::v4i16, Custom);
  890. setOperationAction(ISD::SINT_TO_FP, MVT::v8i16, Custom);
  891. setOperationAction(ISD::UINT_TO_FP, MVT::v8i16, Custom);
  892. } else {
  893. // when AArch64 doesn't have fullfp16 support, promote the input
  894. // to i32 first.
  895. setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v4i16, MVT::v4i32);
  896. setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v4i16, MVT::v4i32);
  897. setOperationPromotedToType(ISD::SINT_TO_FP, MVT::v8i16, MVT::v8i32);
  898. setOperationPromotedToType(ISD::UINT_TO_FP, MVT::v8i16, MVT::v8i32);
  899. }
  900. setOperationAction(ISD::CTLZ, MVT::v1i64, Expand);
  901. setOperationAction(ISD::CTLZ, MVT::v2i64, Expand);
  902. // AArch64 doesn't have MUL.2d:
  903. setOperationAction(ISD::MUL, MVT::v2i64, Expand);
  904. // Custom handling for some quad-vector types to detect MULL.
  905. setOperationAction(ISD::MUL, MVT::v8i16, Custom);
  906. setOperationAction(ISD::MUL, MVT::v4i32, Custom);
  907. setOperationAction(ISD::MUL, MVT::v2i64, Custom);
  908. // Saturates
  909. for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
  910. MVT::v16i8, MVT::v8i16, MVT::v4i32, MVT::v2i64 }) {
  911. setOperationAction(ISD::SADDSAT, VT, Legal);
  912. setOperationAction(ISD::UADDSAT, VT, Legal);
  913. setOperationAction(ISD::SSUBSAT, VT, Legal);
  914. setOperationAction(ISD::USUBSAT, VT, Legal);
  915. }
  916. // Vector reductions
  917. for (MVT VT : { MVT::v4f16, MVT::v2f32,
  918. MVT::v8f16, MVT::v4f32, MVT::v2f64 }) {
  919. if (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()) {
  920. setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
  921. setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
  922. setOperationAction(ISD::VECREDUCE_FADD, VT, Legal);
  923. }
  924. }
  925. for (MVT VT : { MVT::v8i8, MVT::v4i16, MVT::v2i32,
  926. MVT::v16i8, MVT::v8i16, MVT::v4i32 }) {
  927. setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
  928. setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
  929. setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
  930. setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
  931. setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
  932. }
  933. setOperationAction(ISD::VECREDUCE_ADD, MVT::v2i64, Custom);
  934. setOperationAction(ISD::ANY_EXTEND, MVT::v4i32, Legal);
  935. setTruncStoreAction(MVT::v2i32, MVT::v2i16, Expand);
  936. // Likewise, narrowing and extending vector loads/stores aren't handled
  937. // directly.
  938. for (MVT VT : MVT::fixedlen_vector_valuetypes()) {
  939. setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Expand);
  940. if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32) {
  941. setOperationAction(ISD::MULHS, VT, Legal);
  942. setOperationAction(ISD::MULHU, VT, Legal);
  943. } else {
  944. setOperationAction(ISD::MULHS, VT, Expand);
  945. setOperationAction(ISD::MULHU, VT, Expand);
  946. }
  947. setOperationAction(ISD::SMUL_LOHI, VT, Expand);
  948. setOperationAction(ISD::UMUL_LOHI, VT, Expand);
  949. setOperationAction(ISD::BSWAP, VT, Expand);
  950. setOperationAction(ISD::CTTZ, VT, Expand);
  951. for (MVT InnerVT : MVT::fixedlen_vector_valuetypes()) {
  952. setTruncStoreAction(VT, InnerVT, Expand);
  953. setLoadExtAction(ISD::SEXTLOAD, VT, InnerVT, Expand);
  954. setLoadExtAction(ISD::ZEXTLOAD, VT, InnerVT, Expand);
  955. setLoadExtAction(ISD::EXTLOAD, VT, InnerVT, Expand);
  956. }
  957. }
  958. // AArch64 has implementations of a lot of rounding-like FP operations.
  959. for (MVT Ty : {MVT::v2f32, MVT::v4f32, MVT::v2f64}) {
  960. setOperationAction(ISD::FFLOOR, Ty, Legal);
  961. setOperationAction(ISD::FNEARBYINT, Ty, Legal);
  962. setOperationAction(ISD::FCEIL, Ty, Legal);
  963. setOperationAction(ISD::FRINT, Ty, Legal);
  964. setOperationAction(ISD::FTRUNC, Ty, Legal);
  965. setOperationAction(ISD::FROUND, Ty, Legal);
  966. }
  967. if (Subtarget->hasFullFP16()) {
  968. for (MVT Ty : {MVT::v4f16, MVT::v8f16}) {
  969. setOperationAction(ISD::FFLOOR, Ty, Legal);
  970. setOperationAction(ISD::FNEARBYINT, Ty, Legal);
  971. setOperationAction(ISD::FCEIL, Ty, Legal);
  972. setOperationAction(ISD::FRINT, Ty, Legal);
  973. setOperationAction(ISD::FTRUNC, Ty, Legal);
  974. setOperationAction(ISD::FROUND, Ty, Legal);
  975. }
  976. }
  977. if (Subtarget->hasSVE())
  978. setOperationAction(ISD::VSCALE, MVT::i32, Custom);
  979. setTruncStoreAction(MVT::v4i16, MVT::v4i8, Custom);
  980. }
  981. if (Subtarget->hasSVE()) {
  982. // FIXME: Add custom lowering of MLOAD to handle different passthrus (not a
  983. // splat of 0 or undef) once vector selects supported in SVE codegen. See
  984. // D68877 for more details.
  985. for (auto VT : {MVT::nxv16i8, MVT::nxv8i16, MVT::nxv4i32, MVT::nxv2i64}) {
  986. setOperationAction(ISD::BITREVERSE, VT, Custom);
  987. setOperationAction(ISD::BSWAP, VT, Custom);
  988. setOperationAction(ISD::CTLZ, VT, Custom);
  989. setOperationAction(ISD::CTPOP, VT, Custom);
  990. setOperationAction(ISD::CTTZ, VT, Custom);
  991. setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
  992. setOperationAction(ISD::UINT_TO_FP, VT, Custom);
  993. setOperationAction(ISD::SINT_TO_FP, VT, Custom);
  994. setOperationAction(ISD::FP_TO_UINT, VT, Custom);
  995. setOperationAction(ISD::FP_TO_SINT, VT, Custom);
  996. setOperationAction(ISD::MGATHER, VT, Custom);
  997. setOperationAction(ISD::MSCATTER, VT, Custom);
  998. setOperationAction(ISD::MUL, VT, Custom);
  999. setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
  1000. setOperationAction(ISD::SELECT, VT, Custom);
  1001. setOperationAction(ISD::SDIV, VT, Custom);
  1002. setOperationAction(ISD::UDIV, VT, Custom);
  1003. setOperationAction(ISD::SMIN, VT, Custom);
  1004. setOperationAction(ISD::UMIN, VT, Custom);
  1005. setOperationAction(ISD::SMAX, VT, Custom);
  1006. setOperationAction(ISD::UMAX, VT, Custom);
  1007. setOperationAction(ISD::SHL, VT, Custom);
  1008. setOperationAction(ISD::SRL, VT, Custom);
  1009. setOperationAction(ISD::SRA, VT, Custom);
  1010. setOperationAction(ISD::ABS, VT, Custom);
  1011. setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
  1012. setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
  1013. setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
  1014. setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
  1015. setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
  1016. setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
  1017. setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
  1018. setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
  1019. }
  1020. // Illegal unpacked integer vector types.
  1021. for (auto VT : {MVT::nxv8i8, MVT::nxv4i16, MVT::nxv2i32}) {
  1022. setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
  1023. setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
  1024. }
  1025. for (auto VT : {MVT::nxv16i1, MVT::nxv8i1, MVT::nxv4i1, MVT::nxv2i1}) {
  1026. setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
  1027. setOperationAction(ISD::SELECT, VT, Custom);
  1028. setOperationAction(ISD::SETCC, VT, Custom);
  1029. setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
  1030. setOperationAction(ISD::TRUNCATE, VT, Custom);
  1031. setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
  1032. setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
  1033. setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
  1034. // There are no legal MVT::nxv16f## based types.
  1035. if (VT != MVT::nxv16i1) {
  1036. setOperationAction(ISD::SINT_TO_FP, VT, Custom);
  1037. setOperationAction(ISD::UINT_TO_FP, VT, Custom);
  1038. }
  1039. }
  1040. for (auto VT : {MVT::nxv2f16, MVT::nxv4f16, MVT::nxv8f16, MVT::nxv2f32,
  1041. MVT::nxv4f32, MVT::nxv2f64}) {
  1042. setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
  1043. setOperationAction(ISD::INSERT_SUBVECTOR, VT, Custom);
  1044. setOperationAction(ISD::MGATHER, VT, Custom);
  1045. setOperationAction(ISD::MSCATTER, VT, Custom);
  1046. setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
  1047. setOperationAction(ISD::SELECT, VT, Custom);
  1048. setOperationAction(ISD::FADD, VT, Custom);
  1049. setOperationAction(ISD::FDIV, VT, Custom);
  1050. setOperationAction(ISD::FMA, VT, Custom);
  1051. setOperationAction(ISD::FMAXNUM, VT, Custom);
  1052. setOperationAction(ISD::FMINNUM, VT, Custom);
  1053. setOperationAction(ISD::FMUL, VT, Custom);
  1054. setOperationAction(ISD::FNEG, VT, Custom);
  1055. setOperationAction(ISD::FSUB, VT, Custom);
  1056. setOperationAction(ISD::FCEIL, VT, Custom);
  1057. setOperationAction(ISD::FFLOOR, VT, Custom);
  1058. setOperationAction(ISD::FNEARBYINT, VT, Custom);
  1059. setOperationAction(ISD::FRINT, VT, Custom);
  1060. setOperationAction(ISD::FROUND, VT, Custom);
  1061. setOperationAction(ISD::FROUNDEVEN, VT, Custom);
  1062. setOperationAction(ISD::FTRUNC, VT, Custom);
  1063. setOperationAction(ISD::FSQRT, VT, Custom);
  1064. setOperationAction(ISD::FABS, VT, Custom);
  1065. setOperationAction(ISD::FP_EXTEND, VT, Custom);
  1066. setOperationAction(ISD::FP_ROUND, VT, Custom);
  1067. setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
  1068. setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
  1069. setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
  1070. setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
  1071. }
  1072. for (auto VT : {MVT::nxv2bf16, MVT::nxv4bf16, MVT::nxv8bf16}) {
  1073. setOperationAction(ISD::CONCAT_VECTORS, VT, Custom);
  1074. setOperationAction(ISD::MGATHER, VT, Custom);
  1075. setOperationAction(ISD::MSCATTER, VT, Custom);
  1076. }
  1077. setOperationAction(ISD::SPLAT_VECTOR, MVT::nxv8bf16, Custom);
  1078. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i8, Custom);
  1079. setOperationAction(ISD::INTRINSIC_WO_CHAIN, MVT::i16, Custom);
  1080. // NOTE: Currently this has to happen after computeRegisterProperties rather
  1081. // than the preferred option of combining it with the addRegisterClass call.
  1082. if (Subtarget->useSVEForFixedLengthVectors()) {
  1083. for (MVT VT : MVT::integer_fixedlen_vector_valuetypes())
  1084. if (useSVEForFixedLengthVectorVT(VT))
  1085. addTypeForFixedLengthSVE(VT);
  1086. for (MVT VT : MVT::fp_fixedlen_vector_valuetypes())
  1087. if (useSVEForFixedLengthVectorVT(VT))
  1088. addTypeForFixedLengthSVE(VT);
  1089. // 64bit results can mean a bigger than NEON input.
  1090. for (auto VT : {MVT::v8i8, MVT::v4i16})
  1091. setOperationAction(ISD::TRUNCATE, VT, Custom);
  1092. setOperationAction(ISD::FP_ROUND, MVT::v4f16, Custom);
  1093. // 128bit results imply a bigger than NEON input.
  1094. for (auto VT : {MVT::v16i8, MVT::v8i16, MVT::v4i32})
  1095. setOperationAction(ISD::TRUNCATE, VT, Custom);
  1096. for (auto VT : {MVT::v8f16, MVT::v4f32})
  1097. setOperationAction(ISD::FP_ROUND, VT, Expand);
  1098. // These operations are not supported on NEON but SVE can do them.
  1099. setOperationAction(ISD::BITREVERSE, MVT::v1i64, Custom);
  1100. setOperationAction(ISD::CTLZ, MVT::v1i64, Custom);
  1101. setOperationAction(ISD::CTLZ, MVT::v2i64, Custom);
  1102. setOperationAction(ISD::CTTZ, MVT::v1i64, Custom);
  1103. setOperationAction(ISD::MUL, MVT::v1i64, Custom);
  1104. setOperationAction(ISD::MUL, MVT::v2i64, Custom);
  1105. setOperationAction(ISD::SDIV, MVT::v8i8, Custom);
  1106. setOperationAction(ISD::SDIV, MVT::v16i8, Custom);
  1107. setOperationAction(ISD::SDIV, MVT::v4i16, Custom);
  1108. setOperationAction(ISD::SDIV, MVT::v8i16, Custom);
  1109. setOperationAction(ISD::SDIV, MVT::v2i32, Custom);
  1110. setOperationAction(ISD::SDIV, MVT::v4i32, Custom);
  1111. setOperationAction(ISD::SDIV, MVT::v1i64, Custom);
  1112. setOperationAction(ISD::SDIV, MVT::v2i64, Custom);
  1113. setOperationAction(ISD::SMAX, MVT::v1i64, Custom);
  1114. setOperationAction(ISD::SMAX, MVT::v2i64, Custom);
  1115. setOperationAction(ISD::SMIN, MVT::v1i64, Custom);
  1116. setOperationAction(ISD::SMIN, MVT::v2i64, Custom);
  1117. setOperationAction(ISD::UDIV, MVT::v8i8, Custom);
  1118. setOperationAction(ISD::UDIV, MVT::v16i8, Custom);
  1119. setOperationAction(ISD::UDIV, MVT::v4i16, Custom);
  1120. setOperationAction(ISD::UDIV, MVT::v8i16, Custom);
  1121. setOperationAction(ISD::UDIV, MVT::v2i32, Custom);
  1122. setOperationAction(ISD::UDIV, MVT::v4i32, Custom);
  1123. setOperationAction(ISD::UDIV, MVT::v1i64, Custom);
  1124. setOperationAction(ISD::UDIV, MVT::v2i64, Custom);
  1125. setOperationAction(ISD::UMAX, MVT::v1i64, Custom);
  1126. setOperationAction(ISD::UMAX, MVT::v2i64, Custom);
  1127. setOperationAction(ISD::UMIN, MVT::v1i64, Custom);
  1128. setOperationAction(ISD::UMIN, MVT::v2i64, Custom);
  1129. setOperationAction(ISD::VECREDUCE_SMAX, MVT::v2i64, Custom);
  1130. setOperationAction(ISD::VECREDUCE_SMIN, MVT::v2i64, Custom);
  1131. setOperationAction(ISD::VECREDUCE_UMAX, MVT::v2i64, Custom);
  1132. setOperationAction(ISD::VECREDUCE_UMIN, MVT::v2i64, Custom);
  1133. // Int operations with no NEON support.
  1134. for (auto VT : {MVT::v8i8, MVT::v16i8, MVT::v4i16, MVT::v8i16,
  1135. MVT::v2i32, MVT::v4i32, MVT::v2i64}) {
  1136. setOperationAction(ISD::BITREVERSE, VT, Custom);
  1137. setOperationAction(ISD::CTTZ, VT, Custom);
  1138. setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
  1139. setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
  1140. setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
  1141. }
  1142. // FP operations with no NEON support.
  1143. for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v2f32, MVT::v4f32,
  1144. MVT::v1f64, MVT::v2f64})
  1145. setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
  1146. // Use SVE for vectors with more than 2 elements.
  1147. for (auto VT : {MVT::v4f16, MVT::v8f16, MVT::v4f32})
  1148. setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
  1149. }
  1150. }
  1151. PredictableSelectIsExpensive = Subtarget->predictableSelectIsExpensive();
  1152. }
  1153. void AArch64TargetLowering::addTypeForNEON(MVT VT, MVT PromotedBitwiseVT) {
  1154. assert(VT.isVector() && "VT should be a vector type");
  1155. if (VT.isFloatingPoint()) {
  1156. MVT PromoteTo = EVT(VT).changeVectorElementTypeToInteger().getSimpleVT();
  1157. setOperationPromotedToType(ISD::LOAD, VT, PromoteTo);
  1158. setOperationPromotedToType(ISD::STORE, VT, PromoteTo);
  1159. }
  1160. // Mark vector float intrinsics as expand.
  1161. if (VT == MVT::v2f32 || VT == MVT::v4f32 || VT == MVT::v2f64) {
  1162. setOperationAction(ISD::FSIN, VT, Expand);
  1163. setOperationAction(ISD::FCOS, VT, Expand);
  1164. setOperationAction(ISD::FPOW, VT, Expand);
  1165. setOperationAction(ISD::FLOG, VT, Expand);
  1166. setOperationAction(ISD::FLOG2, VT, Expand);
  1167. setOperationAction(ISD::FLOG10, VT, Expand);
  1168. setOperationAction(ISD::FEXP, VT, Expand);
  1169. setOperationAction(ISD::FEXP2, VT, Expand);
  1170. // But we do support custom-lowering for FCOPYSIGN.
  1171. setOperationAction(ISD::FCOPYSIGN, VT, Custom);
  1172. }
  1173. setOperationAction(ISD::EXTRACT_VECTOR_ELT, VT, Custom);
  1174. setOperationAction(ISD::INSERT_VECTOR_ELT, VT, Custom);
  1175. setOperationAction(ISD::BUILD_VECTOR, VT, Custom);
  1176. setOperationAction(ISD::VECTOR_SHUFFLE, VT, Custom);
  1177. setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
  1178. setOperationAction(ISD::SRA, VT, Custom);
  1179. setOperationAction(ISD::SRL, VT, Custom);
  1180. setOperationAction(ISD::SHL, VT, Custom);
  1181. setOperationAction(ISD::OR, VT, Custom);
  1182. setOperationAction(ISD::SETCC, VT, Custom);
  1183. setOperationAction(ISD::CONCAT_VECTORS, VT, Legal);
  1184. setOperationAction(ISD::SELECT, VT, Expand);
  1185. setOperationAction(ISD::SELECT_CC, VT, Expand);
  1186. setOperationAction(ISD::VSELECT, VT, Expand);
  1187. for (MVT InnerVT : MVT::all_valuetypes())
  1188. setLoadExtAction(ISD::EXTLOAD, InnerVT, VT, Expand);
  1189. // CNT supports only B element sizes, then use UADDLP to widen.
  1190. if (VT != MVT::v8i8 && VT != MVT::v16i8)
  1191. setOperationAction(ISD::CTPOP, VT, Custom);
  1192. setOperationAction(ISD::UDIV, VT, Expand);
  1193. setOperationAction(ISD::SDIV, VT, Expand);
  1194. setOperationAction(ISD::UREM, VT, Expand);
  1195. setOperationAction(ISD::SREM, VT, Expand);
  1196. setOperationAction(ISD::FREM, VT, Expand);
  1197. setOperationAction(ISD::FP_TO_SINT, VT, Custom);
  1198. setOperationAction(ISD::FP_TO_UINT, VT, Custom);
  1199. if (!VT.isFloatingPoint())
  1200. setOperationAction(ISD::ABS, VT, Legal);
  1201. // [SU][MIN|MAX] are available for all NEON types apart from i64.
  1202. if (!VT.isFloatingPoint() && VT != MVT::v2i64 && VT != MVT::v1i64)
  1203. for (unsigned Opcode : {ISD::SMIN, ISD::SMAX, ISD::UMIN, ISD::UMAX})
  1204. setOperationAction(Opcode, VT, Legal);
  1205. // F[MIN|MAX][NUM|NAN] are available for all FP NEON types.
  1206. if (VT.isFloatingPoint() &&
  1207. VT.getVectorElementType() != MVT::bf16 &&
  1208. (VT.getVectorElementType() != MVT::f16 || Subtarget->hasFullFP16()))
  1209. for (unsigned Opcode :
  1210. {ISD::FMINIMUM, ISD::FMAXIMUM, ISD::FMINNUM, ISD::FMAXNUM})
  1211. setOperationAction(Opcode, VT, Legal);
  1212. if (Subtarget->isLittleEndian()) {
  1213. for (unsigned im = (unsigned)ISD::PRE_INC;
  1214. im != (unsigned)ISD::LAST_INDEXED_MODE; ++im) {
  1215. setIndexedLoadAction(im, VT, Legal);
  1216. setIndexedStoreAction(im, VT, Legal);
  1217. }
  1218. }
  1219. }
  1220. void AArch64TargetLowering::addTypeForFixedLengthSVE(MVT VT) {
  1221. assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
  1222. // By default everything must be expanded.
  1223. for (unsigned Op = 0; Op < ISD::BUILTIN_OP_END; ++Op)
  1224. setOperationAction(Op, VT, Expand);
  1225. // We use EXTRACT_SUBVECTOR to "cast" a scalable vector to a fixed length one.
  1226. setOperationAction(ISD::EXTRACT_SUBVECTOR, VT, Custom);
  1227. // Lower fixed length vector operations to scalable equivalents.
  1228. setOperationAction(ISD::ABS, VT, Custom);
  1229. setOperationAction(ISD::ADD, VT, Custom);
  1230. setOperationAction(ISD::AND, VT, Custom);
  1231. setOperationAction(ISD::ANY_EXTEND, VT, Custom);
  1232. setOperationAction(ISD::BITREVERSE, VT, Custom);
  1233. setOperationAction(ISD::BSWAP, VT, Custom);
  1234. setOperationAction(ISD::CTLZ, VT, Custom);
  1235. setOperationAction(ISD::CTPOP, VT, Custom);
  1236. setOperationAction(ISD::CTTZ, VT, Custom);
  1237. setOperationAction(ISD::FADD, VT, Custom);
  1238. setOperationAction(ISD::FCEIL, VT, Custom);
  1239. setOperationAction(ISD::FDIV, VT, Custom);
  1240. setOperationAction(ISD::FFLOOR, VT, Custom);
  1241. setOperationAction(ISD::FMA, VT, Custom);
  1242. setOperationAction(ISD::FMAXNUM, VT, Custom);
  1243. setOperationAction(ISD::FMINNUM, VT, Custom);
  1244. setOperationAction(ISD::FMUL, VT, Custom);
  1245. setOperationAction(ISD::FNEARBYINT, VT, Custom);
  1246. setOperationAction(ISD::FNEG, VT, Custom);
  1247. setOperationAction(ISD::FRINT, VT, Custom);
  1248. setOperationAction(ISD::FROUND, VT, Custom);
  1249. setOperationAction(ISD::FSQRT, VT, Custom);
  1250. setOperationAction(ISD::FSUB, VT, Custom);
  1251. setOperationAction(ISD::FTRUNC, VT, Custom);
  1252. setOperationAction(ISD::LOAD, VT, Custom);
  1253. setOperationAction(ISD::MUL, VT, Custom);
  1254. setOperationAction(ISD::OR, VT, Custom);
  1255. setOperationAction(ISD::SDIV, VT, Custom);
  1256. setOperationAction(ISD::SETCC, VT, Custom);
  1257. setOperationAction(ISD::SHL, VT, Custom);
  1258. setOperationAction(ISD::SIGN_EXTEND, VT, Custom);
  1259. setOperationAction(ISD::SIGN_EXTEND_INREG, VT, Custom);
  1260. setOperationAction(ISD::SMAX, VT, Custom);
  1261. setOperationAction(ISD::SMIN, VT, Custom);
  1262. setOperationAction(ISD::SPLAT_VECTOR, VT, Custom);
  1263. setOperationAction(ISD::SRA, VT, Custom);
  1264. setOperationAction(ISD::SRL, VT, Custom);
  1265. setOperationAction(ISD::STORE, VT, Custom);
  1266. setOperationAction(ISD::SUB, VT, Custom);
  1267. setOperationAction(ISD::TRUNCATE, VT, Custom);
  1268. setOperationAction(ISD::UDIV, VT, Custom);
  1269. setOperationAction(ISD::UMAX, VT, Custom);
  1270. setOperationAction(ISD::UMIN, VT, Custom);
  1271. setOperationAction(ISD::VECREDUCE_ADD, VT, Custom);
  1272. setOperationAction(ISD::VECREDUCE_AND, VT, Custom);
  1273. setOperationAction(ISD::VECREDUCE_FADD, VT, Custom);
  1274. setOperationAction(ISD::VECREDUCE_SEQ_FADD, VT, Custom);
  1275. setOperationAction(ISD::VECREDUCE_FMAX, VT, Custom);
  1276. setOperationAction(ISD::VECREDUCE_FMIN, VT, Custom);
  1277. setOperationAction(ISD::VECREDUCE_OR, VT, Custom);
  1278. setOperationAction(ISD::VECREDUCE_SMAX, VT, Custom);
  1279. setOperationAction(ISD::VECREDUCE_SMIN, VT, Custom);
  1280. setOperationAction(ISD::VECREDUCE_UMAX, VT, Custom);
  1281. setOperationAction(ISD::VECREDUCE_UMIN, VT, Custom);
  1282. setOperationAction(ISD::VECREDUCE_XOR, VT, Custom);
  1283. setOperationAction(ISD::VSELECT, VT, Custom);
  1284. setOperationAction(ISD::XOR, VT, Custom);
  1285. setOperationAction(ISD::ZERO_EXTEND, VT, Custom);
  1286. }
  1287. void AArch64TargetLowering::addDRTypeForNEON(MVT VT) {
  1288. addRegisterClass(VT, &AArch64::FPR64RegClass);
  1289. addTypeForNEON(VT, MVT::v2i32);
  1290. }
  1291. void AArch64TargetLowering::addQRTypeForNEON(MVT VT) {
  1292. addRegisterClass(VT, &AArch64::FPR128RegClass);
  1293. addTypeForNEON(VT, MVT::v4i32);
  1294. }
  1295. EVT AArch64TargetLowering::getSetCCResultType(const DataLayout &,
  1296. LLVMContext &C, EVT VT) const {
  1297. if (!VT.isVector())
  1298. return MVT::i32;
  1299. if (VT.isScalableVector())
  1300. return EVT::getVectorVT(C, MVT::i1, VT.getVectorElementCount());
  1301. return VT.changeVectorElementTypeToInteger();
  1302. }
  1303. static bool optimizeLogicalImm(SDValue Op, unsigned Size, uint64_t Imm,
  1304. const APInt &Demanded,
  1305. TargetLowering::TargetLoweringOpt &TLO,
  1306. unsigned NewOpc) {
  1307. uint64_t OldImm = Imm, NewImm, Enc;
  1308. uint64_t Mask = ((uint64_t)(-1LL) >> (64 - Size)), OrigMask = Mask;
  1309. // Return if the immediate is already all zeros, all ones, a bimm32 or a
  1310. // bimm64.
  1311. if (Imm == 0 || Imm == Mask ||
  1312. AArch64_AM::isLogicalImmediate(Imm & Mask, Size))
  1313. return false;
  1314. unsigned EltSize = Size;
  1315. uint64_t DemandedBits = Demanded.getZExtValue();
  1316. // Clear bits that are not demanded.
  1317. Imm &= DemandedBits;
  1318. while (true) {
  1319. // The goal here is to set the non-demanded bits in a way that minimizes
  1320. // the number of switching between 0 and 1. In order to achieve this goal,
  1321. // we set the non-demanded bits to the value of the preceding demanded bits.
  1322. // For example, if we have an immediate 0bx10xx0x1 ('x' indicates a
  1323. // non-demanded bit), we copy bit0 (1) to the least significant 'x',
  1324. // bit2 (0) to 'xx', and bit6 (1) to the most significant 'x'.
  1325. // The final result is 0b11000011.
  1326. uint64_t NonDemandedBits = ~DemandedBits;
  1327. uint64_t InvertedImm = ~Imm & DemandedBits;
  1328. uint64_t RotatedImm =
  1329. ((InvertedImm << 1) | (InvertedImm >> (EltSize - 1) & 1)) &
  1330. NonDemandedBits;
  1331. uint64_t Sum = RotatedImm + NonDemandedBits;
  1332. bool Carry = NonDemandedBits & ~Sum & (1ULL << (EltSize - 1));
  1333. uint64_t Ones = (Sum + Carry) & NonDemandedBits;
  1334. NewImm = (Imm | Ones) & Mask;
  1335. // If NewImm or its bitwise NOT is a shifted mask, it is a bitmask immediate
  1336. // or all-ones or all-zeros, in which case we can stop searching. Otherwise,
  1337. // we halve the element size and continue the search.
  1338. if (isShiftedMask_64(NewImm) || isShiftedMask_64(~(NewImm | ~Mask)))
  1339. break;
  1340. // We cannot shrink the element size any further if it is 2-bits.
  1341. if (EltSize == 2)
  1342. return false;
  1343. EltSize /= 2;
  1344. Mask >>= EltSize;
  1345. uint64_t Hi = Imm >> EltSize, DemandedBitsHi = DemandedBits >> EltSize;
  1346. // Return if there is mismatch in any of the demanded bits of Imm and Hi.
  1347. if (((Imm ^ Hi) & (DemandedBits & DemandedBitsHi) & Mask) != 0)
  1348. return false;
  1349. // Merge the upper and lower halves of Imm and DemandedBits.
  1350. Imm |= Hi;
  1351. DemandedBits |= DemandedBitsHi;
  1352. }
  1353. ++NumOptimizedImms;
  1354. // Replicate the element across the register width.
  1355. while (EltSize < Size) {
  1356. NewImm |= NewImm << EltSize;
  1357. EltSize *= 2;
  1358. }
  1359. (void)OldImm;
  1360. assert(((OldImm ^ NewImm) & Demanded.getZExtValue()) == 0 &&
  1361. "demanded bits should never be altered");
  1362. assert(OldImm != NewImm && "the new imm shouldn't be equal to the old imm");
  1363. // Create the new constant immediate node.
  1364. EVT VT = Op.getValueType();
  1365. SDLoc DL(Op);
  1366. SDValue New;
  1367. // If the new constant immediate is all-zeros or all-ones, let the target
  1368. // independent DAG combine optimize this node.
  1369. if (NewImm == 0 || NewImm == OrigMask) {
  1370. New = TLO.DAG.getNode(Op.getOpcode(), DL, VT, Op.getOperand(0),
  1371. TLO.DAG.getConstant(NewImm, DL, VT));
  1372. // Otherwise, create a machine node so that target independent DAG combine
  1373. // doesn't undo this optimization.
  1374. } else {
  1375. Enc = AArch64_AM::encodeLogicalImmediate(NewImm, Size);
  1376. SDValue EncConst = TLO.DAG.getTargetConstant(Enc, DL, VT);
  1377. New = SDValue(
  1378. TLO.DAG.getMachineNode(NewOpc, DL, VT, Op.getOperand(0), EncConst), 0);
  1379. }
  1380. return TLO.CombineTo(Op, New);
  1381. }
  1382. bool AArch64TargetLowering::targetShrinkDemandedConstant(
  1383. SDValue Op, const APInt &DemandedBits, const APInt &DemandedElts,
  1384. TargetLoweringOpt &TLO) const {
  1385. // Delay this optimization to as late as possible.
  1386. if (!TLO.LegalOps)
  1387. return false;
  1388. if (!EnableOptimizeLogicalImm)
  1389. return false;
  1390. EVT VT = Op.getValueType();
  1391. if (VT.isVector())
  1392. return false;
  1393. unsigned Size = VT.getSizeInBits();
  1394. assert((Size == 32 || Size == 64) &&
  1395. "i32 or i64 is expected after legalization.");
  1396. // Exit early if we demand all bits.
  1397. if (DemandedBits.countPopulation() == Size)
  1398. return false;
  1399. unsigned NewOpc;
  1400. switch (Op.getOpcode()) {
  1401. default:
  1402. return false;
  1403. case ISD::AND:
  1404. NewOpc = Size == 32 ? AArch64::ANDWri : AArch64::ANDXri;
  1405. break;
  1406. case ISD::OR:
  1407. NewOpc = Size == 32 ? AArch64::ORRWri : AArch64::ORRXri;
  1408. break;
  1409. case ISD::XOR:
  1410. NewOpc = Size == 32 ? AArch64::EORWri : AArch64::EORXri;
  1411. break;
  1412. }
  1413. ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  1414. if (!C)
  1415. return false;
  1416. uint64_t Imm = C->getZExtValue();
  1417. return optimizeLogicalImm(Op, Size, Imm, DemandedBits, TLO, NewOpc);
  1418. }
  1419. /// computeKnownBitsForTargetNode - Determine which of the bits specified in
  1420. /// Mask are known to be either zero or one and return them Known.
  1421. void AArch64TargetLowering::computeKnownBitsForTargetNode(
  1422. const SDValue Op, KnownBits &Known,
  1423. const APInt &DemandedElts, const SelectionDAG &DAG, unsigned Depth) const {
  1424. switch (Op.getOpcode()) {
  1425. default:
  1426. break;
  1427. case AArch64ISD::CSEL: {
  1428. KnownBits Known2;
  1429. Known = DAG.computeKnownBits(Op->getOperand(0), Depth + 1);
  1430. Known2 = DAG.computeKnownBits(Op->getOperand(1), Depth + 1);
  1431. Known = KnownBits::commonBits(Known, Known2);
  1432. break;
  1433. }
  1434. case AArch64ISD::LOADgot:
  1435. case AArch64ISD::ADDlow: {
  1436. if (!Subtarget->isTargetILP32())
  1437. break;
  1438. // In ILP32 mode all valid pointers are in the low 4GB of the address-space.
  1439. Known.Zero = APInt::getHighBitsSet(64, 32);
  1440. break;
  1441. }
  1442. case ISD::INTRINSIC_W_CHAIN: {
  1443. ConstantSDNode *CN = cast<ConstantSDNode>(Op->getOperand(1));
  1444. Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
  1445. switch (IntID) {
  1446. default: return;
  1447. case Intrinsic::aarch64_ldaxr:
  1448. case Intrinsic::aarch64_ldxr: {
  1449. unsigned BitWidth = Known.getBitWidth();
  1450. EVT VT = cast<MemIntrinsicSDNode>(Op)->getMemoryVT();
  1451. unsigned MemBits = VT.getScalarSizeInBits();
  1452. Known.Zero |= APInt::getHighBitsSet(BitWidth, BitWidth - MemBits);
  1453. return;
  1454. }
  1455. }
  1456. break;
  1457. }
  1458. case ISD::INTRINSIC_WO_CHAIN:
  1459. case ISD::INTRINSIC_VOID: {
  1460. unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  1461. switch (IntNo) {
  1462. default:
  1463. break;
  1464. case Intrinsic::aarch64_neon_umaxv:
  1465. case Intrinsic::aarch64_neon_uminv: {
  1466. // Figure out the datatype of the vector operand. The UMINV instruction
  1467. // will zero extend the result, so we can mark as known zero all the
  1468. // bits larger than the element datatype. 32-bit or larget doesn't need
  1469. // this as those are legal types and will be handled by isel directly.
  1470. MVT VT = Op.getOperand(1).getValueType().getSimpleVT();
  1471. unsigned BitWidth = Known.getBitWidth();
  1472. if (VT == MVT::v8i8 || VT == MVT::v16i8) {
  1473. assert(BitWidth >= 8 && "Unexpected width!");
  1474. APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 8);
  1475. Known.Zero |= Mask;
  1476. } else if (VT == MVT::v4i16 || VT == MVT::v8i16) {
  1477. assert(BitWidth >= 16 && "Unexpected width!");
  1478. APInt Mask = APInt::getHighBitsSet(BitWidth, BitWidth - 16);
  1479. Known.Zero |= Mask;
  1480. }
  1481. break;
  1482. } break;
  1483. }
  1484. }
  1485. }
  1486. }
  1487. MVT AArch64TargetLowering::getScalarShiftAmountTy(const DataLayout &DL,
  1488. EVT) const {
  1489. return MVT::i64;
  1490. }
  1491. bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
  1492. EVT VT, unsigned AddrSpace, unsigned Align, MachineMemOperand::Flags Flags,
  1493. bool *Fast) const {
  1494. if (Subtarget->requiresStrictAlign())
  1495. return false;
  1496. if (Fast) {
  1497. // Some CPUs are fine with unaligned stores except for 128-bit ones.
  1498. *Fast = !Subtarget->isMisaligned128StoreSlow() || VT.getStoreSize() != 16 ||
  1499. // See comments in performSTORECombine() for more details about
  1500. // these conditions.
  1501. // Code that uses clang vector extensions can mark that it
  1502. // wants unaligned accesses to be treated as fast by
  1503. // underspecifying alignment to be 1 or 2.
  1504. Align <= 2 ||
  1505. // Disregard v2i64. Memcpy lowering produces those and splitting
  1506. // them regresses performance on micro-benchmarks and olden/bh.
  1507. VT == MVT::v2i64;
  1508. }
  1509. return true;
  1510. }
  1511. // Same as above but handling LLTs instead.
  1512. bool AArch64TargetLowering::allowsMisalignedMemoryAccesses(
  1513. LLT Ty, unsigned AddrSpace, Align Alignment, MachineMemOperand::Flags Flags,
  1514. bool *Fast) const {
  1515. if (Subtarget->requiresStrictAlign())
  1516. return false;
  1517. if (Fast) {
  1518. // Some CPUs are fine with unaligned stores except for 128-bit ones.
  1519. *Fast = !Subtarget->isMisaligned128StoreSlow() ||
  1520. Ty.getSizeInBytes() != 16 ||
  1521. // See comments in performSTORECombine() for more details about
  1522. // these conditions.
  1523. // Code that uses clang vector extensions can mark that it
  1524. // wants unaligned accesses to be treated as fast by
  1525. // underspecifying alignment to be 1 or 2.
  1526. Alignment <= 2 ||
  1527. // Disregard v2i64. Memcpy lowering produces those and splitting
  1528. // them regresses performance on micro-benchmarks and olden/bh.
  1529. Ty == LLT::vector(2, 64);
  1530. }
  1531. return true;
  1532. }
  1533. FastISel *
  1534. AArch64TargetLowering::createFastISel(FunctionLoweringInfo &funcInfo,
  1535. const TargetLibraryInfo *libInfo) const {
  1536. return AArch64::createFastISel(funcInfo, libInfo);
  1537. }
  1538. const char *AArch64TargetLowering::getTargetNodeName(unsigned Opcode) const {
  1539. #define MAKE_CASE(V) \
  1540. case V: \
  1541. return #V;
  1542. switch ((AArch64ISD::NodeType)Opcode) {
  1543. case AArch64ISD::FIRST_NUMBER:
  1544. break;
  1545. MAKE_CASE(AArch64ISD::CALL)
  1546. MAKE_CASE(AArch64ISD::ADRP)
  1547. MAKE_CASE(AArch64ISD::ADR)
  1548. MAKE_CASE(AArch64ISD::ADDlow)
  1549. MAKE_CASE(AArch64ISD::LOADgot)
  1550. MAKE_CASE(AArch64ISD::RET_FLAG)
  1551. MAKE_CASE(AArch64ISD::BRCOND)
  1552. MAKE_CASE(AArch64ISD::CSEL)
  1553. MAKE_CASE(AArch64ISD::FCSEL)
  1554. MAKE_CASE(AArch64ISD::CSINV)
  1555. MAKE_CASE(AArch64ISD::CSNEG)
  1556. MAKE_CASE(AArch64ISD::CSINC)
  1557. MAKE_CASE(AArch64ISD::THREAD_POINTER)
  1558. MAKE_CASE(AArch64ISD::TLSDESC_CALLSEQ)
  1559. MAKE_CASE(AArch64ISD::ADD_PRED)
  1560. MAKE_CASE(AArch64ISD::MUL_PRED)
  1561. MAKE_CASE(AArch64ISD::SDIV_PRED)
  1562. MAKE_CASE(AArch64ISD::SHL_PRED)
  1563. MAKE_CASE(AArch64ISD::SMAX_PRED)
  1564. MAKE_CASE(AArch64ISD::SMIN_PRED)
  1565. MAKE_CASE(AArch64ISD::SRA_PRED)
  1566. MAKE_CASE(AArch64ISD::SRL_PRED)
  1567. MAKE_CASE(AArch64ISD::SUB_PRED)
  1568. MAKE_CASE(AArch64ISD::UDIV_PRED)
  1569. MAKE_CASE(AArch64ISD::UMAX_PRED)
  1570. MAKE_CASE(AArch64ISD::UMIN_PRED)
  1571. MAKE_CASE(AArch64ISD::FNEG_MERGE_PASSTHRU)
  1572. MAKE_CASE(AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU)
  1573. MAKE_CASE(AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU)
  1574. MAKE_CASE(AArch64ISD::FCEIL_MERGE_PASSTHRU)
  1575. MAKE_CASE(AArch64ISD::FFLOOR_MERGE_PASSTHRU)
  1576. MAKE_CASE(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU)
  1577. MAKE_CASE(AArch64ISD::FRINT_MERGE_PASSTHRU)
  1578. MAKE_CASE(AArch64ISD::FROUND_MERGE_PASSTHRU)
  1579. MAKE_CASE(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU)
  1580. MAKE_CASE(AArch64ISD::FTRUNC_MERGE_PASSTHRU)
  1581. MAKE_CASE(AArch64ISD::FP_ROUND_MERGE_PASSTHRU)
  1582. MAKE_CASE(AArch64ISD::FP_EXTEND_MERGE_PASSTHRU)
  1583. MAKE_CASE(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU)
  1584. MAKE_CASE(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU)
  1585. MAKE_CASE(AArch64ISD::FCVTZU_MERGE_PASSTHRU)
  1586. MAKE_CASE(AArch64ISD::FCVTZS_MERGE_PASSTHRU)
  1587. MAKE_CASE(AArch64ISD::FSQRT_MERGE_PASSTHRU)
  1588. MAKE_CASE(AArch64ISD::FRECPX_MERGE_PASSTHRU)
  1589. MAKE_CASE(AArch64ISD::FABS_MERGE_PASSTHRU)
  1590. MAKE_CASE(AArch64ISD::ABS_MERGE_PASSTHRU)
  1591. MAKE_CASE(AArch64ISD::NEG_MERGE_PASSTHRU)
  1592. MAKE_CASE(AArch64ISD::SETCC_MERGE_ZERO)
  1593. MAKE_CASE(AArch64ISD::ADC)
  1594. MAKE_CASE(AArch64ISD::SBC)
  1595. MAKE_CASE(AArch64ISD::ADDS)
  1596. MAKE_CASE(AArch64ISD::SUBS)
  1597. MAKE_CASE(AArch64ISD::ADCS)
  1598. MAKE_CASE(AArch64ISD::SBCS)
  1599. MAKE_CASE(AArch64ISD::ANDS)
  1600. MAKE_CASE(AArch64ISD::CCMP)
  1601. MAKE_CASE(AArch64ISD::CCMN)
  1602. MAKE_CASE(AArch64ISD::FCCMP)
  1603. MAKE_CASE(AArch64ISD::FCMP)
  1604. MAKE_CASE(AArch64ISD::STRICT_FCMP)
  1605. MAKE_CASE(AArch64ISD::STRICT_FCMPE)
  1606. MAKE_CASE(AArch64ISD::DUP)
  1607. MAKE_CASE(AArch64ISD::DUPLANE8)
  1608. MAKE_CASE(AArch64ISD::DUPLANE16)
  1609. MAKE_CASE(AArch64ISD::DUPLANE32)
  1610. MAKE_CASE(AArch64ISD::DUPLANE64)
  1611. MAKE_CASE(AArch64ISD::MOVI)
  1612. MAKE_CASE(AArch64ISD::MOVIshift)
  1613. MAKE_CASE(AArch64ISD::MOVIedit)
  1614. MAKE_CASE(AArch64ISD::MOVImsl)
  1615. MAKE_CASE(AArch64ISD::FMOV)
  1616. MAKE_CASE(AArch64ISD::MVNIshift)
  1617. MAKE_CASE(AArch64ISD::MVNImsl)
  1618. MAKE_CASE(AArch64ISD::BICi)
  1619. MAKE_CASE(AArch64ISD::ORRi)
  1620. MAKE_CASE(AArch64ISD::BSP)
  1621. MAKE_CASE(AArch64ISD::NEG)
  1622. MAKE_CASE(AArch64ISD::EXTR)
  1623. MAKE_CASE(AArch64ISD::ZIP1)
  1624. MAKE_CASE(AArch64ISD::ZIP2)
  1625. MAKE_CASE(AArch64ISD::UZP1)
  1626. MAKE_CASE(AArch64ISD::UZP2)
  1627. MAKE_CASE(AArch64ISD::TRN1)
  1628. MAKE_CASE(AArch64ISD::TRN2)
  1629. MAKE_CASE(AArch64ISD::REV16)
  1630. MAKE_CASE(AArch64ISD::REV32)
  1631. MAKE_CASE(AArch64ISD::REV64)
  1632. MAKE_CASE(AArch64ISD::EXT)
  1633. MAKE_CASE(AArch64ISD::VSHL)
  1634. MAKE_CASE(AArch64ISD::VLSHR)
  1635. MAKE_CASE(AArch64ISD::VASHR)
  1636. MAKE_CASE(AArch64ISD::VSLI)
  1637. MAKE_CASE(AArch64ISD::VSRI)
  1638. MAKE_CASE(AArch64ISD::CMEQ)
  1639. MAKE_CASE(AArch64ISD::CMGE)
  1640. MAKE_CASE(AArch64ISD::CMGT)
  1641. MAKE_CASE(AArch64ISD::CMHI)
  1642. MAKE_CASE(AArch64ISD::CMHS)
  1643. MAKE_CASE(AArch64ISD::FCMEQ)
  1644. MAKE_CASE(AArch64ISD::FCMGE)
  1645. MAKE_CASE(AArch64ISD::FCMGT)
  1646. MAKE_CASE(AArch64ISD::CMEQz)
  1647. MAKE_CASE(AArch64ISD::CMGEz)
  1648. MAKE_CASE(AArch64ISD::CMGTz)
  1649. MAKE_CASE(AArch64ISD::CMLEz)
  1650. MAKE_CASE(AArch64ISD::CMLTz)
  1651. MAKE_CASE(AArch64ISD::FCMEQz)
  1652. MAKE_CASE(AArch64ISD::FCMGEz)
  1653. MAKE_CASE(AArch64ISD::FCMGTz)
  1654. MAKE_CASE(AArch64ISD::FCMLEz)
  1655. MAKE_CASE(AArch64ISD::FCMLTz)
  1656. MAKE_CASE(AArch64ISD::SADDV)
  1657. MAKE_CASE(AArch64ISD::UADDV)
  1658. MAKE_CASE(AArch64ISD::SRHADD)
  1659. MAKE_CASE(AArch64ISD::URHADD)
  1660. MAKE_CASE(AArch64ISD::SHADD)
  1661. MAKE_CASE(AArch64ISD::UHADD)
  1662. MAKE_CASE(AArch64ISD::SMINV)
  1663. MAKE_CASE(AArch64ISD::UMINV)
  1664. MAKE_CASE(AArch64ISD::SMAXV)
  1665. MAKE_CASE(AArch64ISD::UMAXV)
  1666. MAKE_CASE(AArch64ISD::SADDV_PRED)
  1667. MAKE_CASE(AArch64ISD::UADDV_PRED)
  1668. MAKE_CASE(AArch64ISD::SMAXV_PRED)
  1669. MAKE_CASE(AArch64ISD::UMAXV_PRED)
  1670. MAKE_CASE(AArch64ISD::SMINV_PRED)
  1671. MAKE_CASE(AArch64ISD::UMINV_PRED)
  1672. MAKE_CASE(AArch64ISD::ORV_PRED)
  1673. MAKE_CASE(AArch64ISD::EORV_PRED)
  1674. MAKE_CASE(AArch64ISD::ANDV_PRED)
  1675. MAKE_CASE(AArch64ISD::CLASTA_N)
  1676. MAKE_CASE(AArch64ISD::CLASTB_N)
  1677. MAKE_CASE(AArch64ISD::LASTA)
  1678. MAKE_CASE(AArch64ISD::LASTB)
  1679. MAKE_CASE(AArch64ISD::REV)
  1680. MAKE_CASE(AArch64ISD::REINTERPRET_CAST)
  1681. MAKE_CASE(AArch64ISD::TBL)
  1682. MAKE_CASE(AArch64ISD::FADD_PRED)
  1683. MAKE_CASE(AArch64ISD::FADDA_PRED)
  1684. MAKE_CASE(AArch64ISD::FADDV_PRED)
  1685. MAKE_CASE(AArch64ISD::FDIV_PRED)
  1686. MAKE_CASE(AArch64ISD::FMA_PRED)
  1687. MAKE_CASE(AArch64ISD::FMAXV_PRED)
  1688. MAKE_CASE(AArch64ISD::FMAXNM_PRED)
  1689. MAKE_CASE(AArch64ISD::FMAXNMV_PRED)
  1690. MAKE_CASE(AArch64ISD::FMINV_PRED)
  1691. MAKE_CASE(AArch64ISD::FMINNM_PRED)
  1692. MAKE_CASE(AArch64ISD::FMINNMV_PRED)
  1693. MAKE_CASE(AArch64ISD::FMUL_PRED)
  1694. MAKE_CASE(AArch64ISD::FSUB_PRED)
  1695. MAKE_CASE(AArch64ISD::BIT)
  1696. MAKE_CASE(AArch64ISD::CBZ)
  1697. MAKE_CASE(AArch64ISD::CBNZ)
  1698. MAKE_CASE(AArch64ISD::TBZ)
  1699. MAKE_CASE(AArch64ISD::TBNZ)
  1700. MAKE_CASE(AArch64ISD::TC_RETURN)
  1701. MAKE_CASE(AArch64ISD::PREFETCH)
  1702. MAKE_CASE(AArch64ISD::SITOF)
  1703. MAKE_CASE(AArch64ISD::UITOF)
  1704. MAKE_CASE(AArch64ISD::NVCAST)
  1705. MAKE_CASE(AArch64ISD::SQSHL_I)
  1706. MAKE_CASE(AArch64ISD::UQSHL_I)
  1707. MAKE_CASE(AArch64ISD::SRSHR_I)
  1708. MAKE_CASE(AArch64ISD::URSHR_I)
  1709. MAKE_CASE(AArch64ISD::SQSHLU_I)
  1710. MAKE_CASE(AArch64ISD::WrapperLarge)
  1711. MAKE_CASE(AArch64ISD::LD2post)
  1712. MAKE_CASE(AArch64ISD::LD3post)
  1713. MAKE_CASE(AArch64ISD::LD4post)
  1714. MAKE_CASE(AArch64ISD::ST2post)
  1715. MAKE_CASE(AArch64ISD::ST3post)
  1716. MAKE_CASE(AArch64ISD::ST4post)
  1717. MAKE_CASE(AArch64ISD::LD1x2post)
  1718. MAKE_CASE(AArch64ISD::LD1x3post)
  1719. MAKE_CASE(AArch64ISD::LD1x4post)
  1720. MAKE_CASE(AArch64ISD::ST1x2post)
  1721. MAKE_CASE(AArch64ISD::ST1x3post)
  1722. MAKE_CASE(AArch64ISD::ST1x4post)
  1723. MAKE_CASE(AArch64ISD::LD1DUPpost)
  1724. MAKE_CASE(AArch64ISD::LD2DUPpost)
  1725. MAKE_CASE(AArch64ISD::LD3DUPpost)
  1726. MAKE_CASE(AArch64ISD::LD4DUPpost)
  1727. MAKE_CASE(AArch64ISD::LD1LANEpost)
  1728. MAKE_CASE(AArch64ISD::LD2LANEpost)
  1729. MAKE_CASE(AArch64ISD::LD3LANEpost)
  1730. MAKE_CASE(AArch64ISD::LD4LANEpost)
  1731. MAKE_CASE(AArch64ISD::ST2LANEpost)
  1732. MAKE_CASE(AArch64ISD::ST3LANEpost)
  1733. MAKE_CASE(AArch64ISD::ST4LANEpost)
  1734. MAKE_CASE(AArch64ISD::SMULL)
  1735. MAKE_CASE(AArch64ISD::UMULL)
  1736. MAKE_CASE(AArch64ISD::FRECPE)
  1737. MAKE_CASE(AArch64ISD::FRECPS)
  1738. MAKE_CASE(AArch64ISD::FRSQRTE)
  1739. MAKE_CASE(AArch64ISD::FRSQRTS)
  1740. MAKE_CASE(AArch64ISD::STG)
  1741. MAKE_CASE(AArch64ISD::STZG)
  1742. MAKE_CASE(AArch64ISD::ST2G)
  1743. MAKE_CASE(AArch64ISD::STZ2G)
  1744. MAKE_CASE(AArch64ISD::SUNPKHI)
  1745. MAKE_CASE(AArch64ISD::SUNPKLO)
  1746. MAKE_CASE(AArch64ISD::UUNPKHI)
  1747. MAKE_CASE(AArch64ISD::UUNPKLO)
  1748. MAKE_CASE(AArch64ISD::INSR)
  1749. MAKE_CASE(AArch64ISD::PTEST)
  1750. MAKE_CASE(AArch64ISD::PTRUE)
  1751. MAKE_CASE(AArch64ISD::LD1_MERGE_ZERO)
  1752. MAKE_CASE(AArch64ISD::LD1S_MERGE_ZERO)
  1753. MAKE_CASE(AArch64ISD::LDNF1_MERGE_ZERO)
  1754. MAKE_CASE(AArch64ISD::LDNF1S_MERGE_ZERO)
  1755. MAKE_CASE(AArch64ISD::LDFF1_MERGE_ZERO)
  1756. MAKE_CASE(AArch64ISD::LDFF1S_MERGE_ZERO)
  1757. MAKE_CASE(AArch64ISD::LD1RQ_MERGE_ZERO)
  1758. MAKE_CASE(AArch64ISD::LD1RO_MERGE_ZERO)
  1759. MAKE_CASE(AArch64ISD::SVE_LD2_MERGE_ZERO)
  1760. MAKE_CASE(AArch64ISD::SVE_LD3_MERGE_ZERO)
  1761. MAKE_CASE(AArch64ISD::SVE_LD4_MERGE_ZERO)
  1762. MAKE_CASE(AArch64ISD::GLD1_MERGE_ZERO)
  1763. MAKE_CASE(AArch64ISD::GLD1_SCALED_MERGE_ZERO)
  1764. MAKE_CASE(AArch64ISD::GLD1_SXTW_MERGE_ZERO)
  1765. MAKE_CASE(AArch64ISD::GLD1_UXTW_MERGE_ZERO)
  1766. MAKE_CASE(AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO)
  1767. MAKE_CASE(AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO)
  1768. MAKE_CASE(AArch64ISD::GLD1_IMM_MERGE_ZERO)
  1769. MAKE_CASE(AArch64ISD::GLD1S_MERGE_ZERO)
  1770. MAKE_CASE(AArch64ISD::GLD1S_SCALED_MERGE_ZERO)
  1771. MAKE_CASE(AArch64ISD::GLD1S_SXTW_MERGE_ZERO)
  1772. MAKE_CASE(AArch64ISD::GLD1S_UXTW_MERGE_ZERO)
  1773. MAKE_CASE(AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO)
  1774. MAKE_CASE(AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO)
  1775. MAKE_CASE(AArch64ISD::GLD1S_IMM_MERGE_ZERO)
  1776. MAKE_CASE(AArch64ISD::GLDFF1_MERGE_ZERO)
  1777. MAKE_CASE(AArch64ISD::GLDFF1_SCALED_MERGE_ZERO)
  1778. MAKE_CASE(AArch64ISD::GLDFF1_SXTW_MERGE_ZERO)
  1779. MAKE_CASE(AArch64ISD::GLDFF1_UXTW_MERGE_ZERO)
  1780. MAKE_CASE(AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO)
  1781. MAKE_CASE(AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO)
  1782. MAKE_CASE(AArch64ISD::GLDFF1_IMM_MERGE_ZERO)
  1783. MAKE_CASE(AArch64ISD::GLDFF1S_MERGE_ZERO)
  1784. MAKE_CASE(AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO)
  1785. MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO)
  1786. MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO)
  1787. MAKE_CASE(AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO)
  1788. MAKE_CASE(AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO)
  1789. MAKE_CASE(AArch64ISD::GLDFF1S_IMM_MERGE_ZERO)
  1790. MAKE_CASE(AArch64ISD::GLDNT1_MERGE_ZERO)
  1791. MAKE_CASE(AArch64ISD::GLDNT1_INDEX_MERGE_ZERO)
  1792. MAKE_CASE(AArch64ISD::GLDNT1S_MERGE_ZERO)
  1793. MAKE_CASE(AArch64ISD::ST1_PRED)
  1794. MAKE_CASE(AArch64ISD::SST1_PRED)
  1795. MAKE_CASE(AArch64ISD::SST1_SCALED_PRED)
  1796. MAKE_CASE(AArch64ISD::SST1_SXTW_PRED)
  1797. MAKE_CASE(AArch64ISD::SST1_UXTW_PRED)
  1798. MAKE_CASE(AArch64ISD::SST1_SXTW_SCALED_PRED)
  1799. MAKE_CASE(AArch64ISD::SST1_UXTW_SCALED_PRED)
  1800. MAKE_CASE(AArch64ISD::SST1_IMM_PRED)
  1801. MAKE_CASE(AArch64ISD::SSTNT1_PRED)
  1802. MAKE_CASE(AArch64ISD::SSTNT1_INDEX_PRED)
  1803. MAKE_CASE(AArch64ISD::LDP)
  1804. MAKE_CASE(AArch64ISD::STP)
  1805. MAKE_CASE(AArch64ISD::STNP)
  1806. MAKE_CASE(AArch64ISD::BITREVERSE_MERGE_PASSTHRU)
  1807. MAKE_CASE(AArch64ISD::BSWAP_MERGE_PASSTHRU)
  1808. MAKE_CASE(AArch64ISD::CTLZ_MERGE_PASSTHRU)
  1809. MAKE_CASE(AArch64ISD::CTPOP_MERGE_PASSTHRU)
  1810. MAKE_CASE(AArch64ISD::DUP_MERGE_PASSTHRU)
  1811. MAKE_CASE(AArch64ISD::INDEX_VECTOR)
  1812. MAKE_CASE(AArch64ISD::UABD)
  1813. MAKE_CASE(AArch64ISD::SABD)
  1814. MAKE_CASE(AArch64ISD::CALL_RVMARKER)
  1815. }
  1816. #undef MAKE_CASE
  1817. return nullptr;
  1818. }
  1819. MachineBasicBlock *
  1820. AArch64TargetLowering::EmitF128CSEL(MachineInstr &MI,
  1821. MachineBasicBlock *MBB) const {
  1822. // We materialise the F128CSEL pseudo-instruction as some control flow and a
  1823. // phi node:
  1824. // OrigBB:
  1825. // [... previous instrs leading to comparison ...]
  1826. // b.ne TrueBB
  1827. // b EndBB
  1828. // TrueBB:
  1829. // ; Fallthrough
  1830. // EndBB:
  1831. // Dest = PHI [IfTrue, TrueBB], [IfFalse, OrigBB]
  1832. MachineFunction *MF = MBB->getParent();
  1833. const TargetInstrInfo *TII = Subtarget->getInstrInfo();
  1834. const BasicBlock *LLVM_BB = MBB->getBasicBlock();
  1835. DebugLoc DL = MI.getDebugLoc();
  1836. MachineFunction::iterator It = ++MBB->getIterator();
  1837. Register DestReg = MI.getOperand(0).getReg();
  1838. Register IfTrueReg = MI.getOperand(1).getReg();
  1839. Register IfFalseReg = MI.getOperand(2).getReg();
  1840. unsigned CondCode = MI.getOperand(3).getImm();
  1841. bool NZCVKilled = MI.getOperand(4).isKill();
  1842. MachineBasicBlock *TrueBB = MF->CreateMachineBasicBlock(LLVM_BB);
  1843. MachineBasicBlock *EndBB = MF->CreateMachineBasicBlock(LLVM_BB);
  1844. MF->insert(It, TrueBB);
  1845. MF->insert(It, EndBB);
  1846. // Transfer rest of current basic-block to EndBB
  1847. EndBB->splice(EndBB->begin(), MBB, std::next(MachineBasicBlock::iterator(MI)),
  1848. MBB->end());
  1849. EndBB->transferSuccessorsAndUpdatePHIs(MBB);
  1850. BuildMI(MBB, DL, TII->get(AArch64::Bcc)).addImm(CondCode).addMBB(TrueBB);
  1851. BuildMI(MBB, DL, TII->get(AArch64::B)).addMBB(EndBB);
  1852. MBB->addSuccessor(TrueBB);
  1853. MBB->addSuccessor(EndBB);
  1854. // TrueBB falls through to the end.
  1855. TrueBB->addSuccessor(EndBB);
  1856. if (!NZCVKilled) {
  1857. TrueBB->addLiveIn(AArch64::NZCV);
  1858. EndBB->addLiveIn(AArch64::NZCV);
  1859. }
  1860. BuildMI(*EndBB, EndBB->begin(), DL, TII->get(AArch64::PHI), DestReg)
  1861. .addReg(IfTrueReg)
  1862. .addMBB(TrueBB)
  1863. .addReg(IfFalseReg)
  1864. .addMBB(MBB);
  1865. MI.eraseFromParent();
  1866. return EndBB;
  1867. }
  1868. MachineBasicBlock *AArch64TargetLowering::EmitLoweredCatchRet(
  1869. MachineInstr &MI, MachineBasicBlock *BB) const {
  1870. assert(!isAsynchronousEHPersonality(classifyEHPersonality(
  1871. BB->getParent()->getFunction().getPersonalityFn())) &&
  1872. "SEH does not use catchret!");
  1873. return BB;
  1874. }
  1875. MachineBasicBlock *AArch64TargetLowering::EmitInstrWithCustomInserter(
  1876. MachineInstr &MI, MachineBasicBlock *BB) const {
  1877. switch (MI.getOpcode()) {
  1878. default:
  1879. #ifndef NDEBUG
  1880. MI.dump();
  1881. #endif
  1882. llvm_unreachable("Unexpected instruction for custom inserter!");
  1883. case AArch64::F128CSEL:
  1884. return EmitF128CSEL(MI, BB);
  1885. case TargetOpcode::STACKMAP:
  1886. case TargetOpcode::PATCHPOINT:
  1887. case TargetOpcode::STATEPOINT:
  1888. return emitPatchPoint(MI, BB);
  1889. case AArch64::CATCHRET:
  1890. return EmitLoweredCatchRet(MI, BB);
  1891. }
  1892. }
  1893. //===----------------------------------------------------------------------===//
  1894. // AArch64 Lowering private implementation.
  1895. //===----------------------------------------------------------------------===//
  1896. //===----------------------------------------------------------------------===//
  1897. // Lowering Code
  1898. //===----------------------------------------------------------------------===//
  1899. /// changeIntCCToAArch64CC - Convert a DAG integer condition code to an AArch64
  1900. /// CC
  1901. static AArch64CC::CondCode changeIntCCToAArch64CC(ISD::CondCode CC) {
  1902. switch (CC) {
  1903. default:
  1904. llvm_unreachable("Unknown condition code!");
  1905. case ISD::SETNE:
  1906. return AArch64CC::NE;
  1907. case ISD::SETEQ:
  1908. return AArch64CC::EQ;
  1909. case ISD::SETGT:
  1910. return AArch64CC::GT;
  1911. case ISD::SETGE:
  1912. return AArch64CC::GE;
  1913. case ISD::SETLT:
  1914. return AArch64CC::LT;
  1915. case ISD::SETLE:
  1916. return AArch64CC::LE;
  1917. case ISD::SETUGT:
  1918. return AArch64CC::HI;
  1919. case ISD::SETUGE:
  1920. return AArch64CC::HS;
  1921. case ISD::SETULT:
  1922. return AArch64CC::LO;
  1923. case ISD::SETULE:
  1924. return AArch64CC::LS;
  1925. }
  1926. }
  1927. /// changeFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64 CC.
  1928. static void changeFPCCToAArch64CC(ISD::CondCode CC,
  1929. AArch64CC::CondCode &CondCode,
  1930. AArch64CC::CondCode &CondCode2) {
  1931. CondCode2 = AArch64CC::AL;
  1932. switch (CC) {
  1933. default:
  1934. llvm_unreachable("Unknown FP condition!");
  1935. case ISD::SETEQ:
  1936. case ISD::SETOEQ:
  1937. CondCode = AArch64CC::EQ;
  1938. break;
  1939. case ISD::SETGT:
  1940. case ISD::SETOGT:
  1941. CondCode = AArch64CC::GT;
  1942. break;
  1943. case ISD::SETGE:
  1944. case ISD::SETOGE:
  1945. CondCode = AArch64CC::GE;
  1946. break;
  1947. case ISD::SETOLT:
  1948. CondCode = AArch64CC::MI;
  1949. break;
  1950. case ISD::SETOLE:
  1951. CondCode = AArch64CC::LS;
  1952. break;
  1953. case ISD::SETONE:
  1954. CondCode = AArch64CC::MI;
  1955. CondCode2 = AArch64CC::GT;
  1956. break;
  1957. case ISD::SETO:
  1958. CondCode = AArch64CC::VC;
  1959. break;
  1960. case ISD::SETUO:
  1961. CondCode = AArch64CC::VS;
  1962. break;
  1963. case ISD::SETUEQ:
  1964. CondCode = AArch64CC::EQ;
  1965. CondCode2 = AArch64CC::VS;
  1966. break;
  1967. case ISD::SETUGT:
  1968. CondCode = AArch64CC::HI;
  1969. break;
  1970. case ISD::SETUGE:
  1971. CondCode = AArch64CC::PL;
  1972. break;
  1973. case ISD::SETLT:
  1974. case ISD::SETULT:
  1975. CondCode = AArch64CC::LT;
  1976. break;
  1977. case ISD::SETLE:
  1978. case ISD::SETULE:
  1979. CondCode = AArch64CC::LE;
  1980. break;
  1981. case ISD::SETNE:
  1982. case ISD::SETUNE:
  1983. CondCode = AArch64CC::NE;
  1984. break;
  1985. }
  1986. }
  1987. /// Convert a DAG fp condition code to an AArch64 CC.
  1988. /// This differs from changeFPCCToAArch64CC in that it returns cond codes that
  1989. /// should be AND'ed instead of OR'ed.
  1990. static void changeFPCCToANDAArch64CC(ISD::CondCode CC,
  1991. AArch64CC::CondCode &CondCode,
  1992. AArch64CC::CondCode &CondCode2) {
  1993. CondCode2 = AArch64CC::AL;
  1994. switch (CC) {
  1995. default:
  1996. changeFPCCToAArch64CC(CC, CondCode, CondCode2);
  1997. assert(CondCode2 == AArch64CC::AL);
  1998. break;
  1999. case ISD::SETONE:
  2000. // (a one b)
  2001. // == ((a olt b) || (a ogt b))
  2002. // == ((a ord b) && (a une b))
  2003. CondCode = AArch64CC::VC;
  2004. CondCode2 = AArch64CC::NE;
  2005. break;
  2006. case ISD::SETUEQ:
  2007. // (a ueq b)
  2008. // == ((a uno b) || (a oeq b))
  2009. // == ((a ule b) && (a uge b))
  2010. CondCode = AArch64CC::PL;
  2011. CondCode2 = AArch64CC::LE;
  2012. break;
  2013. }
  2014. }
  2015. /// changeVectorFPCCToAArch64CC - Convert a DAG fp condition code to an AArch64
  2016. /// CC usable with the vector instructions. Fewer operations are available
  2017. /// without a real NZCV register, so we have to use less efficient combinations
  2018. /// to get the same effect.
  2019. static void changeVectorFPCCToAArch64CC(ISD::CondCode CC,
  2020. AArch64CC::CondCode &CondCode,
  2021. AArch64CC::CondCode &CondCode2,
  2022. bool &Invert) {
  2023. Invert = false;
  2024. switch (CC) {
  2025. default:
  2026. // Mostly the scalar mappings work fine.
  2027. changeFPCCToAArch64CC(CC, CondCode, CondCode2);
  2028. break;
  2029. case ISD::SETUO:
  2030. Invert = true;
  2031. LLVM_FALLTHROUGH;
  2032. case ISD::SETO:
  2033. CondCode = AArch64CC::MI;
  2034. CondCode2 = AArch64CC::GE;
  2035. break;
  2036. case ISD::SETUEQ:
  2037. case ISD::SETULT:
  2038. case ISD::SETULE:
  2039. case ISD::SETUGT:
  2040. case ISD::SETUGE:
  2041. // All of the compare-mask comparisons are ordered, but we can switch
  2042. // between the two by a double inversion. E.g. ULE == !OGT.
  2043. Invert = true;
  2044. changeFPCCToAArch64CC(getSetCCInverse(CC, /* FP inverse */ MVT::f32),
  2045. CondCode, CondCode2);
  2046. break;
  2047. }
  2048. }
  2049. static bool isLegalArithImmed(uint64_t C) {
  2050. // Matches AArch64DAGToDAGISel::SelectArithImmed().
  2051. bool IsLegal = (C >> 12 == 0) || ((C & 0xFFFULL) == 0 && C >> 24 == 0);
  2052. LLVM_DEBUG(dbgs() << "Is imm " << C
  2053. << " legal: " << (IsLegal ? "yes\n" : "no\n"));
  2054. return IsLegal;
  2055. }
  2056. // Can a (CMP op1, (sub 0, op2) be turned into a CMN instruction on
  2057. // the grounds that "op1 - (-op2) == op1 + op2" ? Not always, the C and V flags
  2058. // can be set differently by this operation. It comes down to whether
  2059. // "SInt(~op2)+1 == SInt(~op2+1)" (and the same for UInt). If they are then
  2060. // everything is fine. If not then the optimization is wrong. Thus general
  2061. // comparisons are only valid if op2 != 0.
  2062. //
  2063. // So, finally, the only LLVM-native comparisons that don't mention C and V
  2064. // are SETEQ and SETNE. They're the only ones we can safely use CMN for in
  2065. // the absence of information about op2.
  2066. static bool isCMN(SDValue Op, ISD::CondCode CC) {
  2067. return Op.getOpcode() == ISD::SUB && isNullConstant(Op.getOperand(0)) &&
  2068. (CC == ISD::SETEQ || CC == ISD::SETNE);
  2069. }
  2070. static SDValue emitStrictFPComparison(SDValue LHS, SDValue RHS, const SDLoc &dl,
  2071. SelectionDAG &DAG, SDValue Chain,
  2072. bool IsSignaling) {
  2073. EVT VT = LHS.getValueType();
  2074. assert(VT != MVT::f128);
  2075. assert(VT != MVT::f16 && "Lowering of strict fp16 not yet implemented");
  2076. unsigned Opcode =
  2077. IsSignaling ? AArch64ISD::STRICT_FCMPE : AArch64ISD::STRICT_FCMP;
  2078. return DAG.getNode(Opcode, dl, {VT, MVT::Other}, {Chain, LHS, RHS});
  2079. }
  2080. static SDValue emitComparison(SDValue LHS, SDValue RHS, ISD::CondCode CC,
  2081. const SDLoc &dl, SelectionDAG &DAG) {
  2082. EVT VT = LHS.getValueType();
  2083. const bool FullFP16 =
  2084. static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
  2085. if (VT.isFloatingPoint()) {
  2086. assert(VT != MVT::f128);
  2087. if (VT == MVT::f16 && !FullFP16) {
  2088. LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
  2089. RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
  2090. VT = MVT::f32;
  2091. }
  2092. return DAG.getNode(AArch64ISD::FCMP, dl, VT, LHS, RHS);
  2093. }
  2094. // The CMP instruction is just an alias for SUBS, and representing it as
  2095. // SUBS means that it's possible to get CSE with subtract operations.
  2096. // A later phase can perform the optimization of setting the destination
  2097. // register to WZR/XZR if it ends up being unused.
  2098. unsigned Opcode = AArch64ISD::SUBS;
  2099. if (isCMN(RHS, CC)) {
  2100. // Can we combine a (CMP op1, (sub 0, op2) into a CMN instruction ?
  2101. Opcode = AArch64ISD::ADDS;
  2102. RHS = RHS.getOperand(1);
  2103. } else if (isCMN(LHS, CC)) {
  2104. // As we are looking for EQ/NE compares, the operands can be commuted ; can
  2105. // we combine a (CMP (sub 0, op1), op2) into a CMN instruction ?
  2106. Opcode = AArch64ISD::ADDS;
  2107. LHS = LHS.getOperand(1);
  2108. } else if (isNullConstant(RHS) && !isUnsignedIntSetCC(CC)) {
  2109. if (LHS.getOpcode() == ISD::AND) {
  2110. // Similarly, (CMP (and X, Y), 0) can be implemented with a TST
  2111. // (a.k.a. ANDS) except that the flags are only guaranteed to work for one
  2112. // of the signed comparisons.
  2113. const SDValue ANDSNode = DAG.getNode(AArch64ISD::ANDS, dl,
  2114. DAG.getVTList(VT, MVT_CC),
  2115. LHS.getOperand(0),
  2116. LHS.getOperand(1));
  2117. // Replace all users of (and X, Y) with newly generated (ands X, Y)
  2118. DAG.ReplaceAllUsesWith(LHS, ANDSNode);
  2119. return ANDSNode.getValue(1);
  2120. } else if (LHS.getOpcode() == AArch64ISD::ANDS) {
  2121. // Use result of ANDS
  2122. return LHS.getValue(1);
  2123. }
  2124. }
  2125. return DAG.getNode(Opcode, dl, DAG.getVTList(VT, MVT_CC), LHS, RHS)
  2126. .getValue(1);
  2127. }
  2128. /// \defgroup AArch64CCMP CMP;CCMP matching
  2129. ///
  2130. /// These functions deal with the formation of CMP;CCMP;... sequences.
  2131. /// The CCMP/CCMN/FCCMP/FCCMPE instructions allow the conditional execution of
  2132. /// a comparison. They set the NZCV flags to a predefined value if their
  2133. /// predicate is false. This allows to express arbitrary conjunctions, for
  2134. /// example "cmp 0 (and (setCA (cmp A)) (setCB (cmp B)))"
  2135. /// expressed as:
  2136. /// cmp A
  2137. /// ccmp B, inv(CB), CA
  2138. /// check for CB flags
  2139. ///
  2140. /// This naturally lets us implement chains of AND operations with SETCC
  2141. /// operands. And we can even implement some other situations by transforming
  2142. /// them:
  2143. /// - We can implement (NEG SETCC) i.e. negating a single comparison by
  2144. /// negating the flags used in a CCMP/FCCMP operations.
  2145. /// - We can negate the result of a whole chain of CMP/CCMP/FCCMP operations
  2146. /// by negating the flags we test for afterwards. i.e.
  2147. /// NEG (CMP CCMP CCCMP ...) can be implemented.
  2148. /// - Note that we can only ever negate all previously processed results.
  2149. /// What we can not implement by flipping the flags to test is a negation
  2150. /// of two sub-trees (because the negation affects all sub-trees emitted so
  2151. /// far, so the 2nd sub-tree we emit would also affect the first).
  2152. /// With those tools we can implement some OR operations:
  2153. /// - (OR (SETCC A) (SETCC B)) can be implemented via:
  2154. /// NEG (AND (NEG (SETCC A)) (NEG (SETCC B)))
  2155. /// - After transforming OR to NEG/AND combinations we may be able to use NEG
  2156. /// elimination rules from earlier to implement the whole thing as a
  2157. /// CCMP/FCCMP chain.
  2158. ///
  2159. /// As complete example:
  2160. /// or (or (setCA (cmp A)) (setCB (cmp B)))
  2161. /// (and (setCC (cmp C)) (setCD (cmp D)))"
  2162. /// can be reassociated to:
  2163. /// or (and (setCC (cmp C)) setCD (cmp D))
  2164. // (or (setCA (cmp A)) (setCB (cmp B)))
  2165. /// can be transformed to:
  2166. /// not (and (not (and (setCC (cmp C)) (setCD (cmp D))))
  2167. /// (and (not (setCA (cmp A)) (not (setCB (cmp B))))))"
  2168. /// which can be implemented as:
  2169. /// cmp C
  2170. /// ccmp D, inv(CD), CC
  2171. /// ccmp A, CA, inv(CD)
  2172. /// ccmp B, CB, inv(CA)
  2173. /// check for CB flags
  2174. ///
  2175. /// A counterexample is "or (and A B) (and C D)" which translates to
  2176. /// not (and (not (and (not A) (not B))) (not (and (not C) (not D)))), we
  2177. /// can only implement 1 of the inner (not) operations, but not both!
  2178. /// @{
  2179. /// Create a conditional comparison; Use CCMP, CCMN or FCCMP as appropriate.
  2180. static SDValue emitConditionalComparison(SDValue LHS, SDValue RHS,
  2181. ISD::CondCode CC, SDValue CCOp,
  2182. AArch64CC::CondCode Predicate,
  2183. AArch64CC::CondCode OutCC,
  2184. const SDLoc &DL, SelectionDAG &DAG) {
  2185. unsigned Opcode = 0;
  2186. const bool FullFP16 =
  2187. static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
  2188. if (LHS.getValueType().isFloatingPoint()) {
  2189. assert(LHS.getValueType() != MVT::f128);
  2190. if (LHS.getValueType() == MVT::f16 && !FullFP16) {
  2191. LHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, LHS);
  2192. RHS = DAG.getNode(ISD::FP_EXTEND, DL, MVT::f32, RHS);
  2193. }
  2194. Opcode = AArch64ISD::FCCMP;
  2195. } else if (RHS.getOpcode() == ISD::SUB) {
  2196. SDValue SubOp0 = RHS.getOperand(0);
  2197. if (isNullConstant(SubOp0) && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
  2198. // See emitComparison() on why we can only do this for SETEQ and SETNE.
  2199. Opcode = AArch64ISD::CCMN;
  2200. RHS = RHS.getOperand(1);
  2201. }
  2202. }
  2203. if (Opcode == 0)
  2204. Opcode = AArch64ISD::CCMP;
  2205. SDValue Condition = DAG.getConstant(Predicate, DL, MVT_CC);
  2206. AArch64CC::CondCode InvOutCC = AArch64CC::getInvertedCondCode(OutCC);
  2207. unsigned NZCV = AArch64CC::getNZCVToSatisfyCondCode(InvOutCC);
  2208. SDValue NZCVOp = DAG.getConstant(NZCV, DL, MVT::i32);
  2209. return DAG.getNode(Opcode, DL, MVT_CC, LHS, RHS, NZCVOp, Condition, CCOp);
  2210. }
  2211. /// Returns true if @p Val is a tree of AND/OR/SETCC operations that can be
  2212. /// expressed as a conjunction. See \ref AArch64CCMP.
  2213. /// \param CanNegate Set to true if we can negate the whole sub-tree just by
  2214. /// changing the conditions on the SETCC tests.
  2215. /// (this means we can call emitConjunctionRec() with
  2216. /// Negate==true on this sub-tree)
  2217. /// \param MustBeFirst Set to true if this subtree needs to be negated and we
  2218. /// cannot do the negation naturally. We are required to
  2219. /// emit the subtree first in this case.
  2220. /// \param WillNegate Is true if are called when the result of this
  2221. /// subexpression must be negated. This happens when the
  2222. /// outer expression is an OR. We can use this fact to know
  2223. /// that we have a double negation (or (or ...) ...) that
  2224. /// can be implemented for free.
  2225. static bool canEmitConjunction(const SDValue Val, bool &CanNegate,
  2226. bool &MustBeFirst, bool WillNegate,
  2227. unsigned Depth = 0) {
  2228. if (!Val.hasOneUse())
  2229. return false;
  2230. unsigned Opcode = Val->getOpcode();
  2231. if (Opcode == ISD::SETCC) {
  2232. if (Val->getOperand(0).getValueType() == MVT::f128)
  2233. return false;
  2234. CanNegate = true;
  2235. MustBeFirst = false;
  2236. return true;
  2237. }
  2238. // Protect against exponential runtime and stack overflow.
  2239. if (Depth > 6)
  2240. return false;
  2241. if (Opcode == ISD::AND || Opcode == ISD::OR) {
  2242. bool IsOR = Opcode == ISD::OR;
  2243. SDValue O0 = Val->getOperand(0);
  2244. SDValue O1 = Val->getOperand(1);
  2245. bool CanNegateL;
  2246. bool MustBeFirstL;
  2247. if (!canEmitConjunction(O0, CanNegateL, MustBeFirstL, IsOR, Depth+1))
  2248. return false;
  2249. bool CanNegateR;
  2250. bool MustBeFirstR;
  2251. if (!canEmitConjunction(O1, CanNegateR, MustBeFirstR, IsOR, Depth+1))
  2252. return false;
  2253. if (MustBeFirstL && MustBeFirstR)
  2254. return false;
  2255. if (IsOR) {
  2256. // For an OR expression we need to be able to naturally negate at least
  2257. // one side or we cannot do the transformation at all.
  2258. if (!CanNegateL && !CanNegateR)
  2259. return false;
  2260. // If we the result of the OR will be negated and we can naturally negate
  2261. // the leafs, then this sub-tree as a whole negates naturally.
  2262. CanNegate = WillNegate && CanNegateL && CanNegateR;
  2263. // If we cannot naturally negate the whole sub-tree, then this must be
  2264. // emitted first.
  2265. MustBeFirst = !CanNegate;
  2266. } else {
  2267. assert(Opcode == ISD::AND && "Must be OR or AND");
  2268. // We cannot naturally negate an AND operation.
  2269. CanNegate = false;
  2270. MustBeFirst = MustBeFirstL || MustBeFirstR;
  2271. }
  2272. return true;
  2273. }
  2274. return false;
  2275. }
  2276. /// Emit conjunction or disjunction tree with the CMP/FCMP followed by a chain
  2277. /// of CCMP/CFCMP ops. See @ref AArch64CCMP.
  2278. /// Tries to transform the given i1 producing node @p Val to a series compare
  2279. /// and conditional compare operations. @returns an NZCV flags producing node
  2280. /// and sets @p OutCC to the flags that should be tested or returns SDValue() if
  2281. /// transformation was not possible.
  2282. /// \p Negate is true if we want this sub-tree being negated just by changing
  2283. /// SETCC conditions.
  2284. static SDValue emitConjunctionRec(SelectionDAG &DAG, SDValue Val,
  2285. AArch64CC::CondCode &OutCC, bool Negate, SDValue CCOp,
  2286. AArch64CC::CondCode Predicate) {
  2287. // We're at a tree leaf, produce a conditional comparison operation.
  2288. unsigned Opcode = Val->getOpcode();
  2289. if (Opcode == ISD::SETCC) {
  2290. SDValue LHS = Val->getOperand(0);
  2291. SDValue RHS = Val->getOperand(1);
  2292. ISD::CondCode CC = cast<CondCodeSDNode>(Val->getOperand(2))->get();
  2293. bool isInteger = LHS.getValueType().isInteger();
  2294. if (Negate)
  2295. CC = getSetCCInverse(CC, LHS.getValueType());
  2296. SDLoc DL(Val);
  2297. // Determine OutCC and handle FP special case.
  2298. if (isInteger) {
  2299. OutCC = changeIntCCToAArch64CC(CC);
  2300. } else {
  2301. assert(LHS.getValueType().isFloatingPoint());
  2302. AArch64CC::CondCode ExtraCC;
  2303. changeFPCCToANDAArch64CC(CC, OutCC, ExtraCC);
  2304. // Some floating point conditions can't be tested with a single condition
  2305. // code. Construct an additional comparison in this case.
  2306. if (ExtraCC != AArch64CC::AL) {
  2307. SDValue ExtraCmp;
  2308. if (!CCOp.getNode())
  2309. ExtraCmp = emitComparison(LHS, RHS, CC, DL, DAG);
  2310. else
  2311. ExtraCmp = emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate,
  2312. ExtraCC, DL, DAG);
  2313. CCOp = ExtraCmp;
  2314. Predicate = ExtraCC;
  2315. }
  2316. }
  2317. // Produce a normal comparison if we are first in the chain
  2318. if (!CCOp)
  2319. return emitComparison(LHS, RHS, CC, DL, DAG);
  2320. // Otherwise produce a ccmp.
  2321. return emitConditionalComparison(LHS, RHS, CC, CCOp, Predicate, OutCC, DL,
  2322. DAG);
  2323. }
  2324. assert(Val->hasOneUse() && "Valid conjunction/disjunction tree");
  2325. bool IsOR = Opcode == ISD::OR;
  2326. SDValue LHS = Val->getOperand(0);
  2327. bool CanNegateL;
  2328. bool MustBeFirstL;
  2329. bool ValidL = canEmitConjunction(LHS, CanNegateL, MustBeFirstL, IsOR);
  2330. assert(ValidL && "Valid conjunction/disjunction tree");
  2331. (void)ValidL;
  2332. SDValue RHS = Val->getOperand(1);
  2333. bool CanNegateR;
  2334. bool MustBeFirstR;
  2335. bool ValidR = canEmitConjunction(RHS, CanNegateR, MustBeFirstR, IsOR);
  2336. assert(ValidR && "Valid conjunction/disjunction tree");
  2337. (void)ValidR;
  2338. // Swap sub-tree that must come first to the right side.
  2339. if (MustBeFirstL) {
  2340. assert(!MustBeFirstR && "Valid conjunction/disjunction tree");
  2341. std::swap(LHS, RHS);
  2342. std::swap(CanNegateL, CanNegateR);
  2343. std::swap(MustBeFirstL, MustBeFirstR);
  2344. }
  2345. bool NegateR;
  2346. bool NegateAfterR;
  2347. bool NegateL;
  2348. bool NegateAfterAll;
  2349. if (Opcode == ISD::OR) {
  2350. // Swap the sub-tree that we can negate naturally to the left.
  2351. if (!CanNegateL) {
  2352. assert(CanNegateR && "at least one side must be negatable");
  2353. assert(!MustBeFirstR && "invalid conjunction/disjunction tree");
  2354. assert(!Negate);
  2355. std::swap(LHS, RHS);
  2356. NegateR = false;
  2357. NegateAfterR = true;
  2358. } else {
  2359. // Negate the left sub-tree if possible, otherwise negate the result.
  2360. NegateR = CanNegateR;
  2361. NegateAfterR = !CanNegateR;
  2362. }
  2363. NegateL = true;
  2364. NegateAfterAll = !Negate;
  2365. } else {
  2366. assert(Opcode == ISD::AND && "Valid conjunction/disjunction tree");
  2367. assert(!Negate && "Valid conjunction/disjunction tree");
  2368. NegateL = false;
  2369. NegateR = false;
  2370. NegateAfterR = false;
  2371. NegateAfterAll = false;
  2372. }
  2373. // Emit sub-trees.
  2374. AArch64CC::CondCode RHSCC;
  2375. SDValue CmpR = emitConjunctionRec(DAG, RHS, RHSCC, NegateR, CCOp, Predicate);
  2376. if (NegateAfterR)
  2377. RHSCC = AArch64CC::getInvertedCondCode(RHSCC);
  2378. SDValue CmpL = emitConjunctionRec(DAG, LHS, OutCC, NegateL, CmpR, RHSCC);
  2379. if (NegateAfterAll)
  2380. OutCC = AArch64CC::getInvertedCondCode(OutCC);
  2381. return CmpL;
  2382. }
  2383. /// Emit expression as a conjunction (a series of CCMP/CFCMP ops).
  2384. /// In some cases this is even possible with OR operations in the expression.
  2385. /// See \ref AArch64CCMP.
  2386. /// \see emitConjunctionRec().
  2387. static SDValue emitConjunction(SelectionDAG &DAG, SDValue Val,
  2388. AArch64CC::CondCode &OutCC) {
  2389. bool DummyCanNegate;
  2390. bool DummyMustBeFirst;
  2391. if (!canEmitConjunction(Val, DummyCanNegate, DummyMustBeFirst, false))
  2392. return SDValue();
  2393. return emitConjunctionRec(DAG, Val, OutCC, false, SDValue(), AArch64CC::AL);
  2394. }
  2395. /// @}
  2396. /// Returns how profitable it is to fold a comparison's operand's shift and/or
  2397. /// extension operations.
  2398. static unsigned getCmpOperandFoldingProfit(SDValue Op) {
  2399. auto isSupportedExtend = [&](SDValue V) {
  2400. if (V.getOpcode() == ISD::SIGN_EXTEND_INREG)
  2401. return true;
  2402. if (V.getOpcode() == ISD::AND)
  2403. if (ConstantSDNode *MaskCst = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
  2404. uint64_t Mask = MaskCst->getZExtValue();
  2405. return (Mask == 0xFF || Mask == 0xFFFF || Mask == 0xFFFFFFFF);
  2406. }
  2407. return false;
  2408. };
  2409. if (!Op.hasOneUse())
  2410. return 0;
  2411. if (isSupportedExtend(Op))
  2412. return 1;
  2413. unsigned Opc = Op.getOpcode();
  2414. if (Opc == ISD::SHL || Opc == ISD::SRL || Opc == ISD::SRA)
  2415. if (ConstantSDNode *ShiftCst = dyn_cast<ConstantSDNode>(Op.getOperand(1))) {
  2416. uint64_t Shift = ShiftCst->getZExtValue();
  2417. if (isSupportedExtend(Op.getOperand(0)))
  2418. return (Shift <= 4) ? 2 : 1;
  2419. EVT VT = Op.getValueType();
  2420. if ((VT == MVT::i32 && Shift <= 31) || (VT == MVT::i64 && Shift <= 63))
  2421. return 1;
  2422. }
  2423. return 0;
  2424. }
  2425. static SDValue getAArch64Cmp(SDValue LHS, SDValue RHS, ISD::CondCode CC,
  2426. SDValue &AArch64cc, SelectionDAG &DAG,
  2427. const SDLoc &dl) {
  2428. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS.getNode())) {
  2429. EVT VT = RHS.getValueType();
  2430. uint64_t C = RHSC->getZExtValue();
  2431. if (!isLegalArithImmed(C)) {
  2432. // Constant does not fit, try adjusting it by one?
  2433. switch (CC) {
  2434. default:
  2435. break;
  2436. case ISD::SETLT:
  2437. case ISD::SETGE:
  2438. if ((VT == MVT::i32 && C != 0x80000000 &&
  2439. isLegalArithImmed((uint32_t)(C - 1))) ||
  2440. (VT == MVT::i64 && C != 0x80000000ULL &&
  2441. isLegalArithImmed(C - 1ULL))) {
  2442. CC = (CC == ISD::SETLT) ? ISD::SETLE : ISD::SETGT;
  2443. C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
  2444. RHS = DAG.getConstant(C, dl, VT);
  2445. }
  2446. break;
  2447. case ISD::SETULT:
  2448. case ISD::SETUGE:
  2449. if ((VT == MVT::i32 && C != 0 &&
  2450. isLegalArithImmed((uint32_t)(C - 1))) ||
  2451. (VT == MVT::i64 && C != 0ULL && isLegalArithImmed(C - 1ULL))) {
  2452. CC = (CC == ISD::SETULT) ? ISD::SETULE : ISD::SETUGT;
  2453. C = (VT == MVT::i32) ? (uint32_t)(C - 1) : C - 1;
  2454. RHS = DAG.getConstant(C, dl, VT);
  2455. }
  2456. break;
  2457. case ISD::SETLE:
  2458. case ISD::SETGT:
  2459. if ((VT == MVT::i32 && C != INT32_MAX &&
  2460. isLegalArithImmed((uint32_t)(C + 1))) ||
  2461. (VT == MVT::i64 && C != INT64_MAX &&
  2462. isLegalArithImmed(C + 1ULL))) {
  2463. CC = (CC == ISD::SETLE) ? ISD::SETLT : ISD::SETGE;
  2464. C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
  2465. RHS = DAG.getConstant(C, dl, VT);
  2466. }
  2467. break;
  2468. case ISD::SETULE:
  2469. case ISD::SETUGT:
  2470. if ((VT == MVT::i32 && C != UINT32_MAX &&
  2471. isLegalArithImmed((uint32_t)(C + 1))) ||
  2472. (VT == MVT::i64 && C != UINT64_MAX &&
  2473. isLegalArithImmed(C + 1ULL))) {
  2474. CC = (CC == ISD::SETULE) ? ISD::SETULT : ISD::SETUGE;
  2475. C = (VT == MVT::i32) ? (uint32_t)(C + 1) : C + 1;
  2476. RHS = DAG.getConstant(C, dl, VT);
  2477. }
  2478. break;
  2479. }
  2480. }
  2481. }
  2482. // Comparisons are canonicalized so that the RHS operand is simpler than the
  2483. // LHS one, the extreme case being when RHS is an immediate. However, AArch64
  2484. // can fold some shift+extend operations on the RHS operand, so swap the
  2485. // operands if that can be done.
  2486. //
  2487. // For example:
  2488. // lsl w13, w11, #1
  2489. // cmp w13, w12
  2490. // can be turned into:
  2491. // cmp w12, w11, lsl #1
  2492. if (!isa<ConstantSDNode>(RHS) ||
  2493. !isLegalArithImmed(cast<ConstantSDNode>(RHS)->getZExtValue())) {
  2494. SDValue TheLHS = isCMN(LHS, CC) ? LHS.getOperand(1) : LHS;
  2495. if (getCmpOperandFoldingProfit(TheLHS) > getCmpOperandFoldingProfit(RHS)) {
  2496. std::swap(LHS, RHS);
  2497. CC = ISD::getSetCCSwappedOperands(CC);
  2498. }
  2499. }
  2500. SDValue Cmp;
  2501. AArch64CC::CondCode AArch64CC;
  2502. if ((CC == ISD::SETEQ || CC == ISD::SETNE) && isa<ConstantSDNode>(RHS)) {
  2503. const ConstantSDNode *RHSC = cast<ConstantSDNode>(RHS);
  2504. // The imm operand of ADDS is an unsigned immediate, in the range 0 to 4095.
  2505. // For the i8 operand, the largest immediate is 255, so this can be easily
  2506. // encoded in the compare instruction. For the i16 operand, however, the
  2507. // largest immediate cannot be encoded in the compare.
  2508. // Therefore, use a sign extending load and cmn to avoid materializing the
  2509. // -1 constant. For example,
  2510. // movz w1, #65535
  2511. // ldrh w0, [x0, #0]
  2512. // cmp w0, w1
  2513. // >
  2514. // ldrsh w0, [x0, #0]
  2515. // cmn w0, #1
  2516. // Fundamental, we're relying on the property that (zext LHS) == (zext RHS)
  2517. // if and only if (sext LHS) == (sext RHS). The checks are in place to
  2518. // ensure both the LHS and RHS are truly zero extended and to make sure the
  2519. // transformation is profitable.
  2520. if ((RHSC->getZExtValue() >> 16 == 0) && isa<LoadSDNode>(LHS) &&
  2521. cast<LoadSDNode>(LHS)->getExtensionType() == ISD::ZEXTLOAD &&
  2522. cast<LoadSDNode>(LHS)->getMemoryVT() == MVT::i16 &&
  2523. LHS.getNode()->hasNUsesOfValue(1, 0)) {
  2524. int16_t ValueofRHS = cast<ConstantSDNode>(RHS)->getZExtValue();
  2525. if (ValueofRHS < 0 && isLegalArithImmed(-ValueofRHS)) {
  2526. SDValue SExt =
  2527. DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, LHS.getValueType(), LHS,
  2528. DAG.getValueType(MVT::i16));
  2529. Cmp = emitComparison(SExt, DAG.getConstant(ValueofRHS, dl,
  2530. RHS.getValueType()),
  2531. CC, dl, DAG);
  2532. AArch64CC = changeIntCCToAArch64CC(CC);
  2533. }
  2534. }
  2535. if (!Cmp && (RHSC->isNullValue() || RHSC->isOne())) {
  2536. if ((Cmp = emitConjunction(DAG, LHS, AArch64CC))) {
  2537. if ((CC == ISD::SETNE) ^ RHSC->isNullValue())
  2538. AArch64CC = AArch64CC::getInvertedCondCode(AArch64CC);
  2539. }
  2540. }
  2541. }
  2542. if (!Cmp) {
  2543. Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
  2544. AArch64CC = changeIntCCToAArch64CC(CC);
  2545. }
  2546. AArch64cc = DAG.getConstant(AArch64CC, dl, MVT_CC);
  2547. return Cmp;
  2548. }
  2549. static std::pair<SDValue, SDValue>
  2550. getAArch64XALUOOp(AArch64CC::CondCode &CC, SDValue Op, SelectionDAG &DAG) {
  2551. assert((Op.getValueType() == MVT::i32 || Op.getValueType() == MVT::i64) &&
  2552. "Unsupported value type");
  2553. SDValue Value, Overflow;
  2554. SDLoc DL(Op);
  2555. SDValue LHS = Op.getOperand(0);
  2556. SDValue RHS = Op.getOperand(1);
  2557. unsigned Opc = 0;
  2558. switch (Op.getOpcode()) {
  2559. default:
  2560. llvm_unreachable("Unknown overflow instruction!");
  2561. case ISD::SADDO:
  2562. Opc = AArch64ISD::ADDS;
  2563. CC = AArch64CC::VS;
  2564. break;
  2565. case ISD::UADDO:
  2566. Opc = AArch64ISD::ADDS;
  2567. CC = AArch64CC::HS;
  2568. break;
  2569. case ISD::SSUBO:
  2570. Opc = AArch64ISD::SUBS;
  2571. CC = AArch64CC::VS;
  2572. break;
  2573. case ISD::USUBO:
  2574. Opc = AArch64ISD::SUBS;
  2575. CC = AArch64CC::LO;
  2576. break;
  2577. // Multiply needs a little bit extra work.
  2578. case ISD::SMULO:
  2579. case ISD::UMULO: {
  2580. CC = AArch64CC::NE;
  2581. bool IsSigned = Op.getOpcode() == ISD::SMULO;
  2582. if (Op.getValueType() == MVT::i32) {
  2583. unsigned ExtendOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  2584. // For a 32 bit multiply with overflow check we want the instruction
  2585. // selector to generate a widening multiply (SMADDL/UMADDL). For that we
  2586. // need to generate the following pattern:
  2587. // (i64 add 0, (i64 mul (i64 sext|zext i32 %a), (i64 sext|zext i32 %b))
  2588. LHS = DAG.getNode(ExtendOpc, DL, MVT::i64, LHS);
  2589. RHS = DAG.getNode(ExtendOpc, DL, MVT::i64, RHS);
  2590. SDValue Mul = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
  2591. SDValue Add = DAG.getNode(ISD::ADD, DL, MVT::i64, Mul,
  2592. DAG.getConstant(0, DL, MVT::i64));
  2593. // On AArch64 the upper 32 bits are always zero extended for a 32 bit
  2594. // operation. We need to clear out the upper 32 bits, because we used a
  2595. // widening multiply that wrote all 64 bits. In the end this should be a
  2596. // noop.
  2597. Value = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, Add);
  2598. if (IsSigned) {
  2599. // The signed overflow check requires more than just a simple check for
  2600. // any bit set in the upper 32 bits of the result. These bits could be
  2601. // just the sign bits of a negative number. To perform the overflow
  2602. // check we have to arithmetic shift right the 32nd bit of the result by
  2603. // 31 bits. Then we compare the result to the upper 32 bits.
  2604. SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Add,
  2605. DAG.getConstant(32, DL, MVT::i64));
  2606. UpperBits = DAG.getNode(ISD::TRUNCATE, DL, MVT::i32, UpperBits);
  2607. SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i32, Value,
  2608. DAG.getConstant(31, DL, MVT::i64));
  2609. // It is important that LowerBits is last, otherwise the arithmetic
  2610. // shift will not be folded into the compare (SUBS).
  2611. SDVTList VTs = DAG.getVTList(MVT::i32, MVT::i32);
  2612. Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
  2613. .getValue(1);
  2614. } else {
  2615. // The overflow check for unsigned multiply is easy. We only need to
  2616. // check if any of the upper 32 bits are set. This can be done with a
  2617. // CMP (shifted register). For that we need to generate the following
  2618. // pattern:
  2619. // (i64 AArch64ISD::SUBS i64 0, (i64 srl i64 %Mul, i64 32)
  2620. SDValue UpperBits = DAG.getNode(ISD::SRL, DL, MVT::i64, Mul,
  2621. DAG.getConstant(32, DL, MVT::i64));
  2622. SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
  2623. Overflow =
  2624. DAG.getNode(AArch64ISD::SUBS, DL, VTs,
  2625. DAG.getConstant(0, DL, MVT::i64),
  2626. UpperBits).getValue(1);
  2627. }
  2628. break;
  2629. }
  2630. assert(Op.getValueType() == MVT::i64 && "Expected an i64 value type");
  2631. // For the 64 bit multiply
  2632. Value = DAG.getNode(ISD::MUL, DL, MVT::i64, LHS, RHS);
  2633. if (IsSigned) {
  2634. SDValue UpperBits = DAG.getNode(ISD::MULHS, DL, MVT::i64, LHS, RHS);
  2635. SDValue LowerBits = DAG.getNode(ISD::SRA, DL, MVT::i64, Value,
  2636. DAG.getConstant(63, DL, MVT::i64));
  2637. // It is important that LowerBits is last, otherwise the arithmetic
  2638. // shift will not be folded into the compare (SUBS).
  2639. SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
  2640. Overflow = DAG.getNode(AArch64ISD::SUBS, DL, VTs, UpperBits, LowerBits)
  2641. .getValue(1);
  2642. } else {
  2643. SDValue UpperBits = DAG.getNode(ISD::MULHU, DL, MVT::i64, LHS, RHS);
  2644. SDVTList VTs = DAG.getVTList(MVT::i64, MVT::i32);
  2645. Overflow =
  2646. DAG.getNode(AArch64ISD::SUBS, DL, VTs,
  2647. DAG.getConstant(0, DL, MVT::i64),
  2648. UpperBits).getValue(1);
  2649. }
  2650. break;
  2651. }
  2652. } // switch (...)
  2653. if (Opc) {
  2654. SDVTList VTs = DAG.getVTList(Op->getValueType(0), MVT::i32);
  2655. // Emit the AArch64 operation with overflow check.
  2656. Value = DAG.getNode(Opc, DL, VTs, LHS, RHS);
  2657. Overflow = Value.getValue(1);
  2658. }
  2659. return std::make_pair(Value, Overflow);
  2660. }
  2661. SDValue AArch64TargetLowering::LowerXOR(SDValue Op, SelectionDAG &DAG) const {
  2662. if (useSVEForFixedLengthVectorVT(Op.getValueType()))
  2663. return LowerToScalableOp(Op, DAG);
  2664. SDValue Sel = Op.getOperand(0);
  2665. SDValue Other = Op.getOperand(1);
  2666. SDLoc dl(Sel);
  2667. // If the operand is an overflow checking operation, invert the condition
  2668. // code and kill the Not operation. I.e., transform:
  2669. // (xor (overflow_op_bool, 1))
  2670. // -->
  2671. // (csel 1, 0, invert(cc), overflow_op_bool)
  2672. // ... which later gets transformed to just a cset instruction with an
  2673. // inverted condition code, rather than a cset + eor sequence.
  2674. if (isOneConstant(Other) && ISD::isOverflowIntrOpRes(Sel)) {
  2675. // Only lower legal XALUO ops.
  2676. if (!DAG.getTargetLoweringInfo().isTypeLegal(Sel->getValueType(0)))
  2677. return SDValue();
  2678. SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
  2679. SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
  2680. AArch64CC::CondCode CC;
  2681. SDValue Value, Overflow;
  2682. std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Sel.getValue(0), DAG);
  2683. SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
  2684. return DAG.getNode(AArch64ISD::CSEL, dl, Op.getValueType(), TVal, FVal,
  2685. CCVal, Overflow);
  2686. }
  2687. // If neither operand is a SELECT_CC, give up.
  2688. if (Sel.getOpcode() != ISD::SELECT_CC)
  2689. std::swap(Sel, Other);
  2690. if (Sel.getOpcode() != ISD::SELECT_CC)
  2691. return Op;
  2692. // The folding we want to perform is:
  2693. // (xor x, (select_cc a, b, cc, 0, -1) )
  2694. // -->
  2695. // (csel x, (xor x, -1), cc ...)
  2696. //
  2697. // The latter will get matched to a CSINV instruction.
  2698. ISD::CondCode CC = cast<CondCodeSDNode>(Sel.getOperand(4))->get();
  2699. SDValue LHS = Sel.getOperand(0);
  2700. SDValue RHS = Sel.getOperand(1);
  2701. SDValue TVal = Sel.getOperand(2);
  2702. SDValue FVal = Sel.getOperand(3);
  2703. // FIXME: This could be generalized to non-integer comparisons.
  2704. if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
  2705. return Op;
  2706. ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
  2707. ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
  2708. // The values aren't constants, this isn't the pattern we're looking for.
  2709. if (!CFVal || !CTVal)
  2710. return Op;
  2711. // We can commute the SELECT_CC by inverting the condition. This
  2712. // might be needed to make this fit into a CSINV pattern.
  2713. if (CTVal->isAllOnesValue() && CFVal->isNullValue()) {
  2714. std::swap(TVal, FVal);
  2715. std::swap(CTVal, CFVal);
  2716. CC = ISD::getSetCCInverse(CC, LHS.getValueType());
  2717. }
  2718. // If the constants line up, perform the transform!
  2719. if (CTVal->isNullValue() && CFVal->isAllOnesValue()) {
  2720. SDValue CCVal;
  2721. SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
  2722. FVal = Other;
  2723. TVal = DAG.getNode(ISD::XOR, dl, Other.getValueType(), Other,
  2724. DAG.getConstant(-1ULL, dl, Other.getValueType()));
  2725. return DAG.getNode(AArch64ISD::CSEL, dl, Sel.getValueType(), FVal, TVal,
  2726. CCVal, Cmp);
  2727. }
  2728. return Op;
  2729. }
  2730. static SDValue LowerADDC_ADDE_SUBC_SUBE(SDValue Op, SelectionDAG &DAG) {
  2731. EVT VT = Op.getValueType();
  2732. // Let legalize expand this if it isn't a legal type yet.
  2733. if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
  2734. return SDValue();
  2735. SDVTList VTs = DAG.getVTList(VT, MVT::i32);
  2736. unsigned Opc;
  2737. bool ExtraOp = false;
  2738. switch (Op.getOpcode()) {
  2739. default:
  2740. llvm_unreachable("Invalid code");
  2741. case ISD::ADDC:
  2742. Opc = AArch64ISD::ADDS;
  2743. break;
  2744. case ISD::SUBC:
  2745. Opc = AArch64ISD::SUBS;
  2746. break;
  2747. case ISD::ADDE:
  2748. Opc = AArch64ISD::ADCS;
  2749. ExtraOp = true;
  2750. break;
  2751. case ISD::SUBE:
  2752. Opc = AArch64ISD::SBCS;
  2753. ExtraOp = true;
  2754. break;
  2755. }
  2756. if (!ExtraOp)
  2757. return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1));
  2758. return DAG.getNode(Opc, SDLoc(Op), VTs, Op.getOperand(0), Op.getOperand(1),
  2759. Op.getOperand(2));
  2760. }
  2761. static SDValue LowerXALUO(SDValue Op, SelectionDAG &DAG) {
  2762. // Let legalize expand this if it isn't a legal type yet.
  2763. if (!DAG.getTargetLoweringInfo().isTypeLegal(Op.getValueType()))
  2764. return SDValue();
  2765. SDLoc dl(Op);
  2766. AArch64CC::CondCode CC;
  2767. // The actual operation that sets the overflow or carry flag.
  2768. SDValue Value, Overflow;
  2769. std::tie(Value, Overflow) = getAArch64XALUOOp(CC, Op, DAG);
  2770. // We use 0 and 1 as false and true values.
  2771. SDValue TVal = DAG.getConstant(1, dl, MVT::i32);
  2772. SDValue FVal = DAG.getConstant(0, dl, MVT::i32);
  2773. // We use an inverted condition, because the conditional select is inverted
  2774. // too. This will allow it to be selected to a single instruction:
  2775. // CSINC Wd, WZR, WZR, invert(cond).
  2776. SDValue CCVal = DAG.getConstant(getInvertedCondCode(CC), dl, MVT::i32);
  2777. Overflow = DAG.getNode(AArch64ISD::CSEL, dl, MVT::i32, FVal, TVal,
  2778. CCVal, Overflow);
  2779. SDVTList VTs = DAG.getVTList(Op.getValueType(), MVT::i32);
  2780. return DAG.getNode(ISD::MERGE_VALUES, dl, VTs, Value, Overflow);
  2781. }
  2782. // Prefetch operands are:
  2783. // 1: Address to prefetch
  2784. // 2: bool isWrite
  2785. // 3: int locality (0 = no locality ... 3 = extreme locality)
  2786. // 4: bool isDataCache
  2787. static SDValue LowerPREFETCH(SDValue Op, SelectionDAG &DAG) {
  2788. SDLoc DL(Op);
  2789. unsigned IsWrite = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
  2790. unsigned Locality = cast<ConstantSDNode>(Op.getOperand(3))->getZExtValue();
  2791. unsigned IsData = cast<ConstantSDNode>(Op.getOperand(4))->getZExtValue();
  2792. bool IsStream = !Locality;
  2793. // When the locality number is set
  2794. if (Locality) {
  2795. // The front-end should have filtered out the out-of-range values
  2796. assert(Locality <= 3 && "Prefetch locality out-of-range");
  2797. // The locality degree is the opposite of the cache speed.
  2798. // Put the number the other way around.
  2799. // The encoding starts at 0 for level 1
  2800. Locality = 3 - Locality;
  2801. }
  2802. // built the mask value encoding the expected behavior.
  2803. unsigned PrfOp = (IsWrite << 4) | // Load/Store bit
  2804. (!IsData << 3) | // IsDataCache bit
  2805. (Locality << 1) | // Cache level bits
  2806. (unsigned)IsStream; // Stream bit
  2807. return DAG.getNode(AArch64ISD::PREFETCH, DL, MVT::Other, Op.getOperand(0),
  2808. DAG.getConstant(PrfOp, DL, MVT::i32), Op.getOperand(1));
  2809. }
  2810. SDValue AArch64TargetLowering::LowerFP_EXTEND(SDValue Op,
  2811. SelectionDAG &DAG) const {
  2812. if (Op.getValueType().isScalableVector())
  2813. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_EXTEND_MERGE_PASSTHRU);
  2814. assert(Op.getValueType() == MVT::f128 && "Unexpected lowering");
  2815. return SDValue();
  2816. }
  2817. SDValue AArch64TargetLowering::LowerFP_ROUND(SDValue Op,
  2818. SelectionDAG &DAG) const {
  2819. if (Op.getValueType().isScalableVector())
  2820. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FP_ROUND_MERGE_PASSTHRU);
  2821. bool IsStrict = Op->isStrictFPOpcode();
  2822. SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
  2823. EVT SrcVT = SrcVal.getValueType();
  2824. if (SrcVT != MVT::f128) {
  2825. // Expand cases where the input is a vector bigger than NEON.
  2826. if (useSVEForFixedLengthVectorVT(SrcVT))
  2827. return SDValue();
  2828. // It's legal except when f128 is involved
  2829. return Op;
  2830. }
  2831. return SDValue();
  2832. }
  2833. SDValue AArch64TargetLowering::LowerVectorFP_TO_INT(SDValue Op,
  2834. SelectionDAG &DAG) const {
  2835. // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
  2836. // Any additional optimization in this function should be recorded
  2837. // in the cost tables.
  2838. EVT InVT = Op.getOperand(0).getValueType();
  2839. EVT VT = Op.getValueType();
  2840. if (VT.isScalableVector()) {
  2841. unsigned Opcode = Op.getOpcode() == ISD::FP_TO_UINT
  2842. ? AArch64ISD::FCVTZU_MERGE_PASSTHRU
  2843. : AArch64ISD::FCVTZS_MERGE_PASSTHRU;
  2844. return LowerToPredicatedOp(Op, DAG, Opcode);
  2845. }
  2846. unsigned NumElts = InVT.getVectorNumElements();
  2847. // f16 conversions are promoted to f32 when full fp16 is not supported.
  2848. if (InVT.getVectorElementType() == MVT::f16 &&
  2849. !Subtarget->hasFullFP16()) {
  2850. MVT NewVT = MVT::getVectorVT(MVT::f32, NumElts);
  2851. SDLoc dl(Op);
  2852. return DAG.getNode(
  2853. Op.getOpcode(), dl, Op.getValueType(),
  2854. DAG.getNode(ISD::FP_EXTEND, dl, NewVT, Op.getOperand(0)));
  2855. }
  2856. uint64_t VTSize = VT.getFixedSizeInBits();
  2857. uint64_t InVTSize = InVT.getFixedSizeInBits();
  2858. if (VTSize < InVTSize) {
  2859. SDLoc dl(Op);
  2860. SDValue Cv =
  2861. DAG.getNode(Op.getOpcode(), dl, InVT.changeVectorElementTypeToInteger(),
  2862. Op.getOperand(0));
  2863. return DAG.getNode(ISD::TRUNCATE, dl, VT, Cv);
  2864. }
  2865. if (VTSize > InVTSize) {
  2866. SDLoc dl(Op);
  2867. MVT ExtVT =
  2868. MVT::getVectorVT(MVT::getFloatingPointVT(VT.getScalarSizeInBits()),
  2869. VT.getVectorNumElements());
  2870. SDValue Ext = DAG.getNode(ISD::FP_EXTEND, dl, ExtVT, Op.getOperand(0));
  2871. return DAG.getNode(Op.getOpcode(), dl, VT, Ext);
  2872. }
  2873. // Type changing conversions are illegal.
  2874. return Op;
  2875. }
  2876. SDValue AArch64TargetLowering::LowerFP_TO_INT(SDValue Op,
  2877. SelectionDAG &DAG) const {
  2878. bool IsStrict = Op->isStrictFPOpcode();
  2879. SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
  2880. if (SrcVal.getValueType().isVector())
  2881. return LowerVectorFP_TO_INT(Op, DAG);
  2882. // f16 conversions are promoted to f32 when full fp16 is not supported.
  2883. if (SrcVal.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
  2884. assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
  2885. SDLoc dl(Op);
  2886. return DAG.getNode(
  2887. Op.getOpcode(), dl, Op.getValueType(),
  2888. DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, SrcVal));
  2889. }
  2890. if (SrcVal.getValueType() != MVT::f128) {
  2891. // It's legal except when f128 is involved
  2892. return Op;
  2893. }
  2894. return SDValue();
  2895. }
  2896. SDValue AArch64TargetLowering::LowerVectorINT_TO_FP(SDValue Op,
  2897. SelectionDAG &DAG) const {
  2898. // Warning: We maintain cost tables in AArch64TargetTransformInfo.cpp.
  2899. // Any additional optimization in this function should be recorded
  2900. // in the cost tables.
  2901. EVT VT = Op.getValueType();
  2902. SDLoc dl(Op);
  2903. SDValue In = Op.getOperand(0);
  2904. EVT InVT = In.getValueType();
  2905. unsigned Opc = Op.getOpcode();
  2906. bool IsSigned = Opc == ISD::SINT_TO_FP || Opc == ISD::STRICT_SINT_TO_FP;
  2907. if (VT.isScalableVector()) {
  2908. if (InVT.getVectorElementType() == MVT::i1) {
  2909. // We can't directly extend an SVE predicate; extend it first.
  2910. unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  2911. EVT CastVT = getPromotedVTForPredicate(InVT);
  2912. In = DAG.getNode(CastOpc, dl, CastVT, In);
  2913. return DAG.getNode(Opc, dl, VT, In);
  2914. }
  2915. unsigned Opcode = IsSigned ? AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU
  2916. : AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU;
  2917. return LowerToPredicatedOp(Op, DAG, Opcode);
  2918. }
  2919. uint64_t VTSize = VT.getFixedSizeInBits();
  2920. uint64_t InVTSize = InVT.getFixedSizeInBits();
  2921. if (VTSize < InVTSize) {
  2922. MVT CastVT =
  2923. MVT::getVectorVT(MVT::getFloatingPointVT(InVT.getScalarSizeInBits()),
  2924. InVT.getVectorNumElements());
  2925. In = DAG.getNode(Opc, dl, CastVT, In);
  2926. return DAG.getNode(ISD::FP_ROUND, dl, VT, In, DAG.getIntPtrConstant(0, dl));
  2927. }
  2928. if (VTSize > InVTSize) {
  2929. unsigned CastOpc = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  2930. EVT CastVT = VT.changeVectorElementTypeToInteger();
  2931. In = DAG.getNode(CastOpc, dl, CastVT, In);
  2932. return DAG.getNode(Opc, dl, VT, In);
  2933. }
  2934. return Op;
  2935. }
  2936. SDValue AArch64TargetLowering::LowerINT_TO_FP(SDValue Op,
  2937. SelectionDAG &DAG) const {
  2938. if (Op.getValueType().isVector())
  2939. return LowerVectorINT_TO_FP(Op, DAG);
  2940. bool IsStrict = Op->isStrictFPOpcode();
  2941. SDValue SrcVal = Op.getOperand(IsStrict ? 1 : 0);
  2942. // f16 conversions are promoted to f32 when full fp16 is not supported.
  2943. if (Op.getValueType() == MVT::f16 &&
  2944. !Subtarget->hasFullFP16()) {
  2945. assert(!IsStrict && "Lowering of strict fp16 not yet implemented");
  2946. SDLoc dl(Op);
  2947. return DAG.getNode(
  2948. ISD::FP_ROUND, dl, MVT::f16,
  2949. DAG.getNode(Op.getOpcode(), dl, MVT::f32, SrcVal),
  2950. DAG.getIntPtrConstant(0, dl));
  2951. }
  2952. // i128 conversions are libcalls.
  2953. if (SrcVal.getValueType() == MVT::i128)
  2954. return SDValue();
  2955. // Other conversions are legal, unless it's to the completely software-based
  2956. // fp128.
  2957. if (Op.getValueType() != MVT::f128)
  2958. return Op;
  2959. return SDValue();
  2960. }
  2961. SDValue AArch64TargetLowering::LowerFSINCOS(SDValue Op,
  2962. SelectionDAG &DAG) const {
  2963. // For iOS, we want to call an alternative entry point: __sincos_stret,
  2964. // which returns the values in two S / D registers.
  2965. SDLoc dl(Op);
  2966. SDValue Arg = Op.getOperand(0);
  2967. EVT ArgVT = Arg.getValueType();
  2968. Type *ArgTy = ArgVT.getTypeForEVT(*DAG.getContext());
  2969. ArgListTy Args;
  2970. ArgListEntry Entry;
  2971. Entry.Node = Arg;
  2972. Entry.Ty = ArgTy;
  2973. Entry.IsSExt = false;
  2974. Entry.IsZExt = false;
  2975. Args.push_back(Entry);
  2976. RTLIB::Libcall LC = ArgVT == MVT::f64 ? RTLIB::SINCOS_STRET_F64
  2977. : RTLIB::SINCOS_STRET_F32;
  2978. const char *LibcallName = getLibcallName(LC);
  2979. SDValue Callee =
  2980. DAG.getExternalSymbol(LibcallName, getPointerTy(DAG.getDataLayout()));
  2981. StructType *RetTy = StructType::get(ArgTy, ArgTy);
  2982. TargetLowering::CallLoweringInfo CLI(DAG);
  2983. CLI.setDebugLoc(dl)
  2984. .setChain(DAG.getEntryNode())
  2985. .setLibCallee(CallingConv::Fast, RetTy, Callee, std::move(Args));
  2986. std::pair<SDValue, SDValue> CallResult = LowerCallTo(CLI);
  2987. return CallResult.first;
  2988. }
  2989. static SDValue LowerBITCAST(SDValue Op, SelectionDAG &DAG) {
  2990. EVT OpVT = Op.getValueType();
  2991. if (OpVT != MVT::f16 && OpVT != MVT::bf16)
  2992. return SDValue();
  2993. assert(Op.getOperand(0).getValueType() == MVT::i16);
  2994. SDLoc DL(Op);
  2995. Op = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op.getOperand(0));
  2996. Op = DAG.getNode(ISD::BITCAST, DL, MVT::f32, Op);
  2997. return SDValue(
  2998. DAG.getMachineNode(TargetOpcode::EXTRACT_SUBREG, DL, OpVT, Op,
  2999. DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
  3000. 0);
  3001. }
  3002. static EVT getExtensionTo64Bits(const EVT &OrigVT) {
  3003. if (OrigVT.getSizeInBits() >= 64)
  3004. return OrigVT;
  3005. assert(OrigVT.isSimple() && "Expecting a simple value type");
  3006. MVT::SimpleValueType OrigSimpleTy = OrigVT.getSimpleVT().SimpleTy;
  3007. switch (OrigSimpleTy) {
  3008. default: llvm_unreachable("Unexpected Vector Type");
  3009. case MVT::v2i8:
  3010. case MVT::v2i16:
  3011. return MVT::v2i32;
  3012. case MVT::v4i8:
  3013. return MVT::v4i16;
  3014. }
  3015. }
  3016. static SDValue addRequiredExtensionForVectorMULL(SDValue N, SelectionDAG &DAG,
  3017. const EVT &OrigTy,
  3018. const EVT &ExtTy,
  3019. unsigned ExtOpcode) {
  3020. // The vector originally had a size of OrigTy. It was then extended to ExtTy.
  3021. // We expect the ExtTy to be 128-bits total. If the OrigTy is less than
  3022. // 64-bits we need to insert a new extension so that it will be 64-bits.
  3023. assert(ExtTy.is128BitVector() && "Unexpected extension size");
  3024. if (OrigTy.getSizeInBits() >= 64)
  3025. return N;
  3026. // Must extend size to at least 64 bits to be used as an operand for VMULL.
  3027. EVT NewVT = getExtensionTo64Bits(OrigTy);
  3028. return DAG.getNode(ExtOpcode, SDLoc(N), NewVT, N);
  3029. }
  3030. static bool isExtendedBUILD_VECTOR(SDNode *N, SelectionDAG &DAG,
  3031. bool isSigned) {
  3032. EVT VT = N->getValueType(0);
  3033. if (N->getOpcode() != ISD::BUILD_VECTOR)
  3034. return false;
  3035. for (const SDValue &Elt : N->op_values()) {
  3036. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Elt)) {
  3037. unsigned EltSize = VT.getScalarSizeInBits();
  3038. unsigned HalfSize = EltSize / 2;
  3039. if (isSigned) {
  3040. if (!isIntN(HalfSize, C->getSExtValue()))
  3041. return false;
  3042. } else {
  3043. if (!isUIntN(HalfSize, C->getZExtValue()))
  3044. return false;
  3045. }
  3046. continue;
  3047. }
  3048. return false;
  3049. }
  3050. return true;
  3051. }
  3052. static SDValue skipExtensionForVectorMULL(SDNode *N, SelectionDAG &DAG) {
  3053. if (N->getOpcode() == ISD::SIGN_EXTEND ||
  3054. N->getOpcode() == ISD::ZERO_EXTEND || N->getOpcode() == ISD::ANY_EXTEND)
  3055. return addRequiredExtensionForVectorMULL(N->getOperand(0), DAG,
  3056. N->getOperand(0)->getValueType(0),
  3057. N->getValueType(0),
  3058. N->getOpcode());
  3059. assert(N->getOpcode() == ISD::BUILD_VECTOR && "expected BUILD_VECTOR");
  3060. EVT VT = N->getValueType(0);
  3061. SDLoc dl(N);
  3062. unsigned EltSize = VT.getScalarSizeInBits() / 2;
  3063. unsigned NumElts = VT.getVectorNumElements();
  3064. MVT TruncVT = MVT::getIntegerVT(EltSize);
  3065. SmallVector<SDValue, 8> Ops;
  3066. for (unsigned i = 0; i != NumElts; ++i) {
  3067. ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(i));
  3068. const APInt &CInt = C->getAPIntValue();
  3069. // Element types smaller than 32 bits are not legal, so use i32 elements.
  3070. // The values are implicitly truncated so sext vs. zext doesn't matter.
  3071. Ops.push_back(DAG.getConstant(CInt.zextOrTrunc(32), dl, MVT::i32));
  3072. }
  3073. return DAG.getBuildVector(MVT::getVectorVT(TruncVT, NumElts), dl, Ops);
  3074. }
  3075. static bool isSignExtended(SDNode *N, SelectionDAG &DAG) {
  3076. return N->getOpcode() == ISD::SIGN_EXTEND ||
  3077. N->getOpcode() == ISD::ANY_EXTEND ||
  3078. isExtendedBUILD_VECTOR(N, DAG, true);
  3079. }
  3080. static bool isZeroExtended(SDNode *N, SelectionDAG &DAG) {
  3081. return N->getOpcode() == ISD::ZERO_EXTEND ||
  3082. N->getOpcode() == ISD::ANY_EXTEND ||
  3083. isExtendedBUILD_VECTOR(N, DAG, false);
  3084. }
  3085. static bool isAddSubSExt(SDNode *N, SelectionDAG &DAG) {
  3086. unsigned Opcode = N->getOpcode();
  3087. if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
  3088. SDNode *N0 = N->getOperand(0).getNode();
  3089. SDNode *N1 = N->getOperand(1).getNode();
  3090. return N0->hasOneUse() && N1->hasOneUse() &&
  3091. isSignExtended(N0, DAG) && isSignExtended(N1, DAG);
  3092. }
  3093. return false;
  3094. }
  3095. static bool isAddSubZExt(SDNode *N, SelectionDAG &DAG) {
  3096. unsigned Opcode = N->getOpcode();
  3097. if (Opcode == ISD::ADD || Opcode == ISD::SUB) {
  3098. SDNode *N0 = N->getOperand(0).getNode();
  3099. SDNode *N1 = N->getOperand(1).getNode();
  3100. return N0->hasOneUse() && N1->hasOneUse() &&
  3101. isZeroExtended(N0, DAG) && isZeroExtended(N1, DAG);
  3102. }
  3103. return false;
  3104. }
  3105. SDValue AArch64TargetLowering::LowerFLT_ROUNDS_(SDValue Op,
  3106. SelectionDAG &DAG) const {
  3107. // The rounding mode is in bits 23:22 of the FPSCR.
  3108. // The ARM rounding mode value to FLT_ROUNDS mapping is 0->1, 1->2, 2->3, 3->0
  3109. // The formula we use to implement this is (((FPSCR + 1 << 22) >> 22) & 3)
  3110. // so that the shift + and get folded into a bitfield extract.
  3111. SDLoc dl(Op);
  3112. SDValue Chain = Op.getOperand(0);
  3113. SDValue FPCR_64 = DAG.getNode(
  3114. ISD::INTRINSIC_W_CHAIN, dl, {MVT::i64, MVT::Other},
  3115. {Chain, DAG.getConstant(Intrinsic::aarch64_get_fpcr, dl, MVT::i64)});
  3116. Chain = FPCR_64.getValue(1);
  3117. SDValue FPCR_32 = DAG.getNode(ISD::TRUNCATE, dl, MVT::i32, FPCR_64);
  3118. SDValue FltRounds = DAG.getNode(ISD::ADD, dl, MVT::i32, FPCR_32,
  3119. DAG.getConstant(1U << 22, dl, MVT::i32));
  3120. SDValue RMODE = DAG.getNode(ISD::SRL, dl, MVT::i32, FltRounds,
  3121. DAG.getConstant(22, dl, MVT::i32));
  3122. SDValue AND = DAG.getNode(ISD::AND, dl, MVT::i32, RMODE,
  3123. DAG.getConstant(3, dl, MVT::i32));
  3124. return DAG.getMergeValues({AND, Chain}, dl);
  3125. }
  3126. SDValue AArch64TargetLowering::LowerMUL(SDValue Op, SelectionDAG &DAG) const {
  3127. EVT VT = Op.getValueType();
  3128. // If SVE is available then i64 vector multiplications can also be made legal.
  3129. bool OverrideNEON = VT == MVT::v2i64 || VT == MVT::v1i64;
  3130. if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT, OverrideNEON))
  3131. return LowerToPredicatedOp(Op, DAG, AArch64ISD::MUL_PRED, OverrideNEON);
  3132. // Multiplications are only custom-lowered for 128-bit vectors so that
  3133. // VMULL can be detected. Otherwise v2i64 multiplications are not legal.
  3134. assert(VT.is128BitVector() && VT.isInteger() &&
  3135. "unexpected type for custom-lowering ISD::MUL");
  3136. SDNode *N0 = Op.getOperand(0).getNode();
  3137. SDNode *N1 = Op.getOperand(1).getNode();
  3138. unsigned NewOpc = 0;
  3139. bool isMLA = false;
  3140. bool isN0SExt = isSignExtended(N0, DAG);
  3141. bool isN1SExt = isSignExtended(N1, DAG);
  3142. if (isN0SExt && isN1SExt)
  3143. NewOpc = AArch64ISD::SMULL;
  3144. else {
  3145. bool isN0ZExt = isZeroExtended(N0, DAG);
  3146. bool isN1ZExt = isZeroExtended(N1, DAG);
  3147. if (isN0ZExt && isN1ZExt)
  3148. NewOpc = AArch64ISD::UMULL;
  3149. else if (isN1SExt || isN1ZExt) {
  3150. // Look for (s/zext A + s/zext B) * (s/zext C). We want to turn these
  3151. // into (s/zext A * s/zext C) + (s/zext B * s/zext C)
  3152. if (isN1SExt && isAddSubSExt(N0, DAG)) {
  3153. NewOpc = AArch64ISD::SMULL;
  3154. isMLA = true;
  3155. } else if (isN1ZExt && isAddSubZExt(N0, DAG)) {
  3156. NewOpc = AArch64ISD::UMULL;
  3157. isMLA = true;
  3158. } else if (isN0ZExt && isAddSubZExt(N1, DAG)) {
  3159. std::swap(N0, N1);
  3160. NewOpc = AArch64ISD::UMULL;
  3161. isMLA = true;
  3162. }
  3163. }
  3164. if (!NewOpc) {
  3165. if (VT == MVT::v2i64)
  3166. // Fall through to expand this. It is not legal.
  3167. return SDValue();
  3168. else
  3169. // Other vector multiplications are legal.
  3170. return Op;
  3171. }
  3172. }
  3173. // Legalize to a S/UMULL instruction
  3174. SDLoc DL(Op);
  3175. SDValue Op0;
  3176. SDValue Op1 = skipExtensionForVectorMULL(N1, DAG);
  3177. if (!isMLA) {
  3178. Op0 = skipExtensionForVectorMULL(N0, DAG);
  3179. assert(Op0.getValueType().is64BitVector() &&
  3180. Op1.getValueType().is64BitVector() &&
  3181. "unexpected types for extended operands to VMULL");
  3182. return DAG.getNode(NewOpc, DL, VT, Op0, Op1);
  3183. }
  3184. // Optimizing (zext A + zext B) * C, to (S/UMULL A, C) + (S/UMULL B, C) during
  3185. // isel lowering to take advantage of no-stall back to back s/umul + s/umla.
  3186. // This is true for CPUs with accumulate forwarding such as Cortex-A53/A57
  3187. SDValue N00 = skipExtensionForVectorMULL(N0->getOperand(0).getNode(), DAG);
  3188. SDValue N01 = skipExtensionForVectorMULL(N0->getOperand(1).getNode(), DAG);
  3189. EVT Op1VT = Op1.getValueType();
  3190. return DAG.getNode(N0->getOpcode(), DL, VT,
  3191. DAG.getNode(NewOpc, DL, VT,
  3192. DAG.getNode(ISD::BITCAST, DL, Op1VT, N00), Op1),
  3193. DAG.getNode(NewOpc, DL, VT,
  3194. DAG.getNode(ISD::BITCAST, DL, Op1VT, N01), Op1));
  3195. }
  3196. static inline SDValue getPTrue(SelectionDAG &DAG, SDLoc DL, EVT VT,
  3197. int Pattern) {
  3198. return DAG.getNode(AArch64ISD::PTRUE, DL, VT,
  3199. DAG.getTargetConstant(Pattern, DL, MVT::i32));
  3200. }
  3201. SDValue AArch64TargetLowering::LowerINTRINSIC_WO_CHAIN(SDValue Op,
  3202. SelectionDAG &DAG) const {
  3203. unsigned IntNo = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  3204. SDLoc dl(Op);
  3205. switch (IntNo) {
  3206. default: return SDValue(); // Don't custom lower most intrinsics.
  3207. case Intrinsic::thread_pointer: {
  3208. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  3209. return DAG.getNode(AArch64ISD::THREAD_POINTER, dl, PtrVT);
  3210. }
  3211. case Intrinsic::aarch64_neon_abs: {
  3212. EVT Ty = Op.getValueType();
  3213. if (Ty == MVT::i64) {
  3214. SDValue Result = DAG.getNode(ISD::BITCAST, dl, MVT::v1i64,
  3215. Op.getOperand(1));
  3216. Result = DAG.getNode(ISD::ABS, dl, MVT::v1i64, Result);
  3217. return DAG.getNode(ISD::BITCAST, dl, MVT::i64, Result);
  3218. } else if (Ty.isVector() && Ty.isInteger() && isTypeLegal(Ty)) {
  3219. return DAG.getNode(ISD::ABS, dl, Ty, Op.getOperand(1));
  3220. } else {
  3221. report_fatal_error("Unexpected type for AArch64 NEON intrinic");
  3222. }
  3223. }
  3224. case Intrinsic::aarch64_neon_smax:
  3225. return DAG.getNode(ISD::SMAX, dl, Op.getValueType(),
  3226. Op.getOperand(1), Op.getOperand(2));
  3227. case Intrinsic::aarch64_neon_umax:
  3228. return DAG.getNode(ISD::UMAX, dl, Op.getValueType(),
  3229. Op.getOperand(1), Op.getOperand(2));
  3230. case Intrinsic::aarch64_neon_smin:
  3231. return DAG.getNode(ISD::SMIN, dl, Op.getValueType(),
  3232. Op.getOperand(1), Op.getOperand(2));
  3233. case Intrinsic::aarch64_neon_umin:
  3234. return DAG.getNode(ISD::UMIN, dl, Op.getValueType(),
  3235. Op.getOperand(1), Op.getOperand(2));
  3236. case Intrinsic::aarch64_sve_sunpkhi:
  3237. return DAG.getNode(AArch64ISD::SUNPKHI, dl, Op.getValueType(),
  3238. Op.getOperand(1));
  3239. case Intrinsic::aarch64_sve_sunpklo:
  3240. return DAG.getNode(AArch64ISD::SUNPKLO, dl, Op.getValueType(),
  3241. Op.getOperand(1));
  3242. case Intrinsic::aarch64_sve_uunpkhi:
  3243. return DAG.getNode(AArch64ISD::UUNPKHI, dl, Op.getValueType(),
  3244. Op.getOperand(1));
  3245. case Intrinsic::aarch64_sve_uunpklo:
  3246. return DAG.getNode(AArch64ISD::UUNPKLO, dl, Op.getValueType(),
  3247. Op.getOperand(1));
  3248. case Intrinsic::aarch64_sve_clasta_n:
  3249. return DAG.getNode(AArch64ISD::CLASTA_N, dl, Op.getValueType(),
  3250. Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
  3251. case Intrinsic::aarch64_sve_clastb_n:
  3252. return DAG.getNode(AArch64ISD::CLASTB_N, dl, Op.getValueType(),
  3253. Op.getOperand(1), Op.getOperand(2), Op.getOperand(3));
  3254. case Intrinsic::aarch64_sve_lasta:
  3255. return DAG.getNode(AArch64ISD::LASTA, dl, Op.getValueType(),
  3256. Op.getOperand(1), Op.getOperand(2));
  3257. case Intrinsic::aarch64_sve_lastb:
  3258. return DAG.getNode(AArch64ISD::LASTB, dl, Op.getValueType(),
  3259. Op.getOperand(1), Op.getOperand(2));
  3260. case Intrinsic::aarch64_sve_rev:
  3261. return DAG.getNode(AArch64ISD::REV, dl, Op.getValueType(),
  3262. Op.getOperand(1));
  3263. case Intrinsic::aarch64_sve_tbl:
  3264. return DAG.getNode(AArch64ISD::TBL, dl, Op.getValueType(),
  3265. Op.getOperand(1), Op.getOperand(2));
  3266. case Intrinsic::aarch64_sve_trn1:
  3267. return DAG.getNode(AArch64ISD::TRN1, dl, Op.getValueType(),
  3268. Op.getOperand(1), Op.getOperand(2));
  3269. case Intrinsic::aarch64_sve_trn2:
  3270. return DAG.getNode(AArch64ISD::TRN2, dl, Op.getValueType(),
  3271. Op.getOperand(1), Op.getOperand(2));
  3272. case Intrinsic::aarch64_sve_uzp1:
  3273. return DAG.getNode(AArch64ISD::UZP1, dl, Op.getValueType(),
  3274. Op.getOperand(1), Op.getOperand(2));
  3275. case Intrinsic::aarch64_sve_uzp2:
  3276. return DAG.getNode(AArch64ISD::UZP2, dl, Op.getValueType(),
  3277. Op.getOperand(1), Op.getOperand(2));
  3278. case Intrinsic::aarch64_sve_zip1:
  3279. return DAG.getNode(AArch64ISD::ZIP1, dl, Op.getValueType(),
  3280. Op.getOperand(1), Op.getOperand(2));
  3281. case Intrinsic::aarch64_sve_zip2:
  3282. return DAG.getNode(AArch64ISD::ZIP2, dl, Op.getValueType(),
  3283. Op.getOperand(1), Op.getOperand(2));
  3284. case Intrinsic::aarch64_sve_ptrue:
  3285. return DAG.getNode(AArch64ISD::PTRUE, dl, Op.getValueType(),
  3286. Op.getOperand(1));
  3287. case Intrinsic::aarch64_sve_clz:
  3288. return DAG.getNode(AArch64ISD::CTLZ_MERGE_PASSTHRU, dl, Op.getValueType(),
  3289. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3290. case Intrinsic::aarch64_sve_cnt: {
  3291. SDValue Data = Op.getOperand(3);
  3292. // CTPOP only supports integer operands.
  3293. if (Data.getValueType().isFloatingPoint())
  3294. Data = DAG.getNode(ISD::BITCAST, dl, Op.getValueType(), Data);
  3295. return DAG.getNode(AArch64ISD::CTPOP_MERGE_PASSTHRU, dl, Op.getValueType(),
  3296. Op.getOperand(2), Data, Op.getOperand(1));
  3297. }
  3298. case Intrinsic::aarch64_sve_dupq_lane:
  3299. return LowerDUPQLane(Op, DAG);
  3300. case Intrinsic::aarch64_sve_convert_from_svbool:
  3301. return DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, Op.getValueType(),
  3302. Op.getOperand(1));
  3303. case Intrinsic::aarch64_sve_fneg:
  3304. return DAG.getNode(AArch64ISD::FNEG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3305. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3306. case Intrinsic::aarch64_sve_frintp:
  3307. return DAG.getNode(AArch64ISD::FCEIL_MERGE_PASSTHRU, dl, Op.getValueType(),
  3308. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3309. case Intrinsic::aarch64_sve_frintm:
  3310. return DAG.getNode(AArch64ISD::FFLOOR_MERGE_PASSTHRU, dl, Op.getValueType(),
  3311. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3312. case Intrinsic::aarch64_sve_frinti:
  3313. return DAG.getNode(AArch64ISD::FNEARBYINT_MERGE_PASSTHRU, dl, Op.getValueType(),
  3314. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3315. case Intrinsic::aarch64_sve_frintx:
  3316. return DAG.getNode(AArch64ISD::FRINT_MERGE_PASSTHRU, dl, Op.getValueType(),
  3317. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3318. case Intrinsic::aarch64_sve_frinta:
  3319. return DAG.getNode(AArch64ISD::FROUND_MERGE_PASSTHRU, dl, Op.getValueType(),
  3320. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3321. case Intrinsic::aarch64_sve_frintn:
  3322. return DAG.getNode(AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU, dl, Op.getValueType(),
  3323. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3324. case Intrinsic::aarch64_sve_frintz:
  3325. return DAG.getNode(AArch64ISD::FTRUNC_MERGE_PASSTHRU, dl, Op.getValueType(),
  3326. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3327. case Intrinsic::aarch64_sve_ucvtf:
  3328. return DAG.getNode(AArch64ISD::UINT_TO_FP_MERGE_PASSTHRU, dl,
  3329. Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
  3330. Op.getOperand(1));
  3331. case Intrinsic::aarch64_sve_scvtf:
  3332. return DAG.getNode(AArch64ISD::SINT_TO_FP_MERGE_PASSTHRU, dl,
  3333. Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
  3334. Op.getOperand(1));
  3335. case Intrinsic::aarch64_sve_fcvtzu:
  3336. return DAG.getNode(AArch64ISD::FCVTZU_MERGE_PASSTHRU, dl,
  3337. Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
  3338. Op.getOperand(1));
  3339. case Intrinsic::aarch64_sve_fcvtzs:
  3340. return DAG.getNode(AArch64ISD::FCVTZS_MERGE_PASSTHRU, dl,
  3341. Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
  3342. Op.getOperand(1));
  3343. case Intrinsic::aarch64_sve_fsqrt:
  3344. return DAG.getNode(AArch64ISD::FSQRT_MERGE_PASSTHRU, dl, Op.getValueType(),
  3345. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3346. case Intrinsic::aarch64_sve_frecpx:
  3347. return DAG.getNode(AArch64ISD::FRECPX_MERGE_PASSTHRU, dl, Op.getValueType(),
  3348. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3349. case Intrinsic::aarch64_sve_fabs:
  3350. return DAG.getNode(AArch64ISD::FABS_MERGE_PASSTHRU, dl, Op.getValueType(),
  3351. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3352. case Intrinsic::aarch64_sve_abs:
  3353. return DAG.getNode(AArch64ISD::ABS_MERGE_PASSTHRU, dl, Op.getValueType(),
  3354. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3355. case Intrinsic::aarch64_sve_neg:
  3356. return DAG.getNode(AArch64ISD::NEG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3357. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3358. case Intrinsic::aarch64_sve_convert_to_svbool: {
  3359. EVT OutVT = Op.getValueType();
  3360. EVT InVT = Op.getOperand(1).getValueType();
  3361. // Return the operand if the cast isn't changing type,
  3362. // i.e. <n x 16 x i1> -> <n x 16 x i1>
  3363. if (InVT == OutVT)
  3364. return Op.getOperand(1);
  3365. // Otherwise, zero the newly introduced lanes.
  3366. SDValue Reinterpret =
  3367. DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Op.getOperand(1));
  3368. SDValue Mask = getPTrue(DAG, dl, InVT, AArch64SVEPredPattern::all);
  3369. SDValue MaskReinterpret =
  3370. DAG.getNode(AArch64ISD::REINTERPRET_CAST, dl, OutVT, Mask);
  3371. return DAG.getNode(ISD::AND, dl, OutVT, Reinterpret, MaskReinterpret);
  3372. }
  3373. case Intrinsic::aarch64_sve_insr: {
  3374. SDValue Scalar = Op.getOperand(2);
  3375. EVT ScalarTy = Scalar.getValueType();
  3376. if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
  3377. Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
  3378. return DAG.getNode(AArch64ISD::INSR, dl, Op.getValueType(),
  3379. Op.getOperand(1), Scalar);
  3380. }
  3381. case Intrinsic::aarch64_sve_rbit:
  3382. return DAG.getNode(AArch64ISD::BITREVERSE_MERGE_PASSTHRU, dl,
  3383. Op.getValueType(), Op.getOperand(2), Op.getOperand(3),
  3384. Op.getOperand(1));
  3385. case Intrinsic::aarch64_sve_revb:
  3386. return DAG.getNode(AArch64ISD::BSWAP_MERGE_PASSTHRU, dl, Op.getValueType(),
  3387. Op.getOperand(2), Op.getOperand(3), Op.getOperand(1));
  3388. case Intrinsic::aarch64_sve_sxtb:
  3389. return DAG.getNode(
  3390. AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3391. Op.getOperand(2), Op.getOperand(3),
  3392. DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
  3393. Op.getOperand(1));
  3394. case Intrinsic::aarch64_sve_sxth:
  3395. return DAG.getNode(
  3396. AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3397. Op.getOperand(2), Op.getOperand(3),
  3398. DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
  3399. Op.getOperand(1));
  3400. case Intrinsic::aarch64_sve_sxtw:
  3401. return DAG.getNode(
  3402. AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3403. Op.getOperand(2), Op.getOperand(3),
  3404. DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
  3405. Op.getOperand(1));
  3406. case Intrinsic::aarch64_sve_uxtb:
  3407. return DAG.getNode(
  3408. AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3409. Op.getOperand(2), Op.getOperand(3),
  3410. DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i8)),
  3411. Op.getOperand(1));
  3412. case Intrinsic::aarch64_sve_uxth:
  3413. return DAG.getNode(
  3414. AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3415. Op.getOperand(2), Op.getOperand(3),
  3416. DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i16)),
  3417. Op.getOperand(1));
  3418. case Intrinsic::aarch64_sve_uxtw:
  3419. return DAG.getNode(
  3420. AArch64ISD::ZERO_EXTEND_INREG_MERGE_PASSTHRU, dl, Op.getValueType(),
  3421. Op.getOperand(2), Op.getOperand(3),
  3422. DAG.getValueType(Op.getValueType().changeVectorElementType(MVT::i32)),
  3423. Op.getOperand(1));
  3424. case Intrinsic::localaddress: {
  3425. const auto &MF = DAG.getMachineFunction();
  3426. const auto *RegInfo = Subtarget->getRegisterInfo();
  3427. unsigned Reg = RegInfo->getLocalAddressRegister(MF);
  3428. return DAG.getCopyFromReg(DAG.getEntryNode(), dl, Reg,
  3429. Op.getSimpleValueType());
  3430. }
  3431. case Intrinsic::eh_recoverfp: {
  3432. // FIXME: This needs to be implemented to correctly handle highly aligned
  3433. // stack objects. For now we simply return the incoming FP. Refer D53541
  3434. // for more details.
  3435. SDValue FnOp = Op.getOperand(1);
  3436. SDValue IncomingFPOp = Op.getOperand(2);
  3437. GlobalAddressSDNode *GSD = dyn_cast<GlobalAddressSDNode>(FnOp);
  3438. auto *Fn = dyn_cast_or_null<Function>(GSD ? GSD->getGlobal() : nullptr);
  3439. if (!Fn)
  3440. report_fatal_error(
  3441. "llvm.eh.recoverfp must take a function as the first argument");
  3442. return IncomingFPOp;
  3443. }
  3444. case Intrinsic::aarch64_neon_vsri:
  3445. case Intrinsic::aarch64_neon_vsli: {
  3446. EVT Ty = Op.getValueType();
  3447. if (!Ty.isVector())
  3448. report_fatal_error("Unexpected type for aarch64_neon_vsli");
  3449. assert(Op.getConstantOperandVal(3) <= Ty.getScalarSizeInBits());
  3450. bool IsShiftRight = IntNo == Intrinsic::aarch64_neon_vsri;
  3451. unsigned Opcode = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
  3452. return DAG.getNode(Opcode, dl, Ty, Op.getOperand(1), Op.getOperand(2),
  3453. Op.getOperand(3));
  3454. }
  3455. case Intrinsic::aarch64_neon_srhadd:
  3456. case Intrinsic::aarch64_neon_urhadd:
  3457. case Intrinsic::aarch64_neon_shadd:
  3458. case Intrinsic::aarch64_neon_uhadd: {
  3459. bool IsSignedAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
  3460. IntNo == Intrinsic::aarch64_neon_shadd);
  3461. bool IsRoundingAdd = (IntNo == Intrinsic::aarch64_neon_srhadd ||
  3462. IntNo == Intrinsic::aarch64_neon_urhadd);
  3463. unsigned Opcode =
  3464. IsSignedAdd ? (IsRoundingAdd ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
  3465. : (IsRoundingAdd ? AArch64ISD::URHADD : AArch64ISD::UHADD);
  3466. return DAG.getNode(Opcode, dl, Op.getValueType(), Op.getOperand(1),
  3467. Op.getOperand(2));
  3468. }
  3469. case Intrinsic::aarch64_neon_uabd: {
  3470. return DAG.getNode(AArch64ISD::UABD, dl, Op.getValueType(),
  3471. Op.getOperand(1), Op.getOperand(2));
  3472. }
  3473. case Intrinsic::aarch64_neon_sabd: {
  3474. return DAG.getNode(AArch64ISD::SABD, dl, Op.getValueType(),
  3475. Op.getOperand(1), Op.getOperand(2));
  3476. }
  3477. }
  3478. }
  3479. bool AArch64TargetLowering::shouldRemoveExtendFromGSIndex(EVT VT) const {
  3480. if (VT.getVectorElementType() == MVT::i32 &&
  3481. VT.getVectorElementCount().getKnownMinValue() >= 4)
  3482. return true;
  3483. return false;
  3484. }
  3485. bool AArch64TargetLowering::isVectorLoadExtDesirable(SDValue ExtVal) const {
  3486. return ExtVal.getValueType().isScalableVector();
  3487. }
  3488. unsigned getGatherVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
  3489. std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
  3490. {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
  3491. AArch64ISD::GLD1_MERGE_ZERO},
  3492. {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
  3493. AArch64ISD::GLD1_UXTW_MERGE_ZERO},
  3494. {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
  3495. AArch64ISD::GLD1_MERGE_ZERO},
  3496. {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
  3497. AArch64ISD::GLD1_SXTW_MERGE_ZERO},
  3498. {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
  3499. AArch64ISD::GLD1_SCALED_MERGE_ZERO},
  3500. {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
  3501. AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO},
  3502. {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
  3503. AArch64ISD::GLD1_SCALED_MERGE_ZERO},
  3504. {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
  3505. AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO},
  3506. };
  3507. auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
  3508. return AddrModes.find(Key)->second;
  3509. }
  3510. unsigned getScatterVecOpcode(bool IsScaled, bool IsSigned, bool NeedsExtend) {
  3511. std::map<std::tuple<bool, bool, bool>, unsigned> AddrModes = {
  3512. {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ false),
  3513. AArch64ISD::SST1_PRED},
  3514. {std::make_tuple(/*Scaled*/ false, /*Signed*/ false, /*Extend*/ true),
  3515. AArch64ISD::SST1_UXTW_PRED},
  3516. {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ false),
  3517. AArch64ISD::SST1_PRED},
  3518. {std::make_tuple(/*Scaled*/ false, /*Signed*/ true, /*Extend*/ true),
  3519. AArch64ISD::SST1_SXTW_PRED},
  3520. {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ false),
  3521. AArch64ISD::SST1_SCALED_PRED},
  3522. {std::make_tuple(/*Scaled*/ true, /*Signed*/ false, /*Extend*/ true),
  3523. AArch64ISD::SST1_UXTW_SCALED_PRED},
  3524. {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ false),
  3525. AArch64ISD::SST1_SCALED_PRED},
  3526. {std::make_tuple(/*Scaled*/ true, /*Signed*/ true, /*Extend*/ true),
  3527. AArch64ISD::SST1_SXTW_SCALED_PRED},
  3528. };
  3529. auto Key = std::make_tuple(IsScaled, IsSigned, NeedsExtend);
  3530. return AddrModes.find(Key)->second;
  3531. }
  3532. unsigned getSignExtendedGatherOpcode(unsigned Opcode) {
  3533. switch (Opcode) {
  3534. default:
  3535. llvm_unreachable("unimplemented opcode");
  3536. return Opcode;
  3537. case AArch64ISD::GLD1_MERGE_ZERO:
  3538. return AArch64ISD::GLD1S_MERGE_ZERO;
  3539. case AArch64ISD::GLD1_IMM_MERGE_ZERO:
  3540. return AArch64ISD::GLD1S_IMM_MERGE_ZERO;
  3541. case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
  3542. return AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
  3543. case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
  3544. return AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
  3545. case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
  3546. return AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
  3547. case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
  3548. return AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
  3549. case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
  3550. return AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
  3551. }
  3552. }
  3553. bool getGatherScatterIndexIsExtended(SDValue Index) {
  3554. unsigned Opcode = Index.getOpcode();
  3555. if (Opcode == ISD::SIGN_EXTEND_INREG)
  3556. return true;
  3557. if (Opcode == ISD::AND) {
  3558. SDValue Splat = Index.getOperand(1);
  3559. if (Splat.getOpcode() != ISD::SPLAT_VECTOR)
  3560. return false;
  3561. ConstantSDNode *Mask = dyn_cast<ConstantSDNode>(Splat.getOperand(0));
  3562. if (!Mask || Mask->getZExtValue() != 0xFFFFFFFF)
  3563. return false;
  3564. return true;
  3565. }
  3566. return false;
  3567. }
  3568. // If the base pointer of a masked gather or scatter is null, we
  3569. // may be able to swap BasePtr & Index and use the vector + register
  3570. // or vector + immediate addressing mode, e.g.
  3571. // VECTOR + REGISTER:
  3572. // getelementptr nullptr, <vscale x N x T> (splat(%offset)) + %indices)
  3573. // -> getelementptr %offset, <vscale x N x T> %indices
  3574. // VECTOR + IMMEDIATE:
  3575. // getelementptr nullptr, <vscale x N x T> (splat(#x)) + %indices)
  3576. // -> getelementptr #x, <vscale x N x T> %indices
  3577. void selectGatherScatterAddrMode(SDValue &BasePtr, SDValue &Index, EVT MemVT,
  3578. unsigned &Opcode, bool IsGather,
  3579. SelectionDAG &DAG) {
  3580. if (!isNullConstant(BasePtr))
  3581. return;
  3582. ConstantSDNode *Offset = nullptr;
  3583. if (Index.getOpcode() == ISD::ADD)
  3584. if (auto SplatVal = DAG.getSplatValue(Index.getOperand(1))) {
  3585. if (isa<ConstantSDNode>(SplatVal))
  3586. Offset = cast<ConstantSDNode>(SplatVal);
  3587. else {
  3588. BasePtr = SplatVal;
  3589. Index = Index->getOperand(0);
  3590. return;
  3591. }
  3592. }
  3593. unsigned NewOp =
  3594. IsGather ? AArch64ISD::GLD1_IMM_MERGE_ZERO : AArch64ISD::SST1_IMM_PRED;
  3595. if (!Offset) {
  3596. std::swap(BasePtr, Index);
  3597. Opcode = NewOp;
  3598. return;
  3599. }
  3600. uint64_t OffsetVal = Offset->getZExtValue();
  3601. unsigned ScalarSizeInBytes = MemVT.getScalarSizeInBits() / 8;
  3602. auto ConstOffset = DAG.getConstant(OffsetVal, SDLoc(Index), MVT::i64);
  3603. if (OffsetVal % ScalarSizeInBytes || OffsetVal / ScalarSizeInBytes > 31) {
  3604. // Index is out of range for the immediate addressing mode
  3605. BasePtr = ConstOffset;
  3606. Index = Index->getOperand(0);
  3607. return;
  3608. }
  3609. // Immediate is in range
  3610. Opcode = NewOp;
  3611. BasePtr = Index->getOperand(0);
  3612. Index = ConstOffset;
  3613. }
  3614. SDValue AArch64TargetLowering::LowerMGATHER(SDValue Op,
  3615. SelectionDAG &DAG) const {
  3616. SDLoc DL(Op);
  3617. MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(Op);
  3618. assert(MGT && "Can only custom lower gather load nodes");
  3619. SDValue Index = MGT->getIndex();
  3620. SDValue Chain = MGT->getChain();
  3621. SDValue PassThru = MGT->getPassThru();
  3622. SDValue Mask = MGT->getMask();
  3623. SDValue BasePtr = MGT->getBasePtr();
  3624. ISD::LoadExtType ExtTy = MGT->getExtensionType();
  3625. ISD::MemIndexType IndexType = MGT->getIndexType();
  3626. bool IsScaled =
  3627. IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
  3628. bool IsSigned =
  3629. IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
  3630. bool IdxNeedsExtend =
  3631. getGatherScatterIndexIsExtended(Index) ||
  3632. Index.getSimpleValueType().getVectorElementType() == MVT::i32;
  3633. bool ResNeedsSignExtend = ExtTy == ISD::EXTLOAD || ExtTy == ISD::SEXTLOAD;
  3634. EVT VT = PassThru.getSimpleValueType();
  3635. EVT MemVT = MGT->getMemoryVT();
  3636. SDValue InputVT = DAG.getValueType(MemVT);
  3637. if (VT.getVectorElementType() == MVT::bf16 &&
  3638. !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
  3639. return SDValue();
  3640. // Handle FP data by using an integer gather and casting the result.
  3641. if (VT.isFloatingPoint()) {
  3642. EVT PassThruVT = getPackedSVEVectorVT(VT.getVectorElementCount());
  3643. PassThru = getSVESafeBitCast(PassThruVT, PassThru, DAG);
  3644. InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
  3645. }
  3646. SDVTList VTs = DAG.getVTList(PassThru.getSimpleValueType(), MVT::Other);
  3647. if (getGatherScatterIndexIsExtended(Index))
  3648. Index = Index.getOperand(0);
  3649. unsigned Opcode = getGatherVecOpcode(IsScaled, IsSigned, IdxNeedsExtend);
  3650. selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode,
  3651. /*isGather=*/true, DAG);
  3652. if (ResNeedsSignExtend)
  3653. Opcode = getSignExtendedGatherOpcode(Opcode);
  3654. SDValue Ops[] = {Chain, Mask, BasePtr, Index, InputVT, PassThru};
  3655. SDValue Gather = DAG.getNode(Opcode, DL, VTs, Ops);
  3656. if (VT.isFloatingPoint()) {
  3657. SDValue Cast = getSVESafeBitCast(VT, Gather, DAG);
  3658. return DAG.getMergeValues({Cast, Gather}, DL);
  3659. }
  3660. return Gather;
  3661. }
  3662. SDValue AArch64TargetLowering::LowerMSCATTER(SDValue Op,
  3663. SelectionDAG &DAG) const {
  3664. SDLoc DL(Op);
  3665. MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(Op);
  3666. assert(MSC && "Can only custom lower scatter store nodes");
  3667. SDValue Index = MSC->getIndex();
  3668. SDValue Chain = MSC->getChain();
  3669. SDValue StoreVal = MSC->getValue();
  3670. SDValue Mask = MSC->getMask();
  3671. SDValue BasePtr = MSC->getBasePtr();
  3672. ISD::MemIndexType IndexType = MSC->getIndexType();
  3673. bool IsScaled =
  3674. IndexType == ISD::SIGNED_SCALED || IndexType == ISD::UNSIGNED_SCALED;
  3675. bool IsSigned =
  3676. IndexType == ISD::SIGNED_SCALED || IndexType == ISD::SIGNED_UNSCALED;
  3677. bool NeedsExtend =
  3678. getGatherScatterIndexIsExtended(Index) ||
  3679. Index.getSimpleValueType().getVectorElementType() == MVT::i32;
  3680. EVT VT = StoreVal.getSimpleValueType();
  3681. SDVTList VTs = DAG.getVTList(MVT::Other);
  3682. EVT MemVT = MSC->getMemoryVT();
  3683. SDValue InputVT = DAG.getValueType(MemVT);
  3684. if (VT.getVectorElementType() == MVT::bf16 &&
  3685. !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
  3686. return SDValue();
  3687. // Handle FP data by casting the data so an integer scatter can be used.
  3688. if (VT.isFloatingPoint()) {
  3689. EVT StoreValVT = getPackedSVEVectorVT(VT.getVectorElementCount());
  3690. StoreVal = getSVESafeBitCast(StoreValVT, StoreVal, DAG);
  3691. InputVT = DAG.getValueType(MemVT.changeVectorElementTypeToInteger());
  3692. }
  3693. if (getGatherScatterIndexIsExtended(Index))
  3694. Index = Index.getOperand(0);
  3695. unsigned Opcode = getScatterVecOpcode(IsScaled, IsSigned, NeedsExtend);
  3696. selectGatherScatterAddrMode(BasePtr, Index, MemVT, Opcode,
  3697. /*isGather=*/false, DAG);
  3698. SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, InputVT};
  3699. return DAG.getNode(Opcode, DL, VTs, Ops);
  3700. }
  3701. // Custom lower trunc store for v4i8 vectors, since it is promoted to v4i16.
  3702. static SDValue LowerTruncateVectorStore(SDLoc DL, StoreSDNode *ST,
  3703. EVT VT, EVT MemVT,
  3704. SelectionDAG &DAG) {
  3705. assert(VT.isVector() && "VT should be a vector type");
  3706. assert(MemVT == MVT::v4i8 && VT == MVT::v4i16);
  3707. SDValue Value = ST->getValue();
  3708. // It first extend the promoted v4i16 to v8i16, truncate to v8i8, and extract
  3709. // the word lane which represent the v4i8 subvector. It optimizes the store
  3710. // to:
  3711. //
  3712. // xtn v0.8b, v0.8h
  3713. // str s0, [x0]
  3714. SDValue Undef = DAG.getUNDEF(MVT::i16);
  3715. SDValue UndefVec = DAG.getBuildVector(MVT::v4i16, DL,
  3716. {Undef, Undef, Undef, Undef});
  3717. SDValue TruncExt = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v8i16,
  3718. Value, UndefVec);
  3719. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, MVT::v8i8, TruncExt);
  3720. Trunc = DAG.getNode(ISD::BITCAST, DL, MVT::v2i32, Trunc);
  3721. SDValue ExtractTrunc = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, MVT::i32,
  3722. Trunc, DAG.getConstant(0, DL, MVT::i64));
  3723. return DAG.getStore(ST->getChain(), DL, ExtractTrunc,
  3724. ST->getBasePtr(), ST->getMemOperand());
  3725. }
  3726. // Custom lowering for any store, vector or scalar and/or default or with
  3727. // a truncate operations. Currently only custom lower truncate operation
  3728. // from vector v4i16 to v4i8 or volatile stores of i128.
  3729. SDValue AArch64TargetLowering::LowerSTORE(SDValue Op,
  3730. SelectionDAG &DAG) const {
  3731. SDLoc Dl(Op);
  3732. StoreSDNode *StoreNode = cast<StoreSDNode>(Op);
  3733. assert (StoreNode && "Can only custom lower store nodes");
  3734. SDValue Value = StoreNode->getValue();
  3735. EVT VT = Value.getValueType();
  3736. EVT MemVT = StoreNode->getMemoryVT();
  3737. if (VT.isVector()) {
  3738. if (useSVEForFixedLengthVectorVT(VT))
  3739. return LowerFixedLengthVectorStoreToSVE(Op, DAG);
  3740. unsigned AS = StoreNode->getAddressSpace();
  3741. Align Alignment = StoreNode->getAlign();
  3742. if (Alignment < MemVT.getStoreSize() &&
  3743. !allowsMisalignedMemoryAccesses(MemVT, AS, Alignment.value(),
  3744. StoreNode->getMemOperand()->getFlags(),
  3745. nullptr)) {
  3746. return scalarizeVectorStore(StoreNode, DAG);
  3747. }
  3748. if (StoreNode->isTruncatingStore()) {
  3749. return LowerTruncateVectorStore(Dl, StoreNode, VT, MemVT, DAG);
  3750. }
  3751. // 256 bit non-temporal stores can be lowered to STNP. Do this as part of
  3752. // the custom lowering, as there are no un-paired non-temporal stores and
  3753. // legalization will break up 256 bit inputs.
  3754. ElementCount EC = MemVT.getVectorElementCount();
  3755. if (StoreNode->isNonTemporal() && MemVT.getSizeInBits() == 256u &&
  3756. EC.isKnownEven() &&
  3757. ((MemVT.getScalarSizeInBits() == 8u ||
  3758. MemVT.getScalarSizeInBits() == 16u ||
  3759. MemVT.getScalarSizeInBits() == 32u ||
  3760. MemVT.getScalarSizeInBits() == 64u))) {
  3761. SDValue Lo =
  3762. DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
  3763. MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
  3764. StoreNode->getValue(), DAG.getConstant(0, Dl, MVT::i64));
  3765. SDValue Hi =
  3766. DAG.getNode(ISD::EXTRACT_SUBVECTOR, Dl,
  3767. MemVT.getHalfNumVectorElementsVT(*DAG.getContext()),
  3768. StoreNode->getValue(),
  3769. DAG.getConstant(EC.getKnownMinValue() / 2, Dl, MVT::i64));
  3770. SDValue Result = DAG.getMemIntrinsicNode(
  3771. AArch64ISD::STNP, Dl, DAG.getVTList(MVT::Other),
  3772. {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
  3773. StoreNode->getMemoryVT(), StoreNode->getMemOperand());
  3774. return Result;
  3775. }
  3776. } else if (MemVT == MVT::i128 && StoreNode->isVolatile()) {
  3777. assert(StoreNode->getValue()->getValueType(0) == MVT::i128);
  3778. SDValue Lo =
  3779. DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
  3780. DAG.getConstant(0, Dl, MVT::i64));
  3781. SDValue Hi =
  3782. DAG.getNode(ISD::EXTRACT_ELEMENT, Dl, MVT::i64, StoreNode->getValue(),
  3783. DAG.getConstant(1, Dl, MVT::i64));
  3784. SDValue Result = DAG.getMemIntrinsicNode(
  3785. AArch64ISD::STP, Dl, DAG.getVTList(MVT::Other),
  3786. {StoreNode->getChain(), Lo, Hi, StoreNode->getBasePtr()},
  3787. StoreNode->getMemoryVT(), StoreNode->getMemOperand());
  3788. return Result;
  3789. }
  3790. return SDValue();
  3791. }
  3792. // Generate SUBS and CSEL for integer abs.
  3793. SDValue AArch64TargetLowering::LowerABS(SDValue Op, SelectionDAG &DAG) const {
  3794. MVT VT = Op.getSimpleValueType();
  3795. if (VT.isVector())
  3796. return LowerToPredicatedOp(Op, DAG, AArch64ISD::ABS_MERGE_PASSTHRU);
  3797. SDLoc DL(Op);
  3798. SDValue Neg = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
  3799. Op.getOperand(0));
  3800. // Generate SUBS & CSEL.
  3801. SDValue Cmp =
  3802. DAG.getNode(AArch64ISD::SUBS, DL, DAG.getVTList(VT, MVT::i32),
  3803. Op.getOperand(0), DAG.getConstant(0, DL, VT));
  3804. return DAG.getNode(AArch64ISD::CSEL, DL, VT, Op.getOperand(0), Neg,
  3805. DAG.getConstant(AArch64CC::PL, DL, MVT::i32),
  3806. Cmp.getValue(1));
  3807. }
  3808. SDValue AArch64TargetLowering::LowerOperation(SDValue Op,
  3809. SelectionDAG &DAG) const {
  3810. LLVM_DEBUG(dbgs() << "Custom lowering: ");
  3811. LLVM_DEBUG(Op.dump());
  3812. switch (Op.getOpcode()) {
  3813. default:
  3814. llvm_unreachable("unimplemented operand");
  3815. return SDValue();
  3816. case ISD::BITCAST:
  3817. return LowerBITCAST(Op, DAG);
  3818. case ISD::GlobalAddress:
  3819. return LowerGlobalAddress(Op, DAG);
  3820. case ISD::GlobalTLSAddress:
  3821. return LowerGlobalTLSAddress(Op, DAG);
  3822. case ISD::SETCC:
  3823. case ISD::STRICT_FSETCC:
  3824. case ISD::STRICT_FSETCCS:
  3825. return LowerSETCC(Op, DAG);
  3826. case ISD::BR_CC:
  3827. return LowerBR_CC(Op, DAG);
  3828. case ISD::SELECT:
  3829. return LowerSELECT(Op, DAG);
  3830. case ISD::SELECT_CC:
  3831. return LowerSELECT_CC(Op, DAG);
  3832. case ISD::JumpTable:
  3833. return LowerJumpTable(Op, DAG);
  3834. case ISD::BR_JT:
  3835. return LowerBR_JT(Op, DAG);
  3836. case ISD::ConstantPool:
  3837. return LowerConstantPool(Op, DAG);
  3838. case ISD::BlockAddress:
  3839. return LowerBlockAddress(Op, DAG);
  3840. case ISD::VASTART:
  3841. return LowerVASTART(Op, DAG);
  3842. case ISD::VACOPY:
  3843. return LowerVACOPY(Op, DAG);
  3844. case ISD::VAARG:
  3845. return LowerVAARG(Op, DAG);
  3846. case ISD::ADDC:
  3847. case ISD::ADDE:
  3848. case ISD::SUBC:
  3849. case ISD::SUBE:
  3850. return LowerADDC_ADDE_SUBC_SUBE(Op, DAG);
  3851. case ISD::SADDO:
  3852. case ISD::UADDO:
  3853. case ISD::SSUBO:
  3854. case ISD::USUBO:
  3855. case ISD::SMULO:
  3856. case ISD::UMULO:
  3857. return LowerXALUO(Op, DAG);
  3858. case ISD::FADD:
  3859. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FADD_PRED);
  3860. case ISD::FSUB:
  3861. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSUB_PRED);
  3862. case ISD::FMUL:
  3863. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMUL_PRED);
  3864. case ISD::FMA:
  3865. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMA_PRED);
  3866. case ISD::FDIV:
  3867. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FDIV_PRED);
  3868. case ISD::FNEG:
  3869. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEG_MERGE_PASSTHRU);
  3870. case ISD::FCEIL:
  3871. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FCEIL_MERGE_PASSTHRU);
  3872. case ISD::FFLOOR:
  3873. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FFLOOR_MERGE_PASSTHRU);
  3874. case ISD::FNEARBYINT:
  3875. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FNEARBYINT_MERGE_PASSTHRU);
  3876. case ISD::FRINT:
  3877. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FRINT_MERGE_PASSTHRU);
  3878. case ISD::FROUND:
  3879. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUND_MERGE_PASSTHRU);
  3880. case ISD::FROUNDEVEN:
  3881. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FROUNDEVEN_MERGE_PASSTHRU);
  3882. case ISD::FTRUNC:
  3883. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FTRUNC_MERGE_PASSTHRU);
  3884. case ISD::FSQRT:
  3885. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FSQRT_MERGE_PASSTHRU);
  3886. case ISD::FABS:
  3887. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FABS_MERGE_PASSTHRU);
  3888. case ISD::FP_ROUND:
  3889. case ISD::STRICT_FP_ROUND:
  3890. return LowerFP_ROUND(Op, DAG);
  3891. case ISD::FP_EXTEND:
  3892. return LowerFP_EXTEND(Op, DAG);
  3893. case ISD::FRAMEADDR:
  3894. return LowerFRAMEADDR(Op, DAG);
  3895. case ISD::SPONENTRY:
  3896. return LowerSPONENTRY(Op, DAG);
  3897. case ISD::RETURNADDR:
  3898. return LowerRETURNADDR(Op, DAG);
  3899. case ISD::ADDROFRETURNADDR:
  3900. return LowerADDROFRETURNADDR(Op, DAG);
  3901. case ISD::CONCAT_VECTORS:
  3902. return LowerCONCAT_VECTORS(Op, DAG);
  3903. case ISD::INSERT_VECTOR_ELT:
  3904. return LowerINSERT_VECTOR_ELT(Op, DAG);
  3905. case ISD::EXTRACT_VECTOR_ELT:
  3906. return LowerEXTRACT_VECTOR_ELT(Op, DAG);
  3907. case ISD::BUILD_VECTOR:
  3908. return LowerBUILD_VECTOR(Op, DAG);
  3909. case ISD::VECTOR_SHUFFLE:
  3910. return LowerVECTOR_SHUFFLE(Op, DAG);
  3911. case ISD::SPLAT_VECTOR:
  3912. return LowerSPLAT_VECTOR(Op, DAG);
  3913. case ISD::EXTRACT_SUBVECTOR:
  3914. return LowerEXTRACT_SUBVECTOR(Op, DAG);
  3915. case ISD::INSERT_SUBVECTOR:
  3916. return LowerINSERT_SUBVECTOR(Op, DAG);
  3917. case ISD::SDIV:
  3918. case ISD::UDIV:
  3919. return LowerDIV(Op, DAG);
  3920. case ISD::SMIN:
  3921. return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMIN_PRED,
  3922. /*OverrideNEON=*/true);
  3923. case ISD::UMIN:
  3924. return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMIN_PRED,
  3925. /*OverrideNEON=*/true);
  3926. case ISD::SMAX:
  3927. return LowerToPredicatedOp(Op, DAG, AArch64ISD::SMAX_PRED,
  3928. /*OverrideNEON=*/true);
  3929. case ISD::UMAX:
  3930. return LowerToPredicatedOp(Op, DAG, AArch64ISD::UMAX_PRED,
  3931. /*OverrideNEON=*/true);
  3932. case ISD::SRA:
  3933. case ISD::SRL:
  3934. case ISD::SHL:
  3935. return LowerVectorSRA_SRL_SHL(Op, DAG);
  3936. case ISD::SHL_PARTS:
  3937. return LowerShiftLeftParts(Op, DAG);
  3938. case ISD::SRL_PARTS:
  3939. case ISD::SRA_PARTS:
  3940. return LowerShiftRightParts(Op, DAG);
  3941. case ISD::CTPOP:
  3942. return LowerCTPOP(Op, DAG);
  3943. case ISD::FCOPYSIGN:
  3944. return LowerFCOPYSIGN(Op, DAG);
  3945. case ISD::OR:
  3946. return LowerVectorOR(Op, DAG);
  3947. case ISD::XOR:
  3948. return LowerXOR(Op, DAG);
  3949. case ISD::PREFETCH:
  3950. return LowerPREFETCH(Op, DAG);
  3951. case ISD::SINT_TO_FP:
  3952. case ISD::UINT_TO_FP:
  3953. case ISD::STRICT_SINT_TO_FP:
  3954. case ISD::STRICT_UINT_TO_FP:
  3955. return LowerINT_TO_FP(Op, DAG);
  3956. case ISD::FP_TO_SINT:
  3957. case ISD::FP_TO_UINT:
  3958. case ISD::STRICT_FP_TO_SINT:
  3959. case ISD::STRICT_FP_TO_UINT:
  3960. return LowerFP_TO_INT(Op, DAG);
  3961. case ISD::FSINCOS:
  3962. return LowerFSINCOS(Op, DAG);
  3963. case ISD::FLT_ROUNDS_:
  3964. return LowerFLT_ROUNDS_(Op, DAG);
  3965. case ISD::MUL:
  3966. return LowerMUL(Op, DAG);
  3967. case ISD::INTRINSIC_WO_CHAIN:
  3968. return LowerINTRINSIC_WO_CHAIN(Op, DAG);
  3969. case ISD::STORE:
  3970. return LowerSTORE(Op, DAG);
  3971. case ISD::MGATHER:
  3972. return LowerMGATHER(Op, DAG);
  3973. case ISD::MSCATTER:
  3974. return LowerMSCATTER(Op, DAG);
  3975. case ISD::VECREDUCE_SEQ_FADD:
  3976. return LowerVECREDUCE_SEQ_FADD(Op, DAG);
  3977. case ISD::VECREDUCE_ADD:
  3978. case ISD::VECREDUCE_AND:
  3979. case ISD::VECREDUCE_OR:
  3980. case ISD::VECREDUCE_XOR:
  3981. case ISD::VECREDUCE_SMAX:
  3982. case ISD::VECREDUCE_SMIN:
  3983. case ISD::VECREDUCE_UMAX:
  3984. case ISD::VECREDUCE_UMIN:
  3985. case ISD::VECREDUCE_FADD:
  3986. case ISD::VECREDUCE_FMAX:
  3987. case ISD::VECREDUCE_FMIN:
  3988. return LowerVECREDUCE(Op, DAG);
  3989. case ISD::ATOMIC_LOAD_SUB:
  3990. return LowerATOMIC_LOAD_SUB(Op, DAG);
  3991. case ISD::ATOMIC_LOAD_AND:
  3992. return LowerATOMIC_LOAD_AND(Op, DAG);
  3993. case ISD::DYNAMIC_STACKALLOC:
  3994. return LowerDYNAMIC_STACKALLOC(Op, DAG);
  3995. case ISD::VSCALE:
  3996. return LowerVSCALE(Op, DAG);
  3997. case ISD::ANY_EXTEND:
  3998. case ISD::SIGN_EXTEND:
  3999. case ISD::ZERO_EXTEND:
  4000. return LowerFixedLengthVectorIntExtendToSVE(Op, DAG);
  4001. case ISD::SIGN_EXTEND_INREG: {
  4002. // Only custom lower when ExtraVT has a legal byte based element type.
  4003. EVT ExtraVT = cast<VTSDNode>(Op.getOperand(1))->getVT();
  4004. EVT ExtraEltVT = ExtraVT.getVectorElementType();
  4005. if ((ExtraEltVT != MVT::i8) && (ExtraEltVT != MVT::i16) &&
  4006. (ExtraEltVT != MVT::i32) && (ExtraEltVT != MVT::i64))
  4007. return SDValue();
  4008. return LowerToPredicatedOp(Op, DAG,
  4009. AArch64ISD::SIGN_EXTEND_INREG_MERGE_PASSTHRU);
  4010. }
  4011. case ISD::TRUNCATE:
  4012. return LowerTRUNCATE(Op, DAG);
  4013. case ISD::LOAD:
  4014. if (useSVEForFixedLengthVectorVT(Op.getValueType()))
  4015. return LowerFixedLengthVectorLoadToSVE(Op, DAG);
  4016. llvm_unreachable("Unexpected request to lower ISD::LOAD");
  4017. case ISD::ADD:
  4018. return LowerToPredicatedOp(Op, DAG, AArch64ISD::ADD_PRED);
  4019. case ISD::AND:
  4020. return LowerToScalableOp(Op, DAG);
  4021. case ISD::SUB:
  4022. return LowerToPredicatedOp(Op, DAG, AArch64ISD::SUB_PRED);
  4023. case ISD::FMAXNUM:
  4024. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMAXNM_PRED);
  4025. case ISD::FMINNUM:
  4026. return LowerToPredicatedOp(Op, DAG, AArch64ISD::FMINNM_PRED);
  4027. case ISD::VSELECT:
  4028. return LowerFixedLengthVectorSelectToSVE(Op, DAG);
  4029. case ISD::ABS:
  4030. return LowerABS(Op, DAG);
  4031. case ISD::BITREVERSE:
  4032. return LowerToPredicatedOp(Op, DAG, AArch64ISD::BITREVERSE_MERGE_PASSTHRU,
  4033. /*OverrideNEON=*/true);
  4034. case ISD::BSWAP:
  4035. return LowerToPredicatedOp(Op, DAG, AArch64ISD::BSWAP_MERGE_PASSTHRU);
  4036. case ISD::CTLZ:
  4037. return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTLZ_MERGE_PASSTHRU,
  4038. /*OverrideNEON=*/true);
  4039. case ISD::CTTZ:
  4040. return LowerCTTZ(Op, DAG);
  4041. }
  4042. }
  4043. bool AArch64TargetLowering::mergeStoresAfterLegalization(EVT VT) const {
  4044. return !Subtarget->useSVEForFixedLengthVectors();
  4045. }
  4046. bool AArch64TargetLowering::useSVEForFixedLengthVectorVT(
  4047. EVT VT, bool OverrideNEON) const {
  4048. if (!Subtarget->useSVEForFixedLengthVectors())
  4049. return false;
  4050. if (!VT.isFixedLengthVector())
  4051. return false;
  4052. // Don't use SVE for vectors we cannot scalarize if required.
  4053. switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
  4054. // Fixed length predicates should be promoted to i8.
  4055. // NOTE: This is consistent with how NEON (and thus 64/128bit vectors) work.
  4056. case MVT::i1:
  4057. default:
  4058. return false;
  4059. case MVT::i8:
  4060. case MVT::i16:
  4061. case MVT::i32:
  4062. case MVT::i64:
  4063. case MVT::f16:
  4064. case MVT::f32:
  4065. case MVT::f64:
  4066. break;
  4067. }
  4068. // All SVE implementations support NEON sized vectors.
  4069. if (OverrideNEON && (VT.is128BitVector() || VT.is64BitVector()))
  4070. return true;
  4071. // Ensure NEON MVTs only belong to a single register class.
  4072. if (VT.getFixedSizeInBits() <= 128)
  4073. return false;
  4074. // Don't use SVE for types that don't fit.
  4075. if (VT.getFixedSizeInBits() > Subtarget->getMinSVEVectorSizeInBits())
  4076. return false;
  4077. // TODO: Perhaps an artificial restriction, but worth having whilst getting
  4078. // the base fixed length SVE support in place.
  4079. if (!VT.isPow2VectorType())
  4080. return false;
  4081. return true;
  4082. }
  4083. //===----------------------------------------------------------------------===//
  4084. // Calling Convention Implementation
  4085. //===----------------------------------------------------------------------===//
  4086. /// Selects the correct CCAssignFn for a given CallingConvention value.
  4087. CCAssignFn *AArch64TargetLowering::CCAssignFnForCall(CallingConv::ID CC,
  4088. bool IsVarArg) const {
  4089. switch (CC) {
  4090. default:
  4091. report_fatal_error("Unsupported calling convention.");
  4092. case CallingConv::WebKit_JS:
  4093. return CC_AArch64_WebKit_JS;
  4094. case CallingConv::GHC:
  4095. return CC_AArch64_GHC;
  4096. case CallingConv::C:
  4097. case CallingConv::Fast:
  4098. case CallingConv::PreserveMost:
  4099. case CallingConv::CXX_FAST_TLS:
  4100. case CallingConv::Swift:
  4101. if (Subtarget->isTargetWindows() && IsVarArg)
  4102. return CC_AArch64_Win64_VarArg;
  4103. if (!Subtarget->isTargetDarwin())
  4104. return CC_AArch64_AAPCS;
  4105. if (!IsVarArg)
  4106. return CC_AArch64_DarwinPCS;
  4107. return Subtarget->isTargetILP32() ? CC_AArch64_DarwinPCS_ILP32_VarArg
  4108. : CC_AArch64_DarwinPCS_VarArg;
  4109. case CallingConv::Win64:
  4110. return IsVarArg ? CC_AArch64_Win64_VarArg : CC_AArch64_AAPCS;
  4111. case CallingConv::CFGuard_Check:
  4112. return CC_AArch64_Win64_CFGuard_Check;
  4113. case CallingConv::AArch64_VectorCall:
  4114. case CallingConv::AArch64_SVE_VectorCall:
  4115. return CC_AArch64_AAPCS;
  4116. }
  4117. }
  4118. CCAssignFn *
  4119. AArch64TargetLowering::CCAssignFnForReturn(CallingConv::ID CC) const {
  4120. return CC == CallingConv::WebKit_JS ? RetCC_AArch64_WebKit_JS
  4121. : RetCC_AArch64_AAPCS;
  4122. }
  4123. SDValue AArch64TargetLowering::LowerFormalArguments(
  4124. SDValue Chain, CallingConv::ID CallConv, bool isVarArg,
  4125. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
  4126. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals) const {
  4127. MachineFunction &MF = DAG.getMachineFunction();
  4128. MachineFrameInfo &MFI = MF.getFrameInfo();
  4129. bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
  4130. // Assign locations to all of the incoming arguments.
  4131. SmallVector<CCValAssign, 16> ArgLocs;
  4132. DenseMap<unsigned, SDValue> CopiedRegs;
  4133. CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), ArgLocs,
  4134. *DAG.getContext());
  4135. // At this point, Ins[].VT may already be promoted to i32. To correctly
  4136. // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
  4137. // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
  4138. // Since AnalyzeFormalArguments uses Ins[].VT for both ValVT and LocVT, here
  4139. // we use a special version of AnalyzeFormalArguments to pass in ValVT and
  4140. // LocVT.
  4141. unsigned NumArgs = Ins.size();
  4142. Function::const_arg_iterator CurOrigArg = MF.getFunction().arg_begin();
  4143. unsigned CurArgIdx = 0;
  4144. for (unsigned i = 0; i != NumArgs; ++i) {
  4145. MVT ValVT = Ins[i].VT;
  4146. if (Ins[i].isOrigArg()) {
  4147. std::advance(CurOrigArg, Ins[i].getOrigArgIndex() - CurArgIdx);
  4148. CurArgIdx = Ins[i].getOrigArgIndex();
  4149. // Get type of the original argument.
  4150. EVT ActualVT = getValueType(DAG.getDataLayout(), CurOrigArg->getType(),
  4151. /*AllowUnknown*/ true);
  4152. MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : MVT::Other;
  4153. // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
  4154. if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
  4155. ValVT = MVT::i8;
  4156. else if (ActualMVT == MVT::i16)
  4157. ValVT = MVT::i16;
  4158. }
  4159. CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
  4160. bool Res =
  4161. AssignFn(i, ValVT, ValVT, CCValAssign::Full, Ins[i].Flags, CCInfo);
  4162. assert(!Res && "Call operand has unhandled type");
  4163. (void)Res;
  4164. }
  4165. SmallVector<SDValue, 16> ArgValues;
  4166. unsigned ExtraArgLocs = 0;
  4167. for (unsigned i = 0, e = Ins.size(); i != e; ++i) {
  4168. CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
  4169. if (Ins[i].Flags.isByVal()) {
  4170. // Byval is used for HFAs in the PCS, but the system should work in a
  4171. // non-compliant manner for larger structs.
  4172. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  4173. int Size = Ins[i].Flags.getByValSize();
  4174. unsigned NumRegs = (Size + 7) / 8;
  4175. // FIXME: This works on big-endian for composite byvals, which are the common
  4176. // case. It should also work for fundamental types too.
  4177. unsigned FrameIdx =
  4178. MFI.CreateFixedObject(8 * NumRegs, VA.getLocMemOffset(), false);
  4179. SDValue FrameIdxN = DAG.getFrameIndex(FrameIdx, PtrVT);
  4180. InVals.push_back(FrameIdxN);
  4181. continue;
  4182. }
  4183. SDValue ArgValue;
  4184. if (VA.isRegLoc()) {
  4185. // Arguments stored in registers.
  4186. EVT RegVT = VA.getLocVT();
  4187. const TargetRegisterClass *RC;
  4188. if (RegVT == MVT::i32)
  4189. RC = &AArch64::GPR32RegClass;
  4190. else if (RegVT == MVT::i64)
  4191. RC = &AArch64::GPR64RegClass;
  4192. else if (RegVT == MVT::f16 || RegVT == MVT::bf16)
  4193. RC = &AArch64::FPR16RegClass;
  4194. else if (RegVT == MVT::f32)
  4195. RC = &AArch64::FPR32RegClass;
  4196. else if (RegVT == MVT::f64 || RegVT.is64BitVector())
  4197. RC = &AArch64::FPR64RegClass;
  4198. else if (RegVT == MVT::f128 || RegVT.is128BitVector())
  4199. RC = &AArch64::FPR128RegClass;
  4200. else if (RegVT.isScalableVector() &&
  4201. RegVT.getVectorElementType() == MVT::i1)
  4202. RC = &AArch64::PPRRegClass;
  4203. else if (RegVT.isScalableVector())
  4204. RC = &AArch64::ZPRRegClass;
  4205. else
  4206. llvm_unreachable("RegVT not supported by FORMAL_ARGUMENTS Lowering");
  4207. // Transform the arguments in physical registers into virtual ones.
  4208. unsigned Reg = MF.addLiveIn(VA.getLocReg(), RC);
  4209. ArgValue = DAG.getCopyFromReg(Chain, DL, Reg, RegVT);
  4210. // If this is an 8, 16 or 32-bit value, it is really passed promoted
  4211. // to 64 bits. Insert an assert[sz]ext to capture this, then
  4212. // truncate to the right size.
  4213. switch (VA.getLocInfo()) {
  4214. default:
  4215. llvm_unreachable("Unknown loc info!");
  4216. case CCValAssign::Full:
  4217. break;
  4218. case CCValAssign::Indirect:
  4219. assert(VA.getValVT().isScalableVector() &&
  4220. "Only scalable vectors can be passed indirectly");
  4221. break;
  4222. case CCValAssign::BCvt:
  4223. ArgValue = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), ArgValue);
  4224. break;
  4225. case CCValAssign::AExt:
  4226. case CCValAssign::SExt:
  4227. case CCValAssign::ZExt:
  4228. break;
  4229. case CCValAssign::AExtUpper:
  4230. ArgValue = DAG.getNode(ISD::SRL, DL, RegVT, ArgValue,
  4231. DAG.getConstant(32, DL, RegVT));
  4232. ArgValue = DAG.getZExtOrTrunc(ArgValue, DL, VA.getValVT());
  4233. break;
  4234. }
  4235. } else { // VA.isRegLoc()
  4236. assert(VA.isMemLoc() && "CCValAssign is neither reg nor mem");
  4237. unsigned ArgOffset = VA.getLocMemOffset();
  4238. unsigned ArgSize = (VA.getLocInfo() == CCValAssign::Indirect
  4239. ? VA.getLocVT().getSizeInBits()
  4240. : VA.getValVT().getSizeInBits()) / 8;
  4241. uint32_t BEAlign = 0;
  4242. if (!Subtarget->isLittleEndian() && ArgSize < 8 &&
  4243. !Ins[i].Flags.isInConsecutiveRegs())
  4244. BEAlign = 8 - ArgSize;
  4245. int FI = MFI.CreateFixedObject(ArgSize, ArgOffset + BEAlign, true);
  4246. // Create load nodes to retrieve arguments from the stack.
  4247. SDValue FIN = DAG.getFrameIndex(FI, getPointerTy(DAG.getDataLayout()));
  4248. // For NON_EXTLOAD, generic code in getLoad assert(ValVT == MemVT)
  4249. ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
  4250. MVT MemVT = VA.getValVT();
  4251. switch (VA.getLocInfo()) {
  4252. default:
  4253. break;
  4254. case CCValAssign::Trunc:
  4255. case CCValAssign::BCvt:
  4256. MemVT = VA.getLocVT();
  4257. break;
  4258. case CCValAssign::Indirect:
  4259. assert(VA.getValVT().isScalableVector() &&
  4260. "Only scalable vectors can be passed indirectly");
  4261. MemVT = VA.getLocVT();
  4262. break;
  4263. case CCValAssign::SExt:
  4264. ExtType = ISD::SEXTLOAD;
  4265. break;
  4266. case CCValAssign::ZExt:
  4267. ExtType = ISD::ZEXTLOAD;
  4268. break;
  4269. case CCValAssign::AExt:
  4270. ExtType = ISD::EXTLOAD;
  4271. break;
  4272. }
  4273. ArgValue = DAG.getExtLoad(
  4274. ExtType, DL, VA.getLocVT(), Chain, FIN,
  4275. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI),
  4276. MemVT);
  4277. }
  4278. if (VA.getLocInfo() == CCValAssign::Indirect) {
  4279. assert(VA.getValVT().isScalableVector() &&
  4280. "Only scalable vectors can be passed indirectly");
  4281. uint64_t PartSize = VA.getValVT().getStoreSize().getKnownMinSize();
  4282. unsigned NumParts = 1;
  4283. if (Ins[i].Flags.isInConsecutiveRegs()) {
  4284. assert(!Ins[i].Flags.isInConsecutiveRegsLast());
  4285. while (!Ins[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
  4286. ++NumParts;
  4287. }
  4288. MVT PartLoad = VA.getValVT();
  4289. SDValue Ptr = ArgValue;
  4290. // Ensure we generate all loads for each tuple part, whilst updating the
  4291. // pointer after each load correctly using vscale.
  4292. while (NumParts > 0) {
  4293. ArgValue = DAG.getLoad(PartLoad, DL, Chain, Ptr, MachinePointerInfo());
  4294. InVals.push_back(ArgValue);
  4295. NumParts--;
  4296. if (NumParts > 0) {
  4297. SDValue BytesIncrement = DAG.getVScale(
  4298. DL, Ptr.getValueType(),
  4299. APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize));
  4300. SDNodeFlags Flags;
  4301. Flags.setNoUnsignedWrap(true);
  4302. Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
  4303. BytesIncrement, Flags);
  4304. ExtraArgLocs++;
  4305. i++;
  4306. }
  4307. }
  4308. } else {
  4309. if (Subtarget->isTargetILP32() && Ins[i].Flags.isPointer())
  4310. ArgValue = DAG.getNode(ISD::AssertZext, DL, ArgValue.getValueType(),
  4311. ArgValue, DAG.getValueType(MVT::i32));
  4312. InVals.push_back(ArgValue);
  4313. }
  4314. }
  4315. assert((ArgLocs.size() + ExtraArgLocs) == Ins.size());
  4316. // varargs
  4317. AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  4318. if (isVarArg) {
  4319. if (!Subtarget->isTargetDarwin() || IsWin64) {
  4320. // The AAPCS variadic function ABI is identical to the non-variadic
  4321. // one. As a result there may be more arguments in registers and we should
  4322. // save them for future reference.
  4323. // Win64 variadic functions also pass arguments in registers, but all float
  4324. // arguments are passed in integer registers.
  4325. saveVarArgRegisters(CCInfo, DAG, DL, Chain);
  4326. }
  4327. // This will point to the next argument passed via stack.
  4328. unsigned StackOffset = CCInfo.getNextStackOffset();
  4329. // We currently pass all varargs at 8-byte alignment, or 4 for ILP32
  4330. StackOffset = alignTo(StackOffset, Subtarget->isTargetILP32() ? 4 : 8);
  4331. FuncInfo->setVarArgsStackIndex(MFI.CreateFixedObject(4, StackOffset, true));
  4332. if (MFI.hasMustTailInVarArgFunc()) {
  4333. SmallVector<MVT, 2> RegParmTypes;
  4334. RegParmTypes.push_back(MVT::i64);
  4335. RegParmTypes.push_back(MVT::f128);
  4336. // Compute the set of forwarded registers. The rest are scratch.
  4337. SmallVectorImpl<ForwardedRegister> &Forwards =
  4338. FuncInfo->getForwardedMustTailRegParms();
  4339. CCInfo.analyzeMustTailForwardedRegisters(Forwards, RegParmTypes,
  4340. CC_AArch64_AAPCS);
  4341. // Conservatively forward X8, since it might be used for aggregate return.
  4342. if (!CCInfo.isAllocated(AArch64::X8)) {
  4343. unsigned X8VReg = MF.addLiveIn(AArch64::X8, &AArch64::GPR64RegClass);
  4344. Forwards.push_back(ForwardedRegister(X8VReg, AArch64::X8, MVT::i64));
  4345. }
  4346. }
  4347. }
  4348. // On Windows, InReg pointers must be returned, so record the pointer in a
  4349. // virtual register at the start of the function so it can be returned in the
  4350. // epilogue.
  4351. if (IsWin64) {
  4352. for (unsigned I = 0, E = Ins.size(); I != E; ++I) {
  4353. if (Ins[I].Flags.isInReg()) {
  4354. assert(!FuncInfo->getSRetReturnReg());
  4355. MVT PtrTy = getPointerTy(DAG.getDataLayout());
  4356. Register Reg =
  4357. MF.getRegInfo().createVirtualRegister(getRegClassFor(PtrTy));
  4358. FuncInfo->setSRetReturnReg(Reg);
  4359. SDValue Copy = DAG.getCopyToReg(DAG.getEntryNode(), DL, Reg, InVals[I]);
  4360. Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Copy, Chain);
  4361. break;
  4362. }
  4363. }
  4364. }
  4365. unsigned StackArgSize = CCInfo.getNextStackOffset();
  4366. bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
  4367. if (DoesCalleeRestoreStack(CallConv, TailCallOpt)) {
  4368. // This is a non-standard ABI so by fiat I say we're allowed to make full
  4369. // use of the stack area to be popped, which must be aligned to 16 bytes in
  4370. // any case:
  4371. StackArgSize = alignTo(StackArgSize, 16);
  4372. // If we're expected to restore the stack (e.g. fastcc) then we'll be adding
  4373. // a multiple of 16.
  4374. FuncInfo->setArgumentStackToRestore(StackArgSize);
  4375. // This realignment carries over to the available bytes below. Our own
  4376. // callers will guarantee the space is free by giving an aligned value to
  4377. // CALLSEQ_START.
  4378. }
  4379. // Even if we're not expected to free up the space, it's useful to know how
  4380. // much is there while considering tail calls (because we can reuse it).
  4381. FuncInfo->setBytesInStackArgArea(StackArgSize);
  4382. if (Subtarget->hasCustomCallingConv())
  4383. Subtarget->getRegisterInfo()->UpdateCustomCalleeSavedRegs(MF);
  4384. return Chain;
  4385. }
  4386. void AArch64TargetLowering::saveVarArgRegisters(CCState &CCInfo,
  4387. SelectionDAG &DAG,
  4388. const SDLoc &DL,
  4389. SDValue &Chain) const {
  4390. MachineFunction &MF = DAG.getMachineFunction();
  4391. MachineFrameInfo &MFI = MF.getFrameInfo();
  4392. AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  4393. auto PtrVT = getPointerTy(DAG.getDataLayout());
  4394. bool IsWin64 = Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv());
  4395. SmallVector<SDValue, 8> MemOps;
  4396. static const MCPhysReg GPRArgRegs[] = { AArch64::X0, AArch64::X1, AArch64::X2,
  4397. AArch64::X3, AArch64::X4, AArch64::X5,
  4398. AArch64::X6, AArch64::X7 };
  4399. static const unsigned NumGPRArgRegs = array_lengthof(GPRArgRegs);
  4400. unsigned FirstVariadicGPR = CCInfo.getFirstUnallocated(GPRArgRegs);
  4401. unsigned GPRSaveSize = 8 * (NumGPRArgRegs - FirstVariadicGPR);
  4402. int GPRIdx = 0;
  4403. if (GPRSaveSize != 0) {
  4404. if (IsWin64) {
  4405. GPRIdx = MFI.CreateFixedObject(GPRSaveSize, -(int)GPRSaveSize, false);
  4406. if (GPRSaveSize & 15)
  4407. // The extra size here, if triggered, will always be 8.
  4408. MFI.CreateFixedObject(16 - (GPRSaveSize & 15), -(int)alignTo(GPRSaveSize, 16), false);
  4409. } else
  4410. GPRIdx = MFI.CreateStackObject(GPRSaveSize, Align(8), false);
  4411. SDValue FIN = DAG.getFrameIndex(GPRIdx, PtrVT);
  4412. for (unsigned i = FirstVariadicGPR; i < NumGPRArgRegs; ++i) {
  4413. unsigned VReg = MF.addLiveIn(GPRArgRegs[i], &AArch64::GPR64RegClass);
  4414. SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::i64);
  4415. SDValue Store = DAG.getStore(
  4416. Val.getValue(1), DL, Val, FIN,
  4417. IsWin64
  4418. ? MachinePointerInfo::getFixedStack(DAG.getMachineFunction(),
  4419. GPRIdx,
  4420. (i - FirstVariadicGPR) * 8)
  4421. : MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 8));
  4422. MemOps.push_back(Store);
  4423. FIN =
  4424. DAG.getNode(ISD::ADD, DL, PtrVT, FIN, DAG.getConstant(8, DL, PtrVT));
  4425. }
  4426. }
  4427. FuncInfo->setVarArgsGPRIndex(GPRIdx);
  4428. FuncInfo->setVarArgsGPRSize(GPRSaveSize);
  4429. if (Subtarget->hasFPARMv8() && !IsWin64) {
  4430. static const MCPhysReg FPRArgRegs[] = {
  4431. AArch64::Q0, AArch64::Q1, AArch64::Q2, AArch64::Q3,
  4432. AArch64::Q4, AArch64::Q5, AArch64::Q6, AArch64::Q7};
  4433. static const unsigned NumFPRArgRegs = array_lengthof(FPRArgRegs);
  4434. unsigned FirstVariadicFPR = CCInfo.getFirstUnallocated(FPRArgRegs);
  4435. unsigned FPRSaveSize = 16 * (NumFPRArgRegs - FirstVariadicFPR);
  4436. int FPRIdx = 0;
  4437. if (FPRSaveSize != 0) {
  4438. FPRIdx = MFI.CreateStackObject(FPRSaveSize, Align(16), false);
  4439. SDValue FIN = DAG.getFrameIndex(FPRIdx, PtrVT);
  4440. for (unsigned i = FirstVariadicFPR; i < NumFPRArgRegs; ++i) {
  4441. unsigned VReg = MF.addLiveIn(FPRArgRegs[i], &AArch64::FPR128RegClass);
  4442. SDValue Val = DAG.getCopyFromReg(Chain, DL, VReg, MVT::f128);
  4443. SDValue Store = DAG.getStore(
  4444. Val.getValue(1), DL, Val, FIN,
  4445. MachinePointerInfo::getStack(DAG.getMachineFunction(), i * 16));
  4446. MemOps.push_back(Store);
  4447. FIN = DAG.getNode(ISD::ADD, DL, PtrVT, FIN,
  4448. DAG.getConstant(16, DL, PtrVT));
  4449. }
  4450. }
  4451. FuncInfo->setVarArgsFPRIndex(FPRIdx);
  4452. FuncInfo->setVarArgsFPRSize(FPRSaveSize);
  4453. }
  4454. if (!MemOps.empty()) {
  4455. Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
  4456. }
  4457. }
  4458. /// LowerCallResult - Lower the result values of a call into the
  4459. /// appropriate copies out of appropriate physical registers.
  4460. SDValue AArch64TargetLowering::LowerCallResult(
  4461. SDValue Chain, SDValue InFlag, CallingConv::ID CallConv, bool isVarArg,
  4462. const SmallVectorImpl<ISD::InputArg> &Ins, const SDLoc &DL,
  4463. SelectionDAG &DAG, SmallVectorImpl<SDValue> &InVals, bool isThisReturn,
  4464. SDValue ThisVal) const {
  4465. CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
  4466. // Assign locations to each value returned by this call.
  4467. SmallVector<CCValAssign, 16> RVLocs;
  4468. DenseMap<unsigned, SDValue> CopiedRegs;
  4469. CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
  4470. *DAG.getContext());
  4471. CCInfo.AnalyzeCallResult(Ins, RetCC);
  4472. // Copy all of the result registers out of their specified physreg.
  4473. for (unsigned i = 0; i != RVLocs.size(); ++i) {
  4474. CCValAssign VA = RVLocs[i];
  4475. // Pass 'this' value directly from the argument to return value, to avoid
  4476. // reg unit interference
  4477. if (i == 0 && isThisReturn) {
  4478. assert(!VA.needsCustom() && VA.getLocVT() == MVT::i64 &&
  4479. "unexpected return calling convention register assignment");
  4480. InVals.push_back(ThisVal);
  4481. continue;
  4482. }
  4483. // Avoid copying a physreg twice since RegAllocFast is incompetent and only
  4484. // allows one use of a physreg per block.
  4485. SDValue Val = CopiedRegs.lookup(VA.getLocReg());
  4486. if (!Val) {
  4487. Val =
  4488. DAG.getCopyFromReg(Chain, DL, VA.getLocReg(), VA.getLocVT(), InFlag);
  4489. Chain = Val.getValue(1);
  4490. InFlag = Val.getValue(2);
  4491. CopiedRegs[VA.getLocReg()] = Val;
  4492. }
  4493. switch (VA.getLocInfo()) {
  4494. default:
  4495. llvm_unreachable("Unknown loc info!");
  4496. case CCValAssign::Full:
  4497. break;
  4498. case CCValAssign::BCvt:
  4499. Val = DAG.getNode(ISD::BITCAST, DL, VA.getValVT(), Val);
  4500. break;
  4501. case CCValAssign::AExtUpper:
  4502. Val = DAG.getNode(ISD::SRL, DL, VA.getLocVT(), Val,
  4503. DAG.getConstant(32, DL, VA.getLocVT()));
  4504. LLVM_FALLTHROUGH;
  4505. case CCValAssign::AExt:
  4506. LLVM_FALLTHROUGH;
  4507. case CCValAssign::ZExt:
  4508. Val = DAG.getZExtOrTrunc(Val, DL, VA.getValVT());
  4509. break;
  4510. }
  4511. InVals.push_back(Val);
  4512. }
  4513. return Chain;
  4514. }
  4515. /// Return true if the calling convention is one that we can guarantee TCO for.
  4516. static bool canGuaranteeTCO(CallingConv::ID CC) {
  4517. return CC == CallingConv::Fast;
  4518. }
  4519. /// Return true if we might ever do TCO for calls with this calling convention.
  4520. static bool mayTailCallThisCC(CallingConv::ID CC) {
  4521. switch (CC) {
  4522. case CallingConv::C:
  4523. case CallingConv::AArch64_SVE_VectorCall:
  4524. case CallingConv::PreserveMost:
  4525. case CallingConv::Swift:
  4526. return true;
  4527. default:
  4528. return canGuaranteeTCO(CC);
  4529. }
  4530. }
  4531. bool AArch64TargetLowering::isEligibleForTailCallOptimization(
  4532. SDValue Callee, CallingConv::ID CalleeCC, bool isVarArg,
  4533. const SmallVectorImpl<ISD::OutputArg> &Outs,
  4534. const SmallVectorImpl<SDValue> &OutVals,
  4535. const SmallVectorImpl<ISD::InputArg> &Ins, SelectionDAG &DAG) const {
  4536. if (!mayTailCallThisCC(CalleeCC))
  4537. return false;
  4538. MachineFunction &MF = DAG.getMachineFunction();
  4539. const Function &CallerF = MF.getFunction();
  4540. CallingConv::ID CallerCC = CallerF.getCallingConv();
  4541. // If this function uses the C calling convention but has an SVE signature,
  4542. // then it preserves more registers and should assume the SVE_VectorCall CC.
  4543. // The check for matching callee-saved regs will determine whether it is
  4544. // eligible for TCO.
  4545. if (CallerCC == CallingConv::C &&
  4546. AArch64RegisterInfo::hasSVEArgsOrReturn(&MF))
  4547. CallerCC = CallingConv::AArch64_SVE_VectorCall;
  4548. bool CCMatch = CallerCC == CalleeCC;
  4549. // When using the Windows calling convention on a non-windows OS, we want
  4550. // to back up and restore X18 in such functions; we can't do a tail call
  4551. // from those functions.
  4552. if (CallerCC == CallingConv::Win64 && !Subtarget->isTargetWindows() &&
  4553. CalleeCC != CallingConv::Win64)
  4554. return false;
  4555. // Byval parameters hand the function a pointer directly into the stack area
  4556. // we want to reuse during a tail call. Working around this *is* possible (see
  4557. // X86) but less efficient and uglier in LowerCall.
  4558. for (Function::const_arg_iterator i = CallerF.arg_begin(),
  4559. e = CallerF.arg_end();
  4560. i != e; ++i) {
  4561. if (i->hasByValAttr())
  4562. return false;
  4563. // On Windows, "inreg" attributes signify non-aggregate indirect returns.
  4564. // In this case, it is necessary to save/restore X0 in the callee. Tail
  4565. // call opt interferes with this. So we disable tail call opt when the
  4566. // caller has an argument with "inreg" attribute.
  4567. // FIXME: Check whether the callee also has an "inreg" argument.
  4568. if (i->hasInRegAttr())
  4569. return false;
  4570. }
  4571. if (getTargetMachine().Options.GuaranteedTailCallOpt)
  4572. return canGuaranteeTCO(CalleeCC) && CCMatch;
  4573. // Externally-defined functions with weak linkage should not be
  4574. // tail-called on AArch64 when the OS does not support dynamic
  4575. // pre-emption of symbols, as the AAELF spec requires normal calls
  4576. // to undefined weak functions to be replaced with a NOP or jump to the
  4577. // next instruction. The behaviour of branch instructions in this
  4578. // situation (as used for tail calls) is implementation-defined, so we
  4579. // cannot rely on the linker replacing the tail call with a return.
  4580. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
  4581. const GlobalValue *GV = G->getGlobal();
  4582. const Triple &TT = getTargetMachine().getTargetTriple();
  4583. if (GV->hasExternalWeakLinkage() &&
  4584. (!TT.isOSWindows() || TT.isOSBinFormatELF() || TT.isOSBinFormatMachO()))
  4585. return false;
  4586. }
  4587. // Now we search for cases where we can use a tail call without changing the
  4588. // ABI. Sibcall is used in some places (particularly gcc) to refer to this
  4589. // concept.
  4590. // I want anyone implementing a new calling convention to think long and hard
  4591. // about this assert.
  4592. assert((!isVarArg || CalleeCC == CallingConv::C) &&
  4593. "Unexpected variadic calling convention");
  4594. LLVMContext &C = *DAG.getContext();
  4595. if (isVarArg && !Outs.empty()) {
  4596. // At least two cases here: if caller is fastcc then we can't have any
  4597. // memory arguments (we'd be expected to clean up the stack afterwards). If
  4598. // caller is C then we could potentially use its argument area.
  4599. // FIXME: for now we take the most conservative of these in both cases:
  4600. // disallow all variadic memory operands.
  4601. SmallVector<CCValAssign, 16> ArgLocs;
  4602. CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
  4603. CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, true));
  4604. for (const CCValAssign &ArgLoc : ArgLocs)
  4605. if (!ArgLoc.isRegLoc())
  4606. return false;
  4607. }
  4608. // Check that the call results are passed in the same way.
  4609. if (!CCState::resultsCompatible(CalleeCC, CallerCC, MF, C, Ins,
  4610. CCAssignFnForCall(CalleeCC, isVarArg),
  4611. CCAssignFnForCall(CallerCC, isVarArg)))
  4612. return false;
  4613. // The callee has to preserve all registers the caller needs to preserve.
  4614. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
  4615. const uint32_t *CallerPreserved = TRI->getCallPreservedMask(MF, CallerCC);
  4616. if (!CCMatch) {
  4617. const uint32_t *CalleePreserved = TRI->getCallPreservedMask(MF, CalleeCC);
  4618. if (Subtarget->hasCustomCallingConv()) {
  4619. TRI->UpdateCustomCallPreservedMask(MF, &CallerPreserved);
  4620. TRI->UpdateCustomCallPreservedMask(MF, &CalleePreserved);
  4621. }
  4622. if (!TRI->regmaskSubsetEqual(CallerPreserved, CalleePreserved))
  4623. return false;
  4624. }
  4625. // Nothing more to check if the callee is taking no arguments
  4626. if (Outs.empty())
  4627. return true;
  4628. SmallVector<CCValAssign, 16> ArgLocs;
  4629. CCState CCInfo(CalleeCC, isVarArg, MF, ArgLocs, C);
  4630. CCInfo.AnalyzeCallOperands(Outs, CCAssignFnForCall(CalleeCC, isVarArg));
  4631. const AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  4632. // If any of the arguments is passed indirectly, it must be SVE, so the
  4633. // 'getBytesInStackArgArea' is not sufficient to determine whether we need to
  4634. // allocate space on the stack. That is why we determine this explicitly here
  4635. // the call cannot be a tailcall.
  4636. if (llvm::any_of(ArgLocs, [](CCValAssign &A) {
  4637. assert((A.getLocInfo() != CCValAssign::Indirect ||
  4638. A.getValVT().isScalableVector()) &&
  4639. "Expected value to be scalable");
  4640. return A.getLocInfo() == CCValAssign::Indirect;
  4641. }))
  4642. return false;
  4643. // If the stack arguments for this call do not fit into our own save area then
  4644. // the call cannot be made tail.
  4645. if (CCInfo.getNextStackOffset() > FuncInfo->getBytesInStackArgArea())
  4646. return false;
  4647. const MachineRegisterInfo &MRI = MF.getRegInfo();
  4648. if (!parametersInCSRMatch(MRI, CallerPreserved, ArgLocs, OutVals))
  4649. return false;
  4650. return true;
  4651. }
  4652. SDValue AArch64TargetLowering::addTokenForArgument(SDValue Chain,
  4653. SelectionDAG &DAG,
  4654. MachineFrameInfo &MFI,
  4655. int ClobberedFI) const {
  4656. SmallVector<SDValue, 8> ArgChains;
  4657. int64_t FirstByte = MFI.getObjectOffset(ClobberedFI);
  4658. int64_t LastByte = FirstByte + MFI.getObjectSize(ClobberedFI) - 1;
  4659. // Include the original chain at the beginning of the list. When this is
  4660. // used by target LowerCall hooks, this helps legalize find the
  4661. // CALLSEQ_BEGIN node.
  4662. ArgChains.push_back(Chain);
  4663. // Add a chain value for each stack argument corresponding
  4664. for (SDNode::use_iterator U = DAG.getEntryNode().getNode()->use_begin(),
  4665. UE = DAG.getEntryNode().getNode()->use_end();
  4666. U != UE; ++U)
  4667. if (LoadSDNode *L = dyn_cast<LoadSDNode>(*U))
  4668. if (FrameIndexSDNode *FI = dyn_cast<FrameIndexSDNode>(L->getBasePtr()))
  4669. if (FI->getIndex() < 0) {
  4670. int64_t InFirstByte = MFI.getObjectOffset(FI->getIndex());
  4671. int64_t InLastByte = InFirstByte;
  4672. InLastByte += MFI.getObjectSize(FI->getIndex()) - 1;
  4673. if ((InFirstByte <= FirstByte && FirstByte <= InLastByte) ||
  4674. (FirstByte <= InFirstByte && InFirstByte <= LastByte))
  4675. ArgChains.push_back(SDValue(L, 1));
  4676. }
  4677. // Build a tokenfactor for all the chains.
  4678. return DAG.getNode(ISD::TokenFactor, SDLoc(Chain), MVT::Other, ArgChains);
  4679. }
  4680. bool AArch64TargetLowering::DoesCalleeRestoreStack(CallingConv::ID CallCC,
  4681. bool TailCallOpt) const {
  4682. return CallCC == CallingConv::Fast && TailCallOpt;
  4683. }
  4684. /// LowerCall - Lower a call to a callseq_start + CALL + callseq_end chain,
  4685. /// and add input and output parameter nodes.
  4686. SDValue
  4687. AArch64TargetLowering::LowerCall(CallLoweringInfo &CLI,
  4688. SmallVectorImpl<SDValue> &InVals) const {
  4689. SelectionDAG &DAG = CLI.DAG;
  4690. SDLoc &DL = CLI.DL;
  4691. SmallVector<ISD::OutputArg, 32> &Outs = CLI.Outs;
  4692. SmallVector<SDValue, 32> &OutVals = CLI.OutVals;
  4693. SmallVector<ISD::InputArg, 32> &Ins = CLI.Ins;
  4694. SDValue Chain = CLI.Chain;
  4695. SDValue Callee = CLI.Callee;
  4696. bool &IsTailCall = CLI.IsTailCall;
  4697. CallingConv::ID CallConv = CLI.CallConv;
  4698. bool IsVarArg = CLI.IsVarArg;
  4699. MachineFunction &MF = DAG.getMachineFunction();
  4700. MachineFunction::CallSiteInfo CSInfo;
  4701. bool IsThisReturn = false;
  4702. AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  4703. bool TailCallOpt = MF.getTarget().Options.GuaranteedTailCallOpt;
  4704. bool IsSibCall = false;
  4705. // Check callee args/returns for SVE registers and set calling convention
  4706. // accordingly.
  4707. if (CallConv == CallingConv::C) {
  4708. bool CalleeOutSVE = any_of(Outs, [](ISD::OutputArg &Out){
  4709. return Out.VT.isScalableVector();
  4710. });
  4711. bool CalleeInSVE = any_of(Ins, [](ISD::InputArg &In){
  4712. return In.VT.isScalableVector();
  4713. });
  4714. if (CalleeInSVE || CalleeOutSVE)
  4715. CallConv = CallingConv::AArch64_SVE_VectorCall;
  4716. }
  4717. if (IsTailCall) {
  4718. // Check if it's really possible to do a tail call.
  4719. IsTailCall = isEligibleForTailCallOptimization(
  4720. Callee, CallConv, IsVarArg, Outs, OutVals, Ins, DAG);
  4721. if (!IsTailCall && CLI.CB && CLI.CB->isMustTailCall())
  4722. report_fatal_error("failed to perform tail call elimination on a call "
  4723. "site marked musttail");
  4724. // A sibling call is one where we're under the usual C ABI and not planning
  4725. // to change that but can still do a tail call:
  4726. if (!TailCallOpt && IsTailCall)
  4727. IsSibCall = true;
  4728. if (IsTailCall)
  4729. ++NumTailCalls;
  4730. }
  4731. // Analyze operands of the call, assigning locations to each operand.
  4732. SmallVector<CCValAssign, 16> ArgLocs;
  4733. CCState CCInfo(CallConv, IsVarArg, DAG.getMachineFunction(), ArgLocs,
  4734. *DAG.getContext());
  4735. if (IsVarArg) {
  4736. // Handle fixed and variable vector arguments differently.
  4737. // Variable vector arguments always go into memory.
  4738. unsigned NumArgs = Outs.size();
  4739. for (unsigned i = 0; i != NumArgs; ++i) {
  4740. MVT ArgVT = Outs[i].VT;
  4741. if (!Outs[i].IsFixed && ArgVT.isScalableVector())
  4742. report_fatal_error("Passing SVE types to variadic functions is "
  4743. "currently not supported");
  4744. ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
  4745. CCAssignFn *AssignFn = CCAssignFnForCall(CallConv,
  4746. /*IsVarArg=*/ !Outs[i].IsFixed);
  4747. bool Res = AssignFn(i, ArgVT, ArgVT, CCValAssign::Full, ArgFlags, CCInfo);
  4748. assert(!Res && "Call operand has unhandled type");
  4749. (void)Res;
  4750. }
  4751. } else {
  4752. // At this point, Outs[].VT may already be promoted to i32. To correctly
  4753. // handle passing i8 as i8 instead of i32 on stack, we pass in both i32 and
  4754. // i8 to CC_AArch64_AAPCS with i32 being ValVT and i8 being LocVT.
  4755. // Since AnalyzeCallOperands uses Ins[].VT for both ValVT and LocVT, here
  4756. // we use a special version of AnalyzeCallOperands to pass in ValVT and
  4757. // LocVT.
  4758. unsigned NumArgs = Outs.size();
  4759. for (unsigned i = 0; i != NumArgs; ++i) {
  4760. MVT ValVT = Outs[i].VT;
  4761. // Get type of the original argument.
  4762. EVT ActualVT = getValueType(DAG.getDataLayout(),
  4763. CLI.getArgs()[Outs[i].OrigArgIndex].Ty,
  4764. /*AllowUnknown*/ true);
  4765. MVT ActualMVT = ActualVT.isSimple() ? ActualVT.getSimpleVT() : ValVT;
  4766. ISD::ArgFlagsTy ArgFlags = Outs[i].Flags;
  4767. // If ActualMVT is i1/i8/i16, we should set LocVT to i8/i8/i16.
  4768. if (ActualMVT == MVT::i1 || ActualMVT == MVT::i8)
  4769. ValVT = MVT::i8;
  4770. else if (ActualMVT == MVT::i16)
  4771. ValVT = MVT::i16;
  4772. CCAssignFn *AssignFn = CCAssignFnForCall(CallConv, /*IsVarArg=*/false);
  4773. bool Res = AssignFn(i, ValVT, ValVT, CCValAssign::Full, ArgFlags, CCInfo);
  4774. assert(!Res && "Call operand has unhandled type");
  4775. (void)Res;
  4776. }
  4777. }
  4778. // Get a count of how many bytes are to be pushed on the stack.
  4779. unsigned NumBytes = CCInfo.getNextStackOffset();
  4780. if (IsSibCall) {
  4781. // Since we're not changing the ABI to make this a tail call, the memory
  4782. // operands are already available in the caller's incoming argument space.
  4783. NumBytes = 0;
  4784. }
  4785. // FPDiff is the byte offset of the call's argument area from the callee's.
  4786. // Stores to callee stack arguments will be placed in FixedStackSlots offset
  4787. // by this amount for a tail call. In a sibling call it must be 0 because the
  4788. // caller will deallocate the entire stack and the callee still expects its
  4789. // arguments to begin at SP+0. Completely unused for non-tail calls.
  4790. int FPDiff = 0;
  4791. if (IsTailCall && !IsSibCall) {
  4792. unsigned NumReusableBytes = FuncInfo->getBytesInStackArgArea();
  4793. // Since callee will pop argument stack as a tail call, we must keep the
  4794. // popped size 16-byte aligned.
  4795. NumBytes = alignTo(NumBytes, 16);
  4796. // FPDiff will be negative if this tail call requires more space than we
  4797. // would automatically have in our incoming argument space. Positive if we
  4798. // can actually shrink the stack.
  4799. FPDiff = NumReusableBytes - NumBytes;
  4800. // The stack pointer must be 16-byte aligned at all times it's used for a
  4801. // memory operation, which in practice means at *all* times and in
  4802. // particular across call boundaries. Therefore our own arguments started at
  4803. // a 16-byte aligned SP and the delta applied for the tail call should
  4804. // satisfy the same constraint.
  4805. assert(FPDiff % 16 == 0 && "unaligned stack on tail call");
  4806. }
  4807. // Adjust the stack pointer for the new arguments...
  4808. // These operations are automatically eliminated by the prolog/epilog pass
  4809. if (!IsSibCall)
  4810. Chain = DAG.getCALLSEQ_START(Chain, NumBytes, 0, DL);
  4811. SDValue StackPtr = DAG.getCopyFromReg(Chain, DL, AArch64::SP,
  4812. getPointerTy(DAG.getDataLayout()));
  4813. SmallVector<std::pair<unsigned, SDValue>, 8> RegsToPass;
  4814. SmallSet<unsigned, 8> RegsUsed;
  4815. SmallVector<SDValue, 8> MemOpChains;
  4816. auto PtrVT = getPointerTy(DAG.getDataLayout());
  4817. if (IsVarArg && CLI.CB && CLI.CB->isMustTailCall()) {
  4818. const auto &Forwards = FuncInfo->getForwardedMustTailRegParms();
  4819. for (const auto &F : Forwards) {
  4820. SDValue Val = DAG.getCopyFromReg(Chain, DL, F.VReg, F.VT);
  4821. RegsToPass.emplace_back(F.PReg, Val);
  4822. }
  4823. }
  4824. // Walk the register/memloc assignments, inserting copies/loads.
  4825. unsigned ExtraArgLocs = 0;
  4826. for (unsigned i = 0, e = Outs.size(); i != e; ++i) {
  4827. CCValAssign &VA = ArgLocs[i - ExtraArgLocs];
  4828. SDValue Arg = OutVals[i];
  4829. ISD::ArgFlagsTy Flags = Outs[i].Flags;
  4830. // Promote the value if needed.
  4831. switch (VA.getLocInfo()) {
  4832. default:
  4833. llvm_unreachable("Unknown loc info!");
  4834. case CCValAssign::Full:
  4835. break;
  4836. case CCValAssign::SExt:
  4837. Arg = DAG.getNode(ISD::SIGN_EXTEND, DL, VA.getLocVT(), Arg);
  4838. break;
  4839. case CCValAssign::ZExt:
  4840. Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
  4841. break;
  4842. case CCValAssign::AExt:
  4843. if (Outs[i].ArgVT == MVT::i1) {
  4844. // AAPCS requires i1 to be zero-extended to 8-bits by the caller.
  4845. Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
  4846. Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i8, Arg);
  4847. }
  4848. Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
  4849. break;
  4850. case CCValAssign::AExtUpper:
  4851. assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
  4852. Arg = DAG.getNode(ISD::ANY_EXTEND, DL, VA.getLocVT(), Arg);
  4853. Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
  4854. DAG.getConstant(32, DL, VA.getLocVT()));
  4855. break;
  4856. case CCValAssign::BCvt:
  4857. Arg = DAG.getBitcast(VA.getLocVT(), Arg);
  4858. break;
  4859. case CCValAssign::Trunc:
  4860. Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
  4861. break;
  4862. case CCValAssign::FPExt:
  4863. Arg = DAG.getNode(ISD::FP_EXTEND, DL, VA.getLocVT(), Arg);
  4864. break;
  4865. case CCValAssign::Indirect:
  4866. assert(VA.getValVT().isScalableVector() &&
  4867. "Only scalable vectors can be passed indirectly");
  4868. uint64_t StoreSize = VA.getValVT().getStoreSize().getKnownMinSize();
  4869. uint64_t PartSize = StoreSize;
  4870. unsigned NumParts = 1;
  4871. if (Outs[i].Flags.isInConsecutiveRegs()) {
  4872. assert(!Outs[i].Flags.isInConsecutiveRegsLast());
  4873. while (!Outs[i + NumParts - 1].Flags.isInConsecutiveRegsLast())
  4874. ++NumParts;
  4875. StoreSize *= NumParts;
  4876. }
  4877. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  4878. Type *Ty = EVT(VA.getValVT()).getTypeForEVT(*DAG.getContext());
  4879. Align Alignment = DAG.getDataLayout().getPrefTypeAlign(Ty);
  4880. int FI = MFI.CreateStackObject(StoreSize, Alignment, false);
  4881. MFI.setStackID(FI, TargetStackID::ScalableVector);
  4882. MachinePointerInfo MPI =
  4883. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
  4884. SDValue Ptr = DAG.getFrameIndex(
  4885. FI, DAG.getTargetLoweringInfo().getFrameIndexTy(DAG.getDataLayout()));
  4886. SDValue SpillSlot = Ptr;
  4887. // Ensure we generate all stores for each tuple part, whilst updating the
  4888. // pointer after each store correctly using vscale.
  4889. while (NumParts) {
  4890. Chain = DAG.getStore(Chain, DL, OutVals[i], Ptr, MPI);
  4891. NumParts--;
  4892. if (NumParts > 0) {
  4893. SDValue BytesIncrement = DAG.getVScale(
  4894. DL, Ptr.getValueType(),
  4895. APInt(Ptr.getValueSizeInBits().getFixedSize(), PartSize));
  4896. SDNodeFlags Flags;
  4897. Flags.setNoUnsignedWrap(true);
  4898. MPI = MachinePointerInfo(MPI.getAddrSpace());
  4899. Ptr = DAG.getNode(ISD::ADD, DL, Ptr.getValueType(), Ptr,
  4900. BytesIncrement, Flags);
  4901. ExtraArgLocs++;
  4902. i++;
  4903. }
  4904. }
  4905. Arg = SpillSlot;
  4906. break;
  4907. }
  4908. if (VA.isRegLoc()) {
  4909. if (i == 0 && Flags.isReturned() && !Flags.isSwiftSelf() &&
  4910. Outs[0].VT == MVT::i64) {
  4911. assert(VA.getLocVT() == MVT::i64 &&
  4912. "unexpected calling convention register assignment");
  4913. assert(!Ins.empty() && Ins[0].VT == MVT::i64 &&
  4914. "unexpected use of 'returned'");
  4915. IsThisReturn = true;
  4916. }
  4917. if (RegsUsed.count(VA.getLocReg())) {
  4918. // If this register has already been used then we're trying to pack
  4919. // parts of an [N x i32] into an X-register. The extension type will
  4920. // take care of putting the two halves in the right place but we have to
  4921. // combine them.
  4922. SDValue &Bits =
  4923. llvm::find_if(RegsToPass,
  4924. [=](const std::pair<unsigned, SDValue> &Elt) {
  4925. return Elt.first == VA.getLocReg();
  4926. })
  4927. ->second;
  4928. Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
  4929. // Call site info is used for function's parameter entry value
  4930. // tracking. For now we track only simple cases when parameter
  4931. // is transferred through whole register.
  4932. llvm::erase_if(CSInfo, [&VA](MachineFunction::ArgRegPair ArgReg) {
  4933. return ArgReg.Reg == VA.getLocReg();
  4934. });
  4935. } else {
  4936. RegsToPass.emplace_back(VA.getLocReg(), Arg);
  4937. RegsUsed.insert(VA.getLocReg());
  4938. const TargetOptions &Options = DAG.getTarget().Options;
  4939. if (Options.EmitCallSiteInfo)
  4940. CSInfo.emplace_back(VA.getLocReg(), i);
  4941. }
  4942. } else {
  4943. assert(VA.isMemLoc());
  4944. SDValue DstAddr;
  4945. MachinePointerInfo DstInfo;
  4946. // FIXME: This works on big-endian for composite byvals, which are the
  4947. // common case. It should also work for fundamental types too.
  4948. uint32_t BEAlign = 0;
  4949. unsigned OpSize;
  4950. if (VA.getLocInfo() == CCValAssign::Indirect)
  4951. OpSize = VA.getLocVT().getFixedSizeInBits();
  4952. else
  4953. OpSize = Flags.isByVal() ? Flags.getByValSize() * 8
  4954. : VA.getValVT().getSizeInBits();
  4955. OpSize = (OpSize + 7) / 8;
  4956. if (!Subtarget->isLittleEndian() && !Flags.isByVal() &&
  4957. !Flags.isInConsecutiveRegs()) {
  4958. if (OpSize < 8)
  4959. BEAlign = 8 - OpSize;
  4960. }
  4961. unsigned LocMemOffset = VA.getLocMemOffset();
  4962. int32_t Offset = LocMemOffset + BEAlign;
  4963. SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
  4964. PtrOff = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
  4965. if (IsTailCall) {
  4966. Offset = Offset + FPDiff;
  4967. int FI = MF.getFrameInfo().CreateFixedObject(OpSize, Offset, true);
  4968. DstAddr = DAG.getFrameIndex(FI, PtrVT);
  4969. DstInfo =
  4970. MachinePointerInfo::getFixedStack(DAG.getMachineFunction(), FI);
  4971. // Make sure any stack arguments overlapping with where we're storing
  4972. // are loaded before this eventual operation. Otherwise they'll be
  4973. // clobbered.
  4974. Chain = addTokenForArgument(Chain, DAG, MF.getFrameInfo(), FI);
  4975. } else {
  4976. SDValue PtrOff = DAG.getIntPtrConstant(Offset, DL);
  4977. DstAddr = DAG.getNode(ISD::ADD, DL, PtrVT, StackPtr, PtrOff);
  4978. DstInfo = MachinePointerInfo::getStack(DAG.getMachineFunction(),
  4979. LocMemOffset);
  4980. }
  4981. if (Outs[i].Flags.isByVal()) {
  4982. SDValue SizeNode =
  4983. DAG.getConstant(Outs[i].Flags.getByValSize(), DL, MVT::i64);
  4984. SDValue Cpy = DAG.getMemcpy(
  4985. Chain, DL, DstAddr, Arg, SizeNode,
  4986. Outs[i].Flags.getNonZeroByValAlign(),
  4987. /*isVol = */ false, /*AlwaysInline = */ false,
  4988. /*isTailCall = */ false, DstInfo, MachinePointerInfo());
  4989. MemOpChains.push_back(Cpy);
  4990. } else {
  4991. // Since we pass i1/i8/i16 as i1/i8/i16 on stack and Arg is already
  4992. // promoted to a legal register type i32, we should truncate Arg back to
  4993. // i1/i8/i16.
  4994. if (VA.getValVT() == MVT::i1 || VA.getValVT() == MVT::i8 ||
  4995. VA.getValVT() == MVT::i16)
  4996. Arg = DAG.getNode(ISD::TRUNCATE, DL, VA.getValVT(), Arg);
  4997. SDValue Store = DAG.getStore(Chain, DL, Arg, DstAddr, DstInfo);
  4998. MemOpChains.push_back(Store);
  4999. }
  5000. }
  5001. }
  5002. if (!MemOpChains.empty())
  5003. Chain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOpChains);
  5004. // Build a sequence of copy-to-reg nodes chained together with token chain
  5005. // and flag operands which copy the outgoing args into the appropriate regs.
  5006. SDValue InFlag;
  5007. for (auto &RegToPass : RegsToPass) {
  5008. Chain = DAG.getCopyToReg(Chain, DL, RegToPass.first,
  5009. RegToPass.second, InFlag);
  5010. InFlag = Chain.getValue(1);
  5011. }
  5012. // If the callee is a GlobalAddress/ExternalSymbol node (quite common, every
  5013. // direct call is) turn it into a TargetGlobalAddress/TargetExternalSymbol
  5014. // node so that legalize doesn't hack it.
  5015. if (auto *G = dyn_cast<GlobalAddressSDNode>(Callee)) {
  5016. auto GV = G->getGlobal();
  5017. unsigned OpFlags =
  5018. Subtarget->classifyGlobalFunctionReference(GV, getTargetMachine());
  5019. if (OpFlags & AArch64II::MO_GOT) {
  5020. Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, OpFlags);
  5021. Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
  5022. } else {
  5023. const GlobalValue *GV = G->getGlobal();
  5024. Callee = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, 0);
  5025. }
  5026. } else if (auto *S = dyn_cast<ExternalSymbolSDNode>(Callee)) {
  5027. if (getTargetMachine().getCodeModel() == CodeModel::Large &&
  5028. Subtarget->isTargetMachO()) {
  5029. const char *Sym = S->getSymbol();
  5030. Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, AArch64II::MO_GOT);
  5031. Callee = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, Callee);
  5032. } else {
  5033. const char *Sym = S->getSymbol();
  5034. Callee = DAG.getTargetExternalSymbol(Sym, PtrVT, 0);
  5035. }
  5036. }
  5037. // We don't usually want to end the call-sequence here because we would tidy
  5038. // the frame up *after* the call, however in the ABI-changing tail-call case
  5039. // we've carefully laid out the parameters so that when sp is reset they'll be
  5040. // in the correct location.
  5041. if (IsTailCall && !IsSibCall) {
  5042. Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
  5043. DAG.getIntPtrConstant(0, DL, true), InFlag, DL);
  5044. InFlag = Chain.getValue(1);
  5045. }
  5046. std::vector<SDValue> Ops;
  5047. Ops.push_back(Chain);
  5048. Ops.push_back(Callee);
  5049. if (IsTailCall) {
  5050. // Each tail call may have to adjust the stack by a different amount, so
  5051. // this information must travel along with the operation for eventual
  5052. // consumption by emitEpilogue.
  5053. Ops.push_back(DAG.getTargetConstant(FPDiff, DL, MVT::i32));
  5054. }
  5055. // Add argument registers to the end of the list so that they are known live
  5056. // into the call.
  5057. for (auto &RegToPass : RegsToPass)
  5058. Ops.push_back(DAG.getRegister(RegToPass.first,
  5059. RegToPass.second.getValueType()));
  5060. // Add a register mask operand representing the call-preserved registers.
  5061. const uint32_t *Mask;
  5062. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
  5063. if (IsThisReturn) {
  5064. // For 'this' returns, use the X0-preserving mask if applicable
  5065. Mask = TRI->getThisReturnPreservedMask(MF, CallConv);
  5066. if (!Mask) {
  5067. IsThisReturn = false;
  5068. Mask = TRI->getCallPreservedMask(MF, CallConv);
  5069. }
  5070. } else
  5071. Mask = TRI->getCallPreservedMask(MF, CallConv);
  5072. if (Subtarget->hasCustomCallingConv())
  5073. TRI->UpdateCustomCallPreservedMask(MF, &Mask);
  5074. if (TRI->isAnyArgRegReserved(MF))
  5075. TRI->emitReservedArgRegCallError(MF);
  5076. assert(Mask && "Missing call preserved mask for calling convention");
  5077. Ops.push_back(DAG.getRegisterMask(Mask));
  5078. if (InFlag.getNode())
  5079. Ops.push_back(InFlag);
  5080. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5081. // If we're doing a tall call, use a TC_RETURN here rather than an
  5082. // actual call instruction.
  5083. if (IsTailCall) {
  5084. MF.getFrameInfo().setHasTailCall();
  5085. SDValue Ret = DAG.getNode(AArch64ISD::TC_RETURN, DL, NodeTys, Ops);
  5086. DAG.addCallSiteInfo(Ret.getNode(), std::move(CSInfo));
  5087. return Ret;
  5088. }
  5089. unsigned CallOpc = AArch64ISD::CALL;
  5090. // Calls marked with "rv_marker" are special. They should be expanded to the
  5091. // call, directly followed by a special marker sequence. Use the CALL_RVMARKER
  5092. // to do that.
  5093. if (CLI.CB && CLI.CB->hasRetAttr("rv_marker")) {
  5094. assert(!IsTailCall && "tail calls cannot be marked with rv_marker");
  5095. CallOpc = AArch64ISD::CALL_RVMARKER;
  5096. }
  5097. // Returns a chain and a flag for retval copy to use.
  5098. Chain = DAG.getNode(CallOpc, DL, NodeTys, Ops);
  5099. DAG.addNoMergeSiteInfo(Chain.getNode(), CLI.NoMerge);
  5100. InFlag = Chain.getValue(1);
  5101. DAG.addCallSiteInfo(Chain.getNode(), std::move(CSInfo));
  5102. uint64_t CalleePopBytes =
  5103. DoesCalleeRestoreStack(CallConv, TailCallOpt) ? alignTo(NumBytes, 16) : 0;
  5104. Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(NumBytes, DL, true),
  5105. DAG.getIntPtrConstant(CalleePopBytes, DL, true),
  5106. InFlag, DL);
  5107. if (!Ins.empty())
  5108. InFlag = Chain.getValue(1);
  5109. // Handle result values, copying them out of physregs into vregs that we
  5110. // return.
  5111. return LowerCallResult(Chain, InFlag, CallConv, IsVarArg, Ins, DL, DAG,
  5112. InVals, IsThisReturn,
  5113. IsThisReturn ? OutVals[0] : SDValue());
  5114. }
  5115. bool AArch64TargetLowering::CanLowerReturn(
  5116. CallingConv::ID CallConv, MachineFunction &MF, bool isVarArg,
  5117. const SmallVectorImpl<ISD::OutputArg> &Outs, LLVMContext &Context) const {
  5118. CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
  5119. SmallVector<CCValAssign, 16> RVLocs;
  5120. CCState CCInfo(CallConv, isVarArg, MF, RVLocs, Context);
  5121. return CCInfo.CheckReturn(Outs, RetCC);
  5122. }
  5123. SDValue
  5124. AArch64TargetLowering::LowerReturn(SDValue Chain, CallingConv::ID CallConv,
  5125. bool isVarArg,
  5126. const SmallVectorImpl<ISD::OutputArg> &Outs,
  5127. const SmallVectorImpl<SDValue> &OutVals,
  5128. const SDLoc &DL, SelectionDAG &DAG) const {
  5129. auto &MF = DAG.getMachineFunction();
  5130. auto *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  5131. CCAssignFn *RetCC = CCAssignFnForReturn(CallConv);
  5132. SmallVector<CCValAssign, 16> RVLocs;
  5133. CCState CCInfo(CallConv, isVarArg, DAG.getMachineFunction(), RVLocs,
  5134. *DAG.getContext());
  5135. CCInfo.AnalyzeReturn(Outs, RetCC);
  5136. // Copy the result values into the output registers.
  5137. SDValue Flag;
  5138. SmallVector<std::pair<unsigned, SDValue>, 4> RetVals;
  5139. SmallSet<unsigned, 4> RegsUsed;
  5140. for (unsigned i = 0, realRVLocIdx = 0; i != RVLocs.size();
  5141. ++i, ++realRVLocIdx) {
  5142. CCValAssign &VA = RVLocs[i];
  5143. assert(VA.isRegLoc() && "Can only return in registers!");
  5144. SDValue Arg = OutVals[realRVLocIdx];
  5145. switch (VA.getLocInfo()) {
  5146. default:
  5147. llvm_unreachable("Unknown loc info!");
  5148. case CCValAssign::Full:
  5149. if (Outs[i].ArgVT == MVT::i1) {
  5150. // AAPCS requires i1 to be zero-extended to i8 by the producer of the
  5151. // value. This is strictly redundant on Darwin (which uses "zeroext
  5152. // i1"), but will be optimised out before ISel.
  5153. Arg = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, Arg);
  5154. Arg = DAG.getNode(ISD::ZERO_EXTEND, DL, VA.getLocVT(), Arg);
  5155. }
  5156. break;
  5157. case CCValAssign::BCvt:
  5158. Arg = DAG.getNode(ISD::BITCAST, DL, VA.getLocVT(), Arg);
  5159. break;
  5160. case CCValAssign::AExt:
  5161. case CCValAssign::ZExt:
  5162. Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
  5163. break;
  5164. case CCValAssign::AExtUpper:
  5165. assert(VA.getValVT() == MVT::i32 && "only expect 32 -> 64 upper bits");
  5166. Arg = DAG.getZExtOrTrunc(Arg, DL, VA.getLocVT());
  5167. Arg = DAG.getNode(ISD::SHL, DL, VA.getLocVT(), Arg,
  5168. DAG.getConstant(32, DL, VA.getLocVT()));
  5169. break;
  5170. }
  5171. if (RegsUsed.count(VA.getLocReg())) {
  5172. SDValue &Bits =
  5173. llvm::find_if(RetVals, [=](const std::pair<unsigned, SDValue> &Elt) {
  5174. return Elt.first == VA.getLocReg();
  5175. })->second;
  5176. Bits = DAG.getNode(ISD::OR, DL, Bits.getValueType(), Bits, Arg);
  5177. } else {
  5178. RetVals.emplace_back(VA.getLocReg(), Arg);
  5179. RegsUsed.insert(VA.getLocReg());
  5180. }
  5181. }
  5182. SmallVector<SDValue, 4> RetOps(1, Chain);
  5183. for (auto &RetVal : RetVals) {
  5184. Chain = DAG.getCopyToReg(Chain, DL, RetVal.first, RetVal.second, Flag);
  5185. Flag = Chain.getValue(1);
  5186. RetOps.push_back(
  5187. DAG.getRegister(RetVal.first, RetVal.second.getValueType()));
  5188. }
  5189. // Windows AArch64 ABIs require that for returning structs by value we copy
  5190. // the sret argument into X0 for the return.
  5191. // We saved the argument into a virtual register in the entry block,
  5192. // so now we copy the value out and into X0.
  5193. if (unsigned SRetReg = FuncInfo->getSRetReturnReg()) {
  5194. SDValue Val = DAG.getCopyFromReg(RetOps[0], DL, SRetReg,
  5195. getPointerTy(MF.getDataLayout()));
  5196. unsigned RetValReg = AArch64::X0;
  5197. Chain = DAG.getCopyToReg(Chain, DL, RetValReg, Val, Flag);
  5198. Flag = Chain.getValue(1);
  5199. RetOps.push_back(
  5200. DAG.getRegister(RetValReg, getPointerTy(DAG.getDataLayout())));
  5201. }
  5202. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
  5203. const MCPhysReg *I =
  5204. TRI->getCalleeSavedRegsViaCopy(&DAG.getMachineFunction());
  5205. if (I) {
  5206. for (; *I; ++I) {
  5207. if (AArch64::GPR64RegClass.contains(*I))
  5208. RetOps.push_back(DAG.getRegister(*I, MVT::i64));
  5209. else if (AArch64::FPR64RegClass.contains(*I))
  5210. RetOps.push_back(DAG.getRegister(*I, MVT::getFloatingPointVT(64)));
  5211. else
  5212. llvm_unreachable("Unexpected register class in CSRsViaCopy!");
  5213. }
  5214. }
  5215. RetOps[0] = Chain; // Update chain.
  5216. // Add the flag if we have it.
  5217. if (Flag.getNode())
  5218. RetOps.push_back(Flag);
  5219. return DAG.getNode(AArch64ISD::RET_FLAG, DL, MVT::Other, RetOps);
  5220. }
  5221. //===----------------------------------------------------------------------===//
  5222. // Other Lowering Code
  5223. //===----------------------------------------------------------------------===//
  5224. SDValue AArch64TargetLowering::getTargetNode(GlobalAddressSDNode *N, EVT Ty,
  5225. SelectionDAG &DAG,
  5226. unsigned Flag) const {
  5227. return DAG.getTargetGlobalAddress(N->getGlobal(), SDLoc(N), Ty,
  5228. N->getOffset(), Flag);
  5229. }
  5230. SDValue AArch64TargetLowering::getTargetNode(JumpTableSDNode *N, EVT Ty,
  5231. SelectionDAG &DAG,
  5232. unsigned Flag) const {
  5233. return DAG.getTargetJumpTable(N->getIndex(), Ty, Flag);
  5234. }
  5235. SDValue AArch64TargetLowering::getTargetNode(ConstantPoolSDNode *N, EVT Ty,
  5236. SelectionDAG &DAG,
  5237. unsigned Flag) const {
  5238. return DAG.getTargetConstantPool(N->getConstVal(), Ty, N->getAlign(),
  5239. N->getOffset(), Flag);
  5240. }
  5241. SDValue AArch64TargetLowering::getTargetNode(BlockAddressSDNode* N, EVT Ty,
  5242. SelectionDAG &DAG,
  5243. unsigned Flag) const {
  5244. return DAG.getTargetBlockAddress(N->getBlockAddress(), Ty, 0, Flag);
  5245. }
  5246. // (loadGOT sym)
  5247. template <class NodeTy>
  5248. SDValue AArch64TargetLowering::getGOT(NodeTy *N, SelectionDAG &DAG,
  5249. unsigned Flags) const {
  5250. LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getGOT\n");
  5251. SDLoc DL(N);
  5252. EVT Ty = getPointerTy(DAG.getDataLayout());
  5253. SDValue GotAddr = getTargetNode(N, Ty, DAG, AArch64II::MO_GOT | Flags);
  5254. // FIXME: Once remat is capable of dealing with instructions with register
  5255. // operands, expand this into two nodes instead of using a wrapper node.
  5256. return DAG.getNode(AArch64ISD::LOADgot, DL, Ty, GotAddr);
  5257. }
  5258. // (wrapper %highest(sym), %higher(sym), %hi(sym), %lo(sym))
  5259. template <class NodeTy>
  5260. SDValue AArch64TargetLowering::getAddrLarge(NodeTy *N, SelectionDAG &DAG,
  5261. unsigned Flags) const {
  5262. LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrLarge\n");
  5263. SDLoc DL(N);
  5264. EVT Ty = getPointerTy(DAG.getDataLayout());
  5265. const unsigned char MO_NC = AArch64II::MO_NC;
  5266. return DAG.getNode(
  5267. AArch64ISD::WrapperLarge, DL, Ty,
  5268. getTargetNode(N, Ty, DAG, AArch64II::MO_G3 | Flags),
  5269. getTargetNode(N, Ty, DAG, AArch64II::MO_G2 | MO_NC | Flags),
  5270. getTargetNode(N, Ty, DAG, AArch64II::MO_G1 | MO_NC | Flags),
  5271. getTargetNode(N, Ty, DAG, AArch64II::MO_G0 | MO_NC | Flags));
  5272. }
  5273. // (addlow (adrp %hi(sym)) %lo(sym))
  5274. template <class NodeTy>
  5275. SDValue AArch64TargetLowering::getAddr(NodeTy *N, SelectionDAG &DAG,
  5276. unsigned Flags) const {
  5277. LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddr\n");
  5278. SDLoc DL(N);
  5279. EVT Ty = getPointerTy(DAG.getDataLayout());
  5280. SDValue Hi = getTargetNode(N, Ty, DAG, AArch64II::MO_PAGE | Flags);
  5281. SDValue Lo = getTargetNode(N, Ty, DAG,
  5282. AArch64II::MO_PAGEOFF | AArch64II::MO_NC | Flags);
  5283. SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, Ty, Hi);
  5284. return DAG.getNode(AArch64ISD::ADDlow, DL, Ty, ADRP, Lo);
  5285. }
  5286. // (adr sym)
  5287. template <class NodeTy>
  5288. SDValue AArch64TargetLowering::getAddrTiny(NodeTy *N, SelectionDAG &DAG,
  5289. unsigned Flags) const {
  5290. LLVM_DEBUG(dbgs() << "AArch64TargetLowering::getAddrTiny\n");
  5291. SDLoc DL(N);
  5292. EVT Ty = getPointerTy(DAG.getDataLayout());
  5293. SDValue Sym = getTargetNode(N, Ty, DAG, Flags);
  5294. return DAG.getNode(AArch64ISD::ADR, DL, Ty, Sym);
  5295. }
  5296. SDValue AArch64TargetLowering::LowerGlobalAddress(SDValue Op,
  5297. SelectionDAG &DAG) const {
  5298. GlobalAddressSDNode *GN = cast<GlobalAddressSDNode>(Op);
  5299. const GlobalValue *GV = GN->getGlobal();
  5300. unsigned OpFlags = Subtarget->ClassifyGlobalReference(GV, getTargetMachine());
  5301. if (OpFlags != AArch64II::MO_NO_FLAG)
  5302. assert(cast<GlobalAddressSDNode>(Op)->getOffset() == 0 &&
  5303. "unexpected offset in global node");
  5304. // This also catches the large code model case for Darwin, and tiny code
  5305. // model with got relocations.
  5306. if ((OpFlags & AArch64II::MO_GOT) != 0) {
  5307. return getGOT(GN, DAG, OpFlags);
  5308. }
  5309. SDValue Result;
  5310. if (getTargetMachine().getCodeModel() == CodeModel::Large) {
  5311. Result = getAddrLarge(GN, DAG, OpFlags);
  5312. } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
  5313. Result = getAddrTiny(GN, DAG, OpFlags);
  5314. } else {
  5315. Result = getAddr(GN, DAG, OpFlags);
  5316. }
  5317. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  5318. SDLoc DL(GN);
  5319. if (OpFlags & (AArch64II::MO_DLLIMPORT | AArch64II::MO_COFFSTUB))
  5320. Result = DAG.getLoad(PtrVT, DL, DAG.getEntryNode(), Result,
  5321. MachinePointerInfo::getGOT(DAG.getMachineFunction()));
  5322. return Result;
  5323. }
  5324. /// Convert a TLS address reference into the correct sequence of loads
  5325. /// and calls to compute the variable's address (for Darwin, currently) and
  5326. /// return an SDValue containing the final node.
  5327. /// Darwin only has one TLS scheme which must be capable of dealing with the
  5328. /// fully general situation, in the worst case. This means:
  5329. /// + "extern __thread" declaration.
  5330. /// + Defined in a possibly unknown dynamic library.
  5331. ///
  5332. /// The general system is that each __thread variable has a [3 x i64] descriptor
  5333. /// which contains information used by the runtime to calculate the address. The
  5334. /// only part of this the compiler needs to know about is the first xword, which
  5335. /// contains a function pointer that must be called with the address of the
  5336. /// entire descriptor in "x0".
  5337. ///
  5338. /// Since this descriptor may be in a different unit, in general even the
  5339. /// descriptor must be accessed via an indirect load. The "ideal" code sequence
  5340. /// is:
  5341. /// adrp x0, _var@TLVPPAGE
  5342. /// ldr x0, [x0, _var@TLVPPAGEOFF] ; x0 now contains address of descriptor
  5343. /// ldr x1, [x0] ; x1 contains 1st entry of descriptor,
  5344. /// ; the function pointer
  5345. /// blr x1 ; Uses descriptor address in x0
  5346. /// ; Address of _var is now in x0.
  5347. ///
  5348. /// If the address of _var's descriptor *is* known to the linker, then it can
  5349. /// change the first "ldr" instruction to an appropriate "add x0, x0, #imm" for
  5350. /// a slight efficiency gain.
  5351. SDValue
  5352. AArch64TargetLowering::LowerDarwinGlobalTLSAddress(SDValue Op,
  5353. SelectionDAG &DAG) const {
  5354. assert(Subtarget->isTargetDarwin() &&
  5355. "This function expects a Darwin target");
  5356. SDLoc DL(Op);
  5357. MVT PtrVT = getPointerTy(DAG.getDataLayout());
  5358. MVT PtrMemVT = getPointerMemTy(DAG.getDataLayout());
  5359. const GlobalValue *GV = cast<GlobalAddressSDNode>(Op)->getGlobal();
  5360. SDValue TLVPAddr =
  5361. DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
  5362. SDValue DescAddr = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TLVPAddr);
  5363. // The first entry in the descriptor is a function pointer that we must call
  5364. // to obtain the address of the variable.
  5365. SDValue Chain = DAG.getEntryNode();
  5366. SDValue FuncTLVGet = DAG.getLoad(
  5367. PtrMemVT, DL, Chain, DescAddr,
  5368. MachinePointerInfo::getGOT(DAG.getMachineFunction()),
  5369. Align(PtrMemVT.getSizeInBits() / 8),
  5370. MachineMemOperand::MOInvariant | MachineMemOperand::MODereferenceable);
  5371. Chain = FuncTLVGet.getValue(1);
  5372. // Extend loaded pointer if necessary (i.e. if ILP32) to DAG pointer.
  5373. FuncTLVGet = DAG.getZExtOrTrunc(FuncTLVGet, DL, PtrVT);
  5374. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  5375. MFI.setAdjustsStack(true);
  5376. // TLS calls preserve all registers except those that absolutely must be
  5377. // trashed: X0 (it takes an argument), LR (it's a call) and NZCV (let's not be
  5378. // silly).
  5379. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
  5380. const uint32_t *Mask = TRI->getTLSCallPreservedMask();
  5381. if (Subtarget->hasCustomCallingConv())
  5382. TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
  5383. // Finally, we can make the call. This is just a degenerate version of a
  5384. // normal AArch64 call node: x0 takes the address of the descriptor, and
  5385. // returns the address of the variable in this thread.
  5386. Chain = DAG.getCopyToReg(Chain, DL, AArch64::X0, DescAddr, SDValue());
  5387. Chain =
  5388. DAG.getNode(AArch64ISD::CALL, DL, DAG.getVTList(MVT::Other, MVT::Glue),
  5389. Chain, FuncTLVGet, DAG.getRegister(AArch64::X0, MVT::i64),
  5390. DAG.getRegisterMask(Mask), Chain.getValue(1));
  5391. return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Chain.getValue(1));
  5392. }
  5393. /// Convert a thread-local variable reference into a sequence of instructions to
  5394. /// compute the variable's address for the local exec TLS model of ELF targets.
  5395. /// The sequence depends on the maximum TLS area size.
  5396. SDValue AArch64TargetLowering::LowerELFTLSLocalExec(const GlobalValue *GV,
  5397. SDValue ThreadBase,
  5398. const SDLoc &DL,
  5399. SelectionDAG &DAG) const {
  5400. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  5401. SDValue TPOff, Addr;
  5402. switch (DAG.getTarget().Options.TLSSize) {
  5403. default:
  5404. llvm_unreachable("Unexpected TLS size");
  5405. case 12: {
  5406. // mrs x0, TPIDR_EL0
  5407. // add x0, x0, :tprel_lo12:a
  5408. SDValue Var = DAG.getTargetGlobalAddress(
  5409. GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_PAGEOFF);
  5410. return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
  5411. Var,
  5412. DAG.getTargetConstant(0, DL, MVT::i32)),
  5413. 0);
  5414. }
  5415. case 24: {
  5416. // mrs x0, TPIDR_EL0
  5417. // add x0, x0, :tprel_hi12:a
  5418. // add x0, x0, :tprel_lo12_nc:a
  5419. SDValue HiVar = DAG.getTargetGlobalAddress(
  5420. GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
  5421. SDValue LoVar = DAG.getTargetGlobalAddress(
  5422. GV, DL, PtrVT, 0,
  5423. AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  5424. Addr = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, ThreadBase,
  5425. HiVar,
  5426. DAG.getTargetConstant(0, DL, MVT::i32)),
  5427. 0);
  5428. return SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, Addr,
  5429. LoVar,
  5430. DAG.getTargetConstant(0, DL, MVT::i32)),
  5431. 0);
  5432. }
  5433. case 32: {
  5434. // mrs x1, TPIDR_EL0
  5435. // movz x0, #:tprel_g1:a
  5436. // movk x0, #:tprel_g0_nc:a
  5437. // add x0, x1, x0
  5438. SDValue HiVar = DAG.getTargetGlobalAddress(
  5439. GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G1);
  5440. SDValue LoVar = DAG.getTargetGlobalAddress(
  5441. GV, DL, PtrVT, 0,
  5442. AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
  5443. TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
  5444. DAG.getTargetConstant(16, DL, MVT::i32)),
  5445. 0);
  5446. TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
  5447. DAG.getTargetConstant(0, DL, MVT::i32)),
  5448. 0);
  5449. return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
  5450. }
  5451. case 48: {
  5452. // mrs x1, TPIDR_EL0
  5453. // movz x0, #:tprel_g2:a
  5454. // movk x0, #:tprel_g1_nc:a
  5455. // movk x0, #:tprel_g0_nc:a
  5456. // add x0, x1, x0
  5457. SDValue HiVar = DAG.getTargetGlobalAddress(
  5458. GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_G2);
  5459. SDValue MiVar = DAG.getTargetGlobalAddress(
  5460. GV, DL, PtrVT, 0,
  5461. AArch64II::MO_TLS | AArch64II::MO_G1 | AArch64II::MO_NC);
  5462. SDValue LoVar = DAG.getTargetGlobalAddress(
  5463. GV, DL, PtrVT, 0,
  5464. AArch64II::MO_TLS | AArch64II::MO_G0 | AArch64II::MO_NC);
  5465. TPOff = SDValue(DAG.getMachineNode(AArch64::MOVZXi, DL, PtrVT, HiVar,
  5466. DAG.getTargetConstant(32, DL, MVT::i32)),
  5467. 0);
  5468. TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, MiVar,
  5469. DAG.getTargetConstant(16, DL, MVT::i32)),
  5470. 0);
  5471. TPOff = SDValue(DAG.getMachineNode(AArch64::MOVKXi, DL, PtrVT, TPOff, LoVar,
  5472. DAG.getTargetConstant(0, DL, MVT::i32)),
  5473. 0);
  5474. return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
  5475. }
  5476. }
  5477. }
  5478. /// When accessing thread-local variables under either the general-dynamic or
  5479. /// local-dynamic system, we make a "TLS-descriptor" call. The variable will
  5480. /// have a descriptor, accessible via a PC-relative ADRP, and whose first entry
  5481. /// is a function pointer to carry out the resolution.
  5482. ///
  5483. /// The sequence is:
  5484. /// adrp x0, :tlsdesc:var
  5485. /// ldr x1, [x0, #:tlsdesc_lo12:var]
  5486. /// add x0, x0, #:tlsdesc_lo12:var
  5487. /// .tlsdesccall var
  5488. /// blr x1
  5489. /// (TPIDR_EL0 offset now in x0)
  5490. ///
  5491. /// The above sequence must be produced unscheduled, to enable the linker to
  5492. /// optimize/relax this sequence.
  5493. /// Therefore, a pseudo-instruction (TLSDESC_CALLSEQ) is used to represent the
  5494. /// above sequence, and expanded really late in the compilation flow, to ensure
  5495. /// the sequence is produced as per above.
  5496. SDValue AArch64TargetLowering::LowerELFTLSDescCallSeq(SDValue SymAddr,
  5497. const SDLoc &DL,
  5498. SelectionDAG &DAG) const {
  5499. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  5500. SDValue Chain = DAG.getEntryNode();
  5501. SDVTList NodeTys = DAG.getVTList(MVT::Other, MVT::Glue);
  5502. Chain =
  5503. DAG.getNode(AArch64ISD::TLSDESC_CALLSEQ, DL, NodeTys, {Chain, SymAddr});
  5504. SDValue Glue = Chain.getValue(1);
  5505. return DAG.getCopyFromReg(Chain, DL, AArch64::X0, PtrVT, Glue);
  5506. }
  5507. SDValue
  5508. AArch64TargetLowering::LowerELFGlobalTLSAddress(SDValue Op,
  5509. SelectionDAG &DAG) const {
  5510. assert(Subtarget->isTargetELF() && "This function expects an ELF target");
  5511. const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
  5512. TLSModel::Model Model = getTargetMachine().getTLSModel(GA->getGlobal());
  5513. if (!EnableAArch64ELFLocalDynamicTLSGeneration) {
  5514. if (Model == TLSModel::LocalDynamic)
  5515. Model = TLSModel::GeneralDynamic;
  5516. }
  5517. if (getTargetMachine().getCodeModel() == CodeModel::Large &&
  5518. Model != TLSModel::LocalExec)
  5519. report_fatal_error("ELF TLS only supported in small memory model or "
  5520. "in local exec TLS model");
  5521. // Different choices can be made for the maximum size of the TLS area for a
  5522. // module. For the small address model, the default TLS size is 16MiB and the
  5523. // maximum TLS size is 4GiB.
  5524. // FIXME: add tiny and large code model support for TLS access models other
  5525. // than local exec. We currently generate the same code as small for tiny,
  5526. // which may be larger than needed.
  5527. SDValue TPOff;
  5528. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  5529. SDLoc DL(Op);
  5530. const GlobalValue *GV = GA->getGlobal();
  5531. SDValue ThreadBase = DAG.getNode(AArch64ISD::THREAD_POINTER, DL, PtrVT);
  5532. if (Model == TLSModel::LocalExec) {
  5533. return LowerELFTLSLocalExec(GV, ThreadBase, DL, DAG);
  5534. } else if (Model == TLSModel::InitialExec) {
  5535. TPOff = DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
  5536. TPOff = DAG.getNode(AArch64ISD::LOADgot, DL, PtrVT, TPOff);
  5537. } else if (Model == TLSModel::LocalDynamic) {
  5538. // Local-dynamic accesses proceed in two phases. A general-dynamic TLS
  5539. // descriptor call against the special symbol _TLS_MODULE_BASE_ to calculate
  5540. // the beginning of the module's TLS region, followed by a DTPREL offset
  5541. // calculation.
  5542. // These accesses will need deduplicating if there's more than one.
  5543. AArch64FunctionInfo *MFI =
  5544. DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
  5545. MFI->incNumLocalDynamicTLSAccesses();
  5546. // The call needs a relocation too for linker relaxation. It doesn't make
  5547. // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
  5548. // the address.
  5549. SDValue SymAddr = DAG.getTargetExternalSymbol("_TLS_MODULE_BASE_", PtrVT,
  5550. AArch64II::MO_TLS);
  5551. // Now we can calculate the offset from TPIDR_EL0 to this module's
  5552. // thread-local area.
  5553. TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
  5554. // Now use :dtprel_whatever: operations to calculate this variable's offset
  5555. // in its thread-storage area.
  5556. SDValue HiVar = DAG.getTargetGlobalAddress(
  5557. GV, DL, MVT::i64, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
  5558. SDValue LoVar = DAG.getTargetGlobalAddress(
  5559. GV, DL, MVT::i64, 0,
  5560. AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  5561. TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, HiVar,
  5562. DAG.getTargetConstant(0, DL, MVT::i32)),
  5563. 0);
  5564. TPOff = SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TPOff, LoVar,
  5565. DAG.getTargetConstant(0, DL, MVT::i32)),
  5566. 0);
  5567. } else if (Model == TLSModel::GeneralDynamic) {
  5568. // The call needs a relocation too for linker relaxation. It doesn't make
  5569. // sense to call it MO_PAGE or MO_PAGEOFF though so we need another copy of
  5570. // the address.
  5571. SDValue SymAddr =
  5572. DAG.getTargetGlobalAddress(GV, DL, PtrVT, 0, AArch64II::MO_TLS);
  5573. // Finally we can make a call to calculate the offset from tpidr_el0.
  5574. TPOff = LowerELFTLSDescCallSeq(SymAddr, DL, DAG);
  5575. } else
  5576. llvm_unreachable("Unsupported ELF TLS access model");
  5577. return DAG.getNode(ISD::ADD, DL, PtrVT, ThreadBase, TPOff);
  5578. }
  5579. SDValue
  5580. AArch64TargetLowering::LowerWindowsGlobalTLSAddress(SDValue Op,
  5581. SelectionDAG &DAG) const {
  5582. assert(Subtarget->isTargetWindows() && "Windows specific TLS lowering");
  5583. SDValue Chain = DAG.getEntryNode();
  5584. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  5585. SDLoc DL(Op);
  5586. SDValue TEB = DAG.getRegister(AArch64::X18, MVT::i64);
  5587. // Load the ThreadLocalStoragePointer from the TEB
  5588. // A pointer to the TLS array is located at offset 0x58 from the TEB.
  5589. SDValue TLSArray =
  5590. DAG.getNode(ISD::ADD, DL, PtrVT, TEB, DAG.getIntPtrConstant(0x58, DL));
  5591. TLSArray = DAG.getLoad(PtrVT, DL, Chain, TLSArray, MachinePointerInfo());
  5592. Chain = TLSArray.getValue(1);
  5593. // Load the TLS index from the C runtime;
  5594. // This does the same as getAddr(), but without having a GlobalAddressSDNode.
  5595. // This also does the same as LOADgot, but using a generic i32 load,
  5596. // while LOADgot only loads i64.
  5597. SDValue TLSIndexHi =
  5598. DAG.getTargetExternalSymbol("_tls_index", PtrVT, AArch64II::MO_PAGE);
  5599. SDValue TLSIndexLo = DAG.getTargetExternalSymbol(
  5600. "_tls_index", PtrVT, AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  5601. SDValue ADRP = DAG.getNode(AArch64ISD::ADRP, DL, PtrVT, TLSIndexHi);
  5602. SDValue TLSIndex =
  5603. DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, ADRP, TLSIndexLo);
  5604. TLSIndex = DAG.getLoad(MVT::i32, DL, Chain, TLSIndex, MachinePointerInfo());
  5605. Chain = TLSIndex.getValue(1);
  5606. // The pointer to the thread's TLS data area is at the TLS Index scaled by 8
  5607. // offset into the TLSArray.
  5608. TLSIndex = DAG.getNode(ISD::ZERO_EXTEND, DL, PtrVT, TLSIndex);
  5609. SDValue Slot = DAG.getNode(ISD::SHL, DL, PtrVT, TLSIndex,
  5610. DAG.getConstant(3, DL, PtrVT));
  5611. SDValue TLS = DAG.getLoad(PtrVT, DL, Chain,
  5612. DAG.getNode(ISD::ADD, DL, PtrVT, TLSArray, Slot),
  5613. MachinePointerInfo());
  5614. Chain = TLS.getValue(1);
  5615. const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
  5616. const GlobalValue *GV = GA->getGlobal();
  5617. SDValue TGAHi = DAG.getTargetGlobalAddress(
  5618. GV, DL, PtrVT, 0, AArch64II::MO_TLS | AArch64II::MO_HI12);
  5619. SDValue TGALo = DAG.getTargetGlobalAddress(
  5620. GV, DL, PtrVT, 0,
  5621. AArch64II::MO_TLS | AArch64II::MO_PAGEOFF | AArch64II::MO_NC);
  5622. // Add the offset from the start of the .tls section (section base).
  5623. SDValue Addr =
  5624. SDValue(DAG.getMachineNode(AArch64::ADDXri, DL, PtrVT, TLS, TGAHi,
  5625. DAG.getTargetConstant(0, DL, MVT::i32)),
  5626. 0);
  5627. Addr = DAG.getNode(AArch64ISD::ADDlow, DL, PtrVT, Addr, TGALo);
  5628. return Addr;
  5629. }
  5630. SDValue AArch64TargetLowering::LowerGlobalTLSAddress(SDValue Op,
  5631. SelectionDAG &DAG) const {
  5632. const GlobalAddressSDNode *GA = cast<GlobalAddressSDNode>(Op);
  5633. if (DAG.getTarget().useEmulatedTLS())
  5634. return LowerToTLSEmulatedModel(GA, DAG);
  5635. if (Subtarget->isTargetDarwin())
  5636. return LowerDarwinGlobalTLSAddress(Op, DAG);
  5637. if (Subtarget->isTargetELF())
  5638. return LowerELFGlobalTLSAddress(Op, DAG);
  5639. if (Subtarget->isTargetWindows())
  5640. return LowerWindowsGlobalTLSAddress(Op, DAG);
  5641. llvm_unreachable("Unexpected platform trying to use TLS");
  5642. }
  5643. // Looks through \param Val to determine the bit that can be used to
  5644. // check the sign of the value. It returns the unextended value and
  5645. // the sign bit position.
  5646. std::pair<SDValue, uint64_t> lookThroughSignExtension(SDValue Val) {
  5647. if (Val.getOpcode() == ISD::SIGN_EXTEND_INREG)
  5648. return {Val.getOperand(0),
  5649. cast<VTSDNode>(Val.getOperand(1))->getVT().getFixedSizeInBits() -
  5650. 1};
  5651. if (Val.getOpcode() == ISD::SIGN_EXTEND)
  5652. return {Val.getOperand(0),
  5653. Val.getOperand(0)->getValueType(0).getFixedSizeInBits() - 1};
  5654. return {Val, Val.getValueSizeInBits() - 1};
  5655. }
  5656. SDValue AArch64TargetLowering::LowerBR_CC(SDValue Op, SelectionDAG &DAG) const {
  5657. SDValue Chain = Op.getOperand(0);
  5658. ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(1))->get();
  5659. SDValue LHS = Op.getOperand(2);
  5660. SDValue RHS = Op.getOperand(3);
  5661. SDValue Dest = Op.getOperand(4);
  5662. SDLoc dl(Op);
  5663. MachineFunction &MF = DAG.getMachineFunction();
  5664. // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
  5665. // will not be produced, as they are conditional branch instructions that do
  5666. // not set flags.
  5667. bool ProduceNonFlagSettingCondBr =
  5668. !MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening);
  5669. // Handle f128 first, since lowering it will result in comparing the return
  5670. // value of a libcall against zero, which is just what the rest of LowerBR_CC
  5671. // is expecting to deal with.
  5672. if (LHS.getValueType() == MVT::f128) {
  5673. softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
  5674. // If softenSetCCOperands returned a scalar, we need to compare the result
  5675. // against zero to select between true and false values.
  5676. if (!RHS.getNode()) {
  5677. RHS = DAG.getConstant(0, dl, LHS.getValueType());
  5678. CC = ISD::SETNE;
  5679. }
  5680. }
  5681. // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a branch
  5682. // instruction.
  5683. if (ISD::isOverflowIntrOpRes(LHS) && isOneConstant(RHS) &&
  5684. (CC == ISD::SETEQ || CC == ISD::SETNE)) {
  5685. // Only lower legal XALUO ops.
  5686. if (!DAG.getTargetLoweringInfo().isTypeLegal(LHS->getValueType(0)))
  5687. return SDValue();
  5688. // The actual operation with overflow check.
  5689. AArch64CC::CondCode OFCC;
  5690. SDValue Value, Overflow;
  5691. std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, LHS.getValue(0), DAG);
  5692. if (CC == ISD::SETNE)
  5693. OFCC = getInvertedCondCode(OFCC);
  5694. SDValue CCVal = DAG.getConstant(OFCC, dl, MVT::i32);
  5695. return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
  5696. Overflow);
  5697. }
  5698. if (LHS.getValueType().isInteger()) {
  5699. assert((LHS.getValueType() == RHS.getValueType()) &&
  5700. (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
  5701. // If the RHS of the comparison is zero, we can potentially fold this
  5702. // to a specialized branch.
  5703. const ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(RHS);
  5704. if (RHSC && RHSC->getZExtValue() == 0 && ProduceNonFlagSettingCondBr) {
  5705. if (CC == ISD::SETEQ) {
  5706. // See if we can use a TBZ to fold in an AND as well.
  5707. // TBZ has a smaller branch displacement than CBZ. If the offset is
  5708. // out of bounds, a late MI-layer pass rewrites branches.
  5709. // 403.gcc is an example that hits this case.
  5710. if (LHS.getOpcode() == ISD::AND &&
  5711. isa<ConstantSDNode>(LHS.getOperand(1)) &&
  5712. isPowerOf2_64(LHS.getConstantOperandVal(1))) {
  5713. SDValue Test = LHS.getOperand(0);
  5714. uint64_t Mask = LHS.getConstantOperandVal(1);
  5715. return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, Test,
  5716. DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
  5717. Dest);
  5718. }
  5719. return DAG.getNode(AArch64ISD::CBZ, dl, MVT::Other, Chain, LHS, Dest);
  5720. } else if (CC == ISD::SETNE) {
  5721. // See if we can use a TBZ to fold in an AND as well.
  5722. // TBZ has a smaller branch displacement than CBZ. If the offset is
  5723. // out of bounds, a late MI-layer pass rewrites branches.
  5724. // 403.gcc is an example that hits this case.
  5725. if (LHS.getOpcode() == ISD::AND &&
  5726. isa<ConstantSDNode>(LHS.getOperand(1)) &&
  5727. isPowerOf2_64(LHS.getConstantOperandVal(1))) {
  5728. SDValue Test = LHS.getOperand(0);
  5729. uint64_t Mask = LHS.getConstantOperandVal(1);
  5730. return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, Test,
  5731. DAG.getConstant(Log2_64(Mask), dl, MVT::i64),
  5732. Dest);
  5733. }
  5734. return DAG.getNode(AArch64ISD::CBNZ, dl, MVT::Other, Chain, LHS, Dest);
  5735. } else if (CC == ISD::SETLT && LHS.getOpcode() != ISD::AND) {
  5736. // Don't combine AND since emitComparison converts the AND to an ANDS
  5737. // (a.k.a. TST) and the test in the test bit and branch instruction
  5738. // becomes redundant. This would also increase register pressure.
  5739. uint64_t SignBitPos;
  5740. std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
  5741. return DAG.getNode(AArch64ISD::TBNZ, dl, MVT::Other, Chain, LHS,
  5742. DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
  5743. }
  5744. }
  5745. if (RHSC && RHSC->getSExtValue() == -1 && CC == ISD::SETGT &&
  5746. LHS.getOpcode() != ISD::AND && ProduceNonFlagSettingCondBr) {
  5747. // Don't combine AND since emitComparison converts the AND to an ANDS
  5748. // (a.k.a. TST) and the test in the test bit and branch instruction
  5749. // becomes redundant. This would also increase register pressure.
  5750. uint64_t SignBitPos;
  5751. std::tie(LHS, SignBitPos) = lookThroughSignExtension(LHS);
  5752. return DAG.getNode(AArch64ISD::TBZ, dl, MVT::Other, Chain, LHS,
  5753. DAG.getConstant(SignBitPos, dl, MVT::i64), Dest);
  5754. }
  5755. SDValue CCVal;
  5756. SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
  5757. return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CCVal,
  5758. Cmp);
  5759. }
  5760. assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::bf16 ||
  5761. LHS.getValueType() == MVT::f32 || LHS.getValueType() == MVT::f64);
  5762. // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
  5763. // clean. Some of them require two branches to implement.
  5764. SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
  5765. AArch64CC::CondCode CC1, CC2;
  5766. changeFPCCToAArch64CC(CC, CC1, CC2);
  5767. SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
  5768. SDValue BR1 =
  5769. DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, Chain, Dest, CC1Val, Cmp);
  5770. if (CC2 != AArch64CC::AL) {
  5771. SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
  5772. return DAG.getNode(AArch64ISD::BRCOND, dl, MVT::Other, BR1, Dest, CC2Val,
  5773. Cmp);
  5774. }
  5775. return BR1;
  5776. }
  5777. SDValue AArch64TargetLowering::LowerFCOPYSIGN(SDValue Op,
  5778. SelectionDAG &DAG) const {
  5779. EVT VT = Op.getValueType();
  5780. SDLoc DL(Op);
  5781. SDValue In1 = Op.getOperand(0);
  5782. SDValue In2 = Op.getOperand(1);
  5783. EVT SrcVT = In2.getValueType();
  5784. if (SrcVT.bitsLT(VT))
  5785. In2 = DAG.getNode(ISD::FP_EXTEND, DL, VT, In2);
  5786. else if (SrcVT.bitsGT(VT))
  5787. In2 = DAG.getNode(ISD::FP_ROUND, DL, VT, In2, DAG.getIntPtrConstant(0, DL));
  5788. EVT VecVT;
  5789. uint64_t EltMask;
  5790. SDValue VecVal1, VecVal2;
  5791. auto setVecVal = [&] (int Idx) {
  5792. if (!VT.isVector()) {
  5793. VecVal1 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
  5794. DAG.getUNDEF(VecVT), In1);
  5795. VecVal2 = DAG.getTargetInsertSubreg(Idx, DL, VecVT,
  5796. DAG.getUNDEF(VecVT), In2);
  5797. } else {
  5798. VecVal1 = DAG.getNode(ISD::BITCAST, DL, VecVT, In1);
  5799. VecVal2 = DAG.getNode(ISD::BITCAST, DL, VecVT, In2);
  5800. }
  5801. };
  5802. if (VT == MVT::f32 || VT == MVT::v2f32 || VT == MVT::v4f32) {
  5803. VecVT = (VT == MVT::v2f32 ? MVT::v2i32 : MVT::v4i32);
  5804. EltMask = 0x80000000ULL;
  5805. setVecVal(AArch64::ssub);
  5806. } else if (VT == MVT::f64 || VT == MVT::v2f64) {
  5807. VecVT = MVT::v2i64;
  5808. // We want to materialize a mask with the high bit set, but the AdvSIMD
  5809. // immediate moves cannot materialize that in a single instruction for
  5810. // 64-bit elements. Instead, materialize zero and then negate it.
  5811. EltMask = 0;
  5812. setVecVal(AArch64::dsub);
  5813. } else if (VT == MVT::f16 || VT == MVT::v4f16 || VT == MVT::v8f16) {
  5814. VecVT = (VT == MVT::v4f16 ? MVT::v4i16 : MVT::v8i16);
  5815. EltMask = 0x8000ULL;
  5816. setVecVal(AArch64::hsub);
  5817. } else {
  5818. llvm_unreachable("Invalid type for copysign!");
  5819. }
  5820. SDValue BuildVec = DAG.getConstant(EltMask, DL, VecVT);
  5821. // If we couldn't materialize the mask above, then the mask vector will be
  5822. // the zero vector, and we need to negate it here.
  5823. if (VT == MVT::f64 || VT == MVT::v2f64) {
  5824. BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2f64, BuildVec);
  5825. BuildVec = DAG.getNode(ISD::FNEG, DL, MVT::v2f64, BuildVec);
  5826. BuildVec = DAG.getNode(ISD::BITCAST, DL, MVT::v2i64, BuildVec);
  5827. }
  5828. SDValue Sel =
  5829. DAG.getNode(AArch64ISD::BIT, DL, VecVT, VecVal1, VecVal2, BuildVec);
  5830. if (VT == MVT::f16)
  5831. return DAG.getTargetExtractSubreg(AArch64::hsub, DL, VT, Sel);
  5832. if (VT == MVT::f32)
  5833. return DAG.getTargetExtractSubreg(AArch64::ssub, DL, VT, Sel);
  5834. else if (VT == MVT::f64)
  5835. return DAG.getTargetExtractSubreg(AArch64::dsub, DL, VT, Sel);
  5836. else
  5837. return DAG.getNode(ISD::BITCAST, DL, VT, Sel);
  5838. }
  5839. SDValue AArch64TargetLowering::LowerCTPOP(SDValue Op, SelectionDAG &DAG) const {
  5840. if (DAG.getMachineFunction().getFunction().hasFnAttribute(
  5841. Attribute::NoImplicitFloat))
  5842. return SDValue();
  5843. if (!Subtarget->hasNEON())
  5844. return SDValue();
  5845. // While there is no integer popcount instruction, it can
  5846. // be more efficiently lowered to the following sequence that uses
  5847. // AdvSIMD registers/instructions as long as the copies to/from
  5848. // the AdvSIMD registers are cheap.
  5849. // FMOV D0, X0 // copy 64-bit int to vector, high bits zero'd
  5850. // CNT V0.8B, V0.8B // 8xbyte pop-counts
  5851. // ADDV B0, V0.8B // sum 8xbyte pop-counts
  5852. // UMOV X0, V0.B[0] // copy byte result back to integer reg
  5853. SDValue Val = Op.getOperand(0);
  5854. SDLoc DL(Op);
  5855. EVT VT = Op.getValueType();
  5856. if (VT == MVT::i32 || VT == MVT::i64) {
  5857. if (VT == MVT::i32)
  5858. Val = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, Val);
  5859. Val = DAG.getNode(ISD::BITCAST, DL, MVT::v8i8, Val);
  5860. SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v8i8, Val);
  5861. SDValue UaddLV = DAG.getNode(
  5862. ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
  5863. DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
  5864. if (VT == MVT::i64)
  5865. UaddLV = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i64, UaddLV);
  5866. return UaddLV;
  5867. } else if (VT == MVT::i128) {
  5868. Val = DAG.getNode(ISD::BITCAST, DL, MVT::v16i8, Val);
  5869. SDValue CtPop = DAG.getNode(ISD::CTPOP, DL, MVT::v16i8, Val);
  5870. SDValue UaddLV = DAG.getNode(
  5871. ISD::INTRINSIC_WO_CHAIN, DL, MVT::i32,
  5872. DAG.getConstant(Intrinsic::aarch64_neon_uaddlv, DL, MVT::i32), CtPop);
  5873. return DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i128, UaddLV);
  5874. }
  5875. if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
  5876. return LowerToPredicatedOp(Op, DAG, AArch64ISD::CTPOP_MERGE_PASSTHRU);
  5877. assert((VT == MVT::v1i64 || VT == MVT::v2i64 || VT == MVT::v2i32 ||
  5878. VT == MVT::v4i32 || VT == MVT::v4i16 || VT == MVT::v8i16) &&
  5879. "Unexpected type for custom ctpop lowering");
  5880. EVT VT8Bit = VT.is64BitVector() ? MVT::v8i8 : MVT::v16i8;
  5881. Val = DAG.getBitcast(VT8Bit, Val);
  5882. Val = DAG.getNode(ISD::CTPOP, DL, VT8Bit, Val);
  5883. // Widen v8i8/v16i8 CTPOP result to VT by repeatedly widening pairwise adds.
  5884. unsigned EltSize = 8;
  5885. unsigned NumElts = VT.is64BitVector() ? 8 : 16;
  5886. while (EltSize != VT.getScalarSizeInBits()) {
  5887. EltSize *= 2;
  5888. NumElts /= 2;
  5889. MVT WidenVT = MVT::getVectorVT(MVT::getIntegerVT(EltSize), NumElts);
  5890. Val = DAG.getNode(
  5891. ISD::INTRINSIC_WO_CHAIN, DL, WidenVT,
  5892. DAG.getConstant(Intrinsic::aarch64_neon_uaddlp, DL, MVT::i32), Val);
  5893. }
  5894. return Val;
  5895. }
  5896. SDValue AArch64TargetLowering::LowerCTTZ(SDValue Op, SelectionDAG &DAG) const {
  5897. EVT VT = Op.getValueType();
  5898. assert(VT.isScalableVector() ||
  5899. useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true));
  5900. SDLoc DL(Op);
  5901. SDValue RBIT = DAG.getNode(ISD::BITREVERSE, DL, VT, Op.getOperand(0));
  5902. return DAG.getNode(ISD::CTLZ, DL, VT, RBIT);
  5903. }
  5904. SDValue AArch64TargetLowering::LowerSETCC(SDValue Op, SelectionDAG &DAG) const {
  5905. if (Op.getValueType().isVector())
  5906. return LowerVSETCC(Op, DAG);
  5907. bool IsStrict = Op->isStrictFPOpcode();
  5908. bool IsSignaling = Op.getOpcode() == ISD::STRICT_FSETCCS;
  5909. unsigned OpNo = IsStrict ? 1 : 0;
  5910. SDValue Chain;
  5911. if (IsStrict)
  5912. Chain = Op.getOperand(0);
  5913. SDValue LHS = Op.getOperand(OpNo + 0);
  5914. SDValue RHS = Op.getOperand(OpNo + 1);
  5915. ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(OpNo + 2))->get();
  5916. SDLoc dl(Op);
  5917. // We chose ZeroOrOneBooleanContents, so use zero and one.
  5918. EVT VT = Op.getValueType();
  5919. SDValue TVal = DAG.getConstant(1, dl, VT);
  5920. SDValue FVal = DAG.getConstant(0, dl, VT);
  5921. // Handle f128 first, since one possible outcome is a normal integer
  5922. // comparison which gets picked up by the next if statement.
  5923. if (LHS.getValueType() == MVT::f128) {
  5924. softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS, Chain,
  5925. IsSignaling);
  5926. // If softenSetCCOperands returned a scalar, use it.
  5927. if (!RHS.getNode()) {
  5928. assert(LHS.getValueType() == Op.getValueType() &&
  5929. "Unexpected setcc expansion!");
  5930. return IsStrict ? DAG.getMergeValues({LHS, Chain}, dl) : LHS;
  5931. }
  5932. }
  5933. if (LHS.getValueType().isInteger()) {
  5934. SDValue CCVal;
  5935. SDValue Cmp = getAArch64Cmp(
  5936. LHS, RHS, ISD::getSetCCInverse(CC, LHS.getValueType()), CCVal, DAG, dl);
  5937. // Note that we inverted the condition above, so we reverse the order of
  5938. // the true and false operands here. This will allow the setcc to be
  5939. // matched to a single CSINC instruction.
  5940. SDValue Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CCVal, Cmp);
  5941. return IsStrict ? DAG.getMergeValues({Res, Chain}, dl) : Res;
  5942. }
  5943. // Now we know we're dealing with FP values.
  5944. assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
  5945. LHS.getValueType() == MVT::f64);
  5946. // If that fails, we'll need to perform an FCMP + CSEL sequence. Go ahead
  5947. // and do the comparison.
  5948. SDValue Cmp;
  5949. if (IsStrict)
  5950. Cmp = emitStrictFPComparison(LHS, RHS, dl, DAG, Chain, IsSignaling);
  5951. else
  5952. Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
  5953. AArch64CC::CondCode CC1, CC2;
  5954. changeFPCCToAArch64CC(CC, CC1, CC2);
  5955. SDValue Res;
  5956. if (CC2 == AArch64CC::AL) {
  5957. changeFPCCToAArch64CC(ISD::getSetCCInverse(CC, LHS.getValueType()), CC1,
  5958. CC2);
  5959. SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
  5960. // Note that we inverted the condition above, so we reverse the order of
  5961. // the true and false operands here. This will allow the setcc to be
  5962. // matched to a single CSINC instruction.
  5963. Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, FVal, TVal, CC1Val, Cmp);
  5964. } else {
  5965. // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't
  5966. // totally clean. Some of them require two CSELs to implement. As is in
  5967. // this case, we emit the first CSEL and then emit a second using the output
  5968. // of the first as the RHS. We're effectively OR'ing the two CC's together.
  5969. // FIXME: It would be nice if we could match the two CSELs to two CSINCs.
  5970. SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
  5971. SDValue CS1 =
  5972. DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
  5973. SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
  5974. Res = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
  5975. }
  5976. return IsStrict ? DAG.getMergeValues({Res, Cmp.getValue(1)}, dl) : Res;
  5977. }
  5978. SDValue AArch64TargetLowering::LowerSELECT_CC(ISD::CondCode CC, SDValue LHS,
  5979. SDValue RHS, SDValue TVal,
  5980. SDValue FVal, const SDLoc &dl,
  5981. SelectionDAG &DAG) const {
  5982. // Handle f128 first, because it will result in a comparison of some RTLIB
  5983. // call result against zero.
  5984. if (LHS.getValueType() == MVT::f128) {
  5985. softenSetCCOperands(DAG, MVT::f128, LHS, RHS, CC, dl, LHS, RHS);
  5986. // If softenSetCCOperands returned a scalar, we need to compare the result
  5987. // against zero to select between true and false values.
  5988. if (!RHS.getNode()) {
  5989. RHS = DAG.getConstant(0, dl, LHS.getValueType());
  5990. CC = ISD::SETNE;
  5991. }
  5992. }
  5993. // Also handle f16, for which we need to do a f32 comparison.
  5994. if (LHS.getValueType() == MVT::f16 && !Subtarget->hasFullFP16()) {
  5995. LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, LHS);
  5996. RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::f32, RHS);
  5997. }
  5998. // Next, handle integers.
  5999. if (LHS.getValueType().isInteger()) {
  6000. assert((LHS.getValueType() == RHS.getValueType()) &&
  6001. (LHS.getValueType() == MVT::i32 || LHS.getValueType() == MVT::i64));
  6002. unsigned Opcode = AArch64ISD::CSEL;
  6003. // If both the TVal and the FVal are constants, see if we can swap them in
  6004. // order to for a CSINV or CSINC out of them.
  6005. ConstantSDNode *CFVal = dyn_cast<ConstantSDNode>(FVal);
  6006. ConstantSDNode *CTVal = dyn_cast<ConstantSDNode>(TVal);
  6007. if (CTVal && CFVal && CTVal->isAllOnesValue() && CFVal->isNullValue()) {
  6008. std::swap(TVal, FVal);
  6009. std::swap(CTVal, CFVal);
  6010. CC = ISD::getSetCCInverse(CC, LHS.getValueType());
  6011. } else if (CTVal && CFVal && CTVal->isOne() && CFVal->isNullValue()) {
  6012. std::swap(TVal, FVal);
  6013. std::swap(CTVal, CFVal);
  6014. CC = ISD::getSetCCInverse(CC, LHS.getValueType());
  6015. } else if (TVal.getOpcode() == ISD::XOR) {
  6016. // If TVal is a NOT we want to swap TVal and FVal so that we can match
  6017. // with a CSINV rather than a CSEL.
  6018. if (isAllOnesConstant(TVal.getOperand(1))) {
  6019. std::swap(TVal, FVal);
  6020. std::swap(CTVal, CFVal);
  6021. CC = ISD::getSetCCInverse(CC, LHS.getValueType());
  6022. }
  6023. } else if (TVal.getOpcode() == ISD::SUB) {
  6024. // If TVal is a negation (SUB from 0) we want to swap TVal and FVal so
  6025. // that we can match with a CSNEG rather than a CSEL.
  6026. if (isNullConstant(TVal.getOperand(0))) {
  6027. std::swap(TVal, FVal);
  6028. std::swap(CTVal, CFVal);
  6029. CC = ISD::getSetCCInverse(CC, LHS.getValueType());
  6030. }
  6031. } else if (CTVal && CFVal) {
  6032. const int64_t TrueVal = CTVal->getSExtValue();
  6033. const int64_t FalseVal = CFVal->getSExtValue();
  6034. bool Swap = false;
  6035. // If both TVal and FVal are constants, see if FVal is the
  6036. // inverse/negation/increment of TVal and generate a CSINV/CSNEG/CSINC
  6037. // instead of a CSEL in that case.
  6038. if (TrueVal == ~FalseVal) {
  6039. Opcode = AArch64ISD::CSINV;
  6040. } else if (FalseVal > std::numeric_limits<int64_t>::min() &&
  6041. TrueVal == -FalseVal) {
  6042. Opcode = AArch64ISD::CSNEG;
  6043. } else if (TVal.getValueType() == MVT::i32) {
  6044. // If our operands are only 32-bit wide, make sure we use 32-bit
  6045. // arithmetic for the check whether we can use CSINC. This ensures that
  6046. // the addition in the check will wrap around properly in case there is
  6047. // an overflow (which would not be the case if we do the check with
  6048. // 64-bit arithmetic).
  6049. const uint32_t TrueVal32 = CTVal->getZExtValue();
  6050. const uint32_t FalseVal32 = CFVal->getZExtValue();
  6051. if ((TrueVal32 == FalseVal32 + 1) || (TrueVal32 + 1 == FalseVal32)) {
  6052. Opcode = AArch64ISD::CSINC;
  6053. if (TrueVal32 > FalseVal32) {
  6054. Swap = true;
  6055. }
  6056. }
  6057. // 64-bit check whether we can use CSINC.
  6058. } else if ((TrueVal == FalseVal + 1) || (TrueVal + 1 == FalseVal)) {
  6059. Opcode = AArch64ISD::CSINC;
  6060. if (TrueVal > FalseVal) {
  6061. Swap = true;
  6062. }
  6063. }
  6064. // Swap TVal and FVal if necessary.
  6065. if (Swap) {
  6066. std::swap(TVal, FVal);
  6067. std::swap(CTVal, CFVal);
  6068. CC = ISD::getSetCCInverse(CC, LHS.getValueType());
  6069. }
  6070. if (Opcode != AArch64ISD::CSEL) {
  6071. // Drop FVal since we can get its value by simply inverting/negating
  6072. // TVal.
  6073. FVal = TVal;
  6074. }
  6075. }
  6076. // Avoid materializing a constant when possible by reusing a known value in
  6077. // a register. However, don't perform this optimization if the known value
  6078. // is one, zero or negative one in the case of a CSEL. We can always
  6079. // materialize these values using CSINC, CSEL and CSINV with wzr/xzr as the
  6080. // FVal, respectively.
  6081. ConstantSDNode *RHSVal = dyn_cast<ConstantSDNode>(RHS);
  6082. if (Opcode == AArch64ISD::CSEL && RHSVal && !RHSVal->isOne() &&
  6083. !RHSVal->isNullValue() && !RHSVal->isAllOnesValue()) {
  6084. AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
  6085. // Transform "a == C ? C : x" to "a == C ? a : x" and "a != C ? x : C" to
  6086. // "a != C ? x : a" to avoid materializing C.
  6087. if (CTVal && CTVal == RHSVal && AArch64CC == AArch64CC::EQ)
  6088. TVal = LHS;
  6089. else if (CFVal && CFVal == RHSVal && AArch64CC == AArch64CC::NE)
  6090. FVal = LHS;
  6091. } else if (Opcode == AArch64ISD::CSNEG && RHSVal && RHSVal->isOne()) {
  6092. assert (CTVal && CFVal && "Expected constant operands for CSNEG.");
  6093. // Use a CSINV to transform "a == C ? 1 : -1" to "a == C ? a : -1" to
  6094. // avoid materializing C.
  6095. AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
  6096. if (CTVal == RHSVal && AArch64CC == AArch64CC::EQ) {
  6097. Opcode = AArch64ISD::CSINV;
  6098. TVal = LHS;
  6099. FVal = DAG.getConstant(0, dl, FVal.getValueType());
  6100. }
  6101. }
  6102. SDValue CCVal;
  6103. SDValue Cmp = getAArch64Cmp(LHS, RHS, CC, CCVal, DAG, dl);
  6104. EVT VT = TVal.getValueType();
  6105. return DAG.getNode(Opcode, dl, VT, TVal, FVal, CCVal, Cmp);
  6106. }
  6107. // Now we know we're dealing with FP values.
  6108. assert(LHS.getValueType() == MVT::f16 || LHS.getValueType() == MVT::f32 ||
  6109. LHS.getValueType() == MVT::f64);
  6110. assert(LHS.getValueType() == RHS.getValueType());
  6111. EVT VT = TVal.getValueType();
  6112. SDValue Cmp = emitComparison(LHS, RHS, CC, dl, DAG);
  6113. // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
  6114. // clean. Some of them require two CSELs to implement.
  6115. AArch64CC::CondCode CC1, CC2;
  6116. changeFPCCToAArch64CC(CC, CC1, CC2);
  6117. if (DAG.getTarget().Options.UnsafeFPMath) {
  6118. // Transform "a == 0.0 ? 0.0 : x" to "a == 0.0 ? a : x" and
  6119. // "a != 0.0 ? x : 0.0" to "a != 0.0 ? x : a" to avoid materializing 0.0.
  6120. ConstantFPSDNode *RHSVal = dyn_cast<ConstantFPSDNode>(RHS);
  6121. if (RHSVal && RHSVal->isZero()) {
  6122. ConstantFPSDNode *CFVal = dyn_cast<ConstantFPSDNode>(FVal);
  6123. ConstantFPSDNode *CTVal = dyn_cast<ConstantFPSDNode>(TVal);
  6124. if ((CC == ISD::SETEQ || CC == ISD::SETOEQ || CC == ISD::SETUEQ) &&
  6125. CTVal && CTVal->isZero() && TVal.getValueType() == LHS.getValueType())
  6126. TVal = LHS;
  6127. else if ((CC == ISD::SETNE || CC == ISD::SETONE || CC == ISD::SETUNE) &&
  6128. CFVal && CFVal->isZero() &&
  6129. FVal.getValueType() == LHS.getValueType())
  6130. FVal = LHS;
  6131. }
  6132. }
  6133. // Emit first, and possibly only, CSEL.
  6134. SDValue CC1Val = DAG.getConstant(CC1, dl, MVT::i32);
  6135. SDValue CS1 = DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, FVal, CC1Val, Cmp);
  6136. // If we need a second CSEL, emit it, using the output of the first as the
  6137. // RHS. We're effectively OR'ing the two CC's together.
  6138. if (CC2 != AArch64CC::AL) {
  6139. SDValue CC2Val = DAG.getConstant(CC2, dl, MVT::i32);
  6140. return DAG.getNode(AArch64ISD::CSEL, dl, VT, TVal, CS1, CC2Val, Cmp);
  6141. }
  6142. // Otherwise, return the output of the first CSEL.
  6143. return CS1;
  6144. }
  6145. SDValue AArch64TargetLowering::LowerSELECT_CC(SDValue Op,
  6146. SelectionDAG &DAG) const {
  6147. ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(4))->get();
  6148. SDValue LHS = Op.getOperand(0);
  6149. SDValue RHS = Op.getOperand(1);
  6150. SDValue TVal = Op.getOperand(2);
  6151. SDValue FVal = Op.getOperand(3);
  6152. SDLoc DL(Op);
  6153. return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
  6154. }
  6155. SDValue AArch64TargetLowering::LowerSELECT(SDValue Op,
  6156. SelectionDAG &DAG) const {
  6157. SDValue CCVal = Op->getOperand(0);
  6158. SDValue TVal = Op->getOperand(1);
  6159. SDValue FVal = Op->getOperand(2);
  6160. SDLoc DL(Op);
  6161. EVT Ty = Op.getValueType();
  6162. if (Ty.isScalableVector()) {
  6163. SDValue TruncCC = DAG.getNode(ISD::TRUNCATE, DL, MVT::i1, CCVal);
  6164. MVT PredVT = MVT::getVectorVT(MVT::i1, Ty.getVectorElementCount());
  6165. SDValue SplatPred = DAG.getNode(ISD::SPLAT_VECTOR, DL, PredVT, TruncCC);
  6166. return DAG.getNode(ISD::VSELECT, DL, Ty, SplatPred, TVal, FVal);
  6167. }
  6168. // Optimize {s|u}{add|sub|mul}.with.overflow feeding into a select
  6169. // instruction.
  6170. if (ISD::isOverflowIntrOpRes(CCVal)) {
  6171. // Only lower legal XALUO ops.
  6172. if (!DAG.getTargetLoweringInfo().isTypeLegal(CCVal->getValueType(0)))
  6173. return SDValue();
  6174. AArch64CC::CondCode OFCC;
  6175. SDValue Value, Overflow;
  6176. std::tie(Value, Overflow) = getAArch64XALUOOp(OFCC, CCVal.getValue(0), DAG);
  6177. SDValue CCVal = DAG.getConstant(OFCC, DL, MVT::i32);
  6178. return DAG.getNode(AArch64ISD::CSEL, DL, Op.getValueType(), TVal, FVal,
  6179. CCVal, Overflow);
  6180. }
  6181. // Lower it the same way as we would lower a SELECT_CC node.
  6182. ISD::CondCode CC;
  6183. SDValue LHS, RHS;
  6184. if (CCVal.getOpcode() == ISD::SETCC) {
  6185. LHS = CCVal.getOperand(0);
  6186. RHS = CCVal.getOperand(1);
  6187. CC = cast<CondCodeSDNode>(CCVal->getOperand(2))->get();
  6188. } else {
  6189. LHS = CCVal;
  6190. RHS = DAG.getConstant(0, DL, CCVal.getValueType());
  6191. CC = ISD::SETNE;
  6192. }
  6193. return LowerSELECT_CC(CC, LHS, RHS, TVal, FVal, DL, DAG);
  6194. }
  6195. SDValue AArch64TargetLowering::LowerJumpTable(SDValue Op,
  6196. SelectionDAG &DAG) const {
  6197. // Jump table entries as PC relative offsets. No additional tweaking
  6198. // is necessary here. Just get the address of the jump table.
  6199. JumpTableSDNode *JT = cast<JumpTableSDNode>(Op);
  6200. if (getTargetMachine().getCodeModel() == CodeModel::Large &&
  6201. !Subtarget->isTargetMachO()) {
  6202. return getAddrLarge(JT, DAG);
  6203. } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
  6204. return getAddrTiny(JT, DAG);
  6205. }
  6206. return getAddr(JT, DAG);
  6207. }
  6208. SDValue AArch64TargetLowering::LowerBR_JT(SDValue Op,
  6209. SelectionDAG &DAG) const {
  6210. // Jump table entries as PC relative offsets. No additional tweaking
  6211. // is necessary here. Just get the address of the jump table.
  6212. SDLoc DL(Op);
  6213. SDValue JT = Op.getOperand(1);
  6214. SDValue Entry = Op.getOperand(2);
  6215. int JTI = cast<JumpTableSDNode>(JT.getNode())->getIndex();
  6216. auto *AFI = DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
  6217. AFI->setJumpTableEntryInfo(JTI, 4, nullptr);
  6218. SDNode *Dest =
  6219. DAG.getMachineNode(AArch64::JumpTableDest32, DL, MVT::i64, MVT::i64, JT,
  6220. Entry, DAG.getTargetJumpTable(JTI, MVT::i32));
  6221. return DAG.getNode(ISD::BRIND, DL, MVT::Other, Op.getOperand(0),
  6222. SDValue(Dest, 0));
  6223. }
  6224. SDValue AArch64TargetLowering::LowerConstantPool(SDValue Op,
  6225. SelectionDAG &DAG) const {
  6226. ConstantPoolSDNode *CP = cast<ConstantPoolSDNode>(Op);
  6227. if (getTargetMachine().getCodeModel() == CodeModel::Large) {
  6228. // Use the GOT for the large code model on iOS.
  6229. if (Subtarget->isTargetMachO()) {
  6230. return getGOT(CP, DAG);
  6231. }
  6232. return getAddrLarge(CP, DAG);
  6233. } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
  6234. return getAddrTiny(CP, DAG);
  6235. } else {
  6236. return getAddr(CP, DAG);
  6237. }
  6238. }
  6239. SDValue AArch64TargetLowering::LowerBlockAddress(SDValue Op,
  6240. SelectionDAG &DAG) const {
  6241. BlockAddressSDNode *BA = cast<BlockAddressSDNode>(Op);
  6242. if (getTargetMachine().getCodeModel() == CodeModel::Large &&
  6243. !Subtarget->isTargetMachO()) {
  6244. return getAddrLarge(BA, DAG);
  6245. } else if (getTargetMachine().getCodeModel() == CodeModel::Tiny) {
  6246. return getAddrTiny(BA, DAG);
  6247. }
  6248. return getAddr(BA, DAG);
  6249. }
  6250. SDValue AArch64TargetLowering::LowerDarwin_VASTART(SDValue Op,
  6251. SelectionDAG &DAG) const {
  6252. AArch64FunctionInfo *FuncInfo =
  6253. DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
  6254. SDLoc DL(Op);
  6255. SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(),
  6256. getPointerTy(DAG.getDataLayout()));
  6257. FR = DAG.getZExtOrTrunc(FR, DL, getPointerMemTy(DAG.getDataLayout()));
  6258. const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  6259. return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
  6260. MachinePointerInfo(SV));
  6261. }
  6262. SDValue AArch64TargetLowering::LowerWin64_VASTART(SDValue Op,
  6263. SelectionDAG &DAG) const {
  6264. AArch64FunctionInfo *FuncInfo =
  6265. DAG.getMachineFunction().getInfo<AArch64FunctionInfo>();
  6266. SDLoc DL(Op);
  6267. SDValue FR = DAG.getFrameIndex(FuncInfo->getVarArgsGPRSize() > 0
  6268. ? FuncInfo->getVarArgsGPRIndex()
  6269. : FuncInfo->getVarArgsStackIndex(),
  6270. getPointerTy(DAG.getDataLayout()));
  6271. const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  6272. return DAG.getStore(Op.getOperand(0), DL, FR, Op.getOperand(1),
  6273. MachinePointerInfo(SV));
  6274. }
  6275. SDValue AArch64TargetLowering::LowerAAPCS_VASTART(SDValue Op,
  6276. SelectionDAG &DAG) const {
  6277. // The layout of the va_list struct is specified in the AArch64 Procedure Call
  6278. // Standard, section B.3.
  6279. MachineFunction &MF = DAG.getMachineFunction();
  6280. AArch64FunctionInfo *FuncInfo = MF.getInfo<AArch64FunctionInfo>();
  6281. unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
  6282. auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
  6283. auto PtrVT = getPointerTy(DAG.getDataLayout());
  6284. SDLoc DL(Op);
  6285. SDValue Chain = Op.getOperand(0);
  6286. SDValue VAList = Op.getOperand(1);
  6287. const Value *SV = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  6288. SmallVector<SDValue, 4> MemOps;
  6289. // void *__stack at offset 0
  6290. unsigned Offset = 0;
  6291. SDValue Stack = DAG.getFrameIndex(FuncInfo->getVarArgsStackIndex(), PtrVT);
  6292. Stack = DAG.getZExtOrTrunc(Stack, DL, PtrMemVT);
  6293. MemOps.push_back(DAG.getStore(Chain, DL, Stack, VAList,
  6294. MachinePointerInfo(SV), Align(PtrSize)));
  6295. // void *__gr_top at offset 8 (4 on ILP32)
  6296. Offset += PtrSize;
  6297. int GPRSize = FuncInfo->getVarArgsGPRSize();
  6298. if (GPRSize > 0) {
  6299. SDValue GRTop, GRTopAddr;
  6300. GRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
  6301. DAG.getConstant(Offset, DL, PtrVT));
  6302. GRTop = DAG.getFrameIndex(FuncInfo->getVarArgsGPRIndex(), PtrVT);
  6303. GRTop = DAG.getNode(ISD::ADD, DL, PtrVT, GRTop,
  6304. DAG.getConstant(GPRSize, DL, PtrVT));
  6305. GRTop = DAG.getZExtOrTrunc(GRTop, DL, PtrMemVT);
  6306. MemOps.push_back(DAG.getStore(Chain, DL, GRTop, GRTopAddr,
  6307. MachinePointerInfo(SV, Offset),
  6308. Align(PtrSize)));
  6309. }
  6310. // void *__vr_top at offset 16 (8 on ILP32)
  6311. Offset += PtrSize;
  6312. int FPRSize = FuncInfo->getVarArgsFPRSize();
  6313. if (FPRSize > 0) {
  6314. SDValue VRTop, VRTopAddr;
  6315. VRTopAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
  6316. DAG.getConstant(Offset, DL, PtrVT));
  6317. VRTop = DAG.getFrameIndex(FuncInfo->getVarArgsFPRIndex(), PtrVT);
  6318. VRTop = DAG.getNode(ISD::ADD, DL, PtrVT, VRTop,
  6319. DAG.getConstant(FPRSize, DL, PtrVT));
  6320. VRTop = DAG.getZExtOrTrunc(VRTop, DL, PtrMemVT);
  6321. MemOps.push_back(DAG.getStore(Chain, DL, VRTop, VRTopAddr,
  6322. MachinePointerInfo(SV, Offset),
  6323. Align(PtrSize)));
  6324. }
  6325. // int __gr_offs at offset 24 (12 on ILP32)
  6326. Offset += PtrSize;
  6327. SDValue GROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
  6328. DAG.getConstant(Offset, DL, PtrVT));
  6329. MemOps.push_back(
  6330. DAG.getStore(Chain, DL, DAG.getConstant(-GPRSize, DL, MVT::i32),
  6331. GROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
  6332. // int __vr_offs at offset 28 (16 on ILP32)
  6333. Offset += 4;
  6334. SDValue VROffsAddr = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
  6335. DAG.getConstant(Offset, DL, PtrVT));
  6336. MemOps.push_back(
  6337. DAG.getStore(Chain, DL, DAG.getConstant(-FPRSize, DL, MVT::i32),
  6338. VROffsAddr, MachinePointerInfo(SV, Offset), Align(4)));
  6339. return DAG.getNode(ISD::TokenFactor, DL, MVT::Other, MemOps);
  6340. }
  6341. SDValue AArch64TargetLowering::LowerVASTART(SDValue Op,
  6342. SelectionDAG &DAG) const {
  6343. MachineFunction &MF = DAG.getMachineFunction();
  6344. if (Subtarget->isCallingConvWin64(MF.getFunction().getCallingConv()))
  6345. return LowerWin64_VASTART(Op, DAG);
  6346. else if (Subtarget->isTargetDarwin())
  6347. return LowerDarwin_VASTART(Op, DAG);
  6348. else
  6349. return LowerAAPCS_VASTART(Op, DAG);
  6350. }
  6351. SDValue AArch64TargetLowering::LowerVACOPY(SDValue Op,
  6352. SelectionDAG &DAG) const {
  6353. // AAPCS has three pointers and two ints (= 32 bytes), Darwin has single
  6354. // pointer.
  6355. SDLoc DL(Op);
  6356. unsigned PtrSize = Subtarget->isTargetILP32() ? 4 : 8;
  6357. unsigned VaListSize =
  6358. (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
  6359. ? PtrSize
  6360. : Subtarget->isTargetILP32() ? 20 : 32;
  6361. const Value *DestSV = cast<SrcValueSDNode>(Op.getOperand(3))->getValue();
  6362. const Value *SrcSV = cast<SrcValueSDNode>(Op.getOperand(4))->getValue();
  6363. return DAG.getMemcpy(Op.getOperand(0), DL, Op.getOperand(1), Op.getOperand(2),
  6364. DAG.getConstant(VaListSize, DL, MVT::i32),
  6365. Align(PtrSize), false, false, false,
  6366. MachinePointerInfo(DestSV), MachinePointerInfo(SrcSV));
  6367. }
  6368. SDValue AArch64TargetLowering::LowerVAARG(SDValue Op, SelectionDAG &DAG) const {
  6369. assert(Subtarget->isTargetDarwin() &&
  6370. "automatic va_arg instruction only works on Darwin");
  6371. const Value *V = cast<SrcValueSDNode>(Op.getOperand(2))->getValue();
  6372. EVT VT = Op.getValueType();
  6373. SDLoc DL(Op);
  6374. SDValue Chain = Op.getOperand(0);
  6375. SDValue Addr = Op.getOperand(1);
  6376. MaybeAlign Align(Op.getConstantOperandVal(3));
  6377. unsigned MinSlotSize = Subtarget->isTargetILP32() ? 4 : 8;
  6378. auto PtrVT = getPointerTy(DAG.getDataLayout());
  6379. auto PtrMemVT = getPointerMemTy(DAG.getDataLayout());
  6380. SDValue VAList =
  6381. DAG.getLoad(PtrMemVT, DL, Chain, Addr, MachinePointerInfo(V));
  6382. Chain = VAList.getValue(1);
  6383. VAList = DAG.getZExtOrTrunc(VAList, DL, PtrVT);
  6384. if (VT.isScalableVector())
  6385. report_fatal_error("Passing SVE types to variadic functions is "
  6386. "currently not supported");
  6387. if (Align && *Align > MinSlotSize) {
  6388. VAList = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
  6389. DAG.getConstant(Align->value() - 1, DL, PtrVT));
  6390. VAList = DAG.getNode(ISD::AND, DL, PtrVT, VAList,
  6391. DAG.getConstant(-(int64_t)Align->value(), DL, PtrVT));
  6392. }
  6393. Type *ArgTy = VT.getTypeForEVT(*DAG.getContext());
  6394. unsigned ArgSize = DAG.getDataLayout().getTypeAllocSize(ArgTy);
  6395. // Scalar integer and FP values smaller than 64 bits are implicitly extended
  6396. // up to 64 bits. At the very least, we have to increase the striding of the
  6397. // vaargs list to match this, and for FP values we need to introduce
  6398. // FP_ROUND nodes as well.
  6399. if (VT.isInteger() && !VT.isVector())
  6400. ArgSize = std::max(ArgSize, MinSlotSize);
  6401. bool NeedFPTrunc = false;
  6402. if (VT.isFloatingPoint() && !VT.isVector() && VT != MVT::f64) {
  6403. ArgSize = 8;
  6404. NeedFPTrunc = true;
  6405. }
  6406. // Increment the pointer, VAList, to the next vaarg
  6407. SDValue VANext = DAG.getNode(ISD::ADD, DL, PtrVT, VAList,
  6408. DAG.getConstant(ArgSize, DL, PtrVT));
  6409. VANext = DAG.getZExtOrTrunc(VANext, DL, PtrMemVT);
  6410. // Store the incremented VAList to the legalized pointer
  6411. SDValue APStore =
  6412. DAG.getStore(Chain, DL, VANext, Addr, MachinePointerInfo(V));
  6413. // Load the actual argument out of the pointer VAList
  6414. if (NeedFPTrunc) {
  6415. // Load the value as an f64.
  6416. SDValue WideFP =
  6417. DAG.getLoad(MVT::f64, DL, APStore, VAList, MachinePointerInfo());
  6418. // Round the value down to an f32.
  6419. SDValue NarrowFP = DAG.getNode(ISD::FP_ROUND, DL, VT, WideFP.getValue(0),
  6420. DAG.getIntPtrConstant(1, DL));
  6421. SDValue Ops[] = { NarrowFP, WideFP.getValue(1) };
  6422. // Merge the rounded value with the chain output of the load.
  6423. return DAG.getMergeValues(Ops, DL);
  6424. }
  6425. return DAG.getLoad(VT, DL, APStore, VAList, MachinePointerInfo());
  6426. }
  6427. SDValue AArch64TargetLowering::LowerFRAMEADDR(SDValue Op,
  6428. SelectionDAG &DAG) const {
  6429. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  6430. MFI.setFrameAddressIsTaken(true);
  6431. EVT VT = Op.getValueType();
  6432. SDLoc DL(Op);
  6433. unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  6434. SDValue FrameAddr =
  6435. DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, MVT::i64);
  6436. while (Depth--)
  6437. FrameAddr = DAG.getLoad(VT, DL, DAG.getEntryNode(), FrameAddr,
  6438. MachinePointerInfo());
  6439. if (Subtarget->isTargetILP32())
  6440. FrameAddr = DAG.getNode(ISD::AssertZext, DL, MVT::i64, FrameAddr,
  6441. DAG.getValueType(VT));
  6442. return FrameAddr;
  6443. }
  6444. SDValue AArch64TargetLowering::LowerSPONENTRY(SDValue Op,
  6445. SelectionDAG &DAG) const {
  6446. MachineFrameInfo &MFI = DAG.getMachineFunction().getFrameInfo();
  6447. EVT VT = getPointerTy(DAG.getDataLayout());
  6448. SDLoc DL(Op);
  6449. int FI = MFI.CreateFixedObject(4, 0, false);
  6450. return DAG.getFrameIndex(FI, VT);
  6451. }
  6452. #define GET_REGISTER_MATCHER
  6453. #include "AArch64GenAsmMatcher.inc"
  6454. // FIXME? Maybe this could be a TableGen attribute on some registers and
  6455. // this table could be generated automatically from RegInfo.
  6456. Register AArch64TargetLowering::
  6457. getRegisterByName(const char* RegName, LLT VT, const MachineFunction &MF) const {
  6458. Register Reg = MatchRegisterName(RegName);
  6459. if (AArch64::X1 <= Reg && Reg <= AArch64::X28) {
  6460. const MCRegisterInfo *MRI = Subtarget->getRegisterInfo();
  6461. unsigned DwarfRegNum = MRI->getDwarfRegNum(Reg, false);
  6462. if (!Subtarget->isXRegisterReserved(DwarfRegNum))
  6463. Reg = 0;
  6464. }
  6465. if (Reg)
  6466. return Reg;
  6467. report_fatal_error(Twine("Invalid register name \""
  6468. + StringRef(RegName) + "\"."));
  6469. }
  6470. SDValue AArch64TargetLowering::LowerADDROFRETURNADDR(SDValue Op,
  6471. SelectionDAG &DAG) const {
  6472. DAG.getMachineFunction().getFrameInfo().setFrameAddressIsTaken(true);
  6473. EVT VT = Op.getValueType();
  6474. SDLoc DL(Op);
  6475. SDValue FrameAddr =
  6476. DAG.getCopyFromReg(DAG.getEntryNode(), DL, AArch64::FP, VT);
  6477. SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
  6478. return DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset);
  6479. }
  6480. SDValue AArch64TargetLowering::LowerRETURNADDR(SDValue Op,
  6481. SelectionDAG &DAG) const {
  6482. MachineFunction &MF = DAG.getMachineFunction();
  6483. MachineFrameInfo &MFI = MF.getFrameInfo();
  6484. MFI.setReturnAddressIsTaken(true);
  6485. EVT VT = Op.getValueType();
  6486. SDLoc DL(Op);
  6487. unsigned Depth = cast<ConstantSDNode>(Op.getOperand(0))->getZExtValue();
  6488. SDValue ReturnAddress;
  6489. if (Depth) {
  6490. SDValue FrameAddr = LowerFRAMEADDR(Op, DAG);
  6491. SDValue Offset = DAG.getConstant(8, DL, getPointerTy(DAG.getDataLayout()));
  6492. ReturnAddress = DAG.getLoad(
  6493. VT, DL, DAG.getEntryNode(),
  6494. DAG.getNode(ISD::ADD, DL, VT, FrameAddr, Offset), MachinePointerInfo());
  6495. } else {
  6496. // Return LR, which contains the return address. Mark it an implicit
  6497. // live-in.
  6498. unsigned Reg = MF.addLiveIn(AArch64::LR, &AArch64::GPR64RegClass);
  6499. ReturnAddress = DAG.getCopyFromReg(DAG.getEntryNode(), DL, Reg, VT);
  6500. }
  6501. // The XPACLRI instruction assembles to a hint-space instruction before
  6502. // Armv8.3-A therefore this instruction can be safely used for any pre
  6503. // Armv8.3-A architectures. On Armv8.3-A and onwards XPACI is available so use
  6504. // that instead.
  6505. SDNode *St;
  6506. if (Subtarget->hasPAuth()) {
  6507. St = DAG.getMachineNode(AArch64::XPACI, DL, VT, ReturnAddress);
  6508. } else {
  6509. // XPACLRI operates on LR therefore we must move the operand accordingly.
  6510. SDValue Chain =
  6511. DAG.getCopyToReg(DAG.getEntryNode(), DL, AArch64::LR, ReturnAddress);
  6512. St = DAG.getMachineNode(AArch64::XPACLRI, DL, VT, Chain);
  6513. }
  6514. return SDValue(St, 0);
  6515. }
  6516. /// LowerShiftRightParts - Lower SRA_PARTS, which returns two
  6517. /// i64 values and take a 2 x i64 value to shift plus a shift amount.
  6518. SDValue AArch64TargetLowering::LowerShiftRightParts(SDValue Op,
  6519. SelectionDAG &DAG) const {
  6520. assert(Op.getNumOperands() == 3 && "Not a double-shift!");
  6521. EVT VT = Op.getValueType();
  6522. unsigned VTBits = VT.getSizeInBits();
  6523. SDLoc dl(Op);
  6524. SDValue ShOpLo = Op.getOperand(0);
  6525. SDValue ShOpHi = Op.getOperand(1);
  6526. SDValue ShAmt = Op.getOperand(2);
  6527. unsigned Opc = (Op.getOpcode() == ISD::SRA_PARTS) ? ISD::SRA : ISD::SRL;
  6528. assert(Op.getOpcode() == ISD::SRA_PARTS || Op.getOpcode() == ISD::SRL_PARTS);
  6529. SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
  6530. DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
  6531. SDValue HiBitsForLo = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, RevShAmt);
  6532. // Unfortunately, if ShAmt == 0, we just calculated "(SHL ShOpHi, 64)" which
  6533. // is "undef". We wanted 0, so CSEL it directly.
  6534. SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
  6535. ISD::SETEQ, dl, DAG);
  6536. SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
  6537. HiBitsForLo =
  6538. DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
  6539. HiBitsForLo, CCVal, Cmp);
  6540. SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
  6541. DAG.getConstant(VTBits, dl, MVT::i64));
  6542. SDValue LoBitsForLo = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, ShAmt);
  6543. SDValue LoForNormalShift =
  6544. DAG.getNode(ISD::OR, dl, VT, LoBitsForLo, HiBitsForLo);
  6545. Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
  6546. dl, DAG);
  6547. CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
  6548. SDValue LoForBigShift = DAG.getNode(Opc, dl, VT, ShOpHi, ExtraShAmt);
  6549. SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
  6550. LoForNormalShift, CCVal, Cmp);
  6551. // AArch64 shifts larger than the register width are wrapped rather than
  6552. // clamped, so we can't just emit "hi >> x".
  6553. SDValue HiForNormalShift = DAG.getNode(Opc, dl, VT, ShOpHi, ShAmt);
  6554. SDValue HiForBigShift =
  6555. Opc == ISD::SRA
  6556. ? DAG.getNode(Opc, dl, VT, ShOpHi,
  6557. DAG.getConstant(VTBits - 1, dl, MVT::i64))
  6558. : DAG.getConstant(0, dl, VT);
  6559. SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
  6560. HiForNormalShift, CCVal, Cmp);
  6561. SDValue Ops[2] = { Lo, Hi };
  6562. return DAG.getMergeValues(Ops, dl);
  6563. }
  6564. /// LowerShiftLeftParts - Lower SHL_PARTS, which returns two
  6565. /// i64 values and take a 2 x i64 value to shift plus a shift amount.
  6566. SDValue AArch64TargetLowering::LowerShiftLeftParts(SDValue Op,
  6567. SelectionDAG &DAG) const {
  6568. assert(Op.getNumOperands() == 3 && "Not a double-shift!");
  6569. EVT VT = Op.getValueType();
  6570. unsigned VTBits = VT.getSizeInBits();
  6571. SDLoc dl(Op);
  6572. SDValue ShOpLo = Op.getOperand(0);
  6573. SDValue ShOpHi = Op.getOperand(1);
  6574. SDValue ShAmt = Op.getOperand(2);
  6575. assert(Op.getOpcode() == ISD::SHL_PARTS);
  6576. SDValue RevShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64,
  6577. DAG.getConstant(VTBits, dl, MVT::i64), ShAmt);
  6578. SDValue LoBitsForHi = DAG.getNode(ISD::SRL, dl, VT, ShOpLo, RevShAmt);
  6579. // Unfortunately, if ShAmt == 0, we just calculated "(SRL ShOpLo, 64)" which
  6580. // is "undef". We wanted 0, so CSEL it directly.
  6581. SDValue Cmp = emitComparison(ShAmt, DAG.getConstant(0, dl, MVT::i64),
  6582. ISD::SETEQ, dl, DAG);
  6583. SDValue CCVal = DAG.getConstant(AArch64CC::EQ, dl, MVT::i32);
  6584. LoBitsForHi =
  6585. DAG.getNode(AArch64ISD::CSEL, dl, VT, DAG.getConstant(0, dl, MVT::i64),
  6586. LoBitsForHi, CCVal, Cmp);
  6587. SDValue ExtraShAmt = DAG.getNode(ISD::SUB, dl, MVT::i64, ShAmt,
  6588. DAG.getConstant(VTBits, dl, MVT::i64));
  6589. SDValue HiBitsForHi = DAG.getNode(ISD::SHL, dl, VT, ShOpHi, ShAmt);
  6590. SDValue HiForNormalShift =
  6591. DAG.getNode(ISD::OR, dl, VT, LoBitsForHi, HiBitsForHi);
  6592. SDValue HiForBigShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ExtraShAmt);
  6593. Cmp = emitComparison(ExtraShAmt, DAG.getConstant(0, dl, MVT::i64), ISD::SETGE,
  6594. dl, DAG);
  6595. CCVal = DAG.getConstant(AArch64CC::GE, dl, MVT::i32);
  6596. SDValue Hi = DAG.getNode(AArch64ISD::CSEL, dl, VT, HiForBigShift,
  6597. HiForNormalShift, CCVal, Cmp);
  6598. // AArch64 shifts of larger than register sizes are wrapped rather than
  6599. // clamped, so we can't just emit "lo << a" if a is too big.
  6600. SDValue LoForBigShift = DAG.getConstant(0, dl, VT);
  6601. SDValue LoForNormalShift = DAG.getNode(ISD::SHL, dl, VT, ShOpLo, ShAmt);
  6602. SDValue Lo = DAG.getNode(AArch64ISD::CSEL, dl, VT, LoForBigShift,
  6603. LoForNormalShift, CCVal, Cmp);
  6604. SDValue Ops[2] = { Lo, Hi };
  6605. return DAG.getMergeValues(Ops, dl);
  6606. }
  6607. bool AArch64TargetLowering::isOffsetFoldingLegal(
  6608. const GlobalAddressSDNode *GA) const {
  6609. // Offsets are folded in the DAG combine rather than here so that we can
  6610. // intelligently choose an offset based on the uses.
  6611. return false;
  6612. }
  6613. bool AArch64TargetLowering::isFPImmLegal(const APFloat &Imm, EVT VT,
  6614. bool OptForSize) const {
  6615. bool IsLegal = false;
  6616. // We can materialize #0.0 as fmov $Rd, XZR for 64-bit, 32-bit cases, and
  6617. // 16-bit case when target has full fp16 support.
  6618. // FIXME: We should be able to handle f128 as well with a clever lowering.
  6619. const APInt ImmInt = Imm.bitcastToAPInt();
  6620. if (VT == MVT::f64)
  6621. IsLegal = AArch64_AM::getFP64Imm(ImmInt) != -1 || Imm.isPosZero();
  6622. else if (VT == MVT::f32)
  6623. IsLegal = AArch64_AM::getFP32Imm(ImmInt) != -1 || Imm.isPosZero();
  6624. else if (VT == MVT::f16 && Subtarget->hasFullFP16())
  6625. IsLegal = AArch64_AM::getFP16Imm(ImmInt) != -1 || Imm.isPosZero();
  6626. // TODO: fmov h0, w0 is also legal, however on't have an isel pattern to
  6627. // generate that fmov.
  6628. // If we can not materialize in immediate field for fmov, check if the
  6629. // value can be encoded as the immediate operand of a logical instruction.
  6630. // The immediate value will be created with either MOVZ, MOVN, or ORR.
  6631. if (!IsLegal && (VT == MVT::f64 || VT == MVT::f32)) {
  6632. // The cost is actually exactly the same for mov+fmov vs. adrp+ldr;
  6633. // however the mov+fmov sequence is always better because of the reduced
  6634. // cache pressure. The timings are still the same if you consider
  6635. // movw+movk+fmov vs. adrp+ldr (it's one instruction longer, but the
  6636. // movw+movk is fused). So we limit up to 2 instrdduction at most.
  6637. SmallVector<AArch64_IMM::ImmInsnModel, 4> Insn;
  6638. AArch64_IMM::expandMOVImm(ImmInt.getZExtValue(), VT.getSizeInBits(),
  6639. Insn);
  6640. unsigned Limit = (OptForSize ? 1 : (Subtarget->hasFuseLiterals() ? 5 : 2));
  6641. IsLegal = Insn.size() <= Limit;
  6642. }
  6643. LLVM_DEBUG(dbgs() << (IsLegal ? "Legal " : "Illegal ") << VT.getEVTString()
  6644. << " imm value: "; Imm.dump(););
  6645. return IsLegal;
  6646. }
  6647. //===----------------------------------------------------------------------===//
  6648. // AArch64 Optimization Hooks
  6649. //===----------------------------------------------------------------------===//
  6650. static SDValue getEstimate(const AArch64Subtarget *ST, unsigned Opcode,
  6651. SDValue Operand, SelectionDAG &DAG,
  6652. int &ExtraSteps) {
  6653. EVT VT = Operand.getValueType();
  6654. if (ST->hasNEON() &&
  6655. (VT == MVT::f64 || VT == MVT::v1f64 || VT == MVT::v2f64 ||
  6656. VT == MVT::f32 || VT == MVT::v1f32 ||
  6657. VT == MVT::v2f32 || VT == MVT::v4f32)) {
  6658. if (ExtraSteps == TargetLoweringBase::ReciprocalEstimate::Unspecified)
  6659. // For the reciprocal estimates, convergence is quadratic, so the number
  6660. // of digits is doubled after each iteration. In ARMv8, the accuracy of
  6661. // the initial estimate is 2^-8. Thus the number of extra steps to refine
  6662. // the result for float (23 mantissa bits) is 2 and for double (52
  6663. // mantissa bits) is 3.
  6664. ExtraSteps = VT.getScalarType() == MVT::f64 ? 3 : 2;
  6665. return DAG.getNode(Opcode, SDLoc(Operand), VT, Operand);
  6666. }
  6667. return SDValue();
  6668. }
  6669. SDValue
  6670. AArch64TargetLowering::getSqrtInputTest(SDValue Op, SelectionDAG &DAG,
  6671. const DenormalMode &Mode) const {
  6672. SDLoc DL(Op);
  6673. EVT VT = Op.getValueType();
  6674. EVT CCVT = getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
  6675. SDValue FPZero = DAG.getConstantFP(0.0, DL, VT);
  6676. return DAG.getSetCC(DL, CCVT, Op, FPZero, ISD::SETEQ);
  6677. }
  6678. SDValue
  6679. AArch64TargetLowering::getSqrtResultForDenormInput(SDValue Op,
  6680. SelectionDAG &DAG) const {
  6681. return Op;
  6682. }
  6683. SDValue AArch64TargetLowering::getSqrtEstimate(SDValue Operand,
  6684. SelectionDAG &DAG, int Enabled,
  6685. int &ExtraSteps,
  6686. bool &UseOneConst,
  6687. bool Reciprocal) const {
  6688. if (Enabled == ReciprocalEstimate::Enabled ||
  6689. (Enabled == ReciprocalEstimate::Unspecified && Subtarget->useRSqrt()))
  6690. if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRSQRTE, Operand,
  6691. DAG, ExtraSteps)) {
  6692. SDLoc DL(Operand);
  6693. EVT VT = Operand.getValueType();
  6694. SDNodeFlags Flags;
  6695. Flags.setAllowReassociation(true);
  6696. // Newton reciprocal square root iteration: E * 0.5 * (3 - X * E^2)
  6697. // AArch64 reciprocal square root iteration instruction: 0.5 * (3 - M * N)
  6698. for (int i = ExtraSteps; i > 0; --i) {
  6699. SDValue Step = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Estimate,
  6700. Flags);
  6701. Step = DAG.getNode(AArch64ISD::FRSQRTS, DL, VT, Operand, Step, Flags);
  6702. Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
  6703. }
  6704. if (!Reciprocal)
  6705. Estimate = DAG.getNode(ISD::FMUL, DL, VT, Operand, Estimate, Flags);
  6706. ExtraSteps = 0;
  6707. return Estimate;
  6708. }
  6709. return SDValue();
  6710. }
  6711. SDValue AArch64TargetLowering::getRecipEstimate(SDValue Operand,
  6712. SelectionDAG &DAG, int Enabled,
  6713. int &ExtraSteps) const {
  6714. if (Enabled == ReciprocalEstimate::Enabled)
  6715. if (SDValue Estimate = getEstimate(Subtarget, AArch64ISD::FRECPE, Operand,
  6716. DAG, ExtraSteps)) {
  6717. SDLoc DL(Operand);
  6718. EVT VT = Operand.getValueType();
  6719. SDNodeFlags Flags;
  6720. Flags.setAllowReassociation(true);
  6721. // Newton reciprocal iteration: E * (2 - X * E)
  6722. // AArch64 reciprocal iteration instruction: (2 - M * N)
  6723. for (int i = ExtraSteps; i > 0; --i) {
  6724. SDValue Step = DAG.getNode(AArch64ISD::FRECPS, DL, VT, Operand,
  6725. Estimate, Flags);
  6726. Estimate = DAG.getNode(ISD::FMUL, DL, VT, Estimate, Step, Flags);
  6727. }
  6728. ExtraSteps = 0;
  6729. return Estimate;
  6730. }
  6731. return SDValue();
  6732. }
  6733. //===----------------------------------------------------------------------===//
  6734. // AArch64 Inline Assembly Support
  6735. //===----------------------------------------------------------------------===//
  6736. // Table of Constraints
  6737. // TODO: This is the current set of constraints supported by ARM for the
  6738. // compiler, not all of them may make sense.
  6739. //
  6740. // r - A general register
  6741. // w - An FP/SIMD register of some size in the range v0-v31
  6742. // x - An FP/SIMD register of some size in the range v0-v15
  6743. // I - Constant that can be used with an ADD instruction
  6744. // J - Constant that can be used with a SUB instruction
  6745. // K - Constant that can be used with a 32-bit logical instruction
  6746. // L - Constant that can be used with a 64-bit logical instruction
  6747. // M - Constant that can be used as a 32-bit MOV immediate
  6748. // N - Constant that can be used as a 64-bit MOV immediate
  6749. // Q - A memory reference with base register and no offset
  6750. // S - A symbolic address
  6751. // Y - Floating point constant zero
  6752. // Z - Integer constant zero
  6753. //
  6754. // Note that general register operands will be output using their 64-bit x
  6755. // register name, whatever the size of the variable, unless the asm operand
  6756. // is prefixed by the %w modifier. Floating-point and SIMD register operands
  6757. // will be output with the v prefix unless prefixed by the %b, %h, %s, %d or
  6758. // %q modifier.
  6759. const char *AArch64TargetLowering::LowerXConstraint(EVT ConstraintVT) const {
  6760. // At this point, we have to lower this constraint to something else, so we
  6761. // lower it to an "r" or "w". However, by doing this we will force the result
  6762. // to be in register, while the X constraint is much more permissive.
  6763. //
  6764. // Although we are correct (we are free to emit anything, without
  6765. // constraints), we might break use cases that would expect us to be more
  6766. // efficient and emit something else.
  6767. if (!Subtarget->hasFPARMv8())
  6768. return "r";
  6769. if (ConstraintVT.isFloatingPoint())
  6770. return "w";
  6771. if (ConstraintVT.isVector() &&
  6772. (ConstraintVT.getSizeInBits() == 64 ||
  6773. ConstraintVT.getSizeInBits() == 128))
  6774. return "w";
  6775. return "r";
  6776. }
  6777. enum PredicateConstraint {
  6778. Upl,
  6779. Upa,
  6780. Invalid
  6781. };
  6782. static PredicateConstraint parsePredicateConstraint(StringRef Constraint) {
  6783. PredicateConstraint P = PredicateConstraint::Invalid;
  6784. if (Constraint == "Upa")
  6785. P = PredicateConstraint::Upa;
  6786. if (Constraint == "Upl")
  6787. P = PredicateConstraint::Upl;
  6788. return P;
  6789. }
  6790. /// getConstraintType - Given a constraint letter, return the type of
  6791. /// constraint it is for this target.
  6792. AArch64TargetLowering::ConstraintType
  6793. AArch64TargetLowering::getConstraintType(StringRef Constraint) const {
  6794. if (Constraint.size() == 1) {
  6795. switch (Constraint[0]) {
  6796. default:
  6797. break;
  6798. case 'x':
  6799. case 'w':
  6800. case 'y':
  6801. return C_RegisterClass;
  6802. // An address with a single base register. Due to the way we
  6803. // currently handle addresses it is the same as 'r'.
  6804. case 'Q':
  6805. return C_Memory;
  6806. case 'I':
  6807. case 'J':
  6808. case 'K':
  6809. case 'L':
  6810. case 'M':
  6811. case 'N':
  6812. case 'Y':
  6813. case 'Z':
  6814. return C_Immediate;
  6815. case 'z':
  6816. case 'S': // A symbolic address
  6817. return C_Other;
  6818. }
  6819. } else if (parsePredicateConstraint(Constraint) !=
  6820. PredicateConstraint::Invalid)
  6821. return C_RegisterClass;
  6822. return TargetLowering::getConstraintType(Constraint);
  6823. }
  6824. /// Examine constraint type and operand type and determine a weight value.
  6825. /// This object must already have been set up with the operand type
  6826. /// and the current alternative constraint selected.
  6827. TargetLowering::ConstraintWeight
  6828. AArch64TargetLowering::getSingleConstraintMatchWeight(
  6829. AsmOperandInfo &info, const char *constraint) const {
  6830. ConstraintWeight weight = CW_Invalid;
  6831. Value *CallOperandVal = info.CallOperandVal;
  6832. // If we don't have a value, we can't do a match,
  6833. // but allow it at the lowest weight.
  6834. if (!CallOperandVal)
  6835. return CW_Default;
  6836. Type *type = CallOperandVal->getType();
  6837. // Look at the constraint type.
  6838. switch (*constraint) {
  6839. default:
  6840. weight = TargetLowering::getSingleConstraintMatchWeight(info, constraint);
  6841. break;
  6842. case 'x':
  6843. case 'w':
  6844. case 'y':
  6845. if (type->isFloatingPointTy() || type->isVectorTy())
  6846. weight = CW_Register;
  6847. break;
  6848. case 'z':
  6849. weight = CW_Constant;
  6850. break;
  6851. case 'U':
  6852. if (parsePredicateConstraint(constraint) != PredicateConstraint::Invalid)
  6853. weight = CW_Register;
  6854. break;
  6855. }
  6856. return weight;
  6857. }
  6858. std::pair<unsigned, const TargetRegisterClass *>
  6859. AArch64TargetLowering::getRegForInlineAsmConstraint(
  6860. const TargetRegisterInfo *TRI, StringRef Constraint, MVT VT) const {
  6861. if (Constraint.size() == 1) {
  6862. switch (Constraint[0]) {
  6863. case 'r':
  6864. if (VT.isScalableVector())
  6865. return std::make_pair(0U, nullptr);
  6866. if (VT.getFixedSizeInBits() == 64)
  6867. return std::make_pair(0U, &AArch64::GPR64commonRegClass);
  6868. return std::make_pair(0U, &AArch64::GPR32commonRegClass);
  6869. case 'w': {
  6870. if (!Subtarget->hasFPARMv8())
  6871. break;
  6872. if (VT.isScalableVector()) {
  6873. if (VT.getVectorElementType() != MVT::i1)
  6874. return std::make_pair(0U, &AArch64::ZPRRegClass);
  6875. return std::make_pair(0U, nullptr);
  6876. }
  6877. uint64_t VTSize = VT.getFixedSizeInBits();
  6878. if (VTSize == 16)
  6879. return std::make_pair(0U, &AArch64::FPR16RegClass);
  6880. if (VTSize == 32)
  6881. return std::make_pair(0U, &AArch64::FPR32RegClass);
  6882. if (VTSize == 64)
  6883. return std::make_pair(0U, &AArch64::FPR64RegClass);
  6884. if (VTSize == 128)
  6885. return std::make_pair(0U, &AArch64::FPR128RegClass);
  6886. break;
  6887. }
  6888. // The instructions that this constraint is designed for can
  6889. // only take 128-bit registers so just use that regclass.
  6890. case 'x':
  6891. if (!Subtarget->hasFPARMv8())
  6892. break;
  6893. if (VT.isScalableVector())
  6894. return std::make_pair(0U, &AArch64::ZPR_4bRegClass);
  6895. if (VT.getSizeInBits() == 128)
  6896. return std::make_pair(0U, &AArch64::FPR128_loRegClass);
  6897. break;
  6898. case 'y':
  6899. if (!Subtarget->hasFPARMv8())
  6900. break;
  6901. if (VT.isScalableVector())
  6902. return std::make_pair(0U, &AArch64::ZPR_3bRegClass);
  6903. break;
  6904. }
  6905. } else {
  6906. PredicateConstraint PC = parsePredicateConstraint(Constraint);
  6907. if (PC != PredicateConstraint::Invalid) {
  6908. if (!VT.isScalableVector() || VT.getVectorElementType() != MVT::i1)
  6909. return std::make_pair(0U, nullptr);
  6910. bool restricted = (PC == PredicateConstraint::Upl);
  6911. return restricted ? std::make_pair(0U, &AArch64::PPR_3bRegClass)
  6912. : std::make_pair(0U, &AArch64::PPRRegClass);
  6913. }
  6914. }
  6915. if (StringRef("{cc}").equals_lower(Constraint))
  6916. return std::make_pair(unsigned(AArch64::NZCV), &AArch64::CCRRegClass);
  6917. // Use the default implementation in TargetLowering to convert the register
  6918. // constraint into a member of a register class.
  6919. std::pair<unsigned, const TargetRegisterClass *> Res;
  6920. Res = TargetLowering::getRegForInlineAsmConstraint(TRI, Constraint, VT);
  6921. // Not found as a standard register?
  6922. if (!Res.second) {
  6923. unsigned Size = Constraint.size();
  6924. if ((Size == 4 || Size == 5) && Constraint[0] == '{' &&
  6925. tolower(Constraint[1]) == 'v' && Constraint[Size - 1] == '}') {
  6926. int RegNo;
  6927. bool Failed = Constraint.slice(2, Size - 1).getAsInteger(10, RegNo);
  6928. if (!Failed && RegNo >= 0 && RegNo <= 31) {
  6929. // v0 - v31 are aliases of q0 - q31 or d0 - d31 depending on size.
  6930. // By default we'll emit v0-v31 for this unless there's a modifier where
  6931. // we'll emit the correct register as well.
  6932. if (VT != MVT::Other && VT.getSizeInBits() == 64) {
  6933. Res.first = AArch64::FPR64RegClass.getRegister(RegNo);
  6934. Res.second = &AArch64::FPR64RegClass;
  6935. } else {
  6936. Res.first = AArch64::FPR128RegClass.getRegister(RegNo);
  6937. Res.second = &AArch64::FPR128RegClass;
  6938. }
  6939. }
  6940. }
  6941. }
  6942. if (Res.second && !Subtarget->hasFPARMv8() &&
  6943. !AArch64::GPR32allRegClass.hasSubClassEq(Res.second) &&
  6944. !AArch64::GPR64allRegClass.hasSubClassEq(Res.second))
  6945. return std::make_pair(0U, nullptr);
  6946. return Res;
  6947. }
  6948. /// LowerAsmOperandForConstraint - Lower the specified operand into the Ops
  6949. /// vector. If it is invalid, don't add anything to Ops.
  6950. void AArch64TargetLowering::LowerAsmOperandForConstraint(
  6951. SDValue Op, std::string &Constraint, std::vector<SDValue> &Ops,
  6952. SelectionDAG &DAG) const {
  6953. SDValue Result;
  6954. // Currently only support length 1 constraints.
  6955. if (Constraint.length() != 1)
  6956. return;
  6957. char ConstraintLetter = Constraint[0];
  6958. switch (ConstraintLetter) {
  6959. default:
  6960. break;
  6961. // This set of constraints deal with valid constants for various instructions.
  6962. // Validate and return a target constant for them if we can.
  6963. case 'z': {
  6964. // 'z' maps to xzr or wzr so it needs an input of 0.
  6965. if (!isNullConstant(Op))
  6966. return;
  6967. if (Op.getValueType() == MVT::i64)
  6968. Result = DAG.getRegister(AArch64::XZR, MVT::i64);
  6969. else
  6970. Result = DAG.getRegister(AArch64::WZR, MVT::i32);
  6971. break;
  6972. }
  6973. case 'S': {
  6974. // An absolute symbolic address or label reference.
  6975. if (const GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(Op)) {
  6976. Result = DAG.getTargetGlobalAddress(GA->getGlobal(), SDLoc(Op),
  6977. GA->getValueType(0));
  6978. } else if (const BlockAddressSDNode *BA =
  6979. dyn_cast<BlockAddressSDNode>(Op)) {
  6980. Result =
  6981. DAG.getTargetBlockAddress(BA->getBlockAddress(), BA->getValueType(0));
  6982. } else if (const ExternalSymbolSDNode *ES =
  6983. dyn_cast<ExternalSymbolSDNode>(Op)) {
  6984. Result =
  6985. DAG.getTargetExternalSymbol(ES->getSymbol(), ES->getValueType(0));
  6986. } else
  6987. return;
  6988. break;
  6989. }
  6990. case 'I':
  6991. case 'J':
  6992. case 'K':
  6993. case 'L':
  6994. case 'M':
  6995. case 'N':
  6996. ConstantSDNode *C = dyn_cast<ConstantSDNode>(Op);
  6997. if (!C)
  6998. return;
  6999. // Grab the value and do some validation.
  7000. uint64_t CVal = C->getZExtValue();
  7001. switch (ConstraintLetter) {
  7002. // The I constraint applies only to simple ADD or SUB immediate operands:
  7003. // i.e. 0 to 4095 with optional shift by 12
  7004. // The J constraint applies only to ADD or SUB immediates that would be
  7005. // valid when negated, i.e. if [an add pattern] were to be output as a SUB
  7006. // instruction [or vice versa], in other words -1 to -4095 with optional
  7007. // left shift by 12.
  7008. case 'I':
  7009. if (isUInt<12>(CVal) || isShiftedUInt<12, 12>(CVal))
  7010. break;
  7011. return;
  7012. case 'J': {
  7013. uint64_t NVal = -C->getSExtValue();
  7014. if (isUInt<12>(NVal) || isShiftedUInt<12, 12>(NVal)) {
  7015. CVal = C->getSExtValue();
  7016. break;
  7017. }
  7018. return;
  7019. }
  7020. // The K and L constraints apply *only* to logical immediates, including
  7021. // what used to be the MOVI alias for ORR (though the MOVI alias has now
  7022. // been removed and MOV should be used). So these constraints have to
  7023. // distinguish between bit patterns that are valid 32-bit or 64-bit
  7024. // "bitmask immediates": for example 0xaaaaaaaa is a valid bimm32 (K), but
  7025. // not a valid bimm64 (L) where 0xaaaaaaaaaaaaaaaa would be valid, and vice
  7026. // versa.
  7027. case 'K':
  7028. if (AArch64_AM::isLogicalImmediate(CVal, 32))
  7029. break;
  7030. return;
  7031. case 'L':
  7032. if (AArch64_AM::isLogicalImmediate(CVal, 64))
  7033. break;
  7034. return;
  7035. // The M and N constraints are a superset of K and L respectively, for use
  7036. // with the MOV (immediate) alias. As well as the logical immediates they
  7037. // also match 32 or 64-bit immediates that can be loaded either using a
  7038. // *single* MOVZ or MOVN , such as 32-bit 0x12340000, 0x00001234, 0xffffedca
  7039. // (M) or 64-bit 0x1234000000000000 (N) etc.
  7040. // As a note some of this code is liberally stolen from the asm parser.
  7041. case 'M': {
  7042. if (!isUInt<32>(CVal))
  7043. return;
  7044. if (AArch64_AM::isLogicalImmediate(CVal, 32))
  7045. break;
  7046. if ((CVal & 0xFFFF) == CVal)
  7047. break;
  7048. if ((CVal & 0xFFFF0000ULL) == CVal)
  7049. break;
  7050. uint64_t NCVal = ~(uint32_t)CVal;
  7051. if ((NCVal & 0xFFFFULL) == NCVal)
  7052. break;
  7053. if ((NCVal & 0xFFFF0000ULL) == NCVal)
  7054. break;
  7055. return;
  7056. }
  7057. case 'N': {
  7058. if (AArch64_AM::isLogicalImmediate(CVal, 64))
  7059. break;
  7060. if ((CVal & 0xFFFFULL) == CVal)
  7061. break;
  7062. if ((CVal & 0xFFFF0000ULL) == CVal)
  7063. break;
  7064. if ((CVal & 0xFFFF00000000ULL) == CVal)
  7065. break;
  7066. if ((CVal & 0xFFFF000000000000ULL) == CVal)
  7067. break;
  7068. uint64_t NCVal = ~CVal;
  7069. if ((NCVal & 0xFFFFULL) == NCVal)
  7070. break;
  7071. if ((NCVal & 0xFFFF0000ULL) == NCVal)
  7072. break;
  7073. if ((NCVal & 0xFFFF00000000ULL) == NCVal)
  7074. break;
  7075. if ((NCVal & 0xFFFF000000000000ULL) == NCVal)
  7076. break;
  7077. return;
  7078. }
  7079. default:
  7080. return;
  7081. }
  7082. // All assembler immediates are 64-bit integers.
  7083. Result = DAG.getTargetConstant(CVal, SDLoc(Op), MVT::i64);
  7084. break;
  7085. }
  7086. if (Result.getNode()) {
  7087. Ops.push_back(Result);
  7088. return;
  7089. }
  7090. return TargetLowering::LowerAsmOperandForConstraint(Op, Constraint, Ops, DAG);
  7091. }
  7092. //===----------------------------------------------------------------------===//
  7093. // AArch64 Advanced SIMD Support
  7094. //===----------------------------------------------------------------------===//
  7095. /// WidenVector - Given a value in the V64 register class, produce the
  7096. /// equivalent value in the V128 register class.
  7097. static SDValue WidenVector(SDValue V64Reg, SelectionDAG &DAG) {
  7098. EVT VT = V64Reg.getValueType();
  7099. unsigned NarrowSize = VT.getVectorNumElements();
  7100. MVT EltTy = VT.getVectorElementType().getSimpleVT();
  7101. MVT WideTy = MVT::getVectorVT(EltTy, 2 * NarrowSize);
  7102. SDLoc DL(V64Reg);
  7103. return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, WideTy, DAG.getUNDEF(WideTy),
  7104. V64Reg, DAG.getConstant(0, DL, MVT::i32));
  7105. }
  7106. /// getExtFactor - Determine the adjustment factor for the position when
  7107. /// generating an "extract from vector registers" instruction.
  7108. static unsigned getExtFactor(SDValue &V) {
  7109. EVT EltType = V.getValueType().getVectorElementType();
  7110. return EltType.getSizeInBits() / 8;
  7111. }
  7112. /// NarrowVector - Given a value in the V128 register class, produce the
  7113. /// equivalent value in the V64 register class.
  7114. static SDValue NarrowVector(SDValue V128Reg, SelectionDAG &DAG) {
  7115. EVT VT = V128Reg.getValueType();
  7116. unsigned WideSize = VT.getVectorNumElements();
  7117. MVT EltTy = VT.getVectorElementType().getSimpleVT();
  7118. MVT NarrowTy = MVT::getVectorVT(EltTy, WideSize / 2);
  7119. SDLoc DL(V128Reg);
  7120. return DAG.getTargetExtractSubreg(AArch64::dsub, DL, NarrowTy, V128Reg);
  7121. }
  7122. // Gather data to see if the operation can be modelled as a
  7123. // shuffle in combination with VEXTs.
  7124. SDValue AArch64TargetLowering::ReconstructShuffle(SDValue Op,
  7125. SelectionDAG &DAG) const {
  7126. assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
  7127. LLVM_DEBUG(dbgs() << "AArch64TargetLowering::ReconstructShuffle\n");
  7128. SDLoc dl(Op);
  7129. EVT VT = Op.getValueType();
  7130. assert(!VT.isScalableVector() &&
  7131. "Scalable vectors cannot be used with ISD::BUILD_VECTOR");
  7132. unsigned NumElts = VT.getVectorNumElements();
  7133. struct ShuffleSourceInfo {
  7134. SDValue Vec;
  7135. unsigned MinElt;
  7136. unsigned MaxElt;
  7137. // We may insert some combination of BITCASTs and VEXT nodes to force Vec to
  7138. // be compatible with the shuffle we intend to construct. As a result
  7139. // ShuffleVec will be some sliding window into the original Vec.
  7140. SDValue ShuffleVec;
  7141. // Code should guarantee that element i in Vec starts at element "WindowBase
  7142. // + i * WindowScale in ShuffleVec".
  7143. int WindowBase;
  7144. int WindowScale;
  7145. ShuffleSourceInfo(SDValue Vec)
  7146. : Vec(Vec), MinElt(std::numeric_limits<unsigned>::max()), MaxElt(0),
  7147. ShuffleVec(Vec), WindowBase(0), WindowScale(1) {}
  7148. bool operator ==(SDValue OtherVec) { return Vec == OtherVec; }
  7149. };
  7150. // First gather all vectors used as an immediate source for this BUILD_VECTOR
  7151. // node.
  7152. SmallVector<ShuffleSourceInfo, 2> Sources;
  7153. for (unsigned i = 0; i < NumElts; ++i) {
  7154. SDValue V = Op.getOperand(i);
  7155. if (V.isUndef())
  7156. continue;
  7157. else if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  7158. !isa<ConstantSDNode>(V.getOperand(1))) {
  7159. LLVM_DEBUG(
  7160. dbgs() << "Reshuffle failed: "
  7161. "a shuffle can only come from building a vector from "
  7162. "various elements of other vectors, provided their "
  7163. "indices are constant\n");
  7164. return SDValue();
  7165. }
  7166. // Add this element source to the list if it's not already there.
  7167. SDValue SourceVec = V.getOperand(0);
  7168. auto Source = find(Sources, SourceVec);
  7169. if (Source == Sources.end())
  7170. Source = Sources.insert(Sources.end(), ShuffleSourceInfo(SourceVec));
  7171. // Update the minimum and maximum lane number seen.
  7172. unsigned EltNo = cast<ConstantSDNode>(V.getOperand(1))->getZExtValue();
  7173. Source->MinElt = std::min(Source->MinElt, EltNo);
  7174. Source->MaxElt = std::max(Source->MaxElt, EltNo);
  7175. }
  7176. if (Sources.size() > 2) {
  7177. LLVM_DEBUG(
  7178. dbgs() << "Reshuffle failed: currently only do something sane when at "
  7179. "most two source vectors are involved\n");
  7180. return SDValue();
  7181. }
  7182. // Find out the smallest element size among result and two sources, and use
  7183. // it as element size to build the shuffle_vector.
  7184. EVT SmallestEltTy = VT.getVectorElementType();
  7185. for (auto &Source : Sources) {
  7186. EVT SrcEltTy = Source.Vec.getValueType().getVectorElementType();
  7187. if (SrcEltTy.bitsLT(SmallestEltTy)) {
  7188. SmallestEltTy = SrcEltTy;
  7189. }
  7190. }
  7191. unsigned ResMultiplier =
  7192. VT.getScalarSizeInBits() / SmallestEltTy.getFixedSizeInBits();
  7193. uint64_t VTSize = VT.getFixedSizeInBits();
  7194. NumElts = VTSize / SmallestEltTy.getFixedSizeInBits();
  7195. EVT ShuffleVT = EVT::getVectorVT(*DAG.getContext(), SmallestEltTy, NumElts);
  7196. // If the source vector is too wide or too narrow, we may nevertheless be able
  7197. // to construct a compatible shuffle either by concatenating it with UNDEF or
  7198. // extracting a suitable range of elements.
  7199. for (auto &Src : Sources) {
  7200. EVT SrcVT = Src.ShuffleVec.getValueType();
  7201. uint64_t SrcVTSize = SrcVT.getFixedSizeInBits();
  7202. if (SrcVTSize == VTSize)
  7203. continue;
  7204. // This stage of the search produces a source with the same element type as
  7205. // the original, but with a total width matching the BUILD_VECTOR output.
  7206. EVT EltVT = SrcVT.getVectorElementType();
  7207. unsigned NumSrcElts = VTSize / EltVT.getFixedSizeInBits();
  7208. EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT, NumSrcElts);
  7209. if (SrcVTSize < VTSize) {
  7210. assert(2 * SrcVTSize == VTSize);
  7211. // We can pad out the smaller vector for free, so if it's part of a
  7212. // shuffle...
  7213. Src.ShuffleVec =
  7214. DAG.getNode(ISD::CONCAT_VECTORS, dl, DestVT, Src.ShuffleVec,
  7215. DAG.getUNDEF(Src.ShuffleVec.getValueType()));
  7216. continue;
  7217. }
  7218. if (SrcVTSize != 2 * VTSize) {
  7219. LLVM_DEBUG(
  7220. dbgs() << "Reshuffle failed: result vector too small to extract\n");
  7221. return SDValue();
  7222. }
  7223. if (Src.MaxElt - Src.MinElt >= NumSrcElts) {
  7224. LLVM_DEBUG(
  7225. dbgs() << "Reshuffle failed: span too large for a VEXT to cope\n");
  7226. return SDValue();
  7227. }
  7228. if (Src.MinElt >= NumSrcElts) {
  7229. // The extraction can just take the second half
  7230. Src.ShuffleVec =
  7231. DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
  7232. DAG.getConstant(NumSrcElts, dl, MVT::i64));
  7233. Src.WindowBase = -NumSrcElts;
  7234. } else if (Src.MaxElt < NumSrcElts) {
  7235. // The extraction can just take the first half
  7236. Src.ShuffleVec =
  7237. DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
  7238. DAG.getConstant(0, dl, MVT::i64));
  7239. } else {
  7240. // An actual VEXT is needed
  7241. SDValue VEXTSrc1 =
  7242. DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
  7243. DAG.getConstant(0, dl, MVT::i64));
  7244. SDValue VEXTSrc2 =
  7245. DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, DestVT, Src.ShuffleVec,
  7246. DAG.getConstant(NumSrcElts, dl, MVT::i64));
  7247. unsigned Imm = Src.MinElt * getExtFactor(VEXTSrc1);
  7248. if (!SrcVT.is64BitVector()) {
  7249. LLVM_DEBUG(
  7250. dbgs() << "Reshuffle failed: don't know how to lower AArch64ISD::EXT "
  7251. "for SVE vectors.");
  7252. return SDValue();
  7253. }
  7254. Src.ShuffleVec = DAG.getNode(AArch64ISD::EXT, dl, DestVT, VEXTSrc1,
  7255. VEXTSrc2,
  7256. DAG.getConstant(Imm, dl, MVT::i32));
  7257. Src.WindowBase = -Src.MinElt;
  7258. }
  7259. }
  7260. // Another possible incompatibility occurs from the vector element types. We
  7261. // can fix this by bitcasting the source vectors to the same type we intend
  7262. // for the shuffle.
  7263. for (auto &Src : Sources) {
  7264. EVT SrcEltTy = Src.ShuffleVec.getValueType().getVectorElementType();
  7265. if (SrcEltTy == SmallestEltTy)
  7266. continue;
  7267. assert(ShuffleVT.getVectorElementType() == SmallestEltTy);
  7268. Src.ShuffleVec = DAG.getNode(ISD::BITCAST, dl, ShuffleVT, Src.ShuffleVec);
  7269. Src.WindowScale =
  7270. SrcEltTy.getFixedSizeInBits() / SmallestEltTy.getFixedSizeInBits();
  7271. Src.WindowBase *= Src.WindowScale;
  7272. }
  7273. // Final sanity check before we try to actually produce a shuffle.
  7274. LLVM_DEBUG(for (auto Src
  7275. : Sources)
  7276. assert(Src.ShuffleVec.getValueType() == ShuffleVT););
  7277. // The stars all align, our next step is to produce the mask for the shuffle.
  7278. SmallVector<int, 8> Mask(ShuffleVT.getVectorNumElements(), -1);
  7279. int BitsPerShuffleLane = ShuffleVT.getScalarSizeInBits();
  7280. for (unsigned i = 0; i < VT.getVectorNumElements(); ++i) {
  7281. SDValue Entry = Op.getOperand(i);
  7282. if (Entry.isUndef())
  7283. continue;
  7284. auto Src = find(Sources, Entry.getOperand(0));
  7285. int EltNo = cast<ConstantSDNode>(Entry.getOperand(1))->getSExtValue();
  7286. // EXTRACT_VECTOR_ELT performs an implicit any_ext; BUILD_VECTOR an implicit
  7287. // trunc. So only std::min(SrcBits, DestBits) actually get defined in this
  7288. // segment.
  7289. EVT OrigEltTy = Entry.getOperand(0).getValueType().getVectorElementType();
  7290. int BitsDefined = std::min(OrigEltTy.getScalarSizeInBits(),
  7291. VT.getScalarSizeInBits());
  7292. int LanesDefined = BitsDefined / BitsPerShuffleLane;
  7293. // This source is expected to fill ResMultiplier lanes of the final shuffle,
  7294. // starting at the appropriate offset.
  7295. int *LaneMask = &Mask[i * ResMultiplier];
  7296. int ExtractBase = EltNo * Src->WindowScale + Src->WindowBase;
  7297. ExtractBase += NumElts * (Src - Sources.begin());
  7298. for (int j = 0; j < LanesDefined; ++j)
  7299. LaneMask[j] = ExtractBase + j;
  7300. }
  7301. // Final check before we try to produce nonsense...
  7302. if (!isShuffleMaskLegal(Mask, ShuffleVT)) {
  7303. LLVM_DEBUG(dbgs() << "Reshuffle failed: illegal shuffle mask\n");
  7304. return SDValue();
  7305. }
  7306. SDValue ShuffleOps[] = { DAG.getUNDEF(ShuffleVT), DAG.getUNDEF(ShuffleVT) };
  7307. for (unsigned i = 0; i < Sources.size(); ++i)
  7308. ShuffleOps[i] = Sources[i].ShuffleVec;
  7309. SDValue Shuffle = DAG.getVectorShuffle(ShuffleVT, dl, ShuffleOps[0],
  7310. ShuffleOps[1], Mask);
  7311. SDValue V = DAG.getNode(ISD::BITCAST, dl, VT, Shuffle);
  7312. LLVM_DEBUG(dbgs() << "Reshuffle, creating node: "; Shuffle.dump();
  7313. dbgs() << "Reshuffle, creating node: "; V.dump(););
  7314. return V;
  7315. }
  7316. // check if an EXT instruction can handle the shuffle mask when the
  7317. // vector sources of the shuffle are the same.
  7318. static bool isSingletonEXTMask(ArrayRef<int> M, EVT VT, unsigned &Imm) {
  7319. unsigned NumElts = VT.getVectorNumElements();
  7320. // Assume that the first shuffle index is not UNDEF. Fail if it is.
  7321. if (M[0] < 0)
  7322. return false;
  7323. Imm = M[0];
  7324. // If this is a VEXT shuffle, the immediate value is the index of the first
  7325. // element. The other shuffle indices must be the successive elements after
  7326. // the first one.
  7327. unsigned ExpectedElt = Imm;
  7328. for (unsigned i = 1; i < NumElts; ++i) {
  7329. // Increment the expected index. If it wraps around, just follow it
  7330. // back to index zero and keep going.
  7331. ++ExpectedElt;
  7332. if (ExpectedElt == NumElts)
  7333. ExpectedElt = 0;
  7334. if (M[i] < 0)
  7335. continue; // ignore UNDEF indices
  7336. if (ExpectedElt != static_cast<unsigned>(M[i]))
  7337. return false;
  7338. }
  7339. return true;
  7340. }
  7341. /// Check if a vector shuffle corresponds to a DUP instructions with a larger
  7342. /// element width than the vector lane type. If that is the case the function
  7343. /// returns true and writes the value of the DUP instruction lane operand into
  7344. /// DupLaneOp
  7345. static bool isWideDUPMask(ArrayRef<int> M, EVT VT, unsigned BlockSize,
  7346. unsigned &DupLaneOp) {
  7347. assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
  7348. "Only possible block sizes for wide DUP are: 16, 32, 64");
  7349. if (BlockSize <= VT.getScalarSizeInBits())
  7350. return false;
  7351. if (BlockSize % VT.getScalarSizeInBits() != 0)
  7352. return false;
  7353. if (VT.getSizeInBits() % BlockSize != 0)
  7354. return false;
  7355. size_t SingleVecNumElements = VT.getVectorNumElements();
  7356. size_t NumEltsPerBlock = BlockSize / VT.getScalarSizeInBits();
  7357. size_t NumBlocks = VT.getSizeInBits() / BlockSize;
  7358. // We are looking for masks like
  7359. // [0, 1, 0, 1] or [2, 3, 2, 3] or [4, 5, 6, 7, 4, 5, 6, 7] where any element
  7360. // might be replaced by 'undefined'. BlockIndices will eventually contain
  7361. // lane indices of the duplicated block (i.e. [0, 1], [2, 3] and [4, 5, 6, 7]
  7362. // for the above examples)
  7363. SmallVector<int, 8> BlockElts(NumEltsPerBlock, -1);
  7364. for (size_t BlockIndex = 0; BlockIndex < NumBlocks; BlockIndex++)
  7365. for (size_t I = 0; I < NumEltsPerBlock; I++) {
  7366. int Elt = M[BlockIndex * NumEltsPerBlock + I];
  7367. if (Elt < 0)
  7368. continue;
  7369. // For now we don't support shuffles that use the second operand
  7370. if ((unsigned)Elt >= SingleVecNumElements)
  7371. return false;
  7372. if (BlockElts[I] < 0)
  7373. BlockElts[I] = Elt;
  7374. else if (BlockElts[I] != Elt)
  7375. return false;
  7376. }
  7377. // We found a candidate block (possibly with some undefs). It must be a
  7378. // sequence of consecutive integers starting with a value divisible by
  7379. // NumEltsPerBlock with some values possibly replaced by undef-s.
  7380. // Find first non-undef element
  7381. auto FirstRealEltIter = find_if(BlockElts, [](int Elt) { return Elt >= 0; });
  7382. assert(FirstRealEltIter != BlockElts.end() &&
  7383. "Shuffle with all-undefs must have been caught by previous cases, "
  7384. "e.g. isSplat()");
  7385. if (FirstRealEltIter == BlockElts.end()) {
  7386. DupLaneOp = 0;
  7387. return true;
  7388. }
  7389. // Index of FirstRealElt in BlockElts
  7390. size_t FirstRealIndex = FirstRealEltIter - BlockElts.begin();
  7391. if ((unsigned)*FirstRealEltIter < FirstRealIndex)
  7392. return false;
  7393. // BlockElts[0] must have the following value if it isn't undef:
  7394. size_t Elt0 = *FirstRealEltIter - FirstRealIndex;
  7395. // Check the first element
  7396. if (Elt0 % NumEltsPerBlock != 0)
  7397. return false;
  7398. // Check that the sequence indeed consists of consecutive integers (modulo
  7399. // undefs)
  7400. for (size_t I = 0; I < NumEltsPerBlock; I++)
  7401. if (BlockElts[I] >= 0 && (unsigned)BlockElts[I] != Elt0 + I)
  7402. return false;
  7403. DupLaneOp = Elt0 / NumEltsPerBlock;
  7404. return true;
  7405. }
  7406. // check if an EXT instruction can handle the shuffle mask when the
  7407. // vector sources of the shuffle are different.
  7408. static bool isEXTMask(ArrayRef<int> M, EVT VT, bool &ReverseEXT,
  7409. unsigned &Imm) {
  7410. // Look for the first non-undef element.
  7411. const int *FirstRealElt = find_if(M, [](int Elt) { return Elt >= 0; });
  7412. // Benefit form APInt to handle overflow when calculating expected element.
  7413. unsigned NumElts = VT.getVectorNumElements();
  7414. unsigned MaskBits = APInt(32, NumElts * 2).logBase2();
  7415. APInt ExpectedElt = APInt(MaskBits, *FirstRealElt + 1);
  7416. // The following shuffle indices must be the successive elements after the
  7417. // first real element.
  7418. const int *FirstWrongElt = std::find_if(FirstRealElt + 1, M.end(),
  7419. [&](int Elt) {return Elt != ExpectedElt++ && Elt != -1;});
  7420. if (FirstWrongElt != M.end())
  7421. return false;
  7422. // The index of an EXT is the first element if it is not UNDEF.
  7423. // Watch out for the beginning UNDEFs. The EXT index should be the expected
  7424. // value of the first element. E.g.
  7425. // <-1, -1, 3, ...> is treated as <1, 2, 3, ...>.
  7426. // <-1, -1, 0, 1, ...> is treated as <2*NumElts-2, 2*NumElts-1, 0, 1, ...>.
  7427. // ExpectedElt is the last mask index plus 1.
  7428. Imm = ExpectedElt.getZExtValue();
  7429. // There are two difference cases requiring to reverse input vectors.
  7430. // For example, for vector <4 x i32> we have the following cases,
  7431. // Case 1: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, -1, 0>)
  7432. // Case 2: shufflevector(<4 x i32>,<4 x i32>,<-1, -1, 7, 0>)
  7433. // For both cases, we finally use mask <5, 6, 7, 0>, which requires
  7434. // to reverse two input vectors.
  7435. if (Imm < NumElts)
  7436. ReverseEXT = true;
  7437. else
  7438. Imm -= NumElts;
  7439. return true;
  7440. }
  7441. /// isREVMask - Check if a vector shuffle corresponds to a REV
  7442. /// instruction with the specified blocksize. (The order of the elements
  7443. /// within each block of the vector is reversed.)
  7444. static bool isREVMask(ArrayRef<int> M, EVT VT, unsigned BlockSize) {
  7445. assert((BlockSize == 16 || BlockSize == 32 || BlockSize == 64) &&
  7446. "Only possible block sizes for REV are: 16, 32, 64");
  7447. unsigned EltSz = VT.getScalarSizeInBits();
  7448. if (EltSz == 64)
  7449. return false;
  7450. unsigned NumElts = VT.getVectorNumElements();
  7451. unsigned BlockElts = M[0] + 1;
  7452. // If the first shuffle index is UNDEF, be optimistic.
  7453. if (M[0] < 0)
  7454. BlockElts = BlockSize / EltSz;
  7455. if (BlockSize <= EltSz || BlockSize != BlockElts * EltSz)
  7456. return false;
  7457. for (unsigned i = 0; i < NumElts; ++i) {
  7458. if (M[i] < 0)
  7459. continue; // ignore UNDEF indices
  7460. if ((unsigned)M[i] != (i - i % BlockElts) + (BlockElts - 1 - i % BlockElts))
  7461. return false;
  7462. }
  7463. return true;
  7464. }
  7465. static bool isZIPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
  7466. unsigned NumElts = VT.getVectorNumElements();
  7467. if (NumElts % 2 != 0)
  7468. return false;
  7469. WhichResult = (M[0] == 0 ? 0 : 1);
  7470. unsigned Idx = WhichResult * NumElts / 2;
  7471. for (unsigned i = 0; i != NumElts; i += 2) {
  7472. if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
  7473. (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx + NumElts))
  7474. return false;
  7475. Idx += 1;
  7476. }
  7477. return true;
  7478. }
  7479. static bool isUZPMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
  7480. unsigned NumElts = VT.getVectorNumElements();
  7481. WhichResult = (M[0] == 0 ? 0 : 1);
  7482. for (unsigned i = 0; i != NumElts; ++i) {
  7483. if (M[i] < 0)
  7484. continue; // ignore UNDEF indices
  7485. if ((unsigned)M[i] != 2 * i + WhichResult)
  7486. return false;
  7487. }
  7488. return true;
  7489. }
  7490. static bool isTRNMask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
  7491. unsigned NumElts = VT.getVectorNumElements();
  7492. if (NumElts % 2 != 0)
  7493. return false;
  7494. WhichResult = (M[0] == 0 ? 0 : 1);
  7495. for (unsigned i = 0; i < NumElts; i += 2) {
  7496. if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
  7497. (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + NumElts + WhichResult))
  7498. return false;
  7499. }
  7500. return true;
  7501. }
  7502. /// isZIP_v_undef_Mask - Special case of isZIPMask for canonical form of
  7503. /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
  7504. /// Mask is e.g., <0, 0, 1, 1> instead of <0, 4, 1, 5>.
  7505. static bool isZIP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
  7506. unsigned NumElts = VT.getVectorNumElements();
  7507. if (NumElts % 2 != 0)
  7508. return false;
  7509. WhichResult = (M[0] == 0 ? 0 : 1);
  7510. unsigned Idx = WhichResult * NumElts / 2;
  7511. for (unsigned i = 0; i != NumElts; i += 2) {
  7512. if ((M[i] >= 0 && (unsigned)M[i] != Idx) ||
  7513. (M[i + 1] >= 0 && (unsigned)M[i + 1] != Idx))
  7514. return false;
  7515. Idx += 1;
  7516. }
  7517. return true;
  7518. }
  7519. /// isUZP_v_undef_Mask - Special case of isUZPMask for canonical form of
  7520. /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
  7521. /// Mask is e.g., <0, 2, 0, 2> instead of <0, 2, 4, 6>,
  7522. static bool isUZP_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
  7523. unsigned Half = VT.getVectorNumElements() / 2;
  7524. WhichResult = (M[0] == 0 ? 0 : 1);
  7525. for (unsigned j = 0; j != 2; ++j) {
  7526. unsigned Idx = WhichResult;
  7527. for (unsigned i = 0; i != Half; ++i) {
  7528. int MIdx = M[i + j * Half];
  7529. if (MIdx >= 0 && (unsigned)MIdx != Idx)
  7530. return false;
  7531. Idx += 2;
  7532. }
  7533. }
  7534. return true;
  7535. }
  7536. /// isTRN_v_undef_Mask - Special case of isTRNMask for canonical form of
  7537. /// "vector_shuffle v, v", i.e., "vector_shuffle v, undef".
  7538. /// Mask is e.g., <0, 0, 2, 2> instead of <0, 4, 2, 6>.
  7539. static bool isTRN_v_undef_Mask(ArrayRef<int> M, EVT VT, unsigned &WhichResult) {
  7540. unsigned NumElts = VT.getVectorNumElements();
  7541. if (NumElts % 2 != 0)
  7542. return false;
  7543. WhichResult = (M[0] == 0 ? 0 : 1);
  7544. for (unsigned i = 0; i < NumElts; i += 2) {
  7545. if ((M[i] >= 0 && (unsigned)M[i] != i + WhichResult) ||
  7546. (M[i + 1] >= 0 && (unsigned)M[i + 1] != i + WhichResult))
  7547. return false;
  7548. }
  7549. return true;
  7550. }
  7551. static bool isINSMask(ArrayRef<int> M, int NumInputElements,
  7552. bool &DstIsLeft, int &Anomaly) {
  7553. if (M.size() != static_cast<size_t>(NumInputElements))
  7554. return false;
  7555. int NumLHSMatch = 0, NumRHSMatch = 0;
  7556. int LastLHSMismatch = -1, LastRHSMismatch = -1;
  7557. for (int i = 0; i < NumInputElements; ++i) {
  7558. if (M[i] == -1) {
  7559. ++NumLHSMatch;
  7560. ++NumRHSMatch;
  7561. continue;
  7562. }
  7563. if (M[i] == i)
  7564. ++NumLHSMatch;
  7565. else
  7566. LastLHSMismatch = i;
  7567. if (M[i] == i + NumInputElements)
  7568. ++NumRHSMatch;
  7569. else
  7570. LastRHSMismatch = i;
  7571. }
  7572. if (NumLHSMatch == NumInputElements - 1) {
  7573. DstIsLeft = true;
  7574. Anomaly = LastLHSMismatch;
  7575. return true;
  7576. } else if (NumRHSMatch == NumInputElements - 1) {
  7577. DstIsLeft = false;
  7578. Anomaly = LastRHSMismatch;
  7579. return true;
  7580. }
  7581. return false;
  7582. }
  7583. static bool isConcatMask(ArrayRef<int> Mask, EVT VT, bool SplitLHS) {
  7584. if (VT.getSizeInBits() != 128)
  7585. return false;
  7586. unsigned NumElts = VT.getVectorNumElements();
  7587. for (int I = 0, E = NumElts / 2; I != E; I++) {
  7588. if (Mask[I] != I)
  7589. return false;
  7590. }
  7591. int Offset = NumElts / 2;
  7592. for (int I = NumElts / 2, E = NumElts; I != E; I++) {
  7593. if (Mask[I] != I + SplitLHS * Offset)
  7594. return false;
  7595. }
  7596. return true;
  7597. }
  7598. static SDValue tryFormConcatFromShuffle(SDValue Op, SelectionDAG &DAG) {
  7599. SDLoc DL(Op);
  7600. EVT VT = Op.getValueType();
  7601. SDValue V0 = Op.getOperand(0);
  7602. SDValue V1 = Op.getOperand(1);
  7603. ArrayRef<int> Mask = cast<ShuffleVectorSDNode>(Op)->getMask();
  7604. if (VT.getVectorElementType() != V0.getValueType().getVectorElementType() ||
  7605. VT.getVectorElementType() != V1.getValueType().getVectorElementType())
  7606. return SDValue();
  7607. bool SplitV0 = V0.getValueSizeInBits() == 128;
  7608. if (!isConcatMask(Mask, VT, SplitV0))
  7609. return SDValue();
  7610. EVT CastVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
  7611. if (SplitV0) {
  7612. V0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V0,
  7613. DAG.getConstant(0, DL, MVT::i64));
  7614. }
  7615. if (V1.getValueSizeInBits() == 128) {
  7616. V1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, CastVT, V1,
  7617. DAG.getConstant(0, DL, MVT::i64));
  7618. }
  7619. return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, V0, V1);
  7620. }
  7621. /// GeneratePerfectShuffle - Given an entry in the perfect-shuffle table, emit
  7622. /// the specified operations to build the shuffle.
  7623. static SDValue GeneratePerfectShuffle(unsigned PFEntry, SDValue LHS,
  7624. SDValue RHS, SelectionDAG &DAG,
  7625. const SDLoc &dl) {
  7626. unsigned OpNum = (PFEntry >> 26) & 0x0F;
  7627. unsigned LHSID = (PFEntry >> 13) & ((1 << 13) - 1);
  7628. unsigned RHSID = (PFEntry >> 0) & ((1 << 13) - 1);
  7629. enum {
  7630. OP_COPY = 0, // Copy, used for things like <u,u,u,3> to say it is <0,1,2,3>
  7631. OP_VREV,
  7632. OP_VDUP0,
  7633. OP_VDUP1,
  7634. OP_VDUP2,
  7635. OP_VDUP3,
  7636. OP_VEXT1,
  7637. OP_VEXT2,
  7638. OP_VEXT3,
  7639. OP_VUZPL, // VUZP, left result
  7640. OP_VUZPR, // VUZP, right result
  7641. OP_VZIPL, // VZIP, left result
  7642. OP_VZIPR, // VZIP, right result
  7643. OP_VTRNL, // VTRN, left result
  7644. OP_VTRNR // VTRN, right result
  7645. };
  7646. if (OpNum == OP_COPY) {
  7647. if (LHSID == (1 * 9 + 2) * 9 + 3)
  7648. return LHS;
  7649. assert(LHSID == ((4 * 9 + 5) * 9 + 6) * 9 + 7 && "Illegal OP_COPY!");
  7650. return RHS;
  7651. }
  7652. SDValue OpLHS, OpRHS;
  7653. OpLHS = GeneratePerfectShuffle(PerfectShuffleTable[LHSID], LHS, RHS, DAG, dl);
  7654. OpRHS = GeneratePerfectShuffle(PerfectShuffleTable[RHSID], LHS, RHS, DAG, dl);
  7655. EVT VT = OpLHS.getValueType();
  7656. switch (OpNum) {
  7657. default:
  7658. llvm_unreachable("Unknown shuffle opcode!");
  7659. case OP_VREV:
  7660. // VREV divides the vector in half and swaps within the half.
  7661. if (VT.getVectorElementType() == MVT::i32 ||
  7662. VT.getVectorElementType() == MVT::f32)
  7663. return DAG.getNode(AArch64ISD::REV64, dl, VT, OpLHS);
  7664. // vrev <4 x i16> -> REV32
  7665. if (VT.getVectorElementType() == MVT::i16 ||
  7666. VT.getVectorElementType() == MVT::f16 ||
  7667. VT.getVectorElementType() == MVT::bf16)
  7668. return DAG.getNode(AArch64ISD::REV32, dl, VT, OpLHS);
  7669. // vrev <4 x i8> -> REV16
  7670. assert(VT.getVectorElementType() == MVT::i8);
  7671. return DAG.getNode(AArch64ISD::REV16, dl, VT, OpLHS);
  7672. case OP_VDUP0:
  7673. case OP_VDUP1:
  7674. case OP_VDUP2:
  7675. case OP_VDUP3: {
  7676. EVT EltTy = VT.getVectorElementType();
  7677. unsigned Opcode;
  7678. if (EltTy == MVT::i8)
  7679. Opcode = AArch64ISD::DUPLANE8;
  7680. else if (EltTy == MVT::i16 || EltTy == MVT::f16 || EltTy == MVT::bf16)
  7681. Opcode = AArch64ISD::DUPLANE16;
  7682. else if (EltTy == MVT::i32 || EltTy == MVT::f32)
  7683. Opcode = AArch64ISD::DUPLANE32;
  7684. else if (EltTy == MVT::i64 || EltTy == MVT::f64)
  7685. Opcode = AArch64ISD::DUPLANE64;
  7686. else
  7687. llvm_unreachable("Invalid vector element type?");
  7688. if (VT.getSizeInBits() == 64)
  7689. OpLHS = WidenVector(OpLHS, DAG);
  7690. SDValue Lane = DAG.getConstant(OpNum - OP_VDUP0, dl, MVT::i64);
  7691. return DAG.getNode(Opcode, dl, VT, OpLHS, Lane);
  7692. }
  7693. case OP_VEXT1:
  7694. case OP_VEXT2:
  7695. case OP_VEXT3: {
  7696. unsigned Imm = (OpNum - OP_VEXT1 + 1) * getExtFactor(OpLHS);
  7697. return DAG.getNode(AArch64ISD::EXT, dl, VT, OpLHS, OpRHS,
  7698. DAG.getConstant(Imm, dl, MVT::i32));
  7699. }
  7700. case OP_VUZPL:
  7701. return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), OpLHS,
  7702. OpRHS);
  7703. case OP_VUZPR:
  7704. return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), OpLHS,
  7705. OpRHS);
  7706. case OP_VZIPL:
  7707. return DAG.getNode(AArch64ISD::ZIP1, dl, DAG.getVTList(VT, VT), OpLHS,
  7708. OpRHS);
  7709. case OP_VZIPR:
  7710. return DAG.getNode(AArch64ISD::ZIP2, dl, DAG.getVTList(VT, VT), OpLHS,
  7711. OpRHS);
  7712. case OP_VTRNL:
  7713. return DAG.getNode(AArch64ISD::TRN1, dl, DAG.getVTList(VT, VT), OpLHS,
  7714. OpRHS);
  7715. case OP_VTRNR:
  7716. return DAG.getNode(AArch64ISD::TRN2, dl, DAG.getVTList(VT, VT), OpLHS,
  7717. OpRHS);
  7718. }
  7719. }
  7720. static SDValue GenerateTBL(SDValue Op, ArrayRef<int> ShuffleMask,
  7721. SelectionDAG &DAG) {
  7722. // Check to see if we can use the TBL instruction.
  7723. SDValue V1 = Op.getOperand(0);
  7724. SDValue V2 = Op.getOperand(1);
  7725. SDLoc DL(Op);
  7726. EVT EltVT = Op.getValueType().getVectorElementType();
  7727. unsigned BytesPerElt = EltVT.getSizeInBits() / 8;
  7728. SmallVector<SDValue, 8> TBLMask;
  7729. for (int Val : ShuffleMask) {
  7730. for (unsigned Byte = 0; Byte < BytesPerElt; ++Byte) {
  7731. unsigned Offset = Byte + Val * BytesPerElt;
  7732. TBLMask.push_back(DAG.getConstant(Offset, DL, MVT::i32));
  7733. }
  7734. }
  7735. MVT IndexVT = MVT::v8i8;
  7736. unsigned IndexLen = 8;
  7737. if (Op.getValueSizeInBits() == 128) {
  7738. IndexVT = MVT::v16i8;
  7739. IndexLen = 16;
  7740. }
  7741. SDValue V1Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V1);
  7742. SDValue V2Cst = DAG.getNode(ISD::BITCAST, DL, IndexVT, V2);
  7743. SDValue Shuffle;
  7744. if (V2.getNode()->isUndef()) {
  7745. if (IndexLen == 8)
  7746. V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V1Cst);
  7747. Shuffle = DAG.getNode(
  7748. ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
  7749. DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
  7750. DAG.getBuildVector(IndexVT, DL,
  7751. makeArrayRef(TBLMask.data(), IndexLen)));
  7752. } else {
  7753. if (IndexLen == 8) {
  7754. V1Cst = DAG.getNode(ISD::CONCAT_VECTORS, DL, MVT::v16i8, V1Cst, V2Cst);
  7755. Shuffle = DAG.getNode(
  7756. ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
  7757. DAG.getConstant(Intrinsic::aarch64_neon_tbl1, DL, MVT::i32), V1Cst,
  7758. DAG.getBuildVector(IndexVT, DL,
  7759. makeArrayRef(TBLMask.data(), IndexLen)));
  7760. } else {
  7761. // FIXME: We cannot, for the moment, emit a TBL2 instruction because we
  7762. // cannot currently represent the register constraints on the input
  7763. // table registers.
  7764. // Shuffle = DAG.getNode(AArch64ISD::TBL2, DL, IndexVT, V1Cst, V2Cst,
  7765. // DAG.getBuildVector(IndexVT, DL, &TBLMask[0],
  7766. // IndexLen));
  7767. Shuffle = DAG.getNode(
  7768. ISD::INTRINSIC_WO_CHAIN, DL, IndexVT,
  7769. DAG.getConstant(Intrinsic::aarch64_neon_tbl2, DL, MVT::i32), V1Cst,
  7770. V2Cst, DAG.getBuildVector(IndexVT, DL,
  7771. makeArrayRef(TBLMask.data(), IndexLen)));
  7772. }
  7773. }
  7774. return DAG.getNode(ISD::BITCAST, DL, Op.getValueType(), Shuffle);
  7775. }
  7776. static unsigned getDUPLANEOp(EVT EltType) {
  7777. if (EltType == MVT::i8)
  7778. return AArch64ISD::DUPLANE8;
  7779. if (EltType == MVT::i16 || EltType == MVT::f16 || EltType == MVT::bf16)
  7780. return AArch64ISD::DUPLANE16;
  7781. if (EltType == MVT::i32 || EltType == MVT::f32)
  7782. return AArch64ISD::DUPLANE32;
  7783. if (EltType == MVT::i64 || EltType == MVT::f64)
  7784. return AArch64ISD::DUPLANE64;
  7785. llvm_unreachable("Invalid vector element type?");
  7786. }
  7787. static SDValue constructDup(SDValue V, int Lane, SDLoc dl, EVT VT,
  7788. unsigned Opcode, SelectionDAG &DAG) {
  7789. // Try to eliminate a bitcasted extract subvector before a DUPLANE.
  7790. auto getScaledOffsetDup = [](SDValue BitCast, int &LaneC, MVT &CastVT) {
  7791. // Match: dup (bitcast (extract_subv X, C)), LaneC
  7792. if (BitCast.getOpcode() != ISD::BITCAST ||
  7793. BitCast.getOperand(0).getOpcode() != ISD::EXTRACT_SUBVECTOR)
  7794. return false;
  7795. // The extract index must align in the destination type. That may not
  7796. // happen if the bitcast is from narrow to wide type.
  7797. SDValue Extract = BitCast.getOperand(0);
  7798. unsigned ExtIdx = Extract.getConstantOperandVal(1);
  7799. unsigned SrcEltBitWidth = Extract.getScalarValueSizeInBits();
  7800. unsigned ExtIdxInBits = ExtIdx * SrcEltBitWidth;
  7801. unsigned CastedEltBitWidth = BitCast.getScalarValueSizeInBits();
  7802. if (ExtIdxInBits % CastedEltBitWidth != 0)
  7803. return false;
  7804. // Update the lane value by offsetting with the scaled extract index.
  7805. LaneC += ExtIdxInBits / CastedEltBitWidth;
  7806. // Determine the casted vector type of the wide vector input.
  7807. // dup (bitcast (extract_subv X, C)), LaneC --> dup (bitcast X), LaneC'
  7808. // Examples:
  7809. // dup (bitcast (extract_subv v2f64 X, 1) to v2f32), 1 --> dup v4f32 X, 3
  7810. // dup (bitcast (extract_subv v16i8 X, 8) to v4i16), 1 --> dup v8i16 X, 5
  7811. unsigned SrcVecNumElts =
  7812. Extract.getOperand(0).getValueSizeInBits() / CastedEltBitWidth;
  7813. CastVT = MVT::getVectorVT(BitCast.getSimpleValueType().getScalarType(),
  7814. SrcVecNumElts);
  7815. return true;
  7816. };
  7817. MVT CastVT;
  7818. if (getScaledOffsetDup(V, Lane, CastVT)) {
  7819. V = DAG.getBitcast(CastVT, V.getOperand(0).getOperand(0));
  7820. } else if (V.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
  7821. // The lane is incremented by the index of the extract.
  7822. // Example: dup v2f32 (extract v4f32 X, 2), 1 --> dup v4f32 X, 3
  7823. Lane += V.getConstantOperandVal(1);
  7824. V = V.getOperand(0);
  7825. } else if (V.getOpcode() == ISD::CONCAT_VECTORS) {
  7826. // The lane is decremented if we are splatting from the 2nd operand.
  7827. // Example: dup v4i32 (concat v2i32 X, v2i32 Y), 3 --> dup v4i32 Y, 1
  7828. unsigned Idx = Lane >= (int)VT.getVectorNumElements() / 2;
  7829. Lane -= Idx * VT.getVectorNumElements() / 2;
  7830. V = WidenVector(V.getOperand(Idx), DAG);
  7831. } else if (VT.getSizeInBits() == 64) {
  7832. // Widen the operand to 128-bit register with undef.
  7833. V = WidenVector(V, DAG);
  7834. }
  7835. return DAG.getNode(Opcode, dl, VT, V, DAG.getConstant(Lane, dl, MVT::i64));
  7836. }
  7837. SDValue AArch64TargetLowering::LowerVECTOR_SHUFFLE(SDValue Op,
  7838. SelectionDAG &DAG) const {
  7839. SDLoc dl(Op);
  7840. EVT VT = Op.getValueType();
  7841. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Op.getNode());
  7842. // Convert shuffles that are directly supported on NEON to target-specific
  7843. // DAG nodes, instead of keeping them as shuffles and matching them again
  7844. // during code selection. This is more efficient and avoids the possibility
  7845. // of inconsistencies between legalization and selection.
  7846. ArrayRef<int> ShuffleMask = SVN->getMask();
  7847. SDValue V1 = Op.getOperand(0);
  7848. SDValue V2 = Op.getOperand(1);
  7849. if (SVN->isSplat()) {
  7850. int Lane = SVN->getSplatIndex();
  7851. // If this is undef splat, generate it via "just" vdup, if possible.
  7852. if (Lane == -1)
  7853. Lane = 0;
  7854. if (Lane == 0 && V1.getOpcode() == ISD::SCALAR_TO_VECTOR)
  7855. return DAG.getNode(AArch64ISD::DUP, dl, V1.getValueType(),
  7856. V1.getOperand(0));
  7857. // Test if V1 is a BUILD_VECTOR and the lane being referenced is a non-
  7858. // constant. If so, we can just reference the lane's definition directly.
  7859. if (V1.getOpcode() == ISD::BUILD_VECTOR &&
  7860. !isa<ConstantSDNode>(V1.getOperand(Lane)))
  7861. return DAG.getNode(AArch64ISD::DUP, dl, VT, V1.getOperand(Lane));
  7862. // Otherwise, duplicate from the lane of the input vector.
  7863. unsigned Opcode = getDUPLANEOp(V1.getValueType().getVectorElementType());
  7864. return constructDup(V1, Lane, dl, VT, Opcode, DAG);
  7865. }
  7866. // Check if the mask matches a DUP for a wider element
  7867. for (unsigned LaneSize : {64U, 32U, 16U}) {
  7868. unsigned Lane = 0;
  7869. if (isWideDUPMask(ShuffleMask, VT, LaneSize, Lane)) {
  7870. unsigned Opcode = LaneSize == 64 ? AArch64ISD::DUPLANE64
  7871. : LaneSize == 32 ? AArch64ISD::DUPLANE32
  7872. : AArch64ISD::DUPLANE16;
  7873. // Cast V1 to an integer vector with required lane size
  7874. MVT NewEltTy = MVT::getIntegerVT(LaneSize);
  7875. unsigned NewEltCount = VT.getSizeInBits() / LaneSize;
  7876. MVT NewVecTy = MVT::getVectorVT(NewEltTy, NewEltCount);
  7877. V1 = DAG.getBitcast(NewVecTy, V1);
  7878. // Constuct the DUP instruction
  7879. V1 = constructDup(V1, Lane, dl, NewVecTy, Opcode, DAG);
  7880. // Cast back to the original type
  7881. return DAG.getBitcast(VT, V1);
  7882. }
  7883. }
  7884. if (isREVMask(ShuffleMask, VT, 64))
  7885. return DAG.getNode(AArch64ISD::REV64, dl, V1.getValueType(), V1, V2);
  7886. if (isREVMask(ShuffleMask, VT, 32))
  7887. return DAG.getNode(AArch64ISD::REV32, dl, V1.getValueType(), V1, V2);
  7888. if (isREVMask(ShuffleMask, VT, 16))
  7889. return DAG.getNode(AArch64ISD::REV16, dl, V1.getValueType(), V1, V2);
  7890. bool ReverseEXT = false;
  7891. unsigned Imm;
  7892. if (isEXTMask(ShuffleMask, VT, ReverseEXT, Imm)) {
  7893. if (ReverseEXT)
  7894. std::swap(V1, V2);
  7895. Imm *= getExtFactor(V1);
  7896. return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V2,
  7897. DAG.getConstant(Imm, dl, MVT::i32));
  7898. } else if (V2->isUndef() && isSingletonEXTMask(ShuffleMask, VT, Imm)) {
  7899. Imm *= getExtFactor(V1);
  7900. return DAG.getNode(AArch64ISD::EXT, dl, V1.getValueType(), V1, V1,
  7901. DAG.getConstant(Imm, dl, MVT::i32));
  7902. }
  7903. unsigned WhichResult;
  7904. if (isZIPMask(ShuffleMask, VT, WhichResult)) {
  7905. unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
  7906. return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
  7907. }
  7908. if (isUZPMask(ShuffleMask, VT, WhichResult)) {
  7909. unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
  7910. return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
  7911. }
  7912. if (isTRNMask(ShuffleMask, VT, WhichResult)) {
  7913. unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
  7914. return DAG.getNode(Opc, dl, V1.getValueType(), V1, V2);
  7915. }
  7916. if (isZIP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
  7917. unsigned Opc = (WhichResult == 0) ? AArch64ISD::ZIP1 : AArch64ISD::ZIP2;
  7918. return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
  7919. }
  7920. if (isUZP_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
  7921. unsigned Opc = (WhichResult == 0) ? AArch64ISD::UZP1 : AArch64ISD::UZP2;
  7922. return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
  7923. }
  7924. if (isTRN_v_undef_Mask(ShuffleMask, VT, WhichResult)) {
  7925. unsigned Opc = (WhichResult == 0) ? AArch64ISD::TRN1 : AArch64ISD::TRN2;
  7926. return DAG.getNode(Opc, dl, V1.getValueType(), V1, V1);
  7927. }
  7928. if (SDValue Concat = tryFormConcatFromShuffle(Op, DAG))
  7929. return Concat;
  7930. bool DstIsLeft;
  7931. int Anomaly;
  7932. int NumInputElements = V1.getValueType().getVectorNumElements();
  7933. if (isINSMask(ShuffleMask, NumInputElements, DstIsLeft, Anomaly)) {
  7934. SDValue DstVec = DstIsLeft ? V1 : V2;
  7935. SDValue DstLaneV = DAG.getConstant(Anomaly, dl, MVT::i64);
  7936. SDValue SrcVec = V1;
  7937. int SrcLane = ShuffleMask[Anomaly];
  7938. if (SrcLane >= NumInputElements) {
  7939. SrcVec = V2;
  7940. SrcLane -= VT.getVectorNumElements();
  7941. }
  7942. SDValue SrcLaneV = DAG.getConstant(SrcLane, dl, MVT::i64);
  7943. EVT ScalarVT = VT.getVectorElementType();
  7944. if (ScalarVT.getFixedSizeInBits() < 32 && ScalarVT.isInteger())
  7945. ScalarVT = MVT::i32;
  7946. return DAG.getNode(
  7947. ISD::INSERT_VECTOR_ELT, dl, VT, DstVec,
  7948. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, ScalarVT, SrcVec, SrcLaneV),
  7949. DstLaneV);
  7950. }
  7951. // If the shuffle is not directly supported and it has 4 elements, use
  7952. // the PerfectShuffle-generated table to synthesize it from other shuffles.
  7953. unsigned NumElts = VT.getVectorNumElements();
  7954. if (NumElts == 4) {
  7955. unsigned PFIndexes[4];
  7956. for (unsigned i = 0; i != 4; ++i) {
  7957. if (ShuffleMask[i] < 0)
  7958. PFIndexes[i] = 8;
  7959. else
  7960. PFIndexes[i] = ShuffleMask[i];
  7961. }
  7962. // Compute the index in the perfect shuffle table.
  7963. unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
  7964. PFIndexes[2] * 9 + PFIndexes[3];
  7965. unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
  7966. unsigned Cost = (PFEntry >> 30);
  7967. if (Cost <= 4)
  7968. return GeneratePerfectShuffle(PFEntry, V1, V2, DAG, dl);
  7969. }
  7970. return GenerateTBL(Op, ShuffleMask, DAG);
  7971. }
  7972. SDValue AArch64TargetLowering::LowerSPLAT_VECTOR(SDValue Op,
  7973. SelectionDAG &DAG) const {
  7974. SDLoc dl(Op);
  7975. EVT VT = Op.getValueType();
  7976. EVT ElemVT = VT.getScalarType();
  7977. SDValue SplatVal = Op.getOperand(0);
  7978. if (useSVEForFixedLengthVectorVT(VT))
  7979. return LowerToScalableOp(Op, DAG);
  7980. // Extend input splat value where needed to fit into a GPR (32b or 64b only)
  7981. // FPRs don't have this restriction.
  7982. switch (ElemVT.getSimpleVT().SimpleTy) {
  7983. case MVT::i1: {
  7984. // The only legal i1 vectors are SVE vectors, so we can use SVE-specific
  7985. // lowering code.
  7986. if (auto *ConstVal = dyn_cast<ConstantSDNode>(SplatVal)) {
  7987. if (ConstVal->isOne())
  7988. return getPTrue(DAG, dl, VT, AArch64SVEPredPattern::all);
  7989. // TODO: Add special case for constant false
  7990. }
  7991. // The general case of i1. There isn't any natural way to do this,
  7992. // so we use some trickery with whilelo.
  7993. SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
  7994. SplatVal = DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, MVT::i64, SplatVal,
  7995. DAG.getValueType(MVT::i1));
  7996. SDValue ID = DAG.getTargetConstant(Intrinsic::aarch64_sve_whilelo, dl,
  7997. MVT::i64);
  7998. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, dl, VT, ID,
  7999. DAG.getConstant(0, dl, MVT::i64), SplatVal);
  8000. }
  8001. case MVT::i8:
  8002. case MVT::i16:
  8003. case MVT::i32:
  8004. SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i32);
  8005. break;
  8006. case MVT::i64:
  8007. SplatVal = DAG.getAnyExtOrTrunc(SplatVal, dl, MVT::i64);
  8008. break;
  8009. case MVT::f16:
  8010. case MVT::bf16:
  8011. case MVT::f32:
  8012. case MVT::f64:
  8013. // Fine as is
  8014. break;
  8015. default:
  8016. report_fatal_error("Unsupported SPLAT_VECTOR input operand type");
  8017. }
  8018. return DAG.getNode(AArch64ISD::DUP, dl, VT, SplatVal);
  8019. }
  8020. SDValue AArch64TargetLowering::LowerDUPQLane(SDValue Op,
  8021. SelectionDAG &DAG) const {
  8022. SDLoc DL(Op);
  8023. EVT VT = Op.getValueType();
  8024. if (!isTypeLegal(VT) || !VT.isScalableVector())
  8025. return SDValue();
  8026. // Current lowering only supports the SVE-ACLE types.
  8027. if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
  8028. return SDValue();
  8029. // The DUPQ operation is indepedent of element type so normalise to i64s.
  8030. SDValue V = DAG.getNode(ISD::BITCAST, DL, MVT::nxv2i64, Op.getOperand(1));
  8031. SDValue Idx128 = Op.getOperand(2);
  8032. // DUPQ can be used when idx is in range.
  8033. auto *CIdx = dyn_cast<ConstantSDNode>(Idx128);
  8034. if (CIdx && (CIdx->getZExtValue() <= 3)) {
  8035. SDValue CI = DAG.getTargetConstant(CIdx->getZExtValue(), DL, MVT::i64);
  8036. SDNode *DUPQ =
  8037. DAG.getMachineNode(AArch64::DUP_ZZI_Q, DL, MVT::nxv2i64, V, CI);
  8038. return DAG.getNode(ISD::BITCAST, DL, VT, SDValue(DUPQ, 0));
  8039. }
  8040. // The ACLE says this must produce the same result as:
  8041. // svtbl(data, svadd_x(svptrue_b64(),
  8042. // svand_x(svptrue_b64(), svindex_u64(0, 1), 1),
  8043. // index * 2))
  8044. SDValue One = DAG.getConstant(1, DL, MVT::i64);
  8045. SDValue SplatOne = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, One);
  8046. // create the vector 0,1,0,1,...
  8047. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  8048. SDValue SV = DAG.getNode(AArch64ISD::INDEX_VECTOR,
  8049. DL, MVT::nxv2i64, Zero, One);
  8050. SV = DAG.getNode(ISD::AND, DL, MVT::nxv2i64, SV, SplatOne);
  8051. // create the vector idx64,idx64+1,idx64,idx64+1,...
  8052. SDValue Idx64 = DAG.getNode(ISD::ADD, DL, MVT::i64, Idx128, Idx128);
  8053. SDValue SplatIdx64 = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Idx64);
  8054. SDValue ShuffleMask = DAG.getNode(ISD::ADD, DL, MVT::nxv2i64, SV, SplatIdx64);
  8055. // create the vector Val[idx64],Val[idx64+1],Val[idx64],Val[idx64+1],...
  8056. SDValue TBL = DAG.getNode(AArch64ISD::TBL, DL, MVT::nxv2i64, V, ShuffleMask);
  8057. return DAG.getNode(ISD::BITCAST, DL, VT, TBL);
  8058. }
  8059. static bool resolveBuildVector(BuildVectorSDNode *BVN, APInt &CnstBits,
  8060. APInt &UndefBits) {
  8061. EVT VT = BVN->getValueType(0);
  8062. APInt SplatBits, SplatUndef;
  8063. unsigned SplatBitSize;
  8064. bool HasAnyUndefs;
  8065. if (BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize, HasAnyUndefs)) {
  8066. unsigned NumSplats = VT.getSizeInBits() / SplatBitSize;
  8067. for (unsigned i = 0; i < NumSplats; ++i) {
  8068. CnstBits <<= SplatBitSize;
  8069. UndefBits <<= SplatBitSize;
  8070. CnstBits |= SplatBits.zextOrTrunc(VT.getSizeInBits());
  8071. UndefBits |= (SplatBits ^ SplatUndef).zextOrTrunc(VT.getSizeInBits());
  8072. }
  8073. return true;
  8074. }
  8075. return false;
  8076. }
  8077. // Try 64-bit splatted SIMD immediate.
  8078. static SDValue tryAdvSIMDModImm64(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
  8079. const APInt &Bits) {
  8080. if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
  8081. uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
  8082. EVT VT = Op.getValueType();
  8083. MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v2i64 : MVT::f64;
  8084. if (AArch64_AM::isAdvSIMDModImmType10(Value)) {
  8085. Value = AArch64_AM::encodeAdvSIMDModImmType10(Value);
  8086. SDLoc dl(Op);
  8087. SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
  8088. DAG.getConstant(Value, dl, MVT::i32));
  8089. return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
  8090. }
  8091. }
  8092. return SDValue();
  8093. }
  8094. // Try 32-bit splatted SIMD immediate.
  8095. static SDValue tryAdvSIMDModImm32(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
  8096. const APInt &Bits,
  8097. const SDValue *LHS = nullptr) {
  8098. if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
  8099. uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
  8100. EVT VT = Op.getValueType();
  8101. MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
  8102. bool isAdvSIMDModImm = false;
  8103. uint64_t Shift;
  8104. if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType1(Value))) {
  8105. Value = AArch64_AM::encodeAdvSIMDModImmType1(Value);
  8106. Shift = 0;
  8107. }
  8108. else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType2(Value))) {
  8109. Value = AArch64_AM::encodeAdvSIMDModImmType2(Value);
  8110. Shift = 8;
  8111. }
  8112. else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType3(Value))) {
  8113. Value = AArch64_AM::encodeAdvSIMDModImmType3(Value);
  8114. Shift = 16;
  8115. }
  8116. else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType4(Value))) {
  8117. Value = AArch64_AM::encodeAdvSIMDModImmType4(Value);
  8118. Shift = 24;
  8119. }
  8120. if (isAdvSIMDModImm) {
  8121. SDLoc dl(Op);
  8122. SDValue Mov;
  8123. if (LHS)
  8124. Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
  8125. DAG.getConstant(Value, dl, MVT::i32),
  8126. DAG.getConstant(Shift, dl, MVT::i32));
  8127. else
  8128. Mov = DAG.getNode(NewOp, dl, MovTy,
  8129. DAG.getConstant(Value, dl, MVT::i32),
  8130. DAG.getConstant(Shift, dl, MVT::i32));
  8131. return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
  8132. }
  8133. }
  8134. return SDValue();
  8135. }
  8136. // Try 16-bit splatted SIMD immediate.
  8137. static SDValue tryAdvSIMDModImm16(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
  8138. const APInt &Bits,
  8139. const SDValue *LHS = nullptr) {
  8140. if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
  8141. uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
  8142. EVT VT = Op.getValueType();
  8143. MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v8i16 : MVT::v4i16;
  8144. bool isAdvSIMDModImm = false;
  8145. uint64_t Shift;
  8146. if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType5(Value))) {
  8147. Value = AArch64_AM::encodeAdvSIMDModImmType5(Value);
  8148. Shift = 0;
  8149. }
  8150. else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType6(Value))) {
  8151. Value = AArch64_AM::encodeAdvSIMDModImmType6(Value);
  8152. Shift = 8;
  8153. }
  8154. if (isAdvSIMDModImm) {
  8155. SDLoc dl(Op);
  8156. SDValue Mov;
  8157. if (LHS)
  8158. Mov = DAG.getNode(NewOp, dl, MovTy, *LHS,
  8159. DAG.getConstant(Value, dl, MVT::i32),
  8160. DAG.getConstant(Shift, dl, MVT::i32));
  8161. else
  8162. Mov = DAG.getNode(NewOp, dl, MovTy,
  8163. DAG.getConstant(Value, dl, MVT::i32),
  8164. DAG.getConstant(Shift, dl, MVT::i32));
  8165. return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
  8166. }
  8167. }
  8168. return SDValue();
  8169. }
  8170. // Try 32-bit splatted SIMD immediate with shifted ones.
  8171. static SDValue tryAdvSIMDModImm321s(unsigned NewOp, SDValue Op,
  8172. SelectionDAG &DAG, const APInt &Bits) {
  8173. if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
  8174. uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
  8175. EVT VT = Op.getValueType();
  8176. MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v4i32 : MVT::v2i32;
  8177. bool isAdvSIMDModImm = false;
  8178. uint64_t Shift;
  8179. if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType7(Value))) {
  8180. Value = AArch64_AM::encodeAdvSIMDModImmType7(Value);
  8181. Shift = 264;
  8182. }
  8183. else if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType8(Value))) {
  8184. Value = AArch64_AM::encodeAdvSIMDModImmType8(Value);
  8185. Shift = 272;
  8186. }
  8187. if (isAdvSIMDModImm) {
  8188. SDLoc dl(Op);
  8189. SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
  8190. DAG.getConstant(Value, dl, MVT::i32),
  8191. DAG.getConstant(Shift, dl, MVT::i32));
  8192. return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
  8193. }
  8194. }
  8195. return SDValue();
  8196. }
  8197. // Try 8-bit splatted SIMD immediate.
  8198. static SDValue tryAdvSIMDModImm8(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
  8199. const APInt &Bits) {
  8200. if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
  8201. uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
  8202. EVT VT = Op.getValueType();
  8203. MVT MovTy = (VT.getSizeInBits() == 128) ? MVT::v16i8 : MVT::v8i8;
  8204. if (AArch64_AM::isAdvSIMDModImmType9(Value)) {
  8205. Value = AArch64_AM::encodeAdvSIMDModImmType9(Value);
  8206. SDLoc dl(Op);
  8207. SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
  8208. DAG.getConstant(Value, dl, MVT::i32));
  8209. return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
  8210. }
  8211. }
  8212. return SDValue();
  8213. }
  8214. // Try FP splatted SIMD immediate.
  8215. static SDValue tryAdvSIMDModImmFP(unsigned NewOp, SDValue Op, SelectionDAG &DAG,
  8216. const APInt &Bits) {
  8217. if (Bits.getHiBits(64) == Bits.getLoBits(64)) {
  8218. uint64_t Value = Bits.zextOrTrunc(64).getZExtValue();
  8219. EVT VT = Op.getValueType();
  8220. bool isWide = (VT.getSizeInBits() == 128);
  8221. MVT MovTy;
  8222. bool isAdvSIMDModImm = false;
  8223. if ((isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType11(Value))) {
  8224. Value = AArch64_AM::encodeAdvSIMDModImmType11(Value);
  8225. MovTy = isWide ? MVT::v4f32 : MVT::v2f32;
  8226. }
  8227. else if (isWide &&
  8228. (isAdvSIMDModImm = AArch64_AM::isAdvSIMDModImmType12(Value))) {
  8229. Value = AArch64_AM::encodeAdvSIMDModImmType12(Value);
  8230. MovTy = MVT::v2f64;
  8231. }
  8232. if (isAdvSIMDModImm) {
  8233. SDLoc dl(Op);
  8234. SDValue Mov = DAG.getNode(NewOp, dl, MovTy,
  8235. DAG.getConstant(Value, dl, MVT::i32));
  8236. return DAG.getNode(AArch64ISD::NVCAST, dl, VT, Mov);
  8237. }
  8238. }
  8239. return SDValue();
  8240. }
  8241. // Specialized code to quickly find if PotentialBVec is a BuildVector that
  8242. // consists of only the same constant int value, returned in reference arg
  8243. // ConstVal
  8244. static bool isAllConstantBuildVector(const SDValue &PotentialBVec,
  8245. uint64_t &ConstVal) {
  8246. BuildVectorSDNode *Bvec = dyn_cast<BuildVectorSDNode>(PotentialBVec);
  8247. if (!Bvec)
  8248. return false;
  8249. ConstantSDNode *FirstElt = dyn_cast<ConstantSDNode>(Bvec->getOperand(0));
  8250. if (!FirstElt)
  8251. return false;
  8252. EVT VT = Bvec->getValueType(0);
  8253. unsigned NumElts = VT.getVectorNumElements();
  8254. for (unsigned i = 1; i < NumElts; ++i)
  8255. if (dyn_cast<ConstantSDNode>(Bvec->getOperand(i)) != FirstElt)
  8256. return false;
  8257. ConstVal = FirstElt->getZExtValue();
  8258. return true;
  8259. }
  8260. static unsigned getIntrinsicID(const SDNode *N) {
  8261. unsigned Opcode = N->getOpcode();
  8262. switch (Opcode) {
  8263. default:
  8264. return Intrinsic::not_intrinsic;
  8265. case ISD::INTRINSIC_WO_CHAIN: {
  8266. unsigned IID = cast<ConstantSDNode>(N->getOperand(0))->getZExtValue();
  8267. if (IID < Intrinsic::num_intrinsics)
  8268. return IID;
  8269. return Intrinsic::not_intrinsic;
  8270. }
  8271. }
  8272. }
  8273. // Attempt to form a vector S[LR]I from (or (and X, BvecC1), (lsl Y, C2)),
  8274. // to (SLI X, Y, C2), where X and Y have matching vector types, BvecC1 is a
  8275. // BUILD_VECTORs with constant element C1, C2 is a constant, and:
  8276. // - for the SLI case: C1 == ~(Ones(ElemSizeInBits) << C2)
  8277. // - for the SRI case: C1 == ~(Ones(ElemSizeInBits) >> C2)
  8278. // The (or (lsl Y, C2), (and X, BvecC1)) case is also handled.
  8279. static SDValue tryLowerToSLI(SDNode *N, SelectionDAG &DAG) {
  8280. EVT VT = N->getValueType(0);
  8281. if (!VT.isVector())
  8282. return SDValue();
  8283. SDLoc DL(N);
  8284. SDValue And;
  8285. SDValue Shift;
  8286. SDValue FirstOp = N->getOperand(0);
  8287. unsigned FirstOpc = FirstOp.getOpcode();
  8288. SDValue SecondOp = N->getOperand(1);
  8289. unsigned SecondOpc = SecondOp.getOpcode();
  8290. // Is one of the operands an AND or a BICi? The AND may have been optimised to
  8291. // a BICi in order to use an immediate instead of a register.
  8292. // Is the other operand an shl or lshr? This will have been turned into:
  8293. // AArch64ISD::VSHL vector, #shift or AArch64ISD::VLSHR vector, #shift.
  8294. if ((FirstOpc == ISD::AND || FirstOpc == AArch64ISD::BICi) &&
  8295. (SecondOpc == AArch64ISD::VSHL || SecondOpc == AArch64ISD::VLSHR)) {
  8296. And = FirstOp;
  8297. Shift = SecondOp;
  8298. } else if ((SecondOpc == ISD::AND || SecondOpc == AArch64ISD::BICi) &&
  8299. (FirstOpc == AArch64ISD::VSHL || FirstOpc == AArch64ISD::VLSHR)) {
  8300. And = SecondOp;
  8301. Shift = FirstOp;
  8302. } else
  8303. return SDValue();
  8304. bool IsAnd = And.getOpcode() == ISD::AND;
  8305. bool IsShiftRight = Shift.getOpcode() == AArch64ISD::VLSHR;
  8306. // Is the shift amount constant?
  8307. ConstantSDNode *C2node = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
  8308. if (!C2node)
  8309. return SDValue();
  8310. uint64_t C1;
  8311. if (IsAnd) {
  8312. // Is the and mask vector all constant?
  8313. if (!isAllConstantBuildVector(And.getOperand(1), C1))
  8314. return SDValue();
  8315. } else {
  8316. // Reconstruct the corresponding AND immediate from the two BICi immediates.
  8317. ConstantSDNode *C1nodeImm = dyn_cast<ConstantSDNode>(And.getOperand(1));
  8318. ConstantSDNode *C1nodeShift = dyn_cast<ConstantSDNode>(And.getOperand(2));
  8319. assert(C1nodeImm && C1nodeShift);
  8320. C1 = ~(C1nodeImm->getZExtValue() << C1nodeShift->getZExtValue());
  8321. }
  8322. // Is C1 == ~(Ones(ElemSizeInBits) << C2) or
  8323. // C1 == ~(Ones(ElemSizeInBits) >> C2), taking into account
  8324. // how much one can shift elements of a particular size?
  8325. uint64_t C2 = C2node->getZExtValue();
  8326. unsigned ElemSizeInBits = VT.getScalarSizeInBits();
  8327. if (C2 > ElemSizeInBits)
  8328. return SDValue();
  8329. APInt C1AsAPInt(ElemSizeInBits, C1);
  8330. APInt RequiredC1 = IsShiftRight ? APInt::getHighBitsSet(ElemSizeInBits, C2)
  8331. : APInt::getLowBitsSet(ElemSizeInBits, C2);
  8332. if (C1AsAPInt != RequiredC1)
  8333. return SDValue();
  8334. SDValue X = And.getOperand(0);
  8335. SDValue Y = Shift.getOperand(0);
  8336. unsigned Inst = IsShiftRight ? AArch64ISD::VSRI : AArch64ISD::VSLI;
  8337. SDValue ResultSLI = DAG.getNode(Inst, DL, VT, X, Y, Shift.getOperand(1));
  8338. LLVM_DEBUG(dbgs() << "aarch64-lower: transformed: \n");
  8339. LLVM_DEBUG(N->dump(&DAG));
  8340. LLVM_DEBUG(dbgs() << "into: \n");
  8341. LLVM_DEBUG(ResultSLI->dump(&DAG));
  8342. ++NumShiftInserts;
  8343. return ResultSLI;
  8344. }
  8345. SDValue AArch64TargetLowering::LowerVectorOR(SDValue Op,
  8346. SelectionDAG &DAG) const {
  8347. if (useSVEForFixedLengthVectorVT(Op.getValueType()))
  8348. return LowerToScalableOp(Op, DAG);
  8349. // Attempt to form a vector S[LR]I from (or (and X, C1), (lsl Y, C2))
  8350. if (SDValue Res = tryLowerToSLI(Op.getNode(), DAG))
  8351. return Res;
  8352. EVT VT = Op.getValueType();
  8353. SDValue LHS = Op.getOperand(0);
  8354. BuildVectorSDNode *BVN =
  8355. dyn_cast<BuildVectorSDNode>(Op.getOperand(1).getNode());
  8356. if (!BVN) {
  8357. // OR commutes, so try swapping the operands.
  8358. LHS = Op.getOperand(1);
  8359. BVN = dyn_cast<BuildVectorSDNode>(Op.getOperand(0).getNode());
  8360. }
  8361. if (!BVN)
  8362. return Op;
  8363. APInt DefBits(VT.getSizeInBits(), 0);
  8364. APInt UndefBits(VT.getSizeInBits(), 0);
  8365. if (resolveBuildVector(BVN, DefBits, UndefBits)) {
  8366. SDValue NewOp;
  8367. if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
  8368. DefBits, &LHS)) ||
  8369. (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
  8370. DefBits, &LHS)))
  8371. return NewOp;
  8372. if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::ORRi, Op, DAG,
  8373. UndefBits, &LHS)) ||
  8374. (NewOp = tryAdvSIMDModImm16(AArch64ISD::ORRi, Op, DAG,
  8375. UndefBits, &LHS)))
  8376. return NewOp;
  8377. }
  8378. // We can always fall back to a non-immediate OR.
  8379. return Op;
  8380. }
  8381. // Normalize the operands of BUILD_VECTOR. The value of constant operands will
  8382. // be truncated to fit element width.
  8383. static SDValue NormalizeBuildVector(SDValue Op,
  8384. SelectionDAG &DAG) {
  8385. assert(Op.getOpcode() == ISD::BUILD_VECTOR && "Unknown opcode!");
  8386. SDLoc dl(Op);
  8387. EVT VT = Op.getValueType();
  8388. EVT EltTy= VT.getVectorElementType();
  8389. if (EltTy.isFloatingPoint() || EltTy.getSizeInBits() > 16)
  8390. return Op;
  8391. SmallVector<SDValue, 16> Ops;
  8392. for (SDValue Lane : Op->ops()) {
  8393. // For integer vectors, type legalization would have promoted the
  8394. // operands already. Otherwise, if Op is a floating-point splat
  8395. // (with operands cast to integers), then the only possibilities
  8396. // are constants and UNDEFs.
  8397. if (auto *CstLane = dyn_cast<ConstantSDNode>(Lane)) {
  8398. APInt LowBits(EltTy.getSizeInBits(),
  8399. CstLane->getZExtValue());
  8400. Lane = DAG.getConstant(LowBits.getZExtValue(), dl, MVT::i32);
  8401. } else if (Lane.getNode()->isUndef()) {
  8402. Lane = DAG.getUNDEF(MVT::i32);
  8403. } else {
  8404. assert(Lane.getValueType() == MVT::i32 &&
  8405. "Unexpected BUILD_VECTOR operand type");
  8406. }
  8407. Ops.push_back(Lane);
  8408. }
  8409. return DAG.getBuildVector(VT, dl, Ops);
  8410. }
  8411. static SDValue ConstantBuildVector(SDValue Op, SelectionDAG &DAG) {
  8412. EVT VT = Op.getValueType();
  8413. APInt DefBits(VT.getSizeInBits(), 0);
  8414. APInt UndefBits(VT.getSizeInBits(), 0);
  8415. BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
  8416. if (resolveBuildVector(BVN, DefBits, UndefBits)) {
  8417. SDValue NewOp;
  8418. if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
  8419. (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
  8420. (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
  8421. (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
  8422. (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
  8423. (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
  8424. return NewOp;
  8425. DefBits = ~DefBits;
  8426. if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
  8427. (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
  8428. (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
  8429. return NewOp;
  8430. DefBits = UndefBits;
  8431. if ((NewOp = tryAdvSIMDModImm64(AArch64ISD::MOVIedit, Op, DAG, DefBits)) ||
  8432. (NewOp = tryAdvSIMDModImm32(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
  8433. (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MOVImsl, Op, DAG, DefBits)) ||
  8434. (NewOp = tryAdvSIMDModImm16(AArch64ISD::MOVIshift, Op, DAG, DefBits)) ||
  8435. (NewOp = tryAdvSIMDModImm8(AArch64ISD::MOVI, Op, DAG, DefBits)) ||
  8436. (NewOp = tryAdvSIMDModImmFP(AArch64ISD::FMOV, Op, DAG, DefBits)))
  8437. return NewOp;
  8438. DefBits = ~UndefBits;
  8439. if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::MVNIshift, Op, DAG, DefBits)) ||
  8440. (NewOp = tryAdvSIMDModImm321s(AArch64ISD::MVNImsl, Op, DAG, DefBits)) ||
  8441. (NewOp = tryAdvSIMDModImm16(AArch64ISD::MVNIshift, Op, DAG, DefBits)))
  8442. return NewOp;
  8443. }
  8444. return SDValue();
  8445. }
  8446. SDValue AArch64TargetLowering::LowerBUILD_VECTOR(SDValue Op,
  8447. SelectionDAG &DAG) const {
  8448. EVT VT = Op.getValueType();
  8449. // Try to build a simple constant vector.
  8450. Op = NormalizeBuildVector(Op, DAG);
  8451. if (VT.isInteger()) {
  8452. // Certain vector constants, used to express things like logical NOT and
  8453. // arithmetic NEG, are passed through unmodified. This allows special
  8454. // patterns for these operations to match, which will lower these constants
  8455. // to whatever is proven necessary.
  8456. BuildVectorSDNode *BVN = cast<BuildVectorSDNode>(Op.getNode());
  8457. if (BVN->isConstant())
  8458. if (ConstantSDNode *Const = BVN->getConstantSplatNode()) {
  8459. unsigned BitSize = VT.getVectorElementType().getSizeInBits();
  8460. APInt Val(BitSize,
  8461. Const->getAPIntValue().zextOrTrunc(BitSize).getZExtValue());
  8462. if (Val.isNullValue() || Val.isAllOnesValue())
  8463. return Op;
  8464. }
  8465. }
  8466. if (SDValue V = ConstantBuildVector(Op, DAG))
  8467. return V;
  8468. // Scan through the operands to find some interesting properties we can
  8469. // exploit:
  8470. // 1) If only one value is used, we can use a DUP, or
  8471. // 2) if only the low element is not undef, we can just insert that, or
  8472. // 3) if only one constant value is used (w/ some non-constant lanes),
  8473. // we can splat the constant value into the whole vector then fill
  8474. // in the non-constant lanes.
  8475. // 4) FIXME: If different constant values are used, but we can intelligently
  8476. // select the values we'll be overwriting for the non-constant
  8477. // lanes such that we can directly materialize the vector
  8478. // some other way (MOVI, e.g.), we can be sneaky.
  8479. // 5) if all operands are EXTRACT_VECTOR_ELT, check for VUZP.
  8480. SDLoc dl(Op);
  8481. unsigned NumElts = VT.getVectorNumElements();
  8482. bool isOnlyLowElement = true;
  8483. bool usesOnlyOneValue = true;
  8484. bool usesOnlyOneConstantValue = true;
  8485. bool isConstant = true;
  8486. bool AllLanesExtractElt = true;
  8487. unsigned NumConstantLanes = 0;
  8488. unsigned NumDifferentLanes = 0;
  8489. unsigned NumUndefLanes = 0;
  8490. SDValue Value;
  8491. SDValue ConstantValue;
  8492. for (unsigned i = 0; i < NumElts; ++i) {
  8493. SDValue V = Op.getOperand(i);
  8494. if (V.getOpcode() != ISD::EXTRACT_VECTOR_ELT)
  8495. AllLanesExtractElt = false;
  8496. if (V.isUndef()) {
  8497. ++NumUndefLanes;
  8498. continue;
  8499. }
  8500. if (i > 0)
  8501. isOnlyLowElement = false;
  8502. if (!isa<ConstantFPSDNode>(V) && !isa<ConstantSDNode>(V))
  8503. isConstant = false;
  8504. if (isa<ConstantSDNode>(V) || isa<ConstantFPSDNode>(V)) {
  8505. ++NumConstantLanes;
  8506. if (!ConstantValue.getNode())
  8507. ConstantValue = V;
  8508. else if (ConstantValue != V)
  8509. usesOnlyOneConstantValue = false;
  8510. }
  8511. if (!Value.getNode())
  8512. Value = V;
  8513. else if (V != Value) {
  8514. usesOnlyOneValue = false;
  8515. ++NumDifferentLanes;
  8516. }
  8517. }
  8518. if (!Value.getNode()) {
  8519. LLVM_DEBUG(
  8520. dbgs() << "LowerBUILD_VECTOR: value undefined, creating undef node\n");
  8521. return DAG.getUNDEF(VT);
  8522. }
  8523. // Convert BUILD_VECTOR where all elements but the lowest are undef into
  8524. // SCALAR_TO_VECTOR, except for when we have a single-element constant vector
  8525. // as SimplifyDemandedBits will just turn that back into BUILD_VECTOR.
  8526. if (isOnlyLowElement && !(NumElts == 1 && isa<ConstantSDNode>(Value))) {
  8527. LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: only low element used, creating 1 "
  8528. "SCALAR_TO_VECTOR node\n");
  8529. return DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Value);
  8530. }
  8531. if (AllLanesExtractElt) {
  8532. SDNode *Vector = nullptr;
  8533. bool Even = false;
  8534. bool Odd = false;
  8535. // Check whether the extract elements match the Even pattern <0,2,4,...> or
  8536. // the Odd pattern <1,3,5,...>.
  8537. for (unsigned i = 0; i < NumElts; ++i) {
  8538. SDValue V = Op.getOperand(i);
  8539. const SDNode *N = V.getNode();
  8540. if (!isa<ConstantSDNode>(N->getOperand(1)))
  8541. break;
  8542. SDValue N0 = N->getOperand(0);
  8543. // All elements are extracted from the same vector.
  8544. if (!Vector) {
  8545. Vector = N0.getNode();
  8546. // Check that the type of EXTRACT_VECTOR_ELT matches the type of
  8547. // BUILD_VECTOR.
  8548. if (VT.getVectorElementType() !=
  8549. N0.getValueType().getVectorElementType())
  8550. break;
  8551. } else if (Vector != N0.getNode()) {
  8552. Odd = false;
  8553. Even = false;
  8554. break;
  8555. }
  8556. // Extracted values are either at Even indices <0,2,4,...> or at Odd
  8557. // indices <1,3,5,...>.
  8558. uint64_t Val = N->getConstantOperandVal(1);
  8559. if (Val == 2 * i) {
  8560. Even = true;
  8561. continue;
  8562. }
  8563. if (Val - 1 == 2 * i) {
  8564. Odd = true;
  8565. continue;
  8566. }
  8567. // Something does not match: abort.
  8568. Odd = false;
  8569. Even = false;
  8570. break;
  8571. }
  8572. if (Even || Odd) {
  8573. SDValue LHS =
  8574. DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
  8575. DAG.getConstant(0, dl, MVT::i64));
  8576. SDValue RHS =
  8577. DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, VT, SDValue(Vector, 0),
  8578. DAG.getConstant(NumElts, dl, MVT::i64));
  8579. if (Even && !Odd)
  8580. return DAG.getNode(AArch64ISD::UZP1, dl, DAG.getVTList(VT, VT), LHS,
  8581. RHS);
  8582. if (Odd && !Even)
  8583. return DAG.getNode(AArch64ISD::UZP2, dl, DAG.getVTList(VT, VT), LHS,
  8584. RHS);
  8585. }
  8586. }
  8587. // Use DUP for non-constant splats. For f32 constant splats, reduce to
  8588. // i32 and try again.
  8589. if (usesOnlyOneValue) {
  8590. if (!isConstant) {
  8591. if (Value.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  8592. Value.getValueType() != VT) {
  8593. LLVM_DEBUG(
  8594. dbgs() << "LowerBUILD_VECTOR: use DUP for non-constant splats\n");
  8595. return DAG.getNode(AArch64ISD::DUP, dl, VT, Value);
  8596. }
  8597. // This is actually a DUPLANExx operation, which keeps everything vectory.
  8598. SDValue Lane = Value.getOperand(1);
  8599. Value = Value.getOperand(0);
  8600. if (Value.getValueSizeInBits() == 64) {
  8601. LLVM_DEBUG(
  8602. dbgs() << "LowerBUILD_VECTOR: DUPLANE works on 128-bit vectors, "
  8603. "widening it\n");
  8604. Value = WidenVector(Value, DAG);
  8605. }
  8606. unsigned Opcode = getDUPLANEOp(VT.getVectorElementType());
  8607. return DAG.getNode(Opcode, dl, VT, Value, Lane);
  8608. }
  8609. if (VT.getVectorElementType().isFloatingPoint()) {
  8610. SmallVector<SDValue, 8> Ops;
  8611. EVT EltTy = VT.getVectorElementType();
  8612. assert ((EltTy == MVT::f16 || EltTy == MVT::bf16 || EltTy == MVT::f32 ||
  8613. EltTy == MVT::f64) && "Unsupported floating-point vector type");
  8614. LLVM_DEBUG(
  8615. dbgs() << "LowerBUILD_VECTOR: float constant splats, creating int "
  8616. "BITCASTS, and try again\n");
  8617. MVT NewType = MVT::getIntegerVT(EltTy.getSizeInBits());
  8618. for (unsigned i = 0; i < NumElts; ++i)
  8619. Ops.push_back(DAG.getNode(ISD::BITCAST, dl, NewType, Op.getOperand(i)));
  8620. EVT VecVT = EVT::getVectorVT(*DAG.getContext(), NewType, NumElts);
  8621. SDValue Val = DAG.getBuildVector(VecVT, dl, Ops);
  8622. LLVM_DEBUG(dbgs() << "LowerBUILD_VECTOR: trying to lower new vector: ";
  8623. Val.dump(););
  8624. Val = LowerBUILD_VECTOR(Val, DAG);
  8625. if (Val.getNode())
  8626. return DAG.getNode(ISD::BITCAST, dl, VT, Val);
  8627. }
  8628. }
  8629. // If we need to insert a small number of different non-constant elements and
  8630. // the vector width is sufficiently large, prefer using DUP with the common
  8631. // value and INSERT_VECTOR_ELT for the different lanes. If DUP is preferred,
  8632. // skip the constant lane handling below.
  8633. bool PreferDUPAndInsert =
  8634. !isConstant && NumDifferentLanes >= 1 &&
  8635. NumDifferentLanes < ((NumElts - NumUndefLanes) / 2) &&
  8636. NumDifferentLanes >= NumConstantLanes;
  8637. // If there was only one constant value used and for more than one lane,
  8638. // start by splatting that value, then replace the non-constant lanes. This
  8639. // is better than the default, which will perform a separate initialization
  8640. // for each lane.
  8641. if (!PreferDUPAndInsert && NumConstantLanes > 0 && usesOnlyOneConstantValue) {
  8642. // Firstly, try to materialize the splat constant.
  8643. SDValue Vec = DAG.getSplatBuildVector(VT, dl, ConstantValue),
  8644. Val = ConstantBuildVector(Vec, DAG);
  8645. if (!Val) {
  8646. // Otherwise, materialize the constant and splat it.
  8647. Val = DAG.getNode(AArch64ISD::DUP, dl, VT, ConstantValue);
  8648. DAG.ReplaceAllUsesWith(Vec.getNode(), &Val);
  8649. }
  8650. // Now insert the non-constant lanes.
  8651. for (unsigned i = 0; i < NumElts; ++i) {
  8652. SDValue V = Op.getOperand(i);
  8653. SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
  8654. if (!isa<ConstantSDNode>(V) && !isa<ConstantFPSDNode>(V))
  8655. // Note that type legalization likely mucked about with the VT of the
  8656. // source operand, so we may have to convert it here before inserting.
  8657. Val = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Val, V, LaneIdx);
  8658. }
  8659. return Val;
  8660. }
  8661. // This will generate a load from the constant pool.
  8662. if (isConstant) {
  8663. LLVM_DEBUG(
  8664. dbgs() << "LowerBUILD_VECTOR: all elements are constant, use default "
  8665. "expansion\n");
  8666. return SDValue();
  8667. }
  8668. // Empirical tests suggest this is rarely worth it for vectors of length <= 2.
  8669. if (NumElts >= 4) {
  8670. if (SDValue shuffle = ReconstructShuffle(Op, DAG))
  8671. return shuffle;
  8672. }
  8673. if (PreferDUPAndInsert) {
  8674. // First, build a constant vector with the common element.
  8675. SmallVector<SDValue, 8> Ops;
  8676. for (unsigned I = 0; I < NumElts; ++I)
  8677. Ops.push_back(Value);
  8678. SDValue NewVector = LowerBUILD_VECTOR(DAG.getBuildVector(VT, dl, Ops), DAG);
  8679. // Next, insert the elements that do not match the common value.
  8680. for (unsigned I = 0; I < NumElts; ++I)
  8681. if (Op.getOperand(I) != Value)
  8682. NewVector =
  8683. DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, NewVector,
  8684. Op.getOperand(I), DAG.getConstant(I, dl, MVT::i64));
  8685. return NewVector;
  8686. }
  8687. // If all else fails, just use a sequence of INSERT_VECTOR_ELT when we
  8688. // know the default expansion would otherwise fall back on something even
  8689. // worse. For a vector with one or two non-undef values, that's
  8690. // scalar_to_vector for the elements followed by a shuffle (provided the
  8691. // shuffle is valid for the target) and materialization element by element
  8692. // on the stack followed by a load for everything else.
  8693. if (!isConstant && !usesOnlyOneValue) {
  8694. LLVM_DEBUG(
  8695. dbgs() << "LowerBUILD_VECTOR: alternatives failed, creating sequence "
  8696. "of INSERT_VECTOR_ELT\n");
  8697. SDValue Vec = DAG.getUNDEF(VT);
  8698. SDValue Op0 = Op.getOperand(0);
  8699. unsigned i = 0;
  8700. // Use SCALAR_TO_VECTOR for lane zero to
  8701. // a) Avoid a RMW dependency on the full vector register, and
  8702. // b) Allow the register coalescer to fold away the copy if the
  8703. // value is already in an S or D register, and we're forced to emit an
  8704. // INSERT_SUBREG that we can't fold anywhere.
  8705. //
  8706. // We also allow types like i8 and i16 which are illegal scalar but legal
  8707. // vector element types. After type-legalization the inserted value is
  8708. // extended (i32) and it is safe to cast them to the vector type by ignoring
  8709. // the upper bits of the lowest lane (e.g. v8i8, v4i16).
  8710. if (!Op0.isUndef()) {
  8711. LLVM_DEBUG(dbgs() << "Creating node for op0, it is not undefined:\n");
  8712. Vec = DAG.getNode(ISD::SCALAR_TO_VECTOR, dl, VT, Op0);
  8713. ++i;
  8714. }
  8715. LLVM_DEBUG(if (i < NumElts) dbgs()
  8716. << "Creating nodes for the other vector elements:\n";);
  8717. for (; i < NumElts; ++i) {
  8718. SDValue V = Op.getOperand(i);
  8719. if (V.isUndef())
  8720. continue;
  8721. SDValue LaneIdx = DAG.getConstant(i, dl, MVT::i64);
  8722. Vec = DAG.getNode(ISD::INSERT_VECTOR_ELT, dl, VT, Vec, V, LaneIdx);
  8723. }
  8724. return Vec;
  8725. }
  8726. LLVM_DEBUG(
  8727. dbgs() << "LowerBUILD_VECTOR: use default expansion, failed to find "
  8728. "better alternative\n");
  8729. return SDValue();
  8730. }
  8731. SDValue AArch64TargetLowering::LowerCONCAT_VECTORS(SDValue Op,
  8732. SelectionDAG &DAG) const {
  8733. assert(Op.getValueType().isScalableVector() &&
  8734. isTypeLegal(Op.getValueType()) &&
  8735. "Expected legal scalable vector type!");
  8736. if (isTypeLegal(Op.getOperand(0).getValueType()) && Op.getNumOperands() == 2)
  8737. return Op;
  8738. return SDValue();
  8739. }
  8740. SDValue AArch64TargetLowering::LowerINSERT_VECTOR_ELT(SDValue Op,
  8741. SelectionDAG &DAG) const {
  8742. assert(Op.getOpcode() == ISD::INSERT_VECTOR_ELT && "Unknown opcode!");
  8743. // Check for non-constant or out of range lane.
  8744. EVT VT = Op.getOperand(0).getValueType();
  8745. ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(2));
  8746. if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
  8747. return SDValue();
  8748. // Insertion/extraction are legal for V128 types.
  8749. if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
  8750. VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
  8751. VT == MVT::v8f16 || VT == MVT::v8bf16)
  8752. return Op;
  8753. if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
  8754. VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
  8755. VT != MVT::v4bf16)
  8756. return SDValue();
  8757. // For V64 types, we perform insertion by expanding the value
  8758. // to a V128 type and perform the insertion on that.
  8759. SDLoc DL(Op);
  8760. SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
  8761. EVT WideTy = WideVec.getValueType();
  8762. SDValue Node = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, WideTy, WideVec,
  8763. Op.getOperand(1), Op.getOperand(2));
  8764. // Re-narrow the resultant vector.
  8765. return NarrowVector(Node, DAG);
  8766. }
  8767. SDValue
  8768. AArch64TargetLowering::LowerEXTRACT_VECTOR_ELT(SDValue Op,
  8769. SelectionDAG &DAG) const {
  8770. assert(Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT && "Unknown opcode!");
  8771. // Check for non-constant or out of range lane.
  8772. EVT VT = Op.getOperand(0).getValueType();
  8773. ConstantSDNode *CI = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  8774. if (!CI || CI->getZExtValue() >= VT.getVectorNumElements())
  8775. return SDValue();
  8776. // Insertion/extraction are legal for V128 types.
  8777. if (VT == MVT::v16i8 || VT == MVT::v8i16 || VT == MVT::v4i32 ||
  8778. VT == MVT::v2i64 || VT == MVT::v4f32 || VT == MVT::v2f64 ||
  8779. VT == MVT::v8f16 || VT == MVT::v8bf16)
  8780. return Op;
  8781. if (VT != MVT::v8i8 && VT != MVT::v4i16 && VT != MVT::v2i32 &&
  8782. VT != MVT::v1i64 && VT != MVT::v2f32 && VT != MVT::v4f16 &&
  8783. VT != MVT::v4bf16)
  8784. return SDValue();
  8785. // For V64 types, we perform extraction by expanding the value
  8786. // to a V128 type and perform the extraction on that.
  8787. SDLoc DL(Op);
  8788. SDValue WideVec = WidenVector(Op.getOperand(0), DAG);
  8789. EVT WideTy = WideVec.getValueType();
  8790. EVT ExtrTy = WideTy.getVectorElementType();
  8791. if (ExtrTy == MVT::i16 || ExtrTy == MVT::i8)
  8792. ExtrTy = MVT::i32;
  8793. // For extractions, we just return the result directly.
  8794. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ExtrTy, WideVec,
  8795. Op.getOperand(1));
  8796. }
  8797. SDValue AArch64TargetLowering::LowerEXTRACT_SUBVECTOR(SDValue Op,
  8798. SelectionDAG &DAG) const {
  8799. assert(Op.getValueType().isFixedLengthVector() &&
  8800. "Only cases that extract a fixed length vector are supported!");
  8801. EVT InVT = Op.getOperand(0).getValueType();
  8802. unsigned Idx = cast<ConstantSDNode>(Op.getOperand(1))->getZExtValue();
  8803. unsigned Size = Op.getValueSizeInBits();
  8804. if (InVT.isScalableVector()) {
  8805. // This will be matched by custom code during ISelDAGToDAG.
  8806. if (Idx == 0 && isPackedVectorType(InVT, DAG))
  8807. return Op;
  8808. return SDValue();
  8809. }
  8810. // This will get lowered to an appropriate EXTRACT_SUBREG in ISel.
  8811. if (Idx == 0 && InVT.getSizeInBits() <= 128)
  8812. return Op;
  8813. // If this is extracting the upper 64-bits of a 128-bit vector, we match
  8814. // that directly.
  8815. if (Size == 64 && Idx * InVT.getScalarSizeInBits() == 64 &&
  8816. InVT.getSizeInBits() == 128)
  8817. return Op;
  8818. return SDValue();
  8819. }
  8820. SDValue AArch64TargetLowering::LowerINSERT_SUBVECTOR(SDValue Op,
  8821. SelectionDAG &DAG) const {
  8822. assert(Op.getValueType().isScalableVector() &&
  8823. "Only expect to lower inserts into scalable vectors!");
  8824. EVT InVT = Op.getOperand(1).getValueType();
  8825. unsigned Idx = cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue();
  8826. if (InVT.isScalableVector()) {
  8827. SDLoc DL(Op);
  8828. EVT VT = Op.getValueType();
  8829. if (!isTypeLegal(VT) || !VT.isInteger())
  8830. return SDValue();
  8831. SDValue Vec0 = Op.getOperand(0);
  8832. SDValue Vec1 = Op.getOperand(1);
  8833. // Ensure the subvector is half the size of the main vector.
  8834. if (VT.getVectorElementCount() != (InVT.getVectorElementCount() * 2))
  8835. return SDValue();
  8836. // Extend elements of smaller vector...
  8837. EVT WideVT = InVT.widenIntegerVectorElementType(*(DAG.getContext()));
  8838. SDValue ExtVec = DAG.getNode(ISD::ANY_EXTEND, DL, WideVT, Vec1);
  8839. if (Idx == 0) {
  8840. SDValue HiVec0 = DAG.getNode(AArch64ISD::UUNPKHI, DL, WideVT, Vec0);
  8841. return DAG.getNode(AArch64ISD::UZP1, DL, VT, ExtVec, HiVec0);
  8842. } else if (Idx == InVT.getVectorMinNumElements()) {
  8843. SDValue LoVec0 = DAG.getNode(AArch64ISD::UUNPKLO, DL, WideVT, Vec0);
  8844. return DAG.getNode(AArch64ISD::UZP1, DL, VT, LoVec0, ExtVec);
  8845. }
  8846. return SDValue();
  8847. }
  8848. // This will be matched by custom code during ISelDAGToDAG.
  8849. if (Idx == 0 && isPackedVectorType(InVT, DAG) && Op.getOperand(0).isUndef())
  8850. return Op;
  8851. return SDValue();
  8852. }
  8853. SDValue AArch64TargetLowering::LowerDIV(SDValue Op, SelectionDAG &DAG) const {
  8854. EVT VT = Op.getValueType();
  8855. if (useSVEForFixedLengthVectorVT(VT, /*OverrideNEON=*/true))
  8856. return LowerFixedLengthVectorIntDivideToSVE(Op, DAG);
  8857. assert(VT.isScalableVector() && "Expected a scalable vector.");
  8858. bool Signed = Op.getOpcode() == ISD::SDIV;
  8859. unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
  8860. if (VT == MVT::nxv4i32 || VT == MVT::nxv2i64)
  8861. return LowerToPredicatedOp(Op, DAG, PredOpcode);
  8862. // SVE doesn't have i8 and i16 DIV operations; widen them to 32-bit
  8863. // operations, and truncate the result.
  8864. EVT WidenedVT;
  8865. if (VT == MVT::nxv16i8)
  8866. WidenedVT = MVT::nxv8i16;
  8867. else if (VT == MVT::nxv8i16)
  8868. WidenedVT = MVT::nxv4i32;
  8869. else
  8870. llvm_unreachable("Unexpected Custom DIV operation");
  8871. SDLoc dl(Op);
  8872. unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
  8873. unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
  8874. SDValue Op0Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(0));
  8875. SDValue Op1Lo = DAG.getNode(UnpkLo, dl, WidenedVT, Op.getOperand(1));
  8876. SDValue Op0Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(0));
  8877. SDValue Op1Hi = DAG.getNode(UnpkHi, dl, WidenedVT, Op.getOperand(1));
  8878. SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Lo, Op1Lo);
  8879. SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, WidenedVT, Op0Hi, Op1Hi);
  8880. return DAG.getNode(AArch64ISD::UZP1, dl, VT, ResultLo, ResultHi);
  8881. }
  8882. bool AArch64TargetLowering::isShuffleMaskLegal(ArrayRef<int> M, EVT VT) const {
  8883. // Currently no fixed length shuffles that require SVE are legal.
  8884. if (useSVEForFixedLengthVectorVT(VT))
  8885. return false;
  8886. if (VT.getVectorNumElements() == 4 &&
  8887. (VT.is128BitVector() || VT.is64BitVector())) {
  8888. unsigned PFIndexes[4];
  8889. for (unsigned i = 0; i != 4; ++i) {
  8890. if (M[i] < 0)
  8891. PFIndexes[i] = 8;
  8892. else
  8893. PFIndexes[i] = M[i];
  8894. }
  8895. // Compute the index in the perfect shuffle table.
  8896. unsigned PFTableIndex = PFIndexes[0] * 9 * 9 * 9 + PFIndexes[1] * 9 * 9 +
  8897. PFIndexes[2] * 9 + PFIndexes[3];
  8898. unsigned PFEntry = PerfectShuffleTable[PFTableIndex];
  8899. unsigned Cost = (PFEntry >> 30);
  8900. if (Cost <= 4)
  8901. return true;
  8902. }
  8903. bool DummyBool;
  8904. int DummyInt;
  8905. unsigned DummyUnsigned;
  8906. return (ShuffleVectorSDNode::isSplatMask(&M[0], VT) || isREVMask(M, VT, 64) ||
  8907. isREVMask(M, VT, 32) || isREVMask(M, VT, 16) ||
  8908. isEXTMask(M, VT, DummyBool, DummyUnsigned) ||
  8909. // isTBLMask(M, VT) || // FIXME: Port TBL support from ARM.
  8910. isTRNMask(M, VT, DummyUnsigned) || isUZPMask(M, VT, DummyUnsigned) ||
  8911. isZIPMask(M, VT, DummyUnsigned) ||
  8912. isTRN_v_undef_Mask(M, VT, DummyUnsigned) ||
  8913. isUZP_v_undef_Mask(M, VT, DummyUnsigned) ||
  8914. isZIP_v_undef_Mask(M, VT, DummyUnsigned) ||
  8915. isINSMask(M, VT.getVectorNumElements(), DummyBool, DummyInt) ||
  8916. isConcatMask(M, VT, VT.getSizeInBits() == 128));
  8917. }
  8918. /// getVShiftImm - Check if this is a valid build_vector for the immediate
  8919. /// operand of a vector shift operation, where all the elements of the
  8920. /// build_vector must have the same constant integer value.
  8921. static bool getVShiftImm(SDValue Op, unsigned ElementBits, int64_t &Cnt) {
  8922. // Ignore bit_converts.
  8923. while (Op.getOpcode() == ISD::BITCAST)
  8924. Op = Op.getOperand(0);
  8925. BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(Op.getNode());
  8926. APInt SplatBits, SplatUndef;
  8927. unsigned SplatBitSize;
  8928. bool HasAnyUndefs;
  8929. if (!BVN || !BVN->isConstantSplat(SplatBits, SplatUndef, SplatBitSize,
  8930. HasAnyUndefs, ElementBits) ||
  8931. SplatBitSize > ElementBits)
  8932. return false;
  8933. Cnt = SplatBits.getSExtValue();
  8934. return true;
  8935. }
  8936. /// isVShiftLImm - Check if this is a valid build_vector for the immediate
  8937. /// operand of a vector shift left operation. That value must be in the range:
  8938. /// 0 <= Value < ElementBits for a left shift; or
  8939. /// 0 <= Value <= ElementBits for a long left shift.
  8940. static bool isVShiftLImm(SDValue Op, EVT VT, bool isLong, int64_t &Cnt) {
  8941. assert(VT.isVector() && "vector shift count is not a vector type");
  8942. int64_t ElementBits = VT.getScalarSizeInBits();
  8943. if (!getVShiftImm(Op, ElementBits, Cnt))
  8944. return false;
  8945. return (Cnt >= 0 && (isLong ? Cnt - 1 : Cnt) < ElementBits);
  8946. }
  8947. /// isVShiftRImm - Check if this is a valid build_vector for the immediate
  8948. /// operand of a vector shift right operation. The value must be in the range:
  8949. /// 1 <= Value <= ElementBits for a right shift; or
  8950. static bool isVShiftRImm(SDValue Op, EVT VT, bool isNarrow, int64_t &Cnt) {
  8951. assert(VT.isVector() && "vector shift count is not a vector type");
  8952. int64_t ElementBits = VT.getScalarSizeInBits();
  8953. if (!getVShiftImm(Op, ElementBits, Cnt))
  8954. return false;
  8955. return (Cnt >= 1 && Cnt <= (isNarrow ? ElementBits / 2 : ElementBits));
  8956. }
  8957. SDValue AArch64TargetLowering::LowerTRUNCATE(SDValue Op,
  8958. SelectionDAG &DAG) const {
  8959. EVT VT = Op.getValueType();
  8960. if (VT.getScalarType() == MVT::i1) {
  8961. // Lower i1 truncate to `(x & 1) != 0`.
  8962. SDLoc dl(Op);
  8963. EVT OpVT = Op.getOperand(0).getValueType();
  8964. SDValue Zero = DAG.getConstant(0, dl, OpVT);
  8965. SDValue One = DAG.getConstant(1, dl, OpVT);
  8966. SDValue And = DAG.getNode(ISD::AND, dl, OpVT, Op.getOperand(0), One);
  8967. return DAG.getSetCC(dl, VT, And, Zero, ISD::SETNE);
  8968. }
  8969. if (!VT.isVector() || VT.isScalableVector())
  8970. return SDValue();
  8971. if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
  8972. return LowerFixedLengthVectorTruncateToSVE(Op, DAG);
  8973. return SDValue();
  8974. }
  8975. SDValue AArch64TargetLowering::LowerVectorSRA_SRL_SHL(SDValue Op,
  8976. SelectionDAG &DAG) const {
  8977. EVT VT = Op.getValueType();
  8978. SDLoc DL(Op);
  8979. int64_t Cnt;
  8980. if (!Op.getOperand(1).getValueType().isVector())
  8981. return Op;
  8982. unsigned EltSize = VT.getScalarSizeInBits();
  8983. switch (Op.getOpcode()) {
  8984. default:
  8985. llvm_unreachable("unexpected shift opcode");
  8986. case ISD::SHL:
  8987. if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT))
  8988. return LowerToPredicatedOp(Op, DAG, AArch64ISD::SHL_PRED);
  8989. if (isVShiftLImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize)
  8990. return DAG.getNode(AArch64ISD::VSHL, DL, VT, Op.getOperand(0),
  8991. DAG.getConstant(Cnt, DL, MVT::i32));
  8992. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
  8993. DAG.getConstant(Intrinsic::aarch64_neon_ushl, DL,
  8994. MVT::i32),
  8995. Op.getOperand(0), Op.getOperand(1));
  8996. case ISD::SRA:
  8997. case ISD::SRL:
  8998. if (VT.isScalableVector() || useSVEForFixedLengthVectorVT(VT)) {
  8999. unsigned Opc = Op.getOpcode() == ISD::SRA ? AArch64ISD::SRA_PRED
  9000. : AArch64ISD::SRL_PRED;
  9001. return LowerToPredicatedOp(Op, DAG, Opc);
  9002. }
  9003. // Right shift immediate
  9004. if (isVShiftRImm(Op.getOperand(1), VT, false, Cnt) && Cnt < EltSize) {
  9005. unsigned Opc =
  9006. (Op.getOpcode() == ISD::SRA) ? AArch64ISD::VASHR : AArch64ISD::VLSHR;
  9007. return DAG.getNode(Opc, DL, VT, Op.getOperand(0),
  9008. DAG.getConstant(Cnt, DL, MVT::i32));
  9009. }
  9010. // Right shift register. Note, there is not a shift right register
  9011. // instruction, but the shift left register instruction takes a signed
  9012. // value, where negative numbers specify a right shift.
  9013. unsigned Opc = (Op.getOpcode() == ISD::SRA) ? Intrinsic::aarch64_neon_sshl
  9014. : Intrinsic::aarch64_neon_ushl;
  9015. // negate the shift amount
  9016. SDValue NegShift = DAG.getNode(AArch64ISD::NEG, DL, VT, Op.getOperand(1));
  9017. SDValue NegShiftLeft =
  9018. DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VT,
  9019. DAG.getConstant(Opc, DL, MVT::i32), Op.getOperand(0),
  9020. NegShift);
  9021. return NegShiftLeft;
  9022. }
  9023. return SDValue();
  9024. }
  9025. static SDValue EmitVectorComparison(SDValue LHS, SDValue RHS,
  9026. AArch64CC::CondCode CC, bool NoNans, EVT VT,
  9027. const SDLoc &dl, SelectionDAG &DAG) {
  9028. EVT SrcVT = LHS.getValueType();
  9029. assert(VT.getSizeInBits() == SrcVT.getSizeInBits() &&
  9030. "function only supposed to emit natural comparisons");
  9031. BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(RHS.getNode());
  9032. APInt CnstBits(VT.getSizeInBits(), 0);
  9033. APInt UndefBits(VT.getSizeInBits(), 0);
  9034. bool IsCnst = BVN && resolveBuildVector(BVN, CnstBits, UndefBits);
  9035. bool IsZero = IsCnst && (CnstBits == 0);
  9036. if (SrcVT.getVectorElementType().isFloatingPoint()) {
  9037. switch (CC) {
  9038. default:
  9039. return SDValue();
  9040. case AArch64CC::NE: {
  9041. SDValue Fcmeq;
  9042. if (IsZero)
  9043. Fcmeq = DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
  9044. else
  9045. Fcmeq = DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
  9046. return DAG.getNOT(dl, Fcmeq, VT);
  9047. }
  9048. case AArch64CC::EQ:
  9049. if (IsZero)
  9050. return DAG.getNode(AArch64ISD::FCMEQz, dl, VT, LHS);
  9051. return DAG.getNode(AArch64ISD::FCMEQ, dl, VT, LHS, RHS);
  9052. case AArch64CC::GE:
  9053. if (IsZero)
  9054. return DAG.getNode(AArch64ISD::FCMGEz, dl, VT, LHS);
  9055. return DAG.getNode(AArch64ISD::FCMGE, dl, VT, LHS, RHS);
  9056. case AArch64CC::GT:
  9057. if (IsZero)
  9058. return DAG.getNode(AArch64ISD::FCMGTz, dl, VT, LHS);
  9059. return DAG.getNode(AArch64ISD::FCMGT, dl, VT, LHS, RHS);
  9060. case AArch64CC::LS:
  9061. if (IsZero)
  9062. return DAG.getNode(AArch64ISD::FCMLEz, dl, VT, LHS);
  9063. return DAG.getNode(AArch64ISD::FCMGE, dl, VT, RHS, LHS);
  9064. case AArch64CC::LT:
  9065. if (!NoNans)
  9066. return SDValue();
  9067. // If we ignore NaNs then we can use to the MI implementation.
  9068. LLVM_FALLTHROUGH;
  9069. case AArch64CC::MI:
  9070. if (IsZero)
  9071. return DAG.getNode(AArch64ISD::FCMLTz, dl, VT, LHS);
  9072. return DAG.getNode(AArch64ISD::FCMGT, dl, VT, RHS, LHS);
  9073. }
  9074. }
  9075. switch (CC) {
  9076. default:
  9077. return SDValue();
  9078. case AArch64CC::NE: {
  9079. SDValue Cmeq;
  9080. if (IsZero)
  9081. Cmeq = DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
  9082. else
  9083. Cmeq = DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
  9084. return DAG.getNOT(dl, Cmeq, VT);
  9085. }
  9086. case AArch64CC::EQ:
  9087. if (IsZero)
  9088. return DAG.getNode(AArch64ISD::CMEQz, dl, VT, LHS);
  9089. return DAG.getNode(AArch64ISD::CMEQ, dl, VT, LHS, RHS);
  9090. case AArch64CC::GE:
  9091. if (IsZero)
  9092. return DAG.getNode(AArch64ISD::CMGEz, dl, VT, LHS);
  9093. return DAG.getNode(AArch64ISD::CMGE, dl, VT, LHS, RHS);
  9094. case AArch64CC::GT:
  9095. if (IsZero)
  9096. return DAG.getNode(AArch64ISD::CMGTz, dl, VT, LHS);
  9097. return DAG.getNode(AArch64ISD::CMGT, dl, VT, LHS, RHS);
  9098. case AArch64CC::LE:
  9099. if (IsZero)
  9100. return DAG.getNode(AArch64ISD::CMLEz, dl, VT, LHS);
  9101. return DAG.getNode(AArch64ISD::CMGE, dl, VT, RHS, LHS);
  9102. case AArch64CC::LS:
  9103. return DAG.getNode(AArch64ISD::CMHS, dl, VT, RHS, LHS);
  9104. case AArch64CC::LO:
  9105. return DAG.getNode(AArch64ISD::CMHI, dl, VT, RHS, LHS);
  9106. case AArch64CC::LT:
  9107. if (IsZero)
  9108. return DAG.getNode(AArch64ISD::CMLTz, dl, VT, LHS);
  9109. return DAG.getNode(AArch64ISD::CMGT, dl, VT, RHS, LHS);
  9110. case AArch64CC::HI:
  9111. return DAG.getNode(AArch64ISD::CMHI, dl, VT, LHS, RHS);
  9112. case AArch64CC::HS:
  9113. return DAG.getNode(AArch64ISD::CMHS, dl, VT, LHS, RHS);
  9114. }
  9115. }
  9116. SDValue AArch64TargetLowering::LowerVSETCC(SDValue Op,
  9117. SelectionDAG &DAG) const {
  9118. if (Op.getValueType().isScalableVector()) {
  9119. if (Op.getOperand(0).getValueType().isFloatingPoint())
  9120. return Op;
  9121. return LowerToPredicatedOp(Op, DAG, AArch64ISD::SETCC_MERGE_ZERO);
  9122. }
  9123. if (useSVEForFixedLengthVectorVT(Op.getOperand(0).getValueType()))
  9124. return LowerFixedLengthVectorSetccToSVE(Op, DAG);
  9125. ISD::CondCode CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
  9126. SDValue LHS = Op.getOperand(0);
  9127. SDValue RHS = Op.getOperand(1);
  9128. EVT CmpVT = LHS.getValueType().changeVectorElementTypeToInteger();
  9129. SDLoc dl(Op);
  9130. if (LHS.getValueType().getVectorElementType().isInteger()) {
  9131. assert(LHS.getValueType() == RHS.getValueType());
  9132. AArch64CC::CondCode AArch64CC = changeIntCCToAArch64CC(CC);
  9133. SDValue Cmp =
  9134. EmitVectorComparison(LHS, RHS, AArch64CC, false, CmpVT, dl, DAG);
  9135. return DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
  9136. }
  9137. const bool FullFP16 =
  9138. static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
  9139. // Make v4f16 (only) fcmp operations utilise vector instructions
  9140. // v8f16 support will be a litle more complicated
  9141. if (!FullFP16 && LHS.getValueType().getVectorElementType() == MVT::f16) {
  9142. if (LHS.getValueType().getVectorNumElements() == 4) {
  9143. LHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, LHS);
  9144. RHS = DAG.getNode(ISD::FP_EXTEND, dl, MVT::v4f32, RHS);
  9145. SDValue NewSetcc = DAG.getSetCC(dl, MVT::v4i16, LHS, RHS, CC);
  9146. DAG.ReplaceAllUsesWith(Op, NewSetcc);
  9147. CmpVT = MVT::v4i32;
  9148. } else
  9149. return SDValue();
  9150. }
  9151. assert((!FullFP16 && LHS.getValueType().getVectorElementType() != MVT::f16) ||
  9152. LHS.getValueType().getVectorElementType() != MVT::f128);
  9153. // Unfortunately, the mapping of LLVM FP CC's onto AArch64 CC's isn't totally
  9154. // clean. Some of them require two branches to implement.
  9155. AArch64CC::CondCode CC1, CC2;
  9156. bool ShouldInvert;
  9157. changeVectorFPCCToAArch64CC(CC, CC1, CC2, ShouldInvert);
  9158. bool NoNaNs = getTargetMachine().Options.NoNaNsFPMath;
  9159. SDValue Cmp =
  9160. EmitVectorComparison(LHS, RHS, CC1, NoNaNs, CmpVT, dl, DAG);
  9161. if (!Cmp.getNode())
  9162. return SDValue();
  9163. if (CC2 != AArch64CC::AL) {
  9164. SDValue Cmp2 =
  9165. EmitVectorComparison(LHS, RHS, CC2, NoNaNs, CmpVT, dl, DAG);
  9166. if (!Cmp2.getNode())
  9167. return SDValue();
  9168. Cmp = DAG.getNode(ISD::OR, dl, CmpVT, Cmp, Cmp2);
  9169. }
  9170. Cmp = DAG.getSExtOrTrunc(Cmp, dl, Op.getValueType());
  9171. if (ShouldInvert)
  9172. Cmp = DAG.getNOT(dl, Cmp, Cmp.getValueType());
  9173. return Cmp;
  9174. }
  9175. static SDValue getReductionSDNode(unsigned Op, SDLoc DL, SDValue ScalarOp,
  9176. SelectionDAG &DAG) {
  9177. SDValue VecOp = ScalarOp.getOperand(0);
  9178. auto Rdx = DAG.getNode(Op, DL, VecOp.getSimpleValueType(), VecOp);
  9179. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarOp.getValueType(), Rdx,
  9180. DAG.getConstant(0, DL, MVT::i64));
  9181. }
  9182. SDValue AArch64TargetLowering::LowerVECREDUCE(SDValue Op,
  9183. SelectionDAG &DAG) const {
  9184. SDValue Src = Op.getOperand(0);
  9185. // Try to lower fixed length reductions to SVE.
  9186. EVT SrcVT = Src.getValueType();
  9187. bool OverrideNEON = Op.getOpcode() == ISD::VECREDUCE_AND ||
  9188. Op.getOpcode() == ISD::VECREDUCE_OR ||
  9189. Op.getOpcode() == ISD::VECREDUCE_XOR ||
  9190. Op.getOpcode() == ISD::VECREDUCE_FADD ||
  9191. (Op.getOpcode() != ISD::VECREDUCE_ADD &&
  9192. SrcVT.getVectorElementType() == MVT::i64);
  9193. if (SrcVT.isScalableVector() ||
  9194. useSVEForFixedLengthVectorVT(SrcVT, OverrideNEON)) {
  9195. if (SrcVT.getVectorElementType() == MVT::i1)
  9196. return LowerPredReductionToSVE(Op, DAG);
  9197. switch (Op.getOpcode()) {
  9198. case ISD::VECREDUCE_ADD:
  9199. return LowerReductionToSVE(AArch64ISD::UADDV_PRED, Op, DAG);
  9200. case ISD::VECREDUCE_AND:
  9201. return LowerReductionToSVE(AArch64ISD::ANDV_PRED, Op, DAG);
  9202. case ISD::VECREDUCE_OR:
  9203. return LowerReductionToSVE(AArch64ISD::ORV_PRED, Op, DAG);
  9204. case ISD::VECREDUCE_SMAX:
  9205. return LowerReductionToSVE(AArch64ISD::SMAXV_PRED, Op, DAG);
  9206. case ISD::VECREDUCE_SMIN:
  9207. return LowerReductionToSVE(AArch64ISD::SMINV_PRED, Op, DAG);
  9208. case ISD::VECREDUCE_UMAX:
  9209. return LowerReductionToSVE(AArch64ISD::UMAXV_PRED, Op, DAG);
  9210. case ISD::VECREDUCE_UMIN:
  9211. return LowerReductionToSVE(AArch64ISD::UMINV_PRED, Op, DAG);
  9212. case ISD::VECREDUCE_XOR:
  9213. return LowerReductionToSVE(AArch64ISD::EORV_PRED, Op, DAG);
  9214. case ISD::VECREDUCE_FADD:
  9215. return LowerReductionToSVE(AArch64ISD::FADDV_PRED, Op, DAG);
  9216. case ISD::VECREDUCE_FMAX:
  9217. return LowerReductionToSVE(AArch64ISD::FMAXNMV_PRED, Op, DAG);
  9218. case ISD::VECREDUCE_FMIN:
  9219. return LowerReductionToSVE(AArch64ISD::FMINNMV_PRED, Op, DAG);
  9220. default:
  9221. llvm_unreachable("Unhandled fixed length reduction");
  9222. }
  9223. }
  9224. // Lower NEON reductions.
  9225. SDLoc dl(Op);
  9226. switch (Op.getOpcode()) {
  9227. case ISD::VECREDUCE_ADD:
  9228. return getReductionSDNode(AArch64ISD::UADDV, dl, Op, DAG);
  9229. case ISD::VECREDUCE_SMAX:
  9230. return getReductionSDNode(AArch64ISD::SMAXV, dl, Op, DAG);
  9231. case ISD::VECREDUCE_SMIN:
  9232. return getReductionSDNode(AArch64ISD::SMINV, dl, Op, DAG);
  9233. case ISD::VECREDUCE_UMAX:
  9234. return getReductionSDNode(AArch64ISD::UMAXV, dl, Op, DAG);
  9235. case ISD::VECREDUCE_UMIN:
  9236. return getReductionSDNode(AArch64ISD::UMINV, dl, Op, DAG);
  9237. case ISD::VECREDUCE_FMAX: {
  9238. return DAG.getNode(
  9239. ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
  9240. DAG.getConstant(Intrinsic::aarch64_neon_fmaxnmv, dl, MVT::i32),
  9241. Src);
  9242. }
  9243. case ISD::VECREDUCE_FMIN: {
  9244. return DAG.getNode(
  9245. ISD::INTRINSIC_WO_CHAIN, dl, Op.getValueType(),
  9246. DAG.getConstant(Intrinsic::aarch64_neon_fminnmv, dl, MVT::i32),
  9247. Src);
  9248. }
  9249. default:
  9250. llvm_unreachable("Unhandled reduction");
  9251. }
  9252. }
  9253. SDValue AArch64TargetLowering::LowerATOMIC_LOAD_SUB(SDValue Op,
  9254. SelectionDAG &DAG) const {
  9255. auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
  9256. if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
  9257. return SDValue();
  9258. // LSE has an atomic load-add instruction, but not a load-sub.
  9259. SDLoc dl(Op);
  9260. MVT VT = Op.getSimpleValueType();
  9261. SDValue RHS = Op.getOperand(2);
  9262. AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
  9263. RHS = DAG.getNode(ISD::SUB, dl, VT, DAG.getConstant(0, dl, VT), RHS);
  9264. return DAG.getAtomic(ISD::ATOMIC_LOAD_ADD, dl, AN->getMemoryVT(),
  9265. Op.getOperand(0), Op.getOperand(1), RHS,
  9266. AN->getMemOperand());
  9267. }
  9268. SDValue AArch64TargetLowering::LowerATOMIC_LOAD_AND(SDValue Op,
  9269. SelectionDAG &DAG) const {
  9270. auto &Subtarget = static_cast<const AArch64Subtarget &>(DAG.getSubtarget());
  9271. if (!Subtarget.hasLSE() && !Subtarget.outlineAtomics())
  9272. return SDValue();
  9273. // LSE has an atomic load-clear instruction, but not a load-and.
  9274. SDLoc dl(Op);
  9275. MVT VT = Op.getSimpleValueType();
  9276. SDValue RHS = Op.getOperand(2);
  9277. AtomicSDNode *AN = cast<AtomicSDNode>(Op.getNode());
  9278. RHS = DAG.getNode(ISD::XOR, dl, VT, DAG.getConstant(-1ULL, dl, VT), RHS);
  9279. return DAG.getAtomic(ISD::ATOMIC_LOAD_CLR, dl, AN->getMemoryVT(),
  9280. Op.getOperand(0), Op.getOperand(1), RHS,
  9281. AN->getMemOperand());
  9282. }
  9283. SDValue AArch64TargetLowering::LowerWindowsDYNAMIC_STACKALLOC(
  9284. SDValue Op, SDValue Chain, SDValue &Size, SelectionDAG &DAG) const {
  9285. SDLoc dl(Op);
  9286. EVT PtrVT = getPointerTy(DAG.getDataLayout());
  9287. SDValue Callee = DAG.getTargetExternalSymbol("__chkstk", PtrVT, 0);
  9288. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
  9289. const uint32_t *Mask = TRI->getWindowsStackProbePreservedMask();
  9290. if (Subtarget->hasCustomCallingConv())
  9291. TRI->UpdateCustomCallPreservedMask(DAG.getMachineFunction(), &Mask);
  9292. Size = DAG.getNode(ISD::SRL, dl, MVT::i64, Size,
  9293. DAG.getConstant(4, dl, MVT::i64));
  9294. Chain = DAG.getCopyToReg(Chain, dl, AArch64::X15, Size, SDValue());
  9295. Chain =
  9296. DAG.getNode(AArch64ISD::CALL, dl, DAG.getVTList(MVT::Other, MVT::Glue),
  9297. Chain, Callee, DAG.getRegister(AArch64::X15, MVT::i64),
  9298. DAG.getRegisterMask(Mask), Chain.getValue(1));
  9299. // To match the actual intent better, we should read the output from X15 here
  9300. // again (instead of potentially spilling it to the stack), but rereading Size
  9301. // from X15 here doesn't work at -O0, since it thinks that X15 is undefined
  9302. // here.
  9303. Size = DAG.getNode(ISD::SHL, dl, MVT::i64, Size,
  9304. DAG.getConstant(4, dl, MVT::i64));
  9305. return Chain;
  9306. }
  9307. SDValue
  9308. AArch64TargetLowering::LowerDYNAMIC_STACKALLOC(SDValue Op,
  9309. SelectionDAG &DAG) const {
  9310. assert(Subtarget->isTargetWindows() &&
  9311. "Only Windows alloca probing supported");
  9312. SDLoc dl(Op);
  9313. // Get the inputs.
  9314. SDNode *Node = Op.getNode();
  9315. SDValue Chain = Op.getOperand(0);
  9316. SDValue Size = Op.getOperand(1);
  9317. MaybeAlign Align =
  9318. cast<ConstantSDNode>(Op.getOperand(2))->getMaybeAlignValue();
  9319. EVT VT = Node->getValueType(0);
  9320. if (DAG.getMachineFunction().getFunction().hasFnAttribute(
  9321. "no-stack-arg-probe")) {
  9322. SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
  9323. Chain = SP.getValue(1);
  9324. SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
  9325. if (Align)
  9326. SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
  9327. DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
  9328. Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
  9329. SDValue Ops[2] = {SP, Chain};
  9330. return DAG.getMergeValues(Ops, dl);
  9331. }
  9332. Chain = DAG.getCALLSEQ_START(Chain, 0, 0, dl);
  9333. Chain = LowerWindowsDYNAMIC_STACKALLOC(Op, Chain, Size, DAG);
  9334. SDValue SP = DAG.getCopyFromReg(Chain, dl, AArch64::SP, MVT::i64);
  9335. Chain = SP.getValue(1);
  9336. SP = DAG.getNode(ISD::SUB, dl, MVT::i64, SP, Size);
  9337. if (Align)
  9338. SP = DAG.getNode(ISD::AND, dl, VT, SP.getValue(0),
  9339. DAG.getConstant(-(uint64_t)Align->value(), dl, VT));
  9340. Chain = DAG.getCopyToReg(Chain, dl, AArch64::SP, SP);
  9341. Chain = DAG.getCALLSEQ_END(Chain, DAG.getIntPtrConstant(0, dl, true),
  9342. DAG.getIntPtrConstant(0, dl, true), SDValue(), dl);
  9343. SDValue Ops[2] = {SP, Chain};
  9344. return DAG.getMergeValues(Ops, dl);
  9345. }
  9346. SDValue AArch64TargetLowering::LowerVSCALE(SDValue Op,
  9347. SelectionDAG &DAG) const {
  9348. EVT VT = Op.getValueType();
  9349. assert(VT != MVT::i64 && "Expected illegal VSCALE node");
  9350. SDLoc DL(Op);
  9351. APInt MulImm = cast<ConstantSDNode>(Op.getOperand(0))->getAPIntValue();
  9352. return DAG.getZExtOrTrunc(DAG.getVScale(DL, MVT::i64, MulImm.sextOrSelf(64)),
  9353. DL, VT);
  9354. }
  9355. /// Set the IntrinsicInfo for the `aarch64_sve_st<N>` intrinsics.
  9356. template <unsigned NumVecs>
  9357. static bool
  9358. setInfoSVEStN(const AArch64TargetLowering &TLI, const DataLayout &DL,
  9359. AArch64TargetLowering::IntrinsicInfo &Info, const CallInst &CI) {
  9360. Info.opc = ISD::INTRINSIC_VOID;
  9361. // Retrieve EC from first vector argument.
  9362. const EVT VT = TLI.getMemValueType(DL, CI.getArgOperand(0)->getType());
  9363. ElementCount EC = VT.getVectorElementCount();
  9364. #ifndef NDEBUG
  9365. // Check the assumption that all input vectors are the same type.
  9366. for (unsigned I = 0; I < NumVecs; ++I)
  9367. assert(VT == TLI.getMemValueType(DL, CI.getArgOperand(I)->getType()) &&
  9368. "Invalid type.");
  9369. #endif
  9370. // memVT is `NumVecs * VT`.
  9371. Info.memVT = EVT::getVectorVT(CI.getType()->getContext(), VT.getScalarType(),
  9372. EC * NumVecs);
  9373. Info.ptrVal = CI.getArgOperand(CI.getNumArgOperands() - 1);
  9374. Info.offset = 0;
  9375. Info.align.reset();
  9376. Info.flags = MachineMemOperand::MOStore;
  9377. return true;
  9378. }
  9379. /// getTgtMemIntrinsic - Represent NEON load and store intrinsics as
  9380. /// MemIntrinsicNodes. The associated MachineMemOperands record the alignment
  9381. /// specified in the intrinsic calls.
  9382. bool AArch64TargetLowering::getTgtMemIntrinsic(IntrinsicInfo &Info,
  9383. const CallInst &I,
  9384. MachineFunction &MF,
  9385. unsigned Intrinsic) const {
  9386. auto &DL = I.getModule()->getDataLayout();
  9387. switch (Intrinsic) {
  9388. case Intrinsic::aarch64_sve_st2:
  9389. return setInfoSVEStN<2>(*this, DL, Info, I);
  9390. case Intrinsic::aarch64_sve_st3:
  9391. return setInfoSVEStN<3>(*this, DL, Info, I);
  9392. case Intrinsic::aarch64_sve_st4:
  9393. return setInfoSVEStN<4>(*this, DL, Info, I);
  9394. case Intrinsic::aarch64_neon_ld2:
  9395. case Intrinsic::aarch64_neon_ld3:
  9396. case Intrinsic::aarch64_neon_ld4:
  9397. case Intrinsic::aarch64_neon_ld1x2:
  9398. case Intrinsic::aarch64_neon_ld1x3:
  9399. case Intrinsic::aarch64_neon_ld1x4:
  9400. case Intrinsic::aarch64_neon_ld2lane:
  9401. case Intrinsic::aarch64_neon_ld3lane:
  9402. case Intrinsic::aarch64_neon_ld4lane:
  9403. case Intrinsic::aarch64_neon_ld2r:
  9404. case Intrinsic::aarch64_neon_ld3r:
  9405. case Intrinsic::aarch64_neon_ld4r: {
  9406. Info.opc = ISD::INTRINSIC_W_CHAIN;
  9407. // Conservatively set memVT to the entire set of vectors loaded.
  9408. uint64_t NumElts = DL.getTypeSizeInBits(I.getType()) / 64;
  9409. Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
  9410. Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
  9411. Info.offset = 0;
  9412. Info.align.reset();
  9413. // volatile loads with NEON intrinsics not supported
  9414. Info.flags = MachineMemOperand::MOLoad;
  9415. return true;
  9416. }
  9417. case Intrinsic::aarch64_neon_st2:
  9418. case Intrinsic::aarch64_neon_st3:
  9419. case Intrinsic::aarch64_neon_st4:
  9420. case Intrinsic::aarch64_neon_st1x2:
  9421. case Intrinsic::aarch64_neon_st1x3:
  9422. case Intrinsic::aarch64_neon_st1x4:
  9423. case Intrinsic::aarch64_neon_st2lane:
  9424. case Intrinsic::aarch64_neon_st3lane:
  9425. case Intrinsic::aarch64_neon_st4lane: {
  9426. Info.opc = ISD::INTRINSIC_VOID;
  9427. // Conservatively set memVT to the entire set of vectors stored.
  9428. unsigned NumElts = 0;
  9429. for (unsigned ArgI = 0, ArgE = I.getNumArgOperands(); ArgI < ArgE; ++ArgI) {
  9430. Type *ArgTy = I.getArgOperand(ArgI)->getType();
  9431. if (!ArgTy->isVectorTy())
  9432. break;
  9433. NumElts += DL.getTypeSizeInBits(ArgTy) / 64;
  9434. }
  9435. Info.memVT = EVT::getVectorVT(I.getType()->getContext(), MVT::i64, NumElts);
  9436. Info.ptrVal = I.getArgOperand(I.getNumArgOperands() - 1);
  9437. Info.offset = 0;
  9438. Info.align.reset();
  9439. // volatile stores with NEON intrinsics not supported
  9440. Info.flags = MachineMemOperand::MOStore;
  9441. return true;
  9442. }
  9443. case Intrinsic::aarch64_ldaxr:
  9444. case Intrinsic::aarch64_ldxr: {
  9445. PointerType *PtrTy = cast<PointerType>(I.getArgOperand(0)->getType());
  9446. Info.opc = ISD::INTRINSIC_W_CHAIN;
  9447. Info.memVT = MVT::getVT(PtrTy->getElementType());
  9448. Info.ptrVal = I.getArgOperand(0);
  9449. Info.offset = 0;
  9450. Info.align = DL.getABITypeAlign(PtrTy->getElementType());
  9451. Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
  9452. return true;
  9453. }
  9454. case Intrinsic::aarch64_stlxr:
  9455. case Intrinsic::aarch64_stxr: {
  9456. PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
  9457. Info.opc = ISD::INTRINSIC_W_CHAIN;
  9458. Info.memVT = MVT::getVT(PtrTy->getElementType());
  9459. Info.ptrVal = I.getArgOperand(1);
  9460. Info.offset = 0;
  9461. Info.align = DL.getABITypeAlign(PtrTy->getElementType());
  9462. Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
  9463. return true;
  9464. }
  9465. case Intrinsic::aarch64_ldaxp:
  9466. case Intrinsic::aarch64_ldxp:
  9467. Info.opc = ISD::INTRINSIC_W_CHAIN;
  9468. Info.memVT = MVT::i128;
  9469. Info.ptrVal = I.getArgOperand(0);
  9470. Info.offset = 0;
  9471. Info.align = Align(16);
  9472. Info.flags = MachineMemOperand::MOLoad | MachineMemOperand::MOVolatile;
  9473. return true;
  9474. case Intrinsic::aarch64_stlxp:
  9475. case Intrinsic::aarch64_stxp:
  9476. Info.opc = ISD::INTRINSIC_W_CHAIN;
  9477. Info.memVT = MVT::i128;
  9478. Info.ptrVal = I.getArgOperand(2);
  9479. Info.offset = 0;
  9480. Info.align = Align(16);
  9481. Info.flags = MachineMemOperand::MOStore | MachineMemOperand::MOVolatile;
  9482. return true;
  9483. case Intrinsic::aarch64_sve_ldnt1: {
  9484. PointerType *PtrTy = cast<PointerType>(I.getArgOperand(1)->getType());
  9485. Info.opc = ISD::INTRINSIC_W_CHAIN;
  9486. Info.memVT = MVT::getVT(I.getType());
  9487. Info.ptrVal = I.getArgOperand(1);
  9488. Info.offset = 0;
  9489. Info.align = DL.getABITypeAlign(PtrTy->getElementType());
  9490. Info.flags = MachineMemOperand::MOLoad;
  9491. if (Intrinsic == Intrinsic::aarch64_sve_ldnt1)
  9492. Info.flags |= MachineMemOperand::MONonTemporal;
  9493. return true;
  9494. }
  9495. case Intrinsic::aarch64_sve_stnt1: {
  9496. PointerType *PtrTy = cast<PointerType>(I.getArgOperand(2)->getType());
  9497. Info.opc = ISD::INTRINSIC_W_CHAIN;
  9498. Info.memVT = MVT::getVT(I.getOperand(0)->getType());
  9499. Info.ptrVal = I.getArgOperand(2);
  9500. Info.offset = 0;
  9501. Info.align = DL.getABITypeAlign(PtrTy->getElementType());
  9502. Info.flags = MachineMemOperand::MOStore;
  9503. if (Intrinsic == Intrinsic::aarch64_sve_stnt1)
  9504. Info.flags |= MachineMemOperand::MONonTemporal;
  9505. return true;
  9506. }
  9507. default:
  9508. break;
  9509. }
  9510. return false;
  9511. }
  9512. bool AArch64TargetLowering::shouldReduceLoadWidth(SDNode *Load,
  9513. ISD::LoadExtType ExtTy,
  9514. EVT NewVT) const {
  9515. // TODO: This may be worth removing. Check regression tests for diffs.
  9516. if (!TargetLoweringBase::shouldReduceLoadWidth(Load, ExtTy, NewVT))
  9517. return false;
  9518. // If we're reducing the load width in order to avoid having to use an extra
  9519. // instruction to do extension then it's probably a good idea.
  9520. if (ExtTy != ISD::NON_EXTLOAD)
  9521. return true;
  9522. // Don't reduce load width if it would prevent us from combining a shift into
  9523. // the offset.
  9524. MemSDNode *Mem = dyn_cast<MemSDNode>(Load);
  9525. assert(Mem);
  9526. const SDValue &Base = Mem->getBasePtr();
  9527. if (Base.getOpcode() == ISD::ADD &&
  9528. Base.getOperand(1).getOpcode() == ISD::SHL &&
  9529. Base.getOperand(1).hasOneUse() &&
  9530. Base.getOperand(1).getOperand(1).getOpcode() == ISD::Constant) {
  9531. // The shift can be combined if it matches the size of the value being
  9532. // loaded (and so reducing the width would make it not match).
  9533. uint64_t ShiftAmount = Base.getOperand(1).getConstantOperandVal(1);
  9534. uint64_t LoadBytes = Mem->getMemoryVT().getSizeInBits()/8;
  9535. if (ShiftAmount == Log2_32(LoadBytes))
  9536. return false;
  9537. }
  9538. // We have no reason to disallow reducing the load width, so allow it.
  9539. return true;
  9540. }
  9541. // Truncations from 64-bit GPR to 32-bit GPR is free.
  9542. bool AArch64TargetLowering::isTruncateFree(Type *Ty1, Type *Ty2) const {
  9543. if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
  9544. return false;
  9545. uint64_t NumBits1 = Ty1->getPrimitiveSizeInBits().getFixedSize();
  9546. uint64_t NumBits2 = Ty2->getPrimitiveSizeInBits().getFixedSize();
  9547. return NumBits1 > NumBits2;
  9548. }
  9549. bool AArch64TargetLowering::isTruncateFree(EVT VT1, EVT VT2) const {
  9550. if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
  9551. return false;
  9552. uint64_t NumBits1 = VT1.getFixedSizeInBits();
  9553. uint64_t NumBits2 = VT2.getFixedSizeInBits();
  9554. return NumBits1 > NumBits2;
  9555. }
  9556. /// Check if it is profitable to hoist instruction in then/else to if.
  9557. /// Not profitable if I and it's user can form a FMA instruction
  9558. /// because we prefer FMSUB/FMADD.
  9559. bool AArch64TargetLowering::isProfitableToHoist(Instruction *I) const {
  9560. if (I->getOpcode() != Instruction::FMul)
  9561. return true;
  9562. if (!I->hasOneUse())
  9563. return true;
  9564. Instruction *User = I->user_back();
  9565. if (User &&
  9566. !(User->getOpcode() == Instruction::FSub ||
  9567. User->getOpcode() == Instruction::FAdd))
  9568. return true;
  9569. const TargetOptions &Options = getTargetMachine().Options;
  9570. const Function *F = I->getFunction();
  9571. const DataLayout &DL = F->getParent()->getDataLayout();
  9572. Type *Ty = User->getOperand(0)->getType();
  9573. return !(isFMAFasterThanFMulAndFAdd(*F, Ty) &&
  9574. isOperationLegalOrCustom(ISD::FMA, getValueType(DL, Ty)) &&
  9575. (Options.AllowFPOpFusion == FPOpFusion::Fast ||
  9576. Options.UnsafeFPMath));
  9577. }
  9578. // All 32-bit GPR operations implicitly zero the high-half of the corresponding
  9579. // 64-bit GPR.
  9580. bool AArch64TargetLowering::isZExtFree(Type *Ty1, Type *Ty2) const {
  9581. if (!Ty1->isIntegerTy() || !Ty2->isIntegerTy())
  9582. return false;
  9583. unsigned NumBits1 = Ty1->getPrimitiveSizeInBits();
  9584. unsigned NumBits2 = Ty2->getPrimitiveSizeInBits();
  9585. return NumBits1 == 32 && NumBits2 == 64;
  9586. }
  9587. bool AArch64TargetLowering::isZExtFree(EVT VT1, EVT VT2) const {
  9588. if (VT1.isVector() || VT2.isVector() || !VT1.isInteger() || !VT2.isInteger())
  9589. return false;
  9590. unsigned NumBits1 = VT1.getSizeInBits();
  9591. unsigned NumBits2 = VT2.getSizeInBits();
  9592. return NumBits1 == 32 && NumBits2 == 64;
  9593. }
  9594. bool AArch64TargetLowering::isZExtFree(SDValue Val, EVT VT2) const {
  9595. EVT VT1 = Val.getValueType();
  9596. if (isZExtFree(VT1, VT2)) {
  9597. return true;
  9598. }
  9599. if (Val.getOpcode() != ISD::LOAD)
  9600. return false;
  9601. // 8-, 16-, and 32-bit integer loads all implicitly zero-extend.
  9602. return (VT1.isSimple() && !VT1.isVector() && VT1.isInteger() &&
  9603. VT2.isSimple() && !VT2.isVector() && VT2.isInteger() &&
  9604. VT1.getSizeInBits() <= 32);
  9605. }
  9606. bool AArch64TargetLowering::isExtFreeImpl(const Instruction *Ext) const {
  9607. if (isa<FPExtInst>(Ext))
  9608. return false;
  9609. // Vector types are not free.
  9610. if (Ext->getType()->isVectorTy())
  9611. return false;
  9612. for (const Use &U : Ext->uses()) {
  9613. // The extension is free if we can fold it with a left shift in an
  9614. // addressing mode or an arithmetic operation: add, sub, and cmp.
  9615. // Is there a shift?
  9616. const Instruction *Instr = cast<Instruction>(U.getUser());
  9617. // Is this a constant shift?
  9618. switch (Instr->getOpcode()) {
  9619. case Instruction::Shl:
  9620. if (!isa<ConstantInt>(Instr->getOperand(1)))
  9621. return false;
  9622. break;
  9623. case Instruction::GetElementPtr: {
  9624. gep_type_iterator GTI = gep_type_begin(Instr);
  9625. auto &DL = Ext->getModule()->getDataLayout();
  9626. std::advance(GTI, U.getOperandNo()-1);
  9627. Type *IdxTy = GTI.getIndexedType();
  9628. // This extension will end up with a shift because of the scaling factor.
  9629. // 8-bit sized types have a scaling factor of 1, thus a shift amount of 0.
  9630. // Get the shift amount based on the scaling factor:
  9631. // log2(sizeof(IdxTy)) - log2(8).
  9632. uint64_t ShiftAmt =
  9633. countTrailingZeros(DL.getTypeStoreSizeInBits(IdxTy).getFixedSize()) - 3;
  9634. // Is the constant foldable in the shift of the addressing mode?
  9635. // I.e., shift amount is between 1 and 4 inclusive.
  9636. if (ShiftAmt == 0 || ShiftAmt > 4)
  9637. return false;
  9638. break;
  9639. }
  9640. case Instruction::Trunc:
  9641. // Check if this is a noop.
  9642. // trunc(sext ty1 to ty2) to ty1.
  9643. if (Instr->getType() == Ext->getOperand(0)->getType())
  9644. continue;
  9645. LLVM_FALLTHROUGH;
  9646. default:
  9647. return false;
  9648. }
  9649. // At this point we can use the bfm family, so this extension is free
  9650. // for that use.
  9651. }
  9652. return true;
  9653. }
  9654. /// Check if both Op1 and Op2 are shufflevector extracts of either the lower
  9655. /// or upper half of the vector elements.
  9656. static bool areExtractShuffleVectors(Value *Op1, Value *Op2) {
  9657. auto areTypesHalfed = [](Value *FullV, Value *HalfV) {
  9658. auto *FullTy = FullV->getType();
  9659. auto *HalfTy = HalfV->getType();
  9660. return FullTy->getPrimitiveSizeInBits().getFixedSize() ==
  9661. 2 * HalfTy->getPrimitiveSizeInBits().getFixedSize();
  9662. };
  9663. auto extractHalf = [](Value *FullV, Value *HalfV) {
  9664. auto *FullVT = cast<FixedVectorType>(FullV->getType());
  9665. auto *HalfVT = cast<FixedVectorType>(HalfV->getType());
  9666. return FullVT->getNumElements() == 2 * HalfVT->getNumElements();
  9667. };
  9668. ArrayRef<int> M1, M2;
  9669. Value *S1Op1, *S2Op1;
  9670. if (!match(Op1, m_Shuffle(m_Value(S1Op1), m_Undef(), m_Mask(M1))) ||
  9671. !match(Op2, m_Shuffle(m_Value(S2Op1), m_Undef(), m_Mask(M2))))
  9672. return false;
  9673. // Check that the operands are half as wide as the result and we extract
  9674. // half of the elements of the input vectors.
  9675. if (!areTypesHalfed(S1Op1, Op1) || !areTypesHalfed(S2Op1, Op2) ||
  9676. !extractHalf(S1Op1, Op1) || !extractHalf(S2Op1, Op2))
  9677. return false;
  9678. // Check the mask extracts either the lower or upper half of vector
  9679. // elements.
  9680. int M1Start = -1;
  9681. int M2Start = -1;
  9682. int NumElements = cast<FixedVectorType>(Op1->getType())->getNumElements() * 2;
  9683. if (!ShuffleVectorInst::isExtractSubvectorMask(M1, NumElements, M1Start) ||
  9684. !ShuffleVectorInst::isExtractSubvectorMask(M2, NumElements, M2Start) ||
  9685. M1Start != M2Start || (M1Start != 0 && M2Start != (NumElements / 2)))
  9686. return false;
  9687. return true;
  9688. }
  9689. /// Check if Ext1 and Ext2 are extends of the same type, doubling the bitwidth
  9690. /// of the vector elements.
  9691. static bool areExtractExts(Value *Ext1, Value *Ext2) {
  9692. auto areExtDoubled = [](Instruction *Ext) {
  9693. return Ext->getType()->getScalarSizeInBits() ==
  9694. 2 * Ext->getOperand(0)->getType()->getScalarSizeInBits();
  9695. };
  9696. if (!match(Ext1, m_ZExtOrSExt(m_Value())) ||
  9697. !match(Ext2, m_ZExtOrSExt(m_Value())) ||
  9698. !areExtDoubled(cast<Instruction>(Ext1)) ||
  9699. !areExtDoubled(cast<Instruction>(Ext2)))
  9700. return false;
  9701. return true;
  9702. }
  9703. /// Check if Op could be used with vmull_high_p64 intrinsic.
  9704. static bool isOperandOfVmullHighP64(Value *Op) {
  9705. Value *VectorOperand = nullptr;
  9706. ConstantInt *ElementIndex = nullptr;
  9707. return match(Op, m_ExtractElt(m_Value(VectorOperand),
  9708. m_ConstantInt(ElementIndex))) &&
  9709. ElementIndex->getValue() == 1 &&
  9710. isa<FixedVectorType>(VectorOperand->getType()) &&
  9711. cast<FixedVectorType>(VectorOperand->getType())->getNumElements() == 2;
  9712. }
  9713. /// Check if Op1 and Op2 could be used with vmull_high_p64 intrinsic.
  9714. static bool areOperandsOfVmullHighP64(Value *Op1, Value *Op2) {
  9715. return isOperandOfVmullHighP64(Op1) && isOperandOfVmullHighP64(Op2);
  9716. }
  9717. /// Check if sinking \p I's operands to I's basic block is profitable, because
  9718. /// the operands can be folded into a target instruction, e.g.
  9719. /// shufflevectors extracts and/or sext/zext can be folded into (u,s)subl(2).
  9720. bool AArch64TargetLowering::shouldSinkOperands(
  9721. Instruction *I, SmallVectorImpl<Use *> &Ops) const {
  9722. if (!I->getType()->isVectorTy())
  9723. return false;
  9724. if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(I)) {
  9725. switch (II->getIntrinsicID()) {
  9726. case Intrinsic::aarch64_neon_umull:
  9727. if (!areExtractShuffleVectors(II->getOperand(0), II->getOperand(1)))
  9728. return false;
  9729. Ops.push_back(&II->getOperandUse(0));
  9730. Ops.push_back(&II->getOperandUse(1));
  9731. return true;
  9732. case Intrinsic::aarch64_neon_pmull64:
  9733. if (!areOperandsOfVmullHighP64(II->getArgOperand(0),
  9734. II->getArgOperand(1)))
  9735. return false;
  9736. Ops.push_back(&II->getArgOperandUse(0));
  9737. Ops.push_back(&II->getArgOperandUse(1));
  9738. return true;
  9739. default:
  9740. return false;
  9741. }
  9742. }
  9743. switch (I->getOpcode()) {
  9744. case Instruction::Sub:
  9745. case Instruction::Add: {
  9746. if (!areExtractExts(I->getOperand(0), I->getOperand(1)))
  9747. return false;
  9748. // If the exts' operands extract either the lower or upper elements, we
  9749. // can sink them too.
  9750. auto Ext1 = cast<Instruction>(I->getOperand(0));
  9751. auto Ext2 = cast<Instruction>(I->getOperand(1));
  9752. if (areExtractShuffleVectors(Ext1, Ext2)) {
  9753. Ops.push_back(&Ext1->getOperandUse(0));
  9754. Ops.push_back(&Ext2->getOperandUse(0));
  9755. }
  9756. Ops.push_back(&I->getOperandUse(0));
  9757. Ops.push_back(&I->getOperandUse(1));
  9758. return true;
  9759. }
  9760. case Instruction::Mul: {
  9761. bool IsProfitable = false;
  9762. for (auto &Op : I->operands()) {
  9763. // Make sure we are not already sinking this operand
  9764. if (any_of(Ops, [&](Use *U) { return U->get() == Op; }))
  9765. continue;
  9766. ShuffleVectorInst *Shuffle = dyn_cast<ShuffleVectorInst>(Op);
  9767. if (!Shuffle || !Shuffle->isZeroEltSplat())
  9768. continue;
  9769. Value *ShuffleOperand = Shuffle->getOperand(0);
  9770. InsertElementInst *Insert = dyn_cast<InsertElementInst>(ShuffleOperand);
  9771. if (!Insert)
  9772. continue;
  9773. Instruction *OperandInstr = dyn_cast<Instruction>(Insert->getOperand(1));
  9774. if (!OperandInstr)
  9775. continue;
  9776. ConstantInt *ElementConstant =
  9777. dyn_cast<ConstantInt>(Insert->getOperand(2));
  9778. // Check that the insertelement is inserting into element 0
  9779. if (!ElementConstant || ElementConstant->getZExtValue() != 0)
  9780. continue;
  9781. unsigned Opcode = OperandInstr->getOpcode();
  9782. if (Opcode != Instruction::SExt && Opcode != Instruction::ZExt)
  9783. continue;
  9784. Ops.push_back(&Shuffle->getOperandUse(0));
  9785. Ops.push_back(&Op);
  9786. IsProfitable = true;
  9787. }
  9788. return IsProfitable;
  9789. }
  9790. default:
  9791. return false;
  9792. }
  9793. return false;
  9794. }
  9795. bool AArch64TargetLowering::hasPairedLoad(EVT LoadedType,
  9796. Align &RequiredAligment) const {
  9797. if (!LoadedType.isSimple() ||
  9798. (!LoadedType.isInteger() && !LoadedType.isFloatingPoint()))
  9799. return false;
  9800. // Cyclone supports unaligned accesses.
  9801. RequiredAligment = Align(1);
  9802. unsigned NumBits = LoadedType.getSizeInBits();
  9803. return NumBits == 32 || NumBits == 64;
  9804. }
  9805. /// A helper function for determining the number of interleaved accesses we
  9806. /// will generate when lowering accesses of the given type.
  9807. unsigned
  9808. AArch64TargetLowering::getNumInterleavedAccesses(VectorType *VecTy,
  9809. const DataLayout &DL) const {
  9810. return (DL.getTypeSizeInBits(VecTy) + 127) / 128;
  9811. }
  9812. MachineMemOperand::Flags
  9813. AArch64TargetLowering::getTargetMMOFlags(const Instruction &I) const {
  9814. if (Subtarget->getProcFamily() == AArch64Subtarget::Falkor &&
  9815. I.getMetadata(FALKOR_STRIDED_ACCESS_MD) != nullptr)
  9816. return MOStridedAccess;
  9817. return MachineMemOperand::MONone;
  9818. }
  9819. bool AArch64TargetLowering::isLegalInterleavedAccessType(
  9820. VectorType *VecTy, const DataLayout &DL) const {
  9821. unsigned VecSize = DL.getTypeSizeInBits(VecTy);
  9822. unsigned ElSize = DL.getTypeSizeInBits(VecTy->getElementType());
  9823. // Ensure the number of vector elements is greater than 1.
  9824. if (cast<FixedVectorType>(VecTy)->getNumElements() < 2)
  9825. return false;
  9826. // Ensure the element type is legal.
  9827. if (ElSize != 8 && ElSize != 16 && ElSize != 32 && ElSize != 64)
  9828. return false;
  9829. // Ensure the total vector size is 64 or a multiple of 128. Types larger than
  9830. // 128 will be split into multiple interleaved accesses.
  9831. return VecSize == 64 || VecSize % 128 == 0;
  9832. }
  9833. /// Lower an interleaved load into a ldN intrinsic.
  9834. ///
  9835. /// E.g. Lower an interleaved load (Factor = 2):
  9836. /// %wide.vec = load <8 x i32>, <8 x i32>* %ptr
  9837. /// %v0 = shuffle %wide.vec, undef, <0, 2, 4, 6> ; Extract even elements
  9838. /// %v1 = shuffle %wide.vec, undef, <1, 3, 5, 7> ; Extract odd elements
  9839. ///
  9840. /// Into:
  9841. /// %ld2 = { <4 x i32>, <4 x i32> } call llvm.aarch64.neon.ld2(%ptr)
  9842. /// %vec0 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 0
  9843. /// %vec1 = extractelement { <4 x i32>, <4 x i32> } %ld2, i32 1
  9844. bool AArch64TargetLowering::lowerInterleavedLoad(
  9845. LoadInst *LI, ArrayRef<ShuffleVectorInst *> Shuffles,
  9846. ArrayRef<unsigned> Indices, unsigned Factor) const {
  9847. assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
  9848. "Invalid interleave factor");
  9849. assert(!Shuffles.empty() && "Empty shufflevector input");
  9850. assert(Shuffles.size() == Indices.size() &&
  9851. "Unmatched number of shufflevectors and indices");
  9852. const DataLayout &DL = LI->getModule()->getDataLayout();
  9853. VectorType *VTy = Shuffles[0]->getType();
  9854. // Skip if we do not have NEON and skip illegal vector types. We can
  9855. // "legalize" wide vector types into multiple interleaved accesses as long as
  9856. // the vector types are divisible by 128.
  9857. if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(VTy, DL))
  9858. return false;
  9859. unsigned NumLoads = getNumInterleavedAccesses(VTy, DL);
  9860. auto *FVTy = cast<FixedVectorType>(VTy);
  9861. // A pointer vector can not be the return type of the ldN intrinsics. Need to
  9862. // load integer vectors first and then convert to pointer vectors.
  9863. Type *EltTy = FVTy->getElementType();
  9864. if (EltTy->isPointerTy())
  9865. FVTy =
  9866. FixedVectorType::get(DL.getIntPtrType(EltTy), FVTy->getNumElements());
  9867. IRBuilder<> Builder(LI);
  9868. // The base address of the load.
  9869. Value *BaseAddr = LI->getPointerOperand();
  9870. if (NumLoads > 1) {
  9871. // If we're going to generate more than one load, reset the sub-vector type
  9872. // to something legal.
  9873. FVTy = FixedVectorType::get(FVTy->getElementType(),
  9874. FVTy->getNumElements() / NumLoads);
  9875. // We will compute the pointer operand of each load from the original base
  9876. // address using GEPs. Cast the base address to a pointer to the scalar
  9877. // element type.
  9878. BaseAddr = Builder.CreateBitCast(
  9879. BaseAddr,
  9880. FVTy->getElementType()->getPointerTo(LI->getPointerAddressSpace()));
  9881. }
  9882. Type *PtrTy = FVTy->getPointerTo(LI->getPointerAddressSpace());
  9883. Type *Tys[2] = {FVTy, PtrTy};
  9884. static const Intrinsic::ID LoadInts[3] = {Intrinsic::aarch64_neon_ld2,
  9885. Intrinsic::aarch64_neon_ld3,
  9886. Intrinsic::aarch64_neon_ld4};
  9887. Function *LdNFunc =
  9888. Intrinsic::getDeclaration(LI->getModule(), LoadInts[Factor - 2], Tys);
  9889. // Holds sub-vectors extracted from the load intrinsic return values. The
  9890. // sub-vectors are associated with the shufflevector instructions they will
  9891. // replace.
  9892. DenseMap<ShuffleVectorInst *, SmallVector<Value *, 4>> SubVecs;
  9893. for (unsigned LoadCount = 0; LoadCount < NumLoads; ++LoadCount) {
  9894. // If we're generating more than one load, compute the base address of
  9895. // subsequent loads as an offset from the previous.
  9896. if (LoadCount > 0)
  9897. BaseAddr = Builder.CreateConstGEP1_32(FVTy->getElementType(), BaseAddr,
  9898. FVTy->getNumElements() * Factor);
  9899. CallInst *LdN = Builder.CreateCall(
  9900. LdNFunc, Builder.CreateBitCast(BaseAddr, PtrTy), "ldN");
  9901. // Extract and store the sub-vectors returned by the load intrinsic.
  9902. for (unsigned i = 0; i < Shuffles.size(); i++) {
  9903. ShuffleVectorInst *SVI = Shuffles[i];
  9904. unsigned Index = Indices[i];
  9905. Value *SubVec = Builder.CreateExtractValue(LdN, Index);
  9906. // Convert the integer vector to pointer vector if the element is pointer.
  9907. if (EltTy->isPointerTy())
  9908. SubVec = Builder.CreateIntToPtr(
  9909. SubVec, FixedVectorType::get(SVI->getType()->getElementType(),
  9910. FVTy->getNumElements()));
  9911. SubVecs[SVI].push_back(SubVec);
  9912. }
  9913. }
  9914. // Replace uses of the shufflevector instructions with the sub-vectors
  9915. // returned by the load intrinsic. If a shufflevector instruction is
  9916. // associated with more than one sub-vector, those sub-vectors will be
  9917. // concatenated into a single wide vector.
  9918. for (ShuffleVectorInst *SVI : Shuffles) {
  9919. auto &SubVec = SubVecs[SVI];
  9920. auto *WideVec =
  9921. SubVec.size() > 1 ? concatenateVectors(Builder, SubVec) : SubVec[0];
  9922. SVI->replaceAllUsesWith(WideVec);
  9923. }
  9924. return true;
  9925. }
  9926. /// Lower an interleaved store into a stN intrinsic.
  9927. ///
  9928. /// E.g. Lower an interleaved store (Factor = 3):
  9929. /// %i.vec = shuffle <8 x i32> %v0, <8 x i32> %v1,
  9930. /// <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11>
  9931. /// store <12 x i32> %i.vec, <12 x i32>* %ptr
  9932. ///
  9933. /// Into:
  9934. /// %sub.v0 = shuffle <8 x i32> %v0, <8 x i32> v1, <0, 1, 2, 3>
  9935. /// %sub.v1 = shuffle <8 x i32> %v0, <8 x i32> v1, <4, 5, 6, 7>
  9936. /// %sub.v2 = shuffle <8 x i32> %v0, <8 x i32> v1, <8, 9, 10, 11>
  9937. /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
  9938. ///
  9939. /// Note that the new shufflevectors will be removed and we'll only generate one
  9940. /// st3 instruction in CodeGen.
  9941. ///
  9942. /// Example for a more general valid mask (Factor 3). Lower:
  9943. /// %i.vec = shuffle <32 x i32> %v0, <32 x i32> %v1,
  9944. /// <4, 32, 16, 5, 33, 17, 6, 34, 18, 7, 35, 19>
  9945. /// store <12 x i32> %i.vec, <12 x i32>* %ptr
  9946. ///
  9947. /// Into:
  9948. /// %sub.v0 = shuffle <32 x i32> %v0, <32 x i32> v1, <4, 5, 6, 7>
  9949. /// %sub.v1 = shuffle <32 x i32> %v0, <32 x i32> v1, <32, 33, 34, 35>
  9950. /// %sub.v2 = shuffle <32 x i32> %v0, <32 x i32> v1, <16, 17, 18, 19>
  9951. /// call void llvm.aarch64.neon.st3(%sub.v0, %sub.v1, %sub.v2, %ptr)
  9952. bool AArch64TargetLowering::lowerInterleavedStore(StoreInst *SI,
  9953. ShuffleVectorInst *SVI,
  9954. unsigned Factor) const {
  9955. assert(Factor >= 2 && Factor <= getMaxSupportedInterleaveFactor() &&
  9956. "Invalid interleave factor");
  9957. auto *VecTy = cast<FixedVectorType>(SVI->getType());
  9958. assert(VecTy->getNumElements() % Factor == 0 && "Invalid interleaved store");
  9959. unsigned LaneLen = VecTy->getNumElements() / Factor;
  9960. Type *EltTy = VecTy->getElementType();
  9961. auto *SubVecTy = FixedVectorType::get(EltTy, LaneLen);
  9962. const DataLayout &DL = SI->getModule()->getDataLayout();
  9963. // Skip if we do not have NEON and skip illegal vector types. We can
  9964. // "legalize" wide vector types into multiple interleaved accesses as long as
  9965. // the vector types are divisible by 128.
  9966. if (!Subtarget->hasNEON() || !isLegalInterleavedAccessType(SubVecTy, DL))
  9967. return false;
  9968. unsigned NumStores = getNumInterleavedAccesses(SubVecTy, DL);
  9969. Value *Op0 = SVI->getOperand(0);
  9970. Value *Op1 = SVI->getOperand(1);
  9971. IRBuilder<> Builder(SI);
  9972. // StN intrinsics don't support pointer vectors as arguments. Convert pointer
  9973. // vectors to integer vectors.
  9974. if (EltTy->isPointerTy()) {
  9975. Type *IntTy = DL.getIntPtrType(EltTy);
  9976. unsigned NumOpElts =
  9977. cast<FixedVectorType>(Op0->getType())->getNumElements();
  9978. // Convert to the corresponding integer vector.
  9979. auto *IntVecTy = FixedVectorType::get(IntTy, NumOpElts);
  9980. Op0 = Builder.CreatePtrToInt(Op0, IntVecTy);
  9981. Op1 = Builder.CreatePtrToInt(Op1, IntVecTy);
  9982. SubVecTy = FixedVectorType::get(IntTy, LaneLen);
  9983. }
  9984. // The base address of the store.
  9985. Value *BaseAddr = SI->getPointerOperand();
  9986. if (NumStores > 1) {
  9987. // If we're going to generate more than one store, reset the lane length
  9988. // and sub-vector type to something legal.
  9989. LaneLen /= NumStores;
  9990. SubVecTy = FixedVectorType::get(SubVecTy->getElementType(), LaneLen);
  9991. // We will compute the pointer operand of each store from the original base
  9992. // address using GEPs. Cast the base address to a pointer to the scalar
  9993. // element type.
  9994. BaseAddr = Builder.CreateBitCast(
  9995. BaseAddr,
  9996. SubVecTy->getElementType()->getPointerTo(SI->getPointerAddressSpace()));
  9997. }
  9998. auto Mask = SVI->getShuffleMask();
  9999. Type *PtrTy = SubVecTy->getPointerTo(SI->getPointerAddressSpace());
  10000. Type *Tys[2] = {SubVecTy, PtrTy};
  10001. static const Intrinsic::ID StoreInts[3] = {Intrinsic::aarch64_neon_st2,
  10002. Intrinsic::aarch64_neon_st3,
  10003. Intrinsic::aarch64_neon_st4};
  10004. Function *StNFunc =
  10005. Intrinsic::getDeclaration(SI->getModule(), StoreInts[Factor - 2], Tys);
  10006. for (unsigned StoreCount = 0; StoreCount < NumStores; ++StoreCount) {
  10007. SmallVector<Value *, 5> Ops;
  10008. // Split the shufflevector operands into sub vectors for the new stN call.
  10009. for (unsigned i = 0; i < Factor; i++) {
  10010. unsigned IdxI = StoreCount * LaneLen * Factor + i;
  10011. if (Mask[IdxI] >= 0) {
  10012. Ops.push_back(Builder.CreateShuffleVector(
  10013. Op0, Op1, createSequentialMask(Mask[IdxI], LaneLen, 0)));
  10014. } else {
  10015. unsigned StartMask = 0;
  10016. for (unsigned j = 1; j < LaneLen; j++) {
  10017. unsigned IdxJ = StoreCount * LaneLen * Factor + j;
  10018. if (Mask[IdxJ * Factor + IdxI] >= 0) {
  10019. StartMask = Mask[IdxJ * Factor + IdxI] - IdxJ;
  10020. break;
  10021. }
  10022. }
  10023. // Note: Filling undef gaps with random elements is ok, since
  10024. // those elements were being written anyway (with undefs).
  10025. // In the case of all undefs we're defaulting to using elems from 0
  10026. // Note: StartMask cannot be negative, it's checked in
  10027. // isReInterleaveMask
  10028. Ops.push_back(Builder.CreateShuffleVector(
  10029. Op0, Op1, createSequentialMask(StartMask, LaneLen, 0)));
  10030. }
  10031. }
  10032. // If we generating more than one store, we compute the base address of
  10033. // subsequent stores as an offset from the previous.
  10034. if (StoreCount > 0)
  10035. BaseAddr = Builder.CreateConstGEP1_32(SubVecTy->getElementType(),
  10036. BaseAddr, LaneLen * Factor);
  10037. Ops.push_back(Builder.CreateBitCast(BaseAddr, PtrTy));
  10038. Builder.CreateCall(StNFunc, Ops);
  10039. }
  10040. return true;
  10041. }
  10042. // Lower an SVE structured load intrinsic returning a tuple type to target
  10043. // specific intrinsic taking the same input but returning a multi-result value
  10044. // of the split tuple type.
  10045. //
  10046. // E.g. Lowering an LD3:
  10047. //
  10048. // call <vscale x 12 x i32> @llvm.aarch64.sve.ld3.nxv12i32(
  10049. // <vscale x 4 x i1> %pred,
  10050. // <vscale x 4 x i32>* %addr)
  10051. //
  10052. // Output DAG:
  10053. //
  10054. // t0: ch = EntryToken
  10055. // t2: nxv4i1,ch = CopyFromReg t0, Register:nxv4i1 %0
  10056. // t4: i64,ch = CopyFromReg t0, Register:i64 %1
  10057. // t5: nxv4i32,nxv4i32,nxv4i32,ch = AArch64ISD::SVE_LD3 t0, t2, t4
  10058. // t6: nxv12i32 = concat_vectors t5, t5:1, t5:2
  10059. //
  10060. // This is called pre-legalization to avoid widening/splitting issues with
  10061. // non-power-of-2 tuple types used for LD3, such as nxv12i32.
  10062. SDValue AArch64TargetLowering::LowerSVEStructLoad(unsigned Intrinsic,
  10063. ArrayRef<SDValue> LoadOps,
  10064. EVT VT, SelectionDAG &DAG,
  10065. const SDLoc &DL) const {
  10066. assert(VT.isScalableVector() && "Can only lower scalable vectors");
  10067. unsigned N, Opcode;
  10068. static std::map<unsigned, std::pair<unsigned, unsigned>> IntrinsicMap = {
  10069. {Intrinsic::aarch64_sve_ld2, {2, AArch64ISD::SVE_LD2_MERGE_ZERO}},
  10070. {Intrinsic::aarch64_sve_ld3, {3, AArch64ISD::SVE_LD3_MERGE_ZERO}},
  10071. {Intrinsic::aarch64_sve_ld4, {4, AArch64ISD::SVE_LD4_MERGE_ZERO}}};
  10072. std::tie(N, Opcode) = IntrinsicMap[Intrinsic];
  10073. assert(VT.getVectorElementCount().getKnownMinValue() % N == 0 &&
  10074. "invalid tuple vector type!");
  10075. EVT SplitVT =
  10076. EVT::getVectorVT(*DAG.getContext(), VT.getVectorElementType(),
  10077. VT.getVectorElementCount().divideCoefficientBy(N));
  10078. assert(isTypeLegal(SplitVT));
  10079. SmallVector<EVT, 5> VTs(N, SplitVT);
  10080. VTs.push_back(MVT::Other); // Chain
  10081. SDVTList NodeTys = DAG.getVTList(VTs);
  10082. SDValue PseudoLoad = DAG.getNode(Opcode, DL, NodeTys, LoadOps);
  10083. SmallVector<SDValue, 4> PseudoLoadOps;
  10084. for (unsigned I = 0; I < N; ++I)
  10085. PseudoLoadOps.push_back(SDValue(PseudoLoad.getNode(), I));
  10086. return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, PseudoLoadOps);
  10087. }
  10088. EVT AArch64TargetLowering::getOptimalMemOpType(
  10089. const MemOp &Op, const AttributeList &FuncAttributes) const {
  10090. bool CanImplicitFloat =
  10091. !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
  10092. bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
  10093. bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
  10094. // Only use AdvSIMD to implement memset of 32-byte and above. It would have
  10095. // taken one instruction to materialize the v2i64 zero and one store (with
  10096. // restrictive addressing mode). Just do i64 stores.
  10097. bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
  10098. auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
  10099. if (Op.isAligned(AlignCheck))
  10100. return true;
  10101. bool Fast;
  10102. return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
  10103. &Fast) &&
  10104. Fast;
  10105. };
  10106. if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
  10107. AlignmentIsAcceptable(MVT::v2i64, Align(16)))
  10108. return MVT::v2i64;
  10109. if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
  10110. return MVT::f128;
  10111. if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
  10112. return MVT::i64;
  10113. if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
  10114. return MVT::i32;
  10115. return MVT::Other;
  10116. }
  10117. LLT AArch64TargetLowering::getOptimalMemOpLLT(
  10118. const MemOp &Op, const AttributeList &FuncAttributes) const {
  10119. bool CanImplicitFloat =
  10120. !FuncAttributes.hasFnAttribute(Attribute::NoImplicitFloat);
  10121. bool CanUseNEON = Subtarget->hasNEON() && CanImplicitFloat;
  10122. bool CanUseFP = Subtarget->hasFPARMv8() && CanImplicitFloat;
  10123. // Only use AdvSIMD to implement memset of 32-byte and above. It would have
  10124. // taken one instruction to materialize the v2i64 zero and one store (with
  10125. // restrictive addressing mode). Just do i64 stores.
  10126. bool IsSmallMemset = Op.isMemset() && Op.size() < 32;
  10127. auto AlignmentIsAcceptable = [&](EVT VT, Align AlignCheck) {
  10128. if (Op.isAligned(AlignCheck))
  10129. return true;
  10130. bool Fast;
  10131. return allowsMisalignedMemoryAccesses(VT, 0, 1, MachineMemOperand::MONone,
  10132. &Fast) &&
  10133. Fast;
  10134. };
  10135. if (CanUseNEON && Op.isMemset() && !IsSmallMemset &&
  10136. AlignmentIsAcceptable(MVT::v2i64, Align(16)))
  10137. return LLT::vector(2, 64);
  10138. if (CanUseFP && !IsSmallMemset && AlignmentIsAcceptable(MVT::f128, Align(16)))
  10139. return LLT::scalar(128);
  10140. if (Op.size() >= 8 && AlignmentIsAcceptable(MVT::i64, Align(8)))
  10141. return LLT::scalar(64);
  10142. if (Op.size() >= 4 && AlignmentIsAcceptable(MVT::i32, Align(4)))
  10143. return LLT::scalar(32);
  10144. return LLT();
  10145. }
  10146. // 12-bit optionally shifted immediates are legal for adds.
  10147. bool AArch64TargetLowering::isLegalAddImmediate(int64_t Immed) const {
  10148. if (Immed == std::numeric_limits<int64_t>::min()) {
  10149. LLVM_DEBUG(dbgs() << "Illegal add imm " << Immed
  10150. << ": avoid UB for INT64_MIN\n");
  10151. return false;
  10152. }
  10153. // Same encoding for add/sub, just flip the sign.
  10154. Immed = std::abs(Immed);
  10155. bool IsLegal = ((Immed >> 12) == 0 ||
  10156. ((Immed & 0xfff) == 0 && Immed >> 24 == 0));
  10157. LLVM_DEBUG(dbgs() << "Is " << Immed
  10158. << " legal add imm: " << (IsLegal ? "yes" : "no") << "\n");
  10159. return IsLegal;
  10160. }
  10161. // Integer comparisons are implemented with ADDS/SUBS, so the range of valid
  10162. // immediates is the same as for an add or a sub.
  10163. bool AArch64TargetLowering::isLegalICmpImmediate(int64_t Immed) const {
  10164. return isLegalAddImmediate(Immed);
  10165. }
  10166. /// isLegalAddressingMode - Return true if the addressing mode represented
  10167. /// by AM is legal for this target, for a load/store of the specified type.
  10168. bool AArch64TargetLowering::isLegalAddressingMode(const DataLayout &DL,
  10169. const AddrMode &AM, Type *Ty,
  10170. unsigned AS, Instruction *I) const {
  10171. // AArch64 has five basic addressing modes:
  10172. // reg
  10173. // reg + 9-bit signed offset
  10174. // reg + SIZE_IN_BYTES * 12-bit unsigned offset
  10175. // reg1 + reg2
  10176. // reg + SIZE_IN_BYTES * reg
  10177. // No global is ever allowed as a base.
  10178. if (AM.BaseGV)
  10179. return false;
  10180. // No reg+reg+imm addressing.
  10181. if (AM.HasBaseReg && AM.BaseOffs && AM.Scale)
  10182. return false;
  10183. // FIXME: Update this method to support scalable addressing modes.
  10184. if (isa<ScalableVectorType>(Ty))
  10185. return AM.HasBaseReg && !AM.BaseOffs && !AM.Scale;
  10186. // check reg + imm case:
  10187. // i.e., reg + 0, reg + imm9, reg + SIZE_IN_BYTES * uimm12
  10188. uint64_t NumBytes = 0;
  10189. if (Ty->isSized()) {
  10190. uint64_t NumBits = DL.getTypeSizeInBits(Ty);
  10191. NumBytes = NumBits / 8;
  10192. if (!isPowerOf2_64(NumBits))
  10193. NumBytes = 0;
  10194. }
  10195. if (!AM.Scale) {
  10196. int64_t Offset = AM.BaseOffs;
  10197. // 9-bit signed offset
  10198. if (isInt<9>(Offset))
  10199. return true;
  10200. // 12-bit unsigned offset
  10201. unsigned shift = Log2_64(NumBytes);
  10202. if (NumBytes && Offset > 0 && (Offset / NumBytes) <= (1LL << 12) - 1 &&
  10203. // Must be a multiple of NumBytes (NumBytes is a power of 2)
  10204. (Offset >> shift) << shift == Offset)
  10205. return true;
  10206. return false;
  10207. }
  10208. // Check reg1 + SIZE_IN_BYTES * reg2 and reg1 + reg2
  10209. return AM.Scale == 1 || (AM.Scale > 0 && (uint64_t)AM.Scale == NumBytes);
  10210. }
  10211. bool AArch64TargetLowering::shouldConsiderGEPOffsetSplit() const {
  10212. // Consider splitting large offset of struct or array.
  10213. return true;
  10214. }
  10215. int AArch64TargetLowering::getScalingFactorCost(const DataLayout &DL,
  10216. const AddrMode &AM, Type *Ty,
  10217. unsigned AS) const {
  10218. // Scaling factors are not free at all.
  10219. // Operands | Rt Latency
  10220. // -------------------------------------------
  10221. // Rt, [Xn, Xm] | 4
  10222. // -------------------------------------------
  10223. // Rt, [Xn, Xm, lsl #imm] | Rn: 4 Rm: 5
  10224. // Rt, [Xn, Wm, <extend> #imm] |
  10225. if (isLegalAddressingMode(DL, AM, Ty, AS))
  10226. // Scale represents reg2 * scale, thus account for 1 if
  10227. // it is not equal to 0 or 1.
  10228. return AM.Scale != 0 && AM.Scale != 1;
  10229. return -1;
  10230. }
  10231. bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(
  10232. const MachineFunction &MF, EVT VT) const {
  10233. VT = VT.getScalarType();
  10234. if (!VT.isSimple())
  10235. return false;
  10236. switch (VT.getSimpleVT().SimpleTy) {
  10237. case MVT::f32:
  10238. case MVT::f64:
  10239. return true;
  10240. default:
  10241. break;
  10242. }
  10243. return false;
  10244. }
  10245. bool AArch64TargetLowering::isFMAFasterThanFMulAndFAdd(const Function &F,
  10246. Type *Ty) const {
  10247. switch (Ty->getScalarType()->getTypeID()) {
  10248. case Type::FloatTyID:
  10249. case Type::DoubleTyID:
  10250. return true;
  10251. default:
  10252. return false;
  10253. }
  10254. }
  10255. const MCPhysReg *
  10256. AArch64TargetLowering::getScratchRegisters(CallingConv::ID) const {
  10257. // LR is a callee-save register, but we must treat it as clobbered by any call
  10258. // site. Hence we include LR in the scratch registers, which are in turn added
  10259. // as implicit-defs for stackmaps and patchpoints.
  10260. static const MCPhysReg ScratchRegs[] = {
  10261. AArch64::X16, AArch64::X17, AArch64::LR, 0
  10262. };
  10263. return ScratchRegs;
  10264. }
  10265. bool
  10266. AArch64TargetLowering::isDesirableToCommuteWithShift(const SDNode *N,
  10267. CombineLevel Level) const {
  10268. N = N->getOperand(0).getNode();
  10269. EVT VT = N->getValueType(0);
  10270. // If N is unsigned bit extraction: ((x >> C) & mask), then do not combine
  10271. // it with shift to let it be lowered to UBFX.
  10272. if (N->getOpcode() == ISD::AND && (VT == MVT::i32 || VT == MVT::i64) &&
  10273. isa<ConstantSDNode>(N->getOperand(1))) {
  10274. uint64_t TruncMask = N->getConstantOperandVal(1);
  10275. if (isMask_64(TruncMask) &&
  10276. N->getOperand(0).getOpcode() == ISD::SRL &&
  10277. isa<ConstantSDNode>(N->getOperand(0)->getOperand(1)))
  10278. return false;
  10279. }
  10280. return true;
  10281. }
  10282. bool AArch64TargetLowering::shouldConvertConstantLoadToIntImm(const APInt &Imm,
  10283. Type *Ty) const {
  10284. assert(Ty->isIntegerTy());
  10285. unsigned BitSize = Ty->getPrimitiveSizeInBits();
  10286. if (BitSize == 0)
  10287. return false;
  10288. int64_t Val = Imm.getSExtValue();
  10289. if (Val == 0 || AArch64_AM::isLogicalImmediate(Val, BitSize))
  10290. return true;
  10291. if ((int64_t)Val < 0)
  10292. Val = ~Val;
  10293. if (BitSize == 32)
  10294. Val &= (1LL << 32) - 1;
  10295. unsigned LZ = countLeadingZeros((uint64_t)Val);
  10296. unsigned Shift = (63 - LZ) / 16;
  10297. // MOVZ is free so return true for one or fewer MOVK.
  10298. return Shift < 3;
  10299. }
  10300. bool AArch64TargetLowering::isExtractSubvectorCheap(EVT ResVT, EVT SrcVT,
  10301. unsigned Index) const {
  10302. if (!isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, ResVT))
  10303. return false;
  10304. return (Index == 0 || Index == ResVT.getVectorNumElements());
  10305. }
  10306. /// Turn vector tests of the signbit in the form of:
  10307. /// xor (sra X, elt_size(X)-1), -1
  10308. /// into:
  10309. /// cmge X, X, #0
  10310. static SDValue foldVectorXorShiftIntoCmp(SDNode *N, SelectionDAG &DAG,
  10311. const AArch64Subtarget *Subtarget) {
  10312. EVT VT = N->getValueType(0);
  10313. if (!Subtarget->hasNEON() || !VT.isVector())
  10314. return SDValue();
  10315. // There must be a shift right algebraic before the xor, and the xor must be a
  10316. // 'not' operation.
  10317. SDValue Shift = N->getOperand(0);
  10318. SDValue Ones = N->getOperand(1);
  10319. if (Shift.getOpcode() != AArch64ISD::VASHR || !Shift.hasOneUse() ||
  10320. !ISD::isBuildVectorAllOnes(Ones.getNode()))
  10321. return SDValue();
  10322. // The shift should be smearing the sign bit across each vector element.
  10323. auto *ShiftAmt = dyn_cast<ConstantSDNode>(Shift.getOperand(1));
  10324. EVT ShiftEltTy = Shift.getValueType().getVectorElementType();
  10325. if (!ShiftAmt || ShiftAmt->getZExtValue() != ShiftEltTy.getSizeInBits() - 1)
  10326. return SDValue();
  10327. return DAG.getNode(AArch64ISD::CMGEz, SDLoc(N), VT, Shift.getOperand(0));
  10328. }
  10329. // VECREDUCE_ADD( EXTEND(v16i8_type) ) to
  10330. // VECREDUCE_ADD( DOTv16i8(v16i8_type) )
  10331. static SDValue performVecReduceAddCombine(SDNode *N, SelectionDAG &DAG,
  10332. const AArch64Subtarget *ST) {
  10333. SDValue Op0 = N->getOperand(0);
  10334. if (!ST->hasDotProd() || N->getValueType(0) != MVT::i32)
  10335. return SDValue();
  10336. if (Op0.getValueType().getVectorElementType() != MVT::i32)
  10337. return SDValue();
  10338. unsigned ExtOpcode = Op0.getOpcode();
  10339. if (ExtOpcode != ISD::ZERO_EXTEND && ExtOpcode != ISD::SIGN_EXTEND)
  10340. return SDValue();
  10341. EVT Op0VT = Op0.getOperand(0).getValueType();
  10342. if (Op0VT != MVT::v16i8)
  10343. return SDValue();
  10344. SDLoc DL(Op0);
  10345. SDValue Ones = DAG.getConstant(1, DL, Op0VT);
  10346. SDValue Zeros = DAG.getConstant(0, DL, MVT::v4i32);
  10347. auto DotIntrisic = (ExtOpcode == ISD::ZERO_EXTEND)
  10348. ? Intrinsic::aarch64_neon_udot
  10349. : Intrinsic::aarch64_neon_sdot;
  10350. SDValue Dot = DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Zeros.getValueType(),
  10351. DAG.getConstant(DotIntrisic, DL, MVT::i32), Zeros,
  10352. Ones, Op0.getOperand(0));
  10353. return DAG.getNode(ISD::VECREDUCE_ADD, DL, N->getValueType(0), Dot);
  10354. }
  10355. // Given a ABS node, detect the following pattern:
  10356. // (ABS (SUB (EXTEND a), (EXTEND b))).
  10357. // Generates UABD/SABD instruction.
  10358. static SDValue performABSCombine(SDNode *N, SelectionDAG &DAG,
  10359. TargetLowering::DAGCombinerInfo &DCI,
  10360. const AArch64Subtarget *Subtarget) {
  10361. SDValue AbsOp1 = N->getOperand(0);
  10362. SDValue Op0, Op1;
  10363. if (AbsOp1.getOpcode() != ISD::SUB)
  10364. return SDValue();
  10365. Op0 = AbsOp1.getOperand(0);
  10366. Op1 = AbsOp1.getOperand(1);
  10367. unsigned Opc0 = Op0.getOpcode();
  10368. // Check if the operands of the sub are (zero|sign)-extended.
  10369. if (Opc0 != Op1.getOpcode() ||
  10370. (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND))
  10371. return SDValue();
  10372. EVT VectorT1 = Op0.getOperand(0).getValueType();
  10373. EVT VectorT2 = Op1.getOperand(0).getValueType();
  10374. // Check if vectors are of same type and valid size.
  10375. uint64_t Size = VectorT1.getFixedSizeInBits();
  10376. if (VectorT1 != VectorT2 || (Size != 64 && Size != 128))
  10377. return SDValue();
  10378. // Check if vector element types are valid.
  10379. EVT VT1 = VectorT1.getVectorElementType();
  10380. if (VT1 != MVT::i8 && VT1 != MVT::i16 && VT1 != MVT::i32)
  10381. return SDValue();
  10382. Op0 = Op0.getOperand(0);
  10383. Op1 = Op1.getOperand(0);
  10384. unsigned ABDOpcode =
  10385. (Opc0 == ISD::SIGN_EXTEND) ? AArch64ISD::SABD : AArch64ISD::UABD;
  10386. SDValue ABD =
  10387. DAG.getNode(ABDOpcode, SDLoc(N), Op0->getValueType(0), Op0, Op1);
  10388. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), ABD);
  10389. }
  10390. static SDValue performXorCombine(SDNode *N, SelectionDAG &DAG,
  10391. TargetLowering::DAGCombinerInfo &DCI,
  10392. const AArch64Subtarget *Subtarget) {
  10393. if (DCI.isBeforeLegalizeOps())
  10394. return SDValue();
  10395. return foldVectorXorShiftIntoCmp(N, DAG, Subtarget);
  10396. }
  10397. SDValue
  10398. AArch64TargetLowering::BuildSDIVPow2(SDNode *N, const APInt &Divisor,
  10399. SelectionDAG &DAG,
  10400. SmallVectorImpl<SDNode *> &Created) const {
  10401. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  10402. if (isIntDivCheap(N->getValueType(0), Attr))
  10403. return SDValue(N,0); // Lower SDIV as SDIV
  10404. // fold (sdiv X, pow2)
  10405. EVT VT = N->getValueType(0);
  10406. if ((VT != MVT::i32 && VT != MVT::i64) ||
  10407. !(Divisor.isPowerOf2() || (-Divisor).isPowerOf2()))
  10408. return SDValue();
  10409. SDLoc DL(N);
  10410. SDValue N0 = N->getOperand(0);
  10411. unsigned Lg2 = Divisor.countTrailingZeros();
  10412. SDValue Zero = DAG.getConstant(0, DL, VT);
  10413. SDValue Pow2MinusOne = DAG.getConstant((1ULL << Lg2) - 1, DL, VT);
  10414. // Add (N0 < 0) ? Pow2 - 1 : 0;
  10415. SDValue CCVal;
  10416. SDValue Cmp = getAArch64Cmp(N0, Zero, ISD::SETLT, CCVal, DAG, DL);
  10417. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Pow2MinusOne);
  10418. SDValue CSel = DAG.getNode(AArch64ISD::CSEL, DL, VT, Add, N0, CCVal, Cmp);
  10419. Created.push_back(Cmp.getNode());
  10420. Created.push_back(Add.getNode());
  10421. Created.push_back(CSel.getNode());
  10422. // Divide by pow2.
  10423. SDValue SRA =
  10424. DAG.getNode(ISD::SRA, DL, VT, CSel, DAG.getConstant(Lg2, DL, MVT::i64));
  10425. // If we're dividing by a positive value, we're done. Otherwise, we must
  10426. // negate the result.
  10427. if (Divisor.isNonNegative())
  10428. return SRA;
  10429. Created.push_back(SRA.getNode());
  10430. return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), SRA);
  10431. }
  10432. static bool IsSVECntIntrinsic(SDValue S) {
  10433. switch(getIntrinsicID(S.getNode())) {
  10434. default:
  10435. break;
  10436. case Intrinsic::aarch64_sve_cntb:
  10437. case Intrinsic::aarch64_sve_cnth:
  10438. case Intrinsic::aarch64_sve_cntw:
  10439. case Intrinsic::aarch64_sve_cntd:
  10440. return true;
  10441. }
  10442. return false;
  10443. }
  10444. /// Calculates what the pre-extend type is, based on the extension
  10445. /// operation node provided by \p Extend.
  10446. ///
  10447. /// In the case that \p Extend is a SIGN_EXTEND or a ZERO_EXTEND, the
  10448. /// pre-extend type is pulled directly from the operand, while other extend
  10449. /// operations need a bit more inspection to get this information.
  10450. ///
  10451. /// \param Extend The SDNode from the DAG that represents the extend operation
  10452. /// \param DAG The SelectionDAG hosting the \p Extend node
  10453. ///
  10454. /// \returns The type representing the \p Extend source type, or \p MVT::Other
  10455. /// if no valid type can be determined
  10456. static EVT calculatePreExtendType(SDValue Extend, SelectionDAG &DAG) {
  10457. switch (Extend.getOpcode()) {
  10458. case ISD::SIGN_EXTEND:
  10459. case ISD::ZERO_EXTEND:
  10460. return Extend.getOperand(0).getValueType();
  10461. case ISD::AssertSext:
  10462. case ISD::AssertZext:
  10463. case ISD::SIGN_EXTEND_INREG: {
  10464. VTSDNode *TypeNode = dyn_cast<VTSDNode>(Extend.getOperand(1));
  10465. if (!TypeNode)
  10466. return MVT::Other;
  10467. return TypeNode->getVT();
  10468. }
  10469. case ISD::AND: {
  10470. ConstantSDNode *Constant =
  10471. dyn_cast<ConstantSDNode>(Extend.getOperand(1).getNode());
  10472. if (!Constant)
  10473. return MVT::Other;
  10474. uint32_t Mask = Constant->getZExtValue();
  10475. if (Mask == UCHAR_MAX)
  10476. return MVT::i8;
  10477. else if (Mask == USHRT_MAX)
  10478. return MVT::i16;
  10479. else if (Mask == UINT_MAX)
  10480. return MVT::i32;
  10481. return MVT::Other;
  10482. }
  10483. default:
  10484. return MVT::Other;
  10485. }
  10486. llvm_unreachable("Code path unhandled in calculatePreExtendType!");
  10487. }
  10488. /// Combines a dup(sext/zext) node pattern into sext/zext(dup)
  10489. /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
  10490. static SDValue performCommonVectorExtendCombine(SDValue VectorShuffle,
  10491. SelectionDAG &DAG) {
  10492. ShuffleVectorSDNode *ShuffleNode =
  10493. dyn_cast<ShuffleVectorSDNode>(VectorShuffle.getNode());
  10494. if (!ShuffleNode)
  10495. return SDValue();
  10496. // Ensuring the mask is zero before continuing
  10497. if (!ShuffleNode->isSplat() || ShuffleNode->getSplatIndex() != 0)
  10498. return SDValue();
  10499. SDValue InsertVectorElt = VectorShuffle.getOperand(0);
  10500. if (InsertVectorElt.getOpcode() != ISD::INSERT_VECTOR_ELT)
  10501. return SDValue();
  10502. SDValue InsertLane = InsertVectorElt.getOperand(2);
  10503. ConstantSDNode *Constant = dyn_cast<ConstantSDNode>(InsertLane.getNode());
  10504. // Ensures the insert is inserting into lane 0
  10505. if (!Constant || Constant->getZExtValue() != 0)
  10506. return SDValue();
  10507. SDValue Extend = InsertVectorElt.getOperand(1);
  10508. unsigned ExtendOpcode = Extend.getOpcode();
  10509. bool IsSExt = ExtendOpcode == ISD::SIGN_EXTEND ||
  10510. ExtendOpcode == ISD::SIGN_EXTEND_INREG ||
  10511. ExtendOpcode == ISD::AssertSext;
  10512. if (!IsSExt && ExtendOpcode != ISD::ZERO_EXTEND &&
  10513. ExtendOpcode != ISD::AssertZext && ExtendOpcode != ISD::AND)
  10514. return SDValue();
  10515. EVT TargetType = VectorShuffle.getValueType();
  10516. EVT PreExtendType = calculatePreExtendType(Extend, DAG);
  10517. if ((TargetType != MVT::v8i16 && TargetType != MVT::v4i32 &&
  10518. TargetType != MVT::v2i64) ||
  10519. (PreExtendType == MVT::Other))
  10520. return SDValue();
  10521. // Restrict valid pre-extend data type
  10522. if (PreExtendType != MVT::i8 && PreExtendType != MVT::i16 &&
  10523. PreExtendType != MVT::i32)
  10524. return SDValue();
  10525. EVT PreExtendVT = TargetType.changeVectorElementType(PreExtendType);
  10526. if (PreExtendVT.getVectorElementCount() != TargetType.getVectorElementCount())
  10527. return SDValue();
  10528. if (TargetType.getScalarSizeInBits() != PreExtendVT.getScalarSizeInBits() * 2)
  10529. return SDValue();
  10530. SDLoc DL(VectorShuffle);
  10531. SDValue InsertVectorNode = DAG.getNode(
  10532. InsertVectorElt.getOpcode(), DL, PreExtendVT, DAG.getUNDEF(PreExtendVT),
  10533. DAG.getAnyExtOrTrunc(Extend.getOperand(0), DL, PreExtendType),
  10534. DAG.getConstant(0, DL, MVT::i64));
  10535. std::vector<int> ShuffleMask(TargetType.getVectorElementCount().getValue());
  10536. SDValue VectorShuffleNode =
  10537. DAG.getVectorShuffle(PreExtendVT, DL, InsertVectorNode,
  10538. DAG.getUNDEF(PreExtendVT), ShuffleMask);
  10539. SDValue ExtendNode = DAG.getNode(IsSExt ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND,
  10540. DL, TargetType, VectorShuffleNode);
  10541. return ExtendNode;
  10542. }
  10543. /// Combines a mul(dup(sext/zext)) node pattern into mul(sext/zext(dup))
  10544. /// making use of the vector SExt/ZExt rather than the scalar SExt/ZExt
  10545. static SDValue performMulVectorExtendCombine(SDNode *Mul, SelectionDAG &DAG) {
  10546. // If the value type isn't a vector, none of the operands are going to be dups
  10547. if (!Mul->getValueType(0).isVector())
  10548. return SDValue();
  10549. SDValue Op0 = performCommonVectorExtendCombine(Mul->getOperand(0), DAG);
  10550. SDValue Op1 = performCommonVectorExtendCombine(Mul->getOperand(1), DAG);
  10551. // Neither operands have been changed, don't make any further changes
  10552. if (!Op0 && !Op1)
  10553. return SDValue();
  10554. SDLoc DL(Mul);
  10555. return DAG.getNode(Mul->getOpcode(), DL, Mul->getValueType(0),
  10556. Op0 ? Op0 : Mul->getOperand(0),
  10557. Op1 ? Op1 : Mul->getOperand(1));
  10558. }
  10559. static SDValue performMulCombine(SDNode *N, SelectionDAG &DAG,
  10560. TargetLowering::DAGCombinerInfo &DCI,
  10561. const AArch64Subtarget *Subtarget) {
  10562. if (SDValue Ext = performMulVectorExtendCombine(N, DAG))
  10563. return Ext;
  10564. if (DCI.isBeforeLegalizeOps())
  10565. return SDValue();
  10566. // The below optimizations require a constant RHS.
  10567. if (!isa<ConstantSDNode>(N->getOperand(1)))
  10568. return SDValue();
  10569. SDValue N0 = N->getOperand(0);
  10570. ConstantSDNode *C = cast<ConstantSDNode>(N->getOperand(1));
  10571. const APInt &ConstValue = C->getAPIntValue();
  10572. // Allow the scaling to be folded into the `cnt` instruction by preventing
  10573. // the scaling to be obscured here. This makes it easier to pattern match.
  10574. if (IsSVECntIntrinsic(N0) ||
  10575. (N0->getOpcode() == ISD::TRUNCATE &&
  10576. (IsSVECntIntrinsic(N0->getOperand(0)))))
  10577. if (ConstValue.sge(1) && ConstValue.sle(16))
  10578. return SDValue();
  10579. // Multiplication of a power of two plus/minus one can be done more
  10580. // cheaply as as shift+add/sub. For now, this is true unilaterally. If
  10581. // future CPUs have a cheaper MADD instruction, this may need to be
  10582. // gated on a subtarget feature. For Cyclone, 32-bit MADD is 4 cycles and
  10583. // 64-bit is 5 cycles, so this is always a win.
  10584. // More aggressively, some multiplications N0 * C can be lowered to
  10585. // shift+add+shift if the constant C = A * B where A = 2^N + 1 and B = 2^M,
  10586. // e.g. 6=3*2=(2+1)*2.
  10587. // TODO: consider lowering more cases, e.g. C = 14, -6, -14 or even 45
  10588. // which equals to (1+2)*16-(1+2).
  10589. // TrailingZeroes is used to test if the mul can be lowered to
  10590. // shift+add+shift.
  10591. unsigned TrailingZeroes = ConstValue.countTrailingZeros();
  10592. if (TrailingZeroes) {
  10593. // Conservatively do not lower to shift+add+shift if the mul might be
  10594. // folded into smul or umul.
  10595. if (N0->hasOneUse() && (isSignExtended(N0.getNode(), DAG) ||
  10596. isZeroExtended(N0.getNode(), DAG)))
  10597. return SDValue();
  10598. // Conservatively do not lower to shift+add+shift if the mul might be
  10599. // folded into madd or msub.
  10600. if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ADD ||
  10601. N->use_begin()->getOpcode() == ISD::SUB))
  10602. return SDValue();
  10603. }
  10604. // Use ShiftedConstValue instead of ConstValue to support both shift+add/sub
  10605. // and shift+add+shift.
  10606. APInt ShiftedConstValue = ConstValue.ashr(TrailingZeroes);
  10607. unsigned ShiftAmt, AddSubOpc;
  10608. // Is the shifted value the LHS operand of the add/sub?
  10609. bool ShiftValUseIsN0 = true;
  10610. // Do we need to negate the result?
  10611. bool NegateResult = false;
  10612. if (ConstValue.isNonNegative()) {
  10613. // (mul x, 2^N + 1) => (add (shl x, N), x)
  10614. // (mul x, 2^N - 1) => (sub (shl x, N), x)
  10615. // (mul x, (2^N + 1) * 2^M) => (shl (add (shl x, N), x), M)
  10616. APInt SCVMinus1 = ShiftedConstValue - 1;
  10617. APInt CVPlus1 = ConstValue + 1;
  10618. if (SCVMinus1.isPowerOf2()) {
  10619. ShiftAmt = SCVMinus1.logBase2();
  10620. AddSubOpc = ISD::ADD;
  10621. } else if (CVPlus1.isPowerOf2()) {
  10622. ShiftAmt = CVPlus1.logBase2();
  10623. AddSubOpc = ISD::SUB;
  10624. } else
  10625. return SDValue();
  10626. } else {
  10627. // (mul x, -(2^N - 1)) => (sub x, (shl x, N))
  10628. // (mul x, -(2^N + 1)) => - (add (shl x, N), x)
  10629. APInt CVNegPlus1 = -ConstValue + 1;
  10630. APInt CVNegMinus1 = -ConstValue - 1;
  10631. if (CVNegPlus1.isPowerOf2()) {
  10632. ShiftAmt = CVNegPlus1.logBase2();
  10633. AddSubOpc = ISD::SUB;
  10634. ShiftValUseIsN0 = false;
  10635. } else if (CVNegMinus1.isPowerOf2()) {
  10636. ShiftAmt = CVNegMinus1.logBase2();
  10637. AddSubOpc = ISD::ADD;
  10638. NegateResult = true;
  10639. } else
  10640. return SDValue();
  10641. }
  10642. SDLoc DL(N);
  10643. EVT VT = N->getValueType(0);
  10644. SDValue ShiftedVal = DAG.getNode(ISD::SHL, DL, VT, N0,
  10645. DAG.getConstant(ShiftAmt, DL, MVT::i64));
  10646. SDValue AddSubN0 = ShiftValUseIsN0 ? ShiftedVal : N0;
  10647. SDValue AddSubN1 = ShiftValUseIsN0 ? N0 : ShiftedVal;
  10648. SDValue Res = DAG.getNode(AddSubOpc, DL, VT, AddSubN0, AddSubN1);
  10649. assert(!(NegateResult && TrailingZeroes) &&
  10650. "NegateResult and TrailingZeroes cannot both be true for now.");
  10651. // Negate the result.
  10652. if (NegateResult)
  10653. return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Res);
  10654. // Shift the result.
  10655. if (TrailingZeroes)
  10656. return DAG.getNode(ISD::SHL, DL, VT, Res,
  10657. DAG.getConstant(TrailingZeroes, DL, MVT::i64));
  10658. return Res;
  10659. }
  10660. static SDValue performVectorCompareAndMaskUnaryOpCombine(SDNode *N,
  10661. SelectionDAG &DAG) {
  10662. // Take advantage of vector comparisons producing 0 or -1 in each lane to
  10663. // optimize away operation when it's from a constant.
  10664. //
  10665. // The general transformation is:
  10666. // UNARYOP(AND(VECTOR_CMP(x,y), constant)) -->
  10667. // AND(VECTOR_CMP(x,y), constant2)
  10668. // constant2 = UNARYOP(constant)
  10669. // Early exit if this isn't a vector operation, the operand of the
  10670. // unary operation isn't a bitwise AND, or if the sizes of the operations
  10671. // aren't the same.
  10672. EVT VT = N->getValueType(0);
  10673. if (!VT.isVector() || N->getOperand(0)->getOpcode() != ISD::AND ||
  10674. N->getOperand(0)->getOperand(0)->getOpcode() != ISD::SETCC ||
  10675. VT.getSizeInBits() != N->getOperand(0)->getValueType(0).getSizeInBits())
  10676. return SDValue();
  10677. // Now check that the other operand of the AND is a constant. We could
  10678. // make the transformation for non-constant splats as well, but it's unclear
  10679. // that would be a benefit as it would not eliminate any operations, just
  10680. // perform one more step in scalar code before moving to the vector unit.
  10681. if (BuildVectorSDNode *BV =
  10682. dyn_cast<BuildVectorSDNode>(N->getOperand(0)->getOperand(1))) {
  10683. // Bail out if the vector isn't a constant.
  10684. if (!BV->isConstant())
  10685. return SDValue();
  10686. // Everything checks out. Build up the new and improved node.
  10687. SDLoc DL(N);
  10688. EVT IntVT = BV->getValueType(0);
  10689. // Create a new constant of the appropriate type for the transformed
  10690. // DAG.
  10691. SDValue SourceConst = DAG.getNode(N->getOpcode(), DL, VT, SDValue(BV, 0));
  10692. // The AND node needs bitcasts to/from an integer vector type around it.
  10693. SDValue MaskConst = DAG.getNode(ISD::BITCAST, DL, IntVT, SourceConst);
  10694. SDValue NewAnd = DAG.getNode(ISD::AND, DL, IntVT,
  10695. N->getOperand(0)->getOperand(0), MaskConst);
  10696. SDValue Res = DAG.getNode(ISD::BITCAST, DL, VT, NewAnd);
  10697. return Res;
  10698. }
  10699. return SDValue();
  10700. }
  10701. static SDValue performIntToFpCombine(SDNode *N, SelectionDAG &DAG,
  10702. const AArch64Subtarget *Subtarget) {
  10703. // First try to optimize away the conversion when it's conditionally from
  10704. // a constant. Vectors only.
  10705. if (SDValue Res = performVectorCompareAndMaskUnaryOpCombine(N, DAG))
  10706. return Res;
  10707. EVT VT = N->getValueType(0);
  10708. if (VT != MVT::f32 && VT != MVT::f64)
  10709. return SDValue();
  10710. // Only optimize when the source and destination types have the same width.
  10711. if (VT.getSizeInBits() != N->getOperand(0).getValueSizeInBits())
  10712. return SDValue();
  10713. // If the result of an integer load is only used by an integer-to-float
  10714. // conversion, use a fp load instead and a AdvSIMD scalar {S|U}CVTF instead.
  10715. // This eliminates an "integer-to-vector-move" UOP and improves throughput.
  10716. SDValue N0 = N->getOperand(0);
  10717. if (Subtarget->hasNEON() && ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
  10718. // Do not change the width of a volatile load.
  10719. !cast<LoadSDNode>(N0)->isVolatile()) {
  10720. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  10721. SDValue Load = DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
  10722. LN0->getPointerInfo(), LN0->getAlignment(),
  10723. LN0->getMemOperand()->getFlags());
  10724. // Make sure successors of the original load stay after it by updating them
  10725. // to use the new Chain.
  10726. DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), Load.getValue(1));
  10727. unsigned Opcode =
  10728. (N->getOpcode() == ISD::SINT_TO_FP) ? AArch64ISD::SITOF : AArch64ISD::UITOF;
  10729. return DAG.getNode(Opcode, SDLoc(N), VT, Load);
  10730. }
  10731. return SDValue();
  10732. }
  10733. /// Fold a floating-point multiply by power of two into floating-point to
  10734. /// fixed-point conversion.
  10735. static SDValue performFpToIntCombine(SDNode *N, SelectionDAG &DAG,
  10736. TargetLowering::DAGCombinerInfo &DCI,
  10737. const AArch64Subtarget *Subtarget) {
  10738. if (!Subtarget->hasNEON())
  10739. return SDValue();
  10740. if (!N->getValueType(0).isSimple())
  10741. return SDValue();
  10742. SDValue Op = N->getOperand(0);
  10743. if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
  10744. Op.getOpcode() != ISD::FMUL)
  10745. return SDValue();
  10746. SDValue ConstVec = Op->getOperand(1);
  10747. if (!isa<BuildVectorSDNode>(ConstVec))
  10748. return SDValue();
  10749. MVT FloatTy = Op.getSimpleValueType().getVectorElementType();
  10750. uint32_t FloatBits = FloatTy.getSizeInBits();
  10751. if (FloatBits != 32 && FloatBits != 64)
  10752. return SDValue();
  10753. MVT IntTy = N->getSimpleValueType(0).getVectorElementType();
  10754. uint32_t IntBits = IntTy.getSizeInBits();
  10755. if (IntBits != 16 && IntBits != 32 && IntBits != 64)
  10756. return SDValue();
  10757. // Avoid conversions where iN is larger than the float (e.g., float -> i64).
  10758. if (IntBits > FloatBits)
  10759. return SDValue();
  10760. BitVector UndefElements;
  10761. BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
  10762. int32_t Bits = IntBits == 64 ? 64 : 32;
  10763. int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, Bits + 1);
  10764. if (C == -1 || C == 0 || C > Bits)
  10765. return SDValue();
  10766. MVT ResTy;
  10767. unsigned NumLanes = Op.getValueType().getVectorNumElements();
  10768. switch (NumLanes) {
  10769. default:
  10770. return SDValue();
  10771. case 2:
  10772. ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
  10773. break;
  10774. case 4:
  10775. ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
  10776. break;
  10777. }
  10778. if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
  10779. return SDValue();
  10780. assert((ResTy != MVT::v4i64 || DCI.isBeforeLegalizeOps()) &&
  10781. "Illegal vector type after legalization");
  10782. SDLoc DL(N);
  10783. bool IsSigned = N->getOpcode() == ISD::FP_TO_SINT;
  10784. unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfp2fxs
  10785. : Intrinsic::aarch64_neon_vcvtfp2fxu;
  10786. SDValue FixConv =
  10787. DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, ResTy,
  10788. DAG.getConstant(IntrinsicOpcode, DL, MVT::i32),
  10789. Op->getOperand(0), DAG.getConstant(C, DL, MVT::i32));
  10790. // We can handle smaller integers by generating an extra trunc.
  10791. if (IntBits < FloatBits)
  10792. FixConv = DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), FixConv);
  10793. return FixConv;
  10794. }
  10795. /// Fold a floating-point divide by power of two into fixed-point to
  10796. /// floating-point conversion.
  10797. static SDValue performFDivCombine(SDNode *N, SelectionDAG &DAG,
  10798. TargetLowering::DAGCombinerInfo &DCI,
  10799. const AArch64Subtarget *Subtarget) {
  10800. if (!Subtarget->hasNEON())
  10801. return SDValue();
  10802. SDValue Op = N->getOperand(0);
  10803. unsigned Opc = Op->getOpcode();
  10804. if (!Op.getValueType().isVector() || !Op.getValueType().isSimple() ||
  10805. !Op.getOperand(0).getValueType().isSimple() ||
  10806. (Opc != ISD::SINT_TO_FP && Opc != ISD::UINT_TO_FP))
  10807. return SDValue();
  10808. SDValue ConstVec = N->getOperand(1);
  10809. if (!isa<BuildVectorSDNode>(ConstVec))
  10810. return SDValue();
  10811. MVT IntTy = Op.getOperand(0).getSimpleValueType().getVectorElementType();
  10812. int32_t IntBits = IntTy.getSizeInBits();
  10813. if (IntBits != 16 && IntBits != 32 && IntBits != 64)
  10814. return SDValue();
  10815. MVT FloatTy = N->getSimpleValueType(0).getVectorElementType();
  10816. int32_t FloatBits = FloatTy.getSizeInBits();
  10817. if (FloatBits != 32 && FloatBits != 64)
  10818. return SDValue();
  10819. // Avoid conversions where iN is larger than the float (e.g., i64 -> float).
  10820. if (IntBits > FloatBits)
  10821. return SDValue();
  10822. BitVector UndefElements;
  10823. BuildVectorSDNode *BV = cast<BuildVectorSDNode>(ConstVec);
  10824. int32_t C = BV->getConstantFPSplatPow2ToLog2Int(&UndefElements, FloatBits + 1);
  10825. if (C == -1 || C == 0 || C > FloatBits)
  10826. return SDValue();
  10827. MVT ResTy;
  10828. unsigned NumLanes = Op.getValueType().getVectorNumElements();
  10829. switch (NumLanes) {
  10830. default:
  10831. return SDValue();
  10832. case 2:
  10833. ResTy = FloatBits == 32 ? MVT::v2i32 : MVT::v2i64;
  10834. break;
  10835. case 4:
  10836. ResTy = FloatBits == 32 ? MVT::v4i32 : MVT::v4i64;
  10837. break;
  10838. }
  10839. if (ResTy == MVT::v4i64 && DCI.isBeforeLegalizeOps())
  10840. return SDValue();
  10841. SDLoc DL(N);
  10842. SDValue ConvInput = Op.getOperand(0);
  10843. bool IsSigned = Opc == ISD::SINT_TO_FP;
  10844. if (IntBits < FloatBits)
  10845. ConvInput = DAG.getNode(IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND, DL,
  10846. ResTy, ConvInput);
  10847. unsigned IntrinsicOpcode = IsSigned ? Intrinsic::aarch64_neon_vcvtfxs2fp
  10848. : Intrinsic::aarch64_neon_vcvtfxu2fp;
  10849. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, Op.getValueType(),
  10850. DAG.getConstant(IntrinsicOpcode, DL, MVT::i32), ConvInput,
  10851. DAG.getConstant(C, DL, MVT::i32));
  10852. }
  10853. /// An EXTR instruction is made up of two shifts, ORed together. This helper
  10854. /// searches for and classifies those shifts.
  10855. static bool findEXTRHalf(SDValue N, SDValue &Src, uint32_t &ShiftAmount,
  10856. bool &FromHi) {
  10857. if (N.getOpcode() == ISD::SHL)
  10858. FromHi = false;
  10859. else if (N.getOpcode() == ISD::SRL)
  10860. FromHi = true;
  10861. else
  10862. return false;
  10863. if (!isa<ConstantSDNode>(N.getOperand(1)))
  10864. return false;
  10865. ShiftAmount = N->getConstantOperandVal(1);
  10866. Src = N->getOperand(0);
  10867. return true;
  10868. }
  10869. /// EXTR instruction extracts a contiguous chunk of bits from two existing
  10870. /// registers viewed as a high/low pair. This function looks for the pattern:
  10871. /// <tt>(or (shl VAL1, \#N), (srl VAL2, \#RegWidth-N))</tt> and replaces it
  10872. /// with an EXTR. Can't quite be done in TableGen because the two immediates
  10873. /// aren't independent.
  10874. static SDValue tryCombineToEXTR(SDNode *N,
  10875. TargetLowering::DAGCombinerInfo &DCI) {
  10876. SelectionDAG &DAG = DCI.DAG;
  10877. SDLoc DL(N);
  10878. EVT VT = N->getValueType(0);
  10879. assert(N->getOpcode() == ISD::OR && "Unexpected root");
  10880. if (VT != MVT::i32 && VT != MVT::i64)
  10881. return SDValue();
  10882. SDValue LHS;
  10883. uint32_t ShiftLHS = 0;
  10884. bool LHSFromHi = false;
  10885. if (!findEXTRHalf(N->getOperand(0), LHS, ShiftLHS, LHSFromHi))
  10886. return SDValue();
  10887. SDValue RHS;
  10888. uint32_t ShiftRHS = 0;
  10889. bool RHSFromHi = false;
  10890. if (!findEXTRHalf(N->getOperand(1), RHS, ShiftRHS, RHSFromHi))
  10891. return SDValue();
  10892. // If they're both trying to come from the high part of the register, they're
  10893. // not really an EXTR.
  10894. if (LHSFromHi == RHSFromHi)
  10895. return SDValue();
  10896. if (ShiftLHS + ShiftRHS != VT.getSizeInBits())
  10897. return SDValue();
  10898. if (LHSFromHi) {
  10899. std::swap(LHS, RHS);
  10900. std::swap(ShiftLHS, ShiftRHS);
  10901. }
  10902. return DAG.getNode(AArch64ISD::EXTR, DL, VT, LHS, RHS,
  10903. DAG.getConstant(ShiftRHS, DL, MVT::i64));
  10904. }
  10905. static SDValue tryCombineToBSL(SDNode *N,
  10906. TargetLowering::DAGCombinerInfo &DCI) {
  10907. EVT VT = N->getValueType(0);
  10908. SelectionDAG &DAG = DCI.DAG;
  10909. SDLoc DL(N);
  10910. if (!VT.isVector())
  10911. return SDValue();
  10912. SDValue N0 = N->getOperand(0);
  10913. if (N0.getOpcode() != ISD::AND)
  10914. return SDValue();
  10915. SDValue N1 = N->getOperand(1);
  10916. if (N1.getOpcode() != ISD::AND)
  10917. return SDValue();
  10918. // We only have to look for constant vectors here since the general, variable
  10919. // case can be handled in TableGen.
  10920. unsigned Bits = VT.getScalarSizeInBits();
  10921. uint64_t BitMask = Bits == 64 ? -1ULL : ((1ULL << Bits) - 1);
  10922. for (int i = 1; i >= 0; --i)
  10923. for (int j = 1; j >= 0; --j) {
  10924. BuildVectorSDNode *BVN0 = dyn_cast<BuildVectorSDNode>(N0->getOperand(i));
  10925. BuildVectorSDNode *BVN1 = dyn_cast<BuildVectorSDNode>(N1->getOperand(j));
  10926. if (!BVN0 || !BVN1)
  10927. continue;
  10928. bool FoundMatch = true;
  10929. for (unsigned k = 0; k < VT.getVectorNumElements(); ++k) {
  10930. ConstantSDNode *CN0 = dyn_cast<ConstantSDNode>(BVN0->getOperand(k));
  10931. ConstantSDNode *CN1 = dyn_cast<ConstantSDNode>(BVN1->getOperand(k));
  10932. if (!CN0 || !CN1 ||
  10933. CN0->getZExtValue() != (BitMask & ~CN1->getZExtValue())) {
  10934. FoundMatch = false;
  10935. break;
  10936. }
  10937. }
  10938. if (FoundMatch)
  10939. return DAG.getNode(AArch64ISD::BSP, DL, VT, SDValue(BVN0, 0),
  10940. N0->getOperand(1 - i), N1->getOperand(1 - j));
  10941. }
  10942. return SDValue();
  10943. }
  10944. static SDValue performORCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
  10945. const AArch64Subtarget *Subtarget) {
  10946. // Attempt to form an EXTR from (or (shl VAL1, #N), (srl VAL2, #RegWidth-N))
  10947. SelectionDAG &DAG = DCI.DAG;
  10948. EVT VT = N->getValueType(0);
  10949. if (!DAG.getTargetLoweringInfo().isTypeLegal(VT))
  10950. return SDValue();
  10951. if (SDValue Res = tryCombineToEXTR(N, DCI))
  10952. return Res;
  10953. if (SDValue Res = tryCombineToBSL(N, DCI))
  10954. return Res;
  10955. return SDValue();
  10956. }
  10957. static bool isConstantSplatVectorMaskForType(SDNode *N, EVT MemVT) {
  10958. if (!MemVT.getVectorElementType().isSimple())
  10959. return false;
  10960. uint64_t MaskForTy = 0ull;
  10961. switch (MemVT.getVectorElementType().getSimpleVT().SimpleTy) {
  10962. case MVT::i8:
  10963. MaskForTy = 0xffull;
  10964. break;
  10965. case MVT::i16:
  10966. MaskForTy = 0xffffull;
  10967. break;
  10968. case MVT::i32:
  10969. MaskForTy = 0xffffffffull;
  10970. break;
  10971. default:
  10972. return false;
  10973. break;
  10974. }
  10975. if (N->getOpcode() == AArch64ISD::DUP || N->getOpcode() == ISD::SPLAT_VECTOR)
  10976. if (auto *Op0 = dyn_cast<ConstantSDNode>(N->getOperand(0)))
  10977. return Op0->getAPIntValue().getLimitedValue() == MaskForTy;
  10978. return false;
  10979. }
  10980. static SDValue performSVEAndCombine(SDNode *N,
  10981. TargetLowering::DAGCombinerInfo &DCI) {
  10982. if (DCI.isBeforeLegalizeOps())
  10983. return SDValue();
  10984. SelectionDAG &DAG = DCI.DAG;
  10985. SDValue Src = N->getOperand(0);
  10986. unsigned Opc = Src->getOpcode();
  10987. // Zero/any extend of an unsigned unpack
  10988. if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
  10989. SDValue UnpkOp = Src->getOperand(0);
  10990. SDValue Dup = N->getOperand(1);
  10991. if (Dup.getOpcode() != AArch64ISD::DUP)
  10992. return SDValue();
  10993. SDLoc DL(N);
  10994. ConstantSDNode *C = dyn_cast<ConstantSDNode>(Dup->getOperand(0));
  10995. uint64_t ExtVal = C->getZExtValue();
  10996. // If the mask is fully covered by the unpack, we don't need to push
  10997. // a new AND onto the operand
  10998. EVT EltTy = UnpkOp->getValueType(0).getVectorElementType();
  10999. if ((ExtVal == 0xFF && EltTy == MVT::i8) ||
  11000. (ExtVal == 0xFFFF && EltTy == MVT::i16) ||
  11001. (ExtVal == 0xFFFFFFFF && EltTy == MVT::i32))
  11002. return Src;
  11003. // Truncate to prevent a DUP with an over wide constant
  11004. APInt Mask = C->getAPIntValue().trunc(EltTy.getSizeInBits());
  11005. // Otherwise, make sure we propagate the AND to the operand
  11006. // of the unpack
  11007. Dup = DAG.getNode(AArch64ISD::DUP, DL,
  11008. UnpkOp->getValueType(0),
  11009. DAG.getConstant(Mask.zextOrTrunc(32), DL, MVT::i32));
  11010. SDValue And = DAG.getNode(ISD::AND, DL,
  11011. UnpkOp->getValueType(0), UnpkOp, Dup);
  11012. return DAG.getNode(Opc, DL, N->getValueType(0), And);
  11013. }
  11014. if (!EnableCombineMGatherIntrinsics)
  11015. return SDValue();
  11016. SDValue Mask = N->getOperand(1);
  11017. if (!Src.hasOneUse())
  11018. return SDValue();
  11019. EVT MemVT;
  11020. // SVE load instructions perform an implicit zero-extend, which makes them
  11021. // perfect candidates for combining.
  11022. switch (Opc) {
  11023. case AArch64ISD::LD1_MERGE_ZERO:
  11024. case AArch64ISD::LDNF1_MERGE_ZERO:
  11025. case AArch64ISD::LDFF1_MERGE_ZERO:
  11026. MemVT = cast<VTSDNode>(Src->getOperand(3))->getVT();
  11027. break;
  11028. case AArch64ISD::GLD1_MERGE_ZERO:
  11029. case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
  11030. case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
  11031. case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
  11032. case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
  11033. case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
  11034. case AArch64ISD::GLD1_IMM_MERGE_ZERO:
  11035. case AArch64ISD::GLDFF1_MERGE_ZERO:
  11036. case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
  11037. case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
  11038. case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
  11039. case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
  11040. case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
  11041. case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
  11042. case AArch64ISD::GLDNT1_MERGE_ZERO:
  11043. MemVT = cast<VTSDNode>(Src->getOperand(4))->getVT();
  11044. break;
  11045. default:
  11046. return SDValue();
  11047. }
  11048. if (isConstantSplatVectorMaskForType(Mask.getNode(), MemVT))
  11049. return Src;
  11050. return SDValue();
  11051. }
  11052. static SDValue performANDCombine(SDNode *N,
  11053. TargetLowering::DAGCombinerInfo &DCI) {
  11054. SelectionDAG &DAG = DCI.DAG;
  11055. SDValue LHS = N->getOperand(0);
  11056. EVT VT = N->getValueType(0);
  11057. if (!VT.isVector() || !DAG.getTargetLoweringInfo().isTypeLegal(VT))
  11058. return SDValue();
  11059. if (VT.isScalableVector())
  11060. return performSVEAndCombine(N, DCI);
  11061. // The combining code below works only for NEON vectors. In particular, it
  11062. // does not work for SVE when dealing with vectors wider than 128 bits.
  11063. if (!(VT.is64BitVector() || VT.is128BitVector()))
  11064. return SDValue();
  11065. BuildVectorSDNode *BVN =
  11066. dyn_cast<BuildVectorSDNode>(N->getOperand(1).getNode());
  11067. if (!BVN)
  11068. return SDValue();
  11069. // AND does not accept an immediate, so check if we can use a BIC immediate
  11070. // instruction instead. We do this here instead of using a (and x, (mvni imm))
  11071. // pattern in isel, because some immediates may be lowered to the preferred
  11072. // (and x, (movi imm)) form, even though an mvni representation also exists.
  11073. APInt DefBits(VT.getSizeInBits(), 0);
  11074. APInt UndefBits(VT.getSizeInBits(), 0);
  11075. if (resolveBuildVector(BVN, DefBits, UndefBits)) {
  11076. SDValue NewOp;
  11077. DefBits = ~DefBits;
  11078. if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
  11079. DefBits, &LHS)) ||
  11080. (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
  11081. DefBits, &LHS)))
  11082. return NewOp;
  11083. UndefBits = ~UndefBits;
  11084. if ((NewOp = tryAdvSIMDModImm32(AArch64ISD::BICi, SDValue(N, 0), DAG,
  11085. UndefBits, &LHS)) ||
  11086. (NewOp = tryAdvSIMDModImm16(AArch64ISD::BICi, SDValue(N, 0), DAG,
  11087. UndefBits, &LHS)))
  11088. return NewOp;
  11089. }
  11090. return SDValue();
  11091. }
  11092. static SDValue performSRLCombine(SDNode *N,
  11093. TargetLowering::DAGCombinerInfo &DCI) {
  11094. SelectionDAG &DAG = DCI.DAG;
  11095. EVT VT = N->getValueType(0);
  11096. if (VT != MVT::i32 && VT != MVT::i64)
  11097. return SDValue();
  11098. // Canonicalize (srl (bswap i32 x), 16) to (rotr (bswap i32 x), 16), if the
  11099. // high 16-bits of x are zero. Similarly, canonicalize (srl (bswap i64 x), 32)
  11100. // to (rotr (bswap i64 x), 32), if the high 32-bits of x are zero.
  11101. SDValue N0 = N->getOperand(0);
  11102. if (N0.getOpcode() == ISD::BSWAP) {
  11103. SDLoc DL(N);
  11104. SDValue N1 = N->getOperand(1);
  11105. SDValue N00 = N0.getOperand(0);
  11106. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
  11107. uint64_t ShiftAmt = C->getZExtValue();
  11108. if (VT == MVT::i32 && ShiftAmt == 16 &&
  11109. DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(32, 16)))
  11110. return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
  11111. if (VT == MVT::i64 && ShiftAmt == 32 &&
  11112. DAG.MaskedValueIsZero(N00, APInt::getHighBitsSet(64, 32)))
  11113. return DAG.getNode(ISD::ROTR, DL, VT, N0, N1);
  11114. }
  11115. }
  11116. return SDValue();
  11117. }
  11118. // Attempt to form urhadd(OpA, OpB) from
  11119. // truncate(vlshr(sub(zext(OpB), xor(zext(OpA), Ones(ElemSizeInBits))), 1))
  11120. // or uhadd(OpA, OpB) from truncate(vlshr(add(zext(OpA), zext(OpB)), 1)).
  11121. // The original form of the first expression is
  11122. // truncate(srl(add(zext(OpB), add(zext(OpA), 1)), 1)) and the
  11123. // (OpA + OpB + 1) subexpression will have been changed to (OpB - (~OpA)).
  11124. // Before this function is called the srl will have been lowered to
  11125. // AArch64ISD::VLSHR.
  11126. // This pass can also recognize signed variants of the patterns that use sign
  11127. // extension instead of zero extension and form a srhadd(OpA, OpB) or a
  11128. // shadd(OpA, OpB) from them.
  11129. static SDValue
  11130. performVectorTruncateCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
  11131. SelectionDAG &DAG) {
  11132. EVT VT = N->getValueType(0);
  11133. // Since we are looking for a right shift by a constant value of 1 and we are
  11134. // operating on types at least 16 bits in length (sign/zero extended OpA and
  11135. // OpB, which are at least 8 bits), it follows that the truncate will always
  11136. // discard the shifted-in bit and therefore the right shift will be logical
  11137. // regardless of the signedness of OpA and OpB.
  11138. SDValue Shift = N->getOperand(0);
  11139. if (Shift.getOpcode() != AArch64ISD::VLSHR)
  11140. return SDValue();
  11141. // Is the right shift using an immediate value of 1?
  11142. uint64_t ShiftAmount = Shift.getConstantOperandVal(1);
  11143. if (ShiftAmount != 1)
  11144. return SDValue();
  11145. SDValue ExtendOpA, ExtendOpB;
  11146. SDValue ShiftOp0 = Shift.getOperand(0);
  11147. unsigned ShiftOp0Opc = ShiftOp0.getOpcode();
  11148. if (ShiftOp0Opc == ISD::SUB) {
  11149. SDValue Xor = ShiftOp0.getOperand(1);
  11150. if (Xor.getOpcode() != ISD::XOR)
  11151. return SDValue();
  11152. // Is the XOR using a constant amount of all ones in the right hand side?
  11153. uint64_t C;
  11154. if (!isAllConstantBuildVector(Xor.getOperand(1), C))
  11155. return SDValue();
  11156. unsigned ElemSizeInBits = VT.getScalarSizeInBits();
  11157. APInt CAsAPInt(ElemSizeInBits, C);
  11158. if (CAsAPInt != APInt::getAllOnesValue(ElemSizeInBits))
  11159. return SDValue();
  11160. ExtendOpA = Xor.getOperand(0);
  11161. ExtendOpB = ShiftOp0.getOperand(0);
  11162. } else if (ShiftOp0Opc == ISD::ADD) {
  11163. ExtendOpA = ShiftOp0.getOperand(0);
  11164. ExtendOpB = ShiftOp0.getOperand(1);
  11165. } else
  11166. return SDValue();
  11167. unsigned ExtendOpAOpc = ExtendOpA.getOpcode();
  11168. unsigned ExtendOpBOpc = ExtendOpB.getOpcode();
  11169. if (!(ExtendOpAOpc == ExtendOpBOpc &&
  11170. (ExtendOpAOpc == ISD::ZERO_EXTEND || ExtendOpAOpc == ISD::SIGN_EXTEND)))
  11171. return SDValue();
  11172. // Is the result of the right shift being truncated to the same value type as
  11173. // the original operands, OpA and OpB?
  11174. SDValue OpA = ExtendOpA.getOperand(0);
  11175. SDValue OpB = ExtendOpB.getOperand(0);
  11176. EVT OpAVT = OpA.getValueType();
  11177. assert(ExtendOpA.getValueType() == ExtendOpB.getValueType());
  11178. if (!(VT == OpAVT && OpAVT == OpB.getValueType()))
  11179. return SDValue();
  11180. SDLoc DL(N);
  11181. bool IsSignExtend = ExtendOpAOpc == ISD::SIGN_EXTEND;
  11182. bool IsRHADD = ShiftOp0Opc == ISD::SUB;
  11183. unsigned HADDOpc = IsSignExtend
  11184. ? (IsRHADD ? AArch64ISD::SRHADD : AArch64ISD::SHADD)
  11185. : (IsRHADD ? AArch64ISD::URHADD : AArch64ISD::UHADD);
  11186. SDValue ResultHADD = DAG.getNode(HADDOpc, DL, VT, OpA, OpB);
  11187. return ResultHADD;
  11188. }
  11189. static bool hasPairwiseAdd(unsigned Opcode, EVT VT, bool FullFP16) {
  11190. switch (Opcode) {
  11191. case ISD::FADD:
  11192. return (FullFP16 && VT == MVT::f16) || VT == MVT::f32 || VT == MVT::f64;
  11193. case ISD::ADD:
  11194. return VT == MVT::i64;
  11195. default:
  11196. return false;
  11197. }
  11198. }
  11199. static SDValue performExtractVectorEltCombine(SDNode *N, SelectionDAG &DAG) {
  11200. SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
  11201. ConstantSDNode *ConstantN1 = dyn_cast<ConstantSDNode>(N1);
  11202. EVT VT = N->getValueType(0);
  11203. const bool FullFP16 =
  11204. static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasFullFP16();
  11205. // Rewrite for pairwise fadd pattern
  11206. // (f32 (extract_vector_elt
  11207. // (fadd (vXf32 Other)
  11208. // (vector_shuffle (vXf32 Other) undef <1,X,...> )) 0))
  11209. // ->
  11210. // (f32 (fadd (extract_vector_elt (vXf32 Other) 0)
  11211. // (extract_vector_elt (vXf32 Other) 1))
  11212. if (ConstantN1 && ConstantN1->getZExtValue() == 0 &&
  11213. hasPairwiseAdd(N0->getOpcode(), VT, FullFP16)) {
  11214. SDLoc DL(N0);
  11215. SDValue N00 = N0->getOperand(0);
  11216. SDValue N01 = N0->getOperand(1);
  11217. ShuffleVectorSDNode *Shuffle = dyn_cast<ShuffleVectorSDNode>(N01);
  11218. SDValue Other = N00;
  11219. // And handle the commutative case.
  11220. if (!Shuffle) {
  11221. Shuffle = dyn_cast<ShuffleVectorSDNode>(N00);
  11222. Other = N01;
  11223. }
  11224. if (Shuffle && Shuffle->getMaskElt(0) == 1 &&
  11225. Other == Shuffle->getOperand(0)) {
  11226. return DAG.getNode(N0->getOpcode(), DL, VT,
  11227. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
  11228. DAG.getConstant(0, DL, MVT::i64)),
  11229. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Other,
  11230. DAG.getConstant(1, DL, MVT::i64)));
  11231. }
  11232. }
  11233. return SDValue();
  11234. }
  11235. static SDValue performConcatVectorsCombine(SDNode *N,
  11236. TargetLowering::DAGCombinerInfo &DCI,
  11237. SelectionDAG &DAG) {
  11238. SDLoc dl(N);
  11239. EVT VT = N->getValueType(0);
  11240. SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
  11241. unsigned N0Opc = N0->getOpcode(), N1Opc = N1->getOpcode();
  11242. // Optimize concat_vectors of truncated vectors, where the intermediate
  11243. // type is illegal, to avoid said illegality, e.g.,
  11244. // (v4i16 (concat_vectors (v2i16 (truncate (v2i64))),
  11245. // (v2i16 (truncate (v2i64)))))
  11246. // ->
  11247. // (v4i16 (truncate (vector_shuffle (v4i32 (bitcast (v2i64))),
  11248. // (v4i32 (bitcast (v2i64))),
  11249. // <0, 2, 4, 6>)))
  11250. // This isn't really target-specific, but ISD::TRUNCATE legality isn't keyed
  11251. // on both input and result type, so we might generate worse code.
  11252. // On AArch64 we know it's fine for v2i64->v4i16 and v4i32->v8i8.
  11253. if (N->getNumOperands() == 2 && N0Opc == ISD::TRUNCATE &&
  11254. N1Opc == ISD::TRUNCATE) {
  11255. SDValue N00 = N0->getOperand(0);
  11256. SDValue N10 = N1->getOperand(0);
  11257. EVT N00VT = N00.getValueType();
  11258. if (N00VT == N10.getValueType() &&
  11259. (N00VT == MVT::v2i64 || N00VT == MVT::v4i32) &&
  11260. N00VT.getScalarSizeInBits() == 4 * VT.getScalarSizeInBits()) {
  11261. MVT MidVT = (N00VT == MVT::v2i64 ? MVT::v4i32 : MVT::v8i16);
  11262. SmallVector<int, 8> Mask(MidVT.getVectorNumElements());
  11263. for (size_t i = 0; i < Mask.size(); ++i)
  11264. Mask[i] = i * 2;
  11265. return DAG.getNode(ISD::TRUNCATE, dl, VT,
  11266. DAG.getVectorShuffle(
  11267. MidVT, dl,
  11268. DAG.getNode(ISD::BITCAST, dl, MidVT, N00),
  11269. DAG.getNode(ISD::BITCAST, dl, MidVT, N10), Mask));
  11270. }
  11271. }
  11272. // Wait 'til after everything is legalized to try this. That way we have
  11273. // legal vector types and such.
  11274. if (DCI.isBeforeLegalizeOps())
  11275. return SDValue();
  11276. // Optimise concat_vectors of two [us]rhadds or [us]hadds that use extracted
  11277. // subvectors from the same original vectors. Combine these into a single
  11278. // [us]rhadd or [us]hadd that operates on the two original vectors. Example:
  11279. // (v16i8 (concat_vectors (v8i8 (urhadd (extract_subvector (v16i8 OpA, <0>),
  11280. // extract_subvector (v16i8 OpB,
  11281. // <0>))),
  11282. // (v8i8 (urhadd (extract_subvector (v16i8 OpA, <8>),
  11283. // extract_subvector (v16i8 OpB,
  11284. // <8>)))))
  11285. // ->
  11286. // (v16i8(urhadd(v16i8 OpA, v16i8 OpB)))
  11287. if (N->getNumOperands() == 2 && N0Opc == N1Opc &&
  11288. (N0Opc == AArch64ISD::URHADD || N0Opc == AArch64ISD::SRHADD ||
  11289. N0Opc == AArch64ISD::UHADD || N0Opc == AArch64ISD::SHADD)) {
  11290. SDValue N00 = N0->getOperand(0);
  11291. SDValue N01 = N0->getOperand(1);
  11292. SDValue N10 = N1->getOperand(0);
  11293. SDValue N11 = N1->getOperand(1);
  11294. EVT N00VT = N00.getValueType();
  11295. EVT N10VT = N10.getValueType();
  11296. if (N00->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  11297. N01->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  11298. N10->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  11299. N11->getOpcode() == ISD::EXTRACT_SUBVECTOR && N00VT == N10VT) {
  11300. SDValue N00Source = N00->getOperand(0);
  11301. SDValue N01Source = N01->getOperand(0);
  11302. SDValue N10Source = N10->getOperand(0);
  11303. SDValue N11Source = N11->getOperand(0);
  11304. if (N00Source == N10Source && N01Source == N11Source &&
  11305. N00Source.getValueType() == VT && N01Source.getValueType() == VT) {
  11306. assert(N0.getValueType() == N1.getValueType());
  11307. uint64_t N00Index = N00.getConstantOperandVal(1);
  11308. uint64_t N01Index = N01.getConstantOperandVal(1);
  11309. uint64_t N10Index = N10.getConstantOperandVal(1);
  11310. uint64_t N11Index = N11.getConstantOperandVal(1);
  11311. if (N00Index == N01Index && N10Index == N11Index && N00Index == 0 &&
  11312. N10Index == N00VT.getVectorNumElements())
  11313. return DAG.getNode(N0Opc, dl, VT, N00Source, N01Source);
  11314. }
  11315. }
  11316. }
  11317. // If we see a (concat_vectors (v1x64 A), (v1x64 A)) it's really a vector
  11318. // splat. The indexed instructions are going to be expecting a DUPLANE64, so
  11319. // canonicalise to that.
  11320. if (N0 == N1 && VT.getVectorNumElements() == 2) {
  11321. assert(VT.getScalarSizeInBits() == 64);
  11322. return DAG.getNode(AArch64ISD::DUPLANE64, dl, VT, WidenVector(N0, DAG),
  11323. DAG.getConstant(0, dl, MVT::i64));
  11324. }
  11325. // Canonicalise concat_vectors so that the right-hand vector has as few
  11326. // bit-casts as possible before its real operation. The primary matching
  11327. // destination for these operations will be the narrowing "2" instructions,
  11328. // which depend on the operation being performed on this right-hand vector.
  11329. // For example,
  11330. // (concat_vectors LHS, (v1i64 (bitconvert (v4i16 RHS))))
  11331. // becomes
  11332. // (bitconvert (concat_vectors (v4i16 (bitconvert LHS)), RHS))
  11333. if (N1Opc != ISD::BITCAST)
  11334. return SDValue();
  11335. SDValue RHS = N1->getOperand(0);
  11336. MVT RHSTy = RHS.getValueType().getSimpleVT();
  11337. // If the RHS is not a vector, this is not the pattern we're looking for.
  11338. if (!RHSTy.isVector())
  11339. return SDValue();
  11340. LLVM_DEBUG(
  11341. dbgs() << "aarch64-lower: concat_vectors bitcast simplification\n");
  11342. MVT ConcatTy = MVT::getVectorVT(RHSTy.getVectorElementType(),
  11343. RHSTy.getVectorNumElements() * 2);
  11344. return DAG.getNode(ISD::BITCAST, dl, VT,
  11345. DAG.getNode(ISD::CONCAT_VECTORS, dl, ConcatTy,
  11346. DAG.getNode(ISD::BITCAST, dl, RHSTy, N0),
  11347. RHS));
  11348. }
  11349. static SDValue tryCombineFixedPointConvert(SDNode *N,
  11350. TargetLowering::DAGCombinerInfo &DCI,
  11351. SelectionDAG &DAG) {
  11352. // Wait until after everything is legalized to try this. That way we have
  11353. // legal vector types and such.
  11354. if (DCI.isBeforeLegalizeOps())
  11355. return SDValue();
  11356. // Transform a scalar conversion of a value from a lane extract into a
  11357. // lane extract of a vector conversion. E.g., from foo1 to foo2:
  11358. // double foo1(int64x2_t a) { return vcvtd_n_f64_s64(a[1], 9); }
  11359. // double foo2(int64x2_t a) { return vcvtq_n_f64_s64(a, 9)[1]; }
  11360. //
  11361. // The second form interacts better with instruction selection and the
  11362. // register allocator to avoid cross-class register copies that aren't
  11363. // coalescable due to a lane reference.
  11364. // Check the operand and see if it originates from a lane extract.
  11365. SDValue Op1 = N->getOperand(1);
  11366. if (Op1.getOpcode() == ISD::EXTRACT_VECTOR_ELT) {
  11367. // Yep, no additional predication needed. Perform the transform.
  11368. SDValue IID = N->getOperand(0);
  11369. SDValue Shift = N->getOperand(2);
  11370. SDValue Vec = Op1.getOperand(0);
  11371. SDValue Lane = Op1.getOperand(1);
  11372. EVT ResTy = N->getValueType(0);
  11373. EVT VecResTy;
  11374. SDLoc DL(N);
  11375. // The vector width should be 128 bits by the time we get here, even
  11376. // if it started as 64 bits (the extract_vector handling will have
  11377. // done so).
  11378. assert(Vec.getValueSizeInBits() == 128 &&
  11379. "unexpected vector size on extract_vector_elt!");
  11380. if (Vec.getValueType() == MVT::v4i32)
  11381. VecResTy = MVT::v4f32;
  11382. else if (Vec.getValueType() == MVT::v2i64)
  11383. VecResTy = MVT::v2f64;
  11384. else
  11385. llvm_unreachable("unexpected vector type!");
  11386. SDValue Convert =
  11387. DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, VecResTy, IID, Vec, Shift);
  11388. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResTy, Convert, Lane);
  11389. }
  11390. return SDValue();
  11391. }
  11392. // AArch64 high-vector "long" operations are formed by performing the non-high
  11393. // version on an extract_subvector of each operand which gets the high half:
  11394. //
  11395. // (longop2 LHS, RHS) == (longop (extract_high LHS), (extract_high RHS))
  11396. //
  11397. // However, there are cases which don't have an extract_high explicitly, but
  11398. // have another operation that can be made compatible with one for free. For
  11399. // example:
  11400. //
  11401. // (dupv64 scalar) --> (extract_high (dup128 scalar))
  11402. //
  11403. // This routine does the actual conversion of such DUPs, once outer routines
  11404. // have determined that everything else is in order.
  11405. // It also supports immediate DUP-like nodes (MOVI/MVNi), which we can fold
  11406. // similarly here.
  11407. static SDValue tryExtendDUPToExtractHigh(SDValue N, SelectionDAG &DAG) {
  11408. switch (N.getOpcode()) {
  11409. case AArch64ISD::DUP:
  11410. case AArch64ISD::DUPLANE8:
  11411. case AArch64ISD::DUPLANE16:
  11412. case AArch64ISD::DUPLANE32:
  11413. case AArch64ISD::DUPLANE64:
  11414. case AArch64ISD::MOVI:
  11415. case AArch64ISD::MOVIshift:
  11416. case AArch64ISD::MOVIedit:
  11417. case AArch64ISD::MOVImsl:
  11418. case AArch64ISD::MVNIshift:
  11419. case AArch64ISD::MVNImsl:
  11420. break;
  11421. default:
  11422. // FMOV could be supported, but isn't very useful, as it would only occur
  11423. // if you passed a bitcast' floating point immediate to an eligible long
  11424. // integer op (addl, smull, ...).
  11425. return SDValue();
  11426. }
  11427. MVT NarrowTy = N.getSimpleValueType();
  11428. if (!NarrowTy.is64BitVector())
  11429. return SDValue();
  11430. MVT ElementTy = NarrowTy.getVectorElementType();
  11431. unsigned NumElems = NarrowTy.getVectorNumElements();
  11432. MVT NewVT = MVT::getVectorVT(ElementTy, NumElems * 2);
  11433. SDLoc dl(N);
  11434. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NarrowTy,
  11435. DAG.getNode(N->getOpcode(), dl, NewVT, N->ops()),
  11436. DAG.getConstant(NumElems, dl, MVT::i64));
  11437. }
  11438. static bool isEssentiallyExtractHighSubvector(SDValue N) {
  11439. if (N.getOpcode() == ISD::BITCAST)
  11440. N = N.getOperand(0);
  11441. if (N.getOpcode() != ISD::EXTRACT_SUBVECTOR)
  11442. return false;
  11443. return cast<ConstantSDNode>(N.getOperand(1))->getAPIntValue() ==
  11444. N.getOperand(0).getValueType().getVectorNumElements() / 2;
  11445. }
  11446. /// Helper structure to keep track of ISD::SET_CC operands.
  11447. struct GenericSetCCInfo {
  11448. const SDValue *Opnd0;
  11449. const SDValue *Opnd1;
  11450. ISD::CondCode CC;
  11451. };
  11452. /// Helper structure to keep track of a SET_CC lowered into AArch64 code.
  11453. struct AArch64SetCCInfo {
  11454. const SDValue *Cmp;
  11455. AArch64CC::CondCode CC;
  11456. };
  11457. /// Helper structure to keep track of SetCC information.
  11458. union SetCCInfo {
  11459. GenericSetCCInfo Generic;
  11460. AArch64SetCCInfo AArch64;
  11461. };
  11462. /// Helper structure to be able to read SetCC information. If set to
  11463. /// true, IsAArch64 field, Info is a AArch64SetCCInfo, otherwise Info is a
  11464. /// GenericSetCCInfo.
  11465. struct SetCCInfoAndKind {
  11466. SetCCInfo Info;
  11467. bool IsAArch64;
  11468. };
  11469. /// Check whether or not \p Op is a SET_CC operation, either a generic or
  11470. /// an
  11471. /// AArch64 lowered one.
  11472. /// \p SetCCInfo is filled accordingly.
  11473. /// \post SetCCInfo is meanginfull only when this function returns true.
  11474. /// \return True when Op is a kind of SET_CC operation.
  11475. static bool isSetCC(SDValue Op, SetCCInfoAndKind &SetCCInfo) {
  11476. // If this is a setcc, this is straight forward.
  11477. if (Op.getOpcode() == ISD::SETCC) {
  11478. SetCCInfo.Info.Generic.Opnd0 = &Op.getOperand(0);
  11479. SetCCInfo.Info.Generic.Opnd1 = &Op.getOperand(1);
  11480. SetCCInfo.Info.Generic.CC = cast<CondCodeSDNode>(Op.getOperand(2))->get();
  11481. SetCCInfo.IsAArch64 = false;
  11482. return true;
  11483. }
  11484. // Otherwise, check if this is a matching csel instruction.
  11485. // In other words:
  11486. // - csel 1, 0, cc
  11487. // - csel 0, 1, !cc
  11488. if (Op.getOpcode() != AArch64ISD::CSEL)
  11489. return false;
  11490. // Set the information about the operands.
  11491. // TODO: we want the operands of the Cmp not the csel
  11492. SetCCInfo.Info.AArch64.Cmp = &Op.getOperand(3);
  11493. SetCCInfo.IsAArch64 = true;
  11494. SetCCInfo.Info.AArch64.CC = static_cast<AArch64CC::CondCode>(
  11495. cast<ConstantSDNode>(Op.getOperand(2))->getZExtValue());
  11496. // Check that the operands matches the constraints:
  11497. // (1) Both operands must be constants.
  11498. // (2) One must be 1 and the other must be 0.
  11499. ConstantSDNode *TValue = dyn_cast<ConstantSDNode>(Op.getOperand(0));
  11500. ConstantSDNode *FValue = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  11501. // Check (1).
  11502. if (!TValue || !FValue)
  11503. return false;
  11504. // Check (2).
  11505. if (!TValue->isOne()) {
  11506. // Update the comparison when we are interested in !cc.
  11507. std::swap(TValue, FValue);
  11508. SetCCInfo.Info.AArch64.CC =
  11509. AArch64CC::getInvertedCondCode(SetCCInfo.Info.AArch64.CC);
  11510. }
  11511. return TValue->isOne() && FValue->isNullValue();
  11512. }
  11513. // Returns true if Op is setcc or zext of setcc.
  11514. static bool isSetCCOrZExtSetCC(const SDValue& Op, SetCCInfoAndKind &Info) {
  11515. if (isSetCC(Op, Info))
  11516. return true;
  11517. return ((Op.getOpcode() == ISD::ZERO_EXTEND) &&
  11518. isSetCC(Op->getOperand(0), Info));
  11519. }
  11520. // The folding we want to perform is:
  11521. // (add x, [zext] (setcc cc ...) )
  11522. // -->
  11523. // (csel x, (add x, 1), !cc ...)
  11524. //
  11525. // The latter will get matched to a CSINC instruction.
  11526. static SDValue performSetccAddFolding(SDNode *Op, SelectionDAG &DAG) {
  11527. assert(Op && Op->getOpcode() == ISD::ADD && "Unexpected operation!");
  11528. SDValue LHS = Op->getOperand(0);
  11529. SDValue RHS = Op->getOperand(1);
  11530. SetCCInfoAndKind InfoAndKind;
  11531. // If neither operand is a SET_CC, give up.
  11532. if (!isSetCCOrZExtSetCC(LHS, InfoAndKind)) {
  11533. std::swap(LHS, RHS);
  11534. if (!isSetCCOrZExtSetCC(LHS, InfoAndKind))
  11535. return SDValue();
  11536. }
  11537. // FIXME: This could be generatized to work for FP comparisons.
  11538. EVT CmpVT = InfoAndKind.IsAArch64
  11539. ? InfoAndKind.Info.AArch64.Cmp->getOperand(0).getValueType()
  11540. : InfoAndKind.Info.Generic.Opnd0->getValueType();
  11541. if (CmpVT != MVT::i32 && CmpVT != MVT::i64)
  11542. return SDValue();
  11543. SDValue CCVal;
  11544. SDValue Cmp;
  11545. SDLoc dl(Op);
  11546. if (InfoAndKind.IsAArch64) {
  11547. CCVal = DAG.getConstant(
  11548. AArch64CC::getInvertedCondCode(InfoAndKind.Info.AArch64.CC), dl,
  11549. MVT::i32);
  11550. Cmp = *InfoAndKind.Info.AArch64.Cmp;
  11551. } else
  11552. Cmp = getAArch64Cmp(
  11553. *InfoAndKind.Info.Generic.Opnd0, *InfoAndKind.Info.Generic.Opnd1,
  11554. ISD::getSetCCInverse(InfoAndKind.Info.Generic.CC, CmpVT), CCVal, DAG,
  11555. dl);
  11556. EVT VT = Op->getValueType(0);
  11557. LHS = DAG.getNode(ISD::ADD, dl, VT, RHS, DAG.getConstant(1, dl, VT));
  11558. return DAG.getNode(AArch64ISD::CSEL, dl, VT, RHS, LHS, CCVal, Cmp);
  11559. }
  11560. // ADD(UADDV a, UADDV b) --> UADDV(ADD a, b)
  11561. static SDValue performUADDVCombine(SDNode *N, SelectionDAG &DAG) {
  11562. EVT VT = N->getValueType(0);
  11563. // Only scalar integer and vector types.
  11564. if (N->getOpcode() != ISD::ADD || !VT.isScalarInteger())
  11565. return SDValue();
  11566. SDValue LHS = N->getOperand(0);
  11567. SDValue RHS = N->getOperand(1);
  11568. if (LHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  11569. RHS.getOpcode() != ISD::EXTRACT_VECTOR_ELT || LHS.getValueType() != VT)
  11570. return SDValue();
  11571. auto *LHSN1 = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
  11572. auto *RHSN1 = dyn_cast<ConstantSDNode>(RHS->getOperand(1));
  11573. if (!LHSN1 || LHSN1 != RHSN1 || !RHSN1->isNullValue())
  11574. return SDValue();
  11575. SDValue Op1 = LHS->getOperand(0);
  11576. SDValue Op2 = RHS->getOperand(0);
  11577. EVT OpVT1 = Op1.getValueType();
  11578. EVT OpVT2 = Op2.getValueType();
  11579. if (Op1.getOpcode() != AArch64ISD::UADDV || OpVT1 != OpVT2 ||
  11580. Op2.getOpcode() != AArch64ISD::UADDV ||
  11581. OpVT1.getVectorElementType() != VT)
  11582. return SDValue();
  11583. SDValue Val1 = Op1.getOperand(0);
  11584. SDValue Val2 = Op2.getOperand(0);
  11585. EVT ValVT = Val1->getValueType(0);
  11586. SDLoc DL(N);
  11587. SDValue AddVal = DAG.getNode(ISD::ADD, DL, ValVT, Val1, Val2);
  11588. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT,
  11589. DAG.getNode(AArch64ISD::UADDV, DL, ValVT, AddVal),
  11590. DAG.getConstant(0, DL, MVT::i64));
  11591. }
  11592. // The basic add/sub long vector instructions have variants with "2" on the end
  11593. // which act on the high-half of their inputs. They are normally matched by
  11594. // patterns like:
  11595. //
  11596. // (add (zeroext (extract_high LHS)),
  11597. // (zeroext (extract_high RHS)))
  11598. // -> uaddl2 vD, vN, vM
  11599. //
  11600. // However, if one of the extracts is something like a duplicate, this
  11601. // instruction can still be used profitably. This function puts the DAG into a
  11602. // more appropriate form for those patterns to trigger.
  11603. static SDValue performAddSubLongCombine(SDNode *N,
  11604. TargetLowering::DAGCombinerInfo &DCI,
  11605. SelectionDAG &DAG) {
  11606. if (DCI.isBeforeLegalizeOps())
  11607. return SDValue();
  11608. MVT VT = N->getSimpleValueType(0);
  11609. if (!VT.is128BitVector()) {
  11610. if (N->getOpcode() == ISD::ADD)
  11611. return performSetccAddFolding(N, DAG);
  11612. return SDValue();
  11613. }
  11614. // Make sure both branches are extended in the same way.
  11615. SDValue LHS = N->getOperand(0);
  11616. SDValue RHS = N->getOperand(1);
  11617. if ((LHS.getOpcode() != ISD::ZERO_EXTEND &&
  11618. LHS.getOpcode() != ISD::SIGN_EXTEND) ||
  11619. LHS.getOpcode() != RHS.getOpcode())
  11620. return SDValue();
  11621. unsigned ExtType = LHS.getOpcode();
  11622. // It's not worth doing if at least one of the inputs isn't already an
  11623. // extract, but we don't know which it'll be so we have to try both.
  11624. if (isEssentiallyExtractHighSubvector(LHS.getOperand(0))) {
  11625. RHS = tryExtendDUPToExtractHigh(RHS.getOperand(0), DAG);
  11626. if (!RHS.getNode())
  11627. return SDValue();
  11628. RHS = DAG.getNode(ExtType, SDLoc(N), VT, RHS);
  11629. } else if (isEssentiallyExtractHighSubvector(RHS.getOperand(0))) {
  11630. LHS = tryExtendDUPToExtractHigh(LHS.getOperand(0), DAG);
  11631. if (!LHS.getNode())
  11632. return SDValue();
  11633. LHS = DAG.getNode(ExtType, SDLoc(N), VT, LHS);
  11634. }
  11635. return DAG.getNode(N->getOpcode(), SDLoc(N), VT, LHS, RHS);
  11636. }
  11637. static SDValue performAddSubCombine(SDNode *N,
  11638. TargetLowering::DAGCombinerInfo &DCI,
  11639. SelectionDAG &DAG) {
  11640. // Try to change sum of two reductions.
  11641. if (SDValue Val = performUADDVCombine(N, DAG))
  11642. return Val;
  11643. return performAddSubLongCombine(N, DCI, DAG);
  11644. }
  11645. // Massage DAGs which we can use the high-half "long" operations on into
  11646. // something isel will recognize better. E.g.
  11647. //
  11648. // (aarch64_neon_umull (extract_high vec) (dupv64 scalar)) -->
  11649. // (aarch64_neon_umull (extract_high (v2i64 vec)))
  11650. // (extract_high (v2i64 (dup128 scalar)))))
  11651. //
  11652. static SDValue tryCombineLongOpWithDup(unsigned IID, SDNode *N,
  11653. TargetLowering::DAGCombinerInfo &DCI,
  11654. SelectionDAG &DAG) {
  11655. if (DCI.isBeforeLegalizeOps())
  11656. return SDValue();
  11657. SDValue LHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 0 : 1);
  11658. SDValue RHS = N->getOperand((IID == Intrinsic::not_intrinsic) ? 1 : 2);
  11659. assert(LHS.getValueType().is64BitVector() &&
  11660. RHS.getValueType().is64BitVector() &&
  11661. "unexpected shape for long operation");
  11662. // Either node could be a DUP, but it's not worth doing both of them (you'd
  11663. // just as well use the non-high version) so look for a corresponding extract
  11664. // operation on the other "wing".
  11665. if (isEssentiallyExtractHighSubvector(LHS)) {
  11666. RHS = tryExtendDUPToExtractHigh(RHS, DAG);
  11667. if (!RHS.getNode())
  11668. return SDValue();
  11669. } else if (isEssentiallyExtractHighSubvector(RHS)) {
  11670. LHS = tryExtendDUPToExtractHigh(LHS, DAG);
  11671. if (!LHS.getNode())
  11672. return SDValue();
  11673. }
  11674. if (IID == Intrinsic::not_intrinsic)
  11675. return DAG.getNode(N->getOpcode(), SDLoc(N), N->getValueType(0), LHS, RHS);
  11676. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), N->getValueType(0),
  11677. N->getOperand(0), LHS, RHS);
  11678. }
  11679. static SDValue tryCombineShiftImm(unsigned IID, SDNode *N, SelectionDAG &DAG) {
  11680. MVT ElemTy = N->getSimpleValueType(0).getScalarType();
  11681. unsigned ElemBits = ElemTy.getSizeInBits();
  11682. int64_t ShiftAmount;
  11683. if (BuildVectorSDNode *BVN = dyn_cast<BuildVectorSDNode>(N->getOperand(2))) {
  11684. APInt SplatValue, SplatUndef;
  11685. unsigned SplatBitSize;
  11686. bool HasAnyUndefs;
  11687. if (!BVN->isConstantSplat(SplatValue, SplatUndef, SplatBitSize,
  11688. HasAnyUndefs, ElemBits) ||
  11689. SplatBitSize != ElemBits)
  11690. return SDValue();
  11691. ShiftAmount = SplatValue.getSExtValue();
  11692. } else if (ConstantSDNode *CVN = dyn_cast<ConstantSDNode>(N->getOperand(2))) {
  11693. ShiftAmount = CVN->getSExtValue();
  11694. } else
  11695. return SDValue();
  11696. unsigned Opcode;
  11697. bool IsRightShift;
  11698. switch (IID) {
  11699. default:
  11700. llvm_unreachable("Unknown shift intrinsic");
  11701. case Intrinsic::aarch64_neon_sqshl:
  11702. Opcode = AArch64ISD::SQSHL_I;
  11703. IsRightShift = false;
  11704. break;
  11705. case Intrinsic::aarch64_neon_uqshl:
  11706. Opcode = AArch64ISD::UQSHL_I;
  11707. IsRightShift = false;
  11708. break;
  11709. case Intrinsic::aarch64_neon_srshl:
  11710. Opcode = AArch64ISD::SRSHR_I;
  11711. IsRightShift = true;
  11712. break;
  11713. case Intrinsic::aarch64_neon_urshl:
  11714. Opcode = AArch64ISD::URSHR_I;
  11715. IsRightShift = true;
  11716. break;
  11717. case Intrinsic::aarch64_neon_sqshlu:
  11718. Opcode = AArch64ISD::SQSHLU_I;
  11719. IsRightShift = false;
  11720. break;
  11721. case Intrinsic::aarch64_neon_sshl:
  11722. case Intrinsic::aarch64_neon_ushl:
  11723. // For positive shift amounts we can use SHL, as ushl/sshl perform a regular
  11724. // left shift for positive shift amounts. Below, we only replace the current
  11725. // node with VSHL, if this condition is met.
  11726. Opcode = AArch64ISD::VSHL;
  11727. IsRightShift = false;
  11728. break;
  11729. }
  11730. if (IsRightShift && ShiftAmount <= -1 && ShiftAmount >= -(int)ElemBits) {
  11731. SDLoc dl(N);
  11732. return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
  11733. DAG.getConstant(-ShiftAmount, dl, MVT::i32));
  11734. } else if (!IsRightShift && ShiftAmount >= 0 && ShiftAmount < ElemBits) {
  11735. SDLoc dl(N);
  11736. return DAG.getNode(Opcode, dl, N->getValueType(0), N->getOperand(1),
  11737. DAG.getConstant(ShiftAmount, dl, MVT::i32));
  11738. }
  11739. return SDValue();
  11740. }
  11741. // The CRC32[BH] instructions ignore the high bits of their data operand. Since
  11742. // the intrinsics must be legal and take an i32, this means there's almost
  11743. // certainly going to be a zext in the DAG which we can eliminate.
  11744. static SDValue tryCombineCRC32(unsigned Mask, SDNode *N, SelectionDAG &DAG) {
  11745. SDValue AndN = N->getOperand(2);
  11746. if (AndN.getOpcode() != ISD::AND)
  11747. return SDValue();
  11748. ConstantSDNode *CMask = dyn_cast<ConstantSDNode>(AndN.getOperand(1));
  11749. if (!CMask || CMask->getZExtValue() != Mask)
  11750. return SDValue();
  11751. return DAG.getNode(ISD::INTRINSIC_WO_CHAIN, SDLoc(N), MVT::i32,
  11752. N->getOperand(0), N->getOperand(1), AndN.getOperand(0));
  11753. }
  11754. static SDValue combineAcrossLanesIntrinsic(unsigned Opc, SDNode *N,
  11755. SelectionDAG &DAG) {
  11756. SDLoc dl(N);
  11757. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, N->getValueType(0),
  11758. DAG.getNode(Opc, dl,
  11759. N->getOperand(1).getSimpleValueType(),
  11760. N->getOperand(1)),
  11761. DAG.getConstant(0, dl, MVT::i64));
  11762. }
  11763. static SDValue LowerSVEIntrinsicIndex(SDNode *N, SelectionDAG &DAG) {
  11764. SDLoc DL(N);
  11765. SDValue Op1 = N->getOperand(1);
  11766. SDValue Op2 = N->getOperand(2);
  11767. EVT ScalarTy = Op1.getValueType();
  11768. if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16)) {
  11769. Op1 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op1);
  11770. Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, Op2);
  11771. }
  11772. return DAG.getNode(AArch64ISD::INDEX_VECTOR, DL, N->getValueType(0),
  11773. Op1, Op2);
  11774. }
  11775. static SDValue LowerSVEIntrinsicDUP(SDNode *N, SelectionDAG &DAG) {
  11776. SDLoc dl(N);
  11777. SDValue Scalar = N->getOperand(3);
  11778. EVT ScalarTy = Scalar.getValueType();
  11779. if ((ScalarTy == MVT::i8) || (ScalarTy == MVT::i16))
  11780. Scalar = DAG.getNode(ISD::ANY_EXTEND, dl, MVT::i32, Scalar);
  11781. SDValue Passthru = N->getOperand(1);
  11782. SDValue Pred = N->getOperand(2);
  11783. return DAG.getNode(AArch64ISD::DUP_MERGE_PASSTHRU, dl, N->getValueType(0),
  11784. Pred, Scalar, Passthru);
  11785. }
  11786. static SDValue LowerSVEIntrinsicEXT(SDNode *N, SelectionDAG &DAG) {
  11787. SDLoc dl(N);
  11788. LLVMContext &Ctx = *DAG.getContext();
  11789. EVT VT = N->getValueType(0);
  11790. assert(VT.isScalableVector() && "Expected a scalable vector.");
  11791. // Current lowering only supports the SVE-ACLE types.
  11792. if (VT.getSizeInBits().getKnownMinSize() != AArch64::SVEBitsPerBlock)
  11793. return SDValue();
  11794. unsigned ElemSize = VT.getVectorElementType().getSizeInBits() / 8;
  11795. unsigned ByteSize = VT.getSizeInBits().getKnownMinSize() / 8;
  11796. EVT ByteVT =
  11797. EVT::getVectorVT(Ctx, MVT::i8, ElementCount::getScalable(ByteSize));
  11798. // Convert everything to the domain of EXT (i.e bytes).
  11799. SDValue Op0 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(1));
  11800. SDValue Op1 = DAG.getNode(ISD::BITCAST, dl, ByteVT, N->getOperand(2));
  11801. SDValue Op2 = DAG.getNode(ISD::MUL, dl, MVT::i32, N->getOperand(3),
  11802. DAG.getConstant(ElemSize, dl, MVT::i32));
  11803. SDValue EXT = DAG.getNode(AArch64ISD::EXT, dl, ByteVT, Op0, Op1, Op2);
  11804. return DAG.getNode(ISD::BITCAST, dl, VT, EXT);
  11805. }
  11806. static SDValue tryConvertSVEWideCompare(SDNode *N, ISD::CondCode CC,
  11807. TargetLowering::DAGCombinerInfo &DCI,
  11808. SelectionDAG &DAG) {
  11809. if (DCI.isBeforeLegalize())
  11810. return SDValue();
  11811. SDValue Comparator = N->getOperand(3);
  11812. if (Comparator.getOpcode() == AArch64ISD::DUP ||
  11813. Comparator.getOpcode() == ISD::SPLAT_VECTOR) {
  11814. unsigned IID = getIntrinsicID(N);
  11815. EVT VT = N->getValueType(0);
  11816. EVT CmpVT = N->getOperand(2).getValueType();
  11817. SDValue Pred = N->getOperand(1);
  11818. SDValue Imm;
  11819. SDLoc DL(N);
  11820. switch (IID) {
  11821. default:
  11822. llvm_unreachable("Called with wrong intrinsic!");
  11823. break;
  11824. // Signed comparisons
  11825. case Intrinsic::aarch64_sve_cmpeq_wide:
  11826. case Intrinsic::aarch64_sve_cmpne_wide:
  11827. case Intrinsic::aarch64_sve_cmpge_wide:
  11828. case Intrinsic::aarch64_sve_cmpgt_wide:
  11829. case Intrinsic::aarch64_sve_cmplt_wide:
  11830. case Intrinsic::aarch64_sve_cmple_wide: {
  11831. if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
  11832. int64_t ImmVal = CN->getSExtValue();
  11833. if (ImmVal >= -16 && ImmVal <= 15)
  11834. Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
  11835. else
  11836. return SDValue();
  11837. }
  11838. break;
  11839. }
  11840. // Unsigned comparisons
  11841. case Intrinsic::aarch64_sve_cmphs_wide:
  11842. case Intrinsic::aarch64_sve_cmphi_wide:
  11843. case Intrinsic::aarch64_sve_cmplo_wide:
  11844. case Intrinsic::aarch64_sve_cmpls_wide: {
  11845. if (auto *CN = dyn_cast<ConstantSDNode>(Comparator.getOperand(0))) {
  11846. uint64_t ImmVal = CN->getZExtValue();
  11847. if (ImmVal <= 127)
  11848. Imm = DAG.getConstant(ImmVal, DL, MVT::i32);
  11849. else
  11850. return SDValue();
  11851. }
  11852. break;
  11853. }
  11854. }
  11855. if (!Imm)
  11856. return SDValue();
  11857. SDValue Splat = DAG.getNode(ISD::SPLAT_VECTOR, DL, CmpVT, Imm);
  11858. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, VT, Pred,
  11859. N->getOperand(2), Splat, DAG.getCondCode(CC));
  11860. }
  11861. return SDValue();
  11862. }
  11863. static SDValue getPTest(SelectionDAG &DAG, EVT VT, SDValue Pg, SDValue Op,
  11864. AArch64CC::CondCode Cond) {
  11865. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  11866. SDLoc DL(Op);
  11867. assert(Op.getValueType().isScalableVector() &&
  11868. TLI.isTypeLegal(Op.getValueType()) &&
  11869. "Expected legal scalable vector type!");
  11870. // Ensure target specific opcodes are using legal type.
  11871. EVT OutVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
  11872. SDValue TVal = DAG.getConstant(1, DL, OutVT);
  11873. SDValue FVal = DAG.getConstant(0, DL, OutVT);
  11874. // Set condition code (CC) flags.
  11875. SDValue Test = DAG.getNode(AArch64ISD::PTEST, DL, MVT::Other, Pg, Op);
  11876. // Convert CC to integer based on requested condition.
  11877. // NOTE: Cond is inverted to promote CSEL's removal when it feeds a compare.
  11878. SDValue CC = DAG.getConstant(getInvertedCondCode(Cond), DL, MVT::i32);
  11879. SDValue Res = DAG.getNode(AArch64ISD::CSEL, DL, OutVT, FVal, TVal, CC, Test);
  11880. return DAG.getZExtOrTrunc(Res, DL, VT);
  11881. }
  11882. static SDValue combineSVEReductionInt(SDNode *N, unsigned Opc,
  11883. SelectionDAG &DAG) {
  11884. SDLoc DL(N);
  11885. SDValue Pred = N->getOperand(1);
  11886. SDValue VecToReduce = N->getOperand(2);
  11887. // NOTE: The integer reduction's result type is not always linked to the
  11888. // operand's element type so we construct it from the intrinsic's result type.
  11889. EVT ReduceVT = getPackedSVEVectorVT(N->getValueType(0));
  11890. SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
  11891. // SVE reductions set the whole vector register with the first element
  11892. // containing the reduction result, which we'll now extract.
  11893. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  11894. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
  11895. Zero);
  11896. }
  11897. static SDValue combineSVEReductionFP(SDNode *N, unsigned Opc,
  11898. SelectionDAG &DAG) {
  11899. SDLoc DL(N);
  11900. SDValue Pred = N->getOperand(1);
  11901. SDValue VecToReduce = N->getOperand(2);
  11902. EVT ReduceVT = VecToReduce.getValueType();
  11903. SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, VecToReduce);
  11904. // SVE reductions set the whole vector register with the first element
  11905. // containing the reduction result, which we'll now extract.
  11906. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  11907. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
  11908. Zero);
  11909. }
  11910. static SDValue combineSVEReductionOrderedFP(SDNode *N, unsigned Opc,
  11911. SelectionDAG &DAG) {
  11912. SDLoc DL(N);
  11913. SDValue Pred = N->getOperand(1);
  11914. SDValue InitVal = N->getOperand(2);
  11915. SDValue VecToReduce = N->getOperand(3);
  11916. EVT ReduceVT = VecToReduce.getValueType();
  11917. // Ordered reductions use the first lane of the result vector as the
  11918. // reduction's initial value.
  11919. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  11920. InitVal = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ReduceVT,
  11921. DAG.getUNDEF(ReduceVT), InitVal, Zero);
  11922. SDValue Reduce = DAG.getNode(Opc, DL, ReduceVT, Pred, InitVal, VecToReduce);
  11923. // SVE reductions set the whole vector register with the first element
  11924. // containing the reduction result, which we'll now extract.
  11925. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, N->getValueType(0), Reduce,
  11926. Zero);
  11927. }
  11928. // If a merged operation has no inactive lanes we can relax it to a predicated
  11929. // or unpredicated operation, which potentially allows better isel (perhaps
  11930. // using immediate forms) or relaxing register reuse requirements.
  11931. static SDValue convertMergedOpToPredOp(SDNode *N, unsigned PredOpc,
  11932. SelectionDAG &DAG) {
  11933. assert(N->getOpcode() == ISD::INTRINSIC_WO_CHAIN && "Expected intrinsic!");
  11934. assert(N->getNumOperands() == 4 && "Expected 3 operand intrinsic!");
  11935. SDValue Pg = N->getOperand(1);
  11936. // ISD way to specify an all active predicate.
  11937. if ((Pg.getOpcode() == AArch64ISD::PTRUE) &&
  11938. (Pg.getConstantOperandVal(0) == AArch64SVEPredPattern::all))
  11939. return DAG.getNode(PredOpc, SDLoc(N), N->getValueType(0), Pg,
  11940. N->getOperand(2), N->getOperand(3));
  11941. // FUTURE: SplatVector(true)
  11942. return SDValue();
  11943. }
  11944. static SDValue performIntrinsicCombine(SDNode *N,
  11945. TargetLowering::DAGCombinerInfo &DCI,
  11946. const AArch64Subtarget *Subtarget) {
  11947. SelectionDAG &DAG = DCI.DAG;
  11948. unsigned IID = getIntrinsicID(N);
  11949. switch (IID) {
  11950. default:
  11951. break;
  11952. case Intrinsic::aarch64_neon_vcvtfxs2fp:
  11953. case Intrinsic::aarch64_neon_vcvtfxu2fp:
  11954. return tryCombineFixedPointConvert(N, DCI, DAG);
  11955. case Intrinsic::aarch64_neon_saddv:
  11956. return combineAcrossLanesIntrinsic(AArch64ISD::SADDV, N, DAG);
  11957. case Intrinsic::aarch64_neon_uaddv:
  11958. return combineAcrossLanesIntrinsic(AArch64ISD::UADDV, N, DAG);
  11959. case Intrinsic::aarch64_neon_sminv:
  11960. return combineAcrossLanesIntrinsic(AArch64ISD::SMINV, N, DAG);
  11961. case Intrinsic::aarch64_neon_uminv:
  11962. return combineAcrossLanesIntrinsic(AArch64ISD::UMINV, N, DAG);
  11963. case Intrinsic::aarch64_neon_smaxv:
  11964. return combineAcrossLanesIntrinsic(AArch64ISD::SMAXV, N, DAG);
  11965. case Intrinsic::aarch64_neon_umaxv:
  11966. return combineAcrossLanesIntrinsic(AArch64ISD::UMAXV, N, DAG);
  11967. case Intrinsic::aarch64_neon_fmax:
  11968. return DAG.getNode(ISD::FMAXIMUM, SDLoc(N), N->getValueType(0),
  11969. N->getOperand(1), N->getOperand(2));
  11970. case Intrinsic::aarch64_neon_fmin:
  11971. return DAG.getNode(ISD::FMINIMUM, SDLoc(N), N->getValueType(0),
  11972. N->getOperand(1), N->getOperand(2));
  11973. case Intrinsic::aarch64_neon_fmaxnm:
  11974. return DAG.getNode(ISD::FMAXNUM, SDLoc(N), N->getValueType(0),
  11975. N->getOperand(1), N->getOperand(2));
  11976. case Intrinsic::aarch64_neon_fminnm:
  11977. return DAG.getNode(ISD::FMINNUM, SDLoc(N), N->getValueType(0),
  11978. N->getOperand(1), N->getOperand(2));
  11979. case Intrinsic::aarch64_neon_smull:
  11980. case Intrinsic::aarch64_neon_umull:
  11981. case Intrinsic::aarch64_neon_pmull:
  11982. case Intrinsic::aarch64_neon_sqdmull:
  11983. return tryCombineLongOpWithDup(IID, N, DCI, DAG);
  11984. case Intrinsic::aarch64_neon_sqshl:
  11985. case Intrinsic::aarch64_neon_uqshl:
  11986. case Intrinsic::aarch64_neon_sqshlu:
  11987. case Intrinsic::aarch64_neon_srshl:
  11988. case Intrinsic::aarch64_neon_urshl:
  11989. case Intrinsic::aarch64_neon_sshl:
  11990. case Intrinsic::aarch64_neon_ushl:
  11991. return tryCombineShiftImm(IID, N, DAG);
  11992. case Intrinsic::aarch64_crc32b:
  11993. case Intrinsic::aarch64_crc32cb:
  11994. return tryCombineCRC32(0xff, N, DAG);
  11995. case Intrinsic::aarch64_crc32h:
  11996. case Intrinsic::aarch64_crc32ch:
  11997. return tryCombineCRC32(0xffff, N, DAG);
  11998. case Intrinsic::aarch64_sve_saddv:
  11999. // There is no i64 version of SADDV because the sign is irrelevant.
  12000. if (N->getOperand(2)->getValueType(0).getVectorElementType() == MVT::i64)
  12001. return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
  12002. else
  12003. return combineSVEReductionInt(N, AArch64ISD::SADDV_PRED, DAG);
  12004. case Intrinsic::aarch64_sve_uaddv:
  12005. return combineSVEReductionInt(N, AArch64ISD::UADDV_PRED, DAG);
  12006. case Intrinsic::aarch64_sve_smaxv:
  12007. return combineSVEReductionInt(N, AArch64ISD::SMAXV_PRED, DAG);
  12008. case Intrinsic::aarch64_sve_umaxv:
  12009. return combineSVEReductionInt(N, AArch64ISD::UMAXV_PRED, DAG);
  12010. case Intrinsic::aarch64_sve_sminv:
  12011. return combineSVEReductionInt(N, AArch64ISD::SMINV_PRED, DAG);
  12012. case Intrinsic::aarch64_sve_uminv:
  12013. return combineSVEReductionInt(N, AArch64ISD::UMINV_PRED, DAG);
  12014. case Intrinsic::aarch64_sve_orv:
  12015. return combineSVEReductionInt(N, AArch64ISD::ORV_PRED, DAG);
  12016. case Intrinsic::aarch64_sve_eorv:
  12017. return combineSVEReductionInt(N, AArch64ISD::EORV_PRED, DAG);
  12018. case Intrinsic::aarch64_sve_andv:
  12019. return combineSVEReductionInt(N, AArch64ISD::ANDV_PRED, DAG);
  12020. case Intrinsic::aarch64_sve_index:
  12021. return LowerSVEIntrinsicIndex(N, DAG);
  12022. case Intrinsic::aarch64_sve_dup:
  12023. return LowerSVEIntrinsicDUP(N, DAG);
  12024. case Intrinsic::aarch64_sve_dup_x:
  12025. return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), N->getValueType(0),
  12026. N->getOperand(1));
  12027. case Intrinsic::aarch64_sve_ext:
  12028. return LowerSVEIntrinsicEXT(N, DAG);
  12029. case Intrinsic::aarch64_sve_smin:
  12030. return convertMergedOpToPredOp(N, AArch64ISD::SMIN_PRED, DAG);
  12031. case Intrinsic::aarch64_sve_umin:
  12032. return convertMergedOpToPredOp(N, AArch64ISD::UMIN_PRED, DAG);
  12033. case Intrinsic::aarch64_sve_smax:
  12034. return convertMergedOpToPredOp(N, AArch64ISD::SMAX_PRED, DAG);
  12035. case Intrinsic::aarch64_sve_umax:
  12036. return convertMergedOpToPredOp(N, AArch64ISD::UMAX_PRED, DAG);
  12037. case Intrinsic::aarch64_sve_lsl:
  12038. return convertMergedOpToPredOp(N, AArch64ISD::SHL_PRED, DAG);
  12039. case Intrinsic::aarch64_sve_lsr:
  12040. return convertMergedOpToPredOp(N, AArch64ISD::SRL_PRED, DAG);
  12041. case Intrinsic::aarch64_sve_asr:
  12042. return convertMergedOpToPredOp(N, AArch64ISD::SRA_PRED, DAG);
  12043. case Intrinsic::aarch64_sve_cmphs:
  12044. if (!N->getOperand(2).getValueType().isFloatingPoint())
  12045. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  12046. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  12047. N->getOperand(3), DAG.getCondCode(ISD::SETUGE));
  12048. break;
  12049. case Intrinsic::aarch64_sve_cmphi:
  12050. if (!N->getOperand(2).getValueType().isFloatingPoint())
  12051. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  12052. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  12053. N->getOperand(3), DAG.getCondCode(ISD::SETUGT));
  12054. break;
  12055. case Intrinsic::aarch64_sve_cmpge:
  12056. if (!N->getOperand(2).getValueType().isFloatingPoint())
  12057. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  12058. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  12059. N->getOperand(3), DAG.getCondCode(ISD::SETGE));
  12060. break;
  12061. case Intrinsic::aarch64_sve_cmpgt:
  12062. if (!N->getOperand(2).getValueType().isFloatingPoint())
  12063. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  12064. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  12065. N->getOperand(3), DAG.getCondCode(ISD::SETGT));
  12066. break;
  12067. case Intrinsic::aarch64_sve_cmpeq:
  12068. if (!N->getOperand(2).getValueType().isFloatingPoint())
  12069. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  12070. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  12071. N->getOperand(3), DAG.getCondCode(ISD::SETEQ));
  12072. break;
  12073. case Intrinsic::aarch64_sve_cmpne:
  12074. if (!N->getOperand(2).getValueType().isFloatingPoint())
  12075. return DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, SDLoc(N),
  12076. N->getValueType(0), N->getOperand(1), N->getOperand(2),
  12077. N->getOperand(3), DAG.getCondCode(ISD::SETNE));
  12078. break;
  12079. case Intrinsic::aarch64_sve_fadda:
  12080. return combineSVEReductionOrderedFP(N, AArch64ISD::FADDA_PRED, DAG);
  12081. case Intrinsic::aarch64_sve_faddv:
  12082. return combineSVEReductionFP(N, AArch64ISD::FADDV_PRED, DAG);
  12083. case Intrinsic::aarch64_sve_fmaxnmv:
  12084. return combineSVEReductionFP(N, AArch64ISD::FMAXNMV_PRED, DAG);
  12085. case Intrinsic::aarch64_sve_fmaxv:
  12086. return combineSVEReductionFP(N, AArch64ISD::FMAXV_PRED, DAG);
  12087. case Intrinsic::aarch64_sve_fminnmv:
  12088. return combineSVEReductionFP(N, AArch64ISD::FMINNMV_PRED, DAG);
  12089. case Intrinsic::aarch64_sve_fminv:
  12090. return combineSVEReductionFP(N, AArch64ISD::FMINV_PRED, DAG);
  12091. case Intrinsic::aarch64_sve_sel:
  12092. return DAG.getNode(ISD::VSELECT, SDLoc(N), N->getValueType(0),
  12093. N->getOperand(1), N->getOperand(2), N->getOperand(3));
  12094. case Intrinsic::aarch64_sve_cmpeq_wide:
  12095. return tryConvertSVEWideCompare(N, ISD::SETEQ, DCI, DAG);
  12096. case Intrinsic::aarch64_sve_cmpne_wide:
  12097. return tryConvertSVEWideCompare(N, ISD::SETNE, DCI, DAG);
  12098. case Intrinsic::aarch64_sve_cmpge_wide:
  12099. return tryConvertSVEWideCompare(N, ISD::SETGE, DCI, DAG);
  12100. case Intrinsic::aarch64_sve_cmpgt_wide:
  12101. return tryConvertSVEWideCompare(N, ISD::SETGT, DCI, DAG);
  12102. case Intrinsic::aarch64_sve_cmplt_wide:
  12103. return tryConvertSVEWideCompare(N, ISD::SETLT, DCI, DAG);
  12104. case Intrinsic::aarch64_sve_cmple_wide:
  12105. return tryConvertSVEWideCompare(N, ISD::SETLE, DCI, DAG);
  12106. case Intrinsic::aarch64_sve_cmphs_wide:
  12107. return tryConvertSVEWideCompare(N, ISD::SETUGE, DCI, DAG);
  12108. case Intrinsic::aarch64_sve_cmphi_wide:
  12109. return tryConvertSVEWideCompare(N, ISD::SETUGT, DCI, DAG);
  12110. case Intrinsic::aarch64_sve_cmplo_wide:
  12111. return tryConvertSVEWideCompare(N, ISD::SETULT, DCI, DAG);
  12112. case Intrinsic::aarch64_sve_cmpls_wide:
  12113. return tryConvertSVEWideCompare(N, ISD::SETULE, DCI, DAG);
  12114. case Intrinsic::aarch64_sve_ptest_any:
  12115. return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
  12116. AArch64CC::ANY_ACTIVE);
  12117. case Intrinsic::aarch64_sve_ptest_first:
  12118. return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
  12119. AArch64CC::FIRST_ACTIVE);
  12120. case Intrinsic::aarch64_sve_ptest_last:
  12121. return getPTest(DAG, N->getValueType(0), N->getOperand(1), N->getOperand(2),
  12122. AArch64CC::LAST_ACTIVE);
  12123. }
  12124. return SDValue();
  12125. }
  12126. static SDValue performExtendCombine(SDNode *N,
  12127. TargetLowering::DAGCombinerInfo &DCI,
  12128. SelectionDAG &DAG) {
  12129. // If we see something like (zext (sabd (extract_high ...), (DUP ...))) then
  12130. // we can convert that DUP into another extract_high (of a bigger DUP), which
  12131. // helps the backend to decide that an sabdl2 would be useful, saving a real
  12132. // extract_high operation.
  12133. if (!DCI.isBeforeLegalizeOps() && N->getOpcode() == ISD::ZERO_EXTEND &&
  12134. (N->getOperand(0).getOpcode() == AArch64ISD::UABD ||
  12135. N->getOperand(0).getOpcode() == AArch64ISD::SABD)) {
  12136. SDNode *ABDNode = N->getOperand(0).getNode();
  12137. SDValue NewABD =
  12138. tryCombineLongOpWithDup(Intrinsic::not_intrinsic, ABDNode, DCI, DAG);
  12139. if (!NewABD.getNode())
  12140. return SDValue();
  12141. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), NewABD);
  12142. }
  12143. // This is effectively a custom type legalization for AArch64.
  12144. //
  12145. // Type legalization will split an extend of a small, legal, type to a larger
  12146. // illegal type by first splitting the destination type, often creating
  12147. // illegal source types, which then get legalized in isel-confusing ways,
  12148. // leading to really terrible codegen. E.g.,
  12149. // %result = v8i32 sext v8i8 %value
  12150. // becomes
  12151. // %losrc = extract_subreg %value, ...
  12152. // %hisrc = extract_subreg %value, ...
  12153. // %lo = v4i32 sext v4i8 %losrc
  12154. // %hi = v4i32 sext v4i8 %hisrc
  12155. // Things go rapidly downhill from there.
  12156. //
  12157. // For AArch64, the [sz]ext vector instructions can only go up one element
  12158. // size, so we can, e.g., extend from i8 to i16, but to go from i8 to i32
  12159. // take two instructions.
  12160. //
  12161. // This implies that the most efficient way to do the extend from v8i8
  12162. // to two v4i32 values is to first extend the v8i8 to v8i16, then do
  12163. // the normal splitting to happen for the v8i16->v8i32.
  12164. // This is pre-legalization to catch some cases where the default
  12165. // type legalization will create ill-tempered code.
  12166. if (!DCI.isBeforeLegalizeOps())
  12167. return SDValue();
  12168. // We're only interested in cleaning things up for non-legal vector types
  12169. // here. If both the source and destination are legal, things will just
  12170. // work naturally without any fiddling.
  12171. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  12172. EVT ResVT = N->getValueType(0);
  12173. if (!ResVT.isVector() || TLI.isTypeLegal(ResVT))
  12174. return SDValue();
  12175. // If the vector type isn't a simple VT, it's beyond the scope of what
  12176. // we're worried about here. Let legalization do its thing and hope for
  12177. // the best.
  12178. SDValue Src = N->getOperand(0);
  12179. EVT SrcVT = Src->getValueType(0);
  12180. if (!ResVT.isSimple() || !SrcVT.isSimple())
  12181. return SDValue();
  12182. // If the source VT is a 64-bit fixed or scalable vector, we can play games
  12183. // and get the better results we want.
  12184. if (SrcVT.getSizeInBits().getKnownMinSize() != 64)
  12185. return SDValue();
  12186. unsigned SrcEltSize = SrcVT.getScalarSizeInBits();
  12187. ElementCount SrcEC = SrcVT.getVectorElementCount();
  12188. SrcVT = MVT::getVectorVT(MVT::getIntegerVT(SrcEltSize * 2), SrcEC);
  12189. SDLoc DL(N);
  12190. Src = DAG.getNode(N->getOpcode(), DL, SrcVT, Src);
  12191. // Now split the rest of the operation into two halves, each with a 64
  12192. // bit source.
  12193. EVT LoVT, HiVT;
  12194. SDValue Lo, Hi;
  12195. LoVT = HiVT = ResVT.getHalfNumVectorElementsVT(*DAG.getContext());
  12196. EVT InNVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getVectorElementType(),
  12197. LoVT.getVectorElementCount());
  12198. Lo = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
  12199. DAG.getConstant(0, DL, MVT::i64));
  12200. Hi = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InNVT, Src,
  12201. DAG.getConstant(InNVT.getVectorMinNumElements(), DL, MVT::i64));
  12202. Lo = DAG.getNode(N->getOpcode(), DL, LoVT, Lo);
  12203. Hi = DAG.getNode(N->getOpcode(), DL, HiVT, Hi);
  12204. // Now combine the parts back together so we still have a single result
  12205. // like the combiner expects.
  12206. return DAG.getNode(ISD::CONCAT_VECTORS, DL, ResVT, Lo, Hi);
  12207. }
  12208. static SDValue splitStoreSplat(SelectionDAG &DAG, StoreSDNode &St,
  12209. SDValue SplatVal, unsigned NumVecElts) {
  12210. assert(!St.isTruncatingStore() && "cannot split truncating vector store");
  12211. unsigned OrigAlignment = St.getAlignment();
  12212. unsigned EltOffset = SplatVal.getValueType().getSizeInBits() / 8;
  12213. // Create scalar stores. This is at least as good as the code sequence for a
  12214. // split unaligned store which is a dup.s, ext.b, and two stores.
  12215. // Most of the time the three stores should be replaced by store pair
  12216. // instructions (stp).
  12217. SDLoc DL(&St);
  12218. SDValue BasePtr = St.getBasePtr();
  12219. uint64_t BaseOffset = 0;
  12220. const MachinePointerInfo &PtrInfo = St.getPointerInfo();
  12221. SDValue NewST1 =
  12222. DAG.getStore(St.getChain(), DL, SplatVal, BasePtr, PtrInfo,
  12223. OrigAlignment, St.getMemOperand()->getFlags());
  12224. // As this in ISel, we will not merge this add which may degrade results.
  12225. if (BasePtr->getOpcode() == ISD::ADD &&
  12226. isa<ConstantSDNode>(BasePtr->getOperand(1))) {
  12227. BaseOffset = cast<ConstantSDNode>(BasePtr->getOperand(1))->getSExtValue();
  12228. BasePtr = BasePtr->getOperand(0);
  12229. }
  12230. unsigned Offset = EltOffset;
  12231. while (--NumVecElts) {
  12232. unsigned Alignment = MinAlign(OrigAlignment, Offset);
  12233. SDValue OffsetPtr =
  12234. DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
  12235. DAG.getConstant(BaseOffset + Offset, DL, MVT::i64));
  12236. NewST1 = DAG.getStore(NewST1.getValue(0), DL, SplatVal, OffsetPtr,
  12237. PtrInfo.getWithOffset(Offset), Alignment,
  12238. St.getMemOperand()->getFlags());
  12239. Offset += EltOffset;
  12240. }
  12241. return NewST1;
  12242. }
  12243. // Returns an SVE type that ContentTy can be trivially sign or zero extended
  12244. // into.
  12245. static MVT getSVEContainerType(EVT ContentTy) {
  12246. assert(ContentTy.isSimple() && "No SVE containers for extended types");
  12247. switch (ContentTy.getSimpleVT().SimpleTy) {
  12248. default:
  12249. llvm_unreachable("No known SVE container for this MVT type");
  12250. case MVT::nxv2i8:
  12251. case MVT::nxv2i16:
  12252. case MVT::nxv2i32:
  12253. case MVT::nxv2i64:
  12254. case MVT::nxv2f32:
  12255. case MVT::nxv2f64:
  12256. return MVT::nxv2i64;
  12257. case MVT::nxv4i8:
  12258. case MVT::nxv4i16:
  12259. case MVT::nxv4i32:
  12260. case MVT::nxv4f32:
  12261. return MVT::nxv4i32;
  12262. case MVT::nxv8i8:
  12263. case MVT::nxv8i16:
  12264. case MVT::nxv8f16:
  12265. case MVT::nxv8bf16:
  12266. return MVT::nxv8i16;
  12267. case MVT::nxv16i8:
  12268. return MVT::nxv16i8;
  12269. }
  12270. }
  12271. static SDValue performLD1Combine(SDNode *N, SelectionDAG &DAG, unsigned Opc) {
  12272. SDLoc DL(N);
  12273. EVT VT = N->getValueType(0);
  12274. if (VT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
  12275. return SDValue();
  12276. EVT ContainerVT = VT;
  12277. if (ContainerVT.isInteger())
  12278. ContainerVT = getSVEContainerType(ContainerVT);
  12279. SDVTList VTs = DAG.getVTList(ContainerVT, MVT::Other);
  12280. SDValue Ops[] = { N->getOperand(0), // Chain
  12281. N->getOperand(2), // Pg
  12282. N->getOperand(3), // Base
  12283. DAG.getValueType(VT) };
  12284. SDValue Load = DAG.getNode(Opc, DL, VTs, Ops);
  12285. SDValue LoadChain = SDValue(Load.getNode(), 1);
  12286. if (ContainerVT.isInteger() && (VT != ContainerVT))
  12287. Load = DAG.getNode(ISD::TRUNCATE, DL, VT, Load.getValue(0));
  12288. return DAG.getMergeValues({ Load, LoadChain }, DL);
  12289. }
  12290. static SDValue performLDNT1Combine(SDNode *N, SelectionDAG &DAG) {
  12291. SDLoc DL(N);
  12292. EVT VT = N->getValueType(0);
  12293. EVT PtrTy = N->getOperand(3).getValueType();
  12294. if (VT == MVT::nxv8bf16 &&
  12295. !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
  12296. return SDValue();
  12297. EVT LoadVT = VT;
  12298. if (VT.isFloatingPoint())
  12299. LoadVT = VT.changeTypeToInteger();
  12300. auto *MINode = cast<MemIntrinsicSDNode>(N);
  12301. SDValue PassThru = DAG.getConstant(0, DL, LoadVT);
  12302. SDValue L = DAG.getMaskedLoad(LoadVT, DL, MINode->getChain(),
  12303. MINode->getOperand(3), DAG.getUNDEF(PtrTy),
  12304. MINode->getOperand(2), PassThru,
  12305. MINode->getMemoryVT(), MINode->getMemOperand(),
  12306. ISD::UNINDEXED, ISD::NON_EXTLOAD, false);
  12307. if (VT.isFloatingPoint()) {
  12308. SDValue Ops[] = { DAG.getNode(ISD::BITCAST, DL, VT, L), L.getValue(1) };
  12309. return DAG.getMergeValues(Ops, DL);
  12310. }
  12311. return L;
  12312. }
  12313. template <unsigned Opcode>
  12314. static SDValue performLD1ReplicateCombine(SDNode *N, SelectionDAG &DAG) {
  12315. static_assert(Opcode == AArch64ISD::LD1RQ_MERGE_ZERO ||
  12316. Opcode == AArch64ISD::LD1RO_MERGE_ZERO,
  12317. "Unsupported opcode.");
  12318. SDLoc DL(N);
  12319. EVT VT = N->getValueType(0);
  12320. if (VT == MVT::nxv8bf16 &&
  12321. !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
  12322. return SDValue();
  12323. EVT LoadVT = VT;
  12324. if (VT.isFloatingPoint())
  12325. LoadVT = VT.changeTypeToInteger();
  12326. SDValue Ops[] = {N->getOperand(0), N->getOperand(2), N->getOperand(3)};
  12327. SDValue Load = DAG.getNode(Opcode, DL, {LoadVT, MVT::Other}, Ops);
  12328. SDValue LoadChain = SDValue(Load.getNode(), 1);
  12329. if (VT.isFloatingPoint())
  12330. Load = DAG.getNode(ISD::BITCAST, DL, VT, Load.getValue(0));
  12331. return DAG.getMergeValues({Load, LoadChain}, DL);
  12332. }
  12333. static SDValue performST1Combine(SDNode *N, SelectionDAG &DAG) {
  12334. SDLoc DL(N);
  12335. SDValue Data = N->getOperand(2);
  12336. EVT DataVT = Data.getValueType();
  12337. EVT HwSrcVt = getSVEContainerType(DataVT);
  12338. SDValue InputVT = DAG.getValueType(DataVT);
  12339. if (DataVT == MVT::nxv8bf16 &&
  12340. !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
  12341. return SDValue();
  12342. if (DataVT.isFloatingPoint())
  12343. InputVT = DAG.getValueType(HwSrcVt);
  12344. SDValue SrcNew;
  12345. if (Data.getValueType().isFloatingPoint())
  12346. SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Data);
  12347. else
  12348. SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Data);
  12349. SDValue Ops[] = { N->getOperand(0), // Chain
  12350. SrcNew,
  12351. N->getOperand(4), // Base
  12352. N->getOperand(3), // Pg
  12353. InputVT
  12354. };
  12355. return DAG.getNode(AArch64ISD::ST1_PRED, DL, N->getValueType(0), Ops);
  12356. }
  12357. static SDValue performSTNT1Combine(SDNode *N, SelectionDAG &DAG) {
  12358. SDLoc DL(N);
  12359. SDValue Data = N->getOperand(2);
  12360. EVT DataVT = Data.getValueType();
  12361. EVT PtrTy = N->getOperand(4).getValueType();
  12362. if (DataVT == MVT::nxv8bf16 &&
  12363. !static_cast<const AArch64Subtarget &>(DAG.getSubtarget()).hasBF16())
  12364. return SDValue();
  12365. if (DataVT.isFloatingPoint())
  12366. Data = DAG.getNode(ISD::BITCAST, DL, DataVT.changeTypeToInteger(), Data);
  12367. auto *MINode = cast<MemIntrinsicSDNode>(N);
  12368. return DAG.getMaskedStore(MINode->getChain(), DL, Data, MINode->getOperand(4),
  12369. DAG.getUNDEF(PtrTy), MINode->getOperand(3),
  12370. MINode->getMemoryVT(), MINode->getMemOperand(),
  12371. ISD::UNINDEXED, false, false);
  12372. }
  12373. /// Replace a splat of zeros to a vector store by scalar stores of WZR/XZR. The
  12374. /// load store optimizer pass will merge them to store pair stores. This should
  12375. /// be better than a movi to create the vector zero followed by a vector store
  12376. /// if the zero constant is not re-used, since one instructions and one register
  12377. /// live range will be removed.
  12378. ///
  12379. /// For example, the final generated code should be:
  12380. ///
  12381. /// stp xzr, xzr, [x0]
  12382. ///
  12383. /// instead of:
  12384. ///
  12385. /// movi v0.2d, #0
  12386. /// str q0, [x0]
  12387. ///
  12388. static SDValue replaceZeroVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
  12389. SDValue StVal = St.getValue();
  12390. EVT VT = StVal.getValueType();
  12391. // Avoid scalarizing zero splat stores for scalable vectors.
  12392. if (VT.isScalableVector())
  12393. return SDValue();
  12394. // It is beneficial to scalarize a zero splat store for 2 or 3 i64 elements or
  12395. // 2, 3 or 4 i32 elements.
  12396. int NumVecElts = VT.getVectorNumElements();
  12397. if (!(((NumVecElts == 2 || NumVecElts == 3) &&
  12398. VT.getVectorElementType().getSizeInBits() == 64) ||
  12399. ((NumVecElts == 2 || NumVecElts == 3 || NumVecElts == 4) &&
  12400. VT.getVectorElementType().getSizeInBits() == 32)))
  12401. return SDValue();
  12402. if (StVal.getOpcode() != ISD::BUILD_VECTOR)
  12403. return SDValue();
  12404. // If the zero constant has more than one use then the vector store could be
  12405. // better since the constant mov will be amortized and stp q instructions
  12406. // should be able to be formed.
  12407. if (!StVal.hasOneUse())
  12408. return SDValue();
  12409. // If the store is truncating then it's going down to i16 or smaller, which
  12410. // means it can be implemented in a single store anyway.
  12411. if (St.isTruncatingStore())
  12412. return SDValue();
  12413. // If the immediate offset of the address operand is too large for the stp
  12414. // instruction, then bail out.
  12415. if (DAG.isBaseWithConstantOffset(St.getBasePtr())) {
  12416. int64_t Offset = St.getBasePtr()->getConstantOperandVal(1);
  12417. if (Offset < -512 || Offset > 504)
  12418. return SDValue();
  12419. }
  12420. for (int I = 0; I < NumVecElts; ++I) {
  12421. SDValue EltVal = StVal.getOperand(I);
  12422. if (!isNullConstant(EltVal) && !isNullFPConstant(EltVal))
  12423. return SDValue();
  12424. }
  12425. // Use a CopyFromReg WZR/XZR here to prevent
  12426. // DAGCombiner::MergeConsecutiveStores from undoing this transformation.
  12427. SDLoc DL(&St);
  12428. unsigned ZeroReg;
  12429. EVT ZeroVT;
  12430. if (VT.getVectorElementType().getSizeInBits() == 32) {
  12431. ZeroReg = AArch64::WZR;
  12432. ZeroVT = MVT::i32;
  12433. } else {
  12434. ZeroReg = AArch64::XZR;
  12435. ZeroVT = MVT::i64;
  12436. }
  12437. SDValue SplatVal =
  12438. DAG.getCopyFromReg(DAG.getEntryNode(), DL, ZeroReg, ZeroVT);
  12439. return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
  12440. }
  12441. /// Replace a splat of a scalar to a vector store by scalar stores of the scalar
  12442. /// value. The load store optimizer pass will merge them to store pair stores.
  12443. /// This has better performance than a splat of the scalar followed by a split
  12444. /// vector store. Even if the stores are not merged it is four stores vs a dup,
  12445. /// followed by an ext.b and two stores.
  12446. static SDValue replaceSplatVectorStore(SelectionDAG &DAG, StoreSDNode &St) {
  12447. SDValue StVal = St.getValue();
  12448. EVT VT = StVal.getValueType();
  12449. // Don't replace floating point stores, they possibly won't be transformed to
  12450. // stp because of the store pair suppress pass.
  12451. if (VT.isFloatingPoint())
  12452. return SDValue();
  12453. // We can express a splat as store pair(s) for 2 or 4 elements.
  12454. unsigned NumVecElts = VT.getVectorNumElements();
  12455. if (NumVecElts != 4 && NumVecElts != 2)
  12456. return SDValue();
  12457. // If the store is truncating then it's going down to i16 or smaller, which
  12458. // means it can be implemented in a single store anyway.
  12459. if (St.isTruncatingStore())
  12460. return SDValue();
  12461. // Check that this is a splat.
  12462. // Make sure that each of the relevant vector element locations are inserted
  12463. // to, i.e. 0 and 1 for v2i64 and 0, 1, 2, 3 for v4i32.
  12464. std::bitset<4> IndexNotInserted((1 << NumVecElts) - 1);
  12465. SDValue SplatVal;
  12466. for (unsigned I = 0; I < NumVecElts; ++I) {
  12467. // Check for insert vector elements.
  12468. if (StVal.getOpcode() != ISD::INSERT_VECTOR_ELT)
  12469. return SDValue();
  12470. // Check that same value is inserted at each vector element.
  12471. if (I == 0)
  12472. SplatVal = StVal.getOperand(1);
  12473. else if (StVal.getOperand(1) != SplatVal)
  12474. return SDValue();
  12475. // Check insert element index.
  12476. ConstantSDNode *CIndex = dyn_cast<ConstantSDNode>(StVal.getOperand(2));
  12477. if (!CIndex)
  12478. return SDValue();
  12479. uint64_t IndexVal = CIndex->getZExtValue();
  12480. if (IndexVal >= NumVecElts)
  12481. return SDValue();
  12482. IndexNotInserted.reset(IndexVal);
  12483. StVal = StVal.getOperand(0);
  12484. }
  12485. // Check that all vector element locations were inserted to.
  12486. if (IndexNotInserted.any())
  12487. return SDValue();
  12488. return splitStoreSplat(DAG, St, SplatVal, NumVecElts);
  12489. }
  12490. static SDValue splitStores(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
  12491. SelectionDAG &DAG,
  12492. const AArch64Subtarget *Subtarget) {
  12493. StoreSDNode *S = cast<StoreSDNode>(N);
  12494. if (S->isVolatile() || S->isIndexed())
  12495. return SDValue();
  12496. SDValue StVal = S->getValue();
  12497. EVT VT = StVal.getValueType();
  12498. if (!VT.isFixedLengthVector())
  12499. return SDValue();
  12500. // If we get a splat of zeros, convert this vector store to a store of
  12501. // scalars. They will be merged into store pairs of xzr thereby removing one
  12502. // instruction and one register.
  12503. if (SDValue ReplacedZeroSplat = replaceZeroVectorStore(DAG, *S))
  12504. return ReplacedZeroSplat;
  12505. // FIXME: The logic for deciding if an unaligned store should be split should
  12506. // be included in TLI.allowsMisalignedMemoryAccesses(), and there should be
  12507. // a call to that function here.
  12508. if (!Subtarget->isMisaligned128StoreSlow())
  12509. return SDValue();
  12510. // Don't split at -Oz.
  12511. if (DAG.getMachineFunction().getFunction().hasMinSize())
  12512. return SDValue();
  12513. // Don't split v2i64 vectors. Memcpy lowering produces those and splitting
  12514. // those up regresses performance on micro-benchmarks and olden/bh.
  12515. if (VT.getVectorNumElements() < 2 || VT == MVT::v2i64)
  12516. return SDValue();
  12517. // Split unaligned 16B stores. They are terrible for performance.
  12518. // Don't split stores with alignment of 1 or 2. Code that uses clang vector
  12519. // extensions can use this to mark that it does not want splitting to happen
  12520. // (by underspecifying alignment to be 1 or 2). Furthermore, the chance of
  12521. // eliminating alignment hazards is only 1 in 8 for alignment of 2.
  12522. if (VT.getSizeInBits() != 128 || S->getAlignment() >= 16 ||
  12523. S->getAlignment() <= 2)
  12524. return SDValue();
  12525. // If we get a splat of a scalar convert this vector store to a store of
  12526. // scalars. They will be merged into store pairs thereby removing two
  12527. // instructions.
  12528. if (SDValue ReplacedSplat = replaceSplatVectorStore(DAG, *S))
  12529. return ReplacedSplat;
  12530. SDLoc DL(S);
  12531. // Split VT into two.
  12532. EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
  12533. unsigned NumElts = HalfVT.getVectorNumElements();
  12534. SDValue SubVector0 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
  12535. DAG.getConstant(0, DL, MVT::i64));
  12536. SDValue SubVector1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, HalfVT, StVal,
  12537. DAG.getConstant(NumElts, DL, MVT::i64));
  12538. SDValue BasePtr = S->getBasePtr();
  12539. SDValue NewST1 =
  12540. DAG.getStore(S->getChain(), DL, SubVector0, BasePtr, S->getPointerInfo(),
  12541. S->getAlignment(), S->getMemOperand()->getFlags());
  12542. SDValue OffsetPtr = DAG.getNode(ISD::ADD, DL, MVT::i64, BasePtr,
  12543. DAG.getConstant(8, DL, MVT::i64));
  12544. return DAG.getStore(NewST1.getValue(0), DL, SubVector1, OffsetPtr,
  12545. S->getPointerInfo(), S->getAlignment(),
  12546. S->getMemOperand()->getFlags());
  12547. }
  12548. static SDValue performUzpCombine(SDNode *N, SelectionDAG &DAG) {
  12549. SDLoc DL(N);
  12550. SDValue Op0 = N->getOperand(0);
  12551. SDValue Op1 = N->getOperand(1);
  12552. EVT ResVT = N->getValueType(0);
  12553. // uzp1(unpklo(uzp1(x, y)), z) => uzp1(x, z)
  12554. if (Op0.getOpcode() == AArch64ISD::UUNPKLO) {
  12555. if (Op0.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
  12556. SDValue X = Op0.getOperand(0).getOperand(0);
  12557. return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, X, Op1);
  12558. }
  12559. }
  12560. // uzp1(x, unpkhi(uzp1(y, z))) => uzp1(x, z)
  12561. if (Op1.getOpcode() == AArch64ISD::UUNPKHI) {
  12562. if (Op1.getOperand(0).getOpcode() == AArch64ISD::UZP1) {
  12563. SDValue Z = Op1.getOperand(0).getOperand(1);
  12564. return DAG.getNode(AArch64ISD::UZP1, DL, ResVT, Op0, Z);
  12565. }
  12566. }
  12567. return SDValue();
  12568. }
  12569. /// Target-specific DAG combine function for post-increment LD1 (lane) and
  12570. /// post-increment LD1R.
  12571. static SDValue performPostLD1Combine(SDNode *N,
  12572. TargetLowering::DAGCombinerInfo &DCI,
  12573. bool IsLaneOp) {
  12574. if (DCI.isBeforeLegalizeOps())
  12575. return SDValue();
  12576. SelectionDAG &DAG = DCI.DAG;
  12577. EVT VT = N->getValueType(0);
  12578. if (VT.isScalableVector())
  12579. return SDValue();
  12580. unsigned LoadIdx = IsLaneOp ? 1 : 0;
  12581. SDNode *LD = N->getOperand(LoadIdx).getNode();
  12582. // If it is not LOAD, can not do such combine.
  12583. if (LD->getOpcode() != ISD::LOAD)
  12584. return SDValue();
  12585. // The vector lane must be a constant in the LD1LANE opcode.
  12586. SDValue Lane;
  12587. if (IsLaneOp) {
  12588. Lane = N->getOperand(2);
  12589. auto *LaneC = dyn_cast<ConstantSDNode>(Lane);
  12590. if (!LaneC || LaneC->getZExtValue() >= VT.getVectorNumElements())
  12591. return SDValue();
  12592. }
  12593. LoadSDNode *LoadSDN = cast<LoadSDNode>(LD);
  12594. EVT MemVT = LoadSDN->getMemoryVT();
  12595. // Check if memory operand is the same type as the vector element.
  12596. if (MemVT != VT.getVectorElementType())
  12597. return SDValue();
  12598. // Check if there are other uses. If so, do not combine as it will introduce
  12599. // an extra load.
  12600. for (SDNode::use_iterator UI = LD->use_begin(), UE = LD->use_end(); UI != UE;
  12601. ++UI) {
  12602. if (UI.getUse().getResNo() == 1) // Ignore uses of the chain result.
  12603. continue;
  12604. if (*UI != N)
  12605. return SDValue();
  12606. }
  12607. SDValue Addr = LD->getOperand(1);
  12608. SDValue Vector = N->getOperand(0);
  12609. // Search for a use of the address operand that is an increment.
  12610. for (SDNode::use_iterator UI = Addr.getNode()->use_begin(), UE =
  12611. Addr.getNode()->use_end(); UI != UE; ++UI) {
  12612. SDNode *User = *UI;
  12613. if (User->getOpcode() != ISD::ADD
  12614. || UI.getUse().getResNo() != Addr.getResNo())
  12615. continue;
  12616. // If the increment is a constant, it must match the memory ref size.
  12617. SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
  12618. if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
  12619. uint32_t IncVal = CInc->getZExtValue();
  12620. unsigned NumBytes = VT.getScalarSizeInBits() / 8;
  12621. if (IncVal != NumBytes)
  12622. continue;
  12623. Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
  12624. }
  12625. // To avoid cycle construction make sure that neither the load nor the add
  12626. // are predecessors to each other or the Vector.
  12627. SmallPtrSet<const SDNode *, 32> Visited;
  12628. SmallVector<const SDNode *, 16> Worklist;
  12629. Visited.insert(Addr.getNode());
  12630. Worklist.push_back(User);
  12631. Worklist.push_back(LD);
  12632. Worklist.push_back(Vector.getNode());
  12633. if (SDNode::hasPredecessorHelper(LD, Visited, Worklist) ||
  12634. SDNode::hasPredecessorHelper(User, Visited, Worklist))
  12635. continue;
  12636. SmallVector<SDValue, 8> Ops;
  12637. Ops.push_back(LD->getOperand(0)); // Chain
  12638. if (IsLaneOp) {
  12639. Ops.push_back(Vector); // The vector to be inserted
  12640. Ops.push_back(Lane); // The lane to be inserted in the vector
  12641. }
  12642. Ops.push_back(Addr);
  12643. Ops.push_back(Inc);
  12644. EVT Tys[3] = { VT, MVT::i64, MVT::Other };
  12645. SDVTList SDTys = DAG.getVTList(Tys);
  12646. unsigned NewOp = IsLaneOp ? AArch64ISD::LD1LANEpost : AArch64ISD::LD1DUPpost;
  12647. SDValue UpdN = DAG.getMemIntrinsicNode(NewOp, SDLoc(N), SDTys, Ops,
  12648. MemVT,
  12649. LoadSDN->getMemOperand());
  12650. // Update the uses.
  12651. SDValue NewResults[] = {
  12652. SDValue(LD, 0), // The result of load
  12653. SDValue(UpdN.getNode(), 2) // Chain
  12654. };
  12655. DCI.CombineTo(LD, NewResults);
  12656. DCI.CombineTo(N, SDValue(UpdN.getNode(), 0)); // Dup/Inserted Result
  12657. DCI.CombineTo(User, SDValue(UpdN.getNode(), 1)); // Write back register
  12658. break;
  12659. }
  12660. return SDValue();
  12661. }
  12662. /// Simplify ``Addr`` given that the top byte of it is ignored by HW during
  12663. /// address translation.
  12664. static bool performTBISimplification(SDValue Addr,
  12665. TargetLowering::DAGCombinerInfo &DCI,
  12666. SelectionDAG &DAG) {
  12667. APInt DemandedMask = APInt::getLowBitsSet(64, 56);
  12668. KnownBits Known;
  12669. TargetLowering::TargetLoweringOpt TLO(DAG, !DCI.isBeforeLegalize(),
  12670. !DCI.isBeforeLegalizeOps());
  12671. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  12672. if (TLI.SimplifyDemandedBits(Addr, DemandedMask, Known, TLO)) {
  12673. DCI.CommitTargetLoweringOpt(TLO);
  12674. return true;
  12675. }
  12676. return false;
  12677. }
  12678. static SDValue performSTORECombine(SDNode *N,
  12679. TargetLowering::DAGCombinerInfo &DCI,
  12680. SelectionDAG &DAG,
  12681. const AArch64Subtarget *Subtarget) {
  12682. if (SDValue Split = splitStores(N, DCI, DAG, Subtarget))
  12683. return Split;
  12684. if (Subtarget->supportsAddressTopByteIgnored() &&
  12685. performTBISimplification(N->getOperand(2), DCI, DAG))
  12686. return SDValue(N, 0);
  12687. return SDValue();
  12688. }
  12689. static SDValue performMaskedGatherScatterCombine(SDNode *N,
  12690. TargetLowering::DAGCombinerInfo &DCI,
  12691. SelectionDAG &DAG) {
  12692. MaskedGatherScatterSDNode *MGS = cast<MaskedGatherScatterSDNode>(N);
  12693. assert(MGS && "Can only combine gather load or scatter store nodes");
  12694. SDLoc DL(MGS);
  12695. SDValue Chain = MGS->getChain();
  12696. SDValue Scale = MGS->getScale();
  12697. SDValue Index = MGS->getIndex();
  12698. SDValue Mask = MGS->getMask();
  12699. SDValue BasePtr = MGS->getBasePtr();
  12700. ISD::MemIndexType IndexType = MGS->getIndexType();
  12701. EVT IdxVT = Index.getValueType();
  12702. if (DCI.isBeforeLegalize()) {
  12703. // SVE gather/scatter requires indices of i32/i64. Promote anything smaller
  12704. // prior to legalisation so the result can be split if required.
  12705. if ((IdxVT.getVectorElementType() == MVT::i8) ||
  12706. (IdxVT.getVectorElementType() == MVT::i16)) {
  12707. EVT NewIdxVT = IdxVT.changeVectorElementType(MVT::i32);
  12708. if (MGS->isIndexSigned())
  12709. Index = DAG.getNode(ISD::SIGN_EXTEND, DL, NewIdxVT, Index);
  12710. else
  12711. Index = DAG.getNode(ISD::ZERO_EXTEND, DL, NewIdxVT, Index);
  12712. if (auto *MGT = dyn_cast<MaskedGatherSDNode>(MGS)) {
  12713. SDValue PassThru = MGT->getPassThru();
  12714. SDValue Ops[] = { Chain, PassThru, Mask, BasePtr, Index, Scale };
  12715. return DAG.getMaskedGather(DAG.getVTList(N->getValueType(0), MVT::Other),
  12716. PassThru.getValueType(), DL, Ops,
  12717. MGT->getMemOperand(),
  12718. MGT->getIndexType(), MGT->getExtensionType());
  12719. } else {
  12720. auto *MSC = cast<MaskedScatterSDNode>(MGS);
  12721. SDValue Data = MSC->getValue();
  12722. SDValue Ops[] = { Chain, Data, Mask, BasePtr, Index, Scale };
  12723. return DAG.getMaskedScatter(DAG.getVTList(MVT::Other),
  12724. MSC->getMemoryVT(), DL, Ops,
  12725. MSC->getMemOperand(), IndexType,
  12726. MSC->isTruncatingStore());
  12727. }
  12728. }
  12729. }
  12730. return SDValue();
  12731. }
  12732. /// Target-specific DAG combine function for NEON load/store intrinsics
  12733. /// to merge base address updates.
  12734. static SDValue performNEONPostLDSTCombine(SDNode *N,
  12735. TargetLowering::DAGCombinerInfo &DCI,
  12736. SelectionDAG &DAG) {
  12737. if (DCI.isBeforeLegalize() || DCI.isCalledByLegalizer())
  12738. return SDValue();
  12739. unsigned AddrOpIdx = N->getNumOperands() - 1;
  12740. SDValue Addr = N->getOperand(AddrOpIdx);
  12741. // Search for a use of the address operand that is an increment.
  12742. for (SDNode::use_iterator UI = Addr.getNode()->use_begin(),
  12743. UE = Addr.getNode()->use_end(); UI != UE; ++UI) {
  12744. SDNode *User = *UI;
  12745. if (User->getOpcode() != ISD::ADD ||
  12746. UI.getUse().getResNo() != Addr.getResNo())
  12747. continue;
  12748. // Check that the add is independent of the load/store. Otherwise, folding
  12749. // it would create a cycle.
  12750. SmallPtrSet<const SDNode *, 32> Visited;
  12751. SmallVector<const SDNode *, 16> Worklist;
  12752. Visited.insert(Addr.getNode());
  12753. Worklist.push_back(N);
  12754. Worklist.push_back(User);
  12755. if (SDNode::hasPredecessorHelper(N, Visited, Worklist) ||
  12756. SDNode::hasPredecessorHelper(User, Visited, Worklist))
  12757. continue;
  12758. // Find the new opcode for the updating load/store.
  12759. bool IsStore = false;
  12760. bool IsLaneOp = false;
  12761. bool IsDupOp = false;
  12762. unsigned NewOpc = 0;
  12763. unsigned NumVecs = 0;
  12764. unsigned IntNo = cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
  12765. switch (IntNo) {
  12766. default: llvm_unreachable("unexpected intrinsic for Neon base update");
  12767. case Intrinsic::aarch64_neon_ld2: NewOpc = AArch64ISD::LD2post;
  12768. NumVecs = 2; break;
  12769. case Intrinsic::aarch64_neon_ld3: NewOpc = AArch64ISD::LD3post;
  12770. NumVecs = 3; break;
  12771. case Intrinsic::aarch64_neon_ld4: NewOpc = AArch64ISD::LD4post;
  12772. NumVecs = 4; break;
  12773. case Intrinsic::aarch64_neon_st2: NewOpc = AArch64ISD::ST2post;
  12774. NumVecs = 2; IsStore = true; break;
  12775. case Intrinsic::aarch64_neon_st3: NewOpc = AArch64ISD::ST3post;
  12776. NumVecs = 3; IsStore = true; break;
  12777. case Intrinsic::aarch64_neon_st4: NewOpc = AArch64ISD::ST4post;
  12778. NumVecs = 4; IsStore = true; break;
  12779. case Intrinsic::aarch64_neon_ld1x2: NewOpc = AArch64ISD::LD1x2post;
  12780. NumVecs = 2; break;
  12781. case Intrinsic::aarch64_neon_ld1x3: NewOpc = AArch64ISD::LD1x3post;
  12782. NumVecs = 3; break;
  12783. case Intrinsic::aarch64_neon_ld1x4: NewOpc = AArch64ISD::LD1x4post;
  12784. NumVecs = 4; break;
  12785. case Intrinsic::aarch64_neon_st1x2: NewOpc = AArch64ISD::ST1x2post;
  12786. NumVecs = 2; IsStore = true; break;
  12787. case Intrinsic::aarch64_neon_st1x3: NewOpc = AArch64ISD::ST1x3post;
  12788. NumVecs = 3; IsStore = true; break;
  12789. case Intrinsic::aarch64_neon_st1x4: NewOpc = AArch64ISD::ST1x4post;
  12790. NumVecs = 4; IsStore = true; break;
  12791. case Intrinsic::aarch64_neon_ld2r: NewOpc = AArch64ISD::LD2DUPpost;
  12792. NumVecs = 2; IsDupOp = true; break;
  12793. case Intrinsic::aarch64_neon_ld3r: NewOpc = AArch64ISD::LD3DUPpost;
  12794. NumVecs = 3; IsDupOp = true; break;
  12795. case Intrinsic::aarch64_neon_ld4r: NewOpc = AArch64ISD::LD4DUPpost;
  12796. NumVecs = 4; IsDupOp = true; break;
  12797. case Intrinsic::aarch64_neon_ld2lane: NewOpc = AArch64ISD::LD2LANEpost;
  12798. NumVecs = 2; IsLaneOp = true; break;
  12799. case Intrinsic::aarch64_neon_ld3lane: NewOpc = AArch64ISD::LD3LANEpost;
  12800. NumVecs = 3; IsLaneOp = true; break;
  12801. case Intrinsic::aarch64_neon_ld4lane: NewOpc = AArch64ISD::LD4LANEpost;
  12802. NumVecs = 4; IsLaneOp = true; break;
  12803. case Intrinsic::aarch64_neon_st2lane: NewOpc = AArch64ISD::ST2LANEpost;
  12804. NumVecs = 2; IsStore = true; IsLaneOp = true; break;
  12805. case Intrinsic::aarch64_neon_st3lane: NewOpc = AArch64ISD::ST3LANEpost;
  12806. NumVecs = 3; IsStore = true; IsLaneOp = true; break;
  12807. case Intrinsic::aarch64_neon_st4lane: NewOpc = AArch64ISD::ST4LANEpost;
  12808. NumVecs = 4; IsStore = true; IsLaneOp = true; break;
  12809. }
  12810. EVT VecTy;
  12811. if (IsStore)
  12812. VecTy = N->getOperand(2).getValueType();
  12813. else
  12814. VecTy = N->getValueType(0);
  12815. // If the increment is a constant, it must match the memory ref size.
  12816. SDValue Inc = User->getOperand(User->getOperand(0) == Addr ? 1 : 0);
  12817. if (ConstantSDNode *CInc = dyn_cast<ConstantSDNode>(Inc.getNode())) {
  12818. uint32_t IncVal = CInc->getZExtValue();
  12819. unsigned NumBytes = NumVecs * VecTy.getSizeInBits() / 8;
  12820. if (IsLaneOp || IsDupOp)
  12821. NumBytes /= VecTy.getVectorNumElements();
  12822. if (IncVal != NumBytes)
  12823. continue;
  12824. Inc = DAG.getRegister(AArch64::XZR, MVT::i64);
  12825. }
  12826. SmallVector<SDValue, 8> Ops;
  12827. Ops.push_back(N->getOperand(0)); // Incoming chain
  12828. // Load lane and store have vector list as input.
  12829. if (IsLaneOp || IsStore)
  12830. for (unsigned i = 2; i < AddrOpIdx; ++i)
  12831. Ops.push_back(N->getOperand(i));
  12832. Ops.push_back(Addr); // Base register
  12833. Ops.push_back(Inc);
  12834. // Return Types.
  12835. EVT Tys[6];
  12836. unsigned NumResultVecs = (IsStore ? 0 : NumVecs);
  12837. unsigned n;
  12838. for (n = 0; n < NumResultVecs; ++n)
  12839. Tys[n] = VecTy;
  12840. Tys[n++] = MVT::i64; // Type of write back register
  12841. Tys[n] = MVT::Other; // Type of the chain
  12842. SDVTList SDTys = DAG.getVTList(makeArrayRef(Tys, NumResultVecs + 2));
  12843. MemIntrinsicSDNode *MemInt = cast<MemIntrinsicSDNode>(N);
  12844. SDValue UpdN = DAG.getMemIntrinsicNode(NewOpc, SDLoc(N), SDTys, Ops,
  12845. MemInt->getMemoryVT(),
  12846. MemInt->getMemOperand());
  12847. // Update the uses.
  12848. std::vector<SDValue> NewResults;
  12849. for (unsigned i = 0; i < NumResultVecs; ++i) {
  12850. NewResults.push_back(SDValue(UpdN.getNode(), i));
  12851. }
  12852. NewResults.push_back(SDValue(UpdN.getNode(), NumResultVecs + 1));
  12853. DCI.CombineTo(N, NewResults);
  12854. DCI.CombineTo(User, SDValue(UpdN.getNode(), NumResultVecs));
  12855. break;
  12856. }
  12857. return SDValue();
  12858. }
  12859. // Checks to see if the value is the prescribed width and returns information
  12860. // about its extension mode.
  12861. static
  12862. bool checkValueWidth(SDValue V, unsigned width, ISD::LoadExtType &ExtType) {
  12863. ExtType = ISD::NON_EXTLOAD;
  12864. switch(V.getNode()->getOpcode()) {
  12865. default:
  12866. return false;
  12867. case ISD::LOAD: {
  12868. LoadSDNode *LoadNode = cast<LoadSDNode>(V.getNode());
  12869. if ((LoadNode->getMemoryVT() == MVT::i8 && width == 8)
  12870. || (LoadNode->getMemoryVT() == MVT::i16 && width == 16)) {
  12871. ExtType = LoadNode->getExtensionType();
  12872. return true;
  12873. }
  12874. return false;
  12875. }
  12876. case ISD::AssertSext: {
  12877. VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
  12878. if ((TypeNode->getVT() == MVT::i8 && width == 8)
  12879. || (TypeNode->getVT() == MVT::i16 && width == 16)) {
  12880. ExtType = ISD::SEXTLOAD;
  12881. return true;
  12882. }
  12883. return false;
  12884. }
  12885. case ISD::AssertZext: {
  12886. VTSDNode *TypeNode = cast<VTSDNode>(V.getNode()->getOperand(1));
  12887. if ((TypeNode->getVT() == MVT::i8 && width == 8)
  12888. || (TypeNode->getVT() == MVT::i16 && width == 16)) {
  12889. ExtType = ISD::ZEXTLOAD;
  12890. return true;
  12891. }
  12892. return false;
  12893. }
  12894. case ISD::Constant:
  12895. case ISD::TargetConstant: {
  12896. return std::abs(cast<ConstantSDNode>(V.getNode())->getSExtValue()) <
  12897. 1LL << (width - 1);
  12898. }
  12899. }
  12900. return true;
  12901. }
  12902. // This function does a whole lot of voodoo to determine if the tests are
  12903. // equivalent without and with a mask. Essentially what happens is that given a
  12904. // DAG resembling:
  12905. //
  12906. // +-------------+ +-------------+ +-------------+ +-------------+
  12907. // | Input | | AddConstant | | CompConstant| | CC |
  12908. // +-------------+ +-------------+ +-------------+ +-------------+
  12909. // | | | |
  12910. // V V | +----------+
  12911. // +-------------+ +----+ | |
  12912. // | ADD | |0xff| | |
  12913. // +-------------+ +----+ | |
  12914. // | | | |
  12915. // V V | |
  12916. // +-------------+ | |
  12917. // | AND | | |
  12918. // +-------------+ | |
  12919. // | | |
  12920. // +-----+ | |
  12921. // | | |
  12922. // V V V
  12923. // +-------------+
  12924. // | CMP |
  12925. // +-------------+
  12926. //
  12927. // The AND node may be safely removed for some combinations of inputs. In
  12928. // particular we need to take into account the extension type of the Input,
  12929. // the exact values of AddConstant, CompConstant, and CC, along with the nominal
  12930. // width of the input (this can work for any width inputs, the above graph is
  12931. // specific to 8 bits.
  12932. //
  12933. // The specific equations were worked out by generating output tables for each
  12934. // AArch64CC value in terms of and AddConstant (w1), CompConstant(w2). The
  12935. // problem was simplified by working with 4 bit inputs, which means we only
  12936. // needed to reason about 24 distinct bit patterns: 8 patterns unique to zero
  12937. // extension (8,15), 8 patterns unique to sign extensions (-8,-1), and 8
  12938. // patterns present in both extensions (0,7). For every distinct set of
  12939. // AddConstant and CompConstants bit patterns we can consider the masked and
  12940. // unmasked versions to be equivalent if the result of this function is true for
  12941. // all 16 distinct bit patterns of for the current extension type of Input (w0).
  12942. //
  12943. // sub w8, w0, w1
  12944. // and w10, w8, #0x0f
  12945. // cmp w8, w2
  12946. // cset w9, AArch64CC
  12947. // cmp w10, w2
  12948. // cset w11, AArch64CC
  12949. // cmp w9, w11
  12950. // cset w0, eq
  12951. // ret
  12952. //
  12953. // Since the above function shows when the outputs are equivalent it defines
  12954. // when it is safe to remove the AND. Unfortunately it only runs on AArch64 and
  12955. // would be expensive to run during compiles. The equations below were written
  12956. // in a test harness that confirmed they gave equivalent outputs to the above
  12957. // for all inputs function, so they can be used determine if the removal is
  12958. // legal instead.
  12959. //
  12960. // isEquivalentMaskless() is the code for testing if the AND can be removed
  12961. // factored out of the DAG recognition as the DAG can take several forms.
  12962. static bool isEquivalentMaskless(unsigned CC, unsigned width,
  12963. ISD::LoadExtType ExtType, int AddConstant,
  12964. int CompConstant) {
  12965. // By being careful about our equations and only writing the in term
  12966. // symbolic values and well known constants (0, 1, -1, MaxUInt) we can
  12967. // make them generally applicable to all bit widths.
  12968. int MaxUInt = (1 << width);
  12969. // For the purposes of these comparisons sign extending the type is
  12970. // equivalent to zero extending the add and displacing it by half the integer
  12971. // width. Provided we are careful and make sure our equations are valid over
  12972. // the whole range we can just adjust the input and avoid writing equations
  12973. // for sign extended inputs.
  12974. if (ExtType == ISD::SEXTLOAD)
  12975. AddConstant -= (1 << (width-1));
  12976. switch(CC) {
  12977. case AArch64CC::LE:
  12978. case AArch64CC::GT:
  12979. if ((AddConstant == 0) ||
  12980. (CompConstant == MaxUInt - 1 && AddConstant < 0) ||
  12981. (AddConstant >= 0 && CompConstant < 0) ||
  12982. (AddConstant <= 0 && CompConstant <= 0 && CompConstant < AddConstant))
  12983. return true;
  12984. break;
  12985. case AArch64CC::LT:
  12986. case AArch64CC::GE:
  12987. if ((AddConstant == 0) ||
  12988. (AddConstant >= 0 && CompConstant <= 0) ||
  12989. (AddConstant <= 0 && CompConstant <= 0 && CompConstant <= AddConstant))
  12990. return true;
  12991. break;
  12992. case AArch64CC::HI:
  12993. case AArch64CC::LS:
  12994. if ((AddConstant >= 0 && CompConstant < 0) ||
  12995. (AddConstant <= 0 && CompConstant >= -1 &&
  12996. CompConstant < AddConstant + MaxUInt))
  12997. return true;
  12998. break;
  12999. case AArch64CC::PL:
  13000. case AArch64CC::MI:
  13001. if ((AddConstant == 0) ||
  13002. (AddConstant > 0 && CompConstant <= 0) ||
  13003. (AddConstant < 0 && CompConstant <= AddConstant))
  13004. return true;
  13005. break;
  13006. case AArch64CC::LO:
  13007. case AArch64CC::HS:
  13008. if ((AddConstant >= 0 && CompConstant <= 0) ||
  13009. (AddConstant <= 0 && CompConstant >= 0 &&
  13010. CompConstant <= AddConstant + MaxUInt))
  13011. return true;
  13012. break;
  13013. case AArch64CC::EQ:
  13014. case AArch64CC::NE:
  13015. if ((AddConstant > 0 && CompConstant < 0) ||
  13016. (AddConstant < 0 && CompConstant >= 0 &&
  13017. CompConstant < AddConstant + MaxUInt) ||
  13018. (AddConstant >= 0 && CompConstant >= 0 &&
  13019. CompConstant >= AddConstant) ||
  13020. (AddConstant <= 0 && CompConstant < 0 && CompConstant < AddConstant))
  13021. return true;
  13022. break;
  13023. case AArch64CC::VS:
  13024. case AArch64CC::VC:
  13025. case AArch64CC::AL:
  13026. case AArch64CC::NV:
  13027. return true;
  13028. case AArch64CC::Invalid:
  13029. break;
  13030. }
  13031. return false;
  13032. }
  13033. static
  13034. SDValue performCONDCombine(SDNode *N,
  13035. TargetLowering::DAGCombinerInfo &DCI,
  13036. SelectionDAG &DAG, unsigned CCIndex,
  13037. unsigned CmpIndex) {
  13038. unsigned CC = cast<ConstantSDNode>(N->getOperand(CCIndex))->getSExtValue();
  13039. SDNode *SubsNode = N->getOperand(CmpIndex).getNode();
  13040. unsigned CondOpcode = SubsNode->getOpcode();
  13041. if (CondOpcode != AArch64ISD::SUBS)
  13042. return SDValue();
  13043. // There is a SUBS feeding this condition. Is it fed by a mask we can
  13044. // use?
  13045. SDNode *AndNode = SubsNode->getOperand(0).getNode();
  13046. unsigned MaskBits = 0;
  13047. if (AndNode->getOpcode() != ISD::AND)
  13048. return SDValue();
  13049. if (ConstantSDNode *CN = dyn_cast<ConstantSDNode>(AndNode->getOperand(1))) {
  13050. uint32_t CNV = CN->getZExtValue();
  13051. if (CNV == 255)
  13052. MaskBits = 8;
  13053. else if (CNV == 65535)
  13054. MaskBits = 16;
  13055. }
  13056. if (!MaskBits)
  13057. return SDValue();
  13058. SDValue AddValue = AndNode->getOperand(0);
  13059. if (AddValue.getOpcode() != ISD::ADD)
  13060. return SDValue();
  13061. // The basic dag structure is correct, grab the inputs and validate them.
  13062. SDValue AddInputValue1 = AddValue.getNode()->getOperand(0);
  13063. SDValue AddInputValue2 = AddValue.getNode()->getOperand(1);
  13064. SDValue SubsInputValue = SubsNode->getOperand(1);
  13065. // The mask is present and the provenance of all the values is a smaller type,
  13066. // lets see if the mask is superfluous.
  13067. if (!isa<ConstantSDNode>(AddInputValue2.getNode()) ||
  13068. !isa<ConstantSDNode>(SubsInputValue.getNode()))
  13069. return SDValue();
  13070. ISD::LoadExtType ExtType;
  13071. if (!checkValueWidth(SubsInputValue, MaskBits, ExtType) ||
  13072. !checkValueWidth(AddInputValue2, MaskBits, ExtType) ||
  13073. !checkValueWidth(AddInputValue1, MaskBits, ExtType) )
  13074. return SDValue();
  13075. if(!isEquivalentMaskless(CC, MaskBits, ExtType,
  13076. cast<ConstantSDNode>(AddInputValue2.getNode())->getSExtValue(),
  13077. cast<ConstantSDNode>(SubsInputValue.getNode())->getSExtValue()))
  13078. return SDValue();
  13079. // The AND is not necessary, remove it.
  13080. SDVTList VTs = DAG.getVTList(SubsNode->getValueType(0),
  13081. SubsNode->getValueType(1));
  13082. SDValue Ops[] = { AddValue, SubsNode->getOperand(1) };
  13083. SDValue NewValue = DAG.getNode(CondOpcode, SDLoc(SubsNode), VTs, Ops);
  13084. DAG.ReplaceAllUsesWith(SubsNode, NewValue.getNode());
  13085. return SDValue(N, 0);
  13086. }
  13087. // Optimize compare with zero and branch.
  13088. static SDValue performBRCONDCombine(SDNode *N,
  13089. TargetLowering::DAGCombinerInfo &DCI,
  13090. SelectionDAG &DAG) {
  13091. MachineFunction &MF = DAG.getMachineFunction();
  13092. // Speculation tracking/SLH assumes that optimized TB(N)Z/CB(N)Z instructions
  13093. // will not be produced, as they are conditional branch instructions that do
  13094. // not set flags.
  13095. if (MF.getFunction().hasFnAttribute(Attribute::SpeculativeLoadHardening))
  13096. return SDValue();
  13097. if (SDValue NV = performCONDCombine(N, DCI, DAG, 2, 3))
  13098. N = NV.getNode();
  13099. SDValue Chain = N->getOperand(0);
  13100. SDValue Dest = N->getOperand(1);
  13101. SDValue CCVal = N->getOperand(2);
  13102. SDValue Cmp = N->getOperand(3);
  13103. assert(isa<ConstantSDNode>(CCVal) && "Expected a ConstantSDNode here!");
  13104. unsigned CC = cast<ConstantSDNode>(CCVal)->getZExtValue();
  13105. if (CC != AArch64CC::EQ && CC != AArch64CC::NE)
  13106. return SDValue();
  13107. unsigned CmpOpc = Cmp.getOpcode();
  13108. if (CmpOpc != AArch64ISD::ADDS && CmpOpc != AArch64ISD::SUBS)
  13109. return SDValue();
  13110. // Only attempt folding if there is only one use of the flag and no use of the
  13111. // value.
  13112. if (!Cmp->hasNUsesOfValue(0, 0) || !Cmp->hasNUsesOfValue(1, 1))
  13113. return SDValue();
  13114. SDValue LHS = Cmp.getOperand(0);
  13115. SDValue RHS = Cmp.getOperand(1);
  13116. assert(LHS.getValueType() == RHS.getValueType() &&
  13117. "Expected the value type to be the same for both operands!");
  13118. if (LHS.getValueType() != MVT::i32 && LHS.getValueType() != MVT::i64)
  13119. return SDValue();
  13120. if (isNullConstant(LHS))
  13121. std::swap(LHS, RHS);
  13122. if (!isNullConstant(RHS))
  13123. return SDValue();
  13124. if (LHS.getOpcode() == ISD::SHL || LHS.getOpcode() == ISD::SRA ||
  13125. LHS.getOpcode() == ISD::SRL)
  13126. return SDValue();
  13127. // Fold the compare into the branch instruction.
  13128. SDValue BR;
  13129. if (CC == AArch64CC::EQ)
  13130. BR = DAG.getNode(AArch64ISD::CBZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
  13131. else
  13132. BR = DAG.getNode(AArch64ISD::CBNZ, SDLoc(N), MVT::Other, Chain, LHS, Dest);
  13133. // Do not add new nodes to DAG combiner worklist.
  13134. DCI.CombineTo(N, BR, false);
  13135. return SDValue();
  13136. }
  13137. // Optimize some simple tbz/tbnz cases. Returns the new operand and bit to test
  13138. // as well as whether the test should be inverted. This code is required to
  13139. // catch these cases (as opposed to standard dag combines) because
  13140. // AArch64ISD::TBZ is matched during legalization.
  13141. static SDValue getTestBitOperand(SDValue Op, unsigned &Bit, bool &Invert,
  13142. SelectionDAG &DAG) {
  13143. if (!Op->hasOneUse())
  13144. return Op;
  13145. // We don't handle undef/constant-fold cases below, as they should have
  13146. // already been taken care of (e.g. and of 0, test of undefined shifted bits,
  13147. // etc.)
  13148. // (tbz (trunc x), b) -> (tbz x, b)
  13149. // This case is just here to enable more of the below cases to be caught.
  13150. if (Op->getOpcode() == ISD::TRUNCATE &&
  13151. Bit < Op->getValueType(0).getSizeInBits()) {
  13152. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  13153. }
  13154. // (tbz (any_ext x), b) -> (tbz x, b) if we don't use the extended bits.
  13155. if (Op->getOpcode() == ISD::ANY_EXTEND &&
  13156. Bit < Op->getOperand(0).getValueSizeInBits()) {
  13157. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  13158. }
  13159. if (Op->getNumOperands() != 2)
  13160. return Op;
  13161. auto *C = dyn_cast<ConstantSDNode>(Op->getOperand(1));
  13162. if (!C)
  13163. return Op;
  13164. switch (Op->getOpcode()) {
  13165. default:
  13166. return Op;
  13167. // (tbz (and x, m), b) -> (tbz x, b)
  13168. case ISD::AND:
  13169. if ((C->getZExtValue() >> Bit) & 1)
  13170. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  13171. return Op;
  13172. // (tbz (shl x, c), b) -> (tbz x, b-c)
  13173. case ISD::SHL:
  13174. if (C->getZExtValue() <= Bit &&
  13175. (Bit - C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
  13176. Bit = Bit - C->getZExtValue();
  13177. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  13178. }
  13179. return Op;
  13180. // (tbz (sra x, c), b) -> (tbz x, b+c) or (tbz x, msb) if b+c is > # bits in x
  13181. case ISD::SRA:
  13182. Bit = Bit + C->getZExtValue();
  13183. if (Bit >= Op->getValueType(0).getSizeInBits())
  13184. Bit = Op->getValueType(0).getSizeInBits() - 1;
  13185. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  13186. // (tbz (srl x, c), b) -> (tbz x, b+c)
  13187. case ISD::SRL:
  13188. if ((Bit + C->getZExtValue()) < Op->getValueType(0).getSizeInBits()) {
  13189. Bit = Bit + C->getZExtValue();
  13190. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  13191. }
  13192. return Op;
  13193. // (tbz (xor x, -1), b) -> (tbnz x, b)
  13194. case ISD::XOR:
  13195. if ((C->getZExtValue() >> Bit) & 1)
  13196. Invert = !Invert;
  13197. return getTestBitOperand(Op->getOperand(0), Bit, Invert, DAG);
  13198. }
  13199. }
  13200. // Optimize test single bit zero/non-zero and branch.
  13201. static SDValue performTBZCombine(SDNode *N,
  13202. TargetLowering::DAGCombinerInfo &DCI,
  13203. SelectionDAG &DAG) {
  13204. unsigned Bit = cast<ConstantSDNode>(N->getOperand(2))->getZExtValue();
  13205. bool Invert = false;
  13206. SDValue TestSrc = N->getOperand(1);
  13207. SDValue NewTestSrc = getTestBitOperand(TestSrc, Bit, Invert, DAG);
  13208. if (TestSrc == NewTestSrc)
  13209. return SDValue();
  13210. unsigned NewOpc = N->getOpcode();
  13211. if (Invert) {
  13212. if (NewOpc == AArch64ISD::TBZ)
  13213. NewOpc = AArch64ISD::TBNZ;
  13214. else {
  13215. assert(NewOpc == AArch64ISD::TBNZ);
  13216. NewOpc = AArch64ISD::TBZ;
  13217. }
  13218. }
  13219. SDLoc DL(N);
  13220. return DAG.getNode(NewOpc, DL, MVT::Other, N->getOperand(0), NewTestSrc,
  13221. DAG.getConstant(Bit, DL, MVT::i64), N->getOperand(3));
  13222. }
  13223. // vselect (v1i1 setcc) ->
  13224. // vselect (v1iXX setcc) (XX is the size of the compared operand type)
  13225. // FIXME: Currently the type legalizer can't handle VSELECT having v1i1 as
  13226. // condition. If it can legalize "VSELECT v1i1" correctly, no need to combine
  13227. // such VSELECT.
  13228. static SDValue performVSelectCombine(SDNode *N, SelectionDAG &DAG) {
  13229. SDValue N0 = N->getOperand(0);
  13230. EVT CCVT = N0.getValueType();
  13231. if (N0.getOpcode() != ISD::SETCC || CCVT.getVectorNumElements() != 1 ||
  13232. CCVT.getVectorElementType() != MVT::i1)
  13233. return SDValue();
  13234. EVT ResVT = N->getValueType(0);
  13235. EVT CmpVT = N0.getOperand(0).getValueType();
  13236. // Only combine when the result type is of the same size as the compared
  13237. // operands.
  13238. if (ResVT.getSizeInBits() != CmpVT.getSizeInBits())
  13239. return SDValue();
  13240. SDValue IfTrue = N->getOperand(1);
  13241. SDValue IfFalse = N->getOperand(2);
  13242. SDValue SetCC =
  13243. DAG.getSetCC(SDLoc(N), CmpVT.changeVectorElementTypeToInteger(),
  13244. N0.getOperand(0), N0.getOperand(1),
  13245. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  13246. return DAG.getNode(ISD::VSELECT, SDLoc(N), ResVT, SetCC,
  13247. IfTrue, IfFalse);
  13248. }
  13249. /// A vector select: "(select vL, vR, (setcc LHS, RHS))" is best performed with
  13250. /// the compare-mask instructions rather than going via NZCV, even if LHS and
  13251. /// RHS are really scalar. This replaces any scalar setcc in the above pattern
  13252. /// with a vector one followed by a DUP shuffle on the result.
  13253. static SDValue performSelectCombine(SDNode *N,
  13254. TargetLowering::DAGCombinerInfo &DCI) {
  13255. SelectionDAG &DAG = DCI.DAG;
  13256. SDValue N0 = N->getOperand(0);
  13257. EVT ResVT = N->getValueType(0);
  13258. if (N0.getOpcode() != ISD::SETCC)
  13259. return SDValue();
  13260. // Make sure the SETCC result is either i1 (initial DAG), or i32, the lowered
  13261. // scalar SetCCResultType. We also don't expect vectors, because we assume
  13262. // that selects fed by vector SETCCs are canonicalized to VSELECT.
  13263. assert((N0.getValueType() == MVT::i1 || N0.getValueType() == MVT::i32) &&
  13264. "Scalar-SETCC feeding SELECT has unexpected result type!");
  13265. // If NumMaskElts == 0, the comparison is larger than select result. The
  13266. // largest real NEON comparison is 64-bits per lane, which means the result is
  13267. // at most 32-bits and an illegal vector. Just bail out for now.
  13268. EVT SrcVT = N0.getOperand(0).getValueType();
  13269. // Don't try to do this optimization when the setcc itself has i1 operands.
  13270. // There are no legal vectors of i1, so this would be pointless.
  13271. if (SrcVT == MVT::i1)
  13272. return SDValue();
  13273. int NumMaskElts = ResVT.getSizeInBits() / SrcVT.getSizeInBits();
  13274. if (!ResVT.isVector() || NumMaskElts == 0)
  13275. return SDValue();
  13276. SrcVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumMaskElts);
  13277. EVT CCVT = SrcVT.changeVectorElementTypeToInteger();
  13278. // Also bail out if the vector CCVT isn't the same size as ResVT.
  13279. // This can happen if the SETCC operand size doesn't divide the ResVT size
  13280. // (e.g., f64 vs v3f32).
  13281. if (CCVT.getSizeInBits() != ResVT.getSizeInBits())
  13282. return SDValue();
  13283. // Make sure we didn't create illegal types, if we're not supposed to.
  13284. assert(DCI.isBeforeLegalize() ||
  13285. DAG.getTargetLoweringInfo().isTypeLegal(SrcVT));
  13286. // First perform a vector comparison, where lane 0 is the one we're interested
  13287. // in.
  13288. SDLoc DL(N0);
  13289. SDValue LHS =
  13290. DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(0));
  13291. SDValue RHS =
  13292. DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, SrcVT, N0.getOperand(1));
  13293. SDValue SetCC = DAG.getNode(ISD::SETCC, DL, CCVT, LHS, RHS, N0.getOperand(2));
  13294. // Now duplicate the comparison mask we want across all other lanes.
  13295. SmallVector<int, 8> DUPMask(CCVT.getVectorNumElements(), 0);
  13296. SDValue Mask = DAG.getVectorShuffle(CCVT, DL, SetCC, SetCC, DUPMask);
  13297. Mask = DAG.getNode(ISD::BITCAST, DL,
  13298. ResVT.changeVectorElementTypeToInteger(), Mask);
  13299. return DAG.getSelect(DL, ResVT, Mask, N->getOperand(1), N->getOperand(2));
  13300. }
  13301. /// Get rid of unnecessary NVCASTs (that don't change the type).
  13302. static SDValue performNVCASTCombine(SDNode *N) {
  13303. if (N->getValueType(0) == N->getOperand(0).getValueType())
  13304. return N->getOperand(0);
  13305. return SDValue();
  13306. }
  13307. // If all users of the globaladdr are of the form (globaladdr + constant), find
  13308. // the smallest constant, fold it into the globaladdr's offset and rewrite the
  13309. // globaladdr as (globaladdr + constant) - constant.
  13310. static SDValue performGlobalAddressCombine(SDNode *N, SelectionDAG &DAG,
  13311. const AArch64Subtarget *Subtarget,
  13312. const TargetMachine &TM) {
  13313. auto *GN = cast<GlobalAddressSDNode>(N);
  13314. if (Subtarget->ClassifyGlobalReference(GN->getGlobal(), TM) !=
  13315. AArch64II::MO_NO_FLAG)
  13316. return SDValue();
  13317. uint64_t MinOffset = -1ull;
  13318. for (SDNode *N : GN->uses()) {
  13319. if (N->getOpcode() != ISD::ADD)
  13320. return SDValue();
  13321. auto *C = dyn_cast<ConstantSDNode>(N->getOperand(0));
  13322. if (!C)
  13323. C = dyn_cast<ConstantSDNode>(N->getOperand(1));
  13324. if (!C)
  13325. return SDValue();
  13326. MinOffset = std::min(MinOffset, C->getZExtValue());
  13327. }
  13328. uint64_t Offset = MinOffset + GN->getOffset();
  13329. // Require that the new offset is larger than the existing one. Otherwise, we
  13330. // can end up oscillating between two possible DAGs, for example,
  13331. // (add (add globaladdr + 10, -1), 1) and (add globaladdr + 9, 1).
  13332. if (Offset <= uint64_t(GN->getOffset()))
  13333. return SDValue();
  13334. // Check whether folding this offset is legal. It must not go out of bounds of
  13335. // the referenced object to avoid violating the code model, and must be
  13336. // smaller than 2^21 because this is the largest offset expressible in all
  13337. // object formats.
  13338. //
  13339. // This check also prevents us from folding negative offsets, which will end
  13340. // up being treated in the same way as large positive ones. They could also
  13341. // cause code model violations, and aren't really common enough to matter.
  13342. if (Offset >= (1 << 21))
  13343. return SDValue();
  13344. const GlobalValue *GV = GN->getGlobal();
  13345. Type *T = GV->getValueType();
  13346. if (!T->isSized() ||
  13347. Offset > GV->getParent()->getDataLayout().getTypeAllocSize(T))
  13348. return SDValue();
  13349. SDLoc DL(GN);
  13350. SDValue Result = DAG.getGlobalAddress(GV, DL, MVT::i64, Offset);
  13351. return DAG.getNode(ISD::SUB, DL, MVT::i64, Result,
  13352. DAG.getConstant(MinOffset, DL, MVT::i64));
  13353. }
  13354. // Turns the vector of indices into a vector of byte offstes by scaling Offset
  13355. // by (BitWidth / 8).
  13356. static SDValue getScaledOffsetForBitWidth(SelectionDAG &DAG, SDValue Offset,
  13357. SDLoc DL, unsigned BitWidth) {
  13358. assert(Offset.getValueType().isScalableVector() &&
  13359. "This method is only for scalable vectors of offsets");
  13360. SDValue Shift = DAG.getConstant(Log2_32(BitWidth / 8), DL, MVT::i64);
  13361. SDValue SplatShift = DAG.getNode(ISD::SPLAT_VECTOR, DL, MVT::nxv2i64, Shift);
  13362. return DAG.getNode(ISD::SHL, DL, MVT::nxv2i64, Offset, SplatShift);
  13363. }
  13364. /// Check if the value of \p OffsetInBytes can be used as an immediate for
  13365. /// the gather load/prefetch and scatter store instructions with vector base and
  13366. /// immediate offset addressing mode:
  13367. ///
  13368. /// [<Zn>.[S|D]{, #<imm>}]
  13369. ///
  13370. /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
  13371. inline static bool isValidImmForSVEVecImmAddrMode(unsigned OffsetInBytes,
  13372. unsigned ScalarSizeInBytes) {
  13373. // The immediate is not a multiple of the scalar size.
  13374. if (OffsetInBytes % ScalarSizeInBytes)
  13375. return false;
  13376. // The immediate is out of range.
  13377. if (OffsetInBytes / ScalarSizeInBytes > 31)
  13378. return false;
  13379. return true;
  13380. }
  13381. /// Check if the value of \p Offset represents a valid immediate for the SVE
  13382. /// gather load/prefetch and scatter store instructiona with vector base and
  13383. /// immediate offset addressing mode:
  13384. ///
  13385. /// [<Zn>.[S|D]{, #<imm>}]
  13386. ///
  13387. /// where <imm> = sizeof(<T>) * k, for k = 0, 1, ..., 31.
  13388. static bool isValidImmForSVEVecImmAddrMode(SDValue Offset,
  13389. unsigned ScalarSizeInBytes) {
  13390. ConstantSDNode *OffsetConst = dyn_cast<ConstantSDNode>(Offset.getNode());
  13391. return OffsetConst && isValidImmForSVEVecImmAddrMode(
  13392. OffsetConst->getZExtValue(), ScalarSizeInBytes);
  13393. }
  13394. static SDValue performScatterStoreCombine(SDNode *N, SelectionDAG &DAG,
  13395. unsigned Opcode,
  13396. bool OnlyPackedOffsets = true) {
  13397. const SDValue Src = N->getOperand(2);
  13398. const EVT SrcVT = Src->getValueType(0);
  13399. assert(SrcVT.isScalableVector() &&
  13400. "Scatter stores are only possible for SVE vectors");
  13401. SDLoc DL(N);
  13402. MVT SrcElVT = SrcVT.getVectorElementType().getSimpleVT();
  13403. // Make sure that source data will fit into an SVE register
  13404. if (SrcVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
  13405. return SDValue();
  13406. // For FPs, ACLE only supports _packed_ single and double precision types.
  13407. if (SrcElVT.isFloatingPoint())
  13408. if ((SrcVT != MVT::nxv4f32) && (SrcVT != MVT::nxv2f64))
  13409. return SDValue();
  13410. // Depending on the addressing mode, this is either a pointer or a vector of
  13411. // pointers (that fits into one register)
  13412. SDValue Base = N->getOperand(4);
  13413. // Depending on the addressing mode, this is either a single offset or a
  13414. // vector of offsets (that fits into one register)
  13415. SDValue Offset = N->getOperand(5);
  13416. // For "scalar + vector of indices", just scale the indices. This only
  13417. // applies to non-temporal scatters because there's no instruction that takes
  13418. // indicies.
  13419. if (Opcode == AArch64ISD::SSTNT1_INDEX_PRED) {
  13420. Offset =
  13421. getScaledOffsetForBitWidth(DAG, Offset, DL, SrcElVT.getSizeInBits());
  13422. Opcode = AArch64ISD::SSTNT1_PRED;
  13423. }
  13424. // In the case of non-temporal gather loads there's only one SVE instruction
  13425. // per data-size: "scalar + vector", i.e.
  13426. // * stnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
  13427. // Since we do have intrinsics that allow the arguments to be in a different
  13428. // order, we may need to swap them to match the spec.
  13429. if (Opcode == AArch64ISD::SSTNT1_PRED && Offset.getValueType().isVector())
  13430. std::swap(Base, Offset);
  13431. // SST1_IMM requires that the offset is an immediate that is:
  13432. // * a multiple of #SizeInBytes,
  13433. // * in the range [0, 31 x #SizeInBytes],
  13434. // where #SizeInBytes is the size in bytes of the stored items. For
  13435. // immediates outside that range and non-immediate scalar offsets use SST1 or
  13436. // SST1_UXTW instead.
  13437. if (Opcode == AArch64ISD::SST1_IMM_PRED) {
  13438. if (!isValidImmForSVEVecImmAddrMode(Offset,
  13439. SrcVT.getScalarSizeInBits() / 8)) {
  13440. if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
  13441. Opcode = AArch64ISD::SST1_UXTW_PRED;
  13442. else
  13443. Opcode = AArch64ISD::SST1_PRED;
  13444. std::swap(Base, Offset);
  13445. }
  13446. }
  13447. auto &TLI = DAG.getTargetLoweringInfo();
  13448. if (!TLI.isTypeLegal(Base.getValueType()))
  13449. return SDValue();
  13450. // Some scatter store variants allow unpacked offsets, but only as nxv2i32
  13451. // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
  13452. // nxv2i64. Legalize accordingly.
  13453. if (!OnlyPackedOffsets &&
  13454. Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
  13455. Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
  13456. if (!TLI.isTypeLegal(Offset.getValueType()))
  13457. return SDValue();
  13458. // Source value type that is representable in hardware
  13459. EVT HwSrcVt = getSVEContainerType(SrcVT);
  13460. // Keep the original type of the input data to store - this is needed to be
  13461. // able to select the correct instruction, e.g. ST1B, ST1H, ST1W and ST1D. For
  13462. // FP values we want the integer equivalent, so just use HwSrcVt.
  13463. SDValue InputVT = DAG.getValueType(SrcVT);
  13464. if (SrcVT.isFloatingPoint())
  13465. InputVT = DAG.getValueType(HwSrcVt);
  13466. SDVTList VTs = DAG.getVTList(MVT::Other);
  13467. SDValue SrcNew;
  13468. if (Src.getValueType().isFloatingPoint())
  13469. SrcNew = DAG.getNode(ISD::BITCAST, DL, HwSrcVt, Src);
  13470. else
  13471. SrcNew = DAG.getNode(ISD::ANY_EXTEND, DL, HwSrcVt, Src);
  13472. SDValue Ops[] = {N->getOperand(0), // Chain
  13473. SrcNew,
  13474. N->getOperand(3), // Pg
  13475. Base,
  13476. Offset,
  13477. InputVT};
  13478. return DAG.getNode(Opcode, DL, VTs, Ops);
  13479. }
  13480. static SDValue performGatherLoadCombine(SDNode *N, SelectionDAG &DAG,
  13481. unsigned Opcode,
  13482. bool OnlyPackedOffsets = true) {
  13483. const EVT RetVT = N->getValueType(0);
  13484. assert(RetVT.isScalableVector() &&
  13485. "Gather loads are only possible for SVE vectors");
  13486. SDLoc DL(N);
  13487. // Make sure that the loaded data will fit into an SVE register
  13488. if (RetVT.getSizeInBits().getKnownMinSize() > AArch64::SVEBitsPerBlock)
  13489. return SDValue();
  13490. // Depending on the addressing mode, this is either a pointer or a vector of
  13491. // pointers (that fits into one register)
  13492. SDValue Base = N->getOperand(3);
  13493. // Depending on the addressing mode, this is either a single offset or a
  13494. // vector of offsets (that fits into one register)
  13495. SDValue Offset = N->getOperand(4);
  13496. // For "scalar + vector of indices", just scale the indices. This only
  13497. // applies to non-temporal gathers because there's no instruction that takes
  13498. // indicies.
  13499. if (Opcode == AArch64ISD::GLDNT1_INDEX_MERGE_ZERO) {
  13500. Offset = getScaledOffsetForBitWidth(DAG, Offset, DL,
  13501. RetVT.getScalarSizeInBits());
  13502. Opcode = AArch64ISD::GLDNT1_MERGE_ZERO;
  13503. }
  13504. // In the case of non-temporal gather loads there's only one SVE instruction
  13505. // per data-size: "scalar + vector", i.e.
  13506. // * ldnt1{b|h|w|d} { z0.s }, p0/z, [z0.s, x0]
  13507. // Since we do have intrinsics that allow the arguments to be in a different
  13508. // order, we may need to swap them to match the spec.
  13509. if (Opcode == AArch64ISD::GLDNT1_MERGE_ZERO &&
  13510. Offset.getValueType().isVector())
  13511. std::swap(Base, Offset);
  13512. // GLD{FF}1_IMM requires that the offset is an immediate that is:
  13513. // * a multiple of #SizeInBytes,
  13514. // * in the range [0, 31 x #SizeInBytes],
  13515. // where #SizeInBytes is the size in bytes of the loaded items. For
  13516. // immediates outside that range and non-immediate scalar offsets use
  13517. // GLD1_MERGE_ZERO or GLD1_UXTW_MERGE_ZERO instead.
  13518. if (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO ||
  13519. Opcode == AArch64ISD::GLDFF1_IMM_MERGE_ZERO) {
  13520. if (!isValidImmForSVEVecImmAddrMode(Offset,
  13521. RetVT.getScalarSizeInBits() / 8)) {
  13522. if (MVT::nxv4i32 == Base.getValueType().getSimpleVT().SimpleTy)
  13523. Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
  13524. ? AArch64ISD::GLD1_UXTW_MERGE_ZERO
  13525. : AArch64ISD::GLDFF1_UXTW_MERGE_ZERO;
  13526. else
  13527. Opcode = (Opcode == AArch64ISD::GLD1_IMM_MERGE_ZERO)
  13528. ? AArch64ISD::GLD1_MERGE_ZERO
  13529. : AArch64ISD::GLDFF1_MERGE_ZERO;
  13530. std::swap(Base, Offset);
  13531. }
  13532. }
  13533. auto &TLI = DAG.getTargetLoweringInfo();
  13534. if (!TLI.isTypeLegal(Base.getValueType()))
  13535. return SDValue();
  13536. // Some gather load variants allow unpacked offsets, but only as nxv2i32
  13537. // vectors. These are implicitly sign (sxtw) or zero (zxtw) extend to
  13538. // nxv2i64. Legalize accordingly.
  13539. if (!OnlyPackedOffsets &&
  13540. Offset.getValueType().getSimpleVT().SimpleTy == MVT::nxv2i32)
  13541. Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset).getValue(0);
  13542. // Return value type that is representable in hardware
  13543. EVT HwRetVt = getSVEContainerType(RetVT);
  13544. // Keep the original output value type around - this is needed to be able to
  13545. // select the correct instruction, e.g. LD1B, LD1H, LD1W and LD1D. For FP
  13546. // values we want the integer equivalent, so just use HwRetVT.
  13547. SDValue OutVT = DAG.getValueType(RetVT);
  13548. if (RetVT.isFloatingPoint())
  13549. OutVT = DAG.getValueType(HwRetVt);
  13550. SDVTList VTs = DAG.getVTList(HwRetVt, MVT::Other);
  13551. SDValue Ops[] = {N->getOperand(0), // Chain
  13552. N->getOperand(2), // Pg
  13553. Base, Offset, OutVT};
  13554. SDValue Load = DAG.getNode(Opcode, DL, VTs, Ops);
  13555. SDValue LoadChain = SDValue(Load.getNode(), 1);
  13556. if (RetVT.isInteger() && (RetVT != HwRetVt))
  13557. Load = DAG.getNode(ISD::TRUNCATE, DL, RetVT, Load.getValue(0));
  13558. // If the original return value was FP, bitcast accordingly. Doing it here
  13559. // means that we can avoid adding TableGen patterns for FPs.
  13560. if (RetVT.isFloatingPoint())
  13561. Load = DAG.getNode(ISD::BITCAST, DL, RetVT, Load.getValue(0));
  13562. return DAG.getMergeValues({Load, LoadChain}, DL);
  13563. }
  13564. static SDValue
  13565. performSignExtendInRegCombine(SDNode *N, TargetLowering::DAGCombinerInfo &DCI,
  13566. SelectionDAG &DAG) {
  13567. SDLoc DL(N);
  13568. SDValue Src = N->getOperand(0);
  13569. unsigned Opc = Src->getOpcode();
  13570. // Sign extend of an unsigned unpack -> signed unpack
  13571. if (Opc == AArch64ISD::UUNPKHI || Opc == AArch64ISD::UUNPKLO) {
  13572. unsigned SOpc = Opc == AArch64ISD::UUNPKHI ? AArch64ISD::SUNPKHI
  13573. : AArch64ISD::SUNPKLO;
  13574. // Push the sign extend to the operand of the unpack
  13575. // This is necessary where, for example, the operand of the unpack
  13576. // is another unpack:
  13577. // 4i32 sign_extend_inreg (4i32 uunpklo(8i16 uunpklo (16i8 opnd)), from 4i8)
  13578. // ->
  13579. // 4i32 sunpklo (8i16 sign_extend_inreg(8i16 uunpklo (16i8 opnd), from 8i8)
  13580. // ->
  13581. // 4i32 sunpklo(8i16 sunpklo(16i8 opnd))
  13582. SDValue ExtOp = Src->getOperand(0);
  13583. auto VT = cast<VTSDNode>(N->getOperand(1))->getVT();
  13584. EVT EltTy = VT.getVectorElementType();
  13585. (void)EltTy;
  13586. assert((EltTy == MVT::i8 || EltTy == MVT::i16 || EltTy == MVT::i32) &&
  13587. "Sign extending from an invalid type");
  13588. EVT ExtVT = VT.getDoubleNumVectorElementsVT(*DAG.getContext());
  13589. SDValue Ext = DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, ExtOp.getValueType(),
  13590. ExtOp, DAG.getValueType(ExtVT));
  13591. return DAG.getNode(SOpc, DL, N->getValueType(0), Ext);
  13592. }
  13593. if (DCI.isBeforeLegalizeOps())
  13594. return SDValue();
  13595. if (!EnableCombineMGatherIntrinsics)
  13596. return SDValue();
  13597. // SVE load nodes (e.g. AArch64ISD::GLD1) are straightforward candidates
  13598. // for DAG Combine with SIGN_EXTEND_INREG. Bail out for all other nodes.
  13599. unsigned NewOpc;
  13600. unsigned MemVTOpNum = 4;
  13601. switch (Opc) {
  13602. case AArch64ISD::LD1_MERGE_ZERO:
  13603. NewOpc = AArch64ISD::LD1S_MERGE_ZERO;
  13604. MemVTOpNum = 3;
  13605. break;
  13606. case AArch64ISD::LDNF1_MERGE_ZERO:
  13607. NewOpc = AArch64ISD::LDNF1S_MERGE_ZERO;
  13608. MemVTOpNum = 3;
  13609. break;
  13610. case AArch64ISD::LDFF1_MERGE_ZERO:
  13611. NewOpc = AArch64ISD::LDFF1S_MERGE_ZERO;
  13612. MemVTOpNum = 3;
  13613. break;
  13614. case AArch64ISD::GLD1_MERGE_ZERO:
  13615. NewOpc = AArch64ISD::GLD1S_MERGE_ZERO;
  13616. break;
  13617. case AArch64ISD::GLD1_SCALED_MERGE_ZERO:
  13618. NewOpc = AArch64ISD::GLD1S_SCALED_MERGE_ZERO;
  13619. break;
  13620. case AArch64ISD::GLD1_SXTW_MERGE_ZERO:
  13621. NewOpc = AArch64ISD::GLD1S_SXTW_MERGE_ZERO;
  13622. break;
  13623. case AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO:
  13624. NewOpc = AArch64ISD::GLD1S_SXTW_SCALED_MERGE_ZERO;
  13625. break;
  13626. case AArch64ISD::GLD1_UXTW_MERGE_ZERO:
  13627. NewOpc = AArch64ISD::GLD1S_UXTW_MERGE_ZERO;
  13628. break;
  13629. case AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO:
  13630. NewOpc = AArch64ISD::GLD1S_UXTW_SCALED_MERGE_ZERO;
  13631. break;
  13632. case AArch64ISD::GLD1_IMM_MERGE_ZERO:
  13633. NewOpc = AArch64ISD::GLD1S_IMM_MERGE_ZERO;
  13634. break;
  13635. case AArch64ISD::GLDFF1_MERGE_ZERO:
  13636. NewOpc = AArch64ISD::GLDFF1S_MERGE_ZERO;
  13637. break;
  13638. case AArch64ISD::GLDFF1_SCALED_MERGE_ZERO:
  13639. NewOpc = AArch64ISD::GLDFF1S_SCALED_MERGE_ZERO;
  13640. break;
  13641. case AArch64ISD::GLDFF1_SXTW_MERGE_ZERO:
  13642. NewOpc = AArch64ISD::GLDFF1S_SXTW_MERGE_ZERO;
  13643. break;
  13644. case AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO:
  13645. NewOpc = AArch64ISD::GLDFF1S_SXTW_SCALED_MERGE_ZERO;
  13646. break;
  13647. case AArch64ISD::GLDFF1_UXTW_MERGE_ZERO:
  13648. NewOpc = AArch64ISD::GLDFF1S_UXTW_MERGE_ZERO;
  13649. break;
  13650. case AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO:
  13651. NewOpc = AArch64ISD::GLDFF1S_UXTW_SCALED_MERGE_ZERO;
  13652. break;
  13653. case AArch64ISD::GLDFF1_IMM_MERGE_ZERO:
  13654. NewOpc = AArch64ISD::GLDFF1S_IMM_MERGE_ZERO;
  13655. break;
  13656. case AArch64ISD::GLDNT1_MERGE_ZERO:
  13657. NewOpc = AArch64ISD::GLDNT1S_MERGE_ZERO;
  13658. break;
  13659. default:
  13660. return SDValue();
  13661. }
  13662. EVT SignExtSrcVT = cast<VTSDNode>(N->getOperand(1))->getVT();
  13663. EVT SrcMemVT = cast<VTSDNode>(Src->getOperand(MemVTOpNum))->getVT();
  13664. if ((SignExtSrcVT != SrcMemVT) || !Src.hasOneUse())
  13665. return SDValue();
  13666. EVT DstVT = N->getValueType(0);
  13667. SDVTList VTs = DAG.getVTList(DstVT, MVT::Other);
  13668. SmallVector<SDValue, 5> Ops;
  13669. for (unsigned I = 0; I < Src->getNumOperands(); ++I)
  13670. Ops.push_back(Src->getOperand(I));
  13671. SDValue ExtLoad = DAG.getNode(NewOpc, SDLoc(N), VTs, Ops);
  13672. DCI.CombineTo(N, ExtLoad);
  13673. DCI.CombineTo(Src.getNode(), ExtLoad, ExtLoad.getValue(1));
  13674. // Return N so it doesn't get rechecked
  13675. return SDValue(N, 0);
  13676. }
  13677. /// Legalize the gather prefetch (scalar + vector addressing mode) when the
  13678. /// offset vector is an unpacked 32-bit scalable vector. The other cases (Offset
  13679. /// != nxv2i32) do not need legalization.
  13680. static SDValue legalizeSVEGatherPrefetchOffsVec(SDNode *N, SelectionDAG &DAG) {
  13681. const unsigned OffsetPos = 4;
  13682. SDValue Offset = N->getOperand(OffsetPos);
  13683. // Not an unpacked vector, bail out.
  13684. if (Offset.getValueType().getSimpleVT().SimpleTy != MVT::nxv2i32)
  13685. return SDValue();
  13686. // Extend the unpacked offset vector to 64-bit lanes.
  13687. SDLoc DL(N);
  13688. Offset = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::nxv2i64, Offset);
  13689. SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
  13690. // Replace the offset operand with the 64-bit one.
  13691. Ops[OffsetPos] = Offset;
  13692. return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
  13693. }
  13694. /// Combines a node carrying the intrinsic
  13695. /// `aarch64_sve_prf<T>_gather_scalar_offset` into a node that uses
  13696. /// `aarch64_sve_prfb_gather_uxtw_index` when the scalar offset passed to
  13697. /// `aarch64_sve_prf<T>_gather_scalar_offset` is not a valid immediate for the
  13698. /// sve gather prefetch instruction with vector plus immediate addressing mode.
  13699. static SDValue combineSVEPrefetchVecBaseImmOff(SDNode *N, SelectionDAG &DAG,
  13700. unsigned ScalarSizeInBytes) {
  13701. const unsigned ImmPos = 4, OffsetPos = 3;
  13702. // No need to combine the node if the immediate is valid...
  13703. if (isValidImmForSVEVecImmAddrMode(N->getOperand(ImmPos), ScalarSizeInBytes))
  13704. return SDValue();
  13705. // ...otherwise swap the offset base with the offset...
  13706. SmallVector<SDValue, 5> Ops(N->op_begin(), N->op_end());
  13707. std::swap(Ops[ImmPos], Ops[OffsetPos]);
  13708. // ...and remap the intrinsic `aarch64_sve_prf<T>_gather_scalar_offset` to
  13709. // `aarch64_sve_prfb_gather_uxtw_index`.
  13710. SDLoc DL(N);
  13711. Ops[1] = DAG.getConstant(Intrinsic::aarch64_sve_prfb_gather_uxtw_index, DL,
  13712. MVT::i64);
  13713. return DAG.getNode(N->getOpcode(), DL, DAG.getVTList(MVT::Other), Ops);
  13714. }
  13715. SDValue AArch64TargetLowering::PerformDAGCombine(SDNode *N,
  13716. DAGCombinerInfo &DCI) const {
  13717. SelectionDAG &DAG = DCI.DAG;
  13718. switch (N->getOpcode()) {
  13719. default:
  13720. LLVM_DEBUG(dbgs() << "Custom combining: skipping\n");
  13721. break;
  13722. case ISD::ABS:
  13723. return performABSCombine(N, DAG, DCI, Subtarget);
  13724. case ISD::ADD:
  13725. case ISD::SUB:
  13726. return performAddSubCombine(N, DCI, DAG);
  13727. case ISD::XOR:
  13728. return performXorCombine(N, DAG, DCI, Subtarget);
  13729. case ISD::MUL:
  13730. return performMulCombine(N, DAG, DCI, Subtarget);
  13731. case ISD::SINT_TO_FP:
  13732. case ISD::UINT_TO_FP:
  13733. return performIntToFpCombine(N, DAG, Subtarget);
  13734. case ISD::FP_TO_SINT:
  13735. case ISD::FP_TO_UINT:
  13736. return performFpToIntCombine(N, DAG, DCI, Subtarget);
  13737. case ISD::FDIV:
  13738. return performFDivCombine(N, DAG, DCI, Subtarget);
  13739. case ISD::OR:
  13740. return performORCombine(N, DCI, Subtarget);
  13741. case ISD::AND:
  13742. return performANDCombine(N, DCI);
  13743. case ISD::SRL:
  13744. return performSRLCombine(N, DCI);
  13745. case ISD::INTRINSIC_WO_CHAIN:
  13746. return performIntrinsicCombine(N, DCI, Subtarget);
  13747. case ISD::ANY_EXTEND:
  13748. case ISD::ZERO_EXTEND:
  13749. case ISD::SIGN_EXTEND:
  13750. return performExtendCombine(N, DCI, DAG);
  13751. case ISD::SIGN_EXTEND_INREG:
  13752. return performSignExtendInRegCombine(N, DCI, DAG);
  13753. case ISD::TRUNCATE:
  13754. return performVectorTruncateCombine(N, DCI, DAG);
  13755. case ISD::CONCAT_VECTORS:
  13756. return performConcatVectorsCombine(N, DCI, DAG);
  13757. case ISD::SELECT:
  13758. return performSelectCombine(N, DCI);
  13759. case ISD::VSELECT:
  13760. return performVSelectCombine(N, DCI.DAG);
  13761. case ISD::LOAD:
  13762. if (performTBISimplification(N->getOperand(1), DCI, DAG))
  13763. return SDValue(N, 0);
  13764. break;
  13765. case ISD::STORE:
  13766. return performSTORECombine(N, DCI, DAG, Subtarget);
  13767. case ISD::MGATHER:
  13768. case ISD::MSCATTER:
  13769. return performMaskedGatherScatterCombine(N, DCI, DAG);
  13770. case AArch64ISD::BRCOND:
  13771. return performBRCONDCombine(N, DCI, DAG);
  13772. case AArch64ISD::TBNZ:
  13773. case AArch64ISD::TBZ:
  13774. return performTBZCombine(N, DCI, DAG);
  13775. case AArch64ISD::CSEL:
  13776. return performCONDCombine(N, DCI, DAG, 2, 3);
  13777. case AArch64ISD::DUP:
  13778. return performPostLD1Combine(N, DCI, false);
  13779. case AArch64ISD::NVCAST:
  13780. return performNVCASTCombine(N);
  13781. case AArch64ISD::UZP1:
  13782. return performUzpCombine(N, DAG);
  13783. case ISD::INSERT_VECTOR_ELT:
  13784. return performPostLD1Combine(N, DCI, true);
  13785. case ISD::EXTRACT_VECTOR_ELT:
  13786. return performExtractVectorEltCombine(N, DAG);
  13787. case ISD::VECREDUCE_ADD:
  13788. return performVecReduceAddCombine(N, DCI.DAG, Subtarget);
  13789. case ISD::INTRINSIC_VOID:
  13790. case ISD::INTRINSIC_W_CHAIN:
  13791. switch (cast<ConstantSDNode>(N->getOperand(1))->getZExtValue()) {
  13792. case Intrinsic::aarch64_sve_prfb_gather_scalar_offset:
  13793. return combineSVEPrefetchVecBaseImmOff(N, DAG, 1 /*=ScalarSizeInBytes*/);
  13794. case Intrinsic::aarch64_sve_prfh_gather_scalar_offset:
  13795. return combineSVEPrefetchVecBaseImmOff(N, DAG, 2 /*=ScalarSizeInBytes*/);
  13796. case Intrinsic::aarch64_sve_prfw_gather_scalar_offset:
  13797. return combineSVEPrefetchVecBaseImmOff(N, DAG, 4 /*=ScalarSizeInBytes*/);
  13798. case Intrinsic::aarch64_sve_prfd_gather_scalar_offset:
  13799. return combineSVEPrefetchVecBaseImmOff(N, DAG, 8 /*=ScalarSizeInBytes*/);
  13800. case Intrinsic::aarch64_sve_prfb_gather_uxtw_index:
  13801. case Intrinsic::aarch64_sve_prfb_gather_sxtw_index:
  13802. case Intrinsic::aarch64_sve_prfh_gather_uxtw_index:
  13803. case Intrinsic::aarch64_sve_prfh_gather_sxtw_index:
  13804. case Intrinsic::aarch64_sve_prfw_gather_uxtw_index:
  13805. case Intrinsic::aarch64_sve_prfw_gather_sxtw_index:
  13806. case Intrinsic::aarch64_sve_prfd_gather_uxtw_index:
  13807. case Intrinsic::aarch64_sve_prfd_gather_sxtw_index:
  13808. return legalizeSVEGatherPrefetchOffsVec(N, DAG);
  13809. case Intrinsic::aarch64_neon_ld2:
  13810. case Intrinsic::aarch64_neon_ld3:
  13811. case Intrinsic::aarch64_neon_ld4:
  13812. case Intrinsic::aarch64_neon_ld1x2:
  13813. case Intrinsic::aarch64_neon_ld1x3:
  13814. case Intrinsic::aarch64_neon_ld1x4:
  13815. case Intrinsic::aarch64_neon_ld2lane:
  13816. case Intrinsic::aarch64_neon_ld3lane:
  13817. case Intrinsic::aarch64_neon_ld4lane:
  13818. case Intrinsic::aarch64_neon_ld2r:
  13819. case Intrinsic::aarch64_neon_ld3r:
  13820. case Intrinsic::aarch64_neon_ld4r:
  13821. case Intrinsic::aarch64_neon_st2:
  13822. case Intrinsic::aarch64_neon_st3:
  13823. case Intrinsic::aarch64_neon_st4:
  13824. case Intrinsic::aarch64_neon_st1x2:
  13825. case Intrinsic::aarch64_neon_st1x3:
  13826. case Intrinsic::aarch64_neon_st1x4:
  13827. case Intrinsic::aarch64_neon_st2lane:
  13828. case Intrinsic::aarch64_neon_st3lane:
  13829. case Intrinsic::aarch64_neon_st4lane:
  13830. return performNEONPostLDSTCombine(N, DCI, DAG);
  13831. case Intrinsic::aarch64_sve_ldnt1:
  13832. return performLDNT1Combine(N, DAG);
  13833. case Intrinsic::aarch64_sve_ld1rq:
  13834. return performLD1ReplicateCombine<AArch64ISD::LD1RQ_MERGE_ZERO>(N, DAG);
  13835. case Intrinsic::aarch64_sve_ld1ro:
  13836. return performLD1ReplicateCombine<AArch64ISD::LD1RO_MERGE_ZERO>(N, DAG);
  13837. case Intrinsic::aarch64_sve_ldnt1_gather_scalar_offset:
  13838. return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
  13839. case Intrinsic::aarch64_sve_ldnt1_gather:
  13840. return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
  13841. case Intrinsic::aarch64_sve_ldnt1_gather_index:
  13842. return performGatherLoadCombine(N, DAG,
  13843. AArch64ISD::GLDNT1_INDEX_MERGE_ZERO);
  13844. case Intrinsic::aarch64_sve_ldnt1_gather_uxtw:
  13845. return performGatherLoadCombine(N, DAG, AArch64ISD::GLDNT1_MERGE_ZERO);
  13846. case Intrinsic::aarch64_sve_ld1:
  13847. return performLD1Combine(N, DAG, AArch64ISD::LD1_MERGE_ZERO);
  13848. case Intrinsic::aarch64_sve_ldnf1:
  13849. return performLD1Combine(N, DAG, AArch64ISD::LDNF1_MERGE_ZERO);
  13850. case Intrinsic::aarch64_sve_ldff1:
  13851. return performLD1Combine(N, DAG, AArch64ISD::LDFF1_MERGE_ZERO);
  13852. case Intrinsic::aarch64_sve_st1:
  13853. return performST1Combine(N, DAG);
  13854. case Intrinsic::aarch64_sve_stnt1:
  13855. return performSTNT1Combine(N, DAG);
  13856. case Intrinsic::aarch64_sve_stnt1_scatter_scalar_offset:
  13857. return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
  13858. case Intrinsic::aarch64_sve_stnt1_scatter_uxtw:
  13859. return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
  13860. case Intrinsic::aarch64_sve_stnt1_scatter:
  13861. return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_PRED);
  13862. case Intrinsic::aarch64_sve_stnt1_scatter_index:
  13863. return performScatterStoreCombine(N, DAG, AArch64ISD::SSTNT1_INDEX_PRED);
  13864. case Intrinsic::aarch64_sve_ld1_gather:
  13865. return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_MERGE_ZERO);
  13866. case Intrinsic::aarch64_sve_ld1_gather_index:
  13867. return performGatherLoadCombine(N, DAG,
  13868. AArch64ISD::GLD1_SCALED_MERGE_ZERO);
  13869. case Intrinsic::aarch64_sve_ld1_gather_sxtw:
  13870. return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_SXTW_MERGE_ZERO,
  13871. /*OnlyPackedOffsets=*/false);
  13872. case Intrinsic::aarch64_sve_ld1_gather_uxtw:
  13873. return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_UXTW_MERGE_ZERO,
  13874. /*OnlyPackedOffsets=*/false);
  13875. case Intrinsic::aarch64_sve_ld1_gather_sxtw_index:
  13876. return performGatherLoadCombine(N, DAG,
  13877. AArch64ISD::GLD1_SXTW_SCALED_MERGE_ZERO,
  13878. /*OnlyPackedOffsets=*/false);
  13879. case Intrinsic::aarch64_sve_ld1_gather_uxtw_index:
  13880. return performGatherLoadCombine(N, DAG,
  13881. AArch64ISD::GLD1_UXTW_SCALED_MERGE_ZERO,
  13882. /*OnlyPackedOffsets=*/false);
  13883. case Intrinsic::aarch64_sve_ld1_gather_scalar_offset:
  13884. return performGatherLoadCombine(N, DAG, AArch64ISD::GLD1_IMM_MERGE_ZERO);
  13885. case Intrinsic::aarch64_sve_ldff1_gather:
  13886. return performGatherLoadCombine(N, DAG, AArch64ISD::GLDFF1_MERGE_ZERO);
  13887. case Intrinsic::aarch64_sve_ldff1_gather_index:
  13888. return performGatherLoadCombine(N, DAG,
  13889. AArch64ISD::GLDFF1_SCALED_MERGE_ZERO);
  13890. case Intrinsic::aarch64_sve_ldff1_gather_sxtw:
  13891. return performGatherLoadCombine(N, DAG,
  13892. AArch64ISD::GLDFF1_SXTW_MERGE_ZERO,
  13893. /*OnlyPackedOffsets=*/false);
  13894. case Intrinsic::aarch64_sve_ldff1_gather_uxtw:
  13895. return performGatherLoadCombine(N, DAG,
  13896. AArch64ISD::GLDFF1_UXTW_MERGE_ZERO,
  13897. /*OnlyPackedOffsets=*/false);
  13898. case Intrinsic::aarch64_sve_ldff1_gather_sxtw_index:
  13899. return performGatherLoadCombine(N, DAG,
  13900. AArch64ISD::GLDFF1_SXTW_SCALED_MERGE_ZERO,
  13901. /*OnlyPackedOffsets=*/false);
  13902. case Intrinsic::aarch64_sve_ldff1_gather_uxtw_index:
  13903. return performGatherLoadCombine(N, DAG,
  13904. AArch64ISD::GLDFF1_UXTW_SCALED_MERGE_ZERO,
  13905. /*OnlyPackedOffsets=*/false);
  13906. case Intrinsic::aarch64_sve_ldff1_gather_scalar_offset:
  13907. return performGatherLoadCombine(N, DAG,
  13908. AArch64ISD::GLDFF1_IMM_MERGE_ZERO);
  13909. case Intrinsic::aarch64_sve_st1_scatter:
  13910. return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_PRED);
  13911. case Intrinsic::aarch64_sve_st1_scatter_index:
  13912. return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SCALED_PRED);
  13913. case Intrinsic::aarch64_sve_st1_scatter_sxtw:
  13914. return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_SXTW_PRED,
  13915. /*OnlyPackedOffsets=*/false);
  13916. case Intrinsic::aarch64_sve_st1_scatter_uxtw:
  13917. return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_UXTW_PRED,
  13918. /*OnlyPackedOffsets=*/false);
  13919. case Intrinsic::aarch64_sve_st1_scatter_sxtw_index:
  13920. return performScatterStoreCombine(N, DAG,
  13921. AArch64ISD::SST1_SXTW_SCALED_PRED,
  13922. /*OnlyPackedOffsets=*/false);
  13923. case Intrinsic::aarch64_sve_st1_scatter_uxtw_index:
  13924. return performScatterStoreCombine(N, DAG,
  13925. AArch64ISD::SST1_UXTW_SCALED_PRED,
  13926. /*OnlyPackedOffsets=*/false);
  13927. case Intrinsic::aarch64_sve_st1_scatter_scalar_offset:
  13928. return performScatterStoreCombine(N, DAG, AArch64ISD::SST1_IMM_PRED);
  13929. case Intrinsic::aarch64_sve_tuple_get: {
  13930. SDLoc DL(N);
  13931. SDValue Chain = N->getOperand(0);
  13932. SDValue Src1 = N->getOperand(2);
  13933. SDValue Idx = N->getOperand(3);
  13934. uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
  13935. EVT ResVT = N->getValueType(0);
  13936. uint64_t NumLanes = ResVT.getVectorElementCount().getKnownMinValue();
  13937. SDValue ExtIdx = DAG.getVectorIdxConstant(IdxConst * NumLanes, DL);
  13938. SDValue Val =
  13939. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, ResVT, Src1, ExtIdx);
  13940. return DAG.getMergeValues({Val, Chain}, DL);
  13941. }
  13942. case Intrinsic::aarch64_sve_tuple_set: {
  13943. SDLoc DL(N);
  13944. SDValue Chain = N->getOperand(0);
  13945. SDValue Tuple = N->getOperand(2);
  13946. SDValue Idx = N->getOperand(3);
  13947. SDValue Vec = N->getOperand(4);
  13948. EVT TupleVT = Tuple.getValueType();
  13949. uint64_t TupleLanes = TupleVT.getVectorElementCount().getKnownMinValue();
  13950. uint64_t IdxConst = cast<ConstantSDNode>(Idx)->getZExtValue();
  13951. uint64_t NumLanes =
  13952. Vec.getValueType().getVectorElementCount().getKnownMinValue();
  13953. if ((TupleLanes % NumLanes) != 0)
  13954. report_fatal_error("invalid tuple vector!");
  13955. uint64_t NumVecs = TupleLanes / NumLanes;
  13956. SmallVector<SDValue, 4> Opnds;
  13957. for (unsigned I = 0; I < NumVecs; ++I) {
  13958. if (I == IdxConst)
  13959. Opnds.push_back(Vec);
  13960. else {
  13961. SDValue ExtIdx = DAG.getVectorIdxConstant(I * NumLanes, DL);
  13962. Opnds.push_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL,
  13963. Vec.getValueType(), Tuple, ExtIdx));
  13964. }
  13965. }
  13966. SDValue Concat =
  13967. DAG.getNode(ISD::CONCAT_VECTORS, DL, Tuple.getValueType(), Opnds);
  13968. return DAG.getMergeValues({Concat, Chain}, DL);
  13969. }
  13970. case Intrinsic::aarch64_sve_tuple_create2:
  13971. case Intrinsic::aarch64_sve_tuple_create3:
  13972. case Intrinsic::aarch64_sve_tuple_create4: {
  13973. SDLoc DL(N);
  13974. SDValue Chain = N->getOperand(0);
  13975. SmallVector<SDValue, 4> Opnds;
  13976. for (unsigned I = 2; I < N->getNumOperands(); ++I)
  13977. Opnds.push_back(N->getOperand(I));
  13978. EVT VT = Opnds[0].getValueType();
  13979. EVT EltVT = VT.getVectorElementType();
  13980. EVT DestVT = EVT::getVectorVT(*DAG.getContext(), EltVT,
  13981. VT.getVectorElementCount() *
  13982. (N->getNumOperands() - 2));
  13983. SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, DL, DestVT, Opnds);
  13984. return DAG.getMergeValues({Concat, Chain}, DL);
  13985. }
  13986. case Intrinsic::aarch64_sve_ld2:
  13987. case Intrinsic::aarch64_sve_ld3:
  13988. case Intrinsic::aarch64_sve_ld4: {
  13989. SDLoc DL(N);
  13990. SDValue Chain = N->getOperand(0);
  13991. SDValue Mask = N->getOperand(2);
  13992. SDValue BasePtr = N->getOperand(3);
  13993. SDValue LoadOps[] = {Chain, Mask, BasePtr};
  13994. unsigned IntrinsicID =
  13995. cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
  13996. SDValue Result =
  13997. LowerSVEStructLoad(IntrinsicID, LoadOps, N->getValueType(0), DAG, DL);
  13998. return DAG.getMergeValues({Result, Chain}, DL);
  13999. }
  14000. default:
  14001. break;
  14002. }
  14003. break;
  14004. case ISD::GlobalAddress:
  14005. return performGlobalAddressCombine(N, DAG, Subtarget, getTargetMachine());
  14006. }
  14007. return SDValue();
  14008. }
  14009. // Check if the return value is used as only a return value, as otherwise
  14010. // we can't perform a tail-call. In particular, we need to check for
  14011. // target ISD nodes that are returns and any other "odd" constructs
  14012. // that the generic analysis code won't necessarily catch.
  14013. bool AArch64TargetLowering::isUsedByReturnOnly(SDNode *N,
  14014. SDValue &Chain) const {
  14015. if (N->getNumValues() != 1)
  14016. return false;
  14017. if (!N->hasNUsesOfValue(1, 0))
  14018. return false;
  14019. SDValue TCChain = Chain;
  14020. SDNode *Copy = *N->use_begin();
  14021. if (Copy->getOpcode() == ISD::CopyToReg) {
  14022. // If the copy has a glue operand, we conservatively assume it isn't safe to
  14023. // perform a tail call.
  14024. if (Copy->getOperand(Copy->getNumOperands() - 1).getValueType() ==
  14025. MVT::Glue)
  14026. return false;
  14027. TCChain = Copy->getOperand(0);
  14028. } else if (Copy->getOpcode() != ISD::FP_EXTEND)
  14029. return false;
  14030. bool HasRet = false;
  14031. for (SDNode *Node : Copy->uses()) {
  14032. if (Node->getOpcode() != AArch64ISD::RET_FLAG)
  14033. return false;
  14034. HasRet = true;
  14035. }
  14036. if (!HasRet)
  14037. return false;
  14038. Chain = TCChain;
  14039. return true;
  14040. }
  14041. // Return whether the an instruction can potentially be optimized to a tail
  14042. // call. This will cause the optimizers to attempt to move, or duplicate,
  14043. // return instructions to help enable tail call optimizations for this
  14044. // instruction.
  14045. bool AArch64TargetLowering::mayBeEmittedAsTailCall(const CallInst *CI) const {
  14046. return CI->isTailCall();
  14047. }
  14048. bool AArch64TargetLowering::getIndexedAddressParts(SDNode *Op, SDValue &Base,
  14049. SDValue &Offset,
  14050. ISD::MemIndexedMode &AM,
  14051. bool &IsInc,
  14052. SelectionDAG &DAG) const {
  14053. if (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB)
  14054. return false;
  14055. Base = Op->getOperand(0);
  14056. // All of the indexed addressing mode instructions take a signed
  14057. // 9 bit immediate offset.
  14058. if (ConstantSDNode *RHS = dyn_cast<ConstantSDNode>(Op->getOperand(1))) {
  14059. int64_t RHSC = RHS->getSExtValue();
  14060. if (Op->getOpcode() == ISD::SUB)
  14061. RHSC = -(uint64_t)RHSC;
  14062. if (!isInt<9>(RHSC))
  14063. return false;
  14064. IsInc = (Op->getOpcode() == ISD::ADD);
  14065. Offset = Op->getOperand(1);
  14066. return true;
  14067. }
  14068. return false;
  14069. }
  14070. bool AArch64TargetLowering::getPreIndexedAddressParts(SDNode *N, SDValue &Base,
  14071. SDValue &Offset,
  14072. ISD::MemIndexedMode &AM,
  14073. SelectionDAG &DAG) const {
  14074. EVT VT;
  14075. SDValue Ptr;
  14076. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
  14077. VT = LD->getMemoryVT();
  14078. Ptr = LD->getBasePtr();
  14079. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
  14080. VT = ST->getMemoryVT();
  14081. Ptr = ST->getBasePtr();
  14082. } else
  14083. return false;
  14084. bool IsInc;
  14085. if (!getIndexedAddressParts(Ptr.getNode(), Base, Offset, AM, IsInc, DAG))
  14086. return false;
  14087. AM = IsInc ? ISD::PRE_INC : ISD::PRE_DEC;
  14088. return true;
  14089. }
  14090. bool AArch64TargetLowering::getPostIndexedAddressParts(
  14091. SDNode *N, SDNode *Op, SDValue &Base, SDValue &Offset,
  14092. ISD::MemIndexedMode &AM, SelectionDAG &DAG) const {
  14093. EVT VT;
  14094. SDValue Ptr;
  14095. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
  14096. VT = LD->getMemoryVT();
  14097. Ptr = LD->getBasePtr();
  14098. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
  14099. VT = ST->getMemoryVT();
  14100. Ptr = ST->getBasePtr();
  14101. } else
  14102. return false;
  14103. bool IsInc;
  14104. if (!getIndexedAddressParts(Op, Base, Offset, AM, IsInc, DAG))
  14105. return false;
  14106. // Post-indexing updates the base, so it's not a valid transform
  14107. // if that's not the same as the load's pointer.
  14108. if (Ptr != Base)
  14109. return false;
  14110. AM = IsInc ? ISD::POST_INC : ISD::POST_DEC;
  14111. return true;
  14112. }
  14113. static void ReplaceBITCASTResults(SDNode *N, SmallVectorImpl<SDValue> &Results,
  14114. SelectionDAG &DAG) {
  14115. SDLoc DL(N);
  14116. SDValue Op = N->getOperand(0);
  14117. if (N->getValueType(0) != MVT::i16 ||
  14118. (Op.getValueType() != MVT::f16 && Op.getValueType() != MVT::bf16))
  14119. return;
  14120. Op = SDValue(
  14121. DAG.getMachineNode(TargetOpcode::INSERT_SUBREG, DL, MVT::f32,
  14122. DAG.getUNDEF(MVT::i32), Op,
  14123. DAG.getTargetConstant(AArch64::hsub, DL, MVT::i32)),
  14124. 0);
  14125. Op = DAG.getNode(ISD::BITCAST, DL, MVT::i32, Op);
  14126. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, MVT::i16, Op));
  14127. }
  14128. static void ReplaceReductionResults(SDNode *N,
  14129. SmallVectorImpl<SDValue> &Results,
  14130. SelectionDAG &DAG, unsigned InterOp,
  14131. unsigned AcrossOp) {
  14132. EVT LoVT, HiVT;
  14133. SDValue Lo, Hi;
  14134. SDLoc dl(N);
  14135. std::tie(LoVT, HiVT) = DAG.GetSplitDestVTs(N->getValueType(0));
  14136. std::tie(Lo, Hi) = DAG.SplitVectorOperand(N, 0);
  14137. SDValue InterVal = DAG.getNode(InterOp, dl, LoVT, Lo, Hi);
  14138. SDValue SplitVal = DAG.getNode(AcrossOp, dl, LoVT, InterVal);
  14139. Results.push_back(SplitVal);
  14140. }
  14141. static std::pair<SDValue, SDValue> splitInt128(SDValue N, SelectionDAG &DAG) {
  14142. SDLoc DL(N);
  14143. SDValue Lo = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64, N);
  14144. SDValue Hi = DAG.getNode(ISD::TRUNCATE, DL, MVT::i64,
  14145. DAG.getNode(ISD::SRL, DL, MVT::i128, N,
  14146. DAG.getConstant(64, DL, MVT::i64)));
  14147. return std::make_pair(Lo, Hi);
  14148. }
  14149. void AArch64TargetLowering::ReplaceExtractSubVectorResults(
  14150. SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
  14151. SDValue In = N->getOperand(0);
  14152. EVT InVT = In.getValueType();
  14153. // Common code will handle these just fine.
  14154. if (!InVT.isScalableVector() || !InVT.isInteger())
  14155. return;
  14156. SDLoc DL(N);
  14157. EVT VT = N->getValueType(0);
  14158. // The following checks bail if this is not a halving operation.
  14159. ElementCount ResEC = VT.getVectorElementCount();
  14160. if (InVT.getVectorElementCount() != (ResEC * 2))
  14161. return;
  14162. auto *CIndex = dyn_cast<ConstantSDNode>(N->getOperand(1));
  14163. if (!CIndex)
  14164. return;
  14165. unsigned Index = CIndex->getZExtValue();
  14166. if ((Index != 0) && (Index != ResEC.getKnownMinValue()))
  14167. return;
  14168. unsigned Opcode = (Index == 0) ? AArch64ISD::UUNPKLO : AArch64ISD::UUNPKHI;
  14169. EVT ExtendedHalfVT = VT.widenIntegerVectorElementType(*DAG.getContext());
  14170. SDValue Half = DAG.getNode(Opcode, DL, ExtendedHalfVT, N->getOperand(0));
  14171. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, Half));
  14172. }
  14173. // Create an even/odd pair of X registers holding integer value V.
  14174. static SDValue createGPRPairNode(SelectionDAG &DAG, SDValue V) {
  14175. SDLoc dl(V.getNode());
  14176. SDValue VLo = DAG.getAnyExtOrTrunc(V, dl, MVT::i64);
  14177. SDValue VHi = DAG.getAnyExtOrTrunc(
  14178. DAG.getNode(ISD::SRL, dl, MVT::i128, V, DAG.getConstant(64, dl, MVT::i64)),
  14179. dl, MVT::i64);
  14180. if (DAG.getDataLayout().isBigEndian())
  14181. std::swap (VLo, VHi);
  14182. SDValue RegClass =
  14183. DAG.getTargetConstant(AArch64::XSeqPairsClassRegClassID, dl, MVT::i32);
  14184. SDValue SubReg0 = DAG.getTargetConstant(AArch64::sube64, dl, MVT::i32);
  14185. SDValue SubReg1 = DAG.getTargetConstant(AArch64::subo64, dl, MVT::i32);
  14186. const SDValue Ops[] = { RegClass, VLo, SubReg0, VHi, SubReg1 };
  14187. return SDValue(
  14188. DAG.getMachineNode(TargetOpcode::REG_SEQUENCE, dl, MVT::Untyped, Ops), 0);
  14189. }
  14190. static void ReplaceCMP_SWAP_128Results(SDNode *N,
  14191. SmallVectorImpl<SDValue> &Results,
  14192. SelectionDAG &DAG,
  14193. const AArch64Subtarget *Subtarget) {
  14194. assert(N->getValueType(0) == MVT::i128 &&
  14195. "AtomicCmpSwap on types less than 128 should be legal");
  14196. if (Subtarget->hasLSE() || Subtarget->outlineAtomics()) {
  14197. // LSE has a 128-bit compare and swap (CASP), but i128 is not a legal type,
  14198. // so lower it here, wrapped in REG_SEQUENCE and EXTRACT_SUBREG.
  14199. SDValue Ops[] = {
  14200. createGPRPairNode(DAG, N->getOperand(2)), // Compare value
  14201. createGPRPairNode(DAG, N->getOperand(3)), // Store value
  14202. N->getOperand(1), // Ptr
  14203. N->getOperand(0), // Chain in
  14204. };
  14205. MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
  14206. unsigned Opcode;
  14207. switch (MemOp->getOrdering()) {
  14208. case AtomicOrdering::Monotonic:
  14209. Opcode = AArch64::CASPX;
  14210. break;
  14211. case AtomicOrdering::Acquire:
  14212. Opcode = AArch64::CASPAX;
  14213. break;
  14214. case AtomicOrdering::Release:
  14215. Opcode = AArch64::CASPLX;
  14216. break;
  14217. case AtomicOrdering::AcquireRelease:
  14218. case AtomicOrdering::SequentiallyConsistent:
  14219. Opcode = AArch64::CASPALX;
  14220. break;
  14221. default:
  14222. llvm_unreachable("Unexpected ordering!");
  14223. }
  14224. MachineSDNode *CmpSwap = DAG.getMachineNode(
  14225. Opcode, SDLoc(N), DAG.getVTList(MVT::Untyped, MVT::Other), Ops);
  14226. DAG.setNodeMemRefs(CmpSwap, {MemOp});
  14227. unsigned SubReg1 = AArch64::sube64, SubReg2 = AArch64::subo64;
  14228. if (DAG.getDataLayout().isBigEndian())
  14229. std::swap(SubReg1, SubReg2);
  14230. SDValue Lo = DAG.getTargetExtractSubreg(SubReg1, SDLoc(N), MVT::i64,
  14231. SDValue(CmpSwap, 0));
  14232. SDValue Hi = DAG.getTargetExtractSubreg(SubReg2, SDLoc(N), MVT::i64,
  14233. SDValue(CmpSwap, 0));
  14234. Results.push_back(
  14235. DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128, Lo, Hi));
  14236. Results.push_back(SDValue(CmpSwap, 1)); // Chain out
  14237. return;
  14238. }
  14239. auto Desired = splitInt128(N->getOperand(2), DAG);
  14240. auto New = splitInt128(N->getOperand(3), DAG);
  14241. SDValue Ops[] = {N->getOperand(1), Desired.first, Desired.second,
  14242. New.first, New.second, N->getOperand(0)};
  14243. SDNode *CmpSwap = DAG.getMachineNode(
  14244. AArch64::CMP_SWAP_128, SDLoc(N),
  14245. DAG.getVTList(MVT::i64, MVT::i64, MVT::i32, MVT::Other), Ops);
  14246. MachineMemOperand *MemOp = cast<MemSDNode>(N)->getMemOperand();
  14247. DAG.setNodeMemRefs(cast<MachineSDNode>(CmpSwap), {MemOp});
  14248. Results.push_back(DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
  14249. SDValue(CmpSwap, 0), SDValue(CmpSwap, 1)));
  14250. Results.push_back(SDValue(CmpSwap, 3));
  14251. }
  14252. void AArch64TargetLowering::ReplaceNodeResults(
  14253. SDNode *N, SmallVectorImpl<SDValue> &Results, SelectionDAG &DAG) const {
  14254. switch (N->getOpcode()) {
  14255. default:
  14256. llvm_unreachable("Don't know how to custom expand this");
  14257. case ISD::BITCAST:
  14258. ReplaceBITCASTResults(N, Results, DAG);
  14259. return;
  14260. case ISD::VECREDUCE_ADD:
  14261. case ISD::VECREDUCE_SMAX:
  14262. case ISD::VECREDUCE_SMIN:
  14263. case ISD::VECREDUCE_UMAX:
  14264. case ISD::VECREDUCE_UMIN:
  14265. Results.push_back(LowerVECREDUCE(SDValue(N, 0), DAG));
  14266. return;
  14267. case ISD::CTPOP:
  14268. if (SDValue Result = LowerCTPOP(SDValue(N, 0), DAG))
  14269. Results.push_back(Result);
  14270. return;
  14271. case AArch64ISD::SADDV:
  14272. ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::SADDV);
  14273. return;
  14274. case AArch64ISD::UADDV:
  14275. ReplaceReductionResults(N, Results, DAG, ISD::ADD, AArch64ISD::UADDV);
  14276. return;
  14277. case AArch64ISD::SMINV:
  14278. ReplaceReductionResults(N, Results, DAG, ISD::SMIN, AArch64ISD::SMINV);
  14279. return;
  14280. case AArch64ISD::UMINV:
  14281. ReplaceReductionResults(N, Results, DAG, ISD::UMIN, AArch64ISD::UMINV);
  14282. return;
  14283. case AArch64ISD::SMAXV:
  14284. ReplaceReductionResults(N, Results, DAG, ISD::SMAX, AArch64ISD::SMAXV);
  14285. return;
  14286. case AArch64ISD::UMAXV:
  14287. ReplaceReductionResults(N, Results, DAG, ISD::UMAX, AArch64ISD::UMAXV);
  14288. return;
  14289. case ISD::FP_TO_UINT:
  14290. case ISD::FP_TO_SINT:
  14291. assert(N->getValueType(0) == MVT::i128 && "unexpected illegal conversion");
  14292. // Let normal code take care of it by not adding anything to Results.
  14293. return;
  14294. case ISD::ATOMIC_CMP_SWAP:
  14295. ReplaceCMP_SWAP_128Results(N, Results, DAG, Subtarget);
  14296. return;
  14297. case ISD::LOAD: {
  14298. assert(SDValue(N, 0).getValueType() == MVT::i128 &&
  14299. "unexpected load's value type");
  14300. LoadSDNode *LoadNode = cast<LoadSDNode>(N);
  14301. if (!LoadNode->isVolatile() || LoadNode->getMemoryVT() != MVT::i128) {
  14302. // Non-volatile loads are optimized later in AArch64's load/store
  14303. // optimizer.
  14304. return;
  14305. }
  14306. SDValue Result = DAG.getMemIntrinsicNode(
  14307. AArch64ISD::LDP, SDLoc(N),
  14308. DAG.getVTList({MVT::i64, MVT::i64, MVT::Other}),
  14309. {LoadNode->getChain(), LoadNode->getBasePtr()}, LoadNode->getMemoryVT(),
  14310. LoadNode->getMemOperand());
  14311. SDValue Pair = DAG.getNode(ISD::BUILD_PAIR, SDLoc(N), MVT::i128,
  14312. Result.getValue(0), Result.getValue(1));
  14313. Results.append({Pair, Result.getValue(2) /* Chain */});
  14314. return;
  14315. }
  14316. case ISD::EXTRACT_SUBVECTOR:
  14317. ReplaceExtractSubVectorResults(N, Results, DAG);
  14318. return;
  14319. case ISD::INTRINSIC_WO_CHAIN: {
  14320. EVT VT = N->getValueType(0);
  14321. assert((VT == MVT::i8 || VT == MVT::i16) &&
  14322. "custom lowering for unexpected type");
  14323. ConstantSDNode *CN = cast<ConstantSDNode>(N->getOperand(0));
  14324. Intrinsic::ID IntID = static_cast<Intrinsic::ID>(CN->getZExtValue());
  14325. switch (IntID) {
  14326. default:
  14327. return;
  14328. case Intrinsic::aarch64_sve_clasta_n: {
  14329. SDLoc DL(N);
  14330. auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
  14331. auto V = DAG.getNode(AArch64ISD::CLASTA_N, DL, MVT::i32,
  14332. N->getOperand(1), Op2, N->getOperand(3));
  14333. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
  14334. return;
  14335. }
  14336. case Intrinsic::aarch64_sve_clastb_n: {
  14337. SDLoc DL(N);
  14338. auto Op2 = DAG.getNode(ISD::ANY_EXTEND, DL, MVT::i32, N->getOperand(2));
  14339. auto V = DAG.getNode(AArch64ISD::CLASTB_N, DL, MVT::i32,
  14340. N->getOperand(1), Op2, N->getOperand(3));
  14341. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
  14342. return;
  14343. }
  14344. case Intrinsic::aarch64_sve_lasta: {
  14345. SDLoc DL(N);
  14346. auto V = DAG.getNode(AArch64ISD::LASTA, DL, MVT::i32,
  14347. N->getOperand(1), N->getOperand(2));
  14348. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
  14349. return;
  14350. }
  14351. case Intrinsic::aarch64_sve_lastb: {
  14352. SDLoc DL(N);
  14353. auto V = DAG.getNode(AArch64ISD::LASTB, DL, MVT::i32,
  14354. N->getOperand(1), N->getOperand(2));
  14355. Results.push_back(DAG.getNode(ISD::TRUNCATE, DL, VT, V));
  14356. return;
  14357. }
  14358. }
  14359. }
  14360. }
  14361. }
  14362. bool AArch64TargetLowering::useLoadStackGuardNode() const {
  14363. if (Subtarget->isTargetAndroid() || Subtarget->isTargetFuchsia())
  14364. return TargetLowering::useLoadStackGuardNode();
  14365. return true;
  14366. }
  14367. unsigned AArch64TargetLowering::combineRepeatedFPDivisors() const {
  14368. // Combine multiple FDIVs with the same divisor into multiple FMULs by the
  14369. // reciprocal if there are three or more FDIVs.
  14370. return 3;
  14371. }
  14372. TargetLoweringBase::LegalizeTypeAction
  14373. AArch64TargetLowering::getPreferredVectorAction(MVT VT) const {
  14374. // During type legalization, we prefer to widen v1i8, v1i16, v1i32 to v8i8,
  14375. // v4i16, v2i32 instead of to promote.
  14376. if (VT == MVT::v1i8 || VT == MVT::v1i16 || VT == MVT::v1i32 ||
  14377. VT == MVT::v1f32)
  14378. return TypeWidenVector;
  14379. return TargetLoweringBase::getPreferredVectorAction(VT);
  14380. }
  14381. // Loads and stores less than 128-bits are already atomic; ones above that
  14382. // are doomed anyway, so defer to the default libcall and blame the OS when
  14383. // things go wrong.
  14384. bool AArch64TargetLowering::shouldExpandAtomicStoreInIR(StoreInst *SI) const {
  14385. unsigned Size = SI->getValueOperand()->getType()->getPrimitiveSizeInBits();
  14386. return Size == 128;
  14387. }
  14388. // Loads and stores less than 128-bits are already atomic; ones above that
  14389. // are doomed anyway, so defer to the default libcall and blame the OS when
  14390. // things go wrong.
  14391. TargetLowering::AtomicExpansionKind
  14392. AArch64TargetLowering::shouldExpandAtomicLoadInIR(LoadInst *LI) const {
  14393. unsigned Size = LI->getType()->getPrimitiveSizeInBits();
  14394. return Size == 128 ? AtomicExpansionKind::LLSC : AtomicExpansionKind::None;
  14395. }
  14396. // For the real atomic operations, we have ldxr/stxr up to 128 bits,
  14397. TargetLowering::AtomicExpansionKind
  14398. AArch64TargetLowering::shouldExpandAtomicRMWInIR(AtomicRMWInst *AI) const {
  14399. if (AI->isFloatingPointOperation())
  14400. return AtomicExpansionKind::CmpXChg;
  14401. unsigned Size = AI->getType()->getPrimitiveSizeInBits();
  14402. if (Size > 128) return AtomicExpansionKind::None;
  14403. // Nand is not supported in LSE.
  14404. // Leave 128 bits to LLSC or CmpXChg.
  14405. if (AI->getOperation() != AtomicRMWInst::Nand && Size < 128) {
  14406. if (Subtarget->hasLSE())
  14407. return AtomicExpansionKind::None;
  14408. if (Subtarget->outlineAtomics()) {
  14409. // [U]Min/[U]Max RWM atomics are used in __sync_fetch_ libcalls so far.
  14410. // Don't outline them unless
  14411. // (1) high level <atomic> support approved:
  14412. // http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p0493r1.pdf
  14413. // (2) low level libgcc and compiler-rt support implemented by:
  14414. // min/max outline atomics helpers
  14415. if (AI->getOperation() != AtomicRMWInst::Min &&
  14416. AI->getOperation() != AtomicRMWInst::Max &&
  14417. AI->getOperation() != AtomicRMWInst::UMin &&
  14418. AI->getOperation() != AtomicRMWInst::UMax) {
  14419. return AtomicExpansionKind::None;
  14420. }
  14421. }
  14422. }
  14423. // At -O0, fast-regalloc cannot cope with the live vregs necessary to
  14424. // implement atomicrmw without spilling. If the target address is also on the
  14425. // stack and close enough to the spill slot, this can lead to a situation
  14426. // where the monitor always gets cleared and the atomic operation can never
  14427. // succeed. So at -O0 lower this operation to a CAS loop.
  14428. if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
  14429. return AtomicExpansionKind::CmpXChg;
  14430. return AtomicExpansionKind::LLSC;
  14431. }
  14432. TargetLowering::AtomicExpansionKind
  14433. AArch64TargetLowering::shouldExpandAtomicCmpXchgInIR(
  14434. AtomicCmpXchgInst *AI) const {
  14435. // If subtarget has LSE, leave cmpxchg intact for codegen.
  14436. if (Subtarget->hasLSE() || Subtarget->outlineAtomics())
  14437. return AtomicExpansionKind::None;
  14438. // At -O0, fast-regalloc cannot cope with the live vregs necessary to
  14439. // implement cmpxchg without spilling. If the address being exchanged is also
  14440. // on the stack and close enough to the spill slot, this can lead to a
  14441. // situation where the monitor always gets cleared and the atomic operation
  14442. // can never succeed. So at -O0 we need a late-expanded pseudo-inst instead.
  14443. if (getTargetMachine().getOptLevel() == CodeGenOpt::None)
  14444. return AtomicExpansionKind::None;
  14445. return AtomicExpansionKind::LLSC;
  14446. }
  14447. Value *AArch64TargetLowering::emitLoadLinked(IRBuilder<> &Builder, Value *Addr,
  14448. AtomicOrdering Ord) const {
  14449. Module *M = Builder.GetInsertBlock()->getParent()->getParent();
  14450. Type *ValTy = cast<PointerType>(Addr->getType())->getElementType();
  14451. bool IsAcquire = isAcquireOrStronger(Ord);
  14452. // Since i128 isn't legal and intrinsics don't get type-lowered, the ldrexd
  14453. // intrinsic must return {i64, i64} and we have to recombine them into a
  14454. // single i128 here.
  14455. if (ValTy->getPrimitiveSizeInBits() == 128) {
  14456. Intrinsic::ID Int =
  14457. IsAcquire ? Intrinsic::aarch64_ldaxp : Intrinsic::aarch64_ldxp;
  14458. Function *Ldxr = Intrinsic::getDeclaration(M, Int);
  14459. Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
  14460. Value *LoHi = Builder.CreateCall(Ldxr, Addr, "lohi");
  14461. Value *Lo = Builder.CreateExtractValue(LoHi, 0, "lo");
  14462. Value *Hi = Builder.CreateExtractValue(LoHi, 1, "hi");
  14463. Lo = Builder.CreateZExt(Lo, ValTy, "lo64");
  14464. Hi = Builder.CreateZExt(Hi, ValTy, "hi64");
  14465. return Builder.CreateOr(
  14466. Lo, Builder.CreateShl(Hi, ConstantInt::get(ValTy, 64)), "val64");
  14467. }
  14468. Type *Tys[] = { Addr->getType() };
  14469. Intrinsic::ID Int =
  14470. IsAcquire ? Intrinsic::aarch64_ldaxr : Intrinsic::aarch64_ldxr;
  14471. Function *Ldxr = Intrinsic::getDeclaration(M, Int, Tys);
  14472. Type *EltTy = cast<PointerType>(Addr->getType())->getElementType();
  14473. const DataLayout &DL = M->getDataLayout();
  14474. IntegerType *IntEltTy = Builder.getIntNTy(DL.getTypeSizeInBits(EltTy));
  14475. Value *Trunc = Builder.CreateTrunc(Builder.CreateCall(Ldxr, Addr), IntEltTy);
  14476. return Builder.CreateBitCast(Trunc, EltTy);
  14477. }
  14478. void AArch64TargetLowering::emitAtomicCmpXchgNoStoreLLBalance(
  14479. IRBuilder<> &Builder) const {
  14480. Module *M = Builder.GetInsertBlock()->getParent()->getParent();
  14481. Builder.CreateCall(Intrinsic::getDeclaration(M, Intrinsic::aarch64_clrex));
  14482. }
  14483. Value *AArch64TargetLowering::emitStoreConditional(IRBuilder<> &Builder,
  14484. Value *Val, Value *Addr,
  14485. AtomicOrdering Ord) const {
  14486. Module *M = Builder.GetInsertBlock()->getParent()->getParent();
  14487. bool IsRelease = isReleaseOrStronger(Ord);
  14488. // Since the intrinsics must have legal type, the i128 intrinsics take two
  14489. // parameters: "i64, i64". We must marshal Val into the appropriate form
  14490. // before the call.
  14491. if (Val->getType()->getPrimitiveSizeInBits() == 128) {
  14492. Intrinsic::ID Int =
  14493. IsRelease ? Intrinsic::aarch64_stlxp : Intrinsic::aarch64_stxp;
  14494. Function *Stxr = Intrinsic::getDeclaration(M, Int);
  14495. Type *Int64Ty = Type::getInt64Ty(M->getContext());
  14496. Value *Lo = Builder.CreateTrunc(Val, Int64Ty, "lo");
  14497. Value *Hi = Builder.CreateTrunc(Builder.CreateLShr(Val, 64), Int64Ty, "hi");
  14498. Addr = Builder.CreateBitCast(Addr, Type::getInt8PtrTy(M->getContext()));
  14499. return Builder.CreateCall(Stxr, {Lo, Hi, Addr});
  14500. }
  14501. Intrinsic::ID Int =
  14502. IsRelease ? Intrinsic::aarch64_stlxr : Intrinsic::aarch64_stxr;
  14503. Type *Tys[] = { Addr->getType() };
  14504. Function *Stxr = Intrinsic::getDeclaration(M, Int, Tys);
  14505. const DataLayout &DL = M->getDataLayout();
  14506. IntegerType *IntValTy = Builder.getIntNTy(DL.getTypeSizeInBits(Val->getType()));
  14507. Val = Builder.CreateBitCast(Val, IntValTy);
  14508. return Builder.CreateCall(Stxr,
  14509. {Builder.CreateZExtOrBitCast(
  14510. Val, Stxr->getFunctionType()->getParamType(0)),
  14511. Addr});
  14512. }
  14513. bool AArch64TargetLowering::functionArgumentNeedsConsecutiveRegisters(
  14514. Type *Ty, CallingConv::ID CallConv, bool isVarArg) const {
  14515. if (Ty->isArrayTy())
  14516. return true;
  14517. const TypeSize &TySize = Ty->getPrimitiveSizeInBits();
  14518. if (TySize.isScalable() && TySize.getKnownMinSize() > 128)
  14519. return true;
  14520. return false;
  14521. }
  14522. bool AArch64TargetLowering::shouldNormalizeToSelectSequence(LLVMContext &,
  14523. EVT) const {
  14524. return false;
  14525. }
  14526. static Value *UseTlsOffset(IRBuilder<> &IRB, unsigned Offset) {
  14527. Module *M = IRB.GetInsertBlock()->getParent()->getParent();
  14528. Function *ThreadPointerFunc =
  14529. Intrinsic::getDeclaration(M, Intrinsic::thread_pointer);
  14530. return IRB.CreatePointerCast(
  14531. IRB.CreateConstGEP1_32(IRB.getInt8Ty(), IRB.CreateCall(ThreadPointerFunc),
  14532. Offset),
  14533. IRB.getInt8PtrTy()->getPointerTo(0));
  14534. }
  14535. Value *AArch64TargetLowering::getIRStackGuard(IRBuilder<> &IRB) const {
  14536. // Android provides a fixed TLS slot for the stack cookie. See the definition
  14537. // of TLS_SLOT_STACK_GUARD in
  14538. // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
  14539. if (Subtarget->isTargetAndroid())
  14540. return UseTlsOffset(IRB, 0x28);
  14541. // Fuchsia is similar.
  14542. // <zircon/tls.h> defines ZX_TLS_STACK_GUARD_OFFSET with this value.
  14543. if (Subtarget->isTargetFuchsia())
  14544. return UseTlsOffset(IRB, -0x10);
  14545. return TargetLowering::getIRStackGuard(IRB);
  14546. }
  14547. void AArch64TargetLowering::insertSSPDeclarations(Module &M) const {
  14548. // MSVC CRT provides functionalities for stack protection.
  14549. if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment()) {
  14550. // MSVC CRT has a global variable holding security cookie.
  14551. M.getOrInsertGlobal("__security_cookie",
  14552. Type::getInt8PtrTy(M.getContext()));
  14553. // MSVC CRT has a function to validate security cookie.
  14554. FunctionCallee SecurityCheckCookie = M.getOrInsertFunction(
  14555. "__security_check_cookie", Type::getVoidTy(M.getContext()),
  14556. Type::getInt8PtrTy(M.getContext()));
  14557. if (Function *F = dyn_cast<Function>(SecurityCheckCookie.getCallee())) {
  14558. F->setCallingConv(CallingConv::Win64);
  14559. F->addAttribute(1, Attribute::AttrKind::InReg);
  14560. }
  14561. return;
  14562. }
  14563. TargetLowering::insertSSPDeclarations(M);
  14564. }
  14565. Value *AArch64TargetLowering::getSDagStackGuard(const Module &M) const {
  14566. // MSVC CRT has a global variable holding security cookie.
  14567. if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
  14568. return M.getGlobalVariable("__security_cookie");
  14569. return TargetLowering::getSDagStackGuard(M);
  14570. }
  14571. Function *AArch64TargetLowering::getSSPStackGuardCheck(const Module &M) const {
  14572. // MSVC CRT has a function to validate security cookie.
  14573. if (Subtarget->getTargetTriple().isWindowsMSVCEnvironment())
  14574. return M.getFunction("__security_check_cookie");
  14575. return TargetLowering::getSSPStackGuardCheck(M);
  14576. }
  14577. Value *AArch64TargetLowering::getSafeStackPointerLocation(IRBuilder<> &IRB) const {
  14578. // Android provides a fixed TLS slot for the SafeStack pointer. See the
  14579. // definition of TLS_SLOT_SAFESTACK in
  14580. // https://android.googlesource.com/platform/bionic/+/master/libc/private/bionic_tls.h
  14581. if (Subtarget->isTargetAndroid())
  14582. return UseTlsOffset(IRB, 0x48);
  14583. // Fuchsia is similar.
  14584. // <zircon/tls.h> defines ZX_TLS_UNSAFE_SP_OFFSET with this value.
  14585. if (Subtarget->isTargetFuchsia())
  14586. return UseTlsOffset(IRB, -0x8);
  14587. return TargetLowering::getSafeStackPointerLocation(IRB);
  14588. }
  14589. bool AArch64TargetLowering::isMaskAndCmp0FoldingBeneficial(
  14590. const Instruction &AndI) const {
  14591. // Only sink 'and' mask to cmp use block if it is masking a single bit, since
  14592. // this is likely to be fold the and/cmp/br into a single tbz instruction. It
  14593. // may be beneficial to sink in other cases, but we would have to check that
  14594. // the cmp would not get folded into the br to form a cbz for these to be
  14595. // beneficial.
  14596. ConstantInt* Mask = dyn_cast<ConstantInt>(AndI.getOperand(1));
  14597. if (!Mask)
  14598. return false;
  14599. return Mask->getValue().isPowerOf2();
  14600. }
  14601. bool AArch64TargetLowering::
  14602. shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
  14603. SDValue X, ConstantSDNode *XC, ConstantSDNode *CC, SDValue Y,
  14604. unsigned OldShiftOpcode, unsigned NewShiftOpcode,
  14605. SelectionDAG &DAG) const {
  14606. // Does baseline recommend not to perform the fold by default?
  14607. if (!TargetLowering::shouldProduceAndByConstByHoistingConstFromShiftsLHSOfAnd(
  14608. X, XC, CC, Y, OldShiftOpcode, NewShiftOpcode, DAG))
  14609. return false;
  14610. // Else, if this is a vector shift, prefer 'shl'.
  14611. return X.getValueType().isScalarInteger() || NewShiftOpcode == ISD::SHL;
  14612. }
  14613. bool AArch64TargetLowering::shouldExpandShift(SelectionDAG &DAG,
  14614. SDNode *N) const {
  14615. if (DAG.getMachineFunction().getFunction().hasMinSize() &&
  14616. !Subtarget->isTargetWindows() && !Subtarget->isTargetDarwin())
  14617. return false;
  14618. return true;
  14619. }
  14620. void AArch64TargetLowering::initializeSplitCSR(MachineBasicBlock *Entry) const {
  14621. // Update IsSplitCSR in AArch64unctionInfo.
  14622. AArch64FunctionInfo *AFI = Entry->getParent()->getInfo<AArch64FunctionInfo>();
  14623. AFI->setIsSplitCSR(true);
  14624. }
  14625. void AArch64TargetLowering::insertCopiesSplitCSR(
  14626. MachineBasicBlock *Entry,
  14627. const SmallVectorImpl<MachineBasicBlock *> &Exits) const {
  14628. const AArch64RegisterInfo *TRI = Subtarget->getRegisterInfo();
  14629. const MCPhysReg *IStart = TRI->getCalleeSavedRegsViaCopy(Entry->getParent());
  14630. if (!IStart)
  14631. return;
  14632. const TargetInstrInfo *TII = Subtarget->getInstrInfo();
  14633. MachineRegisterInfo *MRI = &Entry->getParent()->getRegInfo();
  14634. MachineBasicBlock::iterator MBBI = Entry->begin();
  14635. for (const MCPhysReg *I = IStart; *I; ++I) {
  14636. const TargetRegisterClass *RC = nullptr;
  14637. if (AArch64::GPR64RegClass.contains(*I))
  14638. RC = &AArch64::GPR64RegClass;
  14639. else if (AArch64::FPR64RegClass.contains(*I))
  14640. RC = &AArch64::FPR64RegClass;
  14641. else
  14642. llvm_unreachable("Unexpected register class in CSRsViaCopy!");
  14643. Register NewVR = MRI->createVirtualRegister(RC);
  14644. // Create copy from CSR to a virtual register.
  14645. // FIXME: this currently does not emit CFI pseudo-instructions, it works
  14646. // fine for CXX_FAST_TLS since the C++-style TLS access functions should be
  14647. // nounwind. If we want to generalize this later, we may need to emit
  14648. // CFI pseudo-instructions.
  14649. assert(Entry->getParent()->getFunction().hasFnAttribute(
  14650. Attribute::NoUnwind) &&
  14651. "Function should be nounwind in insertCopiesSplitCSR!");
  14652. Entry->addLiveIn(*I);
  14653. BuildMI(*Entry, MBBI, DebugLoc(), TII->get(TargetOpcode::COPY), NewVR)
  14654. .addReg(*I);
  14655. // Insert the copy-back instructions right before the terminator.
  14656. for (auto *Exit : Exits)
  14657. BuildMI(*Exit, Exit->getFirstTerminator(), DebugLoc(),
  14658. TII->get(TargetOpcode::COPY), *I)
  14659. .addReg(NewVR);
  14660. }
  14661. }
  14662. bool AArch64TargetLowering::isIntDivCheap(EVT VT, AttributeList Attr) const {
  14663. // Integer division on AArch64 is expensive. However, when aggressively
  14664. // optimizing for code size, we prefer to use a div instruction, as it is
  14665. // usually smaller than the alternative sequence.
  14666. // The exception to this is vector division. Since AArch64 doesn't have vector
  14667. // integer division, leaving the division as-is is a loss even in terms of
  14668. // size, because it will have to be scalarized, while the alternative code
  14669. // sequence can be performed in vector form.
  14670. bool OptSize = Attr.hasFnAttribute(Attribute::MinSize);
  14671. return OptSize && !VT.isVector();
  14672. }
  14673. bool AArch64TargetLowering::preferIncOfAddToSubOfNot(EVT VT) const {
  14674. // We want inc-of-add for scalars and sub-of-not for vectors.
  14675. return VT.isScalarInteger();
  14676. }
  14677. bool AArch64TargetLowering::enableAggressiveFMAFusion(EVT VT) const {
  14678. return Subtarget->hasAggressiveFMA() && VT.isFloatingPoint();
  14679. }
  14680. unsigned
  14681. AArch64TargetLowering::getVaListSizeInBits(const DataLayout &DL) const {
  14682. if (Subtarget->isTargetDarwin() || Subtarget->isTargetWindows())
  14683. return getPointerTy(DL).getSizeInBits();
  14684. return 3 * getPointerTy(DL).getSizeInBits() + 2 * 32;
  14685. }
  14686. void AArch64TargetLowering::finalizeLowering(MachineFunction &MF) const {
  14687. MF.getFrameInfo().computeMaxCallFrameSize(MF);
  14688. TargetLoweringBase::finalizeLowering(MF);
  14689. }
  14690. // Unlike X86, we let frame lowering assign offsets to all catch objects.
  14691. bool AArch64TargetLowering::needsFixedCatchObjects() const {
  14692. return false;
  14693. }
  14694. bool AArch64TargetLowering::shouldLocalize(
  14695. const MachineInstr &MI, const TargetTransformInfo *TTI) const {
  14696. switch (MI.getOpcode()) {
  14697. case TargetOpcode::G_GLOBAL_VALUE: {
  14698. // On Darwin, TLS global vars get selected into function calls, which
  14699. // we don't want localized, as they can get moved into the middle of a
  14700. // another call sequence.
  14701. const GlobalValue &GV = *MI.getOperand(1).getGlobal();
  14702. if (GV.isThreadLocal() && Subtarget->isTargetMachO())
  14703. return false;
  14704. break;
  14705. }
  14706. // If we legalized G_GLOBAL_VALUE into ADRP + G_ADD_LOW, mark both as being
  14707. // localizable.
  14708. case AArch64::ADRP:
  14709. case AArch64::G_ADD_LOW:
  14710. return true;
  14711. default:
  14712. break;
  14713. }
  14714. return TargetLoweringBase::shouldLocalize(MI, TTI);
  14715. }
  14716. bool AArch64TargetLowering::fallBackToDAGISel(const Instruction &Inst) const {
  14717. if (isa<ScalableVectorType>(Inst.getType()))
  14718. return true;
  14719. for (unsigned i = 0; i < Inst.getNumOperands(); ++i)
  14720. if (isa<ScalableVectorType>(Inst.getOperand(i)->getType()))
  14721. return true;
  14722. if (const AllocaInst *AI = dyn_cast<AllocaInst>(&Inst)) {
  14723. if (isa<ScalableVectorType>(AI->getAllocatedType()))
  14724. return true;
  14725. }
  14726. return false;
  14727. }
  14728. // Return the largest legal scalable vector type that matches VT's element type.
  14729. static EVT getContainerForFixedLengthVector(SelectionDAG &DAG, EVT VT) {
  14730. assert(VT.isFixedLengthVector() &&
  14731. DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
  14732. "Expected legal fixed length vector!");
  14733. switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
  14734. default:
  14735. llvm_unreachable("unexpected element type for SVE container");
  14736. case MVT::i8:
  14737. return EVT(MVT::nxv16i8);
  14738. case MVT::i16:
  14739. return EVT(MVT::nxv8i16);
  14740. case MVT::i32:
  14741. return EVT(MVT::nxv4i32);
  14742. case MVT::i64:
  14743. return EVT(MVT::nxv2i64);
  14744. case MVT::f16:
  14745. return EVT(MVT::nxv8f16);
  14746. case MVT::f32:
  14747. return EVT(MVT::nxv4f32);
  14748. case MVT::f64:
  14749. return EVT(MVT::nxv2f64);
  14750. }
  14751. }
  14752. // Return a PTRUE with active lanes corresponding to the extent of VT.
  14753. static SDValue getPredicateForFixedLengthVector(SelectionDAG &DAG, SDLoc &DL,
  14754. EVT VT) {
  14755. assert(VT.isFixedLengthVector() &&
  14756. DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
  14757. "Expected legal fixed length vector!");
  14758. int PgPattern;
  14759. switch (VT.getVectorNumElements()) {
  14760. default:
  14761. llvm_unreachable("unexpected element count for SVE predicate");
  14762. case 1:
  14763. PgPattern = AArch64SVEPredPattern::vl1;
  14764. break;
  14765. case 2:
  14766. PgPattern = AArch64SVEPredPattern::vl2;
  14767. break;
  14768. case 4:
  14769. PgPattern = AArch64SVEPredPattern::vl4;
  14770. break;
  14771. case 8:
  14772. PgPattern = AArch64SVEPredPattern::vl8;
  14773. break;
  14774. case 16:
  14775. PgPattern = AArch64SVEPredPattern::vl16;
  14776. break;
  14777. case 32:
  14778. PgPattern = AArch64SVEPredPattern::vl32;
  14779. break;
  14780. case 64:
  14781. PgPattern = AArch64SVEPredPattern::vl64;
  14782. break;
  14783. case 128:
  14784. PgPattern = AArch64SVEPredPattern::vl128;
  14785. break;
  14786. case 256:
  14787. PgPattern = AArch64SVEPredPattern::vl256;
  14788. break;
  14789. }
  14790. // TODO: For vectors that are exactly getMaxSVEVectorSizeInBits big, we can
  14791. // use AArch64SVEPredPattern::all, which can enable the use of unpredicated
  14792. // variants of instructions when available.
  14793. MVT MaskVT;
  14794. switch (VT.getVectorElementType().getSimpleVT().SimpleTy) {
  14795. default:
  14796. llvm_unreachable("unexpected element type for SVE predicate");
  14797. case MVT::i8:
  14798. MaskVT = MVT::nxv16i1;
  14799. break;
  14800. case MVT::i16:
  14801. case MVT::f16:
  14802. MaskVT = MVT::nxv8i1;
  14803. break;
  14804. case MVT::i32:
  14805. case MVT::f32:
  14806. MaskVT = MVT::nxv4i1;
  14807. break;
  14808. case MVT::i64:
  14809. case MVT::f64:
  14810. MaskVT = MVT::nxv2i1;
  14811. break;
  14812. }
  14813. return DAG.getNode(AArch64ISD::PTRUE, DL, MaskVT,
  14814. DAG.getTargetConstant(PgPattern, DL, MVT::i64));
  14815. }
  14816. static SDValue getPredicateForScalableVector(SelectionDAG &DAG, SDLoc &DL,
  14817. EVT VT) {
  14818. assert(VT.isScalableVector() && DAG.getTargetLoweringInfo().isTypeLegal(VT) &&
  14819. "Expected legal scalable vector!");
  14820. auto PredTy = VT.changeVectorElementType(MVT::i1);
  14821. return getPTrue(DAG, DL, PredTy, AArch64SVEPredPattern::all);
  14822. }
  14823. static SDValue getPredicateForVector(SelectionDAG &DAG, SDLoc &DL, EVT VT) {
  14824. if (VT.isFixedLengthVector())
  14825. return getPredicateForFixedLengthVector(DAG, DL, VT);
  14826. return getPredicateForScalableVector(DAG, DL, VT);
  14827. }
  14828. // Grow V to consume an entire SVE register.
  14829. static SDValue convertToScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
  14830. assert(VT.isScalableVector() &&
  14831. "Expected to convert into a scalable vector!");
  14832. assert(V.getValueType().isFixedLengthVector() &&
  14833. "Expected a fixed length vector operand!");
  14834. SDLoc DL(V);
  14835. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  14836. return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, DAG.getUNDEF(VT), V, Zero);
  14837. }
  14838. // Shrink V so it's just big enough to maintain a VT's worth of data.
  14839. static SDValue convertFromScalableVector(SelectionDAG &DAG, EVT VT, SDValue V) {
  14840. assert(VT.isFixedLengthVector() &&
  14841. "Expected to convert into a fixed length vector!");
  14842. assert(V.getValueType().isScalableVector() &&
  14843. "Expected a scalable vector operand!");
  14844. SDLoc DL(V);
  14845. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  14846. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, V, Zero);
  14847. }
  14848. // Convert all fixed length vector loads larger than NEON to masked_loads.
  14849. SDValue AArch64TargetLowering::LowerFixedLengthVectorLoadToSVE(
  14850. SDValue Op, SelectionDAG &DAG) const {
  14851. auto Load = cast<LoadSDNode>(Op);
  14852. SDLoc DL(Op);
  14853. EVT VT = Op.getValueType();
  14854. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  14855. auto NewLoad = DAG.getMaskedLoad(
  14856. ContainerVT, DL, Load->getChain(), Load->getBasePtr(), Load->getOffset(),
  14857. getPredicateForFixedLengthVector(DAG, DL, VT), DAG.getUNDEF(ContainerVT),
  14858. Load->getMemoryVT(), Load->getMemOperand(), Load->getAddressingMode(),
  14859. Load->getExtensionType());
  14860. auto Result = convertFromScalableVector(DAG, VT, NewLoad);
  14861. SDValue MergedValues[2] = {Result, Load->getChain()};
  14862. return DAG.getMergeValues(MergedValues, DL);
  14863. }
  14864. // Convert all fixed length vector stores larger than NEON to masked_stores.
  14865. SDValue AArch64TargetLowering::LowerFixedLengthVectorStoreToSVE(
  14866. SDValue Op, SelectionDAG &DAG) const {
  14867. auto Store = cast<StoreSDNode>(Op);
  14868. SDLoc DL(Op);
  14869. EVT VT = Store->getValue().getValueType();
  14870. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  14871. auto NewValue = convertToScalableVector(DAG, ContainerVT, Store->getValue());
  14872. return DAG.getMaskedStore(
  14873. Store->getChain(), DL, NewValue, Store->getBasePtr(), Store->getOffset(),
  14874. getPredicateForFixedLengthVector(DAG, DL, VT), Store->getMemoryVT(),
  14875. Store->getMemOperand(), Store->getAddressingMode(),
  14876. Store->isTruncatingStore());
  14877. }
  14878. SDValue AArch64TargetLowering::LowerFixedLengthVectorIntDivideToSVE(
  14879. SDValue Op, SelectionDAG &DAG) const {
  14880. SDLoc dl(Op);
  14881. EVT VT = Op.getValueType();
  14882. EVT EltVT = VT.getVectorElementType();
  14883. bool Signed = Op.getOpcode() == ISD::SDIV;
  14884. unsigned PredOpcode = Signed ? AArch64ISD::SDIV_PRED : AArch64ISD::UDIV_PRED;
  14885. // Scalable vector i32/i64 DIV is supported.
  14886. if (EltVT == MVT::i32 || EltVT == MVT::i64)
  14887. return LowerToPredicatedOp(Op, DAG, PredOpcode, /*OverrideNEON=*/true);
  14888. // Scalable vector i8/i16 DIV is not supported. Promote it to i32.
  14889. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  14890. EVT HalfVT = VT.getHalfNumVectorElementsVT(*DAG.getContext());
  14891. EVT FixedWidenedVT = HalfVT.widenIntegerVectorElementType(*DAG.getContext());
  14892. EVT ScalableWidenedVT = getContainerForFixedLengthVector(DAG, FixedWidenedVT);
  14893. // Convert the operands to scalable vectors.
  14894. SDValue Op0 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
  14895. SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
  14896. // Extend the scalable operands.
  14897. unsigned UnpkLo = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
  14898. unsigned UnpkHi = Signed ? AArch64ISD::SUNPKHI : AArch64ISD::UUNPKHI;
  14899. SDValue Op0Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op0);
  14900. SDValue Op1Lo = DAG.getNode(UnpkLo, dl, ScalableWidenedVT, Op1);
  14901. SDValue Op0Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op0);
  14902. SDValue Op1Hi = DAG.getNode(UnpkHi, dl, ScalableWidenedVT, Op1);
  14903. // Convert back to fixed vectors so the DIV can be further lowered.
  14904. Op0Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op0Lo);
  14905. Op1Lo = convertFromScalableVector(DAG, FixedWidenedVT, Op1Lo);
  14906. Op0Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op0Hi);
  14907. Op1Hi = convertFromScalableVector(DAG, FixedWidenedVT, Op1Hi);
  14908. SDValue ResultLo = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
  14909. Op0Lo, Op1Lo);
  14910. SDValue ResultHi = DAG.getNode(Op.getOpcode(), dl, FixedWidenedVT,
  14911. Op0Hi, Op1Hi);
  14912. // Convert again to scalable vectors to truncate.
  14913. ResultLo = convertToScalableVector(DAG, ScalableWidenedVT, ResultLo);
  14914. ResultHi = convertToScalableVector(DAG, ScalableWidenedVT, ResultHi);
  14915. SDValue ScalableResult = DAG.getNode(AArch64ISD::UZP1, dl, ContainerVT,
  14916. ResultLo, ResultHi);
  14917. return convertFromScalableVector(DAG, VT, ScalableResult);
  14918. }
  14919. SDValue AArch64TargetLowering::LowerFixedLengthVectorIntExtendToSVE(
  14920. SDValue Op, SelectionDAG &DAG) const {
  14921. EVT VT = Op.getValueType();
  14922. assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
  14923. SDLoc DL(Op);
  14924. SDValue Val = Op.getOperand(0);
  14925. EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
  14926. Val = convertToScalableVector(DAG, ContainerVT, Val);
  14927. bool Signed = Op.getOpcode() == ISD::SIGN_EXTEND;
  14928. unsigned ExtendOpc = Signed ? AArch64ISD::SUNPKLO : AArch64ISD::UUNPKLO;
  14929. // Repeatedly unpack Val until the result is of the desired element type.
  14930. switch (ContainerVT.getSimpleVT().SimpleTy) {
  14931. default:
  14932. llvm_unreachable("unimplemented container type");
  14933. case MVT::nxv16i8:
  14934. Val = DAG.getNode(ExtendOpc, DL, MVT::nxv8i16, Val);
  14935. if (VT.getVectorElementType() == MVT::i16)
  14936. break;
  14937. LLVM_FALLTHROUGH;
  14938. case MVT::nxv8i16:
  14939. Val = DAG.getNode(ExtendOpc, DL, MVT::nxv4i32, Val);
  14940. if (VT.getVectorElementType() == MVT::i32)
  14941. break;
  14942. LLVM_FALLTHROUGH;
  14943. case MVT::nxv4i32:
  14944. Val = DAG.getNode(ExtendOpc, DL, MVT::nxv2i64, Val);
  14945. assert(VT.getVectorElementType() == MVT::i64 && "Unexpected element type!");
  14946. break;
  14947. }
  14948. return convertFromScalableVector(DAG, VT, Val);
  14949. }
  14950. SDValue AArch64TargetLowering::LowerFixedLengthVectorTruncateToSVE(
  14951. SDValue Op, SelectionDAG &DAG) const {
  14952. EVT VT = Op.getValueType();
  14953. assert(VT.isFixedLengthVector() && "Expected fixed length vector type!");
  14954. SDLoc DL(Op);
  14955. SDValue Val = Op.getOperand(0);
  14956. EVT ContainerVT = getContainerForFixedLengthVector(DAG, Val.getValueType());
  14957. Val = convertToScalableVector(DAG, ContainerVT, Val);
  14958. // Repeatedly truncate Val until the result is of the desired element type.
  14959. switch (ContainerVT.getSimpleVT().SimpleTy) {
  14960. default:
  14961. llvm_unreachable("unimplemented container type");
  14962. case MVT::nxv2i64:
  14963. Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv4i32, Val);
  14964. Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv4i32, Val, Val);
  14965. if (VT.getVectorElementType() == MVT::i32)
  14966. break;
  14967. LLVM_FALLTHROUGH;
  14968. case MVT::nxv4i32:
  14969. Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv8i16, Val);
  14970. Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv8i16, Val, Val);
  14971. if (VT.getVectorElementType() == MVT::i16)
  14972. break;
  14973. LLVM_FALLTHROUGH;
  14974. case MVT::nxv8i16:
  14975. Val = DAG.getNode(ISD::BITCAST, DL, MVT::nxv16i8, Val);
  14976. Val = DAG.getNode(AArch64ISD::UZP1, DL, MVT::nxv16i8, Val, Val);
  14977. assert(VT.getVectorElementType() == MVT::i8 && "Unexpected element type!");
  14978. break;
  14979. }
  14980. return convertFromScalableVector(DAG, VT, Val);
  14981. }
  14982. // Convert vector operation 'Op' to an equivalent predicated operation whereby
  14983. // the original operation's type is used to construct a suitable predicate.
  14984. // NOTE: The results for inactive lanes are undefined.
  14985. SDValue AArch64TargetLowering::LowerToPredicatedOp(SDValue Op,
  14986. SelectionDAG &DAG,
  14987. unsigned NewOp,
  14988. bool OverrideNEON) const {
  14989. EVT VT = Op.getValueType();
  14990. SDLoc DL(Op);
  14991. auto Pg = getPredicateForVector(DAG, DL, VT);
  14992. if (useSVEForFixedLengthVectorVT(VT, OverrideNEON)) {
  14993. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  14994. // Create list of operands by converting existing ones to scalable types.
  14995. SmallVector<SDValue, 4> Operands = {Pg};
  14996. for (const SDValue &V : Op->op_values()) {
  14997. if (isa<CondCodeSDNode>(V)) {
  14998. Operands.push_back(V);
  14999. continue;
  15000. }
  15001. if (const VTSDNode *VTNode = dyn_cast<VTSDNode>(V)) {
  15002. EVT VTArg = VTNode->getVT().getVectorElementType();
  15003. EVT NewVTArg = ContainerVT.changeVectorElementType(VTArg);
  15004. Operands.push_back(DAG.getValueType(NewVTArg));
  15005. continue;
  15006. }
  15007. assert(useSVEForFixedLengthVectorVT(V.getValueType(), OverrideNEON) &&
  15008. "Only fixed length vectors are supported!");
  15009. Operands.push_back(convertToScalableVector(DAG, ContainerVT, V));
  15010. }
  15011. if (isMergePassthruOpcode(NewOp))
  15012. Operands.push_back(DAG.getUNDEF(ContainerVT));
  15013. auto ScalableRes = DAG.getNode(NewOp, DL, ContainerVT, Operands);
  15014. return convertFromScalableVector(DAG, VT, ScalableRes);
  15015. }
  15016. assert(VT.isScalableVector() && "Only expect to lower scalable vector op!");
  15017. SmallVector<SDValue, 4> Operands = {Pg};
  15018. for (const SDValue &V : Op->op_values()) {
  15019. assert((!V.getValueType().isVector() ||
  15020. V.getValueType().isScalableVector()) &&
  15021. "Only scalable vectors are supported!");
  15022. Operands.push_back(V);
  15023. }
  15024. if (isMergePassthruOpcode(NewOp))
  15025. Operands.push_back(DAG.getUNDEF(VT));
  15026. return DAG.getNode(NewOp, DL, VT, Operands);
  15027. }
  15028. // If a fixed length vector operation has no side effects when applied to
  15029. // undefined elements, we can safely use scalable vectors to perform the same
  15030. // operation without needing to worry about predication.
  15031. SDValue AArch64TargetLowering::LowerToScalableOp(SDValue Op,
  15032. SelectionDAG &DAG) const {
  15033. EVT VT = Op.getValueType();
  15034. assert(useSVEForFixedLengthVectorVT(VT) &&
  15035. "Only expected to lower fixed length vector operation!");
  15036. EVT ContainerVT = getContainerForFixedLengthVector(DAG, VT);
  15037. // Create list of operands by converting existing ones to scalable types.
  15038. SmallVector<SDValue, 4> Ops;
  15039. for (const SDValue &V : Op->op_values()) {
  15040. assert(!isa<VTSDNode>(V) && "Unexpected VTSDNode node!");
  15041. // Pass through non-vector operands.
  15042. if (!V.getValueType().isVector()) {
  15043. Ops.push_back(V);
  15044. continue;
  15045. }
  15046. // "cast" fixed length vector to a scalable vector.
  15047. assert(useSVEForFixedLengthVectorVT(V.getValueType()) &&
  15048. "Only fixed length vectors are supported!");
  15049. Ops.push_back(convertToScalableVector(DAG, ContainerVT, V));
  15050. }
  15051. auto ScalableRes = DAG.getNode(Op.getOpcode(), SDLoc(Op), ContainerVT, Ops);
  15052. return convertFromScalableVector(DAG, VT, ScalableRes);
  15053. }
  15054. SDValue AArch64TargetLowering::LowerVECREDUCE_SEQ_FADD(SDValue ScalarOp,
  15055. SelectionDAG &DAG) const {
  15056. SDLoc DL(ScalarOp);
  15057. SDValue AccOp = ScalarOp.getOperand(0);
  15058. SDValue VecOp = ScalarOp.getOperand(1);
  15059. EVT SrcVT = VecOp.getValueType();
  15060. EVT ResVT = SrcVT.getVectorElementType();
  15061. EVT ContainerVT = SrcVT;
  15062. if (SrcVT.isFixedLengthVector()) {
  15063. ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
  15064. VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
  15065. }
  15066. SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
  15067. SDValue Zero = DAG.getConstant(0, DL, MVT::i64);
  15068. // Convert operands to Scalable.
  15069. AccOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, ContainerVT,
  15070. DAG.getUNDEF(ContainerVT), AccOp, Zero);
  15071. // Perform reduction.
  15072. SDValue Rdx = DAG.getNode(AArch64ISD::FADDA_PRED, DL, ContainerVT,
  15073. Pg, AccOp, VecOp);
  15074. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT, Rdx, Zero);
  15075. }
  15076. SDValue AArch64TargetLowering::LowerPredReductionToSVE(SDValue ReduceOp,
  15077. SelectionDAG &DAG) const {
  15078. SDLoc DL(ReduceOp);
  15079. SDValue Op = ReduceOp.getOperand(0);
  15080. EVT OpVT = Op.getValueType();
  15081. EVT VT = ReduceOp.getValueType();
  15082. if (!OpVT.isScalableVector() || OpVT.getVectorElementType() != MVT::i1)
  15083. return SDValue();
  15084. SDValue Pg = getPredicateForVector(DAG, DL, OpVT);
  15085. switch (ReduceOp.getOpcode()) {
  15086. default:
  15087. return SDValue();
  15088. case ISD::VECREDUCE_OR:
  15089. return getPTest(DAG, VT, Pg, Op, AArch64CC::ANY_ACTIVE);
  15090. case ISD::VECREDUCE_AND: {
  15091. Op = DAG.getNode(ISD::XOR, DL, OpVT, Op, Pg);
  15092. return getPTest(DAG, VT, Pg, Op, AArch64CC::NONE_ACTIVE);
  15093. }
  15094. case ISD::VECREDUCE_XOR: {
  15095. SDValue ID =
  15096. DAG.getTargetConstant(Intrinsic::aarch64_sve_cntp, DL, MVT::i64);
  15097. SDValue Cntp =
  15098. DAG.getNode(ISD::INTRINSIC_WO_CHAIN, DL, MVT::i64, ID, Pg, Op);
  15099. return DAG.getAnyExtOrTrunc(Cntp, DL, VT);
  15100. }
  15101. }
  15102. return SDValue();
  15103. }
  15104. SDValue AArch64TargetLowering::LowerReductionToSVE(unsigned Opcode,
  15105. SDValue ScalarOp,
  15106. SelectionDAG &DAG) const {
  15107. SDLoc DL(ScalarOp);
  15108. SDValue VecOp = ScalarOp.getOperand(0);
  15109. EVT SrcVT = VecOp.getValueType();
  15110. if (useSVEForFixedLengthVectorVT(SrcVT, true)) {
  15111. EVT ContainerVT = getContainerForFixedLengthVector(DAG, SrcVT);
  15112. VecOp = convertToScalableVector(DAG, ContainerVT, VecOp);
  15113. }
  15114. // UADDV always returns an i64 result.
  15115. EVT ResVT = (Opcode == AArch64ISD::UADDV_PRED) ? MVT::i64 :
  15116. SrcVT.getVectorElementType();
  15117. EVT RdxVT = SrcVT;
  15118. if (SrcVT.isFixedLengthVector() || Opcode == AArch64ISD::UADDV_PRED)
  15119. RdxVT = getPackedSVEVectorVT(ResVT);
  15120. SDValue Pg = getPredicateForVector(DAG, DL, SrcVT);
  15121. SDValue Rdx = DAG.getNode(Opcode, DL, RdxVT, Pg, VecOp);
  15122. SDValue Res = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ResVT,
  15123. Rdx, DAG.getConstant(0, DL, MVT::i64));
  15124. // The VEC_REDUCE nodes expect an element size result.
  15125. if (ResVT != ScalarOp.getValueType())
  15126. Res = DAG.getAnyExtOrTrunc(Res, DL, ScalarOp.getValueType());
  15127. return Res;
  15128. }
  15129. SDValue
  15130. AArch64TargetLowering::LowerFixedLengthVectorSelectToSVE(SDValue Op,
  15131. SelectionDAG &DAG) const {
  15132. EVT VT = Op.getValueType();
  15133. SDLoc DL(Op);
  15134. EVT InVT = Op.getOperand(1).getValueType();
  15135. EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
  15136. SDValue Op1 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(1));
  15137. SDValue Op2 = convertToScalableVector(DAG, ContainerVT, Op->getOperand(2));
  15138. // Convert the mask to a predicated (NOTE: We don't need to worry about
  15139. // inactive lanes since VSELECT is safe when given undefined elements).
  15140. EVT MaskVT = Op.getOperand(0).getValueType();
  15141. EVT MaskContainerVT = getContainerForFixedLengthVector(DAG, MaskVT);
  15142. auto Mask = convertToScalableVector(DAG, MaskContainerVT, Op.getOperand(0));
  15143. Mask = DAG.getNode(ISD::TRUNCATE, DL,
  15144. MaskContainerVT.changeVectorElementType(MVT::i1), Mask);
  15145. auto ScalableRes = DAG.getNode(ISD::VSELECT, DL, ContainerVT,
  15146. Mask, Op1, Op2);
  15147. return convertFromScalableVector(DAG, VT, ScalableRes);
  15148. }
  15149. SDValue AArch64TargetLowering::LowerFixedLengthVectorSetccToSVE(
  15150. SDValue Op, SelectionDAG &DAG) const {
  15151. SDLoc DL(Op);
  15152. EVT InVT = Op.getOperand(0).getValueType();
  15153. EVT ContainerVT = getContainerForFixedLengthVector(DAG, InVT);
  15154. assert(useSVEForFixedLengthVectorVT(InVT) &&
  15155. "Only expected to lower fixed length vector operation!");
  15156. assert(Op.getValueType() == InVT.changeTypeToInteger() &&
  15157. "Expected integer result of the same bit length as the inputs!");
  15158. // Expand floating point vector comparisons.
  15159. if (InVT.isFloatingPoint())
  15160. return SDValue();
  15161. auto Op1 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(0));
  15162. auto Op2 = convertToScalableVector(DAG, ContainerVT, Op.getOperand(1));
  15163. auto Pg = getPredicateForFixedLengthVector(DAG, DL, InVT);
  15164. EVT CmpVT = Pg.getValueType();
  15165. auto Cmp = DAG.getNode(AArch64ISD::SETCC_MERGE_ZERO, DL, CmpVT,
  15166. {Pg, Op1, Op2, Op.getOperand(2)});
  15167. EVT PromoteVT = ContainerVT.changeTypeToInteger();
  15168. auto Promote = DAG.getBoolExtOrTrunc(Cmp, DL, PromoteVT, InVT);
  15169. return convertFromScalableVector(DAG, Op.getValueType(), Promote);
  15170. }
  15171. SDValue AArch64TargetLowering::getSVESafeBitCast(EVT VT, SDValue Op,
  15172. SelectionDAG &DAG) const {
  15173. SDLoc DL(Op);
  15174. EVT InVT = Op.getValueType();
  15175. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  15176. (void)TLI;
  15177. assert(VT.isScalableVector() && TLI.isTypeLegal(VT) &&
  15178. InVT.isScalableVector() && TLI.isTypeLegal(InVT) &&
  15179. "Only expect to cast between legal scalable vector types!");
  15180. assert((VT.getVectorElementType() == MVT::i1) ==
  15181. (InVT.getVectorElementType() == MVT::i1) &&
  15182. "Cannot cast between data and predicate scalable vector types!");
  15183. if (InVT == VT)
  15184. return Op;
  15185. if (VT.getVectorElementType() == MVT::i1)
  15186. return DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
  15187. EVT PackedVT = getPackedSVEVectorVT(VT.getVectorElementType());
  15188. EVT PackedInVT = getPackedSVEVectorVT(InVT.getVectorElementType());
  15189. assert((VT == PackedVT || InVT == PackedInVT) &&
  15190. "Cannot cast between unpacked scalable vector types!");
  15191. // Pack input if required.
  15192. if (InVT != PackedInVT)
  15193. Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, PackedInVT, Op);
  15194. Op = DAG.getNode(ISD::BITCAST, DL, PackedVT, Op);
  15195. // Unpack result if required.
  15196. if (VT != PackedVT)
  15197. Op = DAG.getNode(AArch64ISD::REINTERPRET_CAST, DL, VT, Op);
  15198. return Op;
  15199. }