DAGCombiner.cpp 398 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335
  1. //===-- DAGCombiner.cpp - Implement a DAG node combiner -------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This pass combines dag nodes to form fewer, simpler DAG nodes. It can be run
  11. // both before and after the DAG is legalized.
  12. //
  13. // This pass is not a substitute for the LLVM IR instcombine pass. This pass is
  14. // primarily intended to handle simplification opportunities that are implicit
  15. // in the LLVM IR and exposed by the various codegen lowering phases.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #define DEBUG_TYPE "dagcombine"
  19. #include "llvm/CodeGen/SelectionDAG.h"
  20. #include "llvm/ADT/SmallPtrSet.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/Analysis/AliasAnalysis.h"
  23. #include "llvm/CodeGen/MachineFrameInfo.h"
  24. #include "llvm/CodeGen/MachineFunction.h"
  25. #include "llvm/IR/DataLayout.h"
  26. #include "llvm/IR/DerivedTypes.h"
  27. #include "llvm/IR/Function.h"
  28. #include "llvm/IR/LLVMContext.h"
  29. #include "llvm/Support/CommandLine.h"
  30. #include "llvm/Support/Debug.h"
  31. #include "llvm/Support/ErrorHandling.h"
  32. #include "llvm/Support/MathExtras.h"
  33. #include "llvm/Support/raw_ostream.h"
  34. #include "llvm/Target/TargetLowering.h"
  35. #include "llvm/Target/TargetMachine.h"
  36. #include "llvm/Target/TargetOptions.h"
  37. #include <algorithm>
  38. using namespace llvm;
  39. STATISTIC(NodesCombined , "Number of dag nodes combined");
  40. STATISTIC(PreIndexedNodes , "Number of pre-indexed nodes created");
  41. STATISTIC(PostIndexedNodes, "Number of post-indexed nodes created");
  42. STATISTIC(OpsNarrowed , "Number of load/op/store narrowed");
  43. STATISTIC(LdStFP2Int , "Number of fp load/store pairs transformed to int");
  44. namespace {
  45. static cl::opt<bool>
  46. CombinerAA("combiner-alias-analysis", cl::Hidden,
  47. cl::desc("Turn on alias analysis during testing"));
  48. static cl::opt<bool>
  49. CombinerGlobalAA("combiner-global-alias-analysis", cl::Hidden,
  50. cl::desc("Include global information in alias analysis"));
  51. //------------------------------ DAGCombiner ---------------------------------//
  52. class DAGCombiner {
  53. SelectionDAG &DAG;
  54. const TargetLowering &TLI;
  55. CombineLevel Level;
  56. CodeGenOpt::Level OptLevel;
  57. bool LegalOperations;
  58. bool LegalTypes;
  59. // Worklist of all of the nodes that need to be simplified.
  60. //
  61. // This has the semantics that when adding to the worklist,
  62. // the item added must be next to be processed. It should
  63. // also only appear once. The naive approach to this takes
  64. // linear time.
  65. //
  66. // To reduce the insert/remove time to logarithmic, we use
  67. // a set and a vector to maintain our worklist.
  68. //
  69. // The set contains the items on the worklist, but does not
  70. // maintain the order they should be visited.
  71. //
  72. // The vector maintains the order nodes should be visited, but may
  73. // contain duplicate or removed nodes. When choosing a node to
  74. // visit, we pop off the order stack until we find an item that is
  75. // also in the contents set. All operations are O(log N).
  76. SmallPtrSet<SDNode*, 64> WorkListContents;
  77. SmallVector<SDNode*, 64> WorkListOrder;
  78. // AA - Used for DAG load/store alias analysis.
  79. AliasAnalysis &AA;
  80. /// AddUsersToWorkList - When an instruction is simplified, add all users of
  81. /// the instruction to the work lists because they might get more simplified
  82. /// now.
  83. ///
  84. void AddUsersToWorkList(SDNode *N) {
  85. for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
  86. UI != UE; ++UI)
  87. AddToWorkList(*UI);
  88. }
  89. /// visit - call the node-specific routine that knows how to fold each
  90. /// particular type of node.
  91. SDValue visit(SDNode *N);
  92. public:
  93. /// AddToWorkList - Add to the work list making sure its instance is at the
  94. /// back (next to be processed.)
  95. void AddToWorkList(SDNode *N) {
  96. WorkListContents.insert(N);
  97. WorkListOrder.push_back(N);
  98. }
  99. /// removeFromWorkList - remove all instances of N from the worklist.
  100. ///
  101. void removeFromWorkList(SDNode *N) {
  102. WorkListContents.erase(N);
  103. }
  104. SDValue CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
  105. bool AddTo = true);
  106. SDValue CombineTo(SDNode *N, SDValue Res, bool AddTo = true) {
  107. return CombineTo(N, &Res, 1, AddTo);
  108. }
  109. SDValue CombineTo(SDNode *N, SDValue Res0, SDValue Res1,
  110. bool AddTo = true) {
  111. SDValue To[] = { Res0, Res1 };
  112. return CombineTo(N, To, 2, AddTo);
  113. }
  114. void CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO);
  115. private:
  116. /// SimplifyDemandedBits - Check the specified integer node value to see if
  117. /// it can be simplified or if things it uses can be simplified by bit
  118. /// propagation. If so, return true.
  119. bool SimplifyDemandedBits(SDValue Op) {
  120. unsigned BitWidth = Op.getValueType().getScalarType().getSizeInBits();
  121. APInt Demanded = APInt::getAllOnesValue(BitWidth);
  122. return SimplifyDemandedBits(Op, Demanded);
  123. }
  124. bool SimplifyDemandedBits(SDValue Op, const APInt &Demanded);
  125. bool CombineToPreIndexedLoadStore(SDNode *N);
  126. bool CombineToPostIndexedLoadStore(SDNode *N);
  127. void ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad);
  128. SDValue PromoteOperand(SDValue Op, EVT PVT, bool &Replace);
  129. SDValue SExtPromoteOperand(SDValue Op, EVT PVT);
  130. SDValue ZExtPromoteOperand(SDValue Op, EVT PVT);
  131. SDValue PromoteIntBinOp(SDValue Op);
  132. SDValue PromoteIntShiftOp(SDValue Op);
  133. SDValue PromoteExtend(SDValue Op);
  134. bool PromoteLoad(SDValue Op);
  135. void ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
  136. SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
  137. ISD::NodeType ExtType);
  138. /// combine - call the node-specific routine that knows how to fold each
  139. /// particular type of node. If that doesn't do anything, try the
  140. /// target-specific DAG combines.
  141. SDValue combine(SDNode *N);
  142. // Visitation implementation - Implement dag node combining for different
  143. // node types. The semantics are as follows:
  144. // Return Value:
  145. // SDValue.getNode() == 0 - No change was made
  146. // SDValue.getNode() == N - N was replaced, is dead and has been handled.
  147. // otherwise - N should be replaced by the returned Operand.
  148. //
  149. SDValue visitTokenFactor(SDNode *N);
  150. SDValue visitMERGE_VALUES(SDNode *N);
  151. SDValue visitADD(SDNode *N);
  152. SDValue visitSUB(SDNode *N);
  153. SDValue visitADDC(SDNode *N);
  154. SDValue visitSUBC(SDNode *N);
  155. SDValue visitADDE(SDNode *N);
  156. SDValue visitSUBE(SDNode *N);
  157. SDValue visitMUL(SDNode *N);
  158. SDValue visitSDIV(SDNode *N);
  159. SDValue visitUDIV(SDNode *N);
  160. SDValue visitSREM(SDNode *N);
  161. SDValue visitUREM(SDNode *N);
  162. SDValue visitMULHU(SDNode *N);
  163. SDValue visitMULHS(SDNode *N);
  164. SDValue visitSMUL_LOHI(SDNode *N);
  165. SDValue visitUMUL_LOHI(SDNode *N);
  166. SDValue visitSMULO(SDNode *N);
  167. SDValue visitUMULO(SDNode *N);
  168. SDValue visitSDIVREM(SDNode *N);
  169. SDValue visitUDIVREM(SDNode *N);
  170. SDValue visitAND(SDNode *N);
  171. SDValue visitOR(SDNode *N);
  172. SDValue visitXOR(SDNode *N);
  173. SDValue SimplifyVBinOp(SDNode *N);
  174. SDValue SimplifyVUnaryOp(SDNode *N);
  175. SDValue visitSHL(SDNode *N);
  176. SDValue visitSRA(SDNode *N);
  177. SDValue visitSRL(SDNode *N);
  178. SDValue visitCTLZ(SDNode *N);
  179. SDValue visitCTLZ_ZERO_UNDEF(SDNode *N);
  180. SDValue visitCTTZ(SDNode *N);
  181. SDValue visitCTTZ_ZERO_UNDEF(SDNode *N);
  182. SDValue visitCTPOP(SDNode *N);
  183. SDValue visitSELECT(SDNode *N);
  184. SDValue visitVSELECT(SDNode *N);
  185. SDValue visitSELECT_CC(SDNode *N);
  186. SDValue visitSETCC(SDNode *N);
  187. SDValue visitSIGN_EXTEND(SDNode *N);
  188. SDValue visitZERO_EXTEND(SDNode *N);
  189. SDValue visitANY_EXTEND(SDNode *N);
  190. SDValue visitSIGN_EXTEND_INREG(SDNode *N);
  191. SDValue visitTRUNCATE(SDNode *N);
  192. SDValue visitBITCAST(SDNode *N);
  193. SDValue visitBUILD_PAIR(SDNode *N);
  194. SDValue visitFADD(SDNode *N);
  195. SDValue visitFSUB(SDNode *N);
  196. SDValue visitFMUL(SDNode *N);
  197. SDValue visitFMA(SDNode *N);
  198. SDValue visitFDIV(SDNode *N);
  199. SDValue visitFREM(SDNode *N);
  200. SDValue visitFCOPYSIGN(SDNode *N);
  201. SDValue visitSINT_TO_FP(SDNode *N);
  202. SDValue visitUINT_TO_FP(SDNode *N);
  203. SDValue visitFP_TO_SINT(SDNode *N);
  204. SDValue visitFP_TO_UINT(SDNode *N);
  205. SDValue visitFP_ROUND(SDNode *N);
  206. SDValue visitFP_ROUND_INREG(SDNode *N);
  207. SDValue visitFP_EXTEND(SDNode *N);
  208. SDValue visitFNEG(SDNode *N);
  209. SDValue visitFABS(SDNode *N);
  210. SDValue visitFCEIL(SDNode *N);
  211. SDValue visitFTRUNC(SDNode *N);
  212. SDValue visitFFLOOR(SDNode *N);
  213. SDValue visitBRCOND(SDNode *N);
  214. SDValue visitBR_CC(SDNode *N);
  215. SDValue visitLOAD(SDNode *N);
  216. SDValue visitSTORE(SDNode *N);
  217. SDValue visitINSERT_VECTOR_ELT(SDNode *N);
  218. SDValue visitEXTRACT_VECTOR_ELT(SDNode *N);
  219. SDValue visitBUILD_VECTOR(SDNode *N);
  220. SDValue visitCONCAT_VECTORS(SDNode *N);
  221. SDValue visitEXTRACT_SUBVECTOR(SDNode *N);
  222. SDValue visitVECTOR_SHUFFLE(SDNode *N);
  223. SDValue XformToShuffleWithZero(SDNode *N);
  224. SDValue ReassociateOps(unsigned Opc, DebugLoc DL, SDValue LHS, SDValue RHS);
  225. SDValue visitShiftByConstant(SDNode *N, unsigned Amt);
  226. bool SimplifySelectOps(SDNode *SELECT, SDValue LHS, SDValue RHS);
  227. SDValue SimplifyBinOpWithSameOpcodeHands(SDNode *N);
  228. SDValue SimplifySelect(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2);
  229. SDValue SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1, SDValue N2,
  230. SDValue N3, ISD::CondCode CC,
  231. bool NotExtCompare = false);
  232. SDValue SimplifySetCC(EVT VT, SDValue N0, SDValue N1, ISD::CondCode Cond,
  233. DebugLoc DL, bool foldBooleans = true);
  234. SDValue SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
  235. unsigned HiOp);
  236. SDValue CombineConsecutiveLoads(SDNode *N, EVT VT);
  237. SDValue ConstantFoldBITCASTofBUILD_VECTOR(SDNode *, EVT);
  238. SDValue BuildSDIV(SDNode *N);
  239. SDValue BuildUDIV(SDNode *N);
  240. SDValue MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
  241. bool DemandHighBits = true);
  242. SDValue MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1);
  243. SDNode *MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL);
  244. SDValue ReduceLoadWidth(SDNode *N);
  245. SDValue ReduceLoadOpStoreWidth(SDNode *N);
  246. SDValue TransformFPLoadStorePair(SDNode *N);
  247. SDValue reduceBuildVecExtToExtBuildVec(SDNode *N);
  248. SDValue reduceBuildVecConvertToConvertBuildVec(SDNode *N);
  249. SDValue GetDemandedBits(SDValue V, const APInt &Mask);
  250. /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
  251. /// looking for aliasing nodes and adding them to the Aliases vector.
  252. void GatherAllAliases(SDNode *N, SDValue OriginalChain,
  253. SmallVector<SDValue, 8> &Aliases);
  254. /// isAlias - Return true if there is any possibility that the two addresses
  255. /// overlap.
  256. bool isAlias(SDValue Ptr1, int64_t Size1,
  257. const Value *SrcValue1, int SrcValueOffset1,
  258. unsigned SrcValueAlign1,
  259. const MDNode *TBAAInfo1,
  260. SDValue Ptr2, int64_t Size2,
  261. const Value *SrcValue2, int SrcValueOffset2,
  262. unsigned SrcValueAlign2,
  263. const MDNode *TBAAInfo2) const;
  264. /// isAlias - Return true if there is any possibility that the two addresses
  265. /// overlap.
  266. bool isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1);
  267. /// FindAliasInfo - Extracts the relevant alias information from the memory
  268. /// node. Returns true if the operand was a load.
  269. bool FindAliasInfo(SDNode *N,
  270. SDValue &Ptr, int64_t &Size,
  271. const Value *&SrcValue, int &SrcValueOffset,
  272. unsigned &SrcValueAlignment,
  273. const MDNode *&TBAAInfo) const;
  274. /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes,
  275. /// looking for a better chain (aliasing node.)
  276. SDValue FindBetterChain(SDNode *N, SDValue Chain);
  277. /// Merge consecutive store operations into a wide store.
  278. /// This optimization uses wide integers or vectors when possible.
  279. /// \return True if some memory operations were changed.
  280. bool MergeConsecutiveStores(StoreSDNode *N);
  281. public:
  282. DAGCombiner(SelectionDAG &D, AliasAnalysis &A, CodeGenOpt::Level OL)
  283. : DAG(D), TLI(D.getTargetLoweringInfo()), Level(BeforeLegalizeTypes),
  284. OptLevel(OL), LegalOperations(false), LegalTypes(false), AA(A) {}
  285. /// Run - runs the dag combiner on all nodes in the work list
  286. void Run(CombineLevel AtLevel);
  287. SelectionDAG &getDAG() const { return DAG; }
  288. /// getShiftAmountTy - Returns a type large enough to hold any valid
  289. /// shift amount - before type legalization these can be huge.
  290. EVT getShiftAmountTy(EVT LHSTy) {
  291. return LegalTypes ? TLI.getShiftAmountTy(LHSTy) : TLI.getPointerTy();
  292. }
  293. /// isTypeLegal - This method returns true if we are running before type
  294. /// legalization or if the specified VT is legal.
  295. bool isTypeLegal(const EVT &VT) {
  296. if (!LegalTypes) return true;
  297. return TLI.isTypeLegal(VT);
  298. }
  299. /// getSetCCResultType - Convenience wrapper around
  300. /// TargetLowering::getSetCCResultType
  301. EVT getSetCCResultType(EVT VT) const {
  302. return TLI.getSetCCResultType(*DAG.getContext(), VT);
  303. }
  304. };
  305. }
  306. namespace {
  307. /// WorkListRemover - This class is a DAGUpdateListener that removes any deleted
  308. /// nodes from the worklist.
  309. class WorkListRemover : public SelectionDAG::DAGUpdateListener {
  310. DAGCombiner &DC;
  311. public:
  312. explicit WorkListRemover(DAGCombiner &dc)
  313. : SelectionDAG::DAGUpdateListener(dc.getDAG()), DC(dc) {}
  314. virtual void NodeDeleted(SDNode *N, SDNode *E) {
  315. DC.removeFromWorkList(N);
  316. }
  317. };
  318. }
  319. //===----------------------------------------------------------------------===//
  320. // TargetLowering::DAGCombinerInfo implementation
  321. //===----------------------------------------------------------------------===//
  322. void TargetLowering::DAGCombinerInfo::AddToWorklist(SDNode *N) {
  323. ((DAGCombiner*)DC)->AddToWorkList(N);
  324. }
  325. void TargetLowering::DAGCombinerInfo::RemoveFromWorklist(SDNode *N) {
  326. ((DAGCombiner*)DC)->removeFromWorkList(N);
  327. }
  328. SDValue TargetLowering::DAGCombinerInfo::
  329. CombineTo(SDNode *N, const std::vector<SDValue> &To, bool AddTo) {
  330. return ((DAGCombiner*)DC)->CombineTo(N, &To[0], To.size(), AddTo);
  331. }
  332. SDValue TargetLowering::DAGCombinerInfo::
  333. CombineTo(SDNode *N, SDValue Res, bool AddTo) {
  334. return ((DAGCombiner*)DC)->CombineTo(N, Res, AddTo);
  335. }
  336. SDValue TargetLowering::DAGCombinerInfo::
  337. CombineTo(SDNode *N, SDValue Res0, SDValue Res1, bool AddTo) {
  338. return ((DAGCombiner*)DC)->CombineTo(N, Res0, Res1, AddTo);
  339. }
  340. void TargetLowering::DAGCombinerInfo::
  341. CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
  342. return ((DAGCombiner*)DC)->CommitTargetLoweringOpt(TLO);
  343. }
  344. //===----------------------------------------------------------------------===//
  345. // Helper Functions
  346. //===----------------------------------------------------------------------===//
  347. /// isNegatibleForFree - Return 1 if we can compute the negated form of the
  348. /// specified expression for the same cost as the expression itself, or 2 if we
  349. /// can compute the negated form more cheaply than the expression itself.
  350. static char isNegatibleForFree(SDValue Op, bool LegalOperations,
  351. const TargetLowering &TLI,
  352. const TargetOptions *Options,
  353. unsigned Depth = 0) {
  354. // fneg is removable even if it has multiple uses.
  355. if (Op.getOpcode() == ISD::FNEG) return 2;
  356. // Don't allow anything with multiple uses.
  357. if (!Op.hasOneUse()) return 0;
  358. // Don't recurse exponentially.
  359. if (Depth > 6) return 0;
  360. switch (Op.getOpcode()) {
  361. default: return false;
  362. case ISD::ConstantFP:
  363. // Don't invert constant FP values after legalize. The negated constant
  364. // isn't necessarily legal.
  365. return LegalOperations ? 0 : 1;
  366. case ISD::FADD:
  367. // FIXME: determine better conditions for this xform.
  368. if (!Options->UnsafeFPMath) return 0;
  369. // After operation legalization, it might not be legal to create new FSUBs.
  370. if (LegalOperations &&
  371. !TLI.isOperationLegalOrCustom(ISD::FSUB, Op.getValueType()))
  372. return 0;
  373. // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
  374. if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
  375. Options, Depth + 1))
  376. return V;
  377. // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
  378. return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
  379. Depth + 1);
  380. case ISD::FSUB:
  381. // We can't turn -(A-B) into B-A when we honor signed zeros.
  382. if (!Options->UnsafeFPMath) return 0;
  383. // fold (fneg (fsub A, B)) -> (fsub B, A)
  384. return 1;
  385. case ISD::FMUL:
  386. case ISD::FDIV:
  387. if (Options->HonorSignDependentRoundingFPMath()) return 0;
  388. // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y) or (fmul X, (fneg Y))
  389. if (char V = isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI,
  390. Options, Depth + 1))
  391. return V;
  392. return isNegatibleForFree(Op.getOperand(1), LegalOperations, TLI, Options,
  393. Depth + 1);
  394. case ISD::FP_EXTEND:
  395. case ISD::FP_ROUND:
  396. case ISD::FSIN:
  397. return isNegatibleForFree(Op.getOperand(0), LegalOperations, TLI, Options,
  398. Depth + 1);
  399. }
  400. }
  401. /// GetNegatedExpression - If isNegatibleForFree returns true, this function
  402. /// returns the newly negated expression.
  403. static SDValue GetNegatedExpression(SDValue Op, SelectionDAG &DAG,
  404. bool LegalOperations, unsigned Depth = 0) {
  405. // fneg is removable even if it has multiple uses.
  406. if (Op.getOpcode() == ISD::FNEG) return Op.getOperand(0);
  407. // Don't allow anything with multiple uses.
  408. assert(Op.hasOneUse() && "Unknown reuse!");
  409. assert(Depth <= 6 && "GetNegatedExpression doesn't match isNegatibleForFree");
  410. switch (Op.getOpcode()) {
  411. default: llvm_unreachable("Unknown code");
  412. case ISD::ConstantFP: {
  413. APFloat V = cast<ConstantFPSDNode>(Op)->getValueAPF();
  414. V.changeSign();
  415. return DAG.getConstantFP(V, Op.getValueType());
  416. }
  417. case ISD::FADD:
  418. // FIXME: determine better conditions for this xform.
  419. assert(DAG.getTarget().Options.UnsafeFPMath);
  420. // fold (fneg (fadd A, B)) -> (fsub (fneg A), B)
  421. if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
  422. DAG.getTargetLoweringInfo(),
  423. &DAG.getTarget().Options, Depth+1))
  424. return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
  425. GetNegatedExpression(Op.getOperand(0), DAG,
  426. LegalOperations, Depth+1),
  427. Op.getOperand(1));
  428. // fold (fneg (fadd A, B)) -> (fsub (fneg B), A)
  429. return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
  430. GetNegatedExpression(Op.getOperand(1), DAG,
  431. LegalOperations, Depth+1),
  432. Op.getOperand(0));
  433. case ISD::FSUB:
  434. // We can't turn -(A-B) into B-A when we honor signed zeros.
  435. assert(DAG.getTarget().Options.UnsafeFPMath);
  436. // fold (fneg (fsub 0, B)) -> B
  437. if (ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(Op.getOperand(0)))
  438. if (N0CFP->getValueAPF().isZero())
  439. return Op.getOperand(1);
  440. // fold (fneg (fsub A, B)) -> (fsub B, A)
  441. return DAG.getNode(ISD::FSUB, Op.getDebugLoc(), Op.getValueType(),
  442. Op.getOperand(1), Op.getOperand(0));
  443. case ISD::FMUL:
  444. case ISD::FDIV:
  445. assert(!DAG.getTarget().Options.HonorSignDependentRoundingFPMath());
  446. // fold (fneg (fmul X, Y)) -> (fmul (fneg X), Y)
  447. if (isNegatibleForFree(Op.getOperand(0), LegalOperations,
  448. DAG.getTargetLoweringInfo(),
  449. &DAG.getTarget().Options, Depth+1))
  450. return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
  451. GetNegatedExpression(Op.getOperand(0), DAG,
  452. LegalOperations, Depth+1),
  453. Op.getOperand(1));
  454. // fold (fneg (fmul X, Y)) -> (fmul X, (fneg Y))
  455. return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
  456. Op.getOperand(0),
  457. GetNegatedExpression(Op.getOperand(1), DAG,
  458. LegalOperations, Depth+1));
  459. case ISD::FP_EXTEND:
  460. case ISD::FSIN:
  461. return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), Op.getValueType(),
  462. GetNegatedExpression(Op.getOperand(0), DAG,
  463. LegalOperations, Depth+1));
  464. case ISD::FP_ROUND:
  465. return DAG.getNode(ISD::FP_ROUND, Op.getDebugLoc(), Op.getValueType(),
  466. GetNegatedExpression(Op.getOperand(0), DAG,
  467. LegalOperations, Depth+1),
  468. Op.getOperand(1));
  469. }
  470. }
  471. // isSetCCEquivalent - Return true if this node is a setcc, or is a select_cc
  472. // that selects between the values 1 and 0, making it equivalent to a setcc.
  473. // Also, set the incoming LHS, RHS, and CC references to the appropriate
  474. // nodes based on the type of node we are checking. This simplifies life a
  475. // bit for the callers.
  476. static bool isSetCCEquivalent(SDValue N, SDValue &LHS, SDValue &RHS,
  477. SDValue &CC) {
  478. if (N.getOpcode() == ISD::SETCC) {
  479. LHS = N.getOperand(0);
  480. RHS = N.getOperand(1);
  481. CC = N.getOperand(2);
  482. return true;
  483. }
  484. if (N.getOpcode() == ISD::SELECT_CC &&
  485. N.getOperand(2).getOpcode() == ISD::Constant &&
  486. N.getOperand(3).getOpcode() == ISD::Constant &&
  487. cast<ConstantSDNode>(N.getOperand(2))->getAPIntValue() == 1 &&
  488. cast<ConstantSDNode>(N.getOperand(3))->isNullValue()) {
  489. LHS = N.getOperand(0);
  490. RHS = N.getOperand(1);
  491. CC = N.getOperand(4);
  492. return true;
  493. }
  494. return false;
  495. }
  496. // isOneUseSetCC - Return true if this is a SetCC-equivalent operation with only
  497. // one use. If this is true, it allows the users to invert the operation for
  498. // free when it is profitable to do so.
  499. static bool isOneUseSetCC(SDValue N) {
  500. SDValue N0, N1, N2;
  501. if (isSetCCEquivalent(N, N0, N1, N2) && N.getNode()->hasOneUse())
  502. return true;
  503. return false;
  504. }
  505. SDValue DAGCombiner::ReassociateOps(unsigned Opc, DebugLoc DL,
  506. SDValue N0, SDValue N1) {
  507. EVT VT = N0.getValueType();
  508. if (N0.getOpcode() == Opc && isa<ConstantSDNode>(N0.getOperand(1))) {
  509. if (isa<ConstantSDNode>(N1)) {
  510. // reassoc. (op (op x, c1), c2) -> (op x, (op c1, c2))
  511. SDValue OpNode =
  512. DAG.FoldConstantArithmetic(Opc, VT,
  513. cast<ConstantSDNode>(N0.getOperand(1)),
  514. cast<ConstantSDNode>(N1));
  515. return DAG.getNode(Opc, DL, VT, N0.getOperand(0), OpNode);
  516. }
  517. if (N0.hasOneUse()) {
  518. // reassoc. (op (op x, c1), y) -> (op (op x, y), c1) iff x+c1 has one use
  519. SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
  520. N0.getOperand(0), N1);
  521. AddToWorkList(OpNode.getNode());
  522. return DAG.getNode(Opc, DL, VT, OpNode, N0.getOperand(1));
  523. }
  524. }
  525. if (N1.getOpcode() == Opc && isa<ConstantSDNode>(N1.getOperand(1))) {
  526. if (isa<ConstantSDNode>(N0)) {
  527. // reassoc. (op c2, (op x, c1)) -> (op x, (op c1, c2))
  528. SDValue OpNode =
  529. DAG.FoldConstantArithmetic(Opc, VT,
  530. cast<ConstantSDNode>(N1.getOperand(1)),
  531. cast<ConstantSDNode>(N0));
  532. return DAG.getNode(Opc, DL, VT, N1.getOperand(0), OpNode);
  533. }
  534. if (N1.hasOneUse()) {
  535. // reassoc. (op y, (op x, c1)) -> (op (op x, y), c1) iff x+c1 has one use
  536. SDValue OpNode = DAG.getNode(Opc, N0.getDebugLoc(), VT,
  537. N1.getOperand(0), N0);
  538. AddToWorkList(OpNode.getNode());
  539. return DAG.getNode(Opc, DL, VT, OpNode, N1.getOperand(1));
  540. }
  541. }
  542. return SDValue();
  543. }
  544. SDValue DAGCombiner::CombineTo(SDNode *N, const SDValue *To, unsigned NumTo,
  545. bool AddTo) {
  546. assert(N->getNumValues() == NumTo && "Broken CombineTo call!");
  547. ++NodesCombined;
  548. DEBUG(dbgs() << "\nReplacing.1 ";
  549. N->dump(&DAG);
  550. dbgs() << "\nWith: ";
  551. To[0].getNode()->dump(&DAG);
  552. dbgs() << " and " << NumTo-1 << " other values\n";
  553. for (unsigned i = 0, e = NumTo; i != e; ++i)
  554. assert((!To[i].getNode() ||
  555. N->getValueType(i) == To[i].getValueType()) &&
  556. "Cannot combine value to value of different type!"));
  557. WorkListRemover DeadNodes(*this);
  558. DAG.ReplaceAllUsesWith(N, To);
  559. if (AddTo) {
  560. // Push the new nodes and any users onto the worklist
  561. for (unsigned i = 0, e = NumTo; i != e; ++i) {
  562. if (To[i].getNode()) {
  563. AddToWorkList(To[i].getNode());
  564. AddUsersToWorkList(To[i].getNode());
  565. }
  566. }
  567. }
  568. // Finally, if the node is now dead, remove it from the graph. The node
  569. // may not be dead if the replacement process recursively simplified to
  570. // something else needing this node.
  571. if (N->use_empty()) {
  572. // Nodes can be reintroduced into the worklist. Make sure we do not
  573. // process a node that has been replaced.
  574. removeFromWorkList(N);
  575. // Finally, since the node is now dead, remove it from the graph.
  576. DAG.DeleteNode(N);
  577. }
  578. return SDValue(N, 0);
  579. }
  580. void DAGCombiner::
  581. CommitTargetLoweringOpt(const TargetLowering::TargetLoweringOpt &TLO) {
  582. // Replace all uses. If any nodes become isomorphic to other nodes and
  583. // are deleted, make sure to remove them from our worklist.
  584. WorkListRemover DeadNodes(*this);
  585. DAG.ReplaceAllUsesOfValueWith(TLO.Old, TLO.New);
  586. // Push the new node and any (possibly new) users onto the worklist.
  587. AddToWorkList(TLO.New.getNode());
  588. AddUsersToWorkList(TLO.New.getNode());
  589. // Finally, if the node is now dead, remove it from the graph. The node
  590. // may not be dead if the replacement process recursively simplified to
  591. // something else needing this node.
  592. if (TLO.Old.getNode()->use_empty()) {
  593. removeFromWorkList(TLO.Old.getNode());
  594. // If the operands of this node are only used by the node, they will now
  595. // be dead. Make sure to visit them first to delete dead nodes early.
  596. for (unsigned i = 0, e = TLO.Old.getNode()->getNumOperands(); i != e; ++i)
  597. if (TLO.Old.getNode()->getOperand(i).getNode()->hasOneUse())
  598. AddToWorkList(TLO.Old.getNode()->getOperand(i).getNode());
  599. DAG.DeleteNode(TLO.Old.getNode());
  600. }
  601. }
  602. /// SimplifyDemandedBits - Check the specified integer node value to see if
  603. /// it can be simplified or if things it uses can be simplified by bit
  604. /// propagation. If so, return true.
  605. bool DAGCombiner::SimplifyDemandedBits(SDValue Op, const APInt &Demanded) {
  606. TargetLowering::TargetLoweringOpt TLO(DAG, LegalTypes, LegalOperations);
  607. APInt KnownZero, KnownOne;
  608. if (!TLI.SimplifyDemandedBits(Op, Demanded, KnownZero, KnownOne, TLO))
  609. return false;
  610. // Revisit the node.
  611. AddToWorkList(Op.getNode());
  612. // Replace the old value with the new one.
  613. ++NodesCombined;
  614. DEBUG(dbgs() << "\nReplacing.2 ";
  615. TLO.Old.getNode()->dump(&DAG);
  616. dbgs() << "\nWith: ";
  617. TLO.New.getNode()->dump(&DAG);
  618. dbgs() << '\n');
  619. CommitTargetLoweringOpt(TLO);
  620. return true;
  621. }
  622. void DAGCombiner::ReplaceLoadWithPromotedLoad(SDNode *Load, SDNode *ExtLoad) {
  623. DebugLoc dl = Load->getDebugLoc();
  624. EVT VT = Load->getValueType(0);
  625. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, dl, VT, SDValue(ExtLoad, 0));
  626. DEBUG(dbgs() << "\nReplacing.9 ";
  627. Load->dump(&DAG);
  628. dbgs() << "\nWith: ";
  629. Trunc.getNode()->dump(&DAG);
  630. dbgs() << '\n');
  631. WorkListRemover DeadNodes(*this);
  632. DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 0), Trunc);
  633. DAG.ReplaceAllUsesOfValueWith(SDValue(Load, 1), SDValue(ExtLoad, 1));
  634. removeFromWorkList(Load);
  635. DAG.DeleteNode(Load);
  636. AddToWorkList(Trunc.getNode());
  637. }
  638. SDValue DAGCombiner::PromoteOperand(SDValue Op, EVT PVT, bool &Replace) {
  639. Replace = false;
  640. DebugLoc dl = Op.getDebugLoc();
  641. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Op)) {
  642. EVT MemVT = LD->getMemoryVT();
  643. ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
  644. ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
  645. : ISD::EXTLOAD)
  646. : LD->getExtensionType();
  647. Replace = true;
  648. return DAG.getExtLoad(ExtType, dl, PVT,
  649. LD->getChain(), LD->getBasePtr(),
  650. LD->getPointerInfo(),
  651. MemVT, LD->isVolatile(),
  652. LD->isNonTemporal(), LD->getAlignment());
  653. }
  654. unsigned Opc = Op.getOpcode();
  655. switch (Opc) {
  656. default: break;
  657. case ISD::AssertSext:
  658. return DAG.getNode(ISD::AssertSext, dl, PVT,
  659. SExtPromoteOperand(Op.getOperand(0), PVT),
  660. Op.getOperand(1));
  661. case ISD::AssertZext:
  662. return DAG.getNode(ISD::AssertZext, dl, PVT,
  663. ZExtPromoteOperand(Op.getOperand(0), PVT),
  664. Op.getOperand(1));
  665. case ISD::Constant: {
  666. unsigned ExtOpc =
  667. Op.getValueType().isByteSized() ? ISD::SIGN_EXTEND : ISD::ZERO_EXTEND;
  668. return DAG.getNode(ExtOpc, dl, PVT, Op);
  669. }
  670. }
  671. if (!TLI.isOperationLegal(ISD::ANY_EXTEND, PVT))
  672. return SDValue();
  673. return DAG.getNode(ISD::ANY_EXTEND, dl, PVT, Op);
  674. }
  675. SDValue DAGCombiner::SExtPromoteOperand(SDValue Op, EVT PVT) {
  676. if (!TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, PVT))
  677. return SDValue();
  678. EVT OldVT = Op.getValueType();
  679. DebugLoc dl = Op.getDebugLoc();
  680. bool Replace = false;
  681. SDValue NewOp = PromoteOperand(Op, PVT, Replace);
  682. if (NewOp.getNode() == 0)
  683. return SDValue();
  684. AddToWorkList(NewOp.getNode());
  685. if (Replace)
  686. ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
  687. return DAG.getNode(ISD::SIGN_EXTEND_INREG, dl, NewOp.getValueType(), NewOp,
  688. DAG.getValueType(OldVT));
  689. }
  690. SDValue DAGCombiner::ZExtPromoteOperand(SDValue Op, EVT PVT) {
  691. EVT OldVT = Op.getValueType();
  692. DebugLoc dl = Op.getDebugLoc();
  693. bool Replace = false;
  694. SDValue NewOp = PromoteOperand(Op, PVT, Replace);
  695. if (NewOp.getNode() == 0)
  696. return SDValue();
  697. AddToWorkList(NewOp.getNode());
  698. if (Replace)
  699. ReplaceLoadWithPromotedLoad(Op.getNode(), NewOp.getNode());
  700. return DAG.getZeroExtendInReg(NewOp, dl, OldVT);
  701. }
  702. /// PromoteIntBinOp - Promote the specified integer binary operation if the
  703. /// target indicates it is beneficial. e.g. On x86, it's usually better to
  704. /// promote i16 operations to i32 since i16 instructions are longer.
  705. SDValue DAGCombiner::PromoteIntBinOp(SDValue Op) {
  706. if (!LegalOperations)
  707. return SDValue();
  708. EVT VT = Op.getValueType();
  709. if (VT.isVector() || !VT.isInteger())
  710. return SDValue();
  711. // If operation type is 'undesirable', e.g. i16 on x86, consider
  712. // promoting it.
  713. unsigned Opc = Op.getOpcode();
  714. if (TLI.isTypeDesirableForOp(Opc, VT))
  715. return SDValue();
  716. EVT PVT = VT;
  717. // Consult target whether it is a good idea to promote this operation and
  718. // what's the right type to promote it to.
  719. if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
  720. assert(PVT != VT && "Don't know what type to promote to!");
  721. bool Replace0 = false;
  722. SDValue N0 = Op.getOperand(0);
  723. SDValue NN0 = PromoteOperand(N0, PVT, Replace0);
  724. if (NN0.getNode() == 0)
  725. return SDValue();
  726. bool Replace1 = false;
  727. SDValue N1 = Op.getOperand(1);
  728. SDValue NN1;
  729. if (N0 == N1)
  730. NN1 = NN0;
  731. else {
  732. NN1 = PromoteOperand(N1, PVT, Replace1);
  733. if (NN1.getNode() == 0)
  734. return SDValue();
  735. }
  736. AddToWorkList(NN0.getNode());
  737. if (NN1.getNode())
  738. AddToWorkList(NN1.getNode());
  739. if (Replace0)
  740. ReplaceLoadWithPromotedLoad(N0.getNode(), NN0.getNode());
  741. if (Replace1)
  742. ReplaceLoadWithPromotedLoad(N1.getNode(), NN1.getNode());
  743. DEBUG(dbgs() << "\nPromoting ";
  744. Op.getNode()->dump(&DAG));
  745. DebugLoc dl = Op.getDebugLoc();
  746. return DAG.getNode(ISD::TRUNCATE, dl, VT,
  747. DAG.getNode(Opc, dl, PVT, NN0, NN1));
  748. }
  749. return SDValue();
  750. }
  751. /// PromoteIntShiftOp - Promote the specified integer shift operation if the
  752. /// target indicates it is beneficial. e.g. On x86, it's usually better to
  753. /// promote i16 operations to i32 since i16 instructions are longer.
  754. SDValue DAGCombiner::PromoteIntShiftOp(SDValue Op) {
  755. if (!LegalOperations)
  756. return SDValue();
  757. EVT VT = Op.getValueType();
  758. if (VT.isVector() || !VT.isInteger())
  759. return SDValue();
  760. // If operation type is 'undesirable', e.g. i16 on x86, consider
  761. // promoting it.
  762. unsigned Opc = Op.getOpcode();
  763. if (TLI.isTypeDesirableForOp(Opc, VT))
  764. return SDValue();
  765. EVT PVT = VT;
  766. // Consult target whether it is a good idea to promote this operation and
  767. // what's the right type to promote it to.
  768. if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
  769. assert(PVT != VT && "Don't know what type to promote to!");
  770. bool Replace = false;
  771. SDValue N0 = Op.getOperand(0);
  772. if (Opc == ISD::SRA)
  773. N0 = SExtPromoteOperand(Op.getOperand(0), PVT);
  774. else if (Opc == ISD::SRL)
  775. N0 = ZExtPromoteOperand(Op.getOperand(0), PVT);
  776. else
  777. N0 = PromoteOperand(N0, PVT, Replace);
  778. if (N0.getNode() == 0)
  779. return SDValue();
  780. AddToWorkList(N0.getNode());
  781. if (Replace)
  782. ReplaceLoadWithPromotedLoad(Op.getOperand(0).getNode(), N0.getNode());
  783. DEBUG(dbgs() << "\nPromoting ";
  784. Op.getNode()->dump(&DAG));
  785. DebugLoc dl = Op.getDebugLoc();
  786. return DAG.getNode(ISD::TRUNCATE, dl, VT,
  787. DAG.getNode(Opc, dl, PVT, N0, Op.getOperand(1)));
  788. }
  789. return SDValue();
  790. }
  791. SDValue DAGCombiner::PromoteExtend(SDValue Op) {
  792. if (!LegalOperations)
  793. return SDValue();
  794. EVT VT = Op.getValueType();
  795. if (VT.isVector() || !VT.isInteger())
  796. return SDValue();
  797. // If operation type is 'undesirable', e.g. i16 on x86, consider
  798. // promoting it.
  799. unsigned Opc = Op.getOpcode();
  800. if (TLI.isTypeDesirableForOp(Opc, VT))
  801. return SDValue();
  802. EVT PVT = VT;
  803. // Consult target whether it is a good idea to promote this operation and
  804. // what's the right type to promote it to.
  805. if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
  806. assert(PVT != VT && "Don't know what type to promote to!");
  807. // fold (aext (aext x)) -> (aext x)
  808. // fold (aext (zext x)) -> (zext x)
  809. // fold (aext (sext x)) -> (sext x)
  810. DEBUG(dbgs() << "\nPromoting ";
  811. Op.getNode()->dump(&DAG));
  812. return DAG.getNode(Op.getOpcode(), Op.getDebugLoc(), VT, Op.getOperand(0));
  813. }
  814. return SDValue();
  815. }
  816. bool DAGCombiner::PromoteLoad(SDValue Op) {
  817. if (!LegalOperations)
  818. return false;
  819. EVT VT = Op.getValueType();
  820. if (VT.isVector() || !VT.isInteger())
  821. return false;
  822. // If operation type is 'undesirable', e.g. i16 on x86, consider
  823. // promoting it.
  824. unsigned Opc = Op.getOpcode();
  825. if (TLI.isTypeDesirableForOp(Opc, VT))
  826. return false;
  827. EVT PVT = VT;
  828. // Consult target whether it is a good idea to promote this operation and
  829. // what's the right type to promote it to.
  830. if (TLI.IsDesirableToPromoteOp(Op, PVT)) {
  831. assert(PVT != VT && "Don't know what type to promote to!");
  832. DebugLoc dl = Op.getDebugLoc();
  833. SDNode *N = Op.getNode();
  834. LoadSDNode *LD = cast<LoadSDNode>(N);
  835. EVT MemVT = LD->getMemoryVT();
  836. ISD::LoadExtType ExtType = ISD::isNON_EXTLoad(LD)
  837. ? (TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT) ? ISD::ZEXTLOAD
  838. : ISD::EXTLOAD)
  839. : LD->getExtensionType();
  840. SDValue NewLD = DAG.getExtLoad(ExtType, dl, PVT,
  841. LD->getChain(), LD->getBasePtr(),
  842. LD->getPointerInfo(),
  843. MemVT, LD->isVolatile(),
  844. LD->isNonTemporal(), LD->getAlignment());
  845. SDValue Result = DAG.getNode(ISD::TRUNCATE, dl, VT, NewLD);
  846. DEBUG(dbgs() << "\nPromoting ";
  847. N->dump(&DAG);
  848. dbgs() << "\nTo: ";
  849. Result.getNode()->dump(&DAG);
  850. dbgs() << '\n');
  851. WorkListRemover DeadNodes(*this);
  852. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result);
  853. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), NewLD.getValue(1));
  854. removeFromWorkList(N);
  855. DAG.DeleteNode(N);
  856. AddToWorkList(Result.getNode());
  857. return true;
  858. }
  859. return false;
  860. }
  861. //===----------------------------------------------------------------------===//
  862. // Main DAG Combiner implementation
  863. //===----------------------------------------------------------------------===//
  864. void DAGCombiner::Run(CombineLevel AtLevel) {
  865. // set the instance variables, so that the various visit routines may use it.
  866. Level = AtLevel;
  867. LegalOperations = Level >= AfterLegalizeVectorOps;
  868. LegalTypes = Level >= AfterLegalizeTypes;
  869. // Add all the dag nodes to the worklist.
  870. for (SelectionDAG::allnodes_iterator I = DAG.allnodes_begin(),
  871. E = DAG.allnodes_end(); I != E; ++I)
  872. AddToWorkList(I);
  873. // Create a dummy node (which is not added to allnodes), that adds a reference
  874. // to the root node, preventing it from being deleted, and tracking any
  875. // changes of the root.
  876. HandleSDNode Dummy(DAG.getRoot());
  877. // The root of the dag may dangle to deleted nodes until the dag combiner is
  878. // done. Set it to null to avoid confusion.
  879. DAG.setRoot(SDValue());
  880. // while the worklist isn't empty, find a node and
  881. // try and combine it.
  882. while (!WorkListContents.empty()) {
  883. SDNode *N;
  884. // The WorkListOrder holds the SDNodes in order, but it may contain duplicates.
  885. // In order to avoid a linear scan, we use a set (O(log N)) to hold what the
  886. // worklist *should* contain, and check the node we want to visit is should
  887. // actually be visited.
  888. do {
  889. N = WorkListOrder.pop_back_val();
  890. } while (!WorkListContents.erase(N));
  891. // If N has no uses, it is dead. Make sure to revisit all N's operands once
  892. // N is deleted from the DAG, since they too may now be dead or may have a
  893. // reduced number of uses, allowing other xforms.
  894. if (N->use_empty() && N != &Dummy) {
  895. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
  896. AddToWorkList(N->getOperand(i).getNode());
  897. DAG.DeleteNode(N);
  898. continue;
  899. }
  900. SDValue RV = combine(N);
  901. if (RV.getNode() == 0)
  902. continue;
  903. ++NodesCombined;
  904. // If we get back the same node we passed in, rather than a new node or
  905. // zero, we know that the node must have defined multiple values and
  906. // CombineTo was used. Since CombineTo takes care of the worklist
  907. // mechanics for us, we have no work to do in this case.
  908. if (RV.getNode() == N)
  909. continue;
  910. assert(N->getOpcode() != ISD::DELETED_NODE &&
  911. RV.getNode()->getOpcode() != ISD::DELETED_NODE &&
  912. "Node was deleted but visit returned new node!");
  913. DEBUG(dbgs() << "\nReplacing.3 ";
  914. N->dump(&DAG);
  915. dbgs() << "\nWith: ";
  916. RV.getNode()->dump(&DAG);
  917. dbgs() << '\n');
  918. // Transfer debug value.
  919. DAG.TransferDbgValues(SDValue(N, 0), RV);
  920. WorkListRemover DeadNodes(*this);
  921. if (N->getNumValues() == RV.getNode()->getNumValues())
  922. DAG.ReplaceAllUsesWith(N, RV.getNode());
  923. else {
  924. assert(N->getValueType(0) == RV.getValueType() &&
  925. N->getNumValues() == 1 && "Type mismatch");
  926. SDValue OpV = RV;
  927. DAG.ReplaceAllUsesWith(N, &OpV);
  928. }
  929. // Push the new node and any users onto the worklist
  930. AddToWorkList(RV.getNode());
  931. AddUsersToWorkList(RV.getNode());
  932. // Add any uses of the old node to the worklist in case this node is the
  933. // last one that uses them. They may become dead after this node is
  934. // deleted.
  935. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
  936. AddToWorkList(N->getOperand(i).getNode());
  937. // Finally, if the node is now dead, remove it from the graph. The node
  938. // may not be dead if the replacement process recursively simplified to
  939. // something else needing this node.
  940. if (N->use_empty()) {
  941. // Nodes can be reintroduced into the worklist. Make sure we do not
  942. // process a node that has been replaced.
  943. removeFromWorkList(N);
  944. // Finally, since the node is now dead, remove it from the graph.
  945. DAG.DeleteNode(N);
  946. }
  947. }
  948. // If the root changed (e.g. it was a dead load, update the root).
  949. DAG.setRoot(Dummy.getValue());
  950. DAG.RemoveDeadNodes();
  951. }
  952. SDValue DAGCombiner::visit(SDNode *N) {
  953. switch (N->getOpcode()) {
  954. default: break;
  955. case ISD::TokenFactor: return visitTokenFactor(N);
  956. case ISD::MERGE_VALUES: return visitMERGE_VALUES(N);
  957. case ISD::ADD: return visitADD(N);
  958. case ISD::SUB: return visitSUB(N);
  959. case ISD::ADDC: return visitADDC(N);
  960. case ISD::SUBC: return visitSUBC(N);
  961. case ISD::ADDE: return visitADDE(N);
  962. case ISD::SUBE: return visitSUBE(N);
  963. case ISD::MUL: return visitMUL(N);
  964. case ISD::SDIV: return visitSDIV(N);
  965. case ISD::UDIV: return visitUDIV(N);
  966. case ISD::SREM: return visitSREM(N);
  967. case ISD::UREM: return visitUREM(N);
  968. case ISD::MULHU: return visitMULHU(N);
  969. case ISD::MULHS: return visitMULHS(N);
  970. case ISD::SMUL_LOHI: return visitSMUL_LOHI(N);
  971. case ISD::UMUL_LOHI: return visitUMUL_LOHI(N);
  972. case ISD::SMULO: return visitSMULO(N);
  973. case ISD::UMULO: return visitUMULO(N);
  974. case ISD::SDIVREM: return visitSDIVREM(N);
  975. case ISD::UDIVREM: return visitUDIVREM(N);
  976. case ISD::AND: return visitAND(N);
  977. case ISD::OR: return visitOR(N);
  978. case ISD::XOR: return visitXOR(N);
  979. case ISD::SHL: return visitSHL(N);
  980. case ISD::SRA: return visitSRA(N);
  981. case ISD::SRL: return visitSRL(N);
  982. case ISD::CTLZ: return visitCTLZ(N);
  983. case ISD::CTLZ_ZERO_UNDEF: return visitCTLZ_ZERO_UNDEF(N);
  984. case ISD::CTTZ: return visitCTTZ(N);
  985. case ISD::CTTZ_ZERO_UNDEF: return visitCTTZ_ZERO_UNDEF(N);
  986. case ISD::CTPOP: return visitCTPOP(N);
  987. case ISD::SELECT: return visitSELECT(N);
  988. case ISD::VSELECT: return visitVSELECT(N);
  989. case ISD::SELECT_CC: return visitSELECT_CC(N);
  990. case ISD::SETCC: return visitSETCC(N);
  991. case ISD::SIGN_EXTEND: return visitSIGN_EXTEND(N);
  992. case ISD::ZERO_EXTEND: return visitZERO_EXTEND(N);
  993. case ISD::ANY_EXTEND: return visitANY_EXTEND(N);
  994. case ISD::SIGN_EXTEND_INREG: return visitSIGN_EXTEND_INREG(N);
  995. case ISD::TRUNCATE: return visitTRUNCATE(N);
  996. case ISD::BITCAST: return visitBITCAST(N);
  997. case ISD::BUILD_PAIR: return visitBUILD_PAIR(N);
  998. case ISD::FADD: return visitFADD(N);
  999. case ISD::FSUB: return visitFSUB(N);
  1000. case ISD::FMUL: return visitFMUL(N);
  1001. case ISD::FMA: return visitFMA(N);
  1002. case ISD::FDIV: return visitFDIV(N);
  1003. case ISD::FREM: return visitFREM(N);
  1004. case ISD::FCOPYSIGN: return visitFCOPYSIGN(N);
  1005. case ISD::SINT_TO_FP: return visitSINT_TO_FP(N);
  1006. case ISD::UINT_TO_FP: return visitUINT_TO_FP(N);
  1007. case ISD::FP_TO_SINT: return visitFP_TO_SINT(N);
  1008. case ISD::FP_TO_UINT: return visitFP_TO_UINT(N);
  1009. case ISD::FP_ROUND: return visitFP_ROUND(N);
  1010. case ISD::FP_ROUND_INREG: return visitFP_ROUND_INREG(N);
  1011. case ISD::FP_EXTEND: return visitFP_EXTEND(N);
  1012. case ISD::FNEG: return visitFNEG(N);
  1013. case ISD::FABS: return visitFABS(N);
  1014. case ISD::FFLOOR: return visitFFLOOR(N);
  1015. case ISD::FCEIL: return visitFCEIL(N);
  1016. case ISD::FTRUNC: return visitFTRUNC(N);
  1017. case ISD::BRCOND: return visitBRCOND(N);
  1018. case ISD::BR_CC: return visitBR_CC(N);
  1019. case ISD::LOAD: return visitLOAD(N);
  1020. case ISD::STORE: return visitSTORE(N);
  1021. case ISD::INSERT_VECTOR_ELT: return visitINSERT_VECTOR_ELT(N);
  1022. case ISD::EXTRACT_VECTOR_ELT: return visitEXTRACT_VECTOR_ELT(N);
  1023. case ISD::BUILD_VECTOR: return visitBUILD_VECTOR(N);
  1024. case ISD::CONCAT_VECTORS: return visitCONCAT_VECTORS(N);
  1025. case ISD::EXTRACT_SUBVECTOR: return visitEXTRACT_SUBVECTOR(N);
  1026. case ISD::VECTOR_SHUFFLE: return visitVECTOR_SHUFFLE(N);
  1027. }
  1028. return SDValue();
  1029. }
  1030. SDValue DAGCombiner::combine(SDNode *N) {
  1031. SDValue RV = visit(N);
  1032. // If nothing happened, try a target-specific DAG combine.
  1033. if (RV.getNode() == 0) {
  1034. assert(N->getOpcode() != ISD::DELETED_NODE &&
  1035. "Node was deleted but visit returned NULL!");
  1036. if (N->getOpcode() >= ISD::BUILTIN_OP_END ||
  1037. TLI.hasTargetDAGCombine((ISD::NodeType)N->getOpcode())) {
  1038. // Expose the DAG combiner to the target combiner impls.
  1039. TargetLowering::DAGCombinerInfo
  1040. DagCombineInfo(DAG, Level, false, this);
  1041. RV = TLI.PerformDAGCombine(N, DagCombineInfo);
  1042. }
  1043. }
  1044. // If nothing happened still, try promoting the operation.
  1045. if (RV.getNode() == 0) {
  1046. switch (N->getOpcode()) {
  1047. default: break;
  1048. case ISD::ADD:
  1049. case ISD::SUB:
  1050. case ISD::MUL:
  1051. case ISD::AND:
  1052. case ISD::OR:
  1053. case ISD::XOR:
  1054. RV = PromoteIntBinOp(SDValue(N, 0));
  1055. break;
  1056. case ISD::SHL:
  1057. case ISD::SRA:
  1058. case ISD::SRL:
  1059. RV = PromoteIntShiftOp(SDValue(N, 0));
  1060. break;
  1061. case ISD::SIGN_EXTEND:
  1062. case ISD::ZERO_EXTEND:
  1063. case ISD::ANY_EXTEND:
  1064. RV = PromoteExtend(SDValue(N, 0));
  1065. break;
  1066. case ISD::LOAD:
  1067. if (PromoteLoad(SDValue(N, 0)))
  1068. RV = SDValue(N, 0);
  1069. break;
  1070. }
  1071. }
  1072. // If N is a commutative binary node, try commuting it to enable more
  1073. // sdisel CSE.
  1074. if (RV.getNode() == 0 &&
  1075. SelectionDAG::isCommutativeBinOp(N->getOpcode()) &&
  1076. N->getNumValues() == 1) {
  1077. SDValue N0 = N->getOperand(0);
  1078. SDValue N1 = N->getOperand(1);
  1079. // Constant operands are canonicalized to RHS.
  1080. if (isa<ConstantSDNode>(N0) || !isa<ConstantSDNode>(N1)) {
  1081. SDValue Ops[] = { N1, N0 };
  1082. SDNode *CSENode = DAG.getNodeIfExists(N->getOpcode(), N->getVTList(),
  1083. Ops, 2);
  1084. if (CSENode)
  1085. return SDValue(CSENode, 0);
  1086. }
  1087. }
  1088. return RV;
  1089. }
  1090. /// getInputChainForNode - Given a node, return its input chain if it has one,
  1091. /// otherwise return a null sd operand.
  1092. static SDValue getInputChainForNode(SDNode *N) {
  1093. if (unsigned NumOps = N->getNumOperands()) {
  1094. if (N->getOperand(0).getValueType() == MVT::Other)
  1095. return N->getOperand(0);
  1096. else if (N->getOperand(NumOps-1).getValueType() == MVT::Other)
  1097. return N->getOperand(NumOps-1);
  1098. for (unsigned i = 1; i < NumOps-1; ++i)
  1099. if (N->getOperand(i).getValueType() == MVT::Other)
  1100. return N->getOperand(i);
  1101. }
  1102. return SDValue();
  1103. }
  1104. SDValue DAGCombiner::visitTokenFactor(SDNode *N) {
  1105. // If N has two operands, where one has an input chain equal to the other,
  1106. // the 'other' chain is redundant.
  1107. if (N->getNumOperands() == 2) {
  1108. if (getInputChainForNode(N->getOperand(0).getNode()) == N->getOperand(1))
  1109. return N->getOperand(0);
  1110. if (getInputChainForNode(N->getOperand(1).getNode()) == N->getOperand(0))
  1111. return N->getOperand(1);
  1112. }
  1113. SmallVector<SDNode *, 8> TFs; // List of token factors to visit.
  1114. SmallVector<SDValue, 8> Ops; // Ops for replacing token factor.
  1115. SmallPtrSet<SDNode*, 16> SeenOps;
  1116. bool Changed = false; // If we should replace this token factor.
  1117. // Start out with this token factor.
  1118. TFs.push_back(N);
  1119. // Iterate through token factors. The TFs grows when new token factors are
  1120. // encountered.
  1121. for (unsigned i = 0; i < TFs.size(); ++i) {
  1122. SDNode *TF = TFs[i];
  1123. // Check each of the operands.
  1124. for (unsigned i = 0, ie = TF->getNumOperands(); i != ie; ++i) {
  1125. SDValue Op = TF->getOperand(i);
  1126. switch (Op.getOpcode()) {
  1127. case ISD::EntryToken:
  1128. // Entry tokens don't need to be added to the list. They are
  1129. // rededundant.
  1130. Changed = true;
  1131. break;
  1132. case ISD::TokenFactor:
  1133. if (Op.hasOneUse() &&
  1134. std::find(TFs.begin(), TFs.end(), Op.getNode()) == TFs.end()) {
  1135. // Queue up for processing.
  1136. TFs.push_back(Op.getNode());
  1137. // Clean up in case the token factor is removed.
  1138. AddToWorkList(Op.getNode());
  1139. Changed = true;
  1140. break;
  1141. }
  1142. // Fall thru
  1143. default:
  1144. // Only add if it isn't already in the list.
  1145. if (SeenOps.insert(Op.getNode()))
  1146. Ops.push_back(Op);
  1147. else
  1148. Changed = true;
  1149. break;
  1150. }
  1151. }
  1152. }
  1153. SDValue Result;
  1154. // If we've change things around then replace token factor.
  1155. if (Changed) {
  1156. if (Ops.empty()) {
  1157. // The entry token is the only possible outcome.
  1158. Result = DAG.getEntryNode();
  1159. } else {
  1160. // New and improved token factor.
  1161. Result = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
  1162. MVT::Other, &Ops[0], Ops.size());
  1163. }
  1164. // Don't add users to work list.
  1165. return CombineTo(N, Result, false);
  1166. }
  1167. return Result;
  1168. }
  1169. /// MERGE_VALUES can always be eliminated.
  1170. SDValue DAGCombiner::visitMERGE_VALUES(SDNode *N) {
  1171. WorkListRemover DeadNodes(*this);
  1172. // Replacing results may cause a different MERGE_VALUES to suddenly
  1173. // be CSE'd with N, and carry its uses with it. Iterate until no
  1174. // uses remain, to ensure that the node can be safely deleted.
  1175. // First add the users of this node to the work list so that they
  1176. // can be tried again once they have new operands.
  1177. AddUsersToWorkList(N);
  1178. do {
  1179. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i)
  1180. DAG.ReplaceAllUsesOfValueWith(SDValue(N, i), N->getOperand(i));
  1181. } while (!N->use_empty());
  1182. removeFromWorkList(N);
  1183. DAG.DeleteNode(N);
  1184. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  1185. }
  1186. static
  1187. SDValue combineShlAddConstant(DebugLoc DL, SDValue N0, SDValue N1,
  1188. SelectionDAG &DAG) {
  1189. EVT VT = N0.getValueType();
  1190. SDValue N00 = N0.getOperand(0);
  1191. SDValue N01 = N0.getOperand(1);
  1192. ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N01);
  1193. if (N01C && N00.getOpcode() == ISD::ADD && N00.getNode()->hasOneUse() &&
  1194. isa<ConstantSDNode>(N00.getOperand(1))) {
  1195. // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
  1196. N0 = DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
  1197. DAG.getNode(ISD::SHL, N00.getDebugLoc(), VT,
  1198. N00.getOperand(0), N01),
  1199. DAG.getNode(ISD::SHL, N01.getDebugLoc(), VT,
  1200. N00.getOperand(1), N01));
  1201. return DAG.getNode(ISD::ADD, DL, VT, N0, N1);
  1202. }
  1203. return SDValue();
  1204. }
  1205. SDValue DAGCombiner::visitADD(SDNode *N) {
  1206. SDValue N0 = N->getOperand(0);
  1207. SDValue N1 = N->getOperand(1);
  1208. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  1209. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  1210. EVT VT = N0.getValueType();
  1211. // fold vector ops
  1212. if (VT.isVector()) {
  1213. SDValue FoldedVOp = SimplifyVBinOp(N);
  1214. if (FoldedVOp.getNode()) return FoldedVOp;
  1215. // fold (add x, 0) -> x, vector edition
  1216. if (ISD::isBuildVectorAllZeros(N1.getNode()))
  1217. return N0;
  1218. if (ISD::isBuildVectorAllZeros(N0.getNode()))
  1219. return N1;
  1220. }
  1221. // fold (add x, undef) -> undef
  1222. if (N0.getOpcode() == ISD::UNDEF)
  1223. return N0;
  1224. if (N1.getOpcode() == ISD::UNDEF)
  1225. return N1;
  1226. // fold (add c1, c2) -> c1+c2
  1227. if (N0C && N1C)
  1228. return DAG.FoldConstantArithmetic(ISD::ADD, VT, N0C, N1C);
  1229. // canonicalize constant to RHS
  1230. if (N0C && !N1C)
  1231. return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1, N0);
  1232. // fold (add x, 0) -> x
  1233. if (N1C && N1C->isNullValue())
  1234. return N0;
  1235. // fold (add Sym, c) -> Sym+c
  1236. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
  1237. if (!LegalOperations && TLI.isOffsetFoldingLegal(GA) && N1C &&
  1238. GA->getOpcode() == ISD::GlobalAddress)
  1239. return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
  1240. GA->getOffset() +
  1241. (uint64_t)N1C->getSExtValue());
  1242. // fold ((c1-A)+c2) -> (c1+c2)-A
  1243. if (N1C && N0.getOpcode() == ISD::SUB)
  1244. if (ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getOperand(0)))
  1245. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
  1246. DAG.getConstant(N1C->getAPIntValue()+
  1247. N0C->getAPIntValue(), VT),
  1248. N0.getOperand(1));
  1249. // reassociate add
  1250. SDValue RADD = ReassociateOps(ISD::ADD, N->getDebugLoc(), N0, N1);
  1251. if (RADD.getNode() != 0)
  1252. return RADD;
  1253. // fold ((0-A) + B) -> B-A
  1254. if (N0.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N0.getOperand(0)) &&
  1255. cast<ConstantSDNode>(N0.getOperand(0))->isNullValue())
  1256. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1, N0.getOperand(1));
  1257. // fold (A + (0-B)) -> A-B
  1258. if (N1.getOpcode() == ISD::SUB && isa<ConstantSDNode>(N1.getOperand(0)) &&
  1259. cast<ConstantSDNode>(N1.getOperand(0))->isNullValue())
  1260. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1.getOperand(1));
  1261. // fold (A+(B-A)) -> B
  1262. if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(1))
  1263. return N1.getOperand(0);
  1264. // fold ((B-A)+A) -> B
  1265. if (N0.getOpcode() == ISD::SUB && N1 == N0.getOperand(1))
  1266. return N0.getOperand(0);
  1267. // fold (A+(B-(A+C))) to (B-C)
  1268. if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
  1269. N0 == N1.getOperand(1).getOperand(0))
  1270. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
  1271. N1.getOperand(1).getOperand(1));
  1272. // fold (A+(B-(C+A))) to (B-C)
  1273. if (N1.getOpcode() == ISD::SUB && N1.getOperand(1).getOpcode() == ISD::ADD &&
  1274. N0 == N1.getOperand(1).getOperand(1))
  1275. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1.getOperand(0),
  1276. N1.getOperand(1).getOperand(0));
  1277. // fold (A+((B-A)+or-C)) to (B+or-C)
  1278. if ((N1.getOpcode() == ISD::SUB || N1.getOpcode() == ISD::ADD) &&
  1279. N1.getOperand(0).getOpcode() == ISD::SUB &&
  1280. N0 == N1.getOperand(0).getOperand(1))
  1281. return DAG.getNode(N1.getOpcode(), N->getDebugLoc(), VT,
  1282. N1.getOperand(0).getOperand(0), N1.getOperand(1));
  1283. // fold (A-B)+(C-D) to (A+C)-(B+D) when A or C is constant
  1284. if (N0.getOpcode() == ISD::SUB && N1.getOpcode() == ISD::SUB) {
  1285. SDValue N00 = N0.getOperand(0);
  1286. SDValue N01 = N0.getOperand(1);
  1287. SDValue N10 = N1.getOperand(0);
  1288. SDValue N11 = N1.getOperand(1);
  1289. if (isa<ConstantSDNode>(N00) || isa<ConstantSDNode>(N10))
  1290. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
  1291. DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT, N00, N10),
  1292. DAG.getNode(ISD::ADD, N1.getDebugLoc(), VT, N01, N11));
  1293. }
  1294. if (!VT.isVector() && SimplifyDemandedBits(SDValue(N, 0)))
  1295. return SDValue(N, 0);
  1296. // fold (a+b) -> (a|b) iff a and b share no bits.
  1297. if (VT.isInteger() && !VT.isVector()) {
  1298. APInt LHSZero, LHSOne;
  1299. APInt RHSZero, RHSOne;
  1300. DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
  1301. if (LHSZero.getBoolValue()) {
  1302. DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
  1303. // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
  1304. // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
  1305. if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
  1306. return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1);
  1307. }
  1308. }
  1309. // fold (add (shl (add x, c1), c2), ) -> (add (add (shl x, c2), c1<<c2), )
  1310. if (N0.getOpcode() == ISD::SHL && N0.getNode()->hasOneUse()) {
  1311. SDValue Result = combineShlAddConstant(N->getDebugLoc(), N0, N1, DAG);
  1312. if (Result.getNode()) return Result;
  1313. }
  1314. if (N1.getOpcode() == ISD::SHL && N1.getNode()->hasOneUse()) {
  1315. SDValue Result = combineShlAddConstant(N->getDebugLoc(), N1, N0, DAG);
  1316. if (Result.getNode()) return Result;
  1317. }
  1318. // fold (add x, shl(0 - y, n)) -> sub(x, shl(y, n))
  1319. if (N1.getOpcode() == ISD::SHL &&
  1320. N1.getOperand(0).getOpcode() == ISD::SUB)
  1321. if (ConstantSDNode *C =
  1322. dyn_cast<ConstantSDNode>(N1.getOperand(0).getOperand(0)))
  1323. if (C->getAPIntValue() == 0)
  1324. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0,
  1325. DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
  1326. N1.getOperand(0).getOperand(1),
  1327. N1.getOperand(1)));
  1328. if (N0.getOpcode() == ISD::SHL &&
  1329. N0.getOperand(0).getOpcode() == ISD::SUB)
  1330. if (ConstantSDNode *C =
  1331. dyn_cast<ConstantSDNode>(N0.getOperand(0).getOperand(0)))
  1332. if (C->getAPIntValue() == 0)
  1333. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N1,
  1334. DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
  1335. N0.getOperand(0).getOperand(1),
  1336. N0.getOperand(1)));
  1337. if (N1.getOpcode() == ISD::AND) {
  1338. SDValue AndOp0 = N1.getOperand(0);
  1339. ConstantSDNode *AndOp1 = dyn_cast<ConstantSDNode>(N1->getOperand(1));
  1340. unsigned NumSignBits = DAG.ComputeNumSignBits(AndOp0);
  1341. unsigned DestBits = VT.getScalarType().getSizeInBits();
  1342. // (add z, (and (sbbl x, x), 1)) -> (sub z, (sbbl x, x))
  1343. // and similar xforms where the inner op is either ~0 or 0.
  1344. if (NumSignBits == DestBits && AndOp1 && AndOp1->isOne()) {
  1345. DebugLoc DL = N->getDebugLoc();
  1346. return DAG.getNode(ISD::SUB, DL, VT, N->getOperand(0), AndOp0);
  1347. }
  1348. }
  1349. // add (sext i1), X -> sub X, (zext i1)
  1350. if (N0.getOpcode() == ISD::SIGN_EXTEND &&
  1351. N0.getOperand(0).getValueType() == MVT::i1 &&
  1352. !TLI.isOperationLegal(ISD::SIGN_EXTEND, MVT::i1)) {
  1353. DebugLoc DL = N->getDebugLoc();
  1354. SDValue ZExt = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0));
  1355. return DAG.getNode(ISD::SUB, DL, VT, N1, ZExt);
  1356. }
  1357. return SDValue();
  1358. }
  1359. SDValue DAGCombiner::visitADDC(SDNode *N) {
  1360. SDValue N0 = N->getOperand(0);
  1361. SDValue N1 = N->getOperand(1);
  1362. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  1363. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  1364. EVT VT = N0.getValueType();
  1365. // If the flag result is dead, turn this into an ADD.
  1366. if (!N->hasAnyUseOfValue(1))
  1367. return CombineTo(N, DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, N1),
  1368. DAG.getNode(ISD::CARRY_FALSE,
  1369. N->getDebugLoc(), MVT::Glue));
  1370. // canonicalize constant to RHS.
  1371. if (N0C && !N1C)
  1372. return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N1, N0);
  1373. // fold (addc x, 0) -> x + no carry out
  1374. if (N1C && N1C->isNullValue())
  1375. return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE,
  1376. N->getDebugLoc(), MVT::Glue));
  1377. // fold (addc a, b) -> (or a, b), CARRY_FALSE iff a and b share no bits.
  1378. APInt LHSZero, LHSOne;
  1379. APInt RHSZero, RHSOne;
  1380. DAG.ComputeMaskedBits(N0, LHSZero, LHSOne);
  1381. if (LHSZero.getBoolValue()) {
  1382. DAG.ComputeMaskedBits(N1, RHSZero, RHSOne);
  1383. // If all possibly-set bits on the LHS are clear on the RHS, return an OR.
  1384. // If all possibly-set bits on the RHS are clear on the LHS, return an OR.
  1385. if ((RHSZero & ~LHSZero) == ~LHSZero || (LHSZero & ~RHSZero) == ~RHSZero)
  1386. return CombineTo(N, DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N1),
  1387. DAG.getNode(ISD::CARRY_FALSE,
  1388. N->getDebugLoc(), MVT::Glue));
  1389. }
  1390. return SDValue();
  1391. }
  1392. SDValue DAGCombiner::visitADDE(SDNode *N) {
  1393. SDValue N0 = N->getOperand(0);
  1394. SDValue N1 = N->getOperand(1);
  1395. SDValue CarryIn = N->getOperand(2);
  1396. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  1397. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  1398. // canonicalize constant to RHS
  1399. if (N0C && !N1C)
  1400. return DAG.getNode(ISD::ADDE, N->getDebugLoc(), N->getVTList(),
  1401. N1, N0, CarryIn);
  1402. // fold (adde x, y, false) -> (addc x, y)
  1403. if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
  1404. return DAG.getNode(ISD::ADDC, N->getDebugLoc(), N->getVTList(), N0, N1);
  1405. return SDValue();
  1406. }
  1407. // Since it may not be valid to emit a fold to zero for vector initializers
  1408. // check if we can before folding.
  1409. static SDValue tryFoldToZero(DebugLoc DL, const TargetLowering &TLI, EVT VT,
  1410. SelectionDAG &DAG, bool LegalOperations) {
  1411. if (!VT.isVector()) {
  1412. return DAG.getConstant(0, VT);
  1413. }
  1414. if (!LegalOperations || TLI.isOperationLegal(ISD::BUILD_VECTOR, VT)) {
  1415. // Produce a vector of zeros.
  1416. SDValue El = DAG.getConstant(0, VT.getVectorElementType());
  1417. std::vector<SDValue> Ops(VT.getVectorNumElements(), El);
  1418. return DAG.getNode(ISD::BUILD_VECTOR, DL, VT,
  1419. &Ops[0], Ops.size());
  1420. }
  1421. return SDValue();
  1422. }
  1423. SDValue DAGCombiner::visitSUB(SDNode *N) {
  1424. SDValue N0 = N->getOperand(0);
  1425. SDValue N1 = N->getOperand(1);
  1426. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
  1427. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
  1428. ConstantSDNode *N1C1 = N1.getOpcode() != ISD::ADD ? 0 :
  1429. dyn_cast<ConstantSDNode>(N1.getOperand(1).getNode());
  1430. EVT VT = N0.getValueType();
  1431. // fold vector ops
  1432. if (VT.isVector()) {
  1433. SDValue FoldedVOp = SimplifyVBinOp(N);
  1434. if (FoldedVOp.getNode()) return FoldedVOp;
  1435. // fold (sub x, 0) -> x, vector edition
  1436. if (ISD::isBuildVectorAllZeros(N1.getNode()))
  1437. return N0;
  1438. }
  1439. // fold (sub x, x) -> 0
  1440. // FIXME: Refactor this and xor and other similar operations together.
  1441. if (N0 == N1)
  1442. return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
  1443. // fold (sub c1, c2) -> c1-c2
  1444. if (N0C && N1C)
  1445. return DAG.FoldConstantArithmetic(ISD::SUB, VT, N0C, N1C);
  1446. // fold (sub x, c) -> (add x, -c)
  1447. if (N1C)
  1448. return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0,
  1449. DAG.getConstant(-N1C->getAPIntValue(), VT));
  1450. // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1)
  1451. if (N0C && N0C->isAllOnesValue())
  1452. return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
  1453. // fold A-(A-B) -> B
  1454. if (N1.getOpcode() == ISD::SUB && N0 == N1.getOperand(0))
  1455. return N1.getOperand(1);
  1456. // fold (A+B)-A -> B
  1457. if (N0.getOpcode() == ISD::ADD && N0.getOperand(0) == N1)
  1458. return N0.getOperand(1);
  1459. // fold (A+B)-B -> A
  1460. if (N0.getOpcode() == ISD::ADD && N0.getOperand(1) == N1)
  1461. return N0.getOperand(0);
  1462. // fold C2-(A+C1) -> (C2-C1)-A
  1463. if (N1.getOpcode() == ISD::ADD && N0C && N1C1) {
  1464. SDValue NewC = DAG.getConstant(N0C->getAPIntValue() - N1C1->getAPIntValue(),
  1465. VT);
  1466. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, NewC,
  1467. N1.getOperand(0));
  1468. }
  1469. // fold ((A+(B+or-C))-B) -> A+or-C
  1470. if (N0.getOpcode() == ISD::ADD &&
  1471. (N0.getOperand(1).getOpcode() == ISD::SUB ||
  1472. N0.getOperand(1).getOpcode() == ISD::ADD) &&
  1473. N0.getOperand(1).getOperand(0) == N1)
  1474. return DAG.getNode(N0.getOperand(1).getOpcode(), N->getDebugLoc(), VT,
  1475. N0.getOperand(0), N0.getOperand(1).getOperand(1));
  1476. // fold ((A+(C+B))-B) -> A+C
  1477. if (N0.getOpcode() == ISD::ADD &&
  1478. N0.getOperand(1).getOpcode() == ISD::ADD &&
  1479. N0.getOperand(1).getOperand(1) == N1)
  1480. return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
  1481. N0.getOperand(0), N0.getOperand(1).getOperand(0));
  1482. // fold ((A-(B-C))-C) -> A-B
  1483. if (N0.getOpcode() == ISD::SUB &&
  1484. N0.getOperand(1).getOpcode() == ISD::SUB &&
  1485. N0.getOperand(1).getOperand(1) == N1)
  1486. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
  1487. N0.getOperand(0), N0.getOperand(1).getOperand(0));
  1488. // If either operand of a sub is undef, the result is undef
  1489. if (N0.getOpcode() == ISD::UNDEF)
  1490. return N0;
  1491. if (N1.getOpcode() == ISD::UNDEF)
  1492. return N1;
  1493. // If the relocation model supports it, consider symbol offsets.
  1494. if (GlobalAddressSDNode *GA = dyn_cast<GlobalAddressSDNode>(N0))
  1495. if (!LegalOperations && TLI.isOffsetFoldingLegal(GA)) {
  1496. // fold (sub Sym, c) -> Sym-c
  1497. if (N1C && GA->getOpcode() == ISD::GlobalAddress)
  1498. return DAG.getGlobalAddress(GA->getGlobal(), N1C->getDebugLoc(), VT,
  1499. GA->getOffset() -
  1500. (uint64_t)N1C->getSExtValue());
  1501. // fold (sub Sym+c1, Sym+c2) -> c1-c2
  1502. if (GlobalAddressSDNode *GB = dyn_cast<GlobalAddressSDNode>(N1))
  1503. if (GA->getGlobal() == GB->getGlobal())
  1504. return DAG.getConstant((uint64_t)GA->getOffset() - GB->getOffset(),
  1505. VT);
  1506. }
  1507. return SDValue();
  1508. }
  1509. SDValue DAGCombiner::visitSUBC(SDNode *N) {
  1510. SDValue N0 = N->getOperand(0);
  1511. SDValue N1 = N->getOperand(1);
  1512. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  1513. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  1514. EVT VT = N0.getValueType();
  1515. // If the flag result is dead, turn this into an SUB.
  1516. if (!N->hasAnyUseOfValue(1))
  1517. return CombineTo(N, DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, N1),
  1518. DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
  1519. MVT::Glue));
  1520. // fold (subc x, x) -> 0 + no borrow
  1521. if (N0 == N1)
  1522. return CombineTo(N, DAG.getConstant(0, VT),
  1523. DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
  1524. MVT::Glue));
  1525. // fold (subc x, 0) -> x + no borrow
  1526. if (N1C && N1C->isNullValue())
  1527. return CombineTo(N, N0, DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
  1528. MVT::Glue));
  1529. // Canonicalize (sub -1, x) -> ~x, i.e. (xor x, -1) + no borrow
  1530. if (N0C && N0C->isAllOnesValue())
  1531. return CombineTo(N, DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0),
  1532. DAG.getNode(ISD::CARRY_FALSE, N->getDebugLoc(),
  1533. MVT::Glue));
  1534. return SDValue();
  1535. }
  1536. SDValue DAGCombiner::visitSUBE(SDNode *N) {
  1537. SDValue N0 = N->getOperand(0);
  1538. SDValue N1 = N->getOperand(1);
  1539. SDValue CarryIn = N->getOperand(2);
  1540. // fold (sube x, y, false) -> (subc x, y)
  1541. if (CarryIn.getOpcode() == ISD::CARRY_FALSE)
  1542. return DAG.getNode(ISD::SUBC, N->getDebugLoc(), N->getVTList(), N0, N1);
  1543. return SDValue();
  1544. }
  1545. SDValue DAGCombiner::visitMUL(SDNode *N) {
  1546. SDValue N0 = N->getOperand(0);
  1547. SDValue N1 = N->getOperand(1);
  1548. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  1549. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  1550. EVT VT = N0.getValueType();
  1551. // fold vector ops
  1552. if (VT.isVector()) {
  1553. SDValue FoldedVOp = SimplifyVBinOp(N);
  1554. if (FoldedVOp.getNode()) return FoldedVOp;
  1555. }
  1556. // fold (mul x, undef) -> 0
  1557. if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
  1558. return DAG.getConstant(0, VT);
  1559. // fold (mul c1, c2) -> c1*c2
  1560. if (N0C && N1C)
  1561. return DAG.FoldConstantArithmetic(ISD::MUL, VT, N0C, N1C);
  1562. // canonicalize constant to RHS
  1563. if (N0C && !N1C)
  1564. return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT, N1, N0);
  1565. // fold (mul x, 0) -> 0
  1566. if (N1C && N1C->isNullValue())
  1567. return N1;
  1568. // fold (mul x, -1) -> 0-x
  1569. if (N1C && N1C->isAllOnesValue())
  1570. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
  1571. DAG.getConstant(0, VT), N0);
  1572. // fold (mul x, (1 << c)) -> x << c
  1573. if (N1C && N1C->getAPIntValue().isPowerOf2())
  1574. return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
  1575. DAG.getConstant(N1C->getAPIntValue().logBase2(),
  1576. getShiftAmountTy(N0.getValueType())));
  1577. // fold (mul x, -(1 << c)) -> -(x << c) or (-x) << c
  1578. if (N1C && (-N1C->getAPIntValue()).isPowerOf2()) {
  1579. unsigned Log2Val = (-N1C->getAPIntValue()).logBase2();
  1580. // FIXME: If the input is something that is easily negated (e.g. a
  1581. // single-use add), we should put the negate there.
  1582. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
  1583. DAG.getConstant(0, VT),
  1584. DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
  1585. DAG.getConstant(Log2Val,
  1586. getShiftAmountTy(N0.getValueType()))));
  1587. }
  1588. // (mul (shl X, c1), c2) -> (mul X, c2 << c1)
  1589. if (N1C && N0.getOpcode() == ISD::SHL &&
  1590. isa<ConstantSDNode>(N0.getOperand(1))) {
  1591. SDValue C3 = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
  1592. N1, N0.getOperand(1));
  1593. AddToWorkList(C3.getNode());
  1594. return DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
  1595. N0.getOperand(0), C3);
  1596. }
  1597. // Change (mul (shl X, C), Y) -> (shl (mul X, Y), C) when the shift has one
  1598. // use.
  1599. {
  1600. SDValue Sh(0,0), Y(0,0);
  1601. // Check for both (mul (shl X, C), Y) and (mul Y, (shl X, C)).
  1602. if (N0.getOpcode() == ISD::SHL && isa<ConstantSDNode>(N0.getOperand(1)) &&
  1603. N0.getNode()->hasOneUse()) {
  1604. Sh = N0; Y = N1;
  1605. } else if (N1.getOpcode() == ISD::SHL &&
  1606. isa<ConstantSDNode>(N1.getOperand(1)) &&
  1607. N1.getNode()->hasOneUse()) {
  1608. Sh = N1; Y = N0;
  1609. }
  1610. if (Sh.getNode()) {
  1611. SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
  1612. Sh.getOperand(0), Y);
  1613. return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT,
  1614. Mul, Sh.getOperand(1));
  1615. }
  1616. }
  1617. // fold (mul (add x, c1), c2) -> (add (mul x, c2), c1*c2)
  1618. if (N1C && N0.getOpcode() == ISD::ADD && N0.getNode()->hasOneUse() &&
  1619. isa<ConstantSDNode>(N0.getOperand(1)))
  1620. return DAG.getNode(ISD::ADD, N->getDebugLoc(), VT,
  1621. DAG.getNode(ISD::MUL, N0.getDebugLoc(), VT,
  1622. N0.getOperand(0), N1),
  1623. DAG.getNode(ISD::MUL, N1.getDebugLoc(), VT,
  1624. N0.getOperand(1), N1));
  1625. // reassociate mul
  1626. SDValue RMUL = ReassociateOps(ISD::MUL, N->getDebugLoc(), N0, N1);
  1627. if (RMUL.getNode() != 0)
  1628. return RMUL;
  1629. return SDValue();
  1630. }
  1631. SDValue DAGCombiner::visitSDIV(SDNode *N) {
  1632. SDValue N0 = N->getOperand(0);
  1633. SDValue N1 = N->getOperand(1);
  1634. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
  1635. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
  1636. EVT VT = N->getValueType(0);
  1637. // fold vector ops
  1638. if (VT.isVector()) {
  1639. SDValue FoldedVOp = SimplifyVBinOp(N);
  1640. if (FoldedVOp.getNode()) return FoldedVOp;
  1641. }
  1642. // fold (sdiv c1, c2) -> c1/c2
  1643. if (N0C && N1C && !N1C->isNullValue())
  1644. return DAG.FoldConstantArithmetic(ISD::SDIV, VT, N0C, N1C);
  1645. // fold (sdiv X, 1) -> X
  1646. if (N1C && N1C->getAPIntValue() == 1LL)
  1647. return N0;
  1648. // fold (sdiv X, -1) -> 0-X
  1649. if (N1C && N1C->isAllOnesValue())
  1650. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
  1651. DAG.getConstant(0, VT), N0);
  1652. // If we know the sign bits of both operands are zero, strength reduce to a
  1653. // udiv instead. Handles (X&15) /s 4 -> X&15 >> 2
  1654. if (!VT.isVector()) {
  1655. if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
  1656. return DAG.getNode(ISD::UDIV, N->getDebugLoc(), N1.getValueType(),
  1657. N0, N1);
  1658. }
  1659. // fold (sdiv X, pow2) -> simple ops after legalize
  1660. if (N1C && !N1C->isNullValue() &&
  1661. (N1C->getAPIntValue().isPowerOf2() ||
  1662. (-N1C->getAPIntValue()).isPowerOf2())) {
  1663. // If dividing by powers of two is cheap, then don't perform the following
  1664. // fold.
  1665. if (TLI.isPow2DivCheap())
  1666. return SDValue();
  1667. unsigned lg2 = N1C->getAPIntValue().countTrailingZeros();
  1668. // Splat the sign bit into the register
  1669. SDValue SGN = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
  1670. DAG.getConstant(VT.getSizeInBits()-1,
  1671. getShiftAmountTy(N0.getValueType())));
  1672. AddToWorkList(SGN.getNode());
  1673. // Add (N0 < 0) ? abs2 - 1 : 0;
  1674. SDValue SRL = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, SGN,
  1675. DAG.getConstant(VT.getSizeInBits() - lg2,
  1676. getShiftAmountTy(SGN.getValueType())));
  1677. SDValue ADD = DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N0, SRL);
  1678. AddToWorkList(SRL.getNode());
  1679. AddToWorkList(ADD.getNode()); // Divide by pow2
  1680. SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, ADD,
  1681. DAG.getConstant(lg2, getShiftAmountTy(ADD.getValueType())));
  1682. // If we're dividing by a positive value, we're done. Otherwise, we must
  1683. // negate the result.
  1684. if (N1C->getAPIntValue().isNonNegative())
  1685. return SRA;
  1686. AddToWorkList(SRA.getNode());
  1687. return DAG.getNode(ISD::SUB, N->getDebugLoc(), VT,
  1688. DAG.getConstant(0, VT), SRA);
  1689. }
  1690. // if integer divide is expensive and we satisfy the requirements, emit an
  1691. // alternate sequence.
  1692. if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
  1693. SDValue Op = BuildSDIV(N);
  1694. if (Op.getNode()) return Op;
  1695. }
  1696. // undef / X -> 0
  1697. if (N0.getOpcode() == ISD::UNDEF)
  1698. return DAG.getConstant(0, VT);
  1699. // X / undef -> undef
  1700. if (N1.getOpcode() == ISD::UNDEF)
  1701. return N1;
  1702. return SDValue();
  1703. }
  1704. SDValue DAGCombiner::visitUDIV(SDNode *N) {
  1705. SDValue N0 = N->getOperand(0);
  1706. SDValue N1 = N->getOperand(1);
  1707. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0.getNode());
  1708. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
  1709. EVT VT = N->getValueType(0);
  1710. // fold vector ops
  1711. if (VT.isVector()) {
  1712. SDValue FoldedVOp = SimplifyVBinOp(N);
  1713. if (FoldedVOp.getNode()) return FoldedVOp;
  1714. }
  1715. // fold (udiv c1, c2) -> c1/c2
  1716. if (N0C && N1C && !N1C->isNullValue())
  1717. return DAG.FoldConstantArithmetic(ISD::UDIV, VT, N0C, N1C);
  1718. // fold (udiv x, (1 << c)) -> x >>u c
  1719. if (N1C && N1C->getAPIntValue().isPowerOf2())
  1720. return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
  1721. DAG.getConstant(N1C->getAPIntValue().logBase2(),
  1722. getShiftAmountTy(N0.getValueType())));
  1723. // fold (udiv x, (shl c, y)) -> x >>u (log2(c)+y) iff c is power of 2
  1724. if (N1.getOpcode() == ISD::SHL) {
  1725. if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
  1726. if (SHC->getAPIntValue().isPowerOf2()) {
  1727. EVT ADDVT = N1.getOperand(1).getValueType();
  1728. SDValue Add = DAG.getNode(ISD::ADD, N->getDebugLoc(), ADDVT,
  1729. N1.getOperand(1),
  1730. DAG.getConstant(SHC->getAPIntValue()
  1731. .logBase2(),
  1732. ADDVT));
  1733. AddToWorkList(Add.getNode());
  1734. return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, Add);
  1735. }
  1736. }
  1737. }
  1738. // fold (udiv x, c) -> alternate
  1739. if (N1C && !N1C->isNullValue() && !TLI.isIntDivCheap()) {
  1740. SDValue Op = BuildUDIV(N);
  1741. if (Op.getNode()) return Op;
  1742. }
  1743. // undef / X -> 0
  1744. if (N0.getOpcode() == ISD::UNDEF)
  1745. return DAG.getConstant(0, VT);
  1746. // X / undef -> undef
  1747. if (N1.getOpcode() == ISD::UNDEF)
  1748. return N1;
  1749. return SDValue();
  1750. }
  1751. SDValue DAGCombiner::visitSREM(SDNode *N) {
  1752. SDValue N0 = N->getOperand(0);
  1753. SDValue N1 = N->getOperand(1);
  1754. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  1755. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  1756. EVT VT = N->getValueType(0);
  1757. // fold (srem c1, c2) -> c1%c2
  1758. if (N0C && N1C && !N1C->isNullValue())
  1759. return DAG.FoldConstantArithmetic(ISD::SREM, VT, N0C, N1C);
  1760. // If we know the sign bits of both operands are zero, strength reduce to a
  1761. // urem instead. Handles (X & 0x0FFFFFFF) %s 16 -> X&15
  1762. if (!VT.isVector()) {
  1763. if (DAG.SignBitIsZero(N1) && DAG.SignBitIsZero(N0))
  1764. return DAG.getNode(ISD::UREM, N->getDebugLoc(), VT, N0, N1);
  1765. }
  1766. // If X/C can be simplified by the division-by-constant logic, lower
  1767. // X%C to the equivalent of X-X/C*C.
  1768. if (N1C && !N1C->isNullValue()) {
  1769. SDValue Div = DAG.getNode(ISD::SDIV, N->getDebugLoc(), VT, N0, N1);
  1770. AddToWorkList(Div.getNode());
  1771. SDValue OptimizedDiv = combine(Div.getNode());
  1772. if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
  1773. SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
  1774. OptimizedDiv, N1);
  1775. SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
  1776. AddToWorkList(Mul.getNode());
  1777. return Sub;
  1778. }
  1779. }
  1780. // undef % X -> 0
  1781. if (N0.getOpcode() == ISD::UNDEF)
  1782. return DAG.getConstant(0, VT);
  1783. // X % undef -> undef
  1784. if (N1.getOpcode() == ISD::UNDEF)
  1785. return N1;
  1786. return SDValue();
  1787. }
  1788. SDValue DAGCombiner::visitUREM(SDNode *N) {
  1789. SDValue N0 = N->getOperand(0);
  1790. SDValue N1 = N->getOperand(1);
  1791. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  1792. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  1793. EVT VT = N->getValueType(0);
  1794. // fold (urem c1, c2) -> c1%c2
  1795. if (N0C && N1C && !N1C->isNullValue())
  1796. return DAG.FoldConstantArithmetic(ISD::UREM, VT, N0C, N1C);
  1797. // fold (urem x, pow2) -> (and x, pow2-1)
  1798. if (N1C && !N1C->isNullValue() && N1C->getAPIntValue().isPowerOf2())
  1799. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0,
  1800. DAG.getConstant(N1C->getAPIntValue()-1,VT));
  1801. // fold (urem x, (shl pow2, y)) -> (and x, (add (shl pow2, y), -1))
  1802. if (N1.getOpcode() == ISD::SHL) {
  1803. if (ConstantSDNode *SHC = dyn_cast<ConstantSDNode>(N1.getOperand(0))) {
  1804. if (SHC->getAPIntValue().isPowerOf2()) {
  1805. SDValue Add =
  1806. DAG.getNode(ISD::ADD, N->getDebugLoc(), VT, N1,
  1807. DAG.getConstant(APInt::getAllOnesValue(VT.getSizeInBits()),
  1808. VT));
  1809. AddToWorkList(Add.getNode());
  1810. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, Add);
  1811. }
  1812. }
  1813. }
  1814. // If X/C can be simplified by the division-by-constant logic, lower
  1815. // X%C to the equivalent of X-X/C*C.
  1816. if (N1C && !N1C->isNullValue()) {
  1817. SDValue Div = DAG.getNode(ISD::UDIV, N->getDebugLoc(), VT, N0, N1);
  1818. AddToWorkList(Div.getNode());
  1819. SDValue OptimizedDiv = combine(Div.getNode());
  1820. if (OptimizedDiv.getNode() && OptimizedDiv.getNode() != Div.getNode()) {
  1821. SDValue Mul = DAG.getNode(ISD::MUL, N->getDebugLoc(), VT,
  1822. OptimizedDiv, N1);
  1823. SDValue Sub = DAG.getNode(ISD::SUB, N->getDebugLoc(), VT, N0, Mul);
  1824. AddToWorkList(Mul.getNode());
  1825. return Sub;
  1826. }
  1827. }
  1828. // undef % X -> 0
  1829. if (N0.getOpcode() == ISD::UNDEF)
  1830. return DAG.getConstant(0, VT);
  1831. // X % undef -> undef
  1832. if (N1.getOpcode() == ISD::UNDEF)
  1833. return N1;
  1834. return SDValue();
  1835. }
  1836. SDValue DAGCombiner::visitMULHS(SDNode *N) {
  1837. SDValue N0 = N->getOperand(0);
  1838. SDValue N1 = N->getOperand(1);
  1839. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  1840. EVT VT = N->getValueType(0);
  1841. DebugLoc DL = N->getDebugLoc();
  1842. // fold (mulhs x, 0) -> 0
  1843. if (N1C && N1C->isNullValue())
  1844. return N1;
  1845. // fold (mulhs x, 1) -> (sra x, size(x)-1)
  1846. if (N1C && N1C->getAPIntValue() == 1)
  1847. return DAG.getNode(ISD::SRA, N->getDebugLoc(), N0.getValueType(), N0,
  1848. DAG.getConstant(N0.getValueType().getSizeInBits() - 1,
  1849. getShiftAmountTy(N0.getValueType())));
  1850. // fold (mulhs x, undef) -> 0
  1851. if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
  1852. return DAG.getConstant(0, VT);
  1853. // If the type twice as wide is legal, transform the mulhs to a wider multiply
  1854. // plus a shift.
  1855. if (VT.isSimple() && !VT.isVector()) {
  1856. MVT Simple = VT.getSimpleVT();
  1857. unsigned SimpleSize = Simple.getSizeInBits();
  1858. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
  1859. if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
  1860. N0 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N0);
  1861. N1 = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N1);
  1862. N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
  1863. N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
  1864. DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
  1865. return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
  1866. }
  1867. }
  1868. return SDValue();
  1869. }
  1870. SDValue DAGCombiner::visitMULHU(SDNode *N) {
  1871. SDValue N0 = N->getOperand(0);
  1872. SDValue N1 = N->getOperand(1);
  1873. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  1874. EVT VT = N->getValueType(0);
  1875. DebugLoc DL = N->getDebugLoc();
  1876. // fold (mulhu x, 0) -> 0
  1877. if (N1C && N1C->isNullValue())
  1878. return N1;
  1879. // fold (mulhu x, 1) -> 0
  1880. if (N1C && N1C->getAPIntValue() == 1)
  1881. return DAG.getConstant(0, N0.getValueType());
  1882. // fold (mulhu x, undef) -> 0
  1883. if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
  1884. return DAG.getConstant(0, VT);
  1885. // If the type twice as wide is legal, transform the mulhu to a wider multiply
  1886. // plus a shift.
  1887. if (VT.isSimple() && !VT.isVector()) {
  1888. MVT Simple = VT.getSimpleVT();
  1889. unsigned SimpleSize = Simple.getSizeInBits();
  1890. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
  1891. if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
  1892. N0 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N0);
  1893. N1 = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N1);
  1894. N1 = DAG.getNode(ISD::MUL, DL, NewVT, N0, N1);
  1895. N1 = DAG.getNode(ISD::SRL, DL, NewVT, N1,
  1896. DAG.getConstant(SimpleSize, getShiftAmountTy(N1.getValueType())));
  1897. return DAG.getNode(ISD::TRUNCATE, DL, VT, N1);
  1898. }
  1899. }
  1900. return SDValue();
  1901. }
  1902. /// SimplifyNodeWithTwoResults - Perform optimizations common to nodes that
  1903. /// compute two values. LoOp and HiOp give the opcodes for the two computations
  1904. /// that are being performed. Return true if a simplification was made.
  1905. ///
  1906. SDValue DAGCombiner::SimplifyNodeWithTwoResults(SDNode *N, unsigned LoOp,
  1907. unsigned HiOp) {
  1908. // If the high half is not needed, just compute the low half.
  1909. bool HiExists = N->hasAnyUseOfValue(1);
  1910. if (!HiExists &&
  1911. (!LegalOperations ||
  1912. TLI.isOperationLegal(LoOp, N->getValueType(0)))) {
  1913. SDValue Res = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
  1914. N->op_begin(), N->getNumOperands());
  1915. return CombineTo(N, Res, Res);
  1916. }
  1917. // If the low half is not needed, just compute the high half.
  1918. bool LoExists = N->hasAnyUseOfValue(0);
  1919. if (!LoExists &&
  1920. (!LegalOperations ||
  1921. TLI.isOperationLegal(HiOp, N->getValueType(1)))) {
  1922. SDValue Res = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
  1923. N->op_begin(), N->getNumOperands());
  1924. return CombineTo(N, Res, Res);
  1925. }
  1926. // If both halves are used, return as it is.
  1927. if (LoExists && HiExists)
  1928. return SDValue();
  1929. // If the two computed results can be simplified separately, separate them.
  1930. if (LoExists) {
  1931. SDValue Lo = DAG.getNode(LoOp, N->getDebugLoc(), N->getValueType(0),
  1932. N->op_begin(), N->getNumOperands());
  1933. AddToWorkList(Lo.getNode());
  1934. SDValue LoOpt = combine(Lo.getNode());
  1935. if (LoOpt.getNode() && LoOpt.getNode() != Lo.getNode() &&
  1936. (!LegalOperations ||
  1937. TLI.isOperationLegal(LoOpt.getOpcode(), LoOpt.getValueType())))
  1938. return CombineTo(N, LoOpt, LoOpt);
  1939. }
  1940. if (HiExists) {
  1941. SDValue Hi = DAG.getNode(HiOp, N->getDebugLoc(), N->getValueType(1),
  1942. N->op_begin(), N->getNumOperands());
  1943. AddToWorkList(Hi.getNode());
  1944. SDValue HiOpt = combine(Hi.getNode());
  1945. if (HiOpt.getNode() && HiOpt != Hi &&
  1946. (!LegalOperations ||
  1947. TLI.isOperationLegal(HiOpt.getOpcode(), HiOpt.getValueType())))
  1948. return CombineTo(N, HiOpt, HiOpt);
  1949. }
  1950. return SDValue();
  1951. }
  1952. SDValue DAGCombiner::visitSMUL_LOHI(SDNode *N) {
  1953. SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHS);
  1954. if (Res.getNode()) return Res;
  1955. EVT VT = N->getValueType(0);
  1956. DebugLoc DL = N->getDebugLoc();
  1957. // If the type twice as wide is legal, transform the mulhu to a wider multiply
  1958. // plus a shift.
  1959. if (VT.isSimple() && !VT.isVector()) {
  1960. MVT Simple = VT.getSimpleVT();
  1961. unsigned SimpleSize = Simple.getSizeInBits();
  1962. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
  1963. if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
  1964. SDValue Lo = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(0));
  1965. SDValue Hi = DAG.getNode(ISD::SIGN_EXTEND, DL, NewVT, N->getOperand(1));
  1966. Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
  1967. // Compute the high part as N1.
  1968. Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
  1969. DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
  1970. Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
  1971. // Compute the low part as N0.
  1972. Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
  1973. return CombineTo(N, Lo, Hi);
  1974. }
  1975. }
  1976. return SDValue();
  1977. }
  1978. SDValue DAGCombiner::visitUMUL_LOHI(SDNode *N) {
  1979. SDValue Res = SimplifyNodeWithTwoResults(N, ISD::MUL, ISD::MULHU);
  1980. if (Res.getNode()) return Res;
  1981. EVT VT = N->getValueType(0);
  1982. DebugLoc DL = N->getDebugLoc();
  1983. // If the type twice as wide is legal, transform the mulhu to a wider multiply
  1984. // plus a shift.
  1985. if (VT.isSimple() && !VT.isVector()) {
  1986. MVT Simple = VT.getSimpleVT();
  1987. unsigned SimpleSize = Simple.getSizeInBits();
  1988. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), SimpleSize*2);
  1989. if (TLI.isOperationLegal(ISD::MUL, NewVT)) {
  1990. SDValue Lo = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(0));
  1991. SDValue Hi = DAG.getNode(ISD::ZERO_EXTEND, DL, NewVT, N->getOperand(1));
  1992. Lo = DAG.getNode(ISD::MUL, DL, NewVT, Lo, Hi);
  1993. // Compute the high part as N1.
  1994. Hi = DAG.getNode(ISD::SRL, DL, NewVT, Lo,
  1995. DAG.getConstant(SimpleSize, getShiftAmountTy(Lo.getValueType())));
  1996. Hi = DAG.getNode(ISD::TRUNCATE, DL, VT, Hi);
  1997. // Compute the low part as N0.
  1998. Lo = DAG.getNode(ISD::TRUNCATE, DL, VT, Lo);
  1999. return CombineTo(N, Lo, Hi);
  2000. }
  2001. }
  2002. return SDValue();
  2003. }
  2004. SDValue DAGCombiner::visitSMULO(SDNode *N) {
  2005. // (smulo x, 2) -> (saddo x, x)
  2006. if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
  2007. if (C2->getAPIntValue() == 2)
  2008. return DAG.getNode(ISD::SADDO, N->getDebugLoc(), N->getVTList(),
  2009. N->getOperand(0), N->getOperand(0));
  2010. return SDValue();
  2011. }
  2012. SDValue DAGCombiner::visitUMULO(SDNode *N) {
  2013. // (umulo x, 2) -> (uaddo x, x)
  2014. if (ConstantSDNode *C2 = dyn_cast<ConstantSDNode>(N->getOperand(1)))
  2015. if (C2->getAPIntValue() == 2)
  2016. return DAG.getNode(ISD::UADDO, N->getDebugLoc(), N->getVTList(),
  2017. N->getOperand(0), N->getOperand(0));
  2018. return SDValue();
  2019. }
  2020. SDValue DAGCombiner::visitSDIVREM(SDNode *N) {
  2021. SDValue Res = SimplifyNodeWithTwoResults(N, ISD::SDIV, ISD::SREM);
  2022. if (Res.getNode()) return Res;
  2023. return SDValue();
  2024. }
  2025. SDValue DAGCombiner::visitUDIVREM(SDNode *N) {
  2026. SDValue Res = SimplifyNodeWithTwoResults(N, ISD::UDIV, ISD::UREM);
  2027. if (Res.getNode()) return Res;
  2028. return SDValue();
  2029. }
  2030. /// SimplifyBinOpWithSameOpcodeHands - If this is a binary operator with
  2031. /// two operands of the same opcode, try to simplify it.
  2032. SDValue DAGCombiner::SimplifyBinOpWithSameOpcodeHands(SDNode *N) {
  2033. SDValue N0 = N->getOperand(0), N1 = N->getOperand(1);
  2034. EVT VT = N0.getValueType();
  2035. assert(N0.getOpcode() == N1.getOpcode() && "Bad input!");
  2036. // Bail early if none of these transforms apply.
  2037. if (N0.getNode()->getNumOperands() == 0) return SDValue();
  2038. // For each of OP in AND/OR/XOR:
  2039. // fold (OP (zext x), (zext y)) -> (zext (OP x, y))
  2040. // fold (OP (sext x), (sext y)) -> (sext (OP x, y))
  2041. // fold (OP (aext x), (aext y)) -> (aext (OP x, y))
  2042. // fold (OP (trunc x), (trunc y)) -> (trunc (OP x, y)) (if trunc isn't free)
  2043. //
  2044. // do not sink logical op inside of a vector extend, since it may combine
  2045. // into a vsetcc.
  2046. EVT Op0VT = N0.getOperand(0).getValueType();
  2047. if ((N0.getOpcode() == ISD::ZERO_EXTEND ||
  2048. N0.getOpcode() == ISD::SIGN_EXTEND ||
  2049. // Avoid infinite looping with PromoteIntBinOp.
  2050. (N0.getOpcode() == ISD::ANY_EXTEND &&
  2051. (!LegalTypes || TLI.isTypeDesirableForOp(N->getOpcode(), Op0VT))) ||
  2052. (N0.getOpcode() == ISD::TRUNCATE &&
  2053. (!TLI.isZExtFree(VT, Op0VT) ||
  2054. !TLI.isTruncateFree(Op0VT, VT)) &&
  2055. TLI.isTypeLegal(Op0VT))) &&
  2056. !VT.isVector() &&
  2057. Op0VT == N1.getOperand(0).getValueType() &&
  2058. (!LegalOperations || TLI.isOperationLegal(N->getOpcode(), Op0VT))) {
  2059. SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
  2060. N0.getOperand(0).getValueType(),
  2061. N0.getOperand(0), N1.getOperand(0));
  2062. AddToWorkList(ORNode.getNode());
  2063. return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, ORNode);
  2064. }
  2065. // For each of OP in SHL/SRL/SRA/AND...
  2066. // fold (and (OP x, z), (OP y, z)) -> (OP (and x, y), z)
  2067. // fold (or (OP x, z), (OP y, z)) -> (OP (or x, y), z)
  2068. // fold (xor (OP x, z), (OP y, z)) -> (OP (xor x, y), z)
  2069. if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL ||
  2070. N0.getOpcode() == ISD::SRA || N0.getOpcode() == ISD::AND) &&
  2071. N0.getOperand(1) == N1.getOperand(1)) {
  2072. SDValue ORNode = DAG.getNode(N->getOpcode(), N0.getDebugLoc(),
  2073. N0.getOperand(0).getValueType(),
  2074. N0.getOperand(0), N1.getOperand(0));
  2075. AddToWorkList(ORNode.getNode());
  2076. return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
  2077. ORNode, N0.getOperand(1));
  2078. }
  2079. // Simplify xor/and/or (bitcast(A), bitcast(B)) -> bitcast(op (A,B))
  2080. // Only perform this optimization after type legalization and before
  2081. // LegalizeVectorOprs. LegalizeVectorOprs promotes vector operations by
  2082. // adding bitcasts. For example (xor v4i32) is promoted to (v2i64), and
  2083. // we don't want to undo this promotion.
  2084. // We also handle SCALAR_TO_VECTOR because xor/or/and operations are cheaper
  2085. // on scalars.
  2086. if ((N0.getOpcode() == ISD::BITCAST ||
  2087. N0.getOpcode() == ISD::SCALAR_TO_VECTOR) &&
  2088. Level == AfterLegalizeTypes) {
  2089. SDValue In0 = N0.getOperand(0);
  2090. SDValue In1 = N1.getOperand(0);
  2091. EVT In0Ty = In0.getValueType();
  2092. EVT In1Ty = In1.getValueType();
  2093. DebugLoc DL = N->getDebugLoc();
  2094. // If both incoming values are integers, and the original types are the
  2095. // same.
  2096. if (In0Ty.isInteger() && In1Ty.isInteger() && In0Ty == In1Ty) {
  2097. SDValue Op = DAG.getNode(N->getOpcode(), DL, In0Ty, In0, In1);
  2098. SDValue BC = DAG.getNode(N0.getOpcode(), DL, VT, Op);
  2099. AddToWorkList(Op.getNode());
  2100. return BC;
  2101. }
  2102. }
  2103. // Xor/and/or are indifferent to the swizzle operation (shuffle of one value).
  2104. // Simplify xor/and/or (shuff(A), shuff(B)) -> shuff(op (A,B))
  2105. // If both shuffles use the same mask, and both shuffle within a single
  2106. // vector, then it is worthwhile to move the swizzle after the operation.
  2107. // The type-legalizer generates this pattern when loading illegal
  2108. // vector types from memory. In many cases this allows additional shuffle
  2109. // optimizations.
  2110. if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
  2111. N0.getOperand(1).getOpcode() == ISD::UNDEF &&
  2112. N1.getOperand(1).getOpcode() == ISD::UNDEF) {
  2113. ShuffleVectorSDNode *SVN0 = cast<ShuffleVectorSDNode>(N0);
  2114. ShuffleVectorSDNode *SVN1 = cast<ShuffleVectorSDNode>(N1);
  2115. assert(N0.getOperand(0).getValueType() == N1.getOperand(1).getValueType() &&
  2116. "Inputs to shuffles are not the same type");
  2117. unsigned NumElts = VT.getVectorNumElements();
  2118. // Check that both shuffles use the same mask. The masks are known to be of
  2119. // the same length because the result vector type is the same.
  2120. bool SameMask = true;
  2121. for (unsigned i = 0; i != NumElts; ++i) {
  2122. int Idx0 = SVN0->getMaskElt(i);
  2123. int Idx1 = SVN1->getMaskElt(i);
  2124. if (Idx0 != Idx1) {
  2125. SameMask = false;
  2126. break;
  2127. }
  2128. }
  2129. if (SameMask) {
  2130. SDValue Op = DAG.getNode(N->getOpcode(), N->getDebugLoc(), VT,
  2131. N0.getOperand(0), N1.getOperand(0));
  2132. AddToWorkList(Op.getNode());
  2133. return DAG.getVectorShuffle(VT, N->getDebugLoc(), Op,
  2134. DAG.getUNDEF(VT), &SVN0->getMask()[0]);
  2135. }
  2136. }
  2137. return SDValue();
  2138. }
  2139. SDValue DAGCombiner::visitAND(SDNode *N) {
  2140. SDValue N0 = N->getOperand(0);
  2141. SDValue N1 = N->getOperand(1);
  2142. SDValue LL, LR, RL, RR, CC0, CC1;
  2143. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  2144. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  2145. EVT VT = N1.getValueType();
  2146. unsigned BitWidth = VT.getScalarType().getSizeInBits();
  2147. // fold vector ops
  2148. if (VT.isVector()) {
  2149. SDValue FoldedVOp = SimplifyVBinOp(N);
  2150. if (FoldedVOp.getNode()) return FoldedVOp;
  2151. // fold (and x, 0) -> 0, vector edition
  2152. if (ISD::isBuildVectorAllZeros(N0.getNode()))
  2153. return N0;
  2154. if (ISD::isBuildVectorAllZeros(N1.getNode()))
  2155. return N1;
  2156. // fold (and x, -1) -> x, vector edition
  2157. if (ISD::isBuildVectorAllOnes(N0.getNode()))
  2158. return N1;
  2159. if (ISD::isBuildVectorAllOnes(N1.getNode()))
  2160. return N0;
  2161. }
  2162. // fold (and x, undef) -> 0
  2163. if (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)
  2164. return DAG.getConstant(0, VT);
  2165. // fold (and c1, c2) -> c1&c2
  2166. if (N0C && N1C)
  2167. return DAG.FoldConstantArithmetic(ISD::AND, VT, N0C, N1C);
  2168. // canonicalize constant to RHS
  2169. if (N0C && !N1C)
  2170. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N1, N0);
  2171. // fold (and x, -1) -> x
  2172. if (N1C && N1C->isAllOnesValue())
  2173. return N0;
  2174. // if (and x, c) is known to be zero, return 0
  2175. if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
  2176. APInt::getAllOnesValue(BitWidth)))
  2177. return DAG.getConstant(0, VT);
  2178. // reassociate and
  2179. SDValue RAND = ReassociateOps(ISD::AND, N->getDebugLoc(), N0, N1);
  2180. if (RAND.getNode() != 0)
  2181. return RAND;
  2182. // fold (and (or x, C), D) -> D if (C & D) == D
  2183. if (N1C && N0.getOpcode() == ISD::OR)
  2184. if (ConstantSDNode *ORI = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
  2185. if ((ORI->getAPIntValue() & N1C->getAPIntValue()) == N1C->getAPIntValue())
  2186. return N1;
  2187. // fold (and (any_ext V), c) -> (zero_ext V) if 'and' only clears top bits.
  2188. if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
  2189. SDValue N0Op0 = N0.getOperand(0);
  2190. APInt Mask = ~N1C->getAPIntValue();
  2191. Mask = Mask.trunc(N0Op0.getValueSizeInBits());
  2192. if (DAG.MaskedValueIsZero(N0Op0, Mask)) {
  2193. SDValue Zext = DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(),
  2194. N0.getValueType(), N0Op0);
  2195. // Replace uses of the AND with uses of the Zero extend node.
  2196. CombineTo(N, Zext);
  2197. // We actually want to replace all uses of the any_extend with the
  2198. // zero_extend, to avoid duplicating things. This will later cause this
  2199. // AND to be folded.
  2200. CombineTo(N0.getNode(), Zext);
  2201. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  2202. }
  2203. }
  2204. // similarly fold (and (X (load ([non_ext|any_ext|zero_ext] V))), c) ->
  2205. // (X (load ([non_ext|zero_ext] V))) if 'and' only clears top bits which must
  2206. // already be zero by virtue of the width of the base type of the load.
  2207. //
  2208. // the 'X' node here can either be nothing or an extract_vector_elt to catch
  2209. // more cases.
  2210. if ((N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  2211. N0.getOperand(0).getOpcode() == ISD::LOAD) ||
  2212. N0.getOpcode() == ISD::LOAD) {
  2213. LoadSDNode *Load = cast<LoadSDNode>( (N0.getOpcode() == ISD::LOAD) ?
  2214. N0 : N0.getOperand(0) );
  2215. // Get the constant (if applicable) the zero'th operand is being ANDed with.
  2216. // This can be a pure constant or a vector splat, in which case we treat the
  2217. // vector as a scalar and use the splat value.
  2218. APInt Constant = APInt::getNullValue(1);
  2219. if (const ConstantSDNode *C = dyn_cast<ConstantSDNode>(N1)) {
  2220. Constant = C->getAPIntValue();
  2221. } else if (BuildVectorSDNode *Vector = dyn_cast<BuildVectorSDNode>(N1)) {
  2222. APInt SplatValue, SplatUndef;
  2223. unsigned SplatBitSize;
  2224. bool HasAnyUndefs;
  2225. bool IsSplat = Vector->isConstantSplat(SplatValue, SplatUndef,
  2226. SplatBitSize, HasAnyUndefs);
  2227. if (IsSplat) {
  2228. // Undef bits can contribute to a possible optimisation if set, so
  2229. // set them.
  2230. SplatValue |= SplatUndef;
  2231. // The splat value may be something like "0x00FFFFFF", which means 0 for
  2232. // the first vector value and FF for the rest, repeating. We need a mask
  2233. // that will apply equally to all members of the vector, so AND all the
  2234. // lanes of the constant together.
  2235. EVT VT = Vector->getValueType(0);
  2236. unsigned BitWidth = VT.getVectorElementType().getSizeInBits();
  2237. // If the splat value has been compressed to a bitlength lower
  2238. // than the size of the vector lane, we need to re-expand it to
  2239. // the lane size.
  2240. if (BitWidth > SplatBitSize)
  2241. for (SplatValue = SplatValue.zextOrTrunc(BitWidth);
  2242. SplatBitSize < BitWidth;
  2243. SplatBitSize = SplatBitSize * 2)
  2244. SplatValue |= SplatValue.shl(SplatBitSize);
  2245. Constant = APInt::getAllOnesValue(BitWidth);
  2246. for (unsigned i = 0, n = SplatBitSize/BitWidth; i < n; ++i)
  2247. Constant &= SplatValue.lshr(i*BitWidth).zextOrTrunc(BitWidth);
  2248. }
  2249. }
  2250. // If we want to change an EXTLOAD to a ZEXTLOAD, ensure a ZEXTLOAD is
  2251. // actually legal and isn't going to get expanded, else this is a false
  2252. // optimisation.
  2253. bool CanZextLoadProfitably = TLI.isLoadExtLegal(ISD::ZEXTLOAD,
  2254. Load->getMemoryVT());
  2255. // Resize the constant to the same size as the original memory access before
  2256. // extension. If it is still the AllOnesValue then this AND is completely
  2257. // unneeded.
  2258. Constant =
  2259. Constant.zextOrTrunc(Load->getMemoryVT().getScalarType().getSizeInBits());
  2260. bool B;
  2261. switch (Load->getExtensionType()) {
  2262. default: B = false; break;
  2263. case ISD::EXTLOAD: B = CanZextLoadProfitably; break;
  2264. case ISD::ZEXTLOAD:
  2265. case ISD::NON_EXTLOAD: B = true; break;
  2266. }
  2267. if (B && Constant.isAllOnesValue()) {
  2268. // If the load type was an EXTLOAD, convert to ZEXTLOAD in order to
  2269. // preserve semantics once we get rid of the AND.
  2270. SDValue NewLoad(Load, 0);
  2271. if (Load->getExtensionType() == ISD::EXTLOAD) {
  2272. NewLoad = DAG.getLoad(Load->getAddressingMode(), ISD::ZEXTLOAD,
  2273. Load->getValueType(0), Load->getDebugLoc(),
  2274. Load->getChain(), Load->getBasePtr(),
  2275. Load->getOffset(), Load->getMemoryVT(),
  2276. Load->getMemOperand());
  2277. // Replace uses of the EXTLOAD with the new ZEXTLOAD.
  2278. if (Load->getNumValues() == 3) {
  2279. // PRE/POST_INC loads have 3 values.
  2280. SDValue To[] = { NewLoad.getValue(0), NewLoad.getValue(1),
  2281. NewLoad.getValue(2) };
  2282. CombineTo(Load, To, 3, true);
  2283. } else {
  2284. CombineTo(Load, NewLoad.getValue(0), NewLoad.getValue(1));
  2285. }
  2286. }
  2287. // Fold the AND away, taking care not to fold to the old load node if we
  2288. // replaced it.
  2289. CombineTo(N, (N0.getNode() == Load) ? NewLoad : N0);
  2290. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  2291. }
  2292. }
  2293. // fold (and (setcc x), (setcc y)) -> (setcc (and x, y))
  2294. if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
  2295. ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
  2296. ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
  2297. if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
  2298. LL.getValueType().isInteger()) {
  2299. // fold (and (seteq X, 0), (seteq Y, 0)) -> (seteq (or X, Y), 0)
  2300. if (cast<ConstantSDNode>(LR)->isNullValue() && Op1 == ISD::SETEQ) {
  2301. SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
  2302. LR.getValueType(), LL, RL);
  2303. AddToWorkList(ORNode.getNode());
  2304. return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
  2305. }
  2306. // fold (and (seteq X, -1), (seteq Y, -1)) -> (seteq (and X, Y), -1)
  2307. if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETEQ) {
  2308. SDValue ANDNode = DAG.getNode(ISD::AND, N0.getDebugLoc(),
  2309. LR.getValueType(), LL, RL);
  2310. AddToWorkList(ANDNode.getNode());
  2311. return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
  2312. }
  2313. // fold (and (setgt X, -1), (setgt Y, -1)) -> (setgt (or X, Y), -1)
  2314. if (cast<ConstantSDNode>(LR)->isAllOnesValue() && Op1 == ISD::SETGT) {
  2315. SDValue ORNode = DAG.getNode(ISD::OR, N0.getDebugLoc(),
  2316. LR.getValueType(), LL, RL);
  2317. AddToWorkList(ORNode.getNode());
  2318. return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
  2319. }
  2320. }
  2321. // canonicalize equivalent to ll == rl
  2322. if (LL == RR && LR == RL) {
  2323. Op1 = ISD::getSetCCSwappedOperands(Op1);
  2324. std::swap(RL, RR);
  2325. }
  2326. if (LL == RL && LR == RR) {
  2327. bool isInteger = LL.getValueType().isInteger();
  2328. ISD::CondCode Result = ISD::getSetCCAndOperation(Op0, Op1, isInteger);
  2329. if (Result != ISD::SETCC_INVALID &&
  2330. (!LegalOperations ||
  2331. (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
  2332. TLI.isOperationLegal(ISD::SETCC,
  2333. getSetCCResultType(N0.getSimpleValueType())))))
  2334. return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
  2335. LL, LR, Result);
  2336. }
  2337. }
  2338. // Simplify: (and (op x...), (op y...)) -> (op (and x, y))
  2339. if (N0.getOpcode() == N1.getOpcode()) {
  2340. SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
  2341. if (Tmp.getNode()) return Tmp;
  2342. }
  2343. // fold (and (sign_extend_inreg x, i16 to i32), 1) -> (and x, 1)
  2344. // fold (and (sra)) -> (and (srl)) when possible.
  2345. if (!VT.isVector() &&
  2346. SimplifyDemandedBits(SDValue(N, 0)))
  2347. return SDValue(N, 0);
  2348. // fold (zext_inreg (extload x)) -> (zextload x)
  2349. if (ISD::isEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode())) {
  2350. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  2351. EVT MemVT = LN0->getMemoryVT();
  2352. // If we zero all the possible extended bits, then we can turn this into
  2353. // a zextload if we are running before legalize or the operation is legal.
  2354. unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
  2355. if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
  2356. BitWidth - MemVT.getScalarType().getSizeInBits())) &&
  2357. ((!LegalOperations && !LN0->isVolatile()) ||
  2358. TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
  2359. SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
  2360. LN0->getChain(), LN0->getBasePtr(),
  2361. LN0->getPointerInfo(), MemVT,
  2362. LN0->isVolatile(), LN0->isNonTemporal(),
  2363. LN0->getAlignment());
  2364. AddToWorkList(N);
  2365. CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
  2366. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  2367. }
  2368. }
  2369. // fold (zext_inreg (sextload x)) -> (zextload x) iff load has one use
  2370. if (ISD::isSEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
  2371. N0.hasOneUse()) {
  2372. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  2373. EVT MemVT = LN0->getMemoryVT();
  2374. // If we zero all the possible extended bits, then we can turn this into
  2375. // a zextload if we are running before legalize or the operation is legal.
  2376. unsigned BitWidth = N1.getValueType().getScalarType().getSizeInBits();
  2377. if (DAG.MaskedValueIsZero(N1, APInt::getHighBitsSet(BitWidth,
  2378. BitWidth - MemVT.getScalarType().getSizeInBits())) &&
  2379. ((!LegalOperations && !LN0->isVolatile()) ||
  2380. TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT))) {
  2381. SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N0.getDebugLoc(), VT,
  2382. LN0->getChain(),
  2383. LN0->getBasePtr(), LN0->getPointerInfo(),
  2384. MemVT,
  2385. LN0->isVolatile(), LN0->isNonTemporal(),
  2386. LN0->getAlignment());
  2387. AddToWorkList(N);
  2388. CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
  2389. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  2390. }
  2391. }
  2392. // fold (and (load x), 255) -> (zextload x, i8)
  2393. // fold (and (extload x, i16), 255) -> (zextload x, i8)
  2394. // fold (and (any_ext (extload x, i16)), 255) -> (zextload x, i8)
  2395. if (N1C && (N0.getOpcode() == ISD::LOAD ||
  2396. (N0.getOpcode() == ISD::ANY_EXTEND &&
  2397. N0.getOperand(0).getOpcode() == ISD::LOAD))) {
  2398. bool HasAnyExt = N0.getOpcode() == ISD::ANY_EXTEND;
  2399. LoadSDNode *LN0 = HasAnyExt
  2400. ? cast<LoadSDNode>(N0.getOperand(0))
  2401. : cast<LoadSDNode>(N0);
  2402. if (LN0->getExtensionType() != ISD::SEXTLOAD &&
  2403. LN0->isUnindexed() && N0.hasOneUse() && LN0->hasOneUse()) {
  2404. uint32_t ActiveBits = N1C->getAPIntValue().getActiveBits();
  2405. if (ActiveBits > 0 && APIntOps::isMask(ActiveBits, N1C->getAPIntValue())){
  2406. EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), ActiveBits);
  2407. EVT LoadedVT = LN0->getMemoryVT();
  2408. if (ExtVT == LoadedVT &&
  2409. (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
  2410. EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
  2411. SDValue NewLoad =
  2412. DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
  2413. LN0->getChain(), LN0->getBasePtr(),
  2414. LN0->getPointerInfo(),
  2415. ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
  2416. LN0->getAlignment());
  2417. AddToWorkList(N);
  2418. CombineTo(LN0, NewLoad, NewLoad.getValue(1));
  2419. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  2420. }
  2421. // Do not change the width of a volatile load.
  2422. // Do not generate loads of non-round integer types since these can
  2423. // be expensive (and would be wrong if the type is not byte sized).
  2424. if (!LN0->isVolatile() && LoadedVT.bitsGT(ExtVT) && ExtVT.isRound() &&
  2425. (!LegalOperations || TLI.isLoadExtLegal(ISD::ZEXTLOAD, ExtVT))) {
  2426. EVT PtrType = LN0->getOperand(1).getValueType();
  2427. unsigned Alignment = LN0->getAlignment();
  2428. SDValue NewPtr = LN0->getBasePtr();
  2429. // For big endian targets, we need to add an offset to the pointer
  2430. // to load the correct bytes. For little endian systems, we merely
  2431. // need to read fewer bytes from the same pointer.
  2432. if (TLI.isBigEndian()) {
  2433. unsigned LVTStoreBytes = LoadedVT.getStoreSize();
  2434. unsigned EVTStoreBytes = ExtVT.getStoreSize();
  2435. unsigned PtrOff = LVTStoreBytes - EVTStoreBytes;
  2436. NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(), PtrType,
  2437. NewPtr, DAG.getConstant(PtrOff, PtrType));
  2438. Alignment = MinAlign(Alignment, PtrOff);
  2439. }
  2440. AddToWorkList(NewPtr.getNode());
  2441. EVT LoadResultTy = HasAnyExt ? LN0->getValueType(0) : VT;
  2442. SDValue Load =
  2443. DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), LoadResultTy,
  2444. LN0->getChain(), NewPtr,
  2445. LN0->getPointerInfo(),
  2446. ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
  2447. Alignment);
  2448. AddToWorkList(N);
  2449. CombineTo(LN0, Load, Load.getValue(1));
  2450. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  2451. }
  2452. }
  2453. }
  2454. }
  2455. if (N0.getOpcode() == ISD::ADD && N1.getOpcode() == ISD::SRL &&
  2456. VT.getSizeInBits() <= 64) {
  2457. if (ConstantSDNode *ADDI = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
  2458. APInt ADDC = ADDI->getAPIntValue();
  2459. if (!TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
  2460. // Look for (and (add x, c1), (lshr y, c2)). If C1 wasn't a legal
  2461. // immediate for an add, but it is legal if its top c2 bits are set,
  2462. // transform the ADD so the immediate doesn't need to be materialized
  2463. // in a register.
  2464. if (ConstantSDNode *SRLI = dyn_cast<ConstantSDNode>(N1.getOperand(1))) {
  2465. APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
  2466. SRLI->getZExtValue());
  2467. if (DAG.MaskedValueIsZero(N0.getOperand(1), Mask)) {
  2468. ADDC |= Mask;
  2469. if (TLI.isLegalAddImmediate(ADDC.getSExtValue())) {
  2470. SDValue NewAdd =
  2471. DAG.getNode(ISD::ADD, N0.getDebugLoc(), VT,
  2472. N0.getOperand(0), DAG.getConstant(ADDC, VT));
  2473. CombineTo(N0.getNode(), NewAdd);
  2474. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  2475. }
  2476. }
  2477. }
  2478. }
  2479. }
  2480. }
  2481. return SDValue();
  2482. }
  2483. /// MatchBSwapHWord - Match (a >> 8) | (a << 8) as (bswap a) >> 16
  2484. ///
  2485. SDValue DAGCombiner::MatchBSwapHWordLow(SDNode *N, SDValue N0, SDValue N1,
  2486. bool DemandHighBits) {
  2487. if (!LegalOperations)
  2488. return SDValue();
  2489. EVT VT = N->getValueType(0);
  2490. if (VT != MVT::i64 && VT != MVT::i32 && VT != MVT::i16)
  2491. return SDValue();
  2492. if (!TLI.isOperationLegal(ISD::BSWAP, VT))
  2493. return SDValue();
  2494. // Recognize (and (shl a, 8), 0xff), (and (srl a, 8), 0xff00)
  2495. bool LookPassAnd0 = false;
  2496. bool LookPassAnd1 = false;
  2497. if (N0.getOpcode() == ISD::AND && N0.getOperand(0).getOpcode() == ISD::SRL)
  2498. std::swap(N0, N1);
  2499. if (N1.getOpcode() == ISD::AND && N1.getOperand(0).getOpcode() == ISD::SHL)
  2500. std::swap(N0, N1);
  2501. if (N0.getOpcode() == ISD::AND) {
  2502. if (!N0.getNode()->hasOneUse())
  2503. return SDValue();
  2504. ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  2505. if (!N01C || N01C->getZExtValue() != 0xFF00)
  2506. return SDValue();
  2507. N0 = N0.getOperand(0);
  2508. LookPassAnd0 = true;
  2509. }
  2510. if (N1.getOpcode() == ISD::AND) {
  2511. if (!N1.getNode()->hasOneUse())
  2512. return SDValue();
  2513. ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
  2514. if (!N11C || N11C->getZExtValue() != 0xFF)
  2515. return SDValue();
  2516. N1 = N1.getOperand(0);
  2517. LookPassAnd1 = true;
  2518. }
  2519. if (N0.getOpcode() == ISD::SRL && N1.getOpcode() == ISD::SHL)
  2520. std::swap(N0, N1);
  2521. if (N0.getOpcode() != ISD::SHL || N1.getOpcode() != ISD::SRL)
  2522. return SDValue();
  2523. if (!N0.getNode()->hasOneUse() ||
  2524. !N1.getNode()->hasOneUse())
  2525. return SDValue();
  2526. ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  2527. ConstantSDNode *N11C = dyn_cast<ConstantSDNode>(N1.getOperand(1));
  2528. if (!N01C || !N11C)
  2529. return SDValue();
  2530. if (N01C->getZExtValue() != 8 || N11C->getZExtValue() != 8)
  2531. return SDValue();
  2532. // Look for (shl (and a, 0xff), 8), (srl (and a, 0xff00), 8)
  2533. SDValue N00 = N0->getOperand(0);
  2534. if (!LookPassAnd0 && N00.getOpcode() == ISD::AND) {
  2535. if (!N00.getNode()->hasOneUse())
  2536. return SDValue();
  2537. ConstantSDNode *N001C = dyn_cast<ConstantSDNode>(N00.getOperand(1));
  2538. if (!N001C || N001C->getZExtValue() != 0xFF)
  2539. return SDValue();
  2540. N00 = N00.getOperand(0);
  2541. LookPassAnd0 = true;
  2542. }
  2543. SDValue N10 = N1->getOperand(0);
  2544. if (!LookPassAnd1 && N10.getOpcode() == ISD::AND) {
  2545. if (!N10.getNode()->hasOneUse())
  2546. return SDValue();
  2547. ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N10.getOperand(1));
  2548. if (!N101C || N101C->getZExtValue() != 0xFF00)
  2549. return SDValue();
  2550. N10 = N10.getOperand(0);
  2551. LookPassAnd1 = true;
  2552. }
  2553. if (N00 != N10)
  2554. return SDValue();
  2555. // Make sure everything beyond the low halfword is zero since the SRL 16
  2556. // will clear the top bits.
  2557. unsigned OpSizeInBits = VT.getSizeInBits();
  2558. if (DemandHighBits && OpSizeInBits > 16 &&
  2559. (!LookPassAnd0 || !LookPassAnd1) &&
  2560. !DAG.MaskedValueIsZero(N10, APInt::getHighBitsSet(OpSizeInBits, 16)))
  2561. return SDValue();
  2562. SDValue Res = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT, N00);
  2563. if (OpSizeInBits > 16)
  2564. Res = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, Res,
  2565. DAG.getConstant(OpSizeInBits-16, getShiftAmountTy(VT)));
  2566. return Res;
  2567. }
  2568. /// isBSwapHWordElement - Return true if the specified node is an element
  2569. /// that makes up a 32-bit packed halfword byteswap. i.e.
  2570. /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
  2571. static bool isBSwapHWordElement(SDValue N, SmallVector<SDNode*,4> &Parts) {
  2572. if (!N.getNode()->hasOneUse())
  2573. return false;
  2574. unsigned Opc = N.getOpcode();
  2575. if (Opc != ISD::AND && Opc != ISD::SHL && Opc != ISD::SRL)
  2576. return false;
  2577. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N.getOperand(1));
  2578. if (!N1C)
  2579. return false;
  2580. unsigned Num;
  2581. switch (N1C->getZExtValue()) {
  2582. default:
  2583. return false;
  2584. case 0xFF: Num = 0; break;
  2585. case 0xFF00: Num = 1; break;
  2586. case 0xFF0000: Num = 2; break;
  2587. case 0xFF000000: Num = 3; break;
  2588. }
  2589. // Look for (x & 0xff) << 8 as well as ((x << 8) & 0xff00).
  2590. SDValue N0 = N.getOperand(0);
  2591. if (Opc == ISD::AND) {
  2592. if (Num == 0 || Num == 2) {
  2593. // (x >> 8) & 0xff
  2594. // (x >> 8) & 0xff0000
  2595. if (N0.getOpcode() != ISD::SRL)
  2596. return false;
  2597. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  2598. if (!C || C->getZExtValue() != 8)
  2599. return false;
  2600. } else {
  2601. // (x << 8) & 0xff00
  2602. // (x << 8) & 0xff000000
  2603. if (N0.getOpcode() != ISD::SHL)
  2604. return false;
  2605. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  2606. if (!C || C->getZExtValue() != 8)
  2607. return false;
  2608. }
  2609. } else if (Opc == ISD::SHL) {
  2610. // (x & 0xff) << 8
  2611. // (x & 0xff0000) << 8
  2612. if (Num != 0 && Num != 2)
  2613. return false;
  2614. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
  2615. if (!C || C->getZExtValue() != 8)
  2616. return false;
  2617. } else { // Opc == ISD::SRL
  2618. // (x & 0xff00) >> 8
  2619. // (x & 0xff000000) >> 8
  2620. if (Num != 1 && Num != 3)
  2621. return false;
  2622. ConstantSDNode *C = dyn_cast<ConstantSDNode>(N.getOperand(1));
  2623. if (!C || C->getZExtValue() != 8)
  2624. return false;
  2625. }
  2626. if (Parts[Num])
  2627. return false;
  2628. Parts[Num] = N0.getOperand(0).getNode();
  2629. return true;
  2630. }
  2631. /// MatchBSwapHWord - Match a 32-bit packed halfword bswap. That is
  2632. /// ((x&0xff)<<8)|((x&0xff00)>>8)|((x&0x00ff0000)<<8)|((x&0xff000000)>>8)
  2633. /// => (rotl (bswap x), 16)
  2634. SDValue DAGCombiner::MatchBSwapHWord(SDNode *N, SDValue N0, SDValue N1) {
  2635. if (!LegalOperations)
  2636. return SDValue();
  2637. EVT VT = N->getValueType(0);
  2638. if (VT != MVT::i32)
  2639. return SDValue();
  2640. if (!TLI.isOperationLegal(ISD::BSWAP, VT))
  2641. return SDValue();
  2642. SmallVector<SDNode*,4> Parts(4, (SDNode*)0);
  2643. // Look for either
  2644. // (or (or (and), (and)), (or (and), (and)))
  2645. // (or (or (or (and), (and)), (and)), (and))
  2646. if (N0.getOpcode() != ISD::OR)
  2647. return SDValue();
  2648. SDValue N00 = N0.getOperand(0);
  2649. SDValue N01 = N0.getOperand(1);
  2650. if (N1.getOpcode() == ISD::OR &&
  2651. N00.getNumOperands() == 2 && N01.getNumOperands() == 2) {
  2652. // (or (or (and), (and)), (or (and), (and)))
  2653. SDValue N000 = N00.getOperand(0);
  2654. if (!isBSwapHWordElement(N000, Parts))
  2655. return SDValue();
  2656. SDValue N001 = N00.getOperand(1);
  2657. if (!isBSwapHWordElement(N001, Parts))
  2658. return SDValue();
  2659. SDValue N010 = N01.getOperand(0);
  2660. if (!isBSwapHWordElement(N010, Parts))
  2661. return SDValue();
  2662. SDValue N011 = N01.getOperand(1);
  2663. if (!isBSwapHWordElement(N011, Parts))
  2664. return SDValue();
  2665. } else {
  2666. // (or (or (or (and), (and)), (and)), (and))
  2667. if (!isBSwapHWordElement(N1, Parts))
  2668. return SDValue();
  2669. if (!isBSwapHWordElement(N01, Parts))
  2670. return SDValue();
  2671. if (N00.getOpcode() != ISD::OR)
  2672. return SDValue();
  2673. SDValue N000 = N00.getOperand(0);
  2674. if (!isBSwapHWordElement(N000, Parts))
  2675. return SDValue();
  2676. SDValue N001 = N00.getOperand(1);
  2677. if (!isBSwapHWordElement(N001, Parts))
  2678. return SDValue();
  2679. }
  2680. // Make sure the parts are all coming from the same node.
  2681. if (Parts[0] != Parts[1] || Parts[0] != Parts[2] || Parts[0] != Parts[3])
  2682. return SDValue();
  2683. SDValue BSwap = DAG.getNode(ISD::BSWAP, N->getDebugLoc(), VT,
  2684. SDValue(Parts[0],0));
  2685. // Result of the bswap should be rotated by 16. If it's not legal, than
  2686. // do (x << 16) | (x >> 16).
  2687. SDValue ShAmt = DAG.getConstant(16, getShiftAmountTy(VT));
  2688. if (TLI.isOperationLegalOrCustom(ISD::ROTL, VT))
  2689. return DAG.getNode(ISD::ROTL, N->getDebugLoc(), VT, BSwap, ShAmt);
  2690. if (TLI.isOperationLegalOrCustom(ISD::ROTR, VT))
  2691. return DAG.getNode(ISD::ROTR, N->getDebugLoc(), VT, BSwap, ShAmt);
  2692. return DAG.getNode(ISD::OR, N->getDebugLoc(), VT,
  2693. DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, BSwap, ShAmt),
  2694. DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, BSwap, ShAmt));
  2695. }
  2696. SDValue DAGCombiner::visitOR(SDNode *N) {
  2697. SDValue N0 = N->getOperand(0);
  2698. SDValue N1 = N->getOperand(1);
  2699. SDValue LL, LR, RL, RR, CC0, CC1;
  2700. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  2701. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  2702. EVT VT = N1.getValueType();
  2703. // fold vector ops
  2704. if (VT.isVector()) {
  2705. SDValue FoldedVOp = SimplifyVBinOp(N);
  2706. if (FoldedVOp.getNode()) return FoldedVOp;
  2707. // fold (or x, 0) -> x, vector edition
  2708. if (ISD::isBuildVectorAllZeros(N0.getNode()))
  2709. return N1;
  2710. if (ISD::isBuildVectorAllZeros(N1.getNode()))
  2711. return N0;
  2712. // fold (or x, -1) -> -1, vector edition
  2713. if (ISD::isBuildVectorAllOnes(N0.getNode()))
  2714. return N0;
  2715. if (ISD::isBuildVectorAllOnes(N1.getNode()))
  2716. return N1;
  2717. }
  2718. // fold (or x, undef) -> -1
  2719. if (!LegalOperations &&
  2720. (N0.getOpcode() == ISD::UNDEF || N1.getOpcode() == ISD::UNDEF)) {
  2721. EVT EltVT = VT.isVector() ? VT.getVectorElementType() : VT;
  2722. return DAG.getConstant(APInt::getAllOnesValue(EltVT.getSizeInBits()), VT);
  2723. }
  2724. // fold (or c1, c2) -> c1|c2
  2725. if (N0C && N1C)
  2726. return DAG.FoldConstantArithmetic(ISD::OR, VT, N0C, N1C);
  2727. // canonicalize constant to RHS
  2728. if (N0C && !N1C)
  2729. return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N1, N0);
  2730. // fold (or x, 0) -> x
  2731. if (N1C && N1C->isNullValue())
  2732. return N0;
  2733. // fold (or x, -1) -> -1
  2734. if (N1C && N1C->isAllOnesValue())
  2735. return N1;
  2736. // fold (or x, c) -> c iff (x & ~c) == 0
  2737. if (N1C && DAG.MaskedValueIsZero(N0, ~N1C->getAPIntValue()))
  2738. return N1;
  2739. // Recognize halfword bswaps as (bswap + rotl 16) or (bswap + shl 16)
  2740. SDValue BSwap = MatchBSwapHWord(N, N0, N1);
  2741. if (BSwap.getNode() != 0)
  2742. return BSwap;
  2743. BSwap = MatchBSwapHWordLow(N, N0, N1);
  2744. if (BSwap.getNode() != 0)
  2745. return BSwap;
  2746. // reassociate or
  2747. SDValue ROR = ReassociateOps(ISD::OR, N->getDebugLoc(), N0, N1);
  2748. if (ROR.getNode() != 0)
  2749. return ROR;
  2750. // Canonicalize (or (and X, c1), c2) -> (and (or X, c2), c1|c2)
  2751. // iff (c1 & c2) == 0.
  2752. if (N1C && N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
  2753. isa<ConstantSDNode>(N0.getOperand(1))) {
  2754. ConstantSDNode *C1 = cast<ConstantSDNode>(N0.getOperand(1));
  2755. if ((C1->getAPIntValue() & N1C->getAPIntValue()) != 0)
  2756. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
  2757. DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
  2758. N0.getOperand(0), N1),
  2759. DAG.FoldConstantArithmetic(ISD::OR, VT, N1C, C1));
  2760. }
  2761. // fold (or (setcc x), (setcc y)) -> (setcc (or x, y))
  2762. if (isSetCCEquivalent(N0, LL, LR, CC0) && isSetCCEquivalent(N1, RL, RR, CC1)){
  2763. ISD::CondCode Op0 = cast<CondCodeSDNode>(CC0)->get();
  2764. ISD::CondCode Op1 = cast<CondCodeSDNode>(CC1)->get();
  2765. if (LR == RR && isa<ConstantSDNode>(LR) && Op0 == Op1 &&
  2766. LL.getValueType().isInteger()) {
  2767. // fold (or (setne X, 0), (setne Y, 0)) -> (setne (or X, Y), 0)
  2768. // fold (or (setlt X, 0), (setlt Y, 0)) -> (setne (or X, Y), 0)
  2769. if (cast<ConstantSDNode>(LR)->isNullValue() &&
  2770. (Op1 == ISD::SETNE || Op1 == ISD::SETLT)) {
  2771. SDValue ORNode = DAG.getNode(ISD::OR, LR.getDebugLoc(),
  2772. LR.getValueType(), LL, RL);
  2773. AddToWorkList(ORNode.getNode());
  2774. return DAG.getSetCC(N->getDebugLoc(), VT, ORNode, LR, Op1);
  2775. }
  2776. // fold (or (setne X, -1), (setne Y, -1)) -> (setne (and X, Y), -1)
  2777. // fold (or (setgt X, -1), (setgt Y -1)) -> (setgt (and X, Y), -1)
  2778. if (cast<ConstantSDNode>(LR)->isAllOnesValue() &&
  2779. (Op1 == ISD::SETNE || Op1 == ISD::SETGT)) {
  2780. SDValue ANDNode = DAG.getNode(ISD::AND, LR.getDebugLoc(),
  2781. LR.getValueType(), LL, RL);
  2782. AddToWorkList(ANDNode.getNode());
  2783. return DAG.getSetCC(N->getDebugLoc(), VT, ANDNode, LR, Op1);
  2784. }
  2785. }
  2786. // canonicalize equivalent to ll == rl
  2787. if (LL == RR && LR == RL) {
  2788. Op1 = ISD::getSetCCSwappedOperands(Op1);
  2789. std::swap(RL, RR);
  2790. }
  2791. if (LL == RL && LR == RR) {
  2792. bool isInteger = LL.getValueType().isInteger();
  2793. ISD::CondCode Result = ISD::getSetCCOrOperation(Op0, Op1, isInteger);
  2794. if (Result != ISD::SETCC_INVALID &&
  2795. (!LegalOperations ||
  2796. (TLI.isCondCodeLegal(Result, LL.getSimpleValueType()) &&
  2797. TLI.isOperationLegal(ISD::SETCC,
  2798. getSetCCResultType(N0.getValueType())))))
  2799. return DAG.getSetCC(N->getDebugLoc(), N0.getValueType(),
  2800. LL, LR, Result);
  2801. }
  2802. }
  2803. // Simplify: (or (op x...), (op y...)) -> (op (or x, y))
  2804. if (N0.getOpcode() == N1.getOpcode()) {
  2805. SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
  2806. if (Tmp.getNode()) return Tmp;
  2807. }
  2808. // (or (and X, C1), (and Y, C2)) -> (and (or X, Y), C3) if possible.
  2809. if (N0.getOpcode() == ISD::AND &&
  2810. N1.getOpcode() == ISD::AND &&
  2811. N0.getOperand(1).getOpcode() == ISD::Constant &&
  2812. N1.getOperand(1).getOpcode() == ISD::Constant &&
  2813. // Don't increase # computations.
  2814. (N0.getNode()->hasOneUse() || N1.getNode()->hasOneUse())) {
  2815. // We can only do this xform if we know that bits from X that are set in C2
  2816. // but not in C1 are already zero. Likewise for Y.
  2817. const APInt &LHSMask =
  2818. cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
  2819. const APInt &RHSMask =
  2820. cast<ConstantSDNode>(N1.getOperand(1))->getAPIntValue();
  2821. if (DAG.MaskedValueIsZero(N0.getOperand(0), RHSMask&~LHSMask) &&
  2822. DAG.MaskedValueIsZero(N1.getOperand(0), LHSMask&~RHSMask)) {
  2823. SDValue X = DAG.getNode(ISD::OR, N0.getDebugLoc(), VT,
  2824. N0.getOperand(0), N1.getOperand(0));
  2825. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, X,
  2826. DAG.getConstant(LHSMask | RHSMask, VT));
  2827. }
  2828. }
  2829. // See if this is some rotate idiom.
  2830. if (SDNode *Rot = MatchRotate(N0, N1, N->getDebugLoc()))
  2831. return SDValue(Rot, 0);
  2832. // Simplify the operands using demanded-bits information.
  2833. if (!VT.isVector() &&
  2834. SimplifyDemandedBits(SDValue(N, 0)))
  2835. return SDValue(N, 0);
  2836. return SDValue();
  2837. }
  2838. /// MatchRotateHalf - Match "(X shl/srl V1) & V2" where V2 may not be present.
  2839. static bool MatchRotateHalf(SDValue Op, SDValue &Shift, SDValue &Mask) {
  2840. if (Op.getOpcode() == ISD::AND) {
  2841. if (isa<ConstantSDNode>(Op.getOperand(1))) {
  2842. Mask = Op.getOperand(1);
  2843. Op = Op.getOperand(0);
  2844. } else {
  2845. return false;
  2846. }
  2847. }
  2848. if (Op.getOpcode() == ISD::SRL || Op.getOpcode() == ISD::SHL) {
  2849. Shift = Op;
  2850. return true;
  2851. }
  2852. return false;
  2853. }
  2854. // MatchRotate - Handle an 'or' of two operands. If this is one of the many
  2855. // idioms for rotate, and if the target supports rotation instructions, generate
  2856. // a rot[lr].
  2857. SDNode *DAGCombiner::MatchRotate(SDValue LHS, SDValue RHS, DebugLoc DL) {
  2858. // Must be a legal type. Expanded 'n promoted things won't work with rotates.
  2859. EVT VT = LHS.getValueType();
  2860. if (!TLI.isTypeLegal(VT)) return 0;
  2861. // The target must have at least one rotate flavor.
  2862. bool HasROTL = TLI.isOperationLegalOrCustom(ISD::ROTL, VT);
  2863. bool HasROTR = TLI.isOperationLegalOrCustom(ISD::ROTR, VT);
  2864. if (!HasROTL && !HasROTR) return 0;
  2865. // Match "(X shl/srl V1) & V2" where V2 may not be present.
  2866. SDValue LHSShift; // The shift.
  2867. SDValue LHSMask; // AND value if any.
  2868. if (!MatchRotateHalf(LHS, LHSShift, LHSMask))
  2869. return 0; // Not part of a rotate.
  2870. SDValue RHSShift; // The shift.
  2871. SDValue RHSMask; // AND value if any.
  2872. if (!MatchRotateHalf(RHS, RHSShift, RHSMask))
  2873. return 0; // Not part of a rotate.
  2874. if (LHSShift.getOperand(0) != RHSShift.getOperand(0))
  2875. return 0; // Not shifting the same value.
  2876. if (LHSShift.getOpcode() == RHSShift.getOpcode())
  2877. return 0; // Shifts must disagree.
  2878. // Canonicalize shl to left side in a shl/srl pair.
  2879. if (RHSShift.getOpcode() == ISD::SHL) {
  2880. std::swap(LHS, RHS);
  2881. std::swap(LHSShift, RHSShift);
  2882. std::swap(LHSMask , RHSMask );
  2883. }
  2884. unsigned OpSizeInBits = VT.getSizeInBits();
  2885. SDValue LHSShiftArg = LHSShift.getOperand(0);
  2886. SDValue LHSShiftAmt = LHSShift.getOperand(1);
  2887. SDValue RHSShiftAmt = RHSShift.getOperand(1);
  2888. // fold (or (shl x, C1), (srl x, C2)) -> (rotl x, C1)
  2889. // fold (or (shl x, C1), (srl x, C2)) -> (rotr x, C2)
  2890. if (LHSShiftAmt.getOpcode() == ISD::Constant &&
  2891. RHSShiftAmt.getOpcode() == ISD::Constant) {
  2892. uint64_t LShVal = cast<ConstantSDNode>(LHSShiftAmt)->getZExtValue();
  2893. uint64_t RShVal = cast<ConstantSDNode>(RHSShiftAmt)->getZExtValue();
  2894. if ((LShVal + RShVal) != OpSizeInBits)
  2895. return 0;
  2896. SDValue Rot = DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
  2897. LHSShiftArg, HasROTL ? LHSShiftAmt : RHSShiftAmt);
  2898. // If there is an AND of either shifted operand, apply it to the result.
  2899. if (LHSMask.getNode() || RHSMask.getNode()) {
  2900. APInt Mask = APInt::getAllOnesValue(OpSizeInBits);
  2901. if (LHSMask.getNode()) {
  2902. APInt RHSBits = APInt::getLowBitsSet(OpSizeInBits, LShVal);
  2903. Mask &= cast<ConstantSDNode>(LHSMask)->getAPIntValue() | RHSBits;
  2904. }
  2905. if (RHSMask.getNode()) {
  2906. APInt LHSBits = APInt::getHighBitsSet(OpSizeInBits, RShVal);
  2907. Mask &= cast<ConstantSDNode>(RHSMask)->getAPIntValue() | LHSBits;
  2908. }
  2909. Rot = DAG.getNode(ISD::AND, DL, VT, Rot, DAG.getConstant(Mask, VT));
  2910. }
  2911. return Rot.getNode();
  2912. }
  2913. // If there is a mask here, and we have a variable shift, we can't be sure
  2914. // that we're masking out the right stuff.
  2915. if (LHSMask.getNode() || RHSMask.getNode())
  2916. return 0;
  2917. // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotl x, y)
  2918. // fold (or (shl x, y), (srl x, (sub 32, y))) -> (rotr x, (sub 32, y))
  2919. if (RHSShiftAmt.getOpcode() == ISD::SUB &&
  2920. LHSShiftAmt == RHSShiftAmt.getOperand(1)) {
  2921. if (ConstantSDNode *SUBC =
  2922. dyn_cast<ConstantSDNode>(RHSShiftAmt.getOperand(0))) {
  2923. if (SUBC->getAPIntValue() == OpSizeInBits) {
  2924. return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT, LHSShiftArg,
  2925. HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
  2926. }
  2927. }
  2928. }
  2929. // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotr x, y)
  2930. // fold (or (shl x, (sub 32, y)), (srl x, r)) -> (rotl x, (sub 32, y))
  2931. if (LHSShiftAmt.getOpcode() == ISD::SUB &&
  2932. RHSShiftAmt == LHSShiftAmt.getOperand(1)) {
  2933. if (ConstantSDNode *SUBC =
  2934. dyn_cast<ConstantSDNode>(LHSShiftAmt.getOperand(0))) {
  2935. if (SUBC->getAPIntValue() == OpSizeInBits) {
  2936. return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT, LHSShiftArg,
  2937. HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
  2938. }
  2939. }
  2940. }
  2941. // Look for sign/zext/any-extended or truncate cases:
  2942. if ((LHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
  2943. LHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
  2944. LHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
  2945. LHSShiftAmt.getOpcode() == ISD::TRUNCATE) &&
  2946. (RHSShiftAmt.getOpcode() == ISD::SIGN_EXTEND ||
  2947. RHSShiftAmt.getOpcode() == ISD::ZERO_EXTEND ||
  2948. RHSShiftAmt.getOpcode() == ISD::ANY_EXTEND ||
  2949. RHSShiftAmt.getOpcode() == ISD::TRUNCATE)) {
  2950. SDValue LExtOp0 = LHSShiftAmt.getOperand(0);
  2951. SDValue RExtOp0 = RHSShiftAmt.getOperand(0);
  2952. if (RExtOp0.getOpcode() == ISD::SUB &&
  2953. RExtOp0.getOperand(1) == LExtOp0) {
  2954. // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
  2955. // (rotl x, y)
  2956. // fold (or (shl x, (*ext y)), (srl x, (*ext (sub 32, y)))) ->
  2957. // (rotr x, (sub 32, y))
  2958. if (ConstantSDNode *SUBC =
  2959. dyn_cast<ConstantSDNode>(RExtOp0.getOperand(0))) {
  2960. if (SUBC->getAPIntValue() == OpSizeInBits) {
  2961. return DAG.getNode(HasROTL ? ISD::ROTL : ISD::ROTR, DL, VT,
  2962. LHSShiftArg,
  2963. HasROTL ? LHSShiftAmt : RHSShiftAmt).getNode();
  2964. }
  2965. }
  2966. } else if (LExtOp0.getOpcode() == ISD::SUB &&
  2967. RExtOp0 == LExtOp0.getOperand(1)) {
  2968. // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
  2969. // (rotr x, y)
  2970. // fold (or (shl x, (*ext (sub 32, y))), (srl x, (*ext y))) ->
  2971. // (rotl x, (sub 32, y))
  2972. if (ConstantSDNode *SUBC =
  2973. dyn_cast<ConstantSDNode>(LExtOp0.getOperand(0))) {
  2974. if (SUBC->getAPIntValue() == OpSizeInBits) {
  2975. return DAG.getNode(HasROTR ? ISD::ROTR : ISD::ROTL, DL, VT,
  2976. LHSShiftArg,
  2977. HasROTR ? RHSShiftAmt : LHSShiftAmt).getNode();
  2978. }
  2979. }
  2980. }
  2981. }
  2982. return 0;
  2983. }
  2984. SDValue DAGCombiner::visitXOR(SDNode *N) {
  2985. SDValue N0 = N->getOperand(0);
  2986. SDValue N1 = N->getOperand(1);
  2987. SDValue LHS, RHS, CC;
  2988. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  2989. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  2990. EVT VT = N0.getValueType();
  2991. // fold vector ops
  2992. if (VT.isVector()) {
  2993. SDValue FoldedVOp = SimplifyVBinOp(N);
  2994. if (FoldedVOp.getNode()) return FoldedVOp;
  2995. // fold (xor x, 0) -> x, vector edition
  2996. if (ISD::isBuildVectorAllZeros(N0.getNode()))
  2997. return N1;
  2998. if (ISD::isBuildVectorAllZeros(N1.getNode()))
  2999. return N0;
  3000. }
  3001. // fold (xor undef, undef) -> 0. This is a common idiom (misuse).
  3002. if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
  3003. return DAG.getConstant(0, VT);
  3004. // fold (xor x, undef) -> undef
  3005. if (N0.getOpcode() == ISD::UNDEF)
  3006. return N0;
  3007. if (N1.getOpcode() == ISD::UNDEF)
  3008. return N1;
  3009. // fold (xor c1, c2) -> c1^c2
  3010. if (N0C && N1C)
  3011. return DAG.FoldConstantArithmetic(ISD::XOR, VT, N0C, N1C);
  3012. // canonicalize constant to RHS
  3013. if (N0C && !N1C)
  3014. return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N1, N0);
  3015. // fold (xor x, 0) -> x
  3016. if (N1C && N1C->isNullValue())
  3017. return N0;
  3018. // reassociate xor
  3019. SDValue RXOR = ReassociateOps(ISD::XOR, N->getDebugLoc(), N0, N1);
  3020. if (RXOR.getNode() != 0)
  3021. return RXOR;
  3022. // fold !(x cc y) -> (x !cc y)
  3023. if (N1C && N1C->getAPIntValue() == 1 && isSetCCEquivalent(N0, LHS, RHS, CC)) {
  3024. bool isInt = LHS.getValueType().isInteger();
  3025. ISD::CondCode NotCC = ISD::getSetCCInverse(cast<CondCodeSDNode>(CC)->get(),
  3026. isInt);
  3027. if (!LegalOperations ||
  3028. TLI.isCondCodeLegal(NotCC, LHS.getSimpleValueType())) {
  3029. switch (N0.getOpcode()) {
  3030. default:
  3031. llvm_unreachable("Unhandled SetCC Equivalent!");
  3032. case ISD::SETCC:
  3033. return DAG.getSetCC(N->getDebugLoc(), VT, LHS, RHS, NotCC);
  3034. case ISD::SELECT_CC:
  3035. return DAG.getSelectCC(N->getDebugLoc(), LHS, RHS, N0.getOperand(2),
  3036. N0.getOperand(3), NotCC);
  3037. }
  3038. }
  3039. }
  3040. // fold (not (zext (setcc x, y))) -> (zext (not (setcc x, y)))
  3041. if (N1C && N1C->getAPIntValue() == 1 && N0.getOpcode() == ISD::ZERO_EXTEND &&
  3042. N0.getNode()->hasOneUse() &&
  3043. isSetCCEquivalent(N0.getOperand(0), LHS, RHS, CC)){
  3044. SDValue V = N0.getOperand(0);
  3045. V = DAG.getNode(ISD::XOR, N0.getDebugLoc(), V.getValueType(), V,
  3046. DAG.getConstant(1, V.getValueType()));
  3047. AddToWorkList(V.getNode());
  3048. return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, V);
  3049. }
  3050. // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are setcc
  3051. if (N1C && N1C->getAPIntValue() == 1 && VT == MVT::i1 &&
  3052. (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
  3053. SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
  3054. if (isOneUseSetCC(RHS) || isOneUseSetCC(LHS)) {
  3055. unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
  3056. LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
  3057. RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
  3058. AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
  3059. return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
  3060. }
  3061. }
  3062. // fold (not (or x, y)) -> (and (not x), (not y)) iff x or y are constants
  3063. if (N1C && N1C->isAllOnesValue() &&
  3064. (N0.getOpcode() == ISD::OR || N0.getOpcode() == ISD::AND)) {
  3065. SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
  3066. if (isa<ConstantSDNode>(RHS) || isa<ConstantSDNode>(LHS)) {
  3067. unsigned NewOpcode = N0.getOpcode() == ISD::AND ? ISD::OR : ISD::AND;
  3068. LHS = DAG.getNode(ISD::XOR, LHS.getDebugLoc(), VT, LHS, N1); // LHS = ~LHS
  3069. RHS = DAG.getNode(ISD::XOR, RHS.getDebugLoc(), VT, RHS, N1); // RHS = ~RHS
  3070. AddToWorkList(LHS.getNode()); AddToWorkList(RHS.getNode());
  3071. return DAG.getNode(NewOpcode, N->getDebugLoc(), VT, LHS, RHS);
  3072. }
  3073. }
  3074. // fold (xor (and x, y), y) -> (and (not x), y)
  3075. if (N0.getOpcode() == ISD::AND && N0.getNode()->hasOneUse() &&
  3076. N0->getOperand(1) == N1) {
  3077. SDValue X = N0->getOperand(0);
  3078. SDValue NotX = DAG.getNOT(X.getDebugLoc(), X, VT);
  3079. AddToWorkList(NotX.getNode());
  3080. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NotX, N1);
  3081. }
  3082. // fold (xor (xor x, c1), c2) -> (xor x, (xor c1, c2))
  3083. if (N1C && N0.getOpcode() == ISD::XOR) {
  3084. ConstantSDNode *N00C = dyn_cast<ConstantSDNode>(N0.getOperand(0));
  3085. ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  3086. if (N00C)
  3087. return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(1),
  3088. DAG.getConstant(N1C->getAPIntValue() ^
  3089. N00C->getAPIntValue(), VT));
  3090. if (N01C)
  3091. return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT, N0.getOperand(0),
  3092. DAG.getConstant(N1C->getAPIntValue() ^
  3093. N01C->getAPIntValue(), VT));
  3094. }
  3095. // fold (xor x, x) -> 0
  3096. if (N0 == N1)
  3097. return tryFoldToZero(N->getDebugLoc(), TLI, VT, DAG, LegalOperations);
  3098. // Simplify: xor (op x...), (op y...) -> (op (xor x, y))
  3099. if (N0.getOpcode() == N1.getOpcode()) {
  3100. SDValue Tmp = SimplifyBinOpWithSameOpcodeHands(N);
  3101. if (Tmp.getNode()) return Tmp;
  3102. }
  3103. // Simplify the expression using non-local knowledge.
  3104. if (!VT.isVector() &&
  3105. SimplifyDemandedBits(SDValue(N, 0)))
  3106. return SDValue(N, 0);
  3107. return SDValue();
  3108. }
  3109. /// visitShiftByConstant - Handle transforms common to the three shifts, when
  3110. /// the shift amount is a constant.
  3111. SDValue DAGCombiner::visitShiftByConstant(SDNode *N, unsigned Amt) {
  3112. SDNode *LHS = N->getOperand(0).getNode();
  3113. if (!LHS->hasOneUse()) return SDValue();
  3114. // We want to pull some binops through shifts, so that we have (and (shift))
  3115. // instead of (shift (and)), likewise for add, or, xor, etc. This sort of
  3116. // thing happens with address calculations, so it's important to canonicalize
  3117. // it.
  3118. bool HighBitSet = false; // Can we transform this if the high bit is set?
  3119. switch (LHS->getOpcode()) {
  3120. default: return SDValue();
  3121. case ISD::OR:
  3122. case ISD::XOR:
  3123. HighBitSet = false; // We can only transform sra if the high bit is clear.
  3124. break;
  3125. case ISD::AND:
  3126. HighBitSet = true; // We can only transform sra if the high bit is set.
  3127. break;
  3128. case ISD::ADD:
  3129. if (N->getOpcode() != ISD::SHL)
  3130. return SDValue(); // only shl(add) not sr[al](add).
  3131. HighBitSet = false; // We can only transform sra if the high bit is clear.
  3132. break;
  3133. }
  3134. // We require the RHS of the binop to be a constant as well.
  3135. ConstantSDNode *BinOpCst = dyn_cast<ConstantSDNode>(LHS->getOperand(1));
  3136. if (!BinOpCst) return SDValue();
  3137. // FIXME: disable this unless the input to the binop is a shift by a constant.
  3138. // If it is not a shift, it pessimizes some common cases like:
  3139. //
  3140. // void foo(int *X, int i) { X[i & 1235] = 1; }
  3141. // int bar(int *X, int i) { return X[i & 255]; }
  3142. SDNode *BinOpLHSVal = LHS->getOperand(0).getNode();
  3143. if ((BinOpLHSVal->getOpcode() != ISD::SHL &&
  3144. BinOpLHSVal->getOpcode() != ISD::SRA &&
  3145. BinOpLHSVal->getOpcode() != ISD::SRL) ||
  3146. !isa<ConstantSDNode>(BinOpLHSVal->getOperand(1)))
  3147. return SDValue();
  3148. EVT VT = N->getValueType(0);
  3149. // If this is a signed shift right, and the high bit is modified by the
  3150. // logical operation, do not perform the transformation. The highBitSet
  3151. // boolean indicates the value of the high bit of the constant which would
  3152. // cause it to be modified for this operation.
  3153. if (N->getOpcode() == ISD::SRA) {
  3154. bool BinOpRHSSignSet = BinOpCst->getAPIntValue().isNegative();
  3155. if (BinOpRHSSignSet != HighBitSet)
  3156. return SDValue();
  3157. }
  3158. // Fold the constants, shifting the binop RHS by the shift amount.
  3159. SDValue NewRHS = DAG.getNode(N->getOpcode(), LHS->getOperand(1).getDebugLoc(),
  3160. N->getValueType(0),
  3161. LHS->getOperand(1), N->getOperand(1));
  3162. // Create the new shift.
  3163. SDValue NewShift = DAG.getNode(N->getOpcode(),
  3164. LHS->getOperand(0).getDebugLoc(),
  3165. VT, LHS->getOperand(0), N->getOperand(1));
  3166. // Create the new binop.
  3167. return DAG.getNode(LHS->getOpcode(), N->getDebugLoc(), VT, NewShift, NewRHS);
  3168. }
  3169. SDValue DAGCombiner::visitSHL(SDNode *N) {
  3170. SDValue N0 = N->getOperand(0);
  3171. SDValue N1 = N->getOperand(1);
  3172. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  3173. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  3174. EVT VT = N0.getValueType();
  3175. unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
  3176. // fold (shl c1, c2) -> c1<<c2
  3177. if (N0C && N1C)
  3178. return DAG.FoldConstantArithmetic(ISD::SHL, VT, N0C, N1C);
  3179. // fold (shl 0, x) -> 0
  3180. if (N0C && N0C->isNullValue())
  3181. return N0;
  3182. // fold (shl x, c >= size(x)) -> undef
  3183. if (N1C && N1C->getZExtValue() >= OpSizeInBits)
  3184. return DAG.getUNDEF(VT);
  3185. // fold (shl x, 0) -> x
  3186. if (N1C && N1C->isNullValue())
  3187. return N0;
  3188. // fold (shl undef, x) -> 0
  3189. if (N0.getOpcode() == ISD::UNDEF)
  3190. return DAG.getConstant(0, VT);
  3191. // if (shl x, c) is known to be zero, return 0
  3192. if (DAG.MaskedValueIsZero(SDValue(N, 0),
  3193. APInt::getAllOnesValue(OpSizeInBits)))
  3194. return DAG.getConstant(0, VT);
  3195. // fold (shl x, (trunc (and y, c))) -> (shl x, (and (trunc y), (trunc c))).
  3196. if (N1.getOpcode() == ISD::TRUNCATE &&
  3197. N1.getOperand(0).getOpcode() == ISD::AND &&
  3198. N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
  3199. SDValue N101 = N1.getOperand(0).getOperand(1);
  3200. if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
  3201. EVT TruncVT = N1.getValueType();
  3202. SDValue N100 = N1.getOperand(0).getOperand(0);
  3203. APInt TruncC = N101C->getAPIntValue();
  3204. TruncC = TruncC.trunc(TruncVT.getSizeInBits());
  3205. return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0,
  3206. DAG.getNode(ISD::AND, N->getDebugLoc(), TruncVT,
  3207. DAG.getNode(ISD::TRUNCATE,
  3208. N->getDebugLoc(),
  3209. TruncVT, N100),
  3210. DAG.getConstant(TruncC, TruncVT)));
  3211. }
  3212. }
  3213. if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
  3214. return SDValue(N, 0);
  3215. // fold (shl (shl x, c1), c2) -> 0 or (shl x, (add c1, c2))
  3216. if (N1C && N0.getOpcode() == ISD::SHL &&
  3217. N0.getOperand(1).getOpcode() == ISD::Constant) {
  3218. uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
  3219. uint64_t c2 = N1C->getZExtValue();
  3220. if (c1 + c2 >= OpSizeInBits)
  3221. return DAG.getConstant(0, VT);
  3222. return DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
  3223. DAG.getConstant(c1 + c2, N1.getValueType()));
  3224. }
  3225. // fold (shl (ext (shl x, c1)), c2) -> (ext (shl x, (add c1, c2)))
  3226. // For this to be valid, the second form must not preserve any of the bits
  3227. // that are shifted out by the inner shift in the first form. This means
  3228. // the outer shift size must be >= the number of bits added by the ext.
  3229. // As a corollary, we don't care what kind of ext it is.
  3230. if (N1C && (N0.getOpcode() == ISD::ZERO_EXTEND ||
  3231. N0.getOpcode() == ISD::ANY_EXTEND ||
  3232. N0.getOpcode() == ISD::SIGN_EXTEND) &&
  3233. N0.getOperand(0).getOpcode() == ISD::SHL &&
  3234. isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
  3235. uint64_t c1 =
  3236. cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
  3237. uint64_t c2 = N1C->getZExtValue();
  3238. EVT InnerShiftVT = N0.getOperand(0).getValueType();
  3239. uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
  3240. if (c2 >= OpSizeInBits - InnerShiftSize) {
  3241. if (c1 + c2 >= OpSizeInBits)
  3242. return DAG.getConstant(0, VT);
  3243. return DAG.getNode(ISD::SHL, N0->getDebugLoc(), VT,
  3244. DAG.getNode(N0.getOpcode(), N0->getDebugLoc(), VT,
  3245. N0.getOperand(0)->getOperand(0)),
  3246. DAG.getConstant(c1 + c2, N1.getValueType()));
  3247. }
  3248. }
  3249. // fold (shl (srl x, c1), c2) -> (and (shl x, (sub c2, c1), MASK) or
  3250. // (and (srl x, (sub c1, c2), MASK)
  3251. // Only fold this if the inner shift has no other uses -- if it does, folding
  3252. // this will increase the total number of instructions.
  3253. if (N1C && N0.getOpcode() == ISD::SRL && N0.hasOneUse() &&
  3254. N0.getOperand(1).getOpcode() == ISD::Constant) {
  3255. uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
  3256. if (c1 < VT.getSizeInBits()) {
  3257. uint64_t c2 = N1C->getZExtValue();
  3258. APInt Mask = APInt::getHighBitsSet(VT.getSizeInBits(),
  3259. VT.getSizeInBits() - c1);
  3260. SDValue Shift;
  3261. if (c2 > c1) {
  3262. Mask = Mask.shl(c2-c1);
  3263. Shift = DAG.getNode(ISD::SHL, N->getDebugLoc(), VT, N0.getOperand(0),
  3264. DAG.getConstant(c2-c1, N1.getValueType()));
  3265. } else {
  3266. Mask = Mask.lshr(c1-c2);
  3267. Shift = DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
  3268. DAG.getConstant(c1-c2, N1.getValueType()));
  3269. }
  3270. return DAG.getNode(ISD::AND, N0.getDebugLoc(), VT, Shift,
  3271. DAG.getConstant(Mask, VT));
  3272. }
  3273. }
  3274. // fold (shl (sra x, c1), c1) -> (and x, (shl -1, c1))
  3275. if (N1C && N0.getOpcode() == ISD::SRA && N1 == N0.getOperand(1)) {
  3276. SDValue HiBitsMask =
  3277. DAG.getConstant(APInt::getHighBitsSet(VT.getSizeInBits(),
  3278. VT.getSizeInBits() -
  3279. N1C->getZExtValue()),
  3280. VT);
  3281. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
  3282. HiBitsMask);
  3283. }
  3284. if (N1C) {
  3285. SDValue NewSHL = visitShiftByConstant(N, N1C->getZExtValue());
  3286. if (NewSHL.getNode())
  3287. return NewSHL;
  3288. }
  3289. return SDValue();
  3290. }
  3291. SDValue DAGCombiner::visitSRA(SDNode *N) {
  3292. SDValue N0 = N->getOperand(0);
  3293. SDValue N1 = N->getOperand(1);
  3294. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  3295. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  3296. EVT VT = N0.getValueType();
  3297. unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
  3298. // fold (sra c1, c2) -> (sra c1, c2)
  3299. if (N0C && N1C)
  3300. return DAG.FoldConstantArithmetic(ISD::SRA, VT, N0C, N1C);
  3301. // fold (sra 0, x) -> 0
  3302. if (N0C && N0C->isNullValue())
  3303. return N0;
  3304. // fold (sra -1, x) -> -1
  3305. if (N0C && N0C->isAllOnesValue())
  3306. return N0;
  3307. // fold (sra x, (setge c, size(x))) -> undef
  3308. if (N1C && N1C->getZExtValue() >= OpSizeInBits)
  3309. return DAG.getUNDEF(VT);
  3310. // fold (sra x, 0) -> x
  3311. if (N1C && N1C->isNullValue())
  3312. return N0;
  3313. // fold (sra (shl x, c1), c1) -> sext_inreg for some c1 and target supports
  3314. // sext_inreg.
  3315. if (N1C && N0.getOpcode() == ISD::SHL && N1 == N0.getOperand(1)) {
  3316. unsigned LowBits = OpSizeInBits - (unsigned)N1C->getZExtValue();
  3317. EVT ExtVT = EVT::getIntegerVT(*DAG.getContext(), LowBits);
  3318. if (VT.isVector())
  3319. ExtVT = EVT::getVectorVT(*DAG.getContext(),
  3320. ExtVT, VT.getVectorNumElements());
  3321. if ((!LegalOperations ||
  3322. TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG, ExtVT)))
  3323. return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
  3324. N0.getOperand(0), DAG.getValueType(ExtVT));
  3325. }
  3326. // fold (sra (sra x, c1), c2) -> (sra x, (add c1, c2))
  3327. if (N1C && N0.getOpcode() == ISD::SRA) {
  3328. if (ConstantSDNode *C1 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
  3329. unsigned Sum = N1C->getZExtValue() + C1->getZExtValue();
  3330. if (Sum >= OpSizeInBits) Sum = OpSizeInBits-1;
  3331. return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0.getOperand(0),
  3332. DAG.getConstant(Sum, N1C->getValueType(0)));
  3333. }
  3334. }
  3335. // fold (sra (shl X, m), (sub result_size, n))
  3336. // -> (sign_extend (trunc (shl X, (sub (sub result_size, n), m)))) for
  3337. // result_size - n != m.
  3338. // If truncate is free for the target sext(shl) is likely to result in better
  3339. // code.
  3340. if (N0.getOpcode() == ISD::SHL) {
  3341. // Get the two constanst of the shifts, CN0 = m, CN = n.
  3342. const ConstantSDNode *N01C = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  3343. if (N01C && N1C) {
  3344. // Determine what the truncate's result bitsize and type would be.
  3345. EVT TruncVT =
  3346. EVT::getIntegerVT(*DAG.getContext(),
  3347. OpSizeInBits - N1C->getZExtValue());
  3348. // Determine the residual right-shift amount.
  3349. signed ShiftAmt = N1C->getZExtValue() - N01C->getZExtValue();
  3350. // If the shift is not a no-op (in which case this should be just a sign
  3351. // extend already), the truncated to type is legal, sign_extend is legal
  3352. // on that type, and the truncate to that type is both legal and free,
  3353. // perform the transform.
  3354. if ((ShiftAmt > 0) &&
  3355. TLI.isOperationLegalOrCustom(ISD::SIGN_EXTEND, TruncVT) &&
  3356. TLI.isOperationLegalOrCustom(ISD::TRUNCATE, VT) &&
  3357. TLI.isTruncateFree(VT, TruncVT)) {
  3358. SDValue Amt = DAG.getConstant(ShiftAmt,
  3359. getShiftAmountTy(N0.getOperand(0).getValueType()));
  3360. SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT,
  3361. N0.getOperand(0), Amt);
  3362. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), TruncVT,
  3363. Shift);
  3364. return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(),
  3365. N->getValueType(0), Trunc);
  3366. }
  3367. }
  3368. }
  3369. // fold (sra x, (trunc (and y, c))) -> (sra x, (and (trunc y), (trunc c))).
  3370. if (N1.getOpcode() == ISD::TRUNCATE &&
  3371. N1.getOperand(0).getOpcode() == ISD::AND &&
  3372. N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
  3373. SDValue N101 = N1.getOperand(0).getOperand(1);
  3374. if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
  3375. EVT TruncVT = N1.getValueType();
  3376. SDValue N100 = N1.getOperand(0).getOperand(0);
  3377. APInt TruncC = N101C->getAPIntValue();
  3378. TruncC = TruncC.trunc(TruncVT.getScalarType().getSizeInBits());
  3379. return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT, N0,
  3380. DAG.getNode(ISD::AND, N->getDebugLoc(),
  3381. TruncVT,
  3382. DAG.getNode(ISD::TRUNCATE,
  3383. N->getDebugLoc(),
  3384. TruncVT, N100),
  3385. DAG.getConstant(TruncC, TruncVT)));
  3386. }
  3387. }
  3388. // fold (sra (trunc (sr x, c1)), c2) -> (trunc (sra x, c1+c2))
  3389. // if c1 is equal to the number of bits the trunc removes
  3390. if (N0.getOpcode() == ISD::TRUNCATE &&
  3391. (N0.getOperand(0).getOpcode() == ISD::SRL ||
  3392. N0.getOperand(0).getOpcode() == ISD::SRA) &&
  3393. N0.getOperand(0).hasOneUse() &&
  3394. N0.getOperand(0).getOperand(1).hasOneUse() &&
  3395. N1C && isa<ConstantSDNode>(N0.getOperand(0).getOperand(1))) {
  3396. EVT LargeVT = N0.getOperand(0).getValueType();
  3397. ConstantSDNode *LargeShiftAmt =
  3398. cast<ConstantSDNode>(N0.getOperand(0).getOperand(1));
  3399. if (LargeVT.getScalarType().getSizeInBits() - OpSizeInBits ==
  3400. LargeShiftAmt->getZExtValue()) {
  3401. SDValue Amt =
  3402. DAG.getConstant(LargeShiftAmt->getZExtValue() + N1C->getZExtValue(),
  3403. getShiftAmountTy(N0.getOperand(0).getOperand(0).getValueType()));
  3404. SDValue SRA = DAG.getNode(ISD::SRA, N->getDebugLoc(), LargeVT,
  3405. N0.getOperand(0).getOperand(0), Amt);
  3406. return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, SRA);
  3407. }
  3408. }
  3409. // Simplify, based on bits shifted out of the LHS.
  3410. if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
  3411. return SDValue(N, 0);
  3412. // If the sign bit is known to be zero, switch this to a SRL.
  3413. if (DAG.SignBitIsZero(N0))
  3414. return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0, N1);
  3415. if (N1C) {
  3416. SDValue NewSRA = visitShiftByConstant(N, N1C->getZExtValue());
  3417. if (NewSRA.getNode())
  3418. return NewSRA;
  3419. }
  3420. return SDValue();
  3421. }
  3422. SDValue DAGCombiner::visitSRL(SDNode *N) {
  3423. SDValue N0 = N->getOperand(0);
  3424. SDValue N1 = N->getOperand(1);
  3425. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  3426. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  3427. EVT VT = N0.getValueType();
  3428. unsigned OpSizeInBits = VT.getScalarType().getSizeInBits();
  3429. // fold (srl c1, c2) -> c1 >>u c2
  3430. if (N0C && N1C)
  3431. return DAG.FoldConstantArithmetic(ISD::SRL, VT, N0C, N1C);
  3432. // fold (srl 0, x) -> 0
  3433. if (N0C && N0C->isNullValue())
  3434. return N0;
  3435. // fold (srl x, c >= size(x)) -> undef
  3436. if (N1C && N1C->getZExtValue() >= OpSizeInBits)
  3437. return DAG.getUNDEF(VT);
  3438. // fold (srl x, 0) -> x
  3439. if (N1C && N1C->isNullValue())
  3440. return N0;
  3441. // if (srl x, c) is known to be zero, return 0
  3442. if (N1C && DAG.MaskedValueIsZero(SDValue(N, 0),
  3443. APInt::getAllOnesValue(OpSizeInBits)))
  3444. return DAG.getConstant(0, VT);
  3445. // fold (srl (srl x, c1), c2) -> 0 or (srl x, (add c1, c2))
  3446. if (N1C && N0.getOpcode() == ISD::SRL &&
  3447. N0.getOperand(1).getOpcode() == ISD::Constant) {
  3448. uint64_t c1 = cast<ConstantSDNode>(N0.getOperand(1))->getZExtValue();
  3449. uint64_t c2 = N1C->getZExtValue();
  3450. if (c1 + c2 >= OpSizeInBits)
  3451. return DAG.getConstant(0, VT);
  3452. return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0),
  3453. DAG.getConstant(c1 + c2, N1.getValueType()));
  3454. }
  3455. // fold (srl (trunc (srl x, c1)), c2) -> 0 or (trunc (srl x, (add c1, c2)))
  3456. if (N1C && N0.getOpcode() == ISD::TRUNCATE &&
  3457. N0.getOperand(0).getOpcode() == ISD::SRL &&
  3458. isa<ConstantSDNode>(N0.getOperand(0)->getOperand(1))) {
  3459. uint64_t c1 =
  3460. cast<ConstantSDNode>(N0.getOperand(0)->getOperand(1))->getZExtValue();
  3461. uint64_t c2 = N1C->getZExtValue();
  3462. EVT InnerShiftVT = N0.getOperand(0).getValueType();
  3463. EVT ShiftCountVT = N0.getOperand(0)->getOperand(1).getValueType();
  3464. uint64_t InnerShiftSize = InnerShiftVT.getScalarType().getSizeInBits();
  3465. // This is only valid if the OpSizeInBits + c1 = size of inner shift.
  3466. if (c1 + OpSizeInBits == InnerShiftSize) {
  3467. if (c1 + c2 >= InnerShiftSize)
  3468. return DAG.getConstant(0, VT);
  3469. return DAG.getNode(ISD::TRUNCATE, N0->getDebugLoc(), VT,
  3470. DAG.getNode(ISD::SRL, N0->getDebugLoc(), InnerShiftVT,
  3471. N0.getOperand(0)->getOperand(0),
  3472. DAG.getConstant(c1 + c2, ShiftCountVT)));
  3473. }
  3474. }
  3475. // fold (srl (shl x, c), c) -> (and x, cst2)
  3476. if (N1C && N0.getOpcode() == ISD::SHL && N0.getOperand(1) == N1 &&
  3477. N0.getValueSizeInBits() <= 64) {
  3478. uint64_t ShAmt = N1C->getZExtValue()+64-N0.getValueSizeInBits();
  3479. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0.getOperand(0),
  3480. DAG.getConstant(~0ULL >> ShAmt, VT));
  3481. }
  3482. // fold (srl (anyextend x), c) -> (anyextend (srl x, c))
  3483. if (N1C && N0.getOpcode() == ISD::ANY_EXTEND) {
  3484. // Shifting in all undef bits?
  3485. EVT SmallVT = N0.getOperand(0).getValueType();
  3486. if (N1C->getZExtValue() >= SmallVT.getSizeInBits())
  3487. return DAG.getUNDEF(VT);
  3488. if (!LegalTypes || TLI.isTypeDesirableForOp(ISD::SRL, SmallVT)) {
  3489. uint64_t ShiftAmt = N1C->getZExtValue();
  3490. SDValue SmallShift = DAG.getNode(ISD::SRL, N0.getDebugLoc(), SmallVT,
  3491. N0.getOperand(0),
  3492. DAG.getConstant(ShiftAmt, getShiftAmountTy(SmallVT)));
  3493. AddToWorkList(SmallShift.getNode());
  3494. return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, SmallShift);
  3495. }
  3496. }
  3497. // fold (srl (sra X, Y), 31) -> (srl X, 31). This srl only looks at the sign
  3498. // bit, which is unmodified by sra.
  3499. if (N1C && N1C->getZExtValue() + 1 == VT.getSizeInBits()) {
  3500. if (N0.getOpcode() == ISD::SRA)
  3501. return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0.getOperand(0), N1);
  3502. }
  3503. // fold (srl (ctlz x), "5") -> x iff x has one bit set (the low bit).
  3504. if (N1C && N0.getOpcode() == ISD::CTLZ &&
  3505. N1C->getAPIntValue() == Log2_32(VT.getSizeInBits())) {
  3506. APInt KnownZero, KnownOne;
  3507. DAG.ComputeMaskedBits(N0.getOperand(0), KnownZero, KnownOne);
  3508. // If any of the input bits are KnownOne, then the input couldn't be all
  3509. // zeros, thus the result of the srl will always be zero.
  3510. if (KnownOne.getBoolValue()) return DAG.getConstant(0, VT);
  3511. // If all of the bits input the to ctlz node are known to be zero, then
  3512. // the result of the ctlz is "32" and the result of the shift is one.
  3513. APInt UnknownBits = ~KnownZero;
  3514. if (UnknownBits == 0) return DAG.getConstant(1, VT);
  3515. // Otherwise, check to see if there is exactly one bit input to the ctlz.
  3516. if ((UnknownBits & (UnknownBits - 1)) == 0) {
  3517. // Okay, we know that only that the single bit specified by UnknownBits
  3518. // could be set on input to the CTLZ node. If this bit is set, the SRL
  3519. // will return 0, if it is clear, it returns 1. Change the CTLZ/SRL pair
  3520. // to an SRL/XOR pair, which is likely to simplify more.
  3521. unsigned ShAmt = UnknownBits.countTrailingZeros();
  3522. SDValue Op = N0.getOperand(0);
  3523. if (ShAmt) {
  3524. Op = DAG.getNode(ISD::SRL, N0.getDebugLoc(), VT, Op,
  3525. DAG.getConstant(ShAmt, getShiftAmountTy(Op.getValueType())));
  3526. AddToWorkList(Op.getNode());
  3527. }
  3528. return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
  3529. Op, DAG.getConstant(1, VT));
  3530. }
  3531. }
  3532. // fold (srl x, (trunc (and y, c))) -> (srl x, (and (trunc y), (trunc c))).
  3533. if (N1.getOpcode() == ISD::TRUNCATE &&
  3534. N1.getOperand(0).getOpcode() == ISD::AND &&
  3535. N1.hasOneUse() && N1.getOperand(0).hasOneUse()) {
  3536. SDValue N101 = N1.getOperand(0).getOperand(1);
  3537. if (ConstantSDNode *N101C = dyn_cast<ConstantSDNode>(N101)) {
  3538. EVT TruncVT = N1.getValueType();
  3539. SDValue N100 = N1.getOperand(0).getOperand(0);
  3540. APInt TruncC = N101C->getAPIntValue();
  3541. TruncC = TruncC.trunc(TruncVT.getSizeInBits());
  3542. return DAG.getNode(ISD::SRL, N->getDebugLoc(), VT, N0,
  3543. DAG.getNode(ISD::AND, N->getDebugLoc(),
  3544. TruncVT,
  3545. DAG.getNode(ISD::TRUNCATE,
  3546. N->getDebugLoc(),
  3547. TruncVT, N100),
  3548. DAG.getConstant(TruncC, TruncVT)));
  3549. }
  3550. }
  3551. // fold operands of srl based on knowledge that the low bits are not
  3552. // demanded.
  3553. if (N1C && SimplifyDemandedBits(SDValue(N, 0)))
  3554. return SDValue(N, 0);
  3555. if (N1C) {
  3556. SDValue NewSRL = visitShiftByConstant(N, N1C->getZExtValue());
  3557. if (NewSRL.getNode())
  3558. return NewSRL;
  3559. }
  3560. // Attempt to convert a srl of a load into a narrower zero-extending load.
  3561. SDValue NarrowLoad = ReduceLoadWidth(N);
  3562. if (NarrowLoad.getNode())
  3563. return NarrowLoad;
  3564. // Here is a common situation. We want to optimize:
  3565. //
  3566. // %a = ...
  3567. // %b = and i32 %a, 2
  3568. // %c = srl i32 %b, 1
  3569. // brcond i32 %c ...
  3570. //
  3571. // into
  3572. //
  3573. // %a = ...
  3574. // %b = and %a, 2
  3575. // %c = setcc eq %b, 0
  3576. // brcond %c ...
  3577. //
  3578. // However when after the source operand of SRL is optimized into AND, the SRL
  3579. // itself may not be optimized further. Look for it and add the BRCOND into
  3580. // the worklist.
  3581. if (N->hasOneUse()) {
  3582. SDNode *Use = *N->use_begin();
  3583. if (Use->getOpcode() == ISD::BRCOND)
  3584. AddToWorkList(Use);
  3585. else if (Use->getOpcode() == ISD::TRUNCATE && Use->hasOneUse()) {
  3586. // Also look pass the truncate.
  3587. Use = *Use->use_begin();
  3588. if (Use->getOpcode() == ISD::BRCOND)
  3589. AddToWorkList(Use);
  3590. }
  3591. }
  3592. return SDValue();
  3593. }
  3594. SDValue DAGCombiner::visitCTLZ(SDNode *N) {
  3595. SDValue N0 = N->getOperand(0);
  3596. EVT VT = N->getValueType(0);
  3597. // fold (ctlz c1) -> c2
  3598. if (isa<ConstantSDNode>(N0))
  3599. return DAG.getNode(ISD::CTLZ, N->getDebugLoc(), VT, N0);
  3600. return SDValue();
  3601. }
  3602. SDValue DAGCombiner::visitCTLZ_ZERO_UNDEF(SDNode *N) {
  3603. SDValue N0 = N->getOperand(0);
  3604. EVT VT = N->getValueType(0);
  3605. // fold (ctlz_zero_undef c1) -> c2
  3606. if (isa<ConstantSDNode>(N0))
  3607. return DAG.getNode(ISD::CTLZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
  3608. return SDValue();
  3609. }
  3610. SDValue DAGCombiner::visitCTTZ(SDNode *N) {
  3611. SDValue N0 = N->getOperand(0);
  3612. EVT VT = N->getValueType(0);
  3613. // fold (cttz c1) -> c2
  3614. if (isa<ConstantSDNode>(N0))
  3615. return DAG.getNode(ISD::CTTZ, N->getDebugLoc(), VT, N0);
  3616. return SDValue();
  3617. }
  3618. SDValue DAGCombiner::visitCTTZ_ZERO_UNDEF(SDNode *N) {
  3619. SDValue N0 = N->getOperand(0);
  3620. EVT VT = N->getValueType(0);
  3621. // fold (cttz_zero_undef c1) -> c2
  3622. if (isa<ConstantSDNode>(N0))
  3623. return DAG.getNode(ISD::CTTZ_ZERO_UNDEF, N->getDebugLoc(), VT, N0);
  3624. return SDValue();
  3625. }
  3626. SDValue DAGCombiner::visitCTPOP(SDNode *N) {
  3627. SDValue N0 = N->getOperand(0);
  3628. EVT VT = N->getValueType(0);
  3629. // fold (ctpop c1) -> c2
  3630. if (isa<ConstantSDNode>(N0))
  3631. return DAG.getNode(ISD::CTPOP, N->getDebugLoc(), VT, N0);
  3632. return SDValue();
  3633. }
  3634. SDValue DAGCombiner::visitSELECT(SDNode *N) {
  3635. SDValue N0 = N->getOperand(0);
  3636. SDValue N1 = N->getOperand(1);
  3637. SDValue N2 = N->getOperand(2);
  3638. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  3639. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1);
  3640. ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2);
  3641. EVT VT = N->getValueType(0);
  3642. EVT VT0 = N0.getValueType();
  3643. // fold (select C, X, X) -> X
  3644. if (N1 == N2)
  3645. return N1;
  3646. // fold (select true, X, Y) -> X
  3647. if (N0C && !N0C->isNullValue())
  3648. return N1;
  3649. // fold (select false, X, Y) -> Y
  3650. if (N0C && N0C->isNullValue())
  3651. return N2;
  3652. // fold (select C, 1, X) -> (or C, X)
  3653. if (VT == MVT::i1 && N1C && N1C->getAPIntValue() == 1)
  3654. return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
  3655. // fold (select C, 0, 1) -> (xor C, 1)
  3656. if (VT.isInteger() &&
  3657. (VT0 == MVT::i1 ||
  3658. (VT0.isInteger() &&
  3659. TLI.getBooleanContents(false) ==
  3660. TargetLowering::ZeroOrOneBooleanContent)) &&
  3661. N1C && N2C && N1C->isNullValue() && N2C->getAPIntValue() == 1) {
  3662. SDValue XORNode;
  3663. if (VT == VT0)
  3664. return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT0,
  3665. N0, DAG.getConstant(1, VT0));
  3666. XORNode = DAG.getNode(ISD::XOR, N0.getDebugLoc(), VT0,
  3667. N0, DAG.getConstant(1, VT0));
  3668. AddToWorkList(XORNode.getNode());
  3669. if (VT.bitsGT(VT0))
  3670. return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, XORNode);
  3671. return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, XORNode);
  3672. }
  3673. // fold (select C, 0, X) -> (and (not C), X)
  3674. if (VT == VT0 && VT == MVT::i1 && N1C && N1C->isNullValue()) {
  3675. SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
  3676. AddToWorkList(NOTNode.getNode());
  3677. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, NOTNode, N2);
  3678. }
  3679. // fold (select C, X, 1) -> (or (not C), X)
  3680. if (VT == VT0 && VT == MVT::i1 && N2C && N2C->getAPIntValue() == 1) {
  3681. SDValue NOTNode = DAG.getNOT(N0.getDebugLoc(), N0, VT);
  3682. AddToWorkList(NOTNode.getNode());
  3683. return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, NOTNode, N1);
  3684. }
  3685. // fold (select C, X, 0) -> (and C, X)
  3686. if (VT == MVT::i1 && N2C && N2C->isNullValue())
  3687. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
  3688. // fold (select X, X, Y) -> (or X, Y)
  3689. // fold (select X, 1, Y) -> (or X, Y)
  3690. if (VT == MVT::i1 && (N0 == N1 || (N1C && N1C->getAPIntValue() == 1)))
  3691. return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, N0, N2);
  3692. // fold (select X, Y, X) -> (and X, Y)
  3693. // fold (select X, Y, 0) -> (and X, Y)
  3694. if (VT == MVT::i1 && (N0 == N2 || (N2C && N2C->getAPIntValue() == 0)))
  3695. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT, N0, N1);
  3696. // If we can fold this based on the true/false value, do so.
  3697. if (SimplifySelectOps(N, N1, N2))
  3698. return SDValue(N, 0); // Don't revisit N.
  3699. // fold selects based on a setcc into other things, such as min/max/abs
  3700. if (N0.getOpcode() == ISD::SETCC) {
  3701. // FIXME:
  3702. // Check against MVT::Other for SELECT_CC, which is a workaround for targets
  3703. // having to say they don't support SELECT_CC on every type the DAG knows
  3704. // about, since there is no way to mark an opcode illegal at all value types
  3705. if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other) &&
  3706. TLI.isOperationLegalOrCustom(ISD::SELECT_CC, VT))
  3707. return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT,
  3708. N0.getOperand(0), N0.getOperand(1),
  3709. N1, N2, N0.getOperand(2));
  3710. return SimplifySelect(N->getDebugLoc(), N0, N1, N2);
  3711. }
  3712. return SDValue();
  3713. }
  3714. SDValue DAGCombiner::visitVSELECT(SDNode *N) {
  3715. SDValue N0 = N->getOperand(0);
  3716. SDValue N1 = N->getOperand(1);
  3717. SDValue N2 = N->getOperand(2);
  3718. DebugLoc DL = N->getDebugLoc();
  3719. // Canonicalize integer abs.
  3720. // vselect (setg[te] X, 0), X, -X ->
  3721. // vselect (setgt X, -1), X, -X ->
  3722. // vselect (setl[te] X, 0), -X, X ->
  3723. // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
  3724. if (N0.getOpcode() == ISD::SETCC) {
  3725. SDValue LHS = N0.getOperand(0), RHS = N0.getOperand(1);
  3726. ISD::CondCode CC = cast<CondCodeSDNode>(N0.getOperand(2))->get();
  3727. bool isAbs = false;
  3728. bool RHSIsAllZeros = ISD::isBuildVectorAllZeros(RHS.getNode());
  3729. if (((RHSIsAllZeros && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
  3730. (ISD::isBuildVectorAllOnes(RHS.getNode()) && CC == ISD::SETGT)) &&
  3731. N1 == LHS && N2.getOpcode() == ISD::SUB && N1 == N2.getOperand(1))
  3732. isAbs = ISD::isBuildVectorAllZeros(N2.getOperand(0).getNode());
  3733. else if ((RHSIsAllZeros && (CC == ISD::SETLT || CC == ISD::SETLE)) &&
  3734. N2 == LHS && N1.getOpcode() == ISD::SUB && N2 == N1.getOperand(1))
  3735. isAbs = ISD::isBuildVectorAllZeros(N1.getOperand(0).getNode());
  3736. if (isAbs) {
  3737. EVT VT = LHS.getValueType();
  3738. SDValue Shift = DAG.getNode(
  3739. ISD::SRA, DL, VT, LHS,
  3740. DAG.getConstant(VT.getScalarType().getSizeInBits() - 1, VT));
  3741. SDValue Add = DAG.getNode(ISD::ADD, DL, VT, LHS, Shift);
  3742. AddToWorkList(Shift.getNode());
  3743. AddToWorkList(Add.getNode());
  3744. return DAG.getNode(ISD::XOR, DL, VT, Add, Shift);
  3745. }
  3746. }
  3747. return SDValue();
  3748. }
  3749. SDValue DAGCombiner::visitSELECT_CC(SDNode *N) {
  3750. SDValue N0 = N->getOperand(0);
  3751. SDValue N1 = N->getOperand(1);
  3752. SDValue N2 = N->getOperand(2);
  3753. SDValue N3 = N->getOperand(3);
  3754. SDValue N4 = N->getOperand(4);
  3755. ISD::CondCode CC = cast<CondCodeSDNode>(N4)->get();
  3756. // fold select_cc lhs, rhs, x, x, cc -> x
  3757. if (N2 == N3)
  3758. return N2;
  3759. // Determine if the condition we're dealing with is constant
  3760. SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
  3761. N0, N1, CC, N->getDebugLoc(), false);
  3762. if (SCC.getNode()) AddToWorkList(SCC.getNode());
  3763. if (ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode())) {
  3764. if (!SCCC->isNullValue())
  3765. return N2; // cond always true -> true val
  3766. else
  3767. return N3; // cond always false -> false val
  3768. }
  3769. // Fold to a simpler select_cc
  3770. if (SCC.getNode() && SCC.getOpcode() == ISD::SETCC)
  3771. return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), N2.getValueType(),
  3772. SCC.getOperand(0), SCC.getOperand(1), N2, N3,
  3773. SCC.getOperand(2));
  3774. // If we can fold this based on the true/false value, do so.
  3775. if (SimplifySelectOps(N, N2, N3))
  3776. return SDValue(N, 0); // Don't revisit N.
  3777. // fold select_cc into other things, such as min/max/abs
  3778. return SimplifySelectCC(N->getDebugLoc(), N0, N1, N2, N3, CC);
  3779. }
  3780. SDValue DAGCombiner::visitSETCC(SDNode *N) {
  3781. return SimplifySetCC(N->getValueType(0), N->getOperand(0), N->getOperand(1),
  3782. cast<CondCodeSDNode>(N->getOperand(2))->get(),
  3783. N->getDebugLoc());
  3784. }
  3785. // ExtendUsesToFormExtLoad - Trying to extend uses of a load to enable this:
  3786. // "fold ({s|z|a}ext (load x)) -> ({s|z|a}ext (truncate ({s|z|a}extload x)))"
  3787. // transformation. Returns true if extension are possible and the above
  3788. // mentioned transformation is profitable.
  3789. static bool ExtendUsesToFormExtLoad(SDNode *N, SDValue N0,
  3790. unsigned ExtOpc,
  3791. SmallVector<SDNode*, 4> &ExtendNodes,
  3792. const TargetLowering &TLI) {
  3793. bool HasCopyToRegUses = false;
  3794. bool isTruncFree = TLI.isTruncateFree(N->getValueType(0), N0.getValueType());
  3795. for (SDNode::use_iterator UI = N0.getNode()->use_begin(),
  3796. UE = N0.getNode()->use_end();
  3797. UI != UE; ++UI) {
  3798. SDNode *User = *UI;
  3799. if (User == N)
  3800. continue;
  3801. if (UI.getUse().getResNo() != N0.getResNo())
  3802. continue;
  3803. // FIXME: Only extend SETCC N, N and SETCC N, c for now.
  3804. if (ExtOpc != ISD::ANY_EXTEND && User->getOpcode() == ISD::SETCC) {
  3805. ISD::CondCode CC = cast<CondCodeSDNode>(User->getOperand(2))->get();
  3806. if (ExtOpc == ISD::ZERO_EXTEND && ISD::isSignedIntSetCC(CC))
  3807. // Sign bits will be lost after a zext.
  3808. return false;
  3809. bool Add = false;
  3810. for (unsigned i = 0; i != 2; ++i) {
  3811. SDValue UseOp = User->getOperand(i);
  3812. if (UseOp == N0)
  3813. continue;
  3814. if (!isa<ConstantSDNode>(UseOp))
  3815. return false;
  3816. Add = true;
  3817. }
  3818. if (Add)
  3819. ExtendNodes.push_back(User);
  3820. continue;
  3821. }
  3822. // If truncates aren't free and there are users we can't
  3823. // extend, it isn't worthwhile.
  3824. if (!isTruncFree)
  3825. return false;
  3826. // Remember if this value is live-out.
  3827. if (User->getOpcode() == ISD::CopyToReg)
  3828. HasCopyToRegUses = true;
  3829. }
  3830. if (HasCopyToRegUses) {
  3831. bool BothLiveOut = false;
  3832. for (SDNode::use_iterator UI = N->use_begin(), UE = N->use_end();
  3833. UI != UE; ++UI) {
  3834. SDUse &Use = UI.getUse();
  3835. if (Use.getResNo() == 0 && Use.getUser()->getOpcode() == ISD::CopyToReg) {
  3836. BothLiveOut = true;
  3837. break;
  3838. }
  3839. }
  3840. if (BothLiveOut)
  3841. // Both unextended and extended values are live out. There had better be
  3842. // a good reason for the transformation.
  3843. return ExtendNodes.size();
  3844. }
  3845. return true;
  3846. }
  3847. void DAGCombiner::ExtendSetCCUses(SmallVector<SDNode*, 4> SetCCs,
  3848. SDValue Trunc, SDValue ExtLoad, DebugLoc DL,
  3849. ISD::NodeType ExtType) {
  3850. // Extend SetCC uses if necessary.
  3851. for (unsigned i = 0, e = SetCCs.size(); i != e; ++i) {
  3852. SDNode *SetCC = SetCCs[i];
  3853. SmallVector<SDValue, 4> Ops;
  3854. for (unsigned j = 0; j != 2; ++j) {
  3855. SDValue SOp = SetCC->getOperand(j);
  3856. if (SOp == Trunc)
  3857. Ops.push_back(ExtLoad);
  3858. else
  3859. Ops.push_back(DAG.getNode(ExtType, DL, ExtLoad->getValueType(0), SOp));
  3860. }
  3861. Ops.push_back(SetCC->getOperand(2));
  3862. CombineTo(SetCC, DAG.getNode(ISD::SETCC, DL, SetCC->getValueType(0),
  3863. &Ops[0], Ops.size()));
  3864. }
  3865. }
  3866. SDValue DAGCombiner::visitSIGN_EXTEND(SDNode *N) {
  3867. SDValue N0 = N->getOperand(0);
  3868. EVT VT = N->getValueType(0);
  3869. // fold (sext c1) -> c1
  3870. if (isa<ConstantSDNode>(N0))
  3871. return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N0);
  3872. // fold (sext (sext x)) -> (sext x)
  3873. // fold (sext (aext x)) -> (sext x)
  3874. if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
  3875. return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT,
  3876. N0.getOperand(0));
  3877. if (N0.getOpcode() == ISD::TRUNCATE) {
  3878. // fold (sext (truncate (load x))) -> (sext (smaller load x))
  3879. // fold (sext (truncate (srl (load x), c))) -> (sext (smaller load (x+c/n)))
  3880. SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
  3881. if (NarrowLoad.getNode()) {
  3882. SDNode* oye = N0.getNode()->getOperand(0).getNode();
  3883. if (NarrowLoad.getNode() != N0.getNode()) {
  3884. CombineTo(N0.getNode(), NarrowLoad);
  3885. // CombineTo deleted the truncate, if needed, but not what's under it.
  3886. AddToWorkList(oye);
  3887. }
  3888. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  3889. }
  3890. // See if the value being truncated is already sign extended. If so, just
  3891. // eliminate the trunc/sext pair.
  3892. SDValue Op = N0.getOperand(0);
  3893. unsigned OpBits = Op.getValueType().getScalarType().getSizeInBits();
  3894. unsigned MidBits = N0.getValueType().getScalarType().getSizeInBits();
  3895. unsigned DestBits = VT.getScalarType().getSizeInBits();
  3896. unsigned NumSignBits = DAG.ComputeNumSignBits(Op);
  3897. if (OpBits == DestBits) {
  3898. // Op is i32, Mid is i8, and Dest is i32. If Op has more than 24 sign
  3899. // bits, it is already ready.
  3900. if (NumSignBits > DestBits-MidBits)
  3901. return Op;
  3902. } else if (OpBits < DestBits) {
  3903. // Op is i32, Mid is i8, and Dest is i64. If Op has more than 24 sign
  3904. // bits, just sext from i32.
  3905. if (NumSignBits > OpBits-MidBits)
  3906. return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, Op);
  3907. } else {
  3908. // Op is i64, Mid is i8, and Dest is i32. If Op has more than 56 sign
  3909. // bits, just truncate to i32.
  3910. if (NumSignBits > OpBits-MidBits)
  3911. return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
  3912. }
  3913. // fold (sext (truncate x)) -> (sextinreg x).
  3914. if (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND_INREG,
  3915. N0.getValueType())) {
  3916. if (OpBits < DestBits)
  3917. Op = DAG.getNode(ISD::ANY_EXTEND, N0.getDebugLoc(), VT, Op);
  3918. else if (OpBits > DestBits)
  3919. Op = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), VT, Op);
  3920. return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, Op,
  3921. DAG.getValueType(N0.getValueType()));
  3922. }
  3923. }
  3924. // fold (sext (load x)) -> (sext (truncate (sextload x)))
  3925. // None of the supported targets knows how to perform load and sign extend
  3926. // on vectors in one instruction. We only perform this transformation on
  3927. // scalars.
  3928. if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
  3929. ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
  3930. TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()))) {
  3931. bool DoXform = true;
  3932. SmallVector<SDNode*, 4> SetCCs;
  3933. if (!N0.hasOneUse())
  3934. DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::SIGN_EXTEND, SetCCs, TLI);
  3935. if (DoXform) {
  3936. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  3937. SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
  3938. LN0->getChain(),
  3939. LN0->getBasePtr(), LN0->getPointerInfo(),
  3940. N0.getValueType(),
  3941. LN0->isVolatile(), LN0->isNonTemporal(),
  3942. LN0->getAlignment());
  3943. CombineTo(N, ExtLoad);
  3944. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
  3945. N0.getValueType(), ExtLoad);
  3946. CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
  3947. ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
  3948. ISD::SIGN_EXTEND);
  3949. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  3950. }
  3951. }
  3952. // fold (sext (sextload x)) -> (sext (truncate (sextload x)))
  3953. // fold (sext ( extload x)) -> (sext (truncate (sextload x)))
  3954. if ((ISD::isSEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
  3955. ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
  3956. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  3957. EVT MemVT = LN0->getMemoryVT();
  3958. if ((!LegalOperations && !LN0->isVolatile()) ||
  3959. TLI.isLoadExtLegal(ISD::SEXTLOAD, MemVT)) {
  3960. SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
  3961. LN0->getChain(),
  3962. LN0->getBasePtr(), LN0->getPointerInfo(),
  3963. MemVT,
  3964. LN0->isVolatile(), LN0->isNonTemporal(),
  3965. LN0->getAlignment());
  3966. CombineTo(N, ExtLoad);
  3967. CombineTo(N0.getNode(),
  3968. DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
  3969. N0.getValueType(), ExtLoad),
  3970. ExtLoad.getValue(1));
  3971. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  3972. }
  3973. }
  3974. // fold (sext (and/or/xor (load x), cst)) ->
  3975. // (and/or/xor (sextload x), (sext cst))
  3976. if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
  3977. N0.getOpcode() == ISD::XOR) &&
  3978. isa<LoadSDNode>(N0.getOperand(0)) &&
  3979. N0.getOperand(1).getOpcode() == ISD::Constant &&
  3980. TLI.isLoadExtLegal(ISD::SEXTLOAD, N0.getValueType()) &&
  3981. (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
  3982. LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
  3983. if (LN0->getExtensionType() != ISD::ZEXTLOAD) {
  3984. bool DoXform = true;
  3985. SmallVector<SDNode*, 4> SetCCs;
  3986. if (!N0.hasOneUse())
  3987. DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::SIGN_EXTEND,
  3988. SetCCs, TLI);
  3989. if (DoXform) {
  3990. SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, LN0->getDebugLoc(), VT,
  3991. LN0->getChain(), LN0->getBasePtr(),
  3992. LN0->getPointerInfo(),
  3993. LN0->getMemoryVT(),
  3994. LN0->isVolatile(),
  3995. LN0->isNonTemporal(),
  3996. LN0->getAlignment());
  3997. APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
  3998. Mask = Mask.sext(VT.getSizeInBits());
  3999. SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
  4000. ExtLoad, DAG.getConstant(Mask, VT));
  4001. SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
  4002. N0.getOperand(0).getDebugLoc(),
  4003. N0.getOperand(0).getValueType(), ExtLoad);
  4004. CombineTo(N, And);
  4005. CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
  4006. ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
  4007. ISD::SIGN_EXTEND);
  4008. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  4009. }
  4010. }
  4011. }
  4012. if (N0.getOpcode() == ISD::SETCC) {
  4013. // sext(setcc) -> sext_in_reg(vsetcc) for vectors.
  4014. // Only do this before legalize for now.
  4015. if (VT.isVector() && !LegalOperations &&
  4016. TLI.getBooleanContents(true) ==
  4017. TargetLowering::ZeroOrNegativeOneBooleanContent) {
  4018. EVT N0VT = N0.getOperand(0).getValueType();
  4019. // On some architectures (such as SSE/NEON/etc) the SETCC result type is
  4020. // of the same size as the compared operands. Only optimize sext(setcc())
  4021. // if this is the case.
  4022. EVT SVT = getSetCCResultType(N0VT);
  4023. // We know that the # elements of the results is the same as the
  4024. // # elements of the compare (and the # elements of the compare result
  4025. // for that matter). Check to see that they are the same size. If so,
  4026. // we know that the element size of the sext'd result matches the
  4027. // element size of the compare operands.
  4028. if (VT.getSizeInBits() == SVT.getSizeInBits())
  4029. return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
  4030. N0.getOperand(1),
  4031. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  4032. // If the desired elements are smaller or larger than the source
  4033. // elements we can use a matching integer vector type and then
  4034. // truncate/sign extend
  4035. EVT MatchingVectorType = N0VT.changeVectorElementTypeToInteger();
  4036. if (SVT == MatchingVectorType) {
  4037. SDValue VsetCC = DAG.getSetCC(N->getDebugLoc(), MatchingVectorType,
  4038. N0.getOperand(0), N0.getOperand(1),
  4039. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  4040. return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
  4041. }
  4042. }
  4043. // sext(setcc x, y, cc) -> (select_cc x, y, -1, 0, cc)
  4044. unsigned ElementWidth = VT.getScalarType().getSizeInBits();
  4045. SDValue NegOne =
  4046. DAG.getConstant(APInt::getAllOnesValue(ElementWidth), VT);
  4047. SDValue SCC =
  4048. SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
  4049. NegOne, DAG.getConstant(0, VT),
  4050. cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
  4051. if (SCC.getNode()) return SCC;
  4052. if (!VT.isVector() && (!LegalOperations ||
  4053. TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(VT))))
  4054. return DAG.getNode(ISD::SELECT, N->getDebugLoc(), VT,
  4055. DAG.getSetCC(N->getDebugLoc(),
  4056. getSetCCResultType(VT),
  4057. N0.getOperand(0), N0.getOperand(1),
  4058. cast<CondCodeSDNode>(N0.getOperand(2))->get()),
  4059. NegOne, DAG.getConstant(0, VT));
  4060. }
  4061. // fold (sext x) -> (zext x) if the sign bit is known zero.
  4062. if ((!LegalOperations || TLI.isOperationLegal(ISD::ZERO_EXTEND, VT)) &&
  4063. DAG.SignBitIsZero(N0))
  4064. return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
  4065. return SDValue();
  4066. }
  4067. // isTruncateOf - If N is a truncate of some other value, return true, record
  4068. // the value being truncated in Op and which of Op's bits are zero in KnownZero.
  4069. // This function computes KnownZero to avoid a duplicated call to
  4070. // ComputeMaskedBits in the caller.
  4071. static bool isTruncateOf(SelectionDAG &DAG, SDValue N, SDValue &Op,
  4072. APInt &KnownZero) {
  4073. APInt KnownOne;
  4074. if (N->getOpcode() == ISD::TRUNCATE) {
  4075. Op = N->getOperand(0);
  4076. DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
  4077. return true;
  4078. }
  4079. if (N->getOpcode() != ISD::SETCC || N->getValueType(0) != MVT::i1 ||
  4080. cast<CondCodeSDNode>(N->getOperand(2))->get() != ISD::SETNE)
  4081. return false;
  4082. SDValue Op0 = N->getOperand(0);
  4083. SDValue Op1 = N->getOperand(1);
  4084. assert(Op0.getValueType() == Op1.getValueType());
  4085. ConstantSDNode *COp0 = dyn_cast<ConstantSDNode>(Op0);
  4086. ConstantSDNode *COp1 = dyn_cast<ConstantSDNode>(Op1);
  4087. if (COp0 && COp0->isNullValue())
  4088. Op = Op1;
  4089. else if (COp1 && COp1->isNullValue())
  4090. Op = Op0;
  4091. else
  4092. return false;
  4093. DAG.ComputeMaskedBits(Op, KnownZero, KnownOne);
  4094. if (!(KnownZero | APInt(Op.getValueSizeInBits(), 1)).isAllOnesValue())
  4095. return false;
  4096. return true;
  4097. }
  4098. SDValue DAGCombiner::visitZERO_EXTEND(SDNode *N) {
  4099. SDValue N0 = N->getOperand(0);
  4100. EVT VT = N->getValueType(0);
  4101. // fold (zext c1) -> c1
  4102. if (isa<ConstantSDNode>(N0))
  4103. return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, N0);
  4104. // fold (zext (zext x)) -> (zext x)
  4105. // fold (zext (aext x)) -> (zext x)
  4106. if (N0.getOpcode() == ISD::ZERO_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND)
  4107. return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT,
  4108. N0.getOperand(0));
  4109. // fold (zext (truncate x)) -> (zext x) or
  4110. // (zext (truncate x)) -> (truncate x)
  4111. // This is valid when the truncated bits of x are already zero.
  4112. // FIXME: We should extend this to work for vectors too.
  4113. SDValue Op;
  4114. APInt KnownZero;
  4115. if (!VT.isVector() && isTruncateOf(DAG, N0, Op, KnownZero)) {
  4116. APInt TruncatedBits =
  4117. (Op.getValueSizeInBits() == N0.getValueSizeInBits()) ?
  4118. APInt(Op.getValueSizeInBits(), 0) :
  4119. APInt::getBitsSet(Op.getValueSizeInBits(),
  4120. N0.getValueSizeInBits(),
  4121. std::min(Op.getValueSizeInBits(),
  4122. VT.getSizeInBits()));
  4123. if (TruncatedBits == (KnownZero & TruncatedBits)) {
  4124. if (VT.bitsGT(Op.getValueType()))
  4125. return DAG.getNode(ISD::ZERO_EXTEND, N->getDebugLoc(), VT, Op);
  4126. if (VT.bitsLT(Op.getValueType()))
  4127. return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
  4128. return Op;
  4129. }
  4130. }
  4131. // fold (zext (truncate (load x))) -> (zext (smaller load x))
  4132. // fold (zext (truncate (srl (load x), c))) -> (zext (small load (x+c/n)))
  4133. if (N0.getOpcode() == ISD::TRUNCATE) {
  4134. SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
  4135. if (NarrowLoad.getNode()) {
  4136. SDNode* oye = N0.getNode()->getOperand(0).getNode();
  4137. if (NarrowLoad.getNode() != N0.getNode()) {
  4138. CombineTo(N0.getNode(), NarrowLoad);
  4139. // CombineTo deleted the truncate, if needed, but not what's under it.
  4140. AddToWorkList(oye);
  4141. }
  4142. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  4143. }
  4144. }
  4145. // fold (zext (truncate x)) -> (and x, mask)
  4146. if (N0.getOpcode() == ISD::TRUNCATE &&
  4147. (!LegalOperations || TLI.isOperationLegal(ISD::AND, VT))) {
  4148. // fold (zext (truncate (load x))) -> (zext (smaller load x))
  4149. // fold (zext (truncate (srl (load x), c))) -> (zext (smaller load (x+c/n)))
  4150. SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
  4151. if (NarrowLoad.getNode()) {
  4152. SDNode* oye = N0.getNode()->getOperand(0).getNode();
  4153. if (NarrowLoad.getNode() != N0.getNode()) {
  4154. CombineTo(N0.getNode(), NarrowLoad);
  4155. // CombineTo deleted the truncate, if needed, but not what's under it.
  4156. AddToWorkList(oye);
  4157. }
  4158. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  4159. }
  4160. SDValue Op = N0.getOperand(0);
  4161. if (Op.getValueType().bitsLT(VT)) {
  4162. Op = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, Op);
  4163. AddToWorkList(Op.getNode());
  4164. } else if (Op.getValueType().bitsGT(VT)) {
  4165. Op = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Op);
  4166. AddToWorkList(Op.getNode());
  4167. }
  4168. return DAG.getZeroExtendInReg(Op, N->getDebugLoc(),
  4169. N0.getValueType().getScalarType());
  4170. }
  4171. // Fold (zext (and (trunc x), cst)) -> (and x, cst),
  4172. // if either of the casts is not free.
  4173. if (N0.getOpcode() == ISD::AND &&
  4174. N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
  4175. N0.getOperand(1).getOpcode() == ISD::Constant &&
  4176. (!TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
  4177. N0.getValueType()) ||
  4178. !TLI.isZExtFree(N0.getValueType(), VT))) {
  4179. SDValue X = N0.getOperand(0).getOperand(0);
  4180. if (X.getValueType().bitsLT(VT)) {
  4181. X = DAG.getNode(ISD::ANY_EXTEND, X.getDebugLoc(), VT, X);
  4182. } else if (X.getValueType().bitsGT(VT)) {
  4183. X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
  4184. }
  4185. APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
  4186. Mask = Mask.zext(VT.getSizeInBits());
  4187. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
  4188. X, DAG.getConstant(Mask, VT));
  4189. }
  4190. // fold (zext (load x)) -> (zext (truncate (zextload x)))
  4191. // None of the supported targets knows how to perform load and vector_zext
  4192. // on vectors in one instruction. We only perform this transformation on
  4193. // scalars.
  4194. if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
  4195. ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
  4196. TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()))) {
  4197. bool DoXform = true;
  4198. SmallVector<SDNode*, 4> SetCCs;
  4199. if (!N0.hasOneUse())
  4200. DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ZERO_EXTEND, SetCCs, TLI);
  4201. if (DoXform) {
  4202. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  4203. SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
  4204. LN0->getChain(),
  4205. LN0->getBasePtr(), LN0->getPointerInfo(),
  4206. N0.getValueType(),
  4207. LN0->isVolatile(), LN0->isNonTemporal(),
  4208. LN0->getAlignment());
  4209. CombineTo(N, ExtLoad);
  4210. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
  4211. N0.getValueType(), ExtLoad);
  4212. CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
  4213. ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
  4214. ISD::ZERO_EXTEND);
  4215. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  4216. }
  4217. }
  4218. // fold (zext (and/or/xor (load x), cst)) ->
  4219. // (and/or/xor (zextload x), (zext cst))
  4220. if ((N0.getOpcode() == ISD::AND || N0.getOpcode() == ISD::OR ||
  4221. N0.getOpcode() == ISD::XOR) &&
  4222. isa<LoadSDNode>(N0.getOperand(0)) &&
  4223. N0.getOperand(1).getOpcode() == ISD::Constant &&
  4224. TLI.isLoadExtLegal(ISD::ZEXTLOAD, N0.getValueType()) &&
  4225. (!LegalOperations && TLI.isOperationLegal(N0.getOpcode(), VT))) {
  4226. LoadSDNode *LN0 = cast<LoadSDNode>(N0.getOperand(0));
  4227. if (LN0->getExtensionType() != ISD::SEXTLOAD) {
  4228. bool DoXform = true;
  4229. SmallVector<SDNode*, 4> SetCCs;
  4230. if (!N0.hasOneUse())
  4231. DoXform = ExtendUsesToFormExtLoad(N, N0.getOperand(0), ISD::ZERO_EXTEND,
  4232. SetCCs, TLI);
  4233. if (DoXform) {
  4234. SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, LN0->getDebugLoc(), VT,
  4235. LN0->getChain(), LN0->getBasePtr(),
  4236. LN0->getPointerInfo(),
  4237. LN0->getMemoryVT(),
  4238. LN0->isVolatile(),
  4239. LN0->isNonTemporal(),
  4240. LN0->getAlignment());
  4241. APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
  4242. Mask = Mask.zext(VT.getSizeInBits());
  4243. SDValue And = DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
  4244. ExtLoad, DAG.getConstant(Mask, VT));
  4245. SDValue Trunc = DAG.getNode(ISD::TRUNCATE,
  4246. N0.getOperand(0).getDebugLoc(),
  4247. N0.getOperand(0).getValueType(), ExtLoad);
  4248. CombineTo(N, And);
  4249. CombineTo(N0.getOperand(0).getNode(), Trunc, ExtLoad.getValue(1));
  4250. ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
  4251. ISD::ZERO_EXTEND);
  4252. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  4253. }
  4254. }
  4255. }
  4256. // fold (zext (zextload x)) -> (zext (truncate (zextload x)))
  4257. // fold (zext ( extload x)) -> (zext (truncate (zextload x)))
  4258. if ((ISD::isZEXTLoad(N0.getNode()) || ISD::isEXTLoad(N0.getNode())) &&
  4259. ISD::isUNINDEXEDLoad(N0.getNode()) && N0.hasOneUse()) {
  4260. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  4261. EVT MemVT = LN0->getMemoryVT();
  4262. if ((!LegalOperations && !LN0->isVolatile()) ||
  4263. TLI.isLoadExtLegal(ISD::ZEXTLOAD, MemVT)) {
  4264. SDValue ExtLoad = DAG.getExtLoad(ISD::ZEXTLOAD, N->getDebugLoc(), VT,
  4265. LN0->getChain(),
  4266. LN0->getBasePtr(), LN0->getPointerInfo(),
  4267. MemVT,
  4268. LN0->isVolatile(), LN0->isNonTemporal(),
  4269. LN0->getAlignment());
  4270. CombineTo(N, ExtLoad);
  4271. CombineTo(N0.getNode(),
  4272. DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(), N0.getValueType(),
  4273. ExtLoad),
  4274. ExtLoad.getValue(1));
  4275. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  4276. }
  4277. }
  4278. if (N0.getOpcode() == ISD::SETCC) {
  4279. if (!LegalOperations && VT.isVector()) {
  4280. // zext(setcc) -> (and (vsetcc), (1, 1, ...) for vectors.
  4281. // Only do this before legalize for now.
  4282. EVT N0VT = N0.getOperand(0).getValueType();
  4283. EVT EltVT = VT.getVectorElementType();
  4284. SmallVector<SDValue,8> OneOps(VT.getVectorNumElements(),
  4285. DAG.getConstant(1, EltVT));
  4286. if (VT.getSizeInBits() == N0VT.getSizeInBits())
  4287. // We know that the # elements of the results is the same as the
  4288. // # elements of the compare (and the # elements of the compare result
  4289. // for that matter). Check to see that they are the same size. If so,
  4290. // we know that the element size of the sext'd result matches the
  4291. // element size of the compare operands.
  4292. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
  4293. DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
  4294. N0.getOperand(1),
  4295. cast<CondCodeSDNode>(N0.getOperand(2))->get()),
  4296. DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
  4297. &OneOps[0], OneOps.size()));
  4298. // If the desired elements are smaller or larger than the source
  4299. // elements we can use a matching integer vector type and then
  4300. // truncate/sign extend
  4301. EVT MatchingElementType =
  4302. EVT::getIntegerVT(*DAG.getContext(),
  4303. N0VT.getScalarType().getSizeInBits());
  4304. EVT MatchingVectorType =
  4305. EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
  4306. N0VT.getVectorNumElements());
  4307. SDValue VsetCC =
  4308. DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
  4309. N0.getOperand(1),
  4310. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  4311. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
  4312. DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT),
  4313. DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT,
  4314. &OneOps[0], OneOps.size()));
  4315. }
  4316. // zext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
  4317. SDValue SCC =
  4318. SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
  4319. DAG.getConstant(1, VT), DAG.getConstant(0, VT),
  4320. cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
  4321. if (SCC.getNode()) return SCC;
  4322. }
  4323. // (zext (shl (zext x), cst)) -> (shl (zext x), cst)
  4324. if ((N0.getOpcode() == ISD::SHL || N0.getOpcode() == ISD::SRL) &&
  4325. isa<ConstantSDNode>(N0.getOperand(1)) &&
  4326. N0.getOperand(0).getOpcode() == ISD::ZERO_EXTEND &&
  4327. N0.hasOneUse()) {
  4328. SDValue ShAmt = N0.getOperand(1);
  4329. unsigned ShAmtVal = cast<ConstantSDNode>(ShAmt)->getZExtValue();
  4330. if (N0.getOpcode() == ISD::SHL) {
  4331. SDValue InnerZExt = N0.getOperand(0);
  4332. // If the original shl may be shifting out bits, do not perform this
  4333. // transformation.
  4334. unsigned KnownZeroBits = InnerZExt.getValueType().getSizeInBits() -
  4335. InnerZExt.getOperand(0).getValueType().getSizeInBits();
  4336. if (ShAmtVal > KnownZeroBits)
  4337. return SDValue();
  4338. }
  4339. DebugLoc DL = N->getDebugLoc();
  4340. // Ensure that the shift amount is wide enough for the shifted value.
  4341. if (VT.getSizeInBits() >= 256)
  4342. ShAmt = DAG.getNode(ISD::ZERO_EXTEND, DL, MVT::i32, ShAmt);
  4343. return DAG.getNode(N0.getOpcode(), DL, VT,
  4344. DAG.getNode(ISD::ZERO_EXTEND, DL, VT, N0.getOperand(0)),
  4345. ShAmt);
  4346. }
  4347. return SDValue();
  4348. }
  4349. SDValue DAGCombiner::visitANY_EXTEND(SDNode *N) {
  4350. SDValue N0 = N->getOperand(0);
  4351. EVT VT = N->getValueType(0);
  4352. // fold (aext c1) -> c1
  4353. if (isa<ConstantSDNode>(N0))
  4354. return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, N0);
  4355. // fold (aext (aext x)) -> (aext x)
  4356. // fold (aext (zext x)) -> (zext x)
  4357. // fold (aext (sext x)) -> (sext x)
  4358. if (N0.getOpcode() == ISD::ANY_EXTEND ||
  4359. N0.getOpcode() == ISD::ZERO_EXTEND ||
  4360. N0.getOpcode() == ISD::SIGN_EXTEND)
  4361. return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT, N0.getOperand(0));
  4362. // fold (aext (truncate (load x))) -> (aext (smaller load x))
  4363. // fold (aext (truncate (srl (load x), c))) -> (aext (small load (x+c/n)))
  4364. if (N0.getOpcode() == ISD::TRUNCATE) {
  4365. SDValue NarrowLoad = ReduceLoadWidth(N0.getNode());
  4366. if (NarrowLoad.getNode()) {
  4367. SDNode* oye = N0.getNode()->getOperand(0).getNode();
  4368. if (NarrowLoad.getNode() != N0.getNode()) {
  4369. CombineTo(N0.getNode(), NarrowLoad);
  4370. // CombineTo deleted the truncate, if needed, but not what's under it.
  4371. AddToWorkList(oye);
  4372. }
  4373. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  4374. }
  4375. }
  4376. // fold (aext (truncate x))
  4377. if (N0.getOpcode() == ISD::TRUNCATE) {
  4378. SDValue TruncOp = N0.getOperand(0);
  4379. if (TruncOp.getValueType() == VT)
  4380. return TruncOp; // x iff x size == zext size.
  4381. if (TruncOp.getValueType().bitsGT(VT))
  4382. return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, TruncOp);
  4383. return DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, TruncOp);
  4384. }
  4385. // Fold (aext (and (trunc x), cst)) -> (and x, cst)
  4386. // if the trunc is not free.
  4387. if (N0.getOpcode() == ISD::AND &&
  4388. N0.getOperand(0).getOpcode() == ISD::TRUNCATE &&
  4389. N0.getOperand(1).getOpcode() == ISD::Constant &&
  4390. !TLI.isTruncateFree(N0.getOperand(0).getOperand(0).getValueType(),
  4391. N0.getValueType())) {
  4392. SDValue X = N0.getOperand(0).getOperand(0);
  4393. if (X.getValueType().bitsLT(VT)) {
  4394. X = DAG.getNode(ISD::ANY_EXTEND, N->getDebugLoc(), VT, X);
  4395. } else if (X.getValueType().bitsGT(VT)) {
  4396. X = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, X);
  4397. }
  4398. APInt Mask = cast<ConstantSDNode>(N0.getOperand(1))->getAPIntValue();
  4399. Mask = Mask.zext(VT.getSizeInBits());
  4400. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
  4401. X, DAG.getConstant(Mask, VT));
  4402. }
  4403. // fold (aext (load x)) -> (aext (truncate (extload x)))
  4404. // None of the supported targets knows how to perform load and any_ext
  4405. // on vectors in one instruction. We only perform this transformation on
  4406. // scalars.
  4407. if (ISD::isNON_EXTLoad(N0.getNode()) && !VT.isVector() &&
  4408. ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
  4409. TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
  4410. bool DoXform = true;
  4411. SmallVector<SDNode*, 4> SetCCs;
  4412. if (!N0.hasOneUse())
  4413. DoXform = ExtendUsesToFormExtLoad(N, N0, ISD::ANY_EXTEND, SetCCs, TLI);
  4414. if (DoXform) {
  4415. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  4416. SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
  4417. LN0->getChain(),
  4418. LN0->getBasePtr(), LN0->getPointerInfo(),
  4419. N0.getValueType(),
  4420. LN0->isVolatile(), LN0->isNonTemporal(),
  4421. LN0->getAlignment());
  4422. CombineTo(N, ExtLoad);
  4423. SDValue Trunc = DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
  4424. N0.getValueType(), ExtLoad);
  4425. CombineTo(N0.getNode(), Trunc, ExtLoad.getValue(1));
  4426. ExtendSetCCUses(SetCCs, Trunc, ExtLoad, N->getDebugLoc(),
  4427. ISD::ANY_EXTEND);
  4428. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  4429. }
  4430. }
  4431. // fold (aext (zextload x)) -> (aext (truncate (zextload x)))
  4432. // fold (aext (sextload x)) -> (aext (truncate (sextload x)))
  4433. // fold (aext ( extload x)) -> (aext (truncate (extload x)))
  4434. if (N0.getOpcode() == ISD::LOAD &&
  4435. !ISD::isNON_EXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
  4436. N0.hasOneUse()) {
  4437. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  4438. EVT MemVT = LN0->getMemoryVT();
  4439. SDValue ExtLoad = DAG.getExtLoad(LN0->getExtensionType(), N->getDebugLoc(),
  4440. VT, LN0->getChain(), LN0->getBasePtr(),
  4441. LN0->getPointerInfo(), MemVT,
  4442. LN0->isVolatile(), LN0->isNonTemporal(),
  4443. LN0->getAlignment());
  4444. CombineTo(N, ExtLoad);
  4445. CombineTo(N0.getNode(),
  4446. DAG.getNode(ISD::TRUNCATE, N0.getDebugLoc(),
  4447. N0.getValueType(), ExtLoad),
  4448. ExtLoad.getValue(1));
  4449. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  4450. }
  4451. if (N0.getOpcode() == ISD::SETCC) {
  4452. // aext(setcc) -> sext_in_reg(vsetcc) for vectors.
  4453. // Only do this before legalize for now.
  4454. if (VT.isVector() && !LegalOperations) {
  4455. EVT N0VT = N0.getOperand(0).getValueType();
  4456. // We know that the # elements of the results is the same as the
  4457. // # elements of the compare (and the # elements of the compare result
  4458. // for that matter). Check to see that they are the same size. If so,
  4459. // we know that the element size of the sext'd result matches the
  4460. // element size of the compare operands.
  4461. if (VT.getSizeInBits() == N0VT.getSizeInBits())
  4462. return DAG.getSetCC(N->getDebugLoc(), VT, N0.getOperand(0),
  4463. N0.getOperand(1),
  4464. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  4465. // If the desired elements are smaller or larger than the source
  4466. // elements we can use a matching integer vector type and then
  4467. // truncate/sign extend
  4468. else {
  4469. EVT MatchingElementType =
  4470. EVT::getIntegerVT(*DAG.getContext(),
  4471. N0VT.getScalarType().getSizeInBits());
  4472. EVT MatchingVectorType =
  4473. EVT::getVectorVT(*DAG.getContext(), MatchingElementType,
  4474. N0VT.getVectorNumElements());
  4475. SDValue VsetCC =
  4476. DAG.getSetCC(N->getDebugLoc(), MatchingVectorType, N0.getOperand(0),
  4477. N0.getOperand(1),
  4478. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  4479. return DAG.getSExtOrTrunc(VsetCC, N->getDebugLoc(), VT);
  4480. }
  4481. }
  4482. // aext(setcc x,y,cc) -> select_cc x, y, 1, 0, cc
  4483. SDValue SCC =
  4484. SimplifySelectCC(N->getDebugLoc(), N0.getOperand(0), N0.getOperand(1),
  4485. DAG.getConstant(1, VT), DAG.getConstant(0, VT),
  4486. cast<CondCodeSDNode>(N0.getOperand(2))->get(), true);
  4487. if (SCC.getNode())
  4488. return SCC;
  4489. }
  4490. return SDValue();
  4491. }
  4492. /// GetDemandedBits - See if the specified operand can be simplified with the
  4493. /// knowledge that only the bits specified by Mask are used. If so, return the
  4494. /// simpler operand, otherwise return a null SDValue.
  4495. SDValue DAGCombiner::GetDemandedBits(SDValue V, const APInt &Mask) {
  4496. switch (V.getOpcode()) {
  4497. default: break;
  4498. case ISD::Constant: {
  4499. const ConstantSDNode *CV = cast<ConstantSDNode>(V.getNode());
  4500. assert(CV != 0 && "Const value should be ConstSDNode.");
  4501. const APInt &CVal = CV->getAPIntValue();
  4502. APInt NewVal = CVal & Mask;
  4503. if (NewVal != CVal) {
  4504. return DAG.getConstant(NewVal, V.getValueType());
  4505. }
  4506. break;
  4507. }
  4508. case ISD::OR:
  4509. case ISD::XOR:
  4510. // If the LHS or RHS don't contribute bits to the or, drop them.
  4511. if (DAG.MaskedValueIsZero(V.getOperand(0), Mask))
  4512. return V.getOperand(1);
  4513. if (DAG.MaskedValueIsZero(V.getOperand(1), Mask))
  4514. return V.getOperand(0);
  4515. break;
  4516. case ISD::SRL:
  4517. // Only look at single-use SRLs.
  4518. if (!V.getNode()->hasOneUse())
  4519. break;
  4520. if (ConstantSDNode *RHSC = dyn_cast<ConstantSDNode>(V.getOperand(1))) {
  4521. // See if we can recursively simplify the LHS.
  4522. unsigned Amt = RHSC->getZExtValue();
  4523. // Watch out for shift count overflow though.
  4524. if (Amt >= Mask.getBitWidth()) break;
  4525. APInt NewMask = Mask << Amt;
  4526. SDValue SimplifyLHS = GetDemandedBits(V.getOperand(0), NewMask);
  4527. if (SimplifyLHS.getNode())
  4528. return DAG.getNode(ISD::SRL, V.getDebugLoc(), V.getValueType(),
  4529. SimplifyLHS, V.getOperand(1));
  4530. }
  4531. }
  4532. return SDValue();
  4533. }
  4534. /// ReduceLoadWidth - If the result of a wider load is shifted to right of N
  4535. /// bits and then truncated to a narrower type and where N is a multiple
  4536. /// of number of bits of the narrower type, transform it to a narrower load
  4537. /// from address + N / num of bits of new type. If the result is to be
  4538. /// extended, also fold the extension to form a extending load.
  4539. SDValue DAGCombiner::ReduceLoadWidth(SDNode *N) {
  4540. unsigned Opc = N->getOpcode();
  4541. ISD::LoadExtType ExtType = ISD::NON_EXTLOAD;
  4542. SDValue N0 = N->getOperand(0);
  4543. EVT VT = N->getValueType(0);
  4544. EVT ExtVT = VT;
  4545. // This transformation isn't valid for vector loads.
  4546. if (VT.isVector())
  4547. return SDValue();
  4548. // Special case: SIGN_EXTEND_INREG is basically truncating to ExtVT then
  4549. // extended to VT.
  4550. if (Opc == ISD::SIGN_EXTEND_INREG) {
  4551. ExtType = ISD::SEXTLOAD;
  4552. ExtVT = cast<VTSDNode>(N->getOperand(1))->getVT();
  4553. } else if (Opc == ISD::SRL) {
  4554. // Another special-case: SRL is basically zero-extending a narrower value.
  4555. ExtType = ISD::ZEXTLOAD;
  4556. N0 = SDValue(N, 0);
  4557. ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1));
  4558. if (!N01) return SDValue();
  4559. ExtVT = EVT::getIntegerVT(*DAG.getContext(),
  4560. VT.getSizeInBits() - N01->getZExtValue());
  4561. }
  4562. if (LegalOperations && !TLI.isLoadExtLegal(ExtType, ExtVT))
  4563. return SDValue();
  4564. unsigned EVTBits = ExtVT.getSizeInBits();
  4565. // Do not generate loads of non-round integer types since these can
  4566. // be expensive (and would be wrong if the type is not byte sized).
  4567. if (!ExtVT.isRound())
  4568. return SDValue();
  4569. unsigned ShAmt = 0;
  4570. if (N0.getOpcode() == ISD::SRL && N0.hasOneUse()) {
  4571. if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
  4572. ShAmt = N01->getZExtValue();
  4573. // Is the shift amount a multiple of size of VT?
  4574. if ((ShAmt & (EVTBits-1)) == 0) {
  4575. N0 = N0.getOperand(0);
  4576. // Is the load width a multiple of size of VT?
  4577. if ((N0.getValueType().getSizeInBits() & (EVTBits-1)) != 0)
  4578. return SDValue();
  4579. }
  4580. // At this point, we must have a load or else we can't do the transform.
  4581. if (!isa<LoadSDNode>(N0)) return SDValue();
  4582. // Because a SRL must be assumed to *need* to zero-extend the high bits
  4583. // (as opposed to anyext the high bits), we can't combine the zextload
  4584. // lowering of SRL and an sextload.
  4585. if (cast<LoadSDNode>(N0)->getExtensionType() == ISD::SEXTLOAD)
  4586. return SDValue();
  4587. // If the shift amount is larger than the input type then we're not
  4588. // accessing any of the loaded bytes. If the load was a zextload/extload
  4589. // then the result of the shift+trunc is zero/undef (handled elsewhere).
  4590. if (ShAmt >= cast<LoadSDNode>(N0)->getMemoryVT().getSizeInBits())
  4591. return SDValue();
  4592. }
  4593. }
  4594. // If the load is shifted left (and the result isn't shifted back right),
  4595. // we can fold the truncate through the shift.
  4596. unsigned ShLeftAmt = 0;
  4597. if (ShAmt == 0 && N0.getOpcode() == ISD::SHL && N0.hasOneUse() &&
  4598. ExtVT == VT && TLI.isNarrowingProfitable(N0.getValueType(), VT)) {
  4599. if (ConstantSDNode *N01 = dyn_cast<ConstantSDNode>(N0.getOperand(1))) {
  4600. ShLeftAmt = N01->getZExtValue();
  4601. N0 = N0.getOperand(0);
  4602. }
  4603. }
  4604. // If we haven't found a load, we can't narrow it. Don't transform one with
  4605. // multiple uses, this would require adding a new load.
  4606. if (!isa<LoadSDNode>(N0) || !N0.hasOneUse())
  4607. return SDValue();
  4608. // Don't change the width of a volatile load.
  4609. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  4610. if (LN0->isVolatile())
  4611. return SDValue();
  4612. // Verify that we are actually reducing a load width here.
  4613. if (LN0->getMemoryVT().getSizeInBits() < EVTBits)
  4614. return SDValue();
  4615. // For the transform to be legal, the load must produce only two values
  4616. // (the value loaded and the chain). Don't transform a pre-increment
  4617. // load, for example, which produces an extra value. Otherwise the
  4618. // transformation is not equivalent, and the downstream logic to replace
  4619. // uses gets things wrong.
  4620. if (LN0->getNumValues() > 2)
  4621. return SDValue();
  4622. EVT PtrType = N0.getOperand(1).getValueType();
  4623. if (PtrType == MVT::Untyped || PtrType.isExtended())
  4624. // It's not possible to generate a constant of extended or untyped type.
  4625. return SDValue();
  4626. // For big endian targets, we need to adjust the offset to the pointer to
  4627. // load the correct bytes.
  4628. if (TLI.isBigEndian()) {
  4629. unsigned LVTStoreBits = LN0->getMemoryVT().getStoreSizeInBits();
  4630. unsigned EVTStoreBits = ExtVT.getStoreSizeInBits();
  4631. ShAmt = LVTStoreBits - EVTStoreBits - ShAmt;
  4632. }
  4633. uint64_t PtrOff = ShAmt / 8;
  4634. unsigned NewAlign = MinAlign(LN0->getAlignment(), PtrOff);
  4635. SDValue NewPtr = DAG.getNode(ISD::ADD, LN0->getDebugLoc(),
  4636. PtrType, LN0->getBasePtr(),
  4637. DAG.getConstant(PtrOff, PtrType));
  4638. AddToWorkList(NewPtr.getNode());
  4639. SDValue Load;
  4640. if (ExtType == ISD::NON_EXTLOAD)
  4641. Load = DAG.getLoad(VT, N0.getDebugLoc(), LN0->getChain(), NewPtr,
  4642. LN0->getPointerInfo().getWithOffset(PtrOff),
  4643. LN0->isVolatile(), LN0->isNonTemporal(),
  4644. LN0->isInvariant(), NewAlign);
  4645. else
  4646. Load = DAG.getExtLoad(ExtType, N0.getDebugLoc(), VT, LN0->getChain(),NewPtr,
  4647. LN0->getPointerInfo().getWithOffset(PtrOff),
  4648. ExtVT, LN0->isVolatile(), LN0->isNonTemporal(),
  4649. NewAlign);
  4650. // Replace the old load's chain with the new load's chain.
  4651. WorkListRemover DeadNodes(*this);
  4652. DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), Load.getValue(1));
  4653. // Shift the result left, if we've swallowed a left shift.
  4654. SDValue Result = Load;
  4655. if (ShLeftAmt != 0) {
  4656. EVT ShImmTy = getShiftAmountTy(Result.getValueType());
  4657. if (!isUIntN(ShImmTy.getSizeInBits(), ShLeftAmt))
  4658. ShImmTy = VT;
  4659. // If the shift amount is as large as the result size (but, presumably,
  4660. // no larger than the source) then the useful bits of the result are
  4661. // zero; we can't simply return the shortened shift, because the result
  4662. // of that operation is undefined.
  4663. if (ShLeftAmt >= VT.getSizeInBits())
  4664. Result = DAG.getConstant(0, VT);
  4665. else
  4666. Result = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT,
  4667. Result, DAG.getConstant(ShLeftAmt, ShImmTy));
  4668. }
  4669. // Return the new loaded value.
  4670. return Result;
  4671. }
  4672. SDValue DAGCombiner::visitSIGN_EXTEND_INREG(SDNode *N) {
  4673. SDValue N0 = N->getOperand(0);
  4674. SDValue N1 = N->getOperand(1);
  4675. EVT VT = N->getValueType(0);
  4676. EVT EVT = cast<VTSDNode>(N1)->getVT();
  4677. unsigned VTBits = VT.getScalarType().getSizeInBits();
  4678. unsigned EVTBits = EVT.getScalarType().getSizeInBits();
  4679. // fold (sext_in_reg c1) -> c1
  4680. if (isa<ConstantSDNode>(N0) || N0.getOpcode() == ISD::UNDEF)
  4681. return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT, N0, N1);
  4682. // If the input is already sign extended, just drop the extension.
  4683. if (DAG.ComputeNumSignBits(N0) >= VTBits-EVTBits+1)
  4684. return N0;
  4685. // fold (sext_in_reg (sext_in_reg x, VT2), VT1) -> (sext_in_reg x, minVT) pt2
  4686. if (N0.getOpcode() == ISD::SIGN_EXTEND_INREG &&
  4687. EVT.bitsLT(cast<VTSDNode>(N0.getOperand(1))->getVT())) {
  4688. return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
  4689. N0.getOperand(0), N1);
  4690. }
  4691. // fold (sext_in_reg (sext x)) -> (sext x)
  4692. // fold (sext_in_reg (aext x)) -> (sext x)
  4693. // if x is small enough.
  4694. if (N0.getOpcode() == ISD::SIGN_EXTEND || N0.getOpcode() == ISD::ANY_EXTEND) {
  4695. SDValue N00 = N0.getOperand(0);
  4696. if (N00.getValueType().getScalarType().getSizeInBits() <= EVTBits &&
  4697. (!LegalOperations || TLI.isOperationLegal(ISD::SIGN_EXTEND, VT)))
  4698. return DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, N00, N1);
  4699. }
  4700. // fold (sext_in_reg x) -> (zext_in_reg x) if the sign bit is known zero.
  4701. if (DAG.MaskedValueIsZero(N0, APInt::getBitsSet(VTBits, EVTBits-1, EVTBits)))
  4702. return DAG.getZeroExtendInReg(N0, N->getDebugLoc(), EVT);
  4703. // fold operands of sext_in_reg based on knowledge that the top bits are not
  4704. // demanded.
  4705. if (SimplifyDemandedBits(SDValue(N, 0)))
  4706. return SDValue(N, 0);
  4707. // fold (sext_in_reg (load x)) -> (smaller sextload x)
  4708. // fold (sext_in_reg (srl (load x), c)) -> (smaller sextload (x+c/evtbits))
  4709. SDValue NarrowLoad = ReduceLoadWidth(N);
  4710. if (NarrowLoad.getNode())
  4711. return NarrowLoad;
  4712. // fold (sext_in_reg (srl X, 24), i8) -> (sra X, 24)
  4713. // fold (sext_in_reg (srl X, 23), i8) -> (sra X, 23) iff possible.
  4714. // We already fold "(sext_in_reg (srl X, 25), i8) -> srl X, 25" above.
  4715. if (N0.getOpcode() == ISD::SRL) {
  4716. if (ConstantSDNode *ShAmt = dyn_cast<ConstantSDNode>(N0.getOperand(1)))
  4717. if (ShAmt->getZExtValue()+EVTBits <= VTBits) {
  4718. // We can turn this into an SRA iff the input to the SRL is already sign
  4719. // extended enough.
  4720. unsigned InSignBits = DAG.ComputeNumSignBits(N0.getOperand(0));
  4721. if (VTBits-(ShAmt->getZExtValue()+EVTBits) < InSignBits)
  4722. return DAG.getNode(ISD::SRA, N->getDebugLoc(), VT,
  4723. N0.getOperand(0), N0.getOperand(1));
  4724. }
  4725. }
  4726. // fold (sext_inreg (extload x)) -> (sextload x)
  4727. if (ISD::isEXTLoad(N0.getNode()) &&
  4728. ISD::isUNINDEXEDLoad(N0.getNode()) &&
  4729. EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
  4730. ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
  4731. TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
  4732. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  4733. SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
  4734. LN0->getChain(),
  4735. LN0->getBasePtr(), LN0->getPointerInfo(),
  4736. EVT,
  4737. LN0->isVolatile(), LN0->isNonTemporal(),
  4738. LN0->getAlignment());
  4739. CombineTo(N, ExtLoad);
  4740. CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
  4741. AddToWorkList(ExtLoad.getNode());
  4742. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  4743. }
  4744. // fold (sext_inreg (zextload x)) -> (sextload x) iff load has one use
  4745. if (ISD::isZEXTLoad(N0.getNode()) && ISD::isUNINDEXEDLoad(N0.getNode()) &&
  4746. N0.hasOneUse() &&
  4747. EVT == cast<LoadSDNode>(N0)->getMemoryVT() &&
  4748. ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
  4749. TLI.isLoadExtLegal(ISD::SEXTLOAD, EVT))) {
  4750. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  4751. SDValue ExtLoad = DAG.getExtLoad(ISD::SEXTLOAD, N->getDebugLoc(), VT,
  4752. LN0->getChain(),
  4753. LN0->getBasePtr(), LN0->getPointerInfo(),
  4754. EVT,
  4755. LN0->isVolatile(), LN0->isNonTemporal(),
  4756. LN0->getAlignment());
  4757. CombineTo(N, ExtLoad);
  4758. CombineTo(N0.getNode(), ExtLoad, ExtLoad.getValue(1));
  4759. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  4760. }
  4761. // Form (sext_inreg (bswap >> 16)) or (sext_inreg (rotl (bswap) 16))
  4762. if (EVTBits <= 16 && N0.getOpcode() == ISD::OR) {
  4763. SDValue BSwap = MatchBSwapHWordLow(N0.getNode(), N0.getOperand(0),
  4764. N0.getOperand(1), false);
  4765. if (BSwap.getNode() != 0)
  4766. return DAG.getNode(ISD::SIGN_EXTEND_INREG, N->getDebugLoc(), VT,
  4767. BSwap, N1);
  4768. }
  4769. return SDValue();
  4770. }
  4771. SDValue DAGCombiner::visitTRUNCATE(SDNode *N) {
  4772. SDValue N0 = N->getOperand(0);
  4773. EVT VT = N->getValueType(0);
  4774. bool isLE = TLI.isLittleEndian();
  4775. // noop truncate
  4776. if (N0.getValueType() == N->getValueType(0))
  4777. return N0;
  4778. // fold (truncate c1) -> c1
  4779. if (isa<ConstantSDNode>(N0))
  4780. return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0);
  4781. // fold (truncate (truncate x)) -> (truncate x)
  4782. if (N0.getOpcode() == ISD::TRUNCATE)
  4783. return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
  4784. // fold (truncate (ext x)) -> (ext x) or (truncate x) or x
  4785. if (N0.getOpcode() == ISD::ZERO_EXTEND ||
  4786. N0.getOpcode() == ISD::SIGN_EXTEND ||
  4787. N0.getOpcode() == ISD::ANY_EXTEND) {
  4788. if (N0.getOperand(0).getValueType().bitsLT(VT))
  4789. // if the source is smaller than the dest, we still need an extend
  4790. return DAG.getNode(N0.getOpcode(), N->getDebugLoc(), VT,
  4791. N0.getOperand(0));
  4792. if (N0.getOperand(0).getValueType().bitsGT(VT))
  4793. // if the source is larger than the dest, than we just need the truncate
  4794. return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, N0.getOperand(0));
  4795. // if the source and dest are the same type, we can drop both the extend
  4796. // and the truncate.
  4797. return N0.getOperand(0);
  4798. }
  4799. // Fold extract-and-trunc into a narrow extract. For example:
  4800. // i64 x = EXTRACT_VECTOR_ELT(v2i64 val, i32 1)
  4801. // i32 y = TRUNCATE(i64 x)
  4802. // -- becomes --
  4803. // v16i8 b = BITCAST (v2i64 val)
  4804. // i8 x = EXTRACT_VECTOR_ELT(v16i8 b, i32 8)
  4805. //
  4806. // Note: We only run this optimization after type legalization (which often
  4807. // creates this pattern) and before operation legalization after which
  4808. // we need to be more careful about the vector instructions that we generate.
  4809. if (N0.getOpcode() == ISD::EXTRACT_VECTOR_ELT &&
  4810. LegalTypes && !LegalOperations && N0->hasOneUse()) {
  4811. EVT VecTy = N0.getOperand(0).getValueType();
  4812. EVT ExTy = N0.getValueType();
  4813. EVT TrTy = N->getValueType(0);
  4814. unsigned NumElem = VecTy.getVectorNumElements();
  4815. unsigned SizeRatio = ExTy.getSizeInBits()/TrTy.getSizeInBits();
  4816. EVT NVT = EVT::getVectorVT(*DAG.getContext(), TrTy, SizeRatio * NumElem);
  4817. assert(NVT.getSizeInBits() == VecTy.getSizeInBits() && "Invalid Size");
  4818. SDValue EltNo = N0->getOperand(1);
  4819. if (isa<ConstantSDNode>(EltNo) && isTypeLegal(NVT)) {
  4820. int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
  4821. EVT IndexTy = N0->getOperand(1).getValueType();
  4822. int Index = isLE ? (Elt*SizeRatio) : (Elt*SizeRatio + (SizeRatio-1));
  4823. SDValue V = DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
  4824. NVT, N0.getOperand(0));
  4825. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT,
  4826. N->getDebugLoc(), TrTy, V,
  4827. DAG.getConstant(Index, IndexTy));
  4828. }
  4829. }
  4830. // Fold a series of buildvector, bitcast, and truncate if possible.
  4831. // For example fold
  4832. // (2xi32 trunc (bitcast ((4xi32)buildvector x, x, y, y) 2xi64)) to
  4833. // (2xi32 (buildvector x, y)).
  4834. if (Level == AfterLegalizeVectorOps && VT.isVector() &&
  4835. N0.getOpcode() == ISD::BITCAST && N0.hasOneUse() &&
  4836. N0.getOperand(0).getOpcode() == ISD::BUILD_VECTOR &&
  4837. N0.getOperand(0).hasOneUse()) {
  4838. SDValue BuildVect = N0.getOperand(0);
  4839. EVT BuildVectEltTy = BuildVect.getValueType().getVectorElementType();
  4840. EVT TruncVecEltTy = VT.getVectorElementType();
  4841. // Check that the element types match.
  4842. if (BuildVectEltTy == TruncVecEltTy) {
  4843. // Now we only need to compute the offset of the truncated elements.
  4844. unsigned BuildVecNumElts = BuildVect.getNumOperands();
  4845. unsigned TruncVecNumElts = VT.getVectorNumElements();
  4846. unsigned TruncEltOffset = BuildVecNumElts / TruncVecNumElts;
  4847. assert((BuildVecNumElts % TruncVecNumElts) == 0 &&
  4848. "Invalid number of elements");
  4849. SmallVector<SDValue, 8> Opnds;
  4850. for (unsigned i = 0, e = BuildVecNumElts; i != e; i += TruncEltOffset)
  4851. Opnds.push_back(BuildVect.getOperand(i));
  4852. return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(), VT, &Opnds[0],
  4853. Opnds.size());
  4854. }
  4855. }
  4856. // See if we can simplify the input to this truncate through knowledge that
  4857. // only the low bits are being used.
  4858. // For example "trunc (or (shl x, 8), y)" // -> trunc y
  4859. // Currently we only perform this optimization on scalars because vectors
  4860. // may have different active low bits.
  4861. if (!VT.isVector()) {
  4862. SDValue Shorter =
  4863. GetDemandedBits(N0, APInt::getLowBitsSet(N0.getValueSizeInBits(),
  4864. VT.getSizeInBits()));
  4865. if (Shorter.getNode())
  4866. return DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, Shorter);
  4867. }
  4868. // fold (truncate (load x)) -> (smaller load x)
  4869. // fold (truncate (srl (load x), c)) -> (smaller load (x+c/evtbits))
  4870. if (!LegalTypes || TLI.isTypeDesirableForOp(N0.getOpcode(), VT)) {
  4871. SDValue Reduced = ReduceLoadWidth(N);
  4872. if (Reduced.getNode())
  4873. return Reduced;
  4874. }
  4875. // fold (trunc (concat ... x ...)) -> (concat ..., (trunc x), ...)),
  4876. // where ... are all 'undef'.
  4877. if (N0.getOpcode() == ISD::CONCAT_VECTORS && !LegalTypes) {
  4878. SmallVector<EVT, 8> VTs;
  4879. SDValue V;
  4880. unsigned Idx = 0;
  4881. unsigned NumDefs = 0;
  4882. for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
  4883. SDValue X = N0.getOperand(i);
  4884. if (X.getOpcode() != ISD::UNDEF) {
  4885. V = X;
  4886. Idx = i;
  4887. NumDefs++;
  4888. }
  4889. // Stop if more than one members are non-undef.
  4890. if (NumDefs > 1)
  4891. break;
  4892. VTs.push_back(EVT::getVectorVT(*DAG.getContext(),
  4893. VT.getVectorElementType(),
  4894. X.getValueType().getVectorNumElements()));
  4895. }
  4896. if (NumDefs == 0)
  4897. return DAG.getUNDEF(VT);
  4898. if (NumDefs == 1) {
  4899. assert(V.getNode() && "The single defined operand is empty!");
  4900. SmallVector<SDValue, 8> Opnds;
  4901. for (unsigned i = 0, e = VTs.size(); i != e; ++i) {
  4902. if (i != Idx) {
  4903. Opnds.push_back(DAG.getUNDEF(VTs[i]));
  4904. continue;
  4905. }
  4906. SDValue NV = DAG.getNode(ISD::TRUNCATE, V.getDebugLoc(), VTs[i], V);
  4907. AddToWorkList(NV.getNode());
  4908. Opnds.push_back(NV);
  4909. }
  4910. return DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT,
  4911. &Opnds[0], Opnds.size());
  4912. }
  4913. }
  4914. // Simplify the operands using demanded-bits information.
  4915. if (!VT.isVector() &&
  4916. SimplifyDemandedBits(SDValue(N, 0)))
  4917. return SDValue(N, 0);
  4918. return SDValue();
  4919. }
  4920. static SDNode *getBuildPairElt(SDNode *N, unsigned i) {
  4921. SDValue Elt = N->getOperand(i);
  4922. if (Elt.getOpcode() != ISD::MERGE_VALUES)
  4923. return Elt.getNode();
  4924. return Elt.getOperand(Elt.getResNo()).getNode();
  4925. }
  4926. /// CombineConsecutiveLoads - build_pair (load, load) -> load
  4927. /// if load locations are consecutive.
  4928. SDValue DAGCombiner::CombineConsecutiveLoads(SDNode *N, EVT VT) {
  4929. assert(N->getOpcode() == ISD::BUILD_PAIR);
  4930. LoadSDNode *LD1 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 0));
  4931. LoadSDNode *LD2 = dyn_cast<LoadSDNode>(getBuildPairElt(N, 1));
  4932. if (!LD1 || !LD2 || !ISD::isNON_EXTLoad(LD1) || !LD1->hasOneUse() ||
  4933. LD1->getPointerInfo().getAddrSpace() !=
  4934. LD2->getPointerInfo().getAddrSpace())
  4935. return SDValue();
  4936. EVT LD1VT = LD1->getValueType(0);
  4937. if (ISD::isNON_EXTLoad(LD2) &&
  4938. LD2->hasOneUse() &&
  4939. // If both are volatile this would reduce the number of volatile loads.
  4940. // If one is volatile it might be ok, but play conservative and bail out.
  4941. !LD1->isVolatile() &&
  4942. !LD2->isVolatile() &&
  4943. DAG.isConsecutiveLoad(LD2, LD1, LD1VT.getSizeInBits()/8, 1)) {
  4944. unsigned Align = LD1->getAlignment();
  4945. unsigned NewAlign = TLI.getDataLayout()->
  4946. getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
  4947. if (NewAlign <= Align &&
  4948. (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT)))
  4949. return DAG.getLoad(VT, N->getDebugLoc(), LD1->getChain(),
  4950. LD1->getBasePtr(), LD1->getPointerInfo(),
  4951. false, false, false, Align);
  4952. }
  4953. return SDValue();
  4954. }
  4955. SDValue DAGCombiner::visitBITCAST(SDNode *N) {
  4956. SDValue N0 = N->getOperand(0);
  4957. EVT VT = N->getValueType(0);
  4958. // If the input is a BUILD_VECTOR with all constant elements, fold this now.
  4959. // Only do this before legalize, since afterward the target may be depending
  4960. // on the bitconvert.
  4961. // First check to see if this is all constant.
  4962. if (!LegalTypes &&
  4963. N0.getOpcode() == ISD::BUILD_VECTOR && N0.getNode()->hasOneUse() &&
  4964. VT.isVector()) {
  4965. bool isSimple = true;
  4966. for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i)
  4967. if (N0.getOperand(i).getOpcode() != ISD::UNDEF &&
  4968. N0.getOperand(i).getOpcode() != ISD::Constant &&
  4969. N0.getOperand(i).getOpcode() != ISD::ConstantFP) {
  4970. isSimple = false;
  4971. break;
  4972. }
  4973. EVT DestEltVT = N->getValueType(0).getVectorElementType();
  4974. assert(!DestEltVT.isVector() &&
  4975. "Element type of vector ValueType must not be vector!");
  4976. if (isSimple)
  4977. return ConstantFoldBITCASTofBUILD_VECTOR(N0.getNode(), DestEltVT);
  4978. }
  4979. // If the input is a constant, let getNode fold it.
  4980. if (isa<ConstantSDNode>(N0) || isa<ConstantFPSDNode>(N0)) {
  4981. SDValue Res = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT, N0);
  4982. if (Res.getNode() != N) {
  4983. if (!LegalOperations ||
  4984. TLI.isOperationLegal(Res.getNode()->getOpcode(), VT))
  4985. return Res;
  4986. // Folding it resulted in an illegal node, and it's too late to
  4987. // do that. Clean up the old node and forego the transformation.
  4988. // Ideally this won't happen very often, because instcombine
  4989. // and the earlier dagcombine runs (where illegal nodes are
  4990. // permitted) should have folded most of them already.
  4991. DAG.DeleteNode(Res.getNode());
  4992. }
  4993. }
  4994. // (conv (conv x, t1), t2) -> (conv x, t2)
  4995. if (N0.getOpcode() == ISD::BITCAST)
  4996. return DAG.getNode(ISD::BITCAST, N->getDebugLoc(), VT,
  4997. N0.getOperand(0));
  4998. // fold (conv (load x)) -> (load (conv*)x)
  4999. // If the resultant load doesn't need a higher alignment than the original!
  5000. if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
  5001. // Do not change the width of a volatile load.
  5002. !cast<LoadSDNode>(N0)->isVolatile() &&
  5003. (!LegalOperations || TLI.isOperationLegal(ISD::LOAD, VT))) {
  5004. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  5005. unsigned Align = TLI.getDataLayout()->
  5006. getABITypeAlignment(VT.getTypeForEVT(*DAG.getContext()));
  5007. unsigned OrigAlign = LN0->getAlignment();
  5008. if (Align <= OrigAlign) {
  5009. SDValue Load = DAG.getLoad(VT, N->getDebugLoc(), LN0->getChain(),
  5010. LN0->getBasePtr(), LN0->getPointerInfo(),
  5011. LN0->isVolatile(), LN0->isNonTemporal(),
  5012. LN0->isInvariant(), OrigAlign);
  5013. AddToWorkList(N);
  5014. CombineTo(N0.getNode(),
  5015. DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
  5016. N0.getValueType(), Load),
  5017. Load.getValue(1));
  5018. return Load;
  5019. }
  5020. }
  5021. // fold (bitconvert (fneg x)) -> (xor (bitconvert x), signbit)
  5022. // fold (bitconvert (fabs x)) -> (and (bitconvert x), (not signbit))
  5023. // This often reduces constant pool loads.
  5024. if (((N0.getOpcode() == ISD::FNEG && !TLI.isFNegFree(VT)) ||
  5025. (N0.getOpcode() == ISD::FABS && !TLI.isFAbsFree(VT))) &&
  5026. N0.getNode()->hasOneUse() && VT.isInteger() &&
  5027. !VT.isVector() && !N0.getValueType().isVector()) {
  5028. SDValue NewConv = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(), VT,
  5029. N0.getOperand(0));
  5030. AddToWorkList(NewConv.getNode());
  5031. APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
  5032. if (N0.getOpcode() == ISD::FNEG)
  5033. return DAG.getNode(ISD::XOR, N->getDebugLoc(), VT,
  5034. NewConv, DAG.getConstant(SignBit, VT));
  5035. assert(N0.getOpcode() == ISD::FABS);
  5036. return DAG.getNode(ISD::AND, N->getDebugLoc(), VT,
  5037. NewConv, DAG.getConstant(~SignBit, VT));
  5038. }
  5039. // fold (bitconvert (fcopysign cst, x)) ->
  5040. // (or (and (bitconvert x), sign), (and cst, (not sign)))
  5041. // Note that we don't handle (copysign x, cst) because this can always be
  5042. // folded to an fneg or fabs.
  5043. if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse() &&
  5044. isa<ConstantFPSDNode>(N0.getOperand(0)) &&
  5045. VT.isInteger() && !VT.isVector()) {
  5046. unsigned OrigXWidth = N0.getOperand(1).getValueType().getSizeInBits();
  5047. EVT IntXVT = EVT::getIntegerVT(*DAG.getContext(), OrigXWidth);
  5048. if (isTypeLegal(IntXVT)) {
  5049. SDValue X = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
  5050. IntXVT, N0.getOperand(1));
  5051. AddToWorkList(X.getNode());
  5052. // If X has a different width than the result/lhs, sext it or truncate it.
  5053. unsigned VTWidth = VT.getSizeInBits();
  5054. if (OrigXWidth < VTWidth) {
  5055. X = DAG.getNode(ISD::SIGN_EXTEND, N->getDebugLoc(), VT, X);
  5056. AddToWorkList(X.getNode());
  5057. } else if (OrigXWidth > VTWidth) {
  5058. // To get the sign bit in the right place, we have to shift it right
  5059. // before truncating.
  5060. X = DAG.getNode(ISD::SRL, X.getDebugLoc(),
  5061. X.getValueType(), X,
  5062. DAG.getConstant(OrigXWidth-VTWidth, X.getValueType()));
  5063. AddToWorkList(X.getNode());
  5064. X = DAG.getNode(ISD::TRUNCATE, X.getDebugLoc(), VT, X);
  5065. AddToWorkList(X.getNode());
  5066. }
  5067. APInt SignBit = APInt::getSignBit(VT.getSizeInBits());
  5068. X = DAG.getNode(ISD::AND, X.getDebugLoc(), VT,
  5069. X, DAG.getConstant(SignBit, VT));
  5070. AddToWorkList(X.getNode());
  5071. SDValue Cst = DAG.getNode(ISD::BITCAST, N0.getDebugLoc(),
  5072. VT, N0.getOperand(0));
  5073. Cst = DAG.getNode(ISD::AND, Cst.getDebugLoc(), VT,
  5074. Cst, DAG.getConstant(~SignBit, VT));
  5075. AddToWorkList(Cst.getNode());
  5076. return DAG.getNode(ISD::OR, N->getDebugLoc(), VT, X, Cst);
  5077. }
  5078. }
  5079. // bitconvert(build_pair(ld, ld)) -> ld iff load locations are consecutive.
  5080. if (N0.getOpcode() == ISD::BUILD_PAIR) {
  5081. SDValue CombineLD = CombineConsecutiveLoads(N0.getNode(), VT);
  5082. if (CombineLD.getNode())
  5083. return CombineLD;
  5084. }
  5085. return SDValue();
  5086. }
  5087. SDValue DAGCombiner::visitBUILD_PAIR(SDNode *N) {
  5088. EVT VT = N->getValueType(0);
  5089. return CombineConsecutiveLoads(N, VT);
  5090. }
  5091. /// ConstantFoldBITCASTofBUILD_VECTOR - We know that BV is a build_vector
  5092. /// node with Constant, ConstantFP or Undef operands. DstEltVT indicates the
  5093. /// destination element value type.
  5094. SDValue DAGCombiner::
  5095. ConstantFoldBITCASTofBUILD_VECTOR(SDNode *BV, EVT DstEltVT) {
  5096. EVT SrcEltVT = BV->getValueType(0).getVectorElementType();
  5097. // If this is already the right type, we're done.
  5098. if (SrcEltVT == DstEltVT) return SDValue(BV, 0);
  5099. unsigned SrcBitSize = SrcEltVT.getSizeInBits();
  5100. unsigned DstBitSize = DstEltVT.getSizeInBits();
  5101. // If this is a conversion of N elements of one type to N elements of another
  5102. // type, convert each element. This handles FP<->INT cases.
  5103. if (SrcBitSize == DstBitSize) {
  5104. EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
  5105. BV->getValueType(0).getVectorNumElements());
  5106. // Due to the FP element handling below calling this routine recursively,
  5107. // we can end up with a scalar-to-vector node here.
  5108. if (BV->getOpcode() == ISD::SCALAR_TO_VECTOR)
  5109. return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
  5110. DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
  5111. DstEltVT, BV->getOperand(0)));
  5112. SmallVector<SDValue, 8> Ops;
  5113. for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
  5114. SDValue Op = BV->getOperand(i);
  5115. // If the vector element type is not legal, the BUILD_VECTOR operands
  5116. // are promoted and implicitly truncated. Make that explicit here.
  5117. if (Op.getValueType() != SrcEltVT)
  5118. Op = DAG.getNode(ISD::TRUNCATE, BV->getDebugLoc(), SrcEltVT, Op);
  5119. Ops.push_back(DAG.getNode(ISD::BITCAST, BV->getDebugLoc(),
  5120. DstEltVT, Op));
  5121. AddToWorkList(Ops.back().getNode());
  5122. }
  5123. return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
  5124. &Ops[0], Ops.size());
  5125. }
  5126. // Otherwise, we're growing or shrinking the elements. To avoid having to
  5127. // handle annoying details of growing/shrinking FP values, we convert them to
  5128. // int first.
  5129. if (SrcEltVT.isFloatingPoint()) {
  5130. // Convert the input float vector to a int vector where the elements are the
  5131. // same sizes.
  5132. assert((SrcEltVT == MVT::f32 || SrcEltVT == MVT::f64) && "Unknown FP VT!");
  5133. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), SrcEltVT.getSizeInBits());
  5134. BV = ConstantFoldBITCASTofBUILD_VECTOR(BV, IntVT).getNode();
  5135. SrcEltVT = IntVT;
  5136. }
  5137. // Now we know the input is an integer vector. If the output is a FP type,
  5138. // convert to integer first, then to FP of the right size.
  5139. if (DstEltVT.isFloatingPoint()) {
  5140. assert((DstEltVT == MVT::f32 || DstEltVT == MVT::f64) && "Unknown FP VT!");
  5141. EVT TmpVT = EVT::getIntegerVT(*DAG.getContext(), DstEltVT.getSizeInBits());
  5142. SDNode *Tmp = ConstantFoldBITCASTofBUILD_VECTOR(BV, TmpVT).getNode();
  5143. // Next, convert to FP elements of the same size.
  5144. return ConstantFoldBITCASTofBUILD_VECTOR(Tmp, DstEltVT);
  5145. }
  5146. // Okay, we know the src/dst types are both integers of differing types.
  5147. // Handling growing first.
  5148. assert(SrcEltVT.isInteger() && DstEltVT.isInteger());
  5149. if (SrcBitSize < DstBitSize) {
  5150. unsigned NumInputsPerOutput = DstBitSize/SrcBitSize;
  5151. SmallVector<SDValue, 8> Ops;
  5152. for (unsigned i = 0, e = BV->getNumOperands(); i != e;
  5153. i += NumInputsPerOutput) {
  5154. bool isLE = TLI.isLittleEndian();
  5155. APInt NewBits = APInt(DstBitSize, 0);
  5156. bool EltIsUndef = true;
  5157. for (unsigned j = 0; j != NumInputsPerOutput; ++j) {
  5158. // Shift the previously computed bits over.
  5159. NewBits <<= SrcBitSize;
  5160. SDValue Op = BV->getOperand(i+ (isLE ? (NumInputsPerOutput-j-1) : j));
  5161. if (Op.getOpcode() == ISD::UNDEF) continue;
  5162. EltIsUndef = false;
  5163. NewBits |= cast<ConstantSDNode>(Op)->getAPIntValue().
  5164. zextOrTrunc(SrcBitSize).zext(DstBitSize);
  5165. }
  5166. if (EltIsUndef)
  5167. Ops.push_back(DAG.getUNDEF(DstEltVT));
  5168. else
  5169. Ops.push_back(DAG.getConstant(NewBits, DstEltVT));
  5170. }
  5171. EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT, Ops.size());
  5172. return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
  5173. &Ops[0], Ops.size());
  5174. }
  5175. // Finally, this must be the case where we are shrinking elements: each input
  5176. // turns into multiple outputs.
  5177. bool isS2V = ISD::isScalarToVector(BV);
  5178. unsigned NumOutputsPerInput = SrcBitSize/DstBitSize;
  5179. EVT VT = EVT::getVectorVT(*DAG.getContext(), DstEltVT,
  5180. NumOutputsPerInput*BV->getNumOperands());
  5181. SmallVector<SDValue, 8> Ops;
  5182. for (unsigned i = 0, e = BV->getNumOperands(); i != e; ++i) {
  5183. if (BV->getOperand(i).getOpcode() == ISD::UNDEF) {
  5184. for (unsigned j = 0; j != NumOutputsPerInput; ++j)
  5185. Ops.push_back(DAG.getUNDEF(DstEltVT));
  5186. continue;
  5187. }
  5188. APInt OpVal = cast<ConstantSDNode>(BV->getOperand(i))->
  5189. getAPIntValue().zextOrTrunc(SrcBitSize);
  5190. for (unsigned j = 0; j != NumOutputsPerInput; ++j) {
  5191. APInt ThisVal = OpVal.trunc(DstBitSize);
  5192. Ops.push_back(DAG.getConstant(ThisVal, DstEltVT));
  5193. if (isS2V && i == 0 && j == 0 && ThisVal.zext(SrcBitSize) == OpVal)
  5194. // Simply turn this into a SCALAR_TO_VECTOR of the new type.
  5195. return DAG.getNode(ISD::SCALAR_TO_VECTOR, BV->getDebugLoc(), VT,
  5196. Ops[0]);
  5197. OpVal = OpVal.lshr(DstBitSize);
  5198. }
  5199. // For big endian targets, swap the order of the pieces of each element.
  5200. if (TLI.isBigEndian())
  5201. std::reverse(Ops.end()-NumOutputsPerInput, Ops.end());
  5202. }
  5203. return DAG.getNode(ISD::BUILD_VECTOR, BV->getDebugLoc(), VT,
  5204. &Ops[0], Ops.size());
  5205. }
  5206. SDValue DAGCombiner::visitFADD(SDNode *N) {
  5207. SDValue N0 = N->getOperand(0);
  5208. SDValue N1 = N->getOperand(1);
  5209. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5210. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  5211. EVT VT = N->getValueType(0);
  5212. // fold vector ops
  5213. if (VT.isVector()) {
  5214. SDValue FoldedVOp = SimplifyVBinOp(N);
  5215. if (FoldedVOp.getNode()) return FoldedVOp;
  5216. }
  5217. // fold (fadd c1, c2) -> c1 + c2
  5218. if (N0CFP && N1CFP)
  5219. return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N1);
  5220. // canonicalize constant to RHS
  5221. if (N0CFP && !N1CFP)
  5222. return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N0);
  5223. // fold (fadd A, 0) -> A
  5224. if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
  5225. N1CFP->getValueAPF().isZero())
  5226. return N0;
  5227. // fold (fadd A, (fneg B)) -> (fsub A, B)
  5228. if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
  5229. isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
  5230. return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0,
  5231. GetNegatedExpression(N1, DAG, LegalOperations));
  5232. // fold (fadd (fneg A), B) -> (fsub B, A)
  5233. if ((!LegalOperations || TLI.isOperationLegalOrCustom(ISD::FSUB, VT)) &&
  5234. isNegatibleForFree(N0, LegalOperations, TLI, &DAG.getTarget().Options) == 2)
  5235. return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N1,
  5236. GetNegatedExpression(N0, DAG, LegalOperations));
  5237. // If allowed, fold (fadd (fadd x, c1), c2) -> (fadd x, (fadd c1, c2))
  5238. if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
  5239. N0.getOpcode() == ISD::FADD && N0.getNode()->hasOneUse() &&
  5240. isa<ConstantFPSDNode>(N0.getOperand(1)))
  5241. return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0.getOperand(0),
  5242. DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
  5243. N0.getOperand(1), N1));
  5244. // No FP constant should be created after legalization as Instruction
  5245. // Selection pass has hard time in dealing with FP constant.
  5246. //
  5247. // We don't need test this condition for transformation like following, as
  5248. // the DAG being transformed implies it is legal to take FP constant as
  5249. // operand.
  5250. //
  5251. // (fadd (fmul c, x), x) -> (fmul c+1, x)
  5252. //
  5253. bool AllowNewFpConst = (Level < AfterLegalizeDAG);
  5254. // If allow, fold (fadd (fneg x), x) -> 0.0
  5255. if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
  5256. N0.getOpcode() == ISD::FNEG && N0.getOperand(0) == N1) {
  5257. return DAG.getConstantFP(0.0, VT);
  5258. }
  5259. // If allow, fold (fadd x, (fneg x)) -> 0.0
  5260. if (AllowNewFpConst && DAG.getTarget().Options.UnsafeFPMath &&
  5261. N1.getOpcode() == ISD::FNEG && N1.getOperand(0) == N0) {
  5262. return DAG.getConstantFP(0.0, VT);
  5263. }
  5264. // In unsafe math mode, we can fold chains of FADD's of the same value
  5265. // into multiplications. This transform is not safe in general because
  5266. // we are reducing the number of rounding steps.
  5267. if (DAG.getTarget().Options.UnsafeFPMath &&
  5268. TLI.isOperationLegalOrCustom(ISD::FMUL, VT) &&
  5269. !N0CFP && !N1CFP) {
  5270. if (N0.getOpcode() == ISD::FMUL) {
  5271. ConstantFPSDNode *CFP00 = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
  5272. ConstantFPSDNode *CFP01 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
  5273. // (fadd (fmul c, x), x) -> (fmul c+1, x)
  5274. if (CFP00 && !CFP01 && N0.getOperand(1) == N1) {
  5275. SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
  5276. SDValue(CFP00, 0),
  5277. DAG.getConstantFP(1.0, VT));
  5278. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5279. N1, NewCFP);
  5280. }
  5281. // (fadd (fmul x, c), x) -> (fmul c+1, x)
  5282. if (CFP01 && !CFP00 && N0.getOperand(0) == N1) {
  5283. SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
  5284. SDValue(CFP01, 0),
  5285. DAG.getConstantFP(1.0, VT));
  5286. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5287. N1, NewCFP);
  5288. }
  5289. // (fadd (fmul c, x), (fadd x, x)) -> (fmul c+2, x)
  5290. if (CFP00 && !CFP01 && N1.getOpcode() == ISD::FADD &&
  5291. N1.getOperand(0) == N1.getOperand(1) &&
  5292. N0.getOperand(1) == N1.getOperand(0)) {
  5293. SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
  5294. SDValue(CFP00, 0),
  5295. DAG.getConstantFP(2.0, VT));
  5296. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5297. N0.getOperand(1), NewCFP);
  5298. }
  5299. // (fadd (fmul x, c), (fadd x, x)) -> (fmul c+2, x)
  5300. if (CFP01 && !CFP00 && N1.getOpcode() == ISD::FADD &&
  5301. N1.getOperand(0) == N1.getOperand(1) &&
  5302. N0.getOperand(0) == N1.getOperand(0)) {
  5303. SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
  5304. SDValue(CFP01, 0),
  5305. DAG.getConstantFP(2.0, VT));
  5306. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5307. N0.getOperand(0), NewCFP);
  5308. }
  5309. }
  5310. if (N1.getOpcode() == ISD::FMUL) {
  5311. ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
  5312. ConstantFPSDNode *CFP11 = dyn_cast<ConstantFPSDNode>(N1.getOperand(1));
  5313. // (fadd x, (fmul c, x)) -> (fmul c+1, x)
  5314. if (CFP10 && !CFP11 && N1.getOperand(1) == N0) {
  5315. SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
  5316. SDValue(CFP10, 0),
  5317. DAG.getConstantFP(1.0, VT));
  5318. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5319. N0, NewCFP);
  5320. }
  5321. // (fadd x, (fmul x, c)) -> (fmul c+1, x)
  5322. if (CFP11 && !CFP10 && N1.getOperand(0) == N0) {
  5323. SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
  5324. SDValue(CFP11, 0),
  5325. DAG.getConstantFP(1.0, VT));
  5326. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5327. N0, NewCFP);
  5328. }
  5329. // (fadd (fadd x, x), (fmul c, x)) -> (fmul c+2, x)
  5330. if (CFP10 && !CFP11 && N1.getOpcode() == ISD::FADD &&
  5331. N1.getOperand(0) == N1.getOperand(1) &&
  5332. N0.getOperand(1) == N1.getOperand(0)) {
  5333. SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
  5334. SDValue(CFP10, 0),
  5335. DAG.getConstantFP(2.0, VT));
  5336. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5337. N0.getOperand(1), NewCFP);
  5338. }
  5339. // (fadd (fadd x, x), (fmul x, c)) -> (fmul c+2, x)
  5340. if (CFP11 && !CFP10 && N1.getOpcode() == ISD::FADD &&
  5341. N1.getOperand(0) == N1.getOperand(1) &&
  5342. N0.getOperand(0) == N1.getOperand(0)) {
  5343. SDValue NewCFP = DAG.getNode(ISD::FADD, N->getDebugLoc(), VT,
  5344. SDValue(CFP11, 0),
  5345. DAG.getConstantFP(2.0, VT));
  5346. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5347. N0.getOperand(0), NewCFP);
  5348. }
  5349. }
  5350. if (N0.getOpcode() == ISD::FADD && AllowNewFpConst) {
  5351. ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N0.getOperand(0));
  5352. // (fadd (fadd x, x), x) -> (fmul 3.0, x)
  5353. if (!CFP && N0.getOperand(0) == N0.getOperand(1) &&
  5354. (N0.getOperand(0) == N1)) {
  5355. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5356. N1, DAG.getConstantFP(3.0, VT));
  5357. }
  5358. }
  5359. if (N1.getOpcode() == ISD::FADD && AllowNewFpConst) {
  5360. ConstantFPSDNode *CFP10 = dyn_cast<ConstantFPSDNode>(N1.getOperand(0));
  5361. // (fadd x, (fadd x, x)) -> (fmul 3.0, x)
  5362. if (!CFP10 && N1.getOperand(0) == N1.getOperand(1) &&
  5363. N1.getOperand(0) == N0) {
  5364. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5365. N0, DAG.getConstantFP(3.0, VT));
  5366. }
  5367. }
  5368. // (fadd (fadd x, x), (fadd x, x)) -> (fmul 4.0, x)
  5369. if (AllowNewFpConst &&
  5370. N0.getOpcode() == ISD::FADD && N1.getOpcode() == ISD::FADD &&
  5371. N0.getOperand(0) == N0.getOperand(1) &&
  5372. N1.getOperand(0) == N1.getOperand(1) &&
  5373. N0.getOperand(0) == N1.getOperand(0)) {
  5374. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5375. N0.getOperand(0),
  5376. DAG.getConstantFP(4.0, VT));
  5377. }
  5378. }
  5379. // FADD -> FMA combines:
  5380. if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
  5381. DAG.getTarget().Options.UnsafeFPMath) &&
  5382. DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
  5383. TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
  5384. // fold (fadd (fmul x, y), z) -> (fma x, y, z)
  5385. if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
  5386. return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
  5387. N0.getOperand(0), N0.getOperand(1), N1);
  5388. }
  5389. // fold (fadd x, (fmul y, z)) -> (fma y, z, x)
  5390. // Note: Commutes FADD operands.
  5391. if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
  5392. return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT,
  5393. N1.getOperand(0), N1.getOperand(1), N0);
  5394. }
  5395. }
  5396. return SDValue();
  5397. }
  5398. SDValue DAGCombiner::visitFSUB(SDNode *N) {
  5399. SDValue N0 = N->getOperand(0);
  5400. SDValue N1 = N->getOperand(1);
  5401. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5402. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  5403. EVT VT = N->getValueType(0);
  5404. DebugLoc dl = N->getDebugLoc();
  5405. // fold vector ops
  5406. if (VT.isVector()) {
  5407. SDValue FoldedVOp = SimplifyVBinOp(N);
  5408. if (FoldedVOp.getNode()) return FoldedVOp;
  5409. }
  5410. // fold (fsub c1, c2) -> c1-c2
  5411. if (N0CFP && N1CFP)
  5412. return DAG.getNode(ISD::FSUB, N->getDebugLoc(), VT, N0, N1);
  5413. // fold (fsub A, 0) -> A
  5414. if (DAG.getTarget().Options.UnsafeFPMath &&
  5415. N1CFP && N1CFP->getValueAPF().isZero())
  5416. return N0;
  5417. // fold (fsub 0, B) -> -B
  5418. if (DAG.getTarget().Options.UnsafeFPMath &&
  5419. N0CFP && N0CFP->getValueAPF().isZero()) {
  5420. if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
  5421. return GetNegatedExpression(N1, DAG, LegalOperations);
  5422. if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
  5423. return DAG.getNode(ISD::FNEG, dl, VT, N1);
  5424. }
  5425. // fold (fsub A, (fneg B)) -> (fadd A, B)
  5426. if (isNegatibleForFree(N1, LegalOperations, TLI, &DAG.getTarget().Options))
  5427. return DAG.getNode(ISD::FADD, dl, VT, N0,
  5428. GetNegatedExpression(N1, DAG, LegalOperations));
  5429. // If 'unsafe math' is enabled, fold
  5430. // (fsub x, x) -> 0.0 &
  5431. // (fsub x, (fadd x, y)) -> (fneg y) &
  5432. // (fsub x, (fadd y, x)) -> (fneg y)
  5433. if (DAG.getTarget().Options.UnsafeFPMath) {
  5434. if (N0 == N1)
  5435. return DAG.getConstantFP(0.0f, VT);
  5436. if (N1.getOpcode() == ISD::FADD) {
  5437. SDValue N10 = N1->getOperand(0);
  5438. SDValue N11 = N1->getOperand(1);
  5439. if (N10 == N0 && isNegatibleForFree(N11, LegalOperations, TLI,
  5440. &DAG.getTarget().Options))
  5441. return GetNegatedExpression(N11, DAG, LegalOperations);
  5442. else if (N11 == N0 && isNegatibleForFree(N10, LegalOperations, TLI,
  5443. &DAG.getTarget().Options))
  5444. return GetNegatedExpression(N10, DAG, LegalOperations);
  5445. }
  5446. }
  5447. // FSUB -> FMA combines:
  5448. if ((DAG.getTarget().Options.AllowFPOpFusion == FPOpFusion::Fast ||
  5449. DAG.getTarget().Options.UnsafeFPMath) &&
  5450. DAG.getTarget().getTargetLowering()->isFMAFasterThanMulAndAdd(VT) &&
  5451. TLI.isOperationLegalOrCustom(ISD::FMA, VT)) {
  5452. // fold (fsub (fmul x, y), z) -> (fma x, y, (fneg z))
  5453. if (N0.getOpcode() == ISD::FMUL && N0->hasOneUse()) {
  5454. return DAG.getNode(ISD::FMA, dl, VT,
  5455. N0.getOperand(0), N0.getOperand(1),
  5456. DAG.getNode(ISD::FNEG, dl, VT, N1));
  5457. }
  5458. // fold (fsub x, (fmul y, z)) -> (fma (fneg y), z, x)
  5459. // Note: Commutes FSUB operands.
  5460. if (N1.getOpcode() == ISD::FMUL && N1->hasOneUse()) {
  5461. return DAG.getNode(ISD::FMA, dl, VT,
  5462. DAG.getNode(ISD::FNEG, dl, VT,
  5463. N1.getOperand(0)),
  5464. N1.getOperand(1), N0);
  5465. }
  5466. // fold (fsub (-(fmul, x, y)), z) -> (fma (fneg x), y, (fneg z))
  5467. if (N0.getOpcode() == ISD::FNEG &&
  5468. N0.getOperand(0).getOpcode() == ISD::FMUL &&
  5469. N0->hasOneUse() && N0.getOperand(0).hasOneUse()) {
  5470. SDValue N00 = N0.getOperand(0).getOperand(0);
  5471. SDValue N01 = N0.getOperand(0).getOperand(1);
  5472. return DAG.getNode(ISD::FMA, dl, VT,
  5473. DAG.getNode(ISD::FNEG, dl, VT, N00), N01,
  5474. DAG.getNode(ISD::FNEG, dl, VT, N1));
  5475. }
  5476. }
  5477. return SDValue();
  5478. }
  5479. SDValue DAGCombiner::visitFMUL(SDNode *N) {
  5480. SDValue N0 = N->getOperand(0);
  5481. SDValue N1 = N->getOperand(1);
  5482. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5483. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  5484. EVT VT = N->getValueType(0);
  5485. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5486. // fold vector ops
  5487. if (VT.isVector()) {
  5488. SDValue FoldedVOp = SimplifyVBinOp(N);
  5489. if (FoldedVOp.getNode()) return FoldedVOp;
  5490. }
  5491. // fold (fmul c1, c2) -> c1*c2
  5492. if (N0CFP && N1CFP)
  5493. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0, N1);
  5494. // canonicalize constant to RHS
  5495. if (N0CFP && !N1CFP)
  5496. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N1, N0);
  5497. // fold (fmul A, 0) -> 0
  5498. if (DAG.getTarget().Options.UnsafeFPMath &&
  5499. N1CFP && N1CFP->getValueAPF().isZero())
  5500. return N1;
  5501. // fold (fmul A, 0) -> 0, vector edition.
  5502. if (DAG.getTarget().Options.UnsafeFPMath &&
  5503. ISD::isBuildVectorAllZeros(N1.getNode()))
  5504. return N1;
  5505. // fold (fmul A, 1.0) -> A
  5506. if (N1CFP && N1CFP->isExactlyValue(1.0))
  5507. return N0;
  5508. // fold (fmul X, 2.0) -> (fadd X, X)
  5509. if (N1CFP && N1CFP->isExactlyValue(+2.0))
  5510. return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N0);
  5511. // fold (fmul X, -1.0) -> (fneg X)
  5512. if (N1CFP && N1CFP->isExactlyValue(-1.0))
  5513. if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
  5514. return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT, N0);
  5515. // fold (fmul (fneg X), (fneg Y)) -> (fmul X, Y)
  5516. if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
  5517. &DAG.getTarget().Options)) {
  5518. if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
  5519. &DAG.getTarget().Options)) {
  5520. // Both can be negated for free, check to see if at least one is cheaper
  5521. // negated.
  5522. if (LHSNeg == 2 || RHSNeg == 2)
  5523. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5524. GetNegatedExpression(N0, DAG, LegalOperations),
  5525. GetNegatedExpression(N1, DAG, LegalOperations));
  5526. }
  5527. }
  5528. // If allowed, fold (fmul (fmul x, c1), c2) -> (fmul x, (fmul c1, c2))
  5529. if (DAG.getTarget().Options.UnsafeFPMath &&
  5530. N1CFP && N0.getOpcode() == ISD::FMUL &&
  5531. N0.getNode()->hasOneUse() && isa<ConstantFPSDNode>(N0.getOperand(1)))
  5532. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0.getOperand(0),
  5533. DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5534. N0.getOperand(1), N1));
  5535. return SDValue();
  5536. }
  5537. SDValue DAGCombiner::visitFMA(SDNode *N) {
  5538. SDValue N0 = N->getOperand(0);
  5539. SDValue N1 = N->getOperand(1);
  5540. SDValue N2 = N->getOperand(2);
  5541. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5542. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  5543. EVT VT = N->getValueType(0);
  5544. DebugLoc dl = N->getDebugLoc();
  5545. if (DAG.getTarget().Options.UnsafeFPMath) {
  5546. if (N0CFP && N0CFP->isZero())
  5547. return N2;
  5548. if (N1CFP && N1CFP->isZero())
  5549. return N2;
  5550. }
  5551. if (N0CFP && N0CFP->isExactlyValue(1.0))
  5552. return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N1, N2);
  5553. if (N1CFP && N1CFP->isExactlyValue(1.0))
  5554. return DAG.getNode(ISD::FADD, N->getDebugLoc(), VT, N0, N2);
  5555. // Canonicalize (fma c, x, y) -> (fma x, c, y)
  5556. if (N0CFP && !N1CFP)
  5557. return DAG.getNode(ISD::FMA, N->getDebugLoc(), VT, N1, N0, N2);
  5558. // (fma x, c1, (fmul x, c2)) -> (fmul x, c1+c2)
  5559. if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
  5560. N2.getOpcode() == ISD::FMUL &&
  5561. N0 == N2.getOperand(0) &&
  5562. N2.getOperand(1).getOpcode() == ISD::ConstantFP) {
  5563. return DAG.getNode(ISD::FMUL, dl, VT, N0,
  5564. DAG.getNode(ISD::FADD, dl, VT, N1, N2.getOperand(1)));
  5565. }
  5566. // (fma (fmul x, c1), c2, y) -> (fma x, c1*c2, y)
  5567. if (DAG.getTarget().Options.UnsafeFPMath &&
  5568. N0.getOpcode() == ISD::FMUL && N1CFP &&
  5569. N0.getOperand(1).getOpcode() == ISD::ConstantFP) {
  5570. return DAG.getNode(ISD::FMA, dl, VT,
  5571. N0.getOperand(0),
  5572. DAG.getNode(ISD::FMUL, dl, VT, N1, N0.getOperand(1)),
  5573. N2);
  5574. }
  5575. // (fma x, 1, y) -> (fadd x, y)
  5576. // (fma x, -1, y) -> (fadd (fneg x), y)
  5577. if (N1CFP) {
  5578. if (N1CFP->isExactlyValue(1.0))
  5579. return DAG.getNode(ISD::FADD, dl, VT, N0, N2);
  5580. if (N1CFP->isExactlyValue(-1.0) &&
  5581. (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))) {
  5582. SDValue RHSNeg = DAG.getNode(ISD::FNEG, dl, VT, N0);
  5583. AddToWorkList(RHSNeg.getNode());
  5584. return DAG.getNode(ISD::FADD, dl, VT, N2, RHSNeg);
  5585. }
  5586. }
  5587. // (fma x, c, x) -> (fmul x, (c+1))
  5588. if (DAG.getTarget().Options.UnsafeFPMath && N1CFP && N0 == N2) {
  5589. return DAG.getNode(ISD::FMUL, dl, VT,
  5590. N0,
  5591. DAG.getNode(ISD::FADD, dl, VT,
  5592. N1, DAG.getConstantFP(1.0, VT)));
  5593. }
  5594. // (fma x, c, (fneg x)) -> (fmul x, (c-1))
  5595. if (DAG.getTarget().Options.UnsafeFPMath && N1CFP &&
  5596. N2.getOpcode() == ISD::FNEG && N2.getOperand(0) == N0) {
  5597. return DAG.getNode(ISD::FMUL, dl, VT,
  5598. N0,
  5599. DAG.getNode(ISD::FADD, dl, VT,
  5600. N1, DAG.getConstantFP(-1.0, VT)));
  5601. }
  5602. return SDValue();
  5603. }
  5604. SDValue DAGCombiner::visitFDIV(SDNode *N) {
  5605. SDValue N0 = N->getOperand(0);
  5606. SDValue N1 = N->getOperand(1);
  5607. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5608. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  5609. EVT VT = N->getValueType(0);
  5610. const TargetLowering &TLI = DAG.getTargetLoweringInfo();
  5611. // fold vector ops
  5612. if (VT.isVector()) {
  5613. SDValue FoldedVOp = SimplifyVBinOp(N);
  5614. if (FoldedVOp.getNode()) return FoldedVOp;
  5615. }
  5616. // fold (fdiv c1, c2) -> c1/c2
  5617. if (N0CFP && N1CFP)
  5618. return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT, N0, N1);
  5619. // fold (fdiv X, c2) -> fmul X, 1/c2 if losing precision is acceptable.
  5620. if (N1CFP && DAG.getTarget().Options.UnsafeFPMath) {
  5621. // Compute the reciprocal 1.0 / c2.
  5622. APFloat N1APF = N1CFP->getValueAPF();
  5623. APFloat Recip(N1APF.getSemantics(), 1); // 1.0
  5624. APFloat::opStatus st = Recip.divide(N1APF, APFloat::rmNearestTiesToEven);
  5625. // Only do the transform if the reciprocal is a legal fp immediate that
  5626. // isn't too nasty (eg NaN, denormal, ...).
  5627. if ((st == APFloat::opOK || st == APFloat::opInexact) && // Not too nasty
  5628. (!LegalOperations ||
  5629. // FIXME: custom lowering of ConstantFP might fail (see e.g. ARM
  5630. // backend)... we should handle this gracefully after Legalize.
  5631. // TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT) ||
  5632. TLI.isOperationLegal(llvm::ISD::ConstantFP, VT) ||
  5633. TLI.isFPImmLegal(Recip, VT)))
  5634. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT, N0,
  5635. DAG.getConstantFP(Recip, VT));
  5636. }
  5637. // (fdiv (fneg X), (fneg Y)) -> (fdiv X, Y)
  5638. if (char LHSNeg = isNegatibleForFree(N0, LegalOperations, TLI,
  5639. &DAG.getTarget().Options)) {
  5640. if (char RHSNeg = isNegatibleForFree(N1, LegalOperations, TLI,
  5641. &DAG.getTarget().Options)) {
  5642. // Both can be negated for free, check to see if at least one is cheaper
  5643. // negated.
  5644. if (LHSNeg == 2 || RHSNeg == 2)
  5645. return DAG.getNode(ISD::FDIV, N->getDebugLoc(), VT,
  5646. GetNegatedExpression(N0, DAG, LegalOperations),
  5647. GetNegatedExpression(N1, DAG, LegalOperations));
  5648. }
  5649. }
  5650. return SDValue();
  5651. }
  5652. SDValue DAGCombiner::visitFREM(SDNode *N) {
  5653. SDValue N0 = N->getOperand(0);
  5654. SDValue N1 = N->getOperand(1);
  5655. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5656. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  5657. EVT VT = N->getValueType(0);
  5658. // fold (frem c1, c2) -> fmod(c1,c2)
  5659. if (N0CFP && N1CFP)
  5660. return DAG.getNode(ISD::FREM, N->getDebugLoc(), VT, N0, N1);
  5661. return SDValue();
  5662. }
  5663. SDValue DAGCombiner::visitFCOPYSIGN(SDNode *N) {
  5664. SDValue N0 = N->getOperand(0);
  5665. SDValue N1 = N->getOperand(1);
  5666. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5667. ConstantFPSDNode *N1CFP = dyn_cast<ConstantFPSDNode>(N1);
  5668. EVT VT = N->getValueType(0);
  5669. if (N0CFP && N1CFP) // Constant fold
  5670. return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT, N0, N1);
  5671. if (N1CFP) {
  5672. const APFloat& V = N1CFP->getValueAPF();
  5673. // copysign(x, c1) -> fabs(x) iff ispos(c1)
  5674. // copysign(x, c1) -> fneg(fabs(x)) iff isneg(c1)
  5675. if (!V.isNegative()) {
  5676. if (!LegalOperations || TLI.isOperationLegal(ISD::FABS, VT))
  5677. return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
  5678. } else {
  5679. if (!LegalOperations || TLI.isOperationLegal(ISD::FNEG, VT))
  5680. return DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
  5681. DAG.getNode(ISD::FABS, N0.getDebugLoc(), VT, N0));
  5682. }
  5683. }
  5684. // copysign(fabs(x), y) -> copysign(x, y)
  5685. // copysign(fneg(x), y) -> copysign(x, y)
  5686. // copysign(copysign(x,z), y) -> copysign(x, y)
  5687. if (N0.getOpcode() == ISD::FABS || N0.getOpcode() == ISD::FNEG ||
  5688. N0.getOpcode() == ISD::FCOPYSIGN)
  5689. return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
  5690. N0.getOperand(0), N1);
  5691. // copysign(x, abs(y)) -> abs(x)
  5692. if (N1.getOpcode() == ISD::FABS)
  5693. return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
  5694. // copysign(x, copysign(y,z)) -> copysign(x, z)
  5695. if (N1.getOpcode() == ISD::FCOPYSIGN)
  5696. return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
  5697. N0, N1.getOperand(1));
  5698. // copysign(x, fp_extend(y)) -> copysign(x, y)
  5699. // copysign(x, fp_round(y)) -> copysign(x, y)
  5700. if (N1.getOpcode() == ISD::FP_EXTEND || N1.getOpcode() == ISD::FP_ROUND)
  5701. return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
  5702. N0, N1.getOperand(0));
  5703. return SDValue();
  5704. }
  5705. SDValue DAGCombiner::visitSINT_TO_FP(SDNode *N) {
  5706. SDValue N0 = N->getOperand(0);
  5707. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  5708. EVT VT = N->getValueType(0);
  5709. EVT OpVT = N0.getValueType();
  5710. // fold (sint_to_fp c1) -> c1fp
  5711. if (N0C &&
  5712. // ...but only if the target supports immediate floating-point values
  5713. (!LegalOperations ||
  5714. TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
  5715. return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
  5716. // If the input is a legal type, and SINT_TO_FP is not legal on this target,
  5717. // but UINT_TO_FP is legal on this target, try to convert.
  5718. if (!TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT) &&
  5719. TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT)) {
  5720. // If the sign bit is known to be zero, we can change this to UINT_TO_FP.
  5721. if (DAG.SignBitIsZero(N0))
  5722. return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
  5723. }
  5724. // The next optimizations are desireable only if SELECT_CC can be lowered.
  5725. // Check against MVT::Other for SELECT_CC, which is a workaround for targets
  5726. // having to say they don't support SELECT_CC on every type the DAG knows
  5727. // about, since there is no way to mark an opcode illegal at all value types
  5728. // (See also visitSELECT)
  5729. if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
  5730. // fold (sint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
  5731. if (N0.getOpcode() == ISD::SETCC && N0.getValueType() == MVT::i1 &&
  5732. !VT.isVector() &&
  5733. (!LegalOperations ||
  5734. TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
  5735. SDValue Ops[] =
  5736. { N0.getOperand(0), N0.getOperand(1),
  5737. DAG.getConstantFP(-1.0, VT) , DAG.getConstantFP(0.0, VT),
  5738. N0.getOperand(2) };
  5739. return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
  5740. }
  5741. // fold (sint_to_fp (zext (setcc x, y, cc))) ->
  5742. // (select_cc x, y, 1.0, 0.0,, cc)
  5743. if (N0.getOpcode() == ISD::ZERO_EXTEND &&
  5744. N0.getOperand(0).getOpcode() == ISD::SETCC &&!VT.isVector() &&
  5745. (!LegalOperations ||
  5746. TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
  5747. SDValue Ops[] =
  5748. { N0.getOperand(0).getOperand(0), N0.getOperand(0).getOperand(1),
  5749. DAG.getConstantFP(1.0, VT) , DAG.getConstantFP(0.0, VT),
  5750. N0.getOperand(0).getOperand(2) };
  5751. return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
  5752. }
  5753. }
  5754. return SDValue();
  5755. }
  5756. SDValue DAGCombiner::visitUINT_TO_FP(SDNode *N) {
  5757. SDValue N0 = N->getOperand(0);
  5758. ConstantSDNode *N0C = dyn_cast<ConstantSDNode>(N0);
  5759. EVT VT = N->getValueType(0);
  5760. EVT OpVT = N0.getValueType();
  5761. // fold (uint_to_fp c1) -> c1fp
  5762. if (N0C &&
  5763. // ...but only if the target supports immediate floating-point values
  5764. (!LegalOperations ||
  5765. TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT)))
  5766. return DAG.getNode(ISD::UINT_TO_FP, N->getDebugLoc(), VT, N0);
  5767. // If the input is a legal type, and UINT_TO_FP is not legal on this target,
  5768. // but SINT_TO_FP is legal on this target, try to convert.
  5769. if (!TLI.isOperationLegalOrCustom(ISD::UINT_TO_FP, OpVT) &&
  5770. TLI.isOperationLegalOrCustom(ISD::SINT_TO_FP, OpVT)) {
  5771. // If the sign bit is known to be zero, we can change this to SINT_TO_FP.
  5772. if (DAG.SignBitIsZero(N0))
  5773. return DAG.getNode(ISD::SINT_TO_FP, N->getDebugLoc(), VT, N0);
  5774. }
  5775. // The next optimizations are desireable only if SELECT_CC can be lowered.
  5776. // Check against MVT::Other for SELECT_CC, which is a workaround for targets
  5777. // having to say they don't support SELECT_CC on every type the DAG knows
  5778. // about, since there is no way to mark an opcode illegal at all value types
  5779. // (See also visitSELECT)
  5780. if (TLI.isOperationLegalOrCustom(ISD::SELECT_CC, MVT::Other)) {
  5781. // fold (uint_to_fp (setcc x, y, cc)) -> (select_cc x, y, -1.0, 0.0,, cc)
  5782. if (N0.getOpcode() == ISD::SETCC && !VT.isVector() &&
  5783. (!LegalOperations ||
  5784. TLI.isOperationLegalOrCustom(llvm::ISD::ConstantFP, VT))) {
  5785. SDValue Ops[] =
  5786. { N0.getOperand(0), N0.getOperand(1),
  5787. DAG.getConstantFP(1.0, VT), DAG.getConstantFP(0.0, VT),
  5788. N0.getOperand(2) };
  5789. return DAG.getNode(ISD::SELECT_CC, N->getDebugLoc(), VT, Ops, 5);
  5790. }
  5791. }
  5792. return SDValue();
  5793. }
  5794. SDValue DAGCombiner::visitFP_TO_SINT(SDNode *N) {
  5795. SDValue N0 = N->getOperand(0);
  5796. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5797. EVT VT = N->getValueType(0);
  5798. // fold (fp_to_sint c1fp) -> c1
  5799. if (N0CFP)
  5800. return DAG.getNode(ISD::FP_TO_SINT, N->getDebugLoc(), VT, N0);
  5801. return SDValue();
  5802. }
  5803. SDValue DAGCombiner::visitFP_TO_UINT(SDNode *N) {
  5804. SDValue N0 = N->getOperand(0);
  5805. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5806. EVT VT = N->getValueType(0);
  5807. // fold (fp_to_uint c1fp) -> c1
  5808. if (N0CFP)
  5809. return DAG.getNode(ISD::FP_TO_UINT, N->getDebugLoc(), VT, N0);
  5810. return SDValue();
  5811. }
  5812. SDValue DAGCombiner::visitFP_ROUND(SDNode *N) {
  5813. SDValue N0 = N->getOperand(0);
  5814. SDValue N1 = N->getOperand(1);
  5815. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5816. EVT VT = N->getValueType(0);
  5817. // fold (fp_round c1fp) -> c1fp
  5818. if (N0CFP)
  5819. return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0, N1);
  5820. // fold (fp_round (fp_extend x)) -> x
  5821. if (N0.getOpcode() == ISD::FP_EXTEND && VT == N0.getOperand(0).getValueType())
  5822. return N0.getOperand(0);
  5823. // fold (fp_round (fp_round x)) -> (fp_round x)
  5824. if (N0.getOpcode() == ISD::FP_ROUND) {
  5825. // This is a value preserving truncation if both round's are.
  5826. bool IsTrunc = N->getConstantOperandVal(1) == 1 &&
  5827. N0.getNode()->getConstantOperandVal(1) == 1;
  5828. return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT, N0.getOperand(0),
  5829. DAG.getIntPtrConstant(IsTrunc));
  5830. }
  5831. // fold (fp_round (copysign X, Y)) -> (copysign (fp_round X), Y)
  5832. if (N0.getOpcode() == ISD::FCOPYSIGN && N0.getNode()->hasOneUse()) {
  5833. SDValue Tmp = DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(), VT,
  5834. N0.getOperand(0), N1);
  5835. AddToWorkList(Tmp.getNode());
  5836. return DAG.getNode(ISD::FCOPYSIGN, N->getDebugLoc(), VT,
  5837. Tmp, N0.getOperand(1));
  5838. }
  5839. return SDValue();
  5840. }
  5841. SDValue DAGCombiner::visitFP_ROUND_INREG(SDNode *N) {
  5842. SDValue N0 = N->getOperand(0);
  5843. EVT VT = N->getValueType(0);
  5844. EVT EVT = cast<VTSDNode>(N->getOperand(1))->getVT();
  5845. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5846. // fold (fp_round_inreg c1fp) -> c1fp
  5847. if (N0CFP && isTypeLegal(EVT)) {
  5848. SDValue Round = DAG.getConstantFP(*N0CFP->getConstantFPValue(), EVT);
  5849. return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, Round);
  5850. }
  5851. return SDValue();
  5852. }
  5853. SDValue DAGCombiner::visitFP_EXTEND(SDNode *N) {
  5854. SDValue N0 = N->getOperand(0);
  5855. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5856. EVT VT = N->getValueType(0);
  5857. // If this is fp_round(fpextend), don't fold it, allow ourselves to be folded.
  5858. if (N->hasOneUse() &&
  5859. N->use_begin()->getOpcode() == ISD::FP_ROUND)
  5860. return SDValue();
  5861. // fold (fp_extend c1fp) -> c1fp
  5862. if (N0CFP)
  5863. return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, N0);
  5864. // Turn fp_extend(fp_round(X, 1)) -> x since the fp_round doesn't affect the
  5865. // value of X.
  5866. if (N0.getOpcode() == ISD::FP_ROUND
  5867. && N0.getNode()->getConstantOperandVal(1) == 1) {
  5868. SDValue In = N0.getOperand(0);
  5869. if (In.getValueType() == VT) return In;
  5870. if (VT.bitsLT(In.getValueType()))
  5871. return DAG.getNode(ISD::FP_ROUND, N->getDebugLoc(), VT,
  5872. In, N0.getOperand(1));
  5873. return DAG.getNode(ISD::FP_EXTEND, N->getDebugLoc(), VT, In);
  5874. }
  5875. // fold (fpext (load x)) -> (fpext (fptrunc (extload x)))
  5876. if (ISD::isNON_EXTLoad(N0.getNode()) && N0.hasOneUse() &&
  5877. ((!LegalOperations && !cast<LoadSDNode>(N0)->isVolatile()) ||
  5878. TLI.isLoadExtLegal(ISD::EXTLOAD, N0.getValueType()))) {
  5879. LoadSDNode *LN0 = cast<LoadSDNode>(N0);
  5880. SDValue ExtLoad = DAG.getExtLoad(ISD::EXTLOAD, N->getDebugLoc(), VT,
  5881. LN0->getChain(),
  5882. LN0->getBasePtr(), LN0->getPointerInfo(),
  5883. N0.getValueType(),
  5884. LN0->isVolatile(), LN0->isNonTemporal(),
  5885. LN0->getAlignment());
  5886. CombineTo(N, ExtLoad);
  5887. CombineTo(N0.getNode(),
  5888. DAG.getNode(ISD::FP_ROUND, N0.getDebugLoc(),
  5889. N0.getValueType(), ExtLoad, DAG.getIntPtrConstant(1)),
  5890. ExtLoad.getValue(1));
  5891. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  5892. }
  5893. return SDValue();
  5894. }
  5895. SDValue DAGCombiner::visitFNEG(SDNode *N) {
  5896. SDValue N0 = N->getOperand(0);
  5897. EVT VT = N->getValueType(0);
  5898. if (VT.isVector()) {
  5899. SDValue FoldedVOp = SimplifyVUnaryOp(N);
  5900. if (FoldedVOp.getNode()) return FoldedVOp;
  5901. }
  5902. if (isNegatibleForFree(N0, LegalOperations, DAG.getTargetLoweringInfo(),
  5903. &DAG.getTarget().Options))
  5904. return GetNegatedExpression(N0, DAG, LegalOperations);
  5905. // Transform fneg(bitconvert(x)) -> bitconvert(x^sign) to avoid loading
  5906. // constant pool values.
  5907. if (!TLI.isFNegFree(VT) && N0.getOpcode() == ISD::BITCAST &&
  5908. !VT.isVector() &&
  5909. N0.getNode()->hasOneUse() &&
  5910. N0.getOperand(0).getValueType().isInteger()) {
  5911. SDValue Int = N0.getOperand(0);
  5912. EVT IntVT = Int.getValueType();
  5913. if (IntVT.isInteger() && !IntVT.isVector()) {
  5914. Int = DAG.getNode(ISD::XOR, N0.getDebugLoc(), IntVT, Int,
  5915. DAG.getConstant(APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
  5916. AddToWorkList(Int.getNode());
  5917. return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
  5918. VT, Int);
  5919. }
  5920. }
  5921. // (fneg (fmul c, x)) -> (fmul -c, x)
  5922. if (N0.getOpcode() == ISD::FMUL) {
  5923. ConstantFPSDNode *CFP1 = dyn_cast<ConstantFPSDNode>(N0.getOperand(1));
  5924. if (CFP1) {
  5925. return DAG.getNode(ISD::FMUL, N->getDebugLoc(), VT,
  5926. N0.getOperand(0),
  5927. DAG.getNode(ISD::FNEG, N->getDebugLoc(), VT,
  5928. N0.getOperand(1)));
  5929. }
  5930. }
  5931. return SDValue();
  5932. }
  5933. SDValue DAGCombiner::visitFCEIL(SDNode *N) {
  5934. SDValue N0 = N->getOperand(0);
  5935. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5936. EVT VT = N->getValueType(0);
  5937. // fold (fceil c1) -> fceil(c1)
  5938. if (N0CFP)
  5939. return DAG.getNode(ISD::FCEIL, N->getDebugLoc(), VT, N0);
  5940. return SDValue();
  5941. }
  5942. SDValue DAGCombiner::visitFTRUNC(SDNode *N) {
  5943. SDValue N0 = N->getOperand(0);
  5944. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5945. EVT VT = N->getValueType(0);
  5946. // fold (ftrunc c1) -> ftrunc(c1)
  5947. if (N0CFP)
  5948. return DAG.getNode(ISD::FTRUNC, N->getDebugLoc(), VT, N0);
  5949. return SDValue();
  5950. }
  5951. SDValue DAGCombiner::visitFFLOOR(SDNode *N) {
  5952. SDValue N0 = N->getOperand(0);
  5953. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5954. EVT VT = N->getValueType(0);
  5955. // fold (ffloor c1) -> ffloor(c1)
  5956. if (N0CFP)
  5957. return DAG.getNode(ISD::FFLOOR, N->getDebugLoc(), VT, N0);
  5958. return SDValue();
  5959. }
  5960. SDValue DAGCombiner::visitFABS(SDNode *N) {
  5961. SDValue N0 = N->getOperand(0);
  5962. ConstantFPSDNode *N0CFP = dyn_cast<ConstantFPSDNode>(N0);
  5963. EVT VT = N->getValueType(0);
  5964. if (VT.isVector()) {
  5965. SDValue FoldedVOp = SimplifyVUnaryOp(N);
  5966. if (FoldedVOp.getNode()) return FoldedVOp;
  5967. }
  5968. // fold (fabs c1) -> fabs(c1)
  5969. if (N0CFP)
  5970. return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0);
  5971. // fold (fabs (fabs x)) -> (fabs x)
  5972. if (N0.getOpcode() == ISD::FABS)
  5973. return N->getOperand(0);
  5974. // fold (fabs (fneg x)) -> (fabs x)
  5975. // fold (fabs (fcopysign x, y)) -> (fabs x)
  5976. if (N0.getOpcode() == ISD::FNEG || N0.getOpcode() == ISD::FCOPYSIGN)
  5977. return DAG.getNode(ISD::FABS, N->getDebugLoc(), VT, N0.getOperand(0));
  5978. // Transform fabs(bitconvert(x)) -> bitconvert(x&~sign) to avoid loading
  5979. // constant pool values.
  5980. if (!TLI.isFAbsFree(VT) &&
  5981. N0.getOpcode() == ISD::BITCAST && N0.getNode()->hasOneUse() &&
  5982. N0.getOperand(0).getValueType().isInteger() &&
  5983. !N0.getOperand(0).getValueType().isVector()) {
  5984. SDValue Int = N0.getOperand(0);
  5985. EVT IntVT = Int.getValueType();
  5986. if (IntVT.isInteger() && !IntVT.isVector()) {
  5987. Int = DAG.getNode(ISD::AND, N0.getDebugLoc(), IntVT, Int,
  5988. DAG.getConstant(~APInt::getSignBit(IntVT.getSizeInBits()), IntVT));
  5989. AddToWorkList(Int.getNode());
  5990. return DAG.getNode(ISD::BITCAST, N->getDebugLoc(),
  5991. N->getValueType(0), Int);
  5992. }
  5993. }
  5994. return SDValue();
  5995. }
  5996. SDValue DAGCombiner::visitBRCOND(SDNode *N) {
  5997. SDValue Chain = N->getOperand(0);
  5998. SDValue N1 = N->getOperand(1);
  5999. SDValue N2 = N->getOperand(2);
  6000. // If N is a constant we could fold this into a fallthrough or unconditional
  6001. // branch. However that doesn't happen very often in normal code, because
  6002. // Instcombine/SimplifyCFG should have handled the available opportunities.
  6003. // If we did this folding here, it would be necessary to update the
  6004. // MachineBasicBlock CFG, which is awkward.
  6005. // fold a brcond with a setcc condition into a BR_CC node if BR_CC is legal
  6006. // on the target.
  6007. if (N1.getOpcode() == ISD::SETCC &&
  6008. TLI.isOperationLegalOrCustom(ISD::BR_CC,
  6009. N1.getOperand(0).getValueType())) {
  6010. return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
  6011. Chain, N1.getOperand(2),
  6012. N1.getOperand(0), N1.getOperand(1), N2);
  6013. }
  6014. if ((N1.hasOneUse() && N1.getOpcode() == ISD::SRL) ||
  6015. ((N1.getOpcode() == ISD::TRUNCATE && N1.hasOneUse()) &&
  6016. (N1.getOperand(0).hasOneUse() &&
  6017. N1.getOperand(0).getOpcode() == ISD::SRL))) {
  6018. SDNode *Trunc = 0;
  6019. if (N1.getOpcode() == ISD::TRUNCATE) {
  6020. // Look pass the truncate.
  6021. Trunc = N1.getNode();
  6022. N1 = N1.getOperand(0);
  6023. }
  6024. // Match this pattern so that we can generate simpler code:
  6025. //
  6026. // %a = ...
  6027. // %b = and i32 %a, 2
  6028. // %c = srl i32 %b, 1
  6029. // brcond i32 %c ...
  6030. //
  6031. // into
  6032. //
  6033. // %a = ...
  6034. // %b = and i32 %a, 2
  6035. // %c = setcc eq %b, 0
  6036. // brcond %c ...
  6037. //
  6038. // This applies only when the AND constant value has one bit set and the
  6039. // SRL constant is equal to the log2 of the AND constant. The back-end is
  6040. // smart enough to convert the result into a TEST/JMP sequence.
  6041. SDValue Op0 = N1.getOperand(0);
  6042. SDValue Op1 = N1.getOperand(1);
  6043. if (Op0.getOpcode() == ISD::AND &&
  6044. Op1.getOpcode() == ISD::Constant) {
  6045. SDValue AndOp1 = Op0.getOperand(1);
  6046. if (AndOp1.getOpcode() == ISD::Constant) {
  6047. const APInt &AndConst = cast<ConstantSDNode>(AndOp1)->getAPIntValue();
  6048. if (AndConst.isPowerOf2() &&
  6049. cast<ConstantSDNode>(Op1)->getAPIntValue()==AndConst.logBase2()) {
  6050. SDValue SetCC =
  6051. DAG.getSetCC(N->getDebugLoc(),
  6052. getSetCCResultType(Op0.getValueType()),
  6053. Op0, DAG.getConstant(0, Op0.getValueType()),
  6054. ISD::SETNE);
  6055. SDValue NewBRCond = DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
  6056. MVT::Other, Chain, SetCC, N2);
  6057. // Don't add the new BRCond into the worklist or else SimplifySelectCC
  6058. // will convert it back to (X & C1) >> C2.
  6059. CombineTo(N, NewBRCond, false);
  6060. // Truncate is dead.
  6061. if (Trunc) {
  6062. removeFromWorkList(Trunc);
  6063. DAG.DeleteNode(Trunc);
  6064. }
  6065. // Replace the uses of SRL with SETCC
  6066. WorkListRemover DeadNodes(*this);
  6067. DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
  6068. removeFromWorkList(N1.getNode());
  6069. DAG.DeleteNode(N1.getNode());
  6070. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  6071. }
  6072. }
  6073. }
  6074. if (Trunc)
  6075. // Restore N1 if the above transformation doesn't match.
  6076. N1 = N->getOperand(1);
  6077. }
  6078. // Transform br(xor(x, y)) -> br(x != y)
  6079. // Transform br(xor(xor(x,y), 1)) -> br (x == y)
  6080. if (N1.hasOneUse() && N1.getOpcode() == ISD::XOR) {
  6081. SDNode *TheXor = N1.getNode();
  6082. SDValue Op0 = TheXor->getOperand(0);
  6083. SDValue Op1 = TheXor->getOperand(1);
  6084. if (Op0.getOpcode() == Op1.getOpcode()) {
  6085. // Avoid missing important xor optimizations.
  6086. SDValue Tmp = visitXOR(TheXor);
  6087. if (Tmp.getNode()) {
  6088. if (Tmp.getNode() != TheXor) {
  6089. DEBUG(dbgs() << "\nReplacing.8 ";
  6090. TheXor->dump(&DAG);
  6091. dbgs() << "\nWith: ";
  6092. Tmp.getNode()->dump(&DAG);
  6093. dbgs() << '\n');
  6094. WorkListRemover DeadNodes(*this);
  6095. DAG.ReplaceAllUsesOfValueWith(N1, Tmp);
  6096. removeFromWorkList(TheXor);
  6097. DAG.DeleteNode(TheXor);
  6098. return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
  6099. MVT::Other, Chain, Tmp, N2);
  6100. }
  6101. // visitXOR has changed XOR's operands or replaced the XOR completely,
  6102. // bail out.
  6103. return SDValue(N, 0);
  6104. }
  6105. }
  6106. if (Op0.getOpcode() != ISD::SETCC && Op1.getOpcode() != ISD::SETCC) {
  6107. bool Equal = false;
  6108. if (ConstantSDNode *RHSCI = dyn_cast<ConstantSDNode>(Op0))
  6109. if (RHSCI->getAPIntValue() == 1 && Op0.hasOneUse() &&
  6110. Op0.getOpcode() == ISD::XOR) {
  6111. TheXor = Op0.getNode();
  6112. Equal = true;
  6113. }
  6114. EVT SetCCVT = N1.getValueType();
  6115. if (LegalTypes)
  6116. SetCCVT = getSetCCResultType(SetCCVT);
  6117. SDValue SetCC = DAG.getSetCC(TheXor->getDebugLoc(),
  6118. SetCCVT,
  6119. Op0, Op1,
  6120. Equal ? ISD::SETEQ : ISD::SETNE);
  6121. // Replace the uses of XOR with SETCC
  6122. WorkListRemover DeadNodes(*this);
  6123. DAG.ReplaceAllUsesOfValueWith(N1, SetCC);
  6124. removeFromWorkList(N1.getNode());
  6125. DAG.DeleteNode(N1.getNode());
  6126. return DAG.getNode(ISD::BRCOND, N->getDebugLoc(),
  6127. MVT::Other, Chain, SetCC, N2);
  6128. }
  6129. }
  6130. return SDValue();
  6131. }
  6132. // Operand List for BR_CC: Chain, CondCC, CondLHS, CondRHS, DestBB.
  6133. //
  6134. SDValue DAGCombiner::visitBR_CC(SDNode *N) {
  6135. CondCodeSDNode *CC = cast<CondCodeSDNode>(N->getOperand(1));
  6136. SDValue CondLHS = N->getOperand(2), CondRHS = N->getOperand(3);
  6137. // If N is a constant we could fold this into a fallthrough or unconditional
  6138. // branch. However that doesn't happen very often in normal code, because
  6139. // Instcombine/SimplifyCFG should have handled the available opportunities.
  6140. // If we did this folding here, it would be necessary to update the
  6141. // MachineBasicBlock CFG, which is awkward.
  6142. // Use SimplifySetCC to simplify SETCC's.
  6143. SDValue Simp = SimplifySetCC(getSetCCResultType(CondLHS.getValueType()),
  6144. CondLHS, CondRHS, CC->get(), N->getDebugLoc(),
  6145. false);
  6146. if (Simp.getNode()) AddToWorkList(Simp.getNode());
  6147. // fold to a simpler setcc
  6148. if (Simp.getNode() && Simp.getOpcode() == ISD::SETCC)
  6149. return DAG.getNode(ISD::BR_CC, N->getDebugLoc(), MVT::Other,
  6150. N->getOperand(0), Simp.getOperand(2),
  6151. Simp.getOperand(0), Simp.getOperand(1),
  6152. N->getOperand(4));
  6153. return SDValue();
  6154. }
  6155. /// canFoldInAddressingMode - Return true if 'Use' is a load or a store that
  6156. /// uses N as its base pointer and that N may be folded in the load / store
  6157. /// addressing mode.
  6158. static bool canFoldInAddressingMode(SDNode *N, SDNode *Use,
  6159. SelectionDAG &DAG,
  6160. const TargetLowering &TLI) {
  6161. EVT VT;
  6162. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(Use)) {
  6163. if (LD->isIndexed() || LD->getBasePtr().getNode() != N)
  6164. return false;
  6165. VT = Use->getValueType(0);
  6166. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(Use)) {
  6167. if (ST->isIndexed() || ST->getBasePtr().getNode() != N)
  6168. return false;
  6169. VT = ST->getValue().getValueType();
  6170. } else
  6171. return false;
  6172. TargetLowering::AddrMode AM;
  6173. if (N->getOpcode() == ISD::ADD) {
  6174. ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
  6175. if (Offset)
  6176. // [reg +/- imm]
  6177. AM.BaseOffs = Offset->getSExtValue();
  6178. else
  6179. // [reg +/- reg]
  6180. AM.Scale = 1;
  6181. } else if (N->getOpcode() == ISD::SUB) {
  6182. ConstantSDNode *Offset = dyn_cast<ConstantSDNode>(N->getOperand(1));
  6183. if (Offset)
  6184. // [reg +/- imm]
  6185. AM.BaseOffs = -Offset->getSExtValue();
  6186. else
  6187. // [reg +/- reg]
  6188. AM.Scale = 1;
  6189. } else
  6190. return false;
  6191. return TLI.isLegalAddressingMode(AM, VT.getTypeForEVT(*DAG.getContext()));
  6192. }
  6193. /// CombineToPreIndexedLoadStore - Try turning a load / store into a
  6194. /// pre-indexed load / store when the base pointer is an add or subtract
  6195. /// and it has other uses besides the load / store. After the
  6196. /// transformation, the new indexed load / store has effectively folded
  6197. /// the add / subtract in and all of its other uses are redirected to the
  6198. /// new load / store.
  6199. bool DAGCombiner::CombineToPreIndexedLoadStore(SDNode *N) {
  6200. if (Level < AfterLegalizeDAG)
  6201. return false;
  6202. bool isLoad = true;
  6203. SDValue Ptr;
  6204. EVT VT;
  6205. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
  6206. if (LD->isIndexed())
  6207. return false;
  6208. VT = LD->getMemoryVT();
  6209. if (!TLI.isIndexedLoadLegal(ISD::PRE_INC, VT) &&
  6210. !TLI.isIndexedLoadLegal(ISD::PRE_DEC, VT))
  6211. return false;
  6212. Ptr = LD->getBasePtr();
  6213. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
  6214. if (ST->isIndexed())
  6215. return false;
  6216. VT = ST->getMemoryVT();
  6217. if (!TLI.isIndexedStoreLegal(ISD::PRE_INC, VT) &&
  6218. !TLI.isIndexedStoreLegal(ISD::PRE_DEC, VT))
  6219. return false;
  6220. Ptr = ST->getBasePtr();
  6221. isLoad = false;
  6222. } else {
  6223. return false;
  6224. }
  6225. // If the pointer is not an add/sub, or if it doesn't have multiple uses, bail
  6226. // out. There is no reason to make this a preinc/predec.
  6227. if ((Ptr.getOpcode() != ISD::ADD && Ptr.getOpcode() != ISD::SUB) ||
  6228. Ptr.getNode()->hasOneUse())
  6229. return false;
  6230. // Ask the target to do addressing mode selection.
  6231. SDValue BasePtr;
  6232. SDValue Offset;
  6233. ISD::MemIndexedMode AM = ISD::UNINDEXED;
  6234. if (!TLI.getPreIndexedAddressParts(N, BasePtr, Offset, AM, DAG))
  6235. return false;
  6236. // Backends without true r+i pre-indexed forms may need to pass a
  6237. // constant base with a variable offset so that constant coercion
  6238. // will work with the patterns in canonical form.
  6239. bool Swapped = false;
  6240. if (isa<ConstantSDNode>(BasePtr)) {
  6241. std::swap(BasePtr, Offset);
  6242. Swapped = true;
  6243. }
  6244. // Don't create a indexed load / store with zero offset.
  6245. if (isa<ConstantSDNode>(Offset) &&
  6246. cast<ConstantSDNode>(Offset)->isNullValue())
  6247. return false;
  6248. // Try turning it into a pre-indexed load / store except when:
  6249. // 1) The new base ptr is a frame index.
  6250. // 2) If N is a store and the new base ptr is either the same as or is a
  6251. // predecessor of the value being stored.
  6252. // 3) Another use of old base ptr is a predecessor of N. If ptr is folded
  6253. // that would create a cycle.
  6254. // 4) All uses are load / store ops that use it as old base ptr.
  6255. // Check #1. Preinc'ing a frame index would require copying the stack pointer
  6256. // (plus the implicit offset) to a register to preinc anyway.
  6257. if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
  6258. return false;
  6259. // Check #2.
  6260. if (!isLoad) {
  6261. SDValue Val = cast<StoreSDNode>(N)->getValue();
  6262. if (Val == BasePtr || BasePtr.getNode()->isPredecessorOf(Val.getNode()))
  6263. return false;
  6264. }
  6265. // If the offset is a constant, there may be other adds of constants that
  6266. // can be folded with this one. We should do this to avoid having to keep
  6267. // a copy of the original base pointer.
  6268. SmallVector<SDNode *, 16> OtherUses;
  6269. if (isa<ConstantSDNode>(Offset))
  6270. for (SDNode::use_iterator I = BasePtr.getNode()->use_begin(),
  6271. E = BasePtr.getNode()->use_end(); I != E; ++I) {
  6272. SDNode *Use = *I;
  6273. if (Use == Ptr.getNode())
  6274. continue;
  6275. if (Use->isPredecessorOf(N))
  6276. continue;
  6277. if (Use->getOpcode() != ISD::ADD && Use->getOpcode() != ISD::SUB) {
  6278. OtherUses.clear();
  6279. break;
  6280. }
  6281. SDValue Op0 = Use->getOperand(0), Op1 = Use->getOperand(1);
  6282. if (Op1.getNode() == BasePtr.getNode())
  6283. std::swap(Op0, Op1);
  6284. assert(Op0.getNode() == BasePtr.getNode() &&
  6285. "Use of ADD/SUB but not an operand");
  6286. if (!isa<ConstantSDNode>(Op1)) {
  6287. OtherUses.clear();
  6288. break;
  6289. }
  6290. // FIXME: In some cases, we can be smarter about this.
  6291. if (Op1.getValueType() != Offset.getValueType()) {
  6292. OtherUses.clear();
  6293. break;
  6294. }
  6295. OtherUses.push_back(Use);
  6296. }
  6297. if (Swapped)
  6298. std::swap(BasePtr, Offset);
  6299. // Now check for #3 and #4.
  6300. bool RealUse = false;
  6301. // Caches for hasPredecessorHelper
  6302. SmallPtrSet<const SDNode *, 32> Visited;
  6303. SmallVector<const SDNode *, 16> Worklist;
  6304. for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
  6305. E = Ptr.getNode()->use_end(); I != E; ++I) {
  6306. SDNode *Use = *I;
  6307. if (Use == N)
  6308. continue;
  6309. if (N->hasPredecessorHelper(Use, Visited, Worklist))
  6310. return false;
  6311. // If Ptr may be folded in addressing mode of other use, then it's
  6312. // not profitable to do this transformation.
  6313. if (!canFoldInAddressingMode(Ptr.getNode(), Use, DAG, TLI))
  6314. RealUse = true;
  6315. }
  6316. if (!RealUse)
  6317. return false;
  6318. SDValue Result;
  6319. if (isLoad)
  6320. Result = DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
  6321. BasePtr, Offset, AM);
  6322. else
  6323. Result = DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
  6324. BasePtr, Offset, AM);
  6325. ++PreIndexedNodes;
  6326. ++NodesCombined;
  6327. DEBUG(dbgs() << "\nReplacing.4 ";
  6328. N->dump(&DAG);
  6329. dbgs() << "\nWith: ";
  6330. Result.getNode()->dump(&DAG);
  6331. dbgs() << '\n');
  6332. WorkListRemover DeadNodes(*this);
  6333. if (isLoad) {
  6334. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
  6335. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
  6336. } else {
  6337. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
  6338. }
  6339. // Finally, since the node is now dead, remove it from the graph.
  6340. DAG.DeleteNode(N);
  6341. if (Swapped)
  6342. std::swap(BasePtr, Offset);
  6343. // Replace other uses of BasePtr that can be updated to use Ptr
  6344. for (unsigned i = 0, e = OtherUses.size(); i != e; ++i) {
  6345. unsigned OffsetIdx = 1;
  6346. if (OtherUses[i]->getOperand(OffsetIdx).getNode() == BasePtr.getNode())
  6347. OffsetIdx = 0;
  6348. assert(OtherUses[i]->getOperand(!OffsetIdx).getNode() ==
  6349. BasePtr.getNode() && "Expected BasePtr operand");
  6350. // We need to replace ptr0 in the following expression:
  6351. // x0 * offset0 + y0 * ptr0 = t0
  6352. // knowing that
  6353. // x1 * offset1 + y1 * ptr0 = t1 (the indexed load/store)
  6354. //
  6355. // where x0, x1, y0 and y1 in {-1, 1} are given by the types of the
  6356. // indexed load/store and the expresion that needs to be re-written.
  6357. //
  6358. // Therefore, we have:
  6359. // t0 = (x0 * offset0 - x1 * y0 * y1 *offset1) + (y0 * y1) * t1
  6360. ConstantSDNode *CN =
  6361. cast<ConstantSDNode>(OtherUses[i]->getOperand(OffsetIdx));
  6362. int X0, X1, Y0, Y1;
  6363. APInt Offset0 = CN->getAPIntValue();
  6364. APInt Offset1 = cast<ConstantSDNode>(Offset)->getAPIntValue();
  6365. X0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 1) ? -1 : 1;
  6366. Y0 = (OtherUses[i]->getOpcode() == ISD::SUB && OffsetIdx == 0) ? -1 : 1;
  6367. X1 = (AM == ISD::PRE_DEC && !Swapped) ? -1 : 1;
  6368. Y1 = (AM == ISD::PRE_DEC && Swapped) ? -1 : 1;
  6369. unsigned Opcode = (Y0 * Y1 < 0) ? ISD::SUB : ISD::ADD;
  6370. APInt CNV = Offset0;
  6371. if (X0 < 0) CNV = -CNV;
  6372. if (X1 * Y0 * Y1 < 0) CNV = CNV + Offset1;
  6373. else CNV = CNV - Offset1;
  6374. // We can now generate the new expression.
  6375. SDValue NewOp1 = DAG.getConstant(CNV, CN->getValueType(0));
  6376. SDValue NewOp2 = Result.getValue(isLoad ? 1 : 0);
  6377. SDValue NewUse = DAG.getNode(Opcode,
  6378. OtherUses[i]->getDebugLoc(),
  6379. OtherUses[i]->getValueType(0), NewOp1, NewOp2);
  6380. DAG.ReplaceAllUsesOfValueWith(SDValue(OtherUses[i], 0), NewUse);
  6381. removeFromWorkList(OtherUses[i]);
  6382. DAG.DeleteNode(OtherUses[i]);
  6383. }
  6384. // Replace the uses of Ptr with uses of the updated base value.
  6385. DAG.ReplaceAllUsesOfValueWith(Ptr, Result.getValue(isLoad ? 1 : 0));
  6386. removeFromWorkList(Ptr.getNode());
  6387. DAG.DeleteNode(Ptr.getNode());
  6388. return true;
  6389. }
  6390. /// CombineToPostIndexedLoadStore - Try to combine a load / store with a
  6391. /// add / sub of the base pointer node into a post-indexed load / store.
  6392. /// The transformation folded the add / subtract into the new indexed
  6393. /// load / store effectively and all of its uses are redirected to the
  6394. /// new load / store.
  6395. bool DAGCombiner::CombineToPostIndexedLoadStore(SDNode *N) {
  6396. if (Level < AfterLegalizeDAG)
  6397. return false;
  6398. bool isLoad = true;
  6399. SDValue Ptr;
  6400. EVT VT;
  6401. if (LoadSDNode *LD = dyn_cast<LoadSDNode>(N)) {
  6402. if (LD->isIndexed())
  6403. return false;
  6404. VT = LD->getMemoryVT();
  6405. if (!TLI.isIndexedLoadLegal(ISD::POST_INC, VT) &&
  6406. !TLI.isIndexedLoadLegal(ISD::POST_DEC, VT))
  6407. return false;
  6408. Ptr = LD->getBasePtr();
  6409. } else if (StoreSDNode *ST = dyn_cast<StoreSDNode>(N)) {
  6410. if (ST->isIndexed())
  6411. return false;
  6412. VT = ST->getMemoryVT();
  6413. if (!TLI.isIndexedStoreLegal(ISD::POST_INC, VT) &&
  6414. !TLI.isIndexedStoreLegal(ISD::POST_DEC, VT))
  6415. return false;
  6416. Ptr = ST->getBasePtr();
  6417. isLoad = false;
  6418. } else {
  6419. return false;
  6420. }
  6421. if (Ptr.getNode()->hasOneUse())
  6422. return false;
  6423. for (SDNode::use_iterator I = Ptr.getNode()->use_begin(),
  6424. E = Ptr.getNode()->use_end(); I != E; ++I) {
  6425. SDNode *Op = *I;
  6426. if (Op == N ||
  6427. (Op->getOpcode() != ISD::ADD && Op->getOpcode() != ISD::SUB))
  6428. continue;
  6429. SDValue BasePtr;
  6430. SDValue Offset;
  6431. ISD::MemIndexedMode AM = ISD::UNINDEXED;
  6432. if (TLI.getPostIndexedAddressParts(N, Op, BasePtr, Offset, AM, DAG)) {
  6433. // Don't create a indexed load / store with zero offset.
  6434. if (isa<ConstantSDNode>(Offset) &&
  6435. cast<ConstantSDNode>(Offset)->isNullValue())
  6436. continue;
  6437. // Try turning it into a post-indexed load / store except when
  6438. // 1) All uses are load / store ops that use it as base ptr (and
  6439. // it may be folded as addressing mmode).
  6440. // 2) Op must be independent of N, i.e. Op is neither a predecessor
  6441. // nor a successor of N. Otherwise, if Op is folded that would
  6442. // create a cycle.
  6443. if (isa<FrameIndexSDNode>(BasePtr) || isa<RegisterSDNode>(BasePtr))
  6444. continue;
  6445. // Check for #1.
  6446. bool TryNext = false;
  6447. for (SDNode::use_iterator II = BasePtr.getNode()->use_begin(),
  6448. EE = BasePtr.getNode()->use_end(); II != EE; ++II) {
  6449. SDNode *Use = *II;
  6450. if (Use == Ptr.getNode())
  6451. continue;
  6452. // If all the uses are load / store addresses, then don't do the
  6453. // transformation.
  6454. if (Use->getOpcode() == ISD::ADD || Use->getOpcode() == ISD::SUB){
  6455. bool RealUse = false;
  6456. for (SDNode::use_iterator III = Use->use_begin(),
  6457. EEE = Use->use_end(); III != EEE; ++III) {
  6458. SDNode *UseUse = *III;
  6459. if (!canFoldInAddressingMode(Use, UseUse, DAG, TLI))
  6460. RealUse = true;
  6461. }
  6462. if (!RealUse) {
  6463. TryNext = true;
  6464. break;
  6465. }
  6466. }
  6467. }
  6468. if (TryNext)
  6469. continue;
  6470. // Check for #2
  6471. if (!Op->isPredecessorOf(N) && !N->isPredecessorOf(Op)) {
  6472. SDValue Result = isLoad
  6473. ? DAG.getIndexedLoad(SDValue(N,0), N->getDebugLoc(),
  6474. BasePtr, Offset, AM)
  6475. : DAG.getIndexedStore(SDValue(N,0), N->getDebugLoc(),
  6476. BasePtr, Offset, AM);
  6477. ++PostIndexedNodes;
  6478. ++NodesCombined;
  6479. DEBUG(dbgs() << "\nReplacing.5 ";
  6480. N->dump(&DAG);
  6481. dbgs() << "\nWith: ";
  6482. Result.getNode()->dump(&DAG);
  6483. dbgs() << '\n');
  6484. WorkListRemover DeadNodes(*this);
  6485. if (isLoad) {
  6486. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(0));
  6487. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Result.getValue(2));
  6488. } else {
  6489. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Result.getValue(1));
  6490. }
  6491. // Finally, since the node is now dead, remove it from the graph.
  6492. DAG.DeleteNode(N);
  6493. // Replace the uses of Use with uses of the updated base value.
  6494. DAG.ReplaceAllUsesOfValueWith(SDValue(Op, 0),
  6495. Result.getValue(isLoad ? 1 : 0));
  6496. removeFromWorkList(Op);
  6497. DAG.DeleteNode(Op);
  6498. return true;
  6499. }
  6500. }
  6501. }
  6502. return false;
  6503. }
  6504. SDValue DAGCombiner::visitLOAD(SDNode *N) {
  6505. LoadSDNode *LD = cast<LoadSDNode>(N);
  6506. SDValue Chain = LD->getChain();
  6507. SDValue Ptr = LD->getBasePtr();
  6508. // If load is not volatile and there are no uses of the loaded value (and
  6509. // the updated indexed value in case of indexed loads), change uses of the
  6510. // chain value into uses of the chain input (i.e. delete the dead load).
  6511. if (!LD->isVolatile()) {
  6512. if (N->getValueType(1) == MVT::Other) {
  6513. // Unindexed loads.
  6514. if (!N->hasAnyUseOfValue(0)) {
  6515. // It's not safe to use the two value CombineTo variant here. e.g.
  6516. // v1, chain2 = load chain1, loc
  6517. // v2, chain3 = load chain2, loc
  6518. // v3 = add v2, c
  6519. // Now we replace use of chain2 with chain1. This makes the second load
  6520. // isomorphic to the one we are deleting, and thus makes this load live.
  6521. DEBUG(dbgs() << "\nReplacing.6 ";
  6522. N->dump(&DAG);
  6523. dbgs() << "\nWith chain: ";
  6524. Chain.getNode()->dump(&DAG);
  6525. dbgs() << "\n");
  6526. WorkListRemover DeadNodes(*this);
  6527. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1), Chain);
  6528. if (N->use_empty()) {
  6529. removeFromWorkList(N);
  6530. DAG.DeleteNode(N);
  6531. }
  6532. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  6533. }
  6534. } else {
  6535. // Indexed loads.
  6536. assert(N->getValueType(2) == MVT::Other && "Malformed indexed loads?");
  6537. if (!N->hasAnyUseOfValue(0) && !N->hasAnyUseOfValue(1)) {
  6538. SDValue Undef = DAG.getUNDEF(N->getValueType(0));
  6539. DEBUG(dbgs() << "\nReplacing.7 ";
  6540. N->dump(&DAG);
  6541. dbgs() << "\nWith: ";
  6542. Undef.getNode()->dump(&DAG);
  6543. dbgs() << " and 2 other values\n");
  6544. WorkListRemover DeadNodes(*this);
  6545. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 0), Undef);
  6546. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 1),
  6547. DAG.getUNDEF(N->getValueType(1)));
  6548. DAG.ReplaceAllUsesOfValueWith(SDValue(N, 2), Chain);
  6549. removeFromWorkList(N);
  6550. DAG.DeleteNode(N);
  6551. return SDValue(N, 0); // Return N so it doesn't get rechecked!
  6552. }
  6553. }
  6554. }
  6555. // If this load is directly stored, replace the load value with the stored
  6556. // value.
  6557. // TODO: Handle store large -> read small portion.
  6558. // TODO: Handle TRUNCSTORE/LOADEXT
  6559. if (ISD::isNormalLoad(N) && !LD->isVolatile()) {
  6560. if (ISD::isNON_TRUNCStore(Chain.getNode())) {
  6561. StoreSDNode *PrevST = cast<StoreSDNode>(Chain);
  6562. if (PrevST->getBasePtr() == Ptr &&
  6563. PrevST->getValue().getValueType() == N->getValueType(0))
  6564. return CombineTo(N, Chain.getOperand(1), Chain);
  6565. }
  6566. }
  6567. // Try to infer better alignment information than the load already has.
  6568. if (OptLevel != CodeGenOpt::None && LD->isUnindexed()) {
  6569. if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
  6570. if (Align > LD->getMemOperand()->getBaseAlignment()) {
  6571. SDValue NewLoad =
  6572. DAG.getExtLoad(LD->getExtensionType(), N->getDebugLoc(),
  6573. LD->getValueType(0),
  6574. Chain, Ptr, LD->getPointerInfo(),
  6575. LD->getMemoryVT(),
  6576. LD->isVolatile(), LD->isNonTemporal(), Align);
  6577. return CombineTo(N, NewLoad, SDValue(NewLoad.getNode(), 1), true);
  6578. }
  6579. }
  6580. }
  6581. if (CombinerAA) {
  6582. // Walk up chain skipping non-aliasing memory nodes.
  6583. SDValue BetterChain = FindBetterChain(N, Chain);
  6584. // If there is a better chain.
  6585. if (Chain != BetterChain) {
  6586. SDValue ReplLoad;
  6587. // Replace the chain to void dependency.
  6588. if (LD->getExtensionType() == ISD::NON_EXTLOAD) {
  6589. ReplLoad = DAG.getLoad(N->getValueType(0), LD->getDebugLoc(),
  6590. BetterChain, Ptr, LD->getPointerInfo(),
  6591. LD->isVolatile(), LD->isNonTemporal(),
  6592. LD->isInvariant(), LD->getAlignment());
  6593. } else {
  6594. ReplLoad = DAG.getExtLoad(LD->getExtensionType(), LD->getDebugLoc(),
  6595. LD->getValueType(0),
  6596. BetterChain, Ptr, LD->getPointerInfo(),
  6597. LD->getMemoryVT(),
  6598. LD->isVolatile(),
  6599. LD->isNonTemporal(),
  6600. LD->getAlignment());
  6601. }
  6602. // Create token factor to keep old chain connected.
  6603. SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
  6604. MVT::Other, Chain, ReplLoad.getValue(1));
  6605. // Make sure the new and old chains are cleaned up.
  6606. AddToWorkList(Token.getNode());
  6607. // Replace uses with load result and token factor. Don't add users
  6608. // to work list.
  6609. return CombineTo(N, ReplLoad.getValue(0), Token, false);
  6610. }
  6611. }
  6612. // Try transforming N to an indexed load.
  6613. if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
  6614. return SDValue(N, 0);
  6615. return SDValue();
  6616. }
  6617. /// CheckForMaskedLoad - Check to see if V is (and load (ptr), imm), where the
  6618. /// load is having specific bytes cleared out. If so, return the byte size
  6619. /// being masked out and the shift amount.
  6620. static std::pair<unsigned, unsigned>
  6621. CheckForMaskedLoad(SDValue V, SDValue Ptr, SDValue Chain) {
  6622. std::pair<unsigned, unsigned> Result(0, 0);
  6623. // Check for the structure we're looking for.
  6624. if (V->getOpcode() != ISD::AND ||
  6625. !isa<ConstantSDNode>(V->getOperand(1)) ||
  6626. !ISD::isNormalLoad(V->getOperand(0).getNode()))
  6627. return Result;
  6628. // Check the chain and pointer.
  6629. LoadSDNode *LD = cast<LoadSDNode>(V->getOperand(0));
  6630. if (LD->getBasePtr() != Ptr) return Result; // Not from same pointer.
  6631. // The store should be chained directly to the load or be an operand of a
  6632. // tokenfactor.
  6633. if (LD == Chain.getNode())
  6634. ; // ok.
  6635. else if (Chain->getOpcode() != ISD::TokenFactor)
  6636. return Result; // Fail.
  6637. else {
  6638. bool isOk = false;
  6639. for (unsigned i = 0, e = Chain->getNumOperands(); i != e; ++i)
  6640. if (Chain->getOperand(i).getNode() == LD) {
  6641. isOk = true;
  6642. break;
  6643. }
  6644. if (!isOk) return Result;
  6645. }
  6646. // This only handles simple types.
  6647. if (V.getValueType() != MVT::i16 &&
  6648. V.getValueType() != MVT::i32 &&
  6649. V.getValueType() != MVT::i64)
  6650. return Result;
  6651. // Check the constant mask. Invert it so that the bits being masked out are
  6652. // 0 and the bits being kept are 1. Use getSExtValue so that leading bits
  6653. // follow the sign bit for uniformity.
  6654. uint64_t NotMask = ~cast<ConstantSDNode>(V->getOperand(1))->getSExtValue();
  6655. unsigned NotMaskLZ = CountLeadingZeros_64(NotMask);
  6656. if (NotMaskLZ & 7) return Result; // Must be multiple of a byte.
  6657. unsigned NotMaskTZ = CountTrailingZeros_64(NotMask);
  6658. if (NotMaskTZ & 7) return Result; // Must be multiple of a byte.
  6659. if (NotMaskLZ == 64) return Result; // All zero mask.
  6660. // See if we have a continuous run of bits. If so, we have 0*1+0*
  6661. if (CountTrailingOnes_64(NotMask >> NotMaskTZ)+NotMaskTZ+NotMaskLZ != 64)
  6662. return Result;
  6663. // Adjust NotMaskLZ down to be from the actual size of the int instead of i64.
  6664. if (V.getValueType() != MVT::i64 && NotMaskLZ)
  6665. NotMaskLZ -= 64-V.getValueSizeInBits();
  6666. unsigned MaskedBytes = (V.getValueSizeInBits()-NotMaskLZ-NotMaskTZ)/8;
  6667. switch (MaskedBytes) {
  6668. case 1:
  6669. case 2:
  6670. case 4: break;
  6671. default: return Result; // All one mask, or 5-byte mask.
  6672. }
  6673. // Verify that the first bit starts at a multiple of mask so that the access
  6674. // is aligned the same as the access width.
  6675. if (NotMaskTZ && NotMaskTZ/8 % MaskedBytes) return Result;
  6676. Result.first = MaskedBytes;
  6677. Result.second = NotMaskTZ/8;
  6678. return Result;
  6679. }
  6680. /// ShrinkLoadReplaceStoreWithStore - Check to see if IVal is something that
  6681. /// provides a value as specified by MaskInfo. If so, replace the specified
  6682. /// store with a narrower store of truncated IVal.
  6683. static SDNode *
  6684. ShrinkLoadReplaceStoreWithStore(const std::pair<unsigned, unsigned> &MaskInfo,
  6685. SDValue IVal, StoreSDNode *St,
  6686. DAGCombiner *DC) {
  6687. unsigned NumBytes = MaskInfo.first;
  6688. unsigned ByteShift = MaskInfo.second;
  6689. SelectionDAG &DAG = DC->getDAG();
  6690. // Check to see if IVal is all zeros in the part being masked in by the 'or'
  6691. // that uses this. If not, this is not a replacement.
  6692. APInt Mask = ~APInt::getBitsSet(IVal.getValueSizeInBits(),
  6693. ByteShift*8, (ByteShift+NumBytes)*8);
  6694. if (!DAG.MaskedValueIsZero(IVal, Mask)) return 0;
  6695. // Check that it is legal on the target to do this. It is legal if the new
  6696. // VT we're shrinking to (i8/i16/i32) is legal or we're still before type
  6697. // legalization.
  6698. MVT VT = MVT::getIntegerVT(NumBytes*8);
  6699. if (!DC->isTypeLegal(VT))
  6700. return 0;
  6701. // Okay, we can do this! Replace the 'St' store with a store of IVal that is
  6702. // shifted by ByteShift and truncated down to NumBytes.
  6703. if (ByteShift)
  6704. IVal = DAG.getNode(ISD::SRL, IVal->getDebugLoc(), IVal.getValueType(), IVal,
  6705. DAG.getConstant(ByteShift*8,
  6706. DC->getShiftAmountTy(IVal.getValueType())));
  6707. // Figure out the offset for the store and the alignment of the access.
  6708. unsigned StOffset;
  6709. unsigned NewAlign = St->getAlignment();
  6710. if (DAG.getTargetLoweringInfo().isLittleEndian())
  6711. StOffset = ByteShift;
  6712. else
  6713. StOffset = IVal.getValueType().getStoreSize() - ByteShift - NumBytes;
  6714. SDValue Ptr = St->getBasePtr();
  6715. if (StOffset) {
  6716. Ptr = DAG.getNode(ISD::ADD, IVal->getDebugLoc(), Ptr.getValueType(),
  6717. Ptr, DAG.getConstant(StOffset, Ptr.getValueType()));
  6718. NewAlign = MinAlign(NewAlign, StOffset);
  6719. }
  6720. // Truncate down to the new size.
  6721. IVal = DAG.getNode(ISD::TRUNCATE, IVal->getDebugLoc(), VT, IVal);
  6722. ++OpsNarrowed;
  6723. return DAG.getStore(St->getChain(), St->getDebugLoc(), IVal, Ptr,
  6724. St->getPointerInfo().getWithOffset(StOffset),
  6725. false, false, NewAlign).getNode();
  6726. }
  6727. /// ReduceLoadOpStoreWidth - Look for sequence of load / op / store where op is
  6728. /// one of 'or', 'xor', and 'and' of immediates. If 'op' is only touching some
  6729. /// of the loaded bits, try narrowing the load and store if it would end up
  6730. /// being a win for performance or code size.
  6731. SDValue DAGCombiner::ReduceLoadOpStoreWidth(SDNode *N) {
  6732. StoreSDNode *ST = cast<StoreSDNode>(N);
  6733. if (ST->isVolatile())
  6734. return SDValue();
  6735. SDValue Chain = ST->getChain();
  6736. SDValue Value = ST->getValue();
  6737. SDValue Ptr = ST->getBasePtr();
  6738. EVT VT = Value.getValueType();
  6739. if (ST->isTruncatingStore() || VT.isVector() || !Value.hasOneUse())
  6740. return SDValue();
  6741. unsigned Opc = Value.getOpcode();
  6742. // If this is "store (or X, Y), P" and X is "(and (load P), cst)", where cst
  6743. // is a byte mask indicating a consecutive number of bytes, check to see if
  6744. // Y is known to provide just those bytes. If so, we try to replace the
  6745. // load + replace + store sequence with a single (narrower) store, which makes
  6746. // the load dead.
  6747. if (Opc == ISD::OR) {
  6748. std::pair<unsigned, unsigned> MaskedLoad;
  6749. MaskedLoad = CheckForMaskedLoad(Value.getOperand(0), Ptr, Chain);
  6750. if (MaskedLoad.first)
  6751. if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
  6752. Value.getOperand(1), ST,this))
  6753. return SDValue(NewST, 0);
  6754. // Or is commutative, so try swapping X and Y.
  6755. MaskedLoad = CheckForMaskedLoad(Value.getOperand(1), Ptr, Chain);
  6756. if (MaskedLoad.first)
  6757. if (SDNode *NewST = ShrinkLoadReplaceStoreWithStore(MaskedLoad,
  6758. Value.getOperand(0), ST,this))
  6759. return SDValue(NewST, 0);
  6760. }
  6761. if ((Opc != ISD::OR && Opc != ISD::XOR && Opc != ISD::AND) ||
  6762. Value.getOperand(1).getOpcode() != ISD::Constant)
  6763. return SDValue();
  6764. SDValue N0 = Value.getOperand(0);
  6765. if (ISD::isNormalLoad(N0.getNode()) && N0.hasOneUse() &&
  6766. Chain == SDValue(N0.getNode(), 1)) {
  6767. LoadSDNode *LD = cast<LoadSDNode>(N0);
  6768. if (LD->getBasePtr() != Ptr ||
  6769. LD->getPointerInfo().getAddrSpace() !=
  6770. ST->getPointerInfo().getAddrSpace())
  6771. return SDValue();
  6772. // Find the type to narrow it the load / op / store to.
  6773. SDValue N1 = Value.getOperand(1);
  6774. unsigned BitWidth = N1.getValueSizeInBits();
  6775. APInt Imm = cast<ConstantSDNode>(N1)->getAPIntValue();
  6776. if (Opc == ISD::AND)
  6777. Imm ^= APInt::getAllOnesValue(BitWidth);
  6778. if (Imm == 0 || Imm.isAllOnesValue())
  6779. return SDValue();
  6780. unsigned ShAmt = Imm.countTrailingZeros();
  6781. unsigned MSB = BitWidth - Imm.countLeadingZeros() - 1;
  6782. unsigned NewBW = NextPowerOf2(MSB - ShAmt);
  6783. EVT NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
  6784. while (NewBW < BitWidth &&
  6785. !(TLI.isOperationLegalOrCustom(Opc, NewVT) &&
  6786. TLI.isNarrowingProfitable(VT, NewVT))) {
  6787. NewBW = NextPowerOf2(NewBW);
  6788. NewVT = EVT::getIntegerVT(*DAG.getContext(), NewBW);
  6789. }
  6790. if (NewBW >= BitWidth)
  6791. return SDValue();
  6792. // If the lsb changed does not start at the type bitwidth boundary,
  6793. // start at the previous one.
  6794. if (ShAmt % NewBW)
  6795. ShAmt = (((ShAmt + NewBW - 1) / NewBW) * NewBW) - NewBW;
  6796. APInt Mask = APInt::getBitsSet(BitWidth, ShAmt,
  6797. std::min(BitWidth, ShAmt + NewBW));
  6798. if ((Imm & Mask) == Imm) {
  6799. APInt NewImm = (Imm & Mask).lshr(ShAmt).trunc(NewBW);
  6800. if (Opc == ISD::AND)
  6801. NewImm ^= APInt::getAllOnesValue(NewBW);
  6802. uint64_t PtrOff = ShAmt / 8;
  6803. // For big endian targets, we need to adjust the offset to the pointer to
  6804. // load the correct bytes.
  6805. if (TLI.isBigEndian())
  6806. PtrOff = (BitWidth + 7 - NewBW) / 8 - PtrOff;
  6807. unsigned NewAlign = MinAlign(LD->getAlignment(), PtrOff);
  6808. Type *NewVTTy = NewVT.getTypeForEVT(*DAG.getContext());
  6809. if (NewAlign < TLI.getDataLayout()->getABITypeAlignment(NewVTTy))
  6810. return SDValue();
  6811. SDValue NewPtr = DAG.getNode(ISD::ADD, LD->getDebugLoc(),
  6812. Ptr.getValueType(), Ptr,
  6813. DAG.getConstant(PtrOff, Ptr.getValueType()));
  6814. SDValue NewLD = DAG.getLoad(NewVT, N0.getDebugLoc(),
  6815. LD->getChain(), NewPtr,
  6816. LD->getPointerInfo().getWithOffset(PtrOff),
  6817. LD->isVolatile(), LD->isNonTemporal(),
  6818. LD->isInvariant(), NewAlign);
  6819. SDValue NewVal = DAG.getNode(Opc, Value.getDebugLoc(), NewVT, NewLD,
  6820. DAG.getConstant(NewImm, NewVT));
  6821. SDValue NewST = DAG.getStore(Chain, N->getDebugLoc(),
  6822. NewVal, NewPtr,
  6823. ST->getPointerInfo().getWithOffset(PtrOff),
  6824. false, false, NewAlign);
  6825. AddToWorkList(NewPtr.getNode());
  6826. AddToWorkList(NewLD.getNode());
  6827. AddToWorkList(NewVal.getNode());
  6828. WorkListRemover DeadNodes(*this);
  6829. DAG.ReplaceAllUsesOfValueWith(N0.getValue(1), NewLD.getValue(1));
  6830. ++OpsNarrowed;
  6831. return NewST;
  6832. }
  6833. }
  6834. return SDValue();
  6835. }
  6836. /// TransformFPLoadStorePair - For a given floating point load / store pair,
  6837. /// if the load value isn't used by any other operations, then consider
  6838. /// transforming the pair to integer load / store operations if the target
  6839. /// deems the transformation profitable.
  6840. SDValue DAGCombiner::TransformFPLoadStorePair(SDNode *N) {
  6841. StoreSDNode *ST = cast<StoreSDNode>(N);
  6842. SDValue Chain = ST->getChain();
  6843. SDValue Value = ST->getValue();
  6844. if (ISD::isNormalStore(ST) && ISD::isNormalLoad(Value.getNode()) &&
  6845. Value.hasOneUse() &&
  6846. Chain == SDValue(Value.getNode(), 1)) {
  6847. LoadSDNode *LD = cast<LoadSDNode>(Value);
  6848. EVT VT = LD->getMemoryVT();
  6849. if (!VT.isFloatingPoint() ||
  6850. VT != ST->getMemoryVT() ||
  6851. LD->isNonTemporal() ||
  6852. ST->isNonTemporal() ||
  6853. LD->getPointerInfo().getAddrSpace() != 0 ||
  6854. ST->getPointerInfo().getAddrSpace() != 0)
  6855. return SDValue();
  6856. EVT IntVT = EVT::getIntegerVT(*DAG.getContext(), VT.getSizeInBits());
  6857. if (!TLI.isOperationLegal(ISD::LOAD, IntVT) ||
  6858. !TLI.isOperationLegal(ISD::STORE, IntVT) ||
  6859. !TLI.isDesirableToTransformToIntegerOp(ISD::LOAD, VT) ||
  6860. !TLI.isDesirableToTransformToIntegerOp(ISD::STORE, VT))
  6861. return SDValue();
  6862. unsigned LDAlign = LD->getAlignment();
  6863. unsigned STAlign = ST->getAlignment();
  6864. Type *IntVTTy = IntVT.getTypeForEVT(*DAG.getContext());
  6865. unsigned ABIAlign = TLI.getDataLayout()->getABITypeAlignment(IntVTTy);
  6866. if (LDAlign < ABIAlign || STAlign < ABIAlign)
  6867. return SDValue();
  6868. SDValue NewLD = DAG.getLoad(IntVT, Value.getDebugLoc(),
  6869. LD->getChain(), LD->getBasePtr(),
  6870. LD->getPointerInfo(),
  6871. false, false, false, LDAlign);
  6872. SDValue NewST = DAG.getStore(NewLD.getValue(1), N->getDebugLoc(),
  6873. NewLD, ST->getBasePtr(),
  6874. ST->getPointerInfo(),
  6875. false, false, STAlign);
  6876. AddToWorkList(NewLD.getNode());
  6877. AddToWorkList(NewST.getNode());
  6878. WorkListRemover DeadNodes(*this);
  6879. DAG.ReplaceAllUsesOfValueWith(Value.getValue(1), NewLD.getValue(1));
  6880. ++LdStFP2Int;
  6881. return NewST;
  6882. }
  6883. return SDValue();
  6884. }
  6885. /// Helper struct to parse and store a memory address as base + index + offset.
  6886. /// We ignore sign extensions when it is safe to do so.
  6887. /// The following two expressions are not equivalent. To differentiate we need
  6888. /// to store whether there was a sign extension involved in the index
  6889. /// computation.
  6890. /// (load (i64 add (i64 copyfromreg %c)
  6891. /// (i64 signextend (add (i8 load %index)
  6892. /// (i8 1))))
  6893. /// vs
  6894. ///
  6895. /// (load (i64 add (i64 copyfromreg %c)
  6896. /// (i64 signextend (i32 add (i32 signextend (i8 load %index))
  6897. /// (i32 1)))))
  6898. struct BaseIndexOffset {
  6899. SDValue Base;
  6900. SDValue Index;
  6901. int64_t Offset;
  6902. bool IsIndexSignExt;
  6903. BaseIndexOffset() : Offset(0), IsIndexSignExt(false) {}
  6904. BaseIndexOffset(SDValue Base, SDValue Index, int64_t Offset,
  6905. bool IsIndexSignExt) :
  6906. Base(Base), Index(Index), Offset(Offset), IsIndexSignExt(IsIndexSignExt) {}
  6907. bool equalBaseIndex(const BaseIndexOffset &Other) {
  6908. return Other.Base == Base && Other.Index == Index &&
  6909. Other.IsIndexSignExt == IsIndexSignExt;
  6910. }
  6911. /// Parses tree in Ptr for base, index, offset addresses.
  6912. static BaseIndexOffset match(SDValue Ptr) {
  6913. bool IsIndexSignExt = false;
  6914. // Just Base or possibly anything else.
  6915. if (Ptr->getOpcode() != ISD::ADD)
  6916. return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
  6917. // Base + offset.
  6918. if (isa<ConstantSDNode>(Ptr->getOperand(1))) {
  6919. int64_t Offset = cast<ConstantSDNode>(Ptr->getOperand(1))->getSExtValue();
  6920. return BaseIndexOffset(Ptr->getOperand(0), SDValue(), Offset,
  6921. IsIndexSignExt);
  6922. }
  6923. // Look at Base + Index + Offset cases.
  6924. SDValue Base = Ptr->getOperand(0);
  6925. SDValue IndexOffset = Ptr->getOperand(1);
  6926. // Skip signextends.
  6927. if (IndexOffset->getOpcode() == ISD::SIGN_EXTEND) {
  6928. IndexOffset = IndexOffset->getOperand(0);
  6929. IsIndexSignExt = true;
  6930. }
  6931. // Either the case of Base + Index (no offset) or something else.
  6932. if (IndexOffset->getOpcode() != ISD::ADD)
  6933. return BaseIndexOffset(Base, IndexOffset, 0, IsIndexSignExt);
  6934. // Now we have the case of Base + Index + offset.
  6935. SDValue Index = IndexOffset->getOperand(0);
  6936. SDValue Offset = IndexOffset->getOperand(1);
  6937. if (!isa<ConstantSDNode>(Offset))
  6938. return BaseIndexOffset(Ptr, SDValue(), 0, IsIndexSignExt);
  6939. // Ignore signextends.
  6940. if (Index->getOpcode() == ISD::SIGN_EXTEND) {
  6941. Index = Index->getOperand(0);
  6942. IsIndexSignExt = true;
  6943. } else IsIndexSignExt = false;
  6944. int64_t Off = cast<ConstantSDNode>(Offset)->getSExtValue();
  6945. return BaseIndexOffset(Base, Index, Off, IsIndexSignExt);
  6946. }
  6947. };
  6948. /// Holds a pointer to an LSBaseSDNode as well as information on where it
  6949. /// is located in a sequence of memory operations connected by a chain.
  6950. struct MemOpLink {
  6951. MemOpLink (LSBaseSDNode *N, int64_t Offset, unsigned Seq):
  6952. MemNode(N), OffsetFromBase(Offset), SequenceNum(Seq) { }
  6953. // Ptr to the mem node.
  6954. LSBaseSDNode *MemNode;
  6955. // Offset from the base ptr.
  6956. int64_t OffsetFromBase;
  6957. // What is the sequence number of this mem node.
  6958. // Lowest mem operand in the DAG starts at zero.
  6959. unsigned SequenceNum;
  6960. };
  6961. /// Sorts store nodes in a link according to their offset from a shared
  6962. // base ptr.
  6963. struct ConsecutiveMemoryChainSorter {
  6964. bool operator()(MemOpLink LHS, MemOpLink RHS) {
  6965. return LHS.OffsetFromBase < RHS.OffsetFromBase;
  6966. }
  6967. };
  6968. bool DAGCombiner::MergeConsecutiveStores(StoreSDNode* St) {
  6969. EVT MemVT = St->getMemoryVT();
  6970. int64_t ElementSizeBytes = MemVT.getSizeInBits()/8;
  6971. bool NoVectors = DAG.getMachineFunction().getFunction()->getAttributes().
  6972. hasAttribute(AttributeSet::FunctionIndex, Attribute::NoImplicitFloat);
  6973. // Don't merge vectors into wider inputs.
  6974. if (MemVT.isVector() || !MemVT.isSimple())
  6975. return false;
  6976. // Perform an early exit check. Do not bother looking at stored values that
  6977. // are not constants or loads.
  6978. SDValue StoredVal = St->getValue();
  6979. bool IsLoadSrc = isa<LoadSDNode>(StoredVal);
  6980. if (!isa<ConstantSDNode>(StoredVal) && !isa<ConstantFPSDNode>(StoredVal) &&
  6981. !IsLoadSrc)
  6982. return false;
  6983. // Only look at ends of store sequences.
  6984. SDValue Chain = SDValue(St, 1);
  6985. if (Chain->hasOneUse() && Chain->use_begin()->getOpcode() == ISD::STORE)
  6986. return false;
  6987. // This holds the base pointer, index, and the offset in bytes from the base
  6988. // pointer.
  6989. BaseIndexOffset BasePtr = BaseIndexOffset::match(St->getBasePtr());
  6990. // We must have a base and an offset.
  6991. if (!BasePtr.Base.getNode())
  6992. return false;
  6993. // Do not handle stores to undef base pointers.
  6994. if (BasePtr.Base.getOpcode() == ISD::UNDEF)
  6995. return false;
  6996. // Save the LoadSDNodes that we find in the chain.
  6997. // We need to make sure that these nodes do not interfere with
  6998. // any of the store nodes.
  6999. SmallVector<LSBaseSDNode*, 8> AliasLoadNodes;
  7000. // Save the StoreSDNodes that we find in the chain.
  7001. SmallVector<MemOpLink, 8> StoreNodes;
  7002. // Walk up the chain and look for nodes with offsets from the same
  7003. // base pointer. Stop when reaching an instruction with a different kind
  7004. // or instruction which has a different base pointer.
  7005. unsigned Seq = 0;
  7006. StoreSDNode *Index = St;
  7007. while (Index) {
  7008. // If the chain has more than one use, then we can't reorder the mem ops.
  7009. if (Index != St && !SDValue(Index, 1)->hasOneUse())
  7010. break;
  7011. // Find the base pointer and offset for this memory node.
  7012. BaseIndexOffset Ptr = BaseIndexOffset::match(Index->getBasePtr());
  7013. // Check that the base pointer is the same as the original one.
  7014. if (!Ptr.equalBaseIndex(BasePtr))
  7015. break;
  7016. // Check that the alignment is the same.
  7017. if (Index->getAlignment() != St->getAlignment())
  7018. break;
  7019. // The memory operands must not be volatile.
  7020. if (Index->isVolatile() || Index->isIndexed())
  7021. break;
  7022. // No truncation.
  7023. if (StoreSDNode *St = dyn_cast<StoreSDNode>(Index))
  7024. if (St->isTruncatingStore())
  7025. break;
  7026. // The stored memory type must be the same.
  7027. if (Index->getMemoryVT() != MemVT)
  7028. break;
  7029. // We do not allow unaligned stores because we want to prevent overriding
  7030. // stores.
  7031. if (Index->getAlignment()*8 != MemVT.getSizeInBits())
  7032. break;
  7033. // We found a potential memory operand to merge.
  7034. StoreNodes.push_back(MemOpLink(Index, Ptr.Offset, Seq++));
  7035. // Find the next memory operand in the chain. If the next operand in the
  7036. // chain is a store then move up and continue the scan with the next
  7037. // memory operand. If the next operand is a load save it and use alias
  7038. // information to check if it interferes with anything.
  7039. SDNode *NextInChain = Index->getChain().getNode();
  7040. while (1) {
  7041. if (StoreSDNode *STn = dyn_cast<StoreSDNode>(NextInChain)) {
  7042. // We found a store node. Use it for the next iteration.
  7043. Index = STn;
  7044. break;
  7045. } else if (LoadSDNode *Ldn = dyn_cast<LoadSDNode>(NextInChain)) {
  7046. // Save the load node for later. Continue the scan.
  7047. AliasLoadNodes.push_back(Ldn);
  7048. NextInChain = Ldn->getChain().getNode();
  7049. continue;
  7050. } else {
  7051. Index = NULL;
  7052. break;
  7053. }
  7054. }
  7055. }
  7056. // Check if there is anything to merge.
  7057. if (StoreNodes.size() < 2)
  7058. return false;
  7059. // Sort the memory operands according to their distance from the base pointer.
  7060. std::sort(StoreNodes.begin(), StoreNodes.end(),
  7061. ConsecutiveMemoryChainSorter());
  7062. // Scan the memory operations on the chain and find the first non-consecutive
  7063. // store memory address.
  7064. unsigned LastConsecutiveStore = 0;
  7065. int64_t StartAddress = StoreNodes[0].OffsetFromBase;
  7066. for (unsigned i = 0, e = StoreNodes.size(); i < e; ++i) {
  7067. // Check that the addresses are consecutive starting from the second
  7068. // element in the list of stores.
  7069. if (i > 0) {
  7070. int64_t CurrAddress = StoreNodes[i].OffsetFromBase;
  7071. if (CurrAddress - StartAddress != (ElementSizeBytes * i))
  7072. break;
  7073. }
  7074. bool Alias = false;
  7075. // Check if this store interferes with any of the loads that we found.
  7076. for (unsigned ld = 0, lde = AliasLoadNodes.size(); ld < lde; ++ld)
  7077. if (isAlias(AliasLoadNodes[ld], StoreNodes[i].MemNode)) {
  7078. Alias = true;
  7079. break;
  7080. }
  7081. // We found a load that alias with this store. Stop the sequence.
  7082. if (Alias)
  7083. break;
  7084. // Mark this node as useful.
  7085. LastConsecutiveStore = i;
  7086. }
  7087. // The node with the lowest store address.
  7088. LSBaseSDNode *FirstInChain = StoreNodes[0].MemNode;
  7089. // Store the constants into memory as one consecutive store.
  7090. if (!IsLoadSrc) {
  7091. unsigned LastLegalType = 0;
  7092. unsigned LastLegalVectorType = 0;
  7093. bool NonZero = false;
  7094. for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
  7095. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
  7096. SDValue StoredVal = St->getValue();
  7097. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(StoredVal)) {
  7098. NonZero |= !C->isNullValue();
  7099. } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(StoredVal)) {
  7100. NonZero |= !C->getConstantFPValue()->isNullValue();
  7101. } else {
  7102. // Non constant.
  7103. break;
  7104. }
  7105. // Find a legal type for the constant store.
  7106. unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
  7107. EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
  7108. if (TLI.isTypeLegal(StoreTy))
  7109. LastLegalType = i+1;
  7110. // Or check whether a truncstore is legal.
  7111. else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
  7112. TargetLowering::TypePromoteInteger) {
  7113. EVT LegalizedStoredValueTy =
  7114. TLI.getTypeToTransformTo(*DAG.getContext(), StoredVal.getValueType());
  7115. if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy))
  7116. LastLegalType = i+1;
  7117. }
  7118. // Find a legal type for the vector store.
  7119. EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
  7120. if (TLI.isTypeLegal(Ty))
  7121. LastLegalVectorType = i + 1;
  7122. }
  7123. // We only use vectors if the constant is known to be zero and the
  7124. // function is not marked with the noimplicitfloat attribute.
  7125. if (NonZero || NoVectors)
  7126. LastLegalVectorType = 0;
  7127. // Check if we found a legal integer type to store.
  7128. if (LastLegalType == 0 && LastLegalVectorType == 0)
  7129. return false;
  7130. bool UseVector = (LastLegalVectorType > LastLegalType) && !NoVectors;
  7131. unsigned NumElem = UseVector ? LastLegalVectorType : LastLegalType;
  7132. // Make sure we have something to merge.
  7133. if (NumElem < 2)
  7134. return false;
  7135. unsigned EarliestNodeUsed = 0;
  7136. for (unsigned i=0; i < NumElem; ++i) {
  7137. // Find a chain for the new wide-store operand. Notice that some
  7138. // of the store nodes that we found may not be selected for inclusion
  7139. // in the wide store. The chain we use needs to be the chain of the
  7140. // earliest store node which is *used* and replaced by the wide store.
  7141. if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
  7142. EarliestNodeUsed = i;
  7143. }
  7144. // The earliest Node in the DAG.
  7145. LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
  7146. DebugLoc DL = StoreNodes[0].MemNode->getDebugLoc();
  7147. SDValue StoredVal;
  7148. if (UseVector) {
  7149. // Find a legal type for the vector store.
  7150. EVT Ty = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
  7151. assert(TLI.isTypeLegal(Ty) && "Illegal vector store");
  7152. StoredVal = DAG.getConstant(0, Ty);
  7153. } else {
  7154. unsigned StoreBW = NumElem * ElementSizeBytes * 8;
  7155. APInt StoreInt(StoreBW, 0);
  7156. // Construct a single integer constant which is made of the smaller
  7157. // constant inputs.
  7158. bool IsLE = TLI.isLittleEndian();
  7159. for (unsigned i = 0; i < NumElem ; ++i) {
  7160. unsigned Idx = IsLE ?(NumElem - 1 - i) : i;
  7161. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[Idx].MemNode);
  7162. SDValue Val = St->getValue();
  7163. StoreInt<<=ElementSizeBytes*8;
  7164. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Val)) {
  7165. StoreInt|=C->getAPIntValue().zext(StoreBW);
  7166. } else if (ConstantFPSDNode *C = dyn_cast<ConstantFPSDNode>(Val)) {
  7167. StoreInt|= C->getValueAPF().bitcastToAPInt().zext(StoreBW);
  7168. } else {
  7169. assert(false && "Invalid constant element type");
  7170. }
  7171. }
  7172. // Create the new Load and Store operations.
  7173. EVT StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
  7174. StoredVal = DAG.getConstant(StoreInt, StoreTy);
  7175. }
  7176. SDValue NewStore = DAG.getStore(EarliestOp->getChain(), DL, StoredVal,
  7177. FirstInChain->getBasePtr(),
  7178. FirstInChain->getPointerInfo(),
  7179. false, false,
  7180. FirstInChain->getAlignment());
  7181. // Replace the first store with the new store
  7182. CombineTo(EarliestOp, NewStore);
  7183. // Erase all other stores.
  7184. for (unsigned i = 0; i < NumElem ; ++i) {
  7185. if (StoreNodes[i].MemNode == EarliestOp)
  7186. continue;
  7187. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
  7188. // ReplaceAllUsesWith will replace all uses that existed when it was
  7189. // called, but graph optimizations may cause new ones to appear. For
  7190. // example, the case in pr14333 looks like
  7191. //
  7192. // St's chain -> St -> another store -> X
  7193. //
  7194. // And the only difference from St to the other store is the chain.
  7195. // When we change it's chain to be St's chain they become identical,
  7196. // get CSEed and the net result is that X is now a use of St.
  7197. // Since we know that St is redundant, just iterate.
  7198. while (!St->use_empty())
  7199. DAG.ReplaceAllUsesWith(SDValue(St, 0), St->getChain());
  7200. removeFromWorkList(St);
  7201. DAG.DeleteNode(St);
  7202. }
  7203. return true;
  7204. }
  7205. // Below we handle the case of multiple consecutive stores that
  7206. // come from multiple consecutive loads. We merge them into a single
  7207. // wide load and a single wide store.
  7208. // Look for load nodes which are used by the stored values.
  7209. SmallVector<MemOpLink, 8> LoadNodes;
  7210. // Find acceptable loads. Loads need to have the same chain (token factor),
  7211. // must not be zext, volatile, indexed, and they must be consecutive.
  7212. BaseIndexOffset LdBasePtr;
  7213. for (unsigned i=0; i<LastConsecutiveStore+1; ++i) {
  7214. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
  7215. LoadSDNode *Ld = dyn_cast<LoadSDNode>(St->getValue());
  7216. if (!Ld) break;
  7217. // Loads must only have one use.
  7218. if (!Ld->hasNUsesOfValue(1, 0))
  7219. break;
  7220. // Check that the alignment is the same as the stores.
  7221. if (Ld->getAlignment() != St->getAlignment())
  7222. break;
  7223. // The memory operands must not be volatile.
  7224. if (Ld->isVolatile() || Ld->isIndexed())
  7225. break;
  7226. // We do not accept ext loads.
  7227. if (Ld->getExtensionType() != ISD::NON_EXTLOAD)
  7228. break;
  7229. // The stored memory type must be the same.
  7230. if (Ld->getMemoryVT() != MemVT)
  7231. break;
  7232. BaseIndexOffset LdPtr = BaseIndexOffset::match(Ld->getBasePtr());
  7233. // If this is not the first ptr that we check.
  7234. if (LdBasePtr.Base.getNode()) {
  7235. // The base ptr must be the same.
  7236. if (!LdPtr.equalBaseIndex(LdBasePtr))
  7237. break;
  7238. } else {
  7239. // Check that all other base pointers are the same as this one.
  7240. LdBasePtr = LdPtr;
  7241. }
  7242. // We found a potential memory operand to merge.
  7243. LoadNodes.push_back(MemOpLink(Ld, LdPtr.Offset, 0));
  7244. }
  7245. if (LoadNodes.size() < 2)
  7246. return false;
  7247. // Scan the memory operations on the chain and find the first non-consecutive
  7248. // load memory address. These variables hold the index in the store node
  7249. // array.
  7250. unsigned LastConsecutiveLoad = 0;
  7251. // This variable refers to the size and not index in the array.
  7252. unsigned LastLegalVectorType = 0;
  7253. unsigned LastLegalIntegerType = 0;
  7254. StartAddress = LoadNodes[0].OffsetFromBase;
  7255. SDValue FirstChain = LoadNodes[0].MemNode->getChain();
  7256. for (unsigned i = 1; i < LoadNodes.size(); ++i) {
  7257. // All loads much share the same chain.
  7258. if (LoadNodes[i].MemNode->getChain() != FirstChain)
  7259. break;
  7260. int64_t CurrAddress = LoadNodes[i].OffsetFromBase;
  7261. if (CurrAddress - StartAddress != (ElementSizeBytes * i))
  7262. break;
  7263. LastConsecutiveLoad = i;
  7264. // Find a legal type for the vector store.
  7265. EVT StoreTy = EVT::getVectorVT(*DAG.getContext(), MemVT, i+1);
  7266. if (TLI.isTypeLegal(StoreTy))
  7267. LastLegalVectorType = i + 1;
  7268. // Find a legal type for the integer store.
  7269. unsigned StoreBW = (i+1) * ElementSizeBytes * 8;
  7270. StoreTy = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
  7271. if (TLI.isTypeLegal(StoreTy))
  7272. LastLegalIntegerType = i + 1;
  7273. // Or check whether a truncstore and extload is legal.
  7274. else if (TLI.getTypeAction(*DAG.getContext(), StoreTy) ==
  7275. TargetLowering::TypePromoteInteger) {
  7276. EVT LegalizedStoredValueTy =
  7277. TLI.getTypeToTransformTo(*DAG.getContext(), StoreTy);
  7278. if (TLI.isTruncStoreLegal(LegalizedStoredValueTy, StoreTy) &&
  7279. TLI.isLoadExtLegal(ISD::ZEXTLOAD, StoreTy) &&
  7280. TLI.isLoadExtLegal(ISD::SEXTLOAD, StoreTy) &&
  7281. TLI.isLoadExtLegal(ISD::EXTLOAD, StoreTy))
  7282. LastLegalIntegerType = i+1;
  7283. }
  7284. }
  7285. // Only use vector types if the vector type is larger than the integer type.
  7286. // If they are the same, use integers.
  7287. bool UseVectorTy = LastLegalVectorType > LastLegalIntegerType && !NoVectors;
  7288. unsigned LastLegalType = std::max(LastLegalVectorType, LastLegalIntegerType);
  7289. // We add +1 here because the LastXXX variables refer to location while
  7290. // the NumElem refers to array/index size.
  7291. unsigned NumElem = std::min(LastConsecutiveStore, LastConsecutiveLoad) + 1;
  7292. NumElem = std::min(LastLegalType, NumElem);
  7293. if (NumElem < 2)
  7294. return false;
  7295. // The earliest Node in the DAG.
  7296. unsigned EarliestNodeUsed = 0;
  7297. LSBaseSDNode *EarliestOp = StoreNodes[EarliestNodeUsed].MemNode;
  7298. for (unsigned i=1; i<NumElem; ++i) {
  7299. // Find a chain for the new wide-store operand. Notice that some
  7300. // of the store nodes that we found may not be selected for inclusion
  7301. // in the wide store. The chain we use needs to be the chain of the
  7302. // earliest store node which is *used* and replaced by the wide store.
  7303. if (StoreNodes[i].SequenceNum > StoreNodes[EarliestNodeUsed].SequenceNum)
  7304. EarliestNodeUsed = i;
  7305. }
  7306. // Find if it is better to use vectors or integers to load and store
  7307. // to memory.
  7308. EVT JointMemOpVT;
  7309. if (UseVectorTy) {
  7310. JointMemOpVT = EVT::getVectorVT(*DAG.getContext(), MemVT, NumElem);
  7311. } else {
  7312. unsigned StoreBW = NumElem * ElementSizeBytes * 8;
  7313. JointMemOpVT = EVT::getIntegerVT(*DAG.getContext(), StoreBW);
  7314. }
  7315. DebugLoc LoadDL = LoadNodes[0].MemNode->getDebugLoc();
  7316. DebugLoc StoreDL = StoreNodes[0].MemNode->getDebugLoc();
  7317. LoadSDNode *FirstLoad = cast<LoadSDNode>(LoadNodes[0].MemNode);
  7318. SDValue NewLoad = DAG.getLoad(JointMemOpVT, LoadDL,
  7319. FirstLoad->getChain(),
  7320. FirstLoad->getBasePtr(),
  7321. FirstLoad->getPointerInfo(),
  7322. false, false, false,
  7323. FirstLoad->getAlignment());
  7324. SDValue NewStore = DAG.getStore(EarliestOp->getChain(), StoreDL, NewLoad,
  7325. FirstInChain->getBasePtr(),
  7326. FirstInChain->getPointerInfo(), false, false,
  7327. FirstInChain->getAlignment());
  7328. // Replace one of the loads with the new load.
  7329. LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[0].MemNode);
  7330. DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1),
  7331. SDValue(NewLoad.getNode(), 1));
  7332. // Remove the rest of the load chains.
  7333. for (unsigned i = 1; i < NumElem ; ++i) {
  7334. // Replace all chain users of the old load nodes with the chain of the new
  7335. // load node.
  7336. LoadSDNode *Ld = cast<LoadSDNode>(LoadNodes[i].MemNode);
  7337. DAG.ReplaceAllUsesOfValueWith(SDValue(Ld, 1), Ld->getChain());
  7338. }
  7339. // Replace the first store with the new store.
  7340. CombineTo(EarliestOp, NewStore);
  7341. // Erase all other stores.
  7342. for (unsigned i = 0; i < NumElem ; ++i) {
  7343. // Remove all Store nodes.
  7344. if (StoreNodes[i].MemNode == EarliestOp)
  7345. continue;
  7346. StoreSDNode *St = cast<StoreSDNode>(StoreNodes[i].MemNode);
  7347. DAG.ReplaceAllUsesOfValueWith(SDValue(St, 0), St->getChain());
  7348. removeFromWorkList(St);
  7349. DAG.DeleteNode(St);
  7350. }
  7351. return true;
  7352. }
  7353. SDValue DAGCombiner::visitSTORE(SDNode *N) {
  7354. StoreSDNode *ST = cast<StoreSDNode>(N);
  7355. SDValue Chain = ST->getChain();
  7356. SDValue Value = ST->getValue();
  7357. SDValue Ptr = ST->getBasePtr();
  7358. // If this is a store of a bit convert, store the input value if the
  7359. // resultant store does not need a higher alignment than the original.
  7360. if (Value.getOpcode() == ISD::BITCAST && !ST->isTruncatingStore() &&
  7361. ST->isUnindexed()) {
  7362. unsigned OrigAlign = ST->getAlignment();
  7363. EVT SVT = Value.getOperand(0).getValueType();
  7364. unsigned Align = TLI.getDataLayout()->
  7365. getABITypeAlignment(SVT.getTypeForEVT(*DAG.getContext()));
  7366. if (Align <= OrigAlign &&
  7367. ((!LegalOperations && !ST->isVolatile()) ||
  7368. TLI.isOperationLegalOrCustom(ISD::STORE, SVT)))
  7369. return DAG.getStore(Chain, N->getDebugLoc(), Value.getOperand(0),
  7370. Ptr, ST->getPointerInfo(), ST->isVolatile(),
  7371. ST->isNonTemporal(), OrigAlign);
  7372. }
  7373. // Turn 'store undef, Ptr' -> nothing.
  7374. if (Value.getOpcode() == ISD::UNDEF && ST->isUnindexed())
  7375. return Chain;
  7376. // Turn 'store float 1.0, Ptr' -> 'store int 0x12345678, Ptr'
  7377. if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(Value)) {
  7378. // NOTE: If the original store is volatile, this transform must not increase
  7379. // the number of stores. For example, on x86-32 an f64 can be stored in one
  7380. // processor operation but an i64 (which is not legal) requires two. So the
  7381. // transform should not be done in this case.
  7382. if (Value.getOpcode() != ISD::TargetConstantFP) {
  7383. SDValue Tmp;
  7384. switch (CFP->getValueType(0).getSimpleVT().SimpleTy) {
  7385. default: llvm_unreachable("Unknown FP type");
  7386. case MVT::f16: // We don't do this for these yet.
  7387. case MVT::f80:
  7388. case MVT::f128:
  7389. case MVT::ppcf128:
  7390. break;
  7391. case MVT::f32:
  7392. if ((isTypeLegal(MVT::i32) && !LegalOperations && !ST->isVolatile()) ||
  7393. TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
  7394. Tmp = DAG.getConstant((uint32_t)CFP->getValueAPF().
  7395. bitcastToAPInt().getZExtValue(), MVT::i32);
  7396. return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
  7397. Ptr, ST->getPointerInfo(), ST->isVolatile(),
  7398. ST->isNonTemporal(), ST->getAlignment());
  7399. }
  7400. break;
  7401. case MVT::f64:
  7402. if ((TLI.isTypeLegal(MVT::i64) && !LegalOperations &&
  7403. !ST->isVolatile()) ||
  7404. TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i64)) {
  7405. Tmp = DAG.getConstant(CFP->getValueAPF().bitcastToAPInt().
  7406. getZExtValue(), MVT::i64);
  7407. return DAG.getStore(Chain, N->getDebugLoc(), Tmp,
  7408. Ptr, ST->getPointerInfo(), ST->isVolatile(),
  7409. ST->isNonTemporal(), ST->getAlignment());
  7410. }
  7411. if (!ST->isVolatile() &&
  7412. TLI.isOperationLegalOrCustom(ISD::STORE, MVT::i32)) {
  7413. // Many FP stores are not made apparent until after legalize, e.g. for
  7414. // argument passing. Since this is so common, custom legalize the
  7415. // 64-bit integer store into two 32-bit stores.
  7416. uint64_t Val = CFP->getValueAPF().bitcastToAPInt().getZExtValue();
  7417. SDValue Lo = DAG.getConstant(Val & 0xFFFFFFFF, MVT::i32);
  7418. SDValue Hi = DAG.getConstant(Val >> 32, MVT::i32);
  7419. if (TLI.isBigEndian()) std::swap(Lo, Hi);
  7420. unsigned Alignment = ST->getAlignment();
  7421. bool isVolatile = ST->isVolatile();
  7422. bool isNonTemporal = ST->isNonTemporal();
  7423. SDValue St0 = DAG.getStore(Chain, ST->getDebugLoc(), Lo,
  7424. Ptr, ST->getPointerInfo(),
  7425. isVolatile, isNonTemporal,
  7426. ST->getAlignment());
  7427. Ptr = DAG.getNode(ISD::ADD, N->getDebugLoc(), Ptr.getValueType(), Ptr,
  7428. DAG.getConstant(4, Ptr.getValueType()));
  7429. Alignment = MinAlign(Alignment, 4U);
  7430. SDValue St1 = DAG.getStore(Chain, ST->getDebugLoc(), Hi,
  7431. Ptr, ST->getPointerInfo().getWithOffset(4),
  7432. isVolatile, isNonTemporal,
  7433. Alignment);
  7434. return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
  7435. St0, St1);
  7436. }
  7437. break;
  7438. }
  7439. }
  7440. }
  7441. // Try to infer better alignment information than the store already has.
  7442. if (OptLevel != CodeGenOpt::None && ST->isUnindexed()) {
  7443. if (unsigned Align = DAG.InferPtrAlignment(Ptr)) {
  7444. if (Align > ST->getAlignment())
  7445. return DAG.getTruncStore(Chain, N->getDebugLoc(), Value,
  7446. Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
  7447. ST->isVolatile(), ST->isNonTemporal(), Align);
  7448. }
  7449. }
  7450. // Try transforming a pair floating point load / store ops to integer
  7451. // load / store ops.
  7452. SDValue NewST = TransformFPLoadStorePair(N);
  7453. if (NewST.getNode())
  7454. return NewST;
  7455. if (CombinerAA) {
  7456. // Walk up chain skipping non-aliasing memory nodes.
  7457. SDValue BetterChain = FindBetterChain(N, Chain);
  7458. // If there is a better chain.
  7459. if (Chain != BetterChain) {
  7460. SDValue ReplStore;
  7461. // Replace the chain to avoid dependency.
  7462. if (ST->isTruncatingStore()) {
  7463. ReplStore = DAG.getTruncStore(BetterChain, N->getDebugLoc(), Value, Ptr,
  7464. ST->getPointerInfo(),
  7465. ST->getMemoryVT(), ST->isVolatile(),
  7466. ST->isNonTemporal(), ST->getAlignment());
  7467. } else {
  7468. ReplStore = DAG.getStore(BetterChain, N->getDebugLoc(), Value, Ptr,
  7469. ST->getPointerInfo(),
  7470. ST->isVolatile(), ST->isNonTemporal(),
  7471. ST->getAlignment());
  7472. }
  7473. // Create token to keep both nodes around.
  7474. SDValue Token = DAG.getNode(ISD::TokenFactor, N->getDebugLoc(),
  7475. MVT::Other, Chain, ReplStore);
  7476. // Make sure the new and old chains are cleaned up.
  7477. AddToWorkList(Token.getNode());
  7478. // Don't add users to work list.
  7479. return CombineTo(N, Token, false);
  7480. }
  7481. }
  7482. // Try transforming N to an indexed store.
  7483. if (CombineToPreIndexedLoadStore(N) || CombineToPostIndexedLoadStore(N))
  7484. return SDValue(N, 0);
  7485. // FIXME: is there such a thing as a truncating indexed store?
  7486. if (ST->isTruncatingStore() && ST->isUnindexed() &&
  7487. Value.getValueType().isInteger()) {
  7488. // See if we can simplify the input to this truncstore with knowledge that
  7489. // only the low bits are being used. For example:
  7490. // "truncstore (or (shl x, 8), y), i8" -> "truncstore y, i8"
  7491. SDValue Shorter =
  7492. GetDemandedBits(Value,
  7493. APInt::getLowBitsSet(
  7494. Value.getValueType().getScalarType().getSizeInBits(),
  7495. ST->getMemoryVT().getScalarType().getSizeInBits()));
  7496. AddToWorkList(Value.getNode());
  7497. if (Shorter.getNode())
  7498. return DAG.getTruncStore(Chain, N->getDebugLoc(), Shorter,
  7499. Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
  7500. ST->isVolatile(), ST->isNonTemporal(),
  7501. ST->getAlignment());
  7502. // Otherwise, see if we can simplify the operation with
  7503. // SimplifyDemandedBits, which only works if the value has a single use.
  7504. if (SimplifyDemandedBits(Value,
  7505. APInt::getLowBitsSet(
  7506. Value.getValueType().getScalarType().getSizeInBits(),
  7507. ST->getMemoryVT().getScalarType().getSizeInBits())))
  7508. return SDValue(N, 0);
  7509. }
  7510. // If this is a load followed by a store to the same location, then the store
  7511. // is dead/noop.
  7512. if (LoadSDNode *Ld = dyn_cast<LoadSDNode>(Value)) {
  7513. if (Ld->getBasePtr() == Ptr && ST->getMemoryVT() == Ld->getMemoryVT() &&
  7514. ST->isUnindexed() && !ST->isVolatile() &&
  7515. // There can't be any side effects between the load and store, such as
  7516. // a call or store.
  7517. Chain.reachesChainWithoutSideEffects(SDValue(Ld, 1))) {
  7518. // The store is dead, remove it.
  7519. return Chain;
  7520. }
  7521. }
  7522. // If this is an FP_ROUND or TRUNC followed by a store, fold this into a
  7523. // truncating store. We can do this even if this is already a truncstore.
  7524. if ((Value.getOpcode() == ISD::FP_ROUND || Value.getOpcode() == ISD::TRUNCATE)
  7525. && Value.getNode()->hasOneUse() && ST->isUnindexed() &&
  7526. TLI.isTruncStoreLegal(Value.getOperand(0).getValueType(),
  7527. ST->getMemoryVT())) {
  7528. return DAG.getTruncStore(Chain, N->getDebugLoc(), Value.getOperand(0),
  7529. Ptr, ST->getPointerInfo(), ST->getMemoryVT(),
  7530. ST->isVolatile(), ST->isNonTemporal(),
  7531. ST->getAlignment());
  7532. }
  7533. // Only perform this optimization before the types are legal, because we
  7534. // don't want to perform this optimization on every DAGCombine invocation.
  7535. if (!LegalTypes) {
  7536. bool EverChanged = false;
  7537. do {
  7538. // There can be multiple store sequences on the same chain.
  7539. // Keep trying to merge store sequences until we are unable to do so
  7540. // or until we merge the last store on the chain.
  7541. bool Changed = MergeConsecutiveStores(ST);
  7542. EverChanged |= Changed;
  7543. if (!Changed) break;
  7544. } while (ST->getOpcode() != ISD::DELETED_NODE);
  7545. if (EverChanged)
  7546. return SDValue(N, 0);
  7547. }
  7548. return ReduceLoadOpStoreWidth(N);
  7549. }
  7550. SDValue DAGCombiner::visitINSERT_VECTOR_ELT(SDNode *N) {
  7551. SDValue InVec = N->getOperand(0);
  7552. SDValue InVal = N->getOperand(1);
  7553. SDValue EltNo = N->getOperand(2);
  7554. DebugLoc dl = N->getDebugLoc();
  7555. // If the inserted element is an UNDEF, just use the input vector.
  7556. if (InVal.getOpcode() == ISD::UNDEF)
  7557. return InVec;
  7558. EVT VT = InVec.getValueType();
  7559. // If we can't generate a legal BUILD_VECTOR, exit
  7560. if (LegalOperations && !TLI.isOperationLegal(ISD::BUILD_VECTOR, VT))
  7561. return SDValue();
  7562. // Check that we know which element is being inserted
  7563. if (!isa<ConstantSDNode>(EltNo))
  7564. return SDValue();
  7565. unsigned Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
  7566. // Check that the operand is a BUILD_VECTOR (or UNDEF, which can essentially
  7567. // be converted to a BUILD_VECTOR). Fill in the Ops vector with the
  7568. // vector elements.
  7569. SmallVector<SDValue, 8> Ops;
  7570. if (InVec.getOpcode() == ISD::BUILD_VECTOR) {
  7571. Ops.append(InVec.getNode()->op_begin(),
  7572. InVec.getNode()->op_end());
  7573. } else if (InVec.getOpcode() == ISD::UNDEF) {
  7574. unsigned NElts = VT.getVectorNumElements();
  7575. Ops.append(NElts, DAG.getUNDEF(InVal.getValueType()));
  7576. } else {
  7577. return SDValue();
  7578. }
  7579. // Insert the element
  7580. if (Elt < Ops.size()) {
  7581. // All the operands of BUILD_VECTOR must have the same type;
  7582. // we enforce that here.
  7583. EVT OpVT = Ops[0].getValueType();
  7584. if (InVal.getValueType() != OpVT)
  7585. InVal = OpVT.bitsGT(InVal.getValueType()) ?
  7586. DAG.getNode(ISD::ANY_EXTEND, dl, OpVT, InVal) :
  7587. DAG.getNode(ISD::TRUNCATE, dl, OpVT, InVal);
  7588. Ops[Elt] = InVal;
  7589. }
  7590. // Return the new vector
  7591. return DAG.getNode(ISD::BUILD_VECTOR, dl,
  7592. VT, &Ops[0], Ops.size());
  7593. }
  7594. SDValue DAGCombiner::visitEXTRACT_VECTOR_ELT(SDNode *N) {
  7595. // (vextract (scalar_to_vector val, 0) -> val
  7596. SDValue InVec = N->getOperand(0);
  7597. EVT VT = InVec.getValueType();
  7598. EVT NVT = N->getValueType(0);
  7599. if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR) {
  7600. // Check if the result type doesn't match the inserted element type. A
  7601. // SCALAR_TO_VECTOR may truncate the inserted element and the
  7602. // EXTRACT_VECTOR_ELT may widen the extracted vector.
  7603. SDValue InOp = InVec.getOperand(0);
  7604. if (InOp.getValueType() != NVT) {
  7605. assert(InOp.getValueType().isInteger() && NVT.isInteger());
  7606. return DAG.getSExtOrTrunc(InOp, InVec.getDebugLoc(), NVT);
  7607. }
  7608. return InOp;
  7609. }
  7610. SDValue EltNo = N->getOperand(1);
  7611. bool ConstEltNo = isa<ConstantSDNode>(EltNo);
  7612. // Transform: (EXTRACT_VECTOR_ELT( VECTOR_SHUFFLE )) -> EXTRACT_VECTOR_ELT.
  7613. // We only perform this optimization before the op legalization phase because
  7614. // we may introduce new vector instructions which are not backed by TD
  7615. // patterns. For example on AVX, extracting elements from a wide vector
  7616. // without using extract_subvector.
  7617. if (InVec.getOpcode() == ISD::VECTOR_SHUFFLE
  7618. && ConstEltNo && !LegalOperations) {
  7619. int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
  7620. int NumElem = VT.getVectorNumElements();
  7621. ShuffleVectorSDNode *SVOp = cast<ShuffleVectorSDNode>(InVec);
  7622. // Find the new index to extract from.
  7623. int OrigElt = SVOp->getMaskElt(Elt);
  7624. // Extracting an undef index is undef.
  7625. if (OrigElt == -1)
  7626. return DAG.getUNDEF(NVT);
  7627. // Select the right vector half to extract from.
  7628. if (OrigElt < NumElem) {
  7629. InVec = InVec->getOperand(0);
  7630. } else {
  7631. InVec = InVec->getOperand(1);
  7632. OrigElt -= NumElem;
  7633. }
  7634. EVT IndexTy = N->getOperand(1).getValueType();
  7635. return DAG.getNode(ISD::EXTRACT_VECTOR_ELT, N->getDebugLoc(), NVT,
  7636. InVec, DAG.getConstant(OrigElt, IndexTy));
  7637. }
  7638. // Perform only after legalization to ensure build_vector / vector_shuffle
  7639. // optimizations have already been done.
  7640. if (!LegalOperations) return SDValue();
  7641. // (vextract (v4f32 load $addr), c) -> (f32 load $addr+c*size)
  7642. // (vextract (v4f32 s2v (f32 load $addr)), c) -> (f32 load $addr+c*size)
  7643. // (vextract (v4f32 shuffle (load $addr), <1,u,u,u>), 0) -> (f32 load $addr)
  7644. if (ConstEltNo) {
  7645. int Elt = cast<ConstantSDNode>(EltNo)->getZExtValue();
  7646. bool NewLoad = false;
  7647. bool BCNumEltsChanged = false;
  7648. EVT ExtVT = VT.getVectorElementType();
  7649. EVT LVT = ExtVT;
  7650. // If the result of load has to be truncated, then it's not necessarily
  7651. // profitable.
  7652. if (NVT.bitsLT(LVT) && !TLI.isTruncateFree(LVT, NVT))
  7653. return SDValue();
  7654. if (InVec.getOpcode() == ISD::BITCAST) {
  7655. // Don't duplicate a load with other uses.
  7656. if (!InVec.hasOneUse())
  7657. return SDValue();
  7658. EVT BCVT = InVec.getOperand(0).getValueType();
  7659. if (!BCVT.isVector() || ExtVT.bitsGT(BCVT.getVectorElementType()))
  7660. return SDValue();
  7661. if (VT.getVectorNumElements() != BCVT.getVectorNumElements())
  7662. BCNumEltsChanged = true;
  7663. InVec = InVec.getOperand(0);
  7664. ExtVT = BCVT.getVectorElementType();
  7665. NewLoad = true;
  7666. }
  7667. LoadSDNode *LN0 = NULL;
  7668. const ShuffleVectorSDNode *SVN = NULL;
  7669. if (ISD::isNormalLoad(InVec.getNode())) {
  7670. LN0 = cast<LoadSDNode>(InVec);
  7671. } else if (InVec.getOpcode() == ISD::SCALAR_TO_VECTOR &&
  7672. InVec.getOperand(0).getValueType() == ExtVT &&
  7673. ISD::isNormalLoad(InVec.getOperand(0).getNode())) {
  7674. // Don't duplicate a load with other uses.
  7675. if (!InVec.hasOneUse())
  7676. return SDValue();
  7677. LN0 = cast<LoadSDNode>(InVec.getOperand(0));
  7678. } else if ((SVN = dyn_cast<ShuffleVectorSDNode>(InVec))) {
  7679. // (vextract (vector_shuffle (load $addr), v2, <1, u, u, u>), 1)
  7680. // =>
  7681. // (load $addr+1*size)
  7682. // Don't duplicate a load with other uses.
  7683. if (!InVec.hasOneUse())
  7684. return SDValue();
  7685. // If the bit convert changed the number of elements, it is unsafe
  7686. // to examine the mask.
  7687. if (BCNumEltsChanged)
  7688. return SDValue();
  7689. // Select the input vector, guarding against out of range extract vector.
  7690. unsigned NumElems = VT.getVectorNumElements();
  7691. int Idx = (Elt > (int)NumElems) ? -1 : SVN->getMaskElt(Elt);
  7692. InVec = (Idx < (int)NumElems) ? InVec.getOperand(0) : InVec.getOperand(1);
  7693. if (InVec.getOpcode() == ISD::BITCAST) {
  7694. // Don't duplicate a load with other uses.
  7695. if (!InVec.hasOneUse())
  7696. return SDValue();
  7697. InVec = InVec.getOperand(0);
  7698. }
  7699. if (ISD::isNormalLoad(InVec.getNode())) {
  7700. LN0 = cast<LoadSDNode>(InVec);
  7701. Elt = (Idx < (int)NumElems) ? Idx : Idx - (int)NumElems;
  7702. }
  7703. }
  7704. // Make sure we found a non-volatile load and the extractelement is
  7705. // the only use.
  7706. if (!LN0 || !LN0->hasNUsesOfValue(1,0) || LN0->isVolatile())
  7707. return SDValue();
  7708. // If Idx was -1 above, Elt is going to be -1, so just return undef.
  7709. if (Elt == -1)
  7710. return DAG.getUNDEF(LVT);
  7711. unsigned Align = LN0->getAlignment();
  7712. if (NewLoad) {
  7713. // Check the resultant load doesn't need a higher alignment than the
  7714. // original load.
  7715. unsigned NewAlign =
  7716. TLI.getDataLayout()
  7717. ->getABITypeAlignment(LVT.getTypeForEVT(*DAG.getContext()));
  7718. if (NewAlign > Align || !TLI.isOperationLegalOrCustom(ISD::LOAD, LVT))
  7719. return SDValue();
  7720. Align = NewAlign;
  7721. }
  7722. SDValue NewPtr = LN0->getBasePtr();
  7723. unsigned PtrOff = 0;
  7724. if (Elt) {
  7725. PtrOff = LVT.getSizeInBits() * Elt / 8;
  7726. EVT PtrType = NewPtr.getValueType();
  7727. if (TLI.isBigEndian())
  7728. PtrOff = VT.getSizeInBits() / 8 - PtrOff;
  7729. NewPtr = DAG.getNode(ISD::ADD, N->getDebugLoc(), PtrType, NewPtr,
  7730. DAG.getConstant(PtrOff, PtrType));
  7731. }
  7732. // The replacement we need to do here is a little tricky: we need to
  7733. // replace an extractelement of a load with a load.
  7734. // Use ReplaceAllUsesOfValuesWith to do the replacement.
  7735. // Note that this replacement assumes that the extractvalue is the only
  7736. // use of the load; that's okay because we don't want to perform this
  7737. // transformation in other cases anyway.
  7738. SDValue Load;
  7739. SDValue Chain;
  7740. if (NVT.bitsGT(LVT)) {
  7741. // If the result type of vextract is wider than the load, then issue an
  7742. // extending load instead.
  7743. ISD::LoadExtType ExtType = TLI.isLoadExtLegal(ISD::ZEXTLOAD, LVT)
  7744. ? ISD::ZEXTLOAD : ISD::EXTLOAD;
  7745. Load = DAG.getExtLoad(ExtType, N->getDebugLoc(), NVT, LN0->getChain(),
  7746. NewPtr, LN0->getPointerInfo().getWithOffset(PtrOff),
  7747. LVT, LN0->isVolatile(), LN0->isNonTemporal(),Align);
  7748. Chain = Load.getValue(1);
  7749. } else {
  7750. Load = DAG.getLoad(LVT, N->getDebugLoc(), LN0->getChain(), NewPtr,
  7751. LN0->getPointerInfo().getWithOffset(PtrOff),
  7752. LN0->isVolatile(), LN0->isNonTemporal(),
  7753. LN0->isInvariant(), Align);
  7754. Chain = Load.getValue(1);
  7755. if (NVT.bitsLT(LVT))
  7756. Load = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), NVT, Load);
  7757. else
  7758. Load = DAG.getNode(ISD::BITCAST, N->getDebugLoc(), NVT, Load);
  7759. }
  7760. WorkListRemover DeadNodes(*this);
  7761. SDValue From[] = { SDValue(N, 0), SDValue(LN0,1) };
  7762. SDValue To[] = { Load, Chain };
  7763. DAG.ReplaceAllUsesOfValuesWith(From, To, 2);
  7764. // Since we're explcitly calling ReplaceAllUses, add the new node to the
  7765. // worklist explicitly as well.
  7766. AddToWorkList(Load.getNode());
  7767. AddUsersToWorkList(Load.getNode()); // Add users too
  7768. // Make sure to revisit this node to clean it up; it will usually be dead.
  7769. AddToWorkList(N);
  7770. return SDValue(N, 0);
  7771. }
  7772. return SDValue();
  7773. }
  7774. // Simplify (build_vec (ext )) to (bitcast (build_vec ))
  7775. SDValue DAGCombiner::reduceBuildVecExtToExtBuildVec(SDNode *N) {
  7776. // We perform this optimization post type-legalization because
  7777. // the type-legalizer often scalarizes integer-promoted vectors.
  7778. // Performing this optimization before may create bit-casts which
  7779. // will be type-legalized to complex code sequences.
  7780. // We perform this optimization only before the operation legalizer because we
  7781. // may introduce illegal operations.
  7782. if (Level != AfterLegalizeVectorOps && Level != AfterLegalizeTypes)
  7783. return SDValue();
  7784. unsigned NumInScalars = N->getNumOperands();
  7785. DebugLoc dl = N->getDebugLoc();
  7786. EVT VT = N->getValueType(0);
  7787. // Check to see if this is a BUILD_VECTOR of a bunch of values
  7788. // which come from any_extend or zero_extend nodes. If so, we can create
  7789. // a new BUILD_VECTOR using bit-casts which may enable other BUILD_VECTOR
  7790. // optimizations. We do not handle sign-extend because we can't fill the sign
  7791. // using shuffles.
  7792. EVT SourceType = MVT::Other;
  7793. bool AllAnyExt = true;
  7794. for (unsigned i = 0; i != NumInScalars; ++i) {
  7795. SDValue In = N->getOperand(i);
  7796. // Ignore undef inputs.
  7797. if (In.getOpcode() == ISD::UNDEF) continue;
  7798. bool AnyExt = In.getOpcode() == ISD::ANY_EXTEND;
  7799. bool ZeroExt = In.getOpcode() == ISD::ZERO_EXTEND;
  7800. // Abort if the element is not an extension.
  7801. if (!ZeroExt && !AnyExt) {
  7802. SourceType = MVT::Other;
  7803. break;
  7804. }
  7805. // The input is a ZeroExt or AnyExt. Check the original type.
  7806. EVT InTy = In.getOperand(0).getValueType();
  7807. // Check that all of the widened source types are the same.
  7808. if (SourceType == MVT::Other)
  7809. // First time.
  7810. SourceType = InTy;
  7811. else if (InTy != SourceType) {
  7812. // Multiple income types. Abort.
  7813. SourceType = MVT::Other;
  7814. break;
  7815. }
  7816. // Check if all of the extends are ANY_EXTENDs.
  7817. AllAnyExt &= AnyExt;
  7818. }
  7819. // In order to have valid types, all of the inputs must be extended from the
  7820. // same source type and all of the inputs must be any or zero extend.
  7821. // Scalar sizes must be a power of two.
  7822. EVT OutScalarTy = VT.getScalarType();
  7823. bool ValidTypes = SourceType != MVT::Other &&
  7824. isPowerOf2_32(OutScalarTy.getSizeInBits()) &&
  7825. isPowerOf2_32(SourceType.getSizeInBits());
  7826. // Create a new simpler BUILD_VECTOR sequence which other optimizations can
  7827. // turn into a single shuffle instruction.
  7828. if (!ValidTypes)
  7829. return SDValue();
  7830. bool isLE = TLI.isLittleEndian();
  7831. unsigned ElemRatio = OutScalarTy.getSizeInBits()/SourceType.getSizeInBits();
  7832. assert(ElemRatio > 1 && "Invalid element size ratio");
  7833. SDValue Filler = AllAnyExt ? DAG.getUNDEF(SourceType):
  7834. DAG.getConstant(0, SourceType);
  7835. unsigned NewBVElems = ElemRatio * VT.getVectorNumElements();
  7836. SmallVector<SDValue, 8> Ops(NewBVElems, Filler);
  7837. // Populate the new build_vector
  7838. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  7839. SDValue Cast = N->getOperand(i);
  7840. assert((Cast.getOpcode() == ISD::ANY_EXTEND ||
  7841. Cast.getOpcode() == ISD::ZERO_EXTEND ||
  7842. Cast.getOpcode() == ISD::UNDEF) && "Invalid cast opcode");
  7843. SDValue In;
  7844. if (Cast.getOpcode() == ISD::UNDEF)
  7845. In = DAG.getUNDEF(SourceType);
  7846. else
  7847. In = Cast->getOperand(0);
  7848. unsigned Index = isLE ? (i * ElemRatio) :
  7849. (i * ElemRatio + (ElemRatio - 1));
  7850. assert(Index < Ops.size() && "Invalid index");
  7851. Ops[Index] = In;
  7852. }
  7853. // The type of the new BUILD_VECTOR node.
  7854. EVT VecVT = EVT::getVectorVT(*DAG.getContext(), SourceType, NewBVElems);
  7855. assert(VecVT.getSizeInBits() == VT.getSizeInBits() &&
  7856. "Invalid vector size");
  7857. // Check if the new vector type is legal.
  7858. if (!isTypeLegal(VecVT)) return SDValue();
  7859. // Make the new BUILD_VECTOR.
  7860. SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, VecVT, &Ops[0], Ops.size());
  7861. // The new BUILD_VECTOR node has the potential to be further optimized.
  7862. AddToWorkList(BV.getNode());
  7863. // Bitcast to the desired type.
  7864. return DAG.getNode(ISD::BITCAST, dl, VT, BV);
  7865. }
  7866. SDValue DAGCombiner::reduceBuildVecConvertToConvertBuildVec(SDNode *N) {
  7867. EVT VT = N->getValueType(0);
  7868. unsigned NumInScalars = N->getNumOperands();
  7869. DebugLoc dl = N->getDebugLoc();
  7870. EVT SrcVT = MVT::Other;
  7871. unsigned Opcode = ISD::DELETED_NODE;
  7872. unsigned NumDefs = 0;
  7873. for (unsigned i = 0; i != NumInScalars; ++i) {
  7874. SDValue In = N->getOperand(i);
  7875. unsigned Opc = In.getOpcode();
  7876. if (Opc == ISD::UNDEF)
  7877. continue;
  7878. // If all scalar values are floats and converted from integers.
  7879. if (Opcode == ISD::DELETED_NODE &&
  7880. (Opc == ISD::UINT_TO_FP || Opc == ISD::SINT_TO_FP)) {
  7881. Opcode = Opc;
  7882. }
  7883. if (Opc != Opcode)
  7884. return SDValue();
  7885. EVT InVT = In.getOperand(0).getValueType();
  7886. // If all scalar values are typed differently, bail out. It's chosen to
  7887. // simplify BUILD_VECTOR of integer types.
  7888. if (SrcVT == MVT::Other)
  7889. SrcVT = InVT;
  7890. if (SrcVT != InVT)
  7891. return SDValue();
  7892. NumDefs++;
  7893. }
  7894. // If the vector has just one element defined, it's not worth to fold it into
  7895. // a vectorized one.
  7896. if (NumDefs < 2)
  7897. return SDValue();
  7898. assert((Opcode == ISD::UINT_TO_FP || Opcode == ISD::SINT_TO_FP)
  7899. && "Should only handle conversion from integer to float.");
  7900. assert(SrcVT != MVT::Other && "Cannot determine source type!");
  7901. EVT NVT = EVT::getVectorVT(*DAG.getContext(), SrcVT, NumInScalars);
  7902. if (!TLI.isOperationLegalOrCustom(Opcode, NVT))
  7903. return SDValue();
  7904. SmallVector<SDValue, 8> Opnds;
  7905. for (unsigned i = 0; i != NumInScalars; ++i) {
  7906. SDValue In = N->getOperand(i);
  7907. if (In.getOpcode() == ISD::UNDEF)
  7908. Opnds.push_back(DAG.getUNDEF(SrcVT));
  7909. else
  7910. Opnds.push_back(In.getOperand(0));
  7911. }
  7912. SDValue BV = DAG.getNode(ISD::BUILD_VECTOR, dl, NVT,
  7913. &Opnds[0], Opnds.size());
  7914. AddToWorkList(BV.getNode());
  7915. return DAG.getNode(Opcode, dl, VT, BV);
  7916. }
  7917. SDValue DAGCombiner::visitBUILD_VECTOR(SDNode *N) {
  7918. unsigned NumInScalars = N->getNumOperands();
  7919. DebugLoc dl = N->getDebugLoc();
  7920. EVT VT = N->getValueType(0);
  7921. // A vector built entirely of undefs is undef.
  7922. if (ISD::allOperandsUndef(N))
  7923. return DAG.getUNDEF(VT);
  7924. SDValue V = reduceBuildVecExtToExtBuildVec(N);
  7925. if (V.getNode())
  7926. return V;
  7927. V = reduceBuildVecConvertToConvertBuildVec(N);
  7928. if (V.getNode())
  7929. return V;
  7930. // Check to see if this is a BUILD_VECTOR of a bunch of EXTRACT_VECTOR_ELT
  7931. // operations. If so, and if the EXTRACT_VECTOR_ELT vector inputs come from
  7932. // at most two distinct vectors, turn this into a shuffle node.
  7933. // May only combine to shuffle after legalize if shuffle is legal.
  7934. if (LegalOperations &&
  7935. !TLI.isOperationLegalOrCustom(ISD::VECTOR_SHUFFLE, VT))
  7936. return SDValue();
  7937. SDValue VecIn1, VecIn2;
  7938. for (unsigned i = 0; i != NumInScalars; ++i) {
  7939. // Ignore undef inputs.
  7940. if (N->getOperand(i).getOpcode() == ISD::UNDEF) continue;
  7941. // If this input is something other than a EXTRACT_VECTOR_ELT with a
  7942. // constant index, bail out.
  7943. if (N->getOperand(i).getOpcode() != ISD::EXTRACT_VECTOR_ELT ||
  7944. !isa<ConstantSDNode>(N->getOperand(i).getOperand(1))) {
  7945. VecIn1 = VecIn2 = SDValue(0, 0);
  7946. break;
  7947. }
  7948. // We allow up to two distinct input vectors.
  7949. SDValue ExtractedFromVec = N->getOperand(i).getOperand(0);
  7950. if (ExtractedFromVec == VecIn1 || ExtractedFromVec == VecIn2)
  7951. continue;
  7952. if (VecIn1.getNode() == 0) {
  7953. VecIn1 = ExtractedFromVec;
  7954. } else if (VecIn2.getNode() == 0) {
  7955. VecIn2 = ExtractedFromVec;
  7956. } else {
  7957. // Too many inputs.
  7958. VecIn1 = VecIn2 = SDValue(0, 0);
  7959. break;
  7960. }
  7961. }
  7962. // If everything is good, we can make a shuffle operation.
  7963. if (VecIn1.getNode()) {
  7964. SmallVector<int, 8> Mask;
  7965. for (unsigned i = 0; i != NumInScalars; ++i) {
  7966. if (N->getOperand(i).getOpcode() == ISD::UNDEF) {
  7967. Mask.push_back(-1);
  7968. continue;
  7969. }
  7970. // If extracting from the first vector, just use the index directly.
  7971. SDValue Extract = N->getOperand(i);
  7972. SDValue ExtVal = Extract.getOperand(1);
  7973. if (Extract.getOperand(0) == VecIn1) {
  7974. unsigned ExtIndex = cast<ConstantSDNode>(ExtVal)->getZExtValue();
  7975. if (ExtIndex > VT.getVectorNumElements())
  7976. return SDValue();
  7977. Mask.push_back(ExtIndex);
  7978. continue;
  7979. }
  7980. // Otherwise, use InIdx + VecSize
  7981. unsigned Idx = cast<ConstantSDNode>(ExtVal)->getZExtValue();
  7982. Mask.push_back(Idx+NumInScalars);
  7983. }
  7984. // We can't generate a shuffle node with mismatched input and output types.
  7985. // Attempt to transform a single input vector to the correct type.
  7986. if ((VT != VecIn1.getValueType())) {
  7987. // We don't support shuffeling between TWO values of different types.
  7988. if (VecIn2.getNode() != 0)
  7989. return SDValue();
  7990. // We only support widening of vectors which are half the size of the
  7991. // output registers. For example XMM->YMM widening on X86 with AVX.
  7992. if (VecIn1.getValueType().getSizeInBits()*2 != VT.getSizeInBits())
  7993. return SDValue();
  7994. // If the input vector type has a different base type to the output
  7995. // vector type, bail out.
  7996. if (VecIn1.getValueType().getVectorElementType() !=
  7997. VT.getVectorElementType())
  7998. return SDValue();
  7999. // Widen the input vector by adding undef values.
  8000. VecIn1 = DAG.getNode(ISD::CONCAT_VECTORS, dl, VT,
  8001. VecIn1, DAG.getUNDEF(VecIn1.getValueType()));
  8002. }
  8003. // If VecIn2 is unused then change it to undef.
  8004. VecIn2 = VecIn2.getNode() ? VecIn2 : DAG.getUNDEF(VT);
  8005. // Check that we were able to transform all incoming values to the same
  8006. // type.
  8007. if (VecIn2.getValueType() != VecIn1.getValueType() ||
  8008. VecIn1.getValueType() != VT)
  8009. return SDValue();
  8010. // Only type-legal BUILD_VECTOR nodes are converted to shuffle nodes.
  8011. if (!isTypeLegal(VT))
  8012. return SDValue();
  8013. // Return the new VECTOR_SHUFFLE node.
  8014. SDValue Ops[2];
  8015. Ops[0] = VecIn1;
  8016. Ops[1] = VecIn2;
  8017. return DAG.getVectorShuffle(VT, dl, Ops[0], Ops[1], &Mask[0]);
  8018. }
  8019. return SDValue();
  8020. }
  8021. SDValue DAGCombiner::visitCONCAT_VECTORS(SDNode *N) {
  8022. // TODO: Check to see if this is a CONCAT_VECTORS of a bunch of
  8023. // EXTRACT_SUBVECTOR operations. If so, and if the EXTRACT_SUBVECTOR vector
  8024. // inputs come from at most two distinct vectors, turn this into a shuffle
  8025. // node.
  8026. // If we only have one input vector, we don't need to do any concatenation.
  8027. if (N->getNumOperands() == 1)
  8028. return N->getOperand(0);
  8029. // Check if all of the operands are undefs.
  8030. if (ISD::allOperandsUndef(N))
  8031. return DAG.getUNDEF(N->getValueType(0));
  8032. // Type legalization of vectors and DAG canonicalization of SHUFFLE_VECTOR
  8033. // nodes often generate nop CONCAT_VECTOR nodes.
  8034. // Scan the CONCAT_VECTOR operands and look for a CONCAT operations that
  8035. // place the incoming vectors at the exact same location.
  8036. SDValue SingleSource = SDValue();
  8037. unsigned PartNumElem = N->getOperand(0).getValueType().getVectorNumElements();
  8038. for (unsigned i = 0, e = N->getNumOperands(); i != e; ++i) {
  8039. SDValue Op = N->getOperand(i);
  8040. if (Op.getOpcode() == ISD::UNDEF)
  8041. continue;
  8042. // Check if this is the identity extract:
  8043. if (Op.getOpcode() != ISD::EXTRACT_SUBVECTOR)
  8044. return SDValue();
  8045. // Find the single incoming vector for the extract_subvector.
  8046. if (SingleSource.getNode()) {
  8047. if (Op.getOperand(0) != SingleSource)
  8048. return SDValue();
  8049. } else {
  8050. SingleSource = Op.getOperand(0);
  8051. // Check the source type is the same as the type of the result.
  8052. // If not, this concat may extend the vector, so we can not
  8053. // optimize it away.
  8054. if (SingleSource.getValueType() != N->getValueType(0))
  8055. return SDValue();
  8056. }
  8057. unsigned IdentityIndex = i * PartNumElem;
  8058. ConstantSDNode *CS = dyn_cast<ConstantSDNode>(Op.getOperand(1));
  8059. // The extract index must be constant.
  8060. if (!CS)
  8061. return SDValue();
  8062. // Check that we are reading from the identity index.
  8063. if (CS->getZExtValue() != IdentityIndex)
  8064. return SDValue();
  8065. }
  8066. if (SingleSource.getNode())
  8067. return SingleSource;
  8068. return SDValue();
  8069. }
  8070. SDValue DAGCombiner::visitEXTRACT_SUBVECTOR(SDNode* N) {
  8071. EVT NVT = N->getValueType(0);
  8072. SDValue V = N->getOperand(0);
  8073. if (V->getOpcode() == ISD::CONCAT_VECTORS) {
  8074. // Combine:
  8075. // (extract_subvec (concat V1, V2, ...), i)
  8076. // Into:
  8077. // Vi if possible
  8078. // Only operand 0 is checked as 'concat' assumes all inputs of the same type.
  8079. if (V->getOperand(0).getValueType() != NVT)
  8080. return SDValue();
  8081. unsigned Idx = dyn_cast<ConstantSDNode>(N->getOperand(1))->getZExtValue();
  8082. unsigned NumElems = NVT.getVectorNumElements();
  8083. assert((Idx % NumElems) == 0 &&
  8084. "IDX in concat is not a multiple of the result vector length.");
  8085. return V->getOperand(Idx / NumElems);
  8086. }
  8087. // Skip bitcasting
  8088. if (V->getOpcode() == ISD::BITCAST)
  8089. V = V.getOperand(0);
  8090. if (V->getOpcode() == ISD::INSERT_SUBVECTOR) {
  8091. DebugLoc dl = N->getDebugLoc();
  8092. // Handle only simple case where vector being inserted and vector
  8093. // being extracted are of same type, and are half size of larger vectors.
  8094. EVT BigVT = V->getOperand(0).getValueType();
  8095. EVT SmallVT = V->getOperand(1).getValueType();
  8096. if (!NVT.bitsEq(SmallVT) || NVT.getSizeInBits()*2 != BigVT.getSizeInBits())
  8097. return SDValue();
  8098. // Only handle cases where both indexes are constants with the same type.
  8099. ConstantSDNode *ExtIdx = dyn_cast<ConstantSDNode>(N->getOperand(1));
  8100. ConstantSDNode *InsIdx = dyn_cast<ConstantSDNode>(V->getOperand(2));
  8101. if (InsIdx && ExtIdx &&
  8102. InsIdx->getValueType(0).getSizeInBits() <= 64 &&
  8103. ExtIdx->getValueType(0).getSizeInBits() <= 64) {
  8104. // Combine:
  8105. // (extract_subvec (insert_subvec V1, V2, InsIdx), ExtIdx)
  8106. // Into:
  8107. // indices are equal or bit offsets are equal => V1
  8108. // otherwise => (extract_subvec V1, ExtIdx)
  8109. if (InsIdx->getZExtValue() * SmallVT.getScalarType().getSizeInBits() ==
  8110. ExtIdx->getZExtValue() * NVT.getScalarType().getSizeInBits())
  8111. return DAG.getNode(ISD::BITCAST, dl, NVT, V->getOperand(1));
  8112. return DAG.getNode(ISD::EXTRACT_SUBVECTOR, dl, NVT,
  8113. DAG.getNode(ISD::BITCAST, dl,
  8114. N->getOperand(0).getValueType(),
  8115. V->getOperand(0)), N->getOperand(1));
  8116. }
  8117. }
  8118. return SDValue();
  8119. }
  8120. // Tries to turn a shuffle of two CONCAT_VECTORS into a single concat.
  8121. static SDValue partitionShuffleOfConcats(SDNode *N, SelectionDAG &DAG) {
  8122. EVT VT = N->getValueType(0);
  8123. unsigned NumElts = VT.getVectorNumElements();
  8124. SDValue N0 = N->getOperand(0);
  8125. SDValue N1 = N->getOperand(1);
  8126. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
  8127. SmallVector<SDValue, 4> Ops;
  8128. EVT ConcatVT = N0.getOperand(0).getValueType();
  8129. unsigned NumElemsPerConcat = ConcatVT.getVectorNumElements();
  8130. unsigned NumConcats = NumElts / NumElemsPerConcat;
  8131. // Look at every vector that's inserted. We're looking for exact
  8132. // subvector-sized copies from a concatenated vector
  8133. for (unsigned I = 0; I != NumConcats; ++I) {
  8134. // Make sure we're dealing with a copy.
  8135. unsigned Begin = I * NumElemsPerConcat;
  8136. bool AllUndef = true, NoUndef = true;
  8137. for (unsigned J = Begin; J != Begin + NumElemsPerConcat; ++J) {
  8138. if (SVN->getMaskElt(J) >= 0)
  8139. AllUndef = false;
  8140. else
  8141. NoUndef = false;
  8142. }
  8143. if (NoUndef) {
  8144. if (SVN->getMaskElt(Begin) % NumElemsPerConcat != 0)
  8145. return SDValue();
  8146. for (unsigned J = 1; J != NumElemsPerConcat; ++J)
  8147. if (SVN->getMaskElt(Begin + J - 1) + 1 != SVN->getMaskElt(Begin + J))
  8148. return SDValue();
  8149. unsigned FirstElt = SVN->getMaskElt(Begin) / NumElemsPerConcat;
  8150. if (FirstElt < N0.getNumOperands())
  8151. Ops.push_back(N0.getOperand(FirstElt));
  8152. else
  8153. Ops.push_back(N1.getOperand(FirstElt - N0.getNumOperands()));
  8154. } else if (AllUndef) {
  8155. Ops.push_back(DAG.getUNDEF(N0.getOperand(0).getValueType()));
  8156. } else { // Mixed with general masks and undefs, can't do optimization.
  8157. return SDValue();
  8158. }
  8159. }
  8160. return DAG.getNode(ISD::CONCAT_VECTORS, N->getDebugLoc(), VT, Ops.data(),
  8161. Ops.size());
  8162. }
  8163. SDValue DAGCombiner::visitVECTOR_SHUFFLE(SDNode *N) {
  8164. EVT VT = N->getValueType(0);
  8165. unsigned NumElts = VT.getVectorNumElements();
  8166. SDValue N0 = N->getOperand(0);
  8167. SDValue N1 = N->getOperand(1);
  8168. assert(N0.getValueType() == VT && "Vector shuffle must be normalized in DAG");
  8169. // Canonicalize shuffle undef, undef -> undef
  8170. if (N0.getOpcode() == ISD::UNDEF && N1.getOpcode() == ISD::UNDEF)
  8171. return DAG.getUNDEF(VT);
  8172. ShuffleVectorSDNode *SVN = cast<ShuffleVectorSDNode>(N);
  8173. // Canonicalize shuffle v, v -> v, undef
  8174. if (N0 == N1) {
  8175. SmallVector<int, 8> NewMask;
  8176. for (unsigned i = 0; i != NumElts; ++i) {
  8177. int Idx = SVN->getMaskElt(i);
  8178. if (Idx >= (int)NumElts) Idx -= NumElts;
  8179. NewMask.push_back(Idx);
  8180. }
  8181. return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, DAG.getUNDEF(VT),
  8182. &NewMask[0]);
  8183. }
  8184. // Canonicalize shuffle undef, v -> v, undef. Commute the shuffle mask.
  8185. if (N0.getOpcode() == ISD::UNDEF) {
  8186. SmallVector<int, 8> NewMask;
  8187. for (unsigned i = 0; i != NumElts; ++i) {
  8188. int Idx = SVN->getMaskElt(i);
  8189. if (Idx >= 0) {
  8190. if (Idx < (int)NumElts)
  8191. Idx += NumElts;
  8192. else
  8193. Idx -= NumElts;
  8194. }
  8195. NewMask.push_back(Idx);
  8196. }
  8197. return DAG.getVectorShuffle(VT, N->getDebugLoc(), N1, DAG.getUNDEF(VT),
  8198. &NewMask[0]);
  8199. }
  8200. // Remove references to rhs if it is undef
  8201. if (N1.getOpcode() == ISD::UNDEF) {
  8202. bool Changed = false;
  8203. SmallVector<int, 8> NewMask;
  8204. for (unsigned i = 0; i != NumElts; ++i) {
  8205. int Idx = SVN->getMaskElt(i);
  8206. if (Idx >= (int)NumElts) {
  8207. Idx = -1;
  8208. Changed = true;
  8209. }
  8210. NewMask.push_back(Idx);
  8211. }
  8212. if (Changed)
  8213. return DAG.getVectorShuffle(VT, N->getDebugLoc(), N0, N1, &NewMask[0]);
  8214. }
  8215. // If it is a splat, check if the argument vector is another splat or a
  8216. // build_vector with all scalar elements the same.
  8217. if (SVN->isSplat() && SVN->getSplatIndex() < (int)NumElts) {
  8218. SDNode *V = N0.getNode();
  8219. // If this is a bit convert that changes the element type of the vector but
  8220. // not the number of vector elements, look through it. Be careful not to
  8221. // look though conversions that change things like v4f32 to v2f64.
  8222. if (V->getOpcode() == ISD::BITCAST) {
  8223. SDValue ConvInput = V->getOperand(0);
  8224. if (ConvInput.getValueType().isVector() &&
  8225. ConvInput.getValueType().getVectorNumElements() == NumElts)
  8226. V = ConvInput.getNode();
  8227. }
  8228. if (V->getOpcode() == ISD::BUILD_VECTOR) {
  8229. assert(V->getNumOperands() == NumElts &&
  8230. "BUILD_VECTOR has wrong number of operands");
  8231. SDValue Base;
  8232. bool AllSame = true;
  8233. for (unsigned i = 0; i != NumElts; ++i) {
  8234. if (V->getOperand(i).getOpcode() != ISD::UNDEF) {
  8235. Base = V->getOperand(i);
  8236. break;
  8237. }
  8238. }
  8239. // Splat of <u, u, u, u>, return <u, u, u, u>
  8240. if (!Base.getNode())
  8241. return N0;
  8242. for (unsigned i = 0; i != NumElts; ++i) {
  8243. if (V->getOperand(i) != Base) {
  8244. AllSame = false;
  8245. break;
  8246. }
  8247. }
  8248. // Splat of <x, x, x, x>, return <x, x, x, x>
  8249. if (AllSame)
  8250. return N0;
  8251. }
  8252. }
  8253. if (N0.getOpcode() == ISD::CONCAT_VECTORS &&
  8254. Level < AfterLegalizeVectorOps &&
  8255. (N1.getOpcode() == ISD::UNDEF ||
  8256. (N1.getOpcode() == ISD::CONCAT_VECTORS &&
  8257. N0.getOperand(0).getValueType() == N1.getOperand(0).getValueType()))) {
  8258. SDValue V = partitionShuffleOfConcats(N, DAG);
  8259. if (V.getNode())
  8260. return V;
  8261. }
  8262. // If this shuffle node is simply a swizzle of another shuffle node,
  8263. // and it reverses the swizzle of the previous shuffle then we can
  8264. // optimize shuffle(shuffle(x, undef), undef) -> x.
  8265. if (N0.getOpcode() == ISD::VECTOR_SHUFFLE && Level < AfterLegalizeDAG &&
  8266. N1.getOpcode() == ISD::UNDEF) {
  8267. ShuffleVectorSDNode *OtherSV = cast<ShuffleVectorSDNode>(N0);
  8268. // Shuffle nodes can only reverse shuffles with a single non-undef value.
  8269. if (N0.getOperand(1).getOpcode() != ISD::UNDEF)
  8270. return SDValue();
  8271. // The incoming shuffle must be of the same type as the result of the
  8272. // current shuffle.
  8273. assert(OtherSV->getOperand(0).getValueType() == VT &&
  8274. "Shuffle types don't match");
  8275. for (unsigned i = 0; i != NumElts; ++i) {
  8276. int Idx = SVN->getMaskElt(i);
  8277. assert(Idx < (int)NumElts && "Index references undef operand");
  8278. // Next, this index comes from the first value, which is the incoming
  8279. // shuffle. Adopt the incoming index.
  8280. if (Idx >= 0)
  8281. Idx = OtherSV->getMaskElt(Idx);
  8282. // The combined shuffle must map each index to itself.
  8283. if (Idx >= 0 && (unsigned)Idx != i)
  8284. return SDValue();
  8285. }
  8286. return OtherSV->getOperand(0);
  8287. }
  8288. return SDValue();
  8289. }
  8290. /// XformToShuffleWithZero - Returns a vector_shuffle if it able to transform
  8291. /// an AND to a vector_shuffle with the destination vector and a zero vector.
  8292. /// e.g. AND V, <0xffffffff, 0, 0xffffffff, 0>. ==>
  8293. /// vector_shuffle V, Zero, <0, 4, 2, 4>
  8294. SDValue DAGCombiner::XformToShuffleWithZero(SDNode *N) {
  8295. EVT VT = N->getValueType(0);
  8296. DebugLoc dl = N->getDebugLoc();
  8297. SDValue LHS = N->getOperand(0);
  8298. SDValue RHS = N->getOperand(1);
  8299. if (N->getOpcode() == ISD::AND) {
  8300. if (RHS.getOpcode() == ISD::BITCAST)
  8301. RHS = RHS.getOperand(0);
  8302. if (RHS.getOpcode() == ISD::BUILD_VECTOR) {
  8303. SmallVector<int, 8> Indices;
  8304. unsigned NumElts = RHS.getNumOperands();
  8305. for (unsigned i = 0; i != NumElts; ++i) {
  8306. SDValue Elt = RHS.getOperand(i);
  8307. if (!isa<ConstantSDNode>(Elt))
  8308. return SDValue();
  8309. if (cast<ConstantSDNode>(Elt)->isAllOnesValue())
  8310. Indices.push_back(i);
  8311. else if (cast<ConstantSDNode>(Elt)->isNullValue())
  8312. Indices.push_back(NumElts);
  8313. else
  8314. return SDValue();
  8315. }
  8316. // Let's see if the target supports this vector_shuffle.
  8317. EVT RVT = RHS.getValueType();
  8318. if (!TLI.isVectorClearMaskLegal(Indices, RVT))
  8319. return SDValue();
  8320. // Return the new VECTOR_SHUFFLE node.
  8321. EVT EltVT = RVT.getVectorElementType();
  8322. SmallVector<SDValue,8> ZeroOps(RVT.getVectorNumElements(),
  8323. DAG.getConstant(0, EltVT));
  8324. SDValue Zero = DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
  8325. RVT, &ZeroOps[0], ZeroOps.size());
  8326. LHS = DAG.getNode(ISD::BITCAST, dl, RVT, LHS);
  8327. SDValue Shuf = DAG.getVectorShuffle(RVT, dl, LHS, Zero, &Indices[0]);
  8328. return DAG.getNode(ISD::BITCAST, dl, VT, Shuf);
  8329. }
  8330. }
  8331. return SDValue();
  8332. }
  8333. /// SimplifyVBinOp - Visit a binary vector operation, like ADD.
  8334. SDValue DAGCombiner::SimplifyVBinOp(SDNode *N) {
  8335. assert(N->getValueType(0).isVector() &&
  8336. "SimplifyVBinOp only works on vectors!");
  8337. SDValue LHS = N->getOperand(0);
  8338. SDValue RHS = N->getOperand(1);
  8339. SDValue Shuffle = XformToShuffleWithZero(N);
  8340. if (Shuffle.getNode()) return Shuffle;
  8341. // If the LHS and RHS are BUILD_VECTOR nodes, see if we can constant fold
  8342. // this operation.
  8343. if (LHS.getOpcode() == ISD::BUILD_VECTOR &&
  8344. RHS.getOpcode() == ISD::BUILD_VECTOR) {
  8345. SmallVector<SDValue, 8> Ops;
  8346. for (unsigned i = 0, e = LHS.getNumOperands(); i != e; ++i) {
  8347. SDValue LHSOp = LHS.getOperand(i);
  8348. SDValue RHSOp = RHS.getOperand(i);
  8349. // If these two elements can't be folded, bail out.
  8350. if ((LHSOp.getOpcode() != ISD::UNDEF &&
  8351. LHSOp.getOpcode() != ISD::Constant &&
  8352. LHSOp.getOpcode() != ISD::ConstantFP) ||
  8353. (RHSOp.getOpcode() != ISD::UNDEF &&
  8354. RHSOp.getOpcode() != ISD::Constant &&
  8355. RHSOp.getOpcode() != ISD::ConstantFP))
  8356. break;
  8357. // Can't fold divide by zero.
  8358. if (N->getOpcode() == ISD::SDIV || N->getOpcode() == ISD::UDIV ||
  8359. N->getOpcode() == ISD::FDIV) {
  8360. if ((RHSOp.getOpcode() == ISD::Constant &&
  8361. cast<ConstantSDNode>(RHSOp.getNode())->isNullValue()) ||
  8362. (RHSOp.getOpcode() == ISD::ConstantFP &&
  8363. cast<ConstantFPSDNode>(RHSOp.getNode())->getValueAPF().isZero()))
  8364. break;
  8365. }
  8366. EVT VT = LHSOp.getValueType();
  8367. EVT RVT = RHSOp.getValueType();
  8368. if (RVT != VT) {
  8369. // Integer BUILD_VECTOR operands may have types larger than the element
  8370. // size (e.g., when the element type is not legal). Prior to type
  8371. // legalization, the types may not match between the two BUILD_VECTORS.
  8372. // Truncate one of the operands to make them match.
  8373. if (RVT.getSizeInBits() > VT.getSizeInBits()) {
  8374. RHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), VT, RHSOp);
  8375. } else {
  8376. LHSOp = DAG.getNode(ISD::TRUNCATE, N->getDebugLoc(), RVT, LHSOp);
  8377. VT = RVT;
  8378. }
  8379. }
  8380. SDValue FoldOp = DAG.getNode(N->getOpcode(), LHS.getDebugLoc(), VT,
  8381. LHSOp, RHSOp);
  8382. if (FoldOp.getOpcode() != ISD::UNDEF &&
  8383. FoldOp.getOpcode() != ISD::Constant &&
  8384. FoldOp.getOpcode() != ISD::ConstantFP)
  8385. break;
  8386. Ops.push_back(FoldOp);
  8387. AddToWorkList(FoldOp.getNode());
  8388. }
  8389. if (Ops.size() == LHS.getNumOperands())
  8390. return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
  8391. LHS.getValueType(), &Ops[0], Ops.size());
  8392. }
  8393. return SDValue();
  8394. }
  8395. /// SimplifyVUnaryOp - Visit a binary vector operation, like FABS/FNEG.
  8396. SDValue DAGCombiner::SimplifyVUnaryOp(SDNode *N) {
  8397. assert(N->getValueType(0).isVector() &&
  8398. "SimplifyVUnaryOp only works on vectors!");
  8399. SDValue N0 = N->getOperand(0);
  8400. if (N0.getOpcode() != ISD::BUILD_VECTOR)
  8401. return SDValue();
  8402. // Operand is a BUILD_VECTOR node, see if we can constant fold it.
  8403. SmallVector<SDValue, 8> Ops;
  8404. for (unsigned i = 0, e = N0.getNumOperands(); i != e; ++i) {
  8405. SDValue Op = N0.getOperand(i);
  8406. if (Op.getOpcode() != ISD::UNDEF &&
  8407. Op.getOpcode() != ISD::ConstantFP)
  8408. break;
  8409. EVT EltVT = Op.getValueType();
  8410. SDValue FoldOp = DAG.getNode(N->getOpcode(), N0.getDebugLoc(), EltVT, Op);
  8411. if (FoldOp.getOpcode() != ISD::UNDEF &&
  8412. FoldOp.getOpcode() != ISD::ConstantFP)
  8413. break;
  8414. Ops.push_back(FoldOp);
  8415. AddToWorkList(FoldOp.getNode());
  8416. }
  8417. if (Ops.size() != N0.getNumOperands())
  8418. return SDValue();
  8419. return DAG.getNode(ISD::BUILD_VECTOR, N->getDebugLoc(),
  8420. N0.getValueType(), &Ops[0], Ops.size());
  8421. }
  8422. SDValue DAGCombiner::SimplifySelect(DebugLoc DL, SDValue N0,
  8423. SDValue N1, SDValue N2){
  8424. assert(N0.getOpcode() ==ISD::SETCC && "First argument must be a SetCC node!");
  8425. SDValue SCC = SimplifySelectCC(DL, N0.getOperand(0), N0.getOperand(1), N1, N2,
  8426. cast<CondCodeSDNode>(N0.getOperand(2))->get());
  8427. // If we got a simplified select_cc node back from SimplifySelectCC, then
  8428. // break it down into a new SETCC node, and a new SELECT node, and then return
  8429. // the SELECT node, since we were called with a SELECT node.
  8430. if (SCC.getNode()) {
  8431. // Check to see if we got a select_cc back (to turn into setcc/select).
  8432. // Otherwise, just return whatever node we got back, like fabs.
  8433. if (SCC.getOpcode() == ISD::SELECT_CC) {
  8434. SDValue SETCC = DAG.getNode(ISD::SETCC, N0.getDebugLoc(),
  8435. N0.getValueType(),
  8436. SCC.getOperand(0), SCC.getOperand(1),
  8437. SCC.getOperand(4));
  8438. AddToWorkList(SETCC.getNode());
  8439. return DAG.getNode(ISD::SELECT, SCC.getDebugLoc(), SCC.getValueType(),
  8440. SCC.getOperand(2), SCC.getOperand(3), SETCC);
  8441. }
  8442. return SCC;
  8443. }
  8444. return SDValue();
  8445. }
  8446. /// SimplifySelectOps - Given a SELECT or a SELECT_CC node, where LHS and RHS
  8447. /// are the two values being selected between, see if we can simplify the
  8448. /// select. Callers of this should assume that TheSelect is deleted if this
  8449. /// returns true. As such, they should return the appropriate thing (e.g. the
  8450. /// node) back to the top-level of the DAG combiner loop to avoid it being
  8451. /// looked at.
  8452. bool DAGCombiner::SimplifySelectOps(SDNode *TheSelect, SDValue LHS,
  8453. SDValue RHS) {
  8454. // Cannot simplify select with vector condition
  8455. if (TheSelect->getOperand(0).getValueType().isVector()) return false;
  8456. // If this is a select from two identical things, try to pull the operation
  8457. // through the select.
  8458. if (LHS.getOpcode() != RHS.getOpcode() ||
  8459. !LHS.hasOneUse() || !RHS.hasOneUse())
  8460. return false;
  8461. // If this is a load and the token chain is identical, replace the select
  8462. // of two loads with a load through a select of the address to load from.
  8463. // This triggers in things like "select bool X, 10.0, 123.0" after the FP
  8464. // constants have been dropped into the constant pool.
  8465. if (LHS.getOpcode() == ISD::LOAD) {
  8466. LoadSDNode *LLD = cast<LoadSDNode>(LHS);
  8467. LoadSDNode *RLD = cast<LoadSDNode>(RHS);
  8468. // Token chains must be identical.
  8469. if (LHS.getOperand(0) != RHS.getOperand(0) ||
  8470. // Do not let this transformation reduce the number of volatile loads.
  8471. LLD->isVolatile() || RLD->isVolatile() ||
  8472. // If this is an EXTLOAD, the VT's must match.
  8473. LLD->getMemoryVT() != RLD->getMemoryVT() ||
  8474. // If this is an EXTLOAD, the kind of extension must match.
  8475. (LLD->getExtensionType() != RLD->getExtensionType() &&
  8476. // The only exception is if one of the extensions is anyext.
  8477. LLD->getExtensionType() != ISD::EXTLOAD &&
  8478. RLD->getExtensionType() != ISD::EXTLOAD) ||
  8479. // FIXME: this discards src value information. This is
  8480. // over-conservative. It would be beneficial to be able to remember
  8481. // both potential memory locations. Since we are discarding
  8482. // src value info, don't do the transformation if the memory
  8483. // locations are not in the default address space.
  8484. LLD->getPointerInfo().getAddrSpace() != 0 ||
  8485. RLD->getPointerInfo().getAddrSpace() != 0 ||
  8486. !TLI.isOperationLegalOrCustom(TheSelect->getOpcode(),
  8487. LLD->getBasePtr().getValueType()))
  8488. return false;
  8489. // Check that the select condition doesn't reach either load. If so,
  8490. // folding this will induce a cycle into the DAG. If not, this is safe to
  8491. // xform, so create a select of the addresses.
  8492. SDValue Addr;
  8493. if (TheSelect->getOpcode() == ISD::SELECT) {
  8494. SDNode *CondNode = TheSelect->getOperand(0).getNode();
  8495. if ((LLD->hasAnyUseOfValue(1) && LLD->isPredecessorOf(CondNode)) ||
  8496. (RLD->hasAnyUseOfValue(1) && RLD->isPredecessorOf(CondNode)))
  8497. return false;
  8498. // The loads must not depend on one another.
  8499. if (LLD->isPredecessorOf(RLD) ||
  8500. RLD->isPredecessorOf(LLD))
  8501. return false;
  8502. Addr = DAG.getNode(ISD::SELECT, TheSelect->getDebugLoc(),
  8503. LLD->getBasePtr().getValueType(),
  8504. TheSelect->getOperand(0), LLD->getBasePtr(),
  8505. RLD->getBasePtr());
  8506. } else { // Otherwise SELECT_CC
  8507. SDNode *CondLHS = TheSelect->getOperand(0).getNode();
  8508. SDNode *CondRHS = TheSelect->getOperand(1).getNode();
  8509. if ((LLD->hasAnyUseOfValue(1) &&
  8510. (LLD->isPredecessorOf(CondLHS) || LLD->isPredecessorOf(CondRHS))) ||
  8511. (RLD->hasAnyUseOfValue(1) &&
  8512. (RLD->isPredecessorOf(CondLHS) || RLD->isPredecessorOf(CondRHS))))
  8513. return false;
  8514. Addr = DAG.getNode(ISD::SELECT_CC, TheSelect->getDebugLoc(),
  8515. LLD->getBasePtr().getValueType(),
  8516. TheSelect->getOperand(0),
  8517. TheSelect->getOperand(1),
  8518. LLD->getBasePtr(), RLD->getBasePtr(),
  8519. TheSelect->getOperand(4));
  8520. }
  8521. SDValue Load;
  8522. if (LLD->getExtensionType() == ISD::NON_EXTLOAD) {
  8523. Load = DAG.getLoad(TheSelect->getValueType(0),
  8524. TheSelect->getDebugLoc(),
  8525. // FIXME: Discards pointer info.
  8526. LLD->getChain(), Addr, MachinePointerInfo(),
  8527. LLD->isVolatile(), LLD->isNonTemporal(),
  8528. LLD->isInvariant(), LLD->getAlignment());
  8529. } else {
  8530. Load = DAG.getExtLoad(LLD->getExtensionType() == ISD::EXTLOAD ?
  8531. RLD->getExtensionType() : LLD->getExtensionType(),
  8532. TheSelect->getDebugLoc(),
  8533. TheSelect->getValueType(0),
  8534. // FIXME: Discards pointer info.
  8535. LLD->getChain(), Addr, MachinePointerInfo(),
  8536. LLD->getMemoryVT(), LLD->isVolatile(),
  8537. LLD->isNonTemporal(), LLD->getAlignment());
  8538. }
  8539. // Users of the select now use the result of the load.
  8540. CombineTo(TheSelect, Load);
  8541. // Users of the old loads now use the new load's chain. We know the
  8542. // old-load value is dead now.
  8543. CombineTo(LHS.getNode(), Load.getValue(0), Load.getValue(1));
  8544. CombineTo(RHS.getNode(), Load.getValue(0), Load.getValue(1));
  8545. return true;
  8546. }
  8547. return false;
  8548. }
  8549. /// SimplifySelectCC - Simplify an expression of the form (N0 cond N1) ? N2 : N3
  8550. /// where 'cond' is the comparison specified by CC.
  8551. SDValue DAGCombiner::SimplifySelectCC(DebugLoc DL, SDValue N0, SDValue N1,
  8552. SDValue N2, SDValue N3,
  8553. ISD::CondCode CC, bool NotExtCompare) {
  8554. // (x ? y : y) -> y.
  8555. if (N2 == N3) return N2;
  8556. EVT VT = N2.getValueType();
  8557. ConstantSDNode *N1C = dyn_cast<ConstantSDNode>(N1.getNode());
  8558. ConstantSDNode *N2C = dyn_cast<ConstantSDNode>(N2.getNode());
  8559. ConstantSDNode *N3C = dyn_cast<ConstantSDNode>(N3.getNode());
  8560. // Determine if the condition we're dealing with is constant
  8561. SDValue SCC = SimplifySetCC(getSetCCResultType(N0.getValueType()),
  8562. N0, N1, CC, DL, false);
  8563. if (SCC.getNode()) AddToWorkList(SCC.getNode());
  8564. ConstantSDNode *SCCC = dyn_cast_or_null<ConstantSDNode>(SCC.getNode());
  8565. // fold select_cc true, x, y -> x
  8566. if (SCCC && !SCCC->isNullValue())
  8567. return N2;
  8568. // fold select_cc false, x, y -> y
  8569. if (SCCC && SCCC->isNullValue())
  8570. return N3;
  8571. // Check to see if we can simplify the select into an fabs node
  8572. if (ConstantFPSDNode *CFP = dyn_cast<ConstantFPSDNode>(N1)) {
  8573. // Allow either -0.0 or 0.0
  8574. if (CFP->getValueAPF().isZero()) {
  8575. // select (setg[te] X, +/-0.0), X, fneg(X) -> fabs
  8576. if ((CC == ISD::SETGE || CC == ISD::SETGT) &&
  8577. N0 == N2 && N3.getOpcode() == ISD::FNEG &&
  8578. N2 == N3.getOperand(0))
  8579. return DAG.getNode(ISD::FABS, DL, VT, N0);
  8580. // select (setl[te] X, +/-0.0), fneg(X), X -> fabs
  8581. if ((CC == ISD::SETLT || CC == ISD::SETLE) &&
  8582. N0 == N3 && N2.getOpcode() == ISD::FNEG &&
  8583. N2.getOperand(0) == N3)
  8584. return DAG.getNode(ISD::FABS, DL, VT, N3);
  8585. }
  8586. }
  8587. // Turn "(a cond b) ? 1.0f : 2.0f" into "load (tmp + ((a cond b) ? 0 : 4)"
  8588. // where "tmp" is a constant pool entry containing an array with 1.0 and 2.0
  8589. // in it. This is a win when the constant is not otherwise available because
  8590. // it replaces two constant pool loads with one. We only do this if the FP
  8591. // type is known to be legal, because if it isn't, then we are before legalize
  8592. // types an we want the other legalization to happen first (e.g. to avoid
  8593. // messing with soft float) and if the ConstantFP is not legal, because if
  8594. // it is legal, we may not need to store the FP constant in a constant pool.
  8595. if (ConstantFPSDNode *TV = dyn_cast<ConstantFPSDNode>(N2))
  8596. if (ConstantFPSDNode *FV = dyn_cast<ConstantFPSDNode>(N3)) {
  8597. if (TLI.isTypeLegal(N2.getValueType()) &&
  8598. (TLI.getOperationAction(ISD::ConstantFP, N2.getValueType()) !=
  8599. TargetLowering::Legal) &&
  8600. // If both constants have multiple uses, then we won't need to do an
  8601. // extra load, they are likely around in registers for other users.
  8602. (TV->hasOneUse() || FV->hasOneUse())) {
  8603. Constant *Elts[] = {
  8604. const_cast<ConstantFP*>(FV->getConstantFPValue()),
  8605. const_cast<ConstantFP*>(TV->getConstantFPValue())
  8606. };
  8607. Type *FPTy = Elts[0]->getType();
  8608. const DataLayout &TD = *TLI.getDataLayout();
  8609. // Create a ConstantArray of the two constants.
  8610. Constant *CA = ConstantArray::get(ArrayType::get(FPTy, 2), Elts);
  8611. SDValue CPIdx = DAG.getConstantPool(CA, TLI.getPointerTy(),
  8612. TD.getPrefTypeAlignment(FPTy));
  8613. unsigned Alignment = cast<ConstantPoolSDNode>(CPIdx)->getAlignment();
  8614. // Get the offsets to the 0 and 1 element of the array so that we can
  8615. // select between them.
  8616. SDValue Zero = DAG.getIntPtrConstant(0);
  8617. unsigned EltSize = (unsigned)TD.getTypeAllocSize(Elts[0]->getType());
  8618. SDValue One = DAG.getIntPtrConstant(EltSize);
  8619. SDValue Cond = DAG.getSetCC(DL,
  8620. getSetCCResultType(N0.getValueType()),
  8621. N0, N1, CC);
  8622. AddToWorkList(Cond.getNode());
  8623. SDValue CstOffset = DAG.getNode(ISD::SELECT, DL, Zero.getValueType(),
  8624. Cond, One, Zero);
  8625. AddToWorkList(CstOffset.getNode());
  8626. CPIdx = DAG.getNode(ISD::ADD, DL, TLI.getPointerTy(), CPIdx,
  8627. CstOffset);
  8628. AddToWorkList(CPIdx.getNode());
  8629. return DAG.getLoad(TV->getValueType(0), DL, DAG.getEntryNode(), CPIdx,
  8630. MachinePointerInfo::getConstantPool(), false,
  8631. false, false, Alignment);
  8632. }
  8633. }
  8634. // Check to see if we can perform the "gzip trick", transforming
  8635. // (select_cc setlt X, 0, A, 0) -> (and (sra X, (sub size(X), 1), A)
  8636. if (N1C && N3C && N3C->isNullValue() && CC == ISD::SETLT &&
  8637. (N1C->isNullValue() || // (a < 0) ? b : 0
  8638. (N1C->getAPIntValue() == 1 && N0 == N2))) { // (a < 1) ? a : 0
  8639. EVT XType = N0.getValueType();
  8640. EVT AType = N2.getValueType();
  8641. if (XType.bitsGE(AType)) {
  8642. // and (sra X, size(X)-1, A) -> "and (srl X, C2), A" iff A is a
  8643. // single-bit constant.
  8644. if (N2C && ((N2C->getAPIntValue() & (N2C->getAPIntValue()-1)) == 0)) {
  8645. unsigned ShCtV = N2C->getAPIntValue().logBase2();
  8646. ShCtV = XType.getSizeInBits()-ShCtV-1;
  8647. SDValue ShCt = DAG.getConstant(ShCtV,
  8648. getShiftAmountTy(N0.getValueType()));
  8649. SDValue Shift = DAG.getNode(ISD::SRL, N0.getDebugLoc(),
  8650. XType, N0, ShCt);
  8651. AddToWorkList(Shift.getNode());
  8652. if (XType.bitsGT(AType)) {
  8653. Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
  8654. AddToWorkList(Shift.getNode());
  8655. }
  8656. return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
  8657. }
  8658. SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(),
  8659. XType, N0,
  8660. DAG.getConstant(XType.getSizeInBits()-1,
  8661. getShiftAmountTy(N0.getValueType())));
  8662. AddToWorkList(Shift.getNode());
  8663. if (XType.bitsGT(AType)) {
  8664. Shift = DAG.getNode(ISD::TRUNCATE, DL, AType, Shift);
  8665. AddToWorkList(Shift.getNode());
  8666. }
  8667. return DAG.getNode(ISD::AND, DL, AType, Shift, N2);
  8668. }
  8669. }
  8670. // fold (select_cc seteq (and x, y), 0, 0, A) -> (and (shr (shl x)) A)
  8671. // where y is has a single bit set.
  8672. // A plaintext description would be, we can turn the SELECT_CC into an AND
  8673. // when the condition can be materialized as an all-ones register. Any
  8674. // single bit-test can be materialized as an all-ones register with
  8675. // shift-left and shift-right-arith.
  8676. if (CC == ISD::SETEQ && N0->getOpcode() == ISD::AND &&
  8677. N0->getValueType(0) == VT &&
  8678. N1C && N1C->isNullValue() &&
  8679. N2C && N2C->isNullValue()) {
  8680. SDValue AndLHS = N0->getOperand(0);
  8681. ConstantSDNode *ConstAndRHS = dyn_cast<ConstantSDNode>(N0->getOperand(1));
  8682. if (ConstAndRHS && ConstAndRHS->getAPIntValue().countPopulation() == 1) {
  8683. // Shift the tested bit over the sign bit.
  8684. APInt AndMask = ConstAndRHS->getAPIntValue();
  8685. SDValue ShlAmt =
  8686. DAG.getConstant(AndMask.countLeadingZeros(),
  8687. getShiftAmountTy(AndLHS.getValueType()));
  8688. SDValue Shl = DAG.getNode(ISD::SHL, N0.getDebugLoc(), VT, AndLHS, ShlAmt);
  8689. // Now arithmetic right shift it all the way over, so the result is either
  8690. // all-ones, or zero.
  8691. SDValue ShrAmt =
  8692. DAG.getConstant(AndMask.getBitWidth()-1,
  8693. getShiftAmountTy(Shl.getValueType()));
  8694. SDValue Shr = DAG.getNode(ISD::SRA, N0.getDebugLoc(), VT, Shl, ShrAmt);
  8695. return DAG.getNode(ISD::AND, DL, VT, Shr, N3);
  8696. }
  8697. }
  8698. // fold select C, 16, 0 -> shl C, 4
  8699. if (N2C && N3C && N3C->isNullValue() && N2C->getAPIntValue().isPowerOf2() &&
  8700. TLI.getBooleanContents(N0.getValueType().isVector()) ==
  8701. TargetLowering::ZeroOrOneBooleanContent) {
  8702. // If the caller doesn't want us to simplify this into a zext of a compare,
  8703. // don't do it.
  8704. if (NotExtCompare && N2C->getAPIntValue() == 1)
  8705. return SDValue();
  8706. // Get a SetCC of the condition
  8707. // NOTE: Don't create a SETCC if it's not legal on this target.
  8708. if (!LegalOperations ||
  8709. TLI.isOperationLegal(ISD::SETCC,
  8710. LegalTypes ? getSetCCResultType(N0.getValueType()) : MVT::i1)) {
  8711. SDValue Temp, SCC;
  8712. // cast from setcc result type to select result type
  8713. if (LegalTypes) {
  8714. SCC = DAG.getSetCC(DL, getSetCCResultType(N0.getValueType()),
  8715. N0, N1, CC);
  8716. if (N2.getValueType().bitsLT(SCC.getValueType()))
  8717. Temp = DAG.getZeroExtendInReg(SCC, N2.getDebugLoc(),
  8718. N2.getValueType());
  8719. else
  8720. Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
  8721. N2.getValueType(), SCC);
  8722. } else {
  8723. SCC = DAG.getSetCC(N0.getDebugLoc(), MVT::i1, N0, N1, CC);
  8724. Temp = DAG.getNode(ISD::ZERO_EXTEND, N2.getDebugLoc(),
  8725. N2.getValueType(), SCC);
  8726. }
  8727. AddToWorkList(SCC.getNode());
  8728. AddToWorkList(Temp.getNode());
  8729. if (N2C->getAPIntValue() == 1)
  8730. return Temp;
  8731. // shl setcc result by log2 n2c
  8732. return DAG.getNode(ISD::SHL, DL, N2.getValueType(), Temp,
  8733. DAG.getConstant(N2C->getAPIntValue().logBase2(),
  8734. getShiftAmountTy(Temp.getValueType())));
  8735. }
  8736. }
  8737. // Check to see if this is the equivalent of setcc
  8738. // FIXME: Turn all of these into setcc if setcc if setcc is legal
  8739. // otherwise, go ahead with the folds.
  8740. if (0 && N3C && N3C->isNullValue() && N2C && (N2C->getAPIntValue() == 1ULL)) {
  8741. EVT XType = N0.getValueType();
  8742. if (!LegalOperations ||
  8743. TLI.isOperationLegal(ISD::SETCC, getSetCCResultType(XType))) {
  8744. SDValue Res = DAG.getSetCC(DL, getSetCCResultType(XType), N0, N1, CC);
  8745. if (Res.getValueType() != VT)
  8746. Res = DAG.getNode(ISD::ZERO_EXTEND, DL, VT, Res);
  8747. return Res;
  8748. }
  8749. // fold (seteq X, 0) -> (srl (ctlz X, log2(size(X))))
  8750. if (N1C && N1C->isNullValue() && CC == ISD::SETEQ &&
  8751. (!LegalOperations ||
  8752. TLI.isOperationLegal(ISD::CTLZ, XType))) {
  8753. SDValue Ctlz = DAG.getNode(ISD::CTLZ, N0.getDebugLoc(), XType, N0);
  8754. return DAG.getNode(ISD::SRL, DL, XType, Ctlz,
  8755. DAG.getConstant(Log2_32(XType.getSizeInBits()),
  8756. getShiftAmountTy(Ctlz.getValueType())));
  8757. }
  8758. // fold (setgt X, 0) -> (srl (and (-X, ~X), size(X)-1))
  8759. if (N1C && N1C->isNullValue() && CC == ISD::SETGT) {
  8760. SDValue NegN0 = DAG.getNode(ISD::SUB, N0.getDebugLoc(),
  8761. XType, DAG.getConstant(0, XType), N0);
  8762. SDValue NotN0 = DAG.getNOT(N0.getDebugLoc(), N0, XType);
  8763. return DAG.getNode(ISD::SRL, DL, XType,
  8764. DAG.getNode(ISD::AND, DL, XType, NegN0, NotN0),
  8765. DAG.getConstant(XType.getSizeInBits()-1,
  8766. getShiftAmountTy(XType)));
  8767. }
  8768. // fold (setgt X, -1) -> (xor (srl (X, size(X)-1), 1))
  8769. if (N1C && N1C->isAllOnesValue() && CC == ISD::SETGT) {
  8770. SDValue Sign = DAG.getNode(ISD::SRL, N0.getDebugLoc(), XType, N0,
  8771. DAG.getConstant(XType.getSizeInBits()-1,
  8772. getShiftAmountTy(N0.getValueType())));
  8773. return DAG.getNode(ISD::XOR, DL, XType, Sign, DAG.getConstant(1, XType));
  8774. }
  8775. }
  8776. // Check to see if this is an integer abs.
  8777. // select_cc setg[te] X, 0, X, -X ->
  8778. // select_cc setgt X, -1, X, -X ->
  8779. // select_cc setl[te] X, 0, -X, X ->
  8780. // select_cc setlt X, 1, -X, X ->
  8781. // Y = sra (X, size(X)-1); xor (add (X, Y), Y)
  8782. if (N1C) {
  8783. ConstantSDNode *SubC = NULL;
  8784. if (((N1C->isNullValue() && (CC == ISD::SETGT || CC == ISD::SETGE)) ||
  8785. (N1C->isAllOnesValue() && CC == ISD::SETGT)) &&
  8786. N0 == N2 && N3.getOpcode() == ISD::SUB && N0 == N3.getOperand(1))
  8787. SubC = dyn_cast<ConstantSDNode>(N3.getOperand(0));
  8788. else if (((N1C->isNullValue() && (CC == ISD::SETLT || CC == ISD::SETLE)) ||
  8789. (N1C->isOne() && CC == ISD::SETLT)) &&
  8790. N0 == N3 && N2.getOpcode() == ISD::SUB && N0 == N2.getOperand(1))
  8791. SubC = dyn_cast<ConstantSDNode>(N2.getOperand(0));
  8792. EVT XType = N0.getValueType();
  8793. if (SubC && SubC->isNullValue() && XType.isInteger()) {
  8794. SDValue Shift = DAG.getNode(ISD::SRA, N0.getDebugLoc(), XType,
  8795. N0,
  8796. DAG.getConstant(XType.getSizeInBits()-1,
  8797. getShiftAmountTy(N0.getValueType())));
  8798. SDValue Add = DAG.getNode(ISD::ADD, N0.getDebugLoc(),
  8799. XType, N0, Shift);
  8800. AddToWorkList(Shift.getNode());
  8801. AddToWorkList(Add.getNode());
  8802. return DAG.getNode(ISD::XOR, DL, XType, Add, Shift);
  8803. }
  8804. }
  8805. return SDValue();
  8806. }
  8807. /// SimplifySetCC - This is a stub for TargetLowering::SimplifySetCC.
  8808. SDValue DAGCombiner::SimplifySetCC(EVT VT, SDValue N0,
  8809. SDValue N1, ISD::CondCode Cond,
  8810. DebugLoc DL, bool foldBooleans) {
  8811. TargetLowering::DAGCombinerInfo
  8812. DagCombineInfo(DAG, Level, false, this);
  8813. return TLI.SimplifySetCC(VT, N0, N1, Cond, foldBooleans, DagCombineInfo, DL);
  8814. }
  8815. /// BuildSDIVSequence - Given an ISD::SDIV node expressing a divide by constant,
  8816. /// return a DAG expression to select that will generate the same value by
  8817. /// multiplying by a magic number. See:
  8818. /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
  8819. SDValue DAGCombiner::BuildSDIV(SDNode *N) {
  8820. std::vector<SDNode*> Built;
  8821. SDValue S = TLI.BuildSDIV(N, DAG, LegalOperations, &Built);
  8822. for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
  8823. ii != ee; ++ii)
  8824. AddToWorkList(*ii);
  8825. return S;
  8826. }
  8827. /// BuildUDIVSequence - Given an ISD::UDIV node expressing a divide by constant,
  8828. /// return a DAG expression to select that will generate the same value by
  8829. /// multiplying by a magic number. See:
  8830. /// <http://the.wall.riscom.net/books/proc/ppc/cwg/code2.html>
  8831. SDValue DAGCombiner::BuildUDIV(SDNode *N) {
  8832. std::vector<SDNode*> Built;
  8833. SDValue S = TLI.BuildUDIV(N, DAG, LegalOperations, &Built);
  8834. for (std::vector<SDNode*>::iterator ii = Built.begin(), ee = Built.end();
  8835. ii != ee; ++ii)
  8836. AddToWorkList(*ii);
  8837. return S;
  8838. }
  8839. /// FindBaseOffset - Return true if base is a frame index, which is known not
  8840. // to alias with anything but itself. Provides base object and offset as
  8841. // results.
  8842. static bool FindBaseOffset(SDValue Ptr, SDValue &Base, int64_t &Offset,
  8843. const GlobalValue *&GV, const void *&CV) {
  8844. // Assume it is a primitive operation.
  8845. Base = Ptr; Offset = 0; GV = 0; CV = 0;
  8846. // If it's an adding a simple constant then integrate the offset.
  8847. if (Base.getOpcode() == ISD::ADD) {
  8848. if (ConstantSDNode *C = dyn_cast<ConstantSDNode>(Base.getOperand(1))) {
  8849. Base = Base.getOperand(0);
  8850. Offset += C->getZExtValue();
  8851. }
  8852. }
  8853. // Return the underlying GlobalValue, and update the Offset. Return false
  8854. // for GlobalAddressSDNode since the same GlobalAddress may be represented
  8855. // by multiple nodes with different offsets.
  8856. if (GlobalAddressSDNode *G = dyn_cast<GlobalAddressSDNode>(Base)) {
  8857. GV = G->getGlobal();
  8858. Offset += G->getOffset();
  8859. return false;
  8860. }
  8861. // Return the underlying Constant value, and update the Offset. Return false
  8862. // for ConstantSDNodes since the same constant pool entry may be represented
  8863. // by multiple nodes with different offsets.
  8864. if (ConstantPoolSDNode *C = dyn_cast<ConstantPoolSDNode>(Base)) {
  8865. CV = C->isMachineConstantPoolEntry() ? (const void *)C->getMachineCPVal()
  8866. : (const void *)C->getConstVal();
  8867. Offset += C->getOffset();
  8868. return false;
  8869. }
  8870. // If it's any of the following then it can't alias with anything but itself.
  8871. return isa<FrameIndexSDNode>(Base);
  8872. }
  8873. /// isAlias - Return true if there is any possibility that the two addresses
  8874. /// overlap.
  8875. bool DAGCombiner::isAlias(SDValue Ptr1, int64_t Size1,
  8876. const Value *SrcValue1, int SrcValueOffset1,
  8877. unsigned SrcValueAlign1,
  8878. const MDNode *TBAAInfo1,
  8879. SDValue Ptr2, int64_t Size2,
  8880. const Value *SrcValue2, int SrcValueOffset2,
  8881. unsigned SrcValueAlign2,
  8882. const MDNode *TBAAInfo2) const {
  8883. // If they are the same then they must be aliases.
  8884. if (Ptr1 == Ptr2) return true;
  8885. // Gather base node and offset information.
  8886. SDValue Base1, Base2;
  8887. int64_t Offset1, Offset2;
  8888. const GlobalValue *GV1, *GV2;
  8889. const void *CV1, *CV2;
  8890. bool isFrameIndex1 = FindBaseOffset(Ptr1, Base1, Offset1, GV1, CV1);
  8891. bool isFrameIndex2 = FindBaseOffset(Ptr2, Base2, Offset2, GV2, CV2);
  8892. // If they have a same base address then check to see if they overlap.
  8893. if (Base1 == Base2 || (GV1 && (GV1 == GV2)) || (CV1 && (CV1 == CV2)))
  8894. return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
  8895. // It is possible for different frame indices to alias each other, mostly
  8896. // when tail call optimization reuses return address slots for arguments.
  8897. // To catch this case, look up the actual index of frame indices to compute
  8898. // the real alias relationship.
  8899. if (isFrameIndex1 && isFrameIndex2) {
  8900. MachineFrameInfo *MFI = DAG.getMachineFunction().getFrameInfo();
  8901. Offset1 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base1)->getIndex());
  8902. Offset2 += MFI->getObjectOffset(cast<FrameIndexSDNode>(Base2)->getIndex());
  8903. return !((Offset1 + Size1) <= Offset2 || (Offset2 + Size2) <= Offset1);
  8904. }
  8905. // Otherwise, if we know what the bases are, and they aren't identical, then
  8906. // we know they cannot alias.
  8907. if ((isFrameIndex1 || CV1 || GV1) && (isFrameIndex2 || CV2 || GV2))
  8908. return false;
  8909. // If we know required SrcValue1 and SrcValue2 have relatively large alignment
  8910. // compared to the size and offset of the access, we may be able to prove they
  8911. // do not alias. This check is conservative for now to catch cases created by
  8912. // splitting vector types.
  8913. if ((SrcValueAlign1 == SrcValueAlign2) &&
  8914. (SrcValueOffset1 != SrcValueOffset2) &&
  8915. (Size1 == Size2) && (SrcValueAlign1 > Size1)) {
  8916. int64_t OffAlign1 = SrcValueOffset1 % SrcValueAlign1;
  8917. int64_t OffAlign2 = SrcValueOffset2 % SrcValueAlign1;
  8918. // There is no overlap between these relatively aligned accesses of similar
  8919. // size, return no alias.
  8920. if ((OffAlign1 + Size1) <= OffAlign2 || (OffAlign2 + Size2) <= OffAlign1)
  8921. return false;
  8922. }
  8923. if (CombinerGlobalAA) {
  8924. // Use alias analysis information.
  8925. int64_t MinOffset = std::min(SrcValueOffset1, SrcValueOffset2);
  8926. int64_t Overlap1 = Size1 + SrcValueOffset1 - MinOffset;
  8927. int64_t Overlap2 = Size2 + SrcValueOffset2 - MinOffset;
  8928. AliasAnalysis::AliasResult AAResult =
  8929. AA.alias(AliasAnalysis::Location(SrcValue1, Overlap1, TBAAInfo1),
  8930. AliasAnalysis::Location(SrcValue2, Overlap2, TBAAInfo2));
  8931. if (AAResult == AliasAnalysis::NoAlias)
  8932. return false;
  8933. }
  8934. // Otherwise we have to assume they alias.
  8935. return true;
  8936. }
  8937. bool DAGCombiner::isAlias(LSBaseSDNode *Op0, LSBaseSDNode *Op1) {
  8938. SDValue Ptr0, Ptr1;
  8939. int64_t Size0, Size1;
  8940. const Value *SrcValue0, *SrcValue1;
  8941. int SrcValueOffset0, SrcValueOffset1;
  8942. unsigned SrcValueAlign0, SrcValueAlign1;
  8943. const MDNode *SrcTBAAInfo0, *SrcTBAAInfo1;
  8944. FindAliasInfo(Op0, Ptr0, Size0, SrcValue0, SrcValueOffset0,
  8945. SrcValueAlign0, SrcTBAAInfo0);
  8946. FindAliasInfo(Op1, Ptr1, Size1, SrcValue1, SrcValueOffset1,
  8947. SrcValueAlign1, SrcTBAAInfo1);
  8948. return isAlias(Ptr0, Size0, SrcValue0, SrcValueOffset0,
  8949. SrcValueAlign0, SrcTBAAInfo0,
  8950. Ptr1, Size1, SrcValue1, SrcValueOffset1,
  8951. SrcValueAlign1, SrcTBAAInfo1);
  8952. }
  8953. /// FindAliasInfo - Extracts the relevant alias information from the memory
  8954. /// node. Returns true if the operand was a load.
  8955. bool DAGCombiner::FindAliasInfo(SDNode *N,
  8956. SDValue &Ptr, int64_t &Size,
  8957. const Value *&SrcValue,
  8958. int &SrcValueOffset,
  8959. unsigned &SrcValueAlign,
  8960. const MDNode *&TBAAInfo) const {
  8961. LSBaseSDNode *LS = cast<LSBaseSDNode>(N);
  8962. Ptr = LS->getBasePtr();
  8963. Size = LS->getMemoryVT().getSizeInBits() >> 3;
  8964. SrcValue = LS->getSrcValue();
  8965. SrcValueOffset = LS->getSrcValueOffset();
  8966. SrcValueAlign = LS->getOriginalAlignment();
  8967. TBAAInfo = LS->getTBAAInfo();
  8968. return isa<LoadSDNode>(LS);
  8969. }
  8970. /// GatherAllAliases - Walk up chain skipping non-aliasing memory nodes,
  8971. /// looking for aliasing nodes and adding them to the Aliases vector.
  8972. void DAGCombiner::GatherAllAliases(SDNode *N, SDValue OriginalChain,
  8973. SmallVector<SDValue, 8> &Aliases) {
  8974. SmallVector<SDValue, 8> Chains; // List of chains to visit.
  8975. SmallPtrSet<SDNode *, 16> Visited; // Visited node set.
  8976. // Get alias information for node.
  8977. SDValue Ptr;
  8978. int64_t Size;
  8979. const Value *SrcValue;
  8980. int SrcValueOffset;
  8981. unsigned SrcValueAlign;
  8982. const MDNode *SrcTBAAInfo;
  8983. bool IsLoad = FindAliasInfo(N, Ptr, Size, SrcValue, SrcValueOffset,
  8984. SrcValueAlign, SrcTBAAInfo);
  8985. // Starting off.
  8986. Chains.push_back(OriginalChain);
  8987. unsigned Depth = 0;
  8988. // Look at each chain and determine if it is an alias. If so, add it to the
  8989. // aliases list. If not, then continue up the chain looking for the next
  8990. // candidate.
  8991. while (!Chains.empty()) {
  8992. SDValue Chain = Chains.back();
  8993. Chains.pop_back();
  8994. // For TokenFactor nodes, look at each operand and only continue up the
  8995. // chain until we find two aliases. If we've seen two aliases, assume we'll
  8996. // find more and revert to original chain since the xform is unlikely to be
  8997. // profitable.
  8998. //
  8999. // FIXME: The depth check could be made to return the last non-aliasing
  9000. // chain we found before we hit a tokenfactor rather than the original
  9001. // chain.
  9002. if (Depth > 6 || Aliases.size() == 2) {
  9003. Aliases.clear();
  9004. Aliases.push_back(OriginalChain);
  9005. break;
  9006. }
  9007. // Don't bother if we've been before.
  9008. if (!Visited.insert(Chain.getNode()))
  9009. continue;
  9010. switch (Chain.getOpcode()) {
  9011. case ISD::EntryToken:
  9012. // Entry token is ideal chain operand, but handled in FindBetterChain.
  9013. break;
  9014. case ISD::LOAD:
  9015. case ISD::STORE: {
  9016. // Get alias information for Chain.
  9017. SDValue OpPtr;
  9018. int64_t OpSize;
  9019. const Value *OpSrcValue;
  9020. int OpSrcValueOffset;
  9021. unsigned OpSrcValueAlign;
  9022. const MDNode *OpSrcTBAAInfo;
  9023. bool IsOpLoad = FindAliasInfo(Chain.getNode(), OpPtr, OpSize,
  9024. OpSrcValue, OpSrcValueOffset,
  9025. OpSrcValueAlign,
  9026. OpSrcTBAAInfo);
  9027. // If chain is alias then stop here.
  9028. if (!(IsLoad && IsOpLoad) &&
  9029. isAlias(Ptr, Size, SrcValue, SrcValueOffset, SrcValueAlign,
  9030. SrcTBAAInfo,
  9031. OpPtr, OpSize, OpSrcValue, OpSrcValueOffset,
  9032. OpSrcValueAlign, OpSrcTBAAInfo)) {
  9033. Aliases.push_back(Chain);
  9034. } else {
  9035. // Look further up the chain.
  9036. Chains.push_back(Chain.getOperand(0));
  9037. ++Depth;
  9038. }
  9039. break;
  9040. }
  9041. case ISD::TokenFactor:
  9042. // We have to check each of the operands of the token factor for "small"
  9043. // token factors, so we queue them up. Adding the operands to the queue
  9044. // (stack) in reverse order maintains the original order and increases the
  9045. // likelihood that getNode will find a matching token factor (CSE.)
  9046. if (Chain.getNumOperands() > 16) {
  9047. Aliases.push_back(Chain);
  9048. break;
  9049. }
  9050. for (unsigned n = Chain.getNumOperands(); n;)
  9051. Chains.push_back(Chain.getOperand(--n));
  9052. ++Depth;
  9053. break;
  9054. default:
  9055. // For all other instructions we will just have to take what we can get.
  9056. Aliases.push_back(Chain);
  9057. break;
  9058. }
  9059. }
  9060. }
  9061. /// FindBetterChain - Walk up chain skipping non-aliasing memory nodes, looking
  9062. /// for a better chain (aliasing node.)
  9063. SDValue DAGCombiner::FindBetterChain(SDNode *N, SDValue OldChain) {
  9064. SmallVector<SDValue, 8> Aliases; // Ops for replacing token factor.
  9065. // Accumulate all the aliases to this node.
  9066. GatherAllAliases(N, OldChain, Aliases);
  9067. // If no operands then chain to entry token.
  9068. if (Aliases.size() == 0)
  9069. return DAG.getEntryNode();
  9070. // If a single operand then chain to it. We don't need to revisit it.
  9071. if (Aliases.size() == 1)
  9072. return Aliases[0];
  9073. // Construct a custom tailored token factor.
  9074. return DAG.getNode(ISD::TokenFactor, N->getDebugLoc(), MVT::Other,
  9075. &Aliases[0], Aliases.size());
  9076. }
  9077. // SelectionDAG::Combine - This is the entry point for the file.
  9078. //
  9079. void SelectionDAG::Combine(CombineLevel Level, AliasAnalysis &AA,
  9080. CodeGenOpt::Level OptLevel) {
  9081. /// run - This is the main entry point to this class.
  9082. ///
  9083. DAGCombiner(*this, AA, OptLevel).Run(Level);
  9084. }