DAGCombiner.cpp 931 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211
  1. //===- DAGCombiner.cpp - Implement a DAG node combiner --------------------===//
  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 pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
  10. // both before and after the DAG is legalized.
  11. //
  12. // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
  13. // primarily intended to handle simplification opportunities that are implicit
  14. // in the LLVM IR and exposed by the various codegen lowering phases.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #include "llvm/ADT/APFloat.h"
  18. #include "llvm/ADT/APInt.h"
  19. #include "llvm/ADT/ArrayRef.h"
  20. #include "llvm/ADT/DenseMap.h"
  21. #include "llvm/ADT/IntervalMap.h"
  22. #include "llvm/ADT/None.h"
  23. #include "llvm/ADT/Optional.h"
  24. #include "llvm/ADT/STLExtras.h"
  25. #include "llvm/ADT/SetVector.h"
  26. #include "llvm/ADT/SmallBitVector.h"
  27. #include "llvm/ADT/SmallPtrSet.h"
  28. #include "llvm/ADT/SmallSet.h"
  29. #include "llvm/ADT/SmallVector.h"
  30. #include "llvm/ADT/Statistic.h"
  31. #include "llvm/Analysis/AliasAnalysis.h"
  32. #include "llvm/Analysis/MemoryLocation.h"
  33. #include "llvm/Analysis/TargetLibraryInfo.h"
  34. #include "llvm/Analysis/VectorUtils.h"
  35. #include "llvm/CodeGen/DAGCombine.h"
  36. #include "llvm/CodeGen/ISDOpcodes.h"
  37. #include "llvm/CodeGen/MachineFrameInfo.h"
  38. #include "llvm/CodeGen/MachineFunction.h"
  39. #include "llvm/CodeGen/MachineMemOperand.h"
  40. #include "llvm/CodeGen/RuntimeLibcalls.h"
  41. #include "llvm/CodeGen/SelectionDAG.h"
  42. #include "llvm/CodeGen/SelectionDAGAddressAnalysis.h"
  43. #include "llvm/CodeGen/SelectionDAGNodes.h"
  44. #include "llvm/CodeGen/SelectionDAGTargetInfo.h"
  45. #include "llvm/CodeGen/TargetLowering.h"
  46. #include "llvm/CodeGen/TargetRegisterInfo.h"
  47. #include "llvm/CodeGen/TargetSubtargetInfo.h"
  48. #include "llvm/CodeGen/ValueTypes.h"
  49. #include "llvm/IR/Attributes.h"
  50. #include "llvm/IR/Constant.h"
  51. #include "llvm/IR/DataLayout.h"
  52. #include "llvm/IR/DerivedTypes.h"
  53. #include "llvm/IR/Function.h"
  54. #include "llvm/IR/LLVMContext.h"
  55. #include "llvm/IR/Metadata.h"
  56. #include "llvm/Support/Casting.h"
  57. #include "llvm/Support/CodeGen.h"
  58. #include "llvm/Support/CommandLine.h"
  59. #include "llvm/Support/Compiler.h"
  60. #include "llvm/Support/Debug.h"
  61. #include "llvm/Support/ErrorHandling.h"
  62. #include "llvm/Support/KnownBits.h"
  63. #include "llvm/Support/MachineValueType.h"
  64. #include "llvm/Support/MathExtras.h"
  65. #include "llvm/Support/raw_ostream.h"
  66. #include "llvm/Target/TargetMachine.h"
  67. #include "llvm/Target/TargetOptions.h"
  68. #include <algorithm>
  69. #include <cassert>
  70. #include <cstdint>
  71. #include <functional>
  72. #include <iterator>
  73. #include <string>
  74. #include <tuple>
  75. #include <utility>
  76. using namespace llvm;
  77. #define DEBUG_TYPE "dagcombine"
  78. STATISTIC(NodesCombined , "Number of dag nodes combined");
  79. STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
  80. STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
  81. STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
  82. STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
  83. STATISTIC(SlicedLoads, "Number of load sliced");
  84. STATISTIC(NumFPLogicOpsConv, "Number of logic ops converted to fp ops");
  85. static cl::opt<bool>
  86. CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
  87. cl::desc("Enable DAG combiner's use of IR alias analysis"));
  88. static cl::opt<bool>
  89. UseTBAA("combiner-use-tbaa", cl::Hidden, cl::init(true),
  90. cl::desc("Enable DAG combiner's use of TBAA"));
  91. #ifndef NDEBUG
  92. static cl::opt<std::string>
  93. CombinerAAOnlyFunc("combiner-aa-only-func", cl::Hidden,
  94. cl::desc("Only use DAG-combiner alias analysis in this"
  95. " function"));
  96. #endif
  97. /// Hidden option to stress test load slicing, i.e., when this option
  98. /// is enabled, load slicing bypasses most of its profitability guards.
  99. static cl::opt<bool>
  100. StressLoadSlicing("combiner-stress-load-slicing", cl::Hidden,
  101. cl::desc("Bypass the profitability model of load slicing"),
  102. cl::init(false));
  103. static cl::opt<bool>
  104. MaySplitLoadIndex("combiner-split-load-index", cl::Hidden, cl::init(true),
  105. cl::desc("DAG combiner may split indexing from loads"));
  106. static cl::opt<bool>
  107. EnableStoreMerging("combiner-store-merging", cl::Hidden, cl::init(true),
  108. cl::desc("DAG combiner enable merging multiple stores "
  109. "into a wider store"));
  110. static cl::opt<unsigned> TokenFactorInlineLimit(
  111. "combiner-tokenfactor-inline-limit", cl::Hidden, cl::init(2048),
  112. cl::desc("Limit the number of operands to inline for Token Factors"));
  113. static cl::opt<unsigned> StoreMergeDependenceLimit(
  114. "combiner-store-merge-dependence-limit", cl::Hidden, cl::init(10),
  115. cl::desc("Limit the number of times for the same StoreNode and RootNode "
  116. "to bail out in store merging dependence check"));
  117. static cl::opt<bool> EnableReduceLoadOpStoreWidth(
  118. "combiner-reduce-load-op-store-width", cl::Hidden, cl::init(true),
  119. cl::desc("DAG combiner enable reducing the width of load/op/store "
  120. "sequence"));
  121. static cl::opt<bool> EnableShrinkLoadReplaceStoreWithStore(
  122. "combiner-shrink-load-replace-store-with-store", cl::Hidden, cl::init(true),
  123. cl::desc("DAG combiner enable load/<replace bytes>/store with "
  124. "a narrower store"));
  125. namespace {
  126. class DAGCombiner {
  127. SelectionDAG &DAG;
  128. const TargetLowering &TLI;
  129. const SelectionDAGTargetInfo *STI;
  130. CombineLevel Level = BeforeLegalizeTypes;
  131. CodeGenOpt::Level OptLevel;
  132. bool LegalDAG = false;
  133. bool LegalOperations = false;
  134. bool LegalTypes = false;
  135. bool ForCodeSize;
  136. bool DisableGenericCombines;
  137. /// Worklist of all of the nodes that need to be simplified.
  138. ///
  139. /// This must behave as a stack -- new nodes to process are pushed onto the
  140. /// back and when processing we pop off of the back.
  141. ///
  142. /// The worklist will not contain duplicates but may contain null entries
  143. /// due to nodes being deleted from the underlying DAG.
  144. SmallVector<SDNode *, 64> Worklist;
  145. /// Mapping from an SDNode to its position on the worklist.
  146. ///
  147. /// This is used to find and remove nodes from the worklist (by nulling
  148. /// them) when they are deleted from the underlying DAG. It relies on
  149. /// stable indices of nodes within the worklist.
  150. DenseMap<SDNode *, unsigned> WorklistMap;
  151. /// This records all nodes attempted to add to the worklist since we
  152. /// considered a new worklist entry. As we keep do not add duplicate nodes
  153. /// in the worklist, this is different from the tail of the worklist.
  154. SmallSetVector<SDNode *, 32> PruningList;
  155. /// Set of nodes which have been combined (at least once).
  156. ///
  157. /// This is used to allow us to reliably add any operands of a DAG node
  158. /// which have not yet been combined to the worklist.
  159. SmallPtrSet<SDNode *, 32> CombinedNodes;
  160. /// Map from candidate StoreNode to the pair of RootNode and count.
  161. /// The count is used to track how many times we have seen the StoreNode
  162. /// with the same RootNode bail out in dependence check. If we have seen
  163. /// the bail out for the same pair many times over a limit, we won't
  164. /// consider the StoreNode with the same RootNode as store merging
  165. /// candidate again.
  166. DenseMap<SDNode *, std::pair<SDNode *, unsigned>> StoreRootCountMap;
  167. // AA - Used for DAG load/store alias analysis.
  168. AliasAnalysis *AA;
  169. /// When an instruction is simplified, add all users of the instruction to
  170. /// the work lists because they might get more simplified now.
  171. void AddUsersToWorklist(SDNode *N) {
  172. for (SDNode *Node : N->uses())
  173. AddToWorklist(Node);
  174. }
  175. /// Convenient shorthand to add a node and all of its user to the worklist.
  176. void AddToWorklistWithUsers(SDNode *N) {
  177. AddUsersToWorklist(N);
  178. AddToWorklist(N);
  179. }
  180. // Prune potentially dangling nodes. This is called after
  181. // any visit to a node, but should also be called during a visit after any
  182. // failed combine which may have created a DAG node.
  183. void clearAddedDanglingWorklistEntries() {
  184. // Check any nodes added to the worklist to see if they are prunable.
  185. while (!PruningList.empty()) {
  186. auto *N = PruningList.pop_back_val();
  187. if (N->use_empty())
  188. recursivelyDeleteUnusedNodes(N);
  189. }
  190. }
  191. SDNode *getNextWorklistEntry() {
  192. // Before we do any work, remove nodes that are not in use.
  193. clearAddedDanglingWorklistEntries();
  194. SDNode *N = nullptr;
  195. // The Worklist holds the SDNodes in order, but it may contain null
  196. // entries.
  197. while (!N && !Worklist.empty()) {
  198. N = Worklist.pop_back_val();
  199. }
  200. if (N) {
  201. bool GoodWorklistEntry = WorklistMap.erase(N);
  202. (void)GoodWorklistEntry;
  203. assert(GoodWorklistEntry &&
  204. "Found a worklist entry without a corresponding map entry!");
  205. }
  206. return N;
  207. }
  208. /// Call the node-specific routine that folds each particular type of node.
  209. SDValue visit(SDNode *N);
  210. public:
  211. DAGCombiner(SelectionDAG &D, AliasAnalysis *AA, CodeGenOpt::Level OL)
  212. : DAG(D), TLI(D.getTargetLoweringInfo()),
  213. STI(D.getSubtarget().getSelectionDAGInfo()), OptLevel(OL), AA(AA) {
  214. ForCodeSize = DAG.shouldOptForSize();
  215. DisableGenericCombines = STI && STI->disableGenericCombines(OptLevel);
  216. MaximumLegalStoreInBits = 0;
  217. // We use the minimum store size here, since that's all we can guarantee
  218. // for the scalable vector types.
  219. for (MVT VT : MVT::all_valuetypes())
  220. if (EVT(VT).isSimple() && VT != MVT::Other &&
  221. TLI.isTypeLegal(EVT(VT)) &&
  222. VT.getSizeInBits().getKnownMinSize() >= MaximumLegalStoreInBits)
  223. MaximumLegalStoreInBits = VT.getSizeInBits().getKnownMinSize();
  224. }
  225. void ConsiderForPruning(SDNode *N) {
  226. // Mark this for potential pruning.
  227. PruningList.insert(N);
  228. }
  229. /// Add to the worklist making sure its instance is at the back (next to be
  230. /// processed.)
  231. void AddToWorklist(SDNode *N) {
  232. assert(N->getOpcode() != ISD::DELETED_NODE &&
  233. "Deleted Node added to Worklist");
  234. // Skip handle nodes as they can't usefully be combined and confuse the
  235. // zero-use deletion strategy.
  236. if (N->getOpcode() == ISD::HANDLENODE)
  237. return;
  238. ConsiderForPruning(N);
  239. if (WorklistMap.insert(std::make_pair(N, Worklist.size())).second)
  240. Worklist.push_back(N);
  241. }
  242. /// Remove all instances of N from the worklist.
  243. void removeFromWorklist(SDNode *N) {
  244. CombinedNodes.erase(N);
  245. PruningList.remove(N);
  246. StoreRootCountMap.erase(N);
  247. auto It = WorklistMap.find(N);
  248. if (It == WorklistMap.end())
  249. return; // Not in the worklist.
  250. // Null out the entry rather than erasing it to avoid a linear operation.
  251. Worklist[It->second] = nullptr;
  252. WorklistMap.erase(It);
  253. }
  254. void deleteAndRecombine(SDNode *N);
  255. bool recursivelyDeleteUnusedNodes(SDNode *N);
  256. /// Replaces all uses of the results of one DAG node with new values.
  257. SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
  258. bool AddTo = true);
  259. /// Replaces all uses of the results of one DAG node with new values.
  260. SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
  261. return CombineTo(N, &Res, 1, AddTo);
  262. }
  263. /// Replaces all uses of the results of one DAG node with new values.
  264. SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
  265. bool AddTo = true) {
  266. SDValue To[] = { Res0, Res1 };
  267. return CombineTo(N, To, 2, AddTo);
  268. }
  269. void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
  270. private:
  271. unsigned MaximumLegalStoreInBits;
  272. /// Check the specified integer node value to see if it can be simplified or
  273. /// if things it uses can be simplified by bit propagation.
  274. /// If so, return true.
  275. bool SimplifyDemandedBits(SDValue Op) {
  276. unsigned BitWidth = Op.getScalarValueSizeInBits();
  277. APInt DemandedBits = APInt::getAllOnes(BitWidth);
  278. return SimplifyDemandedBits(Op, DemandedBits);
  279. }
  280. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits) {
  281. TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
  282. KnownBits Known;
  283. if (!TLI.SimplifyDemandedBits(Op, DemandedBits, Known, TLO, 0, false))
  284. return false;
  285. // Revisit the node.
  286. AddToWorklist(Op.getNode());
  287. CommitTargetLoweringOpt(TLO);
  288. return true;
  289. }
  290. /// Check the specified vector node value to see if it can be simplified or
  291. /// if things it uses can be simplified as it only uses some of the
  292. /// elements. If so, return true.
  293. bool SimplifyDemandedVectorElts(SDValue Op) {
  294. // TODO: For now just pretend it cannot be simplified.
  295. if (Op.getValueType().isScalableVector())
  296. return false;
  297. unsigned NumElts = Op.getValueType().getVectorNumElements();
  298. APInt DemandedElts = APInt::getAllOnes(NumElts);
  299. return SimplifyDemandedVectorElts(Op, DemandedElts);
  300. }
  301. bool SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
  302. const APInt &DemandedElts,
  303. bool AssumeSingleUse = false);
  304. bool SimplifyDemandedVectorElts(SDValue Op, const APInt &DemandedElts,
  305. bool AssumeSingleUse = false);
  306. bool CombineToPreIndexedLoadStore(SDNode *N);
  307. bool CombineToPostIndexedLoadStore(SDNode *N);
  308. SDValue SplitIndexingFromLoad(LoadSDNode *LD);
  309. bool SliceUpLoad(SDNode *N);
  310. // Scalars have size 0 to distinguish from singleton vectors.
  311. SDValue ForwardStoreValueToDirectLoad(LoadSDNode *LD);
  312. bool getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val);
  313. bool extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val);
  314. /// Replace an ISD::EXTRACT_VECTOR_ELT of a load with a narrowed
  315. /// load.
  316. ///
  317. /// \param EVE ISD::EXTRACT_VECTOR_ELT to be replaced.
  318. /// \param InVecVT type of the input vector to EVE with bitcasts resolved.
  319. /// \param EltNo index of the vector element to load.
  320. /// \param OriginalLoad load that EVE came from to be replaced.
  321. /// \returns EVE on success SDValue() on failure.
  322. SDValue scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT,
  323. SDValue EltNo,
  324. LoadSDNode *OriginalLoad);
  325. void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
  326. SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
  327. SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
  328. SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
  329. SDValue PromoteIntBinOp(SDValue Op);
  330. SDValue PromoteIntShiftOp(SDValue Op);
  331. SDValue PromoteExtend(SDValue Op);
  332. bool PromoteLoad(SDValue Op);
  333. /// Call the node-specific routine that knows how to fold each
  334. /// particular type of node. If that doesn't do anything, try the
  335. /// target-specific DAG combines.
  336. SDValue combine(SDNode *N);
  337. // Visitation implementation - Implement dag node combining for different
  338. // node types. The semantics are as follows:
  339. // Return Value:
  340. // SDValue.getNode() == 0 - No change was made
  341. // SDValue.getNode() == N - N was replaced, is dead and has been handled.
  342. // otherwise - N should be replaced by the returned Operand.
  343. //
  344. SDValue visitTokenFactor(SDNode *N);
  345. SDValue visitMERGE_VALUES(SDNode *N);
  346. SDValue visitADD(SDNode *N);
  347. SDValue visitADDLike(SDNode *N);
  348. SDValue visitADDLikeCommutative(SDValue N0, SDValue N1, SDNode *LocReference);
  349. SDValue visitSUB(SDNode *N);
  350. SDValue visitADDSAT(SDNode *N);
  351. SDValue visitSUBSAT(SDNode *N);
  352. SDValue visitADDC(SDNode *N);
  353. SDValue visitADDO(SDNode *N);
  354. SDValue visitUADDOLike(SDValue N0, SDValue N1, SDNode *N);
  355. SDValue visitSUBC(SDNode *N);
  356. SDValue visitSUBO(SDNode *N);
  357. SDValue visitADDE(SDNode *N);
  358. SDValue visitADDCARRY(SDNode *N);
  359. SDValue visitSADDO_CARRY(SDNode *N);
  360. SDValue visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn, SDNode *N);
  361. SDValue visitSUBE(SDNode *N);
  362. SDValue visitSUBCARRY(SDNode *N);
  363. SDValue visitSSUBO_CARRY(SDNode *N);
  364. SDValue visitMUL(SDNode *N);
  365. SDValue visitMULFIX(SDNode *N);
  366. SDValue useDivRem(SDNode *N);
  367. SDValue visitSDIV(SDNode *N);
  368. SDValue visitSDIVLike(SDValue N0, SDValue N1, SDNode *N);
  369. SDValue visitUDIV(SDNode *N);
  370. SDValue visitUDIVLike(SDValue N0, SDValue N1, SDNode *N);
  371. SDValue visitREM(SDNode *N);
  372. SDValue visitMULHU(SDNode *N);
  373. SDValue visitMULHS(SDNode *N);
  374. SDValue visitSMUL_LOHI(SDNode *N);
  375. SDValue visitUMUL_LOHI(SDNode *N);
  376. SDValue visitMULO(SDNode *N);
  377. SDValue visitIMINMAX(SDNode *N);
  378. SDValue visitAND(SDNode *N);
  379. SDValue visitANDLike(SDValue N0, SDValue N1, SDNode *N);
  380. SDValue visitOR(SDNode *N);
  381. SDValue visitORLike(SDValue N0, SDValue N1, SDNode *N);
  382. SDValue visitXOR(SDNode *N);
  383. SDValue SimplifyVBinOp(SDNode *N, const SDLoc &DL);
  384. SDValue visitSHL(SDNode *N);
  385. SDValue visitSRA(SDNode *N);
  386. SDValue visitSRL(SDNode *N);
  387. SDValue visitFunnelShift(SDNode *N);
  388. SDValue visitSHLSAT(SDNode *N);
  389. SDValue visitRotate(SDNode *N);
  390. SDValue visitABS(SDNode *N);
  391. SDValue visitBSWAP(SDNode *N);
  392. SDValue visitBITREVERSE(SDNode *N);
  393. SDValue visitCTLZ(SDNode *N);
  394. SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
  395. SDValue visitCTTZ(SDNode *N);
  396. SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
  397. SDValue visitCTPOP(SDNode *N);
  398. SDValue visitSELECT(SDNode *N);
  399. SDValue visitVSELECT(SDNode *N);
  400. SDValue visitSELECT_CC(SDNode *N);
  401. SDValue visitSETCC(SDNode *N);
  402. SDValue visitSETCCCARRY(SDNode *N);
  403. SDValue visitSIGN_EXTEND(SDNode *N);
  404. SDValue visitZERO_EXTEND(SDNode *N);
  405. SDValue visitANY_EXTEND(SDNode *N);
  406. SDValue visitAssertExt(SDNode *N);
  407. SDValue visitAssertAlign(SDNode *N);
  408. SDValue visitSIGN_EXTEND_INREG(SDNode *N);
  409. SDValue visitEXTEND_VECTOR_INREG(SDNode *N);
  410. SDValue visitTRUNCATE(SDNode *N);
  411. SDValue visitBITCAST(SDNode *N);
  412. SDValue visitFREEZE(SDNode *N);
  413. SDValue visitBUILD_PAIR(SDNode *N);
  414. SDValue visitFADD(SDNode *N);
  415. SDValue visitSTRICT_FADD(SDNode *N);
  416. SDValue visitFSUB(SDNode *N);
  417. SDValue visitFMUL(SDNode *N);
  418. SDValue visitFMA(SDNode *N);
  419. SDValue visitFDIV(SDNode *N);
  420. SDValue visitFREM(SDNode *N);
  421. SDValue visitFSQRT(SDNode *N);
  422. SDValue visitFCOPYSIGN(SDNode *N);
  423. SDValue visitFPOW(SDNode *N);
  424. SDValue visitSINT_TO_FP(SDNode *N);
  425. SDValue visitUINT_TO_FP(SDNode *N);
  426. SDValue visitFP_TO_SINT(SDNode *N);
  427. SDValue visitFP_TO_UINT(SDNode *N);
  428. SDValue visitFP_ROUND(SDNode *N);
  429. SDValue visitFP_EXTEND(SDNode *N);
  430. SDValue visitFNEG(SDNode *N);
  431. SDValue visitFABS(SDNode *N);
  432. SDValue visitFCEIL(SDNode *N);
  433. SDValue visitFTRUNC(SDNode *N);
  434. SDValue visitFFLOOR(SDNode *N);
  435. SDValue visitFMinMax(SDNode *N);
  436. SDValue visitBRCOND(SDNode *N);
  437. SDValue visitBR_CC(SDNode *N);
  438. SDValue visitLOAD(SDNode *N);
  439. SDValue replaceStoreChain(StoreSDNode *ST, SDValue BetterChain);
  440. SDValue replaceStoreOfFPConstant(StoreSDNode *ST);
  441. SDValue visitSTORE(SDNode *N);
  442. SDValue visitLIFETIME_END(SDNode *N);
  443. SDValue visitINSERT_VECTOR_ELT(SDNode *N);
  444. SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
  445. SDValue visitBUILD_VECTOR(SDNode *N);
  446. SDValue visitCONCAT_VECTORS(SDNode *N);
  447. SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
  448. SDValue visitVECTOR_SHUFFLE(SDNode *N);
  449. SDValue visitSCALAR_TO_VECTOR(SDNode *N);
  450. SDValue visitINSERT_SUBVECTOR(SDNode *N);
  451. SDValue visitMLOAD(SDNode *N);
  452. SDValue visitMSTORE(SDNode *N);
  453. SDValue visitMGATHER(SDNode *N);
  454. SDValue visitMSCATTER(SDNode *N);
  455. SDValue visitFP_TO_FP16(SDNode *N);
  456. SDValue visitFP16_TO_FP(SDNode *N);
  457. SDValue visitVECREDUCE(SDNode *N);
  458. SDValue visitVPOp(SDNode *N);
  459. SDValue visitFADDForFMACombine(SDNode *N);
  460. SDValue visitFSUBForFMACombine(SDNode *N);
  461. SDValue visitFMULForFMADistributiveCombine(SDNode *N);
  462. SDValue XformToShuffleWithZero(SDNode *N);
  463. bool reassociationCanBreakAddressingModePattern(unsigned Opc,
  464. const SDLoc &DL, SDValue N0,
  465. SDValue N1);
  466. SDValue reassociateOpsCommutative(unsigned Opc, const SDLoc &DL, SDValue N0,
  467. SDValue N1);
  468. SDValue reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
  469. SDValue N1, SDNodeFlags Flags);
  470. SDValue visitShiftByConstant(SDNode *N);
  471. SDValue foldSelectOfConstants(SDNode *N);
  472. SDValue foldVSelectOfConstants(SDNode *N);
  473. SDValue foldBinOpIntoSelect(SDNode *BO);
  474. bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
  475. SDValue hoistLogicOpWithSameOpcodeHands(SDNode *N);
  476. SDValue SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2);
  477. SDValue SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
  478. SDValue N2, SDValue N3, ISD::CondCode CC,
  479. bool NotExtCompare = false);
  480. SDValue convertSelectOfFPConstantsToLoadOffset(
  481. const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
  482. ISD::CondCode CC);
  483. SDValue foldSignChangeInBitcast(SDNode *N);
  484. SDValue foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0, SDValue N1,
  485. SDValue N2, SDValue N3, ISD::CondCode CC);
  486. SDValue foldSelectOfBinops(SDNode *N);
  487. SDValue foldSextSetcc(SDNode *N);
  488. SDValue foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
  489. const SDLoc &DL);
  490. SDValue foldSubToUSubSat(EVT DstVT, SDNode *N);
  491. SDValue unfoldMaskedMerge(SDNode *N);
  492. SDValue unfoldExtremeBitClearingToShifts(SDNode *N);
  493. SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
  494. const SDLoc &DL, bool foldBooleans);
  495. SDValue rebuildSetCC(SDValue N);
  496. bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
  497. SDValue &CC, bool MatchStrict = false) const;
  498. bool isOneUseSetCC(SDValue N) const;
  499. SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
  500. unsigned HiOp);
  501. SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
  502. SDValue CombineExtLoad(SDNode *N);
  503. SDValue CombineZExtLogicopShiftLoad(SDNode *N);
  504. SDValue combineRepeatedFPDivisors(SDNode *N);
  505. SDValue combineInsertEltToShuffle(SDNode *N, unsigned InsIndex);
  506. SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
  507. SDValue BuildSDIV(SDNode *N);
  508. SDValue BuildSDIVPow2(SDNode *N);
  509. SDValue BuildUDIV(SDNode *N);
  510. SDValue BuildLogBase2(SDValue V, const SDLoc &DL);
  511. SDValue BuildDivEstimate(SDValue N, SDValue Op, SDNodeFlags Flags);
  512. SDValue buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags);
  513. SDValue buildSqrtEstimate(SDValue Op, SDNodeFlags Flags);
  514. SDValue buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags, bool Recip);
  515. SDValue buildSqrtNROneConst(SDValue Arg, SDValue Est, unsigned Iterations,
  516. SDNodeFlags Flags, bool Reciprocal);
  517. SDValue buildSqrtNRTwoConst(SDValue Arg, SDValue Est, unsigned Iterations,
  518. SDNodeFlags Flags, bool Reciprocal);
  519. SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
  520. bool DemandHighBits = true);
  521. SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
  522. SDValue MatchRotatePosNeg(SDValue Shifted, SDValue Pos, SDValue Neg,
  523. SDValue InnerPos, SDValue InnerNeg,
  524. unsigned PosOpcode, unsigned NegOpcode,
  525. const SDLoc &DL);
  526. SDValue MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos, SDValue Neg,
  527. SDValue InnerPos, SDValue InnerNeg,
  528. unsigned PosOpcode, unsigned NegOpcode,
  529. const SDLoc &DL);
  530. SDValue MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL);
  531. SDValue MatchLoadCombine(SDNode *N);
  532. SDValue mergeTruncStores(StoreSDNode *N);
  533. SDValue reduceLoadWidth(SDNode *N);
  534. SDValue ReduceLoadOpStoreWidth(SDNode *N);
  535. SDValue splitMergedValStore(StoreSDNode *ST);
  536. SDValue TransformFPLoadStorePair(SDNode *N);
  537. SDValue convertBuildVecZextToZext(SDNode *N);
  538. SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
  539. SDValue reduceBuildVecTruncToBitCast(SDNode *N);
  540. SDValue reduceBuildVecToShuffle(SDNode *N);
  541. SDValue createBuildVecShuffle(const SDLoc &DL, SDNode *N,
  542. ArrayRef<int> VectorMask, SDValue VecIn1,
  543. SDValue VecIn2, unsigned LeftIdx,
  544. bool DidSplitVec);
  545. SDValue matchVSelectOpSizesWithSetCC(SDNode *Cast);
  546. /// Walk up chain skipping non-aliasing memory nodes,
  547. /// looking for aliasing nodes and adding them to the Aliases vector.
  548. void GatherAllAliases(SDNode *N, SDValue OriginalChain,
  549. SmallVectorImpl<SDValue> &Aliases);
  550. /// Return true if there is any possibility that the two addresses overlap.
  551. bool mayAlias(SDNode *Op0, SDNode *Op1) const;
  552. /// Walk up chain skipping non-aliasing memory nodes, looking for a better
  553. /// chain (aliasing node.)
  554. SDValue FindBetterChain(SDNode *N, SDValue Chain);
  555. /// Try to replace a store and any possibly adjacent stores on
  556. /// consecutive chains with better chains. Return true only if St is
  557. /// replaced.
  558. ///
  559. /// Notice that other chains may still be replaced even if the function
  560. /// returns false.
  561. bool findBetterNeighborChains(StoreSDNode *St);
  562. // Helper for findBetterNeighborChains. Walk up store chain add additional
  563. // chained stores that do not overlap and can be parallelized.
  564. bool parallelizeChainedStores(StoreSDNode *St);
  565. /// Holds a pointer to an LSBaseSDNode as well as information on where it
  566. /// is located in a sequence of memory operations connected by a chain.
  567. struct MemOpLink {
  568. // Ptr to the mem node.
  569. LSBaseSDNode *MemNode;
  570. // Offset from the base ptr.
  571. int64_t OffsetFromBase;
  572. MemOpLink(LSBaseSDNode *N, int64_t Offset)
  573. : MemNode(N), OffsetFromBase(Offset) {}
  574. };
  575. // Classify the origin of a stored value.
  576. enum class StoreSource { Unknown, Constant, Extract, Load };
  577. StoreSource getStoreSource(SDValue StoreVal) {
  578. switch (StoreVal.getOpcode()) {
  579. case ISD::Constant:
  580. case ISD::ConstantFP:
  581. return StoreSource::Constant;
  582. case ISD::EXTRACT_VECTOR_ELT:
  583. case ISD::EXTRACT_SUBVECTOR:
  584. return StoreSource::Extract;
  585. case ISD::LOAD:
  586. return StoreSource::Load;
  587. default:
  588. return StoreSource::Unknown;
  589. }
  590. }
  591. /// This is a helper function for visitMUL to check the profitability
  592. /// of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
  593. /// MulNode is the original multiply, AddNode is (add x, c1),
  594. /// and ConstNode is c2.
  595. bool isMulAddWithConstProfitable(SDNode *MulNode,
  596. SDValue &AddNode,
  597. SDValue &ConstNode);
  598. /// This is a helper function for visitAND and visitZERO_EXTEND. Returns
  599. /// true if the (and (load x) c) pattern matches an extload. ExtVT returns
  600. /// the type of the loaded value to be extended.
  601. bool isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
  602. EVT LoadResultTy, EVT &ExtVT);
  603. /// Helper function to calculate whether the given Load/Store can have its
  604. /// width reduced to ExtVT.
  605. bool isLegalNarrowLdSt(LSBaseSDNode *LDSTN, ISD::LoadExtType ExtType,
  606. EVT &MemVT, unsigned ShAmt = 0);
  607. /// Used by BackwardsPropagateMask to find suitable loads.
  608. bool SearchForAndLoads(SDNode *N, SmallVectorImpl<LoadSDNode*> &Loads,
  609. SmallPtrSetImpl<SDNode*> &NodesWithConsts,
  610. ConstantSDNode *Mask, SDNode *&NodeToMask);
  611. /// Attempt to propagate a given AND node back to load leaves so that they
  612. /// can be combined into narrow loads.
  613. bool BackwardsPropagateMask(SDNode *N);
  614. /// Helper function for mergeConsecutiveStores which merges the component
  615. /// store chains.
  616. SDValue getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
  617. unsigned NumStores);
  618. /// This is a helper function for mergeConsecutiveStores. When the source
  619. /// elements of the consecutive stores are all constants or all extracted
  620. /// vector elements, try to merge them into one larger store introducing
  621. /// bitcasts if necessary. \return True if a merged store was created.
  622. bool mergeStoresOfConstantsOrVecElts(SmallVectorImpl<MemOpLink> &StoreNodes,
  623. EVT MemVT, unsigned NumStores,
  624. bool IsConstantSrc, bool UseVector,
  625. bool UseTrunc);
  626. /// This is a helper function for mergeConsecutiveStores. Stores that
  627. /// potentially may be merged with St are placed in StoreNodes. RootNode is
  628. /// a chain predecessor to all store candidates.
  629. void getStoreMergeCandidates(StoreSDNode *St,
  630. SmallVectorImpl<MemOpLink> &StoreNodes,
  631. SDNode *&Root);
  632. /// Helper function for mergeConsecutiveStores. Checks if candidate stores
  633. /// have indirect dependency through their operands. RootNode is the
  634. /// predecessor to all stores calculated by getStoreMergeCandidates and is
  635. /// used to prune the dependency check. \return True if safe to merge.
  636. bool checkMergeStoreCandidatesForDependencies(
  637. SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
  638. SDNode *RootNode);
  639. /// This is a helper function for mergeConsecutiveStores. Given a list of
  640. /// store candidates, find the first N that are consecutive in memory.
  641. /// Returns 0 if there are not at least 2 consecutive stores to try merging.
  642. unsigned getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes,
  643. int64_t ElementSizeBytes) const;
  644. /// This is a helper function for mergeConsecutiveStores. It is used for
  645. /// store chains that are composed entirely of constant values.
  646. bool tryStoreMergeOfConstants(SmallVectorImpl<MemOpLink> &StoreNodes,
  647. unsigned NumConsecutiveStores,
  648. EVT MemVT, SDNode *Root, bool AllowVectors);
  649. /// This is a helper function for mergeConsecutiveStores. It is used for
  650. /// store chains that are composed entirely of extracted vector elements.
  651. /// When extracting multiple vector elements, try to store them in one
  652. /// vector store rather than a sequence of scalar stores.
  653. bool tryStoreMergeOfExtracts(SmallVectorImpl<MemOpLink> &StoreNodes,
  654. unsigned NumConsecutiveStores, EVT MemVT,
  655. SDNode *Root);
  656. /// This is a helper function for mergeConsecutiveStores. It is used for
  657. /// store chains that are composed entirely of loaded values.
  658. bool tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes,
  659. unsigned NumConsecutiveStores, EVT MemVT,
  660. SDNode *Root, bool AllowVectors,
  661. bool IsNonTemporalStore, bool IsNonTemporalLoad);
  662. /// Merge consecutive store operations into a wide store.
  663. /// This optimization uses wide integers or vectors when possible.
  664. /// \return true if stores were merged.
  665. bool mergeConsecutiveStores(StoreSDNode *St);
  666. /// Try to transform a truncation where C is a constant:
  667. /// (trunc (and X, C)) -> (and (trunc X), (trunc C))
  668. ///
  669. /// \p N needs to be a truncation and its first operand an AND. Other
  670. /// requirements are checked by the function (e.g. that trunc is
  671. /// single-use) and if missed an empty SDValue is returned.
  672. SDValue distributeTruncateThroughAnd(SDNode *N);
  673. /// Helper function to determine whether the target supports operation
  674. /// given by \p Opcode for type \p VT, that is, whether the operation
  675. /// is legal or custom before legalizing operations, and whether is
  676. /// legal (but not custom) after legalization.
  677. bool hasOperation(unsigned Opcode, EVT VT) {
  678. return TLI.isOperationLegalOrCustom(Opcode, VT, LegalOperations);
  679. }
  680. public:
  681. /// Runs the dag combiner on all nodes in the work list
  682. void Run(CombineLevel AtLevel);
  683. SelectionDAG &getDAG() const { return DAG; }
  684. /// Returns a type large enough to hold any valid shift amount - before type
  685. /// legalization these can be huge.
  686. EVT getShiftAmountTy(EVT LHSTy) {
  687. assert(LHSTy.isInteger() && "Shift amount is not an integer type!");
  688. return TLI.getShiftAmountTy(LHSTy, DAG.getDataLayout(), LegalTypes);
  689. }
  690. /// This method returns true if we are running before type legalization or
  691. /// if the specified VT is legal.
  692. bool isTypeLegal(const EVT &VT) {
  693. if (!LegalTypes) return true;
  694. return TLI.isTypeLegal(VT);
  695. }
  696. /// Convenience wrapper around TargetLowering::getSetCCResultType
  697. EVT getSetCCResultType(EVT VT) const {
  698. return TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
  699. }
  700. void ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
  701. SDValue OrigLoad, SDValue ExtLoad,
  702. ISD::NodeType ExtType);
  703. };
  704. /// This class is a DAGUpdateListener that removes any deleted
  705. /// nodes from the worklist.
  706. class WorklistRemover : public SelectionDAG::DAGUpdateListener {
  707. DAGCombiner &DC;
  708. public:
  709. explicit WorklistRemover(DAGCombiner &dc)
  710. : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
  711. void NodeDeleted(SDNode *N, SDNode *E) override {
  712. DC.removeFromWorklist(N);
  713. }
  714. };
  715. class WorklistInserter : public SelectionDAG::DAGUpdateListener {
  716. DAGCombiner &DC;
  717. public:
  718. explicit WorklistInserter(DAGCombiner &dc)
  719. : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
  720. // FIXME: Ideally we could add N to the worklist, but this causes exponential
  721. // compile time costs in large DAGs, e.g. Halide.
  722. void NodeInserted(SDNode *N) override { DC.ConsiderForPruning(N); }
  723. };
  724. } // end anonymous namespace
  725. //===----------------------------------------------------------------------===//
  726. // TargetLowering::DAGCombinerInfo implementation
  727. //===----------------------------------------------------------------------===//
  728. void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
  729. ((DAGCombiner*)DC)->AddToWorklist(N);
  730. }
  731. SDValue TargetLowering::DAGCombinerInfo::
  732. CombineTo(SDNode *N, ArrayRef<SDValue> To, bool AddTo) {
  733. return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
  734. }
  735. SDValue TargetLowering::DAGCombinerInfo::
  736. CombineTo(SDNode *N, SDValue Res, bool AddTo) {
  737. return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
  738. }
  739. SDValue TargetLowering::DAGCombinerInfo::
  740. CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
  741. return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
  742. }
  743. bool TargetLowering::DAGCombinerInfo::
  744. recursivelyDeleteUnusedNodes(SDNode *N) {
  745. return ((DAGCombiner*)DC)->recursivelyDeleteUnusedNodes(N);
  746. }
  747. void TargetLowering::DAGCombinerInfo::
  748. CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
  749. return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
  750. }
  751. //===----------------------------------------------------------------------===//
  752. // Helper Functions
  753. //===----------------------------------------------------------------------===//
  754. void DAGCombiner::deleteAndRecombine(SDNode *N) {
  755. removeFromWorklist(N);
  756. // If the operands of this node are only used by the node, they will now be
  757. // dead. Make sure to re-visit them and recursively delete dead nodes.
  758. for (const SDValue &Op : N->ops())
  759. // For an operand generating multiple values, one of the values may
  760. // become dead allowing further simplification (e.g. split index
  761. // arithmetic from an indexed load).
  762. if (Op->hasOneUse() || Op->getNumValues() > 1)
  763. AddToWorklist(Op.getNode());
  764. DAG.DeleteNode(N);
  765. }
  766. // APInts must be the same size for most operations, this helper
  767. // function zero extends the shorter of the pair so that they match.
  768. // We provide an Offset so that we can create bitwidths that won't overflow.
  769. static void zeroExtendToMatch(APInt &LHS, APInt &RHS, unsigned Offset = 0) {
  770. unsigned Bits = Offset + std::max(LHS.getBitWidth(), RHS.getBitWidth());
  771. LHS = LHS.zextOrSelf(Bits);
  772. RHS = RHS.zextOrSelf(Bits);
  773. }
  774. // Return true if this node is a setcc, or is a select_cc
  775. // that selects between the target values used for true and false, making it
  776. // equivalent to a setcc. Also, set the incoming LHS, RHS, and CC references to
  777. // the appropriate nodes based on the type of node we are checking. This
  778. // simplifies life a bit for the callers.
  779. bool DAGCombiner::isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
  780. SDValue &CC, bool MatchStrict) const {
  781. if (N.getOpcode() == ISD::SETCC) {
  782. LHS = N.getOperand(0);
  783. RHS = N.getOperand(1);
  784. CC = N.getOperand(2);
  785. return true;
  786. }
  787. if (MatchStrict &&
  788. (N.getOpcode() == ISD::STRICT_FSETCC ||
  789. N.getOpcode() == ISD::STRICT_FSETCCS)) {
  790. LHS = N.getOperand(1);
  791. RHS = N.getOperand(2);
  792. CC = N.getOperand(3);
  793. return true;
  794. }
  795. if (N.getOpcode() != ISD::SELECT_CC || !TLI.isConstTrueVal(N.getOperand(2)) ||
  796. !TLI.isConstFalseVal(N.getOperand(3)))
  797. return false;
  798. if (TLI.getBooleanContents(N.getValueType()) ==
  799. TargetLowering::UndefinedBooleanContent)
  800. return false;
  801. LHS = N.getOperand(0);
  802. RHS = N.getOperand(1);
  803. CC = N.getOperand(4);
  804. return true;
  805. }
  806. /// Return true if this is a SetCC-equivalent operation with only one use.
  807. /// If this is true, it allows the users to invert the operation for free when
  808. /// it is profitable to do so.
  809. bool DAGCombiner::isOneUseSetCC(SDValue N) const {
  810. SDValue N0, N1, N2;
  811. if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
  812. return true;
  813. return false;
  814. }
  815. static bool isConstantSplatVectorMaskForType(SDNode *N, EVT ScalarTy) {
  816. if (!ScalarTy.isSimple())
  817. return false;
  818. uint64_t MaskForTy = 0ULL;
  819. switch (ScalarTy.getSimpleVT().SimpleTy) {
  820. case MVT::i8:
  821. MaskForTy = 0xFFULL;
  822. break;
  823. case MVT::i16:
  824. MaskForTy = 0xFFFFULL;
  825. break;
  826. case MVT::i32:
  827. MaskForTy = 0xFFFFFFFFULL;
  828. break;
  829. default:
  830. return false;
  831. break;
  832. }
  833. APInt Val;
  834. if (ISD::isConstantSplatVector(N, Val))
  835. return Val.getLimitedValue() == MaskForTy;
  836. return false;
  837. }
  838. // Determines if it is a constant integer or a splat/build vector of constant
  839. // integers (and undefs).
  840. // Do not permit build vector implicit truncation.
  841. static bool isConstantOrConstantVector(SDValue N, bool NoOpaques = false) {
  842. if (ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N))
  843. return !(Const->isOpaque() && NoOpaques);
  844. if (N.getOpcode() != ISD::BUILD_VECTOR && N.getOpcode() != ISD::SPLAT_VECTOR)
  845. return false;
  846. unsigned BitWidth = N.getScalarValueSizeInBits();
  847. for (const SDValue &Op : N->op_values()) {
  848. if (Op.isUndef())
  849. continue;
  850. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(Op);
  851. if (!Const || Const->getAPIntValue().getBitWidth() != BitWidth ||
  852. (Const->isOpaque() && NoOpaques))
  853. return false;
  854. }
  855. return true;
  856. }
  857. // Determines if a BUILD_VECTOR is composed of all-constants possibly mixed with
  858. // undef's.
  859. static bool isAnyConstantBuildVector(SDValue V, bool NoOpaques = false) {
  860. if (V.getOpcode() != ISD::BUILD_VECTOR)
  861. return false;
  862. return isConstantOrConstantVector(V, NoOpaques) ||
  863. ISD::isBuildVectorOfConstantFPSDNodes(V.getNode());
  864. }
  865. // Determine if this an indexed load with an opaque target constant index.
  866. static bool canSplitIdx(LoadSDNode *LD) {
  867. return MaySplitLoadIndex &&
  868. (LD->getOperand(2).getOpcode() != ISD::TargetConstant ||
  869. !cast<ConstantSDNode>(LD->getOperand(2))->isOpaque());
  870. }
  871. bool DAGCombiner::reassociationCanBreakAddressingModePattern(unsigned Opc,
  872. const SDLoc &DL,
  873. SDValue N0,
  874. SDValue N1) {
  875. // Currently this only tries to ensure we don't undo the GEP splits done by
  876. // CodeGenPrepare when shouldConsiderGEPOffsetSplit is true. To ensure this,
  877. // we check if the following transformation would be problematic:
  878. // (load/store (add, (add, x, offset1), offset2)) ->
  879. // (load/store (add, x, offset1+offset2)).
  880. if (Opc != ISD::ADD || N0.getOpcode() != ISD::ADD)
  881. return false;
  882. if (N0.hasOneUse())
  883. return false;
  884. auto *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  885. auto *C2 = dyn_cast<ConstantSDNode>(N1);
  886. if (!C1 || !C2)
  887. return false;
  888. const APInt &C1APIntVal = C1->getAPIntValue();
  889. const APInt &C2APIntVal = C2->getAPIntValue();
  890. if (C1APIntVal.getBitWidth() > 64 || C2APIntVal.getBitWidth() > 64)
  891. return false;
  892. const APInt CombinedValueIntVal = C1APIntVal + C2APIntVal;
  893. if (CombinedValueIntVal.getBitWidth() > 64)
  894. return false;
  895. const int64_t CombinedValue = CombinedValueIntVal.getSExtValue();
  896. for (SDNode *Node : N0->uses()) {
  897. auto LoadStore = dyn_cast<MemSDNode>(Node);
  898. if (LoadStore) {
  899. // Is x[offset2] already not a legal addressing mode? If so then
  900. // reassociating the constants breaks nothing (we test offset2 because
  901. // that's the one we hope to fold into the load or store).
  902. TargetLoweringBase::AddrMode AM;
  903. AM.HasBaseReg = true;
  904. AM.BaseOffs = C2APIntVal.getSExtValue();
  905. EVT VT = LoadStore->getMemoryVT();
  906. unsigned AS = LoadStore->getAddressSpace();
  907. Type *AccessTy = VT.getTypeForEVT(*DAG.getContext());
  908. if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
  909. continue;
  910. // Would x[offset1+offset2] still be a legal addressing mode?
  911. AM.BaseOffs = CombinedValue;
  912. if (!TLI.isLegalAddressingMode(DAG.getDataLayout(), AM, AccessTy, AS))
  913. return true;
  914. }
  915. }
  916. return false;
  917. }
  918. // Helper for DAGCombiner::reassociateOps. Try to reassociate an expression
  919. // such as (Opc N0, N1), if \p N0 is the same kind of operation as \p Opc.
  920. SDValue DAGCombiner::reassociateOpsCommutative(unsigned Opc, const SDLoc &DL,
  921. SDValue N0, SDValue N1) {
  922. EVT VT = N0.getValueType();
  923. if (N0.getOpcode() != Opc)
  924. return SDValue();
  925. SDValue N00 = N0.getOperand(0);
  926. SDValue N01 = N0.getOperand(1);
  927. if (DAG.isConstantIntBuildVectorOrConstantInt(peekThroughBitcasts(N01))) {
  928. if (DAG.isConstantIntBuildVectorOrConstantInt(peekThroughBitcasts(N1))) {
  929. // Reassociate: (op (op x, c1), c2) -> (op x, (op c1, c2))
  930. if (SDValue OpNode = DAG.FoldConstantArithmetic(Opc, DL, VT, {N01, N1}))
  931. return DAG.getNode(Opc, DL, VT, N00, OpNode);
  932. return SDValue();
  933. }
  934. if (TLI.isReassocProfitable(DAG, N0, N1)) {
  935. // Reassociate: (op (op x, c1), y) -> (op (op x, y), c1)
  936. // iff (op x, c1) has one use
  937. if (SDValue OpNode = DAG.getNode(Opc, SDLoc(N0), VT, N00, N1))
  938. return DAG.getNode(Opc, DL, VT, OpNode, N01);
  939. return SDValue();
  940. }
  941. }
  942. return SDValue();
  943. }
  944. // Try to reassociate commutative binops.
  945. SDValue DAGCombiner::reassociateOps(unsigned Opc, const SDLoc &DL, SDValue N0,
  946. SDValue N1, SDNodeFlags Flags) {
  947. assert(TLI.isCommutativeBinOp(Opc) && "Operation not commutative.");
  948. // Floating-point reassociation is not allowed without loose FP math.
  949. if (N0.getValueType().isFloatingPoint() ||
  950. N1.getValueType().isFloatingPoint())
  951. if (!Flags.hasAllowReassociation() || !Flags.hasNoSignedZeros())
  952. return SDValue();
  953. if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N0, N1))
  954. return Combined;
  955. if (SDValue Combined = reassociateOpsCommutative(Opc, DL, N1, N0))
  956. return Combined;
  957. return SDValue();
  958. }
  959. SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
  960. bool AddTo) {
  961. assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
  962. ++NodesCombined;
  963. LLVM_DEBUG(dbgs() << "\nReplacing.1 "; N->dump(&DAG); dbgs() << "\nWith: ";
  964. To[0].getNode()->dump(&DAG);
  965. dbgs() << " and " << NumTo - 1 << " other values\n");
  966. for (unsigned i = 0, e = NumTo; i != e; ++i)
  967. assert((!To[i].getNode() ||
  968. N->getValueType(i) == To[i].getValueType()) &&
  969. "Cannot combine value to value of different type!");
  970. WorklistRemover DeadNodes(*this);
  971. DAG.ReplaceAllUsesWith(N, To);
  972. if (AddTo) {
  973. // Push the new nodes and any users onto the worklist
  974. for (unsigned i = 0, e = NumTo; i != e; ++i) {
  975. if (To[i].getNode()) {
  976. AddToWorklist(To[i].getNode());
  977. AddUsersToWorklist(To[i].getNode());
  978. }
  979. }
  980. }
  981. // Finally, if the node is now dead, remove it from the graph. The node
  982. // may not be dead if the replacement process recursively simplified to
  983. // something else needing this node.
  984. if (N->use_empty())
  985. deleteAndRecombine(N);
  986. return SDValue(N, 0);
  987. }
  988. void DAGCombiner::
  989. CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
  990. // Replace the old value with the new one.
  991. ++NodesCombined;
  992. LLVM_DEBUG(dbgs() << "\nReplacing.2 "; TLO.Old.getNode()->dump(&DAG);
  993. dbgs() << "\nWith: "; TLO.New.getNode()->dump(&DAG);
  994. dbgs() << '\n');
  995. // Replace all uses. If any nodes become isomorphic to other nodes and
  996. // are deleted, make sure to remove them from our worklist.
  997. WorklistRemover DeadNodes(*this);
  998. DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
  999. // Push the new node and any (possibly new) users onto the worklist.
  1000. AddToWorklistWithUsers(TLO.New.getNode());
  1001. // Finally, if the node is now dead, remove it from the graph. The node
  1002. // may not be dead if the replacement process recursively simplified to
  1003. // something else needing this node.
  1004. if (TLO.Old.getNode()->use_empty())
  1005. deleteAndRecombine(TLO.Old.getNode());
  1006. }
  1007. /// Check the specified integer node value to see if it can be simplified or if
  1008. /// things it uses can be simplified by bit propagation. If so, return true.
  1009. bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &DemandedBits,
  1010. const APInt &DemandedElts,
  1011. bool AssumeSingleUse) {
  1012. TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
  1013. KnownBits Known;
  1014. if (!TLI.SimplifyDemandedBits(Op, DemandedBits, DemandedElts, Known, TLO, 0,
  1015. AssumeSingleUse))
  1016. return false;
  1017. // Revisit the node.
  1018. AddToWorklist(Op.getNode());
  1019. CommitTargetLoweringOpt(TLO);
  1020. return true;
  1021. }
  1022. /// Check the specified vector node value to see if it can be simplified or
  1023. /// if things it uses can be simplified as it only uses some of the elements.
  1024. /// If so, return true.
  1025. bool DAGCombiner::SimplifyDemandedVectorElts(SDValue Op,
  1026. const APInt &DemandedElts,
  1027. bool AssumeSingleUse) {
  1028. TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
  1029. APInt KnownUndef, KnownZero;
  1030. if (!TLI.SimplifyDemandedVectorElts(Op, DemandedElts, KnownUndef, KnownZero,
  1031. TLO, 0, AssumeSingleUse))
  1032. return false;
  1033. // Revisit the node.
  1034. AddToWorklist(Op.getNode());
  1035. CommitTargetLoweringOpt(TLO);
  1036. return true;
  1037. }
  1038. void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
  1039. SDLoc DL(Load);
  1040. EVT VT = Load->getValueType(0);
  1041. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, VT, SDValue(ExtLoad, 0));
  1042. LLVM_DEBUG(dbgs() << "\nReplacing.9 "; Load->dump(&DAG); dbgs() << "\nWith: ";
  1043. Trunc.getNode()->dump(&DAG); dbgs() << '\n');
  1044. WorklistRemover DeadNodes(*this);
  1045. DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
  1046. DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
  1047. deleteAndRecombine(Load);
  1048. AddToWorklist(Trunc.getNode());
  1049. }
  1050. SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
  1051. Replace = false;
  1052. SDLoc DL(Op);
  1053. if (ISD::isUNINDEXEDLoad(Op.getNode())) {
  1054. LoadSDNode *LD = cast<LoadSDNode>(Op);
  1055. EVT MemVT = LD->getMemoryVT();
  1056. ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
  1057. : LD->getExtensionType();
  1058. Replace = true;
  1059. return DAG.getExtLoad(ExtType, DL, PVT,
  1060. LD->getChain(), LD->getBasePtr(),
  1061. MemVT, LD->getMemOperand());
  1062. }
  1063. unsigned Opc = Op.getOpcode();
  1064. switch (Opc) {
  1065. default: break;
  1066. case ISD::AssertSext:
  1067. if (SDValue Op0 = SExtPromoteOperand(Op.getOperand(0), PVT))
  1068. return DAG.getNode(ISD::AssertSext, DL, PVT, Op0, Op.getOperand(1));
  1069. break;
  1070. case ISD::AssertZext:
  1071. if (SDValue Op0 = ZExtPromoteOperand(Op.getOperand(0), PVT))
  1072. return DAG.getNode(ISD::AssertZext, DL, PVT, Op0, Op.getOperand(1));
  1073. break;
  1074. case ISD::Constant: {
  1075. unsigned ExtOpc =
  1076. Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  1077. return DAG.getNode(ExtOpc, DL, PVT, Op);
  1078. }
  1079. }
  1080. if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
  1081. return SDValue();
  1082. return DAG.getNode(ISD::ANY_EXTEND, DL, PVT, Op);
  1083. }
  1084. SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
  1085. if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
  1086. return SDValue();
  1087. EVT OldVT = Op.getValueType();
  1088. SDLoc DL(Op);
  1089. bool Replace = false;
  1090. SDValue NewOp = PromoteOperand(Op, PVT, Replace);
  1091. if (!NewOp.getNode())
  1092. return SDValue();
  1093. AddToWorklist(NewOp.getNode());
  1094. if (Replace)
  1095. ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
  1096. return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, NewOp.getValueType(), NewOp,
  1097. DAG.getValueType(OldVT));
  1098. }
  1099. SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
  1100. EVT OldVT = Op.getValueType();
  1101. SDLoc DL(Op);
  1102. bool Replace = false;
  1103. SDValue NewOp = PromoteOperand(Op, PVT, Replace);
  1104. if (!NewOp.getNode())
  1105. return SDValue();
  1106. AddToWorklist(NewOp.getNode());
  1107. if (Replace)
  1108. ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
  1109. return DAG.getZeroExtendInReg(NewOp, DL, OldVT);
  1110. }
  1111. /// Promote the specified integer binary operation if the target indicates it is
  1112. /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
  1113. /// i32 since i16 instructions are longer.
  1114. SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
  1115. if (!LegalOperations)
  1116. return SDValue();
  1117. EVT VT = Op.getValueType();
  1118. if (VT.isVector() || !VT.isInteger())
  1119. return SDValue();
  1120. // If operation type is 'undesirable', e.g. i16 on x86, consider
  1121. // promoting it.
  1122. unsigned Opc = Op.getOpcode();
  1123. if (TLI.isTypeDesirableForOp(Opc, VT))
  1124. return SDValue();
  1125. EVT PVT = VT;
  1126. // Consult target whether it is a good idea to promote this operation and
  1127. // what's the right type to promote it to.
  1128. if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
  1129. assert(PVT != VT && "Don't know what type to promote to!");
  1130. LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
  1131. bool Replace0 = false;
  1132. SDValue N0 = Op.getOperand(0);
  1133. SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
  1134. bool Replace1 = false;
  1135. SDValue N1 = Op.getOperand(1);
  1136. SDValue NN1 = PromoteOperand(N1, PVT, Replace1);
  1137. SDLoc DL(Op);
  1138. SDValue RV =
  1139. DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, NN0, NN1));
  1140. // We are always replacing N0/N1's use in N and only need additional
  1141. // replacements if there are additional uses.
  1142. // Note: We are checking uses of the *nodes* (SDNode) rather than values
  1143. // (SDValue) here because the node may reference multiple values
  1144. // (for example, the chain value of a load node).
  1145. Replace0 &= !N0->hasOneUse();
  1146. Replace1 &= (N0 != N1) && !N1->hasOneUse();
  1147. // Combine Op here so it is preserved past replacements.
  1148. CombineTo(Op.getNode(), RV);
  1149. // If operands have a use ordering, make sure we deal with
  1150. // predecessor first.
  1151. if (Replace0 && Replace1 && N0.getNode()->isPredecessorOf(N1.getNode())) {
  1152. std::swap(N0, N1);
  1153. std::swap(NN0, NN1);
  1154. }
  1155. if (Replace0) {
  1156. AddToWorklist(NN0.getNode());
  1157. ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
  1158. }
  1159. if (Replace1) {
  1160. AddToWorklist(NN1.getNode());
  1161. ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
  1162. }
  1163. return Op;
  1164. }
  1165. return SDValue();
  1166. }
  1167. /// Promote the specified integer shift operation if the target indicates it is
  1168. /// beneficial. e.g. On x86, it's usually better to promote i16 operations to
  1169. /// i32 since i16 instructions are longer.
  1170. SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
  1171. if (!LegalOperations)
  1172. return SDValue();
  1173. EVT VT = Op.getValueType();
  1174. if (VT.isVector() || !VT.isInteger())
  1175. return SDValue();
  1176. // If operation type is 'undesirable', e.g. i16 on x86, consider
  1177. // promoting it.
  1178. unsigned Opc = Op.getOpcode();
  1179. if (TLI.isTypeDesirableForOp(Opc, VT))
  1180. return SDValue();
  1181. EVT PVT = VT;
  1182. // Consult target whether it is a good idea to promote this operation and
  1183. // what's the right type to promote it to.
  1184. if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
  1185. assert(PVT != VT && "Don't know what type to promote to!");
  1186. LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
  1187. bool Replace = false;
  1188. SDValue N0 = Op.getOperand(0);
  1189. SDValue N1 = Op.getOperand(1);
  1190. if (Opc == ISD::SRA)
  1191. N0 = SExtPromoteOperand(N0, PVT);
  1192. else if (Opc == ISD::SRL)
  1193. N0 = ZExtPromoteOperand(N0, PVT);
  1194. else
  1195. N0 = PromoteOperand(N0, PVT, Replace);
  1196. if (!N0.getNode())
  1197. return SDValue();
  1198. SDLoc DL(Op);
  1199. SDValue RV =
  1200. DAG.getNode(ISD::TRUNCATE, DL, VT, DAG.getNode(Opc, DL, PVT, N0, N1));
  1201. if (Replace)
  1202. ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
  1203. // Deal with Op being deleted.
  1204. if (Op && Op.getOpcode() != ISD::DELETED_NODE)
  1205. return RV;
  1206. }
  1207. return SDValue();
  1208. }
  1209. SDValue DAGCombiner::PromoteExtend(SDValue Op) {
  1210. if (!LegalOperations)
  1211. return SDValue();
  1212. EVT VT = Op.getValueType();
  1213. if (VT.isVector() || !VT.isInteger())
  1214. return SDValue();
  1215. // If operation type is 'undesirable', e.g. i16 on x86, consider
  1216. // promoting it.
  1217. unsigned Opc = Op.getOpcode();
  1218. if (TLI.isTypeDesirableForOp(Opc, VT))
  1219. return SDValue();
  1220. EVT PVT = VT;
  1221. // Consult target whether it is a good idea to promote this operation and
  1222. // what's the right type to promote it to.
  1223. if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
  1224. assert(PVT != VT && "Don't know what type to promote to!");
  1225. // fold (aext (aext x)) -> (aext x)
  1226. // fold (aext (zext x)) -> (zext x)
  1227. // fold (aext (sext x)) -> (sext x)
  1228. LLVM_DEBUG(dbgs() << "\nPromoting "; Op.getNode()->dump(&DAG));
  1229. return DAG.getNode(Op.getOpcode(), SDLoc(Op), VT, Op.getOperand(0));
  1230. }
  1231. return SDValue();
  1232. }
  1233. bool DAGCombiner::PromoteLoad(SDValue Op) {
  1234. if (!LegalOperations)
  1235. return false;
  1236. if (!ISD::isUNINDEXEDLoad(Op.getNode()))
  1237. return false;
  1238. EVT VT = Op.getValueType();
  1239. if (VT.isVector() || !VT.isInteger())
  1240. return false;
  1241. // If operation type is 'undesirable', e.g. i16 on x86, consider
  1242. // promoting it.
  1243. unsigned Opc = Op.getOpcode();
  1244. if (TLI.isTypeDesirableForOp(Opc, VT))
  1245. return false;
  1246. EVT PVT = VT;
  1247. // Consult target whether it is a good idea to promote this operation and
  1248. // what's the right type to promote it to.
  1249. if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
  1250. assert(PVT != VT && "Don't know what type to promote to!");
  1251. SDLoc DL(Op);
  1252. SDNode *N = Op.getNode();
  1253. LoadSDNode *LD = cast<LoadSDNode>(N);
  1254. EVT MemVT = LD->getMemoryVT();
  1255. ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD) ? ISD::EXTLOAD
  1256. : LD->getExtensionType();
  1257. SDValue NewLD = DAG.getExtLoad(ExtType, DL, PVT,
  1258. LD->getChain(), LD->getBasePtr(),
  1259. MemVT, LD->getMemOperand());
  1260. SDValue Result = DAG.getNode(ISD::TRUNCATE, DL, VT, NewLD);
  1261. LLVM_DEBUG(dbgs() << "\nPromoting "; N->dump(&DAG); dbgs() << "\nTo: ";
  1262. Result.getNode()->dump(&DAG); dbgs() << '\n');
  1263. WorklistRemover DeadNodes(*this);
  1264. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
  1265. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
  1266. deleteAndRecombine(N);
  1267. AddToWorklist(Result.getNode());
  1268. return true;
  1269. }
  1270. return false;
  1271. }
  1272. /// Recursively delete a node which has no uses and any operands for
  1273. /// which it is the only use.
  1274. ///
  1275. /// Note that this both deletes the nodes and removes them from the worklist.
  1276. /// It also adds any nodes who have had a user deleted to the worklist as they
  1277. /// may now have only one use and subject to other combines.
  1278. bool DAGCombiner::recursivelyDeleteUnusedNodes(SDNode *N) {
  1279. if (!N->use_empty())
  1280. return false;
  1281. SmallSetVector<SDNode *, 16> Nodes;
  1282. Nodes.insert(N);
  1283. do {
  1284. N = Nodes.pop_back_val();
  1285. if (!N)
  1286. continue;
  1287. if (N->use_empty()) {
  1288. for (const SDValue &ChildN : N->op_values())
  1289. Nodes.insert(ChildN.getNode());
  1290. removeFromWorklist(N);
  1291. DAG.DeleteNode(N);
  1292. } else {
  1293. AddToWorklist(N);
  1294. }
  1295. } while (!Nodes.empty());
  1296. return true;
  1297. }
  1298. //===----------------------------------------------------------------------===//
  1299. // Main DAG Combiner implementation
  1300. //===----------------------------------------------------------------------===//
  1301. void DAGCombiner::Run(CombineLevel AtLevel) {
  1302. // set the instance variables, so that the various visit routines may use it.
  1303. Level = AtLevel;
  1304. LegalDAG = Level >= AfterLegalizeDAG;
  1305. LegalOperations = Level >= AfterLegalizeVectorOps;
  1306. LegalTypes = Level >= AfterLegalizeTypes;
  1307. WorklistInserter AddNodes(*this);
  1308. // Add all the dag nodes to the worklist.
  1309. for (SDNode &Node : DAG.allnodes())
  1310. AddToWorklist(&Node);
  1311. // Create a dummy node (which is not added to allnodes), that adds a reference
  1312. // to the root node, preventing it from being deleted, and tracking any
  1313. // changes of the root.
  1314. HandleSDNode Dummy(DAG.getRoot());
  1315. // While we have a valid worklist entry node, try to combine it.
  1316. while (SDNode *N = getNextWorklistEntry()) {
  1317. // If N has no uses, it is dead. Make sure to revisit all N's operands once
  1318. // N is deleted from the DAG, since they too may now be dead or may have a
  1319. // reduced number of uses, allowing other xforms.
  1320. if (recursivelyDeleteUnusedNodes(N))
  1321. continue;
  1322. WorklistRemover DeadNodes(*this);
  1323. // If this combine is running after legalizing the DAG, re-legalize any
  1324. // nodes pulled off the worklist.
  1325. if (LegalDAG) {
  1326. SmallSetVector<SDNode *, 16> UpdatedNodes;
  1327. bool NIsValid = DAG.LegalizeOp(N, UpdatedNodes);
  1328. for (SDNode *LN : UpdatedNodes)
  1329. AddToWorklistWithUsers(LN);
  1330. if (!NIsValid)
  1331. continue;
  1332. }
  1333. LLVM_DEBUG(dbgs() << "\nCombining: "; N->dump(&DAG));
  1334. // Add any operands of the new node which have not yet been combined to the
  1335. // worklist as well. Because the worklist uniques things already, this
  1336. // won't repeatedly process the same operand.
  1337. CombinedNodes.insert(N);
  1338. for (const SDValue &ChildN : N->op_values())
  1339. if (!CombinedNodes.count(ChildN.getNode()))
  1340. AddToWorklist(ChildN.getNode());
  1341. SDValue RV = combine(N);
  1342. if (!RV.getNode())
  1343. continue;
  1344. ++NodesCombined;
  1345. // If we get back the same node we passed in, rather than a new node or
  1346. // zero, we know that the node must have defined multiple values and
  1347. // CombineTo was used. Since CombineTo takes care of the worklist
  1348. // mechanics for us, we have no work to do in this case.
  1349. if (RV.getNode() == N)
  1350. continue;
  1351. assert(N->getOpcode() != ISD::DELETED_NODE &&
  1352. RV.getOpcode() != ISD::DELETED_NODE &&
  1353. "Node was deleted but visit returned new node!");
  1354. LLVM_DEBUG(dbgs() << " ... into: "; RV.getNode()->dump(&DAG));
  1355. if (N->getNumValues() == RV.getNode()->getNumValues())
  1356. DAG.ReplaceAllUsesWith(N, RV.getNode());
  1357. else {
  1358. assert(N->getValueType(0) == RV.getValueType() &&
  1359. N->getNumValues() == 1 && "Type mismatch");
  1360. DAG.ReplaceAllUsesWith(N, &RV);
  1361. }
  1362. // Push the new node and any users onto the worklist. Omit this if the
  1363. // new node is the EntryToken (e.g. if a store managed to get optimized
  1364. // out), because re-visiting the EntryToken and its users will not uncover
  1365. // any additional opportunities, but there may be a large number of such
  1366. // users, potentially causing compile time explosion.
  1367. if (RV.getOpcode() != ISD::EntryToken) {
  1368. AddToWorklist(RV.getNode());
  1369. AddUsersToWorklist(RV.getNode());
  1370. }
  1371. // Finally, if the node is now dead, remove it from the graph. The node
  1372. // may not be dead if the replacement process recursively simplified to
  1373. // something else needing this node. This will also take care of adding any
  1374. // operands which have lost a user to the worklist.
  1375. recursivelyDeleteUnusedNodes(N);
  1376. }
  1377. // If the root changed (e.g. it was a dead load, update the root).
  1378. DAG.setRoot(Dummy.getValue());
  1379. DAG.RemoveDeadNodes();
  1380. }
  1381. SDValue DAGCombiner::visit(SDNode *N) {
  1382. switch (N->getOpcode()) {
  1383. default: break;
  1384. case ISD::TokenFactor: return visitTokenFactor(N);
  1385. case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
  1386. case ISD::ADD: return visitADD(N);
  1387. case ISD::SUB: return visitSUB(N);
  1388. case ISD::SADDSAT:
  1389. case ISD::UADDSAT: return visitADDSAT(N);
  1390. case ISD::SSUBSAT:
  1391. case ISD::USUBSAT: return visitSUBSAT(N);
  1392. case ISD::ADDC: return visitADDC(N);
  1393. case ISD::SADDO:
  1394. case ISD::UADDO: return visitADDO(N);
  1395. case ISD::SUBC: return visitSUBC(N);
  1396. case ISD::SSUBO:
  1397. case ISD::USUBO: return visitSUBO(N);
  1398. case ISD::ADDE: return visitADDE(N);
  1399. case ISD::ADDCARRY: return visitADDCARRY(N);
  1400. case ISD::SADDO_CARRY: return visitSADDO_CARRY(N);
  1401. case ISD::SUBE: return visitSUBE(N);
  1402. case ISD::SUBCARRY: return visitSUBCARRY(N);
  1403. case ISD::SSUBO_CARRY: return visitSSUBO_CARRY(N);
  1404. case ISD::SMULFIX:
  1405. case ISD::SMULFIXSAT:
  1406. case ISD::UMULFIX:
  1407. case ISD::UMULFIXSAT: return visitMULFIX(N);
  1408. case ISD::MUL: return visitMUL(N);
  1409. case ISD::SDIV: return visitSDIV(N);
  1410. case ISD::UDIV: return visitUDIV(N);
  1411. case ISD::SREM:
  1412. case ISD::UREM: return visitREM(N);
  1413. case ISD::MULHU: return visitMULHU(N);
  1414. case ISD::MULHS: return visitMULHS(N);
  1415. case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
  1416. case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
  1417. case ISD::SMULO:
  1418. case ISD::UMULO: return visitMULO(N);
  1419. case ISD::SMIN:
  1420. case ISD::SMAX:
  1421. case ISD::UMIN:
  1422. case ISD::UMAX: return visitIMINMAX(N);
  1423. case ISD::AND: return visitAND(N);
  1424. case ISD::OR: return visitOR(N);
  1425. case ISD::XOR: return visitXOR(N);
  1426. case ISD::SHL: return visitSHL(N);
  1427. case ISD::SRA: return visitSRA(N);
  1428. case ISD::SRL: return visitSRL(N);
  1429. case ISD::ROTR:
  1430. case ISD::ROTL: return visitRotate(N);
  1431. case ISD::FSHL:
  1432. case ISD::FSHR: return visitFunnelShift(N);
  1433. case ISD::SSHLSAT:
  1434. case ISD::USHLSAT: return visitSHLSAT(N);
  1435. case ISD::ABS: return visitABS(N);
  1436. case ISD::BSWAP: return visitBSWAP(N);
  1437. case ISD::BITREVERSE: return visitBITREVERSE(N);
  1438. case ISD::CTLZ: return visitCTLZ(N);
  1439. case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
  1440. case ISD::CTTZ: return visitCTTZ(N);
  1441. case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
  1442. case ISD::CTPOP: return visitCTPOP(N);
  1443. case ISD::SELECT: return visitSELECT(N);
  1444. case ISD::VSELECT: return visitVSELECT(N);
  1445. case ISD::SELECT_CC: return visitSELECT_CC(N);
  1446. case ISD::SETCC: return visitSETCC(N);
  1447. case ISD::SETCCCARRY: return visitSETCCCARRY(N);
  1448. case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
  1449. case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
  1450. case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
  1451. case ISD::AssertSext:
  1452. case ISD::AssertZext: return visitAssertExt(N);
  1453. case ISD::AssertAlign: return visitAssertAlign(N);
  1454. case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
  1455. case ISD::SIGN_EXTEND_VECTOR_INREG:
  1456. case ISD::ZERO_EXTEND_VECTOR_INREG: return visitEXTEND_VECTOR_INREG(N);
  1457. case ISD::TRUNCATE: return visitTRUNCATE(N);
  1458. case ISD::BITCAST: return visitBITCAST(N);
  1459. case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
  1460. case ISD::FADD: return visitFADD(N);
  1461. case ISD::STRICT_FADD: return visitSTRICT_FADD(N);
  1462. case ISD::FSUB: return visitFSUB(N);
  1463. case ISD::FMUL: return visitFMUL(N);
  1464. case ISD::FMA: return visitFMA(N);
  1465. case ISD::FDIV: return visitFDIV(N);
  1466. case ISD::FREM: return visitFREM(N);
  1467. case ISD::FSQRT: return visitFSQRT(N);
  1468. case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
  1469. case ISD::FPOW: return visitFPOW(N);
  1470. case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
  1471. case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
  1472. case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
  1473. case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
  1474. case ISD::FP_ROUND: return visitFP_ROUND(N);
  1475. case ISD::FP_EXTEND: return visitFP_EXTEND(N);
  1476. case ISD::FNEG: return visitFNEG(N);
  1477. case ISD::FABS: return visitFABS(N);
  1478. case ISD::FFLOOR: return visitFFLOOR(N);
  1479. case ISD::FMINNUM:
  1480. case ISD::FMAXNUM:
  1481. case ISD::FMINIMUM:
  1482. case ISD::FMAXIMUM: return visitFMinMax(N);
  1483. case ISD::FCEIL: return visitFCEIL(N);
  1484. case ISD::FTRUNC: return visitFTRUNC(N);
  1485. case ISD::BRCOND: return visitBRCOND(N);
  1486. case ISD::BR_CC: return visitBR_CC(N);
  1487. case ISD::LOAD: return visitLOAD(N);
  1488. case ISD::STORE: return visitSTORE(N);
  1489. case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
  1490. case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
  1491. case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
  1492. case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
  1493. case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
  1494. case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
  1495. case ISD::SCALAR_TO_VECTOR: return visitSCALAR_TO_VECTOR(N);
  1496. case ISD::INSERT_SUBVECTOR: return visitINSERT_SUBVECTOR(N);
  1497. case ISD::MGATHER: return visitMGATHER(N);
  1498. case ISD::MLOAD: return visitMLOAD(N);
  1499. case ISD::MSCATTER: return visitMSCATTER(N);
  1500. case ISD::MSTORE: return visitMSTORE(N);
  1501. case ISD::LIFETIME_END: return visitLIFETIME_END(N);
  1502. case ISD::FP_TO_FP16: return visitFP_TO_FP16(N);
  1503. case ISD::FP16_TO_FP: return visitFP16_TO_FP(N);
  1504. case ISD::FREEZE: return visitFREEZE(N);
  1505. case ISD::VECREDUCE_FADD:
  1506. case ISD::VECREDUCE_FMUL:
  1507. case ISD::VECREDUCE_ADD:
  1508. case ISD::VECREDUCE_MUL:
  1509. case ISD::VECREDUCE_AND:
  1510. case ISD::VECREDUCE_OR:
  1511. case ISD::VECREDUCE_XOR:
  1512. case ISD::VECREDUCE_SMAX:
  1513. case ISD::VECREDUCE_SMIN:
  1514. case ISD::VECREDUCE_UMAX:
  1515. case ISD::VECREDUCE_UMIN:
  1516. case ISD::VECREDUCE_FMAX:
  1517. case ISD::VECREDUCE_FMIN: return visitVECREDUCE(N);
  1518. #define BEGIN_REGISTER_VP_SDNODE(SDOPC, ...) case ISD::SDOPC:
  1519. #include "llvm/IR/VPIntrinsics.def"
  1520. return visitVPOp(N);
  1521. }
  1522. return SDValue();
  1523. }
  1524. SDValue DAGCombiner::combine(SDNode *N) {
  1525. SDValue RV;
  1526. if (!DisableGenericCombines)
  1527. RV = visit(N);
  1528. // If nothing happened, try a target-specific DAG combine.
  1529. if (!RV.getNode()) {
  1530. assert(N->getOpcode() != ISD::DELETED_NODE &&
  1531. "Node was deleted but visit returned NULL!");
  1532. if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
  1533. TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
  1534. // Expose the DAG combiner to the target combiner impls.
  1535. TargetLowering::DAGCombinerInfo
  1536. DagCombineInfo(DAG, Level, false, this);
  1537. RV = TLI.PerformDAGCombine(N, DagCombineInfo);
  1538. }
  1539. }
  1540. // If nothing happened still, try promoting the operation.
  1541. if (!RV.getNode()) {
  1542. switch (N->getOpcode()) {
  1543. default: break;
  1544. case ISD::ADD:
  1545. case ISD::SUB:
  1546. case ISD::MUL:
  1547. case ISD::AND:
  1548. case ISD::OR:
  1549. case ISD::XOR:
  1550. RV = PromoteIntBinOp(SDValue(N, 0));
  1551. break;
  1552. case ISD::SHL:
  1553. case ISD::SRA:
  1554. case ISD::SRL:
  1555. RV = PromoteIntShiftOp(SDValue(N, 0));
  1556. break;
  1557. case ISD::SIGN_EXTEND:
  1558. case ISD::ZERO_EXTEND:
  1559. case ISD::ANY_EXTEND:
  1560. RV = PromoteExtend(SDValue(N, 0));
  1561. break;
  1562. case ISD::LOAD:
  1563. if (PromoteLoad(SDValue(N, 0)))
  1564. RV = SDValue(N, 0);
  1565. break;
  1566. }
  1567. }
  1568. // If N is a commutative binary node, try to eliminate it if the commuted
  1569. // version is already present in the DAG.
  1570. if (!RV.getNode() && TLI.isCommutativeBinOp(N->getOpcode()) &&
  1571. N->getNumValues() == 1) {
  1572. SDValue N0 = N->getOperand(0);
  1573. SDValue N1 = N->getOperand(1);
  1574. // Constant operands are canonicalized to RHS.
  1575. if (N0 != N1 && (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1))) {
  1576. SDValue Ops[] = {N1, N0};
  1577. SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(), Ops,
  1578. N->getFlags());
  1579. if (CSENode)
  1580. return SDValue(CSENode, 0);
  1581. }
  1582. }
  1583. return RV;
  1584. }
  1585. /// Given a node, return its input chain if it has one, otherwise return a null
  1586. /// sd operand.
  1587. static SDValue getInputChainForNode(SDNode *N) {
  1588. if (unsigned NumOps = N->getNumOperands()) {
  1589. if (N->getOperand(0).getValueType() == MVT::Other)
  1590. return N->getOperand(0);
  1591. if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
  1592. return N->getOperand(NumOps-1);
  1593. for (unsigned i = 1; i < NumOps-1; ++i)
  1594. if (N->getOperand(i).getValueType() == MVT::Other)
  1595. return N->getOperand(i);
  1596. }
  1597. return SDValue();
  1598. }
  1599. SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
  1600. // If N has two operands, where one has an input chain equal to the other,
  1601. // the 'other' chain is redundant.
  1602. if (N->getNumOperands() == 2) {
  1603. if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
  1604. return N->getOperand(0);
  1605. if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
  1606. return N->getOperand(1);
  1607. }
  1608. // Don't simplify token factors if optnone.
  1609. if (OptLevel == CodeGenOpt::None)
  1610. return SDValue();
  1611. // Don't simplify the token factor if the node itself has too many operands.
  1612. if (N->getNumOperands() > TokenFactorInlineLimit)
  1613. return SDValue();
  1614. // If the sole user is a token factor, we should make sure we have a
  1615. // chance to merge them together. This prevents TF chains from inhibiting
  1616. // optimizations.
  1617. if (N->hasOneUse() && N->use_begin()->getOpcode() == ISD::TokenFactor)
  1618. AddToWorklist(*(N->use_begin()));
  1619. SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
  1620. SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
  1621. SmallPtrSet<SDNode*, 16> SeenOps;
  1622. bool Changed = false; // If we should replace this token factor.
  1623. // Start out with this token factor.
  1624. TFs.push_back(N);
  1625. // Iterate through token factors. The TFs grows when new token factors are
  1626. // encountered.
  1627. for (unsigned i = 0; i < TFs.size(); ++i) {
  1628. // Limit number of nodes to inline, to avoid quadratic compile times.
  1629. // We have to add the outstanding Token Factors to Ops, otherwise we might
  1630. // drop Ops from the resulting Token Factors.
  1631. if (Ops.size() > TokenFactorInlineLimit) {
  1632. for (unsigned j = i; j < TFs.size(); j++)
  1633. Ops.emplace_back(TFs[j], 0);
  1634. // Drop unprocessed Token Factors from TFs, so we do not add them to the
  1635. // combiner worklist later.
  1636. TFs.resize(i);
  1637. break;
  1638. }
  1639. SDNode *TF = TFs[i];
  1640. // Check each of the operands.
  1641. for (const SDValue &Op : TF->op_values()) {
  1642. switch (Op.getOpcode()) {
  1643. case ISD::EntryToken:
  1644. // Entry tokens don't need to be added to the list. They are
  1645. // redundant.
  1646. Changed = true;
  1647. break;
  1648. case ISD::TokenFactor:
  1649. if (Op.hasOneUse() && !is_contained(TFs, Op.getNode())) {
  1650. // Queue up for processing.
  1651. TFs.push_back(Op.getNode());
  1652. Changed = true;
  1653. break;
  1654. }
  1655. LLVM_FALLTHROUGH;
  1656. default:
  1657. // Only add if it isn't already in the list.
  1658. if (SeenOps.insert(Op.getNode()).second)
  1659. Ops.push_back(Op);
  1660. else
  1661. Changed = true;
  1662. break;
  1663. }
  1664. }
  1665. }
  1666. // Re-visit inlined Token Factors, to clean them up in case they have been
  1667. // removed. Skip the first Token Factor, as this is the current node.
  1668. for (unsigned i = 1, e = TFs.size(); i < e; i++)
  1669. AddToWorklist(TFs[i]);
  1670. // Remove Nodes that are chained to another node in the list. Do so
  1671. // by walking up chains breath-first stopping when we've seen
  1672. // another operand. In general we must climb to the EntryNode, but we can exit
  1673. // early if we find all remaining work is associated with just one operand as
  1674. // no further pruning is possible.
  1675. // List of nodes to search through and original Ops from which they originate.
  1676. SmallVector<std::pair<SDNode *, unsigned>, 8> Worklist;
  1677. SmallVector<unsigned, 8> OpWorkCount; // Count of work for each Op.
  1678. SmallPtrSet<SDNode *, 16> SeenChains;
  1679. bool DidPruneOps = false;
  1680. unsigned NumLeftToConsider = 0;
  1681. for (const SDValue &Op : Ops) {
  1682. Worklist.push_back(std::make_pair(Op.getNode(), NumLeftToConsider++));
  1683. OpWorkCount.push_back(1);
  1684. }
  1685. auto AddToWorklist = [&](unsigned CurIdx, SDNode *Op, unsigned OpNumber) {
  1686. // If this is an Op, we can remove the op from the list. Remark any
  1687. // search associated with it as from the current OpNumber.
  1688. if (SeenOps.contains(Op)) {
  1689. Changed = true;
  1690. DidPruneOps = true;
  1691. unsigned OrigOpNumber = 0;
  1692. while (OrigOpNumber < Ops.size() && Ops[OrigOpNumber].getNode() != Op)
  1693. OrigOpNumber++;
  1694. assert((OrigOpNumber != Ops.size()) &&
  1695. "expected to find TokenFactor Operand");
  1696. // Re-mark worklist from OrigOpNumber to OpNumber
  1697. for (unsigned i = CurIdx + 1; i < Worklist.size(); ++i) {
  1698. if (Worklist[i].second == OrigOpNumber) {
  1699. Worklist[i].second = OpNumber;
  1700. }
  1701. }
  1702. OpWorkCount[OpNumber] += OpWorkCount[OrigOpNumber];
  1703. OpWorkCount[OrigOpNumber] = 0;
  1704. NumLeftToConsider--;
  1705. }
  1706. // Add if it's a new chain
  1707. if (SeenChains.insert(Op).second) {
  1708. OpWorkCount[OpNumber]++;
  1709. Worklist.push_back(std::make_pair(Op, OpNumber));
  1710. }
  1711. };
  1712. for (unsigned i = 0; i < Worklist.size() && i < 1024; ++i) {
  1713. // We need at least be consider at least 2 Ops to prune.
  1714. if (NumLeftToConsider <= 1)
  1715. break;
  1716. auto CurNode = Worklist[i].first;
  1717. auto CurOpNumber = Worklist[i].second;
  1718. assert((OpWorkCount[CurOpNumber] > 0) &&
  1719. "Node should not appear in worklist");
  1720. switch (CurNode->getOpcode()) {
  1721. case ISD::EntryToken:
  1722. // Hitting EntryToken is the only way for the search to terminate without
  1723. // hitting
  1724. // another operand's search. Prevent us from marking this operand
  1725. // considered.
  1726. NumLeftToConsider++;
  1727. break;
  1728. case ISD::TokenFactor:
  1729. for (const SDValue &Op : CurNode->op_values())
  1730. AddToWorklist(i, Op.getNode(), CurOpNumber);
  1731. break;
  1732. case ISD::LIFETIME_START:
  1733. case ISD::LIFETIME_END:
  1734. case ISD::CopyFromReg:
  1735. case ISD::CopyToReg:
  1736. AddToWorklist(i, CurNode->getOperand(0).getNode(), CurOpNumber);
  1737. break;
  1738. default:
  1739. if (auto *MemNode = dyn_cast<MemSDNode>(CurNode))
  1740. AddToWorklist(i, MemNode->getChain().getNode(), CurOpNumber);
  1741. break;
  1742. }
  1743. OpWorkCount[CurOpNumber]--;
  1744. if (OpWorkCount[CurOpNumber] == 0)
  1745. NumLeftToConsider--;
  1746. }
  1747. // If we've changed things around then replace token factor.
  1748. if (Changed) {
  1749. SDValue Result;
  1750. if (Ops.empty()) {
  1751. // The entry token is the only possible outcome.
  1752. Result = DAG.getEntryNode();
  1753. } else {
  1754. if (DidPruneOps) {
  1755. SmallVector<SDValue, 8> PrunedOps;
  1756. //
  1757. for (const SDValue &Op : Ops) {
  1758. if (SeenChains.count(Op.getNode()) == 0)
  1759. PrunedOps.push_back(Op);
  1760. }
  1761. Result = DAG.getTokenFactor(SDLoc(N), PrunedOps);
  1762. } else {
  1763. Result = DAG.getTokenFactor(SDLoc(N), Ops);
  1764. }
  1765. }
  1766. return Result;
  1767. }
  1768. return SDValue();
  1769. }
  1770. /// MERGE_VALUES can always be eliminated.
  1771. SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
  1772. WorklistRemover DeadNodes(*this);
  1773. // Replacing results may cause a different MERGE_VALUES to suddenly
  1774. // be CSE'd with N, and carry its uses with it. Iterate until no
  1775. // uses remain, to ensure that the node can be safely deleted.
  1776. // First add the users of this node to the work list so that they
  1777. // can be tried again once they have new operands.
  1778. AddUsersToWorklist(N);
  1779. do {
  1780. // Do as a single replacement to avoid rewalking use lists.
  1781. SmallVector<SDValue, 8> Ops;
  1782. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
  1783. Ops.push_back(N->getOperand(i));
  1784. DAG.ReplaceAllUsesWith(N, Ops.data());
  1785. } while (!N->use_empty());
  1786. deleteAndRecombine(N);
  1787. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  1788. }
  1789. /// If \p N is a ConstantSDNode with isOpaque() == false return it casted to a
  1790. /// ConstantSDNode pointer else nullptr.
  1791. static ConstantSDNode *getAsNonOpaqueConstant(SDValue N) {
  1792. ConstantSDNode *Const = dyn_cast<ConstantSDNode>(N);
  1793. return Const != nullptr && !Const->isOpaque() ? Const : nullptr;
  1794. }
  1795. /// Return true if 'Use' is a load or a store that uses N as its base pointer
  1796. /// and that N may be folded in the load / store addressing mode.
  1797. static bool canFoldInAddressingMode(SDNode *N, SDNode *Use, SelectionDAG &DAG,
  1798. const TargetLowering &TLI) {
  1799. EVT VT;
  1800. unsigned AS;
  1801. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
  1802. if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
  1803. return false;
  1804. VT = LD->getMemoryVT();
  1805. AS = LD->getAddressSpace();
  1806. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
  1807. if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
  1808. return false;
  1809. VT = ST->getMemoryVT();
  1810. AS = ST->getAddressSpace();
  1811. } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(Use)) {
  1812. if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
  1813. return false;
  1814. VT = LD->getMemoryVT();
  1815. AS = LD->getAddressSpace();
  1816. } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(Use)) {
  1817. if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
  1818. return false;
  1819. VT = ST->getMemoryVT();
  1820. AS = ST->getAddressSpace();
  1821. } else
  1822. return false;
  1823. TargetLowering::AddrMode AM;
  1824. if (N->getOpcode() == ISD::ADD) {
  1825. AM.HasBaseReg = true;
  1826. ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
  1827. if (Offset)
  1828. // [reg +/- imm]
  1829. AM.BaseOffs = Offset->getSExtValue();
  1830. else
  1831. // [reg +/- reg]
  1832. AM.Scale = 1;
  1833. } else if (N->getOpcode() == ISD::SUB) {
  1834. AM.HasBaseReg = true;
  1835. ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
  1836. if (Offset)
  1837. // [reg +/- imm]
  1838. AM.BaseOffs = -Offset->getSExtValue();
  1839. else
  1840. // [reg +/- reg]
  1841. AM.Scale = 1;
  1842. } else
  1843. return false;
  1844. return TLI.isLegalAddressingMode(DAG.getDataLayout(), AM,
  1845. VT.getTypeForEVT(*DAG.getContext()), AS);
  1846. }
  1847. /// This inverts a canonicalization in IR that replaces a variable select arm
  1848. /// with an identity constant. Codegen improves if we re-use the variable
  1849. /// operand rather than load a constant. This can also be converted into a
  1850. /// masked vector operation if the target supports it.
  1851. static SDValue foldSelectWithIdentityConstant(SDNode *N, SelectionDAG &DAG,
  1852. bool ShouldCommuteOperands) {
  1853. // Match a select as operand 1. The identity constant that we are looking for
  1854. // is only valid as operand 1 of a non-commutative binop.
  1855. SDValue N0 = N->getOperand(0);
  1856. SDValue N1 = N->getOperand(1);
  1857. if (ShouldCommuteOperands)
  1858. std::swap(N0, N1);
  1859. // TODO: Should this apply to scalar select too?
  1860. if (!N1.hasOneUse() || N1.getOpcode() != ISD::VSELECT)
  1861. return SDValue();
  1862. unsigned Opcode = N->getOpcode();
  1863. EVT VT = N->getValueType(0);
  1864. SDValue Cond = N1.getOperand(0);
  1865. SDValue TVal = N1.getOperand(1);
  1866. SDValue FVal = N1.getOperand(2);
  1867. // TODO: The cases should match with IR's ConstantExpr::getBinOpIdentity().
  1868. // TODO: Target-specific opcodes could be added. Ex: "isCommutativeBinOp()".
  1869. // TODO: With fast-math (NSZ), allow the opposite-sign form of zero?
  1870. auto isIdentityConstantForOpcode = [](unsigned Opcode, SDValue V) {
  1871. if (ConstantFPSDNode *C = isConstOrConstSplatFP(V)) {
  1872. switch (Opcode) {
  1873. case ISD::FADD: // X + -0.0 --> X
  1874. return C->isZero() && C->isNegative();
  1875. case ISD::FSUB: // X - 0.0 --> X
  1876. return C->isZero() && !C->isNegative();
  1877. case ISD::FMUL: // X * 1.0 --> X
  1878. case ISD::FDIV: // X / 1.0 --> X
  1879. return C->isExactlyValue(1.0);
  1880. }
  1881. }
  1882. return false;
  1883. };
  1884. // This transform increases uses of N0, so freeze it to be safe.
  1885. // binop N0, (vselect Cond, IDC, FVal) --> vselect Cond, N0, (binop N0, FVal)
  1886. if (isIdentityConstantForOpcode(Opcode, TVal)) {
  1887. SDValue F0 = DAG.getFreeze(N0);
  1888. SDValue NewBO = DAG.getNode(Opcode, SDLoc(N), VT, F0, FVal, N->getFlags());
  1889. return DAG.getSelect(SDLoc(N), VT, Cond, F0, NewBO);
  1890. }
  1891. // binop N0, (vselect Cond, TVal, IDC) --> vselect Cond, (binop N0, TVal), N0
  1892. if (isIdentityConstantForOpcode(Opcode, FVal)) {
  1893. SDValue F0 = DAG.getFreeze(N0);
  1894. SDValue NewBO = DAG.getNode(Opcode, SDLoc(N), VT, F0, TVal, N->getFlags());
  1895. return DAG.getSelect(SDLoc(N), VT, Cond, NewBO, F0);
  1896. }
  1897. return SDValue();
  1898. }
  1899. SDValue DAGCombiner::foldBinOpIntoSelect(SDNode *BO) {
  1900. assert(TLI.isBinOp(BO->getOpcode()) && BO->getNumValues() == 1 &&
  1901. "Unexpected binary operator");
  1902. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  1903. auto BinOpcode = BO->getOpcode();
  1904. EVT VT = BO->getValueType(0);
  1905. if (TLI.shouldFoldSelectWithIdentityConstant(BinOpcode, VT)) {
  1906. if (SDValue Sel = foldSelectWithIdentityConstant(BO, DAG, false))
  1907. return Sel;
  1908. if (TLI.isCommutativeBinOp(BO->getOpcode()))
  1909. if (SDValue Sel = foldSelectWithIdentityConstant(BO, DAG, true))
  1910. return Sel;
  1911. }
  1912. // Don't do this unless the old select is going away. We want to eliminate the
  1913. // binary operator, not replace a binop with a select.
  1914. // TODO: Handle ISD::SELECT_CC.
  1915. unsigned SelOpNo = 0;
  1916. SDValue Sel = BO->getOperand(0);
  1917. if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse()) {
  1918. SelOpNo = 1;
  1919. Sel = BO->getOperand(1);
  1920. }
  1921. if (Sel.getOpcode() != ISD::SELECT || !Sel.hasOneUse())
  1922. return SDValue();
  1923. SDValue CT = Sel.getOperand(1);
  1924. if (!isConstantOrConstantVector(CT, true) &&
  1925. !DAG.isConstantFPBuildVectorOrConstantFP(CT))
  1926. return SDValue();
  1927. SDValue CF = Sel.getOperand(2);
  1928. if (!isConstantOrConstantVector(CF, true) &&
  1929. !DAG.isConstantFPBuildVectorOrConstantFP(CF))
  1930. return SDValue();
  1931. // Bail out if any constants are opaque because we can't constant fold those.
  1932. // The exception is "and" and "or" with either 0 or -1 in which case we can
  1933. // propagate non constant operands into select. I.e.:
  1934. // and (select Cond, 0, -1), X --> select Cond, 0, X
  1935. // or X, (select Cond, -1, 0) --> select Cond, -1, X
  1936. bool CanFoldNonConst =
  1937. (BinOpcode == ISD::AND || BinOpcode == ISD::OR) &&
  1938. (isNullOrNullSplat(CT) || isAllOnesOrAllOnesSplat(CT)) &&
  1939. (isNullOrNullSplat(CF) || isAllOnesOrAllOnesSplat(CF));
  1940. SDValue CBO = BO->getOperand(SelOpNo ^ 1);
  1941. if (!CanFoldNonConst &&
  1942. !isConstantOrConstantVector(CBO, true) &&
  1943. !DAG.isConstantFPBuildVectorOrConstantFP(CBO))
  1944. return SDValue();
  1945. // We have a select-of-constants followed by a binary operator with a
  1946. // constant. Eliminate the binop by pulling the constant math into the select.
  1947. // Example: add (select Cond, CT, CF), CBO --> select Cond, CT + CBO, CF + CBO
  1948. SDLoc DL(Sel);
  1949. SDValue NewCT = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CT)
  1950. : DAG.getNode(BinOpcode, DL, VT, CT, CBO);
  1951. if (!CanFoldNonConst && !NewCT.isUndef() &&
  1952. !isConstantOrConstantVector(NewCT, true) &&
  1953. !DAG.isConstantFPBuildVectorOrConstantFP(NewCT))
  1954. return SDValue();
  1955. SDValue NewCF = SelOpNo ? DAG.getNode(BinOpcode, DL, VT, CBO, CF)
  1956. : DAG.getNode(BinOpcode, DL, VT, CF, CBO);
  1957. if (!CanFoldNonConst && !NewCF.isUndef() &&
  1958. !isConstantOrConstantVector(NewCF, true) &&
  1959. !DAG.isConstantFPBuildVectorOrConstantFP(NewCF))
  1960. return SDValue();
  1961. SDValue SelectOp = DAG.getSelect(DL, VT, Sel.getOperand(0), NewCT, NewCF);
  1962. SelectOp->setFlags(BO->getFlags());
  1963. return SelectOp;
  1964. }
  1965. static SDValue foldAddSubBoolOfMaskedVal(SDNode *N, SelectionDAG &DAG) {
  1966. assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
  1967. "Expecting add or sub");
  1968. // Match a constant operand and a zext operand for the math instruction:
  1969. // add Z, C
  1970. // sub C, Z
  1971. bool IsAdd = N->getOpcode() == ISD::ADD;
  1972. SDValue C = IsAdd ? N->getOperand(1) : N->getOperand(0);
  1973. SDValue Z = IsAdd ? N->getOperand(0) : N->getOperand(1);
  1974. auto *CN = dyn_cast<ConstantSDNode>(C);
  1975. if (!CN || Z.getOpcode() != ISD::ZERO_EXTEND)
  1976. return SDValue();
  1977. // Match the zext operand as a setcc of a boolean.
  1978. if (Z.getOperand(0).getOpcode() != ISD::SETCC ||
  1979. Z.getOperand(0).getValueType() != MVT::i1)
  1980. return SDValue();
  1981. // Match the compare as: setcc (X & 1), 0, eq.
  1982. SDValue SetCC = Z.getOperand(0);
  1983. ISD::CondCode CC = cast<CondCodeSDNode>(SetCC->getOperand(2))->get();
  1984. if (CC != ISD::SETEQ || !isNullConstant(SetCC.getOperand(1)) ||
  1985. SetCC.getOperand(0).getOpcode() != ISD::AND ||
  1986. !isOneConstant(SetCC.getOperand(0).getOperand(1)))
  1987. return SDValue();
  1988. // We are adding/subtracting a constant and an inverted low bit. Turn that
  1989. // into a subtract/add of the low bit with incremented/decremented constant:
  1990. // add (zext i1 (seteq (X & 1), 0)), C --> sub C+1, (zext (X & 1))
  1991. // sub C, (zext i1 (seteq (X & 1), 0)) --> add C-1, (zext (X & 1))
  1992. EVT VT = C.getValueType();
  1993. SDLoc DL(N);
  1994. SDValue LowBit = DAG.getZExtOrTrunc(SetCC.getOperand(0), DL, VT);
  1995. SDValue C1 = IsAdd ? DAG.getConstant(CN->getAPIntValue() + 1, DL, VT) :
  1996. DAG.getConstant(CN->getAPIntValue() - 1, DL, VT);
  1997. return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, C1, LowBit);
  1998. }
  1999. /// Try to fold a 'not' shifted sign-bit with add/sub with constant operand into
  2000. /// a shift and add with a different constant.
  2001. static SDValue foldAddSubOfSignBit(SDNode *N, SelectionDAG &DAG) {
  2002. assert((N->getOpcode() == ISD::ADD || N->getOpcode() == ISD::SUB) &&
  2003. "Expecting add or sub");
  2004. // We need a constant operand for the add/sub, and the other operand is a
  2005. // logical shift right: add (srl), C or sub C, (srl).
  2006. bool IsAdd = N->getOpcode() == ISD::ADD;
  2007. SDValue ConstantOp = IsAdd ? N->getOperand(1) : N->getOperand(0);
  2008. SDValue ShiftOp = IsAdd ? N->getOperand(0) : N->getOperand(1);
  2009. if (!DAG.isConstantIntBuildVectorOrConstantInt(ConstantOp) ||
  2010. ShiftOp.getOpcode() != ISD::SRL)
  2011. return SDValue();
  2012. // The shift must be of a 'not' value.
  2013. SDValue Not = ShiftOp.getOperand(0);
  2014. if (!Not.hasOneUse() || !isBitwiseNot(Not))
  2015. return SDValue();
  2016. // The shift must be moving the sign bit to the least-significant-bit.
  2017. EVT VT = ShiftOp.getValueType();
  2018. SDValue ShAmt = ShiftOp.getOperand(1);
  2019. ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
  2020. if (!ShAmtC || ShAmtC->getAPIntValue() != (VT.getScalarSizeInBits() - 1))
  2021. return SDValue();
  2022. // Eliminate the 'not' by adjusting the shift and add/sub constant:
  2023. // add (srl (not X), 31), C --> add (sra X, 31), (C + 1)
  2024. // sub C, (srl (not X), 31) --> add (srl X, 31), (C - 1)
  2025. SDLoc DL(N);
  2026. auto ShOpcode = IsAdd ? ISD::SRA : ISD::SRL;
  2027. SDValue NewShift = DAG.getNode(ShOpcode, DL, VT, Not.getOperand(0), ShAmt);
  2028. if (SDValue NewC =
  2029. DAG.FoldConstantArithmetic(IsAdd ? ISD::ADD : ISD::SUB, DL, VT,
  2030. {ConstantOp, DAG.getConstant(1, DL, VT)}))
  2031. return DAG.getNode(ISD::ADD, DL, VT, NewShift, NewC);
  2032. return SDValue();
  2033. }
  2034. /// Try to fold a node that behaves like an ADD (note that N isn't necessarily
  2035. /// an ISD::ADD here, it could for example be an ISD::OR if we know that there
  2036. /// are no common bits set in the operands).
  2037. SDValue DAGCombiner::visitADDLike(SDNode *N) {
  2038. SDValue N0 = N->getOperand(0);
  2039. SDValue N1 = N->getOperand(1);
  2040. EVT VT = N0.getValueType();
  2041. SDLoc DL(N);
  2042. // fold (add x, undef) -> undef
  2043. if (N0.isUndef())
  2044. return N0;
  2045. if (N1.isUndef())
  2046. return N1;
  2047. // fold (add c1, c2) -> c1+c2
  2048. if (SDValue C = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0, N1}))
  2049. return C;
  2050. // canonicalize constant to RHS
  2051. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  2052. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  2053. return DAG.getNode(ISD::ADD, DL, VT, N1, N0);
  2054. // fold vector ops
  2055. if (VT.isVector()) {
  2056. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  2057. return FoldedVOp;
  2058. // fold (add x, 0) -> x, vector edition
  2059. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  2060. return N0;
  2061. }
  2062. // fold (add x, 0) -> x
  2063. if (isNullConstant(N1))
  2064. return N0;
  2065. if (isConstantOrConstantVector(N1, /* NoOpaque */ true)) {
  2066. // fold ((A-c1)+c2) -> (A+(c2-c1))
  2067. if (N0.getOpcode() == ISD::SUB &&
  2068. isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true)) {
  2069. SDValue Sub =
  2070. DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N1, N0.getOperand(1)});
  2071. assert(Sub && "Constant folding failed");
  2072. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Sub);
  2073. }
  2074. // fold ((c1-A)+c2) -> (c1+c2)-A
  2075. if (N0.getOpcode() == ISD::SUB &&
  2076. isConstantOrConstantVector(N0.getOperand(0), /* NoOpaque */ true)) {
  2077. SDValue Add =
  2078. DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N1, N0.getOperand(0)});
  2079. assert(Add && "Constant folding failed");
  2080. return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
  2081. }
  2082. // add (sext i1 X), 1 -> zext (not i1 X)
  2083. // We don't transform this pattern:
  2084. // add (zext i1 X), -1 -> sext (not i1 X)
  2085. // because most (?) targets generate better code for the zext form.
  2086. if (N0.getOpcode() == ISD::SIGN_EXTEND && N0.hasOneUse() &&
  2087. isOneOrOneSplat(N1)) {
  2088. SDValue X = N0.getOperand(0);
  2089. if ((!LegalOperations ||
  2090. (TLI.isOperationLegal(ISD::XOR, X.getValueType()) &&
  2091. TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) &&
  2092. X.getScalarValueSizeInBits() == 1) {
  2093. SDValue Not = DAG.getNOT(DL, X, X.getValueType());
  2094. return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Not);
  2095. }
  2096. }
  2097. // Fold (add (or x, c0), c1) -> (add x, (c0 + c1)) if (or x, c0) is
  2098. // equivalent to (add x, c0).
  2099. if (N0.getOpcode() == ISD::OR &&
  2100. isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true) &&
  2101. DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
  2102. if (SDValue Add0 = DAG.FoldConstantArithmetic(ISD::ADD, DL, VT,
  2103. {N1, N0.getOperand(1)}))
  2104. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), Add0);
  2105. }
  2106. }
  2107. if (SDValue NewSel = foldBinOpIntoSelect(N))
  2108. return NewSel;
  2109. // reassociate add
  2110. if (!reassociationCanBreakAddressingModePattern(ISD::ADD, DL, N0, N1)) {
  2111. if (SDValue RADD = reassociateOps(ISD::ADD, DL, N0, N1, N->getFlags()))
  2112. return RADD;
  2113. // Reassociate (add (or x, c), y) -> (add add(x, y), c)) if (or x, c) is
  2114. // equivalent to (add x, c).
  2115. auto ReassociateAddOr = [&](SDValue N0, SDValue N1) {
  2116. if (N0.getOpcode() == ISD::OR && N0.hasOneUse() &&
  2117. isConstantOrConstantVector(N0.getOperand(1), /* NoOpaque */ true) &&
  2118. DAG.haveNoCommonBitsSet(N0.getOperand(0), N0.getOperand(1))) {
  2119. return DAG.getNode(ISD::ADD, DL, VT,
  2120. DAG.getNode(ISD::ADD, DL, VT, N1, N0.getOperand(0)),
  2121. N0.getOperand(1));
  2122. }
  2123. return SDValue();
  2124. };
  2125. if (SDValue Add = ReassociateAddOr(N0, N1))
  2126. return Add;
  2127. if (SDValue Add = ReassociateAddOr(N1, N0))
  2128. return Add;
  2129. }
  2130. // fold ((0-A) + B) -> B-A
  2131. if (N0.getOpcode() == ISD::SUB && isNullOrNullSplat(N0.getOperand(0)))
  2132. return DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
  2133. // fold (A + (0-B)) -> A-B
  2134. if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
  2135. return DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(1));
  2136. // fold (A+(B-A)) -> B
  2137. if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
  2138. return N1.getOperand(0);
  2139. // fold ((B-A)+A) -> B
  2140. if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
  2141. return N0.getOperand(0);
  2142. // fold ((A-B)+(C-A)) -> (C-B)
  2143. if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
  2144. N0.getOperand(0) == N1.getOperand(1))
  2145. return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
  2146. N0.getOperand(1));
  2147. // fold ((A-B)+(B-C)) -> (A-C)
  2148. if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB &&
  2149. N0.getOperand(1) == N1.getOperand(0))
  2150. return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
  2151. N1.getOperand(1));
  2152. // fold (A+(B-(A+C))) to (B-C)
  2153. if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
  2154. N0 == N1.getOperand(1).getOperand(0))
  2155. return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
  2156. N1.getOperand(1).getOperand(1));
  2157. // fold (A+(B-(C+A))) to (B-C)
  2158. if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
  2159. N0 == N1.getOperand(1).getOperand(1))
  2160. return DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(0),
  2161. N1.getOperand(1).getOperand(0));
  2162. // fold (A+((B-A)+or-C)) to (B+or-C)
  2163. if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
  2164. N1.getOperand(0).getOpcode() == ISD::SUB &&
  2165. N0 == N1.getOperand(0).getOperand(1))
  2166. return DAG.getNode(N1.getOpcode(), DL, VT, N1.getOperand(0).getOperand(0),
  2167. N1.getOperand(1));
  2168. // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
  2169. if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
  2170. SDValue N00 = N0.getOperand(0);
  2171. SDValue N01 = N0.getOperand(1);
  2172. SDValue N10 = N1.getOperand(0);
  2173. SDValue N11 = N1.getOperand(1);
  2174. if (isConstantOrConstantVector(N00) || isConstantOrConstantVector(N10))
  2175. return DAG.getNode(ISD::SUB, DL, VT,
  2176. DAG.getNode(ISD::ADD, SDLoc(N0), VT, N00, N10),
  2177. DAG.getNode(ISD::ADD, SDLoc(N1), VT, N01, N11));
  2178. }
  2179. // fold (add (umax X, C), -C) --> (usubsat X, C)
  2180. if (N0.getOpcode() == ISD::UMAX && hasOperation(ISD::USUBSAT, VT)) {
  2181. auto MatchUSUBSAT = [](ConstantSDNode *Max, ConstantSDNode *Op) {
  2182. return (!Max && !Op) ||
  2183. (Max && Op && Max->getAPIntValue() == (-Op->getAPIntValue()));
  2184. };
  2185. if (ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchUSUBSAT,
  2186. /*AllowUndefs*/ true))
  2187. return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0),
  2188. N0.getOperand(1));
  2189. }
  2190. if (SimplifyDemandedBits(SDValue(N, 0)))
  2191. return SDValue(N, 0);
  2192. if (isOneOrOneSplat(N1)) {
  2193. // fold (add (xor a, -1), 1) -> (sub 0, a)
  2194. if (isBitwiseNot(N0))
  2195. return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
  2196. N0.getOperand(0));
  2197. // fold (add (add (xor a, -1), b), 1) -> (sub b, a)
  2198. if (N0.getOpcode() == ISD::ADD) {
  2199. SDValue A, Xor;
  2200. if (isBitwiseNot(N0.getOperand(0))) {
  2201. A = N0.getOperand(1);
  2202. Xor = N0.getOperand(0);
  2203. } else if (isBitwiseNot(N0.getOperand(1))) {
  2204. A = N0.getOperand(0);
  2205. Xor = N0.getOperand(1);
  2206. }
  2207. if (Xor)
  2208. return DAG.getNode(ISD::SUB, DL, VT, A, Xor.getOperand(0));
  2209. }
  2210. // Look for:
  2211. // add (add x, y), 1
  2212. // And if the target does not like this form then turn into:
  2213. // sub y, (xor x, -1)
  2214. if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() &&
  2215. N0.getOpcode() == ISD::ADD) {
  2216. SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
  2217. DAG.getAllOnesConstant(DL, VT));
  2218. return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(1), Not);
  2219. }
  2220. }
  2221. // (x - y) + -1 -> add (xor y, -1), x
  2222. if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
  2223. isAllOnesOrAllOnesSplat(N1)) {
  2224. SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1), N1);
  2225. return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0));
  2226. }
  2227. if (SDValue Combined = visitADDLikeCommutative(N0, N1, N))
  2228. return Combined;
  2229. if (SDValue Combined = visitADDLikeCommutative(N1, N0, N))
  2230. return Combined;
  2231. return SDValue();
  2232. }
  2233. SDValue DAGCombiner::visitADD(SDNode *N) {
  2234. SDValue N0 = N->getOperand(0);
  2235. SDValue N1 = N->getOperand(1);
  2236. EVT VT = N0.getValueType();
  2237. SDLoc DL(N);
  2238. if (SDValue Combined = visitADDLike(N))
  2239. return Combined;
  2240. if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
  2241. return V;
  2242. if (SDValue V = foldAddSubOfSignBit(N, DAG))
  2243. return V;
  2244. // fold (a+b) -> (a|b) iff a and b share no bits.
  2245. if ((!LegalOperations || TLI.isOperationLegal(ISD::OR, VT)) &&
  2246. DAG.haveNoCommonBitsSet(N0, N1))
  2247. return DAG.getNode(ISD::OR, DL, VT, N0, N1);
  2248. // Fold (add (vscale * C0), (vscale * C1)) to (vscale * (C0 + C1)).
  2249. if (N0.getOpcode() == ISD::VSCALE && N1.getOpcode() == ISD::VSCALE) {
  2250. const APInt &C0 = N0->getConstantOperandAPInt(0);
  2251. const APInt &C1 = N1->getConstantOperandAPInt(0);
  2252. return DAG.getVScale(DL, VT, C0 + C1);
  2253. }
  2254. // fold a+vscale(c1)+vscale(c2) -> a+vscale(c1+c2)
  2255. if ((N0.getOpcode() == ISD::ADD) &&
  2256. (N0.getOperand(1).getOpcode() == ISD::VSCALE) &&
  2257. (N1.getOpcode() == ISD::VSCALE)) {
  2258. const APInt &VS0 = N0.getOperand(1)->getConstantOperandAPInt(0);
  2259. const APInt &VS1 = N1->getConstantOperandAPInt(0);
  2260. SDValue VS = DAG.getVScale(DL, VT, VS0 + VS1);
  2261. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), VS);
  2262. }
  2263. // Fold (add step_vector(c1), step_vector(c2) to step_vector(c1+c2))
  2264. if (N0.getOpcode() == ISD::STEP_VECTOR &&
  2265. N1.getOpcode() == ISD::STEP_VECTOR) {
  2266. const APInt &C0 = N0->getConstantOperandAPInt(0);
  2267. const APInt &C1 = N1->getConstantOperandAPInt(0);
  2268. APInt NewStep = C0 + C1;
  2269. return DAG.getStepVector(DL, VT, NewStep);
  2270. }
  2271. // Fold a + step_vector(c1) + step_vector(c2) to a + step_vector(c1+c2)
  2272. if ((N0.getOpcode() == ISD::ADD) &&
  2273. (N0.getOperand(1).getOpcode() == ISD::STEP_VECTOR) &&
  2274. (N1.getOpcode() == ISD::STEP_VECTOR)) {
  2275. const APInt &SV0 = N0.getOperand(1)->getConstantOperandAPInt(0);
  2276. const APInt &SV1 = N1->getConstantOperandAPInt(0);
  2277. APInt NewStep = SV0 + SV1;
  2278. SDValue SV = DAG.getStepVector(DL, VT, NewStep);
  2279. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), SV);
  2280. }
  2281. return SDValue();
  2282. }
  2283. SDValue DAGCombiner::visitADDSAT(SDNode *N) {
  2284. unsigned Opcode = N->getOpcode();
  2285. SDValue N0 = N->getOperand(0);
  2286. SDValue N1 = N->getOperand(1);
  2287. EVT VT = N0.getValueType();
  2288. SDLoc DL(N);
  2289. // fold (add_sat x, undef) -> -1
  2290. if (N0.isUndef() || N1.isUndef())
  2291. return DAG.getAllOnesConstant(DL, VT);
  2292. // fold (add_sat c1, c2) -> c3
  2293. if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
  2294. return C;
  2295. // canonicalize constant to RHS
  2296. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  2297. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  2298. return DAG.getNode(Opcode, DL, VT, N1, N0);
  2299. // fold vector ops
  2300. if (VT.isVector()) {
  2301. // TODO SimplifyVBinOp
  2302. // fold (add_sat x, 0) -> x, vector edition
  2303. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  2304. return N0;
  2305. }
  2306. // fold (add_sat x, 0) -> x
  2307. if (isNullConstant(N1))
  2308. return N0;
  2309. // If it cannot overflow, transform into an add.
  2310. if (Opcode == ISD::UADDSAT)
  2311. if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
  2312. return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
  2313. return SDValue();
  2314. }
  2315. static SDValue getAsCarry(const TargetLowering &TLI, SDValue V) {
  2316. bool Masked = false;
  2317. // First, peel away TRUNCATE/ZERO_EXTEND/AND nodes due to legalization.
  2318. while (true) {
  2319. if (V.getOpcode() == ISD::TRUNCATE || V.getOpcode() == ISD::ZERO_EXTEND) {
  2320. V = V.getOperand(0);
  2321. continue;
  2322. }
  2323. if (V.getOpcode() == ISD::AND && isOneConstant(V.getOperand(1))) {
  2324. Masked = true;
  2325. V = V.getOperand(0);
  2326. continue;
  2327. }
  2328. break;
  2329. }
  2330. // If this is not a carry, return.
  2331. if (V.getResNo() != 1)
  2332. return SDValue();
  2333. if (V.getOpcode() != ISD::ADDCARRY && V.getOpcode() != ISD::SUBCARRY &&
  2334. V.getOpcode() != ISD::UADDO && V.getOpcode() != ISD::USUBO)
  2335. return SDValue();
  2336. EVT VT = V.getNode()->getValueType(0);
  2337. if (!TLI.isOperationLegalOrCustom(V.getOpcode(), VT))
  2338. return SDValue();
  2339. // If the result is masked, then no matter what kind of bool it is we can
  2340. // return. If it isn't, then we need to make sure the bool type is either 0 or
  2341. // 1 and not other values.
  2342. if (Masked ||
  2343. TLI.getBooleanContents(V.getValueType()) ==
  2344. TargetLoweringBase::ZeroOrOneBooleanContent)
  2345. return V;
  2346. return SDValue();
  2347. }
  2348. /// Given the operands of an add/sub operation, see if the 2nd operand is a
  2349. /// masked 0/1 whose source operand is actually known to be 0/-1. If so, invert
  2350. /// the opcode and bypass the mask operation.
  2351. static SDValue foldAddSubMasked1(bool IsAdd, SDValue N0, SDValue N1,
  2352. SelectionDAG &DAG, const SDLoc &DL) {
  2353. if (N1.getOpcode() != ISD::AND || !isOneOrOneSplat(N1->getOperand(1)))
  2354. return SDValue();
  2355. EVT VT = N0.getValueType();
  2356. if (DAG.ComputeNumSignBits(N1.getOperand(0)) != VT.getScalarSizeInBits())
  2357. return SDValue();
  2358. // add N0, (and (AssertSext X, i1), 1) --> sub N0, X
  2359. // sub N0, (and (AssertSext X, i1), 1) --> add N0, X
  2360. return DAG.getNode(IsAdd ? ISD::SUB : ISD::ADD, DL, VT, N0, N1.getOperand(0));
  2361. }
  2362. /// Helper for doing combines based on N0 and N1 being added to each other.
  2363. SDValue DAGCombiner::visitADDLikeCommutative(SDValue N0, SDValue N1,
  2364. SDNode *LocReference) {
  2365. EVT VT = N0.getValueType();
  2366. SDLoc DL(LocReference);
  2367. // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
  2368. if (N1.getOpcode() == ISD::SHL && N1.getOperand(0).getOpcode() == ISD::SUB &&
  2369. isNullOrNullSplat(N1.getOperand(0).getOperand(0)))
  2370. return DAG.getNode(ISD::SUB, DL, VT, N0,
  2371. DAG.getNode(ISD::SHL, DL, VT,
  2372. N1.getOperand(0).getOperand(1),
  2373. N1.getOperand(1)));
  2374. if (SDValue V = foldAddSubMasked1(true, N0, N1, DAG, DL))
  2375. return V;
  2376. // Look for:
  2377. // add (add x, 1), y
  2378. // And if the target does not like this form then turn into:
  2379. // sub y, (xor x, -1)
  2380. if (!TLI.preferIncOfAddToSubOfNot(VT) && N0.hasOneUse() &&
  2381. N0.getOpcode() == ISD::ADD && isOneOrOneSplat(N0.getOperand(1))) {
  2382. SDValue Not = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(0),
  2383. DAG.getAllOnesConstant(DL, VT));
  2384. return DAG.getNode(ISD::SUB, DL, VT, N1, Not);
  2385. }
  2386. // Hoist one-use subtraction by non-opaque constant:
  2387. // (x - C) + y -> (x + y) - C
  2388. // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
  2389. if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
  2390. isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
  2391. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), N1);
  2392. return DAG.getNode(ISD::SUB, DL, VT, Add, N0.getOperand(1));
  2393. }
  2394. // Hoist one-use subtraction from non-opaque constant:
  2395. // (C - x) + y -> (y - x) + C
  2396. if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
  2397. isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
  2398. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N1, N0.getOperand(1));
  2399. return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(0));
  2400. }
  2401. // If the target's bool is represented as 0/1, prefer to make this 'sub 0/1'
  2402. // rather than 'add 0/-1' (the zext should get folded).
  2403. // add (sext i1 Y), X --> sub X, (zext i1 Y)
  2404. if (N0.getOpcode() == ISD::SIGN_EXTEND &&
  2405. N0.getOperand(0).getScalarValueSizeInBits() == 1 &&
  2406. TLI.getBooleanContents(VT) == TargetLowering::ZeroOrOneBooleanContent) {
  2407. SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
  2408. return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
  2409. }
  2410. // add X, (sextinreg Y i1) -> sub X, (and Y 1)
  2411. if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
  2412. VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
  2413. if (TN->getVT() == MVT::i1) {
  2414. SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
  2415. DAG.getConstant(1, DL, VT));
  2416. return DAG.getNode(ISD::SUB, DL, VT, N0, ZExt);
  2417. }
  2418. }
  2419. // (add X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
  2420. if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1)) &&
  2421. N1.getResNo() == 0)
  2422. return DAG.getNode(ISD::ADDCARRY, DL, N1->getVTList(),
  2423. N0, N1.getOperand(0), N1.getOperand(2));
  2424. // (add X, Carry) -> (addcarry X, 0, Carry)
  2425. if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
  2426. if (SDValue Carry = getAsCarry(TLI, N1))
  2427. return DAG.getNode(ISD::ADDCARRY, DL,
  2428. DAG.getVTList(VT, Carry.getValueType()), N0,
  2429. DAG.getConstant(0, DL, VT), Carry);
  2430. return SDValue();
  2431. }
  2432. SDValue DAGCombiner::visitADDC(SDNode *N) {
  2433. SDValue N0 = N->getOperand(0);
  2434. SDValue N1 = N->getOperand(1);
  2435. EVT VT = N0.getValueType();
  2436. SDLoc DL(N);
  2437. // If the flag result is dead, turn this into an ADD.
  2438. if (!N->hasAnyUseOfValue(1))
  2439. return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
  2440. DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
  2441. // canonicalize constant to RHS.
  2442. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  2443. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  2444. if (N0C && !N1C)
  2445. return DAG.getNode(ISD::ADDC, DL, N->getVTList(), N1, N0);
  2446. // fold (addc x, 0) -> x + no carry out
  2447. if (isNullConstant(N1))
  2448. return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
  2449. DL, MVT::Glue));
  2450. // If it cannot overflow, transform into an add.
  2451. if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
  2452. return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
  2453. DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
  2454. return SDValue();
  2455. }
  2456. /**
  2457. * Flips a boolean if it is cheaper to compute. If the Force parameters is set,
  2458. * then the flip also occurs if computing the inverse is the same cost.
  2459. * This function returns an empty SDValue in case it cannot flip the boolean
  2460. * without increasing the cost of the computation. If you want to flip a boolean
  2461. * no matter what, use DAG.getLogicalNOT.
  2462. */
  2463. static SDValue extractBooleanFlip(SDValue V, SelectionDAG &DAG,
  2464. const TargetLowering &TLI,
  2465. bool Force) {
  2466. if (Force && isa<ConstantSDNode>(V))
  2467. return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
  2468. if (V.getOpcode() != ISD::XOR)
  2469. return SDValue();
  2470. ConstantSDNode *Const = isConstOrConstSplat(V.getOperand(1), false);
  2471. if (!Const)
  2472. return SDValue();
  2473. EVT VT = V.getValueType();
  2474. bool IsFlip = false;
  2475. switch(TLI.getBooleanContents(VT)) {
  2476. case TargetLowering::ZeroOrOneBooleanContent:
  2477. IsFlip = Const->isOne();
  2478. break;
  2479. case TargetLowering::ZeroOrNegativeOneBooleanContent:
  2480. IsFlip = Const->isAllOnes();
  2481. break;
  2482. case TargetLowering::UndefinedBooleanContent:
  2483. IsFlip = (Const->getAPIntValue() & 0x01) == 1;
  2484. break;
  2485. }
  2486. if (IsFlip)
  2487. return V.getOperand(0);
  2488. if (Force)
  2489. return DAG.getLogicalNOT(SDLoc(V), V, V.getValueType());
  2490. return SDValue();
  2491. }
  2492. SDValue DAGCombiner::visitADDO(SDNode *N) {
  2493. SDValue N0 = N->getOperand(0);
  2494. SDValue N1 = N->getOperand(1);
  2495. EVT VT = N0.getValueType();
  2496. bool IsSigned = (ISD::SADDO == N->getOpcode());
  2497. EVT CarryVT = N->getValueType(1);
  2498. SDLoc DL(N);
  2499. // If the flag result is dead, turn this into an ADD.
  2500. if (!N->hasAnyUseOfValue(1))
  2501. return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
  2502. DAG.getUNDEF(CarryVT));
  2503. // canonicalize constant to RHS.
  2504. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  2505. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  2506. return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
  2507. // fold (addo x, 0) -> x + no carry out
  2508. if (isNullOrNullSplat(N1))
  2509. return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
  2510. if (!IsSigned) {
  2511. // If it cannot overflow, transform into an add.
  2512. if (DAG.computeOverflowKind(N0, N1) == SelectionDAG::OFK_Never)
  2513. return CombineTo(N, DAG.getNode(ISD::ADD, DL, VT, N0, N1),
  2514. DAG.getConstant(0, DL, CarryVT));
  2515. // fold (uaddo (xor a, -1), 1) -> (usub 0, a) and flip carry.
  2516. if (isBitwiseNot(N0) && isOneOrOneSplat(N1)) {
  2517. SDValue Sub = DAG.getNode(ISD::USUBO, DL, N->getVTList(),
  2518. DAG.getConstant(0, DL, VT), N0.getOperand(0));
  2519. return CombineTo(
  2520. N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
  2521. }
  2522. if (SDValue Combined = visitUADDOLike(N0, N1, N))
  2523. return Combined;
  2524. if (SDValue Combined = visitUADDOLike(N1, N0, N))
  2525. return Combined;
  2526. }
  2527. return SDValue();
  2528. }
  2529. SDValue DAGCombiner::visitUADDOLike(SDValue N0, SDValue N1, SDNode *N) {
  2530. EVT VT = N0.getValueType();
  2531. if (VT.isVector())
  2532. return SDValue();
  2533. // (uaddo X, (addcarry Y, 0, Carry)) -> (addcarry X, Y, Carry)
  2534. // If Y + 1 cannot overflow.
  2535. if (N1.getOpcode() == ISD::ADDCARRY && isNullConstant(N1.getOperand(1))) {
  2536. SDValue Y = N1.getOperand(0);
  2537. SDValue One = DAG.getConstant(1, SDLoc(N), Y.getValueType());
  2538. if (DAG.computeOverflowKind(Y, One) == SelectionDAG::OFK_Never)
  2539. return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0, Y,
  2540. N1.getOperand(2));
  2541. }
  2542. // (uaddo X, Carry) -> (addcarry X, 0, Carry)
  2543. if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT))
  2544. if (SDValue Carry = getAsCarry(TLI, N1))
  2545. return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(), N0,
  2546. DAG.getConstant(0, SDLoc(N), VT), Carry);
  2547. return SDValue();
  2548. }
  2549. SDValue DAGCombiner::visitADDE(SDNode *N) {
  2550. SDValue N0 = N->getOperand(0);
  2551. SDValue N1 = N->getOperand(1);
  2552. SDValue CarryIn = N->getOperand(2);
  2553. // canonicalize constant to RHS
  2554. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  2555. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  2556. if (N0C && !N1C)
  2557. return DAG.getNode(ISD::ADDE, SDLoc(N), N->getVTList(),
  2558. N1, N0, CarryIn);
  2559. // fold (adde x, y, false) -> (addc x, y)
  2560. if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
  2561. return DAG.getNode(ISD::ADDC, SDLoc(N), N->getVTList(), N0, N1);
  2562. return SDValue();
  2563. }
  2564. SDValue DAGCombiner::visitADDCARRY(SDNode *N) {
  2565. SDValue N0 = N->getOperand(0);
  2566. SDValue N1 = N->getOperand(1);
  2567. SDValue CarryIn = N->getOperand(2);
  2568. SDLoc DL(N);
  2569. // canonicalize constant to RHS
  2570. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  2571. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  2572. if (N0C && !N1C)
  2573. return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), N1, N0, CarryIn);
  2574. // fold (addcarry x, y, false) -> (uaddo x, y)
  2575. if (isNullConstant(CarryIn)) {
  2576. if (!LegalOperations ||
  2577. TLI.isOperationLegalOrCustom(ISD::UADDO, N->getValueType(0)))
  2578. return DAG.getNode(ISD::UADDO, DL, N->getVTList(), N0, N1);
  2579. }
  2580. // fold (addcarry 0, 0, X) -> (and (ext/trunc X), 1) and no carry.
  2581. if (isNullConstant(N0) && isNullConstant(N1)) {
  2582. EVT VT = N0.getValueType();
  2583. EVT CarryVT = CarryIn.getValueType();
  2584. SDValue CarryExt = DAG.getBoolExtOrTrunc(CarryIn, DL, VT, CarryVT);
  2585. AddToWorklist(CarryExt.getNode());
  2586. return CombineTo(N, DAG.getNode(ISD::AND, DL, VT, CarryExt,
  2587. DAG.getConstant(1, DL, VT)),
  2588. DAG.getConstant(0, DL, CarryVT));
  2589. }
  2590. if (SDValue Combined = visitADDCARRYLike(N0, N1, CarryIn, N))
  2591. return Combined;
  2592. if (SDValue Combined = visitADDCARRYLike(N1, N0, CarryIn, N))
  2593. return Combined;
  2594. return SDValue();
  2595. }
  2596. SDValue DAGCombiner::visitSADDO_CARRY(SDNode *N) {
  2597. SDValue N0 = N->getOperand(0);
  2598. SDValue N1 = N->getOperand(1);
  2599. SDValue CarryIn = N->getOperand(2);
  2600. SDLoc DL(N);
  2601. // canonicalize constant to RHS
  2602. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  2603. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  2604. if (N0C && !N1C)
  2605. return DAG.getNode(ISD::SADDO_CARRY, DL, N->getVTList(), N1, N0, CarryIn);
  2606. // fold (saddo_carry x, y, false) -> (saddo x, y)
  2607. if (isNullConstant(CarryIn)) {
  2608. if (!LegalOperations ||
  2609. TLI.isOperationLegalOrCustom(ISD::SADDO, N->getValueType(0)))
  2610. return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0, N1);
  2611. }
  2612. return SDValue();
  2613. }
  2614. /**
  2615. * If we are facing some sort of diamond carry propapagtion pattern try to
  2616. * break it up to generate something like:
  2617. * (addcarry X, 0, (addcarry A, B, Z):Carry)
  2618. *
  2619. * The end result is usually an increase in operation required, but because the
  2620. * carry is now linearized, other tranforms can kick in and optimize the DAG.
  2621. *
  2622. * Patterns typically look something like
  2623. * (uaddo A, B)
  2624. * / \
  2625. * Carry Sum
  2626. * | \
  2627. * | (addcarry *, 0, Z)
  2628. * | /
  2629. * \ Carry
  2630. * | /
  2631. * (addcarry X, *, *)
  2632. *
  2633. * But numerous variation exist. Our goal is to identify A, B, X and Z and
  2634. * produce a combine with a single path for carry propagation.
  2635. */
  2636. static SDValue combineADDCARRYDiamond(DAGCombiner &Combiner, SelectionDAG &DAG,
  2637. SDValue X, SDValue Carry0, SDValue Carry1,
  2638. SDNode *N) {
  2639. if (Carry1.getResNo() != 1 || Carry0.getResNo() != 1)
  2640. return SDValue();
  2641. if (Carry1.getOpcode() != ISD::UADDO)
  2642. return SDValue();
  2643. SDValue Z;
  2644. /**
  2645. * First look for a suitable Z. It will present itself in the form of
  2646. * (addcarry Y, 0, Z) or its equivalent (uaddo Y, 1) for Z=true
  2647. */
  2648. if (Carry0.getOpcode() == ISD::ADDCARRY &&
  2649. isNullConstant(Carry0.getOperand(1))) {
  2650. Z = Carry0.getOperand(2);
  2651. } else if (Carry0.getOpcode() == ISD::UADDO &&
  2652. isOneConstant(Carry0.getOperand(1))) {
  2653. EVT VT = Combiner.getSetCCResultType(Carry0.getValueType());
  2654. Z = DAG.getConstant(1, SDLoc(Carry0.getOperand(1)), VT);
  2655. } else {
  2656. // We couldn't find a suitable Z.
  2657. return SDValue();
  2658. }
  2659. auto cancelDiamond = [&](SDValue A,SDValue B) {
  2660. SDLoc DL(N);
  2661. SDValue NewY = DAG.getNode(ISD::ADDCARRY, DL, Carry0->getVTList(), A, B, Z);
  2662. Combiner.AddToWorklist(NewY.getNode());
  2663. return DAG.getNode(ISD::ADDCARRY, DL, N->getVTList(), X,
  2664. DAG.getConstant(0, DL, X.getValueType()),
  2665. NewY.getValue(1));
  2666. };
  2667. /**
  2668. * (uaddo A, B)
  2669. * |
  2670. * Sum
  2671. * |
  2672. * (addcarry *, 0, Z)
  2673. */
  2674. if (Carry0.getOperand(0) == Carry1.getValue(0)) {
  2675. return cancelDiamond(Carry1.getOperand(0), Carry1.getOperand(1));
  2676. }
  2677. /**
  2678. * (addcarry A, 0, Z)
  2679. * |
  2680. * Sum
  2681. * |
  2682. * (uaddo *, B)
  2683. */
  2684. if (Carry1.getOperand(0) == Carry0.getValue(0)) {
  2685. return cancelDiamond(Carry0.getOperand(0), Carry1.getOperand(1));
  2686. }
  2687. if (Carry1.getOperand(1) == Carry0.getValue(0)) {
  2688. return cancelDiamond(Carry1.getOperand(0), Carry0.getOperand(0));
  2689. }
  2690. return SDValue();
  2691. }
  2692. // If we are facing some sort of diamond carry/borrow in/out pattern try to
  2693. // match patterns like:
  2694. //
  2695. // (uaddo A, B) CarryIn
  2696. // | \ |
  2697. // | \ |
  2698. // PartialSum PartialCarryOutX /
  2699. // | | /
  2700. // | ____|____________/
  2701. // | / |
  2702. // (uaddo *, *) \________
  2703. // | \ \
  2704. // | \ |
  2705. // | PartialCarryOutY |
  2706. // | \ |
  2707. // | \ /
  2708. // AddCarrySum | ______/
  2709. // | /
  2710. // CarryOut = (or *, *)
  2711. //
  2712. // And generate ADDCARRY (or SUBCARRY) with two result values:
  2713. //
  2714. // {AddCarrySum, CarryOut} = (addcarry A, B, CarryIn)
  2715. //
  2716. // Our goal is to identify A, B, and CarryIn and produce ADDCARRY/SUBCARRY with
  2717. // a single path for carry/borrow out propagation:
  2718. static SDValue combineCarryDiamond(SelectionDAG &DAG, const TargetLowering &TLI,
  2719. SDValue Carry0, SDValue Carry1, SDNode *N) {
  2720. if (Carry0.getResNo() != 1 || Carry1.getResNo() != 1)
  2721. return SDValue();
  2722. unsigned Opcode = Carry0.getOpcode();
  2723. if (Opcode != Carry1.getOpcode())
  2724. return SDValue();
  2725. if (Opcode != ISD::UADDO && Opcode != ISD::USUBO)
  2726. return SDValue();
  2727. // Canonicalize the add/sub of A and B as Carry0 and the add/sub of the
  2728. // carry/borrow in as Carry1. (The top and middle uaddo nodes respectively in
  2729. // the above ASCII art.)
  2730. if (Carry1.getOperand(0) != Carry0.getValue(0) &&
  2731. Carry1.getOperand(1) != Carry0.getValue(0))
  2732. std::swap(Carry0, Carry1);
  2733. if (Carry1.getOperand(0) != Carry0.getValue(0) &&
  2734. Carry1.getOperand(1) != Carry0.getValue(0))
  2735. return SDValue();
  2736. // The carry in value must be on the righthand side for subtraction.
  2737. unsigned CarryInOperandNum =
  2738. Carry1.getOperand(0) == Carry0.getValue(0) ? 1 : 0;
  2739. if (Opcode == ISD::USUBO && CarryInOperandNum != 1)
  2740. return SDValue();
  2741. SDValue CarryIn = Carry1.getOperand(CarryInOperandNum);
  2742. unsigned NewOp = Opcode == ISD::UADDO ? ISD::ADDCARRY : ISD::SUBCARRY;
  2743. if (!TLI.isOperationLegalOrCustom(NewOp, Carry0.getValue(0).getValueType()))
  2744. return SDValue();
  2745. // Verify that the carry/borrow in is plausibly a carry/borrow bit.
  2746. // TODO: make getAsCarry() aware of how partial carries are merged.
  2747. if (CarryIn.getOpcode() != ISD::ZERO_EXTEND)
  2748. return SDValue();
  2749. CarryIn = CarryIn.getOperand(0);
  2750. if (CarryIn.getValueType() != MVT::i1)
  2751. return SDValue();
  2752. SDLoc DL(N);
  2753. SDValue Merged =
  2754. DAG.getNode(NewOp, DL, Carry1->getVTList(), Carry0.getOperand(0),
  2755. Carry0.getOperand(1), CarryIn);
  2756. // Please note that because we have proven that the result of the UADDO/USUBO
  2757. // of A and B feeds into the UADDO/USUBO that does the carry/borrow in, we can
  2758. // therefore prove that if the first UADDO/USUBO overflows, the second
  2759. // UADDO/USUBO cannot. For example consider 8-bit numbers where 0xFF is the
  2760. // maximum value.
  2761. //
  2762. // 0xFF + 0xFF == 0xFE with carry but 0xFE + 1 does not carry
  2763. // 0x00 - 0xFF == 1 with a carry/borrow but 1 - 1 == 0 (no carry/borrow)
  2764. //
  2765. // This is important because it means that OR and XOR can be used to merge
  2766. // carry flags; and that AND can return a constant zero.
  2767. //
  2768. // TODO: match other operations that can merge flags (ADD, etc)
  2769. DAG.ReplaceAllUsesOfValueWith(Carry1.getValue(0), Merged.getValue(0));
  2770. if (N->getOpcode() == ISD::AND)
  2771. return DAG.getConstant(0, DL, MVT::i1);
  2772. return Merged.getValue(1);
  2773. }
  2774. SDValue DAGCombiner::visitADDCARRYLike(SDValue N0, SDValue N1, SDValue CarryIn,
  2775. SDNode *N) {
  2776. // fold (addcarry (xor a, -1), b, c) -> (subcarry b, a, !c) and flip carry.
  2777. if (isBitwiseNot(N0))
  2778. if (SDValue NotC = extractBooleanFlip(CarryIn, DAG, TLI, true)) {
  2779. SDLoc DL(N);
  2780. SDValue Sub = DAG.getNode(ISD::SUBCARRY, DL, N->getVTList(), N1,
  2781. N0.getOperand(0), NotC);
  2782. return CombineTo(
  2783. N, Sub, DAG.getLogicalNOT(DL, Sub.getValue(1), Sub->getValueType(1)));
  2784. }
  2785. // Iff the flag result is dead:
  2786. // (addcarry (add|uaddo X, Y), 0, Carry) -> (addcarry X, Y, Carry)
  2787. // Don't do this if the Carry comes from the uaddo. It won't remove the uaddo
  2788. // or the dependency between the instructions.
  2789. if ((N0.getOpcode() == ISD::ADD ||
  2790. (N0.getOpcode() == ISD::UADDO && N0.getResNo() == 0 &&
  2791. N0.getValue(1) != CarryIn)) &&
  2792. isNullConstant(N1) && !N->hasAnyUseOfValue(1))
  2793. return DAG.getNode(ISD::ADDCARRY, SDLoc(N), N->getVTList(),
  2794. N0.getOperand(0), N0.getOperand(1), CarryIn);
  2795. /**
  2796. * When one of the addcarry argument is itself a carry, we may be facing
  2797. * a diamond carry propagation. In which case we try to transform the DAG
  2798. * to ensure linear carry propagation if that is possible.
  2799. */
  2800. if (auto Y = getAsCarry(TLI, N1)) {
  2801. // Because both are carries, Y and Z can be swapped.
  2802. if (auto R = combineADDCARRYDiamond(*this, DAG, N0, Y, CarryIn, N))
  2803. return R;
  2804. if (auto R = combineADDCARRYDiamond(*this, DAG, N0, CarryIn, Y, N))
  2805. return R;
  2806. }
  2807. return SDValue();
  2808. }
  2809. // Attempt to create a USUBSAT(LHS, RHS) node with DstVT, performing a
  2810. // clamp/truncation if necessary.
  2811. static SDValue getTruncatedUSUBSAT(EVT DstVT, EVT SrcVT, SDValue LHS,
  2812. SDValue RHS, SelectionDAG &DAG,
  2813. const SDLoc &DL) {
  2814. assert(DstVT.getScalarSizeInBits() <= SrcVT.getScalarSizeInBits() &&
  2815. "Illegal truncation");
  2816. if (DstVT == SrcVT)
  2817. return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
  2818. // If the LHS is zero-extended then we can perform the USUBSAT as DstVT by
  2819. // clamping RHS.
  2820. APInt UpperBits = APInt::getBitsSetFrom(SrcVT.getScalarSizeInBits(),
  2821. DstVT.getScalarSizeInBits());
  2822. if (!DAG.MaskedValueIsZero(LHS, UpperBits))
  2823. return SDValue();
  2824. SDValue SatLimit =
  2825. DAG.getConstant(APInt::getLowBitsSet(SrcVT.getScalarSizeInBits(),
  2826. DstVT.getScalarSizeInBits()),
  2827. DL, SrcVT);
  2828. RHS = DAG.getNode(ISD::UMIN, DL, SrcVT, RHS, SatLimit);
  2829. RHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, RHS);
  2830. LHS = DAG.getNode(ISD::TRUNCATE, DL, DstVT, LHS);
  2831. return DAG.getNode(ISD::USUBSAT, DL, DstVT, LHS, RHS);
  2832. }
  2833. // Try to find umax(a,b) - b or a - umin(a,b) patterns that may be converted to
  2834. // usubsat(a,b), optionally as a truncated type.
  2835. SDValue DAGCombiner::foldSubToUSubSat(EVT DstVT, SDNode *N) {
  2836. if (N->getOpcode() != ISD::SUB ||
  2837. !(!LegalOperations || hasOperation(ISD::USUBSAT, DstVT)))
  2838. return SDValue();
  2839. EVT SubVT = N->getValueType(0);
  2840. SDValue Op0 = N->getOperand(0);
  2841. SDValue Op1 = N->getOperand(1);
  2842. // Try to find umax(a,b) - b or a - umin(a,b) patterns
  2843. // they may be converted to usubsat(a,b).
  2844. if (Op0.getOpcode() == ISD::UMAX && Op0.hasOneUse()) {
  2845. SDValue MaxLHS = Op0.getOperand(0);
  2846. SDValue MaxRHS = Op0.getOperand(1);
  2847. if (MaxLHS == Op1)
  2848. return getTruncatedUSUBSAT(DstVT, SubVT, MaxRHS, Op1, DAG, SDLoc(N));
  2849. if (MaxRHS == Op1)
  2850. return getTruncatedUSUBSAT(DstVT, SubVT, MaxLHS, Op1, DAG, SDLoc(N));
  2851. }
  2852. if (Op1.getOpcode() == ISD::UMIN && Op1.hasOneUse()) {
  2853. SDValue MinLHS = Op1.getOperand(0);
  2854. SDValue MinRHS = Op1.getOperand(1);
  2855. if (MinLHS == Op0)
  2856. return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinRHS, DAG, SDLoc(N));
  2857. if (MinRHS == Op0)
  2858. return getTruncatedUSUBSAT(DstVT, SubVT, Op0, MinLHS, DAG, SDLoc(N));
  2859. }
  2860. // sub(a,trunc(umin(zext(a),b))) -> usubsat(a,trunc(umin(b,SatLimit)))
  2861. if (Op1.getOpcode() == ISD::TRUNCATE &&
  2862. Op1.getOperand(0).getOpcode() == ISD::UMIN &&
  2863. Op1.getOperand(0).hasOneUse()) {
  2864. SDValue MinLHS = Op1.getOperand(0).getOperand(0);
  2865. SDValue MinRHS = Op1.getOperand(0).getOperand(1);
  2866. if (MinLHS.getOpcode() == ISD::ZERO_EXTEND && MinLHS.getOperand(0) == Op0)
  2867. return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinLHS, MinRHS,
  2868. DAG, SDLoc(N));
  2869. if (MinRHS.getOpcode() == ISD::ZERO_EXTEND && MinRHS.getOperand(0) == Op0)
  2870. return getTruncatedUSUBSAT(DstVT, MinLHS.getValueType(), MinRHS, MinLHS,
  2871. DAG, SDLoc(N));
  2872. }
  2873. return SDValue();
  2874. }
  2875. // Since it may not be valid to emit a fold to zero for vector initializers
  2876. // check if we can before folding.
  2877. static SDValue tryFoldToZero(const SDLoc &DL, const TargetLowering &TLI, EVT VT,
  2878. SelectionDAG &DAG, bool LegalOperations) {
  2879. if (!VT.isVector())
  2880. return DAG.getConstant(0, DL, VT);
  2881. if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
  2882. return DAG.getConstant(0, DL, VT);
  2883. return SDValue();
  2884. }
  2885. SDValue DAGCombiner::visitSUB(SDNode *N) {
  2886. SDValue N0 = N->getOperand(0);
  2887. SDValue N1 = N->getOperand(1);
  2888. EVT VT = N0.getValueType();
  2889. SDLoc DL(N);
  2890. // fold (sub x, x) -> 0
  2891. // FIXME: Refactor this and xor and other similar operations together.
  2892. if (N0 == N1)
  2893. return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
  2894. // fold (sub c1, c2) -> c3
  2895. if (SDValue C = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N1}))
  2896. return C;
  2897. // fold vector ops
  2898. if (VT.isVector()) {
  2899. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  2900. return FoldedVOp;
  2901. // fold (sub x, 0) -> x, vector edition
  2902. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  2903. return N0;
  2904. }
  2905. if (SDValue NewSel = foldBinOpIntoSelect(N))
  2906. return NewSel;
  2907. ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
  2908. // fold (sub x, c) -> (add x, -c)
  2909. if (N1C) {
  2910. return DAG.getNode(ISD::ADD, DL, VT, N0,
  2911. DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
  2912. }
  2913. if (isNullOrNullSplat(N0)) {
  2914. unsigned BitWidth = VT.getScalarSizeInBits();
  2915. // Right-shifting everything out but the sign bit followed by negation is
  2916. // the same as flipping arithmetic/logical shift type without the negation:
  2917. // -(X >>u 31) -> (X >>s 31)
  2918. // -(X >>s 31) -> (X >>u 31)
  2919. if (N1->getOpcode() == ISD::SRA || N1->getOpcode() == ISD::SRL) {
  2920. ConstantSDNode *ShiftAmt = isConstOrConstSplat(N1.getOperand(1));
  2921. if (ShiftAmt && ShiftAmt->getAPIntValue() == (BitWidth - 1)) {
  2922. auto NewSh = N1->getOpcode() == ISD::SRA ? ISD::SRL : ISD::SRA;
  2923. if (!LegalOperations || TLI.isOperationLegal(NewSh, VT))
  2924. return DAG.getNode(NewSh, DL, VT, N1.getOperand(0), N1.getOperand(1));
  2925. }
  2926. }
  2927. // 0 - X --> 0 if the sub is NUW.
  2928. if (N->getFlags().hasNoUnsignedWrap())
  2929. return N0;
  2930. if (DAG.MaskedValueIsZero(N1, ~APInt::getSignMask(BitWidth))) {
  2931. // N1 is either 0 or the minimum signed value. If the sub is NSW, then
  2932. // N1 must be 0 because negating the minimum signed value is undefined.
  2933. if (N->getFlags().hasNoSignedWrap())
  2934. return N0;
  2935. // 0 - X --> X if X is 0 or the minimum signed value.
  2936. return N1;
  2937. }
  2938. // Convert 0 - abs(x).
  2939. if (N1->getOpcode() == ISD::ABS &&
  2940. !TLI.isOperationLegalOrCustom(ISD::ABS, VT))
  2941. if (SDValue Result = TLI.expandABS(N1.getNode(), DAG, true))
  2942. return Result;
  2943. // Fold neg(splat(neg(x)) -> splat(x)
  2944. if (VT.isVector()) {
  2945. SDValue N1S = DAG.getSplatValue(N1, true);
  2946. if (N1S && N1S.getOpcode() == ISD::SUB &&
  2947. isNullConstant(N1S.getOperand(0))) {
  2948. if (VT.isScalableVector())
  2949. return DAG.getSplatVector(VT, DL, N1S.getOperand(1));
  2950. return DAG.getSplatBuildVector(VT, DL, N1S.getOperand(1));
  2951. }
  2952. }
  2953. }
  2954. // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
  2955. if (isAllOnesOrAllOnesSplat(N0))
  2956. return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
  2957. // fold (A - (0-B)) -> A+B
  2958. if (N1.getOpcode() == ISD::SUB && isNullOrNullSplat(N1.getOperand(0)))
  2959. return DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(1));
  2960. // fold A-(A-B) -> B
  2961. if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
  2962. return N1.getOperand(1);
  2963. // fold (A+B)-A -> B
  2964. if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
  2965. return N0.getOperand(1);
  2966. // fold (A+B)-B -> A
  2967. if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
  2968. return N0.getOperand(0);
  2969. // fold (A+C1)-C2 -> A+(C1-C2)
  2970. if (N0.getOpcode() == ISD::ADD &&
  2971. isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
  2972. isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
  2973. SDValue NewC =
  2974. DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(1), N1});
  2975. assert(NewC && "Constant folding failed");
  2976. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0), NewC);
  2977. }
  2978. // fold C2-(A+C1) -> (C2-C1)-A
  2979. if (N1.getOpcode() == ISD::ADD) {
  2980. SDValue N11 = N1.getOperand(1);
  2981. if (isConstantOrConstantVector(N0, /* NoOpaques */ true) &&
  2982. isConstantOrConstantVector(N11, /* NoOpaques */ true)) {
  2983. SDValue NewC = DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0, N11});
  2984. assert(NewC && "Constant folding failed");
  2985. return DAG.getNode(ISD::SUB, DL, VT, NewC, N1.getOperand(0));
  2986. }
  2987. }
  2988. // fold (A-C1)-C2 -> A-(C1+C2)
  2989. if (N0.getOpcode() == ISD::SUB &&
  2990. isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
  2991. isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
  2992. SDValue NewC =
  2993. DAG.FoldConstantArithmetic(ISD::ADD, DL, VT, {N0.getOperand(1), N1});
  2994. assert(NewC && "Constant folding failed");
  2995. return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), NewC);
  2996. }
  2997. // fold (c1-A)-c2 -> (c1-c2)-A
  2998. if (N0.getOpcode() == ISD::SUB &&
  2999. isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
  3000. isConstantOrConstantVector(N0.getOperand(0), /* NoOpaques */ true)) {
  3001. SDValue NewC =
  3002. DAG.FoldConstantArithmetic(ISD::SUB, DL, VT, {N0.getOperand(0), N1});
  3003. assert(NewC && "Constant folding failed");
  3004. return DAG.getNode(ISD::SUB, DL, VT, NewC, N0.getOperand(1));
  3005. }
  3006. // fold ((A+(B+or-C))-B) -> A+or-C
  3007. if (N0.getOpcode() == ISD::ADD &&
  3008. (N0.getOperand(1).getOpcode() == ISD::SUB ||
  3009. N0.getOperand(1).getOpcode() == ISD::ADD) &&
  3010. N0.getOperand(1).getOperand(0) == N1)
  3011. return DAG.getNode(N0.getOperand(1).getOpcode(), DL, VT, N0.getOperand(0),
  3012. N0.getOperand(1).getOperand(1));
  3013. // fold ((A+(C+B))-B) -> A+C
  3014. if (N0.getOpcode() == ISD::ADD && N0.getOperand(1).getOpcode() == ISD::ADD &&
  3015. N0.getOperand(1).getOperand(1) == N1)
  3016. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(0),
  3017. N0.getOperand(1).getOperand(0));
  3018. // fold ((A-(B-C))-C) -> A-B
  3019. if (N0.getOpcode() == ISD::SUB && N0.getOperand(1).getOpcode() == ISD::SUB &&
  3020. N0.getOperand(1).getOperand(1) == N1)
  3021. return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0),
  3022. N0.getOperand(1).getOperand(0));
  3023. // fold (A-(B-C)) -> A+(C-B)
  3024. if (N1.getOpcode() == ISD::SUB && N1.hasOneUse())
  3025. return DAG.getNode(ISD::ADD, DL, VT, N0,
  3026. DAG.getNode(ISD::SUB, DL, VT, N1.getOperand(1),
  3027. N1.getOperand(0)));
  3028. // A - (A & B) -> A & (~B)
  3029. if (N1.getOpcode() == ISD::AND) {
  3030. SDValue A = N1.getOperand(0);
  3031. SDValue B = N1.getOperand(1);
  3032. if (A != N0)
  3033. std::swap(A, B);
  3034. if (A == N0 &&
  3035. (N1.hasOneUse() || isConstantOrConstantVector(B, /*NoOpaques=*/true))) {
  3036. SDValue InvB =
  3037. DAG.getNode(ISD::XOR, DL, VT, B, DAG.getAllOnesConstant(DL, VT));
  3038. return DAG.getNode(ISD::AND, DL, VT, A, InvB);
  3039. }
  3040. }
  3041. // fold (X - (-Y * Z)) -> (X + (Y * Z))
  3042. if (N1.getOpcode() == ISD::MUL && N1.hasOneUse()) {
  3043. if (N1.getOperand(0).getOpcode() == ISD::SUB &&
  3044. isNullOrNullSplat(N1.getOperand(0).getOperand(0))) {
  3045. SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
  3046. N1.getOperand(0).getOperand(1),
  3047. N1.getOperand(1));
  3048. return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
  3049. }
  3050. if (N1.getOperand(1).getOpcode() == ISD::SUB &&
  3051. isNullOrNullSplat(N1.getOperand(1).getOperand(0))) {
  3052. SDValue Mul = DAG.getNode(ISD::MUL, DL, VT,
  3053. N1.getOperand(0),
  3054. N1.getOperand(1).getOperand(1));
  3055. return DAG.getNode(ISD::ADD, DL, VT, N0, Mul);
  3056. }
  3057. }
  3058. // If either operand of a sub is undef, the result is undef
  3059. if (N0.isUndef())
  3060. return N0;
  3061. if (N1.isUndef())
  3062. return N1;
  3063. if (SDValue V = foldAddSubBoolOfMaskedVal(N, DAG))
  3064. return V;
  3065. if (SDValue V = foldAddSubOfSignBit(N, DAG))
  3066. return V;
  3067. if (SDValue V = foldAddSubMasked1(false, N0, N1, DAG, SDLoc(N)))
  3068. return V;
  3069. if (SDValue V = foldSubToUSubSat(VT, N))
  3070. return V;
  3071. // (x - y) - 1 -> add (xor y, -1), x
  3072. if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB && isOneOrOneSplat(N1)) {
  3073. SDValue Xor = DAG.getNode(ISD::XOR, DL, VT, N0.getOperand(1),
  3074. DAG.getAllOnesConstant(DL, VT));
  3075. return DAG.getNode(ISD::ADD, DL, VT, Xor, N0.getOperand(0));
  3076. }
  3077. // Look for:
  3078. // sub y, (xor x, -1)
  3079. // And if the target does not like this form then turn into:
  3080. // add (add x, y), 1
  3081. if (TLI.preferIncOfAddToSubOfNot(VT) && N1.hasOneUse() && isBitwiseNot(N1)) {
  3082. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, N1.getOperand(0));
  3083. return DAG.getNode(ISD::ADD, DL, VT, Add, DAG.getConstant(1, DL, VT));
  3084. }
  3085. // Hoist one-use addition by non-opaque constant:
  3086. // (x + C) - y -> (x - y) + C
  3087. if (N0.hasOneUse() && N0.getOpcode() == ISD::ADD &&
  3088. isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
  3089. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
  3090. return DAG.getNode(ISD::ADD, DL, VT, Sub, N0.getOperand(1));
  3091. }
  3092. // y - (x + C) -> (y - x) - C
  3093. if (N1.hasOneUse() && N1.getOpcode() == ISD::ADD &&
  3094. isConstantOrConstantVector(N1.getOperand(1), /*NoOpaques=*/true)) {
  3095. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, N1.getOperand(0));
  3096. return DAG.getNode(ISD::SUB, DL, VT, Sub, N1.getOperand(1));
  3097. }
  3098. // (x - C) - y -> (x - y) - C
  3099. // This is necessary because SUB(X,C) -> ADD(X,-C) doesn't work for vectors.
  3100. if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
  3101. isConstantOrConstantVector(N0.getOperand(1), /*NoOpaques=*/true)) {
  3102. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), N1);
  3103. return DAG.getNode(ISD::SUB, DL, VT, Sub, N0.getOperand(1));
  3104. }
  3105. // (C - x) - y -> C - (x + y)
  3106. if (N0.hasOneUse() && N0.getOpcode() == ISD::SUB &&
  3107. isConstantOrConstantVector(N0.getOperand(0), /*NoOpaques=*/true)) {
  3108. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1), N1);
  3109. return DAG.getNode(ISD::SUB, DL, VT, N0.getOperand(0), Add);
  3110. }
  3111. // If the target's bool is represented as 0/-1, prefer to make this 'add 0/-1'
  3112. // rather than 'sub 0/1' (the sext should get folded).
  3113. // sub X, (zext i1 Y) --> add X, (sext i1 Y)
  3114. if (N1.getOpcode() == ISD::ZERO_EXTEND &&
  3115. N1.getOperand(0).getScalarValueSizeInBits() == 1 &&
  3116. TLI.getBooleanContents(VT) ==
  3117. TargetLowering::ZeroOrNegativeOneBooleanContent) {
  3118. SDValue SExt = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N1.getOperand(0));
  3119. return DAG.getNode(ISD::ADD, DL, VT, N0, SExt);
  3120. }
  3121. // fold Y = sra (X, size(X)-1); sub (xor (X, Y), Y) -> (abs X)
  3122. if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
  3123. if (N0.getOpcode() == ISD::XOR && N1.getOpcode() == ISD::SRA) {
  3124. SDValue X0 = N0.getOperand(0), X1 = N0.getOperand(1);
  3125. SDValue S0 = N1.getOperand(0);
  3126. if ((X0 == S0 && X1 == N1) || (X0 == N1 && X1 == S0))
  3127. if (ConstantSDNode *C = isConstOrConstSplat(N1.getOperand(1)))
  3128. if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1))
  3129. return DAG.getNode(ISD::ABS, SDLoc(N), VT, S0);
  3130. }
  3131. }
  3132. // If the relocation model supports it, consider symbol offsets.
  3133. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
  3134. if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
  3135. // fold (sub Sym, c) -> Sym-c
  3136. if (N1C && GA->getOpcode() == ISD::GlobalAddress)
  3137. return DAG.getGlobalAddress(GA->getGlobal(), SDLoc(N1C), VT,
  3138. GA->getOffset() -
  3139. (uint64_t)N1C->getSExtValue());
  3140. // fold (sub Sym+c1, Sym+c2) -> c1-c2
  3141. if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
  3142. if (GA->getGlobal() == GB->getGlobal())
  3143. return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
  3144. DL, VT);
  3145. }
  3146. // sub X, (sextinreg Y i1) -> add X, (and Y 1)
  3147. if (N1.getOpcode() == ISD::SIGN_EXTEND_INREG) {
  3148. VTSDNode *TN = cast<VTSDNode>(N1.getOperand(1));
  3149. if (TN->getVT() == MVT::i1) {
  3150. SDValue ZExt = DAG.getNode(ISD::AND, DL, VT, N1.getOperand(0),
  3151. DAG.getConstant(1, DL, VT));
  3152. return DAG.getNode(ISD::ADD, DL, VT, N0, ZExt);
  3153. }
  3154. }
  3155. // canonicalize (sub X, (vscale * C)) to (add X, (vscale * -C))
  3156. if (N1.getOpcode() == ISD::VSCALE) {
  3157. const APInt &IntVal = N1.getConstantOperandAPInt(0);
  3158. return DAG.getNode(ISD::ADD, DL, VT, N0, DAG.getVScale(DL, VT, -IntVal));
  3159. }
  3160. // canonicalize (sub X, step_vector(C)) to (add X, step_vector(-C))
  3161. if (N1.getOpcode() == ISD::STEP_VECTOR && N1.hasOneUse()) {
  3162. APInt NewStep = -N1.getConstantOperandAPInt(0);
  3163. return DAG.getNode(ISD::ADD, DL, VT, N0,
  3164. DAG.getStepVector(DL, VT, NewStep));
  3165. }
  3166. // Prefer an add for more folding potential and possibly better codegen:
  3167. // sub N0, (lshr N10, width-1) --> add N0, (ashr N10, width-1)
  3168. if (!LegalOperations && N1.getOpcode() == ISD::SRL && N1.hasOneUse()) {
  3169. SDValue ShAmt = N1.getOperand(1);
  3170. ConstantSDNode *ShAmtC = isConstOrConstSplat(ShAmt);
  3171. if (ShAmtC &&
  3172. ShAmtC->getAPIntValue() == (N1.getScalarValueSizeInBits() - 1)) {
  3173. SDValue SRA = DAG.getNode(ISD::SRA, DL, VT, N1.getOperand(0), ShAmt);
  3174. return DAG.getNode(ISD::ADD, DL, VT, N0, SRA);
  3175. }
  3176. }
  3177. if (TLI.isOperationLegalOrCustom(ISD::ADDCARRY, VT)) {
  3178. // (sub Carry, X) -> (addcarry (sub 0, X), 0, Carry)
  3179. if (SDValue Carry = getAsCarry(TLI, N0)) {
  3180. SDValue X = N1;
  3181. SDValue Zero = DAG.getConstant(0, DL, VT);
  3182. SDValue NegX = DAG.getNode(ISD::SUB, DL, VT, Zero, X);
  3183. return DAG.getNode(ISD::ADDCARRY, DL,
  3184. DAG.getVTList(VT, Carry.getValueType()), NegX, Zero,
  3185. Carry);
  3186. }
  3187. }
  3188. return SDValue();
  3189. }
  3190. SDValue DAGCombiner::visitSUBSAT(SDNode *N) {
  3191. SDValue N0 = N->getOperand(0);
  3192. SDValue N1 = N->getOperand(1);
  3193. EVT VT = N0.getValueType();
  3194. SDLoc DL(N);
  3195. // fold (sub_sat x, undef) -> 0
  3196. if (N0.isUndef() || N1.isUndef())
  3197. return DAG.getConstant(0, DL, VT);
  3198. // fold (sub_sat x, x) -> 0
  3199. if (N0 == N1)
  3200. return DAG.getConstant(0, DL, VT);
  3201. // fold (sub_sat c1, c2) -> c3
  3202. if (SDValue C = DAG.FoldConstantArithmetic(N->getOpcode(), DL, VT, {N0, N1}))
  3203. return C;
  3204. // fold vector ops
  3205. if (VT.isVector()) {
  3206. // TODO SimplifyVBinOp
  3207. // fold (sub_sat x, 0) -> x, vector edition
  3208. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  3209. return N0;
  3210. }
  3211. // fold (sub_sat x, 0) -> x
  3212. if (isNullConstant(N1))
  3213. return N0;
  3214. return SDValue();
  3215. }
  3216. SDValue DAGCombiner::visitSUBC(SDNode *N) {
  3217. SDValue N0 = N->getOperand(0);
  3218. SDValue N1 = N->getOperand(1);
  3219. EVT VT = N0.getValueType();
  3220. SDLoc DL(N);
  3221. // If the flag result is dead, turn this into an SUB.
  3222. if (!N->hasAnyUseOfValue(1))
  3223. return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
  3224. DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
  3225. // fold (subc x, x) -> 0 + no borrow
  3226. if (N0 == N1)
  3227. return CombineTo(N, DAG.getConstant(0, DL, VT),
  3228. DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
  3229. // fold (subc x, 0) -> x + no borrow
  3230. if (isNullConstant(N1))
  3231. return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
  3232. // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
  3233. if (isAllOnesConstant(N0))
  3234. return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
  3235. DAG.getNode(ISD::CARRY_FALSE, DL, MVT::Glue));
  3236. return SDValue();
  3237. }
  3238. SDValue DAGCombiner::visitSUBO(SDNode *N) {
  3239. SDValue N0 = N->getOperand(0);
  3240. SDValue N1 = N->getOperand(1);
  3241. EVT VT = N0.getValueType();
  3242. bool IsSigned = (ISD::SSUBO == N->getOpcode());
  3243. EVT CarryVT = N->getValueType(1);
  3244. SDLoc DL(N);
  3245. // If the flag result is dead, turn this into an SUB.
  3246. if (!N->hasAnyUseOfValue(1))
  3247. return CombineTo(N, DAG.getNode(ISD::SUB, DL, VT, N0, N1),
  3248. DAG.getUNDEF(CarryVT));
  3249. // fold (subo x, x) -> 0 + no borrow
  3250. if (N0 == N1)
  3251. return CombineTo(N, DAG.getConstant(0, DL, VT),
  3252. DAG.getConstant(0, DL, CarryVT));
  3253. ConstantSDNode *N1C = getAsNonOpaqueConstant(N1);
  3254. // fold (subox, c) -> (addo x, -c)
  3255. if (IsSigned && N1C && !N1C->getAPIntValue().isMinSignedValue()) {
  3256. return DAG.getNode(ISD::SADDO, DL, N->getVTList(), N0,
  3257. DAG.getConstant(-N1C->getAPIntValue(), DL, VT));
  3258. }
  3259. // fold (subo x, 0) -> x + no borrow
  3260. if (isNullOrNullSplat(N1))
  3261. return CombineTo(N, N0, DAG.getConstant(0, DL, CarryVT));
  3262. // Canonicalize (usubo -1, x) -> ~x, i.e. (xor x, -1) + no borrow
  3263. if (!IsSigned && isAllOnesOrAllOnesSplat(N0))
  3264. return CombineTo(N, DAG.getNode(ISD::XOR, DL, VT, N1, N0),
  3265. DAG.getConstant(0, DL, CarryVT));
  3266. return SDValue();
  3267. }
  3268. SDValue DAGCombiner::visitSUBE(SDNode *N) {
  3269. SDValue N0 = N->getOperand(0);
  3270. SDValue N1 = N->getOperand(1);
  3271. SDValue CarryIn = N->getOperand(2);
  3272. // fold (sube x, y, false) -> (subc x, y)
  3273. if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
  3274. return DAG.getNode(ISD::SUBC, SDLoc(N), N->getVTList(), N0, N1);
  3275. return SDValue();
  3276. }
  3277. SDValue DAGCombiner::visitSUBCARRY(SDNode *N) {
  3278. SDValue N0 = N->getOperand(0);
  3279. SDValue N1 = N->getOperand(1);
  3280. SDValue CarryIn = N->getOperand(2);
  3281. // fold (subcarry x, y, false) -> (usubo x, y)
  3282. if (isNullConstant(CarryIn)) {
  3283. if (!LegalOperations ||
  3284. TLI.isOperationLegalOrCustom(ISD::USUBO, N->getValueType(0)))
  3285. return DAG.getNode(ISD::USUBO, SDLoc(N), N->getVTList(), N0, N1);
  3286. }
  3287. return SDValue();
  3288. }
  3289. SDValue DAGCombiner::visitSSUBO_CARRY(SDNode *N) {
  3290. SDValue N0 = N->getOperand(0);
  3291. SDValue N1 = N->getOperand(1);
  3292. SDValue CarryIn = N->getOperand(2);
  3293. // fold (ssubo_carry x, y, false) -> (ssubo x, y)
  3294. if (isNullConstant(CarryIn)) {
  3295. if (!LegalOperations ||
  3296. TLI.isOperationLegalOrCustom(ISD::SSUBO, N->getValueType(0)))
  3297. return DAG.getNode(ISD::SSUBO, SDLoc(N), N->getVTList(), N0, N1);
  3298. }
  3299. return SDValue();
  3300. }
  3301. // Notice that "mulfix" can be any of SMULFIX, SMULFIXSAT, UMULFIX and
  3302. // UMULFIXSAT here.
  3303. SDValue DAGCombiner::visitMULFIX(SDNode *N) {
  3304. SDValue N0 = N->getOperand(0);
  3305. SDValue N1 = N->getOperand(1);
  3306. SDValue Scale = N->getOperand(2);
  3307. EVT VT = N0.getValueType();
  3308. // fold (mulfix x, undef, scale) -> 0
  3309. if (N0.isUndef() || N1.isUndef())
  3310. return DAG.getConstant(0, SDLoc(N), VT);
  3311. // Canonicalize constant to RHS (vector doesn't have to splat)
  3312. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  3313. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  3314. return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0, Scale);
  3315. // fold (mulfix x, 0, scale) -> 0
  3316. if (isNullConstant(N1))
  3317. return DAG.getConstant(0, SDLoc(N), VT);
  3318. return SDValue();
  3319. }
  3320. SDValue DAGCombiner::visitMUL(SDNode *N) {
  3321. SDValue N0 = N->getOperand(0);
  3322. SDValue N1 = N->getOperand(1);
  3323. EVT VT = N0.getValueType();
  3324. // fold (mul x, undef) -> 0
  3325. if (N0.isUndef() || N1.isUndef())
  3326. return DAG.getConstant(0, SDLoc(N), VT);
  3327. // fold (mul c1, c2) -> c1*c2
  3328. if (SDValue C = DAG.FoldConstantArithmetic(ISD::MUL, SDLoc(N), VT, {N0, N1}))
  3329. return C;
  3330. // canonicalize constant to RHS (vector doesn't have to splat)
  3331. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  3332. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  3333. return DAG.getNode(ISD::MUL, SDLoc(N), VT, N1, N0);
  3334. bool N1IsConst = false;
  3335. bool N1IsOpaqueConst = false;
  3336. APInt ConstValue1;
  3337. // fold vector ops
  3338. if (VT.isVector()) {
  3339. if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
  3340. return FoldedVOp;
  3341. N1IsConst = ISD::isConstantSplatVector(N1.getNode(), ConstValue1);
  3342. assert((!N1IsConst ||
  3343. ConstValue1.getBitWidth() == VT.getScalarSizeInBits()) &&
  3344. "Splat APInt should be element width");
  3345. } else {
  3346. N1IsConst = isa<ConstantSDNode>(N1);
  3347. if (N1IsConst) {
  3348. ConstValue1 = cast<ConstantSDNode>(N1)->getAPIntValue();
  3349. N1IsOpaqueConst = cast<ConstantSDNode>(N1)->isOpaque();
  3350. }
  3351. }
  3352. // fold (mul x, 0) -> 0
  3353. if (N1IsConst && ConstValue1.isZero())
  3354. return N1;
  3355. // fold (mul x, 1) -> x
  3356. if (N1IsConst && ConstValue1.isOne())
  3357. return N0;
  3358. if (SDValue NewSel = foldBinOpIntoSelect(N))
  3359. return NewSel;
  3360. // fold (mul x, -1) -> 0-x
  3361. if (N1IsConst && ConstValue1.isAllOnes()) {
  3362. SDLoc DL(N);
  3363. return DAG.getNode(ISD::SUB, DL, VT,
  3364. DAG.getConstant(0, DL, VT), N0);
  3365. }
  3366. // fold (mul x, (1 << c)) -> x << c
  3367. if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
  3368. DAG.isKnownToBeAPowerOfTwo(N1) &&
  3369. (!VT.isVector() || Level <= AfterLegalizeVectorOps)) {
  3370. SDLoc DL(N);
  3371. SDValue LogBase2 = BuildLogBase2(N1, DL);
  3372. EVT ShiftVT = getShiftAmountTy(N0.getValueType());
  3373. SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
  3374. return DAG.getNode(ISD::SHL, DL, VT, N0, Trunc);
  3375. }
  3376. // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
  3377. if (N1IsConst && !N1IsOpaqueConst && ConstValue1.isNegatedPowerOf2()) {
  3378. unsigned Log2Val = (-ConstValue1).logBase2();
  3379. SDLoc DL(N);
  3380. // FIXME: If the input is something that is easily negated (e.g. a
  3381. // single-use add), we should put the negate there.
  3382. return DAG.getNode(ISD::SUB, DL, VT,
  3383. DAG.getConstant(0, DL, VT),
  3384. DAG.getNode(ISD::SHL, DL, VT, N0,
  3385. DAG.getConstant(Log2Val, DL,
  3386. getShiftAmountTy(N0.getValueType()))));
  3387. }
  3388. // Try to transform:
  3389. // (1) multiply-by-(power-of-2 +/- 1) into shift and add/sub.
  3390. // mul x, (2^N + 1) --> add (shl x, N), x
  3391. // mul x, (2^N - 1) --> sub (shl x, N), x
  3392. // Examples: x * 33 --> (x << 5) + x
  3393. // x * 15 --> (x << 4) - x
  3394. // x * -33 --> -((x << 5) + x)
  3395. // x * -15 --> -((x << 4) - x) ; this reduces --> x - (x << 4)
  3396. // (2) multiply-by-(power-of-2 +/- power-of-2) into shifts and add/sub.
  3397. // mul x, (2^N + 2^M) --> (add (shl x, N), (shl x, M))
  3398. // mul x, (2^N - 2^M) --> (sub (shl x, N), (shl x, M))
  3399. // Examples: x * 0x8800 --> (x << 15) + (x << 11)
  3400. // x * 0xf800 --> (x << 16) - (x << 11)
  3401. // x * -0x8800 --> -((x << 15) + (x << 11))
  3402. // x * -0xf800 --> -((x << 16) - (x << 11)) ; (x << 11) - (x << 16)
  3403. if (N1IsConst && TLI.decomposeMulByConstant(*DAG.getContext(), VT, N1)) {
  3404. // TODO: We could handle more general decomposition of any constant by
  3405. // having the target set a limit on number of ops and making a
  3406. // callback to determine that sequence (similar to sqrt expansion).
  3407. unsigned MathOp = ISD::DELETED_NODE;
  3408. APInt MulC = ConstValue1.abs();
  3409. // The constant `2` should be treated as (2^0 + 1).
  3410. unsigned TZeros = MulC == 2 ? 0 : MulC.countTrailingZeros();
  3411. MulC.lshrInPlace(TZeros);
  3412. if ((MulC - 1).isPowerOf2())
  3413. MathOp = ISD::ADD;
  3414. else if ((MulC + 1).isPowerOf2())
  3415. MathOp = ISD::SUB;
  3416. if (MathOp != ISD::DELETED_NODE) {
  3417. unsigned ShAmt =
  3418. MathOp == ISD::ADD ? (MulC - 1).logBase2() : (MulC + 1).logBase2();
  3419. ShAmt += TZeros;
  3420. assert(ShAmt < VT.getScalarSizeInBits() &&
  3421. "multiply-by-constant generated out of bounds shift");
  3422. SDLoc DL(N);
  3423. SDValue Shl =
  3424. DAG.getNode(ISD::SHL, DL, VT, N0, DAG.getConstant(ShAmt, DL, VT));
  3425. SDValue R =
  3426. TZeros ? DAG.getNode(MathOp, DL, VT, Shl,
  3427. DAG.getNode(ISD::SHL, DL, VT, N0,
  3428. DAG.getConstant(TZeros, DL, VT)))
  3429. : DAG.getNode(MathOp, DL, VT, Shl, N0);
  3430. if (ConstValue1.isNegative())
  3431. R = DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), R);
  3432. return R;
  3433. }
  3434. }
  3435. // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
  3436. if (N0.getOpcode() == ISD::SHL &&
  3437. isConstantOrConstantVector(N1, /* NoOpaques */ true) &&
  3438. isConstantOrConstantVector(N0.getOperand(1), /* NoOpaques */ true)) {
  3439. SDValue C3 = DAG.getNode(ISD::SHL, SDLoc(N), VT, N1, N0.getOperand(1));
  3440. if (isConstantOrConstantVector(C3))
  3441. return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), C3);
  3442. }
  3443. // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
  3444. // use.
  3445. {
  3446. SDValue Sh, Y;
  3447. // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
  3448. if (N0.getOpcode() == ISD::SHL &&
  3449. isConstantOrConstantVector(N0.getOperand(1)) &&
  3450. N0.getNode()->hasOneUse()) {
  3451. Sh = N0; Y = N1;
  3452. } else if (N1.getOpcode() == ISD::SHL &&
  3453. isConstantOrConstantVector(N1.getOperand(1)) &&
  3454. N1.getNode()->hasOneUse()) {
  3455. Sh = N1; Y = N0;
  3456. }
  3457. if (Sh.getNode()) {
  3458. SDValue Mul = DAG.getNode(ISD::MUL, SDLoc(N), VT, Sh.getOperand(0), Y);
  3459. return DAG.getNode(ISD::SHL, SDLoc(N), VT, Mul, Sh.getOperand(1));
  3460. }
  3461. }
  3462. // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
  3463. if (DAG.isConstantIntBuildVectorOrConstantInt(N1) &&
  3464. N0.getOpcode() == ISD::ADD &&
  3465. DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1)) &&
  3466. isMulAddWithConstProfitable(N, N0, N1))
  3467. return DAG.getNode(ISD::ADD, SDLoc(N), VT,
  3468. DAG.getNode(ISD::MUL, SDLoc(N0), VT,
  3469. N0.getOperand(0), N1),
  3470. DAG.getNode(ISD::MUL, SDLoc(N1), VT,
  3471. N0.getOperand(1), N1));
  3472. // Fold (mul (vscale * C0), C1) to (vscale * (C0 * C1)).
  3473. if (N0.getOpcode() == ISD::VSCALE)
  3474. if (ConstantSDNode *NC1 = isConstOrConstSplat(N1)) {
  3475. const APInt &C0 = N0.getConstantOperandAPInt(0);
  3476. const APInt &C1 = NC1->getAPIntValue();
  3477. return DAG.getVScale(SDLoc(N), VT, C0 * C1);
  3478. }
  3479. // Fold (mul step_vector(C0), C1) to (step_vector(C0 * C1)).
  3480. APInt MulVal;
  3481. if (N0.getOpcode() == ISD::STEP_VECTOR)
  3482. if (ISD::isConstantSplatVector(N1.getNode(), MulVal)) {
  3483. const APInt &C0 = N0.getConstantOperandAPInt(0);
  3484. APInt NewStep = C0 * MulVal;
  3485. return DAG.getStepVector(SDLoc(N), VT, NewStep);
  3486. }
  3487. // Fold ((mul x, 0/undef) -> 0,
  3488. // (mul x, 1) -> x) -> x)
  3489. // -> and(x, mask)
  3490. // We can replace vectors with '0' and '1' factors with a clearing mask.
  3491. if (VT.isFixedLengthVector()) {
  3492. unsigned NumElts = VT.getVectorNumElements();
  3493. SmallBitVector ClearMask;
  3494. ClearMask.reserve(NumElts);
  3495. auto IsClearMask = [&ClearMask](ConstantSDNode *V) {
  3496. if (!V || V->isZero()) {
  3497. ClearMask.push_back(true);
  3498. return true;
  3499. }
  3500. ClearMask.push_back(false);
  3501. return V->isOne();
  3502. };
  3503. if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::AND, VT)) &&
  3504. ISD::matchUnaryPredicate(N1, IsClearMask, /*AllowUndefs*/ true)) {
  3505. assert(N1.getOpcode() == ISD::BUILD_VECTOR && "Unknown constant vector");
  3506. SDLoc DL(N);
  3507. EVT LegalSVT = N1.getOperand(0).getValueType();
  3508. SDValue Zero = DAG.getConstant(0, DL, LegalSVT);
  3509. SDValue AllOnes = DAG.getAllOnesConstant(DL, LegalSVT);
  3510. SmallVector<SDValue, 16> Mask(NumElts, AllOnes);
  3511. for (unsigned I = 0; I != NumElts; ++I)
  3512. if (ClearMask[I])
  3513. Mask[I] = Zero;
  3514. return DAG.getNode(ISD::AND, DL, VT, N0, DAG.getBuildVector(VT, DL, Mask));
  3515. }
  3516. }
  3517. // reassociate mul
  3518. if (SDValue RMUL = reassociateOps(ISD::MUL, SDLoc(N), N0, N1, N->getFlags()))
  3519. return RMUL;
  3520. return SDValue();
  3521. }
  3522. /// Return true if divmod libcall is available.
  3523. static bool isDivRemLibcallAvailable(SDNode *Node, bool isSigned,
  3524. const TargetLowering &TLI) {
  3525. RTLIB::Libcall LC;
  3526. EVT NodeType = Node->getValueType(0);
  3527. if (!NodeType.isSimple())
  3528. return false;
  3529. switch (NodeType.getSimpleVT().SimpleTy) {
  3530. default: return false; // No libcall for vector types.
  3531. case MVT::i8: LC= isSigned ? RTLIB::SDIVREM_I8 : RTLIB::UDIVREM_I8; break;
  3532. case MVT::i16: LC= isSigned ? RTLIB::SDIVREM_I16 : RTLIB::UDIVREM_I16; break;
  3533. case MVT::i32: LC= isSigned ? RTLIB::SDIVREM_I32 : RTLIB::UDIVREM_I32; break;
  3534. case MVT::i64: LC= isSigned ? RTLIB::SDIVREM_I64 : RTLIB::UDIVREM_I64; break;
  3535. case MVT::i128: LC= isSigned ? RTLIB::SDIVREM_I128:RTLIB::UDIVREM_I128; break;
  3536. }
  3537. return TLI.getLibcallName(LC) != nullptr;
  3538. }
  3539. /// Issue divrem if both quotient and remainder are needed.
  3540. SDValue DAGCombiner::useDivRem(SDNode *Node) {
  3541. if (Node->use_empty())
  3542. return SDValue(); // This is a dead node, leave it alone.
  3543. unsigned Opcode = Node->getOpcode();
  3544. bool isSigned = (Opcode == ISD::SDIV) || (Opcode == ISD::SREM);
  3545. unsigned DivRemOpc = isSigned ? ISD::SDIVREM : ISD::UDIVREM;
  3546. // DivMod lib calls can still work on non-legal types if using lib-calls.
  3547. EVT VT = Node->getValueType(0);
  3548. if (VT.isVector() || !VT.isInteger())
  3549. return SDValue();
  3550. if (!TLI.isTypeLegal(VT) && !TLI.isOperationCustom(DivRemOpc, VT))
  3551. return SDValue();
  3552. // If DIVREM is going to get expanded into a libcall,
  3553. // but there is no libcall available, then don't combine.
  3554. if (!TLI.isOperationLegalOrCustom(DivRemOpc, VT) &&
  3555. !isDivRemLibcallAvailable(Node, isSigned, TLI))
  3556. return SDValue();
  3557. // If div is legal, it's better to do the normal expansion
  3558. unsigned OtherOpcode = 0;
  3559. if ((Opcode == ISD::SDIV) || (Opcode == ISD::UDIV)) {
  3560. OtherOpcode = isSigned ? ISD::SREM : ISD::UREM;
  3561. if (TLI.isOperationLegalOrCustom(Opcode, VT))
  3562. return SDValue();
  3563. } else {
  3564. OtherOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
  3565. if (TLI.isOperationLegalOrCustom(OtherOpcode, VT))
  3566. return SDValue();
  3567. }
  3568. SDValue Op0 = Node->getOperand(0);
  3569. SDValue Op1 = Node->getOperand(1);
  3570. SDValue combined;
  3571. for (SDNode *User : Op0.getNode()->uses()) {
  3572. if (User == Node || User->getOpcode() == ISD::DELETED_NODE ||
  3573. User->use_empty())
  3574. continue;
  3575. // Convert the other matching node(s), too;
  3576. // otherwise, the DIVREM may get target-legalized into something
  3577. // target-specific that we won't be able to recognize.
  3578. unsigned UserOpc = User->getOpcode();
  3579. if ((UserOpc == Opcode || UserOpc == OtherOpcode || UserOpc == DivRemOpc) &&
  3580. User->getOperand(0) == Op0 &&
  3581. User->getOperand(1) == Op1) {
  3582. if (!combined) {
  3583. if (UserOpc == OtherOpcode) {
  3584. SDVTList VTs = DAG.getVTList(VT, VT);
  3585. combined = DAG.getNode(DivRemOpc, SDLoc(Node), VTs, Op0, Op1);
  3586. } else if (UserOpc == DivRemOpc) {
  3587. combined = SDValue(User, 0);
  3588. } else {
  3589. assert(UserOpc == Opcode);
  3590. continue;
  3591. }
  3592. }
  3593. if (UserOpc == ISD::SDIV || UserOpc == ISD::UDIV)
  3594. CombineTo(User, combined);
  3595. else if (UserOpc == ISD::SREM || UserOpc == ISD::UREM)
  3596. CombineTo(User, combined.getValue(1));
  3597. }
  3598. }
  3599. return combined;
  3600. }
  3601. static SDValue simplifyDivRem(SDNode *N, SelectionDAG &DAG) {
  3602. SDValue N0 = N->getOperand(0);
  3603. SDValue N1 = N->getOperand(1);
  3604. EVT VT = N->getValueType(0);
  3605. SDLoc DL(N);
  3606. unsigned Opc = N->getOpcode();
  3607. bool IsDiv = (ISD::SDIV == Opc) || (ISD::UDIV == Opc);
  3608. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  3609. // X / undef -> undef
  3610. // X % undef -> undef
  3611. // X / 0 -> undef
  3612. // X % 0 -> undef
  3613. // NOTE: This includes vectors where any divisor element is zero/undef.
  3614. if (DAG.isUndef(Opc, {N0, N1}))
  3615. return DAG.getUNDEF(VT);
  3616. // undef / X -> 0
  3617. // undef % X -> 0
  3618. if (N0.isUndef())
  3619. return DAG.getConstant(0, DL, VT);
  3620. // 0 / X -> 0
  3621. // 0 % X -> 0
  3622. ConstantSDNode *N0C = isConstOrConstSplat(N0);
  3623. if (N0C && N0C->isZero())
  3624. return N0;
  3625. // X / X -> 1
  3626. // X % X -> 0
  3627. if (N0 == N1)
  3628. return DAG.getConstant(IsDiv ? 1 : 0, DL, VT);
  3629. // X / 1 -> X
  3630. // X % 1 -> 0
  3631. // If this is a boolean op (single-bit element type), we can't have
  3632. // division-by-zero or remainder-by-zero, so assume the divisor is 1.
  3633. // TODO: Similarly, if we're zero-extending a boolean divisor, then assume
  3634. // it's a 1.
  3635. if ((N1C && N1C->isOne()) || (VT.getScalarType() == MVT::i1))
  3636. return IsDiv ? N0 : DAG.getConstant(0, DL, VT);
  3637. return SDValue();
  3638. }
  3639. SDValue DAGCombiner::visitSDIV(SDNode *N) {
  3640. SDValue N0 = N->getOperand(0);
  3641. SDValue N1 = N->getOperand(1);
  3642. EVT VT = N->getValueType(0);
  3643. EVT CCVT = getSetCCResultType(VT);
  3644. SDLoc DL(N);
  3645. // fold (sdiv c1, c2) -> c1/c2
  3646. if (SDValue C = DAG.FoldConstantArithmetic(ISD::SDIV, DL, VT, {N0, N1}))
  3647. return C;
  3648. // fold vector ops
  3649. if (VT.isVector())
  3650. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  3651. return FoldedVOp;
  3652. // fold (sdiv X, -1) -> 0-X
  3653. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  3654. if (N1C && N1C->isAllOnes())
  3655. return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), N0);
  3656. // fold (sdiv X, MIN_SIGNED) -> select(X == MIN_SIGNED, 1, 0)
  3657. if (N1C && N1C->getAPIntValue().isMinSignedValue())
  3658. return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
  3659. DAG.getConstant(1, DL, VT),
  3660. DAG.getConstant(0, DL, VT));
  3661. if (SDValue V = simplifyDivRem(N, DAG))
  3662. return V;
  3663. if (SDValue NewSel = foldBinOpIntoSelect(N))
  3664. return NewSel;
  3665. // If we know the sign bits of both operands are zero, strength reduce to a
  3666. // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
  3667. if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
  3668. return DAG.getNode(ISD::UDIV, DL, N1.getValueType(), N0, N1);
  3669. if (SDValue V = visitSDIVLike(N0, N1, N)) {
  3670. // If the corresponding remainder node exists, update its users with
  3671. // (Dividend - (Quotient * Divisor).
  3672. if (SDNode *RemNode = DAG.getNodeIfExists(ISD::SREM, N->getVTList(),
  3673. { N0, N1 })) {
  3674. SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
  3675. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
  3676. AddToWorklist(Mul.getNode());
  3677. AddToWorklist(Sub.getNode());
  3678. CombineTo(RemNode, Sub);
  3679. }
  3680. return V;
  3681. }
  3682. // sdiv, srem -> sdivrem
  3683. // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
  3684. // true. Otherwise, we break the simplification logic in visitREM().
  3685. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  3686. if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
  3687. if (SDValue DivRem = useDivRem(N))
  3688. return DivRem;
  3689. return SDValue();
  3690. }
  3691. SDValue DAGCombiner::visitSDIVLike(SDValue N0, SDValue N1, SDNode *N) {
  3692. SDLoc DL(N);
  3693. EVT VT = N->getValueType(0);
  3694. EVT CCVT = getSetCCResultType(VT);
  3695. unsigned BitWidth = VT.getScalarSizeInBits();
  3696. // Helper for determining whether a value is a power-2 constant scalar or a
  3697. // vector of such elements.
  3698. auto IsPowerOfTwo = [](ConstantSDNode *C) {
  3699. if (C->isZero() || C->isOpaque())
  3700. return false;
  3701. if (C->getAPIntValue().isPowerOf2())
  3702. return true;
  3703. if (C->getAPIntValue().isNegatedPowerOf2())
  3704. return true;
  3705. return false;
  3706. };
  3707. // fold (sdiv X, pow2) -> simple ops after legalize
  3708. // FIXME: We check for the exact bit here because the generic lowering gives
  3709. // better results in that case. The target-specific lowering should learn how
  3710. // to handle exact sdivs efficiently.
  3711. if (!N->getFlags().hasExact() && ISD::matchUnaryPredicate(N1, IsPowerOfTwo)) {
  3712. // Target-specific implementation of sdiv x, pow2.
  3713. if (SDValue Res = BuildSDIVPow2(N))
  3714. return Res;
  3715. // Create constants that are functions of the shift amount value.
  3716. EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
  3717. SDValue Bits = DAG.getConstant(BitWidth, DL, ShiftAmtTy);
  3718. SDValue C1 = DAG.getNode(ISD::CTTZ, DL, VT, N1);
  3719. C1 = DAG.getZExtOrTrunc(C1, DL, ShiftAmtTy);
  3720. SDValue Inexact = DAG.getNode(ISD::SUB, DL, ShiftAmtTy, Bits, C1);
  3721. if (!isConstantOrConstantVector(Inexact))
  3722. return SDValue();
  3723. // Splat the sign bit into the register
  3724. SDValue Sign = DAG.getNode(ISD::SRA, DL, VT, N0,
  3725. DAG.getConstant(BitWidth - 1, DL, ShiftAmtTy));
  3726. AddToWorklist(Sign.getNode());
  3727. // Add (N0 < 0) ? abs2 - 1 : 0;
  3728. SDValue Srl = DAG.getNode(ISD::SRL, DL, VT, Sign, Inexact);
  3729. AddToWorklist(Srl.getNode());
  3730. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N0, Srl);
  3731. AddToWorklist(Add.getNode());
  3732. SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Add, C1);
  3733. AddToWorklist(Sra.getNode());
  3734. // Special case: (sdiv X, 1) -> X
  3735. // Special Case: (sdiv X, -1) -> 0-X
  3736. SDValue One = DAG.getConstant(1, DL, VT);
  3737. SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
  3738. SDValue IsOne = DAG.getSetCC(DL, CCVT, N1, One, ISD::SETEQ);
  3739. SDValue IsAllOnes = DAG.getSetCC(DL, CCVT, N1, AllOnes, ISD::SETEQ);
  3740. SDValue IsOneOrAllOnes = DAG.getNode(ISD::OR, DL, CCVT, IsOne, IsAllOnes);
  3741. Sra = DAG.getSelect(DL, VT, IsOneOrAllOnes, N0, Sra);
  3742. // If dividing by a positive value, we're done. Otherwise, the result must
  3743. // be negated.
  3744. SDValue Zero = DAG.getConstant(0, DL, VT);
  3745. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, Zero, Sra);
  3746. // FIXME: Use SELECT_CC once we improve SELECT_CC constant-folding.
  3747. SDValue IsNeg = DAG.getSetCC(DL, CCVT, N1, Zero, ISD::SETLT);
  3748. SDValue Res = DAG.getSelect(DL, VT, IsNeg, Sub, Sra);
  3749. return Res;
  3750. }
  3751. // If integer divide is expensive and we satisfy the requirements, emit an
  3752. // alternate sequence. Targets may check function attributes for size/speed
  3753. // trade-offs.
  3754. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  3755. if (isConstantOrConstantVector(N1) &&
  3756. !TLI.isIntDivCheap(N->getValueType(0), Attr))
  3757. if (SDValue Op = BuildSDIV(N))
  3758. return Op;
  3759. return SDValue();
  3760. }
  3761. SDValue DAGCombiner::visitUDIV(SDNode *N) {
  3762. SDValue N0 = N->getOperand(0);
  3763. SDValue N1 = N->getOperand(1);
  3764. EVT VT = N->getValueType(0);
  3765. EVT CCVT = getSetCCResultType(VT);
  3766. SDLoc DL(N);
  3767. // fold (udiv c1, c2) -> c1/c2
  3768. if (SDValue C = DAG.FoldConstantArithmetic(ISD::UDIV, DL, VT, {N0, N1}))
  3769. return C;
  3770. // fold vector ops
  3771. if (VT.isVector())
  3772. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  3773. return FoldedVOp;
  3774. // fold (udiv X, -1) -> select(X == -1, 1, 0)
  3775. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  3776. if (N1C && N1C->isAllOnes())
  3777. return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
  3778. DAG.getConstant(1, DL, VT),
  3779. DAG.getConstant(0, DL, VT));
  3780. if (SDValue V = simplifyDivRem(N, DAG))
  3781. return V;
  3782. if (SDValue NewSel = foldBinOpIntoSelect(N))
  3783. return NewSel;
  3784. if (SDValue V = visitUDIVLike(N0, N1, N)) {
  3785. // If the corresponding remainder node exists, update its users with
  3786. // (Dividend - (Quotient * Divisor).
  3787. if (SDNode *RemNode = DAG.getNodeIfExists(ISD::UREM, N->getVTList(),
  3788. { N0, N1 })) {
  3789. SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, V, N1);
  3790. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
  3791. AddToWorklist(Mul.getNode());
  3792. AddToWorklist(Sub.getNode());
  3793. CombineTo(RemNode, Sub);
  3794. }
  3795. return V;
  3796. }
  3797. // sdiv, srem -> sdivrem
  3798. // If the divisor is constant, then return DIVREM only if isIntDivCheap() is
  3799. // true. Otherwise, we break the simplification logic in visitREM().
  3800. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  3801. if (!N1C || TLI.isIntDivCheap(N->getValueType(0), Attr))
  3802. if (SDValue DivRem = useDivRem(N))
  3803. return DivRem;
  3804. return SDValue();
  3805. }
  3806. SDValue DAGCombiner::visitUDIVLike(SDValue N0, SDValue N1, SDNode *N) {
  3807. SDLoc DL(N);
  3808. EVT VT = N->getValueType(0);
  3809. // fold (udiv x, (1 << c)) -> x >>u c
  3810. if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
  3811. DAG.isKnownToBeAPowerOfTwo(N1)) {
  3812. SDValue LogBase2 = BuildLogBase2(N1, DL);
  3813. AddToWorklist(LogBase2.getNode());
  3814. EVT ShiftVT = getShiftAmountTy(N0.getValueType());
  3815. SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ShiftVT);
  3816. AddToWorklist(Trunc.getNode());
  3817. return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
  3818. }
  3819. // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
  3820. if (N1.getOpcode() == ISD::SHL) {
  3821. SDValue N10 = N1.getOperand(0);
  3822. if (isConstantOrConstantVector(N10, /*NoOpaques*/ true) &&
  3823. DAG.isKnownToBeAPowerOfTwo(N10)) {
  3824. SDValue LogBase2 = BuildLogBase2(N10, DL);
  3825. AddToWorklist(LogBase2.getNode());
  3826. EVT ADDVT = N1.getOperand(1).getValueType();
  3827. SDValue Trunc = DAG.getZExtOrTrunc(LogBase2, DL, ADDVT);
  3828. AddToWorklist(Trunc.getNode());
  3829. SDValue Add = DAG.getNode(ISD::ADD, DL, ADDVT, N1.getOperand(1), Trunc);
  3830. AddToWorklist(Add.getNode());
  3831. return DAG.getNode(ISD::SRL, DL, VT, N0, Add);
  3832. }
  3833. }
  3834. // fold (udiv x, c) -> alternate
  3835. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  3836. if (isConstantOrConstantVector(N1) &&
  3837. !TLI.isIntDivCheap(N->getValueType(0), Attr))
  3838. if (SDValue Op = BuildUDIV(N))
  3839. return Op;
  3840. return SDValue();
  3841. }
  3842. // handles ISD::SREM and ISD::UREM
  3843. SDValue DAGCombiner::visitREM(SDNode *N) {
  3844. unsigned Opcode = N->getOpcode();
  3845. SDValue N0 = N->getOperand(0);
  3846. SDValue N1 = N->getOperand(1);
  3847. EVT VT = N->getValueType(0);
  3848. EVT CCVT = getSetCCResultType(VT);
  3849. bool isSigned = (Opcode == ISD::SREM);
  3850. SDLoc DL(N);
  3851. // fold (rem c1, c2) -> c1%c2
  3852. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  3853. if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
  3854. return C;
  3855. // fold (urem X, -1) -> select(X == -1, 0, x)
  3856. if (!isSigned && N1C && N1C->isAllOnes())
  3857. return DAG.getSelect(DL, VT, DAG.getSetCC(DL, CCVT, N0, N1, ISD::SETEQ),
  3858. DAG.getConstant(0, DL, VT), N0);
  3859. if (SDValue V = simplifyDivRem(N, DAG))
  3860. return V;
  3861. if (SDValue NewSel = foldBinOpIntoSelect(N))
  3862. return NewSel;
  3863. if (isSigned) {
  3864. // If we know the sign bits of both operands are zero, strength reduce to a
  3865. // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
  3866. if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
  3867. return DAG.getNode(ISD::UREM, DL, VT, N0, N1);
  3868. } else {
  3869. if (DAG.isKnownToBeAPowerOfTwo(N1)) {
  3870. // fold (urem x, pow2) -> (and x, pow2-1)
  3871. SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
  3872. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
  3873. AddToWorklist(Add.getNode());
  3874. return DAG.getNode(ISD::AND, DL, VT, N0, Add);
  3875. }
  3876. if (N1.getOpcode() == ISD::SHL &&
  3877. DAG.isKnownToBeAPowerOfTwo(N1.getOperand(0))) {
  3878. // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
  3879. SDValue NegOne = DAG.getAllOnesConstant(DL, VT);
  3880. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, N1, NegOne);
  3881. AddToWorklist(Add.getNode());
  3882. return DAG.getNode(ISD::AND, DL, VT, N0, Add);
  3883. }
  3884. }
  3885. AttributeList Attr = DAG.getMachineFunction().getFunction().getAttributes();
  3886. // If X/C can be simplified by the division-by-constant logic, lower
  3887. // X%C to the equivalent of X-X/C*C.
  3888. // Reuse the SDIVLike/UDIVLike combines - to avoid mangling nodes, the
  3889. // speculative DIV must not cause a DIVREM conversion. We guard against this
  3890. // by skipping the simplification if isIntDivCheap(). When div is not cheap,
  3891. // combine will not return a DIVREM. Regardless, checking cheapness here
  3892. // makes sense since the simplification results in fatter code.
  3893. if (DAG.isKnownNeverZero(N1) && !TLI.isIntDivCheap(VT, Attr)) {
  3894. SDValue OptimizedDiv =
  3895. isSigned ? visitSDIVLike(N0, N1, N) : visitUDIVLike(N0, N1, N);
  3896. if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != N) {
  3897. // If the equivalent Div node also exists, update its users.
  3898. unsigned DivOpcode = isSigned ? ISD::SDIV : ISD::UDIV;
  3899. if (SDNode *DivNode = DAG.getNodeIfExists(DivOpcode, N->getVTList(),
  3900. { N0, N1 }))
  3901. CombineTo(DivNode, OptimizedDiv);
  3902. SDValue Mul = DAG.getNode(ISD::MUL, DL, VT, OptimizedDiv, N1);
  3903. SDValue Sub = DAG.getNode(ISD::SUB, DL, VT, N0, Mul);
  3904. AddToWorklist(OptimizedDiv.getNode());
  3905. AddToWorklist(Mul.getNode());
  3906. return Sub;
  3907. }
  3908. }
  3909. // sdiv, srem -> sdivrem
  3910. if (SDValue DivRem = useDivRem(N))
  3911. return DivRem.getValue(1);
  3912. return SDValue();
  3913. }
  3914. SDValue DAGCombiner::visitMULHS(SDNode *N) {
  3915. SDValue N0 = N->getOperand(0);
  3916. SDValue N1 = N->getOperand(1);
  3917. EVT VT = N->getValueType(0);
  3918. SDLoc DL(N);
  3919. // fold (mulhs c1, c2)
  3920. if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHS, DL, VT, {N0, N1}))
  3921. return C;
  3922. // canonicalize constant to RHS.
  3923. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  3924. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  3925. return DAG.getNode(ISD::MULHS, DL, N->getVTList(), N1, N0);
  3926. if (VT.isVector()) {
  3927. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  3928. return FoldedVOp;
  3929. // fold (mulhs x, 0) -> 0
  3930. // do not return N1, because undef node may exist.
  3931. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  3932. return DAG.getConstant(0, DL, VT);
  3933. }
  3934. // fold (mulhs x, 0) -> 0
  3935. if (isNullConstant(N1))
  3936. return N1;
  3937. // fold (mulhs x, 1) -> (sra x, size(x)-1)
  3938. if (isOneConstant(N1))
  3939. return DAG.getNode(ISD::SRA, DL, N0.getValueType(), N0,
  3940. DAG.getConstant(N0.getScalarValueSizeInBits() - 1, DL,
  3941. getShiftAmountTy(N0.getValueType())));
  3942. // fold (mulhs x, undef) -> 0
  3943. if (N0.isUndef() || N1.isUndef())
  3944. return DAG.getConstant(0, DL, VT);
  3945. // If the type twice as wide is legal, transform the mulhs to a wider multiply
  3946. // plus a shift.
  3947. if (!TLI.isOperationLegalOrCustom(ISD::MULHS, VT) && VT.isSimple() &&
  3948. !VT.isVector()) {
  3949. MVT Simple = VT.getSimpleVT();
  3950. unsigned SimpleSize = Simple.getSizeInBits();
  3951. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
  3952. if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
  3953. N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
  3954. N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
  3955. N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
  3956. N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
  3957. DAG.getConstant(SimpleSize, DL,
  3958. getShiftAmountTy(N1.getValueType())));
  3959. return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
  3960. }
  3961. }
  3962. return SDValue();
  3963. }
  3964. SDValue DAGCombiner::visitMULHU(SDNode *N) {
  3965. SDValue N0 = N->getOperand(0);
  3966. SDValue N1 = N->getOperand(1);
  3967. EVT VT = N->getValueType(0);
  3968. SDLoc DL(N);
  3969. // fold (mulhu c1, c2)
  3970. if (SDValue C = DAG.FoldConstantArithmetic(ISD::MULHU, DL, VT, {N0, N1}))
  3971. return C;
  3972. // canonicalize constant to RHS.
  3973. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  3974. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  3975. return DAG.getNode(ISD::MULHU, DL, N->getVTList(), N1, N0);
  3976. if (VT.isVector()) {
  3977. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  3978. return FoldedVOp;
  3979. // fold (mulhu x, 0) -> 0
  3980. // do not return N1, because undef node may exist.
  3981. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  3982. return DAG.getConstant(0, DL, VT);
  3983. }
  3984. // fold (mulhu x, 0) -> 0
  3985. if (isNullConstant(N1))
  3986. return N1;
  3987. // fold (mulhu x, 1) -> 0
  3988. if (isOneConstant(N1))
  3989. return DAG.getConstant(0, DL, N0.getValueType());
  3990. // fold (mulhu x, undef) -> 0
  3991. if (N0.isUndef() || N1.isUndef())
  3992. return DAG.getConstant(0, DL, VT);
  3993. // fold (mulhu x, (1 << c)) -> x >> (bitwidth - c)
  3994. if (isConstantOrConstantVector(N1, /*NoOpaques*/ true) &&
  3995. DAG.isKnownToBeAPowerOfTwo(N1) && hasOperation(ISD::SRL, VT)) {
  3996. unsigned NumEltBits = VT.getScalarSizeInBits();
  3997. SDValue LogBase2 = BuildLogBase2(N1, DL);
  3998. SDValue SRLAmt = DAG.getNode(
  3999. ISD::SUB, DL, VT, DAG.getConstant(NumEltBits, DL, VT), LogBase2);
  4000. EVT ShiftVT = getShiftAmountTy(N0.getValueType());
  4001. SDValue Trunc = DAG.getZExtOrTrunc(SRLAmt, DL, ShiftVT);
  4002. return DAG.getNode(ISD::SRL, DL, VT, N0, Trunc);
  4003. }
  4004. // If the type twice as wide is legal, transform the mulhu to a wider multiply
  4005. // plus a shift.
  4006. if (!TLI.isOperationLegalOrCustom(ISD::MULHU, VT) && VT.isSimple() &&
  4007. !VT.isVector()) {
  4008. MVT Simple = VT.getSimpleVT();
  4009. unsigned SimpleSize = Simple.getSizeInBits();
  4010. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
  4011. if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
  4012. N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
  4013. N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
  4014. N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
  4015. N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
  4016. DAG.getConstant(SimpleSize, DL,
  4017. getShiftAmountTy(N1.getValueType())));
  4018. return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
  4019. }
  4020. }
  4021. // Simplify the operands using demanded-bits information.
  4022. // We don't have demanded bits support for MULHU so this just enables constant
  4023. // folding based on known bits.
  4024. if (SimplifyDemandedBits(SDValue(N, 0)))
  4025. return SDValue(N, 0);
  4026. return SDValue();
  4027. }
  4028. /// Perform optimizations common to nodes that compute two values. LoOp and HiOp
  4029. /// give the opcodes for the two computations that are being performed. Return
  4030. /// true if a simplification was made.
  4031. SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
  4032. unsigned HiOp) {
  4033. // If the high half is not needed, just compute the low half.
  4034. bool HiExists = N->hasAnyUseOfValue(1);
  4035. if (!HiExists && (!LegalOperations ||
  4036. TLI.isOperationLegalOrCustom(LoOp, N->getValueType(0)))) {
  4037. SDValue Res = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
  4038. return CombineTo(N, Res, Res);
  4039. }
  4040. // If the low half is not needed, just compute the high half.
  4041. bool LoExists = N->hasAnyUseOfValue(0);
  4042. if (!LoExists && (!LegalOperations ||
  4043. TLI.isOperationLegalOrCustom(HiOp, N->getValueType(1)))) {
  4044. SDValue Res = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
  4045. return CombineTo(N, Res, Res);
  4046. }
  4047. // If both halves are used, return as it is.
  4048. if (LoExists && HiExists)
  4049. return SDValue();
  4050. // If the two computed results can be simplified separately, separate them.
  4051. if (LoExists) {
  4052. SDValue Lo = DAG.getNode(LoOp, SDLoc(N), N->getValueType(0), N->ops());
  4053. AddToWorklist(Lo.getNode());
  4054. SDValue LoOpt = combine(Lo.getNode());
  4055. if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
  4056. (!LegalOperations ||
  4057. TLI.isOperationLegalOrCustom(LoOpt.getOpcode(), LoOpt.getValueType())))
  4058. return CombineTo(N, LoOpt, LoOpt);
  4059. }
  4060. if (HiExists) {
  4061. SDValue Hi = DAG.getNode(HiOp, SDLoc(N), N->getValueType(1), N->ops());
  4062. AddToWorklist(Hi.getNode());
  4063. SDValue HiOpt = combine(Hi.getNode());
  4064. if (HiOpt.getNode() && HiOpt != Hi &&
  4065. (!LegalOperations ||
  4066. TLI.isOperationLegalOrCustom(HiOpt.getOpcode(), HiOpt.getValueType())))
  4067. return CombineTo(N, HiOpt, HiOpt);
  4068. }
  4069. return SDValue();
  4070. }
  4071. SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
  4072. if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS))
  4073. return Res;
  4074. EVT VT = N->getValueType(0);
  4075. SDLoc DL(N);
  4076. // If the type is twice as wide is legal, transform the mulhu to a wider
  4077. // multiply plus a shift.
  4078. if (VT.isSimple() && !VT.isVector()) {
  4079. MVT Simple = VT.getSimpleVT();
  4080. unsigned SimpleSize = Simple.getSizeInBits();
  4081. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
  4082. if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
  4083. SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
  4084. SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
  4085. Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
  4086. // Compute the high part as N1.
  4087. Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
  4088. DAG.getConstant(SimpleSize, DL,
  4089. getShiftAmountTy(Lo.getValueType())));
  4090. Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
  4091. // Compute the low part as N0.
  4092. Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
  4093. return CombineTo(N, Lo, Hi);
  4094. }
  4095. }
  4096. return SDValue();
  4097. }
  4098. SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
  4099. if (SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU))
  4100. return Res;
  4101. EVT VT = N->getValueType(0);
  4102. SDLoc DL(N);
  4103. // (umul_lohi N0, 0) -> (0, 0)
  4104. if (isNullConstant(N->getOperand(1))) {
  4105. SDValue Zero = DAG.getConstant(0, DL, VT);
  4106. return CombineTo(N, Zero, Zero);
  4107. }
  4108. // (umul_lohi N0, 1) -> (N0, 0)
  4109. if (isOneConstant(N->getOperand(1))) {
  4110. SDValue Zero = DAG.getConstant(0, DL, VT);
  4111. return CombineTo(N, N->getOperand(0), Zero);
  4112. }
  4113. // If the type is twice as wide is legal, transform the mulhu to a wider
  4114. // multiply plus a shift.
  4115. if (VT.isSimple() && !VT.isVector()) {
  4116. MVT Simple = VT.getSimpleVT();
  4117. unsigned SimpleSize = Simple.getSizeInBits();
  4118. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
  4119. if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
  4120. SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
  4121. SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
  4122. Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
  4123. // Compute the high part as N1.
  4124. Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
  4125. DAG.getConstant(SimpleSize, DL,
  4126. getShiftAmountTy(Lo.getValueType())));
  4127. Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
  4128. // Compute the low part as N0.
  4129. Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
  4130. return CombineTo(N, Lo, Hi);
  4131. }
  4132. }
  4133. return SDValue();
  4134. }
  4135. SDValue DAGCombiner::visitMULO(SDNode *N) {
  4136. SDValue N0 = N->getOperand(0);
  4137. SDValue N1 = N->getOperand(1);
  4138. EVT VT = N0.getValueType();
  4139. bool IsSigned = (ISD::SMULO == N->getOpcode());
  4140. EVT CarryVT = N->getValueType(1);
  4141. SDLoc DL(N);
  4142. ConstantSDNode *N0C = isConstOrConstSplat(N0);
  4143. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  4144. // fold operation with constant operands.
  4145. // TODO: Move this to FoldConstantArithmetic when it supports nodes with
  4146. // multiple results.
  4147. if (N0C && N1C) {
  4148. bool Overflow;
  4149. APInt Result =
  4150. IsSigned ? N0C->getAPIntValue().smul_ov(N1C->getAPIntValue(), Overflow)
  4151. : N0C->getAPIntValue().umul_ov(N1C->getAPIntValue(), Overflow);
  4152. return CombineTo(N, DAG.getConstant(Result, DL, VT),
  4153. DAG.getBoolConstant(Overflow, DL, CarryVT, CarryVT));
  4154. }
  4155. // canonicalize constant to RHS.
  4156. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  4157. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  4158. return DAG.getNode(N->getOpcode(), DL, N->getVTList(), N1, N0);
  4159. // fold (mulo x, 0) -> 0 + no carry out
  4160. if (isNullOrNullSplat(N1))
  4161. return CombineTo(N, DAG.getConstant(0, DL, VT),
  4162. DAG.getConstant(0, DL, CarryVT));
  4163. // (mulo x, 2) -> (addo x, x)
  4164. if (N1C && N1C->getAPIntValue() == 2)
  4165. return DAG.getNode(IsSigned ? ISD::SADDO : ISD::UADDO, DL,
  4166. N->getVTList(), N0, N0);
  4167. if (IsSigned) {
  4168. // A 1 bit SMULO overflows if both inputs are 1.
  4169. if (VT.getScalarSizeInBits() == 1) {
  4170. SDValue And = DAG.getNode(ISD::AND, DL, VT, N0, N1);
  4171. return CombineTo(N, And,
  4172. DAG.getSetCC(DL, CarryVT, And,
  4173. DAG.getConstant(0, DL, VT), ISD::SETNE));
  4174. }
  4175. // Multiplying n * m significant bits yields a result of n + m significant
  4176. // bits. If the total number of significant bits does not exceed the
  4177. // result bit width (minus 1), there is no overflow.
  4178. unsigned SignBits = DAG.ComputeNumSignBits(N0);
  4179. if (SignBits > 1)
  4180. SignBits += DAG.ComputeNumSignBits(N1);
  4181. if (SignBits > VT.getScalarSizeInBits() + 1)
  4182. return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1),
  4183. DAG.getConstant(0, DL, CarryVT));
  4184. } else {
  4185. KnownBits N1Known = DAG.computeKnownBits(N1);
  4186. KnownBits N0Known = DAG.computeKnownBits(N0);
  4187. bool Overflow;
  4188. (void)N0Known.getMaxValue().umul_ov(N1Known.getMaxValue(), Overflow);
  4189. if (!Overflow)
  4190. return CombineTo(N, DAG.getNode(ISD::MUL, DL, VT, N0, N1),
  4191. DAG.getConstant(0, DL, CarryVT));
  4192. }
  4193. return SDValue();
  4194. }
  4195. // Function to calculate whether the Min/Max pair of SDNodes (potentially
  4196. // swapped around) make a signed saturate pattern, clamping to between a signed
  4197. // saturate of -2^(BW-1) and 2^(BW-1)-1, or an unsigned saturate of 0 and 2^BW.
  4198. // Returns the node being clamped and the bitwidth of the clamp in BW. Should
  4199. // work with both SMIN/SMAX nodes and setcc/select combo. The operands are the
  4200. // same as SimplifySelectCC. N0<N1 ? N2 : N3.
  4201. static SDValue isSaturatingMinMax(SDValue N0, SDValue N1, SDValue N2,
  4202. SDValue N3, ISD::CondCode CC, unsigned &BW,
  4203. bool &Unsigned) {
  4204. auto isSignedMinMax = [&](SDValue N0, SDValue N1, SDValue N2, SDValue N3,
  4205. ISD::CondCode CC) {
  4206. // The compare and select operand should be the same or the select operands
  4207. // should be truncated versions of the comparison.
  4208. if (N0 != N2 && (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0)))
  4209. return 0;
  4210. // The constants need to be the same or a truncated version of each other.
  4211. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  4212. ConstantSDNode *N3C = isConstOrConstSplat(N3);
  4213. if (!N1C || !N3C)
  4214. return 0;
  4215. const APInt &C1 = N1C->getAPIntValue();
  4216. const APInt &C2 = N3C->getAPIntValue();
  4217. if (C1.getBitWidth() < C2.getBitWidth() ||
  4218. C1 != C2.sextOrSelf(C1.getBitWidth()))
  4219. return 0;
  4220. return CC == ISD::SETLT ? ISD::SMIN : (CC == ISD::SETGT ? ISD::SMAX : 0);
  4221. };
  4222. // Check the initial value is a SMIN/SMAX equivalent.
  4223. unsigned Opcode0 = isSignedMinMax(N0, N1, N2, N3, CC);
  4224. if (!Opcode0)
  4225. return SDValue();
  4226. SDValue N00, N01, N02, N03;
  4227. ISD::CondCode N0CC;
  4228. switch (N0.getOpcode()) {
  4229. case ISD::SMIN:
  4230. case ISD::SMAX:
  4231. N00 = N02 = N0.getOperand(0);
  4232. N01 = N03 = N0.getOperand(1);
  4233. N0CC = N0.getOpcode() == ISD::SMIN ? ISD::SETLT : ISD::SETGT;
  4234. break;
  4235. case ISD::SELECT_CC:
  4236. N00 = N0.getOperand(0);
  4237. N01 = N0.getOperand(1);
  4238. N02 = N0.getOperand(2);
  4239. N03 = N0.getOperand(3);
  4240. N0CC = cast<CondCodeSDNode>(N0.getOperand(4))->get();
  4241. break;
  4242. case ISD::SELECT:
  4243. case ISD::VSELECT:
  4244. if (N0.getOperand(0).getOpcode() != ISD::SETCC)
  4245. return SDValue();
  4246. N00 = N0.getOperand(0).getOperand(0);
  4247. N01 = N0.getOperand(0).getOperand(1);
  4248. N02 = N0.getOperand(1);
  4249. N03 = N0.getOperand(2);
  4250. N0CC = cast<CondCodeSDNode>(N0.getOperand(0).getOperand(2))->get();
  4251. break;
  4252. default:
  4253. return SDValue();
  4254. }
  4255. unsigned Opcode1 = isSignedMinMax(N00, N01, N02, N03, N0CC);
  4256. if (!Opcode1 || Opcode0 == Opcode1)
  4257. return SDValue();
  4258. ConstantSDNode *MinCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N1 : N01);
  4259. ConstantSDNode *MaxCOp = isConstOrConstSplat(Opcode0 == ISD::SMIN ? N01 : N1);
  4260. if (!MinCOp || !MaxCOp || MinCOp->getValueType(0) != MaxCOp->getValueType(0))
  4261. return SDValue();
  4262. const APInt &MinC = MinCOp->getAPIntValue();
  4263. const APInt &MaxC = MaxCOp->getAPIntValue();
  4264. APInt MinCPlus1 = MinC + 1;
  4265. if (-MaxC == MinCPlus1 && MinCPlus1.isPowerOf2()) {
  4266. BW = MinCPlus1.exactLogBase2() + 1;
  4267. Unsigned = false;
  4268. return N02;
  4269. }
  4270. if (MaxC == 0 && MinCPlus1.isPowerOf2()) {
  4271. BW = MinCPlus1.exactLogBase2();
  4272. Unsigned = true;
  4273. return N02;
  4274. }
  4275. return SDValue();
  4276. }
  4277. static SDValue PerformMinMaxFpToSatCombine(SDValue N0, SDValue N1, SDValue N2,
  4278. SDValue N3, ISD::CondCode CC,
  4279. SelectionDAG &DAG) {
  4280. unsigned BW;
  4281. bool Unsigned;
  4282. SDValue Fp = isSaturatingMinMax(N0, N1, N2, N3, CC, BW, Unsigned);
  4283. if (!Fp || Fp.getOpcode() != ISD::FP_TO_SINT)
  4284. return SDValue();
  4285. EVT FPVT = Fp.getOperand(0).getValueType();
  4286. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), BW);
  4287. if (FPVT.isVector())
  4288. NewVT = EVT::getVectorVT(*DAG.getContext(), NewVT,
  4289. FPVT.getVectorElementCount());
  4290. unsigned NewOpc = Unsigned ? ISD::FP_TO_UINT_SAT : ISD::FP_TO_SINT_SAT;
  4291. if (!DAG.getTargetLoweringInfo().shouldConvertFpToSat(NewOpc, FPVT, NewVT))
  4292. return SDValue();
  4293. SDLoc DL(Fp);
  4294. SDValue Sat = DAG.getNode(NewOpc, DL, NewVT, Fp.getOperand(0),
  4295. DAG.getValueType(NewVT.getScalarType()));
  4296. return Unsigned ? DAG.getZExtOrTrunc(Sat, DL, N2->getValueType(0))
  4297. : DAG.getSExtOrTrunc(Sat, DL, N2->getValueType(0));
  4298. }
  4299. static SDValue PerformUMinFpToSatCombine(SDValue N0, SDValue N1, SDValue N2,
  4300. SDValue N3, ISD::CondCode CC,
  4301. SelectionDAG &DAG) {
  4302. // We are looking for UMIN(FPTOUI(X), (2^n)-1), which may have come via a
  4303. // select/vselect/select_cc. The two operands pairs for the select (N2/N3) may
  4304. // be truncated versions of the the setcc (N0/N1).
  4305. if ((N0 != N2 &&
  4306. (N2.getOpcode() != ISD::TRUNCATE || N0 != N2.getOperand(0))) ||
  4307. N0.getOpcode() != ISD::FP_TO_UINT || CC != ISD::SETULT)
  4308. return SDValue();
  4309. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  4310. ConstantSDNode *N3C = isConstOrConstSplat(N3);
  4311. if (!N1C || !N3C)
  4312. return SDValue();
  4313. const APInt &C1 = N1C->getAPIntValue();
  4314. const APInt &C3 = N3C->getAPIntValue();
  4315. if (!(C1 + 1).isPowerOf2() || C1.getBitWidth() < C3.getBitWidth() ||
  4316. C1 != C3.zextOrSelf(C1.getBitWidth()))
  4317. return SDValue();
  4318. unsigned BW = (C1 + 1).exactLogBase2();
  4319. EVT FPVT = N0.getOperand(0).getValueType();
  4320. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), BW);
  4321. if (FPVT.isVector())
  4322. NewVT = EVT::getVectorVT(*DAG.getContext(), NewVT,
  4323. FPVT.getVectorElementCount());
  4324. if (!DAG.getTargetLoweringInfo().shouldConvertFpToSat(ISD::FP_TO_UINT_SAT,
  4325. FPVT, NewVT))
  4326. return SDValue();
  4327. SDValue Sat =
  4328. DAG.getNode(ISD::FP_TO_UINT_SAT, SDLoc(N0), NewVT, N0.getOperand(0),
  4329. DAG.getValueType(NewVT.getScalarType()));
  4330. return DAG.getZExtOrTrunc(Sat, SDLoc(N0), N3.getValueType());
  4331. }
  4332. SDValue DAGCombiner::visitIMINMAX(SDNode *N) {
  4333. SDValue N0 = N->getOperand(0);
  4334. SDValue N1 = N->getOperand(1);
  4335. EVT VT = N0.getValueType();
  4336. unsigned Opcode = N->getOpcode();
  4337. SDLoc DL(N);
  4338. // fold operation with constant operands.
  4339. if (SDValue C = DAG.FoldConstantArithmetic(Opcode, DL, VT, {N0, N1}))
  4340. return C;
  4341. // canonicalize constant to RHS
  4342. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  4343. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  4344. return DAG.getNode(Opcode, DL, VT, N1, N0);
  4345. // fold vector ops
  4346. if (VT.isVector())
  4347. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  4348. return FoldedVOp;
  4349. // Is sign bits are zero, flip between UMIN/UMAX and SMIN/SMAX.
  4350. // Only do this if the current op isn't legal and the flipped is.
  4351. if (!TLI.isOperationLegal(Opcode, VT) &&
  4352. (N0.isUndef() || DAG.SignBitIsZero(N0)) &&
  4353. (N1.isUndef() || DAG.SignBitIsZero(N1))) {
  4354. unsigned AltOpcode;
  4355. switch (Opcode) {
  4356. case ISD::SMIN: AltOpcode = ISD::UMIN; break;
  4357. case ISD::SMAX: AltOpcode = ISD::UMAX; break;
  4358. case ISD::UMIN: AltOpcode = ISD::SMIN; break;
  4359. case ISD::UMAX: AltOpcode = ISD::SMAX; break;
  4360. default: llvm_unreachable("Unknown MINMAX opcode");
  4361. }
  4362. if (TLI.isOperationLegal(AltOpcode, VT))
  4363. return DAG.getNode(AltOpcode, DL, VT, N0, N1);
  4364. }
  4365. if (Opcode == ISD::SMIN || Opcode == ISD::SMAX)
  4366. if (SDValue S = PerformMinMaxFpToSatCombine(
  4367. N0, N1, N0, N1, Opcode == ISD::SMIN ? ISD::SETLT : ISD::SETGT, DAG))
  4368. return S;
  4369. if (Opcode == ISD::UMIN)
  4370. if (SDValue S = PerformUMinFpToSatCombine(N0, N1, N0, N1, ISD::SETULT, DAG))
  4371. return S;
  4372. // Simplify the operands using demanded-bits information.
  4373. if (SimplifyDemandedBits(SDValue(N, 0)))
  4374. return SDValue(N, 0);
  4375. return SDValue();
  4376. }
  4377. /// If this is a bitwise logic instruction and both operands have the same
  4378. /// opcode, try to sink the other opcode after the logic instruction.
  4379. SDValue DAGCombiner::hoistLogicOpWithSameOpcodeHands(SDNode *N) {
  4380. SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
  4381. EVT VT = N0.getValueType();
  4382. unsigned LogicOpcode = N->getOpcode();
  4383. unsigned HandOpcode = N0.getOpcode();
  4384. assert((LogicOpcode == ISD::AND || LogicOpcode == ISD::OR ||
  4385. LogicOpcode == ISD::XOR) && "Expected logic opcode");
  4386. assert(HandOpcode == N1.getOpcode() && "Bad input!");
  4387. // Bail early if none of these transforms apply.
  4388. if (N0.getNumOperands() == 0)
  4389. return SDValue();
  4390. // FIXME: We should check number of uses of the operands to not increase
  4391. // the instruction count for all transforms.
  4392. // Handle size-changing casts.
  4393. SDValue X = N0.getOperand(0);
  4394. SDValue Y = N1.getOperand(0);
  4395. EVT XVT = X.getValueType();
  4396. SDLoc DL(N);
  4397. if (HandOpcode == ISD::ANY_EXTEND || HandOpcode == ISD::ZERO_EXTEND ||
  4398. HandOpcode == ISD::SIGN_EXTEND) {
  4399. // If both operands have other uses, this transform would create extra
  4400. // instructions without eliminating anything.
  4401. if (!N0.hasOneUse() && !N1.hasOneUse())
  4402. return SDValue();
  4403. // We need matching integer source types.
  4404. if (XVT != Y.getValueType())
  4405. return SDValue();
  4406. // Don't create an illegal op during or after legalization. Don't ever
  4407. // create an unsupported vector op.
  4408. if ((VT.isVector() || LegalOperations) &&
  4409. !TLI.isOperationLegalOrCustom(LogicOpcode, XVT))
  4410. return SDValue();
  4411. // Avoid infinite looping with PromoteIntBinOp.
  4412. // TODO: Should we apply desirable/legal constraints to all opcodes?
  4413. if (HandOpcode == ISD::ANY_EXTEND && LegalTypes &&
  4414. !TLI.isTypeDesirableForOp(LogicOpcode, XVT))
  4415. return SDValue();
  4416. // logic_op (hand_op X), (hand_op Y) --> hand_op (logic_op X, Y)
  4417. SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
  4418. return DAG.getNode(HandOpcode, DL, VT, Logic);
  4419. }
  4420. // logic_op (truncate x), (truncate y) --> truncate (logic_op x, y)
  4421. if (HandOpcode == ISD::TRUNCATE) {
  4422. // If both operands have other uses, this transform would create extra
  4423. // instructions without eliminating anything.
  4424. if (!N0.hasOneUse() && !N1.hasOneUse())
  4425. return SDValue();
  4426. // We need matching source types.
  4427. if (XVT != Y.getValueType())
  4428. return SDValue();
  4429. // Don't create an illegal op during or after legalization.
  4430. if (LegalOperations && !TLI.isOperationLegal(LogicOpcode, XVT))
  4431. return SDValue();
  4432. // Be extra careful sinking truncate. If it's free, there's no benefit in
  4433. // widening a binop. Also, don't create a logic op on an illegal type.
  4434. if (TLI.isZExtFree(VT, XVT) && TLI.isTruncateFree(XVT, VT))
  4435. return SDValue();
  4436. if (!TLI.isTypeLegal(XVT))
  4437. return SDValue();
  4438. SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
  4439. return DAG.getNode(HandOpcode, DL, VT, Logic);
  4440. }
  4441. // For binops SHL/SRL/SRA/AND:
  4442. // logic_op (OP x, z), (OP y, z) --> OP (logic_op x, y), z
  4443. if ((HandOpcode == ISD::SHL || HandOpcode == ISD::SRL ||
  4444. HandOpcode == ISD::SRA || HandOpcode == ISD::AND) &&
  4445. N0.getOperand(1) == N1.getOperand(1)) {
  4446. // If either operand has other uses, this transform is not an improvement.
  4447. if (!N0.hasOneUse() || !N1.hasOneUse())
  4448. return SDValue();
  4449. SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
  4450. return DAG.getNode(HandOpcode, DL, VT, Logic, N0.getOperand(1));
  4451. }
  4452. // Unary ops: logic_op (bswap x), (bswap y) --> bswap (logic_op x, y)
  4453. if (HandOpcode == ISD::BSWAP) {
  4454. // If either operand has other uses, this transform is not an improvement.
  4455. if (!N0.hasOneUse() || !N1.hasOneUse())
  4456. return SDValue();
  4457. SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
  4458. return DAG.getNode(HandOpcode, DL, VT, Logic);
  4459. }
  4460. // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
  4461. // Only perform this optimization up until type legalization, before
  4462. // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
  4463. // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
  4464. // we don't want to undo this promotion.
  4465. // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
  4466. // on scalars.
  4467. if ((HandOpcode == ISD::BITCAST || HandOpcode == ISD::SCALAR_TO_VECTOR) &&
  4468. Level <= AfterLegalizeTypes) {
  4469. // Input types must be integer and the same.
  4470. if (XVT.isInteger() && XVT == Y.getValueType() &&
  4471. !(VT.isVector() && TLI.isTypeLegal(VT) &&
  4472. !XVT.isVector() && !TLI.isTypeLegal(XVT))) {
  4473. SDValue Logic = DAG.getNode(LogicOpcode, DL, XVT, X, Y);
  4474. return DAG.getNode(HandOpcode, DL, VT, Logic);
  4475. }
  4476. }
  4477. // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
  4478. // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
  4479. // If both shuffles use the same mask, and both shuffle within a single
  4480. // vector, then it is worthwhile to move the swizzle after the operation.
  4481. // The type-legalizer generates this pattern when loading illegal
  4482. // vector types from memory. In many cases this allows additional shuffle
  4483. // optimizations.
  4484. // There are other cases where moving the shuffle after the xor/and/or
  4485. // is profitable even if shuffles don't perform a swizzle.
  4486. // If both shuffles use the same mask, and both shuffles have the same first
  4487. // or second operand, then it might still be profitable to move the shuffle
  4488. // after the xor/and/or operation.
  4489. if (HandOpcode == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG) {
  4490. auto *SVN0 = cast<ShuffleVectorSDNode>(N0);
  4491. auto *SVN1 = cast<ShuffleVectorSDNode>(N1);
  4492. assert(X.getValueType() == Y.getValueType() &&
  4493. "Inputs to shuffles are not the same type");
  4494. // Check that both shuffles use the same mask. The masks are known to be of
  4495. // the same length because the result vector type is the same.
  4496. // Check also that shuffles have only one use to avoid introducing extra
  4497. // instructions.
  4498. if (!SVN0->hasOneUse() || !SVN1->hasOneUse() ||
  4499. !SVN0->getMask().equals(SVN1->getMask()))
  4500. return SDValue();
  4501. // Don't try to fold this node if it requires introducing a
  4502. // build vector of all zeros that might be illegal at this stage.
  4503. SDValue ShOp = N0.getOperand(1);
  4504. if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
  4505. ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
  4506. // (logic_op (shuf (A, C), shuf (B, C))) --> shuf (logic_op (A, B), C)
  4507. if (N0.getOperand(1) == N1.getOperand(1) && ShOp.getNode()) {
  4508. SDValue Logic = DAG.getNode(LogicOpcode, DL, VT,
  4509. N0.getOperand(0), N1.getOperand(0));
  4510. return DAG.getVectorShuffle(VT, DL, Logic, ShOp, SVN0->getMask());
  4511. }
  4512. // Don't try to fold this node if it requires introducing a
  4513. // build vector of all zeros that might be illegal at this stage.
  4514. ShOp = N0.getOperand(0);
  4515. if (LogicOpcode == ISD::XOR && !ShOp.isUndef())
  4516. ShOp = tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
  4517. // (logic_op (shuf (C, A), shuf (C, B))) --> shuf (C, logic_op (A, B))
  4518. if (N0.getOperand(0) == N1.getOperand(0) && ShOp.getNode()) {
  4519. SDValue Logic = DAG.getNode(LogicOpcode, DL, VT, N0.getOperand(1),
  4520. N1.getOperand(1));
  4521. return DAG.getVectorShuffle(VT, DL, ShOp, Logic, SVN0->getMask());
  4522. }
  4523. }
  4524. return SDValue();
  4525. }
  4526. /// Try to make (and/or setcc (LL, LR), setcc (RL, RR)) more efficient.
  4527. SDValue DAGCombiner::foldLogicOfSetCCs(bool IsAnd, SDValue N0, SDValue N1,
  4528. const SDLoc &DL) {
  4529. SDValue LL, LR, RL, RR, N0CC, N1CC;
  4530. if (!isSetCCEquivalent(N0, LL, LR, N0CC) ||
  4531. !isSetCCEquivalent(N1, RL, RR, N1CC))
  4532. return SDValue();
  4533. assert(N0.getValueType() == N1.getValueType() &&
  4534. "Unexpected operand types for bitwise logic op");
  4535. assert(LL.getValueType() == LR.getValueType() &&
  4536. RL.getValueType() == RR.getValueType() &&
  4537. "Unexpected operand types for setcc");
  4538. // If we're here post-legalization or the logic op type is not i1, the logic
  4539. // op type must match a setcc result type. Also, all folds require new
  4540. // operations on the left and right operands, so those types must match.
  4541. EVT VT = N0.getValueType();
  4542. EVT OpVT = LL.getValueType();
  4543. if (LegalOperations || VT.getScalarType() != MVT::i1)
  4544. if (VT != getSetCCResultType(OpVT))
  4545. return SDValue();
  4546. if (OpVT != RL.getValueType())
  4547. return SDValue();
  4548. ISD::CondCode CC0 = cast<CondCodeSDNode>(N0CC)->get();
  4549. ISD::CondCode CC1 = cast<CondCodeSDNode>(N1CC)->get();
  4550. bool IsInteger = OpVT.isInteger();
  4551. if (LR == RR && CC0 == CC1 && IsInteger) {
  4552. bool IsZero = isNullOrNullSplat(LR);
  4553. bool IsNeg1 = isAllOnesOrAllOnesSplat(LR);
  4554. // All bits clear?
  4555. bool AndEqZero = IsAnd && CC1 == ISD::SETEQ && IsZero;
  4556. // All sign bits clear?
  4557. bool AndGtNeg1 = IsAnd && CC1 == ISD::SETGT && IsNeg1;
  4558. // Any bits set?
  4559. bool OrNeZero = !IsAnd && CC1 == ISD::SETNE && IsZero;
  4560. // Any sign bits set?
  4561. bool OrLtZero = !IsAnd && CC1 == ISD::SETLT && IsZero;
  4562. // (and (seteq X, 0), (seteq Y, 0)) --> (seteq (or X, Y), 0)
  4563. // (and (setgt X, -1), (setgt Y, -1)) --> (setgt (or X, Y), -1)
  4564. // (or (setne X, 0), (setne Y, 0)) --> (setne (or X, Y), 0)
  4565. // (or (setlt X, 0), (setlt Y, 0)) --> (setlt (or X, Y), 0)
  4566. if (AndEqZero || AndGtNeg1 || OrNeZero || OrLtZero) {
  4567. SDValue Or = DAG.getNode(ISD::OR, SDLoc(N0), OpVT, LL, RL);
  4568. AddToWorklist(Or.getNode());
  4569. return DAG.getSetCC(DL, VT, Or, LR, CC1);
  4570. }
  4571. // All bits set?
  4572. bool AndEqNeg1 = IsAnd && CC1 == ISD::SETEQ && IsNeg1;
  4573. // All sign bits set?
  4574. bool AndLtZero = IsAnd && CC1 == ISD::SETLT && IsZero;
  4575. // Any bits clear?
  4576. bool OrNeNeg1 = !IsAnd && CC1 == ISD::SETNE && IsNeg1;
  4577. // Any sign bits clear?
  4578. bool OrGtNeg1 = !IsAnd && CC1 == ISD::SETGT && IsNeg1;
  4579. // (and (seteq X, -1), (seteq Y, -1)) --> (seteq (and X, Y), -1)
  4580. // (and (setlt X, 0), (setlt Y, 0)) --> (setlt (and X, Y), 0)
  4581. // (or (setne X, -1), (setne Y, -1)) --> (setne (and X, Y), -1)
  4582. // (or (setgt X, -1), (setgt Y -1)) --> (setgt (and X, Y), -1)
  4583. if (AndEqNeg1 || AndLtZero || OrNeNeg1 || OrGtNeg1) {
  4584. SDValue And = DAG.getNode(ISD::AND, SDLoc(N0), OpVT, LL, RL);
  4585. AddToWorklist(And.getNode());
  4586. return DAG.getSetCC(DL, VT, And, LR, CC1);
  4587. }
  4588. }
  4589. // TODO: What is the 'or' equivalent of this fold?
  4590. // (and (setne X, 0), (setne X, -1)) --> (setuge (add X, 1), 2)
  4591. if (IsAnd && LL == RL && CC0 == CC1 && OpVT.getScalarSizeInBits() > 1 &&
  4592. IsInteger && CC0 == ISD::SETNE &&
  4593. ((isNullConstant(LR) && isAllOnesConstant(RR)) ||
  4594. (isAllOnesConstant(LR) && isNullConstant(RR)))) {
  4595. SDValue One = DAG.getConstant(1, DL, OpVT);
  4596. SDValue Two = DAG.getConstant(2, DL, OpVT);
  4597. SDValue Add = DAG.getNode(ISD::ADD, SDLoc(N0), OpVT, LL, One);
  4598. AddToWorklist(Add.getNode());
  4599. return DAG.getSetCC(DL, VT, Add, Two, ISD::SETUGE);
  4600. }
  4601. // Try more general transforms if the predicates match and the only user of
  4602. // the compares is the 'and' or 'or'.
  4603. if (IsInteger && TLI.convertSetCCLogicToBitwiseLogic(OpVT) && CC0 == CC1 &&
  4604. N0.hasOneUse() && N1.hasOneUse()) {
  4605. // and (seteq A, B), (seteq C, D) --> seteq (or (xor A, B), (xor C, D)), 0
  4606. // or (setne A, B), (setne C, D) --> setne (or (xor A, B), (xor C, D)), 0
  4607. if ((IsAnd && CC1 == ISD::SETEQ) || (!IsAnd && CC1 == ISD::SETNE)) {
  4608. SDValue XorL = DAG.getNode(ISD::XOR, SDLoc(N0), OpVT, LL, LR);
  4609. SDValue XorR = DAG.getNode(ISD::XOR, SDLoc(N1), OpVT, RL, RR);
  4610. SDValue Or = DAG.getNode(ISD::OR, DL, OpVT, XorL, XorR);
  4611. SDValue Zero = DAG.getConstant(0, DL, OpVT);
  4612. return DAG.getSetCC(DL, VT, Or, Zero, CC1);
  4613. }
  4614. // Turn compare of constants whose difference is 1 bit into add+and+setcc.
  4615. // TODO - support non-uniform vector amounts.
  4616. if ((IsAnd && CC1 == ISD::SETNE) || (!IsAnd && CC1 == ISD::SETEQ)) {
  4617. // Match a shared variable operand and 2 non-opaque constant operands.
  4618. ConstantSDNode *C0 = isConstOrConstSplat(LR);
  4619. ConstantSDNode *C1 = isConstOrConstSplat(RR);
  4620. if (LL == RL && C0 && C1 && !C0->isOpaque() && !C1->isOpaque()) {
  4621. const APInt &CMax =
  4622. APIntOps::umax(C0->getAPIntValue(), C1->getAPIntValue());
  4623. const APInt &CMin =
  4624. APIntOps::umin(C0->getAPIntValue(), C1->getAPIntValue());
  4625. // The difference of the constants must be a single bit.
  4626. if ((CMax - CMin).isPowerOf2()) {
  4627. // and/or (setcc X, CMax, ne), (setcc X, CMin, ne/eq) -->
  4628. // setcc ((sub X, CMin), ~(CMax - CMin)), 0, ne/eq
  4629. SDValue Max = DAG.getNode(ISD::UMAX, DL, OpVT, LR, RR);
  4630. SDValue Min = DAG.getNode(ISD::UMIN, DL, OpVT, LR, RR);
  4631. SDValue Offset = DAG.getNode(ISD::SUB, DL, OpVT, LL, Min);
  4632. SDValue Diff = DAG.getNode(ISD::SUB, DL, OpVT, Max, Min);
  4633. SDValue Mask = DAG.getNOT(DL, Diff, OpVT);
  4634. SDValue And = DAG.getNode(ISD::AND, DL, OpVT, Offset, Mask);
  4635. SDValue Zero = DAG.getConstant(0, DL, OpVT);
  4636. return DAG.getSetCC(DL, VT, And, Zero, CC0);
  4637. }
  4638. }
  4639. }
  4640. }
  4641. // Canonicalize equivalent operands to LL == RL.
  4642. if (LL == RR && LR == RL) {
  4643. CC1 = ISD::getSetCCSwappedOperands(CC1);
  4644. std::swap(RL, RR);
  4645. }
  4646. // (and (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
  4647. // (or (setcc X, Y, CC0), (setcc X, Y, CC1)) --> (setcc X, Y, NewCC)
  4648. if (LL == RL && LR == RR) {
  4649. ISD::CondCode NewCC = IsAnd ? ISD::getSetCCAndOperation(CC0, CC1, OpVT)
  4650. : ISD::getSetCCOrOperation(CC0, CC1, OpVT);
  4651. if (NewCC != ISD::SETCC_INVALID &&
  4652. (!LegalOperations ||
  4653. (TLI.isCondCodeLegal(NewCC, LL.getSimpleValueType()) &&
  4654. TLI.isOperationLegal(ISD::SETCC, OpVT))))
  4655. return DAG.getSetCC(DL, VT, LL, LR, NewCC);
  4656. }
  4657. return SDValue();
  4658. }
  4659. /// This contains all DAGCombine rules which reduce two values combined by
  4660. /// an And operation to a single value. This makes them reusable in the context
  4661. /// of visitSELECT(). Rules involving constants are not included as
  4662. /// visitSELECT() already handles those cases.
  4663. SDValue DAGCombiner::visitANDLike(SDValue N0, SDValue N1, SDNode *N) {
  4664. EVT VT = N1.getValueType();
  4665. SDLoc DL(N);
  4666. // fold (and x, undef) -> 0
  4667. if (N0.isUndef() || N1.isUndef())
  4668. return DAG.getConstant(0, DL, VT);
  4669. if (SDValue V = foldLogicOfSetCCs(true, N0, N1, DL))
  4670. return V;
  4671. // TODO: Rewrite this to return a new 'AND' instead of using CombineTo.
  4672. if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
  4673. VT.getSizeInBits() <= 64 && N0->hasOneUse()) {
  4674. if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
  4675. if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
  4676. // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
  4677. // immediate for an add, but it is legal if its top c2 bits are set,
  4678. // transform the ADD so the immediate doesn't need to be materialized
  4679. // in a register.
  4680. APInt ADDC = ADDI->getAPIntValue();
  4681. APInt SRLC = SRLI->getAPIntValue();
  4682. if (ADDC.getMinSignedBits() <= 64 &&
  4683. SRLC.ult(VT.getSizeInBits()) &&
  4684. !TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
  4685. APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
  4686. SRLC.getZExtValue());
  4687. if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
  4688. ADDC |= Mask;
  4689. if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
  4690. SDLoc DL0(N0);
  4691. SDValue NewAdd =
  4692. DAG.getNode(ISD::ADD, DL0, VT,
  4693. N0.getOperand(0), DAG.getConstant(ADDC, DL, VT));
  4694. CombineTo(N0.getNode(), NewAdd);
  4695. // Return N so it doesn't get rechecked!
  4696. return SDValue(N, 0);
  4697. }
  4698. }
  4699. }
  4700. }
  4701. }
  4702. }
  4703. // Reduce bit extract of low half of an integer to the narrower type.
  4704. // (and (srl i64:x, K), KMask) ->
  4705. // (i64 zero_extend (and (srl (i32 (trunc i64:x)), K)), KMask)
  4706. if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
  4707. if (ConstantSDNode *CAnd = dyn_cast<ConstantSDNode>(N1)) {
  4708. if (ConstantSDNode *CShift = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
  4709. unsigned Size = VT.getSizeInBits();
  4710. const APInt &AndMask = CAnd->getAPIntValue();
  4711. unsigned ShiftBits = CShift->getZExtValue();
  4712. // Bail out, this node will probably disappear anyway.
  4713. if (ShiftBits == 0)
  4714. return SDValue();
  4715. unsigned MaskBits = AndMask.countTrailingOnes();
  4716. EVT HalfVT = EVT::getIntegerVT(*DAG.getContext(), Size / 2);
  4717. if (AndMask.isMask() &&
  4718. // Required bits must not span the two halves of the integer and
  4719. // must fit in the half size type.
  4720. (ShiftBits + MaskBits <= Size / 2) &&
  4721. TLI.isNarrowingProfitable(VT, HalfVT) &&
  4722. TLI.isTypeDesirableForOp(ISD::AND, HalfVT) &&
  4723. TLI.isTypeDesirableForOp(ISD::SRL, HalfVT) &&
  4724. TLI.isTruncateFree(VT, HalfVT) &&
  4725. TLI.isZExtFree(HalfVT, VT)) {
  4726. // The isNarrowingProfitable is to avoid regressions on PPC and
  4727. // AArch64 which match a few 64-bit bit insert / bit extract patterns
  4728. // on downstream users of this. Those patterns could probably be
  4729. // extended to handle extensions mixed in.
  4730. SDValue SL(N0);
  4731. assert(MaskBits <= Size);
  4732. // Extracting the highest bit of the low half.
  4733. EVT ShiftVT = TLI.getShiftAmountTy(HalfVT, DAG.getDataLayout());
  4734. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, HalfVT,
  4735. N0.getOperand(0));
  4736. SDValue NewMask = DAG.getConstant(AndMask.trunc(Size / 2), SL, HalfVT);
  4737. SDValue ShiftK = DAG.getConstant(ShiftBits, SL, ShiftVT);
  4738. SDValue Shift = DAG.getNode(ISD::SRL, SL, HalfVT, Trunc, ShiftK);
  4739. SDValue And = DAG.getNode(ISD::AND, SL, HalfVT, Shift, NewMask);
  4740. return DAG.getNode(ISD::ZERO_EXTEND, SL, VT, And);
  4741. }
  4742. }
  4743. }
  4744. }
  4745. return SDValue();
  4746. }
  4747. bool DAGCombiner::isAndLoadExtLoad(ConstantSDNode *AndC, LoadSDNode *LoadN,
  4748. EVT LoadResultTy, EVT &ExtVT) {
  4749. if (!AndC->getAPIntValue().isMask())
  4750. return false;
  4751. unsigned ActiveBits = AndC->getAPIntValue().countTrailingOnes();
  4752. ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
  4753. EVT LoadedVT = LoadN->getMemoryVT();
  4754. if (ExtVT == LoadedVT &&
  4755. (!LegalOperations ||
  4756. TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))) {
  4757. // ZEXTLOAD will match without needing to change the size of the value being
  4758. // loaded.
  4759. return true;
  4760. }
  4761. // Do not change the width of a volatile or atomic loads.
  4762. if (!LoadN->isSimple())
  4763. return false;
  4764. // Do not generate loads of non-round integer types since these can
  4765. // be expensive (and would be wrong if the type is not byte sized).
  4766. if (!LoadedVT.bitsGT(ExtVT) || !ExtVT.isRound())
  4767. return false;
  4768. if (LegalOperations &&
  4769. !TLI.isLoadExtLegal(ISD::ZEXTLOAD, LoadResultTy, ExtVT))
  4770. return false;
  4771. if (!TLI.shouldReduceLoadWidth(LoadN, ISD::ZEXTLOAD, ExtVT))
  4772. return false;
  4773. return true;
  4774. }
  4775. bool DAGCombiner::isLegalNarrowLdSt(LSBaseSDNode *LDST,
  4776. ISD::LoadExtType ExtType, EVT &MemVT,
  4777. unsigned ShAmt) {
  4778. if (!LDST)
  4779. return false;
  4780. // Only allow byte offsets.
  4781. if (ShAmt % 8)
  4782. return false;
  4783. // Do not generate loads of non-round integer types since these can
  4784. // be expensive (and would be wrong if the type is not byte sized).
  4785. if (!MemVT.isRound())
  4786. return false;
  4787. // Don't change the width of a volatile or atomic loads.
  4788. if (!LDST->isSimple())
  4789. return false;
  4790. EVT LdStMemVT = LDST->getMemoryVT();
  4791. // Bail out when changing the scalable property, since we can't be sure that
  4792. // we're actually narrowing here.
  4793. if (LdStMemVT.isScalableVector() != MemVT.isScalableVector())
  4794. return false;
  4795. // Verify that we are actually reducing a load width here.
  4796. if (LdStMemVT.bitsLT(MemVT))
  4797. return false;
  4798. // Ensure that this isn't going to produce an unsupported memory access.
  4799. if (ShAmt) {
  4800. assert(ShAmt % 8 == 0 && "ShAmt is byte offset");
  4801. const unsigned ByteShAmt = ShAmt / 8;
  4802. const Align LDSTAlign = LDST->getAlign();
  4803. const Align NarrowAlign = commonAlignment(LDSTAlign, ByteShAmt);
  4804. if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
  4805. LDST->getAddressSpace(), NarrowAlign,
  4806. LDST->getMemOperand()->getFlags()))
  4807. return false;
  4808. }
  4809. // It's not possible to generate a constant of extended or untyped type.
  4810. EVT PtrType = LDST->getBasePtr().getValueType();
  4811. if (PtrType == MVT::Untyped || PtrType.isExtended())
  4812. return false;
  4813. if (isa<LoadSDNode>(LDST)) {
  4814. LoadSDNode *Load = cast<LoadSDNode>(LDST);
  4815. // Don't transform one with multiple uses, this would require adding a new
  4816. // load.
  4817. if (!SDValue(Load, 0).hasOneUse())
  4818. return false;
  4819. if (LegalOperations &&
  4820. !TLI.isLoadExtLegal(ExtType, Load->getValueType(0), MemVT))
  4821. return false;
  4822. // For the transform to be legal, the load must produce only two values
  4823. // (the value loaded and the chain). Don't transform a pre-increment
  4824. // load, for example, which produces an extra value. Otherwise the
  4825. // transformation is not equivalent, and the downstream logic to replace
  4826. // uses gets things wrong.
  4827. if (Load->getNumValues() > 2)
  4828. return false;
  4829. // If the load that we're shrinking is an extload and we're not just
  4830. // discarding the extension we can't simply shrink the load. Bail.
  4831. // TODO: It would be possible to merge the extensions in some cases.
  4832. if (Load->getExtensionType() != ISD::NON_EXTLOAD &&
  4833. Load->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
  4834. return false;
  4835. if (!TLI.shouldReduceLoadWidth(Load, ExtType, MemVT))
  4836. return false;
  4837. } else {
  4838. assert(isa<StoreSDNode>(LDST) && "It is not a Load nor a Store SDNode");
  4839. StoreSDNode *Store = cast<StoreSDNode>(LDST);
  4840. // Can't write outside the original store
  4841. if (Store->getMemoryVT().getSizeInBits() < MemVT.getSizeInBits() + ShAmt)
  4842. return false;
  4843. if (LegalOperations &&
  4844. !TLI.isTruncStoreLegal(Store->getValue().getValueType(), MemVT))
  4845. return false;
  4846. }
  4847. return true;
  4848. }
  4849. bool DAGCombiner::SearchForAndLoads(SDNode *N,
  4850. SmallVectorImpl<LoadSDNode*> &Loads,
  4851. SmallPtrSetImpl<SDNode*> &NodesWithConsts,
  4852. ConstantSDNode *Mask,
  4853. SDNode *&NodeToMask) {
  4854. // Recursively search for the operands, looking for loads which can be
  4855. // narrowed.
  4856. for (SDValue Op : N->op_values()) {
  4857. if (Op.getValueType().isVector())
  4858. return false;
  4859. // Some constants may need fixing up later if they are too large.
  4860. if (auto *C = dyn_cast<ConstantSDNode>(Op)) {
  4861. if ((N->getOpcode() == ISD::OR || N->getOpcode() == ISD::XOR) &&
  4862. (Mask->getAPIntValue() & C->getAPIntValue()) != C->getAPIntValue())
  4863. NodesWithConsts.insert(N);
  4864. continue;
  4865. }
  4866. if (!Op.hasOneUse())
  4867. return false;
  4868. switch(Op.getOpcode()) {
  4869. case ISD::LOAD: {
  4870. auto *Load = cast<LoadSDNode>(Op);
  4871. EVT ExtVT;
  4872. if (isAndLoadExtLoad(Mask, Load, Load->getValueType(0), ExtVT) &&
  4873. isLegalNarrowLdSt(Load, ISD::ZEXTLOAD, ExtVT)) {
  4874. // ZEXTLOAD is already small enough.
  4875. if (Load->getExtensionType() == ISD::ZEXTLOAD &&
  4876. ExtVT.bitsGE(Load->getMemoryVT()))
  4877. continue;
  4878. // Use LE to convert equal sized loads to zext.
  4879. if (ExtVT.bitsLE(Load->getMemoryVT()))
  4880. Loads.push_back(Load);
  4881. continue;
  4882. }
  4883. return false;
  4884. }
  4885. case ISD::ZERO_EXTEND:
  4886. case ISD::AssertZext: {
  4887. unsigned ActiveBits = Mask->getAPIntValue().countTrailingOnes();
  4888. EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
  4889. EVT VT = Op.getOpcode() == ISD::AssertZext ?
  4890. cast<VTSDNode>(Op.getOperand(1))->getVT() :
  4891. Op.getOperand(0).getValueType();
  4892. // We can accept extending nodes if the mask is wider or an equal
  4893. // width to the original type.
  4894. if (ExtVT.bitsGE(VT))
  4895. continue;
  4896. break;
  4897. }
  4898. case ISD::OR:
  4899. case ISD::XOR:
  4900. case ISD::AND:
  4901. if (!SearchForAndLoads(Op.getNode(), Loads, NodesWithConsts, Mask,
  4902. NodeToMask))
  4903. return false;
  4904. continue;
  4905. }
  4906. // Allow one node which will masked along with any loads found.
  4907. if (NodeToMask)
  4908. return false;
  4909. // Also ensure that the node to be masked only produces one data result.
  4910. NodeToMask = Op.getNode();
  4911. if (NodeToMask->getNumValues() > 1) {
  4912. bool HasValue = false;
  4913. for (unsigned i = 0, e = NodeToMask->getNumValues(); i < e; ++i) {
  4914. MVT VT = SDValue(NodeToMask, i).getSimpleValueType();
  4915. if (VT != MVT::Glue && VT != MVT::Other) {
  4916. if (HasValue) {
  4917. NodeToMask = nullptr;
  4918. return false;
  4919. }
  4920. HasValue = true;
  4921. }
  4922. }
  4923. assert(HasValue && "Node to be masked has no data result?");
  4924. }
  4925. }
  4926. return true;
  4927. }
  4928. bool DAGCombiner::BackwardsPropagateMask(SDNode *N) {
  4929. auto *Mask = dyn_cast<ConstantSDNode>(N->getOperand(1));
  4930. if (!Mask)
  4931. return false;
  4932. if (!Mask->getAPIntValue().isMask())
  4933. return false;
  4934. // No need to do anything if the and directly uses a load.
  4935. if (isa<LoadSDNode>(N->getOperand(0)))
  4936. return false;
  4937. SmallVector<LoadSDNode*, 8> Loads;
  4938. SmallPtrSet<SDNode*, 2> NodesWithConsts;
  4939. SDNode *FixupNode = nullptr;
  4940. if (SearchForAndLoads(N, Loads, NodesWithConsts, Mask, FixupNode)) {
  4941. if (Loads.size() == 0)
  4942. return false;
  4943. LLVM_DEBUG(dbgs() << "Backwards propagate AND: "; N->dump());
  4944. SDValue MaskOp = N->getOperand(1);
  4945. // If it exists, fixup the single node we allow in the tree that needs
  4946. // masking.
  4947. if (FixupNode) {
  4948. LLVM_DEBUG(dbgs() << "First, need to fix up: "; FixupNode->dump());
  4949. SDValue And = DAG.getNode(ISD::AND, SDLoc(FixupNode),
  4950. FixupNode->getValueType(0),
  4951. SDValue(FixupNode, 0), MaskOp);
  4952. DAG.ReplaceAllUsesOfValueWith(SDValue(FixupNode, 0), And);
  4953. if (And.getOpcode() == ISD ::AND)
  4954. DAG.UpdateNodeOperands(And.getNode(), SDValue(FixupNode, 0), MaskOp);
  4955. }
  4956. // Narrow any constants that need it.
  4957. for (auto *LogicN : NodesWithConsts) {
  4958. SDValue Op0 = LogicN->getOperand(0);
  4959. SDValue Op1 = LogicN->getOperand(1);
  4960. if (isa<ConstantSDNode>(Op0))
  4961. std::swap(Op0, Op1);
  4962. SDValue And = DAG.getNode(ISD::AND, SDLoc(Op1), Op1.getValueType(),
  4963. Op1, MaskOp);
  4964. DAG.UpdateNodeOperands(LogicN, Op0, And);
  4965. }
  4966. // Create narrow loads.
  4967. for (auto *Load : Loads) {
  4968. LLVM_DEBUG(dbgs() << "Propagate AND back to: "; Load->dump());
  4969. SDValue And = DAG.getNode(ISD::AND, SDLoc(Load), Load->getValueType(0),
  4970. SDValue(Load, 0), MaskOp);
  4971. DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), And);
  4972. if (And.getOpcode() == ISD ::AND)
  4973. And = SDValue(
  4974. DAG.UpdateNodeOperands(And.getNode(), SDValue(Load, 0), MaskOp), 0);
  4975. SDValue NewLoad = reduceLoadWidth(And.getNode());
  4976. assert(NewLoad &&
  4977. "Shouldn't be masking the load if it can't be narrowed");
  4978. CombineTo(Load, NewLoad, NewLoad.getValue(1));
  4979. }
  4980. DAG.ReplaceAllUsesWith(N, N->getOperand(0).getNode());
  4981. return true;
  4982. }
  4983. return false;
  4984. }
  4985. // Unfold
  4986. // x & (-1 'logical shift' y)
  4987. // To
  4988. // (x 'opposite logical shift' y) 'logical shift' y
  4989. // if it is better for performance.
  4990. SDValue DAGCombiner::unfoldExtremeBitClearingToShifts(SDNode *N) {
  4991. assert(N->getOpcode() == ISD::AND);
  4992. SDValue N0 = N->getOperand(0);
  4993. SDValue N1 = N->getOperand(1);
  4994. // Do we actually prefer shifts over mask?
  4995. if (!TLI.shouldFoldMaskToVariableShiftPair(N0))
  4996. return SDValue();
  4997. // Try to match (-1 '[outer] logical shift' y)
  4998. unsigned OuterShift;
  4999. unsigned InnerShift; // The opposite direction to the OuterShift.
  5000. SDValue Y; // Shift amount.
  5001. auto matchMask = [&OuterShift, &InnerShift, &Y](SDValue M) -> bool {
  5002. if (!M.hasOneUse())
  5003. return false;
  5004. OuterShift = M->getOpcode();
  5005. if (OuterShift == ISD::SHL)
  5006. InnerShift = ISD::SRL;
  5007. else if (OuterShift == ISD::SRL)
  5008. InnerShift = ISD::SHL;
  5009. else
  5010. return false;
  5011. if (!isAllOnesConstant(M->getOperand(0)))
  5012. return false;
  5013. Y = M->getOperand(1);
  5014. return true;
  5015. };
  5016. SDValue X;
  5017. if (matchMask(N1))
  5018. X = N0;
  5019. else if (matchMask(N0))
  5020. X = N1;
  5021. else
  5022. return SDValue();
  5023. SDLoc DL(N);
  5024. EVT VT = N->getValueType(0);
  5025. // tmp = x 'opposite logical shift' y
  5026. SDValue T0 = DAG.getNode(InnerShift, DL, VT, X, Y);
  5027. // ret = tmp 'logical shift' y
  5028. SDValue T1 = DAG.getNode(OuterShift, DL, VT, T0, Y);
  5029. return T1;
  5030. }
  5031. /// Try to replace shift/logic that tests if a bit is clear with mask + setcc.
  5032. /// For a target with a bit test, this is expected to become test + set and save
  5033. /// at least 1 instruction.
  5034. static SDValue combineShiftAnd1ToBitTest(SDNode *And, SelectionDAG &DAG) {
  5035. assert(And->getOpcode() == ISD::AND && "Expected an 'and' op");
  5036. // This is probably not worthwhile without a supported type.
  5037. EVT VT = And->getValueType(0);
  5038. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5039. if (!TLI.isTypeLegal(VT))
  5040. return SDValue();
  5041. // Look through an optional extension and find a 'not'.
  5042. // TODO: Should we favor test+set even without the 'not' op?
  5043. SDValue Not = And->getOperand(0), And1 = And->getOperand(1);
  5044. if (Not.getOpcode() == ISD::ANY_EXTEND)
  5045. Not = Not.getOperand(0);
  5046. if (!isBitwiseNot(Not) || !Not.hasOneUse() || !isOneConstant(And1))
  5047. return SDValue();
  5048. // Look though an optional truncation. The source operand may not be the same
  5049. // type as the original 'and', but that is ok because we are masking off
  5050. // everything but the low bit.
  5051. SDValue Srl = Not.getOperand(0);
  5052. if (Srl.getOpcode() == ISD::TRUNCATE)
  5053. Srl = Srl.getOperand(0);
  5054. // Match a shift-right by constant.
  5055. if (Srl.getOpcode() != ISD::SRL || !Srl.hasOneUse() ||
  5056. !isa<ConstantSDNode>(Srl.getOperand(1)))
  5057. return SDValue();
  5058. // We might have looked through casts that make this transform invalid.
  5059. // TODO: If the source type is wider than the result type, do the mask and
  5060. // compare in the source type.
  5061. const APInt &ShiftAmt = Srl.getConstantOperandAPInt(1);
  5062. unsigned VTBitWidth = VT.getSizeInBits();
  5063. if (ShiftAmt.uge(VTBitWidth))
  5064. return SDValue();
  5065. // Turn this into a bit-test pattern using mask op + setcc:
  5066. // and (not (srl X, C)), 1 --> (and X, 1<<C) == 0
  5067. SDLoc DL(And);
  5068. SDValue X = DAG.getZExtOrTrunc(Srl.getOperand(0), DL, VT);
  5069. EVT CCVT = TLI.getSetCCResultType(DAG.getDataLayout(), *DAG.getContext(), VT);
  5070. SDValue Mask = DAG.getConstant(
  5071. APInt::getOneBitSet(VTBitWidth, ShiftAmt.getZExtValue()), DL, VT);
  5072. SDValue NewAnd = DAG.getNode(ISD::AND, DL, VT, X, Mask);
  5073. SDValue Zero = DAG.getConstant(0, DL, VT);
  5074. SDValue Setcc = DAG.getSetCC(DL, CCVT, NewAnd, Zero, ISD::SETEQ);
  5075. return DAG.getZExtOrTrunc(Setcc, DL, VT);
  5076. }
  5077. /// For targets that support usubsat, match a bit-hack form of that operation
  5078. /// that ends in 'and' and convert it.
  5079. static SDValue foldAndToUsubsat(SDNode *N, SelectionDAG &DAG) {
  5080. SDValue N0 = N->getOperand(0);
  5081. SDValue N1 = N->getOperand(1);
  5082. EVT VT = N1.getValueType();
  5083. // Canonicalize SRA as operand 1.
  5084. if (N0.getOpcode() == ISD::SRA)
  5085. std::swap(N0, N1);
  5086. // xor/add with SMIN (signmask) are logically equivalent.
  5087. if (N0.getOpcode() != ISD::XOR && N0.getOpcode() != ISD::ADD)
  5088. return SDValue();
  5089. if (N1.getOpcode() != ISD::SRA || !N0.hasOneUse() || !N1.hasOneUse() ||
  5090. N0.getOperand(0) != N1.getOperand(0))
  5091. return SDValue();
  5092. unsigned BitWidth = VT.getScalarSizeInBits();
  5093. ConstantSDNode *XorC = isConstOrConstSplat(N0.getOperand(1), true);
  5094. ConstantSDNode *SraC = isConstOrConstSplat(N1.getOperand(1), true);
  5095. if (!XorC || !XorC->getAPIntValue().isSignMask() ||
  5096. !SraC || SraC->getAPIntValue() != BitWidth - 1)
  5097. return SDValue();
  5098. // (i8 X ^ 128) & (i8 X s>> 7) --> usubsat X, 128
  5099. // (i8 X + 128) & (i8 X s>> 7) --> usubsat X, 128
  5100. SDLoc DL(N);
  5101. SDValue SignMask = DAG.getConstant(XorC->getAPIntValue(), DL, VT);
  5102. return DAG.getNode(ISD::USUBSAT, DL, VT, N0.getOperand(0), SignMask);
  5103. }
  5104. SDValue DAGCombiner::visitAND(SDNode *N) {
  5105. SDValue N0 = N->getOperand(0);
  5106. SDValue N1 = N->getOperand(1);
  5107. EVT VT = N1.getValueType();
  5108. // x & x --> x
  5109. if (N0 == N1)
  5110. return N0;
  5111. // fold (and c1, c2) -> c1&c2
  5112. if (SDValue C = DAG.FoldConstantArithmetic(ISD::AND, SDLoc(N), VT, {N0, N1}))
  5113. return C;
  5114. // canonicalize constant to RHS
  5115. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  5116. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  5117. return DAG.getNode(ISD::AND, SDLoc(N), VT, N1, N0);
  5118. // fold vector ops
  5119. if (VT.isVector()) {
  5120. if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
  5121. return FoldedVOp;
  5122. // fold (and x, 0) -> 0, vector edition
  5123. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  5124. // do not return N1, because undef node may exist in N1
  5125. return DAG.getConstant(APInt::getZero(N1.getScalarValueSizeInBits()),
  5126. SDLoc(N), N1.getValueType());
  5127. // fold (and x, -1) -> x, vector edition
  5128. if (ISD::isConstantSplatVectorAllOnes(N1.getNode()))
  5129. return N0;
  5130. // fold (and (masked_load) (build_vec (x, ...))) to zext_masked_load
  5131. auto *MLoad = dyn_cast<MaskedLoadSDNode>(N0);
  5132. auto *BVec = dyn_cast<BuildVectorSDNode>(N1);
  5133. if (MLoad && BVec && MLoad->getExtensionType() == ISD::EXTLOAD &&
  5134. N0.hasOneUse() && N1.hasOneUse()) {
  5135. EVT LoadVT = MLoad->getMemoryVT();
  5136. EVT ExtVT = VT;
  5137. if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT, LoadVT)) {
  5138. // For this AND to be a zero extension of the masked load the elements
  5139. // of the BuildVec must mask the bottom bits of the extended element
  5140. // type
  5141. if (ConstantSDNode *Splat = BVec->getConstantSplatNode()) {
  5142. uint64_t ElementSize =
  5143. LoadVT.getVectorElementType().getScalarSizeInBits();
  5144. if (Splat->getAPIntValue().isMask(ElementSize)) {
  5145. return DAG.getMaskedLoad(
  5146. ExtVT, SDLoc(N), MLoad->getChain(), MLoad->getBasePtr(),
  5147. MLoad->getOffset(), MLoad->getMask(), MLoad->getPassThru(),
  5148. LoadVT, MLoad->getMemOperand(), MLoad->getAddressingMode(),
  5149. ISD::ZEXTLOAD, MLoad->isExpandingLoad());
  5150. }
  5151. }
  5152. }
  5153. }
  5154. }
  5155. // fold (and x, -1) -> x
  5156. if (isAllOnesConstant(N1))
  5157. return N0;
  5158. // if (and x, c) is known to be zero, return 0
  5159. unsigned BitWidth = VT.getScalarSizeInBits();
  5160. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  5161. if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(BitWidth)))
  5162. return DAG.getConstant(0, SDLoc(N), VT);
  5163. if (SDValue NewSel = foldBinOpIntoSelect(N))
  5164. return NewSel;
  5165. // reassociate and
  5166. if (SDValue RAND = reassociateOps(ISD::AND, SDLoc(N), N0, N1, N->getFlags()))
  5167. return RAND;
  5168. // Try to convert a constant mask AND into a shuffle clear mask.
  5169. if (VT.isVector())
  5170. if (SDValue Shuffle = XformToShuffleWithZero(N))
  5171. return Shuffle;
  5172. if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
  5173. return Combined;
  5174. // fold (and (or x, C), D) -> D if (C & D) == D
  5175. auto MatchSubset = [](ConstantSDNode *LHS, ConstantSDNode *RHS) {
  5176. return RHS->getAPIntValue().isSubsetOf(LHS->getAPIntValue());
  5177. };
  5178. if (N0.getOpcode() == ISD::OR &&
  5179. ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchSubset))
  5180. return N1;
  5181. // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
  5182. if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
  5183. SDValue N0Op0 = N0.getOperand(0);
  5184. APInt Mask = ~N1C->getAPIntValue();
  5185. Mask = Mask.trunc(N0Op0.getScalarValueSizeInBits());
  5186. if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
  5187. SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N),
  5188. N0.getValueType(), N0Op0);
  5189. // Replace uses of the AND with uses of the Zero extend node.
  5190. CombineTo(N, Zext);
  5191. // We actually want to replace all uses of the any_extend with the
  5192. // zero_extend, to avoid duplicating things. This will later cause this
  5193. // AND to be folded.
  5194. CombineTo(N0.getNode(), Zext);
  5195. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  5196. }
  5197. }
  5198. // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
  5199. // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
  5200. // already be zero by virtue of the width of the base type of the load.
  5201. //
  5202. // the 'X' node here can either be nothing or an extract_vector_elt to catch
  5203. // more cases.
  5204. if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  5205. N0.getValueSizeInBits() == N0.getOperand(0).getScalarValueSizeInBits() &&
  5206. N0.getOperand(0).getOpcode() == ISD::LOAD &&
  5207. N0.getOperand(0).getResNo() == 0) ||
  5208. (N0.getOpcode() == ISD::LOAD && N0.getResNo() == 0)) {
  5209. LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
  5210. N0 : N0.getOperand(0) );
  5211. // Get the constant (if applicable) the zero'th operand is being ANDed with.
  5212. // This can be a pure constant or a vector splat, in which case we treat the
  5213. // vector as a scalar and use the splat value.
  5214. APInt Constant = APInt::getZero(1);
  5215. if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
  5216. Constant = C->getAPIntValue();
  5217. } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
  5218. APInt SplatValue, SplatUndef;
  5219. unsigned SplatBitSize;
  5220. bool HasAnyUndefs;
  5221. bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
  5222. SplatBitSize, HasAnyUndefs);
  5223. if (IsSplat) {
  5224. // Undef bits can contribute to a possible optimisation if set, so
  5225. // set them.
  5226. SplatValue |= SplatUndef;
  5227. // The splat value may be something like "0x00FFFFFF", which means 0 for
  5228. // the first vector value and FF for the rest, repeating. We need a mask
  5229. // that will apply equally to all members of the vector, so AND all the
  5230. // lanes of the constant together.
  5231. unsigned EltBitWidth = Vector->getValueType(0).getScalarSizeInBits();
  5232. // If the splat value has been compressed to a bitlength lower
  5233. // than the size of the vector lane, we need to re-expand it to
  5234. // the lane size.
  5235. if (EltBitWidth > SplatBitSize)
  5236. for (SplatValue = SplatValue.zextOrTrunc(EltBitWidth);
  5237. SplatBitSize < EltBitWidth; SplatBitSize = SplatBitSize * 2)
  5238. SplatValue |= SplatValue.shl(SplatBitSize);
  5239. // Make sure that variable 'Constant' is only set if 'SplatBitSize' is a
  5240. // multiple of 'BitWidth'. Otherwise, we could propagate a wrong value.
  5241. if ((SplatBitSize % EltBitWidth) == 0) {
  5242. Constant = APInt::getAllOnes(EltBitWidth);
  5243. for (unsigned i = 0, n = (SplatBitSize / EltBitWidth); i < n; ++i)
  5244. Constant &= SplatValue.extractBits(EltBitWidth, i * EltBitWidth);
  5245. }
  5246. }
  5247. }
  5248. // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
  5249. // actually legal and isn't going to get expanded, else this is a false
  5250. // optimisation.
  5251. bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
  5252. Load->getValueType(0),
  5253. Load->getMemoryVT());
  5254. // Resize the constant to the same size as the original memory access before
  5255. // extension. If it is still the AllOnesValue then this AND is completely
  5256. // unneeded.
  5257. Constant = Constant.zextOrTrunc(Load->getMemoryVT().getScalarSizeInBits());
  5258. bool B;
  5259. switch (Load->getExtensionType()) {
  5260. default: B = false; break;
  5261. case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
  5262. case ISD::ZEXTLOAD:
  5263. case ISD::NON_EXTLOAD: B = true; break;
  5264. }
  5265. if (B && Constant.isAllOnes()) {
  5266. // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
  5267. // preserve semantics once we get rid of the AND.
  5268. SDValue NewLoad(Load, 0);
  5269. // Fold the AND away. NewLoad may get replaced immediately.
  5270. CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
  5271. if (Load->getExtensionType() == ISD::EXTLOAD) {
  5272. NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
  5273. Load->getValueType(0), SDLoc(Load),
  5274. Load->getChain(), Load->getBasePtr(),
  5275. Load->getOffset(), Load->getMemoryVT(),
  5276. Load->getMemOperand());
  5277. // Replace uses of the EXTLOAD with the new ZEXTLOAD.
  5278. if (Load->getNumValues() == 3) {
  5279. // PRE/POST_INC loads have 3 values.
  5280. SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
  5281. NewLoad.getValue(2) };
  5282. CombineTo(Load, To, 3, true);
  5283. } else {
  5284. CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
  5285. }
  5286. }
  5287. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  5288. }
  5289. }
  5290. // fold (and (masked_gather x)) -> (zext_masked_gather x)
  5291. if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) {
  5292. EVT MemVT = GN0->getMemoryVT();
  5293. EVT ScalarVT = MemVT.getScalarType();
  5294. if (SDValue(GN0, 0).hasOneUse() &&
  5295. isConstantSplatVectorMaskForType(N1.getNode(), ScalarVT) &&
  5296. TLI.isVectorLoadExtDesirable(SDValue(SDValue(GN0, 0)))) {
  5297. SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(),
  5298. GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()};
  5299. SDValue ZExtLoad = DAG.getMaskedGather(
  5300. DAG.getVTList(VT, MVT::Other), MemVT, SDLoc(N), Ops,
  5301. GN0->getMemOperand(), GN0->getIndexType(), ISD::ZEXTLOAD);
  5302. CombineTo(N, ZExtLoad);
  5303. AddToWorklist(ZExtLoad.getNode());
  5304. // Avoid recheck of N.
  5305. return SDValue(N, 0);
  5306. }
  5307. }
  5308. // fold (and (load x), 255) -> (zextload x, i8)
  5309. // fold (and (extload x, i16), 255) -> (zextload x, i8)
  5310. // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
  5311. if (!VT.isVector() && N1C && (N0.getOpcode() == ISD::LOAD ||
  5312. (N0.getOpcode() == ISD::ANY_EXTEND &&
  5313. N0.getOperand(0).getOpcode() == ISD::LOAD))) {
  5314. if (SDValue Res = reduceLoadWidth(N)) {
  5315. LoadSDNode *LN0 = N0->getOpcode() == ISD::ANY_EXTEND
  5316. ? cast<LoadSDNode>(N0.getOperand(0)) : cast<LoadSDNode>(N0);
  5317. AddToWorklist(N);
  5318. DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 0), Res);
  5319. return SDValue(N, 0);
  5320. }
  5321. }
  5322. if (LegalTypes) {
  5323. // Attempt to propagate the AND back up to the leaves which, if they're
  5324. // loads, can be combined to narrow loads and the AND node can be removed.
  5325. // Perform after legalization so that extend nodes will already be
  5326. // combined into the loads.
  5327. if (BackwardsPropagateMask(N))
  5328. return SDValue(N, 0);
  5329. }
  5330. if (SDValue Combined = visitANDLike(N0, N1, N))
  5331. return Combined;
  5332. // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
  5333. if (N0.getOpcode() == N1.getOpcode())
  5334. if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
  5335. return V;
  5336. // Masking the negated extension of a boolean is just the zero-extended
  5337. // boolean:
  5338. // and (sub 0, zext(bool X)), 1 --> zext(bool X)
  5339. // and (sub 0, sext(bool X)), 1 --> zext(bool X)
  5340. //
  5341. // Note: the SimplifyDemandedBits fold below can make an information-losing
  5342. // transform, and then we have no way to find this better fold.
  5343. if (N1C && N1C->isOne() && N0.getOpcode() == ISD::SUB) {
  5344. if (isNullOrNullSplat(N0.getOperand(0))) {
  5345. SDValue SubRHS = N0.getOperand(1);
  5346. if (SubRHS.getOpcode() == ISD::ZERO_EXTEND &&
  5347. SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
  5348. return SubRHS;
  5349. if (SubRHS.getOpcode() == ISD::SIGN_EXTEND &&
  5350. SubRHS.getOperand(0).getScalarValueSizeInBits() == 1)
  5351. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, SubRHS.getOperand(0));
  5352. }
  5353. }
  5354. // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
  5355. // fold (and (sra)) -> (and (srl)) when possible.
  5356. if (SimplifyDemandedBits(SDValue(N, 0)))
  5357. return SDValue(N, 0);
  5358. // fold (zext_inreg (extload x)) -> (zextload x)
  5359. // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
  5360. if (ISD::isUNINDEXEDLoad(N0.getNode()) &&
  5361. (ISD::isEXTLoad(N0.getNode()) ||
  5362. (ISD::isSEXTLoad(N0.getNode()) && N0.hasOneUse()))) {
  5363. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  5364. EVT MemVT = LN0->getMemoryVT();
  5365. // If we zero all the possible extended bits, then we can turn this into
  5366. // a zextload if we are running before legalize or the operation is legal.
  5367. unsigned ExtBitSize = N1.getScalarValueSizeInBits();
  5368. unsigned MemBitSize = MemVT.getScalarSizeInBits();
  5369. APInt ExtBits = APInt::getHighBitsSet(ExtBitSize, ExtBitSize - MemBitSize);
  5370. if (DAG.MaskedValueIsZero(N1, ExtBits) &&
  5371. ((!LegalOperations && LN0->isSimple()) ||
  5372. TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT))) {
  5373. SDValue ExtLoad =
  5374. DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(N0), VT, LN0->getChain(),
  5375. LN0->getBasePtr(), MemVT, LN0->getMemOperand());
  5376. AddToWorklist(N);
  5377. CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
  5378. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  5379. }
  5380. }
  5381. // fold (and (or (srl N, 8), (shl N, 8)), 0xffff) -> (srl (bswap N), const)
  5382. if (N1C && N1C->getAPIntValue() == 0xffff && N0.getOpcode() == ISD::OR) {
  5383. if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
  5384. N0.getOperand(1), false))
  5385. return BSwap;
  5386. }
  5387. if (SDValue Shifts = unfoldExtremeBitClearingToShifts(N))
  5388. return Shifts;
  5389. if (TLI.hasBitTest(N0, N1))
  5390. if (SDValue V = combineShiftAnd1ToBitTest(N, DAG))
  5391. return V;
  5392. // Recognize the following pattern:
  5393. //
  5394. // AndVT = (and (sign_extend NarrowVT to AndVT) #bitmask)
  5395. //
  5396. // where bitmask is a mask that clears the upper bits of AndVT. The
  5397. // number of bits in bitmask must be a power of two.
  5398. auto IsAndZeroExtMask = [](SDValue LHS, SDValue RHS) {
  5399. if (LHS->getOpcode() != ISD::SIGN_EXTEND)
  5400. return false;
  5401. auto *C = dyn_cast<ConstantSDNode>(RHS);
  5402. if (!C)
  5403. return false;
  5404. if (!C->getAPIntValue().isMask(
  5405. LHS.getOperand(0).getValueType().getFixedSizeInBits()))
  5406. return false;
  5407. return true;
  5408. };
  5409. // Replace (and (sign_extend ...) #bitmask) with (zero_extend ...).
  5410. if (IsAndZeroExtMask(N0, N1))
  5411. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT, N0.getOperand(0));
  5412. if (hasOperation(ISD::USUBSAT, VT))
  5413. if (SDValue V = foldAndToUsubsat(N, DAG))
  5414. return V;
  5415. return SDValue();
  5416. }
  5417. /// Match (a >> 8) | (a << 8) as (bswap a) >> 16.
  5418. SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
  5419. bool DemandHighBits) {
  5420. if (!LegalOperations)
  5421. return SDValue();
  5422. EVT VT = N->getValueType(0);
  5423. if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
  5424. return SDValue();
  5425. if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
  5426. return SDValue();
  5427. // Recognize (and (shl a, 8), 0xff00), (and (srl a, 8), 0xff)
  5428. bool LookPassAnd0 = false;
  5429. bool LookPassAnd1 = false;
  5430. if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
  5431. std::swap(N0, N1);
  5432. if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
  5433. std::swap(N0, N1);
  5434. if (N0.getOpcode() == ISD::AND) {
  5435. if (!N0.getNode()->hasOneUse())
  5436. return SDValue();
  5437. ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  5438. // Also handle 0xffff since the LHS is guaranteed to have zeros there.
  5439. // This is needed for X86.
  5440. if (!N01C || (N01C->getZExtValue() != 0xFF00 &&
  5441. N01C->getZExtValue() != 0xFFFF))
  5442. return SDValue();
  5443. N0 = N0.getOperand(0);
  5444. LookPassAnd0 = true;
  5445. }
  5446. if (N1.getOpcode() == ISD::AND) {
  5447. if (!N1.getNode()->hasOneUse())
  5448. return SDValue();
  5449. ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
  5450. if (!N11C || N11C->getZExtValue() != 0xFF)
  5451. return SDValue();
  5452. N1 = N1.getOperand(0);
  5453. LookPassAnd1 = true;
  5454. }
  5455. if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
  5456. std::swap(N0, N1);
  5457. if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
  5458. return SDValue();
  5459. if (!N0.getNode()->hasOneUse() || !N1.getNode()->hasOneUse())
  5460. return SDValue();
  5461. ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  5462. ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
  5463. if (!N01C || !N11C)
  5464. return SDValue();
  5465. if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
  5466. return SDValue();
  5467. // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
  5468. SDValue N00 = N0->getOperand(0);
  5469. if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
  5470. if (!N00.getNode()->hasOneUse())
  5471. return SDValue();
  5472. ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
  5473. if (!N001C || N001C->getZExtValue() != 0xFF)
  5474. return SDValue();
  5475. N00 = N00.getOperand(0);
  5476. LookPassAnd0 = true;
  5477. }
  5478. SDValue N10 = N1->getOperand(0);
  5479. if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
  5480. if (!N10.getNode()->hasOneUse())
  5481. return SDValue();
  5482. ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
  5483. // Also allow 0xFFFF since the bits will be shifted out. This is needed
  5484. // for X86.
  5485. if (!N101C || (N101C->getZExtValue() != 0xFF00 &&
  5486. N101C->getZExtValue() != 0xFFFF))
  5487. return SDValue();
  5488. N10 = N10.getOperand(0);
  5489. LookPassAnd1 = true;
  5490. }
  5491. if (N00 != N10)
  5492. return SDValue();
  5493. // Make sure everything beyond the low halfword gets set to zero since the SRL
  5494. // 16 will clear the top bits.
  5495. unsigned OpSizeInBits = VT.getSizeInBits();
  5496. if (DemandHighBits && OpSizeInBits > 16) {
  5497. // If the left-shift isn't masked out then the only way this is a bswap is
  5498. // if all bits beyond the low 8 are 0. In that case the entire pattern
  5499. // reduces to a left shift anyway: leave it for other parts of the combiner.
  5500. if (!LookPassAnd0)
  5501. return SDValue();
  5502. // However, if the right shift isn't masked out then it might be because
  5503. // it's not needed. See if we can spot that too.
  5504. if (!LookPassAnd1 &&
  5505. !DAG.MaskedValueIsZero(
  5506. N10, APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - 16)))
  5507. return SDValue();
  5508. }
  5509. SDValue Res = DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N00);
  5510. if (OpSizeInBits > 16) {
  5511. SDLoc DL(N);
  5512. Res = DAG.getNode(ISD::SRL, DL, VT, Res,
  5513. DAG.getConstant(OpSizeInBits - 16, DL,
  5514. getShiftAmountTy(VT)));
  5515. }
  5516. return Res;
  5517. }
  5518. /// Return true if the specified node is an element that makes up a 32-bit
  5519. /// packed halfword byteswap.
  5520. /// ((x & 0x000000ff) << 8) |
  5521. /// ((x & 0x0000ff00) >> 8) |
  5522. /// ((x & 0x00ff0000) << 8) |
  5523. /// ((x & 0xff000000) >> 8)
  5524. static bool isBSwapHWordElement(SDValue N, MutableArrayRef<SDNode *> Parts) {
  5525. if (!N.getNode()->hasOneUse())
  5526. return false;
  5527. unsigned Opc = N.getOpcode();
  5528. if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
  5529. return false;
  5530. SDValue N0 = N.getOperand(0);
  5531. unsigned Opc0 = N0.getOpcode();
  5532. if (Opc0 != ISD::AND && Opc0 != ISD::SHL && Opc0 != ISD::SRL)
  5533. return false;
  5534. ConstantSDNode *N1C = nullptr;
  5535. // SHL or SRL: look upstream for AND mask operand
  5536. if (Opc == ISD::AND)
  5537. N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
  5538. else if (Opc0 == ISD::AND)
  5539. N1C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  5540. if (!N1C)
  5541. return false;
  5542. unsigned MaskByteOffset;
  5543. switch (N1C->getZExtValue()) {
  5544. default:
  5545. return false;
  5546. case 0xFF: MaskByteOffset = 0; break;
  5547. case 0xFF00: MaskByteOffset = 1; break;
  5548. case 0xFFFF:
  5549. // In case demanded bits didn't clear the bits that will be shifted out.
  5550. // This is needed for X86.
  5551. if (Opc == ISD::SRL || (Opc == ISD::AND && Opc0 == ISD::SHL)) {
  5552. MaskByteOffset = 1;
  5553. break;
  5554. }
  5555. return false;
  5556. case 0xFF0000: MaskByteOffset = 2; break;
  5557. case 0xFF000000: MaskByteOffset = 3; break;
  5558. }
  5559. // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
  5560. if (Opc == ISD::AND) {
  5561. if (MaskByteOffset == 0 || MaskByteOffset == 2) {
  5562. // (x >> 8) & 0xff
  5563. // (x >> 8) & 0xff0000
  5564. if (Opc0 != ISD::SRL)
  5565. return false;
  5566. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  5567. if (!C || C->getZExtValue() != 8)
  5568. return false;
  5569. } else {
  5570. // (x << 8) & 0xff00
  5571. // (x << 8) & 0xff000000
  5572. if (Opc0 != ISD::SHL)
  5573. return false;
  5574. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  5575. if (!C || C->getZExtValue() != 8)
  5576. return false;
  5577. }
  5578. } else if (Opc == ISD::SHL) {
  5579. // (x & 0xff) << 8
  5580. // (x & 0xff0000) << 8
  5581. if (MaskByteOffset != 0 && MaskByteOffset != 2)
  5582. return false;
  5583. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
  5584. if (!C || C->getZExtValue() != 8)
  5585. return false;
  5586. } else { // Opc == ISD::SRL
  5587. // (x & 0xff00) >> 8
  5588. // (x & 0xff000000) >> 8
  5589. if (MaskByteOffset != 1 && MaskByteOffset != 3)
  5590. return false;
  5591. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
  5592. if (!C || C->getZExtValue() != 8)
  5593. return false;
  5594. }
  5595. if (Parts[MaskByteOffset])
  5596. return false;
  5597. Parts[MaskByteOffset] = N0.getOperand(0).getNode();
  5598. return true;
  5599. }
  5600. // Match 2 elements of a packed halfword bswap.
  5601. static bool isBSwapHWordPair(SDValue N, MutableArrayRef<SDNode *> Parts) {
  5602. if (N.getOpcode() == ISD::OR)
  5603. return isBSwapHWordElement(N.getOperand(0), Parts) &&
  5604. isBSwapHWordElement(N.getOperand(1), Parts);
  5605. if (N.getOpcode() == ISD::SRL && N.getOperand(0).getOpcode() == ISD::BSWAP) {
  5606. ConstantSDNode *C = isConstOrConstSplat(N.getOperand(1));
  5607. if (!C || C->getAPIntValue() != 16)
  5608. return false;
  5609. Parts[0] = Parts[1] = N.getOperand(0).getOperand(0).getNode();
  5610. return true;
  5611. }
  5612. return false;
  5613. }
  5614. // Match this pattern:
  5615. // (or (and (shl (A, 8)), 0xff00ff00), (and (srl (A, 8)), 0x00ff00ff))
  5616. // And rewrite this to:
  5617. // (rotr (bswap A), 16)
  5618. static SDValue matchBSwapHWordOrAndAnd(const TargetLowering &TLI,
  5619. SelectionDAG &DAG, SDNode *N, SDValue N0,
  5620. SDValue N1, EVT VT, EVT ShiftAmountTy) {
  5621. assert(N->getOpcode() == ISD::OR && VT == MVT::i32 &&
  5622. "MatchBSwapHWordOrAndAnd: expecting i32");
  5623. if (!TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
  5624. return SDValue();
  5625. if (N0.getOpcode() != ISD::AND || N1.getOpcode() != ISD::AND)
  5626. return SDValue();
  5627. // TODO: this is too restrictive; lifting this restriction requires more tests
  5628. if (!N0->hasOneUse() || !N1->hasOneUse())
  5629. return SDValue();
  5630. ConstantSDNode *Mask0 = isConstOrConstSplat(N0.getOperand(1));
  5631. ConstantSDNode *Mask1 = isConstOrConstSplat(N1.getOperand(1));
  5632. if (!Mask0 || !Mask1)
  5633. return SDValue();
  5634. if (Mask0->getAPIntValue() != 0xff00ff00 ||
  5635. Mask1->getAPIntValue() != 0x00ff00ff)
  5636. return SDValue();
  5637. SDValue Shift0 = N0.getOperand(0);
  5638. SDValue Shift1 = N1.getOperand(0);
  5639. if (Shift0.getOpcode() != ISD::SHL || Shift1.getOpcode() != ISD::SRL)
  5640. return SDValue();
  5641. ConstantSDNode *ShiftAmt0 = isConstOrConstSplat(Shift0.getOperand(1));
  5642. ConstantSDNode *ShiftAmt1 = isConstOrConstSplat(Shift1.getOperand(1));
  5643. if (!ShiftAmt0 || !ShiftAmt1)
  5644. return SDValue();
  5645. if (ShiftAmt0->getAPIntValue() != 8 || ShiftAmt1->getAPIntValue() != 8)
  5646. return SDValue();
  5647. if (Shift0.getOperand(0) != Shift1.getOperand(0))
  5648. return SDValue();
  5649. SDLoc DL(N);
  5650. SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, Shift0.getOperand(0));
  5651. SDValue ShAmt = DAG.getConstant(16, DL, ShiftAmountTy);
  5652. return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
  5653. }
  5654. /// Match a 32-bit packed halfword bswap. That is
  5655. /// ((x & 0x000000ff) << 8) |
  5656. /// ((x & 0x0000ff00) >> 8) |
  5657. /// ((x & 0x00ff0000) << 8) |
  5658. /// ((x & 0xff000000) >> 8)
  5659. /// => (rotl (bswap x), 16)
  5660. SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
  5661. if (!LegalOperations)
  5662. return SDValue();
  5663. EVT VT = N->getValueType(0);
  5664. if (VT != MVT::i32)
  5665. return SDValue();
  5666. if (!TLI.isOperationLegalOrCustom(ISD::BSWAP, VT))
  5667. return SDValue();
  5668. if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N0, N1, VT,
  5669. getShiftAmountTy(VT)))
  5670. return BSwap;
  5671. // Try again with commuted operands.
  5672. if (SDValue BSwap = matchBSwapHWordOrAndAnd(TLI, DAG, N, N1, N0, VT,
  5673. getShiftAmountTy(VT)))
  5674. return BSwap;
  5675. // Look for either
  5676. // (or (bswaphpair), (bswaphpair))
  5677. // (or (or (bswaphpair), (and)), (and))
  5678. // (or (or (and), (bswaphpair)), (and))
  5679. SDNode *Parts[4] = {};
  5680. if (isBSwapHWordPair(N0, Parts)) {
  5681. // (or (or (and), (and)), (or (and), (and)))
  5682. if (!isBSwapHWordPair(N1, Parts))
  5683. return SDValue();
  5684. } else if (N0.getOpcode() == ISD::OR) {
  5685. // (or (or (or (and), (and)), (and)), (and))
  5686. if (!isBSwapHWordElement(N1, Parts))
  5687. return SDValue();
  5688. SDValue N00 = N0.getOperand(0);
  5689. SDValue N01 = N0.getOperand(1);
  5690. if (!(isBSwapHWordElement(N01, Parts) && isBSwapHWordPair(N00, Parts)) &&
  5691. !(isBSwapHWordElement(N00, Parts) && isBSwapHWordPair(N01, Parts)))
  5692. return SDValue();
  5693. } else
  5694. return SDValue();
  5695. // Make sure the parts are all coming from the same node.
  5696. if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
  5697. return SDValue();
  5698. SDLoc DL(N);
  5699. SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT,
  5700. SDValue(Parts[0], 0));
  5701. // Result of the bswap should be rotated by 16. If it's not legal, then
  5702. // do (x << 16) | (x >> 16).
  5703. SDValue ShAmt = DAG.getConstant(16, DL, getShiftAmountTy(VT));
  5704. if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
  5705. return DAG.getNode(ISD::ROTL, DL, VT, BSwap, ShAmt);
  5706. if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
  5707. return DAG.getNode(ISD::ROTR, DL, VT, BSwap, ShAmt);
  5708. return DAG.getNode(ISD::OR, DL, VT,
  5709. DAG.getNode(ISD::SHL, DL, VT, BSwap, ShAmt),
  5710. DAG.getNode(ISD::SRL, DL, VT, BSwap, ShAmt));
  5711. }
  5712. /// This contains all DAGCombine rules which reduce two values combined by
  5713. /// an Or operation to a single value \see visitANDLike().
  5714. SDValue DAGCombiner::visitORLike(SDValue N0, SDValue N1, SDNode *N) {
  5715. EVT VT = N1.getValueType();
  5716. SDLoc DL(N);
  5717. // fold (or x, undef) -> -1
  5718. if (!LegalOperations && (N0.isUndef() || N1.isUndef()))
  5719. return DAG.getAllOnesConstant(DL, VT);
  5720. if (SDValue V = foldLogicOfSetCCs(false, N0, N1, DL))
  5721. return V;
  5722. // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
  5723. if (N0.getOpcode() == ISD::AND && N1.getOpcode() == ISD::AND &&
  5724. // Don't increase # computations.
  5725. (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
  5726. // We can only do this xform if we know that bits from X that are set in C2
  5727. // but not in C1 are already zero. Likewise for Y.
  5728. if (const ConstantSDNode *N0O1C =
  5729. getAsNonOpaqueConstant(N0.getOperand(1))) {
  5730. if (const ConstantSDNode *N1O1C =
  5731. getAsNonOpaqueConstant(N1.getOperand(1))) {
  5732. // We can only do this xform if we know that bits from X that are set in
  5733. // C2 but not in C1 are already zero. Likewise for Y.
  5734. const APInt &LHSMask = N0O1C->getAPIntValue();
  5735. const APInt &RHSMask = N1O1C->getAPIntValue();
  5736. if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
  5737. DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
  5738. SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
  5739. N0.getOperand(0), N1.getOperand(0));
  5740. return DAG.getNode(ISD::AND, DL, VT, X,
  5741. DAG.getConstant(LHSMask | RHSMask, DL, VT));
  5742. }
  5743. }
  5744. }
  5745. }
  5746. // (or (and X, M), (and X, N)) -> (and X, (or M, N))
  5747. if (N0.getOpcode() == ISD::AND &&
  5748. N1.getOpcode() == ISD::AND &&
  5749. N0.getOperand(0) == N1.getOperand(0) &&
  5750. // Don't increase # computations.
  5751. (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
  5752. SDValue X = DAG.getNode(ISD::OR, SDLoc(N0), VT,
  5753. N0.getOperand(1), N1.getOperand(1));
  5754. return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), X);
  5755. }
  5756. return SDValue();
  5757. }
  5758. /// OR combines for which the commuted variant will be tried as well.
  5759. static SDValue visitORCommutative(
  5760. SelectionDAG &DAG, SDValue N0, SDValue N1, SDNode *N) {
  5761. EVT VT = N0.getValueType();
  5762. if (N0.getOpcode() == ISD::AND) {
  5763. // fold (or (and X, (xor Y, -1)), Y) -> (or X, Y)
  5764. if (isBitwiseNot(N0.getOperand(1)) && N0.getOperand(1).getOperand(0) == N1)
  5765. return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(0), N1);
  5766. // fold (or (and (xor Y, -1), X), Y) -> (or X, Y)
  5767. if (isBitwiseNot(N0.getOperand(0)) && N0.getOperand(0).getOperand(0) == N1)
  5768. return DAG.getNode(ISD::OR, SDLoc(N), VT, N0.getOperand(1), N1);
  5769. }
  5770. return SDValue();
  5771. }
  5772. SDValue DAGCombiner::visitOR(SDNode *N) {
  5773. SDValue N0 = N->getOperand(0);
  5774. SDValue N1 = N->getOperand(1);
  5775. EVT VT = N1.getValueType();
  5776. // x | x --> x
  5777. if (N0 == N1)
  5778. return N0;
  5779. // fold (or c1, c2) -> c1|c2
  5780. if (SDValue C = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N), VT, {N0, N1}))
  5781. return C;
  5782. // canonicalize constant to RHS
  5783. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  5784. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  5785. return DAG.getNode(ISD::OR, SDLoc(N), VT, N1, N0);
  5786. // fold vector ops
  5787. if (VT.isVector()) {
  5788. if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
  5789. return FoldedVOp;
  5790. // fold (or x, 0) -> x, vector edition
  5791. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  5792. return N0;
  5793. // fold (or x, -1) -> -1, vector edition
  5794. if (ISD::isConstantSplatVectorAllOnes(N1.getNode()))
  5795. // do not return N1, because undef node may exist in N1
  5796. return DAG.getAllOnesConstant(SDLoc(N), N1.getValueType());
  5797. // fold (or (shuf A, V_0, MA), (shuf B, V_0, MB)) -> (shuf A, B, Mask)
  5798. // Do this only if the resulting shuffle is legal.
  5799. if (isa<ShuffleVectorSDNode>(N0) &&
  5800. isa<ShuffleVectorSDNode>(N1) &&
  5801. // Avoid folding a node with illegal type.
  5802. TLI.isTypeLegal(VT)) {
  5803. bool ZeroN00 = ISD::isBuildVectorAllZeros(N0.getOperand(0).getNode());
  5804. bool ZeroN01 = ISD::isBuildVectorAllZeros(N0.getOperand(1).getNode());
  5805. bool ZeroN10 = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
  5806. bool ZeroN11 = ISD::isBuildVectorAllZeros(N1.getOperand(1).getNode());
  5807. // Ensure both shuffles have a zero input.
  5808. if ((ZeroN00 != ZeroN01) && (ZeroN10 != ZeroN11)) {
  5809. assert((!ZeroN00 || !ZeroN01) && "Both inputs zero!");
  5810. assert((!ZeroN10 || !ZeroN11) && "Both inputs zero!");
  5811. const ShuffleVectorSDNode *SV0 = cast<ShuffleVectorSDNode>(N0);
  5812. const ShuffleVectorSDNode *SV1 = cast<ShuffleVectorSDNode>(N1);
  5813. bool CanFold = true;
  5814. int NumElts = VT.getVectorNumElements();
  5815. SmallVector<int, 4> Mask(NumElts);
  5816. for (int i = 0; i != NumElts; ++i) {
  5817. int M0 = SV0->getMaskElt(i);
  5818. int M1 = SV1->getMaskElt(i);
  5819. // Determine if either index is pointing to a zero vector.
  5820. bool M0Zero = M0 < 0 || (ZeroN00 == (M0 < NumElts));
  5821. bool M1Zero = M1 < 0 || (ZeroN10 == (M1 < NumElts));
  5822. // If one element is zero and the otherside is undef, keep undef.
  5823. // This also handles the case that both are undef.
  5824. if ((M0Zero && M1 < 0) || (M1Zero && M0 < 0)) {
  5825. Mask[i] = -1;
  5826. continue;
  5827. }
  5828. // Make sure only one of the elements is zero.
  5829. if (M0Zero == M1Zero) {
  5830. CanFold = false;
  5831. break;
  5832. }
  5833. assert((M0 >= 0 || M1 >= 0) && "Undef index!");
  5834. // We have a zero and non-zero element. If the non-zero came from
  5835. // SV0 make the index a LHS index. If it came from SV1, make it
  5836. // a RHS index. We need to mod by NumElts because we don't care
  5837. // which operand it came from in the original shuffles.
  5838. Mask[i] = M1Zero ? M0 % NumElts : (M1 % NumElts) + NumElts;
  5839. }
  5840. if (CanFold) {
  5841. SDValue NewLHS = ZeroN00 ? N0.getOperand(1) : N0.getOperand(0);
  5842. SDValue NewRHS = ZeroN10 ? N1.getOperand(1) : N1.getOperand(0);
  5843. SDValue LegalShuffle =
  5844. TLI.buildLegalVectorShuffle(VT, SDLoc(N), NewLHS, NewRHS,
  5845. Mask, DAG);
  5846. if (LegalShuffle)
  5847. return LegalShuffle;
  5848. }
  5849. }
  5850. }
  5851. }
  5852. // fold (or x, 0) -> x
  5853. if (isNullConstant(N1))
  5854. return N0;
  5855. // fold (or x, -1) -> -1
  5856. if (isAllOnesConstant(N1))
  5857. return N1;
  5858. if (SDValue NewSel = foldBinOpIntoSelect(N))
  5859. return NewSel;
  5860. // fold (or x, c) -> c iff (x & ~c) == 0
  5861. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  5862. if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
  5863. return N1;
  5864. if (SDValue Combined = visitORLike(N0, N1, N))
  5865. return Combined;
  5866. if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
  5867. return Combined;
  5868. // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
  5869. if (SDValue BSwap = MatchBSwapHWord(N, N0, N1))
  5870. return BSwap;
  5871. if (SDValue BSwap = MatchBSwapHWordLow(N, N0, N1))
  5872. return BSwap;
  5873. // reassociate or
  5874. if (SDValue ROR = reassociateOps(ISD::OR, SDLoc(N), N0, N1, N->getFlags()))
  5875. return ROR;
  5876. // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
  5877. // iff (c1 & c2) != 0 or c1/c2 are undef.
  5878. auto MatchIntersect = [](ConstantSDNode *C1, ConstantSDNode *C2) {
  5879. return !C1 || !C2 || C1->getAPIntValue().intersects(C2->getAPIntValue());
  5880. };
  5881. if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
  5882. ISD::matchBinaryPredicate(N0.getOperand(1), N1, MatchIntersect, true)) {
  5883. if (SDValue COR = DAG.FoldConstantArithmetic(ISD::OR, SDLoc(N1), VT,
  5884. {N1, N0.getOperand(1)})) {
  5885. SDValue IOR = DAG.getNode(ISD::OR, SDLoc(N0), VT, N0.getOperand(0), N1);
  5886. AddToWorklist(IOR.getNode());
  5887. return DAG.getNode(ISD::AND, SDLoc(N), VT, COR, IOR);
  5888. }
  5889. }
  5890. if (SDValue Combined = visitORCommutative(DAG, N0, N1, N))
  5891. return Combined;
  5892. if (SDValue Combined = visitORCommutative(DAG, N1, N0, N))
  5893. return Combined;
  5894. // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
  5895. if (N0.getOpcode() == N1.getOpcode())
  5896. if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
  5897. return V;
  5898. // See if this is some rotate idiom.
  5899. if (SDValue Rot = MatchRotate(N0, N1, SDLoc(N)))
  5900. return Rot;
  5901. if (SDValue Load = MatchLoadCombine(N))
  5902. return Load;
  5903. // Simplify the operands using demanded-bits information.
  5904. if (SimplifyDemandedBits(SDValue(N, 0)))
  5905. return SDValue(N, 0);
  5906. // If OR can be rewritten into ADD, try combines based on ADD.
  5907. if ((!LegalOperations || TLI.isOperationLegal(ISD::ADD, VT)) &&
  5908. DAG.haveNoCommonBitsSet(N0, N1))
  5909. if (SDValue Combined = visitADDLike(N))
  5910. return Combined;
  5911. return SDValue();
  5912. }
  5913. static SDValue stripConstantMask(SelectionDAG &DAG, SDValue Op, SDValue &Mask) {
  5914. if (Op.getOpcode() == ISD::AND &&
  5915. DAG.isConstantIntBuildVectorOrConstantInt(Op.getOperand(1))) {
  5916. Mask = Op.getOperand(1);
  5917. return Op.getOperand(0);
  5918. }
  5919. return Op;
  5920. }
  5921. /// Match "(X shl/srl V1) & V2" where V2 may not be present.
  5922. static bool matchRotateHalf(SelectionDAG &DAG, SDValue Op, SDValue &Shift,
  5923. SDValue &Mask) {
  5924. Op = stripConstantMask(DAG, Op, Mask);
  5925. if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
  5926. Shift = Op;
  5927. return true;
  5928. }
  5929. return false;
  5930. }
  5931. /// Helper function for visitOR to extract the needed side of a rotate idiom
  5932. /// from a shl/srl/mul/udiv. This is meant to handle cases where
  5933. /// InstCombine merged some outside op with one of the shifts from
  5934. /// the rotate pattern.
  5935. /// \returns An empty \c SDValue if the needed shift couldn't be extracted.
  5936. /// Otherwise, returns an expansion of \p ExtractFrom based on the following
  5937. /// patterns:
  5938. ///
  5939. /// (or (add v v) (shrl v bitwidth-1)):
  5940. /// expands (add v v) -> (shl v 1)
  5941. ///
  5942. /// (or (mul v c0) (shrl (mul v c1) c2)):
  5943. /// expands (mul v c0) -> (shl (mul v c1) c3)
  5944. ///
  5945. /// (or (udiv v c0) (shl (udiv v c1) c2)):
  5946. /// expands (udiv v c0) -> (shrl (udiv v c1) c3)
  5947. ///
  5948. /// (or (shl v c0) (shrl (shl v c1) c2)):
  5949. /// expands (shl v c0) -> (shl (shl v c1) c3)
  5950. ///
  5951. /// (or (shrl v c0) (shl (shrl v c1) c2)):
  5952. /// expands (shrl v c0) -> (shrl (shrl v c1) c3)
  5953. ///
  5954. /// Such that in all cases, c3+c2==bitwidth(op v c1).
  5955. static SDValue extractShiftForRotate(SelectionDAG &DAG, SDValue OppShift,
  5956. SDValue ExtractFrom, SDValue &Mask,
  5957. const SDLoc &DL) {
  5958. assert(OppShift && ExtractFrom && "Empty SDValue");
  5959. assert(
  5960. (OppShift.getOpcode() == ISD::SHL || OppShift.getOpcode() == ISD::SRL) &&
  5961. "Existing shift must be valid as a rotate half");
  5962. ExtractFrom = stripConstantMask(DAG, ExtractFrom, Mask);
  5963. // Value and Type of the shift.
  5964. SDValue OppShiftLHS = OppShift.getOperand(0);
  5965. EVT ShiftedVT = OppShiftLHS.getValueType();
  5966. // Amount of the existing shift.
  5967. ConstantSDNode *OppShiftCst = isConstOrConstSplat(OppShift.getOperand(1));
  5968. // (add v v) -> (shl v 1)
  5969. // TODO: Should this be a general DAG canonicalization?
  5970. if (OppShift.getOpcode() == ISD::SRL && OppShiftCst &&
  5971. ExtractFrom.getOpcode() == ISD::ADD &&
  5972. ExtractFrom.getOperand(0) == ExtractFrom.getOperand(1) &&
  5973. ExtractFrom.getOperand(0) == OppShiftLHS &&
  5974. OppShiftCst->getAPIntValue() == ShiftedVT.getScalarSizeInBits() - 1)
  5975. return DAG.getNode(ISD::SHL, DL, ShiftedVT, OppShiftLHS,
  5976. DAG.getShiftAmountConstant(1, ShiftedVT, DL));
  5977. // Preconditions:
  5978. // (or (op0 v c0) (shiftl/r (op0 v c1) c2))
  5979. //
  5980. // Find opcode of the needed shift to be extracted from (op0 v c0).
  5981. unsigned Opcode = ISD::DELETED_NODE;
  5982. bool IsMulOrDiv = false;
  5983. // Set Opcode and IsMulOrDiv if the extract opcode matches the needed shift
  5984. // opcode or its arithmetic (mul or udiv) variant.
  5985. auto SelectOpcode = [&](unsigned NeededShift, unsigned MulOrDivVariant) {
  5986. IsMulOrDiv = ExtractFrom.getOpcode() == MulOrDivVariant;
  5987. if (!IsMulOrDiv && ExtractFrom.getOpcode() != NeededShift)
  5988. return false;
  5989. Opcode = NeededShift;
  5990. return true;
  5991. };
  5992. // op0 must be either the needed shift opcode or the mul/udiv equivalent
  5993. // that the needed shift can be extracted from.
  5994. if ((OppShift.getOpcode() != ISD::SRL || !SelectOpcode(ISD::SHL, ISD::MUL)) &&
  5995. (OppShift.getOpcode() != ISD::SHL || !SelectOpcode(ISD::SRL, ISD::UDIV)))
  5996. return SDValue();
  5997. // op0 must be the same opcode on both sides, have the same LHS argument,
  5998. // and produce the same value type.
  5999. if (OppShiftLHS.getOpcode() != ExtractFrom.getOpcode() ||
  6000. OppShiftLHS.getOperand(0) != ExtractFrom.getOperand(0) ||
  6001. ShiftedVT != ExtractFrom.getValueType())
  6002. return SDValue();
  6003. // Constant mul/udiv/shift amount from the RHS of the shift's LHS op.
  6004. ConstantSDNode *OppLHSCst = isConstOrConstSplat(OppShiftLHS.getOperand(1));
  6005. // Constant mul/udiv/shift amount from the RHS of the ExtractFrom op.
  6006. ConstantSDNode *ExtractFromCst =
  6007. isConstOrConstSplat(ExtractFrom.getOperand(1));
  6008. // TODO: We should be able to handle non-uniform constant vectors for these values
  6009. // Check that we have constant values.
  6010. if (!OppShiftCst || !OppShiftCst->getAPIntValue() ||
  6011. !OppLHSCst || !OppLHSCst->getAPIntValue() ||
  6012. !ExtractFromCst || !ExtractFromCst->getAPIntValue())
  6013. return SDValue();
  6014. // Compute the shift amount we need to extract to complete the rotate.
  6015. const unsigned VTWidth = ShiftedVT.getScalarSizeInBits();
  6016. if (OppShiftCst->getAPIntValue().ugt(VTWidth))
  6017. return SDValue();
  6018. APInt NeededShiftAmt = VTWidth - OppShiftCst->getAPIntValue();
  6019. // Normalize the bitwidth of the two mul/udiv/shift constant operands.
  6020. APInt ExtractFromAmt = ExtractFromCst->getAPIntValue();
  6021. APInt OppLHSAmt = OppLHSCst->getAPIntValue();
  6022. zeroExtendToMatch(ExtractFromAmt, OppLHSAmt);
  6023. // Now try extract the needed shift from the ExtractFrom op and see if the
  6024. // result matches up with the existing shift's LHS op.
  6025. if (IsMulOrDiv) {
  6026. // Op to extract from is a mul or udiv by a constant.
  6027. // Check:
  6028. // c2 / (1 << (bitwidth(op0 v c0) - c1)) == c0
  6029. // c2 % (1 << (bitwidth(op0 v c0) - c1)) == 0
  6030. const APInt ExtractDiv = APInt::getOneBitSet(ExtractFromAmt.getBitWidth(),
  6031. NeededShiftAmt.getZExtValue());
  6032. APInt ResultAmt;
  6033. APInt Rem;
  6034. APInt::udivrem(ExtractFromAmt, ExtractDiv, ResultAmt, Rem);
  6035. if (Rem != 0 || ResultAmt != OppLHSAmt)
  6036. return SDValue();
  6037. } else {
  6038. // Op to extract from is a shift by a constant.
  6039. // Check:
  6040. // c2 - (bitwidth(op0 v c0) - c1) == c0
  6041. if (OppLHSAmt != ExtractFromAmt - NeededShiftAmt.zextOrTrunc(
  6042. ExtractFromAmt.getBitWidth()))
  6043. return SDValue();
  6044. }
  6045. // Return the expanded shift op that should allow a rotate to be formed.
  6046. EVT ShiftVT = OppShift.getOperand(1).getValueType();
  6047. EVT ResVT = ExtractFrom.getValueType();
  6048. SDValue NewShiftNode = DAG.getConstant(NeededShiftAmt, DL, ShiftVT);
  6049. return DAG.getNode(Opcode, DL, ResVT, OppShiftLHS, NewShiftNode);
  6050. }
  6051. // Return true if we can prove that, whenever Neg and Pos are both in the
  6052. // range [0, EltSize), Neg == (Pos == 0 ? 0 : EltSize - Pos). This means that
  6053. // for two opposing shifts shift1 and shift2 and a value X with OpBits bits:
  6054. //
  6055. // (or (shift1 X, Neg), (shift2 X, Pos))
  6056. //
  6057. // reduces to a rotate in direction shift2 by Pos or (equivalently) a rotate
  6058. // in direction shift1 by Neg. The range [0, EltSize) means that we only need
  6059. // to consider shift amounts with defined behavior.
  6060. //
  6061. // The IsRotate flag should be set when the LHS of both shifts is the same.
  6062. // Otherwise if matching a general funnel shift, it should be clear.
  6063. static bool matchRotateSub(SDValue Pos, SDValue Neg, unsigned EltSize,
  6064. SelectionDAG &DAG, bool IsRotate) {
  6065. // If EltSize is a power of 2 then:
  6066. //
  6067. // (a) (Pos == 0 ? 0 : EltSize - Pos) == (EltSize - Pos) & (EltSize - 1)
  6068. // (b) Neg == Neg & (EltSize - 1) whenever Neg is in [0, EltSize).
  6069. //
  6070. // So if EltSize is a power of 2 and Neg is (and Neg', EltSize-1), we check
  6071. // for the stronger condition:
  6072. //
  6073. // Neg & (EltSize - 1) == (EltSize - Pos) & (EltSize - 1) [A]
  6074. //
  6075. // for all Neg and Pos. Since Neg & (EltSize - 1) == Neg' & (EltSize - 1)
  6076. // we can just replace Neg with Neg' for the rest of the function.
  6077. //
  6078. // In other cases we check for the even stronger condition:
  6079. //
  6080. // Neg == EltSize - Pos [B]
  6081. //
  6082. // for all Neg and Pos. Note that the (or ...) then invokes undefined
  6083. // behavior if Pos == 0 (and consequently Neg == EltSize).
  6084. //
  6085. // We could actually use [A] whenever EltSize is a power of 2, but the
  6086. // only extra cases that it would match are those uninteresting ones
  6087. // where Neg and Pos are never in range at the same time. E.g. for
  6088. // EltSize == 32, using [A] would allow a Neg of the form (sub 64, Pos)
  6089. // as well as (sub 32, Pos), but:
  6090. //
  6091. // (or (shift1 X, (sub 64, Pos)), (shift2 X, Pos))
  6092. //
  6093. // always invokes undefined behavior for 32-bit X.
  6094. //
  6095. // Below, Mask == EltSize - 1 when using [A] and is all-ones otherwise.
  6096. //
  6097. // NOTE: We can only do this when matching an AND and not a general
  6098. // funnel shift.
  6099. unsigned MaskLoBits = 0;
  6100. if (IsRotate && Neg.getOpcode() == ISD::AND && isPowerOf2_64(EltSize)) {
  6101. if (ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(1))) {
  6102. KnownBits Known = DAG.computeKnownBits(Neg.getOperand(0));
  6103. unsigned Bits = Log2_64(EltSize);
  6104. if (NegC->getAPIntValue().getActiveBits() <= Bits &&
  6105. ((NegC->getAPIntValue() | Known.Zero).countTrailingOnes() >= Bits)) {
  6106. Neg = Neg.getOperand(0);
  6107. MaskLoBits = Bits;
  6108. }
  6109. }
  6110. }
  6111. // Check whether Neg has the form (sub NegC, NegOp1) for some NegC and NegOp1.
  6112. if (Neg.getOpcode() != ISD::SUB)
  6113. return false;
  6114. ConstantSDNode *NegC = isConstOrConstSplat(Neg.getOperand(0));
  6115. if (!NegC)
  6116. return false;
  6117. SDValue NegOp1 = Neg.getOperand(1);
  6118. // On the RHS of [A], if Pos is Pos' & (EltSize - 1), just replace Pos with
  6119. // Pos'. The truncation is redundant for the purpose of the equality.
  6120. if (MaskLoBits && Pos.getOpcode() == ISD::AND) {
  6121. if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1))) {
  6122. KnownBits Known = DAG.computeKnownBits(Pos.getOperand(0));
  6123. if (PosC->getAPIntValue().getActiveBits() <= MaskLoBits &&
  6124. ((PosC->getAPIntValue() | Known.Zero).countTrailingOnes() >=
  6125. MaskLoBits))
  6126. Pos = Pos.getOperand(0);
  6127. }
  6128. }
  6129. // The condition we need is now:
  6130. //
  6131. // (NegC - NegOp1) & Mask == (EltSize - Pos) & Mask
  6132. //
  6133. // If NegOp1 == Pos then we need:
  6134. //
  6135. // EltSize & Mask == NegC & Mask
  6136. //
  6137. // (because "x & Mask" is a truncation and distributes through subtraction).
  6138. //
  6139. // We also need to account for a potential truncation of NegOp1 if the amount
  6140. // has already been legalized to a shift amount type.
  6141. APInt Width;
  6142. if ((Pos == NegOp1) ||
  6143. (NegOp1.getOpcode() == ISD::TRUNCATE && Pos == NegOp1.getOperand(0)))
  6144. Width = NegC->getAPIntValue();
  6145. // Check for cases where Pos has the form (add NegOp1, PosC) for some PosC.
  6146. // Then the condition we want to prove becomes:
  6147. //
  6148. // (NegC - NegOp1) & Mask == (EltSize - (NegOp1 + PosC)) & Mask
  6149. //
  6150. // which, again because "x & Mask" is a truncation, becomes:
  6151. //
  6152. // NegC & Mask == (EltSize - PosC) & Mask
  6153. // EltSize & Mask == (NegC + PosC) & Mask
  6154. else if (Pos.getOpcode() == ISD::ADD && Pos.getOperand(0) == NegOp1) {
  6155. if (ConstantSDNode *PosC = isConstOrConstSplat(Pos.getOperand(1)))
  6156. Width = PosC->getAPIntValue() + NegC->getAPIntValue();
  6157. else
  6158. return false;
  6159. } else
  6160. return false;
  6161. // Now we just need to check that EltSize & Mask == Width & Mask.
  6162. if (MaskLoBits)
  6163. // EltSize & Mask is 0 since Mask is EltSize - 1.
  6164. return Width.getLoBits(MaskLoBits) == 0;
  6165. return Width == EltSize;
  6166. }
  6167. // A subroutine of MatchRotate used once we have found an OR of two opposite
  6168. // shifts of Shifted. If Neg == <operand size> - Pos then the OR reduces
  6169. // to both (PosOpcode Shifted, Pos) and (NegOpcode Shifted, Neg), with the
  6170. // former being preferred if supported. InnerPos and InnerNeg are Pos and
  6171. // Neg with outer conversions stripped away.
  6172. SDValue DAGCombiner::MatchRotatePosNeg(SDValue Shifted, SDValue Pos,
  6173. SDValue Neg, SDValue InnerPos,
  6174. SDValue InnerNeg, unsigned PosOpcode,
  6175. unsigned NegOpcode, const SDLoc &DL) {
  6176. // fold (or (shl x, (*ext y)),
  6177. // (srl x, (*ext (sub 32, y)))) ->
  6178. // (rotl x, y) or (rotr x, (sub 32, y))
  6179. //
  6180. // fold (or (shl x, (*ext (sub 32, y))),
  6181. // (srl x, (*ext y))) ->
  6182. // (rotr x, y) or (rotl x, (sub 32, y))
  6183. EVT VT = Shifted.getValueType();
  6184. if (matchRotateSub(InnerPos, InnerNeg, VT.getScalarSizeInBits(), DAG,
  6185. /*IsRotate*/ true)) {
  6186. bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
  6187. return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, Shifted,
  6188. HasPos ? Pos : Neg);
  6189. }
  6190. return SDValue();
  6191. }
  6192. // A subroutine of MatchRotate used once we have found an OR of two opposite
  6193. // shifts of N0 + N1. If Neg == <operand size> - Pos then the OR reduces
  6194. // to both (PosOpcode N0, N1, Pos) and (NegOpcode N0, N1, Neg), with the
  6195. // former being preferred if supported. InnerPos and InnerNeg are Pos and
  6196. // Neg with outer conversions stripped away.
  6197. // TODO: Merge with MatchRotatePosNeg.
  6198. SDValue DAGCombiner::MatchFunnelPosNeg(SDValue N0, SDValue N1, SDValue Pos,
  6199. SDValue Neg, SDValue InnerPos,
  6200. SDValue InnerNeg, unsigned PosOpcode,
  6201. unsigned NegOpcode, const SDLoc &DL) {
  6202. EVT VT = N0.getValueType();
  6203. unsigned EltBits = VT.getScalarSizeInBits();
  6204. // fold (or (shl x0, (*ext y)),
  6205. // (srl x1, (*ext (sub 32, y)))) ->
  6206. // (fshl x0, x1, y) or (fshr x0, x1, (sub 32, y))
  6207. //
  6208. // fold (or (shl x0, (*ext (sub 32, y))),
  6209. // (srl x1, (*ext y))) ->
  6210. // (fshr x0, x1, y) or (fshl x0, x1, (sub 32, y))
  6211. if (matchRotateSub(InnerPos, InnerNeg, EltBits, DAG, /*IsRotate*/ N0 == N1)) {
  6212. bool HasPos = TLI.isOperationLegalOrCustom(PosOpcode, VT);
  6213. return DAG.getNode(HasPos ? PosOpcode : NegOpcode, DL, VT, N0, N1,
  6214. HasPos ? Pos : Neg);
  6215. }
  6216. // Matching the shift+xor cases, we can't easily use the xor'd shift amount
  6217. // so for now just use the PosOpcode case if its legal.
  6218. // TODO: When can we use the NegOpcode case?
  6219. if (PosOpcode == ISD::FSHL && isPowerOf2_32(EltBits)) {
  6220. auto IsBinOpImm = [](SDValue Op, unsigned BinOpc, unsigned Imm) {
  6221. if (Op.getOpcode() != BinOpc)
  6222. return false;
  6223. ConstantSDNode *Cst = isConstOrConstSplat(Op.getOperand(1));
  6224. return Cst && (Cst->getAPIntValue() == Imm);
  6225. };
  6226. // fold (or (shl x0, y), (srl (srl x1, 1), (xor y, 31)))
  6227. // -> (fshl x0, x1, y)
  6228. if (IsBinOpImm(N1, ISD::SRL, 1) &&
  6229. IsBinOpImm(InnerNeg, ISD::XOR, EltBits - 1) &&
  6230. InnerPos == InnerNeg.getOperand(0) &&
  6231. TLI.isOperationLegalOrCustom(ISD::FSHL, VT)) {
  6232. return DAG.getNode(ISD::FSHL, DL, VT, N0, N1.getOperand(0), Pos);
  6233. }
  6234. // fold (or (shl (shl x0, 1), (xor y, 31)), (srl x1, y))
  6235. // -> (fshr x0, x1, y)
  6236. if (IsBinOpImm(N0, ISD::SHL, 1) &&
  6237. IsBinOpImm(InnerPos, ISD::XOR, EltBits - 1) &&
  6238. InnerNeg == InnerPos.getOperand(0) &&
  6239. TLI.isOperationLegalOrCustom(ISD::FSHR, VT)) {
  6240. return DAG.getNode(ISD::FSHR, DL, VT, N0.getOperand(0), N1, Neg);
  6241. }
  6242. // fold (or (shl (add x0, x0), (xor y, 31)), (srl x1, y))
  6243. // -> (fshr x0, x1, y)
  6244. // TODO: Should add(x,x) -> shl(x,1) be a general DAG canonicalization?
  6245. if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N0.getOperand(1) &&
  6246. IsBinOpImm(InnerPos, ISD::XOR, EltBits - 1) &&
  6247. InnerNeg == InnerPos.getOperand(0) &&
  6248. TLI.isOperationLegalOrCustom(ISD::FSHR, VT)) {
  6249. return DAG.getNode(ISD::FSHR, DL, VT, N0.getOperand(0), N1, Neg);
  6250. }
  6251. }
  6252. return SDValue();
  6253. }
  6254. // MatchRotate - Handle an 'or' of two operands. If this is one of the many
  6255. // idioms for rotate, and if the target supports rotation instructions, generate
  6256. // a rot[lr]. This also matches funnel shift patterns, similar to rotation but
  6257. // with different shifted sources.
  6258. SDValue DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, const SDLoc &DL) {
  6259. EVT VT = LHS.getValueType();
  6260. // The target must have at least one rotate/funnel flavor.
  6261. // We still try to match rotate by constant pre-legalization.
  6262. // TODO: Support pre-legalization funnel-shift by constant.
  6263. bool HasROTL = hasOperation(ISD::ROTL, VT);
  6264. bool HasROTR = hasOperation(ISD::ROTR, VT);
  6265. bool HasFSHL = hasOperation(ISD::FSHL, VT);
  6266. bool HasFSHR = hasOperation(ISD::FSHR, VT);
  6267. if (LegalOperations && !HasROTL && !HasROTR && !HasFSHL && !HasFSHR)
  6268. return SDValue();
  6269. // Check for truncated rotate.
  6270. if (LHS.getOpcode() == ISD::TRUNCATE && RHS.getOpcode() == ISD::TRUNCATE &&
  6271. LHS.getOperand(0).getValueType() == RHS.getOperand(0).getValueType()) {
  6272. assert(LHS.getValueType() == RHS.getValueType());
  6273. if (SDValue Rot = MatchRotate(LHS.getOperand(0), RHS.getOperand(0), DL)) {
  6274. return DAG.getNode(ISD::TRUNCATE, SDLoc(LHS), LHS.getValueType(), Rot);
  6275. }
  6276. }
  6277. // Match "(X shl/srl V1) & V2" where V2 may not be present.
  6278. SDValue LHSShift; // The shift.
  6279. SDValue LHSMask; // AND value if any.
  6280. matchRotateHalf(DAG, LHS, LHSShift, LHSMask);
  6281. SDValue RHSShift; // The shift.
  6282. SDValue RHSMask; // AND value if any.
  6283. matchRotateHalf(DAG, RHS, RHSShift, RHSMask);
  6284. // If neither side matched a rotate half, bail
  6285. if (!LHSShift && !RHSShift)
  6286. return SDValue();
  6287. // InstCombine may have combined a constant shl, srl, mul, or udiv with one
  6288. // side of the rotate, so try to handle that here. In all cases we need to
  6289. // pass the matched shift from the opposite side to compute the opcode and
  6290. // needed shift amount to extract. We still want to do this if both sides
  6291. // matched a rotate half because one half may be a potential overshift that
  6292. // can be broken down (ie if InstCombine merged two shl or srl ops into a
  6293. // single one).
  6294. // Have LHS side of the rotate, try to extract the needed shift from the RHS.
  6295. if (LHSShift)
  6296. if (SDValue NewRHSShift =
  6297. extractShiftForRotate(DAG, LHSShift, RHS, RHSMask, DL))
  6298. RHSShift = NewRHSShift;
  6299. // Have RHS side of the rotate, try to extract the needed shift from the LHS.
  6300. if (RHSShift)
  6301. if (SDValue NewLHSShift =
  6302. extractShiftForRotate(DAG, RHSShift, LHS, LHSMask, DL))
  6303. LHSShift = NewLHSShift;
  6304. // If a side is still missing, nothing else we can do.
  6305. if (!RHSShift || !LHSShift)
  6306. return SDValue();
  6307. // At this point we've matched or extracted a shift op on each side.
  6308. if (LHSShift.getOpcode() == RHSShift.getOpcode())
  6309. return SDValue(); // Shifts must disagree.
  6310. // TODO: Support pre-legalization funnel-shift by constant.
  6311. bool IsRotate = LHSShift.getOperand(0) == RHSShift.getOperand(0);
  6312. if (!IsRotate && !(HasFSHL || HasFSHR))
  6313. return SDValue(); // Requires funnel shift support.
  6314. // Canonicalize shl to left side in a shl/srl pair.
  6315. if (RHSShift.getOpcode() == ISD::SHL) {
  6316. std::swap(LHS, RHS);
  6317. std::swap(LHSShift, RHSShift);
  6318. std::swap(LHSMask, RHSMask);
  6319. }
  6320. unsigned EltSizeInBits = VT.getScalarSizeInBits();
  6321. SDValue LHSShiftArg = LHSShift.getOperand(0);
  6322. SDValue LHSShiftAmt = LHSShift.getOperand(1);
  6323. SDValue RHSShiftArg = RHSShift.getOperand(0);
  6324. SDValue RHSShiftAmt = RHSShift.getOperand(1);
  6325. // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
  6326. // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
  6327. // fold (or (shl x, C1), (srl y, C2)) -> (fshl x, y, C1)
  6328. // fold (or (shl x, C1), (srl y, C2)) -> (fshr x, y, C2)
  6329. // iff C1+C2 == EltSizeInBits
  6330. auto MatchRotateSum = [EltSizeInBits](ConstantSDNode *LHS,
  6331. ConstantSDNode *RHS) {
  6332. return (LHS->getAPIntValue() + RHS->getAPIntValue()) == EltSizeInBits;
  6333. };
  6334. if (ISD::matchBinaryPredicate(LHSShiftAmt, RHSShiftAmt, MatchRotateSum)) {
  6335. SDValue Res;
  6336. if (IsRotate && (HasROTL || HasROTR || !(HasFSHL || HasFSHR))) {
  6337. bool UseROTL = !LegalOperations || HasROTL;
  6338. Res = DAG.getNode(UseROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
  6339. UseROTL ? LHSShiftAmt : RHSShiftAmt);
  6340. } else {
  6341. bool UseFSHL = !LegalOperations || HasFSHL;
  6342. Res = DAG.getNode(UseFSHL ? ISD::FSHL : ISD::FSHR, DL, VT, LHSShiftArg,
  6343. RHSShiftArg, UseFSHL ? LHSShiftAmt : RHSShiftAmt);
  6344. }
  6345. // If there is an AND of either shifted operand, apply it to the result.
  6346. if (LHSMask.getNode() || RHSMask.getNode()) {
  6347. SDValue AllOnes = DAG.getAllOnesConstant(DL, VT);
  6348. SDValue Mask = AllOnes;
  6349. if (LHSMask.getNode()) {
  6350. SDValue RHSBits = DAG.getNode(ISD::SRL, DL, VT, AllOnes, RHSShiftAmt);
  6351. Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
  6352. DAG.getNode(ISD::OR, DL, VT, LHSMask, RHSBits));
  6353. }
  6354. if (RHSMask.getNode()) {
  6355. SDValue LHSBits = DAG.getNode(ISD::SHL, DL, VT, AllOnes, LHSShiftAmt);
  6356. Mask = DAG.getNode(ISD::AND, DL, VT, Mask,
  6357. DAG.getNode(ISD::OR, DL, VT, RHSMask, LHSBits));
  6358. }
  6359. Res = DAG.getNode(ISD::AND, DL, VT, Res, Mask);
  6360. }
  6361. return Res;
  6362. }
  6363. // Even pre-legalization, we can't easily rotate/funnel-shift by a variable
  6364. // shift.
  6365. if (!HasROTL && !HasROTR && !HasFSHL && !HasFSHR)
  6366. return SDValue();
  6367. // If there is a mask here, and we have a variable shift, we can't be sure
  6368. // that we're masking out the right stuff.
  6369. if (LHSMask.getNode() || RHSMask.getNode())
  6370. return SDValue();
  6371. // If the shift amount is sign/zext/any-extended just peel it off.
  6372. SDValue LExtOp0 = LHSShiftAmt;
  6373. SDValue RExtOp0 = RHSShiftAmt;
  6374. if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
  6375. LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
  6376. LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
  6377. LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
  6378. (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
  6379. RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
  6380. RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
  6381. RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
  6382. LExtOp0 = LHSShiftAmt.getOperand(0);
  6383. RExtOp0 = RHSShiftAmt.getOperand(0);
  6384. }
  6385. if (IsRotate && (HasROTL || HasROTR)) {
  6386. SDValue TryL =
  6387. MatchRotatePosNeg(LHSShiftArg, LHSShiftAmt, RHSShiftAmt, LExtOp0,
  6388. RExtOp0, ISD::ROTL, ISD::ROTR, DL);
  6389. if (TryL)
  6390. return TryL;
  6391. SDValue TryR =
  6392. MatchRotatePosNeg(RHSShiftArg, RHSShiftAmt, LHSShiftAmt, RExtOp0,
  6393. LExtOp0, ISD::ROTR, ISD::ROTL, DL);
  6394. if (TryR)
  6395. return TryR;
  6396. }
  6397. SDValue TryL =
  6398. MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, LHSShiftAmt, RHSShiftAmt,
  6399. LExtOp0, RExtOp0, ISD::FSHL, ISD::FSHR, DL);
  6400. if (TryL)
  6401. return TryL;
  6402. SDValue TryR =
  6403. MatchFunnelPosNeg(LHSShiftArg, RHSShiftArg, RHSShiftAmt, LHSShiftAmt,
  6404. RExtOp0, LExtOp0, ISD::FSHR, ISD::FSHL, DL);
  6405. if (TryR)
  6406. return TryR;
  6407. return SDValue();
  6408. }
  6409. namespace {
  6410. /// Represents known origin of an individual byte in load combine pattern. The
  6411. /// value of the byte is either constant zero or comes from memory.
  6412. struct ByteProvider {
  6413. // For constant zero providers Load is set to nullptr. For memory providers
  6414. // Load represents the node which loads the byte from memory.
  6415. // ByteOffset is the offset of the byte in the value produced by the load.
  6416. LoadSDNode *Load = nullptr;
  6417. unsigned ByteOffset = 0;
  6418. ByteProvider() = default;
  6419. static ByteProvider getMemory(LoadSDNode *Load, unsigned ByteOffset) {
  6420. return ByteProvider(Load, ByteOffset);
  6421. }
  6422. static ByteProvider getConstantZero() { return ByteProvider(nullptr, 0); }
  6423. bool isConstantZero() const { return !Load; }
  6424. bool isMemory() const { return Load; }
  6425. bool operator==(const ByteProvider &Other) const {
  6426. return Other.Load == Load && Other.ByteOffset == ByteOffset;
  6427. }
  6428. private:
  6429. ByteProvider(LoadSDNode *Load, unsigned ByteOffset)
  6430. : Load(Load), ByteOffset(ByteOffset) {}
  6431. };
  6432. } // end anonymous namespace
  6433. /// Recursively traverses the expression calculating the origin of the requested
  6434. /// byte of the given value. Returns None if the provider can't be calculated.
  6435. ///
  6436. /// For all the values except the root of the expression verifies that the value
  6437. /// has exactly one use and if it's not true return None. This way if the origin
  6438. /// of the byte is returned it's guaranteed that the values which contribute to
  6439. /// the byte are not used outside of this expression.
  6440. ///
  6441. /// Because the parts of the expression are not allowed to have more than one
  6442. /// use this function iterates over trees, not DAGs. So it never visits the same
  6443. /// node more than once.
  6444. static const Optional<ByteProvider>
  6445. calculateByteProvider(SDValue Op, unsigned Index, unsigned Depth,
  6446. bool Root = false) {
  6447. // Typical i64 by i8 pattern requires recursion up to 8 calls depth
  6448. if (Depth == 10)
  6449. return None;
  6450. if (!Root && !Op.hasOneUse())
  6451. return None;
  6452. assert(Op.getValueType().isScalarInteger() && "can't handle other types");
  6453. unsigned BitWidth = Op.getValueSizeInBits();
  6454. if (BitWidth % 8 != 0)
  6455. return None;
  6456. unsigned ByteWidth = BitWidth / 8;
  6457. assert(Index < ByteWidth && "invalid index requested");
  6458. (void) ByteWidth;
  6459. switch (Op.getOpcode()) {
  6460. case ISD::OR: {
  6461. auto LHS = calculateByteProvider(Op->getOperand(0), Index, Depth + 1);
  6462. if (!LHS)
  6463. return None;
  6464. auto RHS = calculateByteProvider(Op->getOperand(1), Index, Depth + 1);
  6465. if (!RHS)
  6466. return None;
  6467. if (LHS->isConstantZero())
  6468. return RHS;
  6469. if (RHS->isConstantZero())
  6470. return LHS;
  6471. return None;
  6472. }
  6473. case ISD::SHL: {
  6474. auto ShiftOp = dyn_cast<ConstantSDNode>(Op->getOperand(1));
  6475. if (!ShiftOp)
  6476. return None;
  6477. uint64_t BitShift = ShiftOp->getZExtValue();
  6478. if (BitShift % 8 != 0)
  6479. return None;
  6480. uint64_t ByteShift = BitShift / 8;
  6481. return Index < ByteShift
  6482. ? ByteProvider::getConstantZero()
  6483. : calculateByteProvider(Op->getOperand(0), Index - ByteShift,
  6484. Depth + 1);
  6485. }
  6486. case ISD::ANY_EXTEND:
  6487. case ISD::SIGN_EXTEND:
  6488. case ISD::ZERO_EXTEND: {
  6489. SDValue NarrowOp = Op->getOperand(0);
  6490. unsigned NarrowBitWidth = NarrowOp.getScalarValueSizeInBits();
  6491. if (NarrowBitWidth % 8 != 0)
  6492. return None;
  6493. uint64_t NarrowByteWidth = NarrowBitWidth / 8;
  6494. if (Index >= NarrowByteWidth)
  6495. return Op.getOpcode() == ISD::ZERO_EXTEND
  6496. ? Optional<ByteProvider>(ByteProvider::getConstantZero())
  6497. : None;
  6498. return calculateByteProvider(NarrowOp, Index, Depth + 1);
  6499. }
  6500. case ISD::BSWAP:
  6501. return calculateByteProvider(Op->getOperand(0), ByteWidth - Index - 1,
  6502. Depth + 1);
  6503. case ISD::LOAD: {
  6504. auto L = cast<LoadSDNode>(Op.getNode());
  6505. if (!L->isSimple() || L->isIndexed())
  6506. return None;
  6507. unsigned NarrowBitWidth = L->getMemoryVT().getSizeInBits();
  6508. if (NarrowBitWidth % 8 != 0)
  6509. return None;
  6510. uint64_t NarrowByteWidth = NarrowBitWidth / 8;
  6511. if (Index >= NarrowByteWidth)
  6512. return L->getExtensionType() == ISD::ZEXTLOAD
  6513. ? Optional<ByteProvider>(ByteProvider::getConstantZero())
  6514. : None;
  6515. return ByteProvider::getMemory(L, Index);
  6516. }
  6517. }
  6518. return None;
  6519. }
  6520. static unsigned littleEndianByteAt(unsigned BW, unsigned i) {
  6521. return i;
  6522. }
  6523. static unsigned bigEndianByteAt(unsigned BW, unsigned i) {
  6524. return BW - i - 1;
  6525. }
  6526. // Check if the bytes offsets we are looking at match with either big or
  6527. // little endian value loaded. Return true for big endian, false for little
  6528. // endian, and None if match failed.
  6529. static Optional<bool> isBigEndian(const ArrayRef<int64_t> ByteOffsets,
  6530. int64_t FirstOffset) {
  6531. // The endian can be decided only when it is 2 bytes at least.
  6532. unsigned Width = ByteOffsets.size();
  6533. if (Width < 2)
  6534. return None;
  6535. bool BigEndian = true, LittleEndian = true;
  6536. for (unsigned i = 0; i < Width; i++) {
  6537. int64_t CurrentByteOffset = ByteOffsets[i] - FirstOffset;
  6538. LittleEndian &= CurrentByteOffset == littleEndianByteAt(Width, i);
  6539. BigEndian &= CurrentByteOffset == bigEndianByteAt(Width, i);
  6540. if (!BigEndian && !LittleEndian)
  6541. return None;
  6542. }
  6543. assert((BigEndian != LittleEndian) && "It should be either big endian or"
  6544. "little endian");
  6545. return BigEndian;
  6546. }
  6547. static SDValue stripTruncAndExt(SDValue Value) {
  6548. switch (Value.getOpcode()) {
  6549. case ISD::TRUNCATE:
  6550. case ISD::ZERO_EXTEND:
  6551. case ISD::SIGN_EXTEND:
  6552. case ISD::ANY_EXTEND:
  6553. return stripTruncAndExt(Value.getOperand(0));
  6554. }
  6555. return Value;
  6556. }
  6557. /// Match a pattern where a wide type scalar value is stored by several narrow
  6558. /// stores. Fold it into a single store or a BSWAP and a store if the targets
  6559. /// supports it.
  6560. ///
  6561. /// Assuming little endian target:
  6562. /// i8 *p = ...
  6563. /// i32 val = ...
  6564. /// p[0] = (val >> 0) & 0xFF;
  6565. /// p[1] = (val >> 8) & 0xFF;
  6566. /// p[2] = (val >> 16) & 0xFF;
  6567. /// p[3] = (val >> 24) & 0xFF;
  6568. /// =>
  6569. /// *((i32)p) = val;
  6570. ///
  6571. /// i8 *p = ...
  6572. /// i32 val = ...
  6573. /// p[0] = (val >> 24) & 0xFF;
  6574. /// p[1] = (val >> 16) & 0xFF;
  6575. /// p[2] = (val >> 8) & 0xFF;
  6576. /// p[3] = (val >> 0) & 0xFF;
  6577. /// =>
  6578. /// *((i32)p) = BSWAP(val);
  6579. SDValue DAGCombiner::mergeTruncStores(StoreSDNode *N) {
  6580. // The matching looks for "store (trunc x)" patterns that appear early but are
  6581. // likely to be replaced by truncating store nodes during combining.
  6582. // TODO: If there is evidence that running this later would help, this
  6583. // limitation could be removed. Legality checks may need to be added
  6584. // for the created store and optional bswap/rotate.
  6585. if (LegalOperations || OptLevel == CodeGenOpt::None)
  6586. return SDValue();
  6587. // We only handle merging simple stores of 1-4 bytes.
  6588. // TODO: Allow unordered atomics when wider type is legal (see D66309)
  6589. EVT MemVT = N->getMemoryVT();
  6590. if (!(MemVT == MVT::i8 || MemVT == MVT::i16 || MemVT == MVT::i32) ||
  6591. !N->isSimple() || N->isIndexed())
  6592. return SDValue();
  6593. // Collect all of the stores in the chain.
  6594. SDValue Chain = N->getChain();
  6595. SmallVector<StoreSDNode *, 8> Stores = {N};
  6596. while (auto *Store = dyn_cast<StoreSDNode>(Chain)) {
  6597. // All stores must be the same size to ensure that we are writing all of the
  6598. // bytes in the wide value.
  6599. // TODO: We could allow multiple sizes by tracking each stored byte.
  6600. if (Store->getMemoryVT() != MemVT || !Store->isSimple() ||
  6601. Store->isIndexed())
  6602. return SDValue();
  6603. Stores.push_back(Store);
  6604. Chain = Store->getChain();
  6605. }
  6606. // There is no reason to continue if we do not have at least a pair of stores.
  6607. if (Stores.size() < 2)
  6608. return SDValue();
  6609. // Handle simple types only.
  6610. LLVMContext &Context = *DAG.getContext();
  6611. unsigned NumStores = Stores.size();
  6612. unsigned NarrowNumBits = N->getMemoryVT().getScalarSizeInBits();
  6613. unsigned WideNumBits = NumStores * NarrowNumBits;
  6614. EVT WideVT = EVT::getIntegerVT(Context, WideNumBits);
  6615. if (WideVT != MVT::i16 && WideVT != MVT::i32 && WideVT != MVT::i64)
  6616. return SDValue();
  6617. // Check if all bytes of the source value that we are looking at are stored
  6618. // to the same base address. Collect offsets from Base address into OffsetMap.
  6619. SDValue SourceValue;
  6620. SmallVector<int64_t, 8> OffsetMap(NumStores, INT64_MAX);
  6621. int64_t FirstOffset = INT64_MAX;
  6622. StoreSDNode *FirstStore = nullptr;
  6623. Optional<BaseIndexOffset> Base;
  6624. for (auto Store : Stores) {
  6625. // All the stores store different parts of the CombinedValue. A truncate is
  6626. // required to get the partial value.
  6627. SDValue Trunc = Store->getValue();
  6628. if (Trunc.getOpcode() != ISD::TRUNCATE)
  6629. return SDValue();
  6630. // Other than the first/last part, a shift operation is required to get the
  6631. // offset.
  6632. int64_t Offset = 0;
  6633. SDValue WideVal = Trunc.getOperand(0);
  6634. if ((WideVal.getOpcode() == ISD::SRL || WideVal.getOpcode() == ISD::SRA) &&
  6635. isa<ConstantSDNode>(WideVal.getOperand(1))) {
  6636. // The shift amount must be a constant multiple of the narrow type.
  6637. // It is translated to the offset address in the wide source value "y".
  6638. //
  6639. // x = srl y, ShiftAmtC
  6640. // i8 z = trunc x
  6641. // store z, ...
  6642. uint64_t ShiftAmtC = WideVal.getConstantOperandVal(1);
  6643. if (ShiftAmtC % NarrowNumBits != 0)
  6644. return SDValue();
  6645. Offset = ShiftAmtC / NarrowNumBits;
  6646. WideVal = WideVal.getOperand(0);
  6647. }
  6648. // Stores must share the same source value with different offsets.
  6649. // Truncate and extends should be stripped to get the single source value.
  6650. if (!SourceValue)
  6651. SourceValue = WideVal;
  6652. else if (stripTruncAndExt(SourceValue) != stripTruncAndExt(WideVal))
  6653. return SDValue();
  6654. else if (SourceValue.getValueType() != WideVT) {
  6655. if (WideVal.getValueType() == WideVT ||
  6656. WideVal.getScalarValueSizeInBits() >
  6657. SourceValue.getScalarValueSizeInBits())
  6658. SourceValue = WideVal;
  6659. // Give up if the source value type is smaller than the store size.
  6660. if (SourceValue.getScalarValueSizeInBits() < WideVT.getScalarSizeInBits())
  6661. return SDValue();
  6662. }
  6663. // Stores must share the same base address.
  6664. BaseIndexOffset Ptr = BaseIndexOffset::match(Store, DAG);
  6665. int64_t ByteOffsetFromBase = 0;
  6666. if (!Base)
  6667. Base = Ptr;
  6668. else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
  6669. return SDValue();
  6670. // Remember the first store.
  6671. if (ByteOffsetFromBase < FirstOffset) {
  6672. FirstStore = Store;
  6673. FirstOffset = ByteOffsetFromBase;
  6674. }
  6675. // Map the offset in the store and the offset in the combined value, and
  6676. // early return if it has been set before.
  6677. if (Offset < 0 || Offset >= NumStores || OffsetMap[Offset] != INT64_MAX)
  6678. return SDValue();
  6679. OffsetMap[Offset] = ByteOffsetFromBase;
  6680. }
  6681. assert(FirstOffset != INT64_MAX && "First byte offset must be set");
  6682. assert(FirstStore && "First store must be set");
  6683. // Check that a store of the wide type is both allowed and fast on the target
  6684. const DataLayout &Layout = DAG.getDataLayout();
  6685. bool Fast = false;
  6686. bool Allowed = TLI.allowsMemoryAccess(Context, Layout, WideVT,
  6687. *FirstStore->getMemOperand(), &Fast);
  6688. if (!Allowed || !Fast)
  6689. return SDValue();
  6690. // Check if the pieces of the value are going to the expected places in memory
  6691. // to merge the stores.
  6692. auto checkOffsets = [&](bool MatchLittleEndian) {
  6693. if (MatchLittleEndian) {
  6694. for (unsigned i = 0; i != NumStores; ++i)
  6695. if (OffsetMap[i] != i * (NarrowNumBits / 8) + FirstOffset)
  6696. return false;
  6697. } else { // MatchBigEndian by reversing loop counter.
  6698. for (unsigned i = 0, j = NumStores - 1; i != NumStores; ++i, --j)
  6699. if (OffsetMap[j] != i * (NarrowNumBits / 8) + FirstOffset)
  6700. return false;
  6701. }
  6702. return true;
  6703. };
  6704. // Check if the offsets line up for the native data layout of this target.
  6705. bool NeedBswap = false;
  6706. bool NeedRotate = false;
  6707. if (!checkOffsets(Layout.isLittleEndian())) {
  6708. // Special-case: check if byte offsets line up for the opposite endian.
  6709. if (NarrowNumBits == 8 && checkOffsets(Layout.isBigEndian()))
  6710. NeedBswap = true;
  6711. else if (NumStores == 2 && checkOffsets(Layout.isBigEndian()))
  6712. NeedRotate = true;
  6713. else
  6714. return SDValue();
  6715. }
  6716. SDLoc DL(N);
  6717. if (WideVT != SourceValue.getValueType()) {
  6718. assert(SourceValue.getValueType().getScalarSizeInBits() > WideNumBits &&
  6719. "Unexpected store value to merge");
  6720. SourceValue = DAG.getNode(ISD::TRUNCATE, DL, WideVT, SourceValue);
  6721. }
  6722. // Before legalize we can introduce illegal bswaps/rotates which will be later
  6723. // converted to an explicit bswap sequence. This way we end up with a single
  6724. // store and byte shuffling instead of several stores and byte shuffling.
  6725. if (NeedBswap) {
  6726. SourceValue = DAG.getNode(ISD::BSWAP, DL, WideVT, SourceValue);
  6727. } else if (NeedRotate) {
  6728. assert(WideNumBits % 2 == 0 && "Unexpected type for rotate");
  6729. SDValue RotAmt = DAG.getConstant(WideNumBits / 2, DL, WideVT);
  6730. SourceValue = DAG.getNode(ISD::ROTR, DL, WideVT, SourceValue, RotAmt);
  6731. }
  6732. SDValue NewStore =
  6733. DAG.getStore(Chain, DL, SourceValue, FirstStore->getBasePtr(),
  6734. FirstStore->getPointerInfo(), FirstStore->getAlign());
  6735. // Rely on other DAG combine rules to remove the other individual stores.
  6736. DAG.ReplaceAllUsesWith(N, NewStore.getNode());
  6737. return NewStore;
  6738. }
  6739. /// Match a pattern where a wide type scalar value is loaded by several narrow
  6740. /// loads and combined by shifts and ors. Fold it into a single load or a load
  6741. /// and a BSWAP if the targets supports it.
  6742. ///
  6743. /// Assuming little endian target:
  6744. /// i8 *a = ...
  6745. /// i32 val = a[0] | (a[1] << 8) | (a[2] << 16) | (a[3] << 24)
  6746. /// =>
  6747. /// i32 val = *((i32)a)
  6748. ///
  6749. /// i8 *a = ...
  6750. /// i32 val = (a[0] << 24) | (a[1] << 16) | (a[2] << 8) | a[3]
  6751. /// =>
  6752. /// i32 val = BSWAP(*((i32)a))
  6753. ///
  6754. /// TODO: This rule matches complex patterns with OR node roots and doesn't
  6755. /// interact well with the worklist mechanism. When a part of the pattern is
  6756. /// updated (e.g. one of the loads) its direct users are put into the worklist,
  6757. /// but the root node of the pattern which triggers the load combine is not
  6758. /// necessarily a direct user of the changed node. For example, once the address
  6759. /// of t28 load is reassociated load combine won't be triggered:
  6760. /// t25: i32 = add t4, Constant:i32<2>
  6761. /// t26: i64 = sign_extend t25
  6762. /// t27: i64 = add t2, t26
  6763. /// t28: i8,ch = load<LD1[%tmp9]> t0, t27, undef:i64
  6764. /// t29: i32 = zero_extend t28
  6765. /// t32: i32 = shl t29, Constant:i8<8>
  6766. /// t33: i32 = or t23, t32
  6767. /// As a possible fix visitLoad can check if the load can be a part of a load
  6768. /// combine pattern and add corresponding OR roots to the worklist.
  6769. SDValue DAGCombiner::MatchLoadCombine(SDNode *N) {
  6770. assert(N->getOpcode() == ISD::OR &&
  6771. "Can only match load combining against OR nodes");
  6772. // Handles simple types only
  6773. EVT VT = N->getValueType(0);
  6774. if (VT != MVT::i16 && VT != MVT::i32 && VT != MVT::i64)
  6775. return SDValue();
  6776. unsigned ByteWidth = VT.getSizeInBits() / 8;
  6777. bool IsBigEndianTarget = DAG.getDataLayout().isBigEndian();
  6778. auto MemoryByteOffset = [&] (ByteProvider P) {
  6779. assert(P.isMemory() && "Must be a memory byte provider");
  6780. unsigned LoadBitWidth = P.Load->getMemoryVT().getSizeInBits();
  6781. assert(LoadBitWidth % 8 == 0 &&
  6782. "can only analyze providers for individual bytes not bit");
  6783. unsigned LoadByteWidth = LoadBitWidth / 8;
  6784. return IsBigEndianTarget
  6785. ? bigEndianByteAt(LoadByteWidth, P.ByteOffset)
  6786. : littleEndianByteAt(LoadByteWidth, P.ByteOffset);
  6787. };
  6788. Optional<BaseIndexOffset> Base;
  6789. SDValue Chain;
  6790. SmallPtrSet<LoadSDNode *, 8> Loads;
  6791. Optional<ByteProvider> FirstByteProvider;
  6792. int64_t FirstOffset = INT64_MAX;
  6793. // Check if all the bytes of the OR we are looking at are loaded from the same
  6794. // base address. Collect bytes offsets from Base address in ByteOffsets.
  6795. SmallVector<int64_t, 8> ByteOffsets(ByteWidth);
  6796. unsigned ZeroExtendedBytes = 0;
  6797. for (int i = ByteWidth - 1; i >= 0; --i) {
  6798. auto P = calculateByteProvider(SDValue(N, 0), i, 0, /*Root=*/true);
  6799. if (!P)
  6800. return SDValue();
  6801. if (P->isConstantZero()) {
  6802. // It's OK for the N most significant bytes to be 0, we can just
  6803. // zero-extend the load.
  6804. if (++ZeroExtendedBytes != (ByteWidth - static_cast<unsigned>(i)))
  6805. return SDValue();
  6806. continue;
  6807. }
  6808. assert(P->isMemory() && "provenance should either be memory or zero");
  6809. LoadSDNode *L = P->Load;
  6810. assert(L->hasNUsesOfValue(1, 0) && L->isSimple() &&
  6811. !L->isIndexed() &&
  6812. "Must be enforced by calculateByteProvider");
  6813. assert(L->getOffset().isUndef() && "Unindexed load must have undef offset");
  6814. // All loads must share the same chain
  6815. SDValue LChain = L->getChain();
  6816. if (!Chain)
  6817. Chain = LChain;
  6818. else if (Chain != LChain)
  6819. return SDValue();
  6820. // Loads must share the same base address
  6821. BaseIndexOffset Ptr = BaseIndexOffset::match(L, DAG);
  6822. int64_t ByteOffsetFromBase = 0;
  6823. if (!Base)
  6824. Base = Ptr;
  6825. else if (!Base->equalBaseIndex(Ptr, DAG, ByteOffsetFromBase))
  6826. return SDValue();
  6827. // Calculate the offset of the current byte from the base address
  6828. ByteOffsetFromBase += MemoryByteOffset(*P);
  6829. ByteOffsets[i] = ByteOffsetFromBase;
  6830. // Remember the first byte load
  6831. if (ByteOffsetFromBase < FirstOffset) {
  6832. FirstByteProvider = P;
  6833. FirstOffset = ByteOffsetFromBase;
  6834. }
  6835. Loads.insert(L);
  6836. }
  6837. assert(!Loads.empty() && "All the bytes of the value must be loaded from "
  6838. "memory, so there must be at least one load which produces the value");
  6839. assert(Base && "Base address of the accessed memory location must be set");
  6840. assert(FirstOffset != INT64_MAX && "First byte offset must be set");
  6841. bool NeedsZext = ZeroExtendedBytes > 0;
  6842. EVT MemVT =
  6843. EVT::getIntegerVT(*DAG.getContext(), (ByteWidth - ZeroExtendedBytes) * 8);
  6844. if (!MemVT.isSimple())
  6845. return SDValue();
  6846. // Before legalize we can introduce too wide illegal loads which will be later
  6847. // split into legal sized loads. This enables us to combine i64 load by i8
  6848. // patterns to a couple of i32 loads on 32 bit targets.
  6849. if (LegalOperations &&
  6850. !TLI.isOperationLegal(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD,
  6851. MemVT))
  6852. return SDValue();
  6853. // Check if the bytes of the OR we are looking at match with either big or
  6854. // little endian value load
  6855. Optional<bool> IsBigEndian = isBigEndian(
  6856. makeArrayRef(ByteOffsets).drop_back(ZeroExtendedBytes), FirstOffset);
  6857. if (!IsBigEndian.hasValue())
  6858. return SDValue();
  6859. assert(FirstByteProvider && "must be set");
  6860. // Ensure that the first byte is loaded from zero offset of the first load.
  6861. // So the combined value can be loaded from the first load address.
  6862. if (MemoryByteOffset(*FirstByteProvider) != 0)
  6863. return SDValue();
  6864. LoadSDNode *FirstLoad = FirstByteProvider->Load;
  6865. // The node we are looking at matches with the pattern, check if we can
  6866. // replace it with a single (possibly zero-extended) load and bswap + shift if
  6867. // needed.
  6868. // If the load needs byte swap check if the target supports it
  6869. bool NeedsBswap = IsBigEndianTarget != *IsBigEndian;
  6870. // Before legalize we can introduce illegal bswaps which will be later
  6871. // converted to an explicit bswap sequence. This way we end up with a single
  6872. // load and byte shuffling instead of several loads and byte shuffling.
  6873. // We do not introduce illegal bswaps when zero-extending as this tends to
  6874. // introduce too many arithmetic instructions.
  6875. if (NeedsBswap && (LegalOperations || NeedsZext) &&
  6876. !TLI.isOperationLegal(ISD::BSWAP, VT))
  6877. return SDValue();
  6878. // If we need to bswap and zero extend, we have to insert a shift. Check that
  6879. // it is legal.
  6880. if (NeedsBswap && NeedsZext && LegalOperations &&
  6881. !TLI.isOperationLegal(ISD::SHL, VT))
  6882. return SDValue();
  6883. // Check that a load of the wide type is both allowed and fast on the target
  6884. bool Fast = false;
  6885. bool Allowed =
  6886. TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), MemVT,
  6887. *FirstLoad->getMemOperand(), &Fast);
  6888. if (!Allowed || !Fast)
  6889. return SDValue();
  6890. SDValue NewLoad =
  6891. DAG.getExtLoad(NeedsZext ? ISD::ZEXTLOAD : ISD::NON_EXTLOAD, SDLoc(N), VT,
  6892. Chain, FirstLoad->getBasePtr(),
  6893. FirstLoad->getPointerInfo(), MemVT, FirstLoad->getAlign());
  6894. // Transfer chain users from old loads to the new load.
  6895. for (LoadSDNode *L : Loads)
  6896. DAG.ReplaceAllUsesOfValueWith(SDValue(L, 1), SDValue(NewLoad.getNode(), 1));
  6897. if (!NeedsBswap)
  6898. return NewLoad;
  6899. SDValue ShiftedLoad =
  6900. NeedsZext
  6901. ? DAG.getNode(ISD::SHL, SDLoc(N), VT, NewLoad,
  6902. DAG.getShiftAmountConstant(ZeroExtendedBytes * 8, VT,
  6903. SDLoc(N), LegalOperations))
  6904. : NewLoad;
  6905. return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, ShiftedLoad);
  6906. }
  6907. // If the target has andn, bsl, or a similar bit-select instruction,
  6908. // we want to unfold masked merge, with canonical pattern of:
  6909. // | A | |B|
  6910. // ((x ^ y) & m) ^ y
  6911. // | D |
  6912. // Into:
  6913. // (x & m) | (y & ~m)
  6914. // If y is a constant, m is not a 'not', and the 'andn' does not work with
  6915. // immediates, we unfold into a different pattern:
  6916. // ~(~x & m) & (m | y)
  6917. // If x is a constant, m is a 'not', and the 'andn' does not work with
  6918. // immediates, we unfold into a different pattern:
  6919. // (x | ~m) & ~(~m & ~y)
  6920. // NOTE: we don't unfold the pattern if 'xor' is actually a 'not', because at
  6921. // the very least that breaks andnpd / andnps patterns, and because those
  6922. // patterns are simplified in IR and shouldn't be created in the DAG
  6923. SDValue DAGCombiner::unfoldMaskedMerge(SDNode *N) {
  6924. assert(N->getOpcode() == ISD::XOR);
  6925. // Don't touch 'not' (i.e. where y = -1).
  6926. if (isAllOnesOrAllOnesSplat(N->getOperand(1)))
  6927. return SDValue();
  6928. EVT VT = N->getValueType(0);
  6929. // There are 3 commutable operators in the pattern,
  6930. // so we have to deal with 8 possible variants of the basic pattern.
  6931. SDValue X, Y, M;
  6932. auto matchAndXor = [&X, &Y, &M](SDValue And, unsigned XorIdx, SDValue Other) {
  6933. if (And.getOpcode() != ISD::AND || !And.hasOneUse())
  6934. return false;
  6935. SDValue Xor = And.getOperand(XorIdx);
  6936. if (Xor.getOpcode() != ISD::XOR || !Xor.hasOneUse())
  6937. return false;
  6938. SDValue Xor0 = Xor.getOperand(0);
  6939. SDValue Xor1 = Xor.getOperand(1);
  6940. // Don't touch 'not' (i.e. where y = -1).
  6941. if (isAllOnesOrAllOnesSplat(Xor1))
  6942. return false;
  6943. if (Other == Xor0)
  6944. std::swap(Xor0, Xor1);
  6945. if (Other != Xor1)
  6946. return false;
  6947. X = Xor0;
  6948. Y = Xor1;
  6949. M = And.getOperand(XorIdx ? 0 : 1);
  6950. return true;
  6951. };
  6952. SDValue N0 = N->getOperand(0);
  6953. SDValue N1 = N->getOperand(1);
  6954. if (!matchAndXor(N0, 0, N1) && !matchAndXor(N0, 1, N1) &&
  6955. !matchAndXor(N1, 0, N0) && !matchAndXor(N1, 1, N0))
  6956. return SDValue();
  6957. // Don't do anything if the mask is constant. This should not be reachable.
  6958. // InstCombine should have already unfolded this pattern, and DAGCombiner
  6959. // probably shouldn't produce it, too.
  6960. if (isa<ConstantSDNode>(M.getNode()))
  6961. return SDValue();
  6962. // We can transform if the target has AndNot
  6963. if (!TLI.hasAndNot(M))
  6964. return SDValue();
  6965. SDLoc DL(N);
  6966. // If Y is a constant, check that 'andn' works with immediates. Unless M is
  6967. // a bitwise not that would already allow ANDN to be used.
  6968. if (!TLI.hasAndNot(Y) && !isBitwiseNot(M)) {
  6969. assert(TLI.hasAndNot(X) && "Only mask is a variable? Unreachable.");
  6970. // If not, we need to do a bit more work to make sure andn is still used.
  6971. SDValue NotX = DAG.getNOT(DL, X, VT);
  6972. SDValue LHS = DAG.getNode(ISD::AND, DL, VT, NotX, M);
  6973. SDValue NotLHS = DAG.getNOT(DL, LHS, VT);
  6974. SDValue RHS = DAG.getNode(ISD::OR, DL, VT, M, Y);
  6975. return DAG.getNode(ISD::AND, DL, VT, NotLHS, RHS);
  6976. }
  6977. // If X is a constant and M is a bitwise not, check that 'andn' works with
  6978. // immediates.
  6979. if (!TLI.hasAndNot(X) && isBitwiseNot(M)) {
  6980. assert(TLI.hasAndNot(Y) && "Only mask is a variable? Unreachable.");
  6981. // If not, we need to do a bit more work to make sure andn is still used.
  6982. SDValue NotM = M.getOperand(0);
  6983. SDValue LHS = DAG.getNode(ISD::OR, DL, VT, X, NotM);
  6984. SDValue NotY = DAG.getNOT(DL, Y, VT);
  6985. SDValue RHS = DAG.getNode(ISD::AND, DL, VT, NotM, NotY);
  6986. SDValue NotRHS = DAG.getNOT(DL, RHS, VT);
  6987. return DAG.getNode(ISD::AND, DL, VT, LHS, NotRHS);
  6988. }
  6989. SDValue LHS = DAG.getNode(ISD::AND, DL, VT, X, M);
  6990. SDValue NotM = DAG.getNOT(DL, M, VT);
  6991. SDValue RHS = DAG.getNode(ISD::AND, DL, VT, Y, NotM);
  6992. return DAG.getNode(ISD::OR, DL, VT, LHS, RHS);
  6993. }
  6994. SDValue DAGCombiner::visitXOR(SDNode *N) {
  6995. SDValue N0 = N->getOperand(0);
  6996. SDValue N1 = N->getOperand(1);
  6997. EVT VT = N0.getValueType();
  6998. SDLoc DL(N);
  6999. // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
  7000. if (N0.isUndef() && N1.isUndef())
  7001. return DAG.getConstant(0, DL, VT);
  7002. // fold (xor x, undef) -> undef
  7003. if (N0.isUndef())
  7004. return N0;
  7005. if (N1.isUndef())
  7006. return N1;
  7007. // fold (xor c1, c2) -> c1^c2
  7008. if (SDValue C = DAG.FoldConstantArithmetic(ISD::XOR, DL, VT, {N0, N1}))
  7009. return C;
  7010. // canonicalize constant to RHS
  7011. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  7012. !DAG.isConstantIntBuildVectorOrConstantInt(N1))
  7013. return DAG.getNode(ISD::XOR, DL, VT, N1, N0);
  7014. // fold vector ops
  7015. if (VT.isVector()) {
  7016. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  7017. return FoldedVOp;
  7018. // fold (xor x, 0) -> x, vector edition
  7019. if (ISD::isConstantSplatVectorAllZeros(N1.getNode()))
  7020. return N0;
  7021. }
  7022. // fold (xor x, 0) -> x
  7023. if (isNullConstant(N1))
  7024. return N0;
  7025. if (SDValue NewSel = foldBinOpIntoSelect(N))
  7026. return NewSel;
  7027. // reassociate xor
  7028. if (SDValue RXOR = reassociateOps(ISD::XOR, DL, N0, N1, N->getFlags()))
  7029. return RXOR;
  7030. // fold !(x cc y) -> (x !cc y)
  7031. unsigned N0Opcode = N0.getOpcode();
  7032. SDValue LHS, RHS, CC;
  7033. if (TLI.isConstTrueVal(N1) &&
  7034. isSetCCEquivalent(N0, LHS, RHS, CC, /*MatchStrict*/ true)) {
  7035. ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
  7036. LHS.getValueType());
  7037. if (!LegalOperations ||
  7038. TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
  7039. switch (N0Opcode) {
  7040. default:
  7041. llvm_unreachable("Unhandled SetCC Equivalent!");
  7042. case ISD::SETCC:
  7043. return DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC);
  7044. case ISD::SELECT_CC:
  7045. return DAG.getSelectCC(SDLoc(N0), LHS, RHS, N0.getOperand(2),
  7046. N0.getOperand(3), NotCC);
  7047. case ISD::STRICT_FSETCC:
  7048. case ISD::STRICT_FSETCCS: {
  7049. if (N0.hasOneUse()) {
  7050. // FIXME Can we handle multiple uses? Could we token factor the chain
  7051. // results from the new/old setcc?
  7052. SDValue SetCC =
  7053. DAG.getSetCC(SDLoc(N0), VT, LHS, RHS, NotCC,
  7054. N0.getOperand(0), N0Opcode == ISD::STRICT_FSETCCS);
  7055. CombineTo(N, SetCC);
  7056. DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), SetCC.getValue(1));
  7057. recursivelyDeleteUnusedNodes(N0.getNode());
  7058. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  7059. }
  7060. break;
  7061. }
  7062. }
  7063. }
  7064. }
  7065. // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
  7066. if (isOneConstant(N1) && N0Opcode == ISD::ZERO_EXTEND && N0.hasOneUse() &&
  7067. isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
  7068. SDValue V = N0.getOperand(0);
  7069. SDLoc DL0(N0);
  7070. V = DAG.getNode(ISD::XOR, DL0, V.getValueType(), V,
  7071. DAG.getConstant(1, DL0, V.getValueType()));
  7072. AddToWorklist(V.getNode());
  7073. return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, V);
  7074. }
  7075. // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
  7076. if (isOneConstant(N1) && VT == MVT::i1 && N0.hasOneUse() &&
  7077. (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
  7078. SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
  7079. if (isOneUseSetCC(N01) || isOneUseSetCC(N00)) {
  7080. unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
  7081. N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00
  7082. N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01
  7083. AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode());
  7084. return DAG.getNode(NewOpcode, DL, VT, N00, N01);
  7085. }
  7086. }
  7087. // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
  7088. if (isAllOnesConstant(N1) && N0.hasOneUse() &&
  7089. (N0Opcode == ISD::OR || N0Opcode == ISD::AND)) {
  7090. SDValue N00 = N0.getOperand(0), N01 = N0.getOperand(1);
  7091. if (isa<ConstantSDNode>(N01) || isa<ConstantSDNode>(N00)) {
  7092. unsigned NewOpcode = N0Opcode == ISD::AND ? ISD::OR : ISD::AND;
  7093. N00 = DAG.getNode(ISD::XOR, SDLoc(N00), VT, N00, N1); // N00 = ~N00
  7094. N01 = DAG.getNode(ISD::XOR, SDLoc(N01), VT, N01, N1); // N01 = ~N01
  7095. AddToWorklist(N00.getNode()); AddToWorklist(N01.getNode());
  7096. return DAG.getNode(NewOpcode, DL, VT, N00, N01);
  7097. }
  7098. }
  7099. // fold (not (neg x)) -> (add X, -1)
  7100. // FIXME: This can be generalized to (not (sub Y, X)) -> (add X, ~Y) if
  7101. // Y is a constant or the subtract has a single use.
  7102. if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::SUB &&
  7103. isNullConstant(N0.getOperand(0))) {
  7104. return DAG.getNode(ISD::ADD, DL, VT, N0.getOperand(1),
  7105. DAG.getAllOnesConstant(DL, VT));
  7106. }
  7107. // fold (not (add X, -1)) -> (neg X)
  7108. if (isAllOnesConstant(N1) && N0.getOpcode() == ISD::ADD &&
  7109. isAllOnesOrAllOnesSplat(N0.getOperand(1))) {
  7110. return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT),
  7111. N0.getOperand(0));
  7112. }
  7113. // fold (xor (and x, y), y) -> (and (not x), y)
  7114. if (N0Opcode == ISD::AND && N0.hasOneUse() && N0->getOperand(1) == N1) {
  7115. SDValue X = N0.getOperand(0);
  7116. SDValue NotX = DAG.getNOT(SDLoc(X), X, VT);
  7117. AddToWorklist(NotX.getNode());
  7118. return DAG.getNode(ISD::AND, DL, VT, NotX, N1);
  7119. }
  7120. if ((N0Opcode == ISD::SRL || N0Opcode == ISD::SHL) && N0.hasOneUse()) {
  7121. ConstantSDNode *XorC = isConstOrConstSplat(N1);
  7122. ConstantSDNode *ShiftC = isConstOrConstSplat(N0.getOperand(1));
  7123. unsigned BitWidth = VT.getScalarSizeInBits();
  7124. if (XorC && ShiftC) {
  7125. // Don't crash on an oversized shift. We can not guarantee that a bogus
  7126. // shift has been simplified to undef.
  7127. uint64_t ShiftAmt = ShiftC->getLimitedValue();
  7128. if (ShiftAmt < BitWidth) {
  7129. APInt Ones = APInt::getAllOnes(BitWidth);
  7130. Ones = N0Opcode == ISD::SHL ? Ones.shl(ShiftAmt) : Ones.lshr(ShiftAmt);
  7131. if (XorC->getAPIntValue() == Ones) {
  7132. // If the xor constant is a shifted -1, do a 'not' before the shift:
  7133. // xor (X << ShiftC), XorC --> (not X) << ShiftC
  7134. // xor (X >> ShiftC), XorC --> (not X) >> ShiftC
  7135. SDValue Not = DAG.getNOT(DL, N0.getOperand(0), VT);
  7136. return DAG.getNode(N0Opcode, DL, VT, Not, N0.getOperand(1));
  7137. }
  7138. }
  7139. }
  7140. }
  7141. // fold Y = sra (X, size(X)-1); xor (add (X, Y), Y) -> (abs X)
  7142. if (TLI.isOperationLegalOrCustom(ISD::ABS, VT)) {
  7143. SDValue A = N0Opcode == ISD::ADD ? N0 : N1;
  7144. SDValue S = N0Opcode == ISD::SRA ? N0 : N1;
  7145. if (A.getOpcode() == ISD::ADD && S.getOpcode() == ISD::SRA) {
  7146. SDValue A0 = A.getOperand(0), A1 = A.getOperand(1);
  7147. SDValue S0 = S.getOperand(0);
  7148. if ((A0 == S && A1 == S0) || (A1 == S && A0 == S0))
  7149. if (ConstantSDNode *C = isConstOrConstSplat(S.getOperand(1)))
  7150. if (C->getAPIntValue() == (VT.getScalarSizeInBits() - 1))
  7151. return DAG.getNode(ISD::ABS, DL, VT, S0);
  7152. }
  7153. }
  7154. // fold (xor x, x) -> 0
  7155. if (N0 == N1)
  7156. return tryFoldToZero(DL, TLI, VT, DAG, LegalOperations);
  7157. // fold (xor (shl 1, x), -1) -> (rotl ~1, x)
  7158. // Here is a concrete example of this equivalence:
  7159. // i16 x == 14
  7160. // i16 shl == 1 << 14 == 16384 == 0b0100000000000000
  7161. // i16 xor == ~(1 << 14) == 49151 == 0b1011111111111111
  7162. //
  7163. // =>
  7164. //
  7165. // i16 ~1 == 0b1111111111111110
  7166. // i16 rol(~1, 14) == 0b1011111111111111
  7167. //
  7168. // Some additional tips to help conceptualize this transform:
  7169. // - Try to see the operation as placing a single zero in a value of all ones.
  7170. // - There exists no value for x which would allow the result to contain zero.
  7171. // - Values of x larger than the bitwidth are undefined and do not require a
  7172. // consistent result.
  7173. // - Pushing the zero left requires shifting one bits in from the right.
  7174. // A rotate left of ~1 is a nice way of achieving the desired result.
  7175. if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT) && N0Opcode == ISD::SHL &&
  7176. isAllOnesConstant(N1) && isOneConstant(N0.getOperand(0))) {
  7177. return DAG.getNode(ISD::ROTL, DL, VT, DAG.getConstant(~1, DL, VT),
  7178. N0.getOperand(1));
  7179. }
  7180. // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
  7181. if (N0Opcode == N1.getOpcode())
  7182. if (SDValue V = hoistLogicOpWithSameOpcodeHands(N))
  7183. return V;
  7184. // Unfold ((x ^ y) & m) ^ y into (x & m) | (y & ~m) if profitable
  7185. if (SDValue MM = unfoldMaskedMerge(N))
  7186. return MM;
  7187. // Simplify the expression using non-local knowledge.
  7188. if (SimplifyDemandedBits(SDValue(N, 0)))
  7189. return SDValue(N, 0);
  7190. if (SDValue Combined = combineCarryDiamond(DAG, TLI, N0, N1, N))
  7191. return Combined;
  7192. return SDValue();
  7193. }
  7194. /// If we have a shift-by-constant of a bitwise logic op that itself has a
  7195. /// shift-by-constant operand with identical opcode, we may be able to convert
  7196. /// that into 2 independent shifts followed by the logic op. This is a
  7197. /// throughput improvement.
  7198. static SDValue combineShiftOfShiftedLogic(SDNode *Shift, SelectionDAG &DAG) {
  7199. // Match a one-use bitwise logic op.
  7200. SDValue LogicOp = Shift->getOperand(0);
  7201. if (!LogicOp.hasOneUse())
  7202. return SDValue();
  7203. unsigned LogicOpcode = LogicOp.getOpcode();
  7204. if (LogicOpcode != ISD::AND && LogicOpcode != ISD::OR &&
  7205. LogicOpcode != ISD::XOR)
  7206. return SDValue();
  7207. // Find a matching one-use shift by constant.
  7208. unsigned ShiftOpcode = Shift->getOpcode();
  7209. SDValue C1 = Shift->getOperand(1);
  7210. ConstantSDNode *C1Node = isConstOrConstSplat(C1);
  7211. assert(C1Node && "Expected a shift with constant operand");
  7212. const APInt &C1Val = C1Node->getAPIntValue();
  7213. auto matchFirstShift = [&](SDValue V, SDValue &ShiftOp,
  7214. const APInt *&ShiftAmtVal) {
  7215. if (V.getOpcode() != ShiftOpcode || !V.hasOneUse())
  7216. return false;
  7217. ConstantSDNode *ShiftCNode = isConstOrConstSplat(V.getOperand(1));
  7218. if (!ShiftCNode)
  7219. return false;
  7220. // Capture the shifted operand and shift amount value.
  7221. ShiftOp = V.getOperand(0);
  7222. ShiftAmtVal = &ShiftCNode->getAPIntValue();
  7223. // Shift amount types do not have to match their operand type, so check that
  7224. // the constants are the same width.
  7225. if (ShiftAmtVal->getBitWidth() != C1Val.getBitWidth())
  7226. return false;
  7227. // The fold is not valid if the sum of the shift values exceeds bitwidth.
  7228. if ((*ShiftAmtVal + C1Val).uge(V.getScalarValueSizeInBits()))
  7229. return false;
  7230. return true;
  7231. };
  7232. // Logic ops are commutative, so check each operand for a match.
  7233. SDValue X, Y;
  7234. const APInt *C0Val;
  7235. if (matchFirstShift(LogicOp.getOperand(0), X, C0Val))
  7236. Y = LogicOp.getOperand(1);
  7237. else if (matchFirstShift(LogicOp.getOperand(1), X, C0Val))
  7238. Y = LogicOp.getOperand(0);
  7239. else
  7240. return SDValue();
  7241. // shift (logic (shift X, C0), Y), C1 -> logic (shift X, C0+C1), (shift Y, C1)
  7242. SDLoc DL(Shift);
  7243. EVT VT = Shift->getValueType(0);
  7244. EVT ShiftAmtVT = Shift->getOperand(1).getValueType();
  7245. SDValue ShiftSumC = DAG.getConstant(*C0Val + C1Val, DL, ShiftAmtVT);
  7246. SDValue NewShift1 = DAG.getNode(ShiftOpcode, DL, VT, X, ShiftSumC);
  7247. SDValue NewShift2 = DAG.getNode(ShiftOpcode, DL, VT, Y, C1);
  7248. return DAG.getNode(LogicOpcode, DL, VT, NewShift1, NewShift2);
  7249. }
  7250. /// Handle transforms common to the three shifts, when the shift amount is a
  7251. /// constant.
  7252. /// We are looking for: (shift being one of shl/sra/srl)
  7253. /// shift (binop X, C0), C1
  7254. /// And want to transform into:
  7255. /// binop (shift X, C1), (shift C0, C1)
  7256. SDValue DAGCombiner::visitShiftByConstant(SDNode *N) {
  7257. assert(isConstOrConstSplat(N->getOperand(1)) && "Expected constant operand");
  7258. // Do not turn a 'not' into a regular xor.
  7259. if (isBitwiseNot(N->getOperand(0)))
  7260. return SDValue();
  7261. // The inner binop must be one-use, since we want to replace it.
  7262. SDValue LHS = N->getOperand(0);
  7263. if (!LHS.hasOneUse() || !TLI.isDesirableToCommuteWithShift(N, Level))
  7264. return SDValue();
  7265. // TODO: This is limited to early combining because it may reveal regressions
  7266. // otherwise. But since we just checked a target hook to see if this is
  7267. // desirable, that should have filtered out cases where this interferes
  7268. // with some other pattern matching.
  7269. if (!LegalTypes)
  7270. if (SDValue R = combineShiftOfShiftedLogic(N, DAG))
  7271. return R;
  7272. // We want to pull some binops through shifts, so that we have (and (shift))
  7273. // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
  7274. // thing happens with address calculations, so it's important to canonicalize
  7275. // it.
  7276. switch (LHS.getOpcode()) {
  7277. default:
  7278. return SDValue();
  7279. case ISD::OR:
  7280. case ISD::XOR:
  7281. case ISD::AND:
  7282. break;
  7283. case ISD::ADD:
  7284. if (N->getOpcode() != ISD::SHL)
  7285. return SDValue(); // only shl(add) not sr[al](add).
  7286. break;
  7287. }
  7288. // We require the RHS of the binop to be a constant and not opaque as well.
  7289. ConstantSDNode *BinOpCst = getAsNonOpaqueConstant(LHS.getOperand(1));
  7290. if (!BinOpCst)
  7291. return SDValue();
  7292. // FIXME: disable this unless the input to the binop is a shift by a constant
  7293. // or is copy/select. Enable this in other cases when figure out it's exactly
  7294. // profitable.
  7295. SDValue BinOpLHSVal = LHS.getOperand(0);
  7296. bool IsShiftByConstant = (BinOpLHSVal.getOpcode() == ISD::SHL ||
  7297. BinOpLHSVal.getOpcode() == ISD::SRA ||
  7298. BinOpLHSVal.getOpcode() == ISD::SRL) &&
  7299. isa<ConstantSDNode>(BinOpLHSVal.getOperand(1));
  7300. bool IsCopyOrSelect = BinOpLHSVal.getOpcode() == ISD::CopyFromReg ||
  7301. BinOpLHSVal.getOpcode() == ISD::SELECT;
  7302. if (!IsShiftByConstant && !IsCopyOrSelect)
  7303. return SDValue();
  7304. if (IsCopyOrSelect && N->hasOneUse())
  7305. return SDValue();
  7306. // Fold the constants, shifting the binop RHS by the shift amount.
  7307. SDLoc DL(N);
  7308. EVT VT = N->getValueType(0);
  7309. SDValue NewRHS = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(1),
  7310. N->getOperand(1));
  7311. assert(isa<ConstantSDNode>(NewRHS) && "Folding was not successful!");
  7312. SDValue NewShift = DAG.getNode(N->getOpcode(), DL, VT, LHS.getOperand(0),
  7313. N->getOperand(1));
  7314. return DAG.getNode(LHS.getOpcode(), DL, VT, NewShift, NewRHS);
  7315. }
  7316. SDValue DAGCombiner::distributeTruncateThroughAnd(SDNode *N) {
  7317. assert(N->getOpcode() == ISD::TRUNCATE);
  7318. assert(N->getOperand(0).getOpcode() == ISD::AND);
  7319. // (truncate:TruncVT (and N00, N01C)) -> (and (truncate:TruncVT N00), TruncC)
  7320. EVT TruncVT = N->getValueType(0);
  7321. if (N->hasOneUse() && N->getOperand(0).hasOneUse() &&
  7322. TLI.isTypeDesirableForOp(ISD::AND, TruncVT)) {
  7323. SDValue N01 = N->getOperand(0).getOperand(1);
  7324. if (isConstantOrConstantVector(N01, /* NoOpaques */ true)) {
  7325. SDLoc DL(N);
  7326. SDValue N00 = N->getOperand(0).getOperand(0);
  7327. SDValue Trunc00 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N00);
  7328. SDValue Trunc01 = DAG.getNode(ISD::TRUNCATE, DL, TruncVT, N01);
  7329. AddToWorklist(Trunc00.getNode());
  7330. AddToWorklist(Trunc01.getNode());
  7331. return DAG.getNode(ISD::AND, DL, TruncVT, Trunc00, Trunc01);
  7332. }
  7333. }
  7334. return SDValue();
  7335. }
  7336. SDValue DAGCombiner::visitRotate(SDNode *N) {
  7337. SDLoc dl(N);
  7338. SDValue N0 = N->getOperand(0);
  7339. SDValue N1 = N->getOperand(1);
  7340. EVT VT = N->getValueType(0);
  7341. unsigned Bitsize = VT.getScalarSizeInBits();
  7342. // fold (rot x, 0) -> x
  7343. if (isNullOrNullSplat(N1))
  7344. return N0;
  7345. // fold (rot x, c) -> x iff (c % BitSize) == 0
  7346. if (isPowerOf2_32(Bitsize) && Bitsize > 1) {
  7347. APInt ModuloMask(N1.getScalarValueSizeInBits(), Bitsize - 1);
  7348. if (DAG.MaskedValueIsZero(N1, ModuloMask))
  7349. return N0;
  7350. }
  7351. // fold (rot x, c) -> (rot x, c % BitSize)
  7352. bool OutOfRange = false;
  7353. auto MatchOutOfRange = [Bitsize, &OutOfRange](ConstantSDNode *C) {
  7354. OutOfRange |= C->getAPIntValue().uge(Bitsize);
  7355. return true;
  7356. };
  7357. if (ISD::matchUnaryPredicate(N1, MatchOutOfRange) && OutOfRange) {
  7358. EVT AmtVT = N1.getValueType();
  7359. SDValue Bits = DAG.getConstant(Bitsize, dl, AmtVT);
  7360. if (SDValue Amt =
  7361. DAG.FoldConstantArithmetic(ISD::UREM, dl, AmtVT, {N1, Bits}))
  7362. return DAG.getNode(N->getOpcode(), dl, VT, N0, Amt);
  7363. }
  7364. // rot i16 X, 8 --> bswap X
  7365. auto *RotAmtC = isConstOrConstSplat(N1);
  7366. if (RotAmtC && RotAmtC->getAPIntValue() == 8 &&
  7367. VT.getScalarSizeInBits() == 16 && hasOperation(ISD::BSWAP, VT))
  7368. return DAG.getNode(ISD::BSWAP, dl, VT, N0);
  7369. // Simplify the operands using demanded-bits information.
  7370. if (SimplifyDemandedBits(SDValue(N, 0)))
  7371. return SDValue(N, 0);
  7372. // fold (rot* x, (trunc (and y, c))) -> (rot* x, (and (trunc y), (trunc c))).
  7373. if (N1.getOpcode() == ISD::TRUNCATE &&
  7374. N1.getOperand(0).getOpcode() == ISD::AND) {
  7375. if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
  7376. return DAG.getNode(N->getOpcode(), dl, VT, N0, NewOp1);
  7377. }
  7378. unsigned NextOp = N0.getOpcode();
  7379. // fold (rot* (rot* x, c2), c1) -> (rot* x, c1 +- c2 % bitsize)
  7380. if (NextOp == ISD::ROTL || NextOp == ISD::ROTR) {
  7381. SDNode *C1 = DAG.isConstantIntBuildVectorOrConstantInt(N1);
  7382. SDNode *C2 = DAG.isConstantIntBuildVectorOrConstantInt(N0.getOperand(1));
  7383. if (C1 && C2 && C1->getValueType(0) == C2->getValueType(0)) {
  7384. EVT ShiftVT = C1->getValueType(0);
  7385. bool SameSide = (N->getOpcode() == NextOp);
  7386. unsigned CombineOp = SameSide ? ISD::ADD : ISD::SUB;
  7387. if (SDValue CombinedShift = DAG.FoldConstantArithmetic(
  7388. CombineOp, dl, ShiftVT, {N1, N0.getOperand(1)})) {
  7389. SDValue BitsizeC = DAG.getConstant(Bitsize, dl, ShiftVT);
  7390. SDValue CombinedShiftNorm = DAG.FoldConstantArithmetic(
  7391. ISD::SREM, dl, ShiftVT, {CombinedShift, BitsizeC});
  7392. return DAG.getNode(N->getOpcode(), dl, VT, N0->getOperand(0),
  7393. CombinedShiftNorm);
  7394. }
  7395. }
  7396. }
  7397. return SDValue();
  7398. }
  7399. SDValue DAGCombiner::visitSHL(SDNode *N) {
  7400. SDValue N0 = N->getOperand(0);
  7401. SDValue N1 = N->getOperand(1);
  7402. if (SDValue V = DAG.simplifyShift(N0, N1))
  7403. return V;
  7404. EVT VT = N0.getValueType();
  7405. EVT ShiftVT = N1.getValueType();
  7406. unsigned OpSizeInBits = VT.getScalarSizeInBits();
  7407. // fold (shl c1, c2) -> c1<<c2
  7408. if (SDValue C = DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, {N0, N1}))
  7409. return C;
  7410. // fold vector ops
  7411. if (VT.isVector()) {
  7412. if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
  7413. return FoldedVOp;
  7414. BuildVectorSDNode *N1CV = dyn_cast<BuildVectorSDNode>(N1);
  7415. // If setcc produces all-one true value then:
  7416. // (shl (and (setcc) N01CV) N1CV) -> (and (setcc) N01CV<<N1CV)
  7417. if (N1CV && N1CV->isConstant()) {
  7418. if (N0.getOpcode() == ISD::AND) {
  7419. SDValue N00 = N0->getOperand(0);
  7420. SDValue N01 = N0->getOperand(1);
  7421. BuildVectorSDNode *N01CV = dyn_cast<BuildVectorSDNode>(N01);
  7422. if (N01CV && N01CV->isConstant() && N00.getOpcode() == ISD::SETCC &&
  7423. TLI.getBooleanContents(N00.getOperand(0).getValueType()) ==
  7424. TargetLowering::ZeroOrNegativeOneBooleanContent) {
  7425. if (SDValue C =
  7426. DAG.FoldConstantArithmetic(ISD::SHL, SDLoc(N), VT, {N01, N1}))
  7427. return DAG.getNode(ISD::AND, SDLoc(N), VT, N00, C);
  7428. }
  7429. }
  7430. }
  7431. }
  7432. if (SDValue NewSel = foldBinOpIntoSelect(N))
  7433. return NewSel;
  7434. // if (shl x, c) is known to be zero, return 0
  7435. if (DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(OpSizeInBits)))
  7436. return DAG.getConstant(0, SDLoc(N), VT);
  7437. // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
  7438. if (N1.getOpcode() == ISD::TRUNCATE &&
  7439. N1.getOperand(0).getOpcode() == ISD::AND) {
  7440. if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
  7441. return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, NewOp1);
  7442. }
  7443. if (SimplifyDemandedBits(SDValue(N, 0)))
  7444. return SDValue(N, 0);
  7445. // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
  7446. if (N0.getOpcode() == ISD::SHL) {
  7447. auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
  7448. ConstantSDNode *RHS) {
  7449. APInt c1 = LHS->getAPIntValue();
  7450. APInt c2 = RHS->getAPIntValue();
  7451. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  7452. return (c1 + c2).uge(OpSizeInBits);
  7453. };
  7454. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
  7455. return DAG.getConstant(0, SDLoc(N), VT);
  7456. auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
  7457. ConstantSDNode *RHS) {
  7458. APInt c1 = LHS->getAPIntValue();
  7459. APInt c2 = RHS->getAPIntValue();
  7460. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  7461. return (c1 + c2).ult(OpSizeInBits);
  7462. };
  7463. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
  7464. SDLoc DL(N);
  7465. SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
  7466. return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0), Sum);
  7467. }
  7468. }
  7469. // fold (shl (ext (shl x, c1)), c2) -> (shl (ext x), (add c1, c2))
  7470. // For this to be valid, the second form must not preserve any of the bits
  7471. // that are shifted out by the inner shift in the first form. This means
  7472. // the outer shift size must be >= the number of bits added by the ext.
  7473. // As a corollary, we don't care what kind of ext it is.
  7474. if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
  7475. N0.getOpcode() == ISD::ANY_EXTEND ||
  7476. N0.getOpcode() == ISD::SIGN_EXTEND) &&
  7477. N0.getOperand(0).getOpcode() == ISD::SHL) {
  7478. SDValue N0Op0 = N0.getOperand(0);
  7479. SDValue InnerShiftAmt = N0Op0.getOperand(1);
  7480. EVT InnerVT = N0Op0.getValueType();
  7481. uint64_t InnerBitwidth = InnerVT.getScalarSizeInBits();
  7482. auto MatchOutOfRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
  7483. ConstantSDNode *RHS) {
  7484. APInt c1 = LHS->getAPIntValue();
  7485. APInt c2 = RHS->getAPIntValue();
  7486. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  7487. return c2.uge(OpSizeInBits - InnerBitwidth) &&
  7488. (c1 + c2).uge(OpSizeInBits);
  7489. };
  7490. if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchOutOfRange,
  7491. /*AllowUndefs*/ false,
  7492. /*AllowTypeMismatch*/ true))
  7493. return DAG.getConstant(0, SDLoc(N), VT);
  7494. auto MatchInRange = [OpSizeInBits, InnerBitwidth](ConstantSDNode *LHS,
  7495. ConstantSDNode *RHS) {
  7496. APInt c1 = LHS->getAPIntValue();
  7497. APInt c2 = RHS->getAPIntValue();
  7498. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  7499. return c2.uge(OpSizeInBits - InnerBitwidth) &&
  7500. (c1 + c2).ult(OpSizeInBits);
  7501. };
  7502. if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchInRange,
  7503. /*AllowUndefs*/ false,
  7504. /*AllowTypeMismatch*/ true)) {
  7505. SDLoc DL(N);
  7506. SDValue Ext = DAG.getNode(N0.getOpcode(), DL, VT, N0Op0.getOperand(0));
  7507. SDValue Sum = DAG.getZExtOrTrunc(InnerShiftAmt, DL, ShiftVT);
  7508. Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, Sum, N1);
  7509. return DAG.getNode(ISD::SHL, DL, VT, Ext, Sum);
  7510. }
  7511. }
  7512. // fold (shl (zext (srl x, C)), C) -> (zext (shl (srl x, C), C))
  7513. // Only fold this if the inner zext has no other uses to avoid increasing
  7514. // the total number of instructions.
  7515. if (N0.getOpcode() == ISD::ZERO_EXTEND && N0.hasOneUse() &&
  7516. N0.getOperand(0).getOpcode() == ISD::SRL) {
  7517. SDValue N0Op0 = N0.getOperand(0);
  7518. SDValue InnerShiftAmt = N0Op0.getOperand(1);
  7519. auto MatchEqual = [VT](ConstantSDNode *LHS, ConstantSDNode *RHS) {
  7520. APInt c1 = LHS->getAPIntValue();
  7521. APInt c2 = RHS->getAPIntValue();
  7522. zeroExtendToMatch(c1, c2);
  7523. return c1.ult(VT.getScalarSizeInBits()) && (c1 == c2);
  7524. };
  7525. if (ISD::matchBinaryPredicate(InnerShiftAmt, N1, MatchEqual,
  7526. /*AllowUndefs*/ false,
  7527. /*AllowTypeMismatch*/ true)) {
  7528. SDLoc DL(N);
  7529. EVT InnerShiftAmtVT = N0Op0.getOperand(1).getValueType();
  7530. SDValue NewSHL = DAG.getZExtOrTrunc(N1, DL, InnerShiftAmtVT);
  7531. NewSHL = DAG.getNode(ISD::SHL, DL, N0Op0.getValueType(), N0Op0, NewSHL);
  7532. AddToWorklist(NewSHL.getNode());
  7533. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N0), VT, NewSHL);
  7534. }
  7535. }
  7536. // fold (shl (sr[la] exact X, C1), C2) -> (shl X, (C2-C1)) if C1 <= C2
  7537. // fold (shl (sr[la] exact X, C1), C2) -> (sr[la] X, (C2-C1)) if C1 > C2
  7538. // TODO - support non-uniform vector shift amounts.
  7539. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  7540. if (N1C && (N0.getOpcode() == ISD::SRL || N0.getOpcode() == ISD::SRA) &&
  7541. N0->getFlags().hasExact()) {
  7542. if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
  7543. uint64_t C1 = N0C1->getZExtValue();
  7544. uint64_t C2 = N1C->getZExtValue();
  7545. SDLoc DL(N);
  7546. if (C1 <= C2)
  7547. return DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
  7548. DAG.getConstant(C2 - C1, DL, ShiftVT));
  7549. return DAG.getNode(N0.getOpcode(), DL, VT, N0.getOperand(0),
  7550. DAG.getConstant(C1 - C2, DL, ShiftVT));
  7551. }
  7552. }
  7553. // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
  7554. // (and (srl x, (sub c1, c2), MASK)
  7555. // Only fold this if the inner shift has no other uses -- if it does, folding
  7556. // this will increase the total number of instructions.
  7557. // TODO - drop hasOneUse requirement if c1 == c2?
  7558. // TODO - support non-uniform vector shift amounts.
  7559. if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
  7560. TLI.shouldFoldConstantShiftPairToMask(N, Level)) {
  7561. if (ConstantSDNode *N0C1 = isConstOrConstSplat(N0.getOperand(1))) {
  7562. if (N0C1->getAPIntValue().ult(OpSizeInBits)) {
  7563. uint64_t c1 = N0C1->getZExtValue();
  7564. uint64_t c2 = N1C->getZExtValue();
  7565. APInt Mask = APInt::getHighBitsSet(OpSizeInBits, OpSizeInBits - c1);
  7566. SDValue Shift;
  7567. if (c2 > c1) {
  7568. Mask <<= c2 - c1;
  7569. SDLoc DL(N);
  7570. Shift = DAG.getNode(ISD::SHL, DL, VT, N0.getOperand(0),
  7571. DAG.getConstant(c2 - c1, DL, ShiftVT));
  7572. } else {
  7573. Mask.lshrInPlace(c1 - c2);
  7574. SDLoc DL(N);
  7575. Shift = DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0),
  7576. DAG.getConstant(c1 - c2, DL, ShiftVT));
  7577. }
  7578. SDLoc DL(N0);
  7579. return DAG.getNode(ISD::AND, DL, VT, Shift,
  7580. DAG.getConstant(Mask, DL, VT));
  7581. }
  7582. }
  7583. }
  7584. // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
  7585. if (N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1) &&
  7586. isConstantOrConstantVector(N1, /* No Opaques */ true)) {
  7587. SDLoc DL(N);
  7588. SDValue AllBits = DAG.getAllOnesConstant(DL, VT);
  7589. SDValue HiBitsMask = DAG.getNode(ISD::SHL, DL, VT, AllBits, N1);
  7590. return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), HiBitsMask);
  7591. }
  7592. // fold (shl (add x, c1), c2) -> (add (shl x, c2), c1 << c2)
  7593. // fold (shl (or x, c1), c2) -> (or (shl x, c2), c1 << c2)
  7594. // Variant of version done on multiply, except mul by a power of 2 is turned
  7595. // into a shift.
  7596. if ((N0.getOpcode() == ISD::ADD || N0.getOpcode() == ISD::OR) &&
  7597. N0.getNode()->hasOneUse() &&
  7598. isConstantOrConstantVector(N1, /* No Opaques */ true) &&
  7599. isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true) &&
  7600. TLI.isDesirableToCommuteWithShift(N, Level)) {
  7601. SDValue Shl0 = DAG.getNode(ISD::SHL, SDLoc(N0), VT, N0.getOperand(0), N1);
  7602. SDValue Shl1 = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
  7603. AddToWorklist(Shl0.getNode());
  7604. AddToWorklist(Shl1.getNode());
  7605. return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, Shl0, Shl1);
  7606. }
  7607. // fold (shl (mul x, c1), c2) -> (mul x, c1 << c2)
  7608. if (N0.getOpcode() == ISD::MUL && N0.getNode()->hasOneUse() &&
  7609. isConstantOrConstantVector(N1, /* No Opaques */ true) &&
  7610. isConstantOrConstantVector(N0.getOperand(1), /* No Opaques */ true)) {
  7611. SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N1), VT, N0.getOperand(1), N1);
  7612. if (isConstantOrConstantVector(Shl))
  7613. return DAG.getNode(ISD::MUL, SDLoc(N), VT, N0.getOperand(0), Shl);
  7614. }
  7615. if (N1C && !N1C->isOpaque())
  7616. if (SDValue NewSHL = visitShiftByConstant(N))
  7617. return NewSHL;
  7618. // Fold (shl (vscale * C0), C1) to (vscale * (C0 << C1)).
  7619. if (N0.getOpcode() == ISD::VSCALE)
  7620. if (ConstantSDNode *NC1 = isConstOrConstSplat(N->getOperand(1))) {
  7621. const APInt &C0 = N0.getConstantOperandAPInt(0);
  7622. const APInt &C1 = NC1->getAPIntValue();
  7623. return DAG.getVScale(SDLoc(N), VT, C0 << C1);
  7624. }
  7625. // Fold (shl step_vector(C0), C1) to (step_vector(C0 << C1)).
  7626. APInt ShlVal;
  7627. if (N0.getOpcode() == ISD::STEP_VECTOR)
  7628. if (ISD::isConstantSplatVector(N1.getNode(), ShlVal)) {
  7629. const APInt &C0 = N0.getConstantOperandAPInt(0);
  7630. if (ShlVal.ult(C0.getBitWidth())) {
  7631. APInt NewStep = C0 << ShlVal;
  7632. return DAG.getStepVector(SDLoc(N), VT, NewStep);
  7633. }
  7634. }
  7635. return SDValue();
  7636. }
  7637. // Transform a right shift of a multiply into a multiply-high.
  7638. // Examples:
  7639. // (srl (mul (zext i32:$a to i64), (zext i32:$a to i64)), 32) -> (mulhu $a, $b)
  7640. // (sra (mul (sext i32:$a to i64), (sext i32:$a to i64)), 32) -> (mulhs $a, $b)
  7641. static SDValue combineShiftToMULH(SDNode *N, SelectionDAG &DAG,
  7642. const TargetLowering &TLI) {
  7643. assert((N->getOpcode() == ISD::SRL || N->getOpcode() == ISD::SRA) &&
  7644. "SRL or SRA node is required here!");
  7645. // Check the shift amount. Proceed with the transformation if the shift
  7646. // amount is constant.
  7647. ConstantSDNode *ShiftAmtSrc = isConstOrConstSplat(N->getOperand(1));
  7648. if (!ShiftAmtSrc)
  7649. return SDValue();
  7650. SDLoc DL(N);
  7651. // The operation feeding into the shift must be a multiply.
  7652. SDValue ShiftOperand = N->getOperand(0);
  7653. if (ShiftOperand.getOpcode() != ISD::MUL)
  7654. return SDValue();
  7655. // Both operands must be equivalent extend nodes.
  7656. SDValue LeftOp = ShiftOperand.getOperand(0);
  7657. SDValue RightOp = ShiftOperand.getOperand(1);
  7658. bool IsSignExt = LeftOp.getOpcode() == ISD::SIGN_EXTEND;
  7659. bool IsZeroExt = LeftOp.getOpcode() == ISD::ZERO_EXTEND;
  7660. if (!IsSignExt && !IsZeroExt)
  7661. return SDValue();
  7662. EVT NarrowVT = LeftOp.getOperand(0).getValueType();
  7663. unsigned NarrowVTSize = NarrowVT.getScalarSizeInBits();
  7664. SDValue MulhRightOp;
  7665. if (ConstantSDNode *Constant = isConstOrConstSplat(RightOp)) {
  7666. unsigned ActiveBits = IsSignExt
  7667. ? Constant->getAPIntValue().getMinSignedBits()
  7668. : Constant->getAPIntValue().getActiveBits();
  7669. if (ActiveBits > NarrowVTSize)
  7670. return SDValue();
  7671. MulhRightOp = DAG.getConstant(
  7672. Constant->getAPIntValue().trunc(NarrowVT.getScalarSizeInBits()), DL,
  7673. NarrowVT);
  7674. } else {
  7675. if (LeftOp.getOpcode() != RightOp.getOpcode())
  7676. return SDValue();
  7677. // Check that the two extend nodes are the same type.
  7678. if (NarrowVT != RightOp.getOperand(0).getValueType())
  7679. return SDValue();
  7680. MulhRightOp = RightOp.getOperand(0);
  7681. }
  7682. EVT WideVT = LeftOp.getValueType();
  7683. // Proceed with the transformation if the wide types match.
  7684. assert((WideVT == RightOp.getValueType()) &&
  7685. "Cannot have a multiply node with two different operand types.");
  7686. // Proceed with the transformation if the wide type is twice as large
  7687. // as the narrow type.
  7688. if (WideVT.getScalarSizeInBits() != 2 * NarrowVTSize)
  7689. return SDValue();
  7690. // Check the shift amount with the narrow type size.
  7691. // Proceed with the transformation if the shift amount is the width
  7692. // of the narrow type.
  7693. unsigned ShiftAmt = ShiftAmtSrc->getZExtValue();
  7694. if (ShiftAmt != NarrowVTSize)
  7695. return SDValue();
  7696. // If the operation feeding into the MUL is a sign extend (sext),
  7697. // we use mulhs. Othewise, zero extends (zext) use mulhu.
  7698. unsigned MulhOpcode = IsSignExt ? ISD::MULHS : ISD::MULHU;
  7699. // Combine to mulh if mulh is legal/custom for the narrow type on the target.
  7700. if (!TLI.isOperationLegalOrCustom(MulhOpcode, NarrowVT))
  7701. return SDValue();
  7702. SDValue Result =
  7703. DAG.getNode(MulhOpcode, DL, NarrowVT, LeftOp.getOperand(0), MulhRightOp);
  7704. return (N->getOpcode() == ISD::SRA ? DAG.getSExtOrTrunc(Result, DL, WideVT)
  7705. : DAG.getZExtOrTrunc(Result, DL, WideVT));
  7706. }
  7707. SDValue DAGCombiner::visitSRA(SDNode *N) {
  7708. SDValue N0 = N->getOperand(0);
  7709. SDValue N1 = N->getOperand(1);
  7710. if (SDValue V = DAG.simplifyShift(N0, N1))
  7711. return V;
  7712. EVT VT = N0.getValueType();
  7713. unsigned OpSizeInBits = VT.getScalarSizeInBits();
  7714. // fold (sra c1, c2) -> (sra c1, c2)
  7715. if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRA, SDLoc(N), VT, {N0, N1}))
  7716. return C;
  7717. // Arithmetic shifting an all-sign-bit value is a no-op.
  7718. // fold (sra 0, x) -> 0
  7719. // fold (sra -1, x) -> -1
  7720. if (DAG.ComputeNumSignBits(N0) == OpSizeInBits)
  7721. return N0;
  7722. // fold vector ops
  7723. if (VT.isVector())
  7724. if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
  7725. return FoldedVOp;
  7726. if (SDValue NewSel = foldBinOpIntoSelect(N))
  7727. return NewSel;
  7728. // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
  7729. // sext_inreg.
  7730. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  7731. if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
  7732. unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
  7733. EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
  7734. if (VT.isVector())
  7735. ExtVT = EVT::getVectorVT(*DAG.getContext(), ExtVT,
  7736. VT.getVectorElementCount());
  7737. if (!LegalOperations ||
  7738. TLI.getOperationAction(ISD::SIGN_EXTEND_INREG, ExtVT) ==
  7739. TargetLowering::Legal)
  7740. return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT,
  7741. N0.getOperand(0), DAG.getValueType(ExtVT));
  7742. // Even if we can't convert to sext_inreg, we might be able to remove
  7743. // this shift pair if the input is already sign extended.
  7744. if (DAG.ComputeNumSignBits(N0.getOperand(0)) > N1C->getZExtValue())
  7745. return N0.getOperand(0);
  7746. }
  7747. // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
  7748. // clamp (add c1, c2) to max shift.
  7749. if (N0.getOpcode() == ISD::SRA) {
  7750. SDLoc DL(N);
  7751. EVT ShiftVT = N1.getValueType();
  7752. EVT ShiftSVT = ShiftVT.getScalarType();
  7753. SmallVector<SDValue, 16> ShiftValues;
  7754. auto SumOfShifts = [&](ConstantSDNode *LHS, ConstantSDNode *RHS) {
  7755. APInt c1 = LHS->getAPIntValue();
  7756. APInt c2 = RHS->getAPIntValue();
  7757. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  7758. APInt Sum = c1 + c2;
  7759. unsigned ShiftSum =
  7760. Sum.uge(OpSizeInBits) ? (OpSizeInBits - 1) : Sum.getZExtValue();
  7761. ShiftValues.push_back(DAG.getConstant(ShiftSum, DL, ShiftSVT));
  7762. return true;
  7763. };
  7764. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), SumOfShifts)) {
  7765. SDValue ShiftValue;
  7766. if (N1.getOpcode() == ISD::BUILD_VECTOR)
  7767. ShiftValue = DAG.getBuildVector(ShiftVT, DL, ShiftValues);
  7768. else if (N1.getOpcode() == ISD::SPLAT_VECTOR) {
  7769. assert(ShiftValues.size() == 1 &&
  7770. "Expected matchBinaryPredicate to return one element for "
  7771. "SPLAT_VECTORs");
  7772. ShiftValue = DAG.getSplatVector(ShiftVT, DL, ShiftValues[0]);
  7773. } else
  7774. ShiftValue = ShiftValues[0];
  7775. return DAG.getNode(ISD::SRA, DL, VT, N0.getOperand(0), ShiftValue);
  7776. }
  7777. }
  7778. // fold (sra (shl X, m), (sub result_size, n))
  7779. // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
  7780. // result_size - n != m.
  7781. // If truncate is free for the target sext(shl) is likely to result in better
  7782. // code.
  7783. if (N0.getOpcode() == ISD::SHL && N1C) {
  7784. // Get the two constanst of the shifts, CN0 = m, CN = n.
  7785. const ConstantSDNode *N01C = isConstOrConstSplat(N0.getOperand(1));
  7786. if (N01C) {
  7787. LLVMContext &Ctx = *DAG.getContext();
  7788. // Determine what the truncate's result bitsize and type would be.
  7789. EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - N1C->getZExtValue());
  7790. if (VT.isVector())
  7791. TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorElementCount());
  7792. // Determine the residual right-shift amount.
  7793. int ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
  7794. // If the shift is not a no-op (in which case this should be just a sign
  7795. // extend already), the truncated to type is legal, sign_extend is legal
  7796. // on that type, and the truncate to that type is both legal and free,
  7797. // perform the transform.
  7798. if ((ShiftAmt > 0) &&
  7799. TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
  7800. TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
  7801. TLI.isTruncateFree(VT, TruncVT)) {
  7802. SDLoc DL(N);
  7803. SDValue Amt = DAG.getConstant(ShiftAmt, DL,
  7804. getShiftAmountTy(N0.getOperand(0).getValueType()));
  7805. SDValue Shift = DAG.getNode(ISD::SRL, DL, VT,
  7806. N0.getOperand(0), Amt);
  7807. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, DL, TruncVT,
  7808. Shift);
  7809. return DAG.getNode(ISD::SIGN_EXTEND, DL,
  7810. N->getValueType(0), Trunc);
  7811. }
  7812. }
  7813. }
  7814. // We convert trunc/ext to opposing shifts in IR, but casts may be cheaper.
  7815. // sra (add (shl X, N1C), AddC), N1C -->
  7816. // sext (add (trunc X to (width - N1C)), AddC')
  7817. if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() && N1C &&
  7818. N0.getOperand(0).getOpcode() == ISD::SHL &&
  7819. N0.getOperand(0).getOperand(1) == N1 && N0.getOperand(0).hasOneUse()) {
  7820. if (ConstantSDNode *AddC = isConstOrConstSplat(N0.getOperand(1))) {
  7821. SDValue Shl = N0.getOperand(0);
  7822. // Determine what the truncate's type would be and ask the target if that
  7823. // is a free operation.
  7824. LLVMContext &Ctx = *DAG.getContext();
  7825. unsigned ShiftAmt = N1C->getZExtValue();
  7826. EVT TruncVT = EVT::getIntegerVT(Ctx, OpSizeInBits - ShiftAmt);
  7827. if (VT.isVector())
  7828. TruncVT = EVT::getVectorVT(Ctx, TruncVT, VT.getVectorElementCount());
  7829. // TODO: The simple type check probably belongs in the default hook
  7830. // implementation and/or target-specific overrides (because
  7831. // non-simple types likely require masking when legalized), but that
  7832. // restriction may conflict with other transforms.
  7833. if (TruncVT.isSimple() && isTypeLegal(TruncVT) &&
  7834. TLI.isTruncateFree(VT, TruncVT)) {
  7835. SDLoc DL(N);
  7836. SDValue Trunc = DAG.getZExtOrTrunc(Shl.getOperand(0), DL, TruncVT);
  7837. SDValue ShiftC = DAG.getConstant(AddC->getAPIntValue().lshr(ShiftAmt).
  7838. trunc(TruncVT.getScalarSizeInBits()), DL, TruncVT);
  7839. SDValue Add = DAG.getNode(ISD::ADD, DL, TruncVT, Trunc, ShiftC);
  7840. return DAG.getSExtOrTrunc(Add, DL, VT);
  7841. }
  7842. }
  7843. }
  7844. // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
  7845. if (N1.getOpcode() == ISD::TRUNCATE &&
  7846. N1.getOperand(0).getOpcode() == ISD::AND) {
  7847. if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
  7848. return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0, NewOp1);
  7849. }
  7850. // fold (sra (trunc (sra x, c1)), c2) -> (trunc (sra x, c1 + c2))
  7851. // fold (sra (trunc (srl x, c1)), c2) -> (trunc (sra x, c1 + c2))
  7852. // if c1 is equal to the number of bits the trunc removes
  7853. // TODO - support non-uniform vector shift amounts.
  7854. if (N0.getOpcode() == ISD::TRUNCATE &&
  7855. (N0.getOperand(0).getOpcode() == ISD::SRL ||
  7856. N0.getOperand(0).getOpcode() == ISD::SRA) &&
  7857. N0.getOperand(0).hasOneUse() &&
  7858. N0.getOperand(0).getOperand(1).hasOneUse() && N1C) {
  7859. SDValue N0Op0 = N0.getOperand(0);
  7860. if (ConstantSDNode *LargeShift = isConstOrConstSplat(N0Op0.getOperand(1))) {
  7861. EVT LargeVT = N0Op0.getValueType();
  7862. unsigned TruncBits = LargeVT.getScalarSizeInBits() - OpSizeInBits;
  7863. if (LargeShift->getAPIntValue() == TruncBits) {
  7864. SDLoc DL(N);
  7865. SDValue Amt = DAG.getConstant(N1C->getZExtValue() + TruncBits, DL,
  7866. getShiftAmountTy(LargeVT));
  7867. SDValue SRA =
  7868. DAG.getNode(ISD::SRA, DL, LargeVT, N0Op0.getOperand(0), Amt);
  7869. return DAG.getNode(ISD::TRUNCATE, DL, VT, SRA);
  7870. }
  7871. }
  7872. }
  7873. // Simplify, based on bits shifted out of the LHS.
  7874. if (SimplifyDemandedBits(SDValue(N, 0)))
  7875. return SDValue(N, 0);
  7876. // If the sign bit is known to be zero, switch this to a SRL.
  7877. if (DAG.SignBitIsZero(N0))
  7878. return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, N1);
  7879. if (N1C && !N1C->isOpaque())
  7880. if (SDValue NewSRA = visitShiftByConstant(N))
  7881. return NewSRA;
  7882. // Try to transform this shift into a multiply-high if
  7883. // it matches the appropriate pattern detected in combineShiftToMULH.
  7884. if (SDValue MULH = combineShiftToMULH(N, DAG, TLI))
  7885. return MULH;
  7886. // Attempt to convert a sra of a load into a narrower sign-extending load.
  7887. if (SDValue NarrowLoad = reduceLoadWidth(N))
  7888. return NarrowLoad;
  7889. return SDValue();
  7890. }
  7891. SDValue DAGCombiner::visitSRL(SDNode *N) {
  7892. SDValue N0 = N->getOperand(0);
  7893. SDValue N1 = N->getOperand(1);
  7894. if (SDValue V = DAG.simplifyShift(N0, N1))
  7895. return V;
  7896. EVT VT = N0.getValueType();
  7897. unsigned OpSizeInBits = VT.getScalarSizeInBits();
  7898. // fold (srl c1, c2) -> c1 >>u c2
  7899. if (SDValue C = DAG.FoldConstantArithmetic(ISD::SRL, SDLoc(N), VT, {N0, N1}))
  7900. return C;
  7901. // fold vector ops
  7902. if (VT.isVector())
  7903. if (SDValue FoldedVOp = SimplifyVBinOp(N, SDLoc(N)))
  7904. return FoldedVOp;
  7905. if (SDValue NewSel = foldBinOpIntoSelect(N))
  7906. return NewSel;
  7907. // if (srl x, c) is known to be zero, return 0
  7908. ConstantSDNode *N1C = isConstOrConstSplat(N1);
  7909. if (N1C &&
  7910. DAG.MaskedValueIsZero(SDValue(N, 0), APInt::getAllOnes(OpSizeInBits)))
  7911. return DAG.getConstant(0, SDLoc(N), VT);
  7912. // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
  7913. if (N0.getOpcode() == ISD::SRL) {
  7914. auto MatchOutOfRange = [OpSizeInBits](ConstantSDNode *LHS,
  7915. ConstantSDNode *RHS) {
  7916. APInt c1 = LHS->getAPIntValue();
  7917. APInt c2 = RHS->getAPIntValue();
  7918. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  7919. return (c1 + c2).uge(OpSizeInBits);
  7920. };
  7921. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchOutOfRange))
  7922. return DAG.getConstant(0, SDLoc(N), VT);
  7923. auto MatchInRange = [OpSizeInBits](ConstantSDNode *LHS,
  7924. ConstantSDNode *RHS) {
  7925. APInt c1 = LHS->getAPIntValue();
  7926. APInt c2 = RHS->getAPIntValue();
  7927. zeroExtendToMatch(c1, c2, 1 /* Overflow Bit */);
  7928. return (c1 + c2).ult(OpSizeInBits);
  7929. };
  7930. if (ISD::matchBinaryPredicate(N1, N0.getOperand(1), MatchInRange)) {
  7931. SDLoc DL(N);
  7932. EVT ShiftVT = N1.getValueType();
  7933. SDValue Sum = DAG.getNode(ISD::ADD, DL, ShiftVT, N1, N0.getOperand(1));
  7934. return DAG.getNode(ISD::SRL, DL, VT, N0.getOperand(0), Sum);
  7935. }
  7936. }
  7937. if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
  7938. N0.getOperand(0).getOpcode() == ISD::SRL) {
  7939. SDValue InnerShift = N0.getOperand(0);
  7940. // TODO - support non-uniform vector shift amounts.
  7941. if (auto *N001C = isConstOrConstSplat(InnerShift.getOperand(1))) {
  7942. uint64_t c1 = N001C->getZExtValue();
  7943. uint64_t c2 = N1C->getZExtValue();
  7944. EVT InnerShiftVT = InnerShift.getValueType();
  7945. EVT ShiftAmtVT = InnerShift.getOperand(1).getValueType();
  7946. uint64_t InnerShiftSize = InnerShiftVT.getScalarSizeInBits();
  7947. // srl (trunc (srl x, c1)), c2 --> 0 or (trunc (srl x, (add c1, c2)))
  7948. // This is only valid if the OpSizeInBits + c1 = size of inner shift.
  7949. if (c1 + OpSizeInBits == InnerShiftSize) {
  7950. SDLoc DL(N);
  7951. if (c1 + c2 >= InnerShiftSize)
  7952. return DAG.getConstant(0, DL, VT);
  7953. SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT);
  7954. SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT,
  7955. InnerShift.getOperand(0), NewShiftAmt);
  7956. return DAG.getNode(ISD::TRUNCATE, DL, VT, NewShift);
  7957. }
  7958. // In the more general case, we can clear the high bits after the shift:
  7959. // srl (trunc (srl x, c1)), c2 --> trunc (and (srl x, (c1+c2)), Mask)
  7960. if (N0.hasOneUse() && InnerShift.hasOneUse() &&
  7961. c1 + c2 < InnerShiftSize) {
  7962. SDLoc DL(N);
  7963. SDValue NewShiftAmt = DAG.getConstant(c1 + c2, DL, ShiftAmtVT);
  7964. SDValue NewShift = DAG.getNode(ISD::SRL, DL, InnerShiftVT,
  7965. InnerShift.getOperand(0), NewShiftAmt);
  7966. SDValue Mask = DAG.getConstant(APInt::getLowBitsSet(InnerShiftSize,
  7967. OpSizeInBits - c2),
  7968. DL, InnerShiftVT);
  7969. SDValue And = DAG.getNode(ISD::AND, DL, InnerShiftVT, NewShift, Mask);
  7970. return DAG.getNode(ISD::TRUNCATE, DL, VT, And);
  7971. }
  7972. }
  7973. }
  7974. // fold (srl (shl x, c), c) -> (and x, cst2)
  7975. // TODO - (srl (shl x, c1), c2).
  7976. if (N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
  7977. isConstantOrConstantVector(N1, /* NoOpaques */ true)) {
  7978. SDLoc DL(N);
  7979. SDValue Mask =
  7980. DAG.getNode(ISD::SRL, DL, VT, DAG.getAllOnesConstant(DL, VT), N1);
  7981. AddToWorklist(Mask.getNode());
  7982. return DAG.getNode(ISD::AND, DL, VT, N0.getOperand(0), Mask);
  7983. }
  7984. // fold (srl (anyextend x), c) -> (and (anyextend (srl x, c)), mask)
  7985. // TODO - support non-uniform vector shift amounts.
  7986. if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
  7987. // Shifting in all undef bits?
  7988. EVT SmallVT = N0.getOperand(0).getValueType();
  7989. unsigned BitSize = SmallVT.getScalarSizeInBits();
  7990. if (N1C->getAPIntValue().uge(BitSize))
  7991. return DAG.getUNDEF(VT);
  7992. if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
  7993. uint64_t ShiftAmt = N1C->getZExtValue();
  7994. SDLoc DL0(N0);
  7995. SDValue SmallShift = DAG.getNode(ISD::SRL, DL0, SmallVT,
  7996. N0.getOperand(0),
  7997. DAG.getConstant(ShiftAmt, DL0,
  7998. getShiftAmountTy(SmallVT)));
  7999. AddToWorklist(SmallShift.getNode());
  8000. APInt Mask = APInt::getLowBitsSet(OpSizeInBits, OpSizeInBits - ShiftAmt);
  8001. SDLoc DL(N);
  8002. return DAG.getNode(ISD::AND, DL, VT,
  8003. DAG.getNode(ISD::ANY_EXTEND, DL, VT, SmallShift),
  8004. DAG.getConstant(Mask, DL, VT));
  8005. }
  8006. }
  8007. // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
  8008. // bit, which is unmodified by sra.
  8009. if (N1C && N1C->getAPIntValue() == (OpSizeInBits - 1)) {
  8010. if (N0.getOpcode() == ISD::SRA)
  8011. return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0.getOperand(0), N1);
  8012. }
  8013. // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
  8014. if (N1C && N0.getOpcode() == ISD::CTLZ &&
  8015. N1C->getAPIntValue() == Log2_32(OpSizeInBits)) {
  8016. KnownBits Known = DAG.computeKnownBits(N0.getOperand(0));
  8017. // If any of the input bits are KnownOne, then the input couldn't be all
  8018. // zeros, thus the result of the srl will always be zero.
  8019. if (Known.One.getBoolValue()) return DAG.getConstant(0, SDLoc(N0), VT);
  8020. // If all of the bits input the to ctlz node are known to be zero, then
  8021. // the result of the ctlz is "32" and the result of the shift is one.
  8022. APInt UnknownBits = ~Known.Zero;
  8023. if (UnknownBits == 0) return DAG.getConstant(1, SDLoc(N0), VT);
  8024. // Otherwise, check to see if there is exactly one bit input to the ctlz.
  8025. if (UnknownBits.isPowerOf2()) {
  8026. // Okay, we know that only that the single bit specified by UnknownBits
  8027. // could be set on input to the CTLZ node. If this bit is set, the SRL
  8028. // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
  8029. // to an SRL/XOR pair, which is likely to simplify more.
  8030. unsigned ShAmt = UnknownBits.countTrailingZeros();
  8031. SDValue Op = N0.getOperand(0);
  8032. if (ShAmt) {
  8033. SDLoc DL(N0);
  8034. Op = DAG.getNode(ISD::SRL, DL, VT, Op,
  8035. DAG.getConstant(ShAmt, DL,
  8036. getShiftAmountTy(Op.getValueType())));
  8037. AddToWorklist(Op.getNode());
  8038. }
  8039. SDLoc DL(N);
  8040. return DAG.getNode(ISD::XOR, DL, VT,
  8041. Op, DAG.getConstant(1, DL, VT));
  8042. }
  8043. }
  8044. // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
  8045. if (N1.getOpcode() == ISD::TRUNCATE &&
  8046. N1.getOperand(0).getOpcode() == ISD::AND) {
  8047. if (SDValue NewOp1 = distributeTruncateThroughAnd(N1.getNode()))
  8048. return DAG.getNode(ISD::SRL, SDLoc(N), VT, N0, NewOp1);
  8049. }
  8050. // fold operands of srl based on knowledge that the low bits are not
  8051. // demanded.
  8052. if (SimplifyDemandedBits(SDValue(N, 0)))
  8053. return SDValue(N, 0);
  8054. if (N1C && !N1C->isOpaque())
  8055. if (SDValue NewSRL = visitShiftByConstant(N))
  8056. return NewSRL;
  8057. // Attempt to convert a srl of a load into a narrower zero-extending load.
  8058. if (SDValue NarrowLoad = reduceLoadWidth(N))
  8059. return NarrowLoad;
  8060. // Here is a common situation. We want to optimize:
  8061. //
  8062. // %a = ...
  8063. // %b = and i32 %a, 2
  8064. // %c = srl i32 %b, 1
  8065. // brcond i32 %c ...
  8066. //
  8067. // into
  8068. //
  8069. // %a = ...
  8070. // %b = and %a, 2
  8071. // %c = setcc eq %b, 0
  8072. // brcond %c ...
  8073. //
  8074. // However when after the source operand of SRL is optimized into AND, the SRL
  8075. // itself may not be optimized further. Look for it and add the BRCOND into
  8076. // the worklist.
  8077. if (N->hasOneUse()) {
  8078. SDNode *Use = *N->use_begin();
  8079. if (Use->getOpcode() == ISD::BRCOND)
  8080. AddToWorklist(Use);
  8081. else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
  8082. // Also look pass the truncate.
  8083. Use = *Use->use_begin();
  8084. if (Use->getOpcode() == ISD::BRCOND)
  8085. AddToWorklist(Use);
  8086. }
  8087. }
  8088. // Try to transform this shift into a multiply-high if
  8089. // it matches the appropriate pattern detected in combineShiftToMULH.
  8090. if (SDValue MULH = combineShiftToMULH(N, DAG, TLI))
  8091. return MULH;
  8092. return SDValue();
  8093. }
  8094. SDValue DAGCombiner::visitFunnelShift(SDNode *N) {
  8095. EVT VT = N->getValueType(0);
  8096. SDValue N0 = N->getOperand(0);
  8097. SDValue N1 = N->getOperand(1);
  8098. SDValue N2 = N->getOperand(2);
  8099. bool IsFSHL = N->getOpcode() == ISD::FSHL;
  8100. unsigned BitWidth = VT.getScalarSizeInBits();
  8101. // fold (fshl N0, N1, 0) -> N0
  8102. // fold (fshr N0, N1, 0) -> N1
  8103. if (isPowerOf2_32(BitWidth))
  8104. if (DAG.MaskedValueIsZero(
  8105. N2, APInt(N2.getScalarValueSizeInBits(), BitWidth - 1)))
  8106. return IsFSHL ? N0 : N1;
  8107. auto IsUndefOrZero = [](SDValue V) {
  8108. return V.isUndef() || isNullOrNullSplat(V, /*AllowUndefs*/ true);
  8109. };
  8110. // TODO - support non-uniform vector shift amounts.
  8111. if (ConstantSDNode *Cst = isConstOrConstSplat(N2)) {
  8112. EVT ShAmtTy = N2.getValueType();
  8113. // fold (fsh* N0, N1, c) -> (fsh* N0, N1, c % BitWidth)
  8114. if (Cst->getAPIntValue().uge(BitWidth)) {
  8115. uint64_t RotAmt = Cst->getAPIntValue().urem(BitWidth);
  8116. return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N0, N1,
  8117. DAG.getConstant(RotAmt, SDLoc(N), ShAmtTy));
  8118. }
  8119. unsigned ShAmt = Cst->getZExtValue();
  8120. if (ShAmt == 0)
  8121. return IsFSHL ? N0 : N1;
  8122. // fold fshl(undef_or_zero, N1, C) -> lshr(N1, BW-C)
  8123. // fold fshr(undef_or_zero, N1, C) -> lshr(N1, C)
  8124. // fold fshl(N0, undef_or_zero, C) -> shl(N0, C)
  8125. // fold fshr(N0, undef_or_zero, C) -> shl(N0, BW-C)
  8126. if (IsUndefOrZero(N0))
  8127. return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1,
  8128. DAG.getConstant(IsFSHL ? BitWidth - ShAmt : ShAmt,
  8129. SDLoc(N), ShAmtTy));
  8130. if (IsUndefOrZero(N1))
  8131. return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0,
  8132. DAG.getConstant(IsFSHL ? ShAmt : BitWidth - ShAmt,
  8133. SDLoc(N), ShAmtTy));
  8134. // fold (fshl ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive.
  8135. // fold (fshr ld1, ld0, c) -> (ld0[ofs]) iff ld0 and ld1 are consecutive.
  8136. // TODO - bigendian support once we have test coverage.
  8137. // TODO - can we merge this with CombineConseutiveLoads/MatchLoadCombine?
  8138. // TODO - permit LHS EXTLOAD if extensions are shifted out.
  8139. if ((BitWidth % 8) == 0 && (ShAmt % 8) == 0 && !VT.isVector() &&
  8140. !DAG.getDataLayout().isBigEndian()) {
  8141. auto *LHS = dyn_cast<LoadSDNode>(N0);
  8142. auto *RHS = dyn_cast<LoadSDNode>(N1);
  8143. if (LHS && RHS && LHS->isSimple() && RHS->isSimple() &&
  8144. LHS->getAddressSpace() == RHS->getAddressSpace() &&
  8145. (LHS->hasOneUse() || RHS->hasOneUse()) && ISD::isNON_EXTLoad(RHS) &&
  8146. ISD::isNON_EXTLoad(LHS)) {
  8147. if (DAG.areNonVolatileConsecutiveLoads(LHS, RHS, BitWidth / 8, 1)) {
  8148. SDLoc DL(RHS);
  8149. uint64_t PtrOff =
  8150. IsFSHL ? (((BitWidth - ShAmt) % BitWidth) / 8) : (ShAmt / 8);
  8151. Align NewAlign = commonAlignment(RHS->getAlign(), PtrOff);
  8152. bool Fast = false;
  8153. if (TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
  8154. RHS->getAddressSpace(), NewAlign,
  8155. RHS->getMemOperand()->getFlags(), &Fast) &&
  8156. Fast) {
  8157. SDValue NewPtr = DAG.getMemBasePlusOffset(
  8158. RHS->getBasePtr(), TypeSize::Fixed(PtrOff), DL);
  8159. AddToWorklist(NewPtr.getNode());
  8160. SDValue Load = DAG.getLoad(
  8161. VT, DL, RHS->getChain(), NewPtr,
  8162. RHS->getPointerInfo().getWithOffset(PtrOff), NewAlign,
  8163. RHS->getMemOperand()->getFlags(), RHS->getAAInfo());
  8164. // Replace the old load's chain with the new load's chain.
  8165. WorklistRemover DeadNodes(*this);
  8166. DAG.ReplaceAllUsesOfValueWith(N1.getValue(1), Load.getValue(1));
  8167. return Load;
  8168. }
  8169. }
  8170. }
  8171. }
  8172. }
  8173. // fold fshr(undef_or_zero, N1, N2) -> lshr(N1, N2)
  8174. // fold fshl(N0, undef_or_zero, N2) -> shl(N0, N2)
  8175. // iff We know the shift amount is in range.
  8176. // TODO: when is it worth doing SUB(BW, N2) as well?
  8177. if (isPowerOf2_32(BitWidth)) {
  8178. APInt ModuloBits(N2.getScalarValueSizeInBits(), BitWidth - 1);
  8179. if (IsUndefOrZero(N0) && !IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
  8180. return DAG.getNode(ISD::SRL, SDLoc(N), VT, N1, N2);
  8181. if (IsUndefOrZero(N1) && IsFSHL && DAG.MaskedValueIsZero(N2, ~ModuloBits))
  8182. return DAG.getNode(ISD::SHL, SDLoc(N), VT, N0, N2);
  8183. }
  8184. // fold (fshl N0, N0, N2) -> (rotl N0, N2)
  8185. // fold (fshr N0, N0, N2) -> (rotr N0, N2)
  8186. // TODO: Investigate flipping this rotate if only one is legal, if funnel shift
  8187. // is legal as well we might be better off avoiding non-constant (BW - N2).
  8188. unsigned RotOpc = IsFSHL ? ISD::ROTL : ISD::ROTR;
  8189. if (N0 == N1 && hasOperation(RotOpc, VT))
  8190. return DAG.getNode(RotOpc, SDLoc(N), VT, N0, N2);
  8191. // Simplify, based on bits shifted out of N0/N1.
  8192. if (SimplifyDemandedBits(SDValue(N, 0)))
  8193. return SDValue(N, 0);
  8194. return SDValue();
  8195. }
  8196. SDValue DAGCombiner::visitSHLSAT(SDNode *N) {
  8197. SDValue N0 = N->getOperand(0);
  8198. SDValue N1 = N->getOperand(1);
  8199. if (SDValue V = DAG.simplifyShift(N0, N1))
  8200. return V;
  8201. EVT VT = N0.getValueType();
  8202. // fold (*shlsat c1, c2) -> c1<<c2
  8203. if (SDValue C =
  8204. DAG.FoldConstantArithmetic(N->getOpcode(), SDLoc(N), VT, {N0, N1}))
  8205. return C;
  8206. return SDValue();
  8207. }
  8208. // Given a ABS node, detect the following pattern:
  8209. // (ABS (SUB (EXTEND a), (EXTEND b))).
  8210. // Generates UABD/SABD instruction.
  8211. static SDValue combineABSToABD(SDNode *N, SelectionDAG &DAG,
  8212. const TargetLowering &TLI) {
  8213. SDValue AbsOp1 = N->getOperand(0);
  8214. SDValue Op0, Op1;
  8215. if (AbsOp1.getOpcode() != ISD::SUB)
  8216. return SDValue();
  8217. Op0 = AbsOp1.getOperand(0);
  8218. Op1 = AbsOp1.getOperand(1);
  8219. unsigned Opc0 = Op0.getOpcode();
  8220. // Check if the operands of the sub are (zero|sign)-extended.
  8221. if (Opc0 != Op1.getOpcode() ||
  8222. (Opc0 != ISD::ZERO_EXTEND && Opc0 != ISD::SIGN_EXTEND))
  8223. return SDValue();
  8224. EVT VT1 = Op0.getOperand(0).getValueType();
  8225. EVT VT2 = Op1.getOperand(0).getValueType();
  8226. // Check if the operands are of same type and valid size.
  8227. unsigned ABDOpcode = (Opc0 == ISD::SIGN_EXTEND) ? ISD::ABDS : ISD::ABDU;
  8228. if (VT1 != VT2 || !TLI.isOperationLegalOrCustom(ABDOpcode, VT1))
  8229. return SDValue();
  8230. Op0 = Op0.getOperand(0);
  8231. Op1 = Op1.getOperand(0);
  8232. SDValue ABD =
  8233. DAG.getNode(ABDOpcode, SDLoc(N), Op0->getValueType(0), Op0, Op1);
  8234. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), N->getValueType(0), ABD);
  8235. }
  8236. SDValue DAGCombiner::visitABS(SDNode *N) {
  8237. SDValue N0 = N->getOperand(0);
  8238. EVT VT = N->getValueType(0);
  8239. // fold (abs c1) -> c2
  8240. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8241. return DAG.getNode(ISD::ABS, SDLoc(N), VT, N0);
  8242. // fold (abs (abs x)) -> (abs x)
  8243. if (N0.getOpcode() == ISD::ABS)
  8244. return N0;
  8245. // fold (abs x) -> x iff not-negative
  8246. if (DAG.SignBitIsZero(N0))
  8247. return N0;
  8248. if (SDValue ABD = combineABSToABD(N, DAG, TLI))
  8249. return ABD;
  8250. return SDValue();
  8251. }
  8252. SDValue DAGCombiner::visitBSWAP(SDNode *N) {
  8253. SDValue N0 = N->getOperand(0);
  8254. EVT VT = N->getValueType(0);
  8255. // fold (bswap c1) -> c2
  8256. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8257. return DAG.getNode(ISD::BSWAP, SDLoc(N), VT, N0);
  8258. // fold (bswap (bswap x)) -> x
  8259. if (N0.getOpcode() == ISD::BSWAP)
  8260. return N0->getOperand(0);
  8261. // Canonicalize bswap(bitreverse(x)) -> bitreverse(bswap(x)). If bitreverse
  8262. // isn't supported, it will be expanded to bswap followed by a manual reversal
  8263. // of bits in each byte. By placing bswaps before bitreverse, we can remove
  8264. // the two bswaps if the bitreverse gets expanded.
  8265. if (N0.getOpcode() == ISD::BITREVERSE && N0.hasOneUse()) {
  8266. SDLoc DL(N);
  8267. SDValue BSwap = DAG.getNode(ISD::BSWAP, DL, VT, N0.getOperand(0));
  8268. return DAG.getNode(ISD::BITREVERSE, DL, VT, BSwap);
  8269. }
  8270. return SDValue();
  8271. }
  8272. SDValue DAGCombiner::visitBITREVERSE(SDNode *N) {
  8273. SDValue N0 = N->getOperand(0);
  8274. EVT VT = N->getValueType(0);
  8275. // fold (bitreverse c1) -> c2
  8276. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8277. return DAG.getNode(ISD::BITREVERSE, SDLoc(N), VT, N0);
  8278. // fold (bitreverse (bitreverse x)) -> x
  8279. if (N0.getOpcode() == ISD::BITREVERSE)
  8280. return N0.getOperand(0);
  8281. return SDValue();
  8282. }
  8283. SDValue DAGCombiner::visitCTLZ(SDNode *N) {
  8284. SDValue N0 = N->getOperand(0);
  8285. EVT VT = N->getValueType(0);
  8286. // fold (ctlz c1) -> c2
  8287. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8288. return DAG.getNode(ISD::CTLZ, SDLoc(N), VT, N0);
  8289. // If the value is known never to be zero, switch to the undef version.
  8290. if (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ_ZERO_UNDEF, VT)) {
  8291. if (DAG.isKnownNeverZero(N0))
  8292. return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
  8293. }
  8294. return SDValue();
  8295. }
  8296. SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
  8297. SDValue N0 = N->getOperand(0);
  8298. EVT VT = N->getValueType(0);
  8299. // fold (ctlz_zero_undef c1) -> c2
  8300. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8301. return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, SDLoc(N), VT, N0);
  8302. return SDValue();
  8303. }
  8304. SDValue DAGCombiner::visitCTTZ(SDNode *N) {
  8305. SDValue N0 = N->getOperand(0);
  8306. EVT VT = N->getValueType(0);
  8307. // fold (cttz c1) -> c2
  8308. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8309. return DAG.getNode(ISD::CTTZ, SDLoc(N), VT, N0);
  8310. // If the value is known never to be zero, switch to the undef version.
  8311. if (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ_ZERO_UNDEF, VT)) {
  8312. if (DAG.isKnownNeverZero(N0))
  8313. return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
  8314. }
  8315. return SDValue();
  8316. }
  8317. SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
  8318. SDValue N0 = N->getOperand(0);
  8319. EVT VT = N->getValueType(0);
  8320. // fold (cttz_zero_undef c1) -> c2
  8321. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8322. return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, SDLoc(N), VT, N0);
  8323. return SDValue();
  8324. }
  8325. SDValue DAGCombiner::visitCTPOP(SDNode *N) {
  8326. SDValue N0 = N->getOperand(0);
  8327. EVT VT = N->getValueType(0);
  8328. // fold (ctpop c1) -> c2
  8329. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  8330. return DAG.getNode(ISD::CTPOP, SDLoc(N), VT, N0);
  8331. return SDValue();
  8332. }
  8333. // FIXME: This should be checking for no signed zeros on individual operands, as
  8334. // well as no nans.
  8335. static bool isLegalToCombineMinNumMaxNum(SelectionDAG &DAG, SDValue LHS,
  8336. SDValue RHS,
  8337. const TargetLowering &TLI) {
  8338. const TargetOptions &Options = DAG.getTarget().Options;
  8339. EVT VT = LHS.getValueType();
  8340. return Options.NoSignedZerosFPMath && VT.isFloatingPoint() &&
  8341. TLI.isProfitableToCombineMinNumMaxNum(VT) &&
  8342. DAG.isKnownNeverNaN(LHS) && DAG.isKnownNeverNaN(RHS);
  8343. }
  8344. /// Generate Min/Max node
  8345. static SDValue combineMinNumMaxNum(const SDLoc &DL, EVT VT, SDValue LHS,
  8346. SDValue RHS, SDValue True, SDValue False,
  8347. ISD::CondCode CC, const TargetLowering &TLI,
  8348. SelectionDAG &DAG) {
  8349. if (!(LHS == True && RHS == False) && !(LHS == False && RHS == True))
  8350. return SDValue();
  8351. EVT TransformVT = TLI.getTypeToTransformTo(*DAG.getContext(), VT);
  8352. switch (CC) {
  8353. case ISD::SETOLT:
  8354. case ISD::SETOLE:
  8355. case ISD::SETLT:
  8356. case ISD::SETLE:
  8357. case ISD::SETULT:
  8358. case ISD::SETULE: {
  8359. // Since it's known never nan to get here already, either fminnum or
  8360. // fminnum_ieee are OK. Try the ieee version first, since it's fminnum is
  8361. // expanded in terms of it.
  8362. unsigned IEEEOpcode = (LHS == True) ? ISD::FMINNUM_IEEE : ISD::FMAXNUM_IEEE;
  8363. if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
  8364. return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS);
  8365. unsigned Opcode = (LHS == True) ? ISD::FMINNUM : ISD::FMAXNUM;
  8366. if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
  8367. return DAG.getNode(Opcode, DL, VT, LHS, RHS);
  8368. return SDValue();
  8369. }
  8370. case ISD::SETOGT:
  8371. case ISD::SETOGE:
  8372. case ISD::SETGT:
  8373. case ISD::SETGE:
  8374. case ISD::SETUGT:
  8375. case ISD::SETUGE: {
  8376. unsigned IEEEOpcode = (LHS == True) ? ISD::FMAXNUM_IEEE : ISD::FMINNUM_IEEE;
  8377. if (TLI.isOperationLegalOrCustom(IEEEOpcode, VT))
  8378. return DAG.getNode(IEEEOpcode, DL, VT, LHS, RHS);
  8379. unsigned Opcode = (LHS == True) ? ISD::FMAXNUM : ISD::FMINNUM;
  8380. if (TLI.isOperationLegalOrCustom(Opcode, TransformVT))
  8381. return DAG.getNode(Opcode, DL, VT, LHS, RHS);
  8382. return SDValue();
  8383. }
  8384. default:
  8385. return SDValue();
  8386. }
  8387. }
  8388. /// If a (v)select has a condition value that is a sign-bit test, try to smear
  8389. /// the condition operand sign-bit across the value width and use it as a mask.
  8390. static SDValue foldSelectOfConstantsUsingSra(SDNode *N, SelectionDAG &DAG) {
  8391. SDValue Cond = N->getOperand(0);
  8392. SDValue C1 = N->getOperand(1);
  8393. SDValue C2 = N->getOperand(2);
  8394. if (!isConstantOrConstantVector(C1) || !isConstantOrConstantVector(C2))
  8395. return SDValue();
  8396. EVT VT = N->getValueType(0);
  8397. if (Cond.getOpcode() != ISD::SETCC || !Cond.hasOneUse() ||
  8398. VT != Cond.getOperand(0).getValueType())
  8399. return SDValue();
  8400. // The inverted-condition + commuted-select variants of these patterns are
  8401. // canonicalized to these forms in IR.
  8402. SDValue X = Cond.getOperand(0);
  8403. SDValue CondC = Cond.getOperand(1);
  8404. ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
  8405. if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(CondC) &&
  8406. isAllOnesOrAllOnesSplat(C2)) {
  8407. // i32 X > -1 ? C1 : -1 --> (X >>s 31) | C1
  8408. SDLoc DL(N);
  8409. SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT);
  8410. SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC);
  8411. return DAG.getNode(ISD::OR, DL, VT, Sra, C1);
  8412. }
  8413. if (CC == ISD::SETLT && isNullOrNullSplat(CondC) && isNullOrNullSplat(C2)) {
  8414. // i8 X < 0 ? C1 : 0 --> (X >>s 7) & C1
  8415. SDLoc DL(N);
  8416. SDValue ShAmtC = DAG.getConstant(X.getScalarValueSizeInBits() - 1, DL, VT);
  8417. SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, X, ShAmtC);
  8418. return DAG.getNode(ISD::AND, DL, VT, Sra, C1);
  8419. }
  8420. return SDValue();
  8421. }
  8422. SDValue DAGCombiner::foldSelectOfConstants(SDNode *N) {
  8423. SDValue Cond = N->getOperand(0);
  8424. SDValue N1 = N->getOperand(1);
  8425. SDValue N2 = N->getOperand(2);
  8426. EVT VT = N->getValueType(0);
  8427. EVT CondVT = Cond.getValueType();
  8428. SDLoc DL(N);
  8429. if (!VT.isInteger())
  8430. return SDValue();
  8431. auto *C1 = dyn_cast<ConstantSDNode>(N1);
  8432. auto *C2 = dyn_cast<ConstantSDNode>(N2);
  8433. if (!C1 || !C2)
  8434. return SDValue();
  8435. // Only do this before legalization to avoid conflicting with target-specific
  8436. // transforms in the other direction (create a select from a zext/sext). There
  8437. // is also a target-independent combine here in DAGCombiner in the other
  8438. // direction for (select Cond, -1, 0) when the condition is not i1.
  8439. if (CondVT == MVT::i1 && !LegalOperations) {
  8440. if (C1->isZero() && C2->isOne()) {
  8441. // select Cond, 0, 1 --> zext (!Cond)
  8442. SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
  8443. if (VT != MVT::i1)
  8444. NotCond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, NotCond);
  8445. return NotCond;
  8446. }
  8447. if (C1->isZero() && C2->isAllOnes()) {
  8448. // select Cond, 0, -1 --> sext (!Cond)
  8449. SDValue NotCond = DAG.getNOT(DL, Cond, MVT::i1);
  8450. if (VT != MVT::i1)
  8451. NotCond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NotCond);
  8452. return NotCond;
  8453. }
  8454. if (C1->isOne() && C2->isZero()) {
  8455. // select Cond, 1, 0 --> zext (Cond)
  8456. if (VT != MVT::i1)
  8457. Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
  8458. return Cond;
  8459. }
  8460. if (C1->isAllOnes() && C2->isZero()) {
  8461. // select Cond, -1, 0 --> sext (Cond)
  8462. if (VT != MVT::i1)
  8463. Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
  8464. return Cond;
  8465. }
  8466. // Use a target hook because some targets may prefer to transform in the
  8467. // other direction.
  8468. if (TLI.convertSelectOfConstantsToMath(VT)) {
  8469. // For any constants that differ by 1, we can transform the select into an
  8470. // extend and add.
  8471. const APInt &C1Val = C1->getAPIntValue();
  8472. const APInt &C2Val = C2->getAPIntValue();
  8473. if (C1Val - 1 == C2Val) {
  8474. // select Cond, C1, C1-1 --> add (zext Cond), C1-1
  8475. if (VT != MVT::i1)
  8476. Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
  8477. return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
  8478. }
  8479. if (C1Val + 1 == C2Val) {
  8480. // select Cond, C1, C1+1 --> add (sext Cond), C1+1
  8481. if (VT != MVT::i1)
  8482. Cond = DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Cond);
  8483. return DAG.getNode(ISD::ADD, DL, VT, Cond, N2);
  8484. }
  8485. // select Cond, Pow2, 0 --> (zext Cond) << log2(Pow2)
  8486. if (C1Val.isPowerOf2() && C2Val.isZero()) {
  8487. if (VT != MVT::i1)
  8488. Cond = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Cond);
  8489. SDValue ShAmtC = DAG.getConstant(C1Val.exactLogBase2(), DL, VT);
  8490. return DAG.getNode(ISD::SHL, DL, VT, Cond, ShAmtC);
  8491. }
  8492. if (SDValue V = foldSelectOfConstantsUsingSra(N, DAG))
  8493. return V;
  8494. }
  8495. return SDValue();
  8496. }
  8497. // fold (select Cond, 0, 1) -> (xor Cond, 1)
  8498. // We can't do this reliably if integer based booleans have different contents
  8499. // to floating point based booleans. This is because we can't tell whether we
  8500. // have an integer-based boolean or a floating-point-based boolean unless we
  8501. // can find the SETCC that produced it and inspect its operands. This is
  8502. // fairly easy if C is the SETCC node, but it can potentially be
  8503. // undiscoverable (or not reasonably discoverable). For example, it could be
  8504. // in another basic block or it could require searching a complicated
  8505. // expression.
  8506. if (CondVT.isInteger() &&
  8507. TLI.getBooleanContents(/*isVec*/false, /*isFloat*/true) ==
  8508. TargetLowering::ZeroOrOneBooleanContent &&
  8509. TLI.getBooleanContents(/*isVec*/false, /*isFloat*/false) ==
  8510. TargetLowering::ZeroOrOneBooleanContent &&
  8511. C1->isZero() && C2->isOne()) {
  8512. SDValue NotCond =
  8513. DAG.getNode(ISD::XOR, DL, CondVT, Cond, DAG.getConstant(1, DL, CondVT));
  8514. if (VT.bitsEq(CondVT))
  8515. return NotCond;
  8516. return DAG.getZExtOrTrunc(NotCond, DL, VT);
  8517. }
  8518. return SDValue();
  8519. }
  8520. static SDValue foldBoolSelectToLogic(SDNode *N, SelectionDAG &DAG) {
  8521. assert((N->getOpcode() == ISD::SELECT || N->getOpcode() == ISD::VSELECT) &&
  8522. "Expected a (v)select");
  8523. SDValue Cond = N->getOperand(0);
  8524. SDValue T = N->getOperand(1), F = N->getOperand(2);
  8525. EVT VT = N->getValueType(0);
  8526. if (VT != Cond.getValueType() || VT.getScalarSizeInBits() != 1)
  8527. return SDValue();
  8528. // select Cond, Cond, F --> or Cond, F
  8529. // select Cond, 1, F --> or Cond, F
  8530. if (Cond == T || isOneOrOneSplat(T, /* AllowUndefs */ true))
  8531. return DAG.getNode(ISD::OR, SDLoc(N), VT, Cond, F);
  8532. // select Cond, T, Cond --> and Cond, T
  8533. // select Cond, T, 0 --> and Cond, T
  8534. if (Cond == F || isNullOrNullSplat(F, /* AllowUndefs */ true))
  8535. return DAG.getNode(ISD::AND, SDLoc(N), VT, Cond, T);
  8536. // select Cond, T, 1 --> or (not Cond), T
  8537. if (isOneOrOneSplat(F, /* AllowUndefs */ true)) {
  8538. SDValue NotCond = DAG.getNOT(SDLoc(N), Cond, VT);
  8539. return DAG.getNode(ISD::OR, SDLoc(N), VT, NotCond, T);
  8540. }
  8541. // select Cond, 0, F --> and (not Cond), F
  8542. if (isNullOrNullSplat(T, /* AllowUndefs */ true)) {
  8543. SDValue NotCond = DAG.getNOT(SDLoc(N), Cond, VT);
  8544. return DAG.getNode(ISD::AND, SDLoc(N), VT, NotCond, F);
  8545. }
  8546. return SDValue();
  8547. }
  8548. static SDValue foldVSelectToSignBitSplatMask(SDNode *N, SelectionDAG &DAG) {
  8549. SDValue N0 = N->getOperand(0);
  8550. SDValue N1 = N->getOperand(1);
  8551. SDValue N2 = N->getOperand(2);
  8552. EVT VT = N->getValueType(0);
  8553. if (N0.getOpcode() != ISD::SETCC || !N0.hasOneUse())
  8554. return SDValue();
  8555. SDValue Cond0 = N0.getOperand(0);
  8556. SDValue Cond1 = N0.getOperand(1);
  8557. ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
  8558. if (VT != Cond0.getValueType())
  8559. return SDValue();
  8560. // Match a signbit check of Cond0 as "Cond0 s<0". Swap select operands if the
  8561. // compare is inverted from that pattern ("Cond0 s> -1").
  8562. if (CC == ISD::SETLT && isNullOrNullSplat(Cond1))
  8563. ; // This is the pattern we are looking for.
  8564. else if (CC == ISD::SETGT && isAllOnesOrAllOnesSplat(Cond1))
  8565. std::swap(N1, N2);
  8566. else
  8567. return SDValue();
  8568. // (Cond0 s< 0) ? N1 : 0 --> (Cond0 s>> BW-1) & N1
  8569. if (isNullOrNullSplat(N2)) {
  8570. SDLoc DL(N);
  8571. SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT);
  8572. SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
  8573. return DAG.getNode(ISD::AND, DL, VT, Sra, N1);
  8574. }
  8575. // (Cond0 s< 0) ? -1 : N2 --> (Cond0 s>> BW-1) | N2
  8576. if (isAllOnesOrAllOnesSplat(N1)) {
  8577. SDLoc DL(N);
  8578. SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT);
  8579. SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
  8580. return DAG.getNode(ISD::OR, DL, VT, Sra, N2);
  8581. }
  8582. // If we have to invert the sign bit mask, only do that transform if the
  8583. // target has a bitwise 'and not' instruction (the invert is free).
  8584. // (Cond0 s< -0) ? 0 : N2 --> ~(Cond0 s>> BW-1) & N2
  8585. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8586. if (isNullOrNullSplat(N1) && TLI.hasAndNot(N1)) {
  8587. SDLoc DL(N);
  8588. SDValue ShiftAmt = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT);
  8589. SDValue Sra = DAG.getNode(ISD::SRA, DL, VT, Cond0, ShiftAmt);
  8590. SDValue Not = DAG.getNOT(DL, Sra, VT);
  8591. return DAG.getNode(ISD::AND, DL, VT, Not, N2);
  8592. }
  8593. // TODO: There's another pattern in this family, but it may require
  8594. // implementing hasOrNot() to check for profitability:
  8595. // (Cond0 s> -1) ? -1 : N2 --> ~(Cond0 s>> BW-1) | N2
  8596. return SDValue();
  8597. }
  8598. SDValue DAGCombiner::visitSELECT(SDNode *N) {
  8599. SDValue N0 = N->getOperand(0);
  8600. SDValue N1 = N->getOperand(1);
  8601. SDValue N2 = N->getOperand(2);
  8602. EVT VT = N->getValueType(0);
  8603. EVT VT0 = N0.getValueType();
  8604. SDLoc DL(N);
  8605. SDNodeFlags Flags = N->getFlags();
  8606. if (SDValue V = DAG.simplifySelect(N0, N1, N2))
  8607. return V;
  8608. if (SDValue V = foldSelectOfConstants(N))
  8609. return V;
  8610. if (SDValue V = foldBoolSelectToLogic(N, DAG))
  8611. return V;
  8612. // If we can fold this based on the true/false value, do so.
  8613. if (SimplifySelectOps(N, N1, N2))
  8614. return SDValue(N, 0); // Don't revisit N.
  8615. if (VT0 == MVT::i1) {
  8616. // The code in this block deals with the following 2 equivalences:
  8617. // select(C0|C1, x, y) <=> select(C0, x, select(C1, x, y))
  8618. // select(C0&C1, x, y) <=> select(C0, select(C1, x, y), y)
  8619. // The target can specify its preferred form with the
  8620. // shouldNormalizeToSelectSequence() callback. However we always transform
  8621. // to the right anyway if we find the inner select exists in the DAG anyway
  8622. // and we always transform to the left side if we know that we can further
  8623. // optimize the combination of the conditions.
  8624. bool normalizeToSequence =
  8625. TLI.shouldNormalizeToSelectSequence(*DAG.getContext(), VT);
  8626. // select (and Cond0, Cond1), X, Y
  8627. // -> select Cond0, (select Cond1, X, Y), Y
  8628. if (N0->getOpcode() == ISD::AND && N0->hasOneUse()) {
  8629. SDValue Cond0 = N0->getOperand(0);
  8630. SDValue Cond1 = N0->getOperand(1);
  8631. SDValue InnerSelect =
  8632. DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond1, N1, N2, Flags);
  8633. if (normalizeToSequence || !InnerSelect.use_empty())
  8634. return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0,
  8635. InnerSelect, N2, Flags);
  8636. // Cleanup on failure.
  8637. if (InnerSelect.use_empty())
  8638. recursivelyDeleteUnusedNodes(InnerSelect.getNode());
  8639. }
  8640. // select (or Cond0, Cond1), X, Y -> select Cond0, X, (select Cond1, X, Y)
  8641. if (N0->getOpcode() == ISD::OR && N0->hasOneUse()) {
  8642. SDValue Cond0 = N0->getOperand(0);
  8643. SDValue Cond1 = N0->getOperand(1);
  8644. SDValue InnerSelect = DAG.getNode(ISD::SELECT, DL, N1.getValueType(),
  8645. Cond1, N1, N2, Flags);
  8646. if (normalizeToSequence || !InnerSelect.use_empty())
  8647. return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Cond0, N1,
  8648. InnerSelect, Flags);
  8649. // Cleanup on failure.
  8650. if (InnerSelect.use_empty())
  8651. recursivelyDeleteUnusedNodes(InnerSelect.getNode());
  8652. }
  8653. // select Cond0, (select Cond1, X, Y), Y -> select (and Cond0, Cond1), X, Y
  8654. if (N1->getOpcode() == ISD::SELECT && N1->hasOneUse()) {
  8655. SDValue N1_0 = N1->getOperand(0);
  8656. SDValue N1_1 = N1->getOperand(1);
  8657. SDValue N1_2 = N1->getOperand(2);
  8658. if (N1_2 == N2 && N0.getValueType() == N1_0.getValueType()) {
  8659. // Create the actual and node if we can generate good code for it.
  8660. if (!normalizeToSequence) {
  8661. SDValue And = DAG.getNode(ISD::AND, DL, N0.getValueType(), N0, N1_0);
  8662. return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), And, N1_1,
  8663. N2, Flags);
  8664. }
  8665. // Otherwise see if we can optimize the "and" to a better pattern.
  8666. if (SDValue Combined = visitANDLike(N0, N1_0, N)) {
  8667. return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1_1,
  8668. N2, Flags);
  8669. }
  8670. }
  8671. }
  8672. // select Cond0, X, (select Cond1, X, Y) -> select (or Cond0, Cond1), X, Y
  8673. if (N2->getOpcode() == ISD::SELECT && N2->hasOneUse()) {
  8674. SDValue N2_0 = N2->getOperand(0);
  8675. SDValue N2_1 = N2->getOperand(1);
  8676. SDValue N2_2 = N2->getOperand(2);
  8677. if (N2_1 == N1 && N0.getValueType() == N2_0.getValueType()) {
  8678. // Create the actual or node if we can generate good code for it.
  8679. if (!normalizeToSequence) {
  8680. SDValue Or = DAG.getNode(ISD::OR, DL, N0.getValueType(), N0, N2_0);
  8681. return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Or, N1,
  8682. N2_2, Flags);
  8683. }
  8684. // Otherwise see if we can optimize to a better pattern.
  8685. if (SDValue Combined = visitORLike(N0, N2_0, N))
  8686. return DAG.getNode(ISD::SELECT, DL, N1.getValueType(), Combined, N1,
  8687. N2_2, Flags);
  8688. }
  8689. }
  8690. }
  8691. // select (not Cond), N1, N2 -> select Cond, N2, N1
  8692. if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false)) {
  8693. SDValue SelectOp = DAG.getSelect(DL, VT, F, N2, N1);
  8694. SelectOp->setFlags(Flags);
  8695. return SelectOp;
  8696. }
  8697. // Fold selects based on a setcc into other things, such as min/max/abs.
  8698. if (N0.getOpcode() == ISD::SETCC) {
  8699. SDValue Cond0 = N0.getOperand(0), Cond1 = N0.getOperand(1);
  8700. ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
  8701. // select (fcmp lt x, y), x, y -> fminnum x, y
  8702. // select (fcmp gt x, y), x, y -> fmaxnum x, y
  8703. //
  8704. // This is OK if we don't care what happens if either operand is a NaN.
  8705. if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, N1, N2, TLI))
  8706. if (SDValue FMinMax = combineMinNumMaxNum(DL, VT, Cond0, Cond1, N1, N2,
  8707. CC, TLI, DAG))
  8708. return FMinMax;
  8709. // Use 'unsigned add with overflow' to optimize an unsigned saturating add.
  8710. // This is conservatively limited to pre-legal-operations to give targets
  8711. // a chance to reverse the transform if they want to do that. Also, it is
  8712. // unlikely that the pattern would be formed late, so it's probably not
  8713. // worth going through the other checks.
  8714. if (!LegalOperations && TLI.isOperationLegalOrCustom(ISD::UADDO, VT) &&
  8715. CC == ISD::SETUGT && N0.hasOneUse() && isAllOnesConstant(N1) &&
  8716. N2.getOpcode() == ISD::ADD && Cond0 == N2.getOperand(0)) {
  8717. auto *C = dyn_cast<ConstantSDNode>(N2.getOperand(1));
  8718. auto *NotC = dyn_cast<ConstantSDNode>(Cond1);
  8719. if (C && NotC && C->getAPIntValue() == ~NotC->getAPIntValue()) {
  8720. // select (setcc Cond0, ~C, ugt), -1, (add Cond0, C) -->
  8721. // uaddo Cond0, C; select uaddo.1, -1, uaddo.0
  8722. //
  8723. // The IR equivalent of this transform would have this form:
  8724. // %a = add %x, C
  8725. // %c = icmp ugt %x, ~C
  8726. // %r = select %c, -1, %a
  8727. // =>
  8728. // %u = call {iN,i1} llvm.uadd.with.overflow(%x, C)
  8729. // %u0 = extractvalue %u, 0
  8730. // %u1 = extractvalue %u, 1
  8731. // %r = select %u1, -1, %u0
  8732. SDVTList VTs = DAG.getVTList(VT, VT0);
  8733. SDValue UAO = DAG.getNode(ISD::UADDO, DL, VTs, Cond0, N2.getOperand(1));
  8734. return DAG.getSelect(DL, VT, UAO.getValue(1), N1, UAO.getValue(0));
  8735. }
  8736. }
  8737. if (TLI.isOperationLegal(ISD::SELECT_CC, VT) ||
  8738. (!LegalOperations &&
  8739. TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))) {
  8740. // Any flags available in a select/setcc fold will be on the setcc as they
  8741. // migrated from fcmp
  8742. Flags = N0.getNode()->getFlags();
  8743. SDValue SelectNode = DAG.getNode(ISD::SELECT_CC, DL, VT, Cond0, Cond1, N1,
  8744. N2, N0.getOperand(2));
  8745. SelectNode->setFlags(Flags);
  8746. return SelectNode;
  8747. }
  8748. if (SDValue NewSel = SimplifySelect(DL, N0, N1, N2))
  8749. return NewSel;
  8750. }
  8751. if (!VT.isVector())
  8752. if (SDValue BinOp = foldSelectOfBinops(N))
  8753. return BinOp;
  8754. return SDValue();
  8755. }
  8756. // This function assumes all the vselect's arguments are CONCAT_VECTOR
  8757. // nodes and that the condition is a BV of ConstantSDNodes (or undefs).
  8758. static SDValue ConvertSelectToConcatVector(SDNode *N, SelectionDAG &DAG) {
  8759. SDLoc DL(N);
  8760. SDValue Cond = N->getOperand(0);
  8761. SDValue LHS = N->getOperand(1);
  8762. SDValue RHS = N->getOperand(2);
  8763. EVT VT = N->getValueType(0);
  8764. int NumElems = VT.getVectorNumElements();
  8765. assert(LHS.getOpcode() == ISD::CONCAT_VECTORS &&
  8766. RHS.getOpcode() == ISD::CONCAT_VECTORS &&
  8767. Cond.getOpcode() == ISD::BUILD_VECTOR);
  8768. // CONCAT_VECTOR can take an arbitrary number of arguments. We only care about
  8769. // binary ones here.
  8770. if (LHS->getNumOperands() != 2 || RHS->getNumOperands() != 2)
  8771. return SDValue();
  8772. // We're sure we have an even number of elements due to the
  8773. // concat_vectors we have as arguments to vselect.
  8774. // Skip BV elements until we find one that's not an UNDEF
  8775. // After we find an UNDEF element, keep looping until we get to half the
  8776. // length of the BV and see if all the non-undef nodes are the same.
  8777. ConstantSDNode *BottomHalf = nullptr;
  8778. for (int i = 0; i < NumElems / 2; ++i) {
  8779. if (Cond->getOperand(i)->isUndef())
  8780. continue;
  8781. if (BottomHalf == nullptr)
  8782. BottomHalf = cast<ConstantSDNode>(Cond.getOperand(i));
  8783. else if (Cond->getOperand(i).getNode() != BottomHalf)
  8784. return SDValue();
  8785. }
  8786. // Do the same for the second half of the BuildVector
  8787. ConstantSDNode *TopHalf = nullptr;
  8788. for (int i = NumElems / 2; i < NumElems; ++i) {
  8789. if (Cond->getOperand(i)->isUndef())
  8790. continue;
  8791. if (TopHalf == nullptr)
  8792. TopHalf = cast<ConstantSDNode>(Cond.getOperand(i));
  8793. else if (Cond->getOperand(i).getNode() != TopHalf)
  8794. return SDValue();
  8795. }
  8796. assert(TopHalf && BottomHalf &&
  8797. "One half of the selector was all UNDEFs and the other was all the "
  8798. "same value. This should have been addressed before this function.");
  8799. return DAG.getNode(
  8800. ISD::CONCAT_VECTORS, DL, VT,
  8801. BottomHalf->isZero() ? RHS->getOperand(0) : LHS->getOperand(0),
  8802. TopHalf->isZero() ? RHS->getOperand(1) : LHS->getOperand(1));
  8803. }
  8804. bool refineUniformBase(SDValue &BasePtr, SDValue &Index, SelectionDAG &DAG) {
  8805. if (!isNullConstant(BasePtr) || Index.getOpcode() != ISD::ADD)
  8806. return false;
  8807. // For now we check only the LHS of the add.
  8808. SDValue LHS = Index.getOperand(0);
  8809. SDValue SplatVal = DAG.getSplatValue(LHS);
  8810. if (!SplatVal)
  8811. return false;
  8812. BasePtr = SplatVal;
  8813. Index = Index.getOperand(1);
  8814. return true;
  8815. }
  8816. // Fold sext/zext of index into index type.
  8817. bool refineIndexType(MaskedGatherScatterSDNode *MGS, SDValue &Index,
  8818. bool Scaled, SelectionDAG &DAG) {
  8819. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  8820. if (Index.getOpcode() == ISD::ZERO_EXTEND) {
  8821. SDValue Op = Index.getOperand(0);
  8822. MGS->setIndexType(Scaled ? ISD::UNSIGNED_SCALED : ISD::UNSIGNED_UNSCALED);
  8823. if (TLI.shouldRemoveExtendFromGSIndex(Op.getValueType())) {
  8824. Index = Op;
  8825. return true;
  8826. }
  8827. }
  8828. if (Index.getOpcode() == ISD::SIGN_EXTEND) {
  8829. SDValue Op = Index.getOperand(0);
  8830. MGS->setIndexType(Scaled ? ISD::SIGNED_SCALED : ISD::SIGNED_UNSCALED);
  8831. if (TLI.shouldRemoveExtendFromGSIndex(Op.getValueType())) {
  8832. Index = Op;
  8833. return true;
  8834. }
  8835. }
  8836. return false;
  8837. }
  8838. SDValue DAGCombiner::visitMSCATTER(SDNode *N) {
  8839. MaskedScatterSDNode *MSC = cast<MaskedScatterSDNode>(N);
  8840. SDValue Mask = MSC->getMask();
  8841. SDValue Chain = MSC->getChain();
  8842. SDValue Index = MSC->getIndex();
  8843. SDValue Scale = MSC->getScale();
  8844. SDValue StoreVal = MSC->getValue();
  8845. SDValue BasePtr = MSC->getBasePtr();
  8846. SDLoc DL(N);
  8847. // Zap scatters with a zero mask.
  8848. if (ISD::isConstantSplatVectorAllZeros(Mask.getNode()))
  8849. return Chain;
  8850. if (refineUniformBase(BasePtr, Index, DAG)) {
  8851. SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale};
  8852. return DAG.getMaskedScatter(
  8853. DAG.getVTList(MVT::Other), MSC->getMemoryVT(), DL, Ops,
  8854. MSC->getMemOperand(), MSC->getIndexType(), MSC->isTruncatingStore());
  8855. }
  8856. if (refineIndexType(MSC, Index, MSC->isIndexScaled(), DAG)) {
  8857. SDValue Ops[] = {Chain, StoreVal, Mask, BasePtr, Index, Scale};
  8858. return DAG.getMaskedScatter(
  8859. DAG.getVTList(MVT::Other), MSC->getMemoryVT(), DL, Ops,
  8860. MSC->getMemOperand(), MSC->getIndexType(), MSC->isTruncatingStore());
  8861. }
  8862. return SDValue();
  8863. }
  8864. SDValue DAGCombiner::visitMSTORE(SDNode *N) {
  8865. MaskedStoreSDNode *MST = cast<MaskedStoreSDNode>(N);
  8866. SDValue Mask = MST->getMask();
  8867. SDValue Chain = MST->getChain();
  8868. SDValue Value = MST->getValue();
  8869. SDValue Ptr = MST->getBasePtr();
  8870. SDLoc DL(N);
  8871. // Zap masked stores with a zero mask.
  8872. if (ISD::isConstantSplatVectorAllZeros(Mask.getNode()))
  8873. return Chain;
  8874. // If this is a masked load with an all ones mask, we can use a unmasked load.
  8875. // FIXME: Can we do this for indexed, compressing, or truncating stores?
  8876. if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && MST->isUnindexed() &&
  8877. !MST->isCompressingStore() && !MST->isTruncatingStore())
  8878. return DAG.getStore(MST->getChain(), SDLoc(N), MST->getValue(),
  8879. MST->getBasePtr(), MST->getPointerInfo(),
  8880. MST->getOriginalAlign(), MachineMemOperand::MOStore,
  8881. MST->getAAInfo());
  8882. // Try transforming N to an indexed store.
  8883. if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
  8884. return SDValue(N, 0);
  8885. if (MST->isTruncatingStore() && MST->isUnindexed() &&
  8886. Value.getValueType().isInteger() &&
  8887. (!isa<ConstantSDNode>(Value) ||
  8888. !cast<ConstantSDNode>(Value)->isOpaque())) {
  8889. APInt TruncDemandedBits =
  8890. APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
  8891. MST->getMemoryVT().getScalarSizeInBits());
  8892. // See if we can simplify the operation with
  8893. // SimplifyDemandedBits, which only works if the value has a single use.
  8894. if (SimplifyDemandedBits(Value, TruncDemandedBits)) {
  8895. // Re-visit the store if anything changed and the store hasn't been merged
  8896. // with another node (N is deleted) SimplifyDemandedBits will add Value's
  8897. // node back to the worklist if necessary, but we also need to re-visit
  8898. // the Store node itself.
  8899. if (N->getOpcode() != ISD::DELETED_NODE)
  8900. AddToWorklist(N);
  8901. return SDValue(N, 0);
  8902. }
  8903. }
  8904. // If this is a TRUNC followed by a masked store, fold this into a masked
  8905. // truncating store. We can do this even if this is already a masked
  8906. // truncstore.
  8907. if ((Value.getOpcode() == ISD::TRUNCATE) && Value.getNode()->hasOneUse() &&
  8908. MST->isUnindexed() &&
  8909. TLI.canCombineTruncStore(Value.getOperand(0).getValueType(),
  8910. MST->getMemoryVT(), LegalOperations)) {
  8911. auto Mask = TLI.promoteTargetBoolean(DAG, MST->getMask(),
  8912. Value.getOperand(0).getValueType());
  8913. return DAG.getMaskedStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
  8914. MST->getOffset(), Mask, MST->getMemoryVT(),
  8915. MST->getMemOperand(), MST->getAddressingMode(),
  8916. /*IsTruncating=*/true);
  8917. }
  8918. return SDValue();
  8919. }
  8920. SDValue DAGCombiner::visitMGATHER(SDNode *N) {
  8921. MaskedGatherSDNode *MGT = cast<MaskedGatherSDNode>(N);
  8922. SDValue Mask = MGT->getMask();
  8923. SDValue Chain = MGT->getChain();
  8924. SDValue Index = MGT->getIndex();
  8925. SDValue Scale = MGT->getScale();
  8926. SDValue PassThru = MGT->getPassThru();
  8927. SDValue BasePtr = MGT->getBasePtr();
  8928. SDLoc DL(N);
  8929. // Zap gathers with a zero mask.
  8930. if (ISD::isConstantSplatVectorAllZeros(Mask.getNode()))
  8931. return CombineTo(N, PassThru, MGT->getChain());
  8932. if (refineUniformBase(BasePtr, Index, DAG)) {
  8933. SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
  8934. return DAG.getMaskedGather(DAG.getVTList(N->getValueType(0), MVT::Other),
  8935. MGT->getMemoryVT(), DL, Ops,
  8936. MGT->getMemOperand(), MGT->getIndexType(),
  8937. MGT->getExtensionType());
  8938. }
  8939. if (refineIndexType(MGT, Index, MGT->isIndexScaled(), DAG)) {
  8940. SDValue Ops[] = {Chain, PassThru, Mask, BasePtr, Index, Scale};
  8941. return DAG.getMaskedGather(DAG.getVTList(N->getValueType(0), MVT::Other),
  8942. MGT->getMemoryVT(), DL, Ops,
  8943. MGT->getMemOperand(), MGT->getIndexType(),
  8944. MGT->getExtensionType());
  8945. }
  8946. return SDValue();
  8947. }
  8948. SDValue DAGCombiner::visitMLOAD(SDNode *N) {
  8949. MaskedLoadSDNode *MLD = cast<MaskedLoadSDNode>(N);
  8950. SDValue Mask = MLD->getMask();
  8951. SDLoc DL(N);
  8952. // Zap masked loads with a zero mask.
  8953. if (ISD::isConstantSplatVectorAllZeros(Mask.getNode()))
  8954. return CombineTo(N, MLD->getPassThru(), MLD->getChain());
  8955. // If this is a masked load with an all ones mask, we can use a unmasked load.
  8956. // FIXME: Can we do this for indexed, expanding, or extending loads?
  8957. if (ISD::isConstantSplatVectorAllOnes(Mask.getNode()) && MLD->isUnindexed() &&
  8958. !MLD->isExpandingLoad() && MLD->getExtensionType() == ISD::NON_EXTLOAD) {
  8959. SDValue NewLd = DAG.getLoad(
  8960. N->getValueType(0), SDLoc(N), MLD->getChain(), MLD->getBasePtr(),
  8961. MLD->getPointerInfo(), MLD->getOriginalAlign(),
  8962. MachineMemOperand::MOLoad, MLD->getAAInfo(), MLD->getRanges());
  8963. return CombineTo(N, NewLd, NewLd.getValue(1));
  8964. }
  8965. // Try transforming N to an indexed load.
  8966. if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
  8967. return SDValue(N, 0);
  8968. return SDValue();
  8969. }
  8970. /// A vector select of 2 constant vectors can be simplified to math/logic to
  8971. /// avoid a variable select instruction and possibly avoid constant loads.
  8972. SDValue DAGCombiner::foldVSelectOfConstants(SDNode *N) {
  8973. SDValue Cond = N->getOperand(0);
  8974. SDValue N1 = N->getOperand(1);
  8975. SDValue N2 = N->getOperand(2);
  8976. EVT VT = N->getValueType(0);
  8977. if (!Cond.hasOneUse() || Cond.getScalarValueSizeInBits() != 1 ||
  8978. !TLI.convertSelectOfConstantsToMath(VT) ||
  8979. !ISD::isBuildVectorOfConstantSDNodes(N1.getNode()) ||
  8980. !ISD::isBuildVectorOfConstantSDNodes(N2.getNode()))
  8981. return SDValue();
  8982. // Check if we can use the condition value to increment/decrement a single
  8983. // constant value. This simplifies a select to an add and removes a constant
  8984. // load/materialization from the general case.
  8985. bool AllAddOne = true;
  8986. bool AllSubOne = true;
  8987. unsigned Elts = VT.getVectorNumElements();
  8988. for (unsigned i = 0; i != Elts; ++i) {
  8989. SDValue N1Elt = N1.getOperand(i);
  8990. SDValue N2Elt = N2.getOperand(i);
  8991. if (N1Elt.isUndef() || N2Elt.isUndef())
  8992. continue;
  8993. if (N1Elt.getValueType() != N2Elt.getValueType())
  8994. continue;
  8995. const APInt &C1 = cast<ConstantSDNode>(N1Elt)->getAPIntValue();
  8996. const APInt &C2 = cast<ConstantSDNode>(N2Elt)->getAPIntValue();
  8997. if (C1 != C2 + 1)
  8998. AllAddOne = false;
  8999. if (C1 != C2 - 1)
  9000. AllSubOne = false;
  9001. }
  9002. // Further simplifications for the extra-special cases where the constants are
  9003. // all 0 or all -1 should be implemented as folds of these patterns.
  9004. SDLoc DL(N);
  9005. if (AllAddOne || AllSubOne) {
  9006. // vselect <N x i1> Cond, C+1, C --> add (zext Cond), C
  9007. // vselect <N x i1> Cond, C-1, C --> add (sext Cond), C
  9008. auto ExtendOpcode = AllAddOne ? ISD::ZERO_EXTEND : ISD::SIGN_EXTEND;
  9009. SDValue ExtendedCond = DAG.getNode(ExtendOpcode, DL, VT, Cond);
  9010. return DAG.getNode(ISD::ADD, DL, VT, ExtendedCond, N2);
  9011. }
  9012. // select Cond, Pow2C, 0 --> (zext Cond) << log2(Pow2C)
  9013. APInt Pow2C;
  9014. if (ISD::isConstantSplatVector(N1.getNode(), Pow2C) && Pow2C.isPowerOf2() &&
  9015. isNullOrNullSplat(N2)) {
  9016. SDValue ZextCond = DAG.getZExtOrTrunc(Cond, DL, VT);
  9017. SDValue ShAmtC = DAG.getConstant(Pow2C.exactLogBase2(), DL, VT);
  9018. return DAG.getNode(ISD::SHL, DL, VT, ZextCond, ShAmtC);
  9019. }
  9020. if (SDValue V = foldSelectOfConstantsUsingSra(N, DAG))
  9021. return V;
  9022. // The general case for select-of-constants:
  9023. // vselect <N x i1> Cond, C1, C2 --> xor (and (sext Cond), (C1^C2)), C2
  9024. // ...but that only makes sense if a vselect is slower than 2 logic ops, so
  9025. // leave that to a machine-specific pass.
  9026. return SDValue();
  9027. }
  9028. SDValue DAGCombiner::visitVSELECT(SDNode *N) {
  9029. SDValue N0 = N->getOperand(0);
  9030. SDValue N1 = N->getOperand(1);
  9031. SDValue N2 = N->getOperand(2);
  9032. EVT VT = N->getValueType(0);
  9033. SDLoc DL(N);
  9034. if (SDValue V = DAG.simplifySelect(N0, N1, N2))
  9035. return V;
  9036. if (SDValue V = foldBoolSelectToLogic(N, DAG))
  9037. return V;
  9038. // vselect (not Cond), N1, N2 -> vselect Cond, N2, N1
  9039. if (SDValue F = extractBooleanFlip(N0, DAG, TLI, false))
  9040. return DAG.getSelect(DL, VT, F, N2, N1);
  9041. // Canonicalize integer abs.
  9042. // vselect (setg[te] X, 0), X, -X ->
  9043. // vselect (setgt X, -1), X, -X ->
  9044. // vselect (setl[te] X, 0), -X, X ->
  9045. // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
  9046. if (N0.getOpcode() == ISD::SETCC) {
  9047. SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
  9048. ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
  9049. bool isAbs = false;
  9050. bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
  9051. if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
  9052. (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
  9053. N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
  9054. isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
  9055. else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
  9056. N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
  9057. isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
  9058. if (isAbs) {
  9059. if (TLI.isOperationLegalOrCustom(ISD::ABS, VT))
  9060. return DAG.getNode(ISD::ABS, DL, VT, LHS);
  9061. SDValue Shift = DAG.getNode(ISD::SRA, DL, VT, LHS,
  9062. DAG.getConstant(VT.getScalarSizeInBits() - 1,
  9063. DL, getShiftAmountTy(VT)));
  9064. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
  9065. AddToWorklist(Shift.getNode());
  9066. AddToWorklist(Add.getNode());
  9067. return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
  9068. }
  9069. // vselect x, y (fcmp lt x, y) -> fminnum x, y
  9070. // vselect x, y (fcmp gt x, y) -> fmaxnum x, y
  9071. //
  9072. // This is OK if we don't care about what happens if either operand is a
  9073. // NaN.
  9074. //
  9075. if (N0.hasOneUse() && isLegalToCombineMinNumMaxNum(DAG, LHS, RHS, TLI)) {
  9076. if (SDValue FMinMax =
  9077. combineMinNumMaxNum(DL, VT, LHS, RHS, N1, N2, CC, TLI, DAG))
  9078. return FMinMax;
  9079. }
  9080. if (SDValue S = PerformMinMaxFpToSatCombine(LHS, RHS, N1, N2, CC, DAG))
  9081. return S;
  9082. if (SDValue S = PerformUMinFpToSatCombine(LHS, RHS, N1, N2, CC, DAG))
  9083. return S;
  9084. // If this select has a condition (setcc) with narrower operands than the
  9085. // select, try to widen the compare to match the select width.
  9086. // TODO: This should be extended to handle any constant.
  9087. // TODO: This could be extended to handle non-loading patterns, but that
  9088. // requires thorough testing to avoid regressions.
  9089. if (isNullOrNullSplat(RHS)) {
  9090. EVT NarrowVT = LHS.getValueType();
  9091. EVT WideVT = N1.getValueType().changeVectorElementTypeToInteger();
  9092. EVT SetCCVT = getSetCCResultType(LHS.getValueType());
  9093. unsigned SetCCWidth = SetCCVT.getScalarSizeInBits();
  9094. unsigned WideWidth = WideVT.getScalarSizeInBits();
  9095. bool IsSigned = isSignedIntSetCC(CC);
  9096. auto LoadExtOpcode = IsSigned ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
  9097. if (LHS.getOpcode() == ISD::LOAD && LHS.hasOneUse() &&
  9098. SetCCWidth != 1 && SetCCWidth < WideWidth &&
  9099. TLI.isLoadExtLegalOrCustom(LoadExtOpcode, WideVT, NarrowVT) &&
  9100. TLI.isOperationLegalOrCustom(ISD::SETCC, WideVT)) {
  9101. // Both compare operands can be widened for free. The LHS can use an
  9102. // extended load, and the RHS is a constant:
  9103. // vselect (ext (setcc load(X), C)), N1, N2 -->
  9104. // vselect (setcc extload(X), C'), N1, N2
  9105. auto ExtOpcode = IsSigned ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  9106. SDValue WideLHS = DAG.getNode(ExtOpcode, DL, WideVT, LHS);
  9107. SDValue WideRHS = DAG.getNode(ExtOpcode, DL, WideVT, RHS);
  9108. EVT WideSetCCVT = getSetCCResultType(WideVT);
  9109. SDValue WideSetCC = DAG.getSetCC(DL, WideSetCCVT, WideLHS, WideRHS, CC);
  9110. return DAG.getSelect(DL, N1.getValueType(), WideSetCC, N1, N2);
  9111. }
  9112. }
  9113. // Match VSELECTs into add with unsigned saturation.
  9114. if (hasOperation(ISD::UADDSAT, VT)) {
  9115. // Check if one of the arms of the VSELECT is vector with all bits set.
  9116. // If it's on the left side invert the predicate to simplify logic below.
  9117. SDValue Other;
  9118. ISD::CondCode SatCC = CC;
  9119. if (ISD::isConstantSplatVectorAllOnes(N1.getNode())) {
  9120. Other = N2;
  9121. SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType());
  9122. } else if (ISD::isConstantSplatVectorAllOnes(N2.getNode())) {
  9123. Other = N1;
  9124. }
  9125. if (Other && Other.getOpcode() == ISD::ADD) {
  9126. SDValue CondLHS = LHS, CondRHS = RHS;
  9127. SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
  9128. // Canonicalize condition operands.
  9129. if (SatCC == ISD::SETUGE) {
  9130. std::swap(CondLHS, CondRHS);
  9131. SatCC = ISD::SETULE;
  9132. }
  9133. // We can test against either of the addition operands.
  9134. // x <= x+y ? x+y : ~0 --> uaddsat x, y
  9135. // x+y >= x ? x+y : ~0 --> uaddsat x, y
  9136. if (SatCC == ISD::SETULE && Other == CondRHS &&
  9137. (OpLHS == CondLHS || OpRHS == CondLHS))
  9138. return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
  9139. if (OpRHS.getOpcode() == CondRHS.getOpcode() &&
  9140. (OpRHS.getOpcode() == ISD::BUILD_VECTOR ||
  9141. OpRHS.getOpcode() == ISD::SPLAT_VECTOR) &&
  9142. CondLHS == OpLHS) {
  9143. // If the RHS is a constant we have to reverse the const
  9144. // canonicalization.
  9145. // x >= ~C ? x+C : ~0 --> uaddsat x, C
  9146. auto MatchUADDSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
  9147. return Cond->getAPIntValue() == ~Op->getAPIntValue();
  9148. };
  9149. if (SatCC == ISD::SETULE &&
  9150. ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUADDSAT))
  9151. return DAG.getNode(ISD::UADDSAT, DL, VT, OpLHS, OpRHS);
  9152. }
  9153. }
  9154. }
  9155. // Match VSELECTs into sub with unsigned saturation.
  9156. if (hasOperation(ISD::USUBSAT, VT)) {
  9157. // Check if one of the arms of the VSELECT is a zero vector. If it's on
  9158. // the left side invert the predicate to simplify logic below.
  9159. SDValue Other;
  9160. ISD::CondCode SatCC = CC;
  9161. if (ISD::isConstantSplatVectorAllZeros(N1.getNode())) {
  9162. Other = N2;
  9163. SatCC = ISD::getSetCCInverse(SatCC, VT.getScalarType());
  9164. } else if (ISD::isConstantSplatVectorAllZeros(N2.getNode())) {
  9165. Other = N1;
  9166. }
  9167. if (Other && Other.getNumOperands() == 2) {
  9168. SDValue CondRHS = RHS;
  9169. SDValue OpLHS = Other.getOperand(0), OpRHS = Other.getOperand(1);
  9170. if (Other.getOpcode() == ISD::SUB &&
  9171. LHS.getOpcode() == ISD::ZERO_EXTEND && LHS.getOperand(0) == OpLHS &&
  9172. OpRHS.getOpcode() == ISD::TRUNCATE && OpRHS.getOperand(0) == RHS) {
  9173. // Look for a general sub with unsigned saturation first.
  9174. // zext(x) >= y ? x - trunc(y) : 0
  9175. // --> usubsat(x,trunc(umin(y,SatLimit)))
  9176. // zext(x) > y ? x - trunc(y) : 0
  9177. // --> usubsat(x,trunc(umin(y,SatLimit)))
  9178. if (SatCC == ISD::SETUGE || SatCC == ISD::SETUGT)
  9179. return getTruncatedUSUBSAT(VT, LHS.getValueType(), LHS, RHS, DAG,
  9180. DL);
  9181. }
  9182. if (OpLHS == LHS) {
  9183. // Look for a general sub with unsigned saturation first.
  9184. // x >= y ? x-y : 0 --> usubsat x, y
  9185. // x > y ? x-y : 0 --> usubsat x, y
  9186. if ((SatCC == ISD::SETUGE || SatCC == ISD::SETUGT) &&
  9187. Other.getOpcode() == ISD::SUB && OpRHS == CondRHS)
  9188. return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
  9189. if (OpRHS.getOpcode() == ISD::BUILD_VECTOR ||
  9190. OpRHS.getOpcode() == ISD::SPLAT_VECTOR) {
  9191. if (CondRHS.getOpcode() == ISD::BUILD_VECTOR ||
  9192. CondRHS.getOpcode() == ISD::SPLAT_VECTOR) {
  9193. // If the RHS is a constant we have to reverse the const
  9194. // canonicalization.
  9195. // x > C-1 ? x+-C : 0 --> usubsat x, C
  9196. auto MatchUSUBSAT = [](ConstantSDNode *Op, ConstantSDNode *Cond) {
  9197. return (!Op && !Cond) ||
  9198. (Op && Cond &&
  9199. Cond->getAPIntValue() == (-Op->getAPIntValue() - 1));
  9200. };
  9201. if (SatCC == ISD::SETUGT && Other.getOpcode() == ISD::ADD &&
  9202. ISD::matchBinaryPredicate(OpRHS, CondRHS, MatchUSUBSAT,
  9203. /*AllowUndefs*/ true)) {
  9204. OpRHS = DAG.getNode(ISD::SUB, DL, VT,
  9205. DAG.getConstant(0, DL, VT), OpRHS);
  9206. return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
  9207. }
  9208. // Another special case: If C was a sign bit, the sub has been
  9209. // canonicalized into a xor.
  9210. // FIXME: Would it be better to use computeKnownBits to determine
  9211. // whether it's safe to decanonicalize the xor?
  9212. // x s< 0 ? x^C : 0 --> usubsat x, C
  9213. APInt SplatValue;
  9214. if (SatCC == ISD::SETLT && Other.getOpcode() == ISD::XOR &&
  9215. ISD::isConstantSplatVector(OpRHS.getNode(), SplatValue) &&
  9216. ISD::isConstantSplatVectorAllZeros(CondRHS.getNode()) &&
  9217. SplatValue.isSignMask()) {
  9218. // Note that we have to rebuild the RHS constant here to
  9219. // ensure we don't rely on particular values of undef lanes.
  9220. OpRHS = DAG.getConstant(SplatValue, DL, VT);
  9221. return DAG.getNode(ISD::USUBSAT, DL, VT, OpLHS, OpRHS);
  9222. }
  9223. }
  9224. }
  9225. }
  9226. }
  9227. }
  9228. }
  9229. if (SimplifySelectOps(N, N1, N2))
  9230. return SDValue(N, 0); // Don't revisit N.
  9231. // Fold (vselect all_ones, N1, N2) -> N1
  9232. if (ISD::isConstantSplatVectorAllOnes(N0.getNode()))
  9233. return N1;
  9234. // Fold (vselect all_zeros, N1, N2) -> N2
  9235. if (ISD::isConstantSplatVectorAllZeros(N0.getNode()))
  9236. return N2;
  9237. // The ConvertSelectToConcatVector function is assuming both the above
  9238. // checks for (vselect (build_vector all{ones,zeros) ...) have been made
  9239. // and addressed.
  9240. if (N1.getOpcode() == ISD::CONCAT_VECTORS &&
  9241. N2.getOpcode() == ISD::CONCAT_VECTORS &&
  9242. ISD::isBuildVectorOfConstantSDNodes(N0.getNode())) {
  9243. if (SDValue CV = ConvertSelectToConcatVector(N, DAG))
  9244. return CV;
  9245. }
  9246. if (SDValue V = foldVSelectOfConstants(N))
  9247. return V;
  9248. if (hasOperation(ISD::SRA, VT))
  9249. if (SDValue V = foldVSelectToSignBitSplatMask(N, DAG))
  9250. return V;
  9251. return SDValue();
  9252. }
  9253. SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
  9254. SDValue N0 = N->getOperand(0);
  9255. SDValue N1 = N->getOperand(1);
  9256. SDValue N2 = N->getOperand(2);
  9257. SDValue N3 = N->getOperand(3);
  9258. SDValue N4 = N->getOperand(4);
  9259. ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
  9260. // fold select_cc lhs, rhs, x, x, cc -> x
  9261. if (N2 == N3)
  9262. return N2;
  9263. // Determine if the condition we're dealing with is constant
  9264. if (SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()), N0, N1,
  9265. CC, SDLoc(N), false)) {
  9266. AddToWorklist(SCC.getNode());
  9267. if (ConstantSDNode *SCCC = dyn_cast<ConstantSDNode>(SCC.getNode())) {
  9268. if (!SCCC->isZero())
  9269. return N2; // cond always true -> true val
  9270. else
  9271. return N3; // cond always false -> false val
  9272. } else if (SCC->isUndef()) {
  9273. // When the condition is UNDEF, just return the first operand. This is
  9274. // coherent the DAG creation, no setcc node is created in this case
  9275. return N2;
  9276. } else if (SCC.getOpcode() == ISD::SETCC) {
  9277. // Fold to a simpler select_cc
  9278. SDValue SelectOp = DAG.getNode(
  9279. ISD::SELECT_CC, SDLoc(N), N2.getValueType(), SCC.getOperand(0),
  9280. SCC.getOperand(1), N2, N3, SCC.getOperand(2));
  9281. SelectOp->setFlags(SCC->getFlags());
  9282. return SelectOp;
  9283. }
  9284. }
  9285. // If we can fold this based on the true/false value, do so.
  9286. if (SimplifySelectOps(N, N2, N3))
  9287. return SDValue(N, 0); // Don't revisit N.
  9288. // fold select_cc into other things, such as min/max/abs
  9289. return SimplifySelectCC(SDLoc(N), N0, N1, N2, N3, CC);
  9290. }
  9291. SDValue DAGCombiner::visitSETCC(SDNode *N) {
  9292. // setcc is very commonly used as an argument to brcond. This pattern
  9293. // also lend itself to numerous combines and, as a result, it is desired
  9294. // we keep the argument to a brcond as a setcc as much as possible.
  9295. bool PreferSetCC =
  9296. N->hasOneUse() && N->use_begin()->getOpcode() == ISD::BRCOND;
  9297. ISD::CondCode Cond = cast<CondCodeSDNode>(N->getOperand(2))->get();
  9298. EVT VT = N->getValueType(0);
  9299. // SETCC(FREEZE(X), CONST, Cond)
  9300. // =>
  9301. // FREEZE(SETCC(X, CONST, Cond))
  9302. // This is correct if FREEZE(X) has one use and SETCC(FREEZE(X), CONST, Cond)
  9303. // isn't equivalent to true or false.
  9304. // For example, SETCC(FREEZE(X), -128, SETULT) cannot be folded to
  9305. // FREEZE(SETCC(X, -128, SETULT)) because X can be poison.
  9306. //
  9307. // This transformation is beneficial because visitBRCOND can fold
  9308. // BRCOND(FREEZE(X)) to BRCOND(X).
  9309. // Conservatively optimize integer comparisons only.
  9310. if (PreferSetCC) {
  9311. // Do this only when SETCC is going to be used by BRCOND.
  9312. SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
  9313. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  9314. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  9315. bool Updated = false;
  9316. // Is 'X Cond C' always true or false?
  9317. auto IsAlwaysTrueOrFalse = [](ISD::CondCode Cond, ConstantSDNode *C) {
  9318. bool False = (Cond == ISD::SETULT && C->isZero()) ||
  9319. (Cond == ISD::SETLT && C->isMinSignedValue()) ||
  9320. (Cond == ISD::SETUGT && C->isAllOnes()) ||
  9321. (Cond == ISD::SETGT && C->isMaxSignedValue());
  9322. bool True = (Cond == ISD::SETULE && C->isAllOnes()) ||
  9323. (Cond == ISD::SETLE && C->isMaxSignedValue()) ||
  9324. (Cond == ISD::SETUGE && C->isZero()) ||
  9325. (Cond == ISD::SETGE && C->isMinSignedValue());
  9326. return True || False;
  9327. };
  9328. if (N0->getOpcode() == ISD::FREEZE && N0.hasOneUse() && N1C) {
  9329. if (!IsAlwaysTrueOrFalse(Cond, N1C)) {
  9330. N0 = N0->getOperand(0);
  9331. Updated = true;
  9332. }
  9333. }
  9334. if (N1->getOpcode() == ISD::FREEZE && N1.hasOneUse() && N0C) {
  9335. if (!IsAlwaysTrueOrFalse(ISD::getSetCCSwappedOperands(Cond),
  9336. N0C)) {
  9337. N1 = N1->getOperand(0);
  9338. Updated = true;
  9339. }
  9340. }
  9341. if (Updated)
  9342. return DAG.getFreeze(DAG.getSetCC(SDLoc(N), VT, N0, N1, Cond));
  9343. }
  9344. SDValue Combined = SimplifySetCC(VT, N->getOperand(0), N->getOperand(1), Cond,
  9345. SDLoc(N), !PreferSetCC);
  9346. if (!Combined)
  9347. return SDValue();
  9348. // If we prefer to have a setcc, and we don't, we'll try our best to
  9349. // recreate one using rebuildSetCC.
  9350. if (PreferSetCC && Combined.getOpcode() != ISD::SETCC) {
  9351. SDValue NewSetCC = rebuildSetCC(Combined);
  9352. // We don't have anything interesting to combine to.
  9353. if (NewSetCC.getNode() == N)
  9354. return SDValue();
  9355. if (NewSetCC)
  9356. return NewSetCC;
  9357. }
  9358. return Combined;
  9359. }
  9360. SDValue DAGCombiner::visitSETCCCARRY(SDNode *N) {
  9361. SDValue LHS = N->getOperand(0);
  9362. SDValue RHS = N->getOperand(1);
  9363. SDValue Carry = N->getOperand(2);
  9364. SDValue Cond = N->getOperand(3);
  9365. // If Carry is false, fold to a regular SETCC.
  9366. if (isNullConstant(Carry))
  9367. return DAG.getNode(ISD::SETCC, SDLoc(N), N->getVTList(), LHS, RHS, Cond);
  9368. return SDValue();
  9369. }
  9370. /// Check if N satisfies:
  9371. /// N is used once.
  9372. /// N is a Load.
  9373. /// The load is compatible with ExtOpcode. It means
  9374. /// If load has explicit zero/sign extension, ExpOpcode must have the same
  9375. /// extension.
  9376. /// Otherwise returns true.
  9377. static bool isCompatibleLoad(SDValue N, unsigned ExtOpcode) {
  9378. if (!N.hasOneUse())
  9379. return false;
  9380. if (!isa<LoadSDNode>(N))
  9381. return false;
  9382. LoadSDNode *Load = cast<LoadSDNode>(N);
  9383. ISD::LoadExtType LoadExt = Load->getExtensionType();
  9384. if (LoadExt == ISD::NON_EXTLOAD || LoadExt == ISD::EXTLOAD)
  9385. return true;
  9386. // Now LoadExt is either SEXTLOAD or ZEXTLOAD, ExtOpcode must have the same
  9387. // extension.
  9388. if ((LoadExt == ISD::SEXTLOAD && ExtOpcode != ISD::SIGN_EXTEND) ||
  9389. (LoadExt == ISD::ZEXTLOAD && ExtOpcode != ISD::ZERO_EXTEND))
  9390. return false;
  9391. return true;
  9392. }
  9393. /// Fold
  9394. /// (sext (select c, load x, load y)) -> (select c, sextload x, sextload y)
  9395. /// (zext (select c, load x, load y)) -> (select c, zextload x, zextload y)
  9396. /// (aext (select c, load x, load y)) -> (select c, extload x, extload y)
  9397. /// This function is called by the DAGCombiner when visiting sext/zext/aext
  9398. /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
  9399. static SDValue tryToFoldExtendSelectLoad(SDNode *N, const TargetLowering &TLI,
  9400. SelectionDAG &DAG) {
  9401. unsigned Opcode = N->getOpcode();
  9402. SDValue N0 = N->getOperand(0);
  9403. EVT VT = N->getValueType(0);
  9404. SDLoc DL(N);
  9405. assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
  9406. Opcode == ISD::ANY_EXTEND) &&
  9407. "Expected EXTEND dag node in input!");
  9408. if (!(N0->getOpcode() == ISD::SELECT || N0->getOpcode() == ISD::VSELECT) ||
  9409. !N0.hasOneUse())
  9410. return SDValue();
  9411. SDValue Op1 = N0->getOperand(1);
  9412. SDValue Op2 = N0->getOperand(2);
  9413. if (!isCompatibleLoad(Op1, Opcode) || !isCompatibleLoad(Op2, Opcode))
  9414. return SDValue();
  9415. auto ExtLoadOpcode = ISD::EXTLOAD;
  9416. if (Opcode == ISD::SIGN_EXTEND)
  9417. ExtLoadOpcode = ISD::SEXTLOAD;
  9418. else if (Opcode == ISD::ZERO_EXTEND)
  9419. ExtLoadOpcode = ISD::ZEXTLOAD;
  9420. LoadSDNode *Load1 = cast<LoadSDNode>(Op1);
  9421. LoadSDNode *Load2 = cast<LoadSDNode>(Op2);
  9422. if (!TLI.isLoadExtLegal(ExtLoadOpcode, VT, Load1->getMemoryVT()) ||
  9423. !TLI.isLoadExtLegal(ExtLoadOpcode, VT, Load2->getMemoryVT()))
  9424. return SDValue();
  9425. SDValue Ext1 = DAG.getNode(Opcode, DL, VT, Op1);
  9426. SDValue Ext2 = DAG.getNode(Opcode, DL, VT, Op2);
  9427. return DAG.getSelect(DL, VT, N0->getOperand(0), Ext1, Ext2);
  9428. }
  9429. /// Try to fold a sext/zext/aext dag node into a ConstantSDNode or
  9430. /// a build_vector of constants.
  9431. /// This function is called by the DAGCombiner when visiting sext/zext/aext
  9432. /// dag nodes (see for example method DAGCombiner::visitSIGN_EXTEND).
  9433. /// Vector extends are not folded if operations are legal; this is to
  9434. /// avoid introducing illegal build_vector dag nodes.
  9435. static SDValue tryToFoldExtendOfConstant(SDNode *N, const TargetLowering &TLI,
  9436. SelectionDAG &DAG, bool LegalTypes) {
  9437. unsigned Opcode = N->getOpcode();
  9438. SDValue N0 = N->getOperand(0);
  9439. EVT VT = N->getValueType(0);
  9440. SDLoc DL(N);
  9441. assert((Opcode == ISD::SIGN_EXTEND || Opcode == ISD::ZERO_EXTEND ||
  9442. Opcode == ISD::ANY_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG ||
  9443. Opcode == ISD::ZERO_EXTEND_VECTOR_INREG)
  9444. && "Expected EXTEND dag node in input!");
  9445. // fold (sext c1) -> c1
  9446. // fold (zext c1) -> c1
  9447. // fold (aext c1) -> c1
  9448. if (isa<ConstantSDNode>(N0))
  9449. return DAG.getNode(Opcode, DL, VT, N0);
  9450. // fold (sext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
  9451. // fold (zext (select cond, c1, c2)) -> (select cond, zext c1, zext c2)
  9452. // fold (aext (select cond, c1, c2)) -> (select cond, sext c1, sext c2)
  9453. if (N0->getOpcode() == ISD::SELECT) {
  9454. SDValue Op1 = N0->getOperand(1);
  9455. SDValue Op2 = N0->getOperand(2);
  9456. if (isa<ConstantSDNode>(Op1) && isa<ConstantSDNode>(Op2) &&
  9457. (Opcode != ISD::ZERO_EXTEND || !TLI.isZExtFree(N0.getValueType(), VT))) {
  9458. // For any_extend, choose sign extension of the constants to allow a
  9459. // possible further transform to sign_extend_inreg.i.e.
  9460. //
  9461. // t1: i8 = select t0, Constant:i8<-1>, Constant:i8<0>
  9462. // t2: i64 = any_extend t1
  9463. // -->
  9464. // t3: i64 = select t0, Constant:i64<-1>, Constant:i64<0>
  9465. // -->
  9466. // t4: i64 = sign_extend_inreg t3
  9467. unsigned FoldOpc = Opcode;
  9468. if (FoldOpc == ISD::ANY_EXTEND)
  9469. FoldOpc = ISD::SIGN_EXTEND;
  9470. return DAG.getSelect(DL, VT, N0->getOperand(0),
  9471. DAG.getNode(FoldOpc, DL, VT, Op1),
  9472. DAG.getNode(FoldOpc, DL, VT, Op2));
  9473. }
  9474. }
  9475. // fold (sext (build_vector AllConstants) -> (build_vector AllConstants)
  9476. // fold (zext (build_vector AllConstants) -> (build_vector AllConstants)
  9477. // fold (aext (build_vector AllConstants) -> (build_vector AllConstants)
  9478. EVT SVT = VT.getScalarType();
  9479. if (!(VT.isVector() && (!LegalTypes || TLI.isTypeLegal(SVT)) &&
  9480. ISD::isBuildVectorOfConstantSDNodes(N0.getNode())))
  9481. return SDValue();
  9482. // We can fold this node into a build_vector.
  9483. unsigned VTBits = SVT.getSizeInBits();
  9484. unsigned EVTBits = N0->getValueType(0).getScalarSizeInBits();
  9485. SmallVector<SDValue, 8> Elts;
  9486. unsigned NumElts = VT.getVectorNumElements();
  9487. // For zero-extensions, UNDEF elements still guarantee to have the upper
  9488. // bits set to zero.
  9489. bool IsZext =
  9490. Opcode == ISD::ZERO_EXTEND || Opcode == ISD::ZERO_EXTEND_VECTOR_INREG;
  9491. for (unsigned i = 0; i != NumElts; ++i) {
  9492. SDValue Op = N0.getOperand(i);
  9493. if (Op.isUndef()) {
  9494. Elts.push_back(IsZext ? DAG.getConstant(0, DL, SVT) : DAG.getUNDEF(SVT));
  9495. continue;
  9496. }
  9497. SDLoc DL(Op);
  9498. // Get the constant value and if needed trunc it to the size of the type.
  9499. // Nodes like build_vector might have constants wider than the scalar type.
  9500. APInt C = cast<ConstantSDNode>(Op)->getAPIntValue().zextOrTrunc(EVTBits);
  9501. if (Opcode == ISD::SIGN_EXTEND || Opcode == ISD::SIGN_EXTEND_VECTOR_INREG)
  9502. Elts.push_back(DAG.getConstant(C.sext(VTBits), DL, SVT));
  9503. else
  9504. Elts.push_back(DAG.getConstant(C.zext(VTBits), DL, SVT));
  9505. }
  9506. return DAG.getBuildVector(VT, DL, Elts);
  9507. }
  9508. // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
  9509. // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
  9510. // transformation. Returns true if extension are possible and the above
  9511. // mentioned transformation is profitable.
  9512. static bool ExtendUsesToFormExtLoad(EVT VT, SDNode *N, SDValue N0,
  9513. unsigned ExtOpc,
  9514. SmallVectorImpl<SDNode *> &ExtendNodes,
  9515. const TargetLowering &TLI) {
  9516. bool HasCopyToRegUses = false;
  9517. bool isTruncFree = TLI.isTruncateFree(VT, N0.getValueType());
  9518. for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
  9519. UE = N0.getNode()->use_end();
  9520. UI != UE; ++UI) {
  9521. SDNode *User = *UI;
  9522. if (User == N)
  9523. continue;
  9524. if (UI.getUse().getResNo() != N0.getResNo())
  9525. continue;
  9526. // FIXME: Only extend SETCC N, N and SETCC N, c for now.
  9527. if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
  9528. ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
  9529. if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
  9530. // Sign bits will be lost after a zext.
  9531. return false;
  9532. bool Add = false;
  9533. for (unsigned i = 0; i != 2; ++i) {
  9534. SDValue UseOp = User->getOperand(i);
  9535. if (UseOp == N0)
  9536. continue;
  9537. if (!isa<ConstantSDNode>(UseOp))
  9538. return false;
  9539. Add = true;
  9540. }
  9541. if (Add)
  9542. ExtendNodes.push_back(User);
  9543. continue;
  9544. }
  9545. // If truncates aren't free and there are users we can't
  9546. // extend, it isn't worthwhile.
  9547. if (!isTruncFree)
  9548. return false;
  9549. // Remember if this value is live-out.
  9550. if (User->getOpcode() == ISD::CopyToReg)
  9551. HasCopyToRegUses = true;
  9552. }
  9553. if (HasCopyToRegUses) {
  9554. bool BothLiveOut = false;
  9555. for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
  9556. UI != UE; ++UI) {
  9557. SDUse &Use = UI.getUse();
  9558. if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
  9559. BothLiveOut = true;
  9560. break;
  9561. }
  9562. }
  9563. if (BothLiveOut)
  9564. // Both unextended and extended values are live out. There had better be
  9565. // a good reason for the transformation.
  9566. return ExtendNodes.size();
  9567. }
  9568. return true;
  9569. }
  9570. void DAGCombiner::ExtendSetCCUses(const SmallVectorImpl<SDNode *> &SetCCs,
  9571. SDValue OrigLoad, SDValue ExtLoad,
  9572. ISD::NodeType ExtType) {
  9573. // Extend SetCC uses if necessary.
  9574. SDLoc DL(ExtLoad);
  9575. for (SDNode *SetCC : SetCCs) {
  9576. SmallVector<SDValue, 4> Ops;
  9577. for (unsigned j = 0; j != 2; ++j) {
  9578. SDValue SOp = SetCC->getOperand(j);
  9579. if (SOp == OrigLoad)
  9580. Ops.push_back(ExtLoad);
  9581. else
  9582. Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
  9583. }
  9584. Ops.push_back(SetCC->getOperand(2));
  9585. CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0), Ops));
  9586. }
  9587. }
  9588. // FIXME: Bring more similar combines here, common to sext/zext (maybe aext?).
  9589. SDValue DAGCombiner::CombineExtLoad(SDNode *N) {
  9590. SDValue N0 = N->getOperand(0);
  9591. EVT DstVT = N->getValueType(0);
  9592. EVT SrcVT = N0.getValueType();
  9593. assert((N->getOpcode() == ISD::SIGN_EXTEND ||
  9594. N->getOpcode() == ISD::ZERO_EXTEND) &&
  9595. "Unexpected node type (not an extend)!");
  9596. // fold (sext (load x)) to multiple smaller sextloads; same for zext.
  9597. // For example, on a target with legal v4i32, but illegal v8i32, turn:
  9598. // (v8i32 (sext (v8i16 (load x))))
  9599. // into:
  9600. // (v8i32 (concat_vectors (v4i32 (sextload x)),
  9601. // (v4i32 (sextload (x + 16)))))
  9602. // Where uses of the original load, i.e.:
  9603. // (v8i16 (load x))
  9604. // are replaced with:
  9605. // (v8i16 (truncate
  9606. // (v8i32 (concat_vectors (v4i32 (sextload x)),
  9607. // (v4i32 (sextload (x + 16)))))))
  9608. //
  9609. // This combine is only applicable to illegal, but splittable, vectors.
  9610. // All legal types, and illegal non-vector types, are handled elsewhere.
  9611. // This combine is controlled by TargetLowering::isVectorLoadExtDesirable.
  9612. //
  9613. if (N0->getOpcode() != ISD::LOAD)
  9614. return SDValue();
  9615. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  9616. if (!ISD::isNON_EXTLoad(LN0) || !ISD::isUNINDEXEDLoad(LN0) ||
  9617. !N0.hasOneUse() || !LN0->isSimple() ||
  9618. !DstVT.isVector() || !DstVT.isPow2VectorType() ||
  9619. !TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
  9620. return SDValue();
  9621. SmallVector<SDNode *, 4> SetCCs;
  9622. if (!ExtendUsesToFormExtLoad(DstVT, N, N0, N->getOpcode(), SetCCs, TLI))
  9623. return SDValue();
  9624. ISD::LoadExtType ExtType =
  9625. N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
  9626. // Try to split the vector types to get down to legal types.
  9627. EVT SplitSrcVT = SrcVT;
  9628. EVT SplitDstVT = DstVT;
  9629. while (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT) &&
  9630. SplitSrcVT.getVectorNumElements() > 1) {
  9631. SplitDstVT = DAG.GetSplitDestVTs(SplitDstVT).first;
  9632. SplitSrcVT = DAG.GetSplitDestVTs(SplitSrcVT).first;
  9633. }
  9634. if (!TLI.isLoadExtLegalOrCustom(ExtType, SplitDstVT, SplitSrcVT))
  9635. return SDValue();
  9636. assert(!DstVT.isScalableVector() && "Unexpected scalable vector type");
  9637. SDLoc DL(N);
  9638. const unsigned NumSplits =
  9639. DstVT.getVectorNumElements() / SplitDstVT.getVectorNumElements();
  9640. const unsigned Stride = SplitSrcVT.getStoreSize();
  9641. SmallVector<SDValue, 4> Loads;
  9642. SmallVector<SDValue, 4> Chains;
  9643. SDValue BasePtr = LN0->getBasePtr();
  9644. for (unsigned Idx = 0; Idx < NumSplits; Idx++) {
  9645. const unsigned Offset = Idx * Stride;
  9646. const Align Align = commonAlignment(LN0->getAlign(), Offset);
  9647. SDValue SplitLoad = DAG.getExtLoad(
  9648. ExtType, SDLoc(LN0), SplitDstVT, LN0->getChain(), BasePtr,
  9649. LN0->getPointerInfo().getWithOffset(Offset), SplitSrcVT, Align,
  9650. LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
  9651. BasePtr = DAG.getMemBasePlusOffset(BasePtr, TypeSize::Fixed(Stride), DL);
  9652. Loads.push_back(SplitLoad.getValue(0));
  9653. Chains.push_back(SplitLoad.getValue(1));
  9654. }
  9655. SDValue NewChain = DAG.getNode(ISD::TokenFactor, DL, MVT::Other, Chains);
  9656. SDValue NewValue = DAG.getNode(ISD::CONCAT_VECTORS, DL, DstVT, Loads);
  9657. // Simplify TF.
  9658. AddToWorklist(NewChain.getNode());
  9659. CombineTo(N, NewValue);
  9660. // Replace uses of the original load (before extension)
  9661. // with a truncate of the concatenated sextloaded vectors.
  9662. SDValue Trunc =
  9663. DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), NewValue);
  9664. ExtendSetCCUses(SetCCs, N0, NewValue, (ISD::NodeType)N->getOpcode());
  9665. CombineTo(N0.getNode(), Trunc, NewChain);
  9666. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  9667. }
  9668. // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
  9669. // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
  9670. SDValue DAGCombiner::CombineZExtLogicopShiftLoad(SDNode *N) {
  9671. assert(N->getOpcode() == ISD::ZERO_EXTEND);
  9672. EVT VT = N->getValueType(0);
  9673. EVT OrigVT = N->getOperand(0).getValueType();
  9674. if (TLI.isZExtFree(OrigVT, VT))
  9675. return SDValue();
  9676. // and/or/xor
  9677. SDValue N0 = N->getOperand(0);
  9678. if (!(N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
  9679. N0.getOpcode() == ISD::XOR) ||
  9680. N0.getOperand(1).getOpcode() != ISD::Constant ||
  9681. (LegalOperations && !TLI.isOperationLegal(N0.getOpcode(), VT)))
  9682. return SDValue();
  9683. // shl/shr
  9684. SDValue N1 = N0->getOperand(0);
  9685. if (!(N1.getOpcode() == ISD::SHL || N1.getOpcode() == ISD::SRL) ||
  9686. N1.getOperand(1).getOpcode() != ISD::Constant ||
  9687. (LegalOperations && !TLI.isOperationLegal(N1.getOpcode(), VT)))
  9688. return SDValue();
  9689. // load
  9690. if (!isa<LoadSDNode>(N1.getOperand(0)))
  9691. return SDValue();
  9692. LoadSDNode *Load = cast<LoadSDNode>(N1.getOperand(0));
  9693. EVT MemVT = Load->getMemoryVT();
  9694. if (!TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) ||
  9695. Load->getExtensionType() == ISD::SEXTLOAD || Load->isIndexed())
  9696. return SDValue();
  9697. // If the shift op is SHL, the logic op must be AND, otherwise the result
  9698. // will be wrong.
  9699. if (N1.getOpcode() == ISD::SHL && N0.getOpcode() != ISD::AND)
  9700. return SDValue();
  9701. if (!N0.hasOneUse() || !N1.hasOneUse())
  9702. return SDValue();
  9703. SmallVector<SDNode*, 4> SetCCs;
  9704. if (!ExtendUsesToFormExtLoad(VT, N1.getNode(), N1.getOperand(0),
  9705. ISD::ZERO_EXTEND, SetCCs, TLI))
  9706. return SDValue();
  9707. // Actually do the transformation.
  9708. SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(Load), VT,
  9709. Load->getChain(), Load->getBasePtr(),
  9710. Load->getMemoryVT(), Load->getMemOperand());
  9711. SDLoc DL1(N1);
  9712. SDValue Shift = DAG.getNode(N1.getOpcode(), DL1, VT, ExtLoad,
  9713. N1.getOperand(1));
  9714. APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
  9715. SDLoc DL0(N0);
  9716. SDValue And = DAG.getNode(N0.getOpcode(), DL0, VT, Shift,
  9717. DAG.getConstant(Mask, DL0, VT));
  9718. ExtendSetCCUses(SetCCs, N1.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
  9719. CombineTo(N, And);
  9720. if (SDValue(Load, 0).hasOneUse()) {
  9721. DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), ExtLoad.getValue(1));
  9722. } else {
  9723. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(Load),
  9724. Load->getValueType(0), ExtLoad);
  9725. CombineTo(Load, Trunc, ExtLoad.getValue(1));
  9726. }
  9727. // N0 is dead at this point.
  9728. recursivelyDeleteUnusedNodes(N0.getNode());
  9729. return SDValue(N,0); // Return N so it doesn't get rechecked!
  9730. }
  9731. /// If we're narrowing or widening the result of a vector select and the final
  9732. /// size is the same size as a setcc (compare) feeding the select, then try to
  9733. /// apply the cast operation to the select's operands because matching vector
  9734. /// sizes for a select condition and other operands should be more efficient.
  9735. SDValue DAGCombiner::matchVSelectOpSizesWithSetCC(SDNode *Cast) {
  9736. unsigned CastOpcode = Cast->getOpcode();
  9737. assert((CastOpcode == ISD::SIGN_EXTEND || CastOpcode == ISD::ZERO_EXTEND ||
  9738. CastOpcode == ISD::TRUNCATE || CastOpcode == ISD::FP_EXTEND ||
  9739. CastOpcode == ISD::FP_ROUND) &&
  9740. "Unexpected opcode for vector select narrowing/widening");
  9741. // We only do this transform before legal ops because the pattern may be
  9742. // obfuscated by target-specific operations after legalization. Do not create
  9743. // an illegal select op, however, because that may be difficult to lower.
  9744. EVT VT = Cast->getValueType(0);
  9745. if (LegalOperations || !TLI.isOperationLegalOrCustom(ISD::VSELECT, VT))
  9746. return SDValue();
  9747. SDValue VSel = Cast->getOperand(0);
  9748. if (VSel.getOpcode() != ISD::VSELECT || !VSel.hasOneUse() ||
  9749. VSel.getOperand(0).getOpcode() != ISD::SETCC)
  9750. return SDValue();
  9751. // Does the setcc have the same vector size as the casted select?
  9752. SDValue SetCC = VSel.getOperand(0);
  9753. EVT SetCCVT = getSetCCResultType(SetCC.getOperand(0).getValueType());
  9754. if (SetCCVT.getSizeInBits() != VT.getSizeInBits())
  9755. return SDValue();
  9756. // cast (vsel (setcc X), A, B) --> vsel (setcc X), (cast A), (cast B)
  9757. SDValue A = VSel.getOperand(1);
  9758. SDValue B = VSel.getOperand(2);
  9759. SDValue CastA, CastB;
  9760. SDLoc DL(Cast);
  9761. if (CastOpcode == ISD::FP_ROUND) {
  9762. // FP_ROUND (fptrunc) has an extra flag operand to pass along.
  9763. CastA = DAG.getNode(CastOpcode, DL, VT, A, Cast->getOperand(1));
  9764. CastB = DAG.getNode(CastOpcode, DL, VT, B, Cast->getOperand(1));
  9765. } else {
  9766. CastA = DAG.getNode(CastOpcode, DL, VT, A);
  9767. CastB = DAG.getNode(CastOpcode, DL, VT, B);
  9768. }
  9769. return DAG.getNode(ISD::VSELECT, DL, VT, SetCC, CastA, CastB);
  9770. }
  9771. // fold ([s|z]ext ([s|z]extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
  9772. // fold ([s|z]ext ( extload x)) -> ([s|z]ext (truncate ([s|z]extload x)))
  9773. static SDValue tryToFoldExtOfExtload(SelectionDAG &DAG, DAGCombiner &Combiner,
  9774. const TargetLowering &TLI, EVT VT,
  9775. bool LegalOperations, SDNode *N,
  9776. SDValue N0, ISD::LoadExtType ExtLoadType) {
  9777. SDNode *N0Node = N0.getNode();
  9778. bool isAExtLoad = (ExtLoadType == ISD::SEXTLOAD) ? ISD::isSEXTLoad(N0Node)
  9779. : ISD::isZEXTLoad(N0Node);
  9780. if ((!isAExtLoad && !ISD::isEXTLoad(N0Node)) ||
  9781. !ISD::isUNINDEXEDLoad(N0Node) || !N0.hasOneUse())
  9782. return SDValue();
  9783. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  9784. EVT MemVT = LN0->getMemoryVT();
  9785. if ((LegalOperations || !LN0->isSimple() ||
  9786. VT.isVector()) &&
  9787. !TLI.isLoadExtLegal(ExtLoadType, VT, MemVT))
  9788. return SDValue();
  9789. SDValue ExtLoad =
  9790. DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(),
  9791. LN0->getBasePtr(), MemVT, LN0->getMemOperand());
  9792. Combiner.CombineTo(N, ExtLoad);
  9793. DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
  9794. if (LN0->use_empty())
  9795. Combiner.recursivelyDeleteUnusedNodes(LN0);
  9796. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  9797. }
  9798. // fold ([s|z]ext (load x)) -> ([s|z]ext (truncate ([s|z]extload x)))
  9799. // Only generate vector extloads when 1) they're legal, and 2) they are
  9800. // deemed desirable by the target.
  9801. static SDValue tryToFoldExtOfLoad(SelectionDAG &DAG, DAGCombiner &Combiner,
  9802. const TargetLowering &TLI, EVT VT,
  9803. bool LegalOperations, SDNode *N, SDValue N0,
  9804. ISD::LoadExtType ExtLoadType,
  9805. ISD::NodeType ExtOpc) {
  9806. if (!ISD::isNON_EXTLoad(N0.getNode()) ||
  9807. !ISD::isUNINDEXEDLoad(N0.getNode()) ||
  9808. ((LegalOperations || VT.isVector() ||
  9809. !cast<LoadSDNode>(N0)->isSimple()) &&
  9810. !TLI.isLoadExtLegal(ExtLoadType, VT, N0.getValueType())))
  9811. return {};
  9812. bool DoXform = true;
  9813. SmallVector<SDNode *, 4> SetCCs;
  9814. if (!N0.hasOneUse())
  9815. DoXform = ExtendUsesToFormExtLoad(VT, N, N0, ExtOpc, SetCCs, TLI);
  9816. if (VT.isVector())
  9817. DoXform &= TLI.isVectorLoadExtDesirable(SDValue(N, 0));
  9818. if (!DoXform)
  9819. return {};
  9820. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  9821. SDValue ExtLoad = DAG.getExtLoad(ExtLoadType, SDLoc(LN0), VT, LN0->getChain(),
  9822. LN0->getBasePtr(), N0.getValueType(),
  9823. LN0->getMemOperand());
  9824. Combiner.ExtendSetCCUses(SetCCs, N0, ExtLoad, ExtOpc);
  9825. // If the load value is used only by N, replace it via CombineTo N.
  9826. bool NoReplaceTrunc = SDValue(LN0, 0).hasOneUse();
  9827. Combiner.CombineTo(N, ExtLoad);
  9828. if (NoReplaceTrunc) {
  9829. DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
  9830. Combiner.recursivelyDeleteUnusedNodes(LN0);
  9831. } else {
  9832. SDValue Trunc =
  9833. DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad);
  9834. Combiner.CombineTo(LN0, Trunc, ExtLoad.getValue(1));
  9835. }
  9836. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  9837. }
  9838. static SDValue tryToFoldExtOfMaskedLoad(SelectionDAG &DAG,
  9839. const TargetLowering &TLI, EVT VT,
  9840. SDNode *N, SDValue N0,
  9841. ISD::LoadExtType ExtLoadType,
  9842. ISD::NodeType ExtOpc) {
  9843. if (!N0.hasOneUse())
  9844. return SDValue();
  9845. MaskedLoadSDNode *Ld = dyn_cast<MaskedLoadSDNode>(N0);
  9846. if (!Ld || Ld->getExtensionType() != ISD::NON_EXTLOAD)
  9847. return SDValue();
  9848. if (!TLI.isLoadExtLegalOrCustom(ExtLoadType, VT, Ld->getValueType(0)))
  9849. return SDValue();
  9850. if (!TLI.isVectorLoadExtDesirable(SDValue(N, 0)))
  9851. return SDValue();
  9852. SDLoc dl(Ld);
  9853. SDValue PassThru = DAG.getNode(ExtOpc, dl, VT, Ld->getPassThru());
  9854. SDValue NewLoad = DAG.getMaskedLoad(
  9855. VT, dl, Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(), Ld->getMask(),
  9856. PassThru, Ld->getMemoryVT(), Ld->getMemOperand(), Ld->getAddressingMode(),
  9857. ExtLoadType, Ld->isExpandingLoad());
  9858. DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), SDValue(NewLoad.getNode(), 1));
  9859. return NewLoad;
  9860. }
  9861. static SDValue foldExtendedSignBitTest(SDNode *N, SelectionDAG &DAG,
  9862. bool LegalOperations) {
  9863. assert((N->getOpcode() == ISD::SIGN_EXTEND ||
  9864. N->getOpcode() == ISD::ZERO_EXTEND) && "Expected sext or zext");
  9865. SDValue SetCC = N->getOperand(0);
  9866. if (LegalOperations || SetCC.getOpcode() != ISD::SETCC ||
  9867. !SetCC.hasOneUse() || SetCC.getValueType() != MVT::i1)
  9868. return SDValue();
  9869. SDValue X = SetCC.getOperand(0);
  9870. SDValue Ones = SetCC.getOperand(1);
  9871. ISD::CondCode CC = cast<CondCodeSDNode>(SetCC.getOperand(2))->get();
  9872. EVT VT = N->getValueType(0);
  9873. EVT XVT = X.getValueType();
  9874. // setge X, C is canonicalized to setgt, so we do not need to match that
  9875. // pattern. The setlt sibling is folded in SimplifySelectCC() because it does
  9876. // not require the 'not' op.
  9877. if (CC == ISD::SETGT && isAllOnesConstant(Ones) && VT == XVT) {
  9878. // Invert and smear/shift the sign bit:
  9879. // sext i1 (setgt iN X, -1) --> sra (not X), (N - 1)
  9880. // zext i1 (setgt iN X, -1) --> srl (not X), (N - 1)
  9881. SDLoc DL(N);
  9882. unsigned ShCt = VT.getSizeInBits() - 1;
  9883. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  9884. if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) {
  9885. SDValue NotX = DAG.getNOT(DL, X, VT);
  9886. SDValue ShiftAmount = DAG.getConstant(ShCt, DL, VT);
  9887. auto ShiftOpcode =
  9888. N->getOpcode() == ISD::SIGN_EXTEND ? ISD::SRA : ISD::SRL;
  9889. return DAG.getNode(ShiftOpcode, DL, VT, NotX, ShiftAmount);
  9890. }
  9891. }
  9892. return SDValue();
  9893. }
  9894. SDValue DAGCombiner::foldSextSetcc(SDNode *N) {
  9895. SDValue N0 = N->getOperand(0);
  9896. if (N0.getOpcode() != ISD::SETCC)
  9897. return SDValue();
  9898. SDValue N00 = N0.getOperand(0);
  9899. SDValue N01 = N0.getOperand(1);
  9900. ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
  9901. EVT VT = N->getValueType(0);
  9902. EVT N00VT = N00.getValueType();
  9903. SDLoc DL(N);
  9904. // On some architectures (such as SSE/NEON/etc) the SETCC result type is
  9905. // the same size as the compared operands. Try to optimize sext(setcc())
  9906. // if this is the case.
  9907. if (VT.isVector() && !LegalOperations &&
  9908. TLI.getBooleanContents(N00VT) ==
  9909. TargetLowering::ZeroOrNegativeOneBooleanContent) {
  9910. EVT SVT = getSetCCResultType(N00VT);
  9911. // If we already have the desired type, don't change it.
  9912. if (SVT != N0.getValueType()) {
  9913. // We know that the # elements of the results is the same as the
  9914. // # elements of the compare (and the # elements of the compare result
  9915. // for that matter). Check to see that they are the same size. If so,
  9916. // we know that the element size of the sext'd result matches the
  9917. // element size of the compare operands.
  9918. if (VT.getSizeInBits() == SVT.getSizeInBits())
  9919. return DAG.getSetCC(DL, VT, N00, N01, CC);
  9920. // If the desired elements are smaller or larger than the source
  9921. // elements, we can use a matching integer vector type and then
  9922. // truncate/sign extend.
  9923. EVT MatchingVecType = N00VT.changeVectorElementTypeToInteger();
  9924. if (SVT == MatchingVecType) {
  9925. SDValue VsetCC = DAG.getSetCC(DL, MatchingVecType, N00, N01, CC);
  9926. return DAG.getSExtOrTrunc(VsetCC, DL, VT);
  9927. }
  9928. }
  9929. // Try to eliminate the sext of a setcc by zexting the compare operands.
  9930. if (N0.hasOneUse() && TLI.isOperationLegalOrCustom(ISD::SETCC, VT) &&
  9931. !TLI.isOperationLegalOrCustom(ISD::SETCC, SVT)) {
  9932. bool IsSignedCmp = ISD::isSignedIntSetCC(CC);
  9933. unsigned LoadOpcode = IsSignedCmp ? ISD::SEXTLOAD : ISD::ZEXTLOAD;
  9934. unsigned ExtOpcode = IsSignedCmp ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  9935. // We have an unsupported narrow vector compare op that would be legal
  9936. // if extended to the destination type. See if the compare operands
  9937. // can be freely extended to the destination type.
  9938. auto IsFreeToExtend = [&](SDValue V) {
  9939. if (isConstantOrConstantVector(V, /*NoOpaques*/ true))
  9940. return true;
  9941. // Match a simple, non-extended load that can be converted to a
  9942. // legal {z/s}ext-load.
  9943. // TODO: Allow widening of an existing {z/s}ext-load?
  9944. if (!(ISD::isNON_EXTLoad(V.getNode()) &&
  9945. ISD::isUNINDEXEDLoad(V.getNode()) &&
  9946. cast<LoadSDNode>(V)->isSimple() &&
  9947. TLI.isLoadExtLegal(LoadOpcode, VT, V.getValueType())))
  9948. return false;
  9949. // Non-chain users of this value must either be the setcc in this
  9950. // sequence or extends that can be folded into the new {z/s}ext-load.
  9951. for (SDNode::use_iterator UI = V->use_begin(), UE = V->use_end();
  9952. UI != UE; ++UI) {
  9953. // Skip uses of the chain and the setcc.
  9954. SDNode *User = *UI;
  9955. if (UI.getUse().getResNo() != 0 || User == N0.getNode())
  9956. continue;
  9957. // Extra users must have exactly the same cast we are about to create.
  9958. // TODO: This restriction could be eased if ExtendUsesToFormExtLoad()
  9959. // is enhanced similarly.
  9960. if (User->getOpcode() != ExtOpcode || User->getValueType(0) != VT)
  9961. return false;
  9962. }
  9963. return true;
  9964. };
  9965. if (IsFreeToExtend(N00) && IsFreeToExtend(N01)) {
  9966. SDValue Ext0 = DAG.getNode(ExtOpcode, DL, VT, N00);
  9967. SDValue Ext1 = DAG.getNode(ExtOpcode, DL, VT, N01);
  9968. return DAG.getSetCC(DL, VT, Ext0, Ext1, CC);
  9969. }
  9970. }
  9971. }
  9972. // sext(setcc x, y, cc) -> (select (setcc x, y, cc), T, 0)
  9973. // Here, T can be 1 or -1, depending on the type of the setcc and
  9974. // getBooleanContents().
  9975. unsigned SetCCWidth = N0.getScalarValueSizeInBits();
  9976. // To determine the "true" side of the select, we need to know the high bit
  9977. // of the value returned by the setcc if it evaluates to true.
  9978. // If the type of the setcc is i1, then the true case of the select is just
  9979. // sext(i1 1), that is, -1.
  9980. // If the type of the setcc is larger (say, i8) then the value of the high
  9981. // bit depends on getBooleanContents(), so ask TLI for a real "true" value
  9982. // of the appropriate width.
  9983. SDValue ExtTrueVal = (SetCCWidth == 1)
  9984. ? DAG.getAllOnesConstant(DL, VT)
  9985. : DAG.getBoolConstant(true, DL, VT, N00VT);
  9986. SDValue Zero = DAG.getConstant(0, DL, VT);
  9987. if (SDValue SCC = SimplifySelectCC(DL, N00, N01, ExtTrueVal, Zero, CC, true))
  9988. return SCC;
  9989. if (!VT.isVector() && !TLI.convertSelectOfConstantsToMath(VT)) {
  9990. EVT SetCCVT = getSetCCResultType(N00VT);
  9991. // Don't do this transform for i1 because there's a select transform
  9992. // that would reverse it.
  9993. // TODO: We should not do this transform at all without a target hook
  9994. // because a sext is likely cheaper than a select?
  9995. if (SetCCVT.getScalarSizeInBits() != 1 &&
  9996. (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, N00VT))) {
  9997. SDValue SetCC = DAG.getSetCC(DL, SetCCVT, N00, N01, CC);
  9998. return DAG.getSelect(DL, VT, SetCC, ExtTrueVal, Zero);
  9999. }
  10000. }
  10001. return SDValue();
  10002. }
  10003. SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
  10004. SDValue N0 = N->getOperand(0);
  10005. EVT VT = N->getValueType(0);
  10006. SDLoc DL(N);
  10007. if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
  10008. return Res;
  10009. // fold (sext (sext x)) -> (sext x)
  10010. // fold (sext (aext x)) -> (sext x)
  10011. if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
  10012. return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, N0.getOperand(0));
  10013. if (N0.getOpcode() == ISD::TRUNCATE) {
  10014. // fold (sext (truncate (load x))) -> (sext (smaller load x))
  10015. // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
  10016. if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
  10017. SDNode *oye = N0.getOperand(0).getNode();
  10018. if (NarrowLoad.getNode() != N0.getNode()) {
  10019. CombineTo(N0.getNode(), NarrowLoad);
  10020. // CombineTo deleted the truncate, if needed, but not what's under it.
  10021. AddToWorklist(oye);
  10022. }
  10023. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  10024. }
  10025. // See if the value being truncated is already sign extended. If so, just
  10026. // eliminate the trunc/sext pair.
  10027. SDValue Op = N0.getOperand(0);
  10028. unsigned OpBits = Op.getScalarValueSizeInBits();
  10029. unsigned MidBits = N0.getScalarValueSizeInBits();
  10030. unsigned DestBits = VT.getScalarSizeInBits();
  10031. unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
  10032. if (OpBits == DestBits) {
  10033. // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
  10034. // bits, it is already ready.
  10035. if (NumSignBits > DestBits-MidBits)
  10036. return Op;
  10037. } else if (OpBits < DestBits) {
  10038. // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
  10039. // bits, just sext from i32.
  10040. if (NumSignBits > OpBits-MidBits)
  10041. return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, Op);
  10042. } else {
  10043. // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
  10044. // bits, just truncate to i32.
  10045. if (NumSignBits > OpBits-MidBits)
  10046. return DAG.getNode(ISD::TRUNCATE, DL, VT, Op);
  10047. }
  10048. // fold (sext (truncate x)) -> (sextinreg x).
  10049. if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
  10050. N0.getValueType())) {
  10051. if (OpBits < DestBits)
  10052. Op = DAG.getNode(ISD::ANY_EXTEND, SDLoc(N0), VT, Op);
  10053. else if (OpBits > DestBits)
  10054. Op = DAG.getNode(ISD::TRUNCATE, SDLoc(N0), VT, Op);
  10055. return DAG.getNode(ISD::SIGN_EXTEND_INREG, DL, VT, Op,
  10056. DAG.getValueType(N0.getValueType()));
  10057. }
  10058. }
  10059. // Try to simplify (sext (load x)).
  10060. if (SDValue foldedExt =
  10061. tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
  10062. ISD::SEXTLOAD, ISD::SIGN_EXTEND))
  10063. return foldedExt;
  10064. if (SDValue foldedExt =
  10065. tryToFoldExtOfMaskedLoad(DAG, TLI, VT, N, N0, ISD::SEXTLOAD,
  10066. ISD::SIGN_EXTEND))
  10067. return foldedExt;
  10068. // fold (sext (load x)) to multiple smaller sextloads.
  10069. // Only on illegal but splittable vectors.
  10070. if (SDValue ExtLoad = CombineExtLoad(N))
  10071. return ExtLoad;
  10072. // Try to simplify (sext (sextload x)).
  10073. if (SDValue foldedExt = tryToFoldExtOfExtload(
  10074. DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::SEXTLOAD))
  10075. return foldedExt;
  10076. // fold (sext (and/or/xor (load x), cst)) ->
  10077. // (and/or/xor (sextload x), (sext cst))
  10078. if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
  10079. N0.getOpcode() == ISD::XOR) &&
  10080. isa<LoadSDNode>(N0.getOperand(0)) &&
  10081. N0.getOperand(1).getOpcode() == ISD::Constant &&
  10082. (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
  10083. LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
  10084. EVT MemVT = LN00->getMemoryVT();
  10085. if (TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, MemVT) &&
  10086. LN00->getExtensionType() != ISD::ZEXTLOAD && LN00->isUnindexed()) {
  10087. SmallVector<SDNode*, 4> SetCCs;
  10088. bool DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
  10089. ISD::SIGN_EXTEND, SetCCs, TLI);
  10090. if (DoXform) {
  10091. SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(LN00), VT,
  10092. LN00->getChain(), LN00->getBasePtr(),
  10093. LN00->getMemoryVT(),
  10094. LN00->getMemOperand());
  10095. APInt Mask = N0.getConstantOperandAPInt(1).sext(VT.getSizeInBits());
  10096. SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
  10097. ExtLoad, DAG.getConstant(Mask, DL, VT));
  10098. ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::SIGN_EXTEND);
  10099. bool NoReplaceTruncAnd = !N0.hasOneUse();
  10100. bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
  10101. CombineTo(N, And);
  10102. // If N0 has multiple uses, change other uses as well.
  10103. if (NoReplaceTruncAnd) {
  10104. SDValue TruncAnd =
  10105. DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
  10106. CombineTo(N0.getNode(), TruncAnd);
  10107. }
  10108. if (NoReplaceTrunc) {
  10109. DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
  10110. } else {
  10111. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
  10112. LN00->getValueType(0), ExtLoad);
  10113. CombineTo(LN00, Trunc, ExtLoad.getValue(1));
  10114. }
  10115. return SDValue(N,0); // Return N so it doesn't get rechecked!
  10116. }
  10117. }
  10118. }
  10119. if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
  10120. return V;
  10121. if (SDValue V = foldSextSetcc(N))
  10122. return V;
  10123. // fold (sext x) -> (zext x) if the sign bit is known zero.
  10124. if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
  10125. DAG.SignBitIsZero(N0))
  10126. return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0);
  10127. if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
  10128. return NewVSel;
  10129. // Eliminate this sign extend by doing a negation in the destination type:
  10130. // sext i32 (0 - (zext i8 X to i32)) to i64 --> 0 - (zext i8 X to i64)
  10131. if (N0.getOpcode() == ISD::SUB && N0.hasOneUse() &&
  10132. isNullOrNullSplat(N0.getOperand(0)) &&
  10133. N0.getOperand(1).getOpcode() == ISD::ZERO_EXTEND &&
  10134. TLI.isOperationLegalOrCustom(ISD::SUB, VT)) {
  10135. SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(1).getOperand(0), DL, VT);
  10136. return DAG.getNode(ISD::SUB, DL, VT, DAG.getConstant(0, DL, VT), Zext);
  10137. }
  10138. // Eliminate this sign extend by doing a decrement in the destination type:
  10139. // sext i32 ((zext i8 X to i32) + (-1)) to i64 --> (zext i8 X to i64) + (-1)
  10140. if (N0.getOpcode() == ISD::ADD && N0.hasOneUse() &&
  10141. isAllOnesOrAllOnesSplat(N0.getOperand(1)) &&
  10142. N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
  10143. TLI.isOperationLegalOrCustom(ISD::ADD, VT)) {
  10144. SDValue Zext = DAG.getZExtOrTrunc(N0.getOperand(0).getOperand(0), DL, VT);
  10145. return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT));
  10146. }
  10147. // fold sext (not i1 X) -> add (zext i1 X), -1
  10148. // TODO: This could be extended to handle bool vectors.
  10149. if (N0.getValueType() == MVT::i1 && isBitwiseNot(N0) && N0.hasOneUse() &&
  10150. (!LegalOperations || (TLI.isOperationLegal(ISD::ZERO_EXTEND, VT) &&
  10151. TLI.isOperationLegal(ISD::ADD, VT)))) {
  10152. // If we can eliminate the 'not', the sext form should be better
  10153. if (SDValue NewXor = visitXOR(N0.getNode())) {
  10154. // Returning N0 is a form of in-visit replacement that may have
  10155. // invalidated N0.
  10156. if (NewXor.getNode() == N0.getNode()) {
  10157. // Return SDValue here as the xor should have already been replaced in
  10158. // this sext.
  10159. return SDValue();
  10160. } else {
  10161. // Return a new sext with the new xor.
  10162. return DAG.getNode(ISD::SIGN_EXTEND, DL, VT, NewXor);
  10163. }
  10164. }
  10165. SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
  10166. return DAG.getNode(ISD::ADD, DL, VT, Zext, DAG.getAllOnesConstant(DL, VT));
  10167. }
  10168. if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG))
  10169. return Res;
  10170. return SDValue();
  10171. }
  10172. // isTruncateOf - If N is a truncate of some other value, return true, record
  10173. // the value being truncated in Op and which of Op's bits are zero/one in Known.
  10174. // This function computes KnownBits to avoid a duplicated call to
  10175. // computeKnownBits in the caller.
  10176. static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
  10177. KnownBits &Known) {
  10178. if (N->getOpcode() == ISD::TRUNCATE) {
  10179. Op = N->getOperand(0);
  10180. Known = DAG.computeKnownBits(Op);
  10181. return true;
  10182. }
  10183. if (N.getOpcode() != ISD::SETCC ||
  10184. N.getValueType().getScalarType() != MVT::i1 ||
  10185. cast<CondCodeSDNode>(N.getOperand(2))->get() != ISD::SETNE)
  10186. return false;
  10187. SDValue Op0 = N->getOperand(0);
  10188. SDValue Op1 = N->getOperand(1);
  10189. assert(Op0.getValueType() == Op1.getValueType());
  10190. if (isNullOrNullSplat(Op0))
  10191. Op = Op1;
  10192. else if (isNullOrNullSplat(Op1))
  10193. Op = Op0;
  10194. else
  10195. return false;
  10196. Known = DAG.computeKnownBits(Op);
  10197. return (Known.Zero | 1).isAllOnes();
  10198. }
  10199. /// Given an extending node with a pop-count operand, if the target does not
  10200. /// support a pop-count in the narrow source type but does support it in the
  10201. /// destination type, widen the pop-count to the destination type.
  10202. static SDValue widenCtPop(SDNode *Extend, SelectionDAG &DAG) {
  10203. assert((Extend->getOpcode() == ISD::ZERO_EXTEND ||
  10204. Extend->getOpcode() == ISD::ANY_EXTEND) && "Expected extend op");
  10205. SDValue CtPop = Extend->getOperand(0);
  10206. if (CtPop.getOpcode() != ISD::CTPOP || !CtPop.hasOneUse())
  10207. return SDValue();
  10208. EVT VT = Extend->getValueType(0);
  10209. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  10210. if (TLI.isOperationLegalOrCustom(ISD::CTPOP, CtPop.getValueType()) ||
  10211. !TLI.isOperationLegalOrCustom(ISD::CTPOP, VT))
  10212. return SDValue();
  10213. // zext (ctpop X) --> ctpop (zext X)
  10214. SDLoc DL(Extend);
  10215. SDValue NewZext = DAG.getZExtOrTrunc(CtPop.getOperand(0), DL, VT);
  10216. return DAG.getNode(ISD::CTPOP, DL, VT, NewZext);
  10217. }
  10218. SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
  10219. SDValue N0 = N->getOperand(0);
  10220. EVT VT = N->getValueType(0);
  10221. if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
  10222. return Res;
  10223. // fold (zext (zext x)) -> (zext x)
  10224. // fold (zext (aext x)) -> (zext x)
  10225. if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
  10226. return DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N), VT,
  10227. N0.getOperand(0));
  10228. // fold (zext (truncate x)) -> (zext x) or
  10229. // (zext (truncate x)) -> (truncate x)
  10230. // This is valid when the truncated bits of x are already zero.
  10231. SDValue Op;
  10232. KnownBits Known;
  10233. if (isTruncateOf(DAG, N0, Op, Known)) {
  10234. APInt TruncatedBits =
  10235. (Op.getScalarValueSizeInBits() == N0.getScalarValueSizeInBits()) ?
  10236. APInt(Op.getScalarValueSizeInBits(), 0) :
  10237. APInt::getBitsSet(Op.getScalarValueSizeInBits(),
  10238. N0.getScalarValueSizeInBits(),
  10239. std::min(Op.getScalarValueSizeInBits(),
  10240. VT.getScalarSizeInBits()));
  10241. if (TruncatedBits.isSubsetOf(Known.Zero))
  10242. return DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
  10243. }
  10244. // fold (zext (truncate x)) -> (and x, mask)
  10245. if (N0.getOpcode() == ISD::TRUNCATE) {
  10246. // fold (zext (truncate (load x))) -> (zext (smaller load x))
  10247. // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
  10248. if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
  10249. SDNode *oye = N0.getOperand(0).getNode();
  10250. if (NarrowLoad.getNode() != N0.getNode()) {
  10251. CombineTo(N0.getNode(), NarrowLoad);
  10252. // CombineTo deleted the truncate, if needed, but not what's under it.
  10253. AddToWorklist(oye);
  10254. }
  10255. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  10256. }
  10257. EVT SrcVT = N0.getOperand(0).getValueType();
  10258. EVT MinVT = N0.getValueType();
  10259. // Try to mask before the extension to avoid having to generate a larger mask,
  10260. // possibly over several sub-vectors.
  10261. if (SrcVT.bitsLT(VT) && VT.isVector()) {
  10262. if (!LegalOperations || (TLI.isOperationLegal(ISD::AND, SrcVT) &&
  10263. TLI.isOperationLegal(ISD::ZERO_EXTEND, VT))) {
  10264. SDValue Op = N0.getOperand(0);
  10265. Op = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT);
  10266. AddToWorklist(Op.getNode());
  10267. SDValue ZExtOrTrunc = DAG.getZExtOrTrunc(Op, SDLoc(N), VT);
  10268. // Transfer the debug info; the new node is equivalent to N0.
  10269. DAG.transferDbgValues(N0, ZExtOrTrunc);
  10270. return ZExtOrTrunc;
  10271. }
  10272. }
  10273. if (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT)) {
  10274. SDValue Op = DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
  10275. AddToWorklist(Op.getNode());
  10276. SDValue And = DAG.getZeroExtendInReg(Op, SDLoc(N), MinVT);
  10277. // We may safely transfer the debug info describing the truncate node over
  10278. // to the equivalent and operation.
  10279. DAG.transferDbgValues(N0, And);
  10280. return And;
  10281. }
  10282. }
  10283. // Fold (zext (and (trunc x), cst)) -> (and x, cst),
  10284. // if either of the casts is not free.
  10285. if (N0.getOpcode() == ISD::AND &&
  10286. N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
  10287. N0.getOperand(1).getOpcode() == ISD::Constant &&
  10288. (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
  10289. N0.getValueType()) ||
  10290. !TLI.isZExtFree(N0.getValueType(), VT))) {
  10291. SDValue X = N0.getOperand(0).getOperand(0);
  10292. X = DAG.getAnyExtOrTrunc(X, SDLoc(X), VT);
  10293. APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
  10294. SDLoc DL(N);
  10295. return DAG.getNode(ISD::AND, DL, VT,
  10296. X, DAG.getConstant(Mask, DL, VT));
  10297. }
  10298. // Try to simplify (zext (load x)).
  10299. if (SDValue foldedExt =
  10300. tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
  10301. ISD::ZEXTLOAD, ISD::ZERO_EXTEND))
  10302. return foldedExt;
  10303. if (SDValue foldedExt =
  10304. tryToFoldExtOfMaskedLoad(DAG, TLI, VT, N, N0, ISD::ZEXTLOAD,
  10305. ISD::ZERO_EXTEND))
  10306. return foldedExt;
  10307. // fold (zext (load x)) to multiple smaller zextloads.
  10308. // Only on illegal but splittable vectors.
  10309. if (SDValue ExtLoad = CombineExtLoad(N))
  10310. return ExtLoad;
  10311. // fold (zext (and/or/xor (load x), cst)) ->
  10312. // (and/or/xor (zextload x), (zext cst))
  10313. // Unless (and (load x) cst) will match as a zextload already and has
  10314. // additional users.
  10315. if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
  10316. N0.getOpcode() == ISD::XOR) &&
  10317. isa<LoadSDNode>(N0.getOperand(0)) &&
  10318. N0.getOperand(1).getOpcode() == ISD::Constant &&
  10319. (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
  10320. LoadSDNode *LN00 = cast<LoadSDNode>(N0.getOperand(0));
  10321. EVT MemVT = LN00->getMemoryVT();
  10322. if (TLI.isLoadExtLegal(ISD::ZEXTLOAD, VT, MemVT) &&
  10323. LN00->getExtensionType() != ISD::SEXTLOAD && LN00->isUnindexed()) {
  10324. bool DoXform = true;
  10325. SmallVector<SDNode*, 4> SetCCs;
  10326. if (!N0.hasOneUse()) {
  10327. if (N0.getOpcode() == ISD::AND) {
  10328. auto *AndC = cast<ConstantSDNode>(N0.getOperand(1));
  10329. EVT LoadResultTy = AndC->getValueType(0);
  10330. EVT ExtVT;
  10331. if (isAndLoadExtLoad(AndC, LN00, LoadResultTy, ExtVT))
  10332. DoXform = false;
  10333. }
  10334. }
  10335. if (DoXform)
  10336. DoXform = ExtendUsesToFormExtLoad(VT, N0.getNode(), N0.getOperand(0),
  10337. ISD::ZERO_EXTEND, SetCCs, TLI);
  10338. if (DoXform) {
  10339. SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, SDLoc(LN00), VT,
  10340. LN00->getChain(), LN00->getBasePtr(),
  10341. LN00->getMemoryVT(),
  10342. LN00->getMemOperand());
  10343. APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
  10344. SDLoc DL(N);
  10345. SDValue And = DAG.getNode(N0.getOpcode(), DL, VT,
  10346. ExtLoad, DAG.getConstant(Mask, DL, VT));
  10347. ExtendSetCCUses(SetCCs, N0.getOperand(0), ExtLoad, ISD::ZERO_EXTEND);
  10348. bool NoReplaceTruncAnd = !N0.hasOneUse();
  10349. bool NoReplaceTrunc = SDValue(LN00, 0).hasOneUse();
  10350. CombineTo(N, And);
  10351. // If N0 has multiple uses, change other uses as well.
  10352. if (NoReplaceTruncAnd) {
  10353. SDValue TruncAnd =
  10354. DAG.getNode(ISD::TRUNCATE, DL, N0.getValueType(), And);
  10355. CombineTo(N0.getNode(), TruncAnd);
  10356. }
  10357. if (NoReplaceTrunc) {
  10358. DAG.ReplaceAllUsesOfValueWith(SDValue(LN00, 1), ExtLoad.getValue(1));
  10359. } else {
  10360. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SDLoc(LN00),
  10361. LN00->getValueType(0), ExtLoad);
  10362. CombineTo(LN00, Trunc, ExtLoad.getValue(1));
  10363. }
  10364. return SDValue(N,0); // Return N so it doesn't get rechecked!
  10365. }
  10366. }
  10367. }
  10368. // fold (zext (and/or/xor (shl/shr (load x), cst), cst)) ->
  10369. // (and/or/xor (shl/shr (zextload x), (zext cst)), (zext cst))
  10370. if (SDValue ZExtLoad = CombineZExtLogicopShiftLoad(N))
  10371. return ZExtLoad;
  10372. // Try to simplify (zext (zextload x)).
  10373. if (SDValue foldedExt = tryToFoldExtOfExtload(
  10374. DAG, *this, TLI, VT, LegalOperations, N, N0, ISD::ZEXTLOAD))
  10375. return foldedExt;
  10376. if (SDValue V = foldExtendedSignBitTest(N, DAG, LegalOperations))
  10377. return V;
  10378. if (N0.getOpcode() == ISD::SETCC) {
  10379. // Only do this before legalize for now.
  10380. if (!LegalOperations && VT.isVector() &&
  10381. N0.getValueType().getVectorElementType() == MVT::i1) {
  10382. EVT N00VT = N0.getOperand(0).getValueType();
  10383. if (getSetCCResultType(N00VT) == N0.getValueType())
  10384. return SDValue();
  10385. // We know that the # elements of the results is the same as the #
  10386. // elements of the compare (and the # elements of the compare result for
  10387. // that matter). Check to see that they are the same size. If so, we know
  10388. // that the element size of the sext'd result matches the element size of
  10389. // the compare operands.
  10390. SDLoc DL(N);
  10391. if (VT.getSizeInBits() == N00VT.getSizeInBits()) {
  10392. // zext(setcc) -> zext_in_reg(vsetcc) for vectors.
  10393. SDValue VSetCC = DAG.getNode(ISD::SETCC, DL, VT, N0.getOperand(0),
  10394. N0.getOperand(1), N0.getOperand(2));
  10395. return DAG.getZeroExtendInReg(VSetCC, DL, N0.getValueType());
  10396. }
  10397. // If the desired elements are smaller or larger than the source
  10398. // elements we can use a matching integer vector type and then
  10399. // truncate/any extend followed by zext_in_reg.
  10400. EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
  10401. SDValue VsetCC =
  10402. DAG.getNode(ISD::SETCC, DL, MatchingVectorType, N0.getOperand(0),
  10403. N0.getOperand(1), N0.getOperand(2));
  10404. return DAG.getZeroExtendInReg(DAG.getAnyExtOrTrunc(VsetCC, DL, VT), DL,
  10405. N0.getValueType());
  10406. }
  10407. // zext(setcc x,y,cc) -> zext(select x, y, true, false, cc)
  10408. SDLoc DL(N);
  10409. EVT N0VT = N0.getValueType();
  10410. EVT N00VT = N0.getOperand(0).getValueType();
  10411. if (SDValue SCC = SimplifySelectCC(
  10412. DL, N0.getOperand(0), N0.getOperand(1),
  10413. DAG.getBoolConstant(true, DL, N0VT, N00VT),
  10414. DAG.getBoolConstant(false, DL, N0VT, N00VT),
  10415. cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
  10416. return DAG.getNode(ISD::ZERO_EXTEND, DL, VT, SCC);
  10417. }
  10418. // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
  10419. if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
  10420. isa<ConstantSDNode>(N0.getOperand(1)) &&
  10421. N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
  10422. N0.hasOneUse()) {
  10423. SDValue ShAmt = N0.getOperand(1);
  10424. if (N0.getOpcode() == ISD::SHL) {
  10425. SDValue InnerZExt = N0.getOperand(0);
  10426. // If the original shl may be shifting out bits, do not perform this
  10427. // transformation.
  10428. unsigned KnownZeroBits = InnerZExt.getValueSizeInBits() -
  10429. InnerZExt.getOperand(0).getValueSizeInBits();
  10430. if (cast<ConstantSDNode>(ShAmt)->getAPIntValue().ugt(KnownZeroBits))
  10431. return SDValue();
  10432. }
  10433. SDLoc DL(N);
  10434. // Ensure that the shift amount is wide enough for the shifted value.
  10435. if (Log2_32_Ceil(VT.getSizeInBits()) > ShAmt.getValueSizeInBits())
  10436. ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
  10437. return DAG.getNode(N0.getOpcode(), DL, VT,
  10438. DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
  10439. ShAmt);
  10440. }
  10441. if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
  10442. return NewVSel;
  10443. if (SDValue NewCtPop = widenCtPop(N, DAG))
  10444. return NewCtPop;
  10445. if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG))
  10446. return Res;
  10447. return SDValue();
  10448. }
  10449. SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
  10450. SDValue N0 = N->getOperand(0);
  10451. EVT VT = N->getValueType(0);
  10452. if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
  10453. return Res;
  10454. // fold (aext (aext x)) -> (aext x)
  10455. // fold (aext (zext x)) -> (zext x)
  10456. // fold (aext (sext x)) -> (sext x)
  10457. if (N0.getOpcode() == ISD::ANY_EXTEND ||
  10458. N0.getOpcode() == ISD::ZERO_EXTEND ||
  10459. N0.getOpcode() == ISD::SIGN_EXTEND)
  10460. return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
  10461. // fold (aext (truncate (load x))) -> (aext (smaller load x))
  10462. // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
  10463. if (N0.getOpcode() == ISD::TRUNCATE) {
  10464. if (SDValue NarrowLoad = reduceLoadWidth(N0.getNode())) {
  10465. SDNode *oye = N0.getOperand(0).getNode();
  10466. if (NarrowLoad.getNode() != N0.getNode()) {
  10467. CombineTo(N0.getNode(), NarrowLoad);
  10468. // CombineTo deleted the truncate, if needed, but not what's under it.
  10469. AddToWorklist(oye);
  10470. }
  10471. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  10472. }
  10473. }
  10474. // fold (aext (truncate x))
  10475. if (N0.getOpcode() == ISD::TRUNCATE)
  10476. return DAG.getAnyExtOrTrunc(N0.getOperand(0), SDLoc(N), VT);
  10477. // Fold (aext (and (trunc x), cst)) -> (and x, cst)
  10478. // if the trunc is not free.
  10479. if (N0.getOpcode() == ISD::AND &&
  10480. N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
  10481. N0.getOperand(1).getOpcode() == ISD::Constant &&
  10482. !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
  10483. N0.getValueType())) {
  10484. SDLoc DL(N);
  10485. SDValue X = N0.getOperand(0).getOperand(0);
  10486. X = DAG.getAnyExtOrTrunc(X, DL, VT);
  10487. APInt Mask = N0.getConstantOperandAPInt(1).zext(VT.getSizeInBits());
  10488. return DAG.getNode(ISD::AND, DL, VT,
  10489. X, DAG.getConstant(Mask, DL, VT));
  10490. }
  10491. // fold (aext (load x)) -> (aext (truncate (extload x)))
  10492. // None of the supported targets knows how to perform load and any_ext
  10493. // on vectors in one instruction, so attempt to fold to zext instead.
  10494. if (VT.isVector()) {
  10495. // Try to simplify (zext (load x)).
  10496. if (SDValue foldedExt =
  10497. tryToFoldExtOfLoad(DAG, *this, TLI, VT, LegalOperations, N, N0,
  10498. ISD::ZEXTLOAD, ISD::ZERO_EXTEND))
  10499. return foldedExt;
  10500. } else if (ISD::isNON_EXTLoad(N0.getNode()) &&
  10501. ISD::isUNINDEXEDLoad(N0.getNode()) &&
  10502. TLI.isLoadExtLegal(ISD::EXTLOAD, VT, N0.getValueType())) {
  10503. bool DoXform = true;
  10504. SmallVector<SDNode *, 4> SetCCs;
  10505. if (!N0.hasOneUse())
  10506. DoXform =
  10507. ExtendUsesToFormExtLoad(VT, N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
  10508. if (DoXform) {
  10509. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  10510. SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
  10511. LN0->getChain(), LN0->getBasePtr(),
  10512. N0.getValueType(), LN0->getMemOperand());
  10513. ExtendSetCCUses(SetCCs, N0, ExtLoad, ISD::ANY_EXTEND);
  10514. // If the load value is used only by N, replace it via CombineTo N.
  10515. bool NoReplaceTrunc = N0.hasOneUse();
  10516. CombineTo(N, ExtLoad);
  10517. if (NoReplaceTrunc) {
  10518. DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
  10519. recursivelyDeleteUnusedNodes(LN0);
  10520. } else {
  10521. SDValue Trunc =
  10522. DAG.getNode(ISD::TRUNCATE, SDLoc(N0), N0.getValueType(), ExtLoad);
  10523. CombineTo(LN0, Trunc, ExtLoad.getValue(1));
  10524. }
  10525. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  10526. }
  10527. }
  10528. // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
  10529. // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
  10530. // fold (aext ( extload x)) -> (aext (truncate (extload x)))
  10531. if (N0.getOpcode() == ISD::LOAD && !ISD::isNON_EXTLoad(N0.getNode()) &&
  10532. ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
  10533. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  10534. ISD::LoadExtType ExtType = LN0->getExtensionType();
  10535. EVT MemVT = LN0->getMemoryVT();
  10536. if (!LegalOperations || TLI.isLoadExtLegal(ExtType, VT, MemVT)) {
  10537. SDValue ExtLoad = DAG.getExtLoad(ExtType, SDLoc(N),
  10538. VT, LN0->getChain(), LN0->getBasePtr(),
  10539. MemVT, LN0->getMemOperand());
  10540. CombineTo(N, ExtLoad);
  10541. DAG.ReplaceAllUsesOfValueWith(SDValue(LN0, 1), ExtLoad.getValue(1));
  10542. recursivelyDeleteUnusedNodes(LN0);
  10543. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  10544. }
  10545. }
  10546. if (N0.getOpcode() == ISD::SETCC) {
  10547. // For vectors:
  10548. // aext(setcc) -> vsetcc
  10549. // aext(setcc) -> truncate(vsetcc)
  10550. // aext(setcc) -> aext(vsetcc)
  10551. // Only do this before legalize for now.
  10552. if (VT.isVector() && !LegalOperations) {
  10553. EVT N00VT = N0.getOperand(0).getValueType();
  10554. if (getSetCCResultType(N00VT) == N0.getValueType())
  10555. return SDValue();
  10556. // We know that the # elements of the results is the same as the
  10557. // # elements of the compare (and the # elements of the compare result
  10558. // for that matter). Check to see that they are the same size. If so,
  10559. // we know that the element size of the sext'd result matches the
  10560. // element size of the compare operands.
  10561. if (VT.getSizeInBits() == N00VT.getSizeInBits())
  10562. return DAG.getSetCC(SDLoc(N), VT, N0.getOperand(0),
  10563. N0.getOperand(1),
  10564. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  10565. // If the desired elements are smaller or larger than the source
  10566. // elements we can use a matching integer vector type and then
  10567. // truncate/any extend
  10568. EVT MatchingVectorType = N00VT.changeVectorElementTypeToInteger();
  10569. SDValue VsetCC =
  10570. DAG.getSetCC(SDLoc(N), MatchingVectorType, N0.getOperand(0),
  10571. N0.getOperand(1),
  10572. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  10573. return DAG.getAnyExtOrTrunc(VsetCC, SDLoc(N), VT);
  10574. }
  10575. // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
  10576. SDLoc DL(N);
  10577. if (SDValue SCC = SimplifySelectCC(
  10578. DL, N0.getOperand(0), N0.getOperand(1), DAG.getConstant(1, DL, VT),
  10579. DAG.getConstant(0, DL, VT),
  10580. cast<CondCodeSDNode>(N0.getOperand(2))->get(), true))
  10581. return SCC;
  10582. }
  10583. if (SDValue NewCtPop = widenCtPop(N, DAG))
  10584. return NewCtPop;
  10585. if (SDValue Res = tryToFoldExtendSelectLoad(N, TLI, DAG))
  10586. return Res;
  10587. return SDValue();
  10588. }
  10589. SDValue DAGCombiner::visitAssertExt(SDNode *N) {
  10590. unsigned Opcode = N->getOpcode();
  10591. SDValue N0 = N->getOperand(0);
  10592. SDValue N1 = N->getOperand(1);
  10593. EVT AssertVT = cast<VTSDNode>(N1)->getVT();
  10594. // fold (assert?ext (assert?ext x, vt), vt) -> (assert?ext x, vt)
  10595. if (N0.getOpcode() == Opcode &&
  10596. AssertVT == cast<VTSDNode>(N0.getOperand(1))->getVT())
  10597. return N0;
  10598. if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
  10599. N0.getOperand(0).getOpcode() == Opcode) {
  10600. // We have an assert, truncate, assert sandwich. Make one stronger assert
  10601. // by asserting on the smallest asserted type to the larger source type.
  10602. // This eliminates the later assert:
  10603. // assert (trunc (assert X, i8) to iN), i1 --> trunc (assert X, i1) to iN
  10604. // assert (trunc (assert X, i1) to iN), i8 --> trunc (assert X, i1) to iN
  10605. SDValue BigA = N0.getOperand(0);
  10606. EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
  10607. assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
  10608. "Asserting zero/sign-extended bits to a type larger than the "
  10609. "truncated destination does not provide information");
  10610. SDLoc DL(N);
  10611. EVT MinAssertVT = AssertVT.bitsLT(BigA_AssertVT) ? AssertVT : BigA_AssertVT;
  10612. SDValue MinAssertVTVal = DAG.getValueType(MinAssertVT);
  10613. SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
  10614. BigA.getOperand(0), MinAssertVTVal);
  10615. return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
  10616. }
  10617. // If we have (AssertZext (truncate (AssertSext X, iX)), iY) and Y is smaller
  10618. // than X. Just move the AssertZext in front of the truncate and drop the
  10619. // AssertSExt.
  10620. if (N0.getOpcode() == ISD::TRUNCATE && N0.hasOneUse() &&
  10621. N0.getOperand(0).getOpcode() == ISD::AssertSext &&
  10622. Opcode == ISD::AssertZext) {
  10623. SDValue BigA = N0.getOperand(0);
  10624. EVT BigA_AssertVT = cast<VTSDNode>(BigA.getOperand(1))->getVT();
  10625. assert(BigA_AssertVT.bitsLE(N0.getValueType()) &&
  10626. "Asserting zero/sign-extended bits to a type larger than the "
  10627. "truncated destination does not provide information");
  10628. if (AssertVT.bitsLT(BigA_AssertVT)) {
  10629. SDLoc DL(N);
  10630. SDValue NewAssert = DAG.getNode(Opcode, DL, BigA.getValueType(),
  10631. BigA.getOperand(0), N1);
  10632. return DAG.getNode(ISD::TRUNCATE, DL, N->getValueType(0), NewAssert);
  10633. }
  10634. }
  10635. return SDValue();
  10636. }
  10637. SDValue DAGCombiner::visitAssertAlign(SDNode *N) {
  10638. SDLoc DL(N);
  10639. Align AL = cast<AssertAlignSDNode>(N)->getAlign();
  10640. SDValue N0 = N->getOperand(0);
  10641. // Fold (assertalign (assertalign x, AL0), AL1) ->
  10642. // (assertalign x, max(AL0, AL1))
  10643. if (auto *AAN = dyn_cast<AssertAlignSDNode>(N0))
  10644. return DAG.getAssertAlign(DL, N0.getOperand(0),
  10645. std::max(AL, AAN->getAlign()));
  10646. // In rare cases, there are trivial arithmetic ops in source operands. Sink
  10647. // this assert down to source operands so that those arithmetic ops could be
  10648. // exposed to the DAG combining.
  10649. switch (N0.getOpcode()) {
  10650. default:
  10651. break;
  10652. case ISD::ADD:
  10653. case ISD::SUB: {
  10654. unsigned AlignShift = Log2(AL);
  10655. SDValue LHS = N0.getOperand(0);
  10656. SDValue RHS = N0.getOperand(1);
  10657. unsigned LHSAlignShift = DAG.computeKnownBits(LHS).countMinTrailingZeros();
  10658. unsigned RHSAlignShift = DAG.computeKnownBits(RHS).countMinTrailingZeros();
  10659. if (LHSAlignShift >= AlignShift || RHSAlignShift >= AlignShift) {
  10660. if (LHSAlignShift < AlignShift)
  10661. LHS = DAG.getAssertAlign(DL, LHS, AL);
  10662. if (RHSAlignShift < AlignShift)
  10663. RHS = DAG.getAssertAlign(DL, RHS, AL);
  10664. return DAG.getNode(N0.getOpcode(), DL, N0.getValueType(), LHS, RHS);
  10665. }
  10666. break;
  10667. }
  10668. }
  10669. return SDValue();
  10670. }
  10671. /// If the result of a load is shifted/masked/truncated to an effectively
  10672. /// narrower type, try to transform the load to a narrower type and/or
  10673. /// use an extending load.
  10674. SDValue DAGCombiner::reduceLoadWidth(SDNode *N) {
  10675. unsigned Opc = N->getOpcode();
  10676. ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
  10677. SDValue N0 = N->getOperand(0);
  10678. EVT VT = N->getValueType(0);
  10679. EVT ExtVT = VT;
  10680. // This transformation isn't valid for vector loads.
  10681. if (VT.isVector())
  10682. return SDValue();
  10683. // The ShAmt variable is used to indicate that we've consumed a right
  10684. // shift. I.e. we want to narrow the width of the load by skipping to load the
  10685. // ShAmt least significant bits.
  10686. unsigned ShAmt = 0;
  10687. // A special case is when the least significant bits from the load are masked
  10688. // away, but using an AND rather than a right shift. HasShiftedOffset is used
  10689. // to indicate that the narrowed load should be left-shifted ShAmt bits to get
  10690. // the result.
  10691. bool HasShiftedOffset = false;
  10692. // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
  10693. // extended to VT.
  10694. if (Opc == ISD::SIGN_EXTEND_INREG) {
  10695. ExtType = ISD::SEXTLOAD;
  10696. ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
  10697. } else if (Opc == ISD::SRL || Opc == ISD::SRA) {
  10698. // Another special-case: SRL/SRA is basically zero/sign-extending a narrower
  10699. // value, or it may be shifting a higher subword, half or byte into the
  10700. // lowest bits.
  10701. // Only handle shift with constant shift amount, and the shiftee must be a
  10702. // load.
  10703. auto *LN = dyn_cast<LoadSDNode>(N0);
  10704. auto *N1C = dyn_cast<ConstantSDNode>(N->getOperand(1));
  10705. if (!N1C || !LN)
  10706. return SDValue();
  10707. // If the shift amount is larger than the memory type then we're not
  10708. // accessing any of the loaded bytes.
  10709. ShAmt = N1C->getZExtValue();
  10710. uint64_t MemoryWidth = LN->getMemoryVT().getScalarSizeInBits();
  10711. if (MemoryWidth <= ShAmt)
  10712. return SDValue();
  10713. // Attempt to fold away the SRL by using ZEXTLOAD and SRA by using SEXTLOAD.
  10714. ExtType = Opc == ISD::SRL ? ISD::ZEXTLOAD : ISD::SEXTLOAD;
  10715. ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShAmt);
  10716. // If original load is a SEXTLOAD then we can't simply replace it by a
  10717. // ZEXTLOAD (we could potentially replace it by a more narrow SEXTLOAD
  10718. // followed by a ZEXT, but that is not handled at the moment). Similarly if
  10719. // the original load is a ZEXTLOAD and we want to use a SEXTLOAD.
  10720. if ((LN->getExtensionType() == ISD::SEXTLOAD ||
  10721. LN->getExtensionType() == ISD::ZEXTLOAD) &&
  10722. LN->getExtensionType() != ExtType)
  10723. return SDValue();
  10724. } else if (Opc == ISD::AND) {
  10725. // An AND with a constant mask is the same as a truncate + zero-extend.
  10726. auto AndC = dyn_cast<ConstantSDNode>(N->getOperand(1));
  10727. if (!AndC)
  10728. return SDValue();
  10729. const APInt &Mask = AndC->getAPIntValue();
  10730. unsigned ActiveBits = 0;
  10731. if (Mask.isMask()) {
  10732. ActiveBits = Mask.countTrailingOnes();
  10733. } else if (Mask.isShiftedMask()) {
  10734. ShAmt = Mask.countTrailingZeros();
  10735. APInt ShiftedMask = Mask.lshr(ShAmt);
  10736. ActiveBits = ShiftedMask.countTrailingOnes();
  10737. HasShiftedOffset = true;
  10738. } else
  10739. return SDValue();
  10740. ExtType = ISD::ZEXTLOAD;
  10741. ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
  10742. }
  10743. // In case Opc==SRL we've already prepared ExtVT/ExtType/ShAmt based on doing
  10744. // a right shift. Here we redo some of those checks, to possibly adjust the
  10745. // ExtVT even further based on "a masking AND". We could also end up here for
  10746. // other reasons (e.g. based on Opc==TRUNCATE) and that is why some checks
  10747. // need to be done here as well.
  10748. if (Opc == ISD::SRL || N0.getOpcode() == ISD::SRL) {
  10749. SDValue SRL = Opc == ISD::SRL ? SDValue(N, 0) : N0;
  10750. // Bail out when the SRL has more than one use. This is done for historical
  10751. // (undocumented) reasons. Maybe intent was to guard the AND-masking below
  10752. // check below? And maybe it could be non-profitable to do the transform in
  10753. // case the SRL has multiple uses and we get here with Opc!=ISD::SRL?
  10754. // FIXME: Can't we just skip this check for the Opc==ISD::SRL case.
  10755. if (!SRL.hasOneUse())
  10756. return SDValue();
  10757. // Only handle shift with constant shift amount, and the shiftee must be a
  10758. // load.
  10759. auto *LN = dyn_cast<LoadSDNode>(SRL.getOperand(0));
  10760. auto *SRL1C = dyn_cast<ConstantSDNode>(SRL.getOperand(1));
  10761. if (!SRL1C || !LN)
  10762. return SDValue();
  10763. // If the shift amount is larger than the input type then we're not
  10764. // accessing any of the loaded bytes. If the load was a zextload/extload
  10765. // then the result of the shift+trunc is zero/undef (handled elsewhere).
  10766. ShAmt = SRL1C->getZExtValue();
  10767. uint64_t MemoryWidth = LN->getMemoryVT().getSizeInBits();
  10768. if (ShAmt >= MemoryWidth)
  10769. return SDValue();
  10770. // Because a SRL must be assumed to *need* to zero-extend the high bits
  10771. // (as opposed to anyext the high bits), we can't combine the zextload
  10772. // lowering of SRL and an sextload.
  10773. if (LN->getExtensionType() == ISD::SEXTLOAD)
  10774. return SDValue();
  10775. // Avoid reading outside the memory accessed by the original load (could
  10776. // happened if we only adjust the load base pointer by ShAmt). Instead we
  10777. // try to narrow the load even further. The typical scenario here is:
  10778. // (i64 (truncate (i96 (srl (load x), 64)))) ->
  10779. // (i64 (truncate (i96 (zextload (load i32 + offset) from i32))))
  10780. if (ExtVT.getScalarSizeInBits() > MemoryWidth - ShAmt) {
  10781. // Don't replace sextload by zextload.
  10782. if (ExtType == ISD::SEXTLOAD)
  10783. return SDValue();
  10784. // Narrow the load.
  10785. ExtType = ISD::ZEXTLOAD;
  10786. ExtVT = EVT::getIntegerVT(*DAG.getContext(), MemoryWidth - ShAmt);
  10787. }
  10788. // If the SRL is only used by a masking AND, we may be able to adjust
  10789. // the ExtVT to make the AND redundant.
  10790. SDNode *Mask = *(SRL->use_begin());
  10791. if (SRL.hasOneUse() && Mask->getOpcode() == ISD::AND &&
  10792. isa<ConstantSDNode>(Mask->getOperand(1))) {
  10793. const APInt& ShiftMask = Mask->getConstantOperandAPInt(1);
  10794. if (ShiftMask.isMask()) {
  10795. EVT MaskedVT = EVT::getIntegerVT(*DAG.getContext(),
  10796. ShiftMask.countTrailingOnes());
  10797. // If the mask is smaller, recompute the type.
  10798. if ((ExtVT.getScalarSizeInBits() > MaskedVT.getScalarSizeInBits()) &&
  10799. TLI.isLoadExtLegal(ExtType, SRL.getValueType(), MaskedVT))
  10800. ExtVT = MaskedVT;
  10801. }
  10802. }
  10803. N0 = SRL.getOperand(0);
  10804. }
  10805. // If the load is shifted left (and the result isn't shifted back right), we
  10806. // can fold a truncate through the shift. The typical scenario is that N
  10807. // points at a TRUNCATE here so the attempted fold is:
  10808. // (truncate (shl (load x), c))) -> (shl (narrow load x), c)
  10809. // ShLeftAmt will indicate how much a narrowed load should be shifted left.
  10810. unsigned ShLeftAmt = 0;
  10811. if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
  10812. ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
  10813. if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
  10814. ShLeftAmt = N01->getZExtValue();
  10815. N0 = N0.getOperand(0);
  10816. }
  10817. }
  10818. // If we haven't found a load, we can't narrow it.
  10819. if (!isa<LoadSDNode>(N0))
  10820. return SDValue();
  10821. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  10822. // Reducing the width of a volatile load is illegal. For atomics, we may be
  10823. // able to reduce the width provided we never widen again. (see D66309)
  10824. if (!LN0->isSimple() ||
  10825. !isLegalNarrowLdSt(LN0, ExtType, ExtVT, ShAmt))
  10826. return SDValue();
  10827. auto AdjustBigEndianShift = [&](unsigned ShAmt) {
  10828. unsigned LVTStoreBits =
  10829. LN0->getMemoryVT().getStoreSizeInBits().getFixedSize();
  10830. unsigned EVTStoreBits = ExtVT.getStoreSizeInBits().getFixedSize();
  10831. return LVTStoreBits - EVTStoreBits - ShAmt;
  10832. };
  10833. // We need to adjust the pointer to the load by ShAmt bits in order to load
  10834. // the correct bytes.
  10835. unsigned PtrAdjustmentInBits =
  10836. DAG.getDataLayout().isBigEndian() ? AdjustBigEndianShift(ShAmt) : ShAmt;
  10837. uint64_t PtrOff = PtrAdjustmentInBits / 8;
  10838. Align NewAlign = commonAlignment(LN0->getAlign(), PtrOff);
  10839. SDLoc DL(LN0);
  10840. // The original load itself didn't wrap, so an offset within it doesn't.
  10841. SDNodeFlags Flags;
  10842. Flags.setNoUnsignedWrap(true);
  10843. SDValue NewPtr = DAG.getMemBasePlusOffset(LN0->getBasePtr(),
  10844. TypeSize::Fixed(PtrOff), DL, Flags);
  10845. AddToWorklist(NewPtr.getNode());
  10846. SDValue Load;
  10847. if (ExtType == ISD::NON_EXTLOAD)
  10848. Load = DAG.getLoad(VT, DL, LN0->getChain(), NewPtr,
  10849. LN0->getPointerInfo().getWithOffset(PtrOff), NewAlign,
  10850. LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
  10851. else
  10852. Load = DAG.getExtLoad(ExtType, DL, VT, LN0->getChain(), NewPtr,
  10853. LN0->getPointerInfo().getWithOffset(PtrOff), ExtVT,
  10854. NewAlign, LN0->getMemOperand()->getFlags(),
  10855. LN0->getAAInfo());
  10856. // Replace the old load's chain with the new load's chain.
  10857. WorklistRemover DeadNodes(*this);
  10858. DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
  10859. // Shift the result left, if we've swallowed a left shift.
  10860. SDValue Result = Load;
  10861. if (ShLeftAmt != 0) {
  10862. EVT ShImmTy = getShiftAmountTy(Result.getValueType());
  10863. if (!isUIntN(ShImmTy.getScalarSizeInBits(), ShLeftAmt))
  10864. ShImmTy = VT;
  10865. // If the shift amount is as large as the result size (but, presumably,
  10866. // no larger than the source) then the useful bits of the result are
  10867. // zero; we can't simply return the shortened shift, because the result
  10868. // of that operation is undefined.
  10869. if (ShLeftAmt >= VT.getScalarSizeInBits())
  10870. Result = DAG.getConstant(0, DL, VT);
  10871. else
  10872. Result = DAG.getNode(ISD::SHL, DL, VT,
  10873. Result, DAG.getConstant(ShLeftAmt, DL, ShImmTy));
  10874. }
  10875. if (HasShiftedOffset) {
  10876. // We're using a shifted mask, so the load now has an offset. This means
  10877. // that data has been loaded into the lower bytes than it would have been
  10878. // before, so we need to shl the loaded data into the correct position in the
  10879. // register.
  10880. SDValue ShiftC = DAG.getConstant(ShAmt, DL, VT);
  10881. Result = DAG.getNode(ISD::SHL, DL, VT, Result, ShiftC);
  10882. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
  10883. }
  10884. // Return the new loaded value.
  10885. return Result;
  10886. }
  10887. SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
  10888. SDValue N0 = N->getOperand(0);
  10889. SDValue N1 = N->getOperand(1);
  10890. EVT VT = N->getValueType(0);
  10891. EVT ExtVT = cast<VTSDNode>(N1)->getVT();
  10892. unsigned VTBits = VT.getScalarSizeInBits();
  10893. unsigned ExtVTBits = ExtVT.getScalarSizeInBits();
  10894. // sext_vector_inreg(undef) = 0 because the top bit will all be the same.
  10895. if (N0.isUndef())
  10896. return DAG.getConstant(0, SDLoc(N), VT);
  10897. // fold (sext_in_reg c1) -> c1
  10898. if (DAG.isConstantIntBuildVectorOrConstantInt(N0))
  10899. return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0, N1);
  10900. // If the input is already sign extended, just drop the extension.
  10901. if (ExtVTBits >= DAG.ComputeMaxSignificantBits(N0))
  10902. return N0;
  10903. // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
  10904. if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
  10905. ExtVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT()))
  10906. return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, N0.getOperand(0),
  10907. N1);
  10908. // fold (sext_in_reg (sext x)) -> (sext x)
  10909. // fold (sext_in_reg (aext x)) -> (sext x)
  10910. // if x is small enough or if we know that x has more than 1 sign bit and the
  10911. // sign_extend_inreg is extending from one of them.
  10912. if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
  10913. SDValue N00 = N0.getOperand(0);
  10914. unsigned N00Bits = N00.getScalarValueSizeInBits();
  10915. if ((N00Bits <= ExtVTBits ||
  10916. DAG.ComputeMaxSignificantBits(N00) <= ExtVTBits) &&
  10917. (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
  10918. return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00);
  10919. }
  10920. // fold (sext_in_reg (*_extend_vector_inreg x)) -> (sext_vector_inreg x)
  10921. // if x is small enough or if we know that x has more than 1 sign bit and the
  10922. // sign_extend_inreg is extending from one of them.
  10923. if (N0.getOpcode() == ISD::ANY_EXTEND_VECTOR_INREG ||
  10924. N0.getOpcode() == ISD::SIGN_EXTEND_VECTOR_INREG ||
  10925. N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG) {
  10926. SDValue N00 = N0.getOperand(0);
  10927. unsigned N00Bits = N00.getScalarValueSizeInBits();
  10928. unsigned DstElts = N0.getValueType().getVectorMinNumElements();
  10929. unsigned SrcElts = N00.getValueType().getVectorMinNumElements();
  10930. bool IsZext = N0.getOpcode() == ISD::ZERO_EXTEND_VECTOR_INREG;
  10931. APInt DemandedSrcElts = APInt::getLowBitsSet(SrcElts, DstElts);
  10932. if ((N00Bits == ExtVTBits ||
  10933. (!IsZext && (N00Bits < ExtVTBits ||
  10934. DAG.ComputeMaxSignificantBits(N00) <= ExtVTBits))) &&
  10935. (!LegalOperations ||
  10936. TLI.isOperationLegal(ISD::SIGN_EXTEND_VECTOR_INREG, VT)))
  10937. return DAG.getNode(ISD::SIGN_EXTEND_VECTOR_INREG, SDLoc(N), VT, N00);
  10938. }
  10939. // fold (sext_in_reg (zext x)) -> (sext x)
  10940. // iff we are extending the source sign bit.
  10941. if (N0.getOpcode() == ISD::ZERO_EXTEND) {
  10942. SDValue N00 = N0.getOperand(0);
  10943. if (N00.getScalarValueSizeInBits() == ExtVTBits &&
  10944. (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
  10945. return DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, N00, N1);
  10946. }
  10947. // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
  10948. if (DAG.MaskedValueIsZero(N0, APInt::getOneBitSet(VTBits, ExtVTBits - 1)))
  10949. return DAG.getZeroExtendInReg(N0, SDLoc(N), ExtVT);
  10950. // fold operands of sext_in_reg based on knowledge that the top bits are not
  10951. // demanded.
  10952. if (SimplifyDemandedBits(SDValue(N, 0)))
  10953. return SDValue(N, 0);
  10954. // fold (sext_in_reg (load x)) -> (smaller sextload x)
  10955. // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
  10956. if (SDValue NarrowLoad = reduceLoadWidth(N))
  10957. return NarrowLoad;
  10958. // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
  10959. // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
  10960. // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
  10961. if (N0.getOpcode() == ISD::SRL) {
  10962. if (auto *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
  10963. if (ShAmt->getAPIntValue().ule(VTBits - ExtVTBits)) {
  10964. // We can turn this into an SRA iff the input to the SRL is already sign
  10965. // extended enough.
  10966. unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
  10967. if (((VTBits - ExtVTBits) - ShAmt->getZExtValue()) < InSignBits)
  10968. return DAG.getNode(ISD::SRA, SDLoc(N), VT, N0.getOperand(0),
  10969. N0.getOperand(1));
  10970. }
  10971. }
  10972. // fold (sext_inreg (extload x)) -> (sextload x)
  10973. // If sextload is not supported by target, we can only do the combine when
  10974. // load has one use. Doing otherwise can block folding the extload with other
  10975. // extends that the target does support.
  10976. if (ISD::isEXTLoad(N0.getNode()) &&
  10977. ISD::isUNINDEXEDLoad(N0.getNode()) &&
  10978. ExtVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
  10979. ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple() &&
  10980. N0.hasOneUse()) ||
  10981. TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT))) {
  10982. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  10983. SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
  10984. LN0->getChain(),
  10985. LN0->getBasePtr(), ExtVT,
  10986. LN0->getMemOperand());
  10987. CombineTo(N, ExtLoad);
  10988. CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
  10989. AddToWorklist(ExtLoad.getNode());
  10990. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  10991. }
  10992. // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
  10993. if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
  10994. N0.hasOneUse() &&
  10995. ExtVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
  10996. ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple()) &&
  10997. TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT))) {
  10998. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  10999. SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, SDLoc(N), VT,
  11000. LN0->getChain(),
  11001. LN0->getBasePtr(), ExtVT,
  11002. LN0->getMemOperand());
  11003. CombineTo(N, ExtLoad);
  11004. CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
  11005. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  11006. }
  11007. // fold (sext_inreg (masked_load x)) -> (sext_masked_load x)
  11008. // ignore it if the masked load is already sign extended
  11009. if (MaskedLoadSDNode *Ld = dyn_cast<MaskedLoadSDNode>(N0)) {
  11010. if (ExtVT == Ld->getMemoryVT() && N0.hasOneUse() &&
  11011. Ld->getExtensionType() != ISD::LoadExtType::NON_EXTLOAD &&
  11012. TLI.isLoadExtLegal(ISD::SEXTLOAD, VT, ExtVT)) {
  11013. SDValue ExtMaskedLoad = DAG.getMaskedLoad(
  11014. VT, SDLoc(N), Ld->getChain(), Ld->getBasePtr(), Ld->getOffset(),
  11015. Ld->getMask(), Ld->getPassThru(), ExtVT, Ld->getMemOperand(),
  11016. Ld->getAddressingMode(), ISD::SEXTLOAD, Ld->isExpandingLoad());
  11017. CombineTo(N, ExtMaskedLoad);
  11018. CombineTo(N0.getNode(), ExtMaskedLoad, ExtMaskedLoad.getValue(1));
  11019. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  11020. }
  11021. }
  11022. // fold (sext_inreg (masked_gather x)) -> (sext_masked_gather x)
  11023. if (auto *GN0 = dyn_cast<MaskedGatherSDNode>(N0)) {
  11024. if (SDValue(GN0, 0).hasOneUse() &&
  11025. ExtVT == GN0->getMemoryVT() &&
  11026. TLI.isVectorLoadExtDesirable(SDValue(SDValue(GN0, 0)))) {
  11027. SDValue Ops[] = {GN0->getChain(), GN0->getPassThru(), GN0->getMask(),
  11028. GN0->getBasePtr(), GN0->getIndex(), GN0->getScale()};
  11029. SDValue ExtLoad = DAG.getMaskedGather(
  11030. DAG.getVTList(VT, MVT::Other), ExtVT, SDLoc(N), Ops,
  11031. GN0->getMemOperand(), GN0->getIndexType(), ISD::SEXTLOAD);
  11032. CombineTo(N, ExtLoad);
  11033. CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
  11034. AddToWorklist(ExtLoad.getNode());
  11035. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  11036. }
  11037. }
  11038. // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
  11039. if (ExtVTBits <= 16 && N0.getOpcode() == ISD::OR) {
  11040. if (SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
  11041. N0.getOperand(1), false))
  11042. return DAG.getNode(ISD::SIGN_EXTEND_INREG, SDLoc(N), VT, BSwap, N1);
  11043. }
  11044. return SDValue();
  11045. }
  11046. SDValue DAGCombiner::visitEXTEND_VECTOR_INREG(SDNode *N) {
  11047. SDValue N0 = N->getOperand(0);
  11048. EVT VT = N->getValueType(0);
  11049. // {s/z}ext_vector_inreg(undef) = 0 because the top bits must be the same.
  11050. if (N0.isUndef())
  11051. return DAG.getConstant(0, SDLoc(N), VT);
  11052. if (SDValue Res = tryToFoldExtendOfConstant(N, TLI, DAG, LegalTypes))
  11053. return Res;
  11054. if (SimplifyDemandedVectorElts(SDValue(N, 0)))
  11055. return SDValue(N, 0);
  11056. return SDValue();
  11057. }
  11058. SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
  11059. SDValue N0 = N->getOperand(0);
  11060. EVT VT = N->getValueType(0);
  11061. EVT SrcVT = N0.getValueType();
  11062. bool isLE = DAG.getDataLayout().isLittleEndian();
  11063. // noop truncate
  11064. if (SrcVT == VT)
  11065. return N0;
  11066. // fold (truncate (truncate x)) -> (truncate x)
  11067. if (N0.getOpcode() == ISD::TRUNCATE)
  11068. return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
  11069. // fold (truncate c1) -> c1
  11070. if (DAG.isConstantIntBuildVectorOrConstantInt(N0)) {
  11071. SDValue C = DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0);
  11072. if (C.getNode() != N)
  11073. return C;
  11074. }
  11075. // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
  11076. if (N0.getOpcode() == ISD::ZERO_EXTEND ||
  11077. N0.getOpcode() == ISD::SIGN_EXTEND ||
  11078. N0.getOpcode() == ISD::ANY_EXTEND) {
  11079. // if the source is smaller than the dest, we still need an extend.
  11080. if (N0.getOperand(0).getValueType().bitsLT(VT))
  11081. return DAG.getNode(N0.getOpcode(), SDLoc(N), VT, N0.getOperand(0));
  11082. // if the source is larger than the dest, than we just need the truncate.
  11083. if (N0.getOperand(0).getValueType().bitsGT(VT))
  11084. return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, N0.getOperand(0));
  11085. // if the source and dest are the same type, we can drop both the extend
  11086. // and the truncate.
  11087. return N0.getOperand(0);
  11088. }
  11089. // If this is anyext(trunc), don't fold it, allow ourselves to be folded.
  11090. if (N->hasOneUse() && (N->use_begin()->getOpcode() == ISD::ANY_EXTEND))
  11091. return SDValue();
  11092. // Fold extract-and-trunc into a narrow extract. For example:
  11093. // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
  11094. // i32 y = TRUNCATE(i64 x)
  11095. // -- becomes --
  11096. // v16i8 b = BITCAST (v2i64 val)
  11097. // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
  11098. //
  11099. // Note: We only run this optimization after type legalization (which often
  11100. // creates this pattern) and before operation legalization after which
  11101. // we need to be more careful about the vector instructions that we generate.
  11102. if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  11103. LegalTypes && !LegalOperations && N0->hasOneUse() && VT != MVT::i1) {
  11104. EVT VecTy = N0.getOperand(0).getValueType();
  11105. EVT ExTy = N0.getValueType();
  11106. EVT TrTy = N->getValueType(0);
  11107. auto EltCnt = VecTy.getVectorElementCount();
  11108. unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
  11109. auto NewEltCnt = EltCnt * SizeRatio;
  11110. EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, NewEltCnt);
  11111. assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
  11112. SDValue EltNo = N0->getOperand(1);
  11113. if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
  11114. int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
  11115. int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
  11116. SDLoc DL(N);
  11117. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, TrTy,
  11118. DAG.getBitcast(NVT, N0.getOperand(0)),
  11119. DAG.getVectorIdxConstant(Index, DL));
  11120. }
  11121. }
  11122. // trunc (select c, a, b) -> select c, (trunc a), (trunc b)
  11123. if (N0.getOpcode() == ISD::SELECT && N0.hasOneUse()) {
  11124. if ((!LegalOperations || TLI.isOperationLegal(ISD::SELECT, SrcVT)) &&
  11125. TLI.isTruncateFree(SrcVT, VT)) {
  11126. SDLoc SL(N0);
  11127. SDValue Cond = N0.getOperand(0);
  11128. SDValue TruncOp0 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
  11129. SDValue TruncOp1 = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(2));
  11130. return DAG.getNode(ISD::SELECT, SDLoc(N), VT, Cond, TruncOp0, TruncOp1);
  11131. }
  11132. }
  11133. // trunc (shl x, K) -> shl (trunc x), K => K < VT.getScalarSizeInBits()
  11134. if (N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
  11135. (!LegalOperations || TLI.isOperationLegal(ISD::SHL, VT)) &&
  11136. TLI.isTypeDesirableForOp(ISD::SHL, VT)) {
  11137. SDValue Amt = N0.getOperand(1);
  11138. KnownBits Known = DAG.computeKnownBits(Amt);
  11139. unsigned Size = VT.getScalarSizeInBits();
  11140. if (Known.countMaxActiveBits() <= Log2_32(Size)) {
  11141. SDLoc SL(N);
  11142. EVT AmtVT = TLI.getShiftAmountTy(VT, DAG.getDataLayout());
  11143. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
  11144. if (AmtVT != Amt.getValueType()) {
  11145. Amt = DAG.getZExtOrTrunc(Amt, SL, AmtVT);
  11146. AddToWorklist(Amt.getNode());
  11147. }
  11148. return DAG.getNode(ISD::SHL, SL, VT, Trunc, Amt);
  11149. }
  11150. }
  11151. if (SDValue V = foldSubToUSubSat(VT, N0.getNode()))
  11152. return V;
  11153. // Attempt to pre-truncate BUILD_VECTOR sources.
  11154. if (N0.getOpcode() == ISD::BUILD_VECTOR && !LegalOperations &&
  11155. TLI.isTruncateFree(SrcVT.getScalarType(), VT.getScalarType()) &&
  11156. // Avoid creating illegal types if running after type legalizer.
  11157. (!LegalTypes || TLI.isTypeLegal(VT.getScalarType()))) {
  11158. SDLoc DL(N);
  11159. EVT SVT = VT.getScalarType();
  11160. SmallVector<SDValue, 8> TruncOps;
  11161. for (const SDValue &Op : N0->op_values()) {
  11162. SDValue TruncOp = DAG.getNode(ISD::TRUNCATE, DL, SVT, Op);
  11163. TruncOps.push_back(TruncOp);
  11164. }
  11165. return DAG.getBuildVector(VT, DL, TruncOps);
  11166. }
  11167. // Fold a series of buildvector, bitcast, and truncate if possible.
  11168. // For example fold
  11169. // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
  11170. // (2xi32 (buildvector x, y)).
  11171. if (Level == AfterLegalizeVectorOps && VT.isVector() &&
  11172. N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
  11173. N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
  11174. N0.getOperand(0).hasOneUse()) {
  11175. SDValue BuildVect = N0.getOperand(0);
  11176. EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
  11177. EVT TruncVecEltTy = VT.getVectorElementType();
  11178. // Check that the element types match.
  11179. if (BuildVectEltTy == TruncVecEltTy) {
  11180. // Now we only need to compute the offset of the truncated elements.
  11181. unsigned BuildVecNumElts = BuildVect.getNumOperands();
  11182. unsigned TruncVecNumElts = VT.getVectorNumElements();
  11183. unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
  11184. assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
  11185. "Invalid number of elements");
  11186. SmallVector<SDValue, 8> Opnds;
  11187. for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
  11188. Opnds.push_back(BuildVect.getOperand(i));
  11189. return DAG.getBuildVector(VT, SDLoc(N), Opnds);
  11190. }
  11191. }
  11192. // See if we can simplify the input to this truncate through knowledge that
  11193. // only the low bits are being used.
  11194. // For example "trunc (or (shl x, 8), y)" // -> trunc y
  11195. // Currently we only perform this optimization on scalars because vectors
  11196. // may have different active low bits.
  11197. if (!VT.isVector()) {
  11198. APInt Mask =
  11199. APInt::getLowBitsSet(N0.getValueSizeInBits(), VT.getSizeInBits());
  11200. if (SDValue Shorter = DAG.GetDemandedBits(N0, Mask))
  11201. return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Shorter);
  11202. }
  11203. // fold (truncate (load x)) -> (smaller load x)
  11204. // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
  11205. if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
  11206. if (SDValue Reduced = reduceLoadWidth(N))
  11207. return Reduced;
  11208. // Handle the case where the load remains an extending load even
  11209. // after truncation.
  11210. if (N0.hasOneUse() && ISD::isUNINDEXEDLoad(N0.getNode())) {
  11211. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  11212. if (LN0->isSimple() && LN0->getMemoryVT().bitsLT(VT)) {
  11213. SDValue NewLoad = DAG.getExtLoad(LN0->getExtensionType(), SDLoc(LN0),
  11214. VT, LN0->getChain(), LN0->getBasePtr(),
  11215. LN0->getMemoryVT(),
  11216. LN0->getMemOperand());
  11217. DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLoad.getValue(1));
  11218. return NewLoad;
  11219. }
  11220. }
  11221. }
  11222. // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
  11223. // where ... are all 'undef'.
  11224. if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
  11225. SmallVector<EVT, 8> VTs;
  11226. SDValue V;
  11227. unsigned Idx = 0;
  11228. unsigned NumDefs = 0;
  11229. for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
  11230. SDValue X = N0.getOperand(i);
  11231. if (!X.isUndef()) {
  11232. V = X;
  11233. Idx = i;
  11234. NumDefs++;
  11235. }
  11236. // Stop if more than one members are non-undef.
  11237. if (NumDefs > 1)
  11238. break;
  11239. VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
  11240. VT.getVectorElementType(),
  11241. X.getValueType().getVectorElementCount()));
  11242. }
  11243. if (NumDefs == 0)
  11244. return DAG.getUNDEF(VT);
  11245. if (NumDefs == 1) {
  11246. assert(V.getNode() && "The single defined operand is empty!");
  11247. SmallVector<SDValue, 8> Opnds;
  11248. for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
  11249. if (i != Idx) {
  11250. Opnds.push_back(DAG.getUNDEF(VTs[i]));
  11251. continue;
  11252. }
  11253. SDValue NV = DAG.getNode(ISD::TRUNCATE, SDLoc(V), VTs[i], V);
  11254. AddToWorklist(NV.getNode());
  11255. Opnds.push_back(NV);
  11256. }
  11257. return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Opnds);
  11258. }
  11259. }
  11260. // Fold truncate of a bitcast of a vector to an extract of the low vector
  11261. // element.
  11262. //
  11263. // e.g. trunc (i64 (bitcast v2i32:x)) -> extract_vector_elt v2i32:x, idx
  11264. if (N0.getOpcode() == ISD::BITCAST && !VT.isVector()) {
  11265. SDValue VecSrc = N0.getOperand(0);
  11266. EVT VecSrcVT = VecSrc.getValueType();
  11267. if (VecSrcVT.isVector() && VecSrcVT.getScalarType() == VT &&
  11268. (!LegalOperations ||
  11269. TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecSrcVT))) {
  11270. SDLoc SL(N);
  11271. unsigned Idx = isLE ? 0 : VecSrcVT.getVectorNumElements() - 1;
  11272. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL, VT, VecSrc,
  11273. DAG.getVectorIdxConstant(Idx, SL));
  11274. }
  11275. }
  11276. // Simplify the operands using demanded-bits information.
  11277. if (SimplifyDemandedBits(SDValue(N, 0)))
  11278. return SDValue(N, 0);
  11279. // (trunc adde(X, Y, Carry)) -> (adde trunc(X), trunc(Y), Carry)
  11280. // (trunc addcarry(X, Y, Carry)) -> (addcarry trunc(X), trunc(Y), Carry)
  11281. // When the adde's carry is not used.
  11282. if ((N0.getOpcode() == ISD::ADDE || N0.getOpcode() == ISD::ADDCARRY) &&
  11283. N0.hasOneUse() && !N0.getNode()->hasAnyUseOfValue(1) &&
  11284. // We only do for addcarry before legalize operation
  11285. ((!LegalOperations && N0.getOpcode() == ISD::ADDCARRY) ||
  11286. TLI.isOperationLegal(N0.getOpcode(), VT))) {
  11287. SDLoc SL(N);
  11288. auto X = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(0));
  11289. auto Y = DAG.getNode(ISD::TRUNCATE, SL, VT, N0.getOperand(1));
  11290. auto VTs = DAG.getVTList(VT, N0->getValueType(1));
  11291. return DAG.getNode(N0.getOpcode(), SL, VTs, X, Y, N0.getOperand(2));
  11292. }
  11293. // fold (truncate (extract_subvector(ext x))) ->
  11294. // (extract_subvector x)
  11295. // TODO: This can be generalized to cover cases where the truncate and extract
  11296. // do not fully cancel each other out.
  11297. if (!LegalTypes && N0.getOpcode() == ISD::EXTRACT_SUBVECTOR) {
  11298. SDValue N00 = N0.getOperand(0);
  11299. if (N00.getOpcode() == ISD::SIGN_EXTEND ||
  11300. N00.getOpcode() == ISD::ZERO_EXTEND ||
  11301. N00.getOpcode() == ISD::ANY_EXTEND) {
  11302. if (N00.getOperand(0)->getValueType(0).getVectorElementType() ==
  11303. VT.getVectorElementType())
  11304. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N0->getOperand(0)), VT,
  11305. N00.getOperand(0), N0.getOperand(1));
  11306. }
  11307. }
  11308. if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
  11309. return NewVSel;
  11310. // Narrow a suitable binary operation with a non-opaque constant operand by
  11311. // moving it ahead of the truncate. This is limited to pre-legalization
  11312. // because targets may prefer a wider type during later combines and invert
  11313. // this transform.
  11314. switch (N0.getOpcode()) {
  11315. case ISD::ADD:
  11316. case ISD::SUB:
  11317. case ISD::MUL:
  11318. case ISD::AND:
  11319. case ISD::OR:
  11320. case ISD::XOR:
  11321. if (!LegalOperations && N0.hasOneUse() &&
  11322. (isConstantOrConstantVector(N0.getOperand(0), true) ||
  11323. isConstantOrConstantVector(N0.getOperand(1), true))) {
  11324. // TODO: We already restricted this to pre-legalization, but for vectors
  11325. // we are extra cautious to not create an unsupported operation.
  11326. // Target-specific changes are likely needed to avoid regressions here.
  11327. if (VT.isScalarInteger() || TLI.isOperationLegal(N0.getOpcode(), VT)) {
  11328. SDLoc DL(N);
  11329. SDValue NarrowL = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(0));
  11330. SDValue NarrowR = DAG.getNode(ISD::TRUNCATE, DL, VT, N0.getOperand(1));
  11331. return DAG.getNode(N0.getOpcode(), DL, VT, NarrowL, NarrowR);
  11332. }
  11333. }
  11334. break;
  11335. case ISD::USUBSAT:
  11336. // Truncate the USUBSAT only if LHS is a known zero-extension, its not
  11337. // enough to know that the upper bits are zero we must ensure that we don't
  11338. // introduce an extra truncate.
  11339. if (!LegalOperations && N0.hasOneUse() &&
  11340. N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
  11341. N0.getOperand(0).getOperand(0).getScalarValueSizeInBits() <=
  11342. VT.getScalarSizeInBits() &&
  11343. hasOperation(N0.getOpcode(), VT)) {
  11344. return getTruncatedUSUBSAT(VT, SrcVT, N0.getOperand(0), N0.getOperand(1),
  11345. DAG, SDLoc(N));
  11346. }
  11347. break;
  11348. }
  11349. return SDValue();
  11350. }
  11351. static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
  11352. SDValue Elt = N->getOperand(i);
  11353. if (Elt.getOpcode() != ISD::MERGE_VALUES)
  11354. return Elt.getNode();
  11355. return Elt.getOperand(Elt.getResNo()).getNode();
  11356. }
  11357. /// build_pair (load, load) -> load
  11358. /// if load locations are consecutive.
  11359. SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
  11360. assert(N->getOpcode() == ISD::BUILD_PAIR);
  11361. auto *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
  11362. auto *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
  11363. // A BUILD_PAIR is always having the least significant part in elt 0 and the
  11364. // most significant part in elt 1. So when combining into one large load, we
  11365. // need to consider the endianness.
  11366. if (DAG.getDataLayout().isBigEndian())
  11367. std::swap(LD1, LD2);
  11368. if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !ISD::isNON_EXTLoad(LD2) ||
  11369. !LD1->hasOneUse() || !LD2->hasOneUse() ||
  11370. LD1->getAddressSpace() != LD2->getAddressSpace())
  11371. return SDValue();
  11372. bool LD1Fast = false;
  11373. EVT LD1VT = LD1->getValueType(0);
  11374. unsigned LD1Bytes = LD1VT.getStoreSize();
  11375. if ((!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)) &&
  11376. DAG.areNonVolatileConsecutiveLoads(LD2, LD1, LD1Bytes, 1) &&
  11377. TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
  11378. *LD1->getMemOperand(), &LD1Fast) && LD1Fast)
  11379. return DAG.getLoad(VT, SDLoc(N), LD1->getChain(), LD1->getBasePtr(),
  11380. LD1->getPointerInfo(), LD1->getAlign());
  11381. return SDValue();
  11382. }
  11383. static unsigned getPPCf128HiElementSelector(const SelectionDAG &DAG) {
  11384. // On little-endian machines, bitcasting from ppcf128 to i128 does swap the Hi
  11385. // and Lo parts; on big-endian machines it doesn't.
  11386. return DAG.getDataLayout().isBigEndian() ? 1 : 0;
  11387. }
  11388. static SDValue foldBitcastedFPLogic(SDNode *N, SelectionDAG &DAG,
  11389. const TargetLowering &TLI) {
  11390. // If this is not a bitcast to an FP type or if the target doesn't have
  11391. // IEEE754-compliant FP logic, we're done.
  11392. EVT VT = N->getValueType(0);
  11393. if (!VT.isFloatingPoint() || !TLI.hasBitPreservingFPLogic(VT))
  11394. return SDValue();
  11395. // TODO: Handle cases where the integer constant is a different scalar
  11396. // bitwidth to the FP.
  11397. SDValue N0 = N->getOperand(0);
  11398. EVT SourceVT = N0.getValueType();
  11399. if (VT.getScalarSizeInBits() != SourceVT.getScalarSizeInBits())
  11400. return SDValue();
  11401. unsigned FPOpcode;
  11402. APInt SignMask;
  11403. switch (N0.getOpcode()) {
  11404. case ISD::AND:
  11405. FPOpcode = ISD::FABS;
  11406. SignMask = ~APInt::getSignMask(SourceVT.getScalarSizeInBits());
  11407. break;
  11408. case ISD::XOR:
  11409. FPOpcode = ISD::FNEG;
  11410. SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
  11411. break;
  11412. case ISD::OR:
  11413. FPOpcode = ISD::FABS;
  11414. SignMask = APInt::getSignMask(SourceVT.getScalarSizeInBits());
  11415. break;
  11416. default:
  11417. return SDValue();
  11418. }
  11419. // Fold (bitcast int (and (bitcast fp X to int), 0x7fff...) to fp) -> fabs X
  11420. // Fold (bitcast int (xor (bitcast fp X to int), 0x8000...) to fp) -> fneg X
  11421. // Fold (bitcast int (or (bitcast fp X to int), 0x8000...) to fp) ->
  11422. // fneg (fabs X)
  11423. SDValue LogicOp0 = N0.getOperand(0);
  11424. ConstantSDNode *LogicOp1 = isConstOrConstSplat(N0.getOperand(1), true);
  11425. if (LogicOp1 && LogicOp1->getAPIntValue() == SignMask &&
  11426. LogicOp0.getOpcode() == ISD::BITCAST &&
  11427. LogicOp0.getOperand(0).getValueType() == VT) {
  11428. SDValue FPOp = DAG.getNode(FPOpcode, SDLoc(N), VT, LogicOp0.getOperand(0));
  11429. NumFPLogicOpsConv++;
  11430. if (N0.getOpcode() == ISD::OR)
  11431. return DAG.getNode(ISD::FNEG, SDLoc(N), VT, FPOp);
  11432. return FPOp;
  11433. }
  11434. return SDValue();
  11435. }
  11436. SDValue DAGCombiner::visitBITCAST(SDNode *N) {
  11437. SDValue N0 = N->getOperand(0);
  11438. EVT VT = N->getValueType(0);
  11439. if (N0.isUndef())
  11440. return DAG.getUNDEF(VT);
  11441. // If the input is a BUILD_VECTOR with all constant elements, fold this now.
  11442. // Only do this before legalize types, unless both types are integer and the
  11443. // scalar type is legal. Only do this before legalize ops, since the target
  11444. // maybe depending on the bitcast.
  11445. // First check to see if this is all constant.
  11446. // TODO: Support FP bitcasts after legalize types.
  11447. if (VT.isVector() &&
  11448. (!LegalTypes ||
  11449. (!LegalOperations && VT.isInteger() && N0.getValueType().isInteger() &&
  11450. TLI.isTypeLegal(VT.getVectorElementType()))) &&
  11451. N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
  11452. cast<BuildVectorSDNode>(N0)->isConstant())
  11453. return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(),
  11454. VT.getVectorElementType());
  11455. // If the input is a constant, let getNode fold it.
  11456. if (isIntOrFPConstant(N0)) {
  11457. // If we can't allow illegal operations, we need to check that this is just
  11458. // a fp -> int or int -> conversion and that the resulting operation will
  11459. // be legal.
  11460. if (!LegalOperations ||
  11461. (isa<ConstantSDNode>(N0) && VT.isFloatingPoint() && !VT.isVector() &&
  11462. TLI.isOperationLegal(ISD::ConstantFP, VT)) ||
  11463. (isa<ConstantFPSDNode>(N0) && VT.isInteger() && !VT.isVector() &&
  11464. TLI.isOperationLegal(ISD::Constant, VT))) {
  11465. SDValue C = DAG.getBitcast(VT, N0);
  11466. if (C.getNode() != N)
  11467. return C;
  11468. }
  11469. }
  11470. // (conv (conv x, t1), t2) -> (conv x, t2)
  11471. if (N0.getOpcode() == ISD::BITCAST)
  11472. return DAG.getBitcast(VT, N0.getOperand(0));
  11473. // fold (conv (load x)) -> (load (conv*)x)
  11474. // If the resultant load doesn't need a higher alignment than the original!
  11475. if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
  11476. // Do not remove the cast if the types differ in endian layout.
  11477. TLI.hasBigEndianPartOrdering(N0.getValueType(), DAG.getDataLayout()) ==
  11478. TLI.hasBigEndianPartOrdering(VT, DAG.getDataLayout()) &&
  11479. // If the load is volatile, we only want to change the load type if the
  11480. // resulting load is legal. Otherwise we might increase the number of
  11481. // memory accesses. We don't care if the original type was legal or not
  11482. // as we assume software couldn't rely on the number of accesses of an
  11483. // illegal type.
  11484. ((!LegalOperations && cast<LoadSDNode>(N0)->isSimple()) ||
  11485. TLI.isOperationLegal(ISD::LOAD, VT))) {
  11486. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  11487. if (TLI.isLoadBitCastBeneficial(N0.getValueType(), VT, DAG,
  11488. *LN0->getMemOperand())) {
  11489. SDValue Load =
  11490. DAG.getLoad(VT, SDLoc(N), LN0->getChain(), LN0->getBasePtr(),
  11491. LN0->getPointerInfo(), LN0->getAlign(),
  11492. LN0->getMemOperand()->getFlags(), LN0->getAAInfo());
  11493. DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
  11494. return Load;
  11495. }
  11496. }
  11497. if (SDValue V = foldBitcastedFPLogic(N, DAG, TLI))
  11498. return V;
  11499. // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
  11500. // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
  11501. //
  11502. // For ppc_fp128:
  11503. // fold (bitcast (fneg x)) ->
  11504. // flipbit = signbit
  11505. // (xor (bitcast x) (build_pair flipbit, flipbit))
  11506. //
  11507. // fold (bitcast (fabs x)) ->
  11508. // flipbit = (and (extract_element (bitcast x), 0), signbit)
  11509. // (xor (bitcast x) (build_pair flipbit, flipbit))
  11510. // This often reduces constant pool loads.
  11511. if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(N0.getValueType())) ||
  11512. (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(N0.getValueType()))) &&
  11513. N0.getNode()->hasOneUse() && VT.isInteger() &&
  11514. !VT.isVector() && !N0.getValueType().isVector()) {
  11515. SDValue NewConv = DAG.getBitcast(VT, N0.getOperand(0));
  11516. AddToWorklist(NewConv.getNode());
  11517. SDLoc DL(N);
  11518. if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
  11519. assert(VT.getSizeInBits() == 128);
  11520. SDValue SignBit = DAG.getConstant(
  11521. APInt::getSignMask(VT.getSizeInBits() / 2), SDLoc(N0), MVT::i64);
  11522. SDValue FlipBit;
  11523. if (N0.getOpcode() == ISD::FNEG) {
  11524. FlipBit = SignBit;
  11525. AddToWorklist(FlipBit.getNode());
  11526. } else {
  11527. assert(N0.getOpcode() == ISD::FABS);
  11528. SDValue Hi =
  11529. DAG.getNode(ISD::EXTRACT_ELEMENT, SDLoc(NewConv), MVT::i64, NewConv,
  11530. DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
  11531. SDLoc(NewConv)));
  11532. AddToWorklist(Hi.getNode());
  11533. FlipBit = DAG.getNode(ISD::AND, SDLoc(N0), MVT::i64, Hi, SignBit);
  11534. AddToWorklist(FlipBit.getNode());
  11535. }
  11536. SDValue FlipBits =
  11537. DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
  11538. AddToWorklist(FlipBits.getNode());
  11539. return DAG.getNode(ISD::XOR, DL, VT, NewConv, FlipBits);
  11540. }
  11541. APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
  11542. if (N0.getOpcode() == ISD::FNEG)
  11543. return DAG.getNode(ISD::XOR, DL, VT,
  11544. NewConv, DAG.getConstant(SignBit, DL, VT));
  11545. assert(N0.getOpcode() == ISD::FABS);
  11546. return DAG.getNode(ISD::AND, DL, VT,
  11547. NewConv, DAG.getConstant(~SignBit, DL, VT));
  11548. }
  11549. // fold (bitconvert (fcopysign cst, x)) ->
  11550. // (or (and (bitconvert x), sign), (and cst, (not sign)))
  11551. // Note that we don't handle (copysign x, cst) because this can always be
  11552. // folded to an fneg or fabs.
  11553. //
  11554. // For ppc_fp128:
  11555. // fold (bitcast (fcopysign cst, x)) ->
  11556. // flipbit = (and (extract_element
  11557. // (xor (bitcast cst), (bitcast x)), 0),
  11558. // signbit)
  11559. // (xor (bitcast cst) (build_pair flipbit, flipbit))
  11560. if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
  11561. isa<ConstantFPSDNode>(N0.getOperand(0)) &&
  11562. VT.isInteger() && !VT.isVector()) {
  11563. unsigned OrigXWidth = N0.getOperand(1).getValueSizeInBits();
  11564. EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
  11565. if (isTypeLegal(IntXVT)) {
  11566. SDValue X = DAG.getBitcast(IntXVT, N0.getOperand(1));
  11567. AddToWorklist(X.getNode());
  11568. // If X has a different width than the result/lhs, sext it or truncate it.
  11569. unsigned VTWidth = VT.getSizeInBits();
  11570. if (OrigXWidth < VTWidth) {
  11571. X = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(N), VT, X);
  11572. AddToWorklist(X.getNode());
  11573. } else if (OrigXWidth > VTWidth) {
  11574. // To get the sign bit in the right place, we have to shift it right
  11575. // before truncating.
  11576. SDLoc DL(X);
  11577. X = DAG.getNode(ISD::SRL, DL,
  11578. X.getValueType(), X,
  11579. DAG.getConstant(OrigXWidth-VTWidth, DL,
  11580. X.getValueType()));
  11581. AddToWorklist(X.getNode());
  11582. X = DAG.getNode(ISD::TRUNCATE, SDLoc(X), VT, X);
  11583. AddToWorklist(X.getNode());
  11584. }
  11585. if (N0.getValueType() == MVT::ppcf128 && !LegalTypes) {
  11586. APInt SignBit = APInt::getSignMask(VT.getSizeInBits() / 2);
  11587. SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
  11588. AddToWorklist(Cst.getNode());
  11589. SDValue X = DAG.getBitcast(VT, N0.getOperand(1));
  11590. AddToWorklist(X.getNode());
  11591. SDValue XorResult = DAG.getNode(ISD::XOR, SDLoc(N0), VT, Cst, X);
  11592. AddToWorklist(XorResult.getNode());
  11593. SDValue XorResult64 = DAG.getNode(
  11594. ISD::EXTRACT_ELEMENT, SDLoc(XorResult), MVT::i64, XorResult,
  11595. DAG.getIntPtrConstant(getPPCf128HiElementSelector(DAG),
  11596. SDLoc(XorResult)));
  11597. AddToWorklist(XorResult64.getNode());
  11598. SDValue FlipBit =
  11599. DAG.getNode(ISD::AND, SDLoc(XorResult64), MVT::i64, XorResult64,
  11600. DAG.getConstant(SignBit, SDLoc(XorResult64), MVT::i64));
  11601. AddToWorklist(FlipBit.getNode());
  11602. SDValue FlipBits =
  11603. DAG.getNode(ISD::BUILD_PAIR, SDLoc(N0), VT, FlipBit, FlipBit);
  11604. AddToWorklist(FlipBits.getNode());
  11605. return DAG.getNode(ISD::XOR, SDLoc(N), VT, Cst, FlipBits);
  11606. }
  11607. APInt SignBit = APInt::getSignMask(VT.getSizeInBits());
  11608. X = DAG.getNode(ISD::AND, SDLoc(X), VT,
  11609. X, DAG.getConstant(SignBit, SDLoc(X), VT));
  11610. AddToWorklist(X.getNode());
  11611. SDValue Cst = DAG.getBitcast(VT, N0.getOperand(0));
  11612. Cst = DAG.getNode(ISD::AND, SDLoc(Cst), VT,
  11613. Cst, DAG.getConstant(~SignBit, SDLoc(Cst), VT));
  11614. AddToWorklist(Cst.getNode());
  11615. return DAG.getNode(ISD::OR, SDLoc(N), VT, X, Cst);
  11616. }
  11617. }
  11618. // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
  11619. if (N0.getOpcode() == ISD::BUILD_PAIR)
  11620. if (SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT))
  11621. return CombineLD;
  11622. // Remove double bitcasts from shuffles - this is often a legacy of
  11623. // XformToShuffleWithZero being used to combine bitmaskings (of
  11624. // float vectors bitcast to integer vectors) into shuffles.
  11625. // bitcast(shuffle(bitcast(s0),bitcast(s1))) -> shuffle(s0,s1)
  11626. if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT) && VT.isVector() &&
  11627. N0->getOpcode() == ISD::VECTOR_SHUFFLE && N0.hasOneUse() &&
  11628. VT.getVectorNumElements() >= N0.getValueType().getVectorNumElements() &&
  11629. !(VT.getVectorNumElements() % N0.getValueType().getVectorNumElements())) {
  11630. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N0);
  11631. // If operands are a bitcast, peek through if it casts the original VT.
  11632. // If operands are a constant, just bitcast back to original VT.
  11633. auto PeekThroughBitcast = [&](SDValue Op) {
  11634. if (Op.getOpcode() == ISD::BITCAST &&
  11635. Op.getOperand(0).getValueType() == VT)
  11636. return SDValue(Op.getOperand(0));
  11637. if (Op.isUndef() || ISD::isBuildVectorOfConstantSDNodes(Op.getNode()) ||
  11638. ISD::isBuildVectorOfConstantFPSDNodes(Op.getNode()))
  11639. return DAG.getBitcast(VT, Op);
  11640. return SDValue();
  11641. };
  11642. // FIXME: If either input vector is bitcast, try to convert the shuffle to
  11643. // the result type of this bitcast. This would eliminate at least one
  11644. // bitcast. See the transform in InstCombine.
  11645. SDValue SV0 = PeekThroughBitcast(N0->getOperand(0));
  11646. SDValue SV1 = PeekThroughBitcast(N0->getOperand(1));
  11647. if (!(SV0 && SV1))
  11648. return SDValue();
  11649. int MaskScale =
  11650. VT.getVectorNumElements() / N0.getValueType().getVectorNumElements();
  11651. SmallVector<int, 8> NewMask;
  11652. for (int M : SVN->getMask())
  11653. for (int i = 0; i != MaskScale; ++i)
  11654. NewMask.push_back(M < 0 ? -1 : M * MaskScale + i);
  11655. SDValue LegalShuffle =
  11656. TLI.buildLegalVectorShuffle(VT, SDLoc(N), SV0, SV1, NewMask, DAG);
  11657. if (LegalShuffle)
  11658. return LegalShuffle;
  11659. }
  11660. return SDValue();
  11661. }
  11662. SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
  11663. EVT VT = N->getValueType(0);
  11664. return CombineConsecutiveLoads(N, VT);
  11665. }
  11666. SDValue DAGCombiner::visitFREEZE(SDNode *N) {
  11667. SDValue N0 = N->getOperand(0);
  11668. if (DAG.isGuaranteedNotToBeUndefOrPoison(N0, /*PoisonOnly*/ false))
  11669. return N0;
  11670. return SDValue();
  11671. }
  11672. /// We know that BV is a build_vector node with Constant, ConstantFP or Undef
  11673. /// operands. DstEltVT indicates the destination element value type.
  11674. SDValue DAGCombiner::
  11675. ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
  11676. EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
  11677. // If this is already the right type, we're done.
  11678. if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
  11679. unsigned SrcBitSize = SrcEltVT.getSizeInBits();
  11680. unsigned DstBitSize = DstEltVT.getSizeInBits();
  11681. // If this is a conversion of N elements of one type to N elements of another
  11682. // type, convert each element. This handles FP<->INT cases.
  11683. if (SrcBitSize == DstBitSize) {
  11684. SmallVector<SDValue, 8> Ops;
  11685. for (SDValue Op : BV->op_values()) {
  11686. // If the vector element type is not legal, the BUILD_VECTOR operands
  11687. // are promoted and implicitly truncated. Make that explicit here.
  11688. if (Op.getValueType() != SrcEltVT)
  11689. Op = DAG.getNode(ISD::TRUNCATE, SDLoc(BV), SrcEltVT, Op);
  11690. Ops.push_back(DAG.getBitcast(DstEltVT, Op));
  11691. AddToWorklist(Ops.back().getNode());
  11692. }
  11693. EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
  11694. BV->getValueType(0).getVectorNumElements());
  11695. return DAG.getBuildVector(VT, SDLoc(BV), Ops);
  11696. }
  11697. // Otherwise, we're growing or shrinking the elements. To avoid having to
  11698. // handle annoying details of growing/shrinking FP values, we convert them to
  11699. // int first.
  11700. if (SrcEltVT.isFloatingPoint()) {
  11701. // Convert the input float vector to a int vector where the elements are the
  11702. // same sizes.
  11703. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
  11704. BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
  11705. SrcEltVT = IntVT;
  11706. }
  11707. // Now we know the input is an integer vector. If the output is a FP type,
  11708. // convert to integer first, then to FP of the right size.
  11709. if (DstEltVT.isFloatingPoint()) {
  11710. EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
  11711. SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
  11712. // Next, convert to FP elements of the same size.
  11713. return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
  11714. }
  11715. // Okay, we know the src/dst types are both integers of differing types.
  11716. assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
  11717. // TODO: Should ConstantFoldBITCASTofBUILD_VECTOR always take a
  11718. // BuildVectorSDNode?
  11719. auto *BVN = cast<BuildVectorSDNode>(BV);
  11720. // Extract the constant raw bit data.
  11721. BitVector UndefElements;
  11722. SmallVector<APInt> RawBits;
  11723. bool IsLE = DAG.getDataLayout().isLittleEndian();
  11724. if (!BVN->getConstantRawBits(IsLE, DstBitSize, RawBits, UndefElements))
  11725. return SDValue();
  11726. SDLoc DL(BV);
  11727. SmallVector<SDValue, 8> Ops;
  11728. for (unsigned I = 0, E = RawBits.size(); I != E; ++I) {
  11729. if (UndefElements[I])
  11730. Ops.push_back(DAG.getUNDEF(DstEltVT));
  11731. else
  11732. Ops.push_back(DAG.getConstant(RawBits[I], DL, DstEltVT));
  11733. }
  11734. EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
  11735. return DAG.getBuildVector(VT, DL, Ops);
  11736. }
  11737. // Returns true if floating point contraction is allowed on the FMUL-SDValue
  11738. // `N`
  11739. static bool isContractableFMUL(const TargetOptions &Options, SDValue N) {
  11740. assert(N.getOpcode() == ISD::FMUL);
  11741. return Options.AllowFPOpFusion == FPOpFusion::Fast || Options.UnsafeFPMath ||
  11742. N->getFlags().hasAllowContract();
  11743. }
  11744. // Returns true if `N` can assume no infinities involved in its computation.
  11745. static bool hasNoInfs(const TargetOptions &Options, SDValue N) {
  11746. return Options.NoInfsFPMath || N.getNode()->getFlags().hasNoInfs();
  11747. }
  11748. /// Try to perform FMA combining on a given FADD node.
  11749. SDValue DAGCombiner::visitFADDForFMACombine(SDNode *N) {
  11750. SDValue N0 = N->getOperand(0);
  11751. SDValue N1 = N->getOperand(1);
  11752. EVT VT = N->getValueType(0);
  11753. SDLoc SL(N);
  11754. const TargetOptions &Options = DAG.getTarget().Options;
  11755. // Floating-point multiply-add with intermediate rounding.
  11756. bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N));
  11757. // Floating-point multiply-add without intermediate rounding.
  11758. bool HasFMA =
  11759. TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) &&
  11760. (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
  11761. // No valid opcode, do not combine.
  11762. if (!HasFMAD && !HasFMA)
  11763. return SDValue();
  11764. bool CanReassociate =
  11765. Options.UnsafeFPMath || N->getFlags().hasAllowReassociation();
  11766. bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
  11767. Options.UnsafeFPMath || HasFMAD);
  11768. // If the addition is not contractable, do not combine.
  11769. if (!AllowFusionGlobally && !N->getFlags().hasAllowContract())
  11770. return SDValue();
  11771. if (TLI.generateFMAsInMachineCombiner(VT, OptLevel))
  11772. return SDValue();
  11773. // Always prefer FMAD to FMA for precision.
  11774. unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
  11775. bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
  11776. auto isFusedOp = [&](SDValue N) {
  11777. unsigned Opcode = N.getOpcode();
  11778. return Opcode == ISD::FMA || Opcode == ISD::FMAD;
  11779. };
  11780. // Is the node an FMUL and contractable either due to global flags or
  11781. // SDNodeFlags.
  11782. auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
  11783. if (N.getOpcode() != ISD::FMUL)
  11784. return false;
  11785. return AllowFusionGlobally || N->getFlags().hasAllowContract();
  11786. };
  11787. // If we have two choices trying to fold (fadd (fmul u, v), (fmul x, y)),
  11788. // prefer to fold the multiply with fewer uses.
  11789. if (Aggressive && isContractableFMUL(N0) && isContractableFMUL(N1)) {
  11790. if (N0.getNode()->use_size() > N1.getNode()->use_size())
  11791. std::swap(N0, N1);
  11792. }
  11793. // fold (fadd (fmul x, y), z) -> (fma x, y, z)
  11794. if (isContractableFMUL(N0) && (Aggressive || N0->hasOneUse())) {
  11795. return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0),
  11796. N0.getOperand(1), N1);
  11797. }
  11798. // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
  11799. // Note: Commutes FADD operands.
  11800. if (isContractableFMUL(N1) && (Aggressive || N1->hasOneUse())) {
  11801. return DAG.getNode(PreferredFusedOpcode, SL, VT, N1.getOperand(0),
  11802. N1.getOperand(1), N0);
  11803. }
  11804. // fadd (fma A, B, (fmul C, D)), E --> fma A, B, (fma C, D, E)
  11805. // fadd E, (fma A, B, (fmul C, D)) --> fma A, B, (fma C, D, E)
  11806. // This requires reassociation because it changes the order of operations.
  11807. SDValue FMA, E;
  11808. if (CanReassociate && isFusedOp(N0) &&
  11809. N0.getOperand(2).getOpcode() == ISD::FMUL && N0.hasOneUse() &&
  11810. N0.getOperand(2).hasOneUse()) {
  11811. FMA = N0;
  11812. E = N1;
  11813. } else if (CanReassociate && isFusedOp(N1) &&
  11814. N1.getOperand(2).getOpcode() == ISD::FMUL && N1.hasOneUse() &&
  11815. N1.getOperand(2).hasOneUse()) {
  11816. FMA = N1;
  11817. E = N0;
  11818. }
  11819. if (FMA && E) {
  11820. SDValue A = FMA.getOperand(0);
  11821. SDValue B = FMA.getOperand(1);
  11822. SDValue C = FMA.getOperand(2).getOperand(0);
  11823. SDValue D = FMA.getOperand(2).getOperand(1);
  11824. SDValue CDE = DAG.getNode(PreferredFusedOpcode, SL, VT, C, D, E);
  11825. return DAG.getNode(PreferredFusedOpcode, SL, VT, A, B, CDE);
  11826. }
  11827. // Look through FP_EXTEND nodes to do more combining.
  11828. // fold (fadd (fpext (fmul x, y)), z) -> (fma (fpext x), (fpext y), z)
  11829. if (N0.getOpcode() == ISD::FP_EXTEND) {
  11830. SDValue N00 = N0.getOperand(0);
  11831. if (isContractableFMUL(N00) &&
  11832. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  11833. N00.getValueType())) {
  11834. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  11835. DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
  11836. DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
  11837. N1);
  11838. }
  11839. }
  11840. // fold (fadd x, (fpext (fmul y, z))) -> (fma (fpext y), (fpext z), x)
  11841. // Note: Commutes FADD operands.
  11842. if (N1.getOpcode() == ISD::FP_EXTEND) {
  11843. SDValue N10 = N1.getOperand(0);
  11844. if (isContractableFMUL(N10) &&
  11845. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  11846. N10.getValueType())) {
  11847. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  11848. DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0)),
  11849. DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)),
  11850. N0);
  11851. }
  11852. }
  11853. // More folding opportunities when target permits.
  11854. if (Aggressive) {
  11855. // fold (fadd (fma x, y, (fpext (fmul u, v))), z)
  11856. // -> (fma x, y, (fma (fpext u), (fpext v), z))
  11857. auto FoldFAddFMAFPExtFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V,
  11858. SDValue Z) {
  11859. return DAG.getNode(PreferredFusedOpcode, SL, VT, X, Y,
  11860. DAG.getNode(PreferredFusedOpcode, SL, VT,
  11861. DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
  11862. DAG.getNode(ISD::FP_EXTEND, SL, VT, V),
  11863. Z));
  11864. };
  11865. if (isFusedOp(N0)) {
  11866. SDValue N02 = N0.getOperand(2);
  11867. if (N02.getOpcode() == ISD::FP_EXTEND) {
  11868. SDValue N020 = N02.getOperand(0);
  11869. if (isContractableFMUL(N020) &&
  11870. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  11871. N020.getValueType())) {
  11872. return FoldFAddFMAFPExtFMul(N0.getOperand(0), N0.getOperand(1),
  11873. N020.getOperand(0), N020.getOperand(1),
  11874. N1);
  11875. }
  11876. }
  11877. }
  11878. // fold (fadd (fpext (fma x, y, (fmul u, v))), z)
  11879. // -> (fma (fpext x), (fpext y), (fma (fpext u), (fpext v), z))
  11880. // FIXME: This turns two single-precision and one double-precision
  11881. // operation into two double-precision operations, which might not be
  11882. // interesting for all targets, especially GPUs.
  11883. auto FoldFAddFPExtFMAFMul = [&](SDValue X, SDValue Y, SDValue U, SDValue V,
  11884. SDValue Z) {
  11885. return DAG.getNode(
  11886. PreferredFusedOpcode, SL, VT, DAG.getNode(ISD::FP_EXTEND, SL, VT, X),
  11887. DAG.getNode(ISD::FP_EXTEND, SL, VT, Y),
  11888. DAG.getNode(PreferredFusedOpcode, SL, VT,
  11889. DAG.getNode(ISD::FP_EXTEND, SL, VT, U),
  11890. DAG.getNode(ISD::FP_EXTEND, SL, VT, V), Z));
  11891. };
  11892. if (N0.getOpcode() == ISD::FP_EXTEND) {
  11893. SDValue N00 = N0.getOperand(0);
  11894. if (isFusedOp(N00)) {
  11895. SDValue N002 = N00.getOperand(2);
  11896. if (isContractableFMUL(N002) &&
  11897. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  11898. N00.getValueType())) {
  11899. return FoldFAddFPExtFMAFMul(N00.getOperand(0), N00.getOperand(1),
  11900. N002.getOperand(0), N002.getOperand(1),
  11901. N1);
  11902. }
  11903. }
  11904. }
  11905. // fold (fadd x, (fma y, z, (fpext (fmul u, v)))
  11906. // -> (fma y, z, (fma (fpext u), (fpext v), x))
  11907. if (isFusedOp(N1)) {
  11908. SDValue N12 = N1.getOperand(2);
  11909. if (N12.getOpcode() == ISD::FP_EXTEND) {
  11910. SDValue N120 = N12.getOperand(0);
  11911. if (isContractableFMUL(N120) &&
  11912. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  11913. N120.getValueType())) {
  11914. return FoldFAddFMAFPExtFMul(N1.getOperand(0), N1.getOperand(1),
  11915. N120.getOperand(0), N120.getOperand(1),
  11916. N0);
  11917. }
  11918. }
  11919. }
  11920. // fold (fadd x, (fpext (fma y, z, (fmul u, v)))
  11921. // -> (fma (fpext y), (fpext z), (fma (fpext u), (fpext v), x))
  11922. // FIXME: This turns two single-precision and one double-precision
  11923. // operation into two double-precision operations, which might not be
  11924. // interesting for all targets, especially GPUs.
  11925. if (N1.getOpcode() == ISD::FP_EXTEND) {
  11926. SDValue N10 = N1.getOperand(0);
  11927. if (isFusedOp(N10)) {
  11928. SDValue N102 = N10.getOperand(2);
  11929. if (isContractableFMUL(N102) &&
  11930. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  11931. N10.getValueType())) {
  11932. return FoldFAddFPExtFMAFMul(N10.getOperand(0), N10.getOperand(1),
  11933. N102.getOperand(0), N102.getOperand(1),
  11934. N0);
  11935. }
  11936. }
  11937. }
  11938. }
  11939. return SDValue();
  11940. }
  11941. /// Try to perform FMA combining on a given FSUB node.
  11942. SDValue DAGCombiner::visitFSUBForFMACombine(SDNode *N) {
  11943. SDValue N0 = N->getOperand(0);
  11944. SDValue N1 = N->getOperand(1);
  11945. EVT VT = N->getValueType(0);
  11946. SDLoc SL(N);
  11947. const TargetOptions &Options = DAG.getTarget().Options;
  11948. // Floating-point multiply-add with intermediate rounding.
  11949. bool HasFMAD = (LegalOperations && TLI.isFMADLegal(DAG, N));
  11950. // Floating-point multiply-add without intermediate rounding.
  11951. bool HasFMA =
  11952. TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) &&
  11953. (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
  11954. // No valid opcode, do not combine.
  11955. if (!HasFMAD && !HasFMA)
  11956. return SDValue();
  11957. const SDNodeFlags Flags = N->getFlags();
  11958. bool AllowFusionGlobally = (Options.AllowFPOpFusion == FPOpFusion::Fast ||
  11959. Options.UnsafeFPMath || HasFMAD);
  11960. // If the subtraction is not contractable, do not combine.
  11961. if (!AllowFusionGlobally && !N->getFlags().hasAllowContract())
  11962. return SDValue();
  11963. if (TLI.generateFMAsInMachineCombiner(VT, OptLevel))
  11964. return SDValue();
  11965. // Always prefer FMAD to FMA for precision.
  11966. unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
  11967. bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
  11968. bool NoSignedZero = Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros();
  11969. // Is the node an FMUL and contractable either due to global flags or
  11970. // SDNodeFlags.
  11971. auto isContractableFMUL = [AllowFusionGlobally](SDValue N) {
  11972. if (N.getOpcode() != ISD::FMUL)
  11973. return false;
  11974. return AllowFusionGlobally || N->getFlags().hasAllowContract();
  11975. };
  11976. // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
  11977. auto tryToFoldXYSubZ = [&](SDValue XY, SDValue Z) {
  11978. if (isContractableFMUL(XY) && (Aggressive || XY->hasOneUse())) {
  11979. return DAG.getNode(PreferredFusedOpcode, SL, VT, XY.getOperand(0),
  11980. XY.getOperand(1), DAG.getNode(ISD::FNEG, SL, VT, Z));
  11981. }
  11982. return SDValue();
  11983. };
  11984. // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
  11985. // Note: Commutes FSUB operands.
  11986. auto tryToFoldXSubYZ = [&](SDValue X, SDValue YZ) {
  11987. if (isContractableFMUL(YZ) && (Aggressive || YZ->hasOneUse())) {
  11988. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  11989. DAG.getNode(ISD::FNEG, SL, VT, YZ.getOperand(0)),
  11990. YZ.getOperand(1), X);
  11991. }
  11992. return SDValue();
  11993. };
  11994. // If we have two choices trying to fold (fsub (fmul u, v), (fmul x, y)),
  11995. // prefer to fold the multiply with fewer uses.
  11996. if (isContractableFMUL(N0) && isContractableFMUL(N1) &&
  11997. (N0.getNode()->use_size() > N1.getNode()->use_size())) {
  11998. // fold (fsub (fmul a, b), (fmul c, d)) -> (fma (fneg c), d, (fmul a, b))
  11999. if (SDValue V = tryToFoldXSubYZ(N0, N1))
  12000. return V;
  12001. // fold (fsub (fmul a, b), (fmul c, d)) -> (fma a, b, (fneg (fmul c, d)))
  12002. if (SDValue V = tryToFoldXYSubZ(N0, N1))
  12003. return V;
  12004. } else {
  12005. // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
  12006. if (SDValue V = tryToFoldXYSubZ(N0, N1))
  12007. return V;
  12008. // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
  12009. if (SDValue V = tryToFoldXSubYZ(N0, N1))
  12010. return V;
  12011. }
  12012. // fold (fsub (fneg (fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
  12013. if (N0.getOpcode() == ISD::FNEG && isContractableFMUL(N0.getOperand(0)) &&
  12014. (Aggressive || (N0->hasOneUse() && N0.getOperand(0).hasOneUse()))) {
  12015. SDValue N00 = N0.getOperand(0).getOperand(0);
  12016. SDValue N01 = N0.getOperand(0).getOperand(1);
  12017. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  12018. DAG.getNode(ISD::FNEG, SL, VT, N00), N01,
  12019. DAG.getNode(ISD::FNEG, SL, VT, N1));
  12020. }
  12021. // Look through FP_EXTEND nodes to do more combining.
  12022. // fold (fsub (fpext (fmul x, y)), z)
  12023. // -> (fma (fpext x), (fpext y), (fneg z))
  12024. if (N0.getOpcode() == ISD::FP_EXTEND) {
  12025. SDValue N00 = N0.getOperand(0);
  12026. if (isContractableFMUL(N00) &&
  12027. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12028. N00.getValueType())) {
  12029. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  12030. DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
  12031. DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
  12032. DAG.getNode(ISD::FNEG, SL, VT, N1));
  12033. }
  12034. }
  12035. // fold (fsub x, (fpext (fmul y, z)))
  12036. // -> (fma (fneg (fpext y)), (fpext z), x)
  12037. // Note: Commutes FSUB operands.
  12038. if (N1.getOpcode() == ISD::FP_EXTEND) {
  12039. SDValue N10 = N1.getOperand(0);
  12040. if (isContractableFMUL(N10) &&
  12041. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12042. N10.getValueType())) {
  12043. return DAG.getNode(
  12044. PreferredFusedOpcode, SL, VT,
  12045. DAG.getNode(ISD::FNEG, SL, VT,
  12046. DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(0))),
  12047. DAG.getNode(ISD::FP_EXTEND, SL, VT, N10.getOperand(1)), N0);
  12048. }
  12049. }
  12050. // fold (fsub (fpext (fneg (fmul, x, y))), z)
  12051. // -> (fneg (fma (fpext x), (fpext y), z))
  12052. // Note: This could be removed with appropriate canonicalization of the
  12053. // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
  12054. // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
  12055. // from implementing the canonicalization in visitFSUB.
  12056. if (N0.getOpcode() == ISD::FP_EXTEND) {
  12057. SDValue N00 = N0.getOperand(0);
  12058. if (N00.getOpcode() == ISD::FNEG) {
  12059. SDValue N000 = N00.getOperand(0);
  12060. if (isContractableFMUL(N000) &&
  12061. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12062. N00.getValueType())) {
  12063. return DAG.getNode(
  12064. ISD::FNEG, SL, VT,
  12065. DAG.getNode(PreferredFusedOpcode, SL, VT,
  12066. DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)),
  12067. DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)),
  12068. N1));
  12069. }
  12070. }
  12071. }
  12072. // fold (fsub (fneg (fpext (fmul, x, y))), z)
  12073. // -> (fneg (fma (fpext x)), (fpext y), z)
  12074. // Note: This could be removed with appropriate canonicalization of the
  12075. // input expression into (fneg (fadd (fpext (fmul, x, y)), z). However, the
  12076. // orthogonal flags -fp-contract=fast and -enable-unsafe-fp-math prevent
  12077. // from implementing the canonicalization in visitFSUB.
  12078. if (N0.getOpcode() == ISD::FNEG) {
  12079. SDValue N00 = N0.getOperand(0);
  12080. if (N00.getOpcode() == ISD::FP_EXTEND) {
  12081. SDValue N000 = N00.getOperand(0);
  12082. if (isContractableFMUL(N000) &&
  12083. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12084. N000.getValueType())) {
  12085. return DAG.getNode(
  12086. ISD::FNEG, SL, VT,
  12087. DAG.getNode(PreferredFusedOpcode, SL, VT,
  12088. DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(0)),
  12089. DAG.getNode(ISD::FP_EXTEND, SL, VT, N000.getOperand(1)),
  12090. N1));
  12091. }
  12092. }
  12093. }
  12094. auto isReassociable = [Options](SDNode *N) {
  12095. return Options.UnsafeFPMath || N->getFlags().hasAllowReassociation();
  12096. };
  12097. auto isContractableAndReassociableFMUL = [isContractableFMUL,
  12098. isReassociable](SDValue N) {
  12099. return isContractableFMUL(N) && isReassociable(N.getNode());
  12100. };
  12101. auto isFusedOp = [&](SDValue N) {
  12102. unsigned Opcode = N.getOpcode();
  12103. return Opcode == ISD::FMA || Opcode == ISD::FMAD;
  12104. };
  12105. // More folding opportunities when target permits.
  12106. if (Aggressive && isReassociable(N)) {
  12107. bool CanFuse = Options.UnsafeFPMath || N->getFlags().hasAllowContract();
  12108. // fold (fsub (fma x, y, (fmul u, v)), z)
  12109. // -> (fma x, y (fma u, v, (fneg z)))
  12110. if (CanFuse && isFusedOp(N0) &&
  12111. isContractableAndReassociableFMUL(N0.getOperand(2)) &&
  12112. N0->hasOneUse() && N0.getOperand(2)->hasOneUse()) {
  12113. return DAG.getNode(PreferredFusedOpcode, SL, VT, N0.getOperand(0),
  12114. N0.getOperand(1),
  12115. DAG.getNode(PreferredFusedOpcode, SL, VT,
  12116. N0.getOperand(2).getOperand(0),
  12117. N0.getOperand(2).getOperand(1),
  12118. DAG.getNode(ISD::FNEG, SL, VT, N1)));
  12119. }
  12120. // fold (fsub x, (fma y, z, (fmul u, v)))
  12121. // -> (fma (fneg y), z, (fma (fneg u), v, x))
  12122. if (CanFuse && isFusedOp(N1) &&
  12123. isContractableAndReassociableFMUL(N1.getOperand(2)) &&
  12124. N1->hasOneUse() && NoSignedZero) {
  12125. SDValue N20 = N1.getOperand(2).getOperand(0);
  12126. SDValue N21 = N1.getOperand(2).getOperand(1);
  12127. return DAG.getNode(
  12128. PreferredFusedOpcode, SL, VT,
  12129. DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1),
  12130. DAG.getNode(PreferredFusedOpcode, SL, VT,
  12131. DAG.getNode(ISD::FNEG, SL, VT, N20), N21, N0));
  12132. }
  12133. // fold (fsub (fma x, y, (fpext (fmul u, v))), z)
  12134. // -> (fma x, y (fma (fpext u), (fpext v), (fneg z)))
  12135. if (isFusedOp(N0) && N0->hasOneUse()) {
  12136. SDValue N02 = N0.getOperand(2);
  12137. if (N02.getOpcode() == ISD::FP_EXTEND) {
  12138. SDValue N020 = N02.getOperand(0);
  12139. if (isContractableAndReassociableFMUL(N020) &&
  12140. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12141. N020.getValueType())) {
  12142. return DAG.getNode(
  12143. PreferredFusedOpcode, SL, VT, N0.getOperand(0), N0.getOperand(1),
  12144. DAG.getNode(
  12145. PreferredFusedOpcode, SL, VT,
  12146. DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(0)),
  12147. DAG.getNode(ISD::FP_EXTEND, SL, VT, N020.getOperand(1)),
  12148. DAG.getNode(ISD::FNEG, SL, VT, N1)));
  12149. }
  12150. }
  12151. }
  12152. // fold (fsub (fpext (fma x, y, (fmul u, v))), z)
  12153. // -> (fma (fpext x), (fpext y),
  12154. // (fma (fpext u), (fpext v), (fneg z)))
  12155. // FIXME: This turns two single-precision and one double-precision
  12156. // operation into two double-precision operations, which might not be
  12157. // interesting for all targets, especially GPUs.
  12158. if (N0.getOpcode() == ISD::FP_EXTEND) {
  12159. SDValue N00 = N0.getOperand(0);
  12160. if (isFusedOp(N00)) {
  12161. SDValue N002 = N00.getOperand(2);
  12162. if (isContractableAndReassociableFMUL(N002) &&
  12163. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12164. N00.getValueType())) {
  12165. return DAG.getNode(
  12166. PreferredFusedOpcode, SL, VT,
  12167. DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(0)),
  12168. DAG.getNode(ISD::FP_EXTEND, SL, VT, N00.getOperand(1)),
  12169. DAG.getNode(
  12170. PreferredFusedOpcode, SL, VT,
  12171. DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(0)),
  12172. DAG.getNode(ISD::FP_EXTEND, SL, VT, N002.getOperand(1)),
  12173. DAG.getNode(ISD::FNEG, SL, VT, N1)));
  12174. }
  12175. }
  12176. }
  12177. // fold (fsub x, (fma y, z, (fpext (fmul u, v))))
  12178. // -> (fma (fneg y), z, (fma (fneg (fpext u)), (fpext v), x))
  12179. if (isFusedOp(N1) && N1.getOperand(2).getOpcode() == ISD::FP_EXTEND &&
  12180. N1->hasOneUse()) {
  12181. SDValue N120 = N1.getOperand(2).getOperand(0);
  12182. if (isContractableAndReassociableFMUL(N120) &&
  12183. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12184. N120.getValueType())) {
  12185. SDValue N1200 = N120.getOperand(0);
  12186. SDValue N1201 = N120.getOperand(1);
  12187. return DAG.getNode(
  12188. PreferredFusedOpcode, SL, VT,
  12189. DAG.getNode(ISD::FNEG, SL, VT, N1.getOperand(0)), N1.getOperand(1),
  12190. DAG.getNode(PreferredFusedOpcode, SL, VT,
  12191. DAG.getNode(ISD::FNEG, SL, VT,
  12192. DAG.getNode(ISD::FP_EXTEND, SL, VT, N1200)),
  12193. DAG.getNode(ISD::FP_EXTEND, SL, VT, N1201), N0));
  12194. }
  12195. }
  12196. // fold (fsub x, (fpext (fma y, z, (fmul u, v))))
  12197. // -> (fma (fneg (fpext y)), (fpext z),
  12198. // (fma (fneg (fpext u)), (fpext v), x))
  12199. // FIXME: This turns two single-precision and one double-precision
  12200. // operation into two double-precision operations, which might not be
  12201. // interesting for all targets, especially GPUs.
  12202. if (N1.getOpcode() == ISD::FP_EXTEND && isFusedOp(N1.getOperand(0))) {
  12203. SDValue CvtSrc = N1.getOperand(0);
  12204. SDValue N100 = CvtSrc.getOperand(0);
  12205. SDValue N101 = CvtSrc.getOperand(1);
  12206. SDValue N102 = CvtSrc.getOperand(2);
  12207. if (isContractableAndReassociableFMUL(N102) &&
  12208. TLI.isFPExtFoldable(DAG, PreferredFusedOpcode, VT,
  12209. CvtSrc.getValueType())) {
  12210. SDValue N1020 = N102.getOperand(0);
  12211. SDValue N1021 = N102.getOperand(1);
  12212. return DAG.getNode(
  12213. PreferredFusedOpcode, SL, VT,
  12214. DAG.getNode(ISD::FNEG, SL, VT,
  12215. DAG.getNode(ISD::FP_EXTEND, SL, VT, N100)),
  12216. DAG.getNode(ISD::FP_EXTEND, SL, VT, N101),
  12217. DAG.getNode(PreferredFusedOpcode, SL, VT,
  12218. DAG.getNode(ISD::FNEG, SL, VT,
  12219. DAG.getNode(ISD::FP_EXTEND, SL, VT, N1020)),
  12220. DAG.getNode(ISD::FP_EXTEND, SL, VT, N1021), N0));
  12221. }
  12222. }
  12223. }
  12224. return SDValue();
  12225. }
  12226. /// Try to perform FMA combining on a given FMUL node based on the distributive
  12227. /// law x * (y + 1) = x * y + x and variants thereof (commuted versions,
  12228. /// subtraction instead of addition).
  12229. SDValue DAGCombiner::visitFMULForFMADistributiveCombine(SDNode *N) {
  12230. SDValue N0 = N->getOperand(0);
  12231. SDValue N1 = N->getOperand(1);
  12232. EVT VT = N->getValueType(0);
  12233. SDLoc SL(N);
  12234. assert(N->getOpcode() == ISD::FMUL && "Expected FMUL Operation");
  12235. const TargetOptions &Options = DAG.getTarget().Options;
  12236. // The transforms below are incorrect when x == 0 and y == inf, because the
  12237. // intermediate multiplication produces a nan.
  12238. SDValue FAdd = N0.getOpcode() == ISD::FADD ? N0 : N1;
  12239. if (!hasNoInfs(Options, FAdd))
  12240. return SDValue();
  12241. // Floating-point multiply-add without intermediate rounding.
  12242. bool HasFMA =
  12243. isContractableFMUL(Options, SDValue(N, 0)) &&
  12244. TLI.isFMAFasterThanFMulAndFAdd(DAG.getMachineFunction(), VT) &&
  12245. (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FMA, VT));
  12246. // Floating-point multiply-add with intermediate rounding. This can result
  12247. // in a less precise result due to the changed rounding order.
  12248. bool HasFMAD = Options.UnsafeFPMath &&
  12249. (LegalOperations && TLI.isFMADLegal(DAG, N));
  12250. // No valid opcode, do not combine.
  12251. if (!HasFMAD && !HasFMA)
  12252. return SDValue();
  12253. // Always prefer FMAD to FMA for precision.
  12254. unsigned PreferredFusedOpcode = HasFMAD ? ISD::FMAD : ISD::FMA;
  12255. bool Aggressive = TLI.enableAggressiveFMAFusion(VT);
  12256. // fold (fmul (fadd x0, +1.0), y) -> (fma x0, y, y)
  12257. // fold (fmul (fadd x0, -1.0), y) -> (fma x0, y, (fneg y))
  12258. auto FuseFADD = [&](SDValue X, SDValue Y) {
  12259. if (X.getOpcode() == ISD::FADD && (Aggressive || X->hasOneUse())) {
  12260. if (auto *C = isConstOrConstSplatFP(X.getOperand(1), true)) {
  12261. if (C->isExactlyValue(+1.0))
  12262. return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
  12263. Y);
  12264. if (C->isExactlyValue(-1.0))
  12265. return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
  12266. DAG.getNode(ISD::FNEG, SL, VT, Y));
  12267. }
  12268. }
  12269. return SDValue();
  12270. };
  12271. if (SDValue FMA = FuseFADD(N0, N1))
  12272. return FMA;
  12273. if (SDValue FMA = FuseFADD(N1, N0))
  12274. return FMA;
  12275. // fold (fmul (fsub +1.0, x1), y) -> (fma (fneg x1), y, y)
  12276. // fold (fmul (fsub -1.0, x1), y) -> (fma (fneg x1), y, (fneg y))
  12277. // fold (fmul (fsub x0, +1.0), y) -> (fma x0, y, (fneg y))
  12278. // fold (fmul (fsub x0, -1.0), y) -> (fma x0, y, y)
  12279. auto FuseFSUB = [&](SDValue X, SDValue Y) {
  12280. if (X.getOpcode() == ISD::FSUB && (Aggressive || X->hasOneUse())) {
  12281. if (auto *C0 = isConstOrConstSplatFP(X.getOperand(0), true)) {
  12282. if (C0->isExactlyValue(+1.0))
  12283. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  12284. DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
  12285. Y);
  12286. if (C0->isExactlyValue(-1.0))
  12287. return DAG.getNode(PreferredFusedOpcode, SL, VT,
  12288. DAG.getNode(ISD::FNEG, SL, VT, X.getOperand(1)), Y,
  12289. DAG.getNode(ISD::FNEG, SL, VT, Y));
  12290. }
  12291. if (auto *C1 = isConstOrConstSplatFP(X.getOperand(1), true)) {
  12292. if (C1->isExactlyValue(+1.0))
  12293. return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
  12294. DAG.getNode(ISD::FNEG, SL, VT, Y));
  12295. if (C1->isExactlyValue(-1.0))
  12296. return DAG.getNode(PreferredFusedOpcode, SL, VT, X.getOperand(0), Y,
  12297. Y);
  12298. }
  12299. }
  12300. return SDValue();
  12301. };
  12302. if (SDValue FMA = FuseFSUB(N0, N1))
  12303. return FMA;
  12304. if (SDValue FMA = FuseFSUB(N1, N0))
  12305. return FMA;
  12306. return SDValue();
  12307. }
  12308. SDValue DAGCombiner::visitFADD(SDNode *N) {
  12309. SDValue N0 = N->getOperand(0);
  12310. SDValue N1 = N->getOperand(1);
  12311. bool N0CFP = DAG.isConstantFPBuildVectorOrConstantFP(N0);
  12312. bool N1CFP = DAG.isConstantFPBuildVectorOrConstantFP(N1);
  12313. EVT VT = N->getValueType(0);
  12314. SDLoc DL(N);
  12315. const TargetOptions &Options = DAG.getTarget().Options;
  12316. SDNodeFlags Flags = N->getFlags();
  12317. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  12318. if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
  12319. return R;
  12320. // fold (fadd c1, c2) -> c1 + c2
  12321. if (SDValue C = DAG.FoldConstantArithmetic(ISD::FADD, DL, VT, {N0, N1}))
  12322. return C;
  12323. // canonicalize constant to RHS
  12324. if (N0CFP && !N1CFP)
  12325. return DAG.getNode(ISD::FADD, DL, VT, N1, N0);
  12326. // fold vector ops
  12327. if (VT.isVector())
  12328. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  12329. return FoldedVOp;
  12330. // N0 + -0.0 --> N0 (also allowed with +0.0 and fast-math)
  12331. ConstantFPSDNode *N1C = isConstOrConstSplatFP(N1, true);
  12332. if (N1C && N1C->isZero())
  12333. if (N1C->isNegative() || Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())
  12334. return N0;
  12335. if (SDValue NewSel = foldBinOpIntoSelect(N))
  12336. return NewSel;
  12337. // fold (fadd A, (fneg B)) -> (fsub A, B)
  12338. if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
  12339. if (SDValue NegN1 = TLI.getCheaperNegatedExpression(
  12340. N1, DAG, LegalOperations, ForCodeSize))
  12341. return DAG.getNode(ISD::FSUB, DL, VT, N0, NegN1);
  12342. // fold (fadd (fneg A), B) -> (fsub B, A)
  12343. if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT))
  12344. if (SDValue NegN0 = TLI.getCheaperNegatedExpression(
  12345. N0, DAG, LegalOperations, ForCodeSize))
  12346. return DAG.getNode(ISD::FSUB, DL, VT, N1, NegN0);
  12347. auto isFMulNegTwo = [](SDValue FMul) {
  12348. if (!FMul.hasOneUse() || FMul.getOpcode() != ISD::FMUL)
  12349. return false;
  12350. auto *C = isConstOrConstSplatFP(FMul.getOperand(1), true);
  12351. return C && C->isExactlyValue(-2.0);
  12352. };
  12353. // fadd (fmul B, -2.0), A --> fsub A, (fadd B, B)
  12354. if (isFMulNegTwo(N0)) {
  12355. SDValue B = N0.getOperand(0);
  12356. SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B);
  12357. return DAG.getNode(ISD::FSUB, DL, VT, N1, Add);
  12358. }
  12359. // fadd A, (fmul B, -2.0) --> fsub A, (fadd B, B)
  12360. if (isFMulNegTwo(N1)) {
  12361. SDValue B = N1.getOperand(0);
  12362. SDValue Add = DAG.getNode(ISD::FADD, DL, VT, B, B);
  12363. return DAG.getNode(ISD::FSUB, DL, VT, N0, Add);
  12364. }
  12365. // No FP constant should be created after legalization as Instruction
  12366. // Selection pass has a hard time dealing with FP constants.
  12367. bool AllowNewConst = (Level < AfterLegalizeDAG);
  12368. // If nnan is enabled, fold lots of things.
  12369. if ((Options.NoNaNsFPMath || Flags.hasNoNaNs()) && AllowNewConst) {
  12370. // If allowed, fold (fadd (fneg x), x) -> 0.0
  12371. if (N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1)
  12372. return DAG.getConstantFP(0.0, DL, VT);
  12373. // If allowed, fold (fadd x, (fneg x)) -> 0.0
  12374. if (N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0)
  12375. return DAG.getConstantFP(0.0, DL, VT);
  12376. }
  12377. // If 'unsafe math' or reassoc and nsz, fold lots of things.
  12378. // TODO: break out portions of the transformations below for which Unsafe is
  12379. // considered and which do not require both nsz and reassoc
  12380. if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) ||
  12381. (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) &&
  12382. AllowNewConst) {
  12383. // fadd (fadd x, c1), c2 -> fadd x, c1 + c2
  12384. if (N1CFP && N0.getOpcode() == ISD::FADD &&
  12385. DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
  12386. SDValue NewC = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1), N1);
  12387. return DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(0), NewC);
  12388. }
  12389. // We can fold chains of FADD's of the same value into multiplications.
  12390. // This transform is not safe in general because we are reducing the number
  12391. // of rounding steps.
  12392. if (TLI.isOperationLegalOrCustom(ISD::FMUL, VT) && !N0CFP && !N1CFP) {
  12393. if (N0.getOpcode() == ISD::FMUL) {
  12394. bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
  12395. bool CFP01 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1));
  12396. // (fadd (fmul x, c), x) -> (fmul x, c+1)
  12397. if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
  12398. SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
  12399. DAG.getConstantFP(1.0, DL, VT));
  12400. return DAG.getNode(ISD::FMUL, DL, VT, N1, NewCFP);
  12401. }
  12402. // (fadd (fmul x, c), (fadd x, x)) -> (fmul x, c+2)
  12403. if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
  12404. N1.getOperand(0) == N1.getOperand(1) &&
  12405. N0.getOperand(0) == N1.getOperand(0)) {
  12406. SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N0.getOperand(1),
  12407. DAG.getConstantFP(2.0, DL, VT));
  12408. return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), NewCFP);
  12409. }
  12410. }
  12411. if (N1.getOpcode() == ISD::FMUL) {
  12412. bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
  12413. bool CFP11 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(1));
  12414. // (fadd x, (fmul x, c)) -> (fmul x, c+1)
  12415. if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
  12416. SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
  12417. DAG.getConstantFP(1.0, DL, VT));
  12418. return DAG.getNode(ISD::FMUL, DL, VT, N0, NewCFP);
  12419. }
  12420. // (fadd (fadd x, x), (fmul x, c)) -> (fmul x, c+2)
  12421. if (CFP11 && !CFP10 && N0.getOpcode() == ISD::FADD &&
  12422. N0.getOperand(0) == N0.getOperand(1) &&
  12423. N1.getOperand(0) == N0.getOperand(0)) {
  12424. SDValue NewCFP = DAG.getNode(ISD::FADD, DL, VT, N1.getOperand(1),
  12425. DAG.getConstantFP(2.0, DL, VT));
  12426. return DAG.getNode(ISD::FMUL, DL, VT, N1.getOperand(0), NewCFP);
  12427. }
  12428. }
  12429. if (N0.getOpcode() == ISD::FADD) {
  12430. bool CFP00 = DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(0));
  12431. // (fadd (fadd x, x), x) -> (fmul x, 3.0)
  12432. if (!CFP00 && N0.getOperand(0) == N0.getOperand(1) &&
  12433. (N0.getOperand(0) == N1)) {
  12434. return DAG.getNode(ISD::FMUL, DL, VT, N1,
  12435. DAG.getConstantFP(3.0, DL, VT));
  12436. }
  12437. }
  12438. if (N1.getOpcode() == ISD::FADD) {
  12439. bool CFP10 = DAG.isConstantFPBuildVectorOrConstantFP(N1.getOperand(0));
  12440. // (fadd x, (fadd x, x)) -> (fmul x, 3.0)
  12441. if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
  12442. N1.getOperand(0) == N0) {
  12443. return DAG.getNode(ISD::FMUL, DL, VT, N0,
  12444. DAG.getConstantFP(3.0, DL, VT));
  12445. }
  12446. }
  12447. // (fadd (fadd x, x), (fadd x, x)) -> (fmul x, 4.0)
  12448. if (N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
  12449. N0.getOperand(0) == N0.getOperand(1) &&
  12450. N1.getOperand(0) == N1.getOperand(1) &&
  12451. N0.getOperand(0) == N1.getOperand(0)) {
  12452. return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0),
  12453. DAG.getConstantFP(4.0, DL, VT));
  12454. }
  12455. }
  12456. } // enable-unsafe-fp-math
  12457. // FADD -> FMA combines:
  12458. if (SDValue Fused = visitFADDForFMACombine(N)) {
  12459. AddToWorklist(Fused.getNode());
  12460. return Fused;
  12461. }
  12462. return SDValue();
  12463. }
  12464. SDValue DAGCombiner::visitSTRICT_FADD(SDNode *N) {
  12465. SDValue Chain = N->getOperand(0);
  12466. SDValue N0 = N->getOperand(1);
  12467. SDValue N1 = N->getOperand(2);
  12468. EVT VT = N->getValueType(0);
  12469. EVT ChainVT = N->getValueType(1);
  12470. SDLoc DL(N);
  12471. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  12472. // fold (strict_fadd A, (fneg B)) -> (strict_fsub A, B)
  12473. if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT))
  12474. if (SDValue NegN1 = TLI.getCheaperNegatedExpression(
  12475. N1, DAG, LegalOperations, ForCodeSize)) {
  12476. return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT),
  12477. {Chain, N0, NegN1});
  12478. }
  12479. // fold (strict_fadd (fneg A), B) -> (strict_fsub B, A)
  12480. if (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::STRICT_FSUB, VT))
  12481. if (SDValue NegN0 = TLI.getCheaperNegatedExpression(
  12482. N0, DAG, LegalOperations, ForCodeSize)) {
  12483. return DAG.getNode(ISD::STRICT_FSUB, DL, DAG.getVTList(VT, ChainVT),
  12484. {Chain, N1, NegN0});
  12485. }
  12486. return SDValue();
  12487. }
  12488. SDValue DAGCombiner::visitFSUB(SDNode *N) {
  12489. SDValue N0 = N->getOperand(0);
  12490. SDValue N1 = N->getOperand(1);
  12491. ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, true);
  12492. ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
  12493. EVT VT = N->getValueType(0);
  12494. SDLoc DL(N);
  12495. const TargetOptions &Options = DAG.getTarget().Options;
  12496. const SDNodeFlags Flags = N->getFlags();
  12497. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  12498. if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
  12499. return R;
  12500. // fold (fsub c1, c2) -> c1-c2
  12501. if (SDValue C = DAG.FoldConstantArithmetic(ISD::FSUB, DL, VT, {N0, N1}))
  12502. return C;
  12503. // fold vector ops
  12504. if (VT.isVector())
  12505. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  12506. return FoldedVOp;
  12507. if (SDValue NewSel = foldBinOpIntoSelect(N))
  12508. return NewSel;
  12509. // (fsub A, 0) -> A
  12510. if (N1CFP && N1CFP->isZero()) {
  12511. if (!N1CFP->isNegative() || Options.NoSignedZerosFPMath ||
  12512. Flags.hasNoSignedZeros()) {
  12513. return N0;
  12514. }
  12515. }
  12516. if (N0 == N1) {
  12517. // (fsub x, x) -> 0.0
  12518. if (Options.NoNaNsFPMath || Flags.hasNoNaNs())
  12519. return DAG.getConstantFP(0.0f, DL, VT);
  12520. }
  12521. // (fsub -0.0, N1) -> -N1
  12522. if (N0CFP && N0CFP->isZero()) {
  12523. if (N0CFP->isNegative() ||
  12524. (Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros())) {
  12525. // We cannot replace an FSUB(+-0.0,X) with FNEG(X) when denormals are
  12526. // flushed to zero, unless all users treat denorms as zero (DAZ).
  12527. // FIXME: This transform will change the sign of a NaN and the behavior
  12528. // of a signaling NaN. It is only valid when a NoNaN flag is present.
  12529. DenormalMode DenormMode = DAG.getDenormalMode(VT);
  12530. if (DenormMode == DenormalMode::getIEEE()) {
  12531. if (SDValue NegN1 =
  12532. TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize))
  12533. return NegN1;
  12534. if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
  12535. return DAG.getNode(ISD::FNEG, DL, VT, N1);
  12536. }
  12537. }
  12538. }
  12539. if (((Options.UnsafeFPMath && Options.NoSignedZerosFPMath) ||
  12540. (Flags.hasAllowReassociation() && Flags.hasNoSignedZeros())) &&
  12541. N1.getOpcode() == ISD::FADD) {
  12542. // X - (X + Y) -> -Y
  12543. if (N0 == N1->getOperand(0))
  12544. return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(1));
  12545. // X - (Y + X) -> -Y
  12546. if (N0 == N1->getOperand(1))
  12547. return DAG.getNode(ISD::FNEG, DL, VT, N1->getOperand(0));
  12548. }
  12549. // fold (fsub A, (fneg B)) -> (fadd A, B)
  12550. if (SDValue NegN1 =
  12551. TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize))
  12552. return DAG.getNode(ISD::FADD, DL, VT, N0, NegN1);
  12553. // FSUB -> FMA combines:
  12554. if (SDValue Fused = visitFSUBForFMACombine(N)) {
  12555. AddToWorklist(Fused.getNode());
  12556. return Fused;
  12557. }
  12558. return SDValue();
  12559. }
  12560. SDValue DAGCombiner::visitFMUL(SDNode *N) {
  12561. SDValue N0 = N->getOperand(0);
  12562. SDValue N1 = N->getOperand(1);
  12563. ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1, true);
  12564. EVT VT = N->getValueType(0);
  12565. SDLoc DL(N);
  12566. const TargetOptions &Options = DAG.getTarget().Options;
  12567. const SDNodeFlags Flags = N->getFlags();
  12568. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  12569. if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
  12570. return R;
  12571. // fold (fmul c1, c2) -> c1*c2
  12572. if (SDValue C = DAG.FoldConstantArithmetic(ISD::FMUL, DL, VT, {N0, N1}))
  12573. return C;
  12574. // canonicalize constant to RHS
  12575. if (DAG.isConstantFPBuildVectorOrConstantFP(N0) &&
  12576. !DAG.isConstantFPBuildVectorOrConstantFP(N1))
  12577. return DAG.getNode(ISD::FMUL, DL, VT, N1, N0);
  12578. // fold vector ops
  12579. if (VT.isVector())
  12580. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  12581. return FoldedVOp;
  12582. if (SDValue NewSel = foldBinOpIntoSelect(N))
  12583. return NewSel;
  12584. if (Options.UnsafeFPMath || Flags.hasAllowReassociation()) {
  12585. // fmul (fmul X, C1), C2 -> fmul X, C1 * C2
  12586. if (DAG.isConstantFPBuildVectorOrConstantFP(N1) &&
  12587. N0.getOpcode() == ISD::FMUL) {
  12588. SDValue N00 = N0.getOperand(0);
  12589. SDValue N01 = N0.getOperand(1);
  12590. // Avoid an infinite loop by making sure that N00 is not a constant
  12591. // (the inner multiply has not been constant folded yet).
  12592. if (DAG.isConstantFPBuildVectorOrConstantFP(N01) &&
  12593. !DAG.isConstantFPBuildVectorOrConstantFP(N00)) {
  12594. SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, N01, N1);
  12595. return DAG.getNode(ISD::FMUL, DL, VT, N00, MulConsts);
  12596. }
  12597. }
  12598. // Match a special-case: we convert X * 2.0 into fadd.
  12599. // fmul (fadd X, X), C -> fmul X, 2.0 * C
  12600. if (N0.getOpcode() == ISD::FADD && N0.hasOneUse() &&
  12601. N0.getOperand(0) == N0.getOperand(1)) {
  12602. const SDValue Two = DAG.getConstantFP(2.0, DL, VT);
  12603. SDValue MulConsts = DAG.getNode(ISD::FMUL, DL, VT, Two, N1);
  12604. return DAG.getNode(ISD::FMUL, DL, VT, N0.getOperand(0), MulConsts);
  12605. }
  12606. }
  12607. // fold (fmul X, 2.0) -> (fadd X, X)
  12608. if (N1CFP && N1CFP->isExactlyValue(+2.0))
  12609. return DAG.getNode(ISD::FADD, DL, VT, N0, N0);
  12610. // fold (fmul X, -1.0) -> (fsub -0.0, X)
  12611. if (N1CFP && N1CFP->isExactlyValue(-1.0)) {
  12612. if (!LegalOperations || TLI.isOperationLegal(ISD::FSUB, VT)) {
  12613. return DAG.getNode(ISD::FSUB, DL, VT,
  12614. DAG.getConstantFP(-0.0, DL, VT), N0, Flags);
  12615. }
  12616. }
  12617. // -N0 * -N1 --> N0 * N1
  12618. TargetLowering::NegatibleCost CostN0 =
  12619. TargetLowering::NegatibleCost::Expensive;
  12620. TargetLowering::NegatibleCost CostN1 =
  12621. TargetLowering::NegatibleCost::Expensive;
  12622. SDValue NegN0 =
  12623. TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
  12624. SDValue NegN1 =
  12625. TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
  12626. if (NegN0 && NegN1 &&
  12627. (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
  12628. CostN1 == TargetLowering::NegatibleCost::Cheaper))
  12629. return DAG.getNode(ISD::FMUL, DL, VT, NegN0, NegN1);
  12630. // fold (fmul X, (select (fcmp X > 0.0), -1.0, 1.0)) -> (fneg (fabs X))
  12631. // fold (fmul X, (select (fcmp X > 0.0), 1.0, -1.0)) -> (fabs X)
  12632. if (Flags.hasNoNaNs() && Flags.hasNoSignedZeros() &&
  12633. (N0.getOpcode() == ISD::SELECT || N1.getOpcode() == ISD::SELECT) &&
  12634. TLI.isOperationLegal(ISD::FABS, VT)) {
  12635. SDValue Select = N0, X = N1;
  12636. if (Select.getOpcode() != ISD::SELECT)
  12637. std::swap(Select, X);
  12638. SDValue Cond = Select.getOperand(0);
  12639. auto TrueOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(1));
  12640. auto FalseOpnd = dyn_cast<ConstantFPSDNode>(Select.getOperand(2));
  12641. if (TrueOpnd && FalseOpnd &&
  12642. Cond.getOpcode() == ISD::SETCC && Cond.getOperand(0) == X &&
  12643. isa<ConstantFPSDNode>(Cond.getOperand(1)) &&
  12644. cast<ConstantFPSDNode>(Cond.getOperand(1))->isExactlyValue(0.0)) {
  12645. ISD::CondCode CC = cast<CondCodeSDNode>(Cond.getOperand(2))->get();
  12646. switch (CC) {
  12647. default: break;
  12648. case ISD::SETOLT:
  12649. case ISD::SETULT:
  12650. case ISD::SETOLE:
  12651. case ISD::SETULE:
  12652. case ISD::SETLT:
  12653. case ISD::SETLE:
  12654. std::swap(TrueOpnd, FalseOpnd);
  12655. LLVM_FALLTHROUGH;
  12656. case ISD::SETOGT:
  12657. case ISD::SETUGT:
  12658. case ISD::SETOGE:
  12659. case ISD::SETUGE:
  12660. case ISD::SETGT:
  12661. case ISD::SETGE:
  12662. if (TrueOpnd->isExactlyValue(-1.0) && FalseOpnd->isExactlyValue(1.0) &&
  12663. TLI.isOperationLegal(ISD::FNEG, VT))
  12664. return DAG.getNode(ISD::FNEG, DL, VT,
  12665. DAG.getNode(ISD::FABS, DL, VT, X));
  12666. if (TrueOpnd->isExactlyValue(1.0) && FalseOpnd->isExactlyValue(-1.0))
  12667. return DAG.getNode(ISD::FABS, DL, VT, X);
  12668. break;
  12669. }
  12670. }
  12671. }
  12672. // FMUL -> FMA combines:
  12673. if (SDValue Fused = visitFMULForFMADistributiveCombine(N)) {
  12674. AddToWorklist(Fused.getNode());
  12675. return Fused;
  12676. }
  12677. return SDValue();
  12678. }
  12679. SDValue DAGCombiner::visitFMA(SDNode *N) {
  12680. SDValue N0 = N->getOperand(0);
  12681. SDValue N1 = N->getOperand(1);
  12682. SDValue N2 = N->getOperand(2);
  12683. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  12684. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  12685. EVT VT = N->getValueType(0);
  12686. SDLoc DL(N);
  12687. const TargetOptions &Options = DAG.getTarget().Options;
  12688. // FMA nodes have flags that propagate to the created nodes.
  12689. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  12690. bool UnsafeFPMath =
  12691. Options.UnsafeFPMath || N->getFlags().hasAllowReassociation();
  12692. // Constant fold FMA.
  12693. if (isa<ConstantFPSDNode>(N0) &&
  12694. isa<ConstantFPSDNode>(N1) &&
  12695. isa<ConstantFPSDNode>(N2)) {
  12696. return DAG.getNode(ISD::FMA, DL, VT, N0, N1, N2);
  12697. }
  12698. // (-N0 * -N1) + N2 --> (N0 * N1) + N2
  12699. TargetLowering::NegatibleCost CostN0 =
  12700. TargetLowering::NegatibleCost::Expensive;
  12701. TargetLowering::NegatibleCost CostN1 =
  12702. TargetLowering::NegatibleCost::Expensive;
  12703. SDValue NegN0 =
  12704. TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
  12705. SDValue NegN1 =
  12706. TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
  12707. if (NegN0 && NegN1 &&
  12708. (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
  12709. CostN1 == TargetLowering::NegatibleCost::Cheaper))
  12710. return DAG.getNode(ISD::FMA, DL, VT, NegN0, NegN1, N2);
  12711. if (UnsafeFPMath) {
  12712. if (N0CFP && N0CFP->isZero())
  12713. return N2;
  12714. if (N1CFP && N1CFP->isZero())
  12715. return N2;
  12716. }
  12717. if (N0CFP && N0CFP->isExactlyValue(1.0))
  12718. return DAG.getNode(ISD::FADD, SDLoc(N), VT, N1, N2);
  12719. if (N1CFP && N1CFP->isExactlyValue(1.0))
  12720. return DAG.getNode(ISD::FADD, SDLoc(N), VT, N0, N2);
  12721. // Canonicalize (fma c, x, y) -> (fma x, c, y)
  12722. if (DAG.isConstantFPBuildVectorOrConstantFP(N0) &&
  12723. !DAG.isConstantFPBuildVectorOrConstantFP(N1))
  12724. return DAG.getNode(ISD::FMA, SDLoc(N), VT, N1, N0, N2);
  12725. if (UnsafeFPMath) {
  12726. // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
  12727. if (N2.getOpcode() == ISD::FMUL && N0 == N2.getOperand(0) &&
  12728. DAG.isConstantFPBuildVectorOrConstantFP(N1) &&
  12729. DAG.isConstantFPBuildVectorOrConstantFP(N2.getOperand(1))) {
  12730. return DAG.getNode(ISD::FMUL, DL, VT, N0,
  12731. DAG.getNode(ISD::FADD, DL, VT, N1, N2.getOperand(1)));
  12732. }
  12733. // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
  12734. if (N0.getOpcode() == ISD::FMUL &&
  12735. DAG.isConstantFPBuildVectorOrConstantFP(N1) &&
  12736. DAG.isConstantFPBuildVectorOrConstantFP(N0.getOperand(1))) {
  12737. return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
  12738. DAG.getNode(ISD::FMUL, DL, VT, N1, N0.getOperand(1)),
  12739. N2);
  12740. }
  12741. }
  12742. // (fma x, -1, y) -> (fadd (fneg x), y)
  12743. if (N1CFP) {
  12744. if (N1CFP->isExactlyValue(1.0))
  12745. return DAG.getNode(ISD::FADD, DL, VT, N0, N2);
  12746. if (N1CFP->isExactlyValue(-1.0) &&
  12747. (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
  12748. SDValue RHSNeg = DAG.getNode(ISD::FNEG, DL, VT, N0);
  12749. AddToWorklist(RHSNeg.getNode());
  12750. return DAG.getNode(ISD::FADD, DL, VT, N2, RHSNeg);
  12751. }
  12752. // fma (fneg x), K, y -> fma x -K, y
  12753. if (N0.getOpcode() == ISD::FNEG &&
  12754. (TLI.isOperationLegal(ISD::ConstantFP, VT) ||
  12755. (N1.hasOneUse() && !TLI.isFPImmLegal(N1CFP->getValueAPF(), VT,
  12756. ForCodeSize)))) {
  12757. return DAG.getNode(ISD::FMA, DL, VT, N0.getOperand(0),
  12758. DAG.getNode(ISD::FNEG, DL, VT, N1), N2);
  12759. }
  12760. }
  12761. if (UnsafeFPMath) {
  12762. // (fma x, c, x) -> (fmul x, (c+1))
  12763. if (N1CFP && N0 == N2) {
  12764. return DAG.getNode(
  12765. ISD::FMUL, DL, VT, N0,
  12766. DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(1.0, DL, VT)));
  12767. }
  12768. // (fma x, c, (fneg x)) -> (fmul x, (c-1))
  12769. if (N1CFP && N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
  12770. return DAG.getNode(
  12771. ISD::FMUL, DL, VT, N0,
  12772. DAG.getNode(ISD::FADD, DL, VT, N1, DAG.getConstantFP(-1.0, DL, VT)));
  12773. }
  12774. }
  12775. // fold ((fma (fneg X), Y, (fneg Z)) -> fneg (fma X, Y, Z))
  12776. // fold ((fma X, (fneg Y), (fneg Z)) -> fneg (fma X, Y, Z))
  12777. if (!TLI.isFNegFree(VT))
  12778. if (SDValue Neg = TLI.getCheaperNegatedExpression(
  12779. SDValue(N, 0), DAG, LegalOperations, ForCodeSize))
  12780. return DAG.getNode(ISD::FNEG, DL, VT, Neg);
  12781. return SDValue();
  12782. }
  12783. // Combine multiple FDIVs with the same divisor into multiple FMULs by the
  12784. // reciprocal.
  12785. // E.g., (a / D; b / D;) -> (recip = 1.0 / D; a * recip; b * recip)
  12786. // Notice that this is not always beneficial. One reason is different targets
  12787. // may have different costs for FDIV and FMUL, so sometimes the cost of two
  12788. // FDIVs may be lower than the cost of one FDIV and two FMULs. Another reason
  12789. // is the critical path is increased from "one FDIV" to "one FDIV + one FMUL".
  12790. SDValue DAGCombiner::combineRepeatedFPDivisors(SDNode *N) {
  12791. // TODO: Limit this transform based on optsize/minsize - it always creates at
  12792. // least 1 extra instruction. But the perf win may be substantial enough
  12793. // that only minsize should restrict this.
  12794. bool UnsafeMath = DAG.getTarget().Options.UnsafeFPMath;
  12795. const SDNodeFlags Flags = N->getFlags();
  12796. if (LegalDAG || (!UnsafeMath && !Flags.hasAllowReciprocal()))
  12797. return SDValue();
  12798. // Skip if current node is a reciprocal/fneg-reciprocal.
  12799. SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
  12800. ConstantFPSDNode *N0CFP = isConstOrConstSplatFP(N0, /* AllowUndefs */ true);
  12801. if (N0CFP && (N0CFP->isExactlyValue(1.0) || N0CFP->isExactlyValue(-1.0)))
  12802. return SDValue();
  12803. // Exit early if the target does not want this transform or if there can't
  12804. // possibly be enough uses of the divisor to make the transform worthwhile.
  12805. unsigned MinUses = TLI.combineRepeatedFPDivisors();
  12806. // For splat vectors, scale the number of uses by the splat factor. If we can
  12807. // convert the division into a scalar op, that will likely be much faster.
  12808. unsigned NumElts = 1;
  12809. EVT VT = N->getValueType(0);
  12810. if (VT.isVector() && DAG.isSplatValue(N1))
  12811. NumElts = VT.getVectorMinNumElements();
  12812. if (!MinUses || (N1->use_size() * NumElts) < MinUses)
  12813. return SDValue();
  12814. // Find all FDIV users of the same divisor.
  12815. // Use a set because duplicates may be present in the user list.
  12816. SetVector<SDNode *> Users;
  12817. for (auto *U : N1->uses()) {
  12818. if (U->getOpcode() == ISD::FDIV && U->getOperand(1) == N1) {
  12819. // Skip X/sqrt(X) that has not been simplified to sqrt(X) yet.
  12820. if (U->getOperand(1).getOpcode() == ISD::FSQRT &&
  12821. U->getOperand(0) == U->getOperand(1).getOperand(0) &&
  12822. U->getFlags().hasAllowReassociation() &&
  12823. U->getFlags().hasNoSignedZeros())
  12824. continue;
  12825. // This division is eligible for optimization only if global unsafe math
  12826. // is enabled or if this division allows reciprocal formation.
  12827. if (UnsafeMath || U->getFlags().hasAllowReciprocal())
  12828. Users.insert(U);
  12829. }
  12830. }
  12831. // Now that we have the actual number of divisor uses, make sure it meets
  12832. // the minimum threshold specified by the target.
  12833. if ((Users.size() * NumElts) < MinUses)
  12834. return SDValue();
  12835. SDLoc DL(N);
  12836. SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
  12837. SDValue Reciprocal = DAG.getNode(ISD::FDIV, DL, VT, FPOne, N1, Flags);
  12838. // Dividend / Divisor -> Dividend * Reciprocal
  12839. for (auto *U : Users) {
  12840. SDValue Dividend = U->getOperand(0);
  12841. if (Dividend != FPOne) {
  12842. SDValue NewNode = DAG.getNode(ISD::FMUL, SDLoc(U), VT, Dividend,
  12843. Reciprocal, Flags);
  12844. CombineTo(U, NewNode);
  12845. } else if (U != Reciprocal.getNode()) {
  12846. // In the absence of fast-math-flags, this user node is always the
  12847. // same node as Reciprocal, but with FMF they may be different nodes.
  12848. CombineTo(U, Reciprocal);
  12849. }
  12850. }
  12851. return SDValue(N, 0); // N was replaced.
  12852. }
  12853. SDValue DAGCombiner::visitFDIV(SDNode *N) {
  12854. SDValue N0 = N->getOperand(0);
  12855. SDValue N1 = N->getOperand(1);
  12856. EVT VT = N->getValueType(0);
  12857. SDLoc DL(N);
  12858. const TargetOptions &Options = DAG.getTarget().Options;
  12859. SDNodeFlags Flags = N->getFlags();
  12860. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  12861. if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
  12862. return R;
  12863. // fold (fdiv c1, c2) -> c1/c2
  12864. if (SDValue C = DAG.FoldConstantArithmetic(ISD::FDIV, DL, VT, {N0, N1}))
  12865. return C;
  12866. // fold vector ops
  12867. if (VT.isVector())
  12868. if (SDValue FoldedVOp = SimplifyVBinOp(N, DL))
  12869. return FoldedVOp;
  12870. if (SDValue NewSel = foldBinOpIntoSelect(N))
  12871. return NewSel;
  12872. if (SDValue V = combineRepeatedFPDivisors(N))
  12873. return V;
  12874. if (Options.UnsafeFPMath || Flags.hasAllowReciprocal()) {
  12875. // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
  12876. if (auto *N1CFP = dyn_cast<ConstantFPSDNode>(N1)) {
  12877. // Compute the reciprocal 1.0 / c2.
  12878. const APFloat &N1APF = N1CFP->getValueAPF();
  12879. APFloat Recip(N1APF.getSemantics(), 1); // 1.0
  12880. APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
  12881. // Only do the transform if the reciprocal is a legal fp immediate that
  12882. // isn't too nasty (eg NaN, denormal, ...).
  12883. if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
  12884. (!LegalOperations ||
  12885. // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
  12886. // backend)... we should handle this gracefully after Legalize.
  12887. // TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT) ||
  12888. TLI.isOperationLegal(ISD::ConstantFP, VT) ||
  12889. TLI.isFPImmLegal(Recip, VT, ForCodeSize)))
  12890. return DAG.getNode(ISD::FMUL, DL, VT, N0,
  12891. DAG.getConstantFP(Recip, DL, VT));
  12892. }
  12893. // If this FDIV is part of a reciprocal square root, it may be folded
  12894. // into a target-specific square root estimate instruction.
  12895. if (N1.getOpcode() == ISD::FSQRT) {
  12896. if (SDValue RV = buildRsqrtEstimate(N1.getOperand(0), Flags))
  12897. return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
  12898. } else if (N1.getOpcode() == ISD::FP_EXTEND &&
  12899. N1.getOperand(0).getOpcode() == ISD::FSQRT) {
  12900. if (SDValue RV =
  12901. buildRsqrtEstimate(N1.getOperand(0).getOperand(0), Flags)) {
  12902. RV = DAG.getNode(ISD::FP_EXTEND, SDLoc(N1), VT, RV);
  12903. AddToWorklist(RV.getNode());
  12904. return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
  12905. }
  12906. } else if (N1.getOpcode() == ISD::FP_ROUND &&
  12907. N1.getOperand(0).getOpcode() == ISD::FSQRT) {
  12908. if (SDValue RV =
  12909. buildRsqrtEstimate(N1.getOperand(0).getOperand(0), Flags)) {
  12910. RV = DAG.getNode(ISD::FP_ROUND, SDLoc(N1), VT, RV, N1.getOperand(1));
  12911. AddToWorklist(RV.getNode());
  12912. return DAG.getNode(ISD::FMUL, DL, VT, N0, RV);
  12913. }
  12914. } else if (N1.getOpcode() == ISD::FMUL) {
  12915. // Look through an FMUL. Even though this won't remove the FDIV directly,
  12916. // it's still worthwhile to get rid of the FSQRT if possible.
  12917. SDValue Sqrt, Y;
  12918. if (N1.getOperand(0).getOpcode() == ISD::FSQRT) {
  12919. Sqrt = N1.getOperand(0);
  12920. Y = N1.getOperand(1);
  12921. } else if (N1.getOperand(1).getOpcode() == ISD::FSQRT) {
  12922. Sqrt = N1.getOperand(1);
  12923. Y = N1.getOperand(0);
  12924. }
  12925. if (Sqrt.getNode()) {
  12926. // If the other multiply operand is known positive, pull it into the
  12927. // sqrt. That will eliminate the division if we convert to an estimate.
  12928. if (Flags.hasAllowReassociation() && N1.hasOneUse() &&
  12929. N1->getFlags().hasAllowReassociation() && Sqrt.hasOneUse()) {
  12930. SDValue A;
  12931. if (Y.getOpcode() == ISD::FABS && Y.hasOneUse())
  12932. A = Y.getOperand(0);
  12933. else if (Y == Sqrt.getOperand(0))
  12934. A = Y;
  12935. if (A) {
  12936. // X / (fabs(A) * sqrt(Z)) --> X / sqrt(A*A*Z) --> X * rsqrt(A*A*Z)
  12937. // X / (A * sqrt(A)) --> X / sqrt(A*A*A) --> X * rsqrt(A*A*A)
  12938. SDValue AA = DAG.getNode(ISD::FMUL, DL, VT, A, A);
  12939. SDValue AAZ =
  12940. DAG.getNode(ISD::FMUL, DL, VT, AA, Sqrt.getOperand(0));
  12941. if (SDValue Rsqrt = buildRsqrtEstimate(AAZ, Flags))
  12942. return DAG.getNode(ISD::FMUL, DL, VT, N0, Rsqrt);
  12943. // Estimate creation failed. Clean up speculatively created nodes.
  12944. recursivelyDeleteUnusedNodes(AAZ.getNode());
  12945. }
  12946. }
  12947. // We found a FSQRT, so try to make this fold:
  12948. // X / (Y * sqrt(Z)) -> X * (rsqrt(Z) / Y)
  12949. if (SDValue Rsqrt = buildRsqrtEstimate(Sqrt.getOperand(0), Flags)) {
  12950. SDValue Div = DAG.getNode(ISD::FDIV, SDLoc(N1), VT, Rsqrt, Y);
  12951. AddToWorklist(Div.getNode());
  12952. return DAG.getNode(ISD::FMUL, DL, VT, N0, Div);
  12953. }
  12954. }
  12955. }
  12956. // Fold into a reciprocal estimate and multiply instead of a real divide.
  12957. if (Options.NoInfsFPMath || Flags.hasNoInfs())
  12958. if (SDValue RV = BuildDivEstimate(N0, N1, Flags))
  12959. return RV;
  12960. }
  12961. // Fold X/Sqrt(X) -> Sqrt(X)
  12962. if ((Options.NoSignedZerosFPMath || Flags.hasNoSignedZeros()) &&
  12963. (Options.UnsafeFPMath || Flags.hasAllowReassociation()))
  12964. if (N1.getOpcode() == ISD::FSQRT && N0 == N1.getOperand(0))
  12965. return N1;
  12966. // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
  12967. TargetLowering::NegatibleCost CostN0 =
  12968. TargetLowering::NegatibleCost::Expensive;
  12969. TargetLowering::NegatibleCost CostN1 =
  12970. TargetLowering::NegatibleCost::Expensive;
  12971. SDValue NegN0 =
  12972. TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize, CostN0);
  12973. SDValue NegN1 =
  12974. TLI.getNegatedExpression(N1, DAG, LegalOperations, ForCodeSize, CostN1);
  12975. if (NegN0 && NegN1 &&
  12976. (CostN0 == TargetLowering::NegatibleCost::Cheaper ||
  12977. CostN1 == TargetLowering::NegatibleCost::Cheaper))
  12978. return DAG.getNode(ISD::FDIV, SDLoc(N), VT, NegN0, NegN1);
  12979. return SDValue();
  12980. }
  12981. SDValue DAGCombiner::visitFREM(SDNode *N) {
  12982. SDValue N0 = N->getOperand(0);
  12983. SDValue N1 = N->getOperand(1);
  12984. EVT VT = N->getValueType(0);
  12985. SDNodeFlags Flags = N->getFlags();
  12986. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  12987. if (SDValue R = DAG.simplifyFPBinop(N->getOpcode(), N0, N1, Flags))
  12988. return R;
  12989. // fold (frem c1, c2) -> fmod(c1,c2)
  12990. if (SDValue C = DAG.FoldConstantArithmetic(ISD::FREM, SDLoc(N), VT, {N0, N1}))
  12991. return C;
  12992. if (SDValue NewSel = foldBinOpIntoSelect(N))
  12993. return NewSel;
  12994. return SDValue();
  12995. }
  12996. SDValue DAGCombiner::visitFSQRT(SDNode *N) {
  12997. SDNodeFlags Flags = N->getFlags();
  12998. const TargetOptions &Options = DAG.getTarget().Options;
  12999. // Require 'ninf' flag since sqrt(+Inf) = +Inf, but the estimation goes as:
  13000. // sqrt(+Inf) == rsqrt(+Inf) * +Inf = 0 * +Inf = NaN
  13001. if (!Flags.hasApproximateFuncs() ||
  13002. (!Options.NoInfsFPMath && !Flags.hasNoInfs()))
  13003. return SDValue();
  13004. SDValue N0 = N->getOperand(0);
  13005. if (TLI.isFsqrtCheap(N0, DAG))
  13006. return SDValue();
  13007. // FSQRT nodes have flags that propagate to the created nodes.
  13008. // TODO: If this is N0/sqrt(N0), and we reach this node before trying to
  13009. // transform the fdiv, we may produce a sub-optimal estimate sequence
  13010. // because the reciprocal calculation may not have to filter out a
  13011. // 0.0 input.
  13012. return buildSqrtEstimate(N0, Flags);
  13013. }
  13014. /// copysign(x, fp_extend(y)) -> copysign(x, y)
  13015. /// copysign(x, fp_round(y)) -> copysign(x, y)
  13016. static inline bool CanCombineFCOPYSIGN_EXTEND_ROUND(SDNode *N) {
  13017. SDValue N1 = N->getOperand(1);
  13018. if ((N1.getOpcode() == ISD::FP_EXTEND ||
  13019. N1.getOpcode() == ISD::FP_ROUND)) {
  13020. EVT N1VT = N1->getValueType(0);
  13021. EVT N1Op0VT = N1->getOperand(0).getValueType();
  13022. // Always fold no-op FP casts.
  13023. if (N1VT == N1Op0VT)
  13024. return true;
  13025. // Do not optimize out type conversion of f128 type yet.
  13026. // For some targets like x86_64, configuration is changed to keep one f128
  13027. // value in one SSE register, but instruction selection cannot handle
  13028. // FCOPYSIGN on SSE registers yet.
  13029. if (N1Op0VT == MVT::f128)
  13030. return false;
  13031. // Avoid mismatched vector operand types, for better instruction selection.
  13032. if (N1Op0VT.isVector())
  13033. return false;
  13034. return true;
  13035. }
  13036. return false;
  13037. }
  13038. SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
  13039. SDValue N0 = N->getOperand(0);
  13040. SDValue N1 = N->getOperand(1);
  13041. EVT VT = N->getValueType(0);
  13042. // fold (fcopysign c1, c2) -> fcopysign(c1,c2)
  13043. if (SDValue C =
  13044. DAG.FoldConstantArithmetic(ISD::FCOPYSIGN, SDLoc(N), VT, {N0, N1}))
  13045. return C;
  13046. if (ConstantFPSDNode *N1C = isConstOrConstSplatFP(N->getOperand(1))) {
  13047. const APFloat &V = N1C->getValueAPF();
  13048. // copysign(x, c1) -> fabs(x) iff ispos(c1)
  13049. // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
  13050. if (!V.isNegative()) {
  13051. if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
  13052. return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
  13053. } else {
  13054. if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
  13055. return DAG.getNode(ISD::FNEG, SDLoc(N), VT,
  13056. DAG.getNode(ISD::FABS, SDLoc(N0), VT, N0));
  13057. }
  13058. }
  13059. // copysign(fabs(x), y) -> copysign(x, y)
  13060. // copysign(fneg(x), y) -> copysign(x, y)
  13061. // copysign(copysign(x,z), y) -> copysign(x, y)
  13062. if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
  13063. N0.getOpcode() == ISD::FCOPYSIGN)
  13064. return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0.getOperand(0), N1);
  13065. // copysign(x, abs(y)) -> abs(x)
  13066. if (N1.getOpcode() == ISD::FABS)
  13067. return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
  13068. // copysign(x, copysign(y,z)) -> copysign(x, z)
  13069. if (N1.getOpcode() == ISD::FCOPYSIGN)
  13070. return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(1));
  13071. // copysign(x, fp_extend(y)) -> copysign(x, y)
  13072. // copysign(x, fp_round(y)) -> copysign(x, y)
  13073. if (CanCombineFCOPYSIGN_EXTEND_ROUND(N))
  13074. return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT, N0, N1.getOperand(0));
  13075. return SDValue();
  13076. }
  13077. SDValue DAGCombiner::visitFPOW(SDNode *N) {
  13078. ConstantFPSDNode *ExponentC = isConstOrConstSplatFP(N->getOperand(1));
  13079. if (!ExponentC)
  13080. return SDValue();
  13081. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  13082. // Try to convert x ** (1/3) into cube root.
  13083. // TODO: Handle the various flavors of long double.
  13084. // TODO: Since we're approximating, we don't need an exact 1/3 exponent.
  13085. // Some range near 1/3 should be fine.
  13086. EVT VT = N->getValueType(0);
  13087. if ((VT == MVT::f32 && ExponentC->getValueAPF().isExactlyValue(1.0f/3.0f)) ||
  13088. (VT == MVT::f64 && ExponentC->getValueAPF().isExactlyValue(1.0/3.0))) {
  13089. // pow(-0.0, 1/3) = +0.0; cbrt(-0.0) = -0.0.
  13090. // pow(-inf, 1/3) = +inf; cbrt(-inf) = -inf.
  13091. // pow(-val, 1/3) = nan; cbrt(-val) = -num.
  13092. // For regular numbers, rounding may cause the results to differ.
  13093. // Therefore, we require { nsz ninf nnan afn } for this transform.
  13094. // TODO: We could select out the special cases if we don't have nsz/ninf.
  13095. SDNodeFlags Flags = N->getFlags();
  13096. if (!Flags.hasNoSignedZeros() || !Flags.hasNoInfs() || !Flags.hasNoNaNs() ||
  13097. !Flags.hasApproximateFuncs())
  13098. return SDValue();
  13099. // Do not create a cbrt() libcall if the target does not have it, and do not
  13100. // turn a pow that has lowering support into a cbrt() libcall.
  13101. if (!DAG.getLibInfo().has(LibFunc_cbrt) ||
  13102. (!DAG.getTargetLoweringInfo().isOperationExpand(ISD::FPOW, VT) &&
  13103. DAG.getTargetLoweringInfo().isOperationExpand(ISD::FCBRT, VT)))
  13104. return SDValue();
  13105. return DAG.getNode(ISD::FCBRT, SDLoc(N), VT, N->getOperand(0));
  13106. }
  13107. // Try to convert x ** (1/4) and x ** (3/4) into square roots.
  13108. // x ** (1/2) is canonicalized to sqrt, so we do not bother with that case.
  13109. // TODO: This could be extended (using a target hook) to handle smaller
  13110. // power-of-2 fractional exponents.
  13111. bool ExponentIs025 = ExponentC->getValueAPF().isExactlyValue(0.25);
  13112. bool ExponentIs075 = ExponentC->getValueAPF().isExactlyValue(0.75);
  13113. if (ExponentIs025 || ExponentIs075) {
  13114. // pow(-0.0, 0.25) = +0.0; sqrt(sqrt(-0.0)) = -0.0.
  13115. // pow(-inf, 0.25) = +inf; sqrt(sqrt(-inf)) = NaN.
  13116. // pow(-0.0, 0.75) = +0.0; sqrt(-0.0) * sqrt(sqrt(-0.0)) = +0.0.
  13117. // pow(-inf, 0.75) = +inf; sqrt(-inf) * sqrt(sqrt(-inf)) = NaN.
  13118. // For regular numbers, rounding may cause the results to differ.
  13119. // Therefore, we require { nsz ninf afn } for this transform.
  13120. // TODO: We could select out the special cases if we don't have nsz/ninf.
  13121. SDNodeFlags Flags = N->getFlags();
  13122. // We only need no signed zeros for the 0.25 case.
  13123. if ((!Flags.hasNoSignedZeros() && ExponentIs025) || !Flags.hasNoInfs() ||
  13124. !Flags.hasApproximateFuncs())
  13125. return SDValue();
  13126. // Don't double the number of libcalls. We are trying to inline fast code.
  13127. if (!DAG.getTargetLoweringInfo().isOperationLegalOrCustom(ISD::FSQRT, VT))
  13128. return SDValue();
  13129. // Assume that libcalls are the smallest code.
  13130. // TODO: This restriction should probably be lifted for vectors.
  13131. if (ForCodeSize)
  13132. return SDValue();
  13133. // pow(X, 0.25) --> sqrt(sqrt(X))
  13134. SDLoc DL(N);
  13135. SDValue Sqrt = DAG.getNode(ISD::FSQRT, DL, VT, N->getOperand(0));
  13136. SDValue SqrtSqrt = DAG.getNode(ISD::FSQRT, DL, VT, Sqrt);
  13137. if (ExponentIs025)
  13138. return SqrtSqrt;
  13139. // pow(X, 0.75) --> sqrt(X) * sqrt(sqrt(X))
  13140. return DAG.getNode(ISD::FMUL, DL, VT, Sqrt, SqrtSqrt);
  13141. }
  13142. return SDValue();
  13143. }
  13144. static SDValue foldFPToIntToFP(SDNode *N, SelectionDAG &DAG,
  13145. const TargetLowering &TLI) {
  13146. // We only do this if the target has legal ftrunc. Otherwise, we'd likely be
  13147. // replacing casts with a libcall. We also must be allowed to ignore -0.0
  13148. // because FTRUNC will return -0.0 for (-1.0, -0.0), but using integer
  13149. // conversions would return +0.0.
  13150. // FIXME: We should be able to use node-level FMF here.
  13151. // TODO: If strict math, should we use FABS (+ range check for signed cast)?
  13152. EVT VT = N->getValueType(0);
  13153. if (!TLI.isOperationLegal(ISD::FTRUNC, VT) ||
  13154. !DAG.getTarget().Options.NoSignedZerosFPMath)
  13155. return SDValue();
  13156. // fptosi/fptoui round towards zero, so converting from FP to integer and
  13157. // back is the same as an 'ftrunc': [us]itofp (fpto[us]i X) --> ftrunc X
  13158. SDValue N0 = N->getOperand(0);
  13159. if (N->getOpcode() == ISD::SINT_TO_FP && N0.getOpcode() == ISD::FP_TO_SINT &&
  13160. N0.getOperand(0).getValueType() == VT)
  13161. return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0));
  13162. if (N->getOpcode() == ISD::UINT_TO_FP && N0.getOpcode() == ISD::FP_TO_UINT &&
  13163. N0.getOperand(0).getValueType() == VT)
  13164. return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0.getOperand(0));
  13165. return SDValue();
  13166. }
  13167. SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
  13168. SDValue N0 = N->getOperand(0);
  13169. EVT VT = N->getValueType(0);
  13170. EVT OpVT = N0.getValueType();
  13171. // [us]itofp(undef) = 0, because the result value is bounded.
  13172. if (N0.isUndef())
  13173. return DAG.getConstantFP(0.0, SDLoc(N), VT);
  13174. // fold (sint_to_fp c1) -> c1fp
  13175. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  13176. // ...but only if the target supports immediate floating-point values
  13177. (!LegalOperations ||
  13178. TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
  13179. return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
  13180. // If the input is a legal type, and SINT_TO_FP is not legal on this target,
  13181. // but UINT_TO_FP is legal on this target, try to convert.
  13182. if (!hasOperation(ISD::SINT_TO_FP, OpVT) &&
  13183. hasOperation(ISD::UINT_TO_FP, OpVT)) {
  13184. // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
  13185. if (DAG.SignBitIsZero(N0))
  13186. return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
  13187. }
  13188. // The next optimizations are desirable only if SELECT_CC can be lowered.
  13189. // fold (sint_to_fp (setcc x, y, cc)) -> (select (setcc x, y, cc), -1.0, 0.0)
  13190. if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
  13191. !VT.isVector() &&
  13192. (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
  13193. SDLoc DL(N);
  13194. return DAG.getSelect(DL, VT, N0, DAG.getConstantFP(-1.0, DL, VT),
  13195. DAG.getConstantFP(0.0, DL, VT));
  13196. }
  13197. // fold (sint_to_fp (zext (setcc x, y, cc))) ->
  13198. // (select (setcc x, y, cc), 1.0, 0.0)
  13199. if (N0.getOpcode() == ISD::ZERO_EXTEND &&
  13200. N0.getOperand(0).getOpcode() == ISD::SETCC && !VT.isVector() &&
  13201. (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
  13202. SDLoc DL(N);
  13203. return DAG.getSelect(DL, VT, N0.getOperand(0),
  13204. DAG.getConstantFP(1.0, DL, VT),
  13205. DAG.getConstantFP(0.0, DL, VT));
  13206. }
  13207. if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI))
  13208. return FTrunc;
  13209. return SDValue();
  13210. }
  13211. SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
  13212. SDValue N0 = N->getOperand(0);
  13213. EVT VT = N->getValueType(0);
  13214. EVT OpVT = N0.getValueType();
  13215. // [us]itofp(undef) = 0, because the result value is bounded.
  13216. if (N0.isUndef())
  13217. return DAG.getConstantFP(0.0, SDLoc(N), VT);
  13218. // fold (uint_to_fp c1) -> c1fp
  13219. if (DAG.isConstantIntBuildVectorOrConstantInt(N0) &&
  13220. // ...but only if the target supports immediate floating-point values
  13221. (!LegalOperations ||
  13222. TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT)))
  13223. return DAG.getNode(ISD::UINT_TO_FP, SDLoc(N), VT, N0);
  13224. // If the input is a legal type, and UINT_TO_FP is not legal on this target,
  13225. // but SINT_TO_FP is legal on this target, try to convert.
  13226. if (!hasOperation(ISD::UINT_TO_FP, OpVT) &&
  13227. hasOperation(ISD::SINT_TO_FP, OpVT)) {
  13228. // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
  13229. if (DAG.SignBitIsZero(N0))
  13230. return DAG.getNode(ISD::SINT_TO_FP, SDLoc(N), VT, N0);
  13231. }
  13232. // fold (uint_to_fp (setcc x, y, cc)) -> (select (setcc x, y, cc), 1.0, 0.0)
  13233. if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
  13234. (!LegalOperations || TLI.isOperationLegalOrCustom(ISD::ConstantFP, VT))) {
  13235. SDLoc DL(N);
  13236. return DAG.getSelect(DL, VT, N0, DAG.getConstantFP(1.0, DL, VT),
  13237. DAG.getConstantFP(0.0, DL, VT));
  13238. }
  13239. if (SDValue FTrunc = foldFPToIntToFP(N, DAG, TLI))
  13240. return FTrunc;
  13241. return SDValue();
  13242. }
  13243. // Fold (fp_to_{s/u}int ({s/u}int_to_fpx)) -> zext x, sext x, trunc x, or x
  13244. static SDValue FoldIntToFPToInt(SDNode *N, SelectionDAG &DAG) {
  13245. SDValue N0 = N->getOperand(0);
  13246. EVT VT = N->getValueType(0);
  13247. if (N0.getOpcode() != ISD::UINT_TO_FP && N0.getOpcode() != ISD::SINT_TO_FP)
  13248. return SDValue();
  13249. SDValue Src = N0.getOperand(0);
  13250. EVT SrcVT = Src.getValueType();
  13251. bool IsInputSigned = N0.getOpcode() == ISD::SINT_TO_FP;
  13252. bool IsOutputSigned = N->getOpcode() == ISD::FP_TO_SINT;
  13253. // We can safely assume the conversion won't overflow the output range,
  13254. // because (for example) (uint8_t)18293.f is undefined behavior.
  13255. // Since we can assume the conversion won't overflow, our decision as to
  13256. // whether the input will fit in the float should depend on the minimum
  13257. // of the input range and output range.
  13258. // This means this is also safe for a signed input and unsigned output, since
  13259. // a negative input would lead to undefined behavior.
  13260. unsigned InputSize = (int)SrcVT.getScalarSizeInBits() - IsInputSigned;
  13261. unsigned OutputSize = (int)VT.getScalarSizeInBits() - IsOutputSigned;
  13262. unsigned ActualSize = std::min(InputSize, OutputSize);
  13263. const fltSemantics &sem = DAG.EVTToAPFloatSemantics(N0.getValueType());
  13264. // We can only fold away the float conversion if the input range can be
  13265. // represented exactly in the float range.
  13266. if (APFloat::semanticsPrecision(sem) >= ActualSize) {
  13267. if (VT.getScalarSizeInBits() > SrcVT.getScalarSizeInBits()) {
  13268. unsigned ExtOp = IsInputSigned && IsOutputSigned ? ISD::SIGN_EXTEND
  13269. : ISD::ZERO_EXTEND;
  13270. return DAG.getNode(ExtOp, SDLoc(N), VT, Src);
  13271. }
  13272. if (VT.getScalarSizeInBits() < SrcVT.getScalarSizeInBits())
  13273. return DAG.getNode(ISD::TRUNCATE, SDLoc(N), VT, Src);
  13274. return DAG.getBitcast(VT, Src);
  13275. }
  13276. return SDValue();
  13277. }
  13278. SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
  13279. SDValue N0 = N->getOperand(0);
  13280. EVT VT = N->getValueType(0);
  13281. // fold (fp_to_sint undef) -> undef
  13282. if (N0.isUndef())
  13283. return DAG.getUNDEF(VT);
  13284. // fold (fp_to_sint c1fp) -> c1
  13285. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  13286. return DAG.getNode(ISD::FP_TO_SINT, SDLoc(N), VT, N0);
  13287. return FoldIntToFPToInt(N, DAG);
  13288. }
  13289. SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
  13290. SDValue N0 = N->getOperand(0);
  13291. EVT VT = N->getValueType(0);
  13292. // fold (fp_to_uint undef) -> undef
  13293. if (N0.isUndef())
  13294. return DAG.getUNDEF(VT);
  13295. // fold (fp_to_uint c1fp) -> c1
  13296. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  13297. return DAG.getNode(ISD::FP_TO_UINT, SDLoc(N), VT, N0);
  13298. return FoldIntToFPToInt(N, DAG);
  13299. }
  13300. SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
  13301. SDValue N0 = N->getOperand(0);
  13302. SDValue N1 = N->getOperand(1);
  13303. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  13304. EVT VT = N->getValueType(0);
  13305. // fold (fp_round c1fp) -> c1fp
  13306. if (N0CFP)
  13307. return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT, N0, N1);
  13308. // fold (fp_round (fp_extend x)) -> x
  13309. if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
  13310. return N0.getOperand(0);
  13311. // fold (fp_round (fp_round x)) -> (fp_round x)
  13312. if (N0.getOpcode() == ISD::FP_ROUND) {
  13313. const bool NIsTrunc = N->getConstantOperandVal(1) == 1;
  13314. const bool N0IsTrunc = N0.getConstantOperandVal(1) == 1;
  13315. // Skip this folding if it results in an fp_round from f80 to f16.
  13316. //
  13317. // f80 to f16 always generates an expensive (and as yet, unimplemented)
  13318. // libcall to __truncxfhf2 instead of selecting native f16 conversion
  13319. // instructions from f32 or f64. Moreover, the first (value-preserving)
  13320. // fp_round from f80 to either f32 or f64 may become a NOP in platforms like
  13321. // x86.
  13322. if (N0.getOperand(0).getValueType() == MVT::f80 && VT == MVT::f16)
  13323. return SDValue();
  13324. // If the first fp_round isn't a value preserving truncation, it might
  13325. // introduce a tie in the second fp_round, that wouldn't occur in the
  13326. // single-step fp_round we want to fold to.
  13327. // In other words, double rounding isn't the same as rounding.
  13328. // Also, this is a value preserving truncation iff both fp_round's are.
  13329. if (DAG.getTarget().Options.UnsafeFPMath || N0IsTrunc) {
  13330. SDLoc DL(N);
  13331. return DAG.getNode(ISD::FP_ROUND, DL, VT, N0.getOperand(0),
  13332. DAG.getIntPtrConstant(NIsTrunc && N0IsTrunc, DL));
  13333. }
  13334. }
  13335. // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
  13336. if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
  13337. SDValue Tmp = DAG.getNode(ISD::FP_ROUND, SDLoc(N0), VT,
  13338. N0.getOperand(0), N1);
  13339. AddToWorklist(Tmp.getNode());
  13340. return DAG.getNode(ISD::FCOPYSIGN, SDLoc(N), VT,
  13341. Tmp, N0.getOperand(1));
  13342. }
  13343. if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
  13344. return NewVSel;
  13345. return SDValue();
  13346. }
  13347. SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
  13348. SDValue N0 = N->getOperand(0);
  13349. EVT VT = N->getValueType(0);
  13350. // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
  13351. if (N->hasOneUse() &&
  13352. N->use_begin()->getOpcode() == ISD::FP_ROUND)
  13353. return SDValue();
  13354. // fold (fp_extend c1fp) -> c1fp
  13355. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  13356. return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, N0);
  13357. // fold (fp_extend (fp16_to_fp op)) -> (fp16_to_fp op)
  13358. if (N0.getOpcode() == ISD::FP16_TO_FP &&
  13359. TLI.getOperationAction(ISD::FP16_TO_FP, VT) == TargetLowering::Legal)
  13360. return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), VT, N0.getOperand(0));
  13361. // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
  13362. // value of X.
  13363. if (N0.getOpcode() == ISD::FP_ROUND
  13364. && N0.getConstantOperandVal(1) == 1) {
  13365. SDValue In = N0.getOperand(0);
  13366. if (In.getValueType() == VT) return In;
  13367. if (VT.bitsLT(In.getValueType()))
  13368. return DAG.getNode(ISD::FP_ROUND, SDLoc(N), VT,
  13369. In, N0.getOperand(1));
  13370. return DAG.getNode(ISD::FP_EXTEND, SDLoc(N), VT, In);
  13371. }
  13372. // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
  13373. if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
  13374. TLI.isLoadExtLegalOrCustom(ISD::EXTLOAD, VT, N0.getValueType())) {
  13375. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  13376. SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, SDLoc(N), VT,
  13377. LN0->getChain(),
  13378. LN0->getBasePtr(), N0.getValueType(),
  13379. LN0->getMemOperand());
  13380. CombineTo(N, ExtLoad);
  13381. CombineTo(N0.getNode(),
  13382. DAG.getNode(ISD::FP_ROUND, SDLoc(N0),
  13383. N0.getValueType(), ExtLoad,
  13384. DAG.getIntPtrConstant(1, SDLoc(N0))),
  13385. ExtLoad.getValue(1));
  13386. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  13387. }
  13388. if (SDValue NewVSel = matchVSelectOpSizesWithSetCC(N))
  13389. return NewVSel;
  13390. return SDValue();
  13391. }
  13392. SDValue DAGCombiner::visitFCEIL(SDNode *N) {
  13393. SDValue N0 = N->getOperand(0);
  13394. EVT VT = N->getValueType(0);
  13395. // fold (fceil c1) -> fceil(c1)
  13396. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  13397. return DAG.getNode(ISD::FCEIL, SDLoc(N), VT, N0);
  13398. return SDValue();
  13399. }
  13400. SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
  13401. SDValue N0 = N->getOperand(0);
  13402. EVT VT = N->getValueType(0);
  13403. // fold (ftrunc c1) -> ftrunc(c1)
  13404. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  13405. return DAG.getNode(ISD::FTRUNC, SDLoc(N), VT, N0);
  13406. // fold ftrunc (known rounded int x) -> x
  13407. // ftrunc is a part of fptosi/fptoui expansion on some targets, so this is
  13408. // likely to be generated to extract integer from a rounded floating value.
  13409. switch (N0.getOpcode()) {
  13410. default: break;
  13411. case ISD::FRINT:
  13412. case ISD::FTRUNC:
  13413. case ISD::FNEARBYINT:
  13414. case ISD::FFLOOR:
  13415. case ISD::FCEIL:
  13416. return N0;
  13417. }
  13418. return SDValue();
  13419. }
  13420. SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
  13421. SDValue N0 = N->getOperand(0);
  13422. EVT VT = N->getValueType(0);
  13423. // fold (ffloor c1) -> ffloor(c1)
  13424. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  13425. return DAG.getNode(ISD::FFLOOR, SDLoc(N), VT, N0);
  13426. return SDValue();
  13427. }
  13428. SDValue DAGCombiner::visitFNEG(SDNode *N) {
  13429. SDValue N0 = N->getOperand(0);
  13430. EVT VT = N->getValueType(0);
  13431. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  13432. // Constant fold FNEG.
  13433. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  13434. return DAG.getNode(ISD::FNEG, SDLoc(N), VT, N0);
  13435. if (SDValue NegN0 =
  13436. TLI.getNegatedExpression(N0, DAG, LegalOperations, ForCodeSize))
  13437. return NegN0;
  13438. // -(X-Y) -> (Y-X) is unsafe because when X==Y, -0.0 != +0.0
  13439. // FIXME: This is duplicated in getNegatibleCost, but getNegatibleCost doesn't
  13440. // know it was called from a context with a nsz flag if the input fsub does
  13441. // not.
  13442. if (N0.getOpcode() == ISD::FSUB &&
  13443. (DAG.getTarget().Options.NoSignedZerosFPMath ||
  13444. N->getFlags().hasNoSignedZeros()) && N0.hasOneUse()) {
  13445. return DAG.getNode(ISD::FSUB, SDLoc(N), VT, N0.getOperand(1),
  13446. N0.getOperand(0));
  13447. }
  13448. if (SDValue Cast = foldSignChangeInBitcast(N))
  13449. return Cast;
  13450. return SDValue();
  13451. }
  13452. SDValue DAGCombiner::visitFMinMax(SDNode *N) {
  13453. SDValue N0 = N->getOperand(0);
  13454. SDValue N1 = N->getOperand(1);
  13455. EVT VT = N->getValueType(0);
  13456. const SDNodeFlags Flags = N->getFlags();
  13457. unsigned Opc = N->getOpcode();
  13458. bool PropagatesNaN = Opc == ISD::FMINIMUM || Opc == ISD::FMAXIMUM;
  13459. bool IsMin = Opc == ISD::FMINNUM || Opc == ISD::FMINIMUM;
  13460. SelectionDAG::FlagInserter FlagsInserter(DAG, N);
  13461. // Constant fold.
  13462. if (SDValue C = DAG.FoldConstantArithmetic(Opc, SDLoc(N), VT, {N0, N1}))
  13463. return C;
  13464. // Canonicalize to constant on RHS.
  13465. if (DAG.isConstantFPBuildVectorOrConstantFP(N0) &&
  13466. !DAG.isConstantFPBuildVectorOrConstantFP(N1))
  13467. return DAG.getNode(N->getOpcode(), SDLoc(N), VT, N1, N0);
  13468. if (const ConstantFPSDNode *N1CFP = isConstOrConstSplatFP(N1)) {
  13469. const APFloat &AF = N1CFP->getValueAPF();
  13470. // minnum(X, nan) -> X
  13471. // maxnum(X, nan) -> X
  13472. // minimum(X, nan) -> nan
  13473. // maximum(X, nan) -> nan
  13474. if (AF.isNaN())
  13475. return PropagatesNaN ? N->getOperand(1) : N->getOperand(0);
  13476. // In the following folds, inf can be replaced with the largest finite
  13477. // float, if the ninf flag is set.
  13478. if (AF.isInfinity() || (Flags.hasNoInfs() && AF.isLargest())) {
  13479. // minnum(X, -inf) -> -inf
  13480. // maxnum(X, +inf) -> +inf
  13481. // minimum(X, -inf) -> -inf if nnan
  13482. // maximum(X, +inf) -> +inf if nnan
  13483. if (IsMin == AF.isNegative() && (!PropagatesNaN || Flags.hasNoNaNs()))
  13484. return N->getOperand(1);
  13485. // minnum(X, +inf) -> X if nnan
  13486. // maxnum(X, -inf) -> X if nnan
  13487. // minimum(X, +inf) -> X
  13488. // maximum(X, -inf) -> X
  13489. if (IsMin != AF.isNegative() && (PropagatesNaN || Flags.hasNoNaNs()))
  13490. return N->getOperand(0);
  13491. }
  13492. }
  13493. return SDValue();
  13494. }
  13495. SDValue DAGCombiner::visitFABS(SDNode *N) {
  13496. SDValue N0 = N->getOperand(0);
  13497. EVT VT = N->getValueType(0);
  13498. // fold (fabs c1) -> fabs(c1)
  13499. if (DAG.isConstantFPBuildVectorOrConstantFP(N0))
  13500. return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0);
  13501. // fold (fabs (fabs x)) -> (fabs x)
  13502. if (N0.getOpcode() == ISD::FABS)
  13503. return N->getOperand(0);
  13504. // fold (fabs (fneg x)) -> (fabs x)
  13505. // fold (fabs (fcopysign x, y)) -> (fabs x)
  13506. if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
  13507. return DAG.getNode(ISD::FABS, SDLoc(N), VT, N0.getOperand(0));
  13508. if (SDValue Cast = foldSignChangeInBitcast(N))
  13509. return Cast;
  13510. return SDValue();
  13511. }
  13512. SDValue DAGCombiner::visitBRCOND(SDNode *N) {
  13513. SDValue Chain = N->getOperand(0);
  13514. SDValue N1 = N->getOperand(1);
  13515. SDValue N2 = N->getOperand(2);
  13516. // BRCOND(FREEZE(cond)) is equivalent to BRCOND(cond) (both are
  13517. // nondeterministic jumps).
  13518. if (N1->getOpcode() == ISD::FREEZE && N1.hasOneUse()) {
  13519. return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other, Chain,
  13520. N1->getOperand(0), N2);
  13521. }
  13522. // If N is a constant we could fold this into a fallthrough or unconditional
  13523. // branch. However that doesn't happen very often in normal code, because
  13524. // Instcombine/SimplifyCFG should have handled the available opportunities.
  13525. // If we did this folding here, it would be necessary to update the
  13526. // MachineBasicBlock CFG, which is awkward.
  13527. // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
  13528. // on the target.
  13529. if (N1.getOpcode() == ISD::SETCC &&
  13530. TLI.isOperationLegalOrCustom(ISD::BR_CC,
  13531. N1.getOperand(0).getValueType())) {
  13532. return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
  13533. Chain, N1.getOperand(2),
  13534. N1.getOperand(0), N1.getOperand(1), N2);
  13535. }
  13536. if (N1.hasOneUse()) {
  13537. // rebuildSetCC calls visitXor which may change the Chain when there is a
  13538. // STRICT_FSETCC/STRICT_FSETCCS involved. Use a handle to track changes.
  13539. HandleSDNode ChainHandle(Chain);
  13540. if (SDValue NewN1 = rebuildSetCC(N1))
  13541. return DAG.getNode(ISD::BRCOND, SDLoc(N), MVT::Other,
  13542. ChainHandle.getValue(), NewN1, N2);
  13543. }
  13544. return SDValue();
  13545. }
  13546. SDValue DAGCombiner::rebuildSetCC(SDValue N) {
  13547. if (N.getOpcode() == ISD::SRL ||
  13548. (N.getOpcode() == ISD::TRUNCATE &&
  13549. (N.getOperand(0).hasOneUse() &&
  13550. N.getOperand(0).getOpcode() == ISD::SRL))) {
  13551. // Look pass the truncate.
  13552. if (N.getOpcode() == ISD::TRUNCATE)
  13553. N = N.getOperand(0);
  13554. // Match this pattern so that we can generate simpler code:
  13555. //
  13556. // %a = ...
  13557. // %b = and i32 %a, 2
  13558. // %c = srl i32 %b, 1
  13559. // brcond i32 %c ...
  13560. //
  13561. // into
  13562. //
  13563. // %a = ...
  13564. // %b = and i32 %a, 2
  13565. // %c = setcc eq %b, 0
  13566. // brcond %c ...
  13567. //
  13568. // This applies only when the AND constant value has one bit set and the
  13569. // SRL constant is equal to the log2 of the AND constant. The back-end is
  13570. // smart enough to convert the result into a TEST/JMP sequence.
  13571. SDValue Op0 = N.getOperand(0);
  13572. SDValue Op1 = N.getOperand(1);
  13573. if (Op0.getOpcode() == ISD::AND && Op1.getOpcode() == ISD::Constant) {
  13574. SDValue AndOp1 = Op0.getOperand(1);
  13575. if (AndOp1.getOpcode() == ISD::Constant) {
  13576. const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
  13577. if (AndConst.isPowerOf2() &&
  13578. cast<ConstantSDNode>(Op1)->getAPIntValue() == AndConst.logBase2()) {
  13579. SDLoc DL(N);
  13580. return DAG.getSetCC(DL, getSetCCResultType(Op0.getValueType()),
  13581. Op0, DAG.getConstant(0, DL, Op0.getValueType()),
  13582. ISD::SETNE);
  13583. }
  13584. }
  13585. }
  13586. }
  13587. // Transform (brcond (xor x, y)) -> (brcond (setcc, x, y, ne))
  13588. // Transform (brcond (xor (xor x, y), -1)) -> (brcond (setcc, x, y, eq))
  13589. if (N.getOpcode() == ISD::XOR) {
  13590. // Because we may call this on a speculatively constructed
  13591. // SimplifiedSetCC Node, we need to simplify this node first.
  13592. // Ideally this should be folded into SimplifySetCC and not
  13593. // here. For now, grab a handle to N so we don't lose it from
  13594. // replacements interal to the visit.
  13595. HandleSDNode XORHandle(N);
  13596. while (N.getOpcode() == ISD::XOR) {
  13597. SDValue Tmp = visitXOR(N.getNode());
  13598. // No simplification done.
  13599. if (!Tmp.getNode())
  13600. break;
  13601. // Returning N is form in-visit replacement that may invalidated
  13602. // N. Grab value from Handle.
  13603. if (Tmp.getNode() == N.getNode())
  13604. N = XORHandle.getValue();
  13605. else // Node simplified. Try simplifying again.
  13606. N = Tmp;
  13607. }
  13608. if (N.getOpcode() != ISD::XOR)
  13609. return N;
  13610. SDValue Op0 = N->getOperand(0);
  13611. SDValue Op1 = N->getOperand(1);
  13612. if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
  13613. bool Equal = false;
  13614. // (brcond (xor (xor x, y), -1)) -> (brcond (setcc x, y, eq))
  13615. if (isBitwiseNot(N) && Op0.hasOneUse() && Op0.getOpcode() == ISD::XOR &&
  13616. Op0.getValueType() == MVT::i1) {
  13617. N = Op0;
  13618. Op0 = N->getOperand(0);
  13619. Op1 = N->getOperand(1);
  13620. Equal = true;
  13621. }
  13622. EVT SetCCVT = N.getValueType();
  13623. if (LegalTypes)
  13624. SetCCVT = getSetCCResultType(SetCCVT);
  13625. // Replace the uses of XOR with SETCC
  13626. return DAG.getSetCC(SDLoc(N), SetCCVT, Op0, Op1,
  13627. Equal ? ISD::SETEQ : ISD::SETNE);
  13628. }
  13629. }
  13630. return SDValue();
  13631. }
  13632. // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
  13633. //
  13634. SDValue DAGCombiner::visitBR_CC(SDNode *N) {
  13635. CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
  13636. SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
  13637. // If N is a constant we could fold this into a fallthrough or unconditional
  13638. // branch. However that doesn't happen very often in normal code, because
  13639. // Instcombine/SimplifyCFG should have handled the available opportunities.
  13640. // If we did this folding here, it would be necessary to update the
  13641. // MachineBasicBlock CFG, which is awkward.
  13642. // Use SimplifySetCC to simplify SETCC's.
  13643. SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
  13644. CondLHS, CondRHS, CC->get(), SDLoc(N),
  13645. false);
  13646. if (Simp.getNode()) AddToWorklist(Simp.getNode());
  13647. // fold to a simpler setcc
  13648. if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
  13649. return DAG.getNode(ISD::BR_CC, SDLoc(N), MVT::Other,
  13650. N->getOperand(0), Simp.getOperand(2),
  13651. Simp.getOperand(0), Simp.getOperand(1),
  13652. N->getOperand(4));
  13653. return SDValue();
  13654. }
  13655. static bool getCombineLoadStoreParts(SDNode *N, unsigned Inc, unsigned Dec,
  13656. bool &IsLoad, bool &IsMasked, SDValue &Ptr,
  13657. const TargetLowering &TLI) {
  13658. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
  13659. if (LD->isIndexed())
  13660. return false;
  13661. EVT VT = LD->getMemoryVT();
  13662. if (!TLI.isIndexedLoadLegal(Inc, VT) && !TLI.isIndexedLoadLegal(Dec, VT))
  13663. return false;
  13664. Ptr = LD->getBasePtr();
  13665. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
  13666. if (ST->isIndexed())
  13667. return false;
  13668. EVT VT = ST->getMemoryVT();
  13669. if (!TLI.isIndexedStoreLegal(Inc, VT) && !TLI.isIndexedStoreLegal(Dec, VT))
  13670. return false;
  13671. Ptr = ST->getBasePtr();
  13672. IsLoad = false;
  13673. } else if (MaskedLoadSDNode *LD = dyn_cast<MaskedLoadSDNode>(N)) {
  13674. if (LD->isIndexed())
  13675. return false;
  13676. EVT VT = LD->getMemoryVT();
  13677. if (!TLI.isIndexedMaskedLoadLegal(Inc, VT) &&
  13678. !TLI.isIndexedMaskedLoadLegal(Dec, VT))
  13679. return false;
  13680. Ptr = LD->getBasePtr();
  13681. IsMasked = true;
  13682. } else if (MaskedStoreSDNode *ST = dyn_cast<MaskedStoreSDNode>(N)) {
  13683. if (ST->isIndexed())
  13684. return false;
  13685. EVT VT = ST->getMemoryVT();
  13686. if (!TLI.isIndexedMaskedStoreLegal(Inc, VT) &&
  13687. !TLI.isIndexedMaskedStoreLegal(Dec, VT))
  13688. return false;
  13689. Ptr = ST->getBasePtr();
  13690. IsLoad = false;
  13691. IsMasked = true;
  13692. } else {
  13693. return false;
  13694. }
  13695. return true;
  13696. }
  13697. /// Try turning a load/store into a pre-indexed load/store when the base
  13698. /// pointer is an add or subtract and it has other uses besides the load/store.
  13699. /// After the transformation, the new indexed load/store has effectively folded
  13700. /// the add/subtract in and all of its other uses are redirected to the
  13701. /// new load/store.
  13702. bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
  13703. if (Level < AfterLegalizeDAG)
  13704. return false;
  13705. bool IsLoad = true;
  13706. bool IsMasked = false;
  13707. SDValue Ptr;
  13708. if (!getCombineLoadStoreParts(N, ISD::PRE_INC, ISD::PRE_DEC, IsLoad, IsMasked,
  13709. Ptr, TLI))
  13710. return false;
  13711. // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
  13712. // out. There is no reason to make this a preinc/predec.
  13713. if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
  13714. Ptr.getNode()->hasOneUse())
  13715. return false;
  13716. // Ask the target to do addressing mode selection.
  13717. SDValue BasePtr;
  13718. SDValue Offset;
  13719. ISD::MemIndexedMode AM = ISD::UNINDEXED;
  13720. if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
  13721. return false;
  13722. // Backends without true r+i pre-indexed forms may need to pass a
  13723. // constant base with a variable offset so that constant coercion
  13724. // will work with the patterns in canonical form.
  13725. bool Swapped = false;
  13726. if (isa<ConstantSDNode>(BasePtr)) {
  13727. std::swap(BasePtr, Offset);
  13728. Swapped = true;
  13729. }
  13730. // Don't create a indexed load / store with zero offset.
  13731. if (isNullConstant(Offset))
  13732. return false;
  13733. // Try turning it into a pre-indexed load / store except when:
  13734. // 1) The new base ptr is a frame index.
  13735. // 2) If N is a store and the new base ptr is either the same as or is a
  13736. // predecessor of the value being stored.
  13737. // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
  13738. // that would create a cycle.
  13739. // 4) All uses are load / store ops that use it as old base ptr.
  13740. // Check #1. Preinc'ing a frame index would require copying the stack pointer
  13741. // (plus the implicit offset) to a register to preinc anyway.
  13742. if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
  13743. return false;
  13744. // Check #2.
  13745. if (!IsLoad) {
  13746. SDValue Val = IsMasked ? cast<MaskedStoreSDNode>(N)->getValue()
  13747. : cast<StoreSDNode>(N)->getValue();
  13748. // Would require a copy.
  13749. if (Val == BasePtr)
  13750. return false;
  13751. // Would create a cycle.
  13752. if (Val == Ptr || Ptr->isPredecessorOf(Val.getNode()))
  13753. return false;
  13754. }
  13755. // Caches for hasPredecessorHelper.
  13756. SmallPtrSet<const SDNode *, 32> Visited;
  13757. SmallVector<const SDNode *, 16> Worklist;
  13758. Worklist.push_back(N);
  13759. // If the offset is a constant, there may be other adds of constants that
  13760. // can be folded with this one. We should do this to avoid having to keep
  13761. // a copy of the original base pointer.
  13762. SmallVector<SDNode *, 16> OtherUses;
  13763. if (isa<ConstantSDNode>(Offset))
  13764. for (SDNode::use_iterator UI = BasePtr.getNode()->use_begin(),
  13765. UE = BasePtr.getNode()->use_end();
  13766. UI != UE; ++UI) {
  13767. SDUse &Use = UI.getUse();
  13768. // Skip the use that is Ptr and uses of other results from BasePtr's
  13769. // node (important for nodes that return multiple results).
  13770. if (Use.getUser() == Ptr.getNode() || Use != BasePtr)
  13771. continue;
  13772. if (SDNode::hasPredecessorHelper(Use.getUser(), Visited, Worklist))
  13773. continue;
  13774. if (Use.getUser()->getOpcode() != ISD::ADD &&
  13775. Use.getUser()->getOpcode() != ISD::SUB) {
  13776. OtherUses.clear();
  13777. break;
  13778. }
  13779. SDValue Op1 = Use.getUser()->getOperand((UI.getOperandNo() + 1) & 1);
  13780. if (!isa<ConstantSDNode>(Op1)) {
  13781. OtherUses.clear();
  13782. break;
  13783. }
  13784. // FIXME: In some cases, we can be smarter about this.
  13785. if (Op1.getValueType() != Offset.getValueType()) {
  13786. OtherUses.clear();
  13787. break;
  13788. }
  13789. OtherUses.push_back(Use.getUser());
  13790. }
  13791. if (Swapped)
  13792. std::swap(BasePtr, Offset);
  13793. // Now check for #3 and #4.
  13794. bool RealUse = false;
  13795. for (SDNode *Use : Ptr.getNode()->uses()) {
  13796. if (Use == N)
  13797. continue;
  13798. if (SDNode::hasPredecessorHelper(Use, Visited, Worklist))
  13799. return false;
  13800. // If Ptr may be folded in addressing mode of other use, then it's
  13801. // not profitable to do this transformation.
  13802. if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
  13803. RealUse = true;
  13804. }
  13805. if (!RealUse)
  13806. return false;
  13807. SDValue Result;
  13808. if (!IsMasked) {
  13809. if (IsLoad)
  13810. Result = DAG.getIndexedLoad(SDValue(N, 0), SDLoc(N), BasePtr, Offset, AM);
  13811. else
  13812. Result =
  13813. DAG.getIndexedStore(SDValue(N, 0), SDLoc(N), BasePtr, Offset, AM);
  13814. } else {
  13815. if (IsLoad)
  13816. Result = DAG.getIndexedMaskedLoad(SDValue(N, 0), SDLoc(N), BasePtr,
  13817. Offset, AM);
  13818. else
  13819. Result = DAG.getIndexedMaskedStore(SDValue(N, 0), SDLoc(N), BasePtr,
  13820. Offset, AM);
  13821. }
  13822. ++PreIndexedNodes;
  13823. ++NodesCombined;
  13824. LLVM_DEBUG(dbgs() << "\nReplacing.4 "; N->dump(&DAG); dbgs() << "\nWith: ";
  13825. Result.getNode()->dump(&DAG); dbgs() << '\n');
  13826. WorklistRemover DeadNodes(*this);
  13827. if (IsLoad) {
  13828. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
  13829. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
  13830. } else {
  13831. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
  13832. }
  13833. // Finally, since the node is now dead, remove it from the graph.
  13834. deleteAndRecombine(N);
  13835. if (Swapped)
  13836. std::swap(BasePtr, Offset);
  13837. // Replace other uses of BasePtr that can be updated to use Ptr
  13838. for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
  13839. unsigned OffsetIdx = 1;
  13840. if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
  13841. OffsetIdx = 0;
  13842. assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
  13843. BasePtr.getNode() && "Expected BasePtr operand");
  13844. // We need to replace ptr0 in the following expression:
  13845. // x0 * offset0 + y0 * ptr0 = t0
  13846. // knowing that
  13847. // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
  13848. //
  13849. // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
  13850. // indexed load/store and the expression that needs to be re-written.
  13851. //
  13852. // Therefore, we have:
  13853. // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
  13854. auto *CN = cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
  13855. const APInt &Offset0 = CN->getAPIntValue();
  13856. const APInt &Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
  13857. int X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
  13858. int Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
  13859. int X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
  13860. int Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
  13861. unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
  13862. APInt CNV = Offset0;
  13863. if (X0 < 0) CNV = -CNV;
  13864. if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
  13865. else CNV = CNV - Offset1;
  13866. SDLoc DL(OtherUses[i]);
  13867. // We can now generate the new expression.
  13868. SDValue NewOp1 = DAG.getConstant(CNV, DL, CN->getValueType(0));
  13869. SDValue NewOp2 = Result.getValue(IsLoad ? 1 : 0);
  13870. SDValue NewUse = DAG.getNode(Opcode,
  13871. DL,
  13872. OtherUses[i]->getValueType(0), NewOp1, NewOp2);
  13873. DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
  13874. deleteAndRecombine(OtherUses[i]);
  13875. }
  13876. // Replace the uses of Ptr with uses of the updated base value.
  13877. DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(IsLoad ? 1 : 0));
  13878. deleteAndRecombine(Ptr.getNode());
  13879. AddToWorklist(Result.getNode());
  13880. return true;
  13881. }
  13882. static bool shouldCombineToPostInc(SDNode *N, SDValue Ptr, SDNode *PtrUse,
  13883. SDValue &BasePtr, SDValue &Offset,
  13884. ISD::MemIndexedMode &AM,
  13885. SelectionDAG &DAG,
  13886. const TargetLowering &TLI) {
  13887. if (PtrUse == N ||
  13888. (PtrUse->getOpcode() != ISD::ADD && PtrUse->getOpcode() != ISD::SUB))
  13889. return false;
  13890. if (!TLI.getPostIndexedAddressParts(N, PtrUse, BasePtr, Offset, AM, DAG))
  13891. return false;
  13892. // Don't create a indexed load / store with zero offset.
  13893. if (isNullConstant(Offset))
  13894. return false;
  13895. if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
  13896. return false;
  13897. SmallPtrSet<const SDNode *, 32> Visited;
  13898. for (SDNode *Use : BasePtr.getNode()->uses()) {
  13899. if (Use == Ptr.getNode())
  13900. continue;
  13901. // No if there's a later user which could perform the index instead.
  13902. if (isa<MemSDNode>(Use)) {
  13903. bool IsLoad = true;
  13904. bool IsMasked = false;
  13905. SDValue OtherPtr;
  13906. if (getCombineLoadStoreParts(Use, ISD::POST_INC, ISD::POST_DEC, IsLoad,
  13907. IsMasked, OtherPtr, TLI)) {
  13908. SmallVector<const SDNode *, 2> Worklist;
  13909. Worklist.push_back(Use);
  13910. if (SDNode::hasPredecessorHelper(N, Visited, Worklist))
  13911. return false;
  13912. }
  13913. }
  13914. // If all the uses are load / store addresses, then don't do the
  13915. // transformation.
  13916. if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB) {
  13917. for (SDNode *UseUse : Use->uses())
  13918. if (canFoldInAddressingMode(Use, UseUse, DAG, TLI))
  13919. return false;
  13920. }
  13921. }
  13922. return true;
  13923. }
  13924. static SDNode *getPostIndexedLoadStoreOp(SDNode *N, bool &IsLoad,
  13925. bool &IsMasked, SDValue &Ptr,
  13926. SDValue &BasePtr, SDValue &Offset,
  13927. ISD::MemIndexedMode &AM,
  13928. SelectionDAG &DAG,
  13929. const TargetLowering &TLI) {
  13930. if (!getCombineLoadStoreParts(N, ISD::POST_INC, ISD::POST_DEC, IsLoad,
  13931. IsMasked, Ptr, TLI) ||
  13932. Ptr.getNode()->hasOneUse())
  13933. return nullptr;
  13934. // Try turning it into a post-indexed load / store except when
  13935. // 1) All uses are load / store ops that use it as base ptr (and
  13936. // it may be folded as addressing mmode).
  13937. // 2) Op must be independent of N, i.e. Op is neither a predecessor
  13938. // nor a successor of N. Otherwise, if Op is folded that would
  13939. // create a cycle.
  13940. for (SDNode *Op : Ptr->uses()) {
  13941. // Check for #1.
  13942. if (!shouldCombineToPostInc(N, Ptr, Op, BasePtr, Offset, AM, DAG, TLI))
  13943. continue;
  13944. // Check for #2.
  13945. SmallPtrSet<const SDNode *, 32> Visited;
  13946. SmallVector<const SDNode *, 8> Worklist;
  13947. // Ptr is predecessor to both N and Op.
  13948. Visited.insert(Ptr.getNode());
  13949. Worklist.push_back(N);
  13950. Worklist.push_back(Op);
  13951. if (!SDNode::hasPredecessorHelper(N, Visited, Worklist) &&
  13952. !SDNode::hasPredecessorHelper(Op, Visited, Worklist))
  13953. return Op;
  13954. }
  13955. return nullptr;
  13956. }
  13957. /// Try to combine a load/store with a add/sub of the base pointer node into a
  13958. /// post-indexed load/store. The transformation folded the add/subtract into the
  13959. /// new indexed load/store effectively and all of its uses are redirected to the
  13960. /// new load/store.
  13961. bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
  13962. if (Level < AfterLegalizeDAG)
  13963. return false;
  13964. bool IsLoad = true;
  13965. bool IsMasked = false;
  13966. SDValue Ptr;
  13967. SDValue BasePtr;
  13968. SDValue Offset;
  13969. ISD::MemIndexedMode AM = ISD::UNINDEXED;
  13970. SDNode *Op = getPostIndexedLoadStoreOp(N, IsLoad, IsMasked, Ptr, BasePtr,
  13971. Offset, AM, DAG, TLI);
  13972. if (!Op)
  13973. return false;
  13974. SDValue Result;
  13975. if (!IsMasked)
  13976. Result = IsLoad ? DAG.getIndexedLoad(SDValue(N, 0), SDLoc(N), BasePtr,
  13977. Offset, AM)
  13978. : DAG.getIndexedStore(SDValue(N, 0), SDLoc(N),
  13979. BasePtr, Offset, AM);
  13980. else
  13981. Result = IsLoad ? DAG.getIndexedMaskedLoad(SDValue(N, 0), SDLoc(N),
  13982. BasePtr, Offset, AM)
  13983. : DAG.getIndexedMaskedStore(SDValue(N, 0), SDLoc(N),
  13984. BasePtr, Offset, AM);
  13985. ++PostIndexedNodes;
  13986. ++NodesCombined;
  13987. LLVM_DEBUG(dbgs() << "\nReplacing.5 "; N->dump(&DAG);
  13988. dbgs() << "\nWith: "; Result.getNode()->dump(&DAG);
  13989. dbgs() << '\n');
  13990. WorklistRemover DeadNodes(*this);
  13991. if (IsLoad) {
  13992. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
  13993. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
  13994. } else {
  13995. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
  13996. }
  13997. // Finally, since the node is now dead, remove it from the graph.
  13998. deleteAndRecombine(N);
  13999. // Replace the uses of Use with uses of the updated base value.
  14000. DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
  14001. Result.getValue(IsLoad ? 1 : 0));
  14002. deleteAndRecombine(Op);
  14003. return true;
  14004. }
  14005. /// Return the base-pointer arithmetic from an indexed \p LD.
  14006. SDValue DAGCombiner::SplitIndexingFromLoad(LoadSDNode *LD) {
  14007. ISD::MemIndexedMode AM = LD->getAddressingMode();
  14008. assert(AM != ISD::UNINDEXED);
  14009. SDValue BP = LD->getOperand(1);
  14010. SDValue Inc = LD->getOperand(2);
  14011. // Some backends use TargetConstants for load offsets, but don't expect
  14012. // TargetConstants in general ADD nodes. We can convert these constants into
  14013. // regular Constants (if the constant is not opaque).
  14014. assert((Inc.getOpcode() != ISD::TargetConstant ||
  14015. !cast<ConstantSDNode>(Inc)->isOpaque()) &&
  14016. "Cannot split out indexing using opaque target constants");
  14017. if (Inc.getOpcode() == ISD::TargetConstant) {
  14018. ConstantSDNode *ConstInc = cast<ConstantSDNode>(Inc);
  14019. Inc = DAG.getConstant(*ConstInc->getConstantIntValue(), SDLoc(Inc),
  14020. ConstInc->getValueType(0));
  14021. }
  14022. unsigned Opc =
  14023. (AM == ISD::PRE_INC || AM == ISD::POST_INC ? ISD::ADD : ISD::SUB);
  14024. return DAG.getNode(Opc, SDLoc(LD), BP.getSimpleValueType(), BP, Inc);
  14025. }
  14026. static inline ElementCount numVectorEltsOrZero(EVT T) {
  14027. return T.isVector() ? T.getVectorElementCount() : ElementCount::getFixed(0);
  14028. }
  14029. bool DAGCombiner::getTruncatedStoreValue(StoreSDNode *ST, SDValue &Val) {
  14030. Val = ST->getValue();
  14031. EVT STType = Val.getValueType();
  14032. EVT STMemType = ST->getMemoryVT();
  14033. if (STType == STMemType)
  14034. return true;
  14035. if (isTypeLegal(STMemType))
  14036. return false; // fail.
  14037. if (STType.isFloatingPoint() && STMemType.isFloatingPoint() &&
  14038. TLI.isOperationLegal(ISD::FTRUNC, STMemType)) {
  14039. Val = DAG.getNode(ISD::FTRUNC, SDLoc(ST), STMemType, Val);
  14040. return true;
  14041. }
  14042. if (numVectorEltsOrZero(STType) == numVectorEltsOrZero(STMemType) &&
  14043. STType.isInteger() && STMemType.isInteger()) {
  14044. Val = DAG.getNode(ISD::TRUNCATE, SDLoc(ST), STMemType, Val);
  14045. return true;
  14046. }
  14047. if (STType.getSizeInBits() == STMemType.getSizeInBits()) {
  14048. Val = DAG.getBitcast(STMemType, Val);
  14049. return true;
  14050. }
  14051. return false; // fail.
  14052. }
  14053. bool DAGCombiner::extendLoadedValueToExtension(LoadSDNode *LD, SDValue &Val) {
  14054. EVT LDMemType = LD->getMemoryVT();
  14055. EVT LDType = LD->getValueType(0);
  14056. assert(Val.getValueType() == LDMemType &&
  14057. "Attempting to extend value of non-matching type");
  14058. if (LDType == LDMemType)
  14059. return true;
  14060. if (LDMemType.isInteger() && LDType.isInteger()) {
  14061. switch (LD->getExtensionType()) {
  14062. case ISD::NON_EXTLOAD:
  14063. Val = DAG.getBitcast(LDType, Val);
  14064. return true;
  14065. case ISD::EXTLOAD:
  14066. Val = DAG.getNode(ISD::ANY_EXTEND, SDLoc(LD), LDType, Val);
  14067. return true;
  14068. case ISD::SEXTLOAD:
  14069. Val = DAG.getNode(ISD::SIGN_EXTEND, SDLoc(LD), LDType, Val);
  14070. return true;
  14071. case ISD::ZEXTLOAD:
  14072. Val = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(LD), LDType, Val);
  14073. return true;
  14074. }
  14075. }
  14076. return false;
  14077. }
  14078. SDValue DAGCombiner::ForwardStoreValueToDirectLoad(LoadSDNode *LD) {
  14079. if (OptLevel == CodeGenOpt::None || !LD->isSimple())
  14080. return SDValue();
  14081. SDValue Chain = LD->getOperand(0);
  14082. StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain.getNode());
  14083. // TODO: Relax this restriction for unordered atomics (see D66309)
  14084. if (!ST || !ST->isSimple())
  14085. return SDValue();
  14086. EVT LDType = LD->getValueType(0);
  14087. EVT LDMemType = LD->getMemoryVT();
  14088. EVT STMemType = ST->getMemoryVT();
  14089. EVT STType = ST->getValue().getValueType();
  14090. // There are two cases to consider here:
  14091. // 1. The store is fixed width and the load is scalable. In this case we
  14092. // don't know at compile time if the store completely envelops the load
  14093. // so we abandon the optimisation.
  14094. // 2. The store is scalable and the load is fixed width. We could
  14095. // potentially support a limited number of cases here, but there has been
  14096. // no cost-benefit analysis to prove it's worth it.
  14097. bool LdStScalable = LDMemType.isScalableVector();
  14098. if (LdStScalable != STMemType.isScalableVector())
  14099. return SDValue();
  14100. // If we are dealing with scalable vectors on a big endian platform the
  14101. // calculation of offsets below becomes trickier, since we do not know at
  14102. // compile time the absolute size of the vector. Until we've done more
  14103. // analysis on big-endian platforms it seems better to bail out for now.
  14104. if (LdStScalable && DAG.getDataLayout().isBigEndian())
  14105. return SDValue();
  14106. BaseIndexOffset BasePtrLD = BaseIndexOffset::match(LD, DAG);
  14107. BaseIndexOffset BasePtrST = BaseIndexOffset::match(ST, DAG);
  14108. int64_t Offset;
  14109. if (!BasePtrST.equalBaseIndex(BasePtrLD, DAG, Offset))
  14110. return SDValue();
  14111. // Normalize for Endianness. After this Offset=0 will denote that the least
  14112. // significant bit in the loaded value maps to the least significant bit in
  14113. // the stored value). With Offset=n (for n > 0) the loaded value starts at the
  14114. // n:th least significant byte of the stored value.
  14115. if (DAG.getDataLayout().isBigEndian())
  14116. Offset = ((int64_t)STMemType.getStoreSizeInBits().getFixedSize() -
  14117. (int64_t)LDMemType.getStoreSizeInBits().getFixedSize()) /
  14118. 8 -
  14119. Offset;
  14120. // Check that the stored value cover all bits that are loaded.
  14121. bool STCoversLD;
  14122. TypeSize LdMemSize = LDMemType.getSizeInBits();
  14123. TypeSize StMemSize = STMemType.getSizeInBits();
  14124. if (LdStScalable)
  14125. STCoversLD = (Offset == 0) && LdMemSize == StMemSize;
  14126. else
  14127. STCoversLD = (Offset >= 0) && (Offset * 8 + LdMemSize.getFixedSize() <=
  14128. StMemSize.getFixedSize());
  14129. auto ReplaceLd = [&](LoadSDNode *LD, SDValue Val, SDValue Chain) -> SDValue {
  14130. if (LD->isIndexed()) {
  14131. // Cannot handle opaque target constants and we must respect the user's
  14132. // request not to split indexes from loads.
  14133. if (!canSplitIdx(LD))
  14134. return SDValue();
  14135. SDValue Idx = SplitIndexingFromLoad(LD);
  14136. SDValue Ops[] = {Val, Idx, Chain};
  14137. return CombineTo(LD, Ops, 3);
  14138. }
  14139. return CombineTo(LD, Val, Chain);
  14140. };
  14141. if (!STCoversLD)
  14142. return SDValue();
  14143. // Memory as copy space (potentially masked).
  14144. if (Offset == 0 && LDType == STType && STMemType == LDMemType) {
  14145. // Simple case: Direct non-truncating forwarding
  14146. if (LDType.getSizeInBits() == LdMemSize)
  14147. return ReplaceLd(LD, ST->getValue(), Chain);
  14148. // Can we model the truncate and extension with an and mask?
  14149. if (STType.isInteger() && LDMemType.isInteger() && !STType.isVector() &&
  14150. !LDMemType.isVector() && LD->getExtensionType() != ISD::SEXTLOAD) {
  14151. // Mask to size of LDMemType
  14152. auto Mask =
  14153. DAG.getConstant(APInt::getLowBitsSet(STType.getFixedSizeInBits(),
  14154. StMemSize.getFixedSize()),
  14155. SDLoc(ST), STType);
  14156. auto Val = DAG.getNode(ISD::AND, SDLoc(LD), LDType, ST->getValue(), Mask);
  14157. return ReplaceLd(LD, Val, Chain);
  14158. }
  14159. }
  14160. // TODO: Deal with nonzero offset.
  14161. if (LD->getBasePtr().isUndef() || Offset != 0)
  14162. return SDValue();
  14163. // Model necessary truncations / extenstions.
  14164. SDValue Val;
  14165. // Truncate Value To Stored Memory Size.
  14166. do {
  14167. if (!getTruncatedStoreValue(ST, Val))
  14168. continue;
  14169. if (!isTypeLegal(LDMemType))
  14170. continue;
  14171. if (STMemType != LDMemType) {
  14172. // TODO: Support vectors? This requires extract_subvector/bitcast.
  14173. if (!STMemType.isVector() && !LDMemType.isVector() &&
  14174. STMemType.isInteger() && LDMemType.isInteger())
  14175. Val = DAG.getNode(ISD::TRUNCATE, SDLoc(LD), LDMemType, Val);
  14176. else
  14177. continue;
  14178. }
  14179. if (!extendLoadedValueToExtension(LD, Val))
  14180. continue;
  14181. return ReplaceLd(LD, Val, Chain);
  14182. } while (false);
  14183. // On failure, cleanup dead nodes we may have created.
  14184. if (Val->use_empty())
  14185. deleteAndRecombine(Val.getNode());
  14186. return SDValue();
  14187. }
  14188. SDValue DAGCombiner::visitLOAD(SDNode *N) {
  14189. LoadSDNode *LD = cast<LoadSDNode>(N);
  14190. SDValue Chain = LD->getChain();
  14191. SDValue Ptr = LD->getBasePtr();
  14192. // If load is not volatile and there are no uses of the loaded value (and
  14193. // the updated indexed value in case of indexed loads), change uses of the
  14194. // chain value into uses of the chain input (i.e. delete the dead load).
  14195. // TODO: Allow this for unordered atomics (see D66309)
  14196. if (LD->isSimple()) {
  14197. if (N->getValueType(1) == MVT::Other) {
  14198. // Unindexed loads.
  14199. if (!N->hasAnyUseOfValue(0)) {
  14200. // It's not safe to use the two value CombineTo variant here. e.g.
  14201. // v1, chain2 = load chain1, loc
  14202. // v2, chain3 = load chain2, loc
  14203. // v3 = add v2, c
  14204. // Now we replace use of chain2 with chain1. This makes the second load
  14205. // isomorphic to the one we are deleting, and thus makes this load live.
  14206. LLVM_DEBUG(dbgs() << "\nReplacing.6 "; N->dump(&DAG);
  14207. dbgs() << "\nWith chain: "; Chain.getNode()->dump(&DAG);
  14208. dbgs() << "\n");
  14209. WorklistRemover DeadNodes(*this);
  14210. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
  14211. AddUsersToWorklist(Chain.getNode());
  14212. if (N->use_empty())
  14213. deleteAndRecombine(N);
  14214. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  14215. }
  14216. } else {
  14217. // Indexed loads.
  14218. assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
  14219. // If this load has an opaque TargetConstant offset, then we cannot split
  14220. // the indexing into an add/sub directly (that TargetConstant may not be
  14221. // valid for a different type of node, and we cannot convert an opaque
  14222. // target constant into a regular constant).
  14223. bool CanSplitIdx = canSplitIdx(LD);
  14224. if (!N->hasAnyUseOfValue(0) && (CanSplitIdx || !N->hasAnyUseOfValue(1))) {
  14225. SDValue Undef = DAG.getUNDEF(N->getValueType(0));
  14226. SDValue Index;
  14227. if (N->hasAnyUseOfValue(1) && CanSplitIdx) {
  14228. Index = SplitIndexingFromLoad(LD);
  14229. // Try to fold the base pointer arithmetic into subsequent loads and
  14230. // stores.
  14231. AddUsersToWorklist(N);
  14232. } else
  14233. Index = DAG.getUNDEF(N->getValueType(1));
  14234. LLVM_DEBUG(dbgs() << "\nReplacing.7 "; N->dump(&DAG);
  14235. dbgs() << "\nWith: "; Undef.getNode()->dump(&DAG);
  14236. dbgs() << " and 2 other values\n");
  14237. WorklistRemover DeadNodes(*this);
  14238. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
  14239. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Index);
  14240. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
  14241. deleteAndRecombine(N);
  14242. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  14243. }
  14244. }
  14245. }
  14246. // If this load is directly stored, replace the load value with the stored
  14247. // value.
  14248. if (auto V = ForwardStoreValueToDirectLoad(LD))
  14249. return V;
  14250. // Try to infer better alignment information than the load already has.
  14251. if (OptLevel != CodeGenOpt::None && LD->isUnindexed() && !LD->isAtomic()) {
  14252. if (MaybeAlign Alignment = DAG.InferPtrAlign(Ptr)) {
  14253. if (*Alignment > LD->getAlign() &&
  14254. isAligned(*Alignment, LD->getSrcValueOffset())) {
  14255. SDValue NewLoad = DAG.getExtLoad(
  14256. LD->getExtensionType(), SDLoc(N), LD->getValueType(0), Chain, Ptr,
  14257. LD->getPointerInfo(), LD->getMemoryVT(), *Alignment,
  14258. LD->getMemOperand()->getFlags(), LD->getAAInfo());
  14259. // NewLoad will always be N as we are only refining the alignment
  14260. assert(NewLoad.getNode() == N);
  14261. (void)NewLoad;
  14262. }
  14263. }
  14264. }
  14265. if (LD->isUnindexed()) {
  14266. // Walk up chain skipping non-aliasing memory nodes.
  14267. SDValue BetterChain = FindBetterChain(LD, Chain);
  14268. // If there is a better chain.
  14269. if (Chain != BetterChain) {
  14270. SDValue ReplLoad;
  14271. // Replace the chain to void dependency.
  14272. if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
  14273. ReplLoad = DAG.getLoad(N->getValueType(0), SDLoc(LD),
  14274. BetterChain, Ptr, LD->getMemOperand());
  14275. } else {
  14276. ReplLoad = DAG.getExtLoad(LD->getExtensionType(), SDLoc(LD),
  14277. LD->getValueType(0),
  14278. BetterChain, Ptr, LD->getMemoryVT(),
  14279. LD->getMemOperand());
  14280. }
  14281. // Create token factor to keep old chain connected.
  14282. SDValue Token = DAG.getNode(ISD::TokenFactor, SDLoc(N),
  14283. MVT::Other, Chain, ReplLoad.getValue(1));
  14284. // Replace uses with load result and token factor
  14285. return CombineTo(N, ReplLoad.getValue(0), Token);
  14286. }
  14287. }
  14288. // Try transforming N to an indexed load.
  14289. if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
  14290. return SDValue(N, 0);
  14291. // Try to slice up N to more direct loads if the slices are mapped to
  14292. // different register banks or pairing can take place.
  14293. if (SliceUpLoad(N))
  14294. return SDValue(N, 0);
  14295. return SDValue();
  14296. }
  14297. namespace {
  14298. /// Helper structure used to slice a load in smaller loads.
  14299. /// Basically a slice is obtained from the following sequence:
  14300. /// Origin = load Ty1, Base
  14301. /// Shift = srl Ty1 Origin, CstTy Amount
  14302. /// Inst = trunc Shift to Ty2
  14303. ///
  14304. /// Then, it will be rewritten into:
  14305. /// Slice = load SliceTy, Base + SliceOffset
  14306. /// [Inst = zext Slice to Ty2], only if SliceTy <> Ty2
  14307. ///
  14308. /// SliceTy is deduced from the number of bits that are actually used to
  14309. /// build Inst.
  14310. struct LoadedSlice {
  14311. /// Helper structure used to compute the cost of a slice.
  14312. struct Cost {
  14313. /// Are we optimizing for code size.
  14314. bool ForCodeSize = false;
  14315. /// Various cost.
  14316. unsigned Loads = 0;
  14317. unsigned Truncates = 0;
  14318. unsigned CrossRegisterBanksCopies = 0;
  14319. unsigned ZExts = 0;
  14320. unsigned Shift = 0;
  14321. explicit Cost(bool ForCodeSize) : ForCodeSize(ForCodeSize) {}
  14322. /// Get the cost of one isolated slice.
  14323. Cost(const LoadedSlice &LS, bool ForCodeSize)
  14324. : ForCodeSize(ForCodeSize), Loads(1) {
  14325. EVT TruncType = LS.Inst->getValueType(0);
  14326. EVT LoadedType = LS.getLoadedType();
  14327. if (TruncType != LoadedType &&
  14328. !LS.DAG->getTargetLoweringInfo().isZExtFree(LoadedType, TruncType))
  14329. ZExts = 1;
  14330. }
  14331. /// Account for slicing gain in the current cost.
  14332. /// Slicing provide a few gains like removing a shift or a
  14333. /// truncate. This method allows to grow the cost of the original
  14334. /// load with the gain from this slice.
  14335. void addSliceGain(const LoadedSlice &LS) {
  14336. // Each slice saves a truncate.
  14337. const TargetLowering &TLI = LS.DAG->getTargetLoweringInfo();
  14338. if (!TLI.isTruncateFree(LS.Inst->getOperand(0).getValueType(),
  14339. LS.Inst->getValueType(0)))
  14340. ++Truncates;
  14341. // If there is a shift amount, this slice gets rid of it.
  14342. if (LS.Shift)
  14343. ++Shift;
  14344. // If this slice can merge a cross register bank copy, account for it.
  14345. if (LS.canMergeExpensiveCrossRegisterBankCopy())
  14346. ++CrossRegisterBanksCopies;
  14347. }
  14348. Cost &operator+=(const Cost &RHS) {
  14349. Loads += RHS.Loads;
  14350. Truncates += RHS.Truncates;
  14351. CrossRegisterBanksCopies += RHS.CrossRegisterBanksCopies;
  14352. ZExts += RHS.ZExts;
  14353. Shift += RHS.Shift;
  14354. return *this;
  14355. }
  14356. bool operator==(const Cost &RHS) const {
  14357. return Loads == RHS.Loads && Truncates == RHS.Truncates &&
  14358. CrossRegisterBanksCopies == RHS.CrossRegisterBanksCopies &&
  14359. ZExts == RHS.ZExts && Shift == RHS.Shift;
  14360. }
  14361. bool operator!=(const Cost &RHS) const { return !(*this == RHS); }
  14362. bool operator<(const Cost &RHS) const {
  14363. // Assume cross register banks copies are as expensive as loads.
  14364. // FIXME: Do we want some more target hooks?
  14365. unsigned ExpensiveOpsLHS = Loads + CrossRegisterBanksCopies;
  14366. unsigned ExpensiveOpsRHS = RHS.Loads + RHS.CrossRegisterBanksCopies;
  14367. // Unless we are optimizing for code size, consider the
  14368. // expensive operation first.
  14369. if (!ForCodeSize && ExpensiveOpsLHS != ExpensiveOpsRHS)
  14370. return ExpensiveOpsLHS < ExpensiveOpsRHS;
  14371. return (Truncates + ZExts + Shift + ExpensiveOpsLHS) <
  14372. (RHS.Truncates + RHS.ZExts + RHS.Shift + ExpensiveOpsRHS);
  14373. }
  14374. bool operator>(const Cost &RHS) const { return RHS < *this; }
  14375. bool operator<=(const Cost &RHS) const { return !(RHS < *this); }
  14376. bool operator>=(const Cost &RHS) const { return !(*this < RHS); }
  14377. };
  14378. // The last instruction that represent the slice. This should be a
  14379. // truncate instruction.
  14380. SDNode *Inst;
  14381. // The original load instruction.
  14382. LoadSDNode *Origin;
  14383. // The right shift amount in bits from the original load.
  14384. unsigned Shift;
  14385. // The DAG from which Origin came from.
  14386. // This is used to get some contextual information about legal types, etc.
  14387. SelectionDAG *DAG;
  14388. LoadedSlice(SDNode *Inst = nullptr, LoadSDNode *Origin = nullptr,
  14389. unsigned Shift = 0, SelectionDAG *DAG = nullptr)
  14390. : Inst(Inst), Origin(Origin), Shift(Shift), DAG(DAG) {}
  14391. /// Get the bits used in a chunk of bits \p BitWidth large.
  14392. /// \return Result is \p BitWidth and has used bits set to 1 and
  14393. /// not used bits set to 0.
  14394. APInt getUsedBits() const {
  14395. // Reproduce the trunc(lshr) sequence:
  14396. // - Start from the truncated value.
  14397. // - Zero extend to the desired bit width.
  14398. // - Shift left.
  14399. assert(Origin && "No original load to compare against.");
  14400. unsigned BitWidth = Origin->getValueSizeInBits(0);
  14401. assert(Inst && "This slice is not bound to an instruction");
  14402. assert(Inst->getValueSizeInBits(0) <= BitWidth &&
  14403. "Extracted slice is bigger than the whole type!");
  14404. APInt UsedBits(Inst->getValueSizeInBits(0), 0);
  14405. UsedBits.setAllBits();
  14406. UsedBits = UsedBits.zext(BitWidth);
  14407. UsedBits <<= Shift;
  14408. return UsedBits;
  14409. }
  14410. /// Get the size of the slice to be loaded in bytes.
  14411. unsigned getLoadedSize() const {
  14412. unsigned SliceSize = getUsedBits().countPopulation();
  14413. assert(!(SliceSize & 0x7) && "Size is not a multiple of a byte.");
  14414. return SliceSize / 8;
  14415. }
  14416. /// Get the type that will be loaded for this slice.
  14417. /// Note: This may not be the final type for the slice.
  14418. EVT getLoadedType() const {
  14419. assert(DAG && "Missing context");
  14420. LLVMContext &Ctxt = *DAG->getContext();
  14421. return EVT::getIntegerVT(Ctxt, getLoadedSize() * 8);
  14422. }
  14423. /// Get the alignment of the load used for this slice.
  14424. Align getAlign() const {
  14425. Align Alignment = Origin->getAlign();
  14426. uint64_t Offset = getOffsetFromBase();
  14427. if (Offset != 0)
  14428. Alignment = commonAlignment(Alignment, Alignment.value() + Offset);
  14429. return Alignment;
  14430. }
  14431. /// Check if this slice can be rewritten with legal operations.
  14432. bool isLegal() const {
  14433. // An invalid slice is not legal.
  14434. if (!Origin || !Inst || !DAG)
  14435. return false;
  14436. // Offsets are for indexed load only, we do not handle that.
  14437. if (!Origin->getOffset().isUndef())
  14438. return false;
  14439. const TargetLowering &TLI = DAG->getTargetLoweringInfo();
  14440. // Check that the type is legal.
  14441. EVT SliceType = getLoadedType();
  14442. if (!TLI.isTypeLegal(SliceType))
  14443. return false;
  14444. // Check that the load is legal for this type.
  14445. if (!TLI.isOperationLegal(ISD::LOAD, SliceType))
  14446. return false;
  14447. // Check that the offset can be computed.
  14448. // 1. Check its type.
  14449. EVT PtrType = Origin->getBasePtr().getValueType();
  14450. if (PtrType == MVT::Untyped || PtrType.isExtended())
  14451. return false;
  14452. // 2. Check that it fits in the immediate.
  14453. if (!TLI.isLegalAddImmediate(getOffsetFromBase()))
  14454. return false;
  14455. // 3. Check that the computation is legal.
  14456. if (!TLI.isOperationLegal(ISD::ADD, PtrType))
  14457. return false;
  14458. // Check that the zext is legal if it needs one.
  14459. EVT TruncateType = Inst->getValueType(0);
  14460. if (TruncateType != SliceType &&
  14461. !TLI.isOperationLegal(ISD::ZERO_EXTEND, TruncateType))
  14462. return false;
  14463. return true;
  14464. }
  14465. /// Get the offset in bytes of this slice in the original chunk of
  14466. /// bits.
  14467. /// \pre DAG != nullptr.
  14468. uint64_t getOffsetFromBase() const {
  14469. assert(DAG && "Missing context.");
  14470. bool IsBigEndian = DAG->getDataLayout().isBigEndian();
  14471. assert(!(Shift & 0x7) && "Shifts not aligned on Bytes are not supported.");
  14472. uint64_t Offset = Shift / 8;
  14473. unsigned TySizeInBytes = Origin->getValueSizeInBits(0) / 8;
  14474. assert(!(Origin->getValueSizeInBits(0) & 0x7) &&
  14475. "The size of the original loaded type is not a multiple of a"
  14476. " byte.");
  14477. // If Offset is bigger than TySizeInBytes, it means we are loading all
  14478. // zeros. This should have been optimized before in the process.
  14479. assert(TySizeInBytes > Offset &&
  14480. "Invalid shift amount for given loaded size");
  14481. if (IsBigEndian)
  14482. Offset = TySizeInBytes - Offset - getLoadedSize();
  14483. return Offset;
  14484. }
  14485. /// Generate the sequence of instructions to load the slice
  14486. /// represented by this object and redirect the uses of this slice to
  14487. /// this new sequence of instructions.
  14488. /// \pre this->Inst && this->Origin are valid Instructions and this
  14489. /// object passed the legal check: LoadedSlice::isLegal returned true.
  14490. /// \return The last instruction of the sequence used to load the slice.
  14491. SDValue loadSlice() const {
  14492. assert(Inst && Origin && "Unable to replace a non-existing slice.");
  14493. const SDValue &OldBaseAddr = Origin->getBasePtr();
  14494. SDValue BaseAddr = OldBaseAddr;
  14495. // Get the offset in that chunk of bytes w.r.t. the endianness.
  14496. int64_t Offset = static_cast<int64_t>(getOffsetFromBase());
  14497. assert(Offset >= 0 && "Offset too big to fit in int64_t!");
  14498. if (Offset) {
  14499. // BaseAddr = BaseAddr + Offset.
  14500. EVT ArithType = BaseAddr.getValueType();
  14501. SDLoc DL(Origin);
  14502. BaseAddr = DAG->getNode(ISD::ADD, DL, ArithType, BaseAddr,
  14503. DAG->getConstant(Offset, DL, ArithType));
  14504. }
  14505. // Create the type of the loaded slice according to its size.
  14506. EVT SliceType = getLoadedType();
  14507. // Create the load for the slice.
  14508. SDValue LastInst =
  14509. DAG->getLoad(SliceType, SDLoc(Origin), Origin->getChain(), BaseAddr,
  14510. Origin->getPointerInfo().getWithOffset(Offset), getAlign(),
  14511. Origin->getMemOperand()->getFlags());
  14512. // If the final type is not the same as the loaded type, this means that
  14513. // we have to pad with zero. Create a zero extend for that.
  14514. EVT FinalType = Inst->getValueType(0);
  14515. if (SliceType != FinalType)
  14516. LastInst =
  14517. DAG->getNode(ISD::ZERO_EXTEND, SDLoc(LastInst), FinalType, LastInst);
  14518. return LastInst;
  14519. }
  14520. /// Check if this slice can be merged with an expensive cross register
  14521. /// bank copy. E.g.,
  14522. /// i = load i32
  14523. /// f = bitcast i32 i to float
  14524. bool canMergeExpensiveCrossRegisterBankCopy() const {
  14525. if (!Inst || !Inst->hasOneUse())
  14526. return false;
  14527. SDNode *Use = *Inst->use_begin();
  14528. if (Use->getOpcode() != ISD::BITCAST)
  14529. return false;
  14530. assert(DAG && "Missing context");
  14531. const TargetLowering &TLI = DAG->getTargetLoweringInfo();
  14532. EVT ResVT = Use->getValueType(0);
  14533. const TargetRegisterClass *ResRC =
  14534. TLI.getRegClassFor(ResVT.getSimpleVT(), Use->isDivergent());
  14535. const TargetRegisterClass *ArgRC =
  14536. TLI.getRegClassFor(Use->getOperand(0).getValueType().getSimpleVT(),
  14537. Use->getOperand(0)->isDivergent());
  14538. if (ArgRC == ResRC || !TLI.isOperationLegal(ISD::LOAD, ResVT))
  14539. return false;
  14540. // At this point, we know that we perform a cross-register-bank copy.
  14541. // Check if it is expensive.
  14542. const TargetRegisterInfo *TRI = DAG->getSubtarget().getRegisterInfo();
  14543. // Assume bitcasts are cheap, unless both register classes do not
  14544. // explicitly share a common sub class.
  14545. if (!TRI || TRI->getCommonSubClass(ArgRC, ResRC))
  14546. return false;
  14547. // Check if it will be merged with the load.
  14548. // 1. Check the alignment / fast memory access constraint.
  14549. bool IsFast = false;
  14550. if (!TLI.allowsMemoryAccess(*DAG->getContext(), DAG->getDataLayout(), ResVT,
  14551. Origin->getAddressSpace(), getAlign(),
  14552. Origin->getMemOperand()->getFlags(), &IsFast) ||
  14553. !IsFast)
  14554. return false;
  14555. // 2. Check that the load is a legal operation for that type.
  14556. if (!TLI.isOperationLegal(ISD::LOAD, ResVT))
  14557. return false;
  14558. // 3. Check that we do not have a zext in the way.
  14559. if (Inst->getValueType(0) != getLoadedType())
  14560. return false;
  14561. return true;
  14562. }
  14563. };
  14564. } // end anonymous namespace
  14565. /// Check that all bits set in \p UsedBits form a dense region, i.e.,
  14566. /// \p UsedBits looks like 0..0 1..1 0..0.
  14567. static bool areUsedBitsDense(const APInt &UsedBits) {
  14568. // If all the bits are one, this is dense!
  14569. if (UsedBits.isAllOnes())
  14570. return true;
  14571. // Get rid of the unused bits on the right.
  14572. APInt NarrowedUsedBits = UsedBits.lshr(UsedBits.countTrailingZeros());
  14573. // Get rid of the unused bits on the left.
  14574. if (NarrowedUsedBits.countLeadingZeros())
  14575. NarrowedUsedBits = NarrowedUsedBits.trunc(NarrowedUsedBits.getActiveBits());
  14576. // Check that the chunk of bits is completely used.
  14577. return NarrowedUsedBits.isAllOnes();
  14578. }
  14579. /// Check whether or not \p First and \p Second are next to each other
  14580. /// in memory. This means that there is no hole between the bits loaded
  14581. /// by \p First and the bits loaded by \p Second.
  14582. static bool areSlicesNextToEachOther(const LoadedSlice &First,
  14583. const LoadedSlice &Second) {
  14584. assert(First.Origin == Second.Origin && First.Origin &&
  14585. "Unable to match different memory origins.");
  14586. APInt UsedBits = First.getUsedBits();
  14587. assert((UsedBits & Second.getUsedBits()) == 0 &&
  14588. "Slices are not supposed to overlap.");
  14589. UsedBits |= Second.getUsedBits();
  14590. return areUsedBitsDense(UsedBits);
  14591. }
  14592. /// Adjust the \p GlobalLSCost according to the target
  14593. /// paring capabilities and the layout of the slices.
  14594. /// \pre \p GlobalLSCost should account for at least as many loads as
  14595. /// there is in the slices in \p LoadedSlices.
  14596. static void adjustCostForPairing(SmallVectorImpl<LoadedSlice> &LoadedSlices,
  14597. LoadedSlice::Cost &GlobalLSCost) {
  14598. unsigned NumberOfSlices = LoadedSlices.size();
  14599. // If there is less than 2 elements, no pairing is possible.
  14600. if (NumberOfSlices < 2)
  14601. return;
  14602. // Sort the slices so that elements that are likely to be next to each
  14603. // other in memory are next to each other in the list.
  14604. llvm::sort(LoadedSlices, [](const LoadedSlice &LHS, const LoadedSlice &RHS) {
  14605. assert(LHS.Origin == RHS.Origin && "Different bases not implemented.");
  14606. return LHS.getOffsetFromBase() < RHS.getOffsetFromBase();
  14607. });
  14608. const TargetLowering &TLI = LoadedSlices[0].DAG->getTargetLoweringInfo();
  14609. // First (resp. Second) is the first (resp. Second) potentially candidate
  14610. // to be placed in a paired load.
  14611. const LoadedSlice *First = nullptr;
  14612. const LoadedSlice *Second = nullptr;
  14613. for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice,
  14614. // Set the beginning of the pair.
  14615. First = Second) {
  14616. Second = &LoadedSlices[CurrSlice];
  14617. // If First is NULL, it means we start a new pair.
  14618. // Get to the next slice.
  14619. if (!First)
  14620. continue;
  14621. EVT LoadedType = First->getLoadedType();
  14622. // If the types of the slices are different, we cannot pair them.
  14623. if (LoadedType != Second->getLoadedType())
  14624. continue;
  14625. // Check if the target supplies paired loads for this type.
  14626. Align RequiredAlignment;
  14627. if (!TLI.hasPairedLoad(LoadedType, RequiredAlignment)) {
  14628. // move to the next pair, this type is hopeless.
  14629. Second = nullptr;
  14630. continue;
  14631. }
  14632. // Check if we meet the alignment requirement.
  14633. if (First->getAlign() < RequiredAlignment)
  14634. continue;
  14635. // Check that both loads are next to each other in memory.
  14636. if (!areSlicesNextToEachOther(*First, *Second))
  14637. continue;
  14638. assert(GlobalLSCost.Loads > 0 && "We save more loads than we created!");
  14639. --GlobalLSCost.Loads;
  14640. // Move to the next pair.
  14641. Second = nullptr;
  14642. }
  14643. }
  14644. /// Check the profitability of all involved LoadedSlice.
  14645. /// Currently, it is considered profitable if there is exactly two
  14646. /// involved slices (1) which are (2) next to each other in memory, and
  14647. /// whose cost (\see LoadedSlice::Cost) is smaller than the original load (3).
  14648. ///
  14649. /// Note: The order of the elements in \p LoadedSlices may be modified, but not
  14650. /// the elements themselves.
  14651. ///
  14652. /// FIXME: When the cost model will be mature enough, we can relax
  14653. /// constraints (1) and (2).
  14654. static bool isSlicingProfitable(SmallVectorImpl<LoadedSlice> &LoadedSlices,
  14655. const APInt &UsedBits, bool ForCodeSize) {
  14656. unsigned NumberOfSlices = LoadedSlices.size();
  14657. if (StressLoadSlicing)
  14658. return NumberOfSlices > 1;
  14659. // Check (1).
  14660. if (NumberOfSlices != 2)
  14661. return false;
  14662. // Check (2).
  14663. if (!areUsedBitsDense(UsedBits))
  14664. return false;
  14665. // Check (3).
  14666. LoadedSlice::Cost OrigCost(ForCodeSize), GlobalSlicingCost(ForCodeSize);
  14667. // The original code has one big load.
  14668. OrigCost.Loads = 1;
  14669. for (unsigned CurrSlice = 0; CurrSlice < NumberOfSlices; ++CurrSlice) {
  14670. const LoadedSlice &LS = LoadedSlices[CurrSlice];
  14671. // Accumulate the cost of all the slices.
  14672. LoadedSlice::Cost SliceCost(LS, ForCodeSize);
  14673. GlobalSlicingCost += SliceCost;
  14674. // Account as cost in the original configuration the gain obtained
  14675. // with the current slices.
  14676. OrigCost.addSliceGain(LS);
  14677. }
  14678. // If the target supports paired load, adjust the cost accordingly.
  14679. adjustCostForPairing(LoadedSlices, GlobalSlicingCost);
  14680. return OrigCost > GlobalSlicingCost;
  14681. }
  14682. /// If the given load, \p LI, is used only by trunc or trunc(lshr)
  14683. /// operations, split it in the various pieces being extracted.
  14684. ///
  14685. /// This sort of thing is introduced by SROA.
  14686. /// This slicing takes care not to insert overlapping loads.
  14687. /// \pre LI is a simple load (i.e., not an atomic or volatile load).
  14688. bool DAGCombiner::SliceUpLoad(SDNode *N) {
  14689. if (Level < AfterLegalizeDAG)
  14690. return false;
  14691. LoadSDNode *LD = cast<LoadSDNode>(N);
  14692. if (!LD->isSimple() || !ISD::isNormalLoad(LD) ||
  14693. !LD->getValueType(0).isInteger())
  14694. return false;
  14695. // The algorithm to split up a load of a scalable vector into individual
  14696. // elements currently requires knowing the length of the loaded type,
  14697. // so will need adjusting to work on scalable vectors.
  14698. if (LD->getValueType(0).isScalableVector())
  14699. return false;
  14700. // Keep track of already used bits to detect overlapping values.
  14701. // In that case, we will just abort the transformation.
  14702. APInt UsedBits(LD->getValueSizeInBits(0), 0);
  14703. SmallVector<LoadedSlice, 4> LoadedSlices;
  14704. // Check if this load is used as several smaller chunks of bits.
  14705. // Basically, look for uses in trunc or trunc(lshr) and record a new chain
  14706. // of computation for each trunc.
  14707. for (SDNode::use_iterator UI = LD->use_begin(), UIEnd = LD->use_end();
  14708. UI != UIEnd; ++UI) {
  14709. // Skip the uses of the chain.
  14710. if (UI.getUse().getResNo() != 0)
  14711. continue;
  14712. SDNode *User = *UI;
  14713. unsigned Shift = 0;
  14714. // Check if this is a trunc(lshr).
  14715. if (User->getOpcode() == ISD::SRL && User->hasOneUse() &&
  14716. isa<ConstantSDNode>(User->getOperand(1))) {
  14717. Shift = User->getConstantOperandVal(1);
  14718. User = *User->use_begin();
  14719. }
  14720. // At this point, User is a Truncate, iff we encountered, trunc or
  14721. // trunc(lshr).
  14722. if (User->getOpcode() != ISD::TRUNCATE)
  14723. return false;
  14724. // The width of the type must be a power of 2 and greater than 8-bits.
  14725. // Otherwise the load cannot be represented in LLVM IR.
  14726. // Moreover, if we shifted with a non-8-bits multiple, the slice
  14727. // will be across several bytes. We do not support that.
  14728. unsigned Width = User->getValueSizeInBits(0);
  14729. if (Width < 8 || !isPowerOf2_32(Width) || (Shift & 0x7))
  14730. return false;
  14731. // Build the slice for this chain of computations.
  14732. LoadedSlice LS(User, LD, Shift, &DAG);
  14733. APInt CurrentUsedBits = LS.getUsedBits();
  14734. // Check if this slice overlaps with another.
  14735. if ((CurrentUsedBits & UsedBits) != 0)
  14736. return false;
  14737. // Update the bits used globally.
  14738. UsedBits |= CurrentUsedBits;
  14739. // Check if the new slice would be legal.
  14740. if (!LS.isLegal())
  14741. return false;
  14742. // Record the slice.
  14743. LoadedSlices.push_back(LS);
  14744. }
  14745. // Abort slicing if it does not seem to be profitable.
  14746. if (!isSlicingProfitable(LoadedSlices, UsedBits, ForCodeSize))
  14747. return false;
  14748. ++SlicedLoads;
  14749. // Rewrite each chain to use an independent load.
  14750. // By construction, each chain can be represented by a unique load.
  14751. // Prepare the argument for the new token factor for all the slices.
  14752. SmallVector<SDValue, 8> ArgChains;
  14753. for (const LoadedSlice &LS : LoadedSlices) {
  14754. SDValue SliceInst = LS.loadSlice();
  14755. CombineTo(LS.Inst, SliceInst, true);
  14756. if (SliceInst.getOpcode() != ISD::LOAD)
  14757. SliceInst = SliceInst.getOperand(0);
  14758. assert(SliceInst->getOpcode() == ISD::LOAD &&
  14759. "It takes more than a zext to get to the loaded slice!!");
  14760. ArgChains.push_back(SliceInst.getValue(1));
  14761. }
  14762. SDValue Chain = DAG.getNode(ISD::TokenFactor, SDLoc(LD), MVT::Other,
  14763. ArgChains);
  14764. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
  14765. AddToWorklist(Chain.getNode());
  14766. return true;
  14767. }
  14768. /// Check to see if V is (and load (ptr), imm), where the load is having
  14769. /// specific bytes cleared out. If so, return the byte size being masked out
  14770. /// and the shift amount.
  14771. static std::pair<unsigned, unsigned>
  14772. CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
  14773. std::pair<unsigned, unsigned> Result(0, 0);
  14774. // Check for the structure we're looking for.
  14775. if (V->getOpcode() != ISD::AND ||
  14776. !isa<ConstantSDNode>(V->getOperand(1)) ||
  14777. !ISD::isNormalLoad(V->getOperand(0).getNode()))
  14778. return Result;
  14779. // Check the chain and pointer.
  14780. LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
  14781. if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
  14782. // This only handles simple types.
  14783. if (V.getValueType() != MVT::i16 &&
  14784. V.getValueType() != MVT::i32 &&
  14785. V.getValueType() != MVT::i64)
  14786. return Result;
  14787. // Check the constant mask. Invert it so that the bits being masked out are
  14788. // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
  14789. // follow the sign bit for uniformity.
  14790. uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
  14791. unsigned NotMaskLZ = countLeadingZeros(NotMask);
  14792. if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
  14793. unsigned NotMaskTZ = countTrailingZeros(NotMask);
  14794. if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
  14795. if (NotMaskLZ == 64) return Result; // All zero mask.
  14796. // See if we have a continuous run of bits. If so, we have 0*1+0*
  14797. if (countTrailingOnes(NotMask >> NotMaskTZ) + NotMaskTZ + NotMaskLZ != 64)
  14798. return Result;
  14799. // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
  14800. if (V.getValueType() != MVT::i64 && NotMaskLZ)
  14801. NotMaskLZ -= 64-V.getValueSizeInBits();
  14802. unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
  14803. switch (MaskedBytes) {
  14804. case 1:
  14805. case 2:
  14806. case 4: break;
  14807. default: return Result; // All one mask, or 5-byte mask.
  14808. }
  14809. // Verify that the first bit starts at a multiple of mask so that the access
  14810. // is aligned the same as the access width.
  14811. if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
  14812. // For narrowing to be valid, it must be the case that the load the
  14813. // immediately preceding memory operation before the store.
  14814. if (LD == Chain.getNode())
  14815. ; // ok.
  14816. else if (Chain->getOpcode() == ISD::TokenFactor &&
  14817. SDValue(LD, 1).hasOneUse()) {
  14818. // LD has only 1 chain use so they are no indirect dependencies.
  14819. if (!LD->isOperandOf(Chain.getNode()))
  14820. return Result;
  14821. } else
  14822. return Result; // Fail.
  14823. Result.first = MaskedBytes;
  14824. Result.second = NotMaskTZ/8;
  14825. return Result;
  14826. }
  14827. /// Check to see if IVal is something that provides a value as specified by
  14828. /// MaskInfo. If so, replace the specified store with a narrower store of
  14829. /// truncated IVal.
  14830. static SDValue
  14831. ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
  14832. SDValue IVal, StoreSDNode *St,
  14833. DAGCombiner *DC) {
  14834. unsigned NumBytes = MaskInfo.first;
  14835. unsigned ByteShift = MaskInfo.second;
  14836. SelectionDAG &DAG = DC->getDAG();
  14837. // Check to see if IVal is all zeros in the part being masked in by the 'or'
  14838. // that uses this. If not, this is not a replacement.
  14839. APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
  14840. ByteShift*8, (ByteShift+NumBytes)*8);
  14841. if (!DAG.MaskedValueIsZero(IVal, Mask)) return SDValue();
  14842. // Check that it is legal on the target to do this. It is legal if the new
  14843. // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
  14844. // legalization (and the target doesn't explicitly think this is a bad idea).
  14845. MVT VT = MVT::getIntegerVT(NumBytes * 8);
  14846. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  14847. if (!DC->isTypeLegal(VT))
  14848. return SDValue();
  14849. if (St->getMemOperand() &&
  14850. !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VT,
  14851. *St->getMemOperand()))
  14852. return SDValue();
  14853. // Okay, we can do this! Replace the 'St' store with a store of IVal that is
  14854. // shifted by ByteShift and truncated down to NumBytes.
  14855. if (ByteShift) {
  14856. SDLoc DL(IVal);
  14857. IVal = DAG.getNode(ISD::SRL, DL, IVal.getValueType(), IVal,
  14858. DAG.getConstant(ByteShift*8, DL,
  14859. DC->getShiftAmountTy(IVal.getValueType())));
  14860. }
  14861. // Figure out the offset for the store and the alignment of the access.
  14862. unsigned StOffset;
  14863. if (DAG.getDataLayout().isLittleEndian())
  14864. StOffset = ByteShift;
  14865. else
  14866. StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
  14867. SDValue Ptr = St->getBasePtr();
  14868. if (StOffset) {
  14869. SDLoc DL(IVal);
  14870. Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(StOffset), DL);
  14871. }
  14872. // Truncate down to the new size.
  14873. IVal = DAG.getNode(ISD::TRUNCATE, SDLoc(IVal), VT, IVal);
  14874. ++OpsNarrowed;
  14875. return DAG
  14876. .getStore(St->getChain(), SDLoc(St), IVal, Ptr,
  14877. St->getPointerInfo().getWithOffset(StOffset),
  14878. St->getOriginalAlign());
  14879. }
  14880. /// Look for sequence of load / op / store where op is one of 'or', 'xor', and
  14881. /// 'and' of immediates. If 'op' is only touching some of the loaded bits, try
  14882. /// narrowing the load and store if it would end up being a win for performance
  14883. /// or code size.
  14884. SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
  14885. StoreSDNode *ST = cast<StoreSDNode>(N);
  14886. if (!ST->isSimple())
  14887. return SDValue();
  14888. SDValue Chain = ST->getChain();
  14889. SDValue Value = ST->getValue();
  14890. SDValue Ptr = ST->getBasePtr();
  14891. EVT VT = Value.getValueType();
  14892. if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
  14893. return SDValue();
  14894. unsigned Opc = Value.getOpcode();
  14895. // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
  14896. // is a byte mask indicating a consecutive number of bytes, check to see if
  14897. // Y is known to provide just those bytes. If so, we try to replace the
  14898. // load + replace + store sequence with a single (narrower) store, which makes
  14899. // the load dead.
  14900. if (Opc == ISD::OR && EnableShrinkLoadReplaceStoreWithStore) {
  14901. std::pair<unsigned, unsigned> MaskedLoad;
  14902. MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
  14903. if (MaskedLoad.first)
  14904. if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
  14905. Value.getOperand(1), ST,this))
  14906. return NewST;
  14907. // Or is commutative, so try swapping X and Y.
  14908. MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
  14909. if (MaskedLoad.first)
  14910. if (SDValue NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
  14911. Value.getOperand(0), ST,this))
  14912. return NewST;
  14913. }
  14914. if (!EnableReduceLoadOpStoreWidth)
  14915. return SDValue();
  14916. if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
  14917. Value.getOperand(1).getOpcode() != ISD::Constant)
  14918. return SDValue();
  14919. SDValue N0 = Value.getOperand(0);
  14920. if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
  14921. Chain == SDValue(N0.getNode(), 1)) {
  14922. LoadSDNode *LD = cast<LoadSDNode>(N0);
  14923. if (LD->getBasePtr() != Ptr ||
  14924. LD->getPointerInfo().getAddrSpace() !=
  14925. ST->getPointerInfo().getAddrSpace())
  14926. return SDValue();
  14927. // Find the type to narrow it the load / op / store to.
  14928. SDValue N1 = Value.getOperand(1);
  14929. unsigned BitWidth = N1.getValueSizeInBits();
  14930. APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
  14931. if (Opc == ISD::AND)
  14932. Imm ^= APInt::getAllOnes(BitWidth);
  14933. if (Imm == 0 || Imm.isAllOnes())
  14934. return SDValue();
  14935. unsigned ShAmt = Imm.countTrailingZeros();
  14936. unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
  14937. unsigned NewBW = NextPowerOf2(MSB - ShAmt);
  14938. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
  14939. // The narrowing should be profitable, the load/store operation should be
  14940. // legal (or custom) and the store size should be equal to the NewVT width.
  14941. while (NewBW < BitWidth &&
  14942. (NewVT.getStoreSizeInBits() != NewBW ||
  14943. !TLI.isOperationLegalOrCustom(Opc, NewVT) ||
  14944. !TLI.isNarrowingProfitable(VT, NewVT))) {
  14945. NewBW = NextPowerOf2(NewBW);
  14946. NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
  14947. }
  14948. if (NewBW >= BitWidth)
  14949. return SDValue();
  14950. // If the lsb changed does not start at the type bitwidth boundary,
  14951. // start at the previous one.
  14952. if (ShAmt % NewBW)
  14953. ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
  14954. APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
  14955. std::min(BitWidth, ShAmt + NewBW));
  14956. if ((Imm & Mask) == Imm) {
  14957. APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
  14958. if (Opc == ISD::AND)
  14959. NewImm ^= APInt::getAllOnes(NewBW);
  14960. uint64_t PtrOff = ShAmt / 8;
  14961. // For big endian targets, we need to adjust the offset to the pointer to
  14962. // load the correct bytes.
  14963. if (DAG.getDataLayout().isBigEndian())
  14964. PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
  14965. bool IsFast = false;
  14966. Align NewAlign = commonAlignment(LD->getAlign(), PtrOff);
  14967. if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), NewVT,
  14968. LD->getAddressSpace(), NewAlign,
  14969. LD->getMemOperand()->getFlags(), &IsFast) ||
  14970. !IsFast)
  14971. return SDValue();
  14972. SDValue NewPtr =
  14973. DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(PtrOff), SDLoc(LD));
  14974. SDValue NewLD =
  14975. DAG.getLoad(NewVT, SDLoc(N0), LD->getChain(), NewPtr,
  14976. LD->getPointerInfo().getWithOffset(PtrOff), NewAlign,
  14977. LD->getMemOperand()->getFlags(), LD->getAAInfo());
  14978. SDValue NewVal = DAG.getNode(Opc, SDLoc(Value), NewVT, NewLD,
  14979. DAG.getConstant(NewImm, SDLoc(Value),
  14980. NewVT));
  14981. SDValue NewST =
  14982. DAG.getStore(Chain, SDLoc(N), NewVal, NewPtr,
  14983. ST->getPointerInfo().getWithOffset(PtrOff), NewAlign);
  14984. AddToWorklist(NewPtr.getNode());
  14985. AddToWorklist(NewLD.getNode());
  14986. AddToWorklist(NewVal.getNode());
  14987. WorklistRemover DeadNodes(*this);
  14988. DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
  14989. ++OpsNarrowed;
  14990. return NewST;
  14991. }
  14992. }
  14993. return SDValue();
  14994. }
  14995. /// For a given floating point load / store pair, if the load value isn't used
  14996. /// by any other operations, then consider transforming the pair to integer
  14997. /// load / store operations if the target deems the transformation profitable.
  14998. SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
  14999. StoreSDNode *ST = cast<StoreSDNode>(N);
  15000. SDValue Value = ST->getValue();
  15001. if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
  15002. Value.hasOneUse()) {
  15003. LoadSDNode *LD = cast<LoadSDNode>(Value);
  15004. EVT VT = LD->getMemoryVT();
  15005. if (!VT.isFloatingPoint() ||
  15006. VT != ST->getMemoryVT() ||
  15007. LD->isNonTemporal() ||
  15008. ST->isNonTemporal() ||
  15009. LD->getPointerInfo().getAddrSpace() != 0 ||
  15010. ST->getPointerInfo().getAddrSpace() != 0)
  15011. return SDValue();
  15012. TypeSize VTSize = VT.getSizeInBits();
  15013. // We don't know the size of scalable types at compile time so we cannot
  15014. // create an integer of the equivalent size.
  15015. if (VTSize.isScalable())
  15016. return SDValue();
  15017. bool FastLD = false, FastST = false;
  15018. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VTSize.getFixedSize());
  15019. if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
  15020. !TLI.isOperationLegal(ISD::STORE, IntVT) ||
  15021. !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
  15022. !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT) ||
  15023. !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), IntVT,
  15024. *LD->getMemOperand(), &FastLD) ||
  15025. !TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), IntVT,
  15026. *ST->getMemOperand(), &FastST) ||
  15027. !FastLD || !FastST)
  15028. return SDValue();
  15029. SDValue NewLD =
  15030. DAG.getLoad(IntVT, SDLoc(Value), LD->getChain(), LD->getBasePtr(),
  15031. LD->getPointerInfo(), LD->getAlign());
  15032. SDValue NewST =
  15033. DAG.getStore(ST->getChain(), SDLoc(N), NewLD, ST->getBasePtr(),
  15034. ST->getPointerInfo(), ST->getAlign());
  15035. AddToWorklist(NewLD.getNode());
  15036. AddToWorklist(NewST.getNode());
  15037. WorklistRemover DeadNodes(*this);
  15038. DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
  15039. ++LdStFP2Int;
  15040. return NewST;
  15041. }
  15042. return SDValue();
  15043. }
  15044. // This is a helper function for visitMUL to check the profitability
  15045. // of folding (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2).
  15046. // MulNode is the original multiply, AddNode is (add x, c1),
  15047. // and ConstNode is c2.
  15048. //
  15049. // If the (add x, c1) has multiple uses, we could increase
  15050. // the number of adds if we make this transformation.
  15051. // It would only be worth doing this if we can remove a
  15052. // multiply in the process. Check for that here.
  15053. // To illustrate:
  15054. // (A + c1) * c3
  15055. // (A + c2) * c3
  15056. // We're checking for cases where we have common "c3 * A" expressions.
  15057. bool DAGCombiner::isMulAddWithConstProfitable(SDNode *MulNode,
  15058. SDValue &AddNode,
  15059. SDValue &ConstNode) {
  15060. APInt Val;
  15061. // If the add only has one use, and the target thinks the folding is
  15062. // profitable or does not lead to worse code, this would be OK to do.
  15063. if (AddNode.getNode()->hasOneUse() &&
  15064. TLI.isMulAddWithConstProfitable(AddNode, ConstNode))
  15065. return true;
  15066. // Walk all the users of the constant with which we're multiplying.
  15067. for (SDNode *Use : ConstNode->uses()) {
  15068. if (Use == MulNode) // This use is the one we're on right now. Skip it.
  15069. continue;
  15070. if (Use->getOpcode() == ISD::MUL) { // We have another multiply use.
  15071. SDNode *OtherOp;
  15072. SDNode *MulVar = AddNode.getOperand(0).getNode();
  15073. // OtherOp is what we're multiplying against the constant.
  15074. if (Use->getOperand(0) == ConstNode)
  15075. OtherOp = Use->getOperand(1).getNode();
  15076. else
  15077. OtherOp = Use->getOperand(0).getNode();
  15078. // Check to see if multiply is with the same operand of our "add".
  15079. //
  15080. // ConstNode = CONST
  15081. // Use = ConstNode * A <-- visiting Use. OtherOp is A.
  15082. // ...
  15083. // AddNode = (A + c1) <-- MulVar is A.
  15084. // = AddNode * ConstNode <-- current visiting instruction.
  15085. //
  15086. // If we make this transformation, we will have a common
  15087. // multiply (ConstNode * A) that we can save.
  15088. if (OtherOp == MulVar)
  15089. return true;
  15090. // Now check to see if a future expansion will give us a common
  15091. // multiply.
  15092. //
  15093. // ConstNode = CONST
  15094. // AddNode = (A + c1)
  15095. // ... = AddNode * ConstNode <-- current visiting instruction.
  15096. // ...
  15097. // OtherOp = (A + c2)
  15098. // Use = OtherOp * ConstNode <-- visiting Use.
  15099. //
  15100. // If we make this transformation, we will have a common
  15101. // multiply (CONST * A) after we also do the same transformation
  15102. // to the "t2" instruction.
  15103. if (OtherOp->getOpcode() == ISD::ADD &&
  15104. DAG.isConstantIntBuildVectorOrConstantInt(OtherOp->getOperand(1)) &&
  15105. OtherOp->getOperand(0).getNode() == MulVar)
  15106. return true;
  15107. }
  15108. }
  15109. // Didn't find a case where this would be profitable.
  15110. return false;
  15111. }
  15112. SDValue DAGCombiner::getMergeStoreChains(SmallVectorImpl<MemOpLink> &StoreNodes,
  15113. unsigned NumStores) {
  15114. SmallVector<SDValue, 8> Chains;
  15115. SmallPtrSet<const SDNode *, 8> Visited;
  15116. SDLoc StoreDL(StoreNodes[0].MemNode);
  15117. for (unsigned i = 0; i < NumStores; ++i) {
  15118. Visited.insert(StoreNodes[i].MemNode);
  15119. }
  15120. // don't include nodes that are children or repeated nodes.
  15121. for (unsigned i = 0; i < NumStores; ++i) {
  15122. if (Visited.insert(StoreNodes[i].MemNode->getChain().getNode()).second)
  15123. Chains.push_back(StoreNodes[i].MemNode->getChain());
  15124. }
  15125. assert(Chains.size() > 0 && "Chain should have generated a chain");
  15126. return DAG.getTokenFactor(StoreDL, Chains);
  15127. }
  15128. bool DAGCombiner::mergeStoresOfConstantsOrVecElts(
  15129. SmallVectorImpl<MemOpLink> &StoreNodes, EVT MemVT, unsigned NumStores,
  15130. bool IsConstantSrc, bool UseVector, bool UseTrunc) {
  15131. // Make sure we have something to merge.
  15132. if (NumStores < 2)
  15133. return false;
  15134. assert((!UseTrunc || !UseVector) &&
  15135. "This optimization cannot emit a vector truncating store");
  15136. // The latest Node in the DAG.
  15137. SDLoc DL(StoreNodes[0].MemNode);
  15138. TypeSize ElementSizeBits = MemVT.getStoreSizeInBits();
  15139. unsigned SizeInBits = NumStores * ElementSizeBits;
  15140. unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
  15141. Optional<MachineMemOperand::Flags> Flags;
  15142. AAMDNodes AAInfo;
  15143. for (unsigned I = 0; I != NumStores; ++I) {
  15144. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
  15145. if (!Flags) {
  15146. Flags = St->getMemOperand()->getFlags();
  15147. AAInfo = St->getAAInfo();
  15148. continue;
  15149. }
  15150. // Skip merging if there's an inconsistent flag.
  15151. if (Flags != St->getMemOperand()->getFlags())
  15152. return false;
  15153. // Concatenate AA metadata.
  15154. AAInfo = AAInfo.concat(St->getAAInfo());
  15155. }
  15156. EVT StoreTy;
  15157. if (UseVector) {
  15158. unsigned Elts = NumStores * NumMemElts;
  15159. // Get the type for the merged vector store.
  15160. StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
  15161. } else
  15162. StoreTy = EVT::getIntegerVT(*DAG.getContext(), SizeInBits);
  15163. SDValue StoredVal;
  15164. if (UseVector) {
  15165. if (IsConstantSrc) {
  15166. SmallVector<SDValue, 8> BuildVector;
  15167. for (unsigned I = 0; I != NumStores; ++I) {
  15168. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[I].MemNode);
  15169. SDValue Val = St->getValue();
  15170. // If constant is of the wrong type, convert it now.
  15171. if (MemVT != Val.getValueType()) {
  15172. Val = peekThroughBitcasts(Val);
  15173. // Deal with constants of wrong size.
  15174. if (ElementSizeBits != Val.getValueSizeInBits()) {
  15175. EVT IntMemVT =
  15176. EVT::getIntegerVT(*DAG.getContext(), MemVT.getSizeInBits());
  15177. if (isa<ConstantFPSDNode>(Val)) {
  15178. // Not clear how to truncate FP values.
  15179. return false;
  15180. } else if (auto *C = dyn_cast<ConstantSDNode>(Val))
  15181. Val = DAG.getConstant(C->getAPIntValue()
  15182. .zextOrTrunc(Val.getValueSizeInBits())
  15183. .zextOrTrunc(ElementSizeBits),
  15184. SDLoc(C), IntMemVT);
  15185. }
  15186. // Make sure correctly size type is the correct type.
  15187. Val = DAG.getBitcast(MemVT, Val);
  15188. }
  15189. BuildVector.push_back(Val);
  15190. }
  15191. StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
  15192. : ISD::BUILD_VECTOR,
  15193. DL, StoreTy, BuildVector);
  15194. } else {
  15195. SmallVector<SDValue, 8> Ops;
  15196. for (unsigned i = 0; i < NumStores; ++i) {
  15197. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
  15198. SDValue Val = peekThroughBitcasts(St->getValue());
  15199. // All operands of BUILD_VECTOR / CONCAT_VECTOR must be of
  15200. // type MemVT. If the underlying value is not the correct
  15201. // type, but it is an extraction of an appropriate vector we
  15202. // can recast Val to be of the correct type. This may require
  15203. // converting between EXTRACT_VECTOR_ELT and
  15204. // EXTRACT_SUBVECTOR.
  15205. if ((MemVT != Val.getValueType()) &&
  15206. (Val.getOpcode() == ISD::EXTRACT_VECTOR_ELT ||
  15207. Val.getOpcode() == ISD::EXTRACT_SUBVECTOR)) {
  15208. EVT MemVTScalarTy = MemVT.getScalarType();
  15209. // We may need to add a bitcast here to get types to line up.
  15210. if (MemVTScalarTy != Val.getValueType().getScalarType()) {
  15211. Val = DAG.getBitcast(MemVT, Val);
  15212. } else {
  15213. unsigned OpC = MemVT.isVector() ? ISD::EXTRACT_SUBVECTOR
  15214. : ISD::EXTRACT_VECTOR_ELT;
  15215. SDValue Vec = Val.getOperand(0);
  15216. SDValue Idx = Val.getOperand(1);
  15217. Val = DAG.getNode(OpC, SDLoc(Val), MemVT, Vec, Idx);
  15218. }
  15219. }
  15220. Ops.push_back(Val);
  15221. }
  15222. // Build the extracted vector elements back into a vector.
  15223. StoredVal = DAG.getNode(MemVT.isVector() ? ISD::CONCAT_VECTORS
  15224. : ISD::BUILD_VECTOR,
  15225. DL, StoreTy, Ops);
  15226. }
  15227. } else {
  15228. // We should always use a vector store when merging extracted vector
  15229. // elements, so this path implies a store of constants.
  15230. assert(IsConstantSrc && "Merged vector elements should use vector store");
  15231. APInt StoreInt(SizeInBits, 0);
  15232. // Construct a single integer constant which is made of the smaller
  15233. // constant inputs.
  15234. bool IsLE = DAG.getDataLayout().isLittleEndian();
  15235. for (unsigned i = 0; i < NumStores; ++i) {
  15236. unsigned Idx = IsLE ? (NumStores - 1 - i) : i;
  15237. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
  15238. SDValue Val = St->getValue();
  15239. Val = peekThroughBitcasts(Val);
  15240. StoreInt <<= ElementSizeBits;
  15241. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
  15242. StoreInt |= C->getAPIntValue()
  15243. .zextOrTrunc(ElementSizeBits)
  15244. .zextOrTrunc(SizeInBits);
  15245. } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
  15246. StoreInt |= C->getValueAPF()
  15247. .bitcastToAPInt()
  15248. .zextOrTrunc(ElementSizeBits)
  15249. .zextOrTrunc(SizeInBits);
  15250. // If fp truncation is necessary give up for now.
  15251. if (MemVT.getSizeInBits() != ElementSizeBits)
  15252. return false;
  15253. } else {
  15254. llvm_unreachable("Invalid constant element type");
  15255. }
  15256. }
  15257. // Create the new Load and Store operations.
  15258. StoredVal = DAG.getConstant(StoreInt, DL, StoreTy);
  15259. }
  15260. LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
  15261. SDValue NewChain = getMergeStoreChains(StoreNodes, NumStores);
  15262. // make sure we use trunc store if it's necessary to be legal.
  15263. SDValue NewStore;
  15264. if (!UseTrunc) {
  15265. NewStore = DAG.getStore(NewChain, DL, StoredVal, FirstInChain->getBasePtr(),
  15266. FirstInChain->getPointerInfo(),
  15267. FirstInChain->getAlign(), Flags.getValue(), AAInfo);
  15268. } else { // Must be realized as a trunc store
  15269. EVT LegalizedStoredValTy =
  15270. TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
  15271. unsigned LegalizedStoreSize = LegalizedStoredValTy.getSizeInBits();
  15272. ConstantSDNode *C = cast<ConstantSDNode>(StoredVal);
  15273. SDValue ExtendedStoreVal =
  15274. DAG.getConstant(C->getAPIntValue().zextOrTrunc(LegalizedStoreSize), DL,
  15275. LegalizedStoredValTy);
  15276. NewStore = DAG.getTruncStore(
  15277. NewChain, DL, ExtendedStoreVal, FirstInChain->getBasePtr(),
  15278. FirstInChain->getPointerInfo(), StoredVal.getValueType() /*TVT*/,
  15279. FirstInChain->getAlign(), Flags.getValue(), AAInfo);
  15280. }
  15281. // Replace all merged stores with the new store.
  15282. for (unsigned i = 0; i < NumStores; ++i)
  15283. CombineTo(StoreNodes[i].MemNode, NewStore);
  15284. AddToWorklist(NewChain.getNode());
  15285. return true;
  15286. }
  15287. void DAGCombiner::getStoreMergeCandidates(
  15288. StoreSDNode *St, SmallVectorImpl<MemOpLink> &StoreNodes,
  15289. SDNode *&RootNode) {
  15290. // This holds the base pointer, index, and the offset in bytes from the base
  15291. // pointer. We must have a base and an offset. Do not handle stores to undef
  15292. // base pointers.
  15293. BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
  15294. if (!BasePtr.getBase().getNode() || BasePtr.getBase().isUndef())
  15295. return;
  15296. SDValue Val = peekThroughBitcasts(St->getValue());
  15297. StoreSource StoreSrc = getStoreSource(Val);
  15298. assert(StoreSrc != StoreSource::Unknown && "Expected known source for store");
  15299. // Match on loadbaseptr if relevant.
  15300. EVT MemVT = St->getMemoryVT();
  15301. BaseIndexOffset LBasePtr;
  15302. EVT LoadVT;
  15303. if (StoreSrc == StoreSource::Load) {
  15304. auto *Ld = cast<LoadSDNode>(Val);
  15305. LBasePtr = BaseIndexOffset::match(Ld, DAG);
  15306. LoadVT = Ld->getMemoryVT();
  15307. // Load and store should be the same type.
  15308. if (MemVT != LoadVT)
  15309. return;
  15310. // Loads must only have one use.
  15311. if (!Ld->hasNUsesOfValue(1, 0))
  15312. return;
  15313. // The memory operands must not be volatile/indexed/atomic.
  15314. // TODO: May be able to relax for unordered atomics (see D66309)
  15315. if (!Ld->isSimple() || Ld->isIndexed())
  15316. return;
  15317. }
  15318. auto CandidateMatch = [&](StoreSDNode *Other, BaseIndexOffset &Ptr,
  15319. int64_t &Offset) -> bool {
  15320. // The memory operands must not be volatile/indexed/atomic.
  15321. // TODO: May be able to relax for unordered atomics (see D66309)
  15322. if (!Other->isSimple() || Other->isIndexed())
  15323. return false;
  15324. // Don't mix temporal stores with non-temporal stores.
  15325. if (St->isNonTemporal() != Other->isNonTemporal())
  15326. return false;
  15327. SDValue OtherBC = peekThroughBitcasts(Other->getValue());
  15328. // Allow merging constants of different types as integers.
  15329. bool NoTypeMatch = (MemVT.isInteger()) ? !MemVT.bitsEq(Other->getMemoryVT())
  15330. : Other->getMemoryVT() != MemVT;
  15331. switch (StoreSrc) {
  15332. case StoreSource::Load: {
  15333. if (NoTypeMatch)
  15334. return false;
  15335. // The Load's Base Ptr must also match.
  15336. auto *OtherLd = dyn_cast<LoadSDNode>(OtherBC);
  15337. if (!OtherLd)
  15338. return false;
  15339. BaseIndexOffset LPtr = BaseIndexOffset::match(OtherLd, DAG);
  15340. if (LoadVT != OtherLd->getMemoryVT())
  15341. return false;
  15342. // Loads must only have one use.
  15343. if (!OtherLd->hasNUsesOfValue(1, 0))
  15344. return false;
  15345. // The memory operands must not be volatile/indexed/atomic.
  15346. // TODO: May be able to relax for unordered atomics (see D66309)
  15347. if (!OtherLd->isSimple() || OtherLd->isIndexed())
  15348. return false;
  15349. // Don't mix temporal loads with non-temporal loads.
  15350. if (cast<LoadSDNode>(Val)->isNonTemporal() != OtherLd->isNonTemporal())
  15351. return false;
  15352. if (!(LBasePtr.equalBaseIndex(LPtr, DAG)))
  15353. return false;
  15354. break;
  15355. }
  15356. case StoreSource::Constant:
  15357. if (NoTypeMatch)
  15358. return false;
  15359. if (!isIntOrFPConstant(OtherBC))
  15360. return false;
  15361. break;
  15362. case StoreSource::Extract:
  15363. // Do not merge truncated stores here.
  15364. if (Other->isTruncatingStore())
  15365. return false;
  15366. if (!MemVT.bitsEq(OtherBC.getValueType()))
  15367. return false;
  15368. if (OtherBC.getOpcode() != ISD::EXTRACT_VECTOR_ELT &&
  15369. OtherBC.getOpcode() != ISD::EXTRACT_SUBVECTOR)
  15370. return false;
  15371. break;
  15372. default:
  15373. llvm_unreachable("Unhandled store source for merging");
  15374. }
  15375. Ptr = BaseIndexOffset::match(Other, DAG);
  15376. return (BasePtr.equalBaseIndex(Ptr, DAG, Offset));
  15377. };
  15378. // Check if the pair of StoreNode and the RootNode already bail out many
  15379. // times which is over the limit in dependence check.
  15380. auto OverLimitInDependenceCheck = [&](SDNode *StoreNode,
  15381. SDNode *RootNode) -> bool {
  15382. auto RootCount = StoreRootCountMap.find(StoreNode);
  15383. return RootCount != StoreRootCountMap.end() &&
  15384. RootCount->second.first == RootNode &&
  15385. RootCount->second.second > StoreMergeDependenceLimit;
  15386. };
  15387. auto TryToAddCandidate = [&](SDNode::use_iterator UseIter) {
  15388. // This must be a chain use.
  15389. if (UseIter.getOperandNo() != 0)
  15390. return;
  15391. if (auto *OtherStore = dyn_cast<StoreSDNode>(*UseIter)) {
  15392. BaseIndexOffset Ptr;
  15393. int64_t PtrDiff;
  15394. if (CandidateMatch(OtherStore, Ptr, PtrDiff) &&
  15395. !OverLimitInDependenceCheck(OtherStore, RootNode))
  15396. StoreNodes.push_back(MemOpLink(OtherStore, PtrDiff));
  15397. }
  15398. };
  15399. // We looking for a root node which is an ancestor to all mergable
  15400. // stores. We search up through a load, to our root and then down
  15401. // through all children. For instance we will find Store{1,2,3} if
  15402. // St is Store1, Store2. or Store3 where the root is not a load
  15403. // which always true for nonvolatile ops. TODO: Expand
  15404. // the search to find all valid candidates through multiple layers of loads.
  15405. //
  15406. // Root
  15407. // |-------|-------|
  15408. // Load Load Store3
  15409. // | |
  15410. // Store1 Store2
  15411. //
  15412. // FIXME: We should be able to climb and
  15413. // descend TokenFactors to find candidates as well.
  15414. RootNode = St->getChain().getNode();
  15415. unsigned NumNodesExplored = 0;
  15416. const unsigned MaxSearchNodes = 1024;
  15417. if (auto *Ldn = dyn_cast<LoadSDNode>(RootNode)) {
  15418. RootNode = Ldn->getChain().getNode();
  15419. for (auto I = RootNode->use_begin(), E = RootNode->use_end();
  15420. I != E && NumNodesExplored < MaxSearchNodes; ++I, ++NumNodesExplored) {
  15421. if (I.getOperandNo() == 0 && isa<LoadSDNode>(*I)) { // walk down chain
  15422. for (auto I2 = (*I)->use_begin(), E2 = (*I)->use_end(); I2 != E2; ++I2)
  15423. TryToAddCandidate(I2);
  15424. }
  15425. // Check stores that depend on the root (e.g. Store 3 in the chart above).
  15426. if (I.getOperandNo() == 0 && isa<StoreSDNode>(*I)) {
  15427. TryToAddCandidate(I);
  15428. }
  15429. }
  15430. } else {
  15431. for (auto I = RootNode->use_begin(), E = RootNode->use_end();
  15432. I != E && NumNodesExplored < MaxSearchNodes; ++I, ++NumNodesExplored)
  15433. TryToAddCandidate(I);
  15434. }
  15435. }
  15436. // We need to check that merging these stores does not cause a loop in
  15437. // the DAG. Any store candidate may depend on another candidate
  15438. // indirectly through its operand (we already consider dependencies
  15439. // through the chain). Check in parallel by searching up from
  15440. // non-chain operands of candidates.
  15441. bool DAGCombiner::checkMergeStoreCandidatesForDependencies(
  15442. SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumStores,
  15443. SDNode *RootNode) {
  15444. // FIXME: We should be able to truncate a full search of
  15445. // predecessors by doing a BFS and keeping tabs the originating
  15446. // stores from which worklist nodes come from in a similar way to
  15447. // TokenFactor simplfication.
  15448. SmallPtrSet<const SDNode *, 32> Visited;
  15449. SmallVector<const SDNode *, 8> Worklist;
  15450. // RootNode is a predecessor to all candidates so we need not search
  15451. // past it. Add RootNode (peeking through TokenFactors). Do not count
  15452. // these towards size check.
  15453. Worklist.push_back(RootNode);
  15454. while (!Worklist.empty()) {
  15455. auto N = Worklist.pop_back_val();
  15456. if (!Visited.insert(N).second)
  15457. continue; // Already present in Visited.
  15458. if (N->getOpcode() == ISD::TokenFactor) {
  15459. for (SDValue Op : N->ops())
  15460. Worklist.push_back(Op.getNode());
  15461. }
  15462. }
  15463. // Don't count pruning nodes towards max.
  15464. unsigned int Max = 1024 + Visited.size();
  15465. // Search Ops of store candidates.
  15466. for (unsigned i = 0; i < NumStores; ++i) {
  15467. SDNode *N = StoreNodes[i].MemNode;
  15468. // Of the 4 Store Operands:
  15469. // * Chain (Op 0) -> We have already considered these
  15470. // in candidate selection and can be
  15471. // safely ignored
  15472. // * Value (Op 1) -> Cycles may happen (e.g. through load chains)
  15473. // * Address (Op 2) -> Merged addresses may only vary by a fixed constant,
  15474. // but aren't necessarily fromt the same base node, so
  15475. // cycles possible (e.g. via indexed store).
  15476. // * (Op 3) -> Represents the pre or post-indexing offset (or undef for
  15477. // non-indexed stores). Not constant on all targets (e.g. ARM)
  15478. // and so can participate in a cycle.
  15479. for (unsigned j = 1; j < N->getNumOperands(); ++j)
  15480. Worklist.push_back(N->getOperand(j).getNode());
  15481. }
  15482. // Search through DAG. We can stop early if we find a store node.
  15483. for (unsigned i = 0; i < NumStores; ++i)
  15484. if (SDNode::hasPredecessorHelper(StoreNodes[i].MemNode, Visited, Worklist,
  15485. Max)) {
  15486. // If the searching bail out, record the StoreNode and RootNode in the
  15487. // StoreRootCountMap. If we have seen the pair many times over a limit,
  15488. // we won't add the StoreNode into StoreNodes set again.
  15489. if (Visited.size() >= Max) {
  15490. auto &RootCount = StoreRootCountMap[StoreNodes[i].MemNode];
  15491. if (RootCount.first == RootNode)
  15492. RootCount.second++;
  15493. else
  15494. RootCount = {RootNode, 1};
  15495. }
  15496. return false;
  15497. }
  15498. return true;
  15499. }
  15500. unsigned
  15501. DAGCombiner::getConsecutiveStores(SmallVectorImpl<MemOpLink> &StoreNodes,
  15502. int64_t ElementSizeBytes) const {
  15503. while (true) {
  15504. // Find a store past the width of the first store.
  15505. size_t StartIdx = 0;
  15506. while ((StartIdx + 1 < StoreNodes.size()) &&
  15507. StoreNodes[StartIdx].OffsetFromBase + ElementSizeBytes !=
  15508. StoreNodes[StartIdx + 1].OffsetFromBase)
  15509. ++StartIdx;
  15510. // Bail if we don't have enough candidates to merge.
  15511. if (StartIdx + 1 >= StoreNodes.size())
  15512. return 0;
  15513. // Trim stores that overlapped with the first store.
  15514. if (StartIdx)
  15515. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + StartIdx);
  15516. // Scan the memory operations on the chain and find the first
  15517. // non-consecutive store memory address.
  15518. unsigned NumConsecutiveStores = 1;
  15519. int64_t StartAddress = StoreNodes[0].OffsetFromBase;
  15520. // Check that the addresses are consecutive starting from the second
  15521. // element in the list of stores.
  15522. for (unsigned i = 1, e = StoreNodes.size(); i < e; ++i) {
  15523. int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
  15524. if (CurrAddress - StartAddress != (ElementSizeBytes * i))
  15525. break;
  15526. NumConsecutiveStores = i + 1;
  15527. }
  15528. if (NumConsecutiveStores > 1)
  15529. return NumConsecutiveStores;
  15530. // There are no consecutive stores at the start of the list.
  15531. // Remove the first store and try again.
  15532. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 1);
  15533. }
  15534. }
  15535. bool DAGCombiner::tryStoreMergeOfConstants(
  15536. SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumConsecutiveStores,
  15537. EVT MemVT, SDNode *RootNode, bool AllowVectors) {
  15538. LLVMContext &Context = *DAG.getContext();
  15539. const DataLayout &DL = DAG.getDataLayout();
  15540. int64_t ElementSizeBytes = MemVT.getStoreSize();
  15541. unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
  15542. bool MadeChange = false;
  15543. // Store the constants into memory as one consecutive store.
  15544. while (NumConsecutiveStores >= 2) {
  15545. LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
  15546. unsigned FirstStoreAS = FirstInChain->getAddressSpace();
  15547. unsigned FirstStoreAlign = FirstInChain->getAlignment();
  15548. unsigned LastLegalType = 1;
  15549. unsigned LastLegalVectorType = 1;
  15550. bool LastIntegerTrunc = false;
  15551. bool NonZero = false;
  15552. unsigned FirstZeroAfterNonZero = NumConsecutiveStores;
  15553. for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
  15554. StoreSDNode *ST = cast<StoreSDNode>(StoreNodes[i].MemNode);
  15555. SDValue StoredVal = ST->getValue();
  15556. bool IsElementZero = false;
  15557. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal))
  15558. IsElementZero = C->isZero();
  15559. else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal))
  15560. IsElementZero = C->getConstantFPValue()->isNullValue();
  15561. if (IsElementZero) {
  15562. if (NonZero && FirstZeroAfterNonZero == NumConsecutiveStores)
  15563. FirstZeroAfterNonZero = i;
  15564. }
  15565. NonZero |= !IsElementZero;
  15566. // Find a legal type for the constant store.
  15567. unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
  15568. EVT StoreTy = EVT::getIntegerVT(Context, SizeInBits);
  15569. bool IsFast = false;
  15570. // Break early when size is too large to be legal.
  15571. if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits)
  15572. break;
  15573. if (TLI.isTypeLegal(StoreTy) &&
  15574. TLI.canMergeStoresTo(FirstStoreAS, StoreTy,
  15575. DAG.getMachineFunction()) &&
  15576. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  15577. *FirstInChain->getMemOperand(), &IsFast) &&
  15578. IsFast) {
  15579. LastIntegerTrunc = false;
  15580. LastLegalType = i + 1;
  15581. // Or check whether a truncstore is legal.
  15582. } else if (TLI.getTypeAction(Context, StoreTy) ==
  15583. TargetLowering::TypePromoteInteger) {
  15584. EVT LegalizedStoredValTy =
  15585. TLI.getTypeToTransformTo(Context, StoredVal.getValueType());
  15586. if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) &&
  15587. TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy,
  15588. DAG.getMachineFunction()) &&
  15589. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  15590. *FirstInChain->getMemOperand(), &IsFast) &&
  15591. IsFast) {
  15592. LastIntegerTrunc = true;
  15593. LastLegalType = i + 1;
  15594. }
  15595. }
  15596. // We only use vectors if the constant is known to be zero or the
  15597. // target allows it and the function is not marked with the
  15598. // noimplicitfloat attribute.
  15599. if ((!NonZero ||
  15600. TLI.storeOfVectorConstantIsCheap(MemVT, i + 1, FirstStoreAS)) &&
  15601. AllowVectors) {
  15602. // Find a legal type for the vector store.
  15603. unsigned Elts = (i + 1) * NumMemElts;
  15604. EVT Ty = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
  15605. if (TLI.isTypeLegal(Ty) && TLI.isTypeLegal(MemVT) &&
  15606. TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG.getMachineFunction()) &&
  15607. TLI.allowsMemoryAccess(Context, DL, Ty,
  15608. *FirstInChain->getMemOperand(), &IsFast) &&
  15609. IsFast)
  15610. LastLegalVectorType = i + 1;
  15611. }
  15612. }
  15613. bool UseVector = (LastLegalVectorType > LastLegalType) && AllowVectors;
  15614. unsigned NumElem = (UseVector) ? LastLegalVectorType : LastLegalType;
  15615. bool UseTrunc = LastIntegerTrunc && !UseVector;
  15616. // Check if we found a legal integer type that creates a meaningful
  15617. // merge.
  15618. if (NumElem < 2) {
  15619. // We know that candidate stores are in order and of correct
  15620. // shape. While there is no mergeable sequence from the
  15621. // beginning one may start later in the sequence. The only
  15622. // reason a merge of size N could have failed where another of
  15623. // the same size would not have, is if the alignment has
  15624. // improved or we've dropped a non-zero value. Drop as many
  15625. // candidates as we can here.
  15626. unsigned NumSkip = 1;
  15627. while ((NumSkip < NumConsecutiveStores) &&
  15628. (NumSkip < FirstZeroAfterNonZero) &&
  15629. (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
  15630. NumSkip++;
  15631. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
  15632. NumConsecutiveStores -= NumSkip;
  15633. continue;
  15634. }
  15635. // Check that we can merge these candidates without causing a cycle.
  15636. if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
  15637. RootNode)) {
  15638. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
  15639. NumConsecutiveStores -= NumElem;
  15640. continue;
  15641. }
  15642. MadeChange |= mergeStoresOfConstantsOrVecElts(StoreNodes, MemVT, NumElem,
  15643. /*IsConstantSrc*/ true,
  15644. UseVector, UseTrunc);
  15645. // Remove merged stores for next iteration.
  15646. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
  15647. NumConsecutiveStores -= NumElem;
  15648. }
  15649. return MadeChange;
  15650. }
  15651. bool DAGCombiner::tryStoreMergeOfExtracts(
  15652. SmallVectorImpl<MemOpLink> &StoreNodes, unsigned NumConsecutiveStores,
  15653. EVT MemVT, SDNode *RootNode) {
  15654. LLVMContext &Context = *DAG.getContext();
  15655. const DataLayout &DL = DAG.getDataLayout();
  15656. unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
  15657. bool MadeChange = false;
  15658. // Loop on Consecutive Stores on success.
  15659. while (NumConsecutiveStores >= 2) {
  15660. LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
  15661. unsigned FirstStoreAS = FirstInChain->getAddressSpace();
  15662. unsigned FirstStoreAlign = FirstInChain->getAlignment();
  15663. unsigned NumStoresToMerge = 1;
  15664. for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
  15665. // Find a legal type for the vector store.
  15666. unsigned Elts = (i + 1) * NumMemElts;
  15667. EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT.getScalarType(), Elts);
  15668. bool IsFast = false;
  15669. // Break early when size is too large to be legal.
  15670. if (Ty.getSizeInBits() > MaximumLegalStoreInBits)
  15671. break;
  15672. if (TLI.isTypeLegal(Ty) &&
  15673. TLI.canMergeStoresTo(FirstStoreAS, Ty, DAG.getMachineFunction()) &&
  15674. TLI.allowsMemoryAccess(Context, DL, Ty,
  15675. *FirstInChain->getMemOperand(), &IsFast) &&
  15676. IsFast)
  15677. NumStoresToMerge = i + 1;
  15678. }
  15679. // Check if we found a legal integer type creating a meaningful
  15680. // merge.
  15681. if (NumStoresToMerge < 2) {
  15682. // We know that candidate stores are in order and of correct
  15683. // shape. While there is no mergeable sequence from the
  15684. // beginning one may start later in the sequence. The only
  15685. // reason a merge of size N could have failed where another of
  15686. // the same size would not have, is if the alignment has
  15687. // improved. Drop as many candidates as we can here.
  15688. unsigned NumSkip = 1;
  15689. while ((NumSkip < NumConsecutiveStores) &&
  15690. (StoreNodes[NumSkip].MemNode->getAlignment() <= FirstStoreAlign))
  15691. NumSkip++;
  15692. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
  15693. NumConsecutiveStores -= NumSkip;
  15694. continue;
  15695. }
  15696. // Check that we can merge these candidates without causing a cycle.
  15697. if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumStoresToMerge,
  15698. RootNode)) {
  15699. StoreNodes.erase(StoreNodes.begin(),
  15700. StoreNodes.begin() + NumStoresToMerge);
  15701. NumConsecutiveStores -= NumStoresToMerge;
  15702. continue;
  15703. }
  15704. MadeChange |= mergeStoresOfConstantsOrVecElts(
  15705. StoreNodes, MemVT, NumStoresToMerge, /*IsConstantSrc*/ false,
  15706. /*UseVector*/ true, /*UseTrunc*/ false);
  15707. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumStoresToMerge);
  15708. NumConsecutiveStores -= NumStoresToMerge;
  15709. }
  15710. return MadeChange;
  15711. }
  15712. bool DAGCombiner::tryStoreMergeOfLoads(SmallVectorImpl<MemOpLink> &StoreNodes,
  15713. unsigned NumConsecutiveStores, EVT MemVT,
  15714. SDNode *RootNode, bool AllowVectors,
  15715. bool IsNonTemporalStore,
  15716. bool IsNonTemporalLoad) {
  15717. LLVMContext &Context = *DAG.getContext();
  15718. const DataLayout &DL = DAG.getDataLayout();
  15719. int64_t ElementSizeBytes = MemVT.getStoreSize();
  15720. unsigned NumMemElts = MemVT.isVector() ? MemVT.getVectorNumElements() : 1;
  15721. bool MadeChange = false;
  15722. // Look for load nodes which are used by the stored values.
  15723. SmallVector<MemOpLink, 8> LoadNodes;
  15724. // Find acceptable loads. Loads need to have the same chain (token factor),
  15725. // must not be zext, volatile, indexed, and they must be consecutive.
  15726. BaseIndexOffset LdBasePtr;
  15727. for (unsigned i = 0; i < NumConsecutiveStores; ++i) {
  15728. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
  15729. SDValue Val = peekThroughBitcasts(St->getValue());
  15730. LoadSDNode *Ld = cast<LoadSDNode>(Val);
  15731. BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld, DAG);
  15732. // If this is not the first ptr that we check.
  15733. int64_t LdOffset = 0;
  15734. if (LdBasePtr.getBase().getNode()) {
  15735. // The base ptr must be the same.
  15736. if (!LdBasePtr.equalBaseIndex(LdPtr, DAG, LdOffset))
  15737. break;
  15738. } else {
  15739. // Check that all other base pointers are the same as this one.
  15740. LdBasePtr = LdPtr;
  15741. }
  15742. // We found a potential memory operand to merge.
  15743. LoadNodes.push_back(MemOpLink(Ld, LdOffset));
  15744. }
  15745. while (NumConsecutiveStores >= 2 && LoadNodes.size() >= 2) {
  15746. Align RequiredAlignment;
  15747. bool NeedRotate = false;
  15748. if (LoadNodes.size() == 2) {
  15749. // If we have load/store pair instructions and we only have two values,
  15750. // don't bother merging.
  15751. if (TLI.hasPairedLoad(MemVT, RequiredAlignment) &&
  15752. StoreNodes[0].MemNode->getAlign() >= RequiredAlignment) {
  15753. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + 2);
  15754. LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + 2);
  15755. break;
  15756. }
  15757. // If the loads are reversed, see if we can rotate the halves into place.
  15758. int64_t Offset0 = LoadNodes[0].OffsetFromBase;
  15759. int64_t Offset1 = LoadNodes[1].OffsetFromBase;
  15760. EVT PairVT = EVT::getIntegerVT(Context, ElementSizeBytes * 8 * 2);
  15761. if (Offset0 - Offset1 == ElementSizeBytes &&
  15762. (hasOperation(ISD::ROTL, PairVT) ||
  15763. hasOperation(ISD::ROTR, PairVT))) {
  15764. std::swap(LoadNodes[0], LoadNodes[1]);
  15765. NeedRotate = true;
  15766. }
  15767. }
  15768. LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
  15769. unsigned FirstStoreAS = FirstInChain->getAddressSpace();
  15770. Align FirstStoreAlign = FirstInChain->getAlign();
  15771. LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
  15772. // Scan the memory operations on the chain and find the first
  15773. // non-consecutive load memory address. These variables hold the index in
  15774. // the store node array.
  15775. unsigned LastConsecutiveLoad = 1;
  15776. // This variable refers to the size and not index in the array.
  15777. unsigned LastLegalVectorType = 1;
  15778. unsigned LastLegalIntegerType = 1;
  15779. bool isDereferenceable = true;
  15780. bool DoIntegerTruncate = false;
  15781. int64_t StartAddress = LoadNodes[0].OffsetFromBase;
  15782. SDValue LoadChain = FirstLoad->getChain();
  15783. for (unsigned i = 1; i < LoadNodes.size(); ++i) {
  15784. // All loads must share the same chain.
  15785. if (LoadNodes[i].MemNode->getChain() != LoadChain)
  15786. break;
  15787. int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
  15788. if (CurrAddress - StartAddress != (ElementSizeBytes * i))
  15789. break;
  15790. LastConsecutiveLoad = i;
  15791. if (isDereferenceable && !LoadNodes[i].MemNode->isDereferenceable())
  15792. isDereferenceable = false;
  15793. // Find a legal type for the vector store.
  15794. unsigned Elts = (i + 1) * NumMemElts;
  15795. EVT StoreTy = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
  15796. // Break early when size is too large to be legal.
  15797. if (StoreTy.getSizeInBits() > MaximumLegalStoreInBits)
  15798. break;
  15799. bool IsFastSt = false;
  15800. bool IsFastLd = false;
  15801. // Don't try vector types if we need a rotate. We may still fail the
  15802. // legality checks for the integer type, but we can't handle the rotate
  15803. // case with vectors.
  15804. // FIXME: We could use a shuffle in place of the rotate.
  15805. if (!NeedRotate && TLI.isTypeLegal(StoreTy) &&
  15806. TLI.canMergeStoresTo(FirstStoreAS, StoreTy,
  15807. DAG.getMachineFunction()) &&
  15808. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  15809. *FirstInChain->getMemOperand(), &IsFastSt) &&
  15810. IsFastSt &&
  15811. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  15812. *FirstLoad->getMemOperand(), &IsFastLd) &&
  15813. IsFastLd) {
  15814. LastLegalVectorType = i + 1;
  15815. }
  15816. // Find a legal type for the integer store.
  15817. unsigned SizeInBits = (i + 1) * ElementSizeBytes * 8;
  15818. StoreTy = EVT::getIntegerVT(Context, SizeInBits);
  15819. if (TLI.isTypeLegal(StoreTy) &&
  15820. TLI.canMergeStoresTo(FirstStoreAS, StoreTy,
  15821. DAG.getMachineFunction()) &&
  15822. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  15823. *FirstInChain->getMemOperand(), &IsFastSt) &&
  15824. IsFastSt &&
  15825. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  15826. *FirstLoad->getMemOperand(), &IsFastLd) &&
  15827. IsFastLd) {
  15828. LastLegalIntegerType = i + 1;
  15829. DoIntegerTruncate = false;
  15830. // Or check whether a truncstore and extload is legal.
  15831. } else if (TLI.getTypeAction(Context, StoreTy) ==
  15832. TargetLowering::TypePromoteInteger) {
  15833. EVT LegalizedStoredValTy = TLI.getTypeToTransformTo(Context, StoreTy);
  15834. if (TLI.isTruncStoreLegal(LegalizedStoredValTy, StoreTy) &&
  15835. TLI.canMergeStoresTo(FirstStoreAS, LegalizedStoredValTy,
  15836. DAG.getMachineFunction()) &&
  15837. TLI.isLoadExtLegal(ISD::ZEXTLOAD, LegalizedStoredValTy, StoreTy) &&
  15838. TLI.isLoadExtLegal(ISD::SEXTLOAD, LegalizedStoredValTy, StoreTy) &&
  15839. TLI.isLoadExtLegal(ISD::EXTLOAD, LegalizedStoredValTy, StoreTy) &&
  15840. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  15841. *FirstInChain->getMemOperand(), &IsFastSt) &&
  15842. IsFastSt &&
  15843. TLI.allowsMemoryAccess(Context, DL, StoreTy,
  15844. *FirstLoad->getMemOperand(), &IsFastLd) &&
  15845. IsFastLd) {
  15846. LastLegalIntegerType = i + 1;
  15847. DoIntegerTruncate = true;
  15848. }
  15849. }
  15850. }
  15851. // Only use vector types if the vector type is larger than the integer
  15852. // type. If they are the same, use integers.
  15853. bool UseVectorTy =
  15854. LastLegalVectorType > LastLegalIntegerType && AllowVectors;
  15855. unsigned LastLegalType =
  15856. std::max(LastLegalVectorType, LastLegalIntegerType);
  15857. // We add +1 here because the LastXXX variables refer to location while
  15858. // the NumElem refers to array/index size.
  15859. unsigned NumElem = std::min(NumConsecutiveStores, LastConsecutiveLoad + 1);
  15860. NumElem = std::min(LastLegalType, NumElem);
  15861. Align FirstLoadAlign = FirstLoad->getAlign();
  15862. if (NumElem < 2) {
  15863. // We know that candidate stores are in order and of correct
  15864. // shape. While there is no mergeable sequence from the
  15865. // beginning one may start later in the sequence. The only
  15866. // reason a merge of size N could have failed where another of
  15867. // the same size would not have is if the alignment or either
  15868. // the load or store has improved. Drop as many candidates as we
  15869. // can here.
  15870. unsigned NumSkip = 1;
  15871. while ((NumSkip < LoadNodes.size()) &&
  15872. (LoadNodes[NumSkip].MemNode->getAlign() <= FirstLoadAlign) &&
  15873. (StoreNodes[NumSkip].MemNode->getAlign() <= FirstStoreAlign))
  15874. NumSkip++;
  15875. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumSkip);
  15876. LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumSkip);
  15877. NumConsecutiveStores -= NumSkip;
  15878. continue;
  15879. }
  15880. // Check that we can merge these candidates without causing a cycle.
  15881. if (!checkMergeStoreCandidatesForDependencies(StoreNodes, NumElem,
  15882. RootNode)) {
  15883. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
  15884. LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem);
  15885. NumConsecutiveStores -= NumElem;
  15886. continue;
  15887. }
  15888. // Find if it is better to use vectors or integers to load and store
  15889. // to memory.
  15890. EVT JointMemOpVT;
  15891. if (UseVectorTy) {
  15892. // Find a legal type for the vector store.
  15893. unsigned Elts = NumElem * NumMemElts;
  15894. JointMemOpVT = EVT::getVectorVT(Context, MemVT.getScalarType(), Elts);
  15895. } else {
  15896. unsigned SizeInBits = NumElem * ElementSizeBytes * 8;
  15897. JointMemOpVT = EVT::getIntegerVT(Context, SizeInBits);
  15898. }
  15899. SDLoc LoadDL(LoadNodes[0].MemNode);
  15900. SDLoc StoreDL(StoreNodes[0].MemNode);
  15901. // The merged loads are required to have the same incoming chain, so
  15902. // using the first's chain is acceptable.
  15903. SDValue NewStoreChain = getMergeStoreChains(StoreNodes, NumElem);
  15904. AddToWorklist(NewStoreChain.getNode());
  15905. MachineMemOperand::Flags LdMMOFlags =
  15906. isDereferenceable ? MachineMemOperand::MODereferenceable
  15907. : MachineMemOperand::MONone;
  15908. if (IsNonTemporalLoad)
  15909. LdMMOFlags |= MachineMemOperand::MONonTemporal;
  15910. MachineMemOperand::Flags StMMOFlags = IsNonTemporalStore
  15911. ? MachineMemOperand::MONonTemporal
  15912. : MachineMemOperand::MONone;
  15913. SDValue NewLoad, NewStore;
  15914. if (UseVectorTy || !DoIntegerTruncate) {
  15915. NewLoad = DAG.getLoad(
  15916. JointMemOpVT, LoadDL, FirstLoad->getChain(), FirstLoad->getBasePtr(),
  15917. FirstLoad->getPointerInfo(), FirstLoadAlign, LdMMOFlags);
  15918. SDValue StoreOp = NewLoad;
  15919. if (NeedRotate) {
  15920. unsigned LoadWidth = ElementSizeBytes * 8 * 2;
  15921. assert(JointMemOpVT == EVT::getIntegerVT(Context, LoadWidth) &&
  15922. "Unexpected type for rotate-able load pair");
  15923. SDValue RotAmt =
  15924. DAG.getShiftAmountConstant(LoadWidth / 2, JointMemOpVT, LoadDL);
  15925. // Target can convert to the identical ROTR if it does not have ROTL.
  15926. StoreOp = DAG.getNode(ISD::ROTL, LoadDL, JointMemOpVT, NewLoad, RotAmt);
  15927. }
  15928. NewStore = DAG.getStore(
  15929. NewStoreChain, StoreDL, StoreOp, FirstInChain->getBasePtr(),
  15930. FirstInChain->getPointerInfo(), FirstStoreAlign, StMMOFlags);
  15931. } else { // This must be the truncstore/extload case
  15932. EVT ExtendedTy =
  15933. TLI.getTypeToTransformTo(*DAG.getContext(), JointMemOpVT);
  15934. NewLoad = DAG.getExtLoad(ISD::EXTLOAD, LoadDL, ExtendedTy,
  15935. FirstLoad->getChain(), FirstLoad->getBasePtr(),
  15936. FirstLoad->getPointerInfo(), JointMemOpVT,
  15937. FirstLoadAlign, LdMMOFlags);
  15938. NewStore = DAG.getTruncStore(
  15939. NewStoreChain, StoreDL, NewLoad, FirstInChain->getBasePtr(),
  15940. FirstInChain->getPointerInfo(), JointMemOpVT,
  15941. FirstInChain->getAlign(), FirstInChain->getMemOperand()->getFlags());
  15942. }
  15943. // Transfer chain users from old loads to the new load.
  15944. for (unsigned i = 0; i < NumElem; ++i) {
  15945. LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
  15946. DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
  15947. SDValue(NewLoad.getNode(), 1));
  15948. }
  15949. // Replace all stores with the new store. Recursively remove corresponding
  15950. // values if they are no longer used.
  15951. for (unsigned i = 0; i < NumElem; ++i) {
  15952. SDValue Val = StoreNodes[i].MemNode->getOperand(1);
  15953. CombineTo(StoreNodes[i].MemNode, NewStore);
  15954. if (Val.getNode()->use_empty())
  15955. recursivelyDeleteUnusedNodes(Val.getNode());
  15956. }
  15957. MadeChange = true;
  15958. StoreNodes.erase(StoreNodes.begin(), StoreNodes.begin() + NumElem);
  15959. LoadNodes.erase(LoadNodes.begin(), LoadNodes.begin() + NumElem);
  15960. NumConsecutiveStores -= NumElem;
  15961. }
  15962. return MadeChange;
  15963. }
  15964. bool DAGCombiner::mergeConsecutiveStores(StoreSDNode *St) {
  15965. if (OptLevel == CodeGenOpt::None || !EnableStoreMerging)
  15966. return false;
  15967. // TODO: Extend this function to merge stores of scalable vectors.
  15968. // (i.e. two <vscale x 8 x i8> stores can be merged to one <vscale x 16 x i8>
  15969. // store since we know <vscale x 16 x i8> is exactly twice as large as
  15970. // <vscale x 8 x i8>). Until then, bail out for scalable vectors.
  15971. EVT MemVT = St->getMemoryVT();
  15972. if (MemVT.isScalableVector())
  15973. return false;
  15974. if (!MemVT.isSimple() || MemVT.getSizeInBits() * 2 > MaximumLegalStoreInBits)
  15975. return false;
  15976. // This function cannot currently deal with non-byte-sized memory sizes.
  15977. int64_t ElementSizeBytes = MemVT.getStoreSize();
  15978. if (ElementSizeBytes * 8 != (int64_t)MemVT.getSizeInBits())
  15979. return false;
  15980. // Do not bother looking at stored values that are not constants, loads, or
  15981. // extracted vector elements.
  15982. SDValue StoredVal = peekThroughBitcasts(St->getValue());
  15983. const StoreSource StoreSrc = getStoreSource(StoredVal);
  15984. if (StoreSrc == StoreSource::Unknown)
  15985. return false;
  15986. SmallVector<MemOpLink, 8> StoreNodes;
  15987. SDNode *RootNode;
  15988. // Find potential store merge candidates by searching through chain sub-DAG
  15989. getStoreMergeCandidates(St, StoreNodes, RootNode);
  15990. // Check if there is anything to merge.
  15991. if (StoreNodes.size() < 2)
  15992. return false;
  15993. // Sort the memory operands according to their distance from the
  15994. // base pointer.
  15995. llvm::sort(StoreNodes, [](MemOpLink LHS, MemOpLink RHS) {
  15996. return LHS.OffsetFromBase < RHS.OffsetFromBase;
  15997. });
  15998. bool AllowVectors = !DAG.getMachineFunction().getFunction().hasFnAttribute(
  15999. Attribute::NoImplicitFloat);
  16000. bool IsNonTemporalStore = St->isNonTemporal();
  16001. bool IsNonTemporalLoad = StoreSrc == StoreSource::Load &&
  16002. cast<LoadSDNode>(StoredVal)->isNonTemporal();
  16003. // Store Merge attempts to merge the lowest stores. This generally
  16004. // works out as if successful, as the remaining stores are checked
  16005. // after the first collection of stores is merged. However, in the
  16006. // case that a non-mergeable store is found first, e.g., {p[-2],
  16007. // p[0], p[1], p[2], p[3]}, we would fail and miss the subsequent
  16008. // mergeable cases. To prevent this, we prune such stores from the
  16009. // front of StoreNodes here.
  16010. bool MadeChange = false;
  16011. while (StoreNodes.size() > 1) {
  16012. unsigned NumConsecutiveStores =
  16013. getConsecutiveStores(StoreNodes, ElementSizeBytes);
  16014. // There are no more stores in the list to examine.
  16015. if (NumConsecutiveStores == 0)
  16016. return MadeChange;
  16017. // We have at least 2 consecutive stores. Try to merge them.
  16018. assert(NumConsecutiveStores >= 2 && "Expected at least 2 stores");
  16019. switch (StoreSrc) {
  16020. case StoreSource::Constant:
  16021. MadeChange |= tryStoreMergeOfConstants(StoreNodes, NumConsecutiveStores,
  16022. MemVT, RootNode, AllowVectors);
  16023. break;
  16024. case StoreSource::Extract:
  16025. MadeChange |= tryStoreMergeOfExtracts(StoreNodes, NumConsecutiveStores,
  16026. MemVT, RootNode);
  16027. break;
  16028. case StoreSource::Load:
  16029. MadeChange |= tryStoreMergeOfLoads(StoreNodes, NumConsecutiveStores,
  16030. MemVT, RootNode, AllowVectors,
  16031. IsNonTemporalStore, IsNonTemporalLoad);
  16032. break;
  16033. default:
  16034. llvm_unreachable("Unhandled store source type");
  16035. }
  16036. }
  16037. return MadeChange;
  16038. }
  16039. SDValue DAGCombiner::replaceStoreChain(StoreSDNode *ST, SDValue BetterChain) {
  16040. SDLoc SL(ST);
  16041. SDValue ReplStore;
  16042. // Replace the chain to avoid dependency.
  16043. if (ST->isTruncatingStore()) {
  16044. ReplStore = DAG.getTruncStore(BetterChain, SL, ST->getValue(),
  16045. ST->getBasePtr(), ST->getMemoryVT(),
  16046. ST->getMemOperand());
  16047. } else {
  16048. ReplStore = DAG.getStore(BetterChain, SL, ST->getValue(), ST->getBasePtr(),
  16049. ST->getMemOperand());
  16050. }
  16051. // Create token to keep both nodes around.
  16052. SDValue Token = DAG.getNode(ISD::TokenFactor, SL,
  16053. MVT::Other, ST->getChain(), ReplStore);
  16054. // Make sure the new and old chains are cleaned up.
  16055. AddToWorklist(Token.getNode());
  16056. // Don't add users to work list.
  16057. return CombineTo(ST, Token, false);
  16058. }
  16059. SDValue DAGCombiner::replaceStoreOfFPConstant(StoreSDNode *ST) {
  16060. SDValue Value = ST->getValue();
  16061. if (Value.getOpcode() == ISD::TargetConstantFP)
  16062. return SDValue();
  16063. if (!ISD::isNormalStore(ST))
  16064. return SDValue();
  16065. SDLoc DL(ST);
  16066. SDValue Chain = ST->getChain();
  16067. SDValue Ptr = ST->getBasePtr();
  16068. const ConstantFPSDNode *CFP = cast<ConstantFPSDNode>(Value);
  16069. // NOTE: If the original store is volatile, this transform must not increase
  16070. // the number of stores. For example, on x86-32 an f64 can be stored in one
  16071. // processor operation but an i64 (which is not legal) requires two. So the
  16072. // transform should not be done in this case.
  16073. SDValue Tmp;
  16074. switch (CFP->getSimpleValueType(0).SimpleTy) {
  16075. default:
  16076. llvm_unreachable("Unknown FP type");
  16077. case MVT::f16: // We don't do this for these yet.
  16078. case MVT::f80:
  16079. case MVT::f128:
  16080. case MVT::ppcf128:
  16081. return SDValue();
  16082. case MVT::f32:
  16083. if ((isTypeLegal(MVT::i32) && !LegalOperations && ST->isSimple()) ||
  16084. TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
  16085. ;
  16086. Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
  16087. bitcastToAPInt().getZExtValue(), SDLoc(CFP),
  16088. MVT::i32);
  16089. return DAG.getStore(Chain, DL, Tmp, Ptr, ST->getMemOperand());
  16090. }
  16091. return SDValue();
  16092. case MVT::f64:
  16093. if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
  16094. ST->isSimple()) ||
  16095. TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
  16096. ;
  16097. Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
  16098. getZExtValue(), SDLoc(CFP), MVT::i64);
  16099. return DAG.getStore(Chain, DL, Tmp,
  16100. Ptr, ST->getMemOperand());
  16101. }
  16102. if (ST->isSimple() &&
  16103. TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
  16104. // Many FP stores are not made apparent until after legalize, e.g. for
  16105. // argument passing. Since this is so common, custom legalize the
  16106. // 64-bit integer store into two 32-bit stores.
  16107. uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
  16108. SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, SDLoc(CFP), MVT::i32);
  16109. SDValue Hi = DAG.getConstant(Val >> 32, SDLoc(CFP), MVT::i32);
  16110. if (DAG.getDataLayout().isBigEndian())
  16111. std::swap(Lo, Hi);
  16112. MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
  16113. AAMDNodes AAInfo = ST->getAAInfo();
  16114. SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
  16115. ST->getOriginalAlign(), MMOFlags, AAInfo);
  16116. Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(4), DL);
  16117. SDValue St1 = DAG.getStore(Chain, DL, Hi, Ptr,
  16118. ST->getPointerInfo().getWithOffset(4),
  16119. ST->getOriginalAlign(), MMOFlags, AAInfo);
  16120. return DAG.getNode(ISD::TokenFactor, DL, MVT::Other,
  16121. St0, St1);
  16122. }
  16123. return SDValue();
  16124. }
  16125. }
  16126. SDValue DAGCombiner::visitSTORE(SDNode *N) {
  16127. StoreSDNode *ST = cast<StoreSDNode>(N);
  16128. SDValue Chain = ST->getChain();
  16129. SDValue Value = ST->getValue();
  16130. SDValue Ptr = ST->getBasePtr();
  16131. // If this is a store of a bit convert, store the input value if the
  16132. // resultant store does not need a higher alignment than the original.
  16133. if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
  16134. ST->isUnindexed()) {
  16135. EVT SVT = Value.getOperand(0).getValueType();
  16136. // If the store is volatile, we only want to change the store type if the
  16137. // resulting store is legal. Otherwise we might increase the number of
  16138. // memory accesses. We don't care if the original type was legal or not
  16139. // as we assume software couldn't rely on the number of accesses of an
  16140. // illegal type.
  16141. // TODO: May be able to relax for unordered atomics (see D66309)
  16142. if (((!LegalOperations && ST->isSimple()) ||
  16143. TLI.isOperationLegal(ISD::STORE, SVT)) &&
  16144. TLI.isStoreBitCastBeneficial(Value.getValueType(), SVT,
  16145. DAG, *ST->getMemOperand())) {
  16146. return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
  16147. ST->getMemOperand());
  16148. }
  16149. }
  16150. // Turn 'store undef, Ptr' -> nothing.
  16151. if (Value.isUndef() && ST->isUnindexed())
  16152. return Chain;
  16153. // Try to infer better alignment information than the store already has.
  16154. if (OptLevel != CodeGenOpt::None && ST->isUnindexed() && !ST->isAtomic()) {
  16155. if (MaybeAlign Alignment = DAG.InferPtrAlign(Ptr)) {
  16156. if (*Alignment > ST->getAlign() &&
  16157. isAligned(*Alignment, ST->getSrcValueOffset())) {
  16158. SDValue NewStore =
  16159. DAG.getTruncStore(Chain, SDLoc(N), Value, Ptr, ST->getPointerInfo(),
  16160. ST->getMemoryVT(), *Alignment,
  16161. ST->getMemOperand()->getFlags(), ST->getAAInfo());
  16162. // NewStore will always be N as we are only refining the alignment
  16163. assert(NewStore.getNode() == N);
  16164. (void)NewStore;
  16165. }
  16166. }
  16167. }
  16168. // Try transforming a pair floating point load / store ops to integer
  16169. // load / store ops.
  16170. if (SDValue NewST = TransformFPLoadStorePair(N))
  16171. return NewST;
  16172. // Try transforming several stores into STORE (BSWAP).
  16173. if (SDValue Store = mergeTruncStores(ST))
  16174. return Store;
  16175. if (ST->isUnindexed()) {
  16176. // Walk up chain skipping non-aliasing memory nodes, on this store and any
  16177. // adjacent stores.
  16178. if (findBetterNeighborChains(ST)) {
  16179. // replaceStoreChain uses CombineTo, which handled all of the worklist
  16180. // manipulation. Return the original node to not do anything else.
  16181. return SDValue(ST, 0);
  16182. }
  16183. Chain = ST->getChain();
  16184. }
  16185. // FIXME: is there such a thing as a truncating indexed store?
  16186. if (ST->isTruncatingStore() && ST->isUnindexed() &&
  16187. Value.getValueType().isInteger() &&
  16188. (!isa<ConstantSDNode>(Value) ||
  16189. !cast<ConstantSDNode>(Value)->isOpaque())) {
  16190. // Convert a truncating store of a extension into a standard store.
  16191. if ((Value.getOpcode() == ISD::ZERO_EXTEND ||
  16192. Value.getOpcode() == ISD::SIGN_EXTEND ||
  16193. Value.getOpcode() == ISD::ANY_EXTEND) &&
  16194. Value.getOperand(0).getValueType() == ST->getMemoryVT() &&
  16195. TLI.isOperationLegalOrCustom(ISD::STORE, ST->getMemoryVT()))
  16196. return DAG.getStore(Chain, SDLoc(N), Value.getOperand(0), Ptr,
  16197. ST->getMemOperand());
  16198. APInt TruncDemandedBits =
  16199. APInt::getLowBitsSet(Value.getScalarValueSizeInBits(),
  16200. ST->getMemoryVT().getScalarSizeInBits());
  16201. // See if we can simplify the input to this truncstore with knowledge that
  16202. // only the low bits are being used. For example:
  16203. // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
  16204. AddToWorklist(Value.getNode());
  16205. if (SDValue Shorter = DAG.GetDemandedBits(Value, TruncDemandedBits))
  16206. return DAG.getTruncStore(Chain, SDLoc(N), Shorter, Ptr, ST->getMemoryVT(),
  16207. ST->getMemOperand());
  16208. // Otherwise, see if we can simplify the operation with
  16209. // SimplifyDemandedBits, which only works if the value has a single use.
  16210. if (SimplifyDemandedBits(Value, TruncDemandedBits)) {
  16211. // Re-visit the store if anything changed and the store hasn't been merged
  16212. // with another node (N is deleted) SimplifyDemandedBits will add Value's
  16213. // node back to the worklist if necessary, but we also need to re-visit
  16214. // the Store node itself.
  16215. if (N->getOpcode() != ISD::DELETED_NODE)
  16216. AddToWorklist(N);
  16217. return SDValue(N, 0);
  16218. }
  16219. }
  16220. // If this is a load followed by a store to the same location, then the store
  16221. // is dead/noop.
  16222. // TODO: Can relax for unordered atomics (see D66309)
  16223. if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
  16224. if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
  16225. ST->isUnindexed() && ST->isSimple() &&
  16226. Ld->getAddressSpace() == ST->getAddressSpace() &&
  16227. // There can't be any side effects between the load and store, such as
  16228. // a call or store.
  16229. Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
  16230. // The store is dead, remove it.
  16231. return Chain;
  16232. }
  16233. }
  16234. // TODO: Can relax for unordered atomics (see D66309)
  16235. if (StoreSDNode *ST1 = dyn_cast<StoreSDNode>(Chain)) {
  16236. if (ST->isUnindexed() && ST->isSimple() &&
  16237. ST1->isUnindexed() && ST1->isSimple()) {
  16238. if (OptLevel != CodeGenOpt::None && ST1->getBasePtr() == Ptr &&
  16239. ST1->getValue() == Value && ST->getMemoryVT() == ST1->getMemoryVT() &&
  16240. ST->getAddressSpace() == ST1->getAddressSpace()) {
  16241. // If this is a store followed by a store with the same value to the
  16242. // same location, then the store is dead/noop.
  16243. return Chain;
  16244. }
  16245. if (OptLevel != CodeGenOpt::None && ST1->hasOneUse() &&
  16246. !ST1->getBasePtr().isUndef() &&
  16247. // BaseIndexOffset and the code below requires knowing the size
  16248. // of a vector, so bail out if MemoryVT is scalable.
  16249. !ST->getMemoryVT().isScalableVector() &&
  16250. !ST1->getMemoryVT().isScalableVector() &&
  16251. ST->getAddressSpace() == ST1->getAddressSpace()) {
  16252. const BaseIndexOffset STBase = BaseIndexOffset::match(ST, DAG);
  16253. const BaseIndexOffset ChainBase = BaseIndexOffset::match(ST1, DAG);
  16254. unsigned STBitSize = ST->getMemoryVT().getFixedSizeInBits();
  16255. unsigned ChainBitSize = ST1->getMemoryVT().getFixedSizeInBits();
  16256. // If this is a store who's preceding store to a subset of the current
  16257. // location and no one other node is chained to that store we can
  16258. // effectively drop the store. Do not remove stores to undef as they may
  16259. // be used as data sinks.
  16260. if (STBase.contains(DAG, STBitSize, ChainBase, ChainBitSize)) {
  16261. CombineTo(ST1, ST1->getChain());
  16262. return SDValue();
  16263. }
  16264. }
  16265. }
  16266. }
  16267. // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
  16268. // truncating store. We can do this even if this is already a truncstore.
  16269. if ((Value.getOpcode() == ISD::FP_ROUND ||
  16270. Value.getOpcode() == ISD::TRUNCATE) &&
  16271. Value.getNode()->hasOneUse() && ST->isUnindexed() &&
  16272. TLI.canCombineTruncStore(Value.getOperand(0).getValueType(),
  16273. ST->getMemoryVT(), LegalOperations)) {
  16274. return DAG.getTruncStore(Chain, SDLoc(N), Value.getOperand(0),
  16275. Ptr, ST->getMemoryVT(), ST->getMemOperand());
  16276. }
  16277. // Always perform this optimization before types are legal. If the target
  16278. // prefers, also try this after legalization to catch stores that were created
  16279. // by intrinsics or other nodes.
  16280. if (!LegalTypes || (TLI.mergeStoresAfterLegalization(ST->getMemoryVT()))) {
  16281. while (true) {
  16282. // There can be multiple store sequences on the same chain.
  16283. // Keep trying to merge store sequences until we are unable to do so
  16284. // or until we merge the last store on the chain.
  16285. bool Changed = mergeConsecutiveStores(ST);
  16286. if (!Changed) break;
  16287. // Return N as merge only uses CombineTo and no worklist clean
  16288. // up is necessary.
  16289. if (N->getOpcode() == ISD::DELETED_NODE || !isa<StoreSDNode>(N))
  16290. return SDValue(N, 0);
  16291. }
  16292. }
  16293. // Try transforming N to an indexed store.
  16294. if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
  16295. return SDValue(N, 0);
  16296. // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
  16297. //
  16298. // Make sure to do this only after attempting to merge stores in order to
  16299. // avoid changing the types of some subset of stores due to visit order,
  16300. // preventing their merging.
  16301. if (isa<ConstantFPSDNode>(ST->getValue())) {
  16302. if (SDValue NewSt = replaceStoreOfFPConstant(ST))
  16303. return NewSt;
  16304. }
  16305. if (SDValue NewSt = splitMergedValStore(ST))
  16306. return NewSt;
  16307. return ReduceLoadOpStoreWidth(N);
  16308. }
  16309. SDValue DAGCombiner::visitLIFETIME_END(SDNode *N) {
  16310. const auto *LifetimeEnd = cast<LifetimeSDNode>(N);
  16311. if (!LifetimeEnd->hasOffset())
  16312. return SDValue();
  16313. const BaseIndexOffset LifetimeEndBase(N->getOperand(1), SDValue(),
  16314. LifetimeEnd->getOffset(), false);
  16315. // We walk up the chains to find stores.
  16316. SmallVector<SDValue, 8> Chains = {N->getOperand(0)};
  16317. while (!Chains.empty()) {
  16318. SDValue Chain = Chains.pop_back_val();
  16319. if (!Chain.hasOneUse())
  16320. continue;
  16321. switch (Chain.getOpcode()) {
  16322. case ISD::TokenFactor:
  16323. for (unsigned Nops = Chain.getNumOperands(); Nops;)
  16324. Chains.push_back(Chain.getOperand(--Nops));
  16325. break;
  16326. case ISD::LIFETIME_START:
  16327. case ISD::LIFETIME_END:
  16328. // We can forward past any lifetime start/end that can be proven not to
  16329. // alias the node.
  16330. if (!mayAlias(Chain.getNode(), N))
  16331. Chains.push_back(Chain.getOperand(0));
  16332. break;
  16333. case ISD::STORE: {
  16334. StoreSDNode *ST = dyn_cast<StoreSDNode>(Chain);
  16335. // TODO: Can relax for unordered atomics (see D66309)
  16336. if (!ST->isSimple() || ST->isIndexed())
  16337. continue;
  16338. const TypeSize StoreSize = ST->getMemoryVT().getStoreSize();
  16339. // The bounds of a scalable store are not known until runtime, so this
  16340. // store cannot be elided.
  16341. if (StoreSize.isScalable())
  16342. continue;
  16343. const BaseIndexOffset StoreBase = BaseIndexOffset::match(ST, DAG);
  16344. // If we store purely within object bounds just before its lifetime ends,
  16345. // we can remove the store.
  16346. if (LifetimeEndBase.contains(DAG, LifetimeEnd->getSize() * 8, StoreBase,
  16347. StoreSize.getFixedSize() * 8)) {
  16348. LLVM_DEBUG(dbgs() << "\nRemoving store:"; StoreBase.dump();
  16349. dbgs() << "\nwithin LIFETIME_END of : ";
  16350. LifetimeEndBase.dump(); dbgs() << "\n");
  16351. CombineTo(ST, ST->getChain());
  16352. return SDValue(N, 0);
  16353. }
  16354. }
  16355. }
  16356. }
  16357. return SDValue();
  16358. }
  16359. /// For the instruction sequence of store below, F and I values
  16360. /// are bundled together as an i64 value before being stored into memory.
  16361. /// Sometimes it is more efficent to generate separate stores for F and I,
  16362. /// which can remove the bitwise instructions or sink them to colder places.
  16363. ///
  16364. /// (store (or (zext (bitcast F to i32) to i64),
  16365. /// (shl (zext I to i64), 32)), addr) -->
  16366. /// (store F, addr) and (store I, addr+4)
  16367. ///
  16368. /// Similarly, splitting for other merged store can also be beneficial, like:
  16369. /// For pair of {i32, i32}, i64 store --> two i32 stores.
  16370. /// For pair of {i32, i16}, i64 store --> two i32 stores.
  16371. /// For pair of {i16, i16}, i32 store --> two i16 stores.
  16372. /// For pair of {i16, i8}, i32 store --> two i16 stores.
  16373. /// For pair of {i8, i8}, i16 store --> two i8 stores.
  16374. ///
  16375. /// We allow each target to determine specifically which kind of splitting is
  16376. /// supported.
  16377. ///
  16378. /// The store patterns are commonly seen from the simple code snippet below
  16379. /// if only std::make_pair(...) is sroa transformed before inlined into hoo.
  16380. /// void goo(const std::pair<int, float> &);
  16381. /// hoo() {
  16382. /// ...
  16383. /// goo(std::make_pair(tmp, ftmp));
  16384. /// ...
  16385. /// }
  16386. ///
  16387. SDValue DAGCombiner::splitMergedValStore(StoreSDNode *ST) {
  16388. if (OptLevel == CodeGenOpt::None)
  16389. return SDValue();
  16390. // Can't change the number of memory accesses for a volatile store or break
  16391. // atomicity for an atomic one.
  16392. if (!ST->isSimple())
  16393. return SDValue();
  16394. SDValue Val = ST->getValue();
  16395. SDLoc DL(ST);
  16396. // Match OR operand.
  16397. if (!Val.getValueType().isScalarInteger() || Val.getOpcode() != ISD::OR)
  16398. return SDValue();
  16399. // Match SHL operand and get Lower and Higher parts of Val.
  16400. SDValue Op1 = Val.getOperand(0);
  16401. SDValue Op2 = Val.getOperand(1);
  16402. SDValue Lo, Hi;
  16403. if (Op1.getOpcode() != ISD::SHL) {
  16404. std::swap(Op1, Op2);
  16405. if (Op1.getOpcode() != ISD::SHL)
  16406. return SDValue();
  16407. }
  16408. Lo = Op2;
  16409. Hi = Op1.getOperand(0);
  16410. if (!Op1.hasOneUse())
  16411. return SDValue();
  16412. // Match shift amount to HalfValBitSize.
  16413. unsigned HalfValBitSize = Val.getValueSizeInBits() / 2;
  16414. ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(Op1.getOperand(1));
  16415. if (!ShAmt || ShAmt->getAPIntValue() != HalfValBitSize)
  16416. return SDValue();
  16417. // Lo and Hi are zero-extended from int with size less equal than 32
  16418. // to i64.
  16419. if (Lo.getOpcode() != ISD::ZERO_EXTEND || !Lo.hasOneUse() ||
  16420. !Lo.getOperand(0).getValueType().isScalarInteger() ||
  16421. Lo.getOperand(0).getValueSizeInBits() > HalfValBitSize ||
  16422. Hi.getOpcode() != ISD::ZERO_EXTEND || !Hi.hasOneUse() ||
  16423. !Hi.getOperand(0).getValueType().isScalarInteger() ||
  16424. Hi.getOperand(0).getValueSizeInBits() > HalfValBitSize)
  16425. return SDValue();
  16426. // Use the EVT of low and high parts before bitcast as the input
  16427. // of target query.
  16428. EVT LowTy = (Lo.getOperand(0).getOpcode() == ISD::BITCAST)
  16429. ? Lo.getOperand(0).getValueType()
  16430. : Lo.getValueType();
  16431. EVT HighTy = (Hi.getOperand(0).getOpcode() == ISD::BITCAST)
  16432. ? Hi.getOperand(0).getValueType()
  16433. : Hi.getValueType();
  16434. if (!TLI.isMultiStoresCheaperThanBitsMerge(LowTy, HighTy))
  16435. return SDValue();
  16436. // Start to split store.
  16437. MachineMemOperand::Flags MMOFlags = ST->getMemOperand()->getFlags();
  16438. AAMDNodes AAInfo = ST->getAAInfo();
  16439. // Change the sizes of Lo and Hi's value types to HalfValBitSize.
  16440. EVT VT = EVT::getIntegerVT(*DAG.getContext(), HalfValBitSize);
  16441. Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Lo.getOperand(0));
  16442. Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Hi.getOperand(0));
  16443. SDValue Chain = ST->getChain();
  16444. SDValue Ptr = ST->getBasePtr();
  16445. // Lower value store.
  16446. SDValue St0 = DAG.getStore(Chain, DL, Lo, Ptr, ST->getPointerInfo(),
  16447. ST->getOriginalAlign(), MMOFlags, AAInfo);
  16448. Ptr = DAG.getMemBasePlusOffset(Ptr, TypeSize::Fixed(HalfValBitSize / 8), DL);
  16449. // Higher value store.
  16450. SDValue St1 = DAG.getStore(
  16451. St0, DL, Hi, Ptr, ST->getPointerInfo().getWithOffset(HalfValBitSize / 8),
  16452. ST->getOriginalAlign(), MMOFlags, AAInfo);
  16453. return St1;
  16454. }
  16455. /// Convert a disguised subvector insertion into a shuffle:
  16456. SDValue DAGCombiner::combineInsertEltToShuffle(SDNode *N, unsigned InsIndex) {
  16457. assert(N->getOpcode() == ISD::INSERT_VECTOR_ELT &&
  16458. "Expected extract_vector_elt");
  16459. SDValue InsertVal = N->getOperand(1);
  16460. SDValue Vec = N->getOperand(0);
  16461. // (insert_vector_elt (vector_shuffle X, Y), (extract_vector_elt X, N),
  16462. // InsIndex)
  16463. // --> (vector_shuffle X, Y) and variations where shuffle operands may be
  16464. // CONCAT_VECTORS.
  16465. if (Vec.getOpcode() == ISD::VECTOR_SHUFFLE && Vec.hasOneUse() &&
  16466. InsertVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  16467. isa<ConstantSDNode>(InsertVal.getOperand(1))) {
  16468. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(Vec.getNode());
  16469. ArrayRef<int> Mask = SVN->getMask();
  16470. SDValue X = Vec.getOperand(0);
  16471. SDValue Y = Vec.getOperand(1);
  16472. // Vec's operand 0 is using indices from 0 to N-1 and
  16473. // operand 1 from N to 2N - 1, where N is the number of
  16474. // elements in the vectors.
  16475. SDValue InsertVal0 = InsertVal.getOperand(0);
  16476. int ElementOffset = -1;
  16477. // We explore the inputs of the shuffle in order to see if we find the
  16478. // source of the extract_vector_elt. If so, we can use it to modify the
  16479. // shuffle rather than perform an insert_vector_elt.
  16480. SmallVector<std::pair<int, SDValue>, 8> ArgWorkList;
  16481. ArgWorkList.emplace_back(Mask.size(), Y);
  16482. ArgWorkList.emplace_back(0, X);
  16483. while (!ArgWorkList.empty()) {
  16484. int ArgOffset;
  16485. SDValue ArgVal;
  16486. std::tie(ArgOffset, ArgVal) = ArgWorkList.pop_back_val();
  16487. if (ArgVal == InsertVal0) {
  16488. ElementOffset = ArgOffset;
  16489. break;
  16490. }
  16491. // Peek through concat_vector.
  16492. if (ArgVal.getOpcode() == ISD::CONCAT_VECTORS) {
  16493. int CurrentArgOffset =
  16494. ArgOffset + ArgVal.getValueType().getVectorNumElements();
  16495. int Step = ArgVal.getOperand(0).getValueType().getVectorNumElements();
  16496. for (SDValue Op : reverse(ArgVal->ops())) {
  16497. CurrentArgOffset -= Step;
  16498. ArgWorkList.emplace_back(CurrentArgOffset, Op);
  16499. }
  16500. // Make sure we went through all the elements and did not screw up index
  16501. // computation.
  16502. assert(CurrentArgOffset == ArgOffset);
  16503. }
  16504. }
  16505. if (ElementOffset != -1) {
  16506. SmallVector<int, 16> NewMask(Mask.begin(), Mask.end());
  16507. auto *ExtrIndex = cast<ConstantSDNode>(InsertVal.getOperand(1));
  16508. NewMask[InsIndex] = ElementOffset + ExtrIndex->getZExtValue();
  16509. assert(NewMask[InsIndex] <
  16510. (int)(2 * Vec.getValueType().getVectorNumElements()) &&
  16511. NewMask[InsIndex] >= 0 && "NewMask[InsIndex] is out of bound");
  16512. SDValue LegalShuffle =
  16513. TLI.buildLegalVectorShuffle(Vec.getValueType(), SDLoc(N), X,
  16514. Y, NewMask, DAG);
  16515. if (LegalShuffle)
  16516. return LegalShuffle;
  16517. }
  16518. }
  16519. // insert_vector_elt V, (bitcast X from vector type), IdxC -->
  16520. // bitcast(shuffle (bitcast V), (extended X), Mask)
  16521. // Note: We do not use an insert_subvector node because that requires a
  16522. // legal subvector type.
  16523. if (InsertVal.getOpcode() != ISD::BITCAST || !InsertVal.hasOneUse() ||
  16524. !InsertVal.getOperand(0).getValueType().isVector())
  16525. return SDValue();
  16526. SDValue SubVec = InsertVal.getOperand(0);
  16527. SDValue DestVec = N->getOperand(0);
  16528. EVT SubVecVT = SubVec.getValueType();
  16529. EVT VT = DestVec.getValueType();
  16530. unsigned NumSrcElts = SubVecVT.getVectorNumElements();
  16531. // If the source only has a single vector element, the cost of creating adding
  16532. // it to a vector is likely to exceed the cost of a insert_vector_elt.
  16533. if (NumSrcElts == 1)
  16534. return SDValue();
  16535. unsigned ExtendRatio = VT.getSizeInBits() / SubVecVT.getSizeInBits();
  16536. unsigned NumMaskVals = ExtendRatio * NumSrcElts;
  16537. // Step 1: Create a shuffle mask that implements this insert operation. The
  16538. // vector that we are inserting into will be operand 0 of the shuffle, so
  16539. // those elements are just 'i'. The inserted subvector is in the first
  16540. // positions of operand 1 of the shuffle. Example:
  16541. // insert v4i32 V, (v2i16 X), 2 --> shuffle v8i16 V', X', {0,1,2,3,8,9,6,7}
  16542. SmallVector<int, 16> Mask(NumMaskVals);
  16543. for (unsigned i = 0; i != NumMaskVals; ++i) {
  16544. if (i / NumSrcElts == InsIndex)
  16545. Mask[i] = (i % NumSrcElts) + NumMaskVals;
  16546. else
  16547. Mask[i] = i;
  16548. }
  16549. // Bail out if the target can not handle the shuffle we want to create.
  16550. EVT SubVecEltVT = SubVecVT.getVectorElementType();
  16551. EVT ShufVT = EVT::getVectorVT(*DAG.getContext(), SubVecEltVT, NumMaskVals);
  16552. if (!TLI.isShuffleMaskLegal(Mask, ShufVT))
  16553. return SDValue();
  16554. // Step 2: Create a wide vector from the inserted source vector by appending
  16555. // undefined elements. This is the same size as our destination vector.
  16556. SDLoc DL(N);
  16557. SmallVector<SDValue, 8> ConcatOps(ExtendRatio, DAG.getUNDEF(SubVecVT));
  16558. ConcatOps[0] = SubVec;
  16559. SDValue PaddedSubV = DAG.getNode(ISD::CONCAT_VECTORS, DL, ShufVT, ConcatOps);
  16560. // Step 3: Shuffle in the padded subvector.
  16561. SDValue DestVecBC = DAG.getBitcast(ShufVT, DestVec);
  16562. SDValue Shuf = DAG.getVectorShuffle(ShufVT, DL, DestVecBC, PaddedSubV, Mask);
  16563. AddToWorklist(PaddedSubV.getNode());
  16564. AddToWorklist(DestVecBC.getNode());
  16565. AddToWorklist(Shuf.getNode());
  16566. return DAG.getBitcast(VT, Shuf);
  16567. }
  16568. SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
  16569. SDValue InVec = N->getOperand(0);
  16570. SDValue InVal = N->getOperand(1);
  16571. SDValue EltNo = N->getOperand(2);
  16572. SDLoc DL(N);
  16573. EVT VT = InVec.getValueType();
  16574. auto *IndexC = dyn_cast<ConstantSDNode>(EltNo);
  16575. // Insert into out-of-bounds element is undefined.
  16576. if (IndexC && VT.isFixedLengthVector() &&
  16577. IndexC->getZExtValue() >= VT.getVectorNumElements())
  16578. return DAG.getUNDEF(VT);
  16579. // Remove redundant insertions:
  16580. // (insert_vector_elt x (extract_vector_elt x idx) idx) -> x
  16581. if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  16582. InVec == InVal.getOperand(0) && EltNo == InVal.getOperand(1))
  16583. return InVec;
  16584. if (!IndexC) {
  16585. // If this is variable insert to undef vector, it might be better to splat:
  16586. // inselt undef, InVal, EltNo --> build_vector < InVal, InVal, ... >
  16587. if (InVec.isUndef() && TLI.shouldSplatInsEltVarIndex(VT)) {
  16588. if (VT.isScalableVector())
  16589. return DAG.getSplatVector(VT, DL, InVal);
  16590. else {
  16591. SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), InVal);
  16592. return DAG.getBuildVector(VT, DL, Ops);
  16593. }
  16594. }
  16595. return SDValue();
  16596. }
  16597. if (VT.isScalableVector())
  16598. return SDValue();
  16599. unsigned NumElts = VT.getVectorNumElements();
  16600. // We must know which element is being inserted for folds below here.
  16601. unsigned Elt = IndexC->getZExtValue();
  16602. if (SDValue Shuf = combineInsertEltToShuffle(N, Elt))
  16603. return Shuf;
  16604. // Canonicalize insert_vector_elt dag nodes.
  16605. // Example:
  16606. // (insert_vector_elt (insert_vector_elt A, Idx0), Idx1)
  16607. // -> (insert_vector_elt (insert_vector_elt A, Idx1), Idx0)
  16608. //
  16609. // Do this only if the child insert_vector node has one use; also
  16610. // do this only if indices are both constants and Idx1 < Idx0.
  16611. if (InVec.getOpcode() == ISD::INSERT_VECTOR_ELT && InVec.hasOneUse()
  16612. && isa<ConstantSDNode>(InVec.getOperand(2))) {
  16613. unsigned OtherElt = InVec.getConstantOperandVal(2);
  16614. if (Elt < OtherElt) {
  16615. // Swap nodes.
  16616. SDValue NewOp = DAG.getNode(ISD::INSERT_VECTOR_ELT, DL, VT,
  16617. InVec.getOperand(0), InVal, EltNo);
  16618. AddToWorklist(NewOp.getNode());
  16619. return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(InVec.getNode()),
  16620. VT, NewOp, InVec.getOperand(1), InVec.getOperand(2));
  16621. }
  16622. }
  16623. // If we can't generate a legal BUILD_VECTOR, exit
  16624. if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
  16625. return SDValue();
  16626. // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
  16627. // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
  16628. // vector elements.
  16629. SmallVector<SDValue, 8> Ops;
  16630. // Do not combine these two vectors if the output vector will not replace
  16631. // the input vector.
  16632. if (InVec.getOpcode() == ISD::BUILD_VECTOR && InVec.hasOneUse()) {
  16633. Ops.append(InVec.getNode()->op_begin(),
  16634. InVec.getNode()->op_end());
  16635. } else if (InVec.isUndef()) {
  16636. Ops.append(NumElts, DAG.getUNDEF(InVal.getValueType()));
  16637. } else {
  16638. return SDValue();
  16639. }
  16640. assert(Ops.size() == NumElts && "Unexpected vector size");
  16641. // Insert the element
  16642. if (Elt < Ops.size()) {
  16643. // All the operands of BUILD_VECTOR must have the same type;
  16644. // we enforce that here.
  16645. EVT OpVT = Ops[0].getValueType();
  16646. Ops[Elt] = OpVT.isInteger() ? DAG.getAnyExtOrTrunc(InVal, DL, OpVT) : InVal;
  16647. }
  16648. // Return the new vector
  16649. return DAG.getBuildVector(VT, DL, Ops);
  16650. }
  16651. SDValue DAGCombiner::scalarizeExtractedVectorLoad(SDNode *EVE, EVT InVecVT,
  16652. SDValue EltNo,
  16653. LoadSDNode *OriginalLoad) {
  16654. assert(OriginalLoad->isSimple());
  16655. EVT ResultVT = EVE->getValueType(0);
  16656. EVT VecEltVT = InVecVT.getVectorElementType();
  16657. // If the vector element type is not a multiple of a byte then we are unable
  16658. // to correctly compute an address to load only the extracted element as a
  16659. // scalar.
  16660. if (!VecEltVT.isByteSized())
  16661. return SDValue();
  16662. ISD::LoadExtType ExtTy =
  16663. ResultVT.bitsGT(VecEltVT) ? ISD::NON_EXTLOAD : ISD::EXTLOAD;
  16664. if (!TLI.isOperationLegalOrCustom(ISD::LOAD, VecEltVT) ||
  16665. !TLI.shouldReduceLoadWidth(OriginalLoad, ExtTy, VecEltVT))
  16666. return SDValue();
  16667. Align Alignment = OriginalLoad->getAlign();
  16668. MachinePointerInfo MPI;
  16669. SDLoc DL(EVE);
  16670. if (auto *ConstEltNo = dyn_cast<ConstantSDNode>(EltNo)) {
  16671. int Elt = ConstEltNo->getZExtValue();
  16672. unsigned PtrOff = VecEltVT.getSizeInBits() * Elt / 8;
  16673. MPI = OriginalLoad->getPointerInfo().getWithOffset(PtrOff);
  16674. Alignment = commonAlignment(Alignment, PtrOff);
  16675. } else {
  16676. // Discard the pointer info except the address space because the memory
  16677. // operand can't represent this new access since the offset is variable.
  16678. MPI = MachinePointerInfo(OriginalLoad->getPointerInfo().getAddrSpace());
  16679. Alignment = commonAlignment(Alignment, VecEltVT.getSizeInBits() / 8);
  16680. }
  16681. bool IsFast = false;
  16682. if (!TLI.allowsMemoryAccess(*DAG.getContext(), DAG.getDataLayout(), VecEltVT,
  16683. OriginalLoad->getAddressSpace(), Alignment,
  16684. OriginalLoad->getMemOperand()->getFlags(),
  16685. &IsFast) ||
  16686. !IsFast)
  16687. return SDValue();
  16688. SDValue NewPtr = TLI.getVectorElementPointer(DAG, OriginalLoad->getBasePtr(),
  16689. InVecVT, EltNo);
  16690. // The replacement we need to do here is a little tricky: we need to
  16691. // replace an extractelement of a load with a load.
  16692. // Use ReplaceAllUsesOfValuesWith to do the replacement.
  16693. // Note that this replacement assumes that the extractvalue is the only
  16694. // use of the load; that's okay because we don't want to perform this
  16695. // transformation in other cases anyway.
  16696. SDValue Load;
  16697. SDValue Chain;
  16698. if (ResultVT.bitsGT(VecEltVT)) {
  16699. // If the result type of vextract is wider than the load, then issue an
  16700. // extending load instead.
  16701. ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, ResultVT,
  16702. VecEltVT)
  16703. ? ISD::ZEXTLOAD
  16704. : ISD::EXTLOAD;
  16705. Load = DAG.getExtLoad(ExtType, SDLoc(EVE), ResultVT,
  16706. OriginalLoad->getChain(), NewPtr, MPI, VecEltVT,
  16707. Alignment, OriginalLoad->getMemOperand()->getFlags(),
  16708. OriginalLoad->getAAInfo());
  16709. Chain = Load.getValue(1);
  16710. } else {
  16711. Load = DAG.getLoad(
  16712. VecEltVT, SDLoc(EVE), OriginalLoad->getChain(), NewPtr, MPI, Alignment,
  16713. OriginalLoad->getMemOperand()->getFlags(), OriginalLoad->getAAInfo());
  16714. Chain = Load.getValue(1);
  16715. if (ResultVT.bitsLT(VecEltVT))
  16716. Load = DAG.getNode(ISD::TRUNCATE, SDLoc(EVE), ResultVT, Load);
  16717. else
  16718. Load = DAG.getBitcast(ResultVT, Load);
  16719. }
  16720. WorklistRemover DeadNodes(*this);
  16721. SDValue From[] = { SDValue(EVE, 0), SDValue(OriginalLoad, 1) };
  16722. SDValue To[] = { Load, Chain };
  16723. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  16724. // Make sure to revisit this node to clean it up; it will usually be dead.
  16725. AddToWorklist(EVE);
  16726. // Since we're explicitly calling ReplaceAllUses, add the new node to the
  16727. // worklist explicitly as well.
  16728. AddToWorklistWithUsers(Load.getNode());
  16729. ++OpsNarrowed;
  16730. return SDValue(EVE, 0);
  16731. }
  16732. /// Transform a vector binary operation into a scalar binary operation by moving
  16733. /// the math/logic after an extract element of a vector.
  16734. static SDValue scalarizeExtractedBinop(SDNode *ExtElt, SelectionDAG &DAG,
  16735. bool LegalOperations) {
  16736. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  16737. SDValue Vec = ExtElt->getOperand(0);
  16738. SDValue Index = ExtElt->getOperand(1);
  16739. auto *IndexC = dyn_cast<ConstantSDNode>(Index);
  16740. if (!IndexC || !TLI.isBinOp(Vec.getOpcode()) || !Vec.hasOneUse() ||
  16741. Vec.getNode()->getNumValues() != 1)
  16742. return SDValue();
  16743. // Targets may want to avoid this to prevent an expensive register transfer.
  16744. if (!TLI.shouldScalarizeBinop(Vec))
  16745. return SDValue();
  16746. // Extracting an element of a vector constant is constant-folded, so this
  16747. // transform is just replacing a vector op with a scalar op while moving the
  16748. // extract.
  16749. SDValue Op0 = Vec.getOperand(0);
  16750. SDValue Op1 = Vec.getOperand(1);
  16751. if (isAnyConstantBuildVector(Op0, true) ||
  16752. isAnyConstantBuildVector(Op1, true)) {
  16753. // extractelt (binop X, C), IndexC --> binop (extractelt X, IndexC), C'
  16754. // extractelt (binop C, X), IndexC --> binop C', (extractelt X, IndexC)
  16755. SDLoc DL(ExtElt);
  16756. EVT VT = ExtElt->getValueType(0);
  16757. SDValue Ext0 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op0, Index);
  16758. SDValue Ext1 = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, VT, Op1, Index);
  16759. return DAG.getNode(Vec.getOpcode(), DL, VT, Ext0, Ext1);
  16760. }
  16761. return SDValue();
  16762. }
  16763. SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
  16764. SDValue VecOp = N->getOperand(0);
  16765. SDValue Index = N->getOperand(1);
  16766. EVT ScalarVT = N->getValueType(0);
  16767. EVT VecVT = VecOp.getValueType();
  16768. if (VecOp.isUndef())
  16769. return DAG.getUNDEF(ScalarVT);
  16770. // extract_vector_elt (insert_vector_elt vec, val, idx), idx) -> val
  16771. //
  16772. // This only really matters if the index is non-constant since other combines
  16773. // on the constant elements already work.
  16774. SDLoc DL(N);
  16775. if (VecOp.getOpcode() == ISD::INSERT_VECTOR_ELT &&
  16776. Index == VecOp.getOperand(2)) {
  16777. SDValue Elt = VecOp.getOperand(1);
  16778. return VecVT.isInteger() ? DAG.getAnyExtOrTrunc(Elt, DL, ScalarVT) : Elt;
  16779. }
  16780. // (vextract (scalar_to_vector val, 0) -> val
  16781. if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR) {
  16782. // Only 0'th element of SCALAR_TO_VECTOR is defined.
  16783. if (DAG.isKnownNeverZero(Index))
  16784. return DAG.getUNDEF(ScalarVT);
  16785. // Check if the result type doesn't match the inserted element type. A
  16786. // SCALAR_TO_VECTOR may truncate the inserted element and the
  16787. // EXTRACT_VECTOR_ELT may widen the extracted vector.
  16788. SDValue InOp = VecOp.getOperand(0);
  16789. if (InOp.getValueType() != ScalarVT) {
  16790. assert(InOp.getValueType().isInteger() && ScalarVT.isInteger());
  16791. return DAG.getSExtOrTrunc(InOp, DL, ScalarVT);
  16792. }
  16793. return InOp;
  16794. }
  16795. // extract_vector_elt of out-of-bounds element -> UNDEF
  16796. auto *IndexC = dyn_cast<ConstantSDNode>(Index);
  16797. if (IndexC && VecVT.isFixedLengthVector() &&
  16798. IndexC->getAPIntValue().uge(VecVT.getVectorNumElements()))
  16799. return DAG.getUNDEF(ScalarVT);
  16800. // extract_vector_elt (build_vector x, y), 1 -> y
  16801. if (((IndexC && VecOp.getOpcode() == ISD::BUILD_VECTOR) ||
  16802. VecOp.getOpcode() == ISD::SPLAT_VECTOR) &&
  16803. TLI.isTypeLegal(VecVT) &&
  16804. (VecOp.hasOneUse() || TLI.aggressivelyPreferBuildVectorSources(VecVT))) {
  16805. assert((VecOp.getOpcode() != ISD::BUILD_VECTOR ||
  16806. VecVT.isFixedLengthVector()) &&
  16807. "BUILD_VECTOR used for scalable vectors");
  16808. unsigned IndexVal =
  16809. VecOp.getOpcode() == ISD::BUILD_VECTOR ? IndexC->getZExtValue() : 0;
  16810. SDValue Elt = VecOp.getOperand(IndexVal);
  16811. EVT InEltVT = Elt.getValueType();
  16812. // Sometimes build_vector's scalar input types do not match result type.
  16813. if (ScalarVT == InEltVT)
  16814. return Elt;
  16815. // TODO: It may be useful to truncate if free if the build_vector implicitly
  16816. // converts.
  16817. }
  16818. if (VecVT.isScalableVector())
  16819. return SDValue();
  16820. // All the code from this point onwards assumes fixed width vectors, but it's
  16821. // possible that some of the combinations could be made to work for scalable
  16822. // vectors too.
  16823. unsigned NumElts = VecVT.getVectorNumElements();
  16824. unsigned VecEltBitWidth = VecVT.getScalarSizeInBits();
  16825. // TODO: These transforms should not require the 'hasOneUse' restriction, but
  16826. // there are regressions on multiple targets without it. We can end up with a
  16827. // mess of scalar and vector code if we reduce only part of the DAG to scalar.
  16828. if (IndexC && VecOp.getOpcode() == ISD::BITCAST && VecVT.isInteger() &&
  16829. VecOp.hasOneUse()) {
  16830. // The vector index of the LSBs of the source depend on the endian-ness.
  16831. bool IsLE = DAG.getDataLayout().isLittleEndian();
  16832. unsigned ExtractIndex = IndexC->getZExtValue();
  16833. // extract_elt (v2i32 (bitcast i64:x)), BCTruncElt -> i32 (trunc i64:x)
  16834. unsigned BCTruncElt = IsLE ? 0 : NumElts - 1;
  16835. SDValue BCSrc = VecOp.getOperand(0);
  16836. if (ExtractIndex == BCTruncElt && BCSrc.getValueType().isScalarInteger())
  16837. return DAG.getNode(ISD::TRUNCATE, DL, ScalarVT, BCSrc);
  16838. if (LegalTypes && BCSrc.getValueType().isInteger() &&
  16839. BCSrc.getOpcode() == ISD::SCALAR_TO_VECTOR) {
  16840. // ext_elt (bitcast (scalar_to_vec i64 X to v2i64) to v4i32), TruncElt -->
  16841. // trunc i64 X to i32
  16842. SDValue X = BCSrc.getOperand(0);
  16843. assert(X.getValueType().isScalarInteger() && ScalarVT.isScalarInteger() &&
  16844. "Extract element and scalar to vector can't change element type "
  16845. "from FP to integer.");
  16846. unsigned XBitWidth = X.getValueSizeInBits();
  16847. BCTruncElt = IsLE ? 0 : XBitWidth / VecEltBitWidth - 1;
  16848. // An extract element return value type can be wider than its vector
  16849. // operand element type. In that case, the high bits are undefined, so
  16850. // it's possible that we may need to extend rather than truncate.
  16851. if (ExtractIndex == BCTruncElt && XBitWidth > VecEltBitWidth) {
  16852. assert(XBitWidth % VecEltBitWidth == 0 &&
  16853. "Scalar bitwidth must be a multiple of vector element bitwidth");
  16854. return DAG.getAnyExtOrTrunc(X, DL, ScalarVT);
  16855. }
  16856. }
  16857. }
  16858. if (SDValue BO = scalarizeExtractedBinop(N, DAG, LegalOperations))
  16859. return BO;
  16860. // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
  16861. // We only perform this optimization before the op legalization phase because
  16862. // we may introduce new vector instructions which are not backed by TD
  16863. // patterns. For example on AVX, extracting elements from a wide vector
  16864. // without using extract_subvector. However, if we can find an underlying
  16865. // scalar value, then we can always use that.
  16866. if (IndexC && VecOp.getOpcode() == ISD::VECTOR_SHUFFLE) {
  16867. auto *Shuf = cast<ShuffleVectorSDNode>(VecOp);
  16868. // Find the new index to extract from.
  16869. int OrigElt = Shuf->getMaskElt(IndexC->getZExtValue());
  16870. // Extracting an undef index is undef.
  16871. if (OrigElt == -1)
  16872. return DAG.getUNDEF(ScalarVT);
  16873. // Select the right vector half to extract from.
  16874. SDValue SVInVec;
  16875. if (OrigElt < (int)NumElts) {
  16876. SVInVec = VecOp.getOperand(0);
  16877. } else {
  16878. SVInVec = VecOp.getOperand(1);
  16879. OrigElt -= NumElts;
  16880. }
  16881. if (SVInVec.getOpcode() == ISD::BUILD_VECTOR) {
  16882. SDValue InOp = SVInVec.getOperand(OrigElt);
  16883. if (InOp.getValueType() != ScalarVT) {
  16884. assert(InOp.getValueType().isInteger() && ScalarVT.isInteger());
  16885. InOp = DAG.getSExtOrTrunc(InOp, DL, ScalarVT);
  16886. }
  16887. return InOp;
  16888. }
  16889. // FIXME: We should handle recursing on other vector shuffles and
  16890. // scalar_to_vector here as well.
  16891. if (!LegalOperations ||
  16892. // FIXME: Should really be just isOperationLegalOrCustom.
  16893. TLI.isOperationLegal(ISD::EXTRACT_VECTOR_ELT, VecVT) ||
  16894. TLI.isOperationExpand(ISD::VECTOR_SHUFFLE, VecVT)) {
  16895. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT, SVInVec,
  16896. DAG.getVectorIdxConstant(OrigElt, DL));
  16897. }
  16898. }
  16899. // If only EXTRACT_VECTOR_ELT nodes use the source vector we can
  16900. // simplify it based on the (valid) extraction indices.
  16901. if (llvm::all_of(VecOp->uses(), [&](SDNode *Use) {
  16902. return Use->getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  16903. Use->getOperand(0) == VecOp &&
  16904. isa<ConstantSDNode>(Use->getOperand(1));
  16905. })) {
  16906. APInt DemandedElts = APInt::getZero(NumElts);
  16907. for (SDNode *Use : VecOp->uses()) {
  16908. auto *CstElt = cast<ConstantSDNode>(Use->getOperand(1));
  16909. if (CstElt->getAPIntValue().ult(NumElts))
  16910. DemandedElts.setBit(CstElt->getZExtValue());
  16911. }
  16912. if (SimplifyDemandedVectorElts(VecOp, DemandedElts, true)) {
  16913. // We simplified the vector operand of this extract element. If this
  16914. // extract is not dead, visit it again so it is folded properly.
  16915. if (N->getOpcode() != ISD::DELETED_NODE)
  16916. AddToWorklist(N);
  16917. return SDValue(N, 0);
  16918. }
  16919. APInt DemandedBits = APInt::getAllOnes(VecEltBitWidth);
  16920. if (SimplifyDemandedBits(VecOp, DemandedBits, DemandedElts, true)) {
  16921. // We simplified the vector operand of this extract element. If this
  16922. // extract is not dead, visit it again so it is folded properly.
  16923. if (N->getOpcode() != ISD::DELETED_NODE)
  16924. AddToWorklist(N);
  16925. return SDValue(N, 0);
  16926. }
  16927. }
  16928. // Everything under here is trying to match an extract of a loaded value.
  16929. // If the result of load has to be truncated, then it's not necessarily
  16930. // profitable.
  16931. bool BCNumEltsChanged = false;
  16932. EVT ExtVT = VecVT.getVectorElementType();
  16933. EVT LVT = ExtVT;
  16934. if (ScalarVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, ScalarVT))
  16935. return SDValue();
  16936. if (VecOp.getOpcode() == ISD::BITCAST) {
  16937. // Don't duplicate a load with other uses.
  16938. if (!VecOp.hasOneUse())
  16939. return SDValue();
  16940. EVT BCVT = VecOp.getOperand(0).getValueType();
  16941. if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
  16942. return SDValue();
  16943. if (NumElts != BCVT.getVectorNumElements())
  16944. BCNumEltsChanged = true;
  16945. VecOp = VecOp.getOperand(0);
  16946. ExtVT = BCVT.getVectorElementType();
  16947. }
  16948. // extract (vector load $addr), i --> load $addr + i * size
  16949. if (!LegalOperations && !IndexC && VecOp.hasOneUse() &&
  16950. ISD::isNormalLoad(VecOp.getNode()) &&
  16951. !Index->hasPredecessor(VecOp.getNode())) {
  16952. auto *VecLoad = dyn_cast<LoadSDNode>(VecOp);
  16953. if (VecLoad && VecLoad->isSimple())
  16954. return scalarizeExtractedVectorLoad(N, VecVT, Index, VecLoad);
  16955. }
  16956. // Perform only after legalization to ensure build_vector / vector_shuffle
  16957. // optimizations have already been done.
  16958. if (!LegalOperations || !IndexC)
  16959. return SDValue();
  16960. // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
  16961. // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
  16962. // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
  16963. int Elt = IndexC->getZExtValue();
  16964. LoadSDNode *LN0 = nullptr;
  16965. if (ISD::isNormalLoad(VecOp.getNode())) {
  16966. LN0 = cast<LoadSDNode>(VecOp);
  16967. } else if (VecOp.getOpcode() == ISD::SCALAR_TO_VECTOR &&
  16968. VecOp.getOperand(0).getValueType() == ExtVT &&
  16969. ISD::isNormalLoad(VecOp.getOperand(0).getNode())) {
  16970. // Don't duplicate a load with other uses.
  16971. if (!VecOp.hasOneUse())
  16972. return SDValue();
  16973. LN0 = cast<LoadSDNode>(VecOp.getOperand(0));
  16974. }
  16975. if (auto *Shuf = dyn_cast<ShuffleVectorSDNode>(VecOp)) {
  16976. // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
  16977. // =>
  16978. // (load $addr+1*size)
  16979. // Don't duplicate a load with other uses.
  16980. if (!VecOp.hasOneUse())
  16981. return SDValue();
  16982. // If the bit convert changed the number of elements, it is unsafe
  16983. // to examine the mask.
  16984. if (BCNumEltsChanged)
  16985. return SDValue();
  16986. // Select the input vector, guarding against out of range extract vector.
  16987. int Idx = (Elt > (int)NumElts) ? -1 : Shuf->getMaskElt(Elt);
  16988. VecOp = (Idx < (int)NumElts) ? VecOp.getOperand(0) : VecOp.getOperand(1);
  16989. if (VecOp.getOpcode() == ISD::BITCAST) {
  16990. // Don't duplicate a load with other uses.
  16991. if (!VecOp.hasOneUse())
  16992. return SDValue();
  16993. VecOp = VecOp.getOperand(0);
  16994. }
  16995. if (ISD::isNormalLoad(VecOp.getNode())) {
  16996. LN0 = cast<LoadSDNode>(VecOp);
  16997. Elt = (Idx < (int)NumElts) ? Idx : Idx - (int)NumElts;
  16998. Index = DAG.getConstant(Elt, DL, Index.getValueType());
  16999. }
  17000. } else if (VecOp.getOpcode() == ISD::CONCAT_VECTORS && !BCNumEltsChanged &&
  17001. VecVT.getVectorElementType() == ScalarVT &&
  17002. (!LegalTypes ||
  17003. TLI.isTypeLegal(
  17004. VecOp.getOperand(0).getValueType().getVectorElementType()))) {
  17005. // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 0
  17006. // -> extract_vector_elt a, 0
  17007. // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 1
  17008. // -> extract_vector_elt a, 1
  17009. // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 2
  17010. // -> extract_vector_elt b, 0
  17011. // extract_vector_elt (concat_vectors v2i16:a, v2i16:b), 3
  17012. // -> extract_vector_elt b, 1
  17013. SDLoc SL(N);
  17014. EVT ConcatVT = VecOp.getOperand(0).getValueType();
  17015. unsigned ConcatNumElts = ConcatVT.getVectorNumElements();
  17016. SDValue NewIdx = DAG.getConstant(Elt % ConcatNumElts, SL,
  17017. Index.getValueType());
  17018. SDValue ConcatOp = VecOp.getOperand(Elt / ConcatNumElts);
  17019. SDValue Elt = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, SL,
  17020. ConcatVT.getVectorElementType(),
  17021. ConcatOp, NewIdx);
  17022. return DAG.getNode(ISD::BITCAST, SL, ScalarVT, Elt);
  17023. }
  17024. // Make sure we found a non-volatile load and the extractelement is
  17025. // the only use.
  17026. if (!LN0 || !LN0->hasNUsesOfValue(1,0) || !LN0->isSimple())
  17027. return SDValue();
  17028. // If Idx was -1 above, Elt is going to be -1, so just return undef.
  17029. if (Elt == -1)
  17030. return DAG.getUNDEF(LVT);
  17031. return scalarizeExtractedVectorLoad(N, VecVT, Index, LN0);
  17032. }
  17033. // Simplify (build_vec (ext )) to (bitcast (build_vec ))
  17034. SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
  17035. // We perform this optimization post type-legalization because
  17036. // the type-legalizer often scalarizes integer-promoted vectors.
  17037. // Performing this optimization before may create bit-casts which
  17038. // will be type-legalized to complex code sequences.
  17039. // We perform this optimization only before the operation legalizer because we
  17040. // may introduce illegal operations.
  17041. if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
  17042. return SDValue();
  17043. unsigned NumInScalars = N->getNumOperands();
  17044. SDLoc DL(N);
  17045. EVT VT = N->getValueType(0);
  17046. // Check to see if this is a BUILD_VECTOR of a bunch of values
  17047. // which come from any_extend or zero_extend nodes. If so, we can create
  17048. // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
  17049. // optimizations. We do not handle sign-extend because we can't fill the sign
  17050. // using shuffles.
  17051. EVT SourceType = MVT::Other;
  17052. bool AllAnyExt = true;
  17053. for (unsigned i = 0; i != NumInScalars; ++i) {
  17054. SDValue In = N->getOperand(i);
  17055. // Ignore undef inputs.
  17056. if (In.isUndef()) continue;
  17057. bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
  17058. bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
  17059. // Abort if the element is not an extension.
  17060. if (!ZeroExt && !AnyExt) {
  17061. SourceType = MVT::Other;
  17062. break;
  17063. }
  17064. // The input is a ZeroExt or AnyExt. Check the original type.
  17065. EVT InTy = In.getOperand(0).getValueType();
  17066. // Check that all of the widened source types are the same.
  17067. if (SourceType == MVT::Other)
  17068. // First time.
  17069. SourceType = InTy;
  17070. else if (InTy != SourceType) {
  17071. // Multiple income types. Abort.
  17072. SourceType = MVT::Other;
  17073. break;
  17074. }
  17075. // Check if all of the extends are ANY_EXTENDs.
  17076. AllAnyExt &= AnyExt;
  17077. }
  17078. // In order to have valid types, all of the inputs must be extended from the
  17079. // same source type and all of the inputs must be any or zero extend.
  17080. // Scalar sizes must be a power of two.
  17081. EVT OutScalarTy = VT.getScalarType();
  17082. bool ValidTypes = SourceType != MVT::Other &&
  17083. isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
  17084. isPowerOf2_32(SourceType.getSizeInBits());
  17085. // Create a new simpler BUILD_VECTOR sequence which other optimizations can
  17086. // turn into a single shuffle instruction.
  17087. if (!ValidTypes)
  17088. return SDValue();
  17089. // If we already have a splat buildvector, then don't fold it if it means
  17090. // introducing zeros.
  17091. if (!AllAnyExt && DAG.isSplatValue(SDValue(N, 0), /*AllowUndefs*/ true))
  17092. return SDValue();
  17093. bool isLE = DAG.getDataLayout().isLittleEndian();
  17094. unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
  17095. assert(ElemRatio > 1 && "Invalid element size ratio");
  17096. SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
  17097. DAG.getConstant(0, DL, SourceType);
  17098. unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
  17099. SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
  17100. // Populate the new build_vector
  17101. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  17102. SDValue Cast = N->getOperand(i);
  17103. assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
  17104. Cast.getOpcode() == ISD::ZERO_EXTEND ||
  17105. Cast.isUndef()) && "Invalid cast opcode");
  17106. SDValue In;
  17107. if (Cast.isUndef())
  17108. In = DAG.getUNDEF(SourceType);
  17109. else
  17110. In = Cast->getOperand(0);
  17111. unsigned Index = isLE ? (i * ElemRatio) :
  17112. (i * ElemRatio + (ElemRatio - 1));
  17113. assert(Index < Ops.size() && "Invalid index");
  17114. Ops[Index] = In;
  17115. }
  17116. // The type of the new BUILD_VECTOR node.
  17117. EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
  17118. assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
  17119. "Invalid vector size");
  17120. // Check if the new vector type is legal.
  17121. if (!isTypeLegal(VecVT) ||
  17122. (!TLI.isOperationLegal(ISD::BUILD_VECTOR, VecVT) &&
  17123. TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)))
  17124. return SDValue();
  17125. // Make the new BUILD_VECTOR.
  17126. SDValue BV = DAG.getBuildVector(VecVT, DL, Ops);
  17127. // The new BUILD_VECTOR node has the potential to be further optimized.
  17128. AddToWorklist(BV.getNode());
  17129. // Bitcast to the desired type.
  17130. return DAG.getBitcast(VT, BV);
  17131. }
  17132. // Simplify (build_vec (trunc $1)
  17133. // (trunc (srl $1 half-width))
  17134. // (trunc (srl $1 (2 * half-width))) …)
  17135. // to (bitcast $1)
  17136. SDValue DAGCombiner::reduceBuildVecTruncToBitCast(SDNode *N) {
  17137. assert(N->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector");
  17138. // Only for little endian
  17139. if (!DAG.getDataLayout().isLittleEndian())
  17140. return SDValue();
  17141. SDLoc DL(N);
  17142. EVT VT = N->getValueType(0);
  17143. EVT OutScalarTy = VT.getScalarType();
  17144. uint64_t ScalarTypeBitsize = OutScalarTy.getSizeInBits();
  17145. // Only for power of two types to be sure that bitcast works well
  17146. if (!isPowerOf2_64(ScalarTypeBitsize))
  17147. return SDValue();
  17148. unsigned NumInScalars = N->getNumOperands();
  17149. // Look through bitcasts
  17150. auto PeekThroughBitcast = [](SDValue Op) {
  17151. if (Op.getOpcode() == ISD::BITCAST)
  17152. return Op.getOperand(0);
  17153. return Op;
  17154. };
  17155. // The source value where all the parts are extracted.
  17156. SDValue Src;
  17157. for (unsigned i = 0; i != NumInScalars; ++i) {
  17158. SDValue In = PeekThroughBitcast(N->getOperand(i));
  17159. // Ignore undef inputs.
  17160. if (In.isUndef()) continue;
  17161. if (In.getOpcode() != ISD::TRUNCATE)
  17162. return SDValue();
  17163. In = PeekThroughBitcast(In.getOperand(0));
  17164. if (In.getOpcode() != ISD::SRL) {
  17165. // For now only build_vec without shuffling, handle shifts here in the
  17166. // future.
  17167. if (i != 0)
  17168. return SDValue();
  17169. Src = In;
  17170. } else {
  17171. // In is SRL
  17172. SDValue part = PeekThroughBitcast(In.getOperand(0));
  17173. if (!Src) {
  17174. Src = part;
  17175. } else if (Src != part) {
  17176. // Vector parts do not stem from the same variable
  17177. return SDValue();
  17178. }
  17179. SDValue ShiftAmtVal = In.getOperand(1);
  17180. if (!isa<ConstantSDNode>(ShiftAmtVal))
  17181. return SDValue();
  17182. uint64_t ShiftAmt = In.getNode()->getConstantOperandVal(1);
  17183. // The extracted value is not extracted at the right position
  17184. if (ShiftAmt != i * ScalarTypeBitsize)
  17185. return SDValue();
  17186. }
  17187. }
  17188. // Only cast if the size is the same
  17189. if (Src.getValueType().getSizeInBits() != VT.getSizeInBits())
  17190. return SDValue();
  17191. return DAG.getBitcast(VT, Src);
  17192. }
  17193. SDValue DAGCombiner::createBuildVecShuffle(const SDLoc &DL, SDNode *N,
  17194. ArrayRef<int> VectorMask,
  17195. SDValue VecIn1, SDValue VecIn2,
  17196. unsigned LeftIdx, bool DidSplitVec) {
  17197. SDValue ZeroIdx = DAG.getVectorIdxConstant(0, DL);
  17198. EVT VT = N->getValueType(0);
  17199. EVT InVT1 = VecIn1.getValueType();
  17200. EVT InVT2 = VecIn2.getNode() ? VecIn2.getValueType() : InVT1;
  17201. unsigned NumElems = VT.getVectorNumElements();
  17202. unsigned ShuffleNumElems = NumElems;
  17203. // If we artificially split a vector in two already, then the offsets in the
  17204. // operands will all be based off of VecIn1, even those in VecIn2.
  17205. unsigned Vec2Offset = DidSplitVec ? 0 : InVT1.getVectorNumElements();
  17206. uint64_t VTSize = VT.getFixedSizeInBits();
  17207. uint64_t InVT1Size = InVT1.getFixedSizeInBits();
  17208. uint64_t InVT2Size = InVT2.getFixedSizeInBits();
  17209. assert(InVT2Size <= InVT1Size &&
  17210. "Inputs must be sorted to be in non-increasing vector size order.");
  17211. // We can't generate a shuffle node with mismatched input and output types.
  17212. // Try to make the types match the type of the output.
  17213. if (InVT1 != VT || InVT2 != VT) {
  17214. if ((VTSize % InVT1Size == 0) && InVT1 == InVT2) {
  17215. // If the output vector length is a multiple of both input lengths,
  17216. // we can concatenate them and pad the rest with undefs.
  17217. unsigned NumConcats = VTSize / InVT1Size;
  17218. assert(NumConcats >= 2 && "Concat needs at least two inputs!");
  17219. SmallVector<SDValue, 2> ConcatOps(NumConcats, DAG.getUNDEF(InVT1));
  17220. ConcatOps[0] = VecIn1;
  17221. ConcatOps[1] = VecIn2 ? VecIn2 : DAG.getUNDEF(InVT1);
  17222. VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
  17223. VecIn2 = SDValue();
  17224. } else if (InVT1Size == VTSize * 2) {
  17225. if (!TLI.isExtractSubvectorCheap(VT, InVT1, NumElems))
  17226. return SDValue();
  17227. if (!VecIn2.getNode()) {
  17228. // If we only have one input vector, and it's twice the size of the
  17229. // output, split it in two.
  17230. VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1,
  17231. DAG.getVectorIdxConstant(NumElems, DL));
  17232. VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, VecIn1, ZeroIdx);
  17233. // Since we now have shorter input vectors, adjust the offset of the
  17234. // second vector's start.
  17235. Vec2Offset = NumElems;
  17236. } else {
  17237. assert(InVT2Size <= InVT1Size &&
  17238. "Second input is not going to be larger than the first one.");
  17239. // VecIn1 is wider than the output, and we have another, possibly
  17240. // smaller input. Pad the smaller input with undefs, shuffle at the
  17241. // input vector width, and extract the output.
  17242. // The shuffle type is different than VT, so check legality again.
  17243. if (LegalOperations &&
  17244. !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, InVT1))
  17245. return SDValue();
  17246. // Legalizing INSERT_SUBVECTOR is tricky - you basically have to
  17247. // lower it back into a BUILD_VECTOR. So if the inserted type is
  17248. // illegal, don't even try.
  17249. if (InVT1 != InVT2) {
  17250. if (!TLI.isTypeLegal(InVT2))
  17251. return SDValue();
  17252. VecIn2 = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, InVT1,
  17253. DAG.getUNDEF(InVT1), VecIn2, ZeroIdx);
  17254. }
  17255. ShuffleNumElems = NumElems * 2;
  17256. }
  17257. } else if (InVT2Size * 2 == VTSize && InVT1Size == VTSize) {
  17258. SmallVector<SDValue, 2> ConcatOps(2, DAG.getUNDEF(InVT2));
  17259. ConcatOps[0] = VecIn2;
  17260. VecIn2 = DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
  17261. } else {
  17262. // TODO: Support cases where the length mismatch isn't exactly by a
  17263. // factor of 2.
  17264. // TODO: Move this check upwards, so that if we have bad type
  17265. // mismatches, we don't create any DAG nodes.
  17266. return SDValue();
  17267. }
  17268. }
  17269. // Initialize mask to undef.
  17270. SmallVector<int, 8> Mask(ShuffleNumElems, -1);
  17271. // Only need to run up to the number of elements actually used, not the
  17272. // total number of elements in the shuffle - if we are shuffling a wider
  17273. // vector, the high lanes should be set to undef.
  17274. for (unsigned i = 0; i != NumElems; ++i) {
  17275. if (VectorMask[i] <= 0)
  17276. continue;
  17277. unsigned ExtIndex = N->getOperand(i).getConstantOperandVal(1);
  17278. if (VectorMask[i] == (int)LeftIdx) {
  17279. Mask[i] = ExtIndex;
  17280. } else if (VectorMask[i] == (int)LeftIdx + 1) {
  17281. Mask[i] = Vec2Offset + ExtIndex;
  17282. }
  17283. }
  17284. // The type the input vectors may have changed above.
  17285. InVT1 = VecIn1.getValueType();
  17286. // If we already have a VecIn2, it should have the same type as VecIn1.
  17287. // If we don't, get an undef/zero vector of the appropriate type.
  17288. VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(InVT1);
  17289. assert(InVT1 == VecIn2.getValueType() && "Unexpected second input type.");
  17290. SDValue Shuffle = DAG.getVectorShuffle(InVT1, DL, VecIn1, VecIn2, Mask);
  17291. if (ShuffleNumElems > NumElems)
  17292. Shuffle = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, VT, Shuffle, ZeroIdx);
  17293. return Shuffle;
  17294. }
  17295. static SDValue reduceBuildVecToShuffleWithZero(SDNode *BV, SelectionDAG &DAG) {
  17296. assert(BV->getOpcode() == ISD::BUILD_VECTOR && "Expected build vector");
  17297. // First, determine where the build vector is not undef.
  17298. // TODO: We could extend this to handle zero elements as well as undefs.
  17299. int NumBVOps = BV->getNumOperands();
  17300. int ZextElt = -1;
  17301. for (int i = 0; i != NumBVOps; ++i) {
  17302. SDValue Op = BV->getOperand(i);
  17303. if (Op.isUndef())
  17304. continue;
  17305. if (ZextElt == -1)
  17306. ZextElt = i;
  17307. else
  17308. return SDValue();
  17309. }
  17310. // Bail out if there's no non-undef element.
  17311. if (ZextElt == -1)
  17312. return SDValue();
  17313. // The build vector contains some number of undef elements and exactly
  17314. // one other element. That other element must be a zero-extended scalar
  17315. // extracted from a vector at a constant index to turn this into a shuffle.
  17316. // Also, require that the build vector does not implicitly truncate/extend
  17317. // its elements.
  17318. // TODO: This could be enhanced to allow ANY_EXTEND as well as ZERO_EXTEND.
  17319. EVT VT = BV->getValueType(0);
  17320. SDValue Zext = BV->getOperand(ZextElt);
  17321. if (Zext.getOpcode() != ISD::ZERO_EXTEND || !Zext.hasOneUse() ||
  17322. Zext.getOperand(0).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  17323. !isa<ConstantSDNode>(Zext.getOperand(0).getOperand(1)) ||
  17324. Zext.getValueSizeInBits() != VT.getScalarSizeInBits())
  17325. return SDValue();
  17326. // The zero-extend must be a multiple of the source size, and we must be
  17327. // building a vector of the same size as the source of the extract element.
  17328. SDValue Extract = Zext.getOperand(0);
  17329. unsigned DestSize = Zext.getValueSizeInBits();
  17330. unsigned SrcSize = Extract.getValueSizeInBits();
  17331. if (DestSize % SrcSize != 0 ||
  17332. Extract.getOperand(0).getValueSizeInBits() != VT.getSizeInBits())
  17333. return SDValue();
  17334. // Create a shuffle mask that will combine the extracted element with zeros
  17335. // and undefs.
  17336. int ZextRatio = DestSize / SrcSize;
  17337. int NumMaskElts = NumBVOps * ZextRatio;
  17338. SmallVector<int, 32> ShufMask(NumMaskElts, -1);
  17339. for (int i = 0; i != NumMaskElts; ++i) {
  17340. if (i / ZextRatio == ZextElt) {
  17341. // The low bits of the (potentially translated) extracted element map to
  17342. // the source vector. The high bits map to zero. We will use a zero vector
  17343. // as the 2nd source operand of the shuffle, so use the 1st element of
  17344. // that vector (mask value is number-of-elements) for the high bits.
  17345. if (i % ZextRatio == 0)
  17346. ShufMask[i] = Extract.getConstantOperandVal(1);
  17347. else
  17348. ShufMask[i] = NumMaskElts;
  17349. }
  17350. // Undef elements of the build vector remain undef because we initialize
  17351. // the shuffle mask with -1.
  17352. }
  17353. // buildvec undef, ..., (zext (extractelt V, IndexC)), undef... -->
  17354. // bitcast (shuffle V, ZeroVec, VectorMask)
  17355. SDLoc DL(BV);
  17356. EVT VecVT = Extract.getOperand(0).getValueType();
  17357. SDValue ZeroVec = DAG.getConstant(0, DL, VecVT);
  17358. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  17359. SDValue Shuf = TLI.buildLegalVectorShuffle(VecVT, DL, Extract.getOperand(0),
  17360. ZeroVec, ShufMask, DAG);
  17361. if (!Shuf)
  17362. return SDValue();
  17363. return DAG.getBitcast(VT, Shuf);
  17364. }
  17365. // FIXME: promote to STLExtras.
  17366. template <typename R, typename T>
  17367. static auto getFirstIndexOf(R &&Range, const T &Val) {
  17368. auto I = find(Range, Val);
  17369. if (I == Range.end())
  17370. return static_cast<decltype(std::distance(Range.begin(), I))>(-1);
  17371. return std::distance(Range.begin(), I);
  17372. }
  17373. // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
  17374. // operations. If the types of the vectors we're extracting from allow it,
  17375. // turn this into a vector_shuffle node.
  17376. SDValue DAGCombiner::reduceBuildVecToShuffle(SDNode *N) {
  17377. SDLoc DL(N);
  17378. EVT VT = N->getValueType(0);
  17379. // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
  17380. if (!isTypeLegal(VT))
  17381. return SDValue();
  17382. if (SDValue V = reduceBuildVecToShuffleWithZero(N, DAG))
  17383. return V;
  17384. // May only combine to shuffle after legalize if shuffle is legal.
  17385. if (LegalOperations && !TLI.isOperationLegal(ISD::VECTOR_SHUFFLE, VT))
  17386. return SDValue();
  17387. bool UsesZeroVector = false;
  17388. unsigned NumElems = N->getNumOperands();
  17389. // Record, for each element of the newly built vector, which input vector
  17390. // that element comes from. -1 stands for undef, 0 for the zero vector,
  17391. // and positive values for the input vectors.
  17392. // VectorMask maps each element to its vector number, and VecIn maps vector
  17393. // numbers to their initial SDValues.
  17394. SmallVector<int, 8> VectorMask(NumElems, -1);
  17395. SmallVector<SDValue, 8> VecIn;
  17396. VecIn.push_back(SDValue());
  17397. for (unsigned i = 0; i != NumElems; ++i) {
  17398. SDValue Op = N->getOperand(i);
  17399. if (Op.isUndef())
  17400. continue;
  17401. // See if we can use a blend with a zero vector.
  17402. // TODO: Should we generalize this to a blend with an arbitrary constant
  17403. // vector?
  17404. if (isNullConstant(Op) || isNullFPConstant(Op)) {
  17405. UsesZeroVector = true;
  17406. VectorMask[i] = 0;
  17407. continue;
  17408. }
  17409. // Not an undef or zero. If the input is something other than an
  17410. // EXTRACT_VECTOR_ELT with an in-range constant index, bail out.
  17411. if (Op.getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  17412. !isa<ConstantSDNode>(Op.getOperand(1)))
  17413. return SDValue();
  17414. SDValue ExtractedFromVec = Op.getOperand(0);
  17415. if (ExtractedFromVec.getValueType().isScalableVector())
  17416. return SDValue();
  17417. const APInt &ExtractIdx = Op.getConstantOperandAPInt(1);
  17418. if (ExtractIdx.uge(ExtractedFromVec.getValueType().getVectorNumElements()))
  17419. return SDValue();
  17420. // All inputs must have the same element type as the output.
  17421. if (VT.getVectorElementType() !=
  17422. ExtractedFromVec.getValueType().getVectorElementType())
  17423. return SDValue();
  17424. // Have we seen this input vector before?
  17425. // The vectors are expected to be tiny (usually 1 or 2 elements), so using
  17426. // a map back from SDValues to numbers isn't worth it.
  17427. int Idx = getFirstIndexOf(VecIn, ExtractedFromVec);
  17428. if (Idx == -1) { // A new source vector?
  17429. Idx = VecIn.size();
  17430. VecIn.push_back(ExtractedFromVec);
  17431. }
  17432. VectorMask[i] = Idx;
  17433. }
  17434. // If we didn't find at least one input vector, bail out.
  17435. if (VecIn.size() < 2)
  17436. return SDValue();
  17437. // If all the Operands of BUILD_VECTOR extract from same
  17438. // vector, then split the vector efficiently based on the maximum
  17439. // vector access index and adjust the VectorMask and
  17440. // VecIn accordingly.
  17441. bool DidSplitVec = false;
  17442. if (VecIn.size() == 2) {
  17443. unsigned MaxIndex = 0;
  17444. unsigned NearestPow2 = 0;
  17445. SDValue Vec = VecIn.back();
  17446. EVT InVT = Vec.getValueType();
  17447. SmallVector<unsigned, 8> IndexVec(NumElems, 0);
  17448. for (unsigned i = 0; i < NumElems; i++) {
  17449. if (VectorMask[i] <= 0)
  17450. continue;
  17451. unsigned Index = N->getOperand(i).getConstantOperandVal(1);
  17452. IndexVec[i] = Index;
  17453. MaxIndex = std::max(MaxIndex, Index);
  17454. }
  17455. NearestPow2 = PowerOf2Ceil(MaxIndex);
  17456. if (InVT.isSimple() && NearestPow2 > 2 && MaxIndex < NearestPow2 &&
  17457. NumElems * 2 < NearestPow2) {
  17458. unsigned SplitSize = NearestPow2 / 2;
  17459. EVT SplitVT = EVT::getVectorVT(*DAG.getContext(),
  17460. InVT.getVectorElementType(), SplitSize);
  17461. if (TLI.isTypeLegal(SplitVT) &&
  17462. SplitSize + SplitVT.getVectorNumElements() <=
  17463. InVT.getVectorNumElements()) {
  17464. SDValue VecIn2 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
  17465. DAG.getVectorIdxConstant(SplitSize, DL));
  17466. SDValue VecIn1 = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, SplitVT, Vec,
  17467. DAG.getVectorIdxConstant(0, DL));
  17468. VecIn.pop_back();
  17469. VecIn.push_back(VecIn1);
  17470. VecIn.push_back(VecIn2);
  17471. DidSplitVec = true;
  17472. for (unsigned i = 0; i < NumElems; i++) {
  17473. if (VectorMask[i] <= 0)
  17474. continue;
  17475. VectorMask[i] = (IndexVec[i] < SplitSize) ? 1 : 2;
  17476. }
  17477. }
  17478. }
  17479. }
  17480. // Sort input vectors by decreasing vector element count,
  17481. // while preserving the relative order of equally-sized vectors.
  17482. // Note that we keep the first "implicit zero vector as-is.
  17483. SmallVector<SDValue, 8> SortedVecIn(VecIn);
  17484. llvm::stable_sort(MutableArrayRef<SDValue>(SortedVecIn).drop_front(),
  17485. [](const SDValue &a, const SDValue &b) {
  17486. return a.getValueType().getVectorNumElements() >
  17487. b.getValueType().getVectorNumElements();
  17488. });
  17489. // We now also need to rebuild the VectorMask, because it referenced element
  17490. // order in VecIn, and we just sorted them.
  17491. for (int &SourceVectorIndex : VectorMask) {
  17492. if (SourceVectorIndex <= 0)
  17493. continue;
  17494. unsigned Idx = getFirstIndexOf(SortedVecIn, VecIn[SourceVectorIndex]);
  17495. assert(Idx > 0 && Idx < SortedVecIn.size() &&
  17496. VecIn[SourceVectorIndex] == SortedVecIn[Idx] && "Remapping failure");
  17497. SourceVectorIndex = Idx;
  17498. }
  17499. VecIn = std::move(SortedVecIn);
  17500. // TODO: Should this fire if some of the input vectors has illegal type (like
  17501. // it does now), or should we let legalization run its course first?
  17502. // Shuffle phase:
  17503. // Take pairs of vectors, and shuffle them so that the result has elements
  17504. // from these vectors in the correct places.
  17505. // For example, given:
  17506. // t10: i32 = extract_vector_elt t1, Constant:i64<0>
  17507. // t11: i32 = extract_vector_elt t2, Constant:i64<0>
  17508. // t12: i32 = extract_vector_elt t3, Constant:i64<0>
  17509. // t13: i32 = extract_vector_elt t1, Constant:i64<1>
  17510. // t14: v4i32 = BUILD_VECTOR t10, t11, t12, t13
  17511. // We will generate:
  17512. // t20: v4i32 = vector_shuffle<0,4,u,1> t1, t2
  17513. // t21: v4i32 = vector_shuffle<u,u,0,u> t3, undef
  17514. SmallVector<SDValue, 4> Shuffles;
  17515. for (unsigned In = 0, Len = (VecIn.size() / 2); In < Len; ++In) {
  17516. unsigned LeftIdx = 2 * In + 1;
  17517. SDValue VecLeft = VecIn[LeftIdx];
  17518. SDValue VecRight =
  17519. (LeftIdx + 1) < VecIn.size() ? VecIn[LeftIdx + 1] : SDValue();
  17520. if (SDValue Shuffle = createBuildVecShuffle(DL, N, VectorMask, VecLeft,
  17521. VecRight, LeftIdx, DidSplitVec))
  17522. Shuffles.push_back(Shuffle);
  17523. else
  17524. return SDValue();
  17525. }
  17526. // If we need the zero vector as an "ingredient" in the blend tree, add it
  17527. // to the list of shuffles.
  17528. if (UsesZeroVector)
  17529. Shuffles.push_back(VT.isInteger() ? DAG.getConstant(0, DL, VT)
  17530. : DAG.getConstantFP(0.0, DL, VT));
  17531. // If we only have one shuffle, we're done.
  17532. if (Shuffles.size() == 1)
  17533. return Shuffles[0];
  17534. // Update the vector mask to point to the post-shuffle vectors.
  17535. for (int &Vec : VectorMask)
  17536. if (Vec == 0)
  17537. Vec = Shuffles.size() - 1;
  17538. else
  17539. Vec = (Vec - 1) / 2;
  17540. // More than one shuffle. Generate a binary tree of blends, e.g. if from
  17541. // the previous step we got the set of shuffles t10, t11, t12, t13, we will
  17542. // generate:
  17543. // t10: v8i32 = vector_shuffle<0,8,u,u,u,u,u,u> t1, t2
  17544. // t11: v8i32 = vector_shuffle<u,u,0,8,u,u,u,u> t3, t4
  17545. // t12: v8i32 = vector_shuffle<u,u,u,u,0,8,u,u> t5, t6
  17546. // t13: v8i32 = vector_shuffle<u,u,u,u,u,u,0,8> t7, t8
  17547. // t20: v8i32 = vector_shuffle<0,1,10,11,u,u,u,u> t10, t11
  17548. // t21: v8i32 = vector_shuffle<u,u,u,u,4,5,14,15> t12, t13
  17549. // t30: v8i32 = vector_shuffle<0,1,2,3,12,13,14,15> t20, t21
  17550. // Make sure the initial size of the shuffle list is even.
  17551. if (Shuffles.size() % 2)
  17552. Shuffles.push_back(DAG.getUNDEF(VT));
  17553. for (unsigned CurSize = Shuffles.size(); CurSize > 1; CurSize /= 2) {
  17554. if (CurSize % 2) {
  17555. Shuffles[CurSize] = DAG.getUNDEF(VT);
  17556. CurSize++;
  17557. }
  17558. for (unsigned In = 0, Len = CurSize / 2; In < Len; ++In) {
  17559. int Left = 2 * In;
  17560. int Right = 2 * In + 1;
  17561. SmallVector<int, 8> Mask(NumElems, -1);
  17562. for (unsigned i = 0; i != NumElems; ++i) {
  17563. if (VectorMask[i] == Left) {
  17564. Mask[i] = i;
  17565. VectorMask[i] = In;
  17566. } else if (VectorMask[i] == Right) {
  17567. Mask[i] = i + NumElems;
  17568. VectorMask[i] = In;
  17569. }
  17570. }
  17571. Shuffles[In] =
  17572. DAG.getVectorShuffle(VT, DL, Shuffles[Left], Shuffles[Right], Mask);
  17573. }
  17574. }
  17575. return Shuffles[0];
  17576. }
  17577. // Try to turn a build vector of zero extends of extract vector elts into a
  17578. // a vector zero extend and possibly an extract subvector.
  17579. // TODO: Support sign extend?
  17580. // TODO: Allow undef elements?
  17581. SDValue DAGCombiner::convertBuildVecZextToZext(SDNode *N) {
  17582. if (LegalOperations)
  17583. return SDValue();
  17584. EVT VT = N->getValueType(0);
  17585. bool FoundZeroExtend = false;
  17586. SDValue Op0 = N->getOperand(0);
  17587. auto checkElem = [&](SDValue Op) -> int64_t {
  17588. unsigned Opc = Op.getOpcode();
  17589. FoundZeroExtend |= (Opc == ISD::ZERO_EXTEND);
  17590. if ((Opc == ISD::ZERO_EXTEND || Opc == ISD::ANY_EXTEND) &&
  17591. Op.getOperand(0).getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  17592. Op0.getOperand(0).getOperand(0) == Op.getOperand(0).getOperand(0))
  17593. if (auto *C = dyn_cast<ConstantSDNode>(Op.getOperand(0).getOperand(1)))
  17594. return C->getZExtValue();
  17595. return -1;
  17596. };
  17597. // Make sure the first element matches
  17598. // (zext (extract_vector_elt X, C))
  17599. // Offset must be a constant multiple of the
  17600. // known-minimum vector length of the result type.
  17601. int64_t Offset = checkElem(Op0);
  17602. if (Offset < 0 || (Offset % VT.getVectorNumElements()) != 0)
  17603. return SDValue();
  17604. unsigned NumElems = N->getNumOperands();
  17605. SDValue In = Op0.getOperand(0).getOperand(0);
  17606. EVT InSVT = In.getValueType().getScalarType();
  17607. EVT InVT = EVT::getVectorVT(*DAG.getContext(), InSVT, NumElems);
  17608. // Don't create an illegal input type after type legalization.
  17609. if (LegalTypes && !TLI.isTypeLegal(InVT))
  17610. return SDValue();
  17611. // Ensure all the elements come from the same vector and are adjacent.
  17612. for (unsigned i = 1; i != NumElems; ++i) {
  17613. if ((Offset + i) != checkElem(N->getOperand(i)))
  17614. return SDValue();
  17615. }
  17616. SDLoc DL(N);
  17617. In = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, InVT, In,
  17618. Op0.getOperand(0).getOperand(1));
  17619. return DAG.getNode(FoundZeroExtend ? ISD::ZERO_EXTEND : ISD::ANY_EXTEND, DL,
  17620. VT, In);
  17621. }
  17622. SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
  17623. EVT VT = N->getValueType(0);
  17624. // A vector built entirely of undefs is undef.
  17625. if (ISD::allOperandsUndef(N))
  17626. return DAG.getUNDEF(VT);
  17627. // If this is a splat of a bitcast from another vector, change to a
  17628. // concat_vector.
  17629. // For example:
  17630. // (build_vector (i64 (bitcast (v2i32 X))), (i64 (bitcast (v2i32 X)))) ->
  17631. // (v2i64 (bitcast (concat_vectors (v2i32 X), (v2i32 X))))
  17632. //
  17633. // If X is a build_vector itself, the concat can become a larger build_vector.
  17634. // TODO: Maybe this is useful for non-splat too?
  17635. if (!LegalOperations) {
  17636. if (SDValue Splat = cast<BuildVectorSDNode>(N)->getSplatValue()) {
  17637. Splat = peekThroughBitcasts(Splat);
  17638. EVT SrcVT = Splat.getValueType();
  17639. if (SrcVT.isVector()) {
  17640. unsigned NumElts = N->getNumOperands() * SrcVT.getVectorNumElements();
  17641. EVT NewVT = EVT::getVectorVT(*DAG.getContext(),
  17642. SrcVT.getVectorElementType(), NumElts);
  17643. if (!LegalTypes || TLI.isTypeLegal(NewVT)) {
  17644. SmallVector<SDValue, 8> Ops(N->getNumOperands(), Splat);
  17645. SDValue Concat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N),
  17646. NewVT, Ops);
  17647. return DAG.getBitcast(VT, Concat);
  17648. }
  17649. }
  17650. }
  17651. }
  17652. // Check if we can express BUILD VECTOR via subvector extract.
  17653. if (!LegalTypes && (N->getNumOperands() > 1)) {
  17654. SDValue Op0 = N->getOperand(0);
  17655. auto checkElem = [&](SDValue Op) -> uint64_t {
  17656. if ((Op.getOpcode() == ISD::EXTRACT_VECTOR_ELT) &&
  17657. (Op0.getOperand(0) == Op.getOperand(0)))
  17658. if (auto CNode = dyn_cast<ConstantSDNode>(Op.getOperand(1)))
  17659. return CNode->getZExtValue();
  17660. return -1;
  17661. };
  17662. int Offset = checkElem(Op0);
  17663. for (unsigned i = 0; i < N->getNumOperands(); ++i) {
  17664. if (Offset + i != checkElem(N->getOperand(i))) {
  17665. Offset = -1;
  17666. break;
  17667. }
  17668. }
  17669. if ((Offset == 0) &&
  17670. (Op0.getOperand(0).getValueType() == N->getValueType(0)))
  17671. return Op0.getOperand(0);
  17672. if ((Offset != -1) &&
  17673. ((Offset % N->getValueType(0).getVectorNumElements()) ==
  17674. 0)) // IDX must be multiple of output size.
  17675. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), N->getValueType(0),
  17676. Op0.getOperand(0), Op0.getOperand(1));
  17677. }
  17678. if (SDValue V = convertBuildVecZextToZext(N))
  17679. return V;
  17680. if (SDValue V = reduceBuildVecExtToExtBuildVec(N))
  17681. return V;
  17682. if (SDValue V = reduceBuildVecTruncToBitCast(N))
  17683. return V;
  17684. if (SDValue V = reduceBuildVecToShuffle(N))
  17685. return V;
  17686. // A splat of a single element is a SPLAT_VECTOR if supported on the target.
  17687. // Do this late as some of the above may replace the splat.
  17688. if (TLI.getOperationAction(ISD::SPLAT_VECTOR, VT) != TargetLowering::Expand)
  17689. if (SDValue V = cast<BuildVectorSDNode>(N)->getSplatValue()) {
  17690. assert(!V.isUndef() && "Splat of undef should have been handled earlier");
  17691. return DAG.getNode(ISD::SPLAT_VECTOR, SDLoc(N), VT, V);
  17692. }
  17693. return SDValue();
  17694. }
  17695. static SDValue combineConcatVectorOfScalars(SDNode *N, SelectionDAG &DAG) {
  17696. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  17697. EVT OpVT = N->getOperand(0).getValueType();
  17698. // If the operands are legal vectors, leave them alone.
  17699. if (TLI.isTypeLegal(OpVT))
  17700. return SDValue();
  17701. SDLoc DL(N);
  17702. EVT VT = N->getValueType(0);
  17703. SmallVector<SDValue, 8> Ops;
  17704. EVT SVT = EVT::getIntegerVT(*DAG.getContext(), OpVT.getSizeInBits());
  17705. SDValue ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
  17706. // Keep track of what we encounter.
  17707. bool AnyInteger = false;
  17708. bool AnyFP = false;
  17709. for (const SDValue &Op : N->ops()) {
  17710. if (ISD::BITCAST == Op.getOpcode() &&
  17711. !Op.getOperand(0).getValueType().isVector())
  17712. Ops.push_back(Op.getOperand(0));
  17713. else if (ISD::UNDEF == Op.getOpcode())
  17714. Ops.push_back(ScalarUndef);
  17715. else
  17716. return SDValue();
  17717. // Note whether we encounter an integer or floating point scalar.
  17718. // If it's neither, bail out, it could be something weird like x86mmx.
  17719. EVT LastOpVT = Ops.back().getValueType();
  17720. if (LastOpVT.isFloatingPoint())
  17721. AnyFP = true;
  17722. else if (LastOpVT.isInteger())
  17723. AnyInteger = true;
  17724. else
  17725. return SDValue();
  17726. }
  17727. // If any of the operands is a floating point scalar bitcast to a vector,
  17728. // use floating point types throughout, and bitcast everything.
  17729. // Replace UNDEFs by another scalar UNDEF node, of the final desired type.
  17730. if (AnyFP) {
  17731. SVT = EVT::getFloatingPointVT(OpVT.getSizeInBits());
  17732. ScalarUndef = DAG.getNode(ISD::UNDEF, DL, SVT);
  17733. if (AnyInteger) {
  17734. for (SDValue &Op : Ops) {
  17735. if (Op.getValueType() == SVT)
  17736. continue;
  17737. if (Op.isUndef())
  17738. Op = ScalarUndef;
  17739. else
  17740. Op = DAG.getBitcast(SVT, Op);
  17741. }
  17742. }
  17743. }
  17744. EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SVT,
  17745. VT.getSizeInBits() / SVT.getSizeInBits());
  17746. return DAG.getBitcast(VT, DAG.getBuildVector(VecVT, DL, Ops));
  17747. }
  17748. // Attempt to merge nested concat_vectors/undefs.
  17749. // Fold concat_vectors(concat_vectors(x,y,z,w),u,u,concat_vectors(a,b,c,d))
  17750. // --> concat_vectors(x,y,z,w,u,u,u,u,u,u,u,u,a,b,c,d)
  17751. static SDValue combineConcatVectorOfConcatVectors(SDNode *N,
  17752. SelectionDAG &DAG) {
  17753. EVT VT = N->getValueType(0);
  17754. // Ensure we're concatenating UNDEF and CONCAT_VECTORS nodes of similar types.
  17755. EVT SubVT;
  17756. SDValue FirstConcat;
  17757. for (const SDValue &Op : N->ops()) {
  17758. if (Op.isUndef())
  17759. continue;
  17760. if (Op.getOpcode() != ISD::CONCAT_VECTORS)
  17761. return SDValue();
  17762. if (!FirstConcat) {
  17763. SubVT = Op.getOperand(0).getValueType();
  17764. if (!DAG.getTargetLoweringInfo().isTypeLegal(SubVT))
  17765. return SDValue();
  17766. FirstConcat = Op;
  17767. continue;
  17768. }
  17769. if (SubVT != Op.getOperand(0).getValueType())
  17770. return SDValue();
  17771. }
  17772. assert(FirstConcat && "Concat of all-undefs found");
  17773. SmallVector<SDValue> ConcatOps;
  17774. for (const SDValue &Op : N->ops()) {
  17775. if (Op.isUndef()) {
  17776. ConcatOps.append(FirstConcat->getNumOperands(), DAG.getUNDEF(SubVT));
  17777. continue;
  17778. }
  17779. ConcatOps.append(Op->op_begin(), Op->op_end());
  17780. }
  17781. return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, ConcatOps);
  17782. }
  17783. // Check to see if this is a CONCAT_VECTORS of a bunch of EXTRACT_SUBVECTOR
  17784. // operations. If so, and if the EXTRACT_SUBVECTOR vector inputs come from at
  17785. // most two distinct vectors the same size as the result, attempt to turn this
  17786. // into a legal shuffle.
  17787. static SDValue combineConcatVectorOfExtracts(SDNode *N, SelectionDAG &DAG) {
  17788. EVT VT = N->getValueType(0);
  17789. EVT OpVT = N->getOperand(0).getValueType();
  17790. // We currently can't generate an appropriate shuffle for a scalable vector.
  17791. if (VT.isScalableVector())
  17792. return SDValue();
  17793. int NumElts = VT.getVectorNumElements();
  17794. int NumOpElts = OpVT.getVectorNumElements();
  17795. SDValue SV0 = DAG.getUNDEF(VT), SV1 = DAG.getUNDEF(VT);
  17796. SmallVector<int, 8> Mask;
  17797. for (SDValue Op : N->ops()) {
  17798. Op = peekThroughBitcasts(Op);
  17799. // UNDEF nodes convert to UNDEF shuffle mask values.
  17800. if (Op.isUndef()) {
  17801. Mask.append((unsigned)NumOpElts, -1);
  17802. continue;
  17803. }
  17804. if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
  17805. return SDValue();
  17806. // What vector are we extracting the subvector from and at what index?
  17807. SDValue ExtVec = Op.getOperand(0);
  17808. int ExtIdx = Op.getConstantOperandVal(1);
  17809. // We want the EVT of the original extraction to correctly scale the
  17810. // extraction index.
  17811. EVT ExtVT = ExtVec.getValueType();
  17812. ExtVec = peekThroughBitcasts(ExtVec);
  17813. // UNDEF nodes convert to UNDEF shuffle mask values.
  17814. if (ExtVec.isUndef()) {
  17815. Mask.append((unsigned)NumOpElts, -1);
  17816. continue;
  17817. }
  17818. // Ensure that we are extracting a subvector from a vector the same
  17819. // size as the result.
  17820. if (ExtVT.getSizeInBits() != VT.getSizeInBits())
  17821. return SDValue();
  17822. // Scale the subvector index to account for any bitcast.
  17823. int NumExtElts = ExtVT.getVectorNumElements();
  17824. if (0 == (NumExtElts % NumElts))
  17825. ExtIdx /= (NumExtElts / NumElts);
  17826. else if (0 == (NumElts % NumExtElts))
  17827. ExtIdx *= (NumElts / NumExtElts);
  17828. else
  17829. return SDValue();
  17830. // At most we can reference 2 inputs in the final shuffle.
  17831. if (SV0.isUndef() || SV0 == ExtVec) {
  17832. SV0 = ExtVec;
  17833. for (int i = 0; i != NumOpElts; ++i)
  17834. Mask.push_back(i + ExtIdx);
  17835. } else if (SV1.isUndef() || SV1 == ExtVec) {
  17836. SV1 = ExtVec;
  17837. for (int i = 0; i != NumOpElts; ++i)
  17838. Mask.push_back(i + ExtIdx + NumElts);
  17839. } else {
  17840. return SDValue();
  17841. }
  17842. }
  17843. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  17844. return TLI.buildLegalVectorShuffle(VT, SDLoc(N), DAG.getBitcast(VT, SV0),
  17845. DAG.getBitcast(VT, SV1), Mask, DAG);
  17846. }
  17847. static SDValue combineConcatVectorOfCasts(SDNode *N, SelectionDAG &DAG) {
  17848. unsigned CastOpcode = N->getOperand(0).getOpcode();
  17849. switch (CastOpcode) {
  17850. case ISD::SINT_TO_FP:
  17851. case ISD::UINT_TO_FP:
  17852. case ISD::FP_TO_SINT:
  17853. case ISD::FP_TO_UINT:
  17854. // TODO: Allow more opcodes?
  17855. // case ISD::BITCAST:
  17856. // case ISD::TRUNCATE:
  17857. // case ISD::ZERO_EXTEND:
  17858. // case ISD::SIGN_EXTEND:
  17859. // case ISD::FP_EXTEND:
  17860. break;
  17861. default:
  17862. return SDValue();
  17863. }
  17864. EVT SrcVT = N->getOperand(0).getOperand(0).getValueType();
  17865. if (!SrcVT.isVector())
  17866. return SDValue();
  17867. // All operands of the concat must be the same kind of cast from the same
  17868. // source type.
  17869. SmallVector<SDValue, 4> SrcOps;
  17870. for (SDValue Op : N->ops()) {
  17871. if (Op.getOpcode() != CastOpcode || !Op.hasOneUse() ||
  17872. Op.getOperand(0).getValueType() != SrcVT)
  17873. return SDValue();
  17874. SrcOps.push_back(Op.getOperand(0));
  17875. }
  17876. // The wider cast must be supported by the target. This is unusual because
  17877. // the operation support type parameter depends on the opcode. In addition,
  17878. // check the other type in the cast to make sure this is really legal.
  17879. EVT VT = N->getValueType(0);
  17880. EVT SrcEltVT = SrcVT.getVectorElementType();
  17881. ElementCount NumElts = SrcVT.getVectorElementCount() * N->getNumOperands();
  17882. EVT ConcatSrcVT = EVT::getVectorVT(*DAG.getContext(), SrcEltVT, NumElts);
  17883. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  17884. switch (CastOpcode) {
  17885. case ISD::SINT_TO_FP:
  17886. case ISD::UINT_TO_FP:
  17887. if (!TLI.isOperationLegalOrCustom(CastOpcode, ConcatSrcVT) ||
  17888. !TLI.isTypeLegal(VT))
  17889. return SDValue();
  17890. break;
  17891. case ISD::FP_TO_SINT:
  17892. case ISD::FP_TO_UINT:
  17893. if (!TLI.isOperationLegalOrCustom(CastOpcode, VT) ||
  17894. !TLI.isTypeLegal(ConcatSrcVT))
  17895. return SDValue();
  17896. break;
  17897. default:
  17898. llvm_unreachable("Unexpected cast opcode");
  17899. }
  17900. // concat (cast X), (cast Y)... -> cast (concat X, Y...)
  17901. SDLoc DL(N);
  17902. SDValue NewConcat = DAG.getNode(ISD::CONCAT_VECTORS, DL, ConcatSrcVT, SrcOps);
  17903. return DAG.getNode(CastOpcode, DL, VT, NewConcat);
  17904. }
  17905. SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
  17906. // If we only have one input vector, we don't need to do any concatenation.
  17907. if (N->getNumOperands() == 1)
  17908. return N->getOperand(0);
  17909. // Check if all of the operands are undefs.
  17910. EVT VT = N->getValueType(0);
  17911. if (ISD::allOperandsUndef(N))
  17912. return DAG.getUNDEF(VT);
  17913. // Optimize concat_vectors where all but the first of the vectors are undef.
  17914. if (all_of(drop_begin(N->ops()),
  17915. [](const SDValue &Op) { return Op.isUndef(); })) {
  17916. SDValue In = N->getOperand(0);
  17917. assert(In.getValueType().isVector() && "Must concat vectors");
  17918. // If the input is a concat_vectors, just make a larger concat by padding
  17919. // with smaller undefs.
  17920. if (In.getOpcode() == ISD::CONCAT_VECTORS && In.hasOneUse()) {
  17921. unsigned NumOps = N->getNumOperands() * In.getNumOperands();
  17922. SmallVector<SDValue, 4> Ops(In->op_begin(), In->op_end());
  17923. Ops.resize(NumOps, DAG.getUNDEF(Ops[0].getValueType()));
  17924. return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
  17925. }
  17926. SDValue Scalar = peekThroughOneUseBitcasts(In);
  17927. // concat_vectors(scalar_to_vector(scalar), undef) ->
  17928. // scalar_to_vector(scalar)
  17929. if (!LegalOperations && Scalar.getOpcode() == ISD::SCALAR_TO_VECTOR &&
  17930. Scalar.hasOneUse()) {
  17931. EVT SVT = Scalar.getValueType().getVectorElementType();
  17932. if (SVT == Scalar.getOperand(0).getValueType())
  17933. Scalar = Scalar.getOperand(0);
  17934. }
  17935. // concat_vectors(scalar, undef) -> scalar_to_vector(scalar)
  17936. if (!Scalar.getValueType().isVector()) {
  17937. // If the bitcast type isn't legal, it might be a trunc of a legal type;
  17938. // look through the trunc so we can still do the transform:
  17939. // concat_vectors(trunc(scalar), undef) -> scalar_to_vector(scalar)
  17940. if (Scalar->getOpcode() == ISD::TRUNCATE &&
  17941. !TLI.isTypeLegal(Scalar.getValueType()) &&
  17942. TLI.isTypeLegal(Scalar->getOperand(0).getValueType()))
  17943. Scalar = Scalar->getOperand(0);
  17944. EVT SclTy = Scalar.getValueType();
  17945. if (!SclTy.isFloatingPoint() && !SclTy.isInteger())
  17946. return SDValue();
  17947. // Bail out if the vector size is not a multiple of the scalar size.
  17948. if (VT.getSizeInBits() % SclTy.getSizeInBits())
  17949. return SDValue();
  17950. unsigned VNTNumElms = VT.getSizeInBits() / SclTy.getSizeInBits();
  17951. if (VNTNumElms < 2)
  17952. return SDValue();
  17953. EVT NVT = EVT::getVectorVT(*DAG.getContext(), SclTy, VNTNumElms);
  17954. if (!TLI.isTypeLegal(NVT) || !TLI.isTypeLegal(Scalar.getValueType()))
  17955. return SDValue();
  17956. SDValue Res = DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), NVT, Scalar);
  17957. return DAG.getBitcast(VT, Res);
  17958. }
  17959. }
  17960. // Fold any combination of BUILD_VECTOR or UNDEF nodes into one BUILD_VECTOR.
  17961. // We have already tested above for an UNDEF only concatenation.
  17962. // fold (concat_vectors (BUILD_VECTOR A, B, ...), (BUILD_VECTOR C, D, ...))
  17963. // -> (BUILD_VECTOR A, B, ..., C, D, ...)
  17964. auto IsBuildVectorOrUndef = [](const SDValue &Op) {
  17965. return ISD::UNDEF == Op.getOpcode() || ISD::BUILD_VECTOR == Op.getOpcode();
  17966. };
  17967. if (llvm::all_of(N->ops(), IsBuildVectorOrUndef)) {
  17968. SmallVector<SDValue, 8> Opnds;
  17969. EVT SVT = VT.getScalarType();
  17970. EVT MinVT = SVT;
  17971. if (!SVT.isFloatingPoint()) {
  17972. // If BUILD_VECTOR are from built from integer, they may have different
  17973. // operand types. Get the smallest type and truncate all operands to it.
  17974. bool FoundMinVT = false;
  17975. for (const SDValue &Op : N->ops())
  17976. if (ISD::BUILD_VECTOR == Op.getOpcode()) {
  17977. EVT OpSVT = Op.getOperand(0).getValueType();
  17978. MinVT = (!FoundMinVT || OpSVT.bitsLE(MinVT)) ? OpSVT : MinVT;
  17979. FoundMinVT = true;
  17980. }
  17981. assert(FoundMinVT && "Concat vector type mismatch");
  17982. }
  17983. for (const SDValue &Op : N->ops()) {
  17984. EVT OpVT = Op.getValueType();
  17985. unsigned NumElts = OpVT.getVectorNumElements();
  17986. if (ISD::UNDEF == Op.getOpcode())
  17987. Opnds.append(NumElts, DAG.getUNDEF(MinVT));
  17988. if (ISD::BUILD_VECTOR == Op.getOpcode()) {
  17989. if (SVT.isFloatingPoint()) {
  17990. assert(SVT == OpVT.getScalarType() && "Concat vector type mismatch");
  17991. Opnds.append(Op->op_begin(), Op->op_begin() + NumElts);
  17992. } else {
  17993. for (unsigned i = 0; i != NumElts; ++i)
  17994. Opnds.push_back(
  17995. DAG.getNode(ISD::TRUNCATE, SDLoc(N), MinVT, Op.getOperand(i)));
  17996. }
  17997. }
  17998. }
  17999. assert(VT.getVectorNumElements() == Opnds.size() &&
  18000. "Concat vector type mismatch");
  18001. return DAG.getBuildVector(VT, SDLoc(N), Opnds);
  18002. }
  18003. // Fold CONCAT_VECTORS of only bitcast scalars (or undef) to BUILD_VECTOR.
  18004. // FIXME: Add support for concat_vectors(bitcast(vec0),bitcast(vec1),...).
  18005. if (SDValue V = combineConcatVectorOfScalars(N, DAG))
  18006. return V;
  18007. if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT)) {
  18008. // Fold CONCAT_VECTORS of CONCAT_VECTORS (or undef) to VECTOR_SHUFFLE.
  18009. if (SDValue V = combineConcatVectorOfConcatVectors(N, DAG))
  18010. return V;
  18011. // Fold CONCAT_VECTORS of EXTRACT_SUBVECTOR (or undef) to VECTOR_SHUFFLE.
  18012. if (SDValue V = combineConcatVectorOfExtracts(N, DAG))
  18013. return V;
  18014. }
  18015. if (SDValue V = combineConcatVectorOfCasts(N, DAG))
  18016. return V;
  18017. // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
  18018. // nodes often generate nop CONCAT_VECTOR nodes. Scan the CONCAT_VECTOR
  18019. // operands and look for a CONCAT operations that place the incoming vectors
  18020. // at the exact same location.
  18021. //
  18022. // For scalable vectors, EXTRACT_SUBVECTOR indexes are implicitly scaled.
  18023. SDValue SingleSource = SDValue();
  18024. unsigned PartNumElem =
  18025. N->getOperand(0).getValueType().getVectorMinNumElements();
  18026. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  18027. SDValue Op = N->getOperand(i);
  18028. if (Op.isUndef())
  18029. continue;
  18030. // Check if this is the identity extract:
  18031. if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
  18032. return SDValue();
  18033. // Find the single incoming vector for the extract_subvector.
  18034. if (SingleSource.getNode()) {
  18035. if (Op.getOperand(0) != SingleSource)
  18036. return SDValue();
  18037. } else {
  18038. SingleSource = Op.getOperand(0);
  18039. // Check the source type is the same as the type of the result.
  18040. // If not, this concat may extend the vector, so we can not
  18041. // optimize it away.
  18042. if (SingleSource.getValueType() != N->getValueType(0))
  18043. return SDValue();
  18044. }
  18045. // Check that we are reading from the identity index.
  18046. unsigned IdentityIndex = i * PartNumElem;
  18047. if (Op.getConstantOperandAPInt(1) != IdentityIndex)
  18048. return SDValue();
  18049. }
  18050. if (SingleSource.getNode())
  18051. return SingleSource;
  18052. return SDValue();
  18053. }
  18054. // Helper that peeks through INSERT_SUBVECTOR/CONCAT_VECTORS to find
  18055. // if the subvector can be sourced for free.
  18056. static SDValue getSubVectorSrc(SDValue V, SDValue Index, EVT SubVT) {
  18057. if (V.getOpcode() == ISD::INSERT_SUBVECTOR &&
  18058. V.getOperand(1).getValueType() == SubVT && V.getOperand(2) == Index) {
  18059. return V.getOperand(1);
  18060. }
  18061. auto *IndexC = dyn_cast<ConstantSDNode>(Index);
  18062. if (IndexC && V.getOpcode() == ISD::CONCAT_VECTORS &&
  18063. V.getOperand(0).getValueType() == SubVT &&
  18064. (IndexC->getZExtValue() % SubVT.getVectorMinNumElements()) == 0) {
  18065. uint64_t SubIdx = IndexC->getZExtValue() / SubVT.getVectorMinNumElements();
  18066. return V.getOperand(SubIdx);
  18067. }
  18068. return SDValue();
  18069. }
  18070. static SDValue narrowInsertExtractVectorBinOp(SDNode *Extract,
  18071. SelectionDAG &DAG,
  18072. bool LegalOperations) {
  18073. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  18074. SDValue BinOp = Extract->getOperand(0);
  18075. unsigned BinOpcode = BinOp.getOpcode();
  18076. if (!TLI.isBinOp(BinOpcode) || BinOp.getNode()->getNumValues() != 1)
  18077. return SDValue();
  18078. EVT VecVT = BinOp.getValueType();
  18079. SDValue Bop0 = BinOp.getOperand(0), Bop1 = BinOp.getOperand(1);
  18080. if (VecVT != Bop0.getValueType() || VecVT != Bop1.getValueType())
  18081. return SDValue();
  18082. SDValue Index = Extract->getOperand(1);
  18083. EVT SubVT = Extract->getValueType(0);
  18084. if (!TLI.isOperationLegalOrCustom(BinOpcode, SubVT, LegalOperations))
  18085. return SDValue();
  18086. SDValue Sub0 = getSubVectorSrc(Bop0, Index, SubVT);
  18087. SDValue Sub1 = getSubVectorSrc(Bop1, Index, SubVT);
  18088. // TODO: We could handle the case where only 1 operand is being inserted by
  18089. // creating an extract of the other operand, but that requires checking
  18090. // number of uses and/or costs.
  18091. if (!Sub0 || !Sub1)
  18092. return SDValue();
  18093. // We are inserting both operands of the wide binop only to extract back
  18094. // to the narrow vector size. Eliminate all of the insert/extract:
  18095. // ext (binop (ins ?, X, Index), (ins ?, Y, Index)), Index --> binop X, Y
  18096. return DAG.getNode(BinOpcode, SDLoc(Extract), SubVT, Sub0, Sub1,
  18097. BinOp->getFlags());
  18098. }
  18099. /// If we are extracting a subvector produced by a wide binary operator try
  18100. /// to use a narrow binary operator and/or avoid concatenation and extraction.
  18101. static SDValue narrowExtractedVectorBinOp(SDNode *Extract, SelectionDAG &DAG,
  18102. bool LegalOperations) {
  18103. // TODO: Refactor with the caller (visitEXTRACT_SUBVECTOR), so we can share
  18104. // some of these bailouts with other transforms.
  18105. if (SDValue V = narrowInsertExtractVectorBinOp(Extract, DAG, LegalOperations))
  18106. return V;
  18107. // The extract index must be a constant, so we can map it to a concat operand.
  18108. auto *ExtractIndexC = dyn_cast<ConstantSDNode>(Extract->getOperand(1));
  18109. if (!ExtractIndexC)
  18110. return SDValue();
  18111. // We are looking for an optionally bitcasted wide vector binary operator
  18112. // feeding an extract subvector.
  18113. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  18114. SDValue BinOp = peekThroughBitcasts(Extract->getOperand(0));
  18115. unsigned BOpcode = BinOp.getOpcode();
  18116. if (!TLI.isBinOp(BOpcode) || BinOp.getNode()->getNumValues() != 1)
  18117. return SDValue();
  18118. // Exclude the fake form of fneg (fsub -0.0, x) because that is likely to be
  18119. // reduced to the unary fneg when it is visited, and we probably want to deal
  18120. // with fneg in a target-specific way.
  18121. if (BOpcode == ISD::FSUB) {
  18122. auto *C = isConstOrConstSplatFP(BinOp.getOperand(0), /*AllowUndefs*/ true);
  18123. if (C && C->getValueAPF().isNegZero())
  18124. return SDValue();
  18125. }
  18126. // The binop must be a vector type, so we can extract some fraction of it.
  18127. EVT WideBVT = BinOp.getValueType();
  18128. // The optimisations below currently assume we are dealing with fixed length
  18129. // vectors. It is possible to add support for scalable vectors, but at the
  18130. // moment we've done no analysis to prove whether they are profitable or not.
  18131. if (!WideBVT.isFixedLengthVector())
  18132. return SDValue();
  18133. EVT VT = Extract->getValueType(0);
  18134. unsigned ExtractIndex = ExtractIndexC->getZExtValue();
  18135. assert(ExtractIndex % VT.getVectorNumElements() == 0 &&
  18136. "Extract index is not a multiple of the vector length.");
  18137. // Bail out if this is not a proper multiple width extraction.
  18138. unsigned WideWidth = WideBVT.getSizeInBits();
  18139. unsigned NarrowWidth = VT.getSizeInBits();
  18140. if (WideWidth % NarrowWidth != 0)
  18141. return SDValue();
  18142. // Bail out if we are extracting a fraction of a single operation. This can
  18143. // occur because we potentially looked through a bitcast of the binop.
  18144. unsigned NarrowingRatio = WideWidth / NarrowWidth;
  18145. unsigned WideNumElts = WideBVT.getVectorNumElements();
  18146. if (WideNumElts % NarrowingRatio != 0)
  18147. return SDValue();
  18148. // Bail out if the target does not support a narrower version of the binop.
  18149. EVT NarrowBVT = EVT::getVectorVT(*DAG.getContext(), WideBVT.getScalarType(),
  18150. WideNumElts / NarrowingRatio);
  18151. if (!TLI.isOperationLegalOrCustomOrPromote(BOpcode, NarrowBVT))
  18152. return SDValue();
  18153. // If extraction is cheap, we don't need to look at the binop operands
  18154. // for concat ops. The narrow binop alone makes this transform profitable.
  18155. // We can't just reuse the original extract index operand because we may have
  18156. // bitcasted.
  18157. unsigned ConcatOpNum = ExtractIndex / VT.getVectorNumElements();
  18158. unsigned ExtBOIdx = ConcatOpNum * NarrowBVT.getVectorNumElements();
  18159. if (TLI.isExtractSubvectorCheap(NarrowBVT, WideBVT, ExtBOIdx) &&
  18160. BinOp.hasOneUse() && Extract->getOperand(0)->hasOneUse()) {
  18161. // extract (binop B0, B1), N --> binop (extract B0, N), (extract B1, N)
  18162. SDLoc DL(Extract);
  18163. SDValue NewExtIndex = DAG.getVectorIdxConstant(ExtBOIdx, DL);
  18164. SDValue X = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
  18165. BinOp.getOperand(0), NewExtIndex);
  18166. SDValue Y = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
  18167. BinOp.getOperand(1), NewExtIndex);
  18168. SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y,
  18169. BinOp.getNode()->getFlags());
  18170. return DAG.getBitcast(VT, NarrowBinOp);
  18171. }
  18172. // Only handle the case where we are doubling and then halving. A larger ratio
  18173. // may require more than two narrow binops to replace the wide binop.
  18174. if (NarrowingRatio != 2)
  18175. return SDValue();
  18176. // TODO: The motivating case for this transform is an x86 AVX1 target. That
  18177. // target has temptingly almost legal versions of bitwise logic ops in 256-bit
  18178. // flavors, but no other 256-bit integer support. This could be extended to
  18179. // handle any binop, but that may require fixing/adding other folds to avoid
  18180. // codegen regressions.
  18181. if (BOpcode != ISD::AND && BOpcode != ISD::OR && BOpcode != ISD::XOR)
  18182. return SDValue();
  18183. // We need at least one concatenation operation of a binop operand to make
  18184. // this transform worthwhile. The concat must double the input vector sizes.
  18185. auto GetSubVector = [ConcatOpNum](SDValue V) -> SDValue {
  18186. if (V.getOpcode() == ISD::CONCAT_VECTORS && V.getNumOperands() == 2)
  18187. return V.getOperand(ConcatOpNum);
  18188. return SDValue();
  18189. };
  18190. SDValue SubVecL = GetSubVector(peekThroughBitcasts(BinOp.getOperand(0)));
  18191. SDValue SubVecR = GetSubVector(peekThroughBitcasts(BinOp.getOperand(1)));
  18192. if (SubVecL || SubVecR) {
  18193. // If a binop operand was not the result of a concat, we must extract a
  18194. // half-sized operand for our new narrow binop:
  18195. // extract (binop (concat X1, X2), (concat Y1, Y2)), N --> binop XN, YN
  18196. // extract (binop (concat X1, X2), Y), N --> binop XN, (extract Y, IndexC)
  18197. // extract (binop X, (concat Y1, Y2)), N --> binop (extract X, IndexC), YN
  18198. SDLoc DL(Extract);
  18199. SDValue IndexC = DAG.getVectorIdxConstant(ExtBOIdx, DL);
  18200. SDValue X = SubVecL ? DAG.getBitcast(NarrowBVT, SubVecL)
  18201. : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
  18202. BinOp.getOperand(0), IndexC);
  18203. SDValue Y = SubVecR ? DAG.getBitcast(NarrowBVT, SubVecR)
  18204. : DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowBVT,
  18205. BinOp.getOperand(1), IndexC);
  18206. SDValue NarrowBinOp = DAG.getNode(BOpcode, DL, NarrowBVT, X, Y);
  18207. return DAG.getBitcast(VT, NarrowBinOp);
  18208. }
  18209. return SDValue();
  18210. }
  18211. /// If we are extracting a subvector from a wide vector load, convert to a
  18212. /// narrow load to eliminate the extraction:
  18213. /// (extract_subvector (load wide vector)) --> (load narrow vector)
  18214. static SDValue narrowExtractedVectorLoad(SDNode *Extract, SelectionDAG &DAG) {
  18215. // TODO: Add support for big-endian. The offset calculation must be adjusted.
  18216. if (DAG.getDataLayout().isBigEndian())
  18217. return SDValue();
  18218. auto *Ld = dyn_cast<LoadSDNode>(Extract->getOperand(0));
  18219. if (!Ld || Ld->getExtensionType() || !Ld->isSimple())
  18220. return SDValue();
  18221. // Allow targets to opt-out.
  18222. EVT VT = Extract->getValueType(0);
  18223. // We can only create byte sized loads.
  18224. if (!VT.isByteSized())
  18225. return SDValue();
  18226. unsigned Index = Extract->getConstantOperandVal(1);
  18227. unsigned NumElts = VT.getVectorMinNumElements();
  18228. // The definition of EXTRACT_SUBVECTOR states that the index must be a
  18229. // multiple of the minimum number of elements in the result type.
  18230. assert(Index % NumElts == 0 && "The extract subvector index is not a "
  18231. "multiple of the result's element count");
  18232. // It's fine to use TypeSize here as we know the offset will not be negative.
  18233. TypeSize Offset = VT.getStoreSize() * (Index / NumElts);
  18234. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  18235. if (!TLI.shouldReduceLoadWidth(Ld, Ld->getExtensionType(), VT))
  18236. return SDValue();
  18237. // The narrow load will be offset from the base address of the old load if
  18238. // we are extracting from something besides index 0 (little-endian).
  18239. SDLoc DL(Extract);
  18240. // TODO: Use "BaseIndexOffset" to make this more effective.
  18241. SDValue NewAddr = DAG.getMemBasePlusOffset(Ld->getBasePtr(), Offset, DL);
  18242. uint64_t StoreSize = MemoryLocation::getSizeOrUnknown(VT.getStoreSize());
  18243. MachineFunction &MF = DAG.getMachineFunction();
  18244. MachineMemOperand *MMO;
  18245. if (Offset.isScalable()) {
  18246. MachinePointerInfo MPI =
  18247. MachinePointerInfo(Ld->getPointerInfo().getAddrSpace());
  18248. MMO = MF.getMachineMemOperand(Ld->getMemOperand(), MPI, StoreSize);
  18249. } else
  18250. MMO = MF.getMachineMemOperand(Ld->getMemOperand(), Offset.getFixedSize(),
  18251. StoreSize);
  18252. SDValue NewLd = DAG.getLoad(VT, DL, Ld->getChain(), NewAddr, MMO);
  18253. DAG.makeEquivalentMemoryOrdering(Ld, NewLd);
  18254. return NewLd;
  18255. }
  18256. /// Given EXTRACT_SUBVECTOR(VECTOR_SHUFFLE(Op0, Op1, Mask)),
  18257. /// try to produce VECTOR_SHUFFLE(EXTRACT_SUBVECTOR(Op?, ?),
  18258. /// EXTRACT_SUBVECTOR(Op?, ?),
  18259. /// Mask'))
  18260. /// iff it is legal and profitable to do so. Notably, the trimmed mask
  18261. /// (containing only the elements that are extracted)
  18262. /// must reference at most two subvectors.
  18263. static SDValue foldExtractSubvectorFromShuffleVector(SDNode *N,
  18264. SelectionDAG &DAG,
  18265. const TargetLowering &TLI,
  18266. bool LegalOperations) {
  18267. assert(N->getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  18268. "Must only be called on EXTRACT_SUBVECTOR's");
  18269. SDValue N0 = N->getOperand(0);
  18270. // Only deal with non-scalable vectors.
  18271. EVT NarrowVT = N->getValueType(0);
  18272. EVT WideVT = N0.getValueType();
  18273. if (!NarrowVT.isFixedLengthVector() || !WideVT.isFixedLengthVector())
  18274. return SDValue();
  18275. // The operand must be a shufflevector.
  18276. auto *WideShuffleVector = dyn_cast<ShuffleVectorSDNode>(N0);
  18277. if (!WideShuffleVector)
  18278. return SDValue();
  18279. // The old shuffleneeds to go away.
  18280. if (!WideShuffleVector->hasOneUse())
  18281. return SDValue();
  18282. // And the narrow shufflevector that we'll form must be legal.
  18283. if (LegalOperations &&
  18284. !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, NarrowVT))
  18285. return SDValue();
  18286. uint64_t FirstExtractedEltIdx = N->getConstantOperandVal(1);
  18287. int NumEltsExtracted = NarrowVT.getVectorNumElements();
  18288. assert((FirstExtractedEltIdx % NumEltsExtracted) == 0 &&
  18289. "Extract index is not a multiple of the output vector length.");
  18290. int WideNumElts = WideVT.getVectorNumElements();
  18291. SmallVector<int, 16> NewMask;
  18292. NewMask.reserve(NumEltsExtracted);
  18293. SmallSetVector<std::pair<SDValue /*Op*/, int /*SubvectorIndex*/>, 2>
  18294. DemandedSubvectors;
  18295. // Try to decode the wide mask into narrow mask from at most two subvectors.
  18296. for (int M : WideShuffleVector->getMask().slice(FirstExtractedEltIdx,
  18297. NumEltsExtracted)) {
  18298. assert((M >= -1) && (M < (2 * WideNumElts)) &&
  18299. "Out-of-bounds shuffle mask?");
  18300. if (M < 0) {
  18301. // Does not depend on operands, does not require adjustment.
  18302. NewMask.emplace_back(M);
  18303. continue;
  18304. }
  18305. // From which operand of the shuffle does this shuffle mask element pick?
  18306. int WideShufOpIdx = M / WideNumElts;
  18307. // Which element of that operand is picked?
  18308. int OpEltIdx = M % WideNumElts;
  18309. assert((OpEltIdx + WideShufOpIdx * WideNumElts) == M &&
  18310. "Shuffle mask vector decomposition failure.");
  18311. // And which NumEltsExtracted-sized subvector of that operand is that?
  18312. int OpSubvecIdx = OpEltIdx / NumEltsExtracted;
  18313. // And which element within that subvector of that operand is that?
  18314. int OpEltIdxInSubvec = OpEltIdx % NumEltsExtracted;
  18315. assert((OpEltIdxInSubvec + OpSubvecIdx * NumEltsExtracted) == OpEltIdx &&
  18316. "Shuffle mask subvector decomposition failure.");
  18317. assert((OpEltIdxInSubvec + OpSubvecIdx * NumEltsExtracted +
  18318. WideShufOpIdx * WideNumElts) == M &&
  18319. "Shuffle mask full decomposition failure.");
  18320. SDValue Op = WideShuffleVector->getOperand(WideShufOpIdx);
  18321. if (Op.isUndef()) {
  18322. // Picking from an undef operand. Let's adjust mask instead.
  18323. NewMask.emplace_back(-1);
  18324. continue;
  18325. }
  18326. // Profitability check: only deal with extractions from the first subvector.
  18327. if (OpSubvecIdx != 0)
  18328. return SDValue();
  18329. const std::pair<SDValue, int> DemandedSubvector =
  18330. std::make_pair(Op, OpSubvecIdx);
  18331. if (DemandedSubvectors.insert(DemandedSubvector)) {
  18332. if (DemandedSubvectors.size() > 2)
  18333. return SDValue(); // We can't handle more than two subvectors.
  18334. // How many elements into the WideVT does this subvector start?
  18335. int Index = NumEltsExtracted * OpSubvecIdx;
  18336. // Bail out if the extraction isn't going to be cheap.
  18337. if (!TLI.isExtractSubvectorCheap(NarrowVT, WideVT, Index))
  18338. return SDValue();
  18339. }
  18340. // Ok, but from which operand of the new shuffle will this element pick?
  18341. int NewOpIdx =
  18342. getFirstIndexOf(DemandedSubvectors.getArrayRef(), DemandedSubvector);
  18343. assert((NewOpIdx == 0 || NewOpIdx == 1) && "Unexpected operand index.");
  18344. int AdjM = OpEltIdxInSubvec + NewOpIdx * NumEltsExtracted;
  18345. NewMask.emplace_back(AdjM);
  18346. }
  18347. assert(NewMask.size() == (unsigned)NumEltsExtracted && "Produced bad mask.");
  18348. assert(DemandedSubvectors.size() <= 2 &&
  18349. "Should have ended up demanding at most two subvectors.");
  18350. // Did we discover that the shuffle does not actually depend on operands?
  18351. if (DemandedSubvectors.empty())
  18352. return DAG.getUNDEF(NarrowVT);
  18353. // We still perform the exact same EXTRACT_SUBVECTOR, just on different
  18354. // operand[s]/index[es], so there is no point in checking for it's legality.
  18355. // Do not turn a legal shuffle into an illegal one.
  18356. if (TLI.isShuffleMaskLegal(WideShuffleVector->getMask(), WideVT) &&
  18357. !TLI.isShuffleMaskLegal(NewMask, NarrowVT))
  18358. return SDValue();
  18359. SDLoc DL(N);
  18360. SmallVector<SDValue, 2> NewOps;
  18361. for (const std::pair<SDValue /*Op*/, int /*SubvectorIndex*/>
  18362. &DemandedSubvector : DemandedSubvectors) {
  18363. // How many elements into the WideVT does this subvector start?
  18364. int Index = NumEltsExtracted * DemandedSubvector.second;
  18365. SDValue IndexC = DAG.getVectorIdxConstant(Index, DL);
  18366. NewOps.emplace_back(DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NarrowVT,
  18367. DemandedSubvector.first, IndexC));
  18368. }
  18369. assert((NewOps.size() == 1 || NewOps.size() == 2) &&
  18370. "Should end up with either one or two ops");
  18371. // If we ended up with only one operand, pad with an undef.
  18372. if (NewOps.size() == 1)
  18373. NewOps.emplace_back(DAG.getUNDEF(NarrowVT));
  18374. return DAG.getVectorShuffle(NarrowVT, DL, NewOps[0], NewOps[1], NewMask);
  18375. }
  18376. SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode *N) {
  18377. EVT NVT = N->getValueType(0);
  18378. SDValue V = N->getOperand(0);
  18379. uint64_t ExtIdx = N->getConstantOperandVal(1);
  18380. // Extract from UNDEF is UNDEF.
  18381. if (V.isUndef())
  18382. return DAG.getUNDEF(NVT);
  18383. if (TLI.isOperationLegalOrCustomOrPromote(ISD::LOAD, NVT))
  18384. if (SDValue NarrowLoad = narrowExtractedVectorLoad(N, DAG))
  18385. return NarrowLoad;
  18386. // Combine an extract of an extract into a single extract_subvector.
  18387. // ext (ext X, C), 0 --> ext X, C
  18388. if (ExtIdx == 0 && V.getOpcode() == ISD::EXTRACT_SUBVECTOR && V.hasOneUse()) {
  18389. if (TLI.isExtractSubvectorCheap(NVT, V.getOperand(0).getValueType(),
  18390. V.getConstantOperandVal(1)) &&
  18391. TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NVT)) {
  18392. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT, V.getOperand(0),
  18393. V.getOperand(1));
  18394. }
  18395. }
  18396. // Try to move vector bitcast after extract_subv by scaling extraction index:
  18397. // extract_subv (bitcast X), Index --> bitcast (extract_subv X, Index')
  18398. if (V.getOpcode() == ISD::BITCAST &&
  18399. V.getOperand(0).getValueType().isVector() &&
  18400. (!LegalOperations || TLI.isOperationLegal(ISD::BITCAST, NVT))) {
  18401. SDValue SrcOp = V.getOperand(0);
  18402. EVT SrcVT = SrcOp.getValueType();
  18403. unsigned SrcNumElts = SrcVT.getVectorMinNumElements();
  18404. unsigned DestNumElts = V.getValueType().getVectorMinNumElements();
  18405. if ((SrcNumElts % DestNumElts) == 0) {
  18406. unsigned SrcDestRatio = SrcNumElts / DestNumElts;
  18407. ElementCount NewExtEC = NVT.getVectorElementCount() * SrcDestRatio;
  18408. EVT NewExtVT = EVT::getVectorVT(*DAG.getContext(), SrcVT.getScalarType(),
  18409. NewExtEC);
  18410. if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) {
  18411. SDLoc DL(N);
  18412. SDValue NewIndex = DAG.getVectorIdxConstant(ExtIdx * SrcDestRatio, DL);
  18413. SDValue NewExtract = DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT,
  18414. V.getOperand(0), NewIndex);
  18415. return DAG.getBitcast(NVT, NewExtract);
  18416. }
  18417. }
  18418. if ((DestNumElts % SrcNumElts) == 0) {
  18419. unsigned DestSrcRatio = DestNumElts / SrcNumElts;
  18420. if (NVT.getVectorElementCount().isKnownMultipleOf(DestSrcRatio)) {
  18421. ElementCount NewExtEC =
  18422. NVT.getVectorElementCount().divideCoefficientBy(DestSrcRatio);
  18423. EVT ScalarVT = SrcVT.getScalarType();
  18424. if ((ExtIdx % DestSrcRatio) == 0) {
  18425. SDLoc DL(N);
  18426. unsigned IndexValScaled = ExtIdx / DestSrcRatio;
  18427. EVT NewExtVT =
  18428. EVT::getVectorVT(*DAG.getContext(), ScalarVT, NewExtEC);
  18429. if (TLI.isOperationLegalOrCustom(ISD::EXTRACT_SUBVECTOR, NewExtVT)) {
  18430. SDValue NewIndex = DAG.getVectorIdxConstant(IndexValScaled, DL);
  18431. SDValue NewExtract =
  18432. DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NewExtVT,
  18433. V.getOperand(0), NewIndex);
  18434. return DAG.getBitcast(NVT, NewExtract);
  18435. }
  18436. if (NewExtEC.isScalar() &&
  18437. TLI.isOperationLegalOrCustom(ISD::EXTRACT_VECTOR_ELT, ScalarVT)) {
  18438. SDValue NewIndex = DAG.getVectorIdxConstant(IndexValScaled, DL);
  18439. SDValue NewExtract =
  18440. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, ScalarVT,
  18441. V.getOperand(0), NewIndex);
  18442. return DAG.getBitcast(NVT, NewExtract);
  18443. }
  18444. }
  18445. }
  18446. }
  18447. }
  18448. if (V.getOpcode() == ISD::CONCAT_VECTORS) {
  18449. unsigned ExtNumElts = NVT.getVectorMinNumElements();
  18450. EVT ConcatSrcVT = V.getOperand(0).getValueType();
  18451. assert(ConcatSrcVT.getVectorElementType() == NVT.getVectorElementType() &&
  18452. "Concat and extract subvector do not change element type");
  18453. assert((ExtIdx % ExtNumElts) == 0 &&
  18454. "Extract index is not a multiple of the input vector length.");
  18455. unsigned ConcatSrcNumElts = ConcatSrcVT.getVectorMinNumElements();
  18456. unsigned ConcatOpIdx = ExtIdx / ConcatSrcNumElts;
  18457. // If the concatenated source types match this extract, it's a direct
  18458. // simplification:
  18459. // extract_subvec (concat V1, V2, ...), i --> Vi
  18460. if (NVT.getVectorElementCount() == ConcatSrcVT.getVectorElementCount())
  18461. return V.getOperand(ConcatOpIdx);
  18462. // If the concatenated source vectors are a multiple length of this extract,
  18463. // then extract a fraction of one of those source vectors directly from a
  18464. // concat operand. Example:
  18465. // v2i8 extract_subvec (v16i8 concat (v8i8 X), (v8i8 Y), 14 -->
  18466. // v2i8 extract_subvec v8i8 Y, 6
  18467. if (NVT.isFixedLengthVector() && ConcatSrcVT.isFixedLengthVector() &&
  18468. ConcatSrcNumElts % ExtNumElts == 0) {
  18469. SDLoc DL(N);
  18470. unsigned NewExtIdx = ExtIdx - ConcatOpIdx * ConcatSrcNumElts;
  18471. assert(NewExtIdx + ExtNumElts <= ConcatSrcNumElts &&
  18472. "Trying to extract from >1 concat operand?");
  18473. assert(NewExtIdx % ExtNumElts == 0 &&
  18474. "Extract index is not a multiple of the input vector length.");
  18475. SDValue NewIndexC = DAG.getVectorIdxConstant(NewExtIdx, DL);
  18476. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, DL, NVT,
  18477. V.getOperand(ConcatOpIdx), NewIndexC);
  18478. }
  18479. }
  18480. if (SDValue V =
  18481. foldExtractSubvectorFromShuffleVector(N, DAG, TLI, LegalOperations))
  18482. return V;
  18483. V = peekThroughBitcasts(V);
  18484. // If the input is a build vector. Try to make a smaller build vector.
  18485. if (V.getOpcode() == ISD::BUILD_VECTOR) {
  18486. EVT InVT = V.getValueType();
  18487. unsigned ExtractSize = NVT.getSizeInBits();
  18488. unsigned EltSize = InVT.getScalarSizeInBits();
  18489. // Only do this if we won't split any elements.
  18490. if (ExtractSize % EltSize == 0) {
  18491. unsigned NumElems = ExtractSize / EltSize;
  18492. EVT EltVT = InVT.getVectorElementType();
  18493. EVT ExtractVT =
  18494. NumElems == 1 ? EltVT
  18495. : EVT::getVectorVT(*DAG.getContext(), EltVT, NumElems);
  18496. if ((Level < AfterLegalizeDAG ||
  18497. (NumElems == 1 ||
  18498. TLI.isOperationLegal(ISD::BUILD_VECTOR, ExtractVT))) &&
  18499. (!LegalTypes || TLI.isTypeLegal(ExtractVT))) {
  18500. unsigned IdxVal = (ExtIdx * NVT.getScalarSizeInBits()) / EltSize;
  18501. if (NumElems == 1) {
  18502. SDValue Src = V->getOperand(IdxVal);
  18503. if (EltVT != Src.getValueType())
  18504. Src = DAG.getNode(ISD::TRUNCATE, SDLoc(N), InVT, Src);
  18505. return DAG.getBitcast(NVT, Src);
  18506. }
  18507. // Extract the pieces from the original build_vector.
  18508. SDValue BuildVec = DAG.getBuildVector(ExtractVT, SDLoc(N),
  18509. V->ops().slice(IdxVal, NumElems));
  18510. return DAG.getBitcast(NVT, BuildVec);
  18511. }
  18512. }
  18513. }
  18514. if (V.getOpcode() == ISD::INSERT_SUBVECTOR) {
  18515. // Handle only simple case where vector being inserted and vector
  18516. // being extracted are of same size.
  18517. EVT SmallVT = V.getOperand(1).getValueType();
  18518. if (!NVT.bitsEq(SmallVT))
  18519. return SDValue();
  18520. // Combine:
  18521. // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
  18522. // Into:
  18523. // indices are equal or bit offsets are equal => V1
  18524. // otherwise => (extract_subvec V1, ExtIdx)
  18525. uint64_t InsIdx = V.getConstantOperandVal(2);
  18526. if (InsIdx * SmallVT.getScalarSizeInBits() ==
  18527. ExtIdx * NVT.getScalarSizeInBits()) {
  18528. if (LegalOperations && !TLI.isOperationLegal(ISD::BITCAST, NVT))
  18529. return SDValue();
  18530. return DAG.getBitcast(NVT, V.getOperand(1));
  18531. }
  18532. return DAG.getNode(
  18533. ISD::EXTRACT_SUBVECTOR, SDLoc(N), NVT,
  18534. DAG.getBitcast(N->getOperand(0).getValueType(), V.getOperand(0)),
  18535. N->getOperand(1));
  18536. }
  18537. if (SDValue NarrowBOp = narrowExtractedVectorBinOp(N, DAG, LegalOperations))
  18538. return NarrowBOp;
  18539. if (SimplifyDemandedVectorElts(SDValue(N, 0)))
  18540. return SDValue(N, 0);
  18541. return SDValue();
  18542. }
  18543. /// Try to convert a wide shuffle of concatenated vectors into 2 narrow shuffles
  18544. /// followed by concatenation. Narrow vector ops may have better performance
  18545. /// than wide ops, and this can unlock further narrowing of other vector ops.
  18546. /// Targets can invert this transform later if it is not profitable.
  18547. static SDValue foldShuffleOfConcatUndefs(ShuffleVectorSDNode *Shuf,
  18548. SelectionDAG &DAG) {
  18549. SDValue N0 = Shuf->getOperand(0), N1 = Shuf->getOperand(1);
  18550. if (N0.getOpcode() != ISD::CONCAT_VECTORS || N0.getNumOperands() != 2 ||
  18551. N1.getOpcode() != ISD::CONCAT_VECTORS || N1.getNumOperands() != 2 ||
  18552. !N0.getOperand(1).isUndef() || !N1.getOperand(1).isUndef())
  18553. return SDValue();
  18554. // Split the wide shuffle mask into halves. Any mask element that is accessing
  18555. // operand 1 is offset down to account for narrowing of the vectors.
  18556. ArrayRef<int> Mask = Shuf->getMask();
  18557. EVT VT = Shuf->getValueType(0);
  18558. unsigned NumElts = VT.getVectorNumElements();
  18559. unsigned HalfNumElts = NumElts / 2;
  18560. SmallVector<int, 16> Mask0(HalfNumElts, -1);
  18561. SmallVector<int, 16> Mask1(HalfNumElts, -1);
  18562. for (unsigned i = 0; i != NumElts; ++i) {
  18563. if (Mask[i] == -1)
  18564. continue;
  18565. // If we reference the upper (undef) subvector then the element is undef.
  18566. if ((Mask[i] % NumElts) >= HalfNumElts)
  18567. continue;
  18568. int M = Mask[i] < (int)NumElts ? Mask[i] : Mask[i] - (int)HalfNumElts;
  18569. if (i < HalfNumElts)
  18570. Mask0[i] = M;
  18571. else
  18572. Mask1[i - HalfNumElts] = M;
  18573. }
  18574. // Ask the target if this is a valid transform.
  18575. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  18576. EVT HalfVT = EVT::getVectorVT(*DAG.getContext(), VT.getScalarType(),
  18577. HalfNumElts);
  18578. if (!TLI.isShuffleMaskLegal(Mask0, HalfVT) ||
  18579. !TLI.isShuffleMaskLegal(Mask1, HalfVT))
  18580. return SDValue();
  18581. // shuffle (concat X, undef), (concat Y, undef), Mask -->
  18582. // concat (shuffle X, Y, Mask0), (shuffle X, Y, Mask1)
  18583. SDValue X = N0.getOperand(0), Y = N1.getOperand(0);
  18584. SDLoc DL(Shuf);
  18585. SDValue Shuf0 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask0);
  18586. SDValue Shuf1 = DAG.getVectorShuffle(HalfVT, DL, X, Y, Mask1);
  18587. return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, Shuf0, Shuf1);
  18588. }
  18589. // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat,
  18590. // or turn a shuffle of a single concat into simpler shuffle then concat.
  18591. static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
  18592. EVT VT = N->getValueType(0);
  18593. unsigned NumElts = VT.getVectorNumElements();
  18594. SDValue N0 = N->getOperand(0);
  18595. SDValue N1 = N->getOperand(1);
  18596. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
  18597. ArrayRef<int> Mask = SVN->getMask();
  18598. SmallVector<SDValue, 4> Ops;
  18599. EVT ConcatVT = N0.getOperand(0).getValueType();
  18600. unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
  18601. unsigned NumConcats = NumElts / NumElemsPerConcat;
  18602. auto IsUndefMaskElt = [](int i) { return i == -1; };
  18603. // Special case: shuffle(concat(A,B)) can be more efficiently represented
  18604. // as concat(shuffle(A,B),UNDEF) if the shuffle doesn't set any of the high
  18605. // half vector elements.
  18606. if (NumElemsPerConcat * 2 == NumElts && N1.isUndef() &&
  18607. llvm::all_of(Mask.slice(NumElemsPerConcat, NumElemsPerConcat),
  18608. IsUndefMaskElt)) {
  18609. N0 = DAG.getVectorShuffle(ConcatVT, SDLoc(N), N0.getOperand(0),
  18610. N0.getOperand(1),
  18611. Mask.slice(0, NumElemsPerConcat));
  18612. N1 = DAG.getUNDEF(ConcatVT);
  18613. return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, N0, N1);
  18614. }
  18615. // Look at every vector that's inserted. We're looking for exact
  18616. // subvector-sized copies from a concatenated vector
  18617. for (unsigned I = 0; I != NumConcats; ++I) {
  18618. unsigned Begin = I * NumElemsPerConcat;
  18619. ArrayRef<int> SubMask = Mask.slice(Begin, NumElemsPerConcat);
  18620. // Make sure we're dealing with a copy.
  18621. if (llvm::all_of(SubMask, IsUndefMaskElt)) {
  18622. Ops.push_back(DAG.getUNDEF(ConcatVT));
  18623. continue;
  18624. }
  18625. int OpIdx = -1;
  18626. for (int i = 0; i != (int)NumElemsPerConcat; ++i) {
  18627. if (IsUndefMaskElt(SubMask[i]))
  18628. continue;
  18629. if ((SubMask[i] % (int)NumElemsPerConcat) != i)
  18630. return SDValue();
  18631. int EltOpIdx = SubMask[i] / NumElemsPerConcat;
  18632. if (0 <= OpIdx && EltOpIdx != OpIdx)
  18633. return SDValue();
  18634. OpIdx = EltOpIdx;
  18635. }
  18636. assert(0 <= OpIdx && "Unknown concat_vectors op");
  18637. if (OpIdx < (int)N0.getNumOperands())
  18638. Ops.push_back(N0.getOperand(OpIdx));
  18639. else
  18640. Ops.push_back(N1.getOperand(OpIdx - N0.getNumOperands()));
  18641. }
  18642. return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
  18643. }
  18644. // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
  18645. // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
  18646. //
  18647. // SHUFFLE(BUILD_VECTOR(), BUILD_VECTOR()) -> BUILD_VECTOR() is always
  18648. // a simplification in some sense, but it isn't appropriate in general: some
  18649. // BUILD_VECTORs are substantially cheaper than others. The general case
  18650. // of a BUILD_VECTOR requires inserting each element individually (or
  18651. // performing the equivalent in a temporary stack variable). A BUILD_VECTOR of
  18652. // all constants is a single constant pool load. A BUILD_VECTOR where each
  18653. // element is identical is a splat. A BUILD_VECTOR where most of the operands
  18654. // are undef lowers to a small number of element insertions.
  18655. //
  18656. // To deal with this, we currently use a bunch of mostly arbitrary heuristics.
  18657. // We don't fold shuffles where one side is a non-zero constant, and we don't
  18658. // fold shuffles if the resulting (non-splat) BUILD_VECTOR would have duplicate
  18659. // non-constant operands. This seems to work out reasonably well in practice.
  18660. static SDValue combineShuffleOfScalars(ShuffleVectorSDNode *SVN,
  18661. SelectionDAG &DAG,
  18662. const TargetLowering &TLI) {
  18663. EVT VT = SVN->getValueType(0);
  18664. unsigned NumElts = VT.getVectorNumElements();
  18665. SDValue N0 = SVN->getOperand(0);
  18666. SDValue N1 = SVN->getOperand(1);
  18667. if (!N0->hasOneUse())
  18668. return SDValue();
  18669. // If only one of N1,N2 is constant, bail out if it is not ALL_ZEROS as
  18670. // discussed above.
  18671. if (!N1.isUndef()) {
  18672. if (!N1->hasOneUse())
  18673. return SDValue();
  18674. bool N0AnyConst = isAnyConstantBuildVector(N0);
  18675. bool N1AnyConst = isAnyConstantBuildVector(N1);
  18676. if (N0AnyConst && !N1AnyConst && !ISD::isBuildVectorAllZeros(N0.getNode()))
  18677. return SDValue();
  18678. if (!N0AnyConst && N1AnyConst && !ISD::isBuildVectorAllZeros(N1.getNode()))
  18679. return SDValue();
  18680. }
  18681. // If both inputs are splats of the same value then we can safely merge this
  18682. // to a single BUILD_VECTOR with undef elements based on the shuffle mask.
  18683. bool IsSplat = false;
  18684. auto *BV0 = dyn_cast<BuildVectorSDNode>(N0);
  18685. auto *BV1 = dyn_cast<BuildVectorSDNode>(N1);
  18686. if (BV0 && BV1)
  18687. if (SDValue Splat0 = BV0->getSplatValue())
  18688. IsSplat = (Splat0 == BV1->getSplatValue());
  18689. SmallVector<SDValue, 8> Ops;
  18690. SmallSet<SDValue, 16> DuplicateOps;
  18691. for (int M : SVN->getMask()) {
  18692. SDValue Op = DAG.getUNDEF(VT.getScalarType());
  18693. if (M >= 0) {
  18694. int Idx = M < (int)NumElts ? M : M - NumElts;
  18695. SDValue &S = (M < (int)NumElts ? N0 : N1);
  18696. if (S.getOpcode() == ISD::BUILD_VECTOR) {
  18697. Op = S.getOperand(Idx);
  18698. } else if (S.getOpcode() == ISD::SCALAR_TO_VECTOR) {
  18699. SDValue Op0 = S.getOperand(0);
  18700. Op = Idx == 0 ? Op0 : DAG.getUNDEF(Op0.getValueType());
  18701. } else {
  18702. // Operand can't be combined - bail out.
  18703. return SDValue();
  18704. }
  18705. }
  18706. // Don't duplicate a non-constant BUILD_VECTOR operand unless we're
  18707. // generating a splat; semantically, this is fine, but it's likely to
  18708. // generate low-quality code if the target can't reconstruct an appropriate
  18709. // shuffle.
  18710. if (!Op.isUndef() && !isIntOrFPConstant(Op))
  18711. if (!IsSplat && !DuplicateOps.insert(Op).second)
  18712. return SDValue();
  18713. Ops.push_back(Op);
  18714. }
  18715. // BUILD_VECTOR requires all inputs to be of the same type, find the
  18716. // maximum type and extend them all.
  18717. EVT SVT = VT.getScalarType();
  18718. if (SVT.isInteger())
  18719. for (SDValue &Op : Ops)
  18720. SVT = (SVT.bitsLT(Op.getValueType()) ? Op.getValueType() : SVT);
  18721. if (SVT != VT.getScalarType())
  18722. for (SDValue &Op : Ops)
  18723. Op = TLI.isZExtFree(Op.getValueType(), SVT)
  18724. ? DAG.getZExtOrTrunc(Op, SDLoc(SVN), SVT)
  18725. : DAG.getSExtOrTrunc(Op, SDLoc(SVN), SVT);
  18726. return DAG.getBuildVector(VT, SDLoc(SVN), Ops);
  18727. }
  18728. // Match shuffles that can be converted to any_vector_extend_in_reg.
  18729. // This is often generated during legalization.
  18730. // e.g. v4i32 <0,u,1,u> -> (v2i64 any_vector_extend_in_reg(v4i32 src))
  18731. // TODO Add support for ZERO_EXTEND_VECTOR_INREG when we have a test case.
  18732. static SDValue combineShuffleToVectorExtend(ShuffleVectorSDNode *SVN,
  18733. SelectionDAG &DAG,
  18734. const TargetLowering &TLI,
  18735. bool LegalOperations) {
  18736. EVT VT = SVN->getValueType(0);
  18737. bool IsBigEndian = DAG.getDataLayout().isBigEndian();
  18738. // TODO Add support for big-endian when we have a test case.
  18739. if (!VT.isInteger() || IsBigEndian)
  18740. return SDValue();
  18741. unsigned NumElts = VT.getVectorNumElements();
  18742. unsigned EltSizeInBits = VT.getScalarSizeInBits();
  18743. ArrayRef<int> Mask = SVN->getMask();
  18744. SDValue N0 = SVN->getOperand(0);
  18745. // shuffle<0,-1,1,-1> == (v2i64 anyextend_vector_inreg(v4i32))
  18746. auto isAnyExtend = [&Mask, &NumElts](unsigned Scale) {
  18747. for (unsigned i = 0; i != NumElts; ++i) {
  18748. if (Mask[i] < 0)
  18749. continue;
  18750. if ((i % Scale) == 0 && Mask[i] == (int)(i / Scale))
  18751. continue;
  18752. return false;
  18753. }
  18754. return true;
  18755. };
  18756. // Attempt to match a '*_extend_vector_inreg' shuffle, we just search for
  18757. // power-of-2 extensions as they are the most likely.
  18758. for (unsigned Scale = 2; Scale < NumElts; Scale *= 2) {
  18759. // Check for non power of 2 vector sizes
  18760. if (NumElts % Scale != 0)
  18761. continue;
  18762. if (!isAnyExtend(Scale))
  18763. continue;
  18764. EVT OutSVT = EVT::getIntegerVT(*DAG.getContext(), EltSizeInBits * Scale);
  18765. EVT OutVT = EVT::getVectorVT(*DAG.getContext(), OutSVT, NumElts / Scale);
  18766. // Never create an illegal type. Only create unsupported operations if we
  18767. // are pre-legalization.
  18768. if (TLI.isTypeLegal(OutVT))
  18769. if (!LegalOperations ||
  18770. TLI.isOperationLegalOrCustom(ISD::ANY_EXTEND_VECTOR_INREG, OutVT))
  18771. return DAG.getBitcast(VT,
  18772. DAG.getNode(ISD::ANY_EXTEND_VECTOR_INREG,
  18773. SDLoc(SVN), OutVT, N0));
  18774. }
  18775. return SDValue();
  18776. }
  18777. // Detect 'truncate_vector_inreg' style shuffles that pack the lower parts of
  18778. // each source element of a large type into the lowest elements of a smaller
  18779. // destination type. This is often generated during legalization.
  18780. // If the source node itself was a '*_extend_vector_inreg' node then we should
  18781. // then be able to remove it.
  18782. static SDValue combineTruncationShuffle(ShuffleVectorSDNode *SVN,
  18783. SelectionDAG &DAG) {
  18784. EVT VT = SVN->getValueType(0);
  18785. bool IsBigEndian = DAG.getDataLayout().isBigEndian();
  18786. // TODO Add support for big-endian when we have a test case.
  18787. if (!VT.isInteger() || IsBigEndian)
  18788. return SDValue();
  18789. SDValue N0 = peekThroughBitcasts(SVN->getOperand(0));
  18790. unsigned Opcode = N0.getOpcode();
  18791. if (Opcode != ISD::ANY_EXTEND_VECTOR_INREG &&
  18792. Opcode != ISD::SIGN_EXTEND_VECTOR_INREG &&
  18793. Opcode != ISD::ZERO_EXTEND_VECTOR_INREG)
  18794. return SDValue();
  18795. SDValue N00 = N0.getOperand(0);
  18796. ArrayRef<int> Mask = SVN->getMask();
  18797. unsigned NumElts = VT.getVectorNumElements();
  18798. unsigned EltSizeInBits = VT.getScalarSizeInBits();
  18799. unsigned ExtSrcSizeInBits = N00.getScalarValueSizeInBits();
  18800. unsigned ExtDstSizeInBits = N0.getScalarValueSizeInBits();
  18801. if (ExtDstSizeInBits % ExtSrcSizeInBits != 0)
  18802. return SDValue();
  18803. unsigned ExtScale = ExtDstSizeInBits / ExtSrcSizeInBits;
  18804. // (v4i32 truncate_vector_inreg(v2i64)) == shuffle<0,2-1,-1>
  18805. // (v8i16 truncate_vector_inreg(v4i32)) == shuffle<0,2,4,6,-1,-1,-1,-1>
  18806. // (v8i16 truncate_vector_inreg(v2i64)) == shuffle<0,4,-1,-1,-1,-1,-1,-1>
  18807. auto isTruncate = [&Mask, &NumElts](unsigned Scale) {
  18808. for (unsigned i = 0; i != NumElts; ++i) {
  18809. if (Mask[i] < 0)
  18810. continue;
  18811. if ((i * Scale) < NumElts && Mask[i] == (int)(i * Scale))
  18812. continue;
  18813. return false;
  18814. }
  18815. return true;
  18816. };
  18817. // At the moment we just handle the case where we've truncated back to the
  18818. // same size as before the extension.
  18819. // TODO: handle more extension/truncation cases as cases arise.
  18820. if (EltSizeInBits != ExtSrcSizeInBits)
  18821. return SDValue();
  18822. // We can remove *extend_vector_inreg only if the truncation happens at
  18823. // the same scale as the extension.
  18824. if (isTruncate(ExtScale))
  18825. return DAG.getBitcast(VT, N00);
  18826. return SDValue();
  18827. }
  18828. // Combine shuffles of splat-shuffles of the form:
  18829. // shuffle (shuffle V, undef, splat-mask), undef, M
  18830. // If splat-mask contains undef elements, we need to be careful about
  18831. // introducing undef's in the folded mask which are not the result of composing
  18832. // the masks of the shuffles.
  18833. static SDValue combineShuffleOfSplatVal(ShuffleVectorSDNode *Shuf,
  18834. SelectionDAG &DAG) {
  18835. if (!Shuf->getOperand(1).isUndef())
  18836. return SDValue();
  18837. auto *Splat = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0));
  18838. if (!Splat || !Splat->isSplat())
  18839. return SDValue();
  18840. ArrayRef<int> ShufMask = Shuf->getMask();
  18841. ArrayRef<int> SplatMask = Splat->getMask();
  18842. assert(ShufMask.size() == SplatMask.size() && "Mask length mismatch");
  18843. // Prefer simplifying to the splat-shuffle, if possible. This is legal if
  18844. // every undef mask element in the splat-shuffle has a corresponding undef
  18845. // element in the user-shuffle's mask or if the composition of mask elements
  18846. // would result in undef.
  18847. // Examples for (shuffle (shuffle v, undef, SplatMask), undef, UserMask):
  18848. // * UserMask=[0,2,u,u], SplatMask=[2,u,2,u] -> [2,2,u,u]
  18849. // In this case it is not legal to simplify to the splat-shuffle because we
  18850. // may be exposing the users of the shuffle an undef element at index 1
  18851. // which was not there before the combine.
  18852. // * UserMask=[0,u,2,u], SplatMask=[2,u,2,u] -> [2,u,2,u]
  18853. // In this case the composition of masks yields SplatMask, so it's ok to
  18854. // simplify to the splat-shuffle.
  18855. // * UserMask=[3,u,2,u], SplatMask=[2,u,2,u] -> [u,u,2,u]
  18856. // In this case the composed mask includes all undef elements of SplatMask
  18857. // and in addition sets element zero to undef. It is safe to simplify to
  18858. // the splat-shuffle.
  18859. auto CanSimplifyToExistingSplat = [](ArrayRef<int> UserMask,
  18860. ArrayRef<int> SplatMask) {
  18861. for (unsigned i = 0, e = UserMask.size(); i != e; ++i)
  18862. if (UserMask[i] != -1 && SplatMask[i] == -1 &&
  18863. SplatMask[UserMask[i]] != -1)
  18864. return false;
  18865. return true;
  18866. };
  18867. if (CanSimplifyToExistingSplat(ShufMask, SplatMask))
  18868. return Shuf->getOperand(0);
  18869. // Create a new shuffle with a mask that is composed of the two shuffles'
  18870. // masks.
  18871. SmallVector<int, 32> NewMask;
  18872. for (int Idx : ShufMask)
  18873. NewMask.push_back(Idx == -1 ? -1 : SplatMask[Idx]);
  18874. return DAG.getVectorShuffle(Splat->getValueType(0), SDLoc(Splat),
  18875. Splat->getOperand(0), Splat->getOperand(1),
  18876. NewMask);
  18877. }
  18878. /// Combine shuffle of shuffle of the form:
  18879. /// shuf (shuf X, undef, InnerMask), undef, OuterMask --> splat X
  18880. static SDValue formSplatFromShuffles(ShuffleVectorSDNode *OuterShuf,
  18881. SelectionDAG &DAG) {
  18882. if (!OuterShuf->getOperand(1).isUndef())
  18883. return SDValue();
  18884. auto *InnerShuf = dyn_cast<ShuffleVectorSDNode>(OuterShuf->getOperand(0));
  18885. if (!InnerShuf || !InnerShuf->getOperand(1).isUndef())
  18886. return SDValue();
  18887. ArrayRef<int> OuterMask = OuterShuf->getMask();
  18888. ArrayRef<int> InnerMask = InnerShuf->getMask();
  18889. unsigned NumElts = OuterMask.size();
  18890. assert(NumElts == InnerMask.size() && "Mask length mismatch");
  18891. SmallVector<int, 32> CombinedMask(NumElts, -1);
  18892. int SplatIndex = -1;
  18893. for (unsigned i = 0; i != NumElts; ++i) {
  18894. // Undef lanes remain undef.
  18895. int OuterMaskElt = OuterMask[i];
  18896. if (OuterMaskElt == -1)
  18897. continue;
  18898. // Peek through the shuffle masks to get the underlying source element.
  18899. int InnerMaskElt = InnerMask[OuterMaskElt];
  18900. if (InnerMaskElt == -1)
  18901. continue;
  18902. // Initialize the splatted element.
  18903. if (SplatIndex == -1)
  18904. SplatIndex = InnerMaskElt;
  18905. // Non-matching index - this is not a splat.
  18906. if (SplatIndex != InnerMaskElt)
  18907. return SDValue();
  18908. CombinedMask[i] = InnerMaskElt;
  18909. }
  18910. assert((all_of(CombinedMask, [](int M) { return M == -1; }) ||
  18911. getSplatIndex(CombinedMask) != -1) &&
  18912. "Expected a splat mask");
  18913. // TODO: The transform may be a win even if the mask is not legal.
  18914. EVT VT = OuterShuf->getValueType(0);
  18915. assert(VT == InnerShuf->getValueType(0) && "Expected matching shuffle types");
  18916. if (!DAG.getTargetLoweringInfo().isShuffleMaskLegal(CombinedMask, VT))
  18917. return SDValue();
  18918. return DAG.getVectorShuffle(VT, SDLoc(OuterShuf), InnerShuf->getOperand(0),
  18919. InnerShuf->getOperand(1), CombinedMask);
  18920. }
  18921. /// If the shuffle mask is taking exactly one element from the first vector
  18922. /// operand and passing through all other elements from the second vector
  18923. /// operand, return the index of the mask element that is choosing an element
  18924. /// from the first operand. Otherwise, return -1.
  18925. static int getShuffleMaskIndexOfOneElementFromOp0IntoOp1(ArrayRef<int> Mask) {
  18926. int MaskSize = Mask.size();
  18927. int EltFromOp0 = -1;
  18928. // TODO: This does not match if there are undef elements in the shuffle mask.
  18929. // Should we ignore undefs in the shuffle mask instead? The trade-off is
  18930. // removing an instruction (a shuffle), but losing the knowledge that some
  18931. // vector lanes are not needed.
  18932. for (int i = 0; i != MaskSize; ++i) {
  18933. if (Mask[i] >= 0 && Mask[i] < MaskSize) {
  18934. // We're looking for a shuffle of exactly one element from operand 0.
  18935. if (EltFromOp0 != -1)
  18936. return -1;
  18937. EltFromOp0 = i;
  18938. } else if (Mask[i] != i + MaskSize) {
  18939. // Nothing from operand 1 can change lanes.
  18940. return -1;
  18941. }
  18942. }
  18943. return EltFromOp0;
  18944. }
  18945. /// If a shuffle inserts exactly one element from a source vector operand into
  18946. /// another vector operand and we can access the specified element as a scalar,
  18947. /// then we can eliminate the shuffle.
  18948. static SDValue replaceShuffleOfInsert(ShuffleVectorSDNode *Shuf,
  18949. SelectionDAG &DAG) {
  18950. // First, check if we are taking one element of a vector and shuffling that
  18951. // element into another vector.
  18952. ArrayRef<int> Mask = Shuf->getMask();
  18953. SmallVector<int, 16> CommutedMask(Mask.begin(), Mask.end());
  18954. SDValue Op0 = Shuf->getOperand(0);
  18955. SDValue Op1 = Shuf->getOperand(1);
  18956. int ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(Mask);
  18957. if (ShufOp0Index == -1) {
  18958. // Commute mask and check again.
  18959. ShuffleVectorSDNode::commuteMask(CommutedMask);
  18960. ShufOp0Index = getShuffleMaskIndexOfOneElementFromOp0IntoOp1(CommutedMask);
  18961. if (ShufOp0Index == -1)
  18962. return SDValue();
  18963. // Commute operands to match the commuted shuffle mask.
  18964. std::swap(Op0, Op1);
  18965. Mask = CommutedMask;
  18966. }
  18967. // The shuffle inserts exactly one element from operand 0 into operand 1.
  18968. // Now see if we can access that element as a scalar via a real insert element
  18969. // instruction.
  18970. // TODO: We can try harder to locate the element as a scalar. Examples: it
  18971. // could be an operand of SCALAR_TO_VECTOR, BUILD_VECTOR, or a constant.
  18972. assert(Mask[ShufOp0Index] >= 0 && Mask[ShufOp0Index] < (int)Mask.size() &&
  18973. "Shuffle mask value must be from operand 0");
  18974. if (Op0.getOpcode() != ISD::INSERT_VECTOR_ELT)
  18975. return SDValue();
  18976. auto *InsIndexC = dyn_cast<ConstantSDNode>(Op0.getOperand(2));
  18977. if (!InsIndexC || InsIndexC->getSExtValue() != Mask[ShufOp0Index])
  18978. return SDValue();
  18979. // There's an existing insertelement with constant insertion index, so we
  18980. // don't need to check the legality/profitability of a replacement operation
  18981. // that differs at most in the constant value. The target should be able to
  18982. // lower any of those in a similar way. If not, legalization will expand this
  18983. // to a scalar-to-vector plus shuffle.
  18984. //
  18985. // Note that the shuffle may move the scalar from the position that the insert
  18986. // element used. Therefore, our new insert element occurs at the shuffle's
  18987. // mask index value, not the insert's index value.
  18988. // shuffle (insertelt v1, x, C), v2, mask --> insertelt v2, x, C'
  18989. SDValue NewInsIndex = DAG.getVectorIdxConstant(ShufOp0Index, SDLoc(Shuf));
  18990. return DAG.getNode(ISD::INSERT_VECTOR_ELT, SDLoc(Shuf), Op0.getValueType(),
  18991. Op1, Op0.getOperand(1), NewInsIndex);
  18992. }
  18993. /// If we have a unary shuffle of a shuffle, see if it can be folded away
  18994. /// completely. This has the potential to lose undef knowledge because the first
  18995. /// shuffle may not have an undef mask element where the second one does. So
  18996. /// only call this after doing simplifications based on demanded elements.
  18997. static SDValue simplifyShuffleOfShuffle(ShuffleVectorSDNode *Shuf) {
  18998. // shuf (shuf0 X, Y, Mask0), undef, Mask
  18999. auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(Shuf->getOperand(0));
  19000. if (!Shuf0 || !Shuf->getOperand(1).isUndef())
  19001. return SDValue();
  19002. ArrayRef<int> Mask = Shuf->getMask();
  19003. ArrayRef<int> Mask0 = Shuf0->getMask();
  19004. for (int i = 0, e = (int)Mask.size(); i != e; ++i) {
  19005. // Ignore undef elements.
  19006. if (Mask[i] == -1)
  19007. continue;
  19008. assert(Mask[i] >= 0 && Mask[i] < e && "Unexpected shuffle mask value");
  19009. // Is the element of the shuffle operand chosen by this shuffle the same as
  19010. // the element chosen by the shuffle operand itself?
  19011. if (Mask0[Mask[i]] != Mask0[i])
  19012. return SDValue();
  19013. }
  19014. // Every element of this shuffle is identical to the result of the previous
  19015. // shuffle, so we can replace this value.
  19016. return Shuf->getOperand(0);
  19017. }
  19018. SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
  19019. EVT VT = N->getValueType(0);
  19020. unsigned NumElts = VT.getVectorNumElements();
  19021. SDValue N0 = N->getOperand(0);
  19022. SDValue N1 = N->getOperand(1);
  19023. assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
  19024. // Canonicalize shuffle undef, undef -> undef
  19025. if (N0.isUndef() && N1.isUndef())
  19026. return DAG.getUNDEF(VT);
  19027. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
  19028. // Canonicalize shuffle v, v -> v, undef
  19029. if (N0 == N1)
  19030. return DAG.getVectorShuffle(VT, SDLoc(N), N0, DAG.getUNDEF(VT),
  19031. createUnaryMask(SVN->getMask(), NumElts));
  19032. // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
  19033. if (N0.isUndef())
  19034. return DAG.getCommutedVectorShuffle(*SVN);
  19035. // Remove references to rhs if it is undef
  19036. if (N1.isUndef()) {
  19037. bool Changed = false;
  19038. SmallVector<int, 8> NewMask;
  19039. for (unsigned i = 0; i != NumElts; ++i) {
  19040. int Idx = SVN->getMaskElt(i);
  19041. if (Idx >= (int)NumElts) {
  19042. Idx = -1;
  19043. Changed = true;
  19044. }
  19045. NewMask.push_back(Idx);
  19046. }
  19047. if (Changed)
  19048. return DAG.getVectorShuffle(VT, SDLoc(N), N0, N1, NewMask);
  19049. }
  19050. if (SDValue InsElt = replaceShuffleOfInsert(SVN, DAG))
  19051. return InsElt;
  19052. // A shuffle of a single vector that is a splatted value can always be folded.
  19053. if (SDValue V = combineShuffleOfSplatVal(SVN, DAG))
  19054. return V;
  19055. if (SDValue V = formSplatFromShuffles(SVN, DAG))
  19056. return V;
  19057. // If it is a splat, check if the argument vector is another splat or a
  19058. // build_vector.
  19059. if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
  19060. int SplatIndex = SVN->getSplatIndex();
  19061. if (N0.hasOneUse() && TLI.isExtractVecEltCheap(VT, SplatIndex) &&
  19062. TLI.isBinOp(N0.getOpcode()) && N0.getNode()->getNumValues() == 1) {
  19063. // splat (vector_bo L, R), Index -->
  19064. // splat (scalar_bo (extelt L, Index), (extelt R, Index))
  19065. SDValue L = N0.getOperand(0), R = N0.getOperand(1);
  19066. SDLoc DL(N);
  19067. EVT EltVT = VT.getScalarType();
  19068. SDValue Index = DAG.getVectorIdxConstant(SplatIndex, DL);
  19069. SDValue ExtL = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, L, Index);
  19070. SDValue ExtR = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, R, Index);
  19071. SDValue NewBO = DAG.getNode(N0.getOpcode(), DL, EltVT, ExtL, ExtR,
  19072. N0.getNode()->getFlags());
  19073. SDValue Insert = DAG.getNode(ISD::SCALAR_TO_VECTOR, DL, VT, NewBO);
  19074. SmallVector<int, 16> ZeroMask(VT.getVectorNumElements(), 0);
  19075. return DAG.getVectorShuffle(VT, DL, Insert, DAG.getUNDEF(VT), ZeroMask);
  19076. }
  19077. // If this is a bit convert that changes the element type of the vector but
  19078. // not the number of vector elements, look through it. Be careful not to
  19079. // look though conversions that change things like v4f32 to v2f64.
  19080. SDNode *V = N0.getNode();
  19081. if (V->getOpcode() == ISD::BITCAST) {
  19082. SDValue ConvInput = V->getOperand(0);
  19083. if (ConvInput.getValueType().isVector() &&
  19084. ConvInput.getValueType().getVectorNumElements() == NumElts)
  19085. V = ConvInput.getNode();
  19086. }
  19087. if (V->getOpcode() == ISD::BUILD_VECTOR) {
  19088. assert(V->getNumOperands() == NumElts &&
  19089. "BUILD_VECTOR has wrong number of operands");
  19090. SDValue Base;
  19091. bool AllSame = true;
  19092. for (unsigned i = 0; i != NumElts; ++i) {
  19093. if (!V->getOperand(i).isUndef()) {
  19094. Base = V->getOperand(i);
  19095. break;
  19096. }
  19097. }
  19098. // Splat of <u, u, u, u>, return <u, u, u, u>
  19099. if (!Base.getNode())
  19100. return N0;
  19101. for (unsigned i = 0; i != NumElts; ++i) {
  19102. if (V->getOperand(i) != Base) {
  19103. AllSame = false;
  19104. break;
  19105. }
  19106. }
  19107. // Splat of <x, x, x, x>, return <x, x, x, x>
  19108. if (AllSame)
  19109. return N0;
  19110. // Canonicalize any other splat as a build_vector.
  19111. SDValue Splatted = V->getOperand(SplatIndex);
  19112. SmallVector<SDValue, 8> Ops(NumElts, Splatted);
  19113. SDValue NewBV = DAG.getBuildVector(V->getValueType(0), SDLoc(N), Ops);
  19114. // We may have jumped through bitcasts, so the type of the
  19115. // BUILD_VECTOR may not match the type of the shuffle.
  19116. if (V->getValueType(0) != VT)
  19117. NewBV = DAG.getBitcast(VT, NewBV);
  19118. return NewBV;
  19119. }
  19120. }
  19121. // Simplify source operands based on shuffle mask.
  19122. if (SimplifyDemandedVectorElts(SDValue(N, 0)))
  19123. return SDValue(N, 0);
  19124. // This is intentionally placed after demanded elements simplification because
  19125. // it could eliminate knowledge of undef elements created by this shuffle.
  19126. if (SDValue ShufOp = simplifyShuffleOfShuffle(SVN))
  19127. return ShufOp;
  19128. // Match shuffles that can be converted to any_vector_extend_in_reg.
  19129. if (SDValue V = combineShuffleToVectorExtend(SVN, DAG, TLI, LegalOperations))
  19130. return V;
  19131. // Combine "truncate_vector_in_reg" style shuffles.
  19132. if (SDValue V = combineTruncationShuffle(SVN, DAG))
  19133. return V;
  19134. if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
  19135. Level < AfterLegalizeVectorOps &&
  19136. (N1.isUndef() ||
  19137. (N1.getOpcode() == ISD::CONCAT_VECTORS &&
  19138. N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
  19139. if (SDValue V = partitionShuffleOfConcats(N, DAG))
  19140. return V;
  19141. }
  19142. // A shuffle of a concat of the same narrow vector can be reduced to use
  19143. // only low-half elements of a concat with undef:
  19144. // shuf (concat X, X), undef, Mask --> shuf (concat X, undef), undef, Mask'
  19145. if (N0.getOpcode() == ISD::CONCAT_VECTORS && N1.isUndef() &&
  19146. N0.getNumOperands() == 2 &&
  19147. N0.getOperand(0) == N0.getOperand(1)) {
  19148. int HalfNumElts = (int)NumElts / 2;
  19149. SmallVector<int, 8> NewMask;
  19150. for (unsigned i = 0; i != NumElts; ++i) {
  19151. int Idx = SVN->getMaskElt(i);
  19152. if (Idx >= HalfNumElts) {
  19153. assert(Idx < (int)NumElts && "Shuffle mask chooses undef op");
  19154. Idx -= HalfNumElts;
  19155. }
  19156. NewMask.push_back(Idx);
  19157. }
  19158. if (TLI.isShuffleMaskLegal(NewMask, VT)) {
  19159. SDValue UndefVec = DAG.getUNDEF(N0.getOperand(0).getValueType());
  19160. SDValue NewCat = DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT,
  19161. N0.getOperand(0), UndefVec);
  19162. return DAG.getVectorShuffle(VT, SDLoc(N), NewCat, N1, NewMask);
  19163. }
  19164. }
  19165. // See if we can replace a shuffle with an insert_subvector.
  19166. // e.g. v2i32 into v8i32:
  19167. // shuffle(lhs,concat(rhs0,rhs1,rhs2,rhs3),0,1,2,3,10,11,6,7).
  19168. // --> insert_subvector(lhs,rhs1,4).
  19169. if (Level < AfterLegalizeVectorOps && TLI.isTypeLegal(VT) &&
  19170. TLI.isOperationLegalOrCustom(ISD::INSERT_SUBVECTOR, VT)) {
  19171. auto ShuffleToInsert = [&](SDValue LHS, SDValue RHS, ArrayRef<int> Mask) {
  19172. // Ensure RHS subvectors are legal.
  19173. assert(RHS.getOpcode() == ISD::CONCAT_VECTORS && "Can't find subvectors");
  19174. EVT SubVT = RHS.getOperand(0).getValueType();
  19175. int NumSubVecs = RHS.getNumOperands();
  19176. int NumSubElts = SubVT.getVectorNumElements();
  19177. assert((NumElts % NumSubElts) == 0 && "Subvector mismatch");
  19178. if (!TLI.isTypeLegal(SubVT))
  19179. return SDValue();
  19180. // Don't bother if we have an unary shuffle (matches undef + LHS elts).
  19181. if (all_of(Mask, [NumElts](int M) { return M < (int)NumElts; }))
  19182. return SDValue();
  19183. // Search [NumSubElts] spans for RHS sequence.
  19184. // TODO: Can we avoid nested loops to increase performance?
  19185. SmallVector<int> InsertionMask(NumElts);
  19186. for (int SubVec = 0; SubVec != NumSubVecs; ++SubVec) {
  19187. for (int SubIdx = 0; SubIdx != (int)NumElts; SubIdx += NumSubElts) {
  19188. // Reset mask to identity.
  19189. std::iota(InsertionMask.begin(), InsertionMask.end(), 0);
  19190. // Add subvector insertion.
  19191. std::iota(InsertionMask.begin() + SubIdx,
  19192. InsertionMask.begin() + SubIdx + NumSubElts,
  19193. NumElts + (SubVec * NumSubElts));
  19194. // See if the shuffle mask matches the reference insertion mask.
  19195. bool MatchingShuffle = true;
  19196. for (int i = 0; i != (int)NumElts; ++i) {
  19197. int ExpectIdx = InsertionMask[i];
  19198. int ActualIdx = Mask[i];
  19199. if (0 <= ActualIdx && ExpectIdx != ActualIdx) {
  19200. MatchingShuffle = false;
  19201. break;
  19202. }
  19203. }
  19204. if (MatchingShuffle)
  19205. return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, LHS,
  19206. RHS.getOperand(SubVec),
  19207. DAG.getVectorIdxConstant(SubIdx, SDLoc(N)));
  19208. }
  19209. }
  19210. return SDValue();
  19211. };
  19212. ArrayRef<int> Mask = SVN->getMask();
  19213. if (N1.getOpcode() == ISD::CONCAT_VECTORS)
  19214. if (SDValue InsertN1 = ShuffleToInsert(N0, N1, Mask))
  19215. return InsertN1;
  19216. if (N0.getOpcode() == ISD::CONCAT_VECTORS) {
  19217. SmallVector<int> CommuteMask(Mask.begin(), Mask.end());
  19218. ShuffleVectorSDNode::commuteMask(CommuteMask);
  19219. if (SDValue InsertN0 = ShuffleToInsert(N1, N0, CommuteMask))
  19220. return InsertN0;
  19221. }
  19222. }
  19223. // Attempt to combine a shuffle of 2 inputs of 'scalar sources' -
  19224. // BUILD_VECTOR or SCALAR_TO_VECTOR into a single BUILD_VECTOR.
  19225. if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT))
  19226. if (SDValue Res = combineShuffleOfScalars(SVN, DAG, TLI))
  19227. return Res;
  19228. // If this shuffle only has a single input that is a bitcasted shuffle,
  19229. // attempt to merge the 2 shuffles and suitably bitcast the inputs/output
  19230. // back to their original types.
  19231. if (N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
  19232. N1.isUndef() && Level < AfterLegalizeVectorOps &&
  19233. TLI.isTypeLegal(VT)) {
  19234. SDValue BC0 = peekThroughOneUseBitcasts(N0);
  19235. if (BC0.getOpcode() == ISD::VECTOR_SHUFFLE && BC0.hasOneUse()) {
  19236. EVT SVT = VT.getScalarType();
  19237. EVT InnerVT = BC0->getValueType(0);
  19238. EVT InnerSVT = InnerVT.getScalarType();
  19239. // Determine which shuffle works with the smaller scalar type.
  19240. EVT ScaleVT = SVT.bitsLT(InnerSVT) ? VT : InnerVT;
  19241. EVT ScaleSVT = ScaleVT.getScalarType();
  19242. if (TLI.isTypeLegal(ScaleVT) &&
  19243. 0 == (InnerSVT.getSizeInBits() % ScaleSVT.getSizeInBits()) &&
  19244. 0 == (SVT.getSizeInBits() % ScaleSVT.getSizeInBits())) {
  19245. int InnerScale = InnerSVT.getSizeInBits() / ScaleSVT.getSizeInBits();
  19246. int OuterScale = SVT.getSizeInBits() / ScaleSVT.getSizeInBits();
  19247. // Scale the shuffle masks to the smaller scalar type.
  19248. ShuffleVectorSDNode *InnerSVN = cast<ShuffleVectorSDNode>(BC0);
  19249. SmallVector<int, 8> InnerMask;
  19250. SmallVector<int, 8> OuterMask;
  19251. narrowShuffleMaskElts(InnerScale, InnerSVN->getMask(), InnerMask);
  19252. narrowShuffleMaskElts(OuterScale, SVN->getMask(), OuterMask);
  19253. // Merge the shuffle masks.
  19254. SmallVector<int, 8> NewMask;
  19255. for (int M : OuterMask)
  19256. NewMask.push_back(M < 0 ? -1 : InnerMask[M]);
  19257. // Test for shuffle mask legality over both commutations.
  19258. SDValue SV0 = BC0->getOperand(0);
  19259. SDValue SV1 = BC0->getOperand(1);
  19260. bool LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
  19261. if (!LegalMask) {
  19262. std::swap(SV0, SV1);
  19263. ShuffleVectorSDNode::commuteMask(NewMask);
  19264. LegalMask = TLI.isShuffleMaskLegal(NewMask, ScaleVT);
  19265. }
  19266. if (LegalMask) {
  19267. SV0 = DAG.getBitcast(ScaleVT, SV0);
  19268. SV1 = DAG.getBitcast(ScaleVT, SV1);
  19269. return DAG.getBitcast(
  19270. VT, DAG.getVectorShuffle(ScaleVT, SDLoc(N), SV0, SV1, NewMask));
  19271. }
  19272. }
  19273. }
  19274. }
  19275. // Compute the combined shuffle mask for a shuffle with SV0 as the first
  19276. // operand, and SV1 as the second operand.
  19277. // i.e. Merge SVN(OtherSVN, N1) -> shuffle(SV0, SV1, Mask) iff Commute = false
  19278. // Merge SVN(N1, OtherSVN) -> shuffle(SV0, SV1, Mask') iff Commute = true
  19279. auto MergeInnerShuffle =
  19280. [NumElts, &VT](bool Commute, ShuffleVectorSDNode *SVN,
  19281. ShuffleVectorSDNode *OtherSVN, SDValue N1,
  19282. const TargetLowering &TLI, SDValue &SV0, SDValue &SV1,
  19283. SmallVectorImpl<int> &Mask) -> bool {
  19284. // Don't try to fold splats; they're likely to simplify somehow, or they
  19285. // might be free.
  19286. if (OtherSVN->isSplat())
  19287. return false;
  19288. SV0 = SV1 = SDValue();
  19289. Mask.clear();
  19290. for (unsigned i = 0; i != NumElts; ++i) {
  19291. int Idx = SVN->getMaskElt(i);
  19292. if (Idx < 0) {
  19293. // Propagate Undef.
  19294. Mask.push_back(Idx);
  19295. continue;
  19296. }
  19297. if (Commute)
  19298. Idx = (Idx < (int)NumElts) ? (Idx + NumElts) : (Idx - NumElts);
  19299. SDValue CurrentVec;
  19300. if (Idx < (int)NumElts) {
  19301. // This shuffle index refers to the inner shuffle N0. Lookup the inner
  19302. // shuffle mask to identify which vector is actually referenced.
  19303. Idx = OtherSVN->getMaskElt(Idx);
  19304. if (Idx < 0) {
  19305. // Propagate Undef.
  19306. Mask.push_back(Idx);
  19307. continue;
  19308. }
  19309. CurrentVec = (Idx < (int)NumElts) ? OtherSVN->getOperand(0)
  19310. : OtherSVN->getOperand(1);
  19311. } else {
  19312. // This shuffle index references an element within N1.
  19313. CurrentVec = N1;
  19314. }
  19315. // Simple case where 'CurrentVec' is UNDEF.
  19316. if (CurrentVec.isUndef()) {
  19317. Mask.push_back(-1);
  19318. continue;
  19319. }
  19320. // Canonicalize the shuffle index. We don't know yet if CurrentVec
  19321. // will be the first or second operand of the combined shuffle.
  19322. Idx = Idx % NumElts;
  19323. if (!SV0.getNode() || SV0 == CurrentVec) {
  19324. // Ok. CurrentVec is the left hand side.
  19325. // Update the mask accordingly.
  19326. SV0 = CurrentVec;
  19327. Mask.push_back(Idx);
  19328. continue;
  19329. }
  19330. if (!SV1.getNode() || SV1 == CurrentVec) {
  19331. // Ok. CurrentVec is the right hand side.
  19332. // Update the mask accordingly.
  19333. SV1 = CurrentVec;
  19334. Mask.push_back(Idx + NumElts);
  19335. continue;
  19336. }
  19337. // Last chance - see if the vector is another shuffle and if it
  19338. // uses one of the existing candidate shuffle ops.
  19339. if (auto *CurrentSVN = dyn_cast<ShuffleVectorSDNode>(CurrentVec)) {
  19340. int InnerIdx = CurrentSVN->getMaskElt(Idx);
  19341. if (InnerIdx < 0) {
  19342. Mask.push_back(-1);
  19343. continue;
  19344. }
  19345. SDValue InnerVec = (InnerIdx < (int)NumElts)
  19346. ? CurrentSVN->getOperand(0)
  19347. : CurrentSVN->getOperand(1);
  19348. if (InnerVec.isUndef()) {
  19349. Mask.push_back(-1);
  19350. continue;
  19351. }
  19352. InnerIdx %= NumElts;
  19353. if (InnerVec == SV0) {
  19354. Mask.push_back(InnerIdx);
  19355. continue;
  19356. }
  19357. if (InnerVec == SV1) {
  19358. Mask.push_back(InnerIdx + NumElts);
  19359. continue;
  19360. }
  19361. }
  19362. // Bail out if we cannot convert the shuffle pair into a single shuffle.
  19363. return false;
  19364. }
  19365. if (llvm::all_of(Mask, [](int M) { return M < 0; }))
  19366. return true;
  19367. // Avoid introducing shuffles with illegal mask.
  19368. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
  19369. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
  19370. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
  19371. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, A, M2)
  19372. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, A, M2)
  19373. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(C, B, M2)
  19374. if (TLI.isShuffleMaskLegal(Mask, VT))
  19375. return true;
  19376. std::swap(SV0, SV1);
  19377. ShuffleVectorSDNode::commuteMask(Mask);
  19378. return TLI.isShuffleMaskLegal(Mask, VT);
  19379. };
  19380. if (Level < AfterLegalizeDAG && TLI.isTypeLegal(VT)) {
  19381. // Canonicalize shuffles according to rules:
  19382. // shuffle(A, shuffle(A, B)) -> shuffle(shuffle(A,B), A)
  19383. // shuffle(B, shuffle(A, B)) -> shuffle(shuffle(A,B), B)
  19384. // shuffle(B, shuffle(A, Undef)) -> shuffle(shuffle(A, Undef), B)
  19385. if (N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
  19386. N0.getOpcode() != ISD::VECTOR_SHUFFLE) {
  19387. // The incoming shuffle must be of the same type as the result of the
  19388. // current shuffle.
  19389. assert(N1->getOperand(0).getValueType() == VT &&
  19390. "Shuffle types don't match");
  19391. SDValue SV0 = N1->getOperand(0);
  19392. SDValue SV1 = N1->getOperand(1);
  19393. bool HasSameOp0 = N0 == SV0;
  19394. bool IsSV1Undef = SV1.isUndef();
  19395. if (HasSameOp0 || IsSV1Undef || N0 == SV1)
  19396. // Commute the operands of this shuffle so merging below will trigger.
  19397. return DAG.getCommutedVectorShuffle(*SVN);
  19398. }
  19399. // Canonicalize splat shuffles to the RHS to improve merging below.
  19400. // shuffle(splat(A,u), shuffle(C,D)) -> shuffle'(shuffle(C,D), splat(A,u))
  19401. if (N0.getOpcode() == ISD::VECTOR_SHUFFLE &&
  19402. N1.getOpcode() == ISD::VECTOR_SHUFFLE &&
  19403. cast<ShuffleVectorSDNode>(N0)->isSplat() &&
  19404. !cast<ShuffleVectorSDNode>(N1)->isSplat()) {
  19405. return DAG.getCommutedVectorShuffle(*SVN);
  19406. }
  19407. // Try to fold according to rules:
  19408. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, B, M2)
  19409. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(A, C, M2)
  19410. // shuffle(shuffle(A, B, M0), C, M1) -> shuffle(B, C, M2)
  19411. // Don't try to fold shuffles with illegal type.
  19412. // Only fold if this shuffle is the only user of the other shuffle.
  19413. // Try matching shuffle(C,shuffle(A,B)) commutted patterns as well.
  19414. for (int i = 0; i != 2; ++i) {
  19415. if (N->getOperand(i).getOpcode() == ISD::VECTOR_SHUFFLE &&
  19416. N->isOnlyUserOf(N->getOperand(i).getNode())) {
  19417. // The incoming shuffle must be of the same type as the result of the
  19418. // current shuffle.
  19419. auto *OtherSV = cast<ShuffleVectorSDNode>(N->getOperand(i));
  19420. assert(OtherSV->getOperand(0).getValueType() == VT &&
  19421. "Shuffle types don't match");
  19422. SDValue SV0, SV1;
  19423. SmallVector<int, 4> Mask;
  19424. if (MergeInnerShuffle(i != 0, SVN, OtherSV, N->getOperand(1 - i), TLI,
  19425. SV0, SV1, Mask)) {
  19426. // Check if all indices in Mask are Undef. In case, propagate Undef.
  19427. if (llvm::all_of(Mask, [](int M) { return M < 0; }))
  19428. return DAG.getUNDEF(VT);
  19429. return DAG.getVectorShuffle(VT, SDLoc(N),
  19430. SV0 ? SV0 : DAG.getUNDEF(VT),
  19431. SV1 ? SV1 : DAG.getUNDEF(VT), Mask);
  19432. }
  19433. }
  19434. }
  19435. // Merge shuffles through binops if we are able to merge it with at least
  19436. // one other shuffles.
  19437. // shuffle(bop(shuffle(x,y),shuffle(z,w)),undef)
  19438. // shuffle(bop(shuffle(x,y),shuffle(z,w)),bop(shuffle(a,b),shuffle(c,d)))
  19439. unsigned SrcOpcode = N0.getOpcode();
  19440. if (TLI.isBinOp(SrcOpcode) && N->isOnlyUserOf(N0.getNode()) &&
  19441. (N1.isUndef() ||
  19442. (SrcOpcode == N1.getOpcode() && N->isOnlyUserOf(N1.getNode())))) {
  19443. // Get binop source ops, or just pass on the undef.
  19444. SDValue Op00 = N0.getOperand(0);
  19445. SDValue Op01 = N0.getOperand(1);
  19446. SDValue Op10 = N1.isUndef() ? N1 : N1.getOperand(0);
  19447. SDValue Op11 = N1.isUndef() ? N1 : N1.getOperand(1);
  19448. // TODO: We might be able to relax the VT check but we don't currently
  19449. // have any isBinOp() that has different result/ops VTs so play safe until
  19450. // we have test coverage.
  19451. if (Op00.getValueType() == VT && Op10.getValueType() == VT &&
  19452. Op01.getValueType() == VT && Op11.getValueType() == VT &&
  19453. (Op00.getOpcode() == ISD::VECTOR_SHUFFLE ||
  19454. Op10.getOpcode() == ISD::VECTOR_SHUFFLE ||
  19455. Op01.getOpcode() == ISD::VECTOR_SHUFFLE ||
  19456. Op11.getOpcode() == ISD::VECTOR_SHUFFLE)) {
  19457. auto CanMergeInnerShuffle = [&](SDValue &SV0, SDValue &SV1,
  19458. SmallVectorImpl<int> &Mask, bool LeftOp,
  19459. bool Commute) {
  19460. SDValue InnerN = Commute ? N1 : N0;
  19461. SDValue Op0 = LeftOp ? Op00 : Op01;
  19462. SDValue Op1 = LeftOp ? Op10 : Op11;
  19463. if (Commute)
  19464. std::swap(Op0, Op1);
  19465. // Only accept the merged shuffle if we don't introduce undef elements,
  19466. // or the inner shuffle already contained undef elements.
  19467. auto *SVN0 = dyn_cast<ShuffleVectorSDNode>(Op0);
  19468. return SVN0 && InnerN->isOnlyUserOf(SVN0) &&
  19469. MergeInnerShuffle(Commute, SVN, SVN0, Op1, TLI, SV0, SV1,
  19470. Mask) &&
  19471. (llvm::any_of(SVN0->getMask(), [](int M) { return M < 0; }) ||
  19472. llvm::none_of(Mask, [](int M) { return M < 0; }));
  19473. };
  19474. // Ensure we don't increase the number of shuffles - we must merge a
  19475. // shuffle from at least one of the LHS and RHS ops.
  19476. bool MergedLeft = false;
  19477. SDValue LeftSV0, LeftSV1;
  19478. SmallVector<int, 4> LeftMask;
  19479. if (CanMergeInnerShuffle(LeftSV0, LeftSV1, LeftMask, true, false) ||
  19480. CanMergeInnerShuffle(LeftSV0, LeftSV1, LeftMask, true, true)) {
  19481. MergedLeft = true;
  19482. } else {
  19483. LeftMask.assign(SVN->getMask().begin(), SVN->getMask().end());
  19484. LeftSV0 = Op00, LeftSV1 = Op10;
  19485. }
  19486. bool MergedRight = false;
  19487. SDValue RightSV0, RightSV1;
  19488. SmallVector<int, 4> RightMask;
  19489. if (CanMergeInnerShuffle(RightSV0, RightSV1, RightMask, false, false) ||
  19490. CanMergeInnerShuffle(RightSV0, RightSV1, RightMask, false, true)) {
  19491. MergedRight = true;
  19492. } else {
  19493. RightMask.assign(SVN->getMask().begin(), SVN->getMask().end());
  19494. RightSV0 = Op01, RightSV1 = Op11;
  19495. }
  19496. if (MergedLeft || MergedRight) {
  19497. SDLoc DL(N);
  19498. SDValue LHS = DAG.getVectorShuffle(
  19499. VT, DL, LeftSV0 ? LeftSV0 : DAG.getUNDEF(VT),
  19500. LeftSV1 ? LeftSV1 : DAG.getUNDEF(VT), LeftMask);
  19501. SDValue RHS = DAG.getVectorShuffle(
  19502. VT, DL, RightSV0 ? RightSV0 : DAG.getUNDEF(VT),
  19503. RightSV1 ? RightSV1 : DAG.getUNDEF(VT), RightMask);
  19504. return DAG.getNode(SrcOpcode, DL, VT, LHS, RHS);
  19505. }
  19506. }
  19507. }
  19508. }
  19509. if (SDValue V = foldShuffleOfConcatUndefs(SVN, DAG))
  19510. return V;
  19511. return SDValue();
  19512. }
  19513. SDValue DAGCombiner::visitSCALAR_TO_VECTOR(SDNode *N) {
  19514. SDValue InVal = N->getOperand(0);
  19515. EVT VT = N->getValueType(0);
  19516. // Replace a SCALAR_TO_VECTOR(EXTRACT_VECTOR_ELT(V,C0)) pattern
  19517. // with a VECTOR_SHUFFLE and possible truncate.
  19518. if (InVal.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  19519. VT.isFixedLengthVector() &&
  19520. InVal->getOperand(0).getValueType().isFixedLengthVector()) {
  19521. SDValue InVec = InVal->getOperand(0);
  19522. SDValue EltNo = InVal->getOperand(1);
  19523. auto InVecT = InVec.getValueType();
  19524. if (ConstantSDNode *C0 = dyn_cast<ConstantSDNode>(EltNo)) {
  19525. SmallVector<int, 8> NewMask(InVecT.getVectorNumElements(), -1);
  19526. int Elt = C0->getZExtValue();
  19527. NewMask[0] = Elt;
  19528. // If we have an implict truncate do truncate here as long as it's legal.
  19529. // if it's not legal, this should
  19530. if (VT.getScalarType() != InVal.getValueType() &&
  19531. InVal.getValueType().isScalarInteger() &&
  19532. isTypeLegal(VT.getScalarType())) {
  19533. SDValue Val =
  19534. DAG.getNode(ISD::TRUNCATE, SDLoc(InVal), VT.getScalarType(), InVal);
  19535. return DAG.getNode(ISD::SCALAR_TO_VECTOR, SDLoc(N), VT, Val);
  19536. }
  19537. if (VT.getScalarType() == InVecT.getScalarType() &&
  19538. VT.getVectorNumElements() <= InVecT.getVectorNumElements()) {
  19539. SDValue LegalShuffle =
  19540. TLI.buildLegalVectorShuffle(InVecT, SDLoc(N), InVec,
  19541. DAG.getUNDEF(InVecT), NewMask, DAG);
  19542. if (LegalShuffle) {
  19543. // If the initial vector is the correct size this shuffle is a
  19544. // valid result.
  19545. if (VT == InVecT)
  19546. return LegalShuffle;
  19547. // If not we must truncate the vector.
  19548. if (VT.getVectorNumElements() != InVecT.getVectorNumElements()) {
  19549. SDValue ZeroIdx = DAG.getVectorIdxConstant(0, SDLoc(N));
  19550. EVT SubVT = EVT::getVectorVT(*DAG.getContext(),
  19551. InVecT.getVectorElementType(),
  19552. VT.getVectorNumElements());
  19553. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, SDLoc(N), SubVT,
  19554. LegalShuffle, ZeroIdx);
  19555. }
  19556. }
  19557. }
  19558. }
  19559. }
  19560. return SDValue();
  19561. }
  19562. SDValue DAGCombiner::visitINSERT_SUBVECTOR(SDNode *N) {
  19563. EVT VT = N->getValueType(0);
  19564. SDValue N0 = N->getOperand(0);
  19565. SDValue N1 = N->getOperand(1);
  19566. SDValue N2 = N->getOperand(2);
  19567. uint64_t InsIdx = N->getConstantOperandVal(2);
  19568. // If inserting an UNDEF, just return the original vector.
  19569. if (N1.isUndef())
  19570. return N0;
  19571. // If this is an insert of an extracted vector into an undef vector, we can
  19572. // just use the input to the extract.
  19573. if (N0.isUndef() && N1.getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  19574. N1.getOperand(1) == N2 && N1.getOperand(0).getValueType() == VT)
  19575. return N1.getOperand(0);
  19576. // If we are inserting a bitcast value into an undef, with the same
  19577. // number of elements, just use the bitcast input of the extract.
  19578. // i.e. INSERT_SUBVECTOR UNDEF (BITCAST N1) N2 ->
  19579. // BITCAST (INSERT_SUBVECTOR UNDEF N1 N2)
  19580. if (N0.isUndef() && N1.getOpcode() == ISD::BITCAST &&
  19581. N1.getOperand(0).getOpcode() == ISD::EXTRACT_SUBVECTOR &&
  19582. N1.getOperand(0).getOperand(1) == N2 &&
  19583. N1.getOperand(0).getOperand(0).getValueType().getVectorElementCount() ==
  19584. VT.getVectorElementCount() &&
  19585. N1.getOperand(0).getOperand(0).getValueType().getSizeInBits() ==
  19586. VT.getSizeInBits()) {
  19587. return DAG.getBitcast(VT, N1.getOperand(0).getOperand(0));
  19588. }
  19589. // If both N1 and N2 are bitcast values on which insert_subvector
  19590. // would makes sense, pull the bitcast through.
  19591. // i.e. INSERT_SUBVECTOR (BITCAST N0) (BITCAST N1) N2 ->
  19592. // BITCAST (INSERT_SUBVECTOR N0 N1 N2)
  19593. if (N0.getOpcode() == ISD::BITCAST && N1.getOpcode() == ISD::BITCAST) {
  19594. SDValue CN0 = N0.getOperand(0);
  19595. SDValue CN1 = N1.getOperand(0);
  19596. EVT CN0VT = CN0.getValueType();
  19597. EVT CN1VT = CN1.getValueType();
  19598. if (CN0VT.isVector() && CN1VT.isVector() &&
  19599. CN0VT.getVectorElementType() == CN1VT.getVectorElementType() &&
  19600. CN0VT.getVectorElementCount() == VT.getVectorElementCount()) {
  19601. SDValue NewINSERT = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N),
  19602. CN0.getValueType(), CN0, CN1, N2);
  19603. return DAG.getBitcast(VT, NewINSERT);
  19604. }
  19605. }
  19606. // Combine INSERT_SUBVECTORs where we are inserting to the same index.
  19607. // INSERT_SUBVECTOR( INSERT_SUBVECTOR( Vec, SubOld, Idx ), SubNew, Idx )
  19608. // --> INSERT_SUBVECTOR( Vec, SubNew, Idx )
  19609. if (N0.getOpcode() == ISD::INSERT_SUBVECTOR &&
  19610. N0.getOperand(1).getValueType() == N1.getValueType() &&
  19611. N0.getOperand(2) == N2)
  19612. return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0.getOperand(0),
  19613. N1, N2);
  19614. // Eliminate an intermediate insert into an undef vector:
  19615. // insert_subvector undef, (insert_subvector undef, X, 0), N2 -->
  19616. // insert_subvector undef, X, N2
  19617. if (N0.isUndef() && N1.getOpcode() == ISD::INSERT_SUBVECTOR &&
  19618. N1.getOperand(0).isUndef() && isNullConstant(N1.getOperand(2)))
  19619. return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT, N0,
  19620. N1.getOperand(1), N2);
  19621. // Push subvector bitcasts to the output, adjusting the index as we go.
  19622. // insert_subvector(bitcast(v), bitcast(s), c1)
  19623. // -> bitcast(insert_subvector(v, s, c2))
  19624. if ((N0.isUndef() || N0.getOpcode() == ISD::BITCAST) &&
  19625. N1.getOpcode() == ISD::BITCAST) {
  19626. SDValue N0Src = peekThroughBitcasts(N0);
  19627. SDValue N1Src = peekThroughBitcasts(N1);
  19628. EVT N0SrcSVT = N0Src.getValueType().getScalarType();
  19629. EVT N1SrcSVT = N1Src.getValueType().getScalarType();
  19630. if ((N0.isUndef() || N0SrcSVT == N1SrcSVT) &&
  19631. N0Src.getValueType().isVector() && N1Src.getValueType().isVector()) {
  19632. EVT NewVT;
  19633. SDLoc DL(N);
  19634. SDValue NewIdx;
  19635. LLVMContext &Ctx = *DAG.getContext();
  19636. ElementCount NumElts = VT.getVectorElementCount();
  19637. unsigned EltSizeInBits = VT.getScalarSizeInBits();
  19638. if ((EltSizeInBits % N1SrcSVT.getSizeInBits()) == 0) {
  19639. unsigned Scale = EltSizeInBits / N1SrcSVT.getSizeInBits();
  19640. NewVT = EVT::getVectorVT(Ctx, N1SrcSVT, NumElts * Scale);
  19641. NewIdx = DAG.getVectorIdxConstant(InsIdx * Scale, DL);
  19642. } else if ((N1SrcSVT.getSizeInBits() % EltSizeInBits) == 0) {
  19643. unsigned Scale = N1SrcSVT.getSizeInBits() / EltSizeInBits;
  19644. if (NumElts.isKnownMultipleOf(Scale) && (InsIdx % Scale) == 0) {
  19645. NewVT = EVT::getVectorVT(Ctx, N1SrcSVT,
  19646. NumElts.divideCoefficientBy(Scale));
  19647. NewIdx = DAG.getVectorIdxConstant(InsIdx / Scale, DL);
  19648. }
  19649. }
  19650. if (NewIdx && hasOperation(ISD::INSERT_SUBVECTOR, NewVT)) {
  19651. SDValue Res = DAG.getBitcast(NewVT, N0Src);
  19652. Res = DAG.getNode(ISD::INSERT_SUBVECTOR, DL, NewVT, Res, N1Src, NewIdx);
  19653. return DAG.getBitcast(VT, Res);
  19654. }
  19655. }
  19656. }
  19657. // Canonicalize insert_subvector dag nodes.
  19658. // Example:
  19659. // (insert_subvector (insert_subvector A, Idx0), Idx1)
  19660. // -> (insert_subvector (insert_subvector A, Idx1), Idx0)
  19661. if (N0.getOpcode() == ISD::INSERT_SUBVECTOR && N0.hasOneUse() &&
  19662. N1.getValueType() == N0.getOperand(1).getValueType()) {
  19663. unsigned OtherIdx = N0.getConstantOperandVal(2);
  19664. if (InsIdx < OtherIdx) {
  19665. // Swap nodes.
  19666. SDValue NewOp = DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N), VT,
  19667. N0.getOperand(0), N1, N2);
  19668. AddToWorklist(NewOp.getNode());
  19669. return DAG.getNode(ISD::INSERT_SUBVECTOR, SDLoc(N0.getNode()),
  19670. VT, NewOp, N0.getOperand(1), N0.getOperand(2));
  19671. }
  19672. }
  19673. // If the input vector is a concatenation, and the insert replaces
  19674. // one of the pieces, we can optimize into a single concat_vectors.
  19675. if (N0.getOpcode() == ISD::CONCAT_VECTORS && N0.hasOneUse() &&
  19676. N0.getOperand(0).getValueType() == N1.getValueType() &&
  19677. N0.getOperand(0).getValueType().isScalableVector() ==
  19678. N1.getValueType().isScalableVector()) {
  19679. unsigned Factor = N1.getValueType().getVectorMinNumElements();
  19680. SmallVector<SDValue, 8> Ops(N0->op_begin(), N0->op_end());
  19681. Ops[InsIdx / Factor] = N1;
  19682. return DAG.getNode(ISD::CONCAT_VECTORS, SDLoc(N), VT, Ops);
  19683. }
  19684. // Simplify source operands based on insertion.
  19685. if (SimplifyDemandedVectorElts(SDValue(N, 0)))
  19686. return SDValue(N, 0);
  19687. return SDValue();
  19688. }
  19689. SDValue DAGCombiner::visitFP_TO_FP16(SDNode *N) {
  19690. SDValue N0 = N->getOperand(0);
  19691. // fold (fp_to_fp16 (fp16_to_fp op)) -> op
  19692. if (N0->getOpcode() == ISD::FP16_TO_FP)
  19693. return N0->getOperand(0);
  19694. return SDValue();
  19695. }
  19696. SDValue DAGCombiner::visitFP16_TO_FP(SDNode *N) {
  19697. SDValue N0 = N->getOperand(0);
  19698. // fold fp16_to_fp(op & 0xffff) -> fp16_to_fp(op)
  19699. if (!TLI.shouldKeepZExtForFP16Conv() && N0->getOpcode() == ISD::AND) {
  19700. ConstantSDNode *AndConst = getAsNonOpaqueConstant(N0.getOperand(1));
  19701. if (AndConst && AndConst->getAPIntValue() == 0xffff) {
  19702. return DAG.getNode(ISD::FP16_TO_FP, SDLoc(N), N->getValueType(0),
  19703. N0.getOperand(0));
  19704. }
  19705. }
  19706. return SDValue();
  19707. }
  19708. SDValue DAGCombiner::visitVECREDUCE(SDNode *N) {
  19709. SDValue N0 = N->getOperand(0);
  19710. EVT VT = N0.getValueType();
  19711. unsigned Opcode = N->getOpcode();
  19712. // VECREDUCE over 1-element vector is just an extract.
  19713. if (VT.getVectorElementCount().isScalar()) {
  19714. SDLoc dl(N);
  19715. SDValue Res =
  19716. DAG.getNode(ISD::EXTRACT_VECTOR_ELT, dl, VT.getVectorElementType(), N0,
  19717. DAG.getVectorIdxConstant(0, dl));
  19718. if (Res.getValueType() != N->getValueType(0))
  19719. Res = DAG.getNode(ISD::ANY_EXTEND, dl, N->getValueType(0), Res);
  19720. return Res;
  19721. }
  19722. // On an boolean vector an and/or reduction is the same as a umin/umax
  19723. // reduction. Convert them if the latter is legal while the former isn't.
  19724. if (Opcode == ISD::VECREDUCE_AND || Opcode == ISD::VECREDUCE_OR) {
  19725. unsigned NewOpcode = Opcode == ISD::VECREDUCE_AND
  19726. ? ISD::VECREDUCE_UMIN : ISD::VECREDUCE_UMAX;
  19727. if (!TLI.isOperationLegalOrCustom(Opcode, VT) &&
  19728. TLI.isOperationLegalOrCustom(NewOpcode, VT) &&
  19729. DAG.ComputeNumSignBits(N0) == VT.getScalarSizeInBits())
  19730. return DAG.getNode(NewOpcode, SDLoc(N), N->getValueType(0), N0);
  19731. }
  19732. return SDValue();
  19733. }
  19734. SDValue DAGCombiner::visitVPOp(SDNode *N) {
  19735. // VP operations in which all vector elements are disabled - either by
  19736. // determining that the mask is all false or that the EVL is 0 - can be
  19737. // eliminated.
  19738. bool AreAllEltsDisabled = false;
  19739. if (auto EVLIdx = ISD::getVPExplicitVectorLengthIdx(N->getOpcode()))
  19740. AreAllEltsDisabled |= isNullConstant(N->getOperand(*EVLIdx));
  19741. if (auto MaskIdx = ISD::getVPMaskIdx(N->getOpcode()))
  19742. AreAllEltsDisabled |=
  19743. ISD::isConstantSplatVectorAllZeros(N->getOperand(*MaskIdx).getNode());
  19744. // This is the only generic VP combine we support for now.
  19745. if (!AreAllEltsDisabled)
  19746. return SDValue();
  19747. // Binary operations can be replaced by UNDEF.
  19748. if (ISD::isVPBinaryOp(N->getOpcode()))
  19749. return DAG.getUNDEF(N->getValueType(0));
  19750. // VP Memory operations can be replaced by either the chain (stores) or the
  19751. // chain + undef (loads).
  19752. if (const auto *MemSD = dyn_cast<MemSDNode>(N)) {
  19753. if (MemSD->writeMem())
  19754. return MemSD->getChain();
  19755. return CombineTo(N, DAG.getUNDEF(N->getValueType(0)), MemSD->getChain());
  19756. }
  19757. // Reduction operations return the start operand when no elements are active.
  19758. if (ISD::isVPReduction(N->getOpcode()))
  19759. return N->getOperand(0);
  19760. return SDValue();
  19761. }
  19762. /// Returns a vector_shuffle if it able to transform an AND to a vector_shuffle
  19763. /// with the destination vector and a zero vector.
  19764. /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
  19765. /// vector_shuffle V, Zero, <0, 4, 2, 4>
  19766. SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
  19767. assert(N->getOpcode() == ISD::AND && "Unexpected opcode!");
  19768. EVT VT = N->getValueType(0);
  19769. SDValue LHS = N->getOperand(0);
  19770. SDValue RHS = peekThroughBitcasts(N->getOperand(1));
  19771. SDLoc DL(N);
  19772. // Make sure we're not running after operation legalization where it
  19773. // may have custom lowered the vector shuffles.
  19774. if (LegalOperations)
  19775. return SDValue();
  19776. if (RHS.getOpcode() != ISD::BUILD_VECTOR)
  19777. return SDValue();
  19778. EVT RVT = RHS.getValueType();
  19779. unsigned NumElts = RHS.getNumOperands();
  19780. // Attempt to create a valid clear mask, splitting the mask into
  19781. // sub elements and checking to see if each is
  19782. // all zeros or all ones - suitable for shuffle masking.
  19783. auto BuildClearMask = [&](int Split) {
  19784. int NumSubElts = NumElts * Split;
  19785. int NumSubBits = RVT.getScalarSizeInBits() / Split;
  19786. SmallVector<int, 8> Indices;
  19787. for (int i = 0; i != NumSubElts; ++i) {
  19788. int EltIdx = i / Split;
  19789. int SubIdx = i % Split;
  19790. SDValue Elt = RHS.getOperand(EltIdx);
  19791. // X & undef --> 0 (not undef). So this lane must be converted to choose
  19792. // from the zero constant vector (same as if the element had all 0-bits).
  19793. if (Elt.isUndef()) {
  19794. Indices.push_back(i + NumSubElts);
  19795. continue;
  19796. }
  19797. APInt Bits;
  19798. if (isa<ConstantSDNode>(Elt))
  19799. Bits = cast<ConstantSDNode>(Elt)->getAPIntValue();
  19800. else if (isa<ConstantFPSDNode>(Elt))
  19801. Bits = cast<ConstantFPSDNode>(Elt)->getValueAPF().bitcastToAPInt();
  19802. else
  19803. return SDValue();
  19804. // Extract the sub element from the constant bit mask.
  19805. if (DAG.getDataLayout().isBigEndian())
  19806. Bits = Bits.extractBits(NumSubBits, (Split - SubIdx - 1) * NumSubBits);
  19807. else
  19808. Bits = Bits.extractBits(NumSubBits, SubIdx * NumSubBits);
  19809. if (Bits.isAllOnes())
  19810. Indices.push_back(i);
  19811. else if (Bits == 0)
  19812. Indices.push_back(i + NumSubElts);
  19813. else
  19814. return SDValue();
  19815. }
  19816. // Let's see if the target supports this vector_shuffle.
  19817. EVT ClearSVT = EVT::getIntegerVT(*DAG.getContext(), NumSubBits);
  19818. EVT ClearVT = EVT::getVectorVT(*DAG.getContext(), ClearSVT, NumSubElts);
  19819. if (!TLI.isVectorClearMaskLegal(Indices, ClearVT))
  19820. return SDValue();
  19821. SDValue Zero = DAG.getConstant(0, DL, ClearVT);
  19822. return DAG.getBitcast(VT, DAG.getVectorShuffle(ClearVT, DL,
  19823. DAG.getBitcast(ClearVT, LHS),
  19824. Zero, Indices));
  19825. };
  19826. // Determine maximum split level (byte level masking).
  19827. int MaxSplit = 1;
  19828. if (RVT.getScalarSizeInBits() % 8 == 0)
  19829. MaxSplit = RVT.getScalarSizeInBits() / 8;
  19830. for (int Split = 1; Split <= MaxSplit; ++Split)
  19831. if (RVT.getScalarSizeInBits() % Split == 0)
  19832. if (SDValue S = BuildClearMask(Split))
  19833. return S;
  19834. return SDValue();
  19835. }
  19836. /// If a vector binop is performed on splat values, it may be profitable to
  19837. /// extract, scalarize, and insert/splat.
  19838. static SDValue scalarizeBinOpOfSplats(SDNode *N, SelectionDAG &DAG,
  19839. const SDLoc &DL) {
  19840. SDValue N0 = N->getOperand(0);
  19841. SDValue N1 = N->getOperand(1);
  19842. unsigned Opcode = N->getOpcode();
  19843. EVT VT = N->getValueType(0);
  19844. EVT EltVT = VT.getVectorElementType();
  19845. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  19846. // TODO: Remove/replace the extract cost check? If the elements are available
  19847. // as scalars, then there may be no extract cost. Should we ask if
  19848. // inserting a scalar back into a vector is cheap instead?
  19849. int Index0, Index1;
  19850. SDValue Src0 = DAG.getSplatSourceVector(N0, Index0);
  19851. SDValue Src1 = DAG.getSplatSourceVector(N1, Index1);
  19852. if (!Src0 || !Src1 || Index0 != Index1 ||
  19853. Src0.getValueType().getVectorElementType() != EltVT ||
  19854. Src1.getValueType().getVectorElementType() != EltVT ||
  19855. !TLI.isExtractVecEltCheap(VT, Index0) ||
  19856. !TLI.isOperationLegalOrCustom(Opcode, EltVT))
  19857. return SDValue();
  19858. SDValue IndexC = DAG.getVectorIdxConstant(Index0, DL);
  19859. SDValue X = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src0, IndexC);
  19860. SDValue Y = DAG.getNode(ISD::EXTRACT_VECTOR_ELT, DL, EltVT, Src1, IndexC);
  19861. SDValue ScalarBO = DAG.getNode(Opcode, DL, EltVT, X, Y, N->getFlags());
  19862. // If all lanes but 1 are undefined, no need to splat the scalar result.
  19863. // TODO: Keep track of undefs and use that info in the general case.
  19864. if (N0.getOpcode() == ISD::BUILD_VECTOR && N0.getOpcode() == N1.getOpcode() &&
  19865. count_if(N0->ops(), [](SDValue V) { return !V.isUndef(); }) == 1 &&
  19866. count_if(N1->ops(), [](SDValue V) { return !V.isUndef(); }) == 1) {
  19867. // bo (build_vec ..undef, X, undef...), (build_vec ..undef, Y, undef...) -->
  19868. // build_vec ..undef, (bo X, Y), undef...
  19869. SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), DAG.getUNDEF(EltVT));
  19870. Ops[Index0] = ScalarBO;
  19871. return DAG.getBuildVector(VT, DL, Ops);
  19872. }
  19873. // bo (splat X, Index), (splat Y, Index) --> splat (bo X, Y), Index
  19874. SmallVector<SDValue, 8> Ops(VT.getVectorNumElements(), ScalarBO);
  19875. return DAG.getBuildVector(VT, DL, Ops);
  19876. }
  19877. /// Visit a binary vector operation, like ADD.
  19878. SDValue DAGCombiner::SimplifyVBinOp(SDNode *N, const SDLoc &DL) {
  19879. EVT VT = N->getValueType(0);
  19880. assert(VT.isVector() && "SimplifyVBinOp only works on vectors!");
  19881. SDValue LHS = N->getOperand(0);
  19882. SDValue RHS = N->getOperand(1);
  19883. unsigned Opcode = N->getOpcode();
  19884. SDNodeFlags Flags = N->getFlags();
  19885. // Move unary shuffles with identical masks after a vector binop:
  19886. // VBinOp (shuffle A, Undef, Mask), (shuffle B, Undef, Mask))
  19887. // --> shuffle (VBinOp A, B), Undef, Mask
  19888. // This does not require type legality checks because we are creating the
  19889. // same types of operations that are in the original sequence. We do have to
  19890. // restrict ops like integer div that have immediate UB (eg, div-by-zero)
  19891. // though. This code is adapted from the identical transform in instcombine.
  19892. if (Opcode != ISD::UDIV && Opcode != ISD::SDIV &&
  19893. Opcode != ISD::UREM && Opcode != ISD::SREM &&
  19894. Opcode != ISD::UDIVREM && Opcode != ISD::SDIVREM) {
  19895. auto *Shuf0 = dyn_cast<ShuffleVectorSDNode>(LHS);
  19896. auto *Shuf1 = dyn_cast<ShuffleVectorSDNode>(RHS);
  19897. if (Shuf0 && Shuf1 && Shuf0->getMask().equals(Shuf1->getMask()) &&
  19898. LHS.getOperand(1).isUndef() && RHS.getOperand(1).isUndef() &&
  19899. (LHS.hasOneUse() || RHS.hasOneUse() || LHS == RHS)) {
  19900. SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS.getOperand(0),
  19901. RHS.getOperand(0), Flags);
  19902. SDValue UndefV = LHS.getOperand(1);
  19903. return DAG.getVectorShuffle(VT, DL, NewBinOp, UndefV, Shuf0->getMask());
  19904. }
  19905. // Try to sink a splat shuffle after a binop with a uniform constant.
  19906. // This is limited to cases where neither the shuffle nor the constant have
  19907. // undefined elements because that could be poison-unsafe or inhibit
  19908. // demanded elements analysis. It is further limited to not change a splat
  19909. // of an inserted scalar because that may be optimized better by
  19910. // load-folding or other target-specific behaviors.
  19911. if (isConstOrConstSplat(RHS) && Shuf0 && is_splat(Shuf0->getMask()) &&
  19912. Shuf0->hasOneUse() && Shuf0->getOperand(1).isUndef() &&
  19913. Shuf0->getOperand(0).getOpcode() != ISD::INSERT_VECTOR_ELT) {
  19914. // binop (splat X), (splat C) --> splat (binop X, C)
  19915. SDValue X = Shuf0->getOperand(0);
  19916. SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, X, RHS, Flags);
  19917. return DAG.getVectorShuffle(VT, DL, NewBinOp, DAG.getUNDEF(VT),
  19918. Shuf0->getMask());
  19919. }
  19920. if (isConstOrConstSplat(LHS) && Shuf1 && is_splat(Shuf1->getMask()) &&
  19921. Shuf1->hasOneUse() && Shuf1->getOperand(1).isUndef() &&
  19922. Shuf1->getOperand(0).getOpcode() != ISD::INSERT_VECTOR_ELT) {
  19923. // binop (splat C), (splat X) --> splat (binop C, X)
  19924. SDValue X = Shuf1->getOperand(0);
  19925. SDValue NewBinOp = DAG.getNode(Opcode, DL, VT, LHS, X, Flags);
  19926. return DAG.getVectorShuffle(VT, DL, NewBinOp, DAG.getUNDEF(VT),
  19927. Shuf1->getMask());
  19928. }
  19929. }
  19930. // The following pattern is likely to emerge with vector reduction ops. Moving
  19931. // the binary operation ahead of insertion may allow using a narrower vector
  19932. // instruction that has better performance than the wide version of the op:
  19933. // VBinOp (ins undef, X, Z), (ins undef, Y, Z) --> ins VecC, (VBinOp X, Y), Z
  19934. if (LHS.getOpcode() == ISD::INSERT_SUBVECTOR && LHS.getOperand(0).isUndef() &&
  19935. RHS.getOpcode() == ISD::INSERT_SUBVECTOR && RHS.getOperand(0).isUndef() &&
  19936. LHS.getOperand(2) == RHS.getOperand(2) &&
  19937. (LHS.hasOneUse() || RHS.hasOneUse())) {
  19938. SDValue X = LHS.getOperand(1);
  19939. SDValue Y = RHS.getOperand(1);
  19940. SDValue Z = LHS.getOperand(2);
  19941. EVT NarrowVT = X.getValueType();
  19942. if (NarrowVT == Y.getValueType() &&
  19943. TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT,
  19944. LegalOperations)) {
  19945. // (binop undef, undef) may not return undef, so compute that result.
  19946. SDValue VecC =
  19947. DAG.getNode(Opcode, DL, VT, DAG.getUNDEF(VT), DAG.getUNDEF(VT));
  19948. SDValue NarrowBO = DAG.getNode(Opcode, DL, NarrowVT, X, Y);
  19949. return DAG.getNode(ISD::INSERT_SUBVECTOR, DL, VT, VecC, NarrowBO, Z);
  19950. }
  19951. }
  19952. // Make sure all but the first op are undef or constant.
  19953. auto ConcatWithConstantOrUndef = [](SDValue Concat) {
  19954. return Concat.getOpcode() == ISD::CONCAT_VECTORS &&
  19955. all_of(drop_begin(Concat->ops()), [](const SDValue &Op) {
  19956. return Op.isUndef() ||
  19957. ISD::isBuildVectorOfConstantSDNodes(Op.getNode());
  19958. });
  19959. };
  19960. // The following pattern is likely to emerge with vector reduction ops. Moving
  19961. // the binary operation ahead of the concat may allow using a narrower vector
  19962. // instruction that has better performance than the wide version of the op:
  19963. // VBinOp (concat X, undef/constant), (concat Y, undef/constant) -->
  19964. // concat (VBinOp X, Y), VecC
  19965. if (ConcatWithConstantOrUndef(LHS) && ConcatWithConstantOrUndef(RHS) &&
  19966. (LHS.hasOneUse() || RHS.hasOneUse())) {
  19967. EVT NarrowVT = LHS.getOperand(0).getValueType();
  19968. if (NarrowVT == RHS.getOperand(0).getValueType() &&
  19969. TLI.isOperationLegalOrCustomOrPromote(Opcode, NarrowVT)) {
  19970. unsigned NumOperands = LHS.getNumOperands();
  19971. SmallVector<SDValue, 4> ConcatOps;
  19972. for (unsigned i = 0; i != NumOperands; ++i) {
  19973. // This constant fold for operands 1 and up.
  19974. ConcatOps.push_back(DAG.getNode(Opcode, DL, NarrowVT, LHS.getOperand(i),
  19975. RHS.getOperand(i)));
  19976. }
  19977. return DAG.getNode(ISD::CONCAT_VECTORS, DL, VT, ConcatOps);
  19978. }
  19979. }
  19980. if (SDValue V = scalarizeBinOpOfSplats(N, DAG, DL))
  19981. return V;
  19982. return SDValue();
  19983. }
  19984. SDValue DAGCombiner::SimplifySelect(const SDLoc &DL, SDValue N0, SDValue N1,
  19985. SDValue N2) {
  19986. assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
  19987. SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
  19988. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  19989. // If we got a simplified select_cc node back from SimplifySelectCC, then
  19990. // break it down into a new SETCC node, and a new SELECT node, and then return
  19991. // the SELECT node, since we were called with a SELECT node.
  19992. if (SCC.getNode()) {
  19993. // Check to see if we got a select_cc back (to turn into setcc/select).
  19994. // Otherwise, just return whatever node we got back, like fabs.
  19995. if (SCC.getOpcode() == ISD::SELECT_CC) {
  19996. const SDNodeFlags Flags = N0.getNode()->getFlags();
  19997. SDValue SETCC = DAG.getNode(ISD::SETCC, SDLoc(N0),
  19998. N0.getValueType(),
  19999. SCC.getOperand(0), SCC.getOperand(1),
  20000. SCC.getOperand(4), Flags);
  20001. AddToWorklist(SETCC.getNode());
  20002. SDValue SelectNode = DAG.getSelect(SDLoc(SCC), SCC.getValueType(), SETCC,
  20003. SCC.getOperand(2), SCC.getOperand(3));
  20004. SelectNode->setFlags(Flags);
  20005. return SelectNode;
  20006. }
  20007. return SCC;
  20008. }
  20009. return SDValue();
  20010. }
  20011. /// Given a SELECT or a SELECT_CC node, where LHS and RHS are the two values
  20012. /// being selected between, see if we can simplify the select. Callers of this
  20013. /// should assume that TheSelect is deleted if this returns true. As such, they
  20014. /// should return the appropriate thing (e.g. the node) back to the top-level of
  20015. /// the DAG combiner loop to avoid it being looked at.
  20016. bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
  20017. SDValue RHS) {
  20018. // fold (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
  20019. // The select + setcc is redundant, because fsqrt returns NaN for X < 0.
  20020. if (const ConstantFPSDNode *NaN = isConstOrConstSplatFP(LHS)) {
  20021. if (NaN->isNaN() && RHS.getOpcode() == ISD::FSQRT) {
  20022. // We have: (select (setcc ?, ?, ?), NaN, (fsqrt ?))
  20023. SDValue Sqrt = RHS;
  20024. ISD::CondCode CC;
  20025. SDValue CmpLHS;
  20026. const ConstantFPSDNode *Zero = nullptr;
  20027. if (TheSelect->getOpcode() == ISD::SELECT_CC) {
  20028. CC = cast<CondCodeSDNode>(TheSelect->getOperand(4))->get();
  20029. CmpLHS = TheSelect->getOperand(0);
  20030. Zero = isConstOrConstSplatFP(TheSelect->getOperand(1));
  20031. } else {
  20032. // SELECT or VSELECT
  20033. SDValue Cmp = TheSelect->getOperand(0);
  20034. if (Cmp.getOpcode() == ISD::SETCC) {
  20035. CC = cast<CondCodeSDNode>(Cmp.getOperand(2))->get();
  20036. CmpLHS = Cmp.getOperand(0);
  20037. Zero = isConstOrConstSplatFP(Cmp.getOperand(1));
  20038. }
  20039. }
  20040. if (Zero && Zero->isZero() &&
  20041. Sqrt.getOperand(0) == CmpLHS && (CC == ISD::SETOLT ||
  20042. CC == ISD::SETULT || CC == ISD::SETLT)) {
  20043. // We have: (select (setcc x, [+-]0.0, *lt), NaN, (fsqrt x))
  20044. CombineTo(TheSelect, Sqrt);
  20045. return true;
  20046. }
  20047. }
  20048. }
  20049. // Cannot simplify select with vector condition
  20050. if (TheSelect->getOperand(0).getValueType().isVector()) return false;
  20051. // If this is a select from two identical things, try to pull the operation
  20052. // through the select.
  20053. if (LHS.getOpcode() != RHS.getOpcode() ||
  20054. !LHS.hasOneUse() || !RHS.hasOneUse())
  20055. return false;
  20056. // If this is a load and the token chain is identical, replace the select
  20057. // of two loads with a load through a select of the address to load from.
  20058. // This triggers in things like "select bool X, 10.0, 123.0" after the FP
  20059. // constants have been dropped into the constant pool.
  20060. if (LHS.getOpcode() == ISD::LOAD) {
  20061. LoadSDNode *LLD = cast<LoadSDNode>(LHS);
  20062. LoadSDNode *RLD = cast<LoadSDNode>(RHS);
  20063. // Token chains must be identical.
  20064. if (LHS.getOperand(0) != RHS.getOperand(0) ||
  20065. // Do not let this transformation reduce the number of volatile loads.
  20066. // Be conservative for atomics for the moment
  20067. // TODO: This does appear to be legal for unordered atomics (see D66309)
  20068. !LLD->isSimple() || !RLD->isSimple() ||
  20069. // FIXME: If either is a pre/post inc/dec load,
  20070. // we'd need to split out the address adjustment.
  20071. LLD->isIndexed() || RLD->isIndexed() ||
  20072. // If this is an EXTLOAD, the VT's must match.
  20073. LLD->getMemoryVT() != RLD->getMemoryVT() ||
  20074. // If this is an EXTLOAD, the kind of extension must match.
  20075. (LLD->getExtensionType() != RLD->getExtensionType() &&
  20076. // The only exception is if one of the extensions is anyext.
  20077. LLD->getExtensionType() != ISD::EXTLOAD &&
  20078. RLD->getExtensionType() != ISD::EXTLOAD) ||
  20079. // FIXME: this discards src value information. This is
  20080. // over-conservative. It would be beneficial to be able to remember
  20081. // both potential memory locations. Since we are discarding
  20082. // src value info, don't do the transformation if the memory
  20083. // locations are not in the default address space.
  20084. LLD->getPointerInfo().getAddrSpace() != 0 ||
  20085. RLD->getPointerInfo().getAddrSpace() != 0 ||
  20086. // We can't produce a CMOV of a TargetFrameIndex since we won't
  20087. // generate the address generation required.
  20088. LLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex ||
  20089. RLD->getBasePtr().getOpcode() == ISD::TargetFrameIndex ||
  20090. !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
  20091. LLD->getBasePtr().getValueType()))
  20092. return false;
  20093. // The loads must not depend on one another.
  20094. if (LLD->isPredecessorOf(RLD) || RLD->isPredecessorOf(LLD))
  20095. return false;
  20096. // Check that the select condition doesn't reach either load. If so,
  20097. // folding this will induce a cycle into the DAG. If not, this is safe to
  20098. // xform, so create a select of the addresses.
  20099. SmallPtrSet<const SDNode *, 32> Visited;
  20100. SmallVector<const SDNode *, 16> Worklist;
  20101. // Always fail if LLD and RLD are not independent. TheSelect is a
  20102. // predecessor to all Nodes in question so we need not search past it.
  20103. Visited.insert(TheSelect);
  20104. Worklist.push_back(LLD);
  20105. Worklist.push_back(RLD);
  20106. if (SDNode::hasPredecessorHelper(LLD, Visited, Worklist) ||
  20107. SDNode::hasPredecessorHelper(RLD, Visited, Worklist))
  20108. return false;
  20109. SDValue Addr;
  20110. if (TheSelect->getOpcode() == ISD::SELECT) {
  20111. // We cannot do this optimization if any pair of {RLD, LLD} is a
  20112. // predecessor to {RLD, LLD, CondNode}. As we've already compared the
  20113. // Loads, we only need to check if CondNode is a successor to one of the
  20114. // loads. We can further avoid this if there's no use of their chain
  20115. // value.
  20116. SDNode *CondNode = TheSelect->getOperand(0).getNode();
  20117. Worklist.push_back(CondNode);
  20118. if ((LLD->hasAnyUseOfValue(1) &&
  20119. SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) ||
  20120. (RLD->hasAnyUseOfValue(1) &&
  20121. SDNode::hasPredecessorHelper(RLD, Visited, Worklist)))
  20122. return false;
  20123. Addr = DAG.getSelect(SDLoc(TheSelect),
  20124. LLD->getBasePtr().getValueType(),
  20125. TheSelect->getOperand(0), LLD->getBasePtr(),
  20126. RLD->getBasePtr());
  20127. } else { // Otherwise SELECT_CC
  20128. // We cannot do this optimization if any pair of {RLD, LLD} is a
  20129. // predecessor to {RLD, LLD, CondLHS, CondRHS}. As we've already compared
  20130. // the Loads, we only need to check if CondLHS/CondRHS is a successor to
  20131. // one of the loads. We can further avoid this if there's no use of their
  20132. // chain value.
  20133. SDNode *CondLHS = TheSelect->getOperand(0).getNode();
  20134. SDNode *CondRHS = TheSelect->getOperand(1).getNode();
  20135. Worklist.push_back(CondLHS);
  20136. Worklist.push_back(CondRHS);
  20137. if ((LLD->hasAnyUseOfValue(1) &&
  20138. SDNode::hasPredecessorHelper(LLD, Visited, Worklist)) ||
  20139. (RLD->hasAnyUseOfValue(1) &&
  20140. SDNode::hasPredecessorHelper(RLD, Visited, Worklist)))
  20141. return false;
  20142. Addr = DAG.getNode(ISD::SELECT_CC, SDLoc(TheSelect),
  20143. LLD->getBasePtr().getValueType(),
  20144. TheSelect->getOperand(0),
  20145. TheSelect->getOperand(1),
  20146. LLD->getBasePtr(), RLD->getBasePtr(),
  20147. TheSelect->getOperand(4));
  20148. }
  20149. SDValue Load;
  20150. // It is safe to replace the two loads if they have different alignments,
  20151. // but the new load must be the minimum (most restrictive) alignment of the
  20152. // inputs.
  20153. Align Alignment = std::min(LLD->getAlign(), RLD->getAlign());
  20154. MachineMemOperand::Flags MMOFlags = LLD->getMemOperand()->getFlags();
  20155. if (!RLD->isInvariant())
  20156. MMOFlags &= ~MachineMemOperand::MOInvariant;
  20157. if (!RLD->isDereferenceable())
  20158. MMOFlags &= ~MachineMemOperand::MODereferenceable;
  20159. if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
  20160. // FIXME: Discards pointer and AA info.
  20161. Load = DAG.getLoad(TheSelect->getValueType(0), SDLoc(TheSelect),
  20162. LLD->getChain(), Addr, MachinePointerInfo(), Alignment,
  20163. MMOFlags);
  20164. } else {
  20165. // FIXME: Discards pointer and AA info.
  20166. Load = DAG.getExtLoad(
  20167. LLD->getExtensionType() == ISD::EXTLOAD ? RLD->getExtensionType()
  20168. : LLD->getExtensionType(),
  20169. SDLoc(TheSelect), TheSelect->getValueType(0), LLD->getChain(), Addr,
  20170. MachinePointerInfo(), LLD->getMemoryVT(), Alignment, MMOFlags);
  20171. }
  20172. // Users of the select now use the result of the load.
  20173. CombineTo(TheSelect, Load);
  20174. // Users of the old loads now use the new load's chain. We know the
  20175. // old-load value is dead now.
  20176. CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
  20177. CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
  20178. return true;
  20179. }
  20180. return false;
  20181. }
  20182. /// Try to fold an expression of the form (N0 cond N1) ? N2 : N3 to a shift and
  20183. /// bitwise 'and'.
  20184. SDValue DAGCombiner::foldSelectCCToShiftAnd(const SDLoc &DL, SDValue N0,
  20185. SDValue N1, SDValue N2, SDValue N3,
  20186. ISD::CondCode CC) {
  20187. // If this is a select where the false operand is zero and the compare is a
  20188. // check of the sign bit, see if we can perform the "gzip trick":
  20189. // select_cc setlt X, 0, A, 0 -> and (sra X, size(X)-1), A
  20190. // select_cc setgt X, 0, A, 0 -> and (not (sra X, size(X)-1)), A
  20191. EVT XType = N0.getValueType();
  20192. EVT AType = N2.getValueType();
  20193. if (!isNullConstant(N3) || !XType.bitsGE(AType))
  20194. return SDValue();
  20195. // If the comparison is testing for a positive value, we have to invert
  20196. // the sign bit mask, so only do that transform if the target has a bitwise
  20197. // 'and not' instruction (the invert is free).
  20198. if (CC == ISD::SETGT && TLI.hasAndNot(N2)) {
  20199. // (X > -1) ? A : 0
  20200. // (X > 0) ? X : 0 <-- This is canonical signed max.
  20201. if (!(isAllOnesConstant(N1) || (isNullConstant(N1) && N0 == N2)))
  20202. return SDValue();
  20203. } else if (CC == ISD::SETLT) {
  20204. // (X < 0) ? A : 0
  20205. // (X < 1) ? X : 0 <-- This is un-canonicalized signed min.
  20206. if (!(isNullConstant(N1) || (isOneConstant(N1) && N0 == N2)))
  20207. return SDValue();
  20208. } else {
  20209. return SDValue();
  20210. }
  20211. // and (sra X, size(X)-1), A -> "and (srl X, C2), A" iff A is a single-bit
  20212. // constant.
  20213. EVT ShiftAmtTy = getShiftAmountTy(N0.getValueType());
  20214. auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
  20215. if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue() - 1)) == 0)) {
  20216. unsigned ShCt = XType.getSizeInBits() - N2C->getAPIntValue().logBase2() - 1;
  20217. if (!TLI.shouldAvoidTransformToShift(XType, ShCt)) {
  20218. SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
  20219. SDValue Shift = DAG.getNode(ISD::SRL, DL, XType, N0, ShiftAmt);
  20220. AddToWorklist(Shift.getNode());
  20221. if (XType.bitsGT(AType)) {
  20222. Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
  20223. AddToWorklist(Shift.getNode());
  20224. }
  20225. if (CC == ISD::SETGT)
  20226. Shift = DAG.getNOT(DL, Shift, AType);
  20227. return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
  20228. }
  20229. }
  20230. unsigned ShCt = XType.getSizeInBits() - 1;
  20231. if (TLI.shouldAvoidTransformToShift(XType, ShCt))
  20232. return SDValue();
  20233. SDValue ShiftAmt = DAG.getConstant(ShCt, DL, ShiftAmtTy);
  20234. SDValue Shift = DAG.getNode(ISD::SRA, DL, XType, N0, ShiftAmt);
  20235. AddToWorklist(Shift.getNode());
  20236. if (XType.bitsGT(AType)) {
  20237. Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
  20238. AddToWorklist(Shift.getNode());
  20239. }
  20240. if (CC == ISD::SETGT)
  20241. Shift = DAG.getNOT(DL, Shift, AType);
  20242. return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
  20243. }
  20244. // Fold select(cc, binop(), binop()) -> binop(select(), select()) etc.
  20245. SDValue DAGCombiner::foldSelectOfBinops(SDNode *N) {
  20246. SDValue N0 = N->getOperand(0);
  20247. SDValue N1 = N->getOperand(1);
  20248. SDValue N2 = N->getOperand(2);
  20249. EVT VT = N->getValueType(0);
  20250. SDLoc DL(N);
  20251. unsigned BinOpc = N1.getOpcode();
  20252. if (!TLI.isBinOp(BinOpc) || (N2.getOpcode() != BinOpc))
  20253. return SDValue();
  20254. // The use checks are intentionally on SDNode because we may be dealing
  20255. // with opcodes that produce more than one SDValue.
  20256. // TODO: Do we really need to check N0 (the condition operand of the select)?
  20257. // But removing that clause could cause an infinite loop...
  20258. if (!N0->hasOneUse() || !N1->hasOneUse() || !N2->hasOneUse())
  20259. return SDValue();
  20260. // Binops may include opcodes that return multiple values, so all values
  20261. // must be created/propagated from the newly created binops below.
  20262. SDVTList OpVTs = N1->getVTList();
  20263. // Fold select(cond, binop(x, y), binop(z, y))
  20264. // --> binop(select(cond, x, z), y)
  20265. if (N1.getOperand(1) == N2.getOperand(1)) {
  20266. SDValue NewSel =
  20267. DAG.getSelect(DL, VT, N0, N1.getOperand(0), N2.getOperand(0));
  20268. SDValue NewBinOp = DAG.getNode(BinOpc, DL, OpVTs, NewSel, N1.getOperand(1));
  20269. NewBinOp->setFlags(N1->getFlags());
  20270. NewBinOp->intersectFlagsWith(N2->getFlags());
  20271. return NewBinOp;
  20272. }
  20273. // Fold select(cond, binop(x, y), binop(x, z))
  20274. // --> binop(x, select(cond, y, z))
  20275. // Second op VT might be different (e.g. shift amount type)
  20276. if (N1.getOperand(0) == N2.getOperand(0) &&
  20277. VT == N1.getOperand(1).getValueType() &&
  20278. VT == N2.getOperand(1).getValueType()) {
  20279. SDValue NewSel =
  20280. DAG.getSelect(DL, VT, N0, N1.getOperand(1), N2.getOperand(1));
  20281. SDValue NewBinOp = DAG.getNode(BinOpc, DL, OpVTs, N1.getOperand(0), NewSel);
  20282. NewBinOp->setFlags(N1->getFlags());
  20283. NewBinOp->intersectFlagsWith(N2->getFlags());
  20284. return NewBinOp;
  20285. }
  20286. // TODO: Handle isCommutativeBinOp patterns as well?
  20287. return SDValue();
  20288. }
  20289. // Transform (fneg/fabs (bitconvert x)) to avoid loading constant pool values.
  20290. SDValue DAGCombiner::foldSignChangeInBitcast(SDNode *N) {
  20291. SDValue N0 = N->getOperand(0);
  20292. EVT VT = N->getValueType(0);
  20293. bool IsFabs = N->getOpcode() == ISD::FABS;
  20294. bool IsFree = IsFabs ? TLI.isFAbsFree(VT) : TLI.isFNegFree(VT);
  20295. if (IsFree || N0.getOpcode() != ISD::BITCAST || !N0.hasOneUse())
  20296. return SDValue();
  20297. SDValue Int = N0.getOperand(0);
  20298. EVT IntVT = Int.getValueType();
  20299. // The operand to cast should be integer.
  20300. if (!IntVT.isInteger() || IntVT.isVector())
  20301. return SDValue();
  20302. // (fneg (bitconvert x)) -> (bitconvert (xor x sign))
  20303. // (fabs (bitconvert x)) -> (bitconvert (and x ~sign))
  20304. APInt SignMask;
  20305. if (N0.getValueType().isVector()) {
  20306. // For vector, create a sign mask (0x80...) or its inverse (for fabs,
  20307. // 0x7f...) per element and splat it.
  20308. SignMask = APInt::getSignMask(N0.getScalarValueSizeInBits());
  20309. if (IsFabs)
  20310. SignMask = ~SignMask;
  20311. SignMask = APInt::getSplat(IntVT.getSizeInBits(), SignMask);
  20312. } else {
  20313. // For scalar, just use the sign mask (0x80... or the inverse, 0x7f...)
  20314. SignMask = APInt::getSignMask(IntVT.getSizeInBits());
  20315. if (IsFabs)
  20316. SignMask = ~SignMask;
  20317. }
  20318. SDLoc DL(N0);
  20319. Int = DAG.getNode(IsFabs ? ISD::AND : ISD::XOR, DL, IntVT, Int,
  20320. DAG.getConstant(SignMask, DL, IntVT));
  20321. AddToWorklist(Int.getNode());
  20322. return DAG.getBitcast(VT, Int);
  20323. }
  20324. /// Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
  20325. /// where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
  20326. /// in it. This may be a win when the constant is not otherwise available
  20327. /// because it replaces two constant pool loads with one.
  20328. SDValue DAGCombiner::convertSelectOfFPConstantsToLoadOffset(
  20329. const SDLoc &DL, SDValue N0, SDValue N1, SDValue N2, SDValue N3,
  20330. ISD::CondCode CC) {
  20331. if (!TLI.reduceSelectOfFPConstantLoads(N0.getValueType()))
  20332. return SDValue();
  20333. // If we are before legalize types, we want the other legalization to happen
  20334. // first (for example, to avoid messing with soft float).
  20335. auto *TV = dyn_cast<ConstantFPSDNode>(N2);
  20336. auto *FV = dyn_cast<ConstantFPSDNode>(N3);
  20337. EVT VT = N2.getValueType();
  20338. if (!TV || !FV || !TLI.isTypeLegal(VT))
  20339. return SDValue();
  20340. // If a constant can be materialized without loads, this does not make sense.
  20341. if (TLI.getOperationAction(ISD::ConstantFP, VT) == TargetLowering::Legal ||
  20342. TLI.isFPImmLegal(TV->getValueAPF(), TV->getValueType(0), ForCodeSize) ||
  20343. TLI.isFPImmLegal(FV->getValueAPF(), FV->getValueType(0), ForCodeSize))
  20344. return SDValue();
  20345. // If both constants have multiple uses, then we won't need to do an extra
  20346. // load. The values are likely around in registers for other users.
  20347. if (!TV->hasOneUse() && !FV->hasOneUse())
  20348. return SDValue();
  20349. Constant *Elts[] = { const_cast<ConstantFP*>(FV->getConstantFPValue()),
  20350. const_cast<ConstantFP*>(TV->getConstantFPValue()) };
  20351. Type *FPTy = Elts[0]->getType();
  20352. const DataLayout &TD = DAG.getDataLayout();
  20353. // Create a ConstantArray of the two constants.
  20354. Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
  20355. SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(DAG.getDataLayout()),
  20356. TD.getPrefTypeAlign(FPTy));
  20357. Align Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlign();
  20358. // Get offsets to the 0 and 1 elements of the array, so we can select between
  20359. // them.
  20360. SDValue Zero = DAG.getIntPtrConstant(0, DL);
  20361. unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
  20362. SDValue One = DAG.getIntPtrConstant(EltSize, SDLoc(FV));
  20363. SDValue Cond =
  20364. DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()), N0, N1, CC);
  20365. AddToWorklist(Cond.getNode());
  20366. SDValue CstOffset = DAG.getSelect(DL, Zero.getValueType(), Cond, One, Zero);
  20367. AddToWorklist(CstOffset.getNode());
  20368. CPIdx = DAG.getNode(ISD::ADD, DL, CPIdx.getValueType(), CPIdx, CstOffset);
  20369. AddToWorklist(CPIdx.getNode());
  20370. return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
  20371. MachinePointerInfo::getConstantPool(
  20372. DAG.getMachineFunction()), Alignment);
  20373. }
  20374. /// Simplify an expression of the form (N0 cond N1) ? N2 : N3
  20375. /// where 'cond' is the comparison specified by CC.
  20376. SDValue DAGCombiner::SimplifySelectCC(const SDLoc &DL, SDValue N0, SDValue N1,
  20377. SDValue N2, SDValue N3, ISD::CondCode CC,
  20378. bool NotExtCompare) {
  20379. // (x ? y : y) -> y.
  20380. if (N2 == N3) return N2;
  20381. EVT CmpOpVT = N0.getValueType();
  20382. EVT CmpResVT = getSetCCResultType(CmpOpVT);
  20383. EVT VT = N2.getValueType();
  20384. auto *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
  20385. auto *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
  20386. auto *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
  20387. // Determine if the condition we're dealing with is constant.
  20388. if (SDValue SCC = DAG.FoldSetCC(CmpResVT, N0, N1, CC, DL)) {
  20389. AddToWorklist(SCC.getNode());
  20390. if (auto *SCCC = dyn_cast<ConstantSDNode>(SCC)) {
  20391. // fold select_cc true, x, y -> x
  20392. // fold select_cc false, x, y -> y
  20393. return !(SCCC->isZero()) ? N2 : N3;
  20394. }
  20395. }
  20396. if (SDValue V =
  20397. convertSelectOfFPConstantsToLoadOffset(DL, N0, N1, N2, N3, CC))
  20398. return V;
  20399. if (SDValue V = foldSelectCCToShiftAnd(DL, N0, N1, N2, N3, CC))
  20400. return V;
  20401. // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
  20402. // where y is has a single bit set.
  20403. // A plaintext description would be, we can turn the SELECT_CC into an AND
  20404. // when the condition can be materialized as an all-ones register. Any
  20405. // single bit-test can be materialized as an all-ones register with
  20406. // shift-left and shift-right-arith.
  20407. if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
  20408. N0->getValueType(0) == VT && isNullConstant(N1) && isNullConstant(N2)) {
  20409. SDValue AndLHS = N0->getOperand(0);
  20410. auto *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
  20411. if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
  20412. // Shift the tested bit over the sign bit.
  20413. const APInt &AndMask = ConstAndRHS->getAPIntValue();
  20414. unsigned ShCt = AndMask.getBitWidth() - 1;
  20415. if (!TLI.shouldAvoidTransformToShift(VT, ShCt)) {
  20416. SDValue ShlAmt =
  20417. DAG.getConstant(AndMask.countLeadingZeros(), SDLoc(AndLHS),
  20418. getShiftAmountTy(AndLHS.getValueType()));
  20419. SDValue Shl = DAG.getNode(ISD::SHL, SDLoc(N0), VT, AndLHS, ShlAmt);
  20420. // Now arithmetic right shift it all the way over, so the result is
  20421. // either all-ones, or zero.
  20422. SDValue ShrAmt =
  20423. DAG.getConstant(ShCt, SDLoc(Shl),
  20424. getShiftAmountTy(Shl.getValueType()));
  20425. SDValue Shr = DAG.getNode(ISD::SRA, SDLoc(N0), VT, Shl, ShrAmt);
  20426. return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
  20427. }
  20428. }
  20429. }
  20430. // fold select C, 16, 0 -> shl C, 4
  20431. bool Fold = N2C && isNullConstant(N3) && N2C->getAPIntValue().isPowerOf2();
  20432. bool Swap = N3C && isNullConstant(N2) && N3C->getAPIntValue().isPowerOf2();
  20433. if ((Fold || Swap) &&
  20434. TLI.getBooleanContents(CmpOpVT) ==
  20435. TargetLowering::ZeroOrOneBooleanContent &&
  20436. (!LegalOperations || TLI.isOperationLegal(ISD::SETCC, CmpOpVT))) {
  20437. if (Swap) {
  20438. CC = ISD::getSetCCInverse(CC, CmpOpVT);
  20439. std::swap(N2C, N3C);
  20440. }
  20441. // If the caller doesn't want us to simplify this into a zext of a compare,
  20442. // don't do it.
  20443. if (NotExtCompare && N2C->isOne())
  20444. return SDValue();
  20445. SDValue Temp, SCC;
  20446. // zext (setcc n0, n1)
  20447. if (LegalTypes) {
  20448. SCC = DAG.getSetCC(DL, CmpResVT, N0, N1, CC);
  20449. if (VT.bitsLT(SCC.getValueType()))
  20450. Temp = DAG.getZeroExtendInReg(SCC, SDLoc(N2), VT);
  20451. else
  20452. Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC);
  20453. } else {
  20454. SCC = DAG.getSetCC(SDLoc(N0), MVT::i1, N0, N1, CC);
  20455. Temp = DAG.getNode(ISD::ZERO_EXTEND, SDLoc(N2), VT, SCC);
  20456. }
  20457. AddToWorklist(SCC.getNode());
  20458. AddToWorklist(Temp.getNode());
  20459. if (N2C->isOne())
  20460. return Temp;
  20461. unsigned ShCt = N2C->getAPIntValue().logBase2();
  20462. if (TLI.shouldAvoidTransformToShift(VT, ShCt))
  20463. return SDValue();
  20464. // shl setcc result by log2 n2c
  20465. return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
  20466. DAG.getConstant(ShCt, SDLoc(Temp),
  20467. getShiftAmountTy(Temp.getValueType())));
  20468. }
  20469. // select_cc seteq X, 0, sizeof(X), ctlz(X) -> ctlz(X)
  20470. // select_cc seteq X, 0, sizeof(X), ctlz_zero_undef(X) -> ctlz(X)
  20471. // select_cc seteq X, 0, sizeof(X), cttz(X) -> cttz(X)
  20472. // select_cc seteq X, 0, sizeof(X), cttz_zero_undef(X) -> cttz(X)
  20473. // select_cc setne X, 0, ctlz(X), sizeof(X) -> ctlz(X)
  20474. // select_cc setne X, 0, ctlz_zero_undef(X), sizeof(X) -> ctlz(X)
  20475. // select_cc setne X, 0, cttz(X), sizeof(X) -> cttz(X)
  20476. // select_cc setne X, 0, cttz_zero_undef(X), sizeof(X) -> cttz(X)
  20477. if (N1C && N1C->isZero() && (CC == ISD::SETEQ || CC == ISD::SETNE)) {
  20478. SDValue ValueOnZero = N2;
  20479. SDValue Count = N3;
  20480. // If the condition is NE instead of E, swap the operands.
  20481. if (CC == ISD::SETNE)
  20482. std::swap(ValueOnZero, Count);
  20483. // Check if the value on zero is a constant equal to the bits in the type.
  20484. if (auto *ValueOnZeroC = dyn_cast<ConstantSDNode>(ValueOnZero)) {
  20485. if (ValueOnZeroC->getAPIntValue() == VT.getSizeInBits()) {
  20486. // If the other operand is cttz/cttz_zero_undef of N0, and cttz is
  20487. // legal, combine to just cttz.
  20488. if ((Count.getOpcode() == ISD::CTTZ ||
  20489. Count.getOpcode() == ISD::CTTZ_ZERO_UNDEF) &&
  20490. N0 == Count.getOperand(0) &&
  20491. (!LegalOperations || TLI.isOperationLegal(ISD::CTTZ, VT)))
  20492. return DAG.getNode(ISD::CTTZ, DL, VT, N0);
  20493. // If the other operand is ctlz/ctlz_zero_undef of N0, and ctlz is
  20494. // legal, combine to just ctlz.
  20495. if ((Count.getOpcode() == ISD::CTLZ ||
  20496. Count.getOpcode() == ISD::CTLZ_ZERO_UNDEF) &&
  20497. N0 == Count.getOperand(0) &&
  20498. (!LegalOperations || TLI.isOperationLegal(ISD::CTLZ, VT)))
  20499. return DAG.getNode(ISD::CTLZ, DL, VT, N0);
  20500. }
  20501. }
  20502. }
  20503. // Fold select_cc setgt X, -1, C, ~C -> xor (ashr X, BW-1), C
  20504. // Fold select_cc setlt X, 0, C, ~C -> xor (ashr X, BW-1), ~C
  20505. if (!NotExtCompare && N1C && N2C && N3C &&
  20506. N2C->getAPIntValue() == ~N3C->getAPIntValue() &&
  20507. ((N1C->isAllOnes() && CC == ISD::SETGT) ||
  20508. (N1C->isZero() && CC == ISD::SETLT)) &&
  20509. !TLI.shouldAvoidTransformToShift(VT, CmpOpVT.getScalarSizeInBits() - 1)) {
  20510. SDValue ASR = DAG.getNode(
  20511. ISD::SRA, DL, CmpOpVT, N0,
  20512. DAG.getConstant(CmpOpVT.getScalarSizeInBits() - 1, DL, CmpOpVT));
  20513. return DAG.getNode(ISD::XOR, DL, VT, DAG.getSExtOrTrunc(ASR, DL, VT),
  20514. DAG.getSExtOrTrunc(CC == ISD::SETLT ? N3 : N2, DL, VT));
  20515. }
  20516. if (SDValue S = PerformMinMaxFpToSatCombine(N0, N1, N2, N3, CC, DAG))
  20517. return S;
  20518. if (SDValue S = PerformUMinFpToSatCombine(N0, N1, N2, N3, CC, DAG))
  20519. return S;
  20520. return SDValue();
  20521. }
  20522. /// This is a stub for TargetLowering::SimplifySetCC.
  20523. SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0, SDValue N1,
  20524. ISD::CondCode Cond, const SDLoc &DL,
  20525. bool foldBooleans) {
  20526. TargetLowering::DAGCombinerInfo
  20527. DagCombineInfo(DAG, Level, false, this);
  20528. return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
  20529. }
  20530. /// Given an ISD::SDIV node expressing a divide by constant, return
  20531. /// a DAG expression to select that will generate the same value by multiplying
  20532. /// by a magic number.
  20533. /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
  20534. SDValue DAGCombiner::BuildSDIV(SDNode *N) {
  20535. // when optimising for minimum size, we don't want to expand a div to a mul
  20536. // and a shift.
  20537. if (DAG.getMachineFunction().getFunction().hasMinSize())
  20538. return SDValue();
  20539. SmallVector<SDNode *, 8> Built;
  20540. if (SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, Built)) {
  20541. for (SDNode *N : Built)
  20542. AddToWorklist(N);
  20543. return S;
  20544. }
  20545. return SDValue();
  20546. }
  20547. /// Given an ISD::SDIV node expressing a divide by constant power of 2, return a
  20548. /// DAG expression that will generate the same value by right shifting.
  20549. SDValue DAGCombiner::BuildSDIVPow2(SDNode *N) {
  20550. ConstantSDNode *C = isConstOrConstSplat(N->getOperand(1));
  20551. if (!C)
  20552. return SDValue();
  20553. // Avoid division by zero.
  20554. if (C->isZero())
  20555. return SDValue();
  20556. SmallVector<SDNode *, 8> Built;
  20557. if (SDValue S = TLI.BuildSDIVPow2(N, C->getAPIntValue(), DAG, Built)) {
  20558. for (SDNode *N : Built)
  20559. AddToWorklist(N);
  20560. return S;
  20561. }
  20562. return SDValue();
  20563. }
  20564. /// Given an ISD::UDIV node expressing a divide by constant, return a DAG
  20565. /// expression that will generate the same value by multiplying by a magic
  20566. /// number.
  20567. /// Ref: "Hacker's Delight" or "The PowerPC Compiler Writer's Guide".
  20568. SDValue DAGCombiner::BuildUDIV(SDNode *N) {
  20569. // when optimising for minimum size, we don't want to expand a div to a mul
  20570. // and a shift.
  20571. if (DAG.getMachineFunction().getFunction().hasMinSize())
  20572. return SDValue();
  20573. SmallVector<SDNode *, 8> Built;
  20574. if (SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, Built)) {
  20575. for (SDNode *N : Built)
  20576. AddToWorklist(N);
  20577. return S;
  20578. }
  20579. return SDValue();
  20580. }
  20581. /// Determines the LogBase2 value for a non-null input value using the
  20582. /// transform: LogBase2(V) = (EltBits - 1) - ctlz(V).
  20583. SDValue DAGCombiner::BuildLogBase2(SDValue V, const SDLoc &DL) {
  20584. EVT VT = V.getValueType();
  20585. SDValue Ctlz = DAG.getNode(ISD::CTLZ, DL, VT, V);
  20586. SDValue Base = DAG.getConstant(VT.getScalarSizeInBits() - 1, DL, VT);
  20587. SDValue LogBase2 = DAG.getNode(ISD::SUB, DL, VT, Base, Ctlz);
  20588. return LogBase2;
  20589. }
  20590. /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
  20591. /// For the reciprocal, we need to find the zero of the function:
  20592. /// F(X) = 1/X - A [which has a zero at X = 1/A]
  20593. /// =>
  20594. /// X_{i+1} = X_i (2 - A X_i) = X_i + X_i (1 - A X_i) [this second form
  20595. /// does not require additional intermediate precision]
  20596. /// For the last iteration, put numerator N into it to gain more precision:
  20597. /// Result = N X_i + X_i (N - N A X_i)
  20598. SDValue DAGCombiner::BuildDivEstimate(SDValue N, SDValue Op,
  20599. SDNodeFlags Flags) {
  20600. if (LegalDAG)
  20601. return SDValue();
  20602. // TODO: Handle extended types?
  20603. EVT VT = Op.getValueType();
  20604. if (VT.getScalarType() != MVT::f16 && VT.getScalarType() != MVT::f32 &&
  20605. VT.getScalarType() != MVT::f64)
  20606. return SDValue();
  20607. // If estimates are explicitly disabled for this function, we're done.
  20608. MachineFunction &MF = DAG.getMachineFunction();
  20609. int Enabled = TLI.getRecipEstimateDivEnabled(VT, MF);
  20610. if (Enabled == TLI.ReciprocalEstimate::Disabled)
  20611. return SDValue();
  20612. // Estimates may be explicitly enabled for this type with a custom number of
  20613. // refinement steps.
  20614. int Iterations = TLI.getDivRefinementSteps(VT, MF);
  20615. if (SDValue Est = TLI.getRecipEstimate(Op, DAG, Enabled, Iterations)) {
  20616. AddToWorklist(Est.getNode());
  20617. SDLoc DL(Op);
  20618. if (Iterations) {
  20619. SDValue FPOne = DAG.getConstantFP(1.0, DL, VT);
  20620. // Newton iterations: Est = Est + Est (N - Arg * Est)
  20621. // If this is the last iteration, also multiply by the numerator.
  20622. for (int i = 0; i < Iterations; ++i) {
  20623. SDValue MulEst = Est;
  20624. if (i == Iterations - 1) {
  20625. MulEst = DAG.getNode(ISD::FMUL, DL, VT, N, Est, Flags);
  20626. AddToWorklist(MulEst.getNode());
  20627. }
  20628. SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Op, MulEst, Flags);
  20629. AddToWorklist(NewEst.getNode());
  20630. NewEst = DAG.getNode(ISD::FSUB, DL, VT,
  20631. (i == Iterations - 1 ? N : FPOne), NewEst, Flags);
  20632. AddToWorklist(NewEst.getNode());
  20633. NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
  20634. AddToWorklist(NewEst.getNode());
  20635. Est = DAG.getNode(ISD::FADD, DL, VT, MulEst, NewEst, Flags);
  20636. AddToWorklist(Est.getNode());
  20637. }
  20638. } else {
  20639. // If no iterations are available, multiply with N.
  20640. Est = DAG.getNode(ISD::FMUL, DL, VT, Est, N, Flags);
  20641. AddToWorklist(Est.getNode());
  20642. }
  20643. return Est;
  20644. }
  20645. return SDValue();
  20646. }
  20647. /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
  20648. /// For the reciprocal sqrt, we need to find the zero of the function:
  20649. /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
  20650. /// =>
  20651. /// X_{i+1} = X_i (1.5 - A X_i^2 / 2)
  20652. /// As a result, we precompute A/2 prior to the iteration loop.
  20653. SDValue DAGCombiner::buildSqrtNROneConst(SDValue Arg, SDValue Est,
  20654. unsigned Iterations,
  20655. SDNodeFlags Flags, bool Reciprocal) {
  20656. EVT VT = Arg.getValueType();
  20657. SDLoc DL(Arg);
  20658. SDValue ThreeHalves = DAG.getConstantFP(1.5, DL, VT);
  20659. // We now need 0.5 * Arg which we can write as (1.5 * Arg - Arg) so that
  20660. // this entire sequence requires only one FP constant.
  20661. SDValue HalfArg = DAG.getNode(ISD::FMUL, DL, VT, ThreeHalves, Arg, Flags);
  20662. HalfArg = DAG.getNode(ISD::FSUB, DL, VT, HalfArg, Arg, Flags);
  20663. // Newton iterations: Est = Est * (1.5 - HalfArg * Est * Est)
  20664. for (unsigned i = 0; i < Iterations; ++i) {
  20665. SDValue NewEst = DAG.getNode(ISD::FMUL, DL, VT, Est, Est, Flags);
  20666. NewEst = DAG.getNode(ISD::FMUL, DL, VT, HalfArg, NewEst, Flags);
  20667. NewEst = DAG.getNode(ISD::FSUB, DL, VT, ThreeHalves, NewEst, Flags);
  20668. Est = DAG.getNode(ISD::FMUL, DL, VT, Est, NewEst, Flags);
  20669. }
  20670. // If non-reciprocal square root is requested, multiply the result by Arg.
  20671. if (!Reciprocal)
  20672. Est = DAG.getNode(ISD::FMUL, DL, VT, Est, Arg, Flags);
  20673. return Est;
  20674. }
  20675. /// Newton iteration for a function: F(X) is X_{i+1} = X_i - F(X_i)/F'(X_i)
  20676. /// For the reciprocal sqrt, we need to find the zero of the function:
  20677. /// F(X) = 1/X^2 - A [which has a zero at X = 1/sqrt(A)]
  20678. /// =>
  20679. /// X_{i+1} = (-0.5 * X_i) * (A * X_i * X_i + (-3.0))
  20680. SDValue DAGCombiner::buildSqrtNRTwoConst(SDValue Arg, SDValue Est,
  20681. unsigned Iterations,
  20682. SDNodeFlags Flags, bool Reciprocal) {
  20683. EVT VT = Arg.getValueType();
  20684. SDLoc DL(Arg);
  20685. SDValue MinusThree = DAG.getConstantFP(-3.0, DL, VT);
  20686. SDValue MinusHalf = DAG.getConstantFP(-0.5, DL, VT);
  20687. // This routine must enter the loop below to work correctly
  20688. // when (Reciprocal == false).
  20689. assert(Iterations > 0);
  20690. // Newton iterations for reciprocal square root:
  20691. // E = (E * -0.5) * ((A * E) * E + -3.0)
  20692. for (unsigned i = 0; i < Iterations; ++i) {
  20693. SDValue AE = DAG.getNode(ISD::FMUL, DL, VT, Arg, Est, Flags);
  20694. SDValue AEE = DAG.getNode(ISD::FMUL, DL, VT, AE, Est, Flags);
  20695. SDValue RHS = DAG.getNode(ISD::FADD, DL, VT, AEE, MinusThree, Flags);
  20696. // When calculating a square root at the last iteration build:
  20697. // S = ((A * E) * -0.5) * ((A * E) * E + -3.0)
  20698. // (notice a common subexpression)
  20699. SDValue LHS;
  20700. if (Reciprocal || (i + 1) < Iterations) {
  20701. // RSQRT: LHS = (E * -0.5)
  20702. LHS = DAG.getNode(ISD::FMUL, DL, VT, Est, MinusHalf, Flags);
  20703. } else {
  20704. // SQRT: LHS = (A * E) * -0.5
  20705. LHS = DAG.getNode(ISD::FMUL, DL, VT, AE, MinusHalf, Flags);
  20706. }
  20707. Est = DAG.getNode(ISD::FMUL, DL, VT, LHS, RHS, Flags);
  20708. }
  20709. return Est;
  20710. }
  20711. /// Build code to calculate either rsqrt(Op) or sqrt(Op). In the latter case
  20712. /// Op*rsqrt(Op) is actually computed, so additional postprocessing is needed if
  20713. /// Op can be zero.
  20714. SDValue DAGCombiner::buildSqrtEstimateImpl(SDValue Op, SDNodeFlags Flags,
  20715. bool Reciprocal) {
  20716. if (LegalDAG)
  20717. return SDValue();
  20718. // TODO: Handle extended types?
  20719. EVT VT = Op.getValueType();
  20720. if (VT.getScalarType() != MVT::f16 && VT.getScalarType() != MVT::f32 &&
  20721. VT.getScalarType() != MVT::f64)
  20722. return SDValue();
  20723. // If estimates are explicitly disabled for this function, we're done.
  20724. MachineFunction &MF = DAG.getMachineFunction();
  20725. int Enabled = TLI.getRecipEstimateSqrtEnabled(VT, MF);
  20726. if (Enabled == TLI.ReciprocalEstimate::Disabled)
  20727. return SDValue();
  20728. // Estimates may be explicitly enabled for this type with a custom number of
  20729. // refinement steps.
  20730. int Iterations = TLI.getSqrtRefinementSteps(VT, MF);
  20731. bool UseOneConstNR = false;
  20732. if (SDValue Est =
  20733. TLI.getSqrtEstimate(Op, DAG, Enabled, Iterations, UseOneConstNR,
  20734. Reciprocal)) {
  20735. AddToWorklist(Est.getNode());
  20736. if (Iterations)
  20737. Est = UseOneConstNR
  20738. ? buildSqrtNROneConst(Op, Est, Iterations, Flags, Reciprocal)
  20739. : buildSqrtNRTwoConst(Op, Est, Iterations, Flags, Reciprocal);
  20740. if (!Reciprocal) {
  20741. SDLoc DL(Op);
  20742. // Try the target specific test first.
  20743. SDValue Test = TLI.getSqrtInputTest(Op, DAG, DAG.getDenormalMode(VT));
  20744. // The estimate is now completely wrong if the input was exactly 0.0 or
  20745. // possibly a denormal. Force the answer to 0.0 or value provided by
  20746. // target for those cases.
  20747. Est = DAG.getNode(
  20748. Test.getValueType().isVector() ? ISD::VSELECT : ISD::SELECT, DL, VT,
  20749. Test, TLI.getSqrtResultForDenormInput(Op, DAG), Est);
  20750. }
  20751. return Est;
  20752. }
  20753. return SDValue();
  20754. }
  20755. SDValue DAGCombiner::buildRsqrtEstimate(SDValue Op, SDNodeFlags Flags) {
  20756. return buildSqrtEstimateImpl(Op, Flags, true);
  20757. }
  20758. SDValue DAGCombiner::buildSqrtEstimate(SDValue Op, SDNodeFlags Flags) {
  20759. return buildSqrtEstimateImpl(Op, Flags, false);
  20760. }
  20761. /// Return true if there is any possibility that the two addresses overlap.
  20762. bool DAGCombiner::mayAlias(SDNode *Op0, SDNode *Op1) const {
  20763. struct MemUseCharacteristics {
  20764. bool IsVolatile;
  20765. bool IsAtomic;
  20766. SDValue BasePtr;
  20767. int64_t Offset;
  20768. Optional<int64_t> NumBytes;
  20769. MachineMemOperand *MMO;
  20770. };
  20771. auto getCharacteristics = [](SDNode *N) -> MemUseCharacteristics {
  20772. if (const auto *LSN = dyn_cast<LSBaseSDNode>(N)) {
  20773. int64_t Offset = 0;
  20774. if (auto *C = dyn_cast<ConstantSDNode>(LSN->getOffset()))
  20775. Offset = (LSN->getAddressingMode() == ISD::PRE_INC)
  20776. ? C->getSExtValue()
  20777. : (LSN->getAddressingMode() == ISD::PRE_DEC)
  20778. ? -1 * C->getSExtValue()
  20779. : 0;
  20780. uint64_t Size =
  20781. MemoryLocation::getSizeOrUnknown(LSN->getMemoryVT().getStoreSize());
  20782. return {LSN->isVolatile(), LSN->isAtomic(), LSN->getBasePtr(),
  20783. Offset /*base offset*/,
  20784. Optional<int64_t>(Size),
  20785. LSN->getMemOperand()};
  20786. }
  20787. if (const auto *LN = cast<LifetimeSDNode>(N))
  20788. return {false /*isVolatile*/, /*isAtomic*/ false, LN->getOperand(1),
  20789. (LN->hasOffset()) ? LN->getOffset() : 0,
  20790. (LN->hasOffset()) ? Optional<int64_t>(LN->getSize())
  20791. : Optional<int64_t>(),
  20792. (MachineMemOperand *)nullptr};
  20793. // Default.
  20794. return {false /*isvolatile*/, /*isAtomic*/ false, SDValue(),
  20795. (int64_t)0 /*offset*/,
  20796. Optional<int64_t>() /*size*/, (MachineMemOperand *)nullptr};
  20797. };
  20798. MemUseCharacteristics MUC0 = getCharacteristics(Op0),
  20799. MUC1 = getCharacteristics(Op1);
  20800. // If they are to the same address, then they must be aliases.
  20801. if (MUC0.BasePtr.getNode() && MUC0.BasePtr == MUC1.BasePtr &&
  20802. MUC0.Offset == MUC1.Offset)
  20803. return true;
  20804. // If they are both volatile then they cannot be reordered.
  20805. if (MUC0.IsVolatile && MUC1.IsVolatile)
  20806. return true;
  20807. // Be conservative about atomics for the moment
  20808. // TODO: This is way overconservative for unordered atomics (see D66309)
  20809. if (MUC0.IsAtomic && MUC1.IsAtomic)
  20810. return true;
  20811. if (MUC0.MMO && MUC1.MMO) {
  20812. if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) ||
  20813. (MUC1.MMO->isInvariant() && MUC0.MMO->isStore()))
  20814. return false;
  20815. }
  20816. // Try to prove that there is aliasing, or that there is no aliasing. Either
  20817. // way, we can return now. If nothing can be proved, proceed with more tests.
  20818. bool IsAlias;
  20819. if (BaseIndexOffset::computeAliasing(Op0, MUC0.NumBytes, Op1, MUC1.NumBytes,
  20820. DAG, IsAlias))
  20821. return IsAlias;
  20822. // The following all rely on MMO0 and MMO1 being valid. Fail conservatively if
  20823. // either are not known.
  20824. if (!MUC0.MMO || !MUC1.MMO)
  20825. return true;
  20826. // If one operation reads from invariant memory, and the other may store, they
  20827. // cannot alias. These should really be checking the equivalent of mayWrite,
  20828. // but it only matters for memory nodes other than load /store.
  20829. if ((MUC0.MMO->isInvariant() && MUC1.MMO->isStore()) ||
  20830. (MUC1.MMO->isInvariant() && MUC0.MMO->isStore()))
  20831. return false;
  20832. // If we know required SrcValue1 and SrcValue2 have relatively large
  20833. // alignment compared to the size and offset of the access, we may be able
  20834. // to prove they do not alias. This check is conservative for now to catch
  20835. // cases created by splitting vector types, it only works when the offsets are
  20836. // multiples of the size of the data.
  20837. int64_t SrcValOffset0 = MUC0.MMO->getOffset();
  20838. int64_t SrcValOffset1 = MUC1.MMO->getOffset();
  20839. Align OrigAlignment0 = MUC0.MMO->getBaseAlign();
  20840. Align OrigAlignment1 = MUC1.MMO->getBaseAlign();
  20841. auto &Size0 = MUC0.NumBytes;
  20842. auto &Size1 = MUC1.NumBytes;
  20843. if (OrigAlignment0 == OrigAlignment1 && SrcValOffset0 != SrcValOffset1 &&
  20844. Size0.hasValue() && Size1.hasValue() && *Size0 == *Size1 &&
  20845. OrigAlignment0 > *Size0 && SrcValOffset0 % *Size0 == 0 &&
  20846. SrcValOffset1 % *Size1 == 0) {
  20847. int64_t OffAlign0 = SrcValOffset0 % OrigAlignment0.value();
  20848. int64_t OffAlign1 = SrcValOffset1 % OrigAlignment1.value();
  20849. // There is no overlap between these relatively aligned accesses of
  20850. // similar size. Return no alias.
  20851. if ((OffAlign0 + *Size0) <= OffAlign1 || (OffAlign1 + *Size1) <= OffAlign0)
  20852. return false;
  20853. }
  20854. bool UseAA = CombinerGlobalAA.getNumOccurrences() > 0
  20855. ? CombinerGlobalAA
  20856. : DAG.getSubtarget().useAA();
  20857. #ifndef NDEBUG
  20858. if (CombinerAAOnlyFunc.getNumOccurrences() &&
  20859. CombinerAAOnlyFunc != DAG.getMachineFunction().getName())
  20860. UseAA = false;
  20861. #endif
  20862. if (UseAA && AA && MUC0.MMO->getValue() && MUC1.MMO->getValue() &&
  20863. Size0.hasValue() && Size1.hasValue()) {
  20864. // Use alias analysis information.
  20865. int64_t MinOffset = std::min(SrcValOffset0, SrcValOffset1);
  20866. int64_t Overlap0 = *Size0 + SrcValOffset0 - MinOffset;
  20867. int64_t Overlap1 = *Size1 + SrcValOffset1 - MinOffset;
  20868. if (AA->isNoAlias(
  20869. MemoryLocation(MUC0.MMO->getValue(), Overlap0,
  20870. UseTBAA ? MUC0.MMO->getAAInfo() : AAMDNodes()),
  20871. MemoryLocation(MUC1.MMO->getValue(), Overlap1,
  20872. UseTBAA ? MUC1.MMO->getAAInfo() : AAMDNodes())))
  20873. return false;
  20874. }
  20875. // Otherwise we have to assume they alias.
  20876. return true;
  20877. }
  20878. /// Walk up chain skipping non-aliasing memory nodes,
  20879. /// looking for aliasing nodes and adding them to the Aliases vector.
  20880. void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
  20881. SmallVectorImpl<SDValue> &Aliases) {
  20882. SmallVector<SDValue, 8> Chains; // List of chains to visit.
  20883. SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
  20884. // Get alias information for node.
  20885. // TODO: relax aliasing for unordered atomics (see D66309)
  20886. const bool IsLoad = isa<LoadSDNode>(N) && cast<LoadSDNode>(N)->isSimple();
  20887. // Starting off.
  20888. Chains.push_back(OriginalChain);
  20889. unsigned Depth = 0;
  20890. // Attempt to improve chain by a single step
  20891. std::function<bool(SDValue &)> ImproveChain = [&](SDValue &C) -> bool {
  20892. switch (C.getOpcode()) {
  20893. case ISD::EntryToken:
  20894. // No need to mark EntryToken.
  20895. C = SDValue();
  20896. return true;
  20897. case ISD::LOAD:
  20898. case ISD::STORE: {
  20899. // Get alias information for C.
  20900. // TODO: Relax aliasing for unordered atomics (see D66309)
  20901. bool IsOpLoad = isa<LoadSDNode>(C.getNode()) &&
  20902. cast<LSBaseSDNode>(C.getNode())->isSimple();
  20903. if ((IsLoad && IsOpLoad) || !mayAlias(N, C.getNode())) {
  20904. // Look further up the chain.
  20905. C = C.getOperand(0);
  20906. return true;
  20907. }
  20908. // Alias, so stop here.
  20909. return false;
  20910. }
  20911. case ISD::CopyFromReg:
  20912. // Always forward past past CopyFromReg.
  20913. C = C.getOperand(0);
  20914. return true;
  20915. case ISD::LIFETIME_START:
  20916. case ISD::LIFETIME_END: {
  20917. // We can forward past any lifetime start/end that can be proven not to
  20918. // alias the memory access.
  20919. if (!mayAlias(N, C.getNode())) {
  20920. // Look further up the chain.
  20921. C = C.getOperand(0);
  20922. return true;
  20923. }
  20924. return false;
  20925. }
  20926. default:
  20927. return false;
  20928. }
  20929. };
  20930. // Look at each chain and determine if it is an alias. If so, add it to the
  20931. // aliases list. If not, then continue up the chain looking for the next
  20932. // candidate.
  20933. while (!Chains.empty()) {
  20934. SDValue Chain = Chains.pop_back_val();
  20935. // Don't bother if we've seen Chain before.
  20936. if (!Visited.insert(Chain.getNode()).second)
  20937. continue;
  20938. // For TokenFactor nodes, look at each operand and only continue up the
  20939. // chain until we reach the depth limit.
  20940. //
  20941. // FIXME: The depth check could be made to return the last non-aliasing
  20942. // chain we found before we hit a tokenfactor rather than the original
  20943. // chain.
  20944. if (Depth > TLI.getGatherAllAliasesMaxDepth()) {
  20945. Aliases.clear();
  20946. Aliases.push_back(OriginalChain);
  20947. return;
  20948. }
  20949. if (Chain.getOpcode() == ISD::TokenFactor) {
  20950. // We have to check each of the operands of the token factor for "small"
  20951. // token factors, so we queue them up. Adding the operands to the queue
  20952. // (stack) in reverse order maintains the original order and increases the
  20953. // likelihood that getNode will find a matching token factor (CSE.)
  20954. if (Chain.getNumOperands() > 16) {
  20955. Aliases.push_back(Chain);
  20956. continue;
  20957. }
  20958. for (unsigned n = Chain.getNumOperands(); n;)
  20959. Chains.push_back(Chain.getOperand(--n));
  20960. ++Depth;
  20961. continue;
  20962. }
  20963. // Everything else
  20964. if (ImproveChain(Chain)) {
  20965. // Updated Chain Found, Consider new chain if one exists.
  20966. if (Chain.getNode())
  20967. Chains.push_back(Chain);
  20968. ++Depth;
  20969. continue;
  20970. }
  20971. // No Improved Chain Possible, treat as Alias.
  20972. Aliases.push_back(Chain);
  20973. }
  20974. }
  20975. /// Walk up chain skipping non-aliasing memory nodes, looking for a better chain
  20976. /// (aliasing node.)
  20977. SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
  20978. if (OptLevel == CodeGenOpt::None)
  20979. return OldChain;
  20980. // Ops for replacing token factor.
  20981. SmallVector<SDValue, 8> Aliases;
  20982. // Accumulate all the aliases to this node.
  20983. GatherAllAliases(N, OldChain, Aliases);
  20984. // If no operands then chain to entry token.
  20985. if (Aliases.size() == 0)
  20986. return DAG.getEntryNode();
  20987. // If a single operand then chain to it. We don't need to revisit it.
  20988. if (Aliases.size() == 1)
  20989. return Aliases[0];
  20990. // Construct a custom tailored token factor.
  20991. return DAG.getTokenFactor(SDLoc(N), Aliases);
  20992. }
  20993. namespace {
  20994. // TODO: Replace with with std::monostate when we move to C++17.
  20995. struct UnitT { } Unit;
  20996. bool operator==(const UnitT &, const UnitT &) { return true; }
  20997. bool operator!=(const UnitT &, const UnitT &) { return false; }
  20998. } // namespace
  20999. // This function tries to collect a bunch of potentially interesting
  21000. // nodes to improve the chains of, all at once. This might seem
  21001. // redundant, as this function gets called when visiting every store
  21002. // node, so why not let the work be done on each store as it's visited?
  21003. //
  21004. // I believe this is mainly important because mergeConsecutiveStores
  21005. // is unable to deal with merging stores of different sizes, so unless
  21006. // we improve the chains of all the potential candidates up-front
  21007. // before running mergeConsecutiveStores, it might only see some of
  21008. // the nodes that will eventually be candidates, and then not be able
  21009. // to go from a partially-merged state to the desired final
  21010. // fully-merged state.
  21011. bool DAGCombiner::parallelizeChainedStores(StoreSDNode *St) {
  21012. SmallVector<StoreSDNode *, 8> ChainedStores;
  21013. StoreSDNode *STChain = St;
  21014. // Intervals records which offsets from BaseIndex have been covered. In
  21015. // the common case, every store writes to the immediately previous address
  21016. // space and thus merged with the previous interval at insertion time.
  21017. using IMap =
  21018. llvm::IntervalMap<int64_t, UnitT, 8, IntervalMapHalfOpenInfo<int64_t>>;
  21019. IMap::Allocator A;
  21020. IMap Intervals(A);
  21021. // This holds the base pointer, index, and the offset in bytes from the base
  21022. // pointer.
  21023. const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
  21024. // We must have a base and an offset.
  21025. if (!BasePtr.getBase().getNode())
  21026. return false;
  21027. // Do not handle stores to undef base pointers.
  21028. if (BasePtr.getBase().isUndef())
  21029. return false;
  21030. // Do not handle stores to opaque types
  21031. if (St->getMemoryVT().isZeroSized())
  21032. return false;
  21033. // BaseIndexOffset assumes that offsets are fixed-size, which
  21034. // is not valid for scalable vectors where the offsets are
  21035. // scaled by `vscale`, so bail out early.
  21036. if (St->getMemoryVT().isScalableVector())
  21037. return false;
  21038. // Add ST's interval.
  21039. Intervals.insert(0, (St->getMemoryVT().getSizeInBits() + 7) / 8, Unit);
  21040. while (StoreSDNode *Chain = dyn_cast<StoreSDNode>(STChain->getChain())) {
  21041. if (Chain->getMemoryVT().isScalableVector())
  21042. return false;
  21043. // If the chain has more than one use, then we can't reorder the mem ops.
  21044. if (!SDValue(Chain, 0)->hasOneUse())
  21045. break;
  21046. // TODO: Relax for unordered atomics (see D66309)
  21047. if (!Chain->isSimple() || Chain->isIndexed())
  21048. break;
  21049. // Find the base pointer and offset for this memory node.
  21050. const BaseIndexOffset Ptr = BaseIndexOffset::match(Chain, DAG);
  21051. // Check that the base pointer is the same as the original one.
  21052. int64_t Offset;
  21053. if (!BasePtr.equalBaseIndex(Ptr, DAG, Offset))
  21054. break;
  21055. int64_t Length = (Chain->getMemoryVT().getSizeInBits() + 7) / 8;
  21056. // Make sure we don't overlap with other intervals by checking the ones to
  21057. // the left or right before inserting.
  21058. auto I = Intervals.find(Offset);
  21059. // If there's a next interval, we should end before it.
  21060. if (I != Intervals.end() && I.start() < (Offset + Length))
  21061. break;
  21062. // If there's a previous interval, we should start after it.
  21063. if (I != Intervals.begin() && (--I).stop() <= Offset)
  21064. break;
  21065. Intervals.insert(Offset, Offset + Length, Unit);
  21066. ChainedStores.push_back(Chain);
  21067. STChain = Chain;
  21068. }
  21069. // If we didn't find a chained store, exit.
  21070. if (ChainedStores.size() == 0)
  21071. return false;
  21072. // Improve all chained stores (St and ChainedStores members) starting from
  21073. // where the store chain ended and return single TokenFactor.
  21074. SDValue NewChain = STChain->getChain();
  21075. SmallVector<SDValue, 8> TFOps;
  21076. for (unsigned I = ChainedStores.size(); I;) {
  21077. StoreSDNode *S = ChainedStores[--I];
  21078. SDValue BetterChain = FindBetterChain(S, NewChain);
  21079. S = cast<StoreSDNode>(DAG.UpdateNodeOperands(
  21080. S, BetterChain, S->getOperand(1), S->getOperand(2), S->getOperand(3)));
  21081. TFOps.push_back(SDValue(S, 0));
  21082. ChainedStores[I] = S;
  21083. }
  21084. // Improve St's chain. Use a new node to avoid creating a loop from CombineTo.
  21085. SDValue BetterChain = FindBetterChain(St, NewChain);
  21086. SDValue NewST;
  21087. if (St->isTruncatingStore())
  21088. NewST = DAG.getTruncStore(BetterChain, SDLoc(St), St->getValue(),
  21089. St->getBasePtr(), St->getMemoryVT(),
  21090. St->getMemOperand());
  21091. else
  21092. NewST = DAG.getStore(BetterChain, SDLoc(St), St->getValue(),
  21093. St->getBasePtr(), St->getMemOperand());
  21094. TFOps.push_back(NewST);
  21095. // If we improved every element of TFOps, then we've lost the dependence on
  21096. // NewChain to successors of St and we need to add it back to TFOps. Do so at
  21097. // the beginning to keep relative order consistent with FindBetterChains.
  21098. auto hasImprovedChain = [&](SDValue ST) -> bool {
  21099. return ST->getOperand(0) != NewChain;
  21100. };
  21101. bool AddNewChain = llvm::all_of(TFOps, hasImprovedChain);
  21102. if (AddNewChain)
  21103. TFOps.insert(TFOps.begin(), NewChain);
  21104. SDValue TF = DAG.getTokenFactor(SDLoc(STChain), TFOps);
  21105. CombineTo(St, TF);
  21106. // Add TF and its operands to the worklist.
  21107. AddToWorklist(TF.getNode());
  21108. for (const SDValue &Op : TF->ops())
  21109. AddToWorklist(Op.getNode());
  21110. AddToWorklist(STChain);
  21111. return true;
  21112. }
  21113. bool DAGCombiner::findBetterNeighborChains(StoreSDNode *St) {
  21114. if (OptLevel == CodeGenOpt::None)
  21115. return false;
  21116. const BaseIndexOffset BasePtr = BaseIndexOffset::match(St, DAG);
  21117. // We must have a base and an offset.
  21118. if (!BasePtr.getBase().getNode())
  21119. return false;
  21120. // Do not handle stores to undef base pointers.
  21121. if (BasePtr.getBase().isUndef())
  21122. return false;
  21123. // Directly improve a chain of disjoint stores starting at St.
  21124. if (parallelizeChainedStores(St))
  21125. return true;
  21126. // Improve St's Chain..
  21127. SDValue BetterChain = FindBetterChain(St, St->getChain());
  21128. if (St->getChain() != BetterChain) {
  21129. replaceStoreChain(St, BetterChain);
  21130. return true;
  21131. }
  21132. return false;
  21133. }
  21134. /// This is the entry point for the file.
  21135. void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis *AA,
  21136. CodeGenOpt::Level OptLevel) {
  21137. /// This is the main entry point to this class.
  21138. DAGCombiner(*this, AA, OptLevel).Run(Level);
  21139. }