InstructionSimplify.cpp 254 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829
  1. //===- InstructionSimplify.cpp - Fold instruction operands ----------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements routines for folding instructions into simpler forms
  10. // that do not require creating new instructions. This does constant folding
  11. // ("add i32 1, 1" -> "2") but can also handle non-constant operands, either
  12. // returning a constant ("and i32 %x, 0" -> "0") or an already existing value
  13. // ("and i32 %x, %x" -> "%x"). All operands are assumed to have already been
  14. // simplified: This is usually true and assuming it simplifies the logic (if
  15. // they have not been simplified then results are correct but maybe suboptimal).
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/Analysis/InstructionSimplify.h"
  19. #include "llvm/ADT/STLExtras.h"
  20. #include "llvm/ADT/SetVector.h"
  21. #include "llvm/ADT/Statistic.h"
  22. #include "llvm/Analysis/AliasAnalysis.h"
  23. #include "llvm/Analysis/AssumptionCache.h"
  24. #include "llvm/Analysis/CaptureTracking.h"
  25. #include "llvm/Analysis/CmpInstAnalysis.h"
  26. #include "llvm/Analysis/ConstantFolding.h"
  27. #include "llvm/Analysis/InstSimplifyFolder.h"
  28. #include "llvm/Analysis/LoopAnalysisManager.h"
  29. #include "llvm/Analysis/MemoryBuiltins.h"
  30. #include "llvm/Analysis/OverflowInstAnalysis.h"
  31. #include "llvm/Analysis/ValueTracking.h"
  32. #include "llvm/Analysis/VectorUtils.h"
  33. #include "llvm/IR/ConstantRange.h"
  34. #include "llvm/IR/DataLayout.h"
  35. #include "llvm/IR/Dominators.h"
  36. #include "llvm/IR/InstrTypes.h"
  37. #include "llvm/IR/Instructions.h"
  38. #include "llvm/IR/Operator.h"
  39. #include "llvm/IR/PatternMatch.h"
  40. #include "llvm/Support/KnownBits.h"
  41. #include <algorithm>
  42. #include <optional>
  43. using namespace llvm;
  44. using namespace llvm::PatternMatch;
  45. #define DEBUG_TYPE "instsimplify"
  46. enum { RecursionLimit = 3 };
  47. STATISTIC(NumExpand, "Number of expansions");
  48. STATISTIC(NumReassoc, "Number of reassociations");
  49. static Value *simplifyAndInst(Value *, Value *, const SimplifyQuery &,
  50. unsigned);
  51. static Value *simplifyUnOp(unsigned, Value *, const SimplifyQuery &, unsigned);
  52. static Value *simplifyFPUnOp(unsigned, Value *, const FastMathFlags &,
  53. const SimplifyQuery &, unsigned);
  54. static Value *simplifyBinOp(unsigned, Value *, Value *, const SimplifyQuery &,
  55. unsigned);
  56. static Value *simplifyBinOp(unsigned, Value *, Value *, const FastMathFlags &,
  57. const SimplifyQuery &, unsigned);
  58. static Value *simplifyCmpInst(unsigned, Value *, Value *, const SimplifyQuery &,
  59. unsigned);
  60. static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  61. const SimplifyQuery &Q, unsigned MaxRecurse);
  62. static Value *simplifyOrInst(Value *, Value *, const SimplifyQuery &, unsigned);
  63. static Value *simplifyXorInst(Value *, Value *, const SimplifyQuery &,
  64. unsigned);
  65. static Value *simplifyCastInst(unsigned, Value *, Type *, const SimplifyQuery &,
  66. unsigned);
  67. static Value *simplifyGEPInst(Type *, Value *, ArrayRef<Value *>, bool,
  68. const SimplifyQuery &, unsigned);
  69. static Value *simplifySelectInst(Value *, Value *, Value *,
  70. const SimplifyQuery &, unsigned);
  71. static Value *foldSelectWithBinaryOp(Value *Cond, Value *TrueVal,
  72. Value *FalseVal) {
  73. BinaryOperator::BinaryOps BinOpCode;
  74. if (auto *BO = dyn_cast<BinaryOperator>(Cond))
  75. BinOpCode = BO->getOpcode();
  76. else
  77. return nullptr;
  78. CmpInst::Predicate ExpectedPred, Pred1, Pred2;
  79. if (BinOpCode == BinaryOperator::Or) {
  80. ExpectedPred = ICmpInst::ICMP_NE;
  81. } else if (BinOpCode == BinaryOperator::And) {
  82. ExpectedPred = ICmpInst::ICMP_EQ;
  83. } else
  84. return nullptr;
  85. // %A = icmp eq %TV, %FV
  86. // %B = icmp eq %X, %Y (and one of these is a select operand)
  87. // %C = and %A, %B
  88. // %D = select %C, %TV, %FV
  89. // -->
  90. // %FV
  91. // %A = icmp ne %TV, %FV
  92. // %B = icmp ne %X, %Y (and one of these is a select operand)
  93. // %C = or %A, %B
  94. // %D = select %C, %TV, %FV
  95. // -->
  96. // %TV
  97. Value *X, *Y;
  98. if (!match(Cond, m_c_BinOp(m_c_ICmp(Pred1, m_Specific(TrueVal),
  99. m_Specific(FalseVal)),
  100. m_ICmp(Pred2, m_Value(X), m_Value(Y)))) ||
  101. Pred1 != Pred2 || Pred1 != ExpectedPred)
  102. return nullptr;
  103. if (X == TrueVal || X == FalseVal || Y == TrueVal || Y == FalseVal)
  104. return BinOpCode == BinaryOperator::Or ? TrueVal : FalseVal;
  105. return nullptr;
  106. }
  107. /// For a boolean type or a vector of boolean type, return false or a vector
  108. /// with every element false.
  109. static Constant *getFalse(Type *Ty) { return ConstantInt::getFalse(Ty); }
  110. /// For a boolean type or a vector of boolean type, return true or a vector
  111. /// with every element true.
  112. static Constant *getTrue(Type *Ty) { return ConstantInt::getTrue(Ty); }
  113. /// isSameCompare - Is V equivalent to the comparison "LHS Pred RHS"?
  114. static bool isSameCompare(Value *V, CmpInst::Predicate Pred, Value *LHS,
  115. Value *RHS) {
  116. CmpInst *Cmp = dyn_cast<CmpInst>(V);
  117. if (!Cmp)
  118. return false;
  119. CmpInst::Predicate CPred = Cmp->getPredicate();
  120. Value *CLHS = Cmp->getOperand(0), *CRHS = Cmp->getOperand(1);
  121. if (CPred == Pred && CLHS == LHS && CRHS == RHS)
  122. return true;
  123. return CPred == CmpInst::getSwappedPredicate(Pred) && CLHS == RHS &&
  124. CRHS == LHS;
  125. }
  126. /// Simplify comparison with true or false branch of select:
  127. /// %sel = select i1 %cond, i32 %tv, i32 %fv
  128. /// %cmp = icmp sle i32 %sel, %rhs
  129. /// Compose new comparison by substituting %sel with either %tv or %fv
  130. /// and see if it simplifies.
  131. static Value *simplifyCmpSelCase(CmpInst::Predicate Pred, Value *LHS,
  132. Value *RHS, Value *Cond,
  133. const SimplifyQuery &Q, unsigned MaxRecurse,
  134. Constant *TrueOrFalse) {
  135. Value *SimplifiedCmp = simplifyCmpInst(Pred, LHS, RHS, Q, MaxRecurse);
  136. if (SimplifiedCmp == Cond) {
  137. // %cmp simplified to the select condition (%cond).
  138. return TrueOrFalse;
  139. } else if (!SimplifiedCmp && isSameCompare(Cond, Pred, LHS, RHS)) {
  140. // It didn't simplify. However, if composed comparison is equivalent
  141. // to the select condition (%cond) then we can replace it.
  142. return TrueOrFalse;
  143. }
  144. return SimplifiedCmp;
  145. }
  146. /// Simplify comparison with true branch of select
  147. static Value *simplifyCmpSelTrueCase(CmpInst::Predicate Pred, Value *LHS,
  148. Value *RHS, Value *Cond,
  149. const SimplifyQuery &Q,
  150. unsigned MaxRecurse) {
  151. return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
  152. getTrue(Cond->getType()));
  153. }
  154. /// Simplify comparison with false branch of select
  155. static Value *simplifyCmpSelFalseCase(CmpInst::Predicate Pred, Value *LHS,
  156. Value *RHS, Value *Cond,
  157. const SimplifyQuery &Q,
  158. unsigned MaxRecurse) {
  159. return simplifyCmpSelCase(Pred, LHS, RHS, Cond, Q, MaxRecurse,
  160. getFalse(Cond->getType()));
  161. }
  162. /// We know comparison with both branches of select can be simplified, but they
  163. /// are not equal. This routine handles some logical simplifications.
  164. static Value *handleOtherCmpSelSimplifications(Value *TCmp, Value *FCmp,
  165. Value *Cond,
  166. const SimplifyQuery &Q,
  167. unsigned MaxRecurse) {
  168. // If the false value simplified to false, then the result of the compare
  169. // is equal to "Cond && TCmp". This also catches the case when the false
  170. // value simplified to false and the true value to true, returning "Cond".
  171. // Folding select to and/or isn't poison-safe in general; impliesPoison
  172. // checks whether folding it does not convert a well-defined value into
  173. // poison.
  174. if (match(FCmp, m_Zero()) && impliesPoison(TCmp, Cond))
  175. if (Value *V = simplifyAndInst(Cond, TCmp, Q, MaxRecurse))
  176. return V;
  177. // If the true value simplified to true, then the result of the compare
  178. // is equal to "Cond || FCmp".
  179. if (match(TCmp, m_One()) && impliesPoison(FCmp, Cond))
  180. if (Value *V = simplifyOrInst(Cond, FCmp, Q, MaxRecurse))
  181. return V;
  182. // Finally, if the false value simplified to true and the true value to
  183. // false, then the result of the compare is equal to "!Cond".
  184. if (match(FCmp, m_One()) && match(TCmp, m_Zero()))
  185. if (Value *V = simplifyXorInst(
  186. Cond, Constant::getAllOnesValue(Cond->getType()), Q, MaxRecurse))
  187. return V;
  188. return nullptr;
  189. }
  190. /// Does the given value dominate the specified phi node?
  191. static bool valueDominatesPHI(Value *V, PHINode *P, const DominatorTree *DT) {
  192. Instruction *I = dyn_cast<Instruction>(V);
  193. if (!I)
  194. // Arguments and constants dominate all instructions.
  195. return true;
  196. // If we are processing instructions (and/or basic blocks) that have not been
  197. // fully added to a function, the parent nodes may still be null. Simply
  198. // return the conservative answer in these cases.
  199. if (!I->getParent() || !P->getParent() || !I->getFunction())
  200. return false;
  201. // If we have a DominatorTree then do a precise test.
  202. if (DT)
  203. return DT->dominates(I, P);
  204. // Otherwise, if the instruction is in the entry block and is not an invoke,
  205. // then it obviously dominates all phi nodes.
  206. if (I->getParent()->isEntryBlock() && !isa<InvokeInst>(I) &&
  207. !isa<CallBrInst>(I))
  208. return true;
  209. return false;
  210. }
  211. /// Try to simplify a binary operator of form "V op OtherOp" where V is
  212. /// "(B0 opex B1)" by distributing 'op' across 'opex' as
  213. /// "(B0 op OtherOp) opex (B1 op OtherOp)".
  214. static Value *expandBinOp(Instruction::BinaryOps Opcode, Value *V,
  215. Value *OtherOp, Instruction::BinaryOps OpcodeToExpand,
  216. const SimplifyQuery &Q, unsigned MaxRecurse) {
  217. auto *B = dyn_cast<BinaryOperator>(V);
  218. if (!B || B->getOpcode() != OpcodeToExpand)
  219. return nullptr;
  220. Value *B0 = B->getOperand(0), *B1 = B->getOperand(1);
  221. Value *L =
  222. simplifyBinOp(Opcode, B0, OtherOp, Q.getWithoutUndef(), MaxRecurse);
  223. if (!L)
  224. return nullptr;
  225. Value *R =
  226. simplifyBinOp(Opcode, B1, OtherOp, Q.getWithoutUndef(), MaxRecurse);
  227. if (!R)
  228. return nullptr;
  229. // Does the expanded pair of binops simplify to the existing binop?
  230. if ((L == B0 && R == B1) ||
  231. (Instruction::isCommutative(OpcodeToExpand) && L == B1 && R == B0)) {
  232. ++NumExpand;
  233. return B;
  234. }
  235. // Otherwise, return "L op' R" if it simplifies.
  236. Value *S = simplifyBinOp(OpcodeToExpand, L, R, Q, MaxRecurse);
  237. if (!S)
  238. return nullptr;
  239. ++NumExpand;
  240. return S;
  241. }
  242. /// Try to simplify binops of form "A op (B op' C)" or the commuted variant by
  243. /// distributing op over op'.
  244. static Value *expandCommutativeBinOp(Instruction::BinaryOps Opcode, Value *L,
  245. Value *R,
  246. Instruction::BinaryOps OpcodeToExpand,
  247. const SimplifyQuery &Q,
  248. unsigned MaxRecurse) {
  249. // Recursion is always used, so bail out at once if we already hit the limit.
  250. if (!MaxRecurse--)
  251. return nullptr;
  252. if (Value *V = expandBinOp(Opcode, L, R, OpcodeToExpand, Q, MaxRecurse))
  253. return V;
  254. if (Value *V = expandBinOp(Opcode, R, L, OpcodeToExpand, Q, MaxRecurse))
  255. return V;
  256. return nullptr;
  257. }
  258. /// Generic simplifications for associative binary operations.
  259. /// Returns the simpler value, or null if none was found.
  260. static Value *simplifyAssociativeBinOp(Instruction::BinaryOps Opcode,
  261. Value *LHS, Value *RHS,
  262. const SimplifyQuery &Q,
  263. unsigned MaxRecurse) {
  264. assert(Instruction::isAssociative(Opcode) && "Not an associative operation!");
  265. // Recursion is always used, so bail out at once if we already hit the limit.
  266. if (!MaxRecurse--)
  267. return nullptr;
  268. BinaryOperator *Op0 = dyn_cast<BinaryOperator>(LHS);
  269. BinaryOperator *Op1 = dyn_cast<BinaryOperator>(RHS);
  270. // Transform: "(A op B) op C" ==> "A op (B op C)" if it simplifies completely.
  271. if (Op0 && Op0->getOpcode() == Opcode) {
  272. Value *A = Op0->getOperand(0);
  273. Value *B = Op0->getOperand(1);
  274. Value *C = RHS;
  275. // Does "B op C" simplify?
  276. if (Value *V = simplifyBinOp(Opcode, B, C, Q, MaxRecurse)) {
  277. // It does! Return "A op V" if it simplifies or is already available.
  278. // If V equals B then "A op V" is just the LHS.
  279. if (V == B)
  280. return LHS;
  281. // Otherwise return "A op V" if it simplifies.
  282. if (Value *W = simplifyBinOp(Opcode, A, V, Q, MaxRecurse)) {
  283. ++NumReassoc;
  284. return W;
  285. }
  286. }
  287. }
  288. // Transform: "A op (B op C)" ==> "(A op B) op C" if it simplifies completely.
  289. if (Op1 && Op1->getOpcode() == Opcode) {
  290. Value *A = LHS;
  291. Value *B = Op1->getOperand(0);
  292. Value *C = Op1->getOperand(1);
  293. // Does "A op B" simplify?
  294. if (Value *V = simplifyBinOp(Opcode, A, B, Q, MaxRecurse)) {
  295. // It does! Return "V op C" if it simplifies or is already available.
  296. // If V equals B then "V op C" is just the RHS.
  297. if (V == B)
  298. return RHS;
  299. // Otherwise return "V op C" if it simplifies.
  300. if (Value *W = simplifyBinOp(Opcode, V, C, Q, MaxRecurse)) {
  301. ++NumReassoc;
  302. return W;
  303. }
  304. }
  305. }
  306. // The remaining transforms require commutativity as well as associativity.
  307. if (!Instruction::isCommutative(Opcode))
  308. return nullptr;
  309. // Transform: "(A op B) op C" ==> "(C op A) op B" if it simplifies completely.
  310. if (Op0 && Op0->getOpcode() == Opcode) {
  311. Value *A = Op0->getOperand(0);
  312. Value *B = Op0->getOperand(1);
  313. Value *C = RHS;
  314. // Does "C op A" simplify?
  315. if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
  316. // It does! Return "V op B" if it simplifies or is already available.
  317. // If V equals A then "V op B" is just the LHS.
  318. if (V == A)
  319. return LHS;
  320. // Otherwise return "V op B" if it simplifies.
  321. if (Value *W = simplifyBinOp(Opcode, V, B, Q, MaxRecurse)) {
  322. ++NumReassoc;
  323. return W;
  324. }
  325. }
  326. }
  327. // Transform: "A op (B op C)" ==> "B op (C op A)" if it simplifies completely.
  328. if (Op1 && Op1->getOpcode() == Opcode) {
  329. Value *A = LHS;
  330. Value *B = Op1->getOperand(0);
  331. Value *C = Op1->getOperand(1);
  332. // Does "C op A" simplify?
  333. if (Value *V = simplifyBinOp(Opcode, C, A, Q, MaxRecurse)) {
  334. // It does! Return "B op V" if it simplifies or is already available.
  335. // If V equals C then "B op V" is just the RHS.
  336. if (V == C)
  337. return RHS;
  338. // Otherwise return "B op V" if it simplifies.
  339. if (Value *W = simplifyBinOp(Opcode, B, V, Q, MaxRecurse)) {
  340. ++NumReassoc;
  341. return W;
  342. }
  343. }
  344. }
  345. return nullptr;
  346. }
  347. /// In the case of a binary operation with a select instruction as an operand,
  348. /// try to simplify the binop by seeing whether evaluating it on both branches
  349. /// of the select results in the same value. Returns the common value if so,
  350. /// otherwise returns null.
  351. static Value *threadBinOpOverSelect(Instruction::BinaryOps Opcode, Value *LHS,
  352. Value *RHS, const SimplifyQuery &Q,
  353. unsigned MaxRecurse) {
  354. // Recursion is always used, so bail out at once if we already hit the limit.
  355. if (!MaxRecurse--)
  356. return nullptr;
  357. SelectInst *SI;
  358. if (isa<SelectInst>(LHS)) {
  359. SI = cast<SelectInst>(LHS);
  360. } else {
  361. assert(isa<SelectInst>(RHS) && "No select instruction operand!");
  362. SI = cast<SelectInst>(RHS);
  363. }
  364. // Evaluate the BinOp on the true and false branches of the select.
  365. Value *TV;
  366. Value *FV;
  367. if (SI == LHS) {
  368. TV = simplifyBinOp(Opcode, SI->getTrueValue(), RHS, Q, MaxRecurse);
  369. FV = simplifyBinOp(Opcode, SI->getFalseValue(), RHS, Q, MaxRecurse);
  370. } else {
  371. TV = simplifyBinOp(Opcode, LHS, SI->getTrueValue(), Q, MaxRecurse);
  372. FV = simplifyBinOp(Opcode, LHS, SI->getFalseValue(), Q, MaxRecurse);
  373. }
  374. // If they simplified to the same value, then return the common value.
  375. // If they both failed to simplify then return null.
  376. if (TV == FV)
  377. return TV;
  378. // If one branch simplified to undef, return the other one.
  379. if (TV && Q.isUndefValue(TV))
  380. return FV;
  381. if (FV && Q.isUndefValue(FV))
  382. return TV;
  383. // If applying the operation did not change the true and false select values,
  384. // then the result of the binop is the select itself.
  385. if (TV == SI->getTrueValue() && FV == SI->getFalseValue())
  386. return SI;
  387. // If one branch simplified and the other did not, and the simplified
  388. // value is equal to the unsimplified one, return the simplified value.
  389. // For example, select (cond, X, X & Z) & Z -> X & Z.
  390. if ((FV && !TV) || (TV && !FV)) {
  391. // Check that the simplified value has the form "X op Y" where "op" is the
  392. // same as the original operation.
  393. Instruction *Simplified = dyn_cast<Instruction>(FV ? FV : TV);
  394. if (Simplified && Simplified->getOpcode() == unsigned(Opcode)) {
  395. // The value that didn't simplify is "UnsimplifiedLHS op UnsimplifiedRHS".
  396. // We already know that "op" is the same as for the simplified value. See
  397. // if the operands match too. If so, return the simplified value.
  398. Value *UnsimplifiedBranch = FV ? SI->getTrueValue() : SI->getFalseValue();
  399. Value *UnsimplifiedLHS = SI == LHS ? UnsimplifiedBranch : LHS;
  400. Value *UnsimplifiedRHS = SI == LHS ? RHS : UnsimplifiedBranch;
  401. if (Simplified->getOperand(0) == UnsimplifiedLHS &&
  402. Simplified->getOperand(1) == UnsimplifiedRHS)
  403. return Simplified;
  404. if (Simplified->isCommutative() &&
  405. Simplified->getOperand(1) == UnsimplifiedLHS &&
  406. Simplified->getOperand(0) == UnsimplifiedRHS)
  407. return Simplified;
  408. }
  409. }
  410. return nullptr;
  411. }
  412. /// In the case of a comparison with a select instruction, try to simplify the
  413. /// comparison by seeing whether both branches of the select result in the same
  414. /// value. Returns the common value if so, otherwise returns null.
  415. /// For example, if we have:
  416. /// %tmp = select i1 %cmp, i32 1, i32 2
  417. /// %cmp1 = icmp sle i32 %tmp, 3
  418. /// We can simplify %cmp1 to true, because both branches of select are
  419. /// less than 3. We compose new comparison by substituting %tmp with both
  420. /// branches of select and see if it can be simplified.
  421. static Value *threadCmpOverSelect(CmpInst::Predicate Pred, Value *LHS,
  422. Value *RHS, const SimplifyQuery &Q,
  423. unsigned MaxRecurse) {
  424. // Recursion is always used, so bail out at once if we already hit the limit.
  425. if (!MaxRecurse--)
  426. return nullptr;
  427. // Make sure the select is on the LHS.
  428. if (!isa<SelectInst>(LHS)) {
  429. std::swap(LHS, RHS);
  430. Pred = CmpInst::getSwappedPredicate(Pred);
  431. }
  432. assert(isa<SelectInst>(LHS) && "Not comparing with a select instruction!");
  433. SelectInst *SI = cast<SelectInst>(LHS);
  434. Value *Cond = SI->getCondition();
  435. Value *TV = SI->getTrueValue();
  436. Value *FV = SI->getFalseValue();
  437. // Now that we have "cmp select(Cond, TV, FV), RHS", analyse it.
  438. // Does "cmp TV, RHS" simplify?
  439. Value *TCmp = simplifyCmpSelTrueCase(Pred, TV, RHS, Cond, Q, MaxRecurse);
  440. if (!TCmp)
  441. return nullptr;
  442. // Does "cmp FV, RHS" simplify?
  443. Value *FCmp = simplifyCmpSelFalseCase(Pred, FV, RHS, Cond, Q, MaxRecurse);
  444. if (!FCmp)
  445. return nullptr;
  446. // If both sides simplified to the same value, then use it as the result of
  447. // the original comparison.
  448. if (TCmp == FCmp)
  449. return TCmp;
  450. // The remaining cases only make sense if the select condition has the same
  451. // type as the result of the comparison, so bail out if this is not so.
  452. if (Cond->getType()->isVectorTy() == RHS->getType()->isVectorTy())
  453. return handleOtherCmpSelSimplifications(TCmp, FCmp, Cond, Q, MaxRecurse);
  454. return nullptr;
  455. }
  456. /// In the case of a binary operation with an operand that is a PHI instruction,
  457. /// try to simplify the binop by seeing whether evaluating it on the incoming
  458. /// phi values yields the same result for every value. If so returns the common
  459. /// value, otherwise returns null.
  460. static Value *threadBinOpOverPHI(Instruction::BinaryOps Opcode, Value *LHS,
  461. Value *RHS, const SimplifyQuery &Q,
  462. unsigned MaxRecurse) {
  463. // Recursion is always used, so bail out at once if we already hit the limit.
  464. if (!MaxRecurse--)
  465. return nullptr;
  466. PHINode *PI;
  467. if (isa<PHINode>(LHS)) {
  468. PI = cast<PHINode>(LHS);
  469. // Bail out if RHS and the phi may be mutually interdependent due to a loop.
  470. if (!valueDominatesPHI(RHS, PI, Q.DT))
  471. return nullptr;
  472. } else {
  473. assert(isa<PHINode>(RHS) && "No PHI instruction operand!");
  474. PI = cast<PHINode>(RHS);
  475. // Bail out if LHS and the phi may be mutually interdependent due to a loop.
  476. if (!valueDominatesPHI(LHS, PI, Q.DT))
  477. return nullptr;
  478. }
  479. // Evaluate the BinOp on the incoming phi values.
  480. Value *CommonValue = nullptr;
  481. for (Value *Incoming : PI->incoming_values()) {
  482. // If the incoming value is the phi node itself, it can safely be skipped.
  483. if (Incoming == PI)
  484. continue;
  485. Value *V = PI == LHS ? simplifyBinOp(Opcode, Incoming, RHS, Q, MaxRecurse)
  486. : simplifyBinOp(Opcode, LHS, Incoming, Q, MaxRecurse);
  487. // If the operation failed to simplify, or simplified to a different value
  488. // to previously, then give up.
  489. if (!V || (CommonValue && V != CommonValue))
  490. return nullptr;
  491. CommonValue = V;
  492. }
  493. return CommonValue;
  494. }
  495. /// In the case of a comparison with a PHI instruction, try to simplify the
  496. /// comparison by seeing whether comparing with all of the incoming phi values
  497. /// yields the same result every time. If so returns the common result,
  498. /// otherwise returns null.
  499. static Value *threadCmpOverPHI(CmpInst::Predicate Pred, Value *LHS, Value *RHS,
  500. const SimplifyQuery &Q, unsigned MaxRecurse) {
  501. // Recursion is always used, so bail out at once if we already hit the limit.
  502. if (!MaxRecurse--)
  503. return nullptr;
  504. // Make sure the phi is on the LHS.
  505. if (!isa<PHINode>(LHS)) {
  506. std::swap(LHS, RHS);
  507. Pred = CmpInst::getSwappedPredicate(Pred);
  508. }
  509. assert(isa<PHINode>(LHS) && "Not comparing with a phi instruction!");
  510. PHINode *PI = cast<PHINode>(LHS);
  511. // Bail out if RHS and the phi may be mutually interdependent due to a loop.
  512. if (!valueDominatesPHI(RHS, PI, Q.DT))
  513. return nullptr;
  514. // Evaluate the BinOp on the incoming phi values.
  515. Value *CommonValue = nullptr;
  516. for (unsigned u = 0, e = PI->getNumIncomingValues(); u < e; ++u) {
  517. Value *Incoming = PI->getIncomingValue(u);
  518. Instruction *InTI = PI->getIncomingBlock(u)->getTerminator();
  519. // If the incoming value is the phi node itself, it can safely be skipped.
  520. if (Incoming == PI)
  521. continue;
  522. // Change the context instruction to the "edge" that flows into the phi.
  523. // This is important because that is where incoming is actually "evaluated"
  524. // even though it is used later somewhere else.
  525. Value *V = simplifyCmpInst(Pred, Incoming, RHS, Q.getWithInstruction(InTI),
  526. MaxRecurse);
  527. // If the operation failed to simplify, or simplified to a different value
  528. // to previously, then give up.
  529. if (!V || (CommonValue && V != CommonValue))
  530. return nullptr;
  531. CommonValue = V;
  532. }
  533. return CommonValue;
  534. }
  535. static Constant *foldOrCommuteConstant(Instruction::BinaryOps Opcode,
  536. Value *&Op0, Value *&Op1,
  537. const SimplifyQuery &Q) {
  538. if (auto *CLHS = dyn_cast<Constant>(Op0)) {
  539. if (auto *CRHS = dyn_cast<Constant>(Op1)) {
  540. switch (Opcode) {
  541. default:
  542. break;
  543. case Instruction::FAdd:
  544. case Instruction::FSub:
  545. case Instruction::FMul:
  546. case Instruction::FDiv:
  547. case Instruction::FRem:
  548. if (Q.CxtI != nullptr)
  549. return ConstantFoldFPInstOperands(Opcode, CLHS, CRHS, Q.DL, Q.CxtI);
  550. }
  551. return ConstantFoldBinaryOpOperands(Opcode, CLHS, CRHS, Q.DL);
  552. }
  553. // Canonicalize the constant to the RHS if this is a commutative operation.
  554. if (Instruction::isCommutative(Opcode))
  555. std::swap(Op0, Op1);
  556. }
  557. return nullptr;
  558. }
  559. /// Given operands for an Add, see if we can fold the result.
  560. /// If not, this returns null.
  561. static Value *simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
  562. const SimplifyQuery &Q, unsigned MaxRecurse) {
  563. if (Constant *C = foldOrCommuteConstant(Instruction::Add, Op0, Op1, Q))
  564. return C;
  565. // X + poison -> poison
  566. if (isa<PoisonValue>(Op1))
  567. return Op1;
  568. // X + undef -> undef
  569. if (Q.isUndefValue(Op1))
  570. return Op1;
  571. // X + 0 -> X
  572. if (match(Op1, m_Zero()))
  573. return Op0;
  574. // If two operands are negative, return 0.
  575. if (isKnownNegation(Op0, Op1))
  576. return Constant::getNullValue(Op0->getType());
  577. // X + (Y - X) -> Y
  578. // (Y - X) + X -> Y
  579. // Eg: X + -X -> 0
  580. Value *Y = nullptr;
  581. if (match(Op1, m_Sub(m_Value(Y), m_Specific(Op0))) ||
  582. match(Op0, m_Sub(m_Value(Y), m_Specific(Op1))))
  583. return Y;
  584. // X + ~X -> -1 since ~X = -X-1
  585. Type *Ty = Op0->getType();
  586. if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
  587. return Constant::getAllOnesValue(Ty);
  588. // add nsw/nuw (xor Y, signmask), signmask --> Y
  589. // The no-wrapping add guarantees that the top bit will be set by the add.
  590. // Therefore, the xor must be clearing the already set sign bit of Y.
  591. if ((IsNSW || IsNUW) && match(Op1, m_SignMask()) &&
  592. match(Op0, m_Xor(m_Value(Y), m_SignMask())))
  593. return Y;
  594. // add nuw %x, -1 -> -1, because %x can only be 0.
  595. if (IsNUW && match(Op1, m_AllOnes()))
  596. return Op1; // Which is -1.
  597. /// i1 add -> xor.
  598. if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
  599. if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
  600. return V;
  601. // Try some generic simplifications for associative operations.
  602. if (Value *V =
  603. simplifyAssociativeBinOp(Instruction::Add, Op0, Op1, Q, MaxRecurse))
  604. return V;
  605. // Threading Add over selects and phi nodes is pointless, so don't bother.
  606. // Threading over the select in "A + select(cond, B, C)" means evaluating
  607. // "A+B" and "A+C" and seeing if they are equal; but they are equal if and
  608. // only if B and C are equal. If B and C are equal then (since we assume
  609. // that operands have already been simplified) "select(cond, B, C)" should
  610. // have been simplified to the common value of B and C already. Analysing
  611. // "A+B" and "A+C" thus gains nothing, but costs compile time. Similarly
  612. // for threading over phi nodes.
  613. return nullptr;
  614. }
  615. Value *llvm::simplifyAddInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
  616. const SimplifyQuery &Query) {
  617. return ::simplifyAddInst(Op0, Op1, IsNSW, IsNUW, Query, RecursionLimit);
  618. }
  619. /// Compute the base pointer and cumulative constant offsets for V.
  620. ///
  621. /// This strips all constant offsets off of V, leaving it the base pointer, and
  622. /// accumulates the total constant offset applied in the returned constant.
  623. /// It returns zero if there are no constant offsets applied.
  624. ///
  625. /// This is very similar to stripAndAccumulateConstantOffsets(), except it
  626. /// normalizes the offset bitwidth to the stripped pointer type, not the
  627. /// original pointer type.
  628. static APInt stripAndComputeConstantOffsets(const DataLayout &DL, Value *&V,
  629. bool AllowNonInbounds = false) {
  630. assert(V->getType()->isPtrOrPtrVectorTy());
  631. APInt Offset = APInt::getZero(DL.getIndexTypeSizeInBits(V->getType()));
  632. V = V->stripAndAccumulateConstantOffsets(DL, Offset, AllowNonInbounds);
  633. // As that strip may trace through `addrspacecast`, need to sext or trunc
  634. // the offset calculated.
  635. return Offset.sextOrTrunc(DL.getIndexTypeSizeInBits(V->getType()));
  636. }
  637. /// Compute the constant difference between two pointer values.
  638. /// If the difference is not a constant, returns zero.
  639. static Constant *computePointerDifference(const DataLayout &DL, Value *LHS,
  640. Value *RHS) {
  641. APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS);
  642. APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS);
  643. // If LHS and RHS are not related via constant offsets to the same base
  644. // value, there is nothing we can do here.
  645. if (LHS != RHS)
  646. return nullptr;
  647. // Otherwise, the difference of LHS - RHS can be computed as:
  648. // LHS - RHS
  649. // = (LHSOffset + Base) - (RHSOffset + Base)
  650. // = LHSOffset - RHSOffset
  651. Constant *Res = ConstantInt::get(LHS->getContext(), LHSOffset - RHSOffset);
  652. if (auto *VecTy = dyn_cast<VectorType>(LHS->getType()))
  653. Res = ConstantVector::getSplat(VecTy->getElementCount(), Res);
  654. return Res;
  655. }
  656. /// Test if there is a dominating equivalence condition for the
  657. /// two operands. If there is, try to reduce the binary operation
  658. /// between the two operands.
  659. /// Example: Op0 - Op1 --> 0 when Op0 == Op1
  660. static Value *simplifyByDomEq(unsigned Opcode, Value *Op0, Value *Op1,
  661. const SimplifyQuery &Q, unsigned MaxRecurse) {
  662. // Recursive run it can not get any benefit
  663. if (MaxRecurse != RecursionLimit)
  664. return nullptr;
  665. std::optional<bool> Imp =
  666. isImpliedByDomCondition(CmpInst::ICMP_EQ, Op0, Op1, Q.CxtI, Q.DL);
  667. if (Imp && *Imp) {
  668. Type *Ty = Op0->getType();
  669. switch (Opcode) {
  670. case Instruction::Sub:
  671. case Instruction::Xor:
  672. case Instruction::URem:
  673. case Instruction::SRem:
  674. return Constant::getNullValue(Ty);
  675. case Instruction::SDiv:
  676. case Instruction::UDiv:
  677. return ConstantInt::get(Ty, 1);
  678. case Instruction::And:
  679. case Instruction::Or:
  680. // Could be either one - choose Op1 since that's more likely a constant.
  681. return Op1;
  682. default:
  683. break;
  684. }
  685. }
  686. return nullptr;
  687. }
  688. /// Given operands for a Sub, see if we can fold the result.
  689. /// If not, this returns null.
  690. static Value *simplifySubInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
  691. const SimplifyQuery &Q, unsigned MaxRecurse) {
  692. if (Constant *C = foldOrCommuteConstant(Instruction::Sub, Op0, Op1, Q))
  693. return C;
  694. // X - poison -> poison
  695. // poison - X -> poison
  696. if (isa<PoisonValue>(Op0) || isa<PoisonValue>(Op1))
  697. return PoisonValue::get(Op0->getType());
  698. // X - undef -> undef
  699. // undef - X -> undef
  700. if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
  701. return UndefValue::get(Op0->getType());
  702. // X - 0 -> X
  703. if (match(Op1, m_Zero()))
  704. return Op0;
  705. // X - X -> 0
  706. if (Op0 == Op1)
  707. return Constant::getNullValue(Op0->getType());
  708. // Is this a negation?
  709. if (match(Op0, m_Zero())) {
  710. // 0 - X -> 0 if the sub is NUW.
  711. if (IsNUW)
  712. return Constant::getNullValue(Op0->getType());
  713. KnownBits Known = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  714. if (Known.Zero.isMaxSignedValue()) {
  715. // Op1 is either 0 or the minimum signed value. If the sub is NSW, then
  716. // Op1 must be 0 because negating the minimum signed value is undefined.
  717. if (IsNSW)
  718. return Constant::getNullValue(Op0->getType());
  719. // 0 - X -> X if X is 0 or the minimum signed value.
  720. return Op1;
  721. }
  722. }
  723. // (X + Y) - Z -> X + (Y - Z) or Y + (X - Z) if everything simplifies.
  724. // For example, (X + Y) - Y -> X; (Y + X) - Y -> X
  725. Value *X = nullptr, *Y = nullptr, *Z = Op1;
  726. if (MaxRecurse && match(Op0, m_Add(m_Value(X), m_Value(Y)))) { // (X + Y) - Z
  727. // See if "V === Y - Z" simplifies.
  728. if (Value *V = simplifyBinOp(Instruction::Sub, Y, Z, Q, MaxRecurse - 1))
  729. // It does! Now see if "X + V" simplifies.
  730. if (Value *W = simplifyBinOp(Instruction::Add, X, V, Q, MaxRecurse - 1)) {
  731. // It does, we successfully reassociated!
  732. ++NumReassoc;
  733. return W;
  734. }
  735. // See if "V === X - Z" simplifies.
  736. if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
  737. // It does! Now see if "Y + V" simplifies.
  738. if (Value *W = simplifyBinOp(Instruction::Add, Y, V, Q, MaxRecurse - 1)) {
  739. // It does, we successfully reassociated!
  740. ++NumReassoc;
  741. return W;
  742. }
  743. }
  744. // X - (Y + Z) -> (X - Y) - Z or (X - Z) - Y if everything simplifies.
  745. // For example, X - (X + 1) -> -1
  746. X = Op0;
  747. if (MaxRecurse && match(Op1, m_Add(m_Value(Y), m_Value(Z)))) { // X - (Y + Z)
  748. // See if "V === X - Y" simplifies.
  749. if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
  750. // It does! Now see if "V - Z" simplifies.
  751. if (Value *W = simplifyBinOp(Instruction::Sub, V, Z, Q, MaxRecurse - 1)) {
  752. // It does, we successfully reassociated!
  753. ++NumReassoc;
  754. return W;
  755. }
  756. // See if "V === X - Z" simplifies.
  757. if (Value *V = simplifyBinOp(Instruction::Sub, X, Z, Q, MaxRecurse - 1))
  758. // It does! Now see if "V - Y" simplifies.
  759. if (Value *W = simplifyBinOp(Instruction::Sub, V, Y, Q, MaxRecurse - 1)) {
  760. // It does, we successfully reassociated!
  761. ++NumReassoc;
  762. return W;
  763. }
  764. }
  765. // Z - (X - Y) -> (Z - X) + Y if everything simplifies.
  766. // For example, X - (X - Y) -> Y.
  767. Z = Op0;
  768. if (MaxRecurse && match(Op1, m_Sub(m_Value(X), m_Value(Y)))) // Z - (X - Y)
  769. // See if "V === Z - X" simplifies.
  770. if (Value *V = simplifyBinOp(Instruction::Sub, Z, X, Q, MaxRecurse - 1))
  771. // It does! Now see if "V + Y" simplifies.
  772. if (Value *W = simplifyBinOp(Instruction::Add, V, Y, Q, MaxRecurse - 1)) {
  773. // It does, we successfully reassociated!
  774. ++NumReassoc;
  775. return W;
  776. }
  777. // trunc(X) - trunc(Y) -> trunc(X - Y) if everything simplifies.
  778. if (MaxRecurse && match(Op0, m_Trunc(m_Value(X))) &&
  779. match(Op1, m_Trunc(m_Value(Y))))
  780. if (X->getType() == Y->getType())
  781. // See if "V === X - Y" simplifies.
  782. if (Value *V = simplifyBinOp(Instruction::Sub, X, Y, Q, MaxRecurse - 1))
  783. // It does! Now see if "trunc V" simplifies.
  784. if (Value *W = simplifyCastInst(Instruction::Trunc, V, Op0->getType(),
  785. Q, MaxRecurse - 1))
  786. // It does, return the simplified "trunc V".
  787. return W;
  788. // Variations on GEP(base, I, ...) - GEP(base, i, ...) -> GEP(null, I-i, ...).
  789. if (match(Op0, m_PtrToInt(m_Value(X))) && match(Op1, m_PtrToInt(m_Value(Y))))
  790. if (Constant *Result = computePointerDifference(Q.DL, X, Y))
  791. return ConstantExpr::getIntegerCast(Result, Op0->getType(), true);
  792. // i1 sub -> xor.
  793. if (MaxRecurse && Op0->getType()->isIntOrIntVectorTy(1))
  794. if (Value *V = simplifyXorInst(Op0, Op1, Q, MaxRecurse - 1))
  795. return V;
  796. // Threading Sub over selects and phi nodes is pointless, so don't bother.
  797. // Threading over the select in "A - select(cond, B, C)" means evaluating
  798. // "A-B" and "A-C" and seeing if they are equal; but they are equal if and
  799. // only if B and C are equal. If B and C are equal then (since we assume
  800. // that operands have already been simplified) "select(cond, B, C)" should
  801. // have been simplified to the common value of B and C already. Analysing
  802. // "A-B" and "A-C" thus gains nothing, but costs compile time. Similarly
  803. // for threading over phi nodes.
  804. if (Value *V = simplifyByDomEq(Instruction::Sub, Op0, Op1, Q, MaxRecurse))
  805. return V;
  806. return nullptr;
  807. }
  808. Value *llvm::simplifySubInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
  809. const SimplifyQuery &Q) {
  810. return ::simplifySubInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
  811. }
  812. /// Given operands for a Mul, see if we can fold the result.
  813. /// If not, this returns null.
  814. static Value *simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
  815. const SimplifyQuery &Q, unsigned MaxRecurse) {
  816. if (Constant *C = foldOrCommuteConstant(Instruction::Mul, Op0, Op1, Q))
  817. return C;
  818. // X * poison -> poison
  819. if (isa<PoisonValue>(Op1))
  820. return Op1;
  821. // X * undef -> 0
  822. // X * 0 -> 0
  823. if (Q.isUndefValue(Op1) || match(Op1, m_Zero()))
  824. return Constant::getNullValue(Op0->getType());
  825. // X * 1 -> X
  826. if (match(Op1, m_One()))
  827. return Op0;
  828. // (X / Y) * Y -> X if the division is exact.
  829. Value *X = nullptr;
  830. if (Q.IIQ.UseInstrInfo &&
  831. (match(Op0,
  832. m_Exact(m_IDiv(m_Value(X), m_Specific(Op1)))) || // (X / Y) * Y
  833. match(Op1, m_Exact(m_IDiv(m_Value(X), m_Specific(Op0)))))) // Y * (X / Y)
  834. return X;
  835. if (Op0->getType()->isIntOrIntVectorTy(1)) {
  836. // mul i1 nsw is a special-case because -1 * -1 is poison (+1 is not
  837. // representable). All other cases reduce to 0, so just return 0.
  838. if (IsNSW)
  839. return ConstantInt::getNullValue(Op0->getType());
  840. // Treat "mul i1" as "and i1".
  841. if (MaxRecurse)
  842. if (Value *V = simplifyAndInst(Op0, Op1, Q, MaxRecurse - 1))
  843. return V;
  844. }
  845. // Try some generic simplifications for associative operations.
  846. if (Value *V =
  847. simplifyAssociativeBinOp(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
  848. return V;
  849. // Mul distributes over Add. Try some generic simplifications based on this.
  850. if (Value *V = expandCommutativeBinOp(Instruction::Mul, Op0, Op1,
  851. Instruction::Add, Q, MaxRecurse))
  852. return V;
  853. // If the operation is with the result of a select instruction, check whether
  854. // operating on either branch of the select always yields the same value.
  855. if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
  856. if (Value *V =
  857. threadBinOpOverSelect(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
  858. return V;
  859. // If the operation is with the result of a phi instruction, check whether
  860. // operating on all incoming values of the phi always yields the same value.
  861. if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
  862. if (Value *V =
  863. threadBinOpOverPHI(Instruction::Mul, Op0, Op1, Q, MaxRecurse))
  864. return V;
  865. return nullptr;
  866. }
  867. Value *llvm::simplifyMulInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
  868. const SimplifyQuery &Q) {
  869. return ::simplifyMulInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
  870. }
  871. /// Check for common or similar folds of integer division or integer remainder.
  872. /// This applies to all 4 opcodes (sdiv/udiv/srem/urem).
  873. static Value *simplifyDivRem(Instruction::BinaryOps Opcode, Value *Op0,
  874. Value *Op1, const SimplifyQuery &Q,
  875. unsigned MaxRecurse) {
  876. bool IsDiv = (Opcode == Instruction::SDiv || Opcode == Instruction::UDiv);
  877. bool IsSigned = (Opcode == Instruction::SDiv || Opcode == Instruction::SRem);
  878. Type *Ty = Op0->getType();
  879. // X / undef -> poison
  880. // X % undef -> poison
  881. if (Q.isUndefValue(Op1) || isa<PoisonValue>(Op1))
  882. return PoisonValue::get(Ty);
  883. // X / 0 -> poison
  884. // X % 0 -> poison
  885. // We don't need to preserve faults!
  886. if (match(Op1, m_Zero()))
  887. return PoisonValue::get(Ty);
  888. // If any element of a constant divisor fixed width vector is zero or undef
  889. // the behavior is undefined and we can fold the whole op to poison.
  890. auto *Op1C = dyn_cast<Constant>(Op1);
  891. auto *VTy = dyn_cast<FixedVectorType>(Ty);
  892. if (Op1C && VTy) {
  893. unsigned NumElts = VTy->getNumElements();
  894. for (unsigned i = 0; i != NumElts; ++i) {
  895. Constant *Elt = Op1C->getAggregateElement(i);
  896. if (Elt && (Elt->isNullValue() || Q.isUndefValue(Elt)))
  897. return PoisonValue::get(Ty);
  898. }
  899. }
  900. // poison / X -> poison
  901. // poison % X -> poison
  902. if (isa<PoisonValue>(Op0))
  903. return Op0;
  904. // undef / X -> 0
  905. // undef % X -> 0
  906. if (Q.isUndefValue(Op0))
  907. return Constant::getNullValue(Ty);
  908. // 0 / X -> 0
  909. // 0 % X -> 0
  910. if (match(Op0, m_Zero()))
  911. return Constant::getNullValue(Op0->getType());
  912. // X / X -> 1
  913. // X % X -> 0
  914. if (Op0 == Op1)
  915. return IsDiv ? ConstantInt::get(Ty, 1) : Constant::getNullValue(Ty);
  916. // X / 1 -> X
  917. // X % 1 -> 0
  918. // If this is a boolean op (single-bit element type), we can't have
  919. // division-by-zero or remainder-by-zero, so assume the divisor is 1.
  920. // Similarly, if we're zero-extending a boolean divisor, then assume it's a 1.
  921. Value *X;
  922. if (match(Op1, m_One()) || Ty->isIntOrIntVectorTy(1) ||
  923. (match(Op1, m_ZExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
  924. return IsDiv ? Op0 : Constant::getNullValue(Ty);
  925. // If X * Y does not overflow, then:
  926. // X * Y / Y -> X
  927. // X * Y % Y -> 0
  928. if (match(Op0, m_c_Mul(m_Value(X), m_Specific(Op1)))) {
  929. auto *Mul = cast<OverflowingBinaryOperator>(Op0);
  930. // The multiplication can't overflow if it is defined not to, or if
  931. // X == A / Y for some A.
  932. if ((IsSigned && Q.IIQ.hasNoSignedWrap(Mul)) ||
  933. (!IsSigned && Q.IIQ.hasNoUnsignedWrap(Mul)) ||
  934. (IsSigned && match(X, m_SDiv(m_Value(), m_Specific(Op1)))) ||
  935. (!IsSigned && match(X, m_UDiv(m_Value(), m_Specific(Op1))))) {
  936. return IsDiv ? X : Constant::getNullValue(Op0->getType());
  937. }
  938. }
  939. if (Value *V = simplifyByDomEq(Opcode, Op0, Op1, Q, MaxRecurse))
  940. return V;
  941. return nullptr;
  942. }
  943. /// Given a predicate and two operands, return true if the comparison is true.
  944. /// This is a helper for div/rem simplification where we return some other value
  945. /// when we can prove a relationship between the operands.
  946. static bool isICmpTrue(ICmpInst::Predicate Pred, Value *LHS, Value *RHS,
  947. const SimplifyQuery &Q, unsigned MaxRecurse) {
  948. Value *V = simplifyICmpInst(Pred, LHS, RHS, Q, MaxRecurse);
  949. Constant *C = dyn_cast_or_null<Constant>(V);
  950. return (C && C->isAllOnesValue());
  951. }
  952. /// Return true if we can simplify X / Y to 0. Remainder can adapt that answer
  953. /// to simplify X % Y to X.
  954. static bool isDivZero(Value *X, Value *Y, const SimplifyQuery &Q,
  955. unsigned MaxRecurse, bool IsSigned) {
  956. // Recursion is always used, so bail out at once if we already hit the limit.
  957. if (!MaxRecurse--)
  958. return false;
  959. if (IsSigned) {
  960. // |X| / |Y| --> 0
  961. //
  962. // We require that 1 operand is a simple constant. That could be extended to
  963. // 2 variables if we computed the sign bit for each.
  964. //
  965. // Make sure that a constant is not the minimum signed value because taking
  966. // the abs() of that is undefined.
  967. Type *Ty = X->getType();
  968. const APInt *C;
  969. if (match(X, m_APInt(C)) && !C->isMinSignedValue()) {
  970. // Is the variable divisor magnitude always greater than the constant
  971. // dividend magnitude?
  972. // |Y| > |C| --> Y < -abs(C) or Y > abs(C)
  973. Constant *PosDividendC = ConstantInt::get(Ty, C->abs());
  974. Constant *NegDividendC = ConstantInt::get(Ty, -C->abs());
  975. if (isICmpTrue(CmpInst::ICMP_SLT, Y, NegDividendC, Q, MaxRecurse) ||
  976. isICmpTrue(CmpInst::ICMP_SGT, Y, PosDividendC, Q, MaxRecurse))
  977. return true;
  978. }
  979. if (match(Y, m_APInt(C))) {
  980. // Special-case: we can't take the abs() of a minimum signed value. If
  981. // that's the divisor, then all we have to do is prove that the dividend
  982. // is also not the minimum signed value.
  983. if (C->isMinSignedValue())
  984. return isICmpTrue(CmpInst::ICMP_NE, X, Y, Q, MaxRecurse);
  985. // Is the variable dividend magnitude always less than the constant
  986. // divisor magnitude?
  987. // |X| < |C| --> X > -abs(C) and X < abs(C)
  988. Constant *PosDivisorC = ConstantInt::get(Ty, C->abs());
  989. Constant *NegDivisorC = ConstantInt::get(Ty, -C->abs());
  990. if (isICmpTrue(CmpInst::ICMP_SGT, X, NegDivisorC, Q, MaxRecurse) &&
  991. isICmpTrue(CmpInst::ICMP_SLT, X, PosDivisorC, Q, MaxRecurse))
  992. return true;
  993. }
  994. return false;
  995. }
  996. // IsSigned == false.
  997. // Is the unsigned dividend known to be less than a constant divisor?
  998. // TODO: Convert this (and above) to range analysis
  999. // ("computeConstantRangeIncludingKnownBits")?
  1000. const APInt *C;
  1001. if (match(Y, m_APInt(C)) &&
  1002. computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT).getMaxValue().ult(*C))
  1003. return true;
  1004. // Try again for any divisor:
  1005. // Is the dividend unsigned less than the divisor?
  1006. return isICmpTrue(ICmpInst::ICMP_ULT, X, Y, Q, MaxRecurse);
  1007. }
  1008. /// These are simplifications common to SDiv and UDiv.
  1009. static Value *simplifyDiv(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
  1010. bool IsExact, const SimplifyQuery &Q,
  1011. unsigned MaxRecurse) {
  1012. if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
  1013. return C;
  1014. if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
  1015. return V;
  1016. // If this is an exact divide by a constant, then the dividend (Op0) must have
  1017. // at least as many trailing zeros as the divisor to divide evenly. If it has
  1018. // less trailing zeros, then the result must be poison.
  1019. const APInt *DivC;
  1020. if (IsExact && match(Op1, m_APInt(DivC)) && DivC->countTrailingZeros()) {
  1021. KnownBits KnownOp0 = computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  1022. if (KnownOp0.countMaxTrailingZeros() < DivC->countTrailingZeros())
  1023. return PoisonValue::get(Op0->getType());
  1024. }
  1025. bool IsSigned = Opcode == Instruction::SDiv;
  1026. // (X rem Y) / Y -> 0
  1027. if ((IsSigned && match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
  1028. (!IsSigned && match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
  1029. return Constant::getNullValue(Op0->getType());
  1030. // (X /u C1) /u C2 -> 0 if C1 * C2 overflow
  1031. ConstantInt *C1, *C2;
  1032. if (!IsSigned && match(Op0, m_UDiv(m_Value(), m_ConstantInt(C1))) &&
  1033. match(Op1, m_ConstantInt(C2))) {
  1034. bool Overflow;
  1035. (void)C1->getValue().umul_ov(C2->getValue(), Overflow);
  1036. if (Overflow)
  1037. return Constant::getNullValue(Op0->getType());
  1038. }
  1039. // If the operation is with the result of a select instruction, check whether
  1040. // operating on either branch of the select always yields the same value.
  1041. if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
  1042. if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
  1043. return V;
  1044. // If the operation is with the result of a phi instruction, check whether
  1045. // operating on all incoming values of the phi always yields the same value.
  1046. if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
  1047. if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
  1048. return V;
  1049. if (isDivZero(Op0, Op1, Q, MaxRecurse, IsSigned))
  1050. return Constant::getNullValue(Op0->getType());
  1051. return nullptr;
  1052. }
  1053. /// These are simplifications common to SRem and URem.
  1054. static Value *simplifyRem(Instruction::BinaryOps Opcode, Value *Op0, Value *Op1,
  1055. const SimplifyQuery &Q, unsigned MaxRecurse) {
  1056. if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
  1057. return C;
  1058. if (Value *V = simplifyDivRem(Opcode, Op0, Op1, Q, MaxRecurse))
  1059. return V;
  1060. // (X % Y) % Y -> X % Y
  1061. if ((Opcode == Instruction::SRem &&
  1062. match(Op0, m_SRem(m_Value(), m_Specific(Op1)))) ||
  1063. (Opcode == Instruction::URem &&
  1064. match(Op0, m_URem(m_Value(), m_Specific(Op1)))))
  1065. return Op0;
  1066. // (X << Y) % X -> 0
  1067. if (Q.IIQ.UseInstrInfo &&
  1068. ((Opcode == Instruction::SRem &&
  1069. match(Op0, m_NSWShl(m_Specific(Op1), m_Value()))) ||
  1070. (Opcode == Instruction::URem &&
  1071. match(Op0, m_NUWShl(m_Specific(Op1), m_Value())))))
  1072. return Constant::getNullValue(Op0->getType());
  1073. // If the operation is with the result of a select instruction, check whether
  1074. // operating on either branch of the select always yields the same value.
  1075. if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
  1076. if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
  1077. return V;
  1078. // If the operation is with the result of a phi instruction, check whether
  1079. // operating on all incoming values of the phi always yields the same value.
  1080. if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
  1081. if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
  1082. return V;
  1083. // If X / Y == 0, then X % Y == X.
  1084. if (isDivZero(Op0, Op1, Q, MaxRecurse, Opcode == Instruction::SRem))
  1085. return Op0;
  1086. return nullptr;
  1087. }
  1088. /// Given operands for an SDiv, see if we can fold the result.
  1089. /// If not, this returns null.
  1090. static Value *simplifySDivInst(Value *Op0, Value *Op1, bool IsExact,
  1091. const SimplifyQuery &Q, unsigned MaxRecurse) {
  1092. // If two operands are negated and no signed overflow, return -1.
  1093. if (isKnownNegation(Op0, Op1, /*NeedNSW=*/true))
  1094. return Constant::getAllOnesValue(Op0->getType());
  1095. return simplifyDiv(Instruction::SDiv, Op0, Op1, IsExact, Q, MaxRecurse);
  1096. }
  1097. Value *llvm::simplifySDivInst(Value *Op0, Value *Op1, bool IsExact,
  1098. const SimplifyQuery &Q) {
  1099. return ::simplifySDivInst(Op0, Op1, IsExact, Q, RecursionLimit);
  1100. }
  1101. /// Given operands for a UDiv, see if we can fold the result.
  1102. /// If not, this returns null.
  1103. static Value *simplifyUDivInst(Value *Op0, Value *Op1, bool IsExact,
  1104. const SimplifyQuery &Q, unsigned MaxRecurse) {
  1105. return simplifyDiv(Instruction::UDiv, Op0, Op1, IsExact, Q, MaxRecurse);
  1106. }
  1107. Value *llvm::simplifyUDivInst(Value *Op0, Value *Op1, bool IsExact,
  1108. const SimplifyQuery &Q) {
  1109. return ::simplifyUDivInst(Op0, Op1, IsExact, Q, RecursionLimit);
  1110. }
  1111. /// Given operands for an SRem, see if we can fold the result.
  1112. /// If not, this returns null.
  1113. static Value *simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
  1114. unsigned MaxRecurse) {
  1115. // If the divisor is 0, the result is undefined, so assume the divisor is -1.
  1116. // srem Op0, (sext i1 X) --> srem Op0, -1 --> 0
  1117. Value *X;
  1118. if (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1))
  1119. return ConstantInt::getNullValue(Op0->getType());
  1120. // If the two operands are negated, return 0.
  1121. if (isKnownNegation(Op0, Op1))
  1122. return ConstantInt::getNullValue(Op0->getType());
  1123. return simplifyRem(Instruction::SRem, Op0, Op1, Q, MaxRecurse);
  1124. }
  1125. Value *llvm::simplifySRemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
  1126. return ::simplifySRemInst(Op0, Op1, Q, RecursionLimit);
  1127. }
  1128. /// Given operands for a URem, see if we can fold the result.
  1129. /// If not, this returns null.
  1130. static Value *simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
  1131. unsigned MaxRecurse) {
  1132. return simplifyRem(Instruction::URem, Op0, Op1, Q, MaxRecurse);
  1133. }
  1134. Value *llvm::simplifyURemInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
  1135. return ::simplifyURemInst(Op0, Op1, Q, RecursionLimit);
  1136. }
  1137. /// Returns true if a shift by \c Amount always yields poison.
  1138. static bool isPoisonShift(Value *Amount, const SimplifyQuery &Q) {
  1139. Constant *C = dyn_cast<Constant>(Amount);
  1140. if (!C)
  1141. return false;
  1142. // X shift by undef -> poison because it may shift by the bitwidth.
  1143. if (Q.isUndefValue(C))
  1144. return true;
  1145. // Shifting by the bitwidth or more is poison. This covers scalars and
  1146. // fixed/scalable vectors with splat constants.
  1147. const APInt *AmountC;
  1148. if (match(C, m_APInt(AmountC)) && AmountC->uge(AmountC->getBitWidth()))
  1149. return true;
  1150. // Try harder for fixed-length vectors:
  1151. // If all lanes of a vector shift are poison, the whole shift is poison.
  1152. if (isa<ConstantVector>(C) || isa<ConstantDataVector>(C)) {
  1153. for (unsigned I = 0,
  1154. E = cast<FixedVectorType>(C->getType())->getNumElements();
  1155. I != E; ++I)
  1156. if (!isPoisonShift(C->getAggregateElement(I), Q))
  1157. return false;
  1158. return true;
  1159. }
  1160. return false;
  1161. }
  1162. /// Given operands for an Shl, LShr or AShr, see if we can fold the result.
  1163. /// If not, this returns null.
  1164. static Value *simplifyShift(Instruction::BinaryOps Opcode, Value *Op0,
  1165. Value *Op1, bool IsNSW, const SimplifyQuery &Q,
  1166. unsigned MaxRecurse) {
  1167. if (Constant *C = foldOrCommuteConstant(Opcode, Op0, Op1, Q))
  1168. return C;
  1169. // poison shift by X -> poison
  1170. if (isa<PoisonValue>(Op0))
  1171. return Op0;
  1172. // 0 shift by X -> 0
  1173. if (match(Op0, m_Zero()))
  1174. return Constant::getNullValue(Op0->getType());
  1175. // X shift by 0 -> X
  1176. // Shift-by-sign-extended bool must be shift-by-0 because shift-by-all-ones
  1177. // would be poison.
  1178. Value *X;
  1179. if (match(Op1, m_Zero()) ||
  1180. (match(Op1, m_SExt(m_Value(X))) && X->getType()->isIntOrIntVectorTy(1)))
  1181. return Op0;
  1182. // Fold undefined shifts.
  1183. if (isPoisonShift(Op1, Q))
  1184. return PoisonValue::get(Op0->getType());
  1185. // If the operation is with the result of a select instruction, check whether
  1186. // operating on either branch of the select always yields the same value.
  1187. if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1))
  1188. if (Value *V = threadBinOpOverSelect(Opcode, Op0, Op1, Q, MaxRecurse))
  1189. return V;
  1190. // If the operation is with the result of a phi instruction, check whether
  1191. // operating on all incoming values of the phi always yields the same value.
  1192. if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
  1193. if (Value *V = threadBinOpOverPHI(Opcode, Op0, Op1, Q, MaxRecurse))
  1194. return V;
  1195. // If any bits in the shift amount make that value greater than or equal to
  1196. // the number of bits in the type, the shift is undefined.
  1197. KnownBits KnownAmt = computeKnownBits(Op1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  1198. if (KnownAmt.getMinValue().uge(KnownAmt.getBitWidth()))
  1199. return PoisonValue::get(Op0->getType());
  1200. // If all valid bits in the shift amount are known zero, the first operand is
  1201. // unchanged.
  1202. unsigned NumValidShiftBits = Log2_32_Ceil(KnownAmt.getBitWidth());
  1203. if (KnownAmt.countMinTrailingZeros() >= NumValidShiftBits)
  1204. return Op0;
  1205. // Check for nsw shl leading to a poison value.
  1206. if (IsNSW) {
  1207. assert(Opcode == Instruction::Shl && "Expected shl for nsw instruction");
  1208. KnownBits KnownVal = computeKnownBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  1209. KnownBits KnownShl = KnownBits::shl(KnownVal, KnownAmt);
  1210. if (KnownVal.Zero.isSignBitSet())
  1211. KnownShl.Zero.setSignBit();
  1212. if (KnownVal.One.isSignBitSet())
  1213. KnownShl.One.setSignBit();
  1214. if (KnownShl.hasConflict())
  1215. return PoisonValue::get(Op0->getType());
  1216. }
  1217. return nullptr;
  1218. }
  1219. /// Given operands for an Shl, LShr or AShr, see if we can
  1220. /// fold the result. If not, this returns null.
  1221. static Value *simplifyRightShift(Instruction::BinaryOps Opcode, Value *Op0,
  1222. Value *Op1, bool IsExact,
  1223. const SimplifyQuery &Q, unsigned MaxRecurse) {
  1224. if (Value *V =
  1225. simplifyShift(Opcode, Op0, Op1, /*IsNSW*/ false, Q, MaxRecurse))
  1226. return V;
  1227. // X >> X -> 0
  1228. if (Op0 == Op1)
  1229. return Constant::getNullValue(Op0->getType());
  1230. // undef >> X -> 0
  1231. // undef >> X -> undef (if it's exact)
  1232. if (Q.isUndefValue(Op0))
  1233. return IsExact ? Op0 : Constant::getNullValue(Op0->getType());
  1234. // The low bit cannot be shifted out of an exact shift if it is set.
  1235. // TODO: Generalize by counting trailing zeros (see fold for exact division).
  1236. if (IsExact) {
  1237. KnownBits Op0Known =
  1238. computeKnownBits(Op0, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT);
  1239. if (Op0Known.One[0])
  1240. return Op0;
  1241. }
  1242. return nullptr;
  1243. }
  1244. /// Given operands for an Shl, see if we can fold the result.
  1245. /// If not, this returns null.
  1246. static Value *simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
  1247. const SimplifyQuery &Q, unsigned MaxRecurse) {
  1248. if (Value *V =
  1249. simplifyShift(Instruction::Shl, Op0, Op1, IsNSW, Q, MaxRecurse))
  1250. return V;
  1251. // undef << X -> 0
  1252. // undef << X -> undef if (if it's NSW/NUW)
  1253. if (Q.isUndefValue(Op0))
  1254. return IsNSW || IsNUW ? Op0 : Constant::getNullValue(Op0->getType());
  1255. // (X >> A) << A -> X
  1256. Value *X;
  1257. if (Q.IIQ.UseInstrInfo &&
  1258. match(Op0, m_Exact(m_Shr(m_Value(X), m_Specific(Op1)))))
  1259. return X;
  1260. // shl nuw i8 C, %x -> C iff C has sign bit set.
  1261. if (IsNUW && match(Op0, m_Negative()))
  1262. return Op0;
  1263. // NOTE: could use computeKnownBits() / LazyValueInfo,
  1264. // but the cost-benefit analysis suggests it isn't worth it.
  1265. return nullptr;
  1266. }
  1267. Value *llvm::simplifyShlInst(Value *Op0, Value *Op1, bool IsNSW, bool IsNUW,
  1268. const SimplifyQuery &Q) {
  1269. return ::simplifyShlInst(Op0, Op1, IsNSW, IsNUW, Q, RecursionLimit);
  1270. }
  1271. /// Given operands for an LShr, see if we can fold the result.
  1272. /// If not, this returns null.
  1273. static Value *simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
  1274. const SimplifyQuery &Q, unsigned MaxRecurse) {
  1275. if (Value *V = simplifyRightShift(Instruction::LShr, Op0, Op1, IsExact, Q,
  1276. MaxRecurse))
  1277. return V;
  1278. // (X << A) >> A -> X
  1279. Value *X;
  1280. if (match(Op0, m_NUWShl(m_Value(X), m_Specific(Op1))))
  1281. return X;
  1282. // ((X << A) | Y) >> A -> X if effective width of Y is not larger than A.
  1283. // We can return X as we do in the above case since OR alters no bits in X.
  1284. // SimplifyDemandedBits in InstCombine can do more general optimization for
  1285. // bit manipulation. This pattern aims to provide opportunities for other
  1286. // optimizers by supporting a simple but common case in InstSimplify.
  1287. Value *Y;
  1288. const APInt *ShRAmt, *ShLAmt;
  1289. if (match(Op1, m_APInt(ShRAmt)) &&
  1290. match(Op0, m_c_Or(m_NUWShl(m_Value(X), m_APInt(ShLAmt)), m_Value(Y))) &&
  1291. *ShRAmt == *ShLAmt) {
  1292. const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  1293. const unsigned EffWidthY = YKnown.countMaxActiveBits();
  1294. if (ShRAmt->uge(EffWidthY))
  1295. return X;
  1296. }
  1297. return nullptr;
  1298. }
  1299. Value *llvm::simplifyLShrInst(Value *Op0, Value *Op1, bool IsExact,
  1300. const SimplifyQuery &Q) {
  1301. return ::simplifyLShrInst(Op0, Op1, IsExact, Q, RecursionLimit);
  1302. }
  1303. /// Given operands for an AShr, see if we can fold the result.
  1304. /// If not, this returns null.
  1305. static Value *simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
  1306. const SimplifyQuery &Q, unsigned MaxRecurse) {
  1307. if (Value *V = simplifyRightShift(Instruction::AShr, Op0, Op1, IsExact, Q,
  1308. MaxRecurse))
  1309. return V;
  1310. // -1 >>a X --> -1
  1311. // (-1 << X) a>> X --> -1
  1312. // Do not return Op0 because it may contain undef elements if it's a vector.
  1313. if (match(Op0, m_AllOnes()) ||
  1314. match(Op0, m_Shl(m_AllOnes(), m_Specific(Op1))))
  1315. return Constant::getAllOnesValue(Op0->getType());
  1316. // (X << A) >> A -> X
  1317. Value *X;
  1318. if (Q.IIQ.UseInstrInfo && match(Op0, m_NSWShl(m_Value(X), m_Specific(Op1))))
  1319. return X;
  1320. // Arithmetic shifting an all-sign-bit value is a no-op.
  1321. unsigned NumSignBits = ComputeNumSignBits(Op0, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  1322. if (NumSignBits == Op0->getType()->getScalarSizeInBits())
  1323. return Op0;
  1324. return nullptr;
  1325. }
  1326. Value *llvm::simplifyAShrInst(Value *Op0, Value *Op1, bool IsExact,
  1327. const SimplifyQuery &Q) {
  1328. return ::simplifyAShrInst(Op0, Op1, IsExact, Q, RecursionLimit);
  1329. }
  1330. /// Commuted variants are assumed to be handled by calling this function again
  1331. /// with the parameters swapped.
  1332. static Value *simplifyUnsignedRangeCheck(ICmpInst *ZeroICmp,
  1333. ICmpInst *UnsignedICmp, bool IsAnd,
  1334. const SimplifyQuery &Q) {
  1335. Value *X, *Y;
  1336. ICmpInst::Predicate EqPred;
  1337. if (!match(ZeroICmp, m_ICmp(EqPred, m_Value(Y), m_Zero())) ||
  1338. !ICmpInst::isEquality(EqPred))
  1339. return nullptr;
  1340. ICmpInst::Predicate UnsignedPred;
  1341. Value *A, *B;
  1342. // Y = (A - B);
  1343. if (match(Y, m_Sub(m_Value(A), m_Value(B)))) {
  1344. if (match(UnsignedICmp,
  1345. m_c_ICmp(UnsignedPred, m_Specific(A), m_Specific(B))) &&
  1346. ICmpInst::isUnsigned(UnsignedPred)) {
  1347. // A >=/<= B || (A - B) != 0 <--> true
  1348. if ((UnsignedPred == ICmpInst::ICMP_UGE ||
  1349. UnsignedPred == ICmpInst::ICMP_ULE) &&
  1350. EqPred == ICmpInst::ICMP_NE && !IsAnd)
  1351. return ConstantInt::getTrue(UnsignedICmp->getType());
  1352. // A </> B && (A - B) == 0 <--> false
  1353. if ((UnsignedPred == ICmpInst::ICMP_ULT ||
  1354. UnsignedPred == ICmpInst::ICMP_UGT) &&
  1355. EqPred == ICmpInst::ICMP_EQ && IsAnd)
  1356. return ConstantInt::getFalse(UnsignedICmp->getType());
  1357. // A </> B && (A - B) != 0 <--> A </> B
  1358. // A </> B || (A - B) != 0 <--> (A - B) != 0
  1359. if (EqPred == ICmpInst::ICMP_NE && (UnsignedPred == ICmpInst::ICMP_ULT ||
  1360. UnsignedPred == ICmpInst::ICMP_UGT))
  1361. return IsAnd ? UnsignedICmp : ZeroICmp;
  1362. // A <=/>= B && (A - B) == 0 <--> (A - B) == 0
  1363. // A <=/>= B || (A - B) == 0 <--> A <=/>= B
  1364. if (EqPred == ICmpInst::ICMP_EQ && (UnsignedPred == ICmpInst::ICMP_ULE ||
  1365. UnsignedPred == ICmpInst::ICMP_UGE))
  1366. return IsAnd ? ZeroICmp : UnsignedICmp;
  1367. }
  1368. // Given Y = (A - B)
  1369. // Y >= A && Y != 0 --> Y >= A iff B != 0
  1370. // Y < A || Y == 0 --> Y < A iff B != 0
  1371. if (match(UnsignedICmp,
  1372. m_c_ICmp(UnsignedPred, m_Specific(Y), m_Specific(A)))) {
  1373. if (UnsignedPred == ICmpInst::ICMP_UGE && IsAnd &&
  1374. EqPred == ICmpInst::ICMP_NE &&
  1375. isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
  1376. return UnsignedICmp;
  1377. if (UnsignedPred == ICmpInst::ICMP_ULT && !IsAnd &&
  1378. EqPred == ICmpInst::ICMP_EQ &&
  1379. isKnownNonZero(B, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
  1380. return UnsignedICmp;
  1381. }
  1382. }
  1383. if (match(UnsignedICmp, m_ICmp(UnsignedPred, m_Value(X), m_Specific(Y))) &&
  1384. ICmpInst::isUnsigned(UnsignedPred))
  1385. ;
  1386. else if (match(UnsignedICmp,
  1387. m_ICmp(UnsignedPred, m_Specific(Y), m_Value(X))) &&
  1388. ICmpInst::isUnsigned(UnsignedPred))
  1389. UnsignedPred = ICmpInst::getSwappedPredicate(UnsignedPred);
  1390. else
  1391. return nullptr;
  1392. // X > Y && Y == 0 --> Y == 0 iff X != 0
  1393. // X > Y || Y == 0 --> X > Y iff X != 0
  1394. if (UnsignedPred == ICmpInst::ICMP_UGT && EqPred == ICmpInst::ICMP_EQ &&
  1395. isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
  1396. return IsAnd ? ZeroICmp : UnsignedICmp;
  1397. // X <= Y && Y != 0 --> X <= Y iff X != 0
  1398. // X <= Y || Y != 0 --> Y != 0 iff X != 0
  1399. if (UnsignedPred == ICmpInst::ICMP_ULE && EqPred == ICmpInst::ICMP_NE &&
  1400. isKnownNonZero(X, Q.DL, /*Depth=*/0, Q.AC, Q.CxtI, Q.DT))
  1401. return IsAnd ? UnsignedICmp : ZeroICmp;
  1402. // The transforms below here are expected to be handled more generally with
  1403. // simplifyAndOrOfICmpsWithLimitConst() or in InstCombine's
  1404. // foldAndOrOfICmpsWithConstEq(). If we are looking to trim optimizer overlap,
  1405. // these are candidates for removal.
  1406. // X < Y && Y != 0 --> X < Y
  1407. // X < Y || Y != 0 --> Y != 0
  1408. if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_NE)
  1409. return IsAnd ? UnsignedICmp : ZeroICmp;
  1410. // X >= Y && Y == 0 --> Y == 0
  1411. // X >= Y || Y == 0 --> X >= Y
  1412. if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_EQ)
  1413. return IsAnd ? ZeroICmp : UnsignedICmp;
  1414. // X < Y && Y == 0 --> false
  1415. if (UnsignedPred == ICmpInst::ICMP_ULT && EqPred == ICmpInst::ICMP_EQ &&
  1416. IsAnd)
  1417. return getFalse(UnsignedICmp->getType());
  1418. // X >= Y || Y != 0 --> true
  1419. if (UnsignedPred == ICmpInst::ICMP_UGE && EqPred == ICmpInst::ICMP_NE &&
  1420. !IsAnd)
  1421. return getTrue(UnsignedICmp->getType());
  1422. return nullptr;
  1423. }
  1424. /// Test if a pair of compares with a shared operand and 2 constants has an
  1425. /// empty set intersection, full set union, or if one compare is a superset of
  1426. /// the other.
  1427. static Value *simplifyAndOrOfICmpsWithConstants(ICmpInst *Cmp0, ICmpInst *Cmp1,
  1428. bool IsAnd) {
  1429. // Look for this pattern: {and/or} (icmp X, C0), (icmp X, C1)).
  1430. if (Cmp0->getOperand(0) != Cmp1->getOperand(0))
  1431. return nullptr;
  1432. const APInt *C0, *C1;
  1433. if (!match(Cmp0->getOperand(1), m_APInt(C0)) ||
  1434. !match(Cmp1->getOperand(1), m_APInt(C1)))
  1435. return nullptr;
  1436. auto Range0 = ConstantRange::makeExactICmpRegion(Cmp0->getPredicate(), *C0);
  1437. auto Range1 = ConstantRange::makeExactICmpRegion(Cmp1->getPredicate(), *C1);
  1438. // For and-of-compares, check if the intersection is empty:
  1439. // (icmp X, C0) && (icmp X, C1) --> empty set --> false
  1440. if (IsAnd && Range0.intersectWith(Range1).isEmptySet())
  1441. return getFalse(Cmp0->getType());
  1442. // For or-of-compares, check if the union is full:
  1443. // (icmp X, C0) || (icmp X, C1) --> full set --> true
  1444. if (!IsAnd && Range0.unionWith(Range1).isFullSet())
  1445. return getTrue(Cmp0->getType());
  1446. // Is one range a superset of the other?
  1447. // If this is and-of-compares, take the smaller set:
  1448. // (icmp sgt X, 4) && (icmp sgt X, 42) --> icmp sgt X, 42
  1449. // If this is or-of-compares, take the larger set:
  1450. // (icmp sgt X, 4) || (icmp sgt X, 42) --> icmp sgt X, 4
  1451. if (Range0.contains(Range1))
  1452. return IsAnd ? Cmp1 : Cmp0;
  1453. if (Range1.contains(Range0))
  1454. return IsAnd ? Cmp0 : Cmp1;
  1455. return nullptr;
  1456. }
  1457. static Value *simplifyAndOrOfICmpsWithZero(ICmpInst *Cmp0, ICmpInst *Cmp1,
  1458. bool IsAnd) {
  1459. ICmpInst::Predicate P0 = Cmp0->getPredicate(), P1 = Cmp1->getPredicate();
  1460. if (!match(Cmp0->getOperand(1), m_Zero()) ||
  1461. !match(Cmp1->getOperand(1), m_Zero()) || P0 != P1)
  1462. return nullptr;
  1463. if ((IsAnd && P0 != ICmpInst::ICMP_NE) || (!IsAnd && P1 != ICmpInst::ICMP_EQ))
  1464. return nullptr;
  1465. // We have either "(X == 0 || Y == 0)" or "(X != 0 && Y != 0)".
  1466. Value *X = Cmp0->getOperand(0);
  1467. Value *Y = Cmp1->getOperand(0);
  1468. // If one of the compares is a masked version of a (not) null check, then
  1469. // that compare implies the other, so we eliminate the other. Optionally, look
  1470. // through a pointer-to-int cast to match a null check of a pointer type.
  1471. // (X == 0) || (([ptrtoint] X & ?) == 0) --> ([ptrtoint] X & ?) == 0
  1472. // (X == 0) || ((? & [ptrtoint] X) == 0) --> (? & [ptrtoint] X) == 0
  1473. // (X != 0) && (([ptrtoint] X & ?) != 0) --> ([ptrtoint] X & ?) != 0
  1474. // (X != 0) && ((? & [ptrtoint] X) != 0) --> (? & [ptrtoint] X) != 0
  1475. if (match(Y, m_c_And(m_Specific(X), m_Value())) ||
  1476. match(Y, m_c_And(m_PtrToInt(m_Specific(X)), m_Value())))
  1477. return Cmp1;
  1478. // (([ptrtoint] Y & ?) == 0) || (Y == 0) --> ([ptrtoint] Y & ?) == 0
  1479. // ((? & [ptrtoint] Y) == 0) || (Y == 0) --> (? & [ptrtoint] Y) == 0
  1480. // (([ptrtoint] Y & ?) != 0) && (Y != 0) --> ([ptrtoint] Y & ?) != 0
  1481. // ((? & [ptrtoint] Y) != 0) && (Y != 0) --> (? & [ptrtoint] Y) != 0
  1482. if (match(X, m_c_And(m_Specific(Y), m_Value())) ||
  1483. match(X, m_c_And(m_PtrToInt(m_Specific(Y)), m_Value())))
  1484. return Cmp0;
  1485. return nullptr;
  1486. }
  1487. static Value *simplifyAndOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
  1488. const InstrInfoQuery &IIQ) {
  1489. // (icmp (add V, C0), C1) & (icmp V, C0)
  1490. ICmpInst::Predicate Pred0, Pred1;
  1491. const APInt *C0, *C1;
  1492. Value *V;
  1493. if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
  1494. return nullptr;
  1495. if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
  1496. return nullptr;
  1497. auto *AddInst = cast<OverflowingBinaryOperator>(Op0->getOperand(0));
  1498. if (AddInst->getOperand(1) != Op1->getOperand(1))
  1499. return nullptr;
  1500. Type *ITy = Op0->getType();
  1501. bool IsNSW = IIQ.hasNoSignedWrap(AddInst);
  1502. bool IsNUW = IIQ.hasNoUnsignedWrap(AddInst);
  1503. const APInt Delta = *C1 - *C0;
  1504. if (C0->isStrictlyPositive()) {
  1505. if (Delta == 2) {
  1506. if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_SGT)
  1507. return getFalse(ITy);
  1508. if (Pred0 == ICmpInst::ICMP_SLT && Pred1 == ICmpInst::ICMP_SGT && IsNSW)
  1509. return getFalse(ITy);
  1510. }
  1511. if (Delta == 1) {
  1512. if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_SGT)
  1513. return getFalse(ITy);
  1514. if (Pred0 == ICmpInst::ICMP_SLE && Pred1 == ICmpInst::ICMP_SGT && IsNSW)
  1515. return getFalse(ITy);
  1516. }
  1517. }
  1518. if (C0->getBoolValue() && IsNUW) {
  1519. if (Delta == 2)
  1520. if (Pred0 == ICmpInst::ICMP_ULT && Pred1 == ICmpInst::ICMP_UGT)
  1521. return getFalse(ITy);
  1522. if (Delta == 1)
  1523. if (Pred0 == ICmpInst::ICMP_ULE && Pred1 == ICmpInst::ICMP_UGT)
  1524. return getFalse(ITy);
  1525. }
  1526. return nullptr;
  1527. }
  1528. /// Try to eliminate compares with signed or unsigned min/max constants.
  1529. static Value *simplifyAndOrOfICmpsWithLimitConst(ICmpInst *Cmp0, ICmpInst *Cmp1,
  1530. bool IsAnd) {
  1531. // Canonicalize an equality compare as Cmp0.
  1532. if (Cmp1->isEquality())
  1533. std::swap(Cmp0, Cmp1);
  1534. if (!Cmp0->isEquality())
  1535. return nullptr;
  1536. // The non-equality compare must include a common operand (X). Canonicalize
  1537. // the common operand as operand 0 (the predicate is swapped if the common
  1538. // operand was operand 1).
  1539. ICmpInst::Predicate Pred0 = Cmp0->getPredicate();
  1540. Value *X = Cmp0->getOperand(0);
  1541. ICmpInst::Predicate Pred1;
  1542. bool HasNotOp = match(Cmp1, m_c_ICmp(Pred1, m_Not(m_Specific(X)), m_Value()));
  1543. if (!HasNotOp && !match(Cmp1, m_c_ICmp(Pred1, m_Specific(X), m_Value())))
  1544. return nullptr;
  1545. if (ICmpInst::isEquality(Pred1))
  1546. return nullptr;
  1547. // The equality compare must be against a constant. Flip bits if we matched
  1548. // a bitwise not. Convert a null pointer constant to an integer zero value.
  1549. APInt MinMaxC;
  1550. const APInt *C;
  1551. if (match(Cmp0->getOperand(1), m_APInt(C)))
  1552. MinMaxC = HasNotOp ? ~*C : *C;
  1553. else if (isa<ConstantPointerNull>(Cmp0->getOperand(1)))
  1554. MinMaxC = APInt::getZero(8);
  1555. else
  1556. return nullptr;
  1557. // DeMorganize if this is 'or': P0 || P1 --> !P0 && !P1.
  1558. if (!IsAnd) {
  1559. Pred0 = ICmpInst::getInversePredicate(Pred0);
  1560. Pred1 = ICmpInst::getInversePredicate(Pred1);
  1561. }
  1562. // Normalize to unsigned compare and unsigned min/max value.
  1563. // Example for 8-bit: -128 + 128 -> 0; 127 + 128 -> 255
  1564. if (ICmpInst::isSigned(Pred1)) {
  1565. Pred1 = ICmpInst::getUnsignedPredicate(Pred1);
  1566. MinMaxC += APInt::getSignedMinValue(MinMaxC.getBitWidth());
  1567. }
  1568. // (X != MAX) && (X < Y) --> X < Y
  1569. // (X == MAX) || (X >= Y) --> X >= Y
  1570. if (MinMaxC.isMaxValue())
  1571. if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_ULT)
  1572. return Cmp1;
  1573. // (X != MIN) && (X > Y) --> X > Y
  1574. // (X == MIN) || (X <= Y) --> X <= Y
  1575. if (MinMaxC.isMinValue())
  1576. if (Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_UGT)
  1577. return Cmp1;
  1578. return nullptr;
  1579. }
  1580. /// Try to simplify and/or of icmp with ctpop intrinsic.
  1581. static Value *simplifyAndOrOfICmpsWithCtpop(ICmpInst *Cmp0, ICmpInst *Cmp1,
  1582. bool IsAnd) {
  1583. ICmpInst::Predicate Pred0, Pred1;
  1584. Value *X;
  1585. const APInt *C;
  1586. if (!match(Cmp0, m_ICmp(Pred0, m_Intrinsic<Intrinsic::ctpop>(m_Value(X)),
  1587. m_APInt(C))) ||
  1588. !match(Cmp1, m_ICmp(Pred1, m_Specific(X), m_ZeroInt())) || C->isZero())
  1589. return nullptr;
  1590. // (ctpop(X) == C) || (X != 0) --> X != 0 where C > 0
  1591. if (!IsAnd && Pred0 == ICmpInst::ICMP_EQ && Pred1 == ICmpInst::ICMP_NE)
  1592. return Cmp1;
  1593. // (ctpop(X) != C) && (X == 0) --> X == 0 where C > 0
  1594. if (IsAnd && Pred0 == ICmpInst::ICMP_NE && Pred1 == ICmpInst::ICMP_EQ)
  1595. return Cmp1;
  1596. return nullptr;
  1597. }
  1598. static Value *simplifyAndOfICmps(ICmpInst *Op0, ICmpInst *Op1,
  1599. const SimplifyQuery &Q) {
  1600. if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/true, Q))
  1601. return X;
  1602. if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/true, Q))
  1603. return X;
  1604. if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, true))
  1605. return X;
  1606. if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, true))
  1607. return X;
  1608. if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, true))
  1609. return X;
  1610. if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, true))
  1611. return X;
  1612. if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, true))
  1613. return X;
  1614. if (Value *X = simplifyAndOfICmpsWithAdd(Op0, Op1, Q.IIQ))
  1615. return X;
  1616. if (Value *X = simplifyAndOfICmpsWithAdd(Op1, Op0, Q.IIQ))
  1617. return X;
  1618. return nullptr;
  1619. }
  1620. static Value *simplifyOrOfICmpsWithAdd(ICmpInst *Op0, ICmpInst *Op1,
  1621. const InstrInfoQuery &IIQ) {
  1622. // (icmp (add V, C0), C1) | (icmp V, C0)
  1623. ICmpInst::Predicate Pred0, Pred1;
  1624. const APInt *C0, *C1;
  1625. Value *V;
  1626. if (!match(Op0, m_ICmp(Pred0, m_Add(m_Value(V), m_APInt(C0)), m_APInt(C1))))
  1627. return nullptr;
  1628. if (!match(Op1, m_ICmp(Pred1, m_Specific(V), m_Value())))
  1629. return nullptr;
  1630. auto *AddInst = cast<BinaryOperator>(Op0->getOperand(0));
  1631. if (AddInst->getOperand(1) != Op1->getOperand(1))
  1632. return nullptr;
  1633. Type *ITy = Op0->getType();
  1634. bool IsNSW = IIQ.hasNoSignedWrap(AddInst);
  1635. bool IsNUW = IIQ.hasNoUnsignedWrap(AddInst);
  1636. const APInt Delta = *C1 - *C0;
  1637. if (C0->isStrictlyPositive()) {
  1638. if (Delta == 2) {
  1639. if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_SLE)
  1640. return getTrue(ITy);
  1641. if (Pred0 == ICmpInst::ICMP_SGE && Pred1 == ICmpInst::ICMP_SLE && IsNSW)
  1642. return getTrue(ITy);
  1643. }
  1644. if (Delta == 1) {
  1645. if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_SLE)
  1646. return getTrue(ITy);
  1647. if (Pred0 == ICmpInst::ICMP_SGT && Pred1 == ICmpInst::ICMP_SLE && IsNSW)
  1648. return getTrue(ITy);
  1649. }
  1650. }
  1651. if (C0->getBoolValue() && IsNUW) {
  1652. if (Delta == 2)
  1653. if (Pred0 == ICmpInst::ICMP_UGE && Pred1 == ICmpInst::ICMP_ULE)
  1654. return getTrue(ITy);
  1655. if (Delta == 1)
  1656. if (Pred0 == ICmpInst::ICMP_UGT && Pred1 == ICmpInst::ICMP_ULE)
  1657. return getTrue(ITy);
  1658. }
  1659. return nullptr;
  1660. }
  1661. static Value *simplifyOrOfICmps(ICmpInst *Op0, ICmpInst *Op1,
  1662. const SimplifyQuery &Q) {
  1663. if (Value *X = simplifyUnsignedRangeCheck(Op0, Op1, /*IsAnd=*/false, Q))
  1664. return X;
  1665. if (Value *X = simplifyUnsignedRangeCheck(Op1, Op0, /*IsAnd=*/false, Q))
  1666. return X;
  1667. if (Value *X = simplifyAndOrOfICmpsWithConstants(Op0, Op1, false))
  1668. return X;
  1669. if (Value *X = simplifyAndOrOfICmpsWithLimitConst(Op0, Op1, false))
  1670. return X;
  1671. if (Value *X = simplifyAndOrOfICmpsWithZero(Op0, Op1, false))
  1672. return X;
  1673. if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op0, Op1, false))
  1674. return X;
  1675. if (Value *X = simplifyAndOrOfICmpsWithCtpop(Op1, Op0, false))
  1676. return X;
  1677. if (Value *X = simplifyOrOfICmpsWithAdd(Op0, Op1, Q.IIQ))
  1678. return X;
  1679. if (Value *X = simplifyOrOfICmpsWithAdd(Op1, Op0, Q.IIQ))
  1680. return X;
  1681. return nullptr;
  1682. }
  1683. static Value *simplifyAndOrOfFCmps(const TargetLibraryInfo *TLI, FCmpInst *LHS,
  1684. FCmpInst *RHS, bool IsAnd) {
  1685. Value *LHS0 = LHS->getOperand(0), *LHS1 = LHS->getOperand(1);
  1686. Value *RHS0 = RHS->getOperand(0), *RHS1 = RHS->getOperand(1);
  1687. if (LHS0->getType() != RHS0->getType())
  1688. return nullptr;
  1689. FCmpInst::Predicate PredL = LHS->getPredicate(), PredR = RHS->getPredicate();
  1690. if ((PredL == FCmpInst::FCMP_ORD && PredR == FCmpInst::FCMP_ORD && IsAnd) ||
  1691. (PredL == FCmpInst::FCMP_UNO && PredR == FCmpInst::FCMP_UNO && !IsAnd)) {
  1692. // (fcmp ord NNAN, X) & (fcmp ord X, Y) --> fcmp ord X, Y
  1693. // (fcmp ord NNAN, X) & (fcmp ord Y, X) --> fcmp ord Y, X
  1694. // (fcmp ord X, NNAN) & (fcmp ord X, Y) --> fcmp ord X, Y
  1695. // (fcmp ord X, NNAN) & (fcmp ord Y, X) --> fcmp ord Y, X
  1696. // (fcmp uno NNAN, X) | (fcmp uno X, Y) --> fcmp uno X, Y
  1697. // (fcmp uno NNAN, X) | (fcmp uno Y, X) --> fcmp uno Y, X
  1698. // (fcmp uno X, NNAN) | (fcmp uno X, Y) --> fcmp uno X, Y
  1699. // (fcmp uno X, NNAN) | (fcmp uno Y, X) --> fcmp uno Y, X
  1700. if ((isKnownNeverNaN(LHS0, TLI) && (LHS1 == RHS0 || LHS1 == RHS1)) ||
  1701. (isKnownNeverNaN(LHS1, TLI) && (LHS0 == RHS0 || LHS0 == RHS1)))
  1702. return RHS;
  1703. // (fcmp ord X, Y) & (fcmp ord NNAN, X) --> fcmp ord X, Y
  1704. // (fcmp ord Y, X) & (fcmp ord NNAN, X) --> fcmp ord Y, X
  1705. // (fcmp ord X, Y) & (fcmp ord X, NNAN) --> fcmp ord X, Y
  1706. // (fcmp ord Y, X) & (fcmp ord X, NNAN) --> fcmp ord Y, X
  1707. // (fcmp uno X, Y) | (fcmp uno NNAN, X) --> fcmp uno X, Y
  1708. // (fcmp uno Y, X) | (fcmp uno NNAN, X) --> fcmp uno Y, X
  1709. // (fcmp uno X, Y) | (fcmp uno X, NNAN) --> fcmp uno X, Y
  1710. // (fcmp uno Y, X) | (fcmp uno X, NNAN) --> fcmp uno Y, X
  1711. if ((isKnownNeverNaN(RHS0, TLI) && (RHS1 == LHS0 || RHS1 == LHS1)) ||
  1712. (isKnownNeverNaN(RHS1, TLI) && (RHS0 == LHS0 || RHS0 == LHS1)))
  1713. return LHS;
  1714. }
  1715. return nullptr;
  1716. }
  1717. static Value *simplifyAndOrOfCmps(const SimplifyQuery &Q, Value *Op0,
  1718. Value *Op1, bool IsAnd) {
  1719. // Look through casts of the 'and' operands to find compares.
  1720. auto *Cast0 = dyn_cast<CastInst>(Op0);
  1721. auto *Cast1 = dyn_cast<CastInst>(Op1);
  1722. if (Cast0 && Cast1 && Cast0->getOpcode() == Cast1->getOpcode() &&
  1723. Cast0->getSrcTy() == Cast1->getSrcTy()) {
  1724. Op0 = Cast0->getOperand(0);
  1725. Op1 = Cast1->getOperand(0);
  1726. }
  1727. Value *V = nullptr;
  1728. auto *ICmp0 = dyn_cast<ICmpInst>(Op0);
  1729. auto *ICmp1 = dyn_cast<ICmpInst>(Op1);
  1730. if (ICmp0 && ICmp1)
  1731. V = IsAnd ? simplifyAndOfICmps(ICmp0, ICmp1, Q)
  1732. : simplifyOrOfICmps(ICmp0, ICmp1, Q);
  1733. auto *FCmp0 = dyn_cast<FCmpInst>(Op0);
  1734. auto *FCmp1 = dyn_cast<FCmpInst>(Op1);
  1735. if (FCmp0 && FCmp1)
  1736. V = simplifyAndOrOfFCmps(Q.TLI, FCmp0, FCmp1, IsAnd);
  1737. if (!V)
  1738. return nullptr;
  1739. if (!Cast0)
  1740. return V;
  1741. // If we looked through casts, we can only handle a constant simplification
  1742. // because we are not allowed to create a cast instruction here.
  1743. if (auto *C = dyn_cast<Constant>(V))
  1744. return ConstantExpr::getCast(Cast0->getOpcode(), C, Cast0->getType());
  1745. return nullptr;
  1746. }
  1747. /// Given a bitwise logic op, check if the operands are add/sub with a common
  1748. /// source value and inverted constant (identity: C - X -> ~(X + ~C)).
  1749. static Value *simplifyLogicOfAddSub(Value *Op0, Value *Op1,
  1750. Instruction::BinaryOps Opcode) {
  1751. assert(Op0->getType() == Op1->getType() && "Mismatched binop types");
  1752. assert(BinaryOperator::isBitwiseLogicOp(Opcode) && "Expected logic op");
  1753. Value *X;
  1754. Constant *C1, *C2;
  1755. if ((match(Op0, m_Add(m_Value(X), m_Constant(C1))) &&
  1756. match(Op1, m_Sub(m_Constant(C2), m_Specific(X)))) ||
  1757. (match(Op1, m_Add(m_Value(X), m_Constant(C1))) &&
  1758. match(Op0, m_Sub(m_Constant(C2), m_Specific(X))))) {
  1759. if (ConstantExpr::getNot(C1) == C2) {
  1760. // (X + C) & (~C - X) --> (X + C) & ~(X + C) --> 0
  1761. // (X + C) | (~C - X) --> (X + C) | ~(X + C) --> -1
  1762. // (X + C) ^ (~C - X) --> (X + C) ^ ~(X + C) --> -1
  1763. Type *Ty = Op0->getType();
  1764. return Opcode == Instruction::And ? ConstantInt::getNullValue(Ty)
  1765. : ConstantInt::getAllOnesValue(Ty);
  1766. }
  1767. }
  1768. return nullptr;
  1769. }
  1770. /// Given operands for an And, see if we can fold the result.
  1771. /// If not, this returns null.
  1772. static Value *simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
  1773. unsigned MaxRecurse) {
  1774. if (Constant *C = foldOrCommuteConstant(Instruction::And, Op0, Op1, Q))
  1775. return C;
  1776. // X & poison -> poison
  1777. if (isa<PoisonValue>(Op1))
  1778. return Op1;
  1779. // X & undef -> 0
  1780. if (Q.isUndefValue(Op1))
  1781. return Constant::getNullValue(Op0->getType());
  1782. // X & X = X
  1783. if (Op0 == Op1)
  1784. return Op0;
  1785. // X & 0 = 0
  1786. if (match(Op1, m_Zero()))
  1787. return Constant::getNullValue(Op0->getType());
  1788. // X & -1 = X
  1789. if (match(Op1, m_AllOnes()))
  1790. return Op0;
  1791. // A & ~A = ~A & A = 0
  1792. if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
  1793. return Constant::getNullValue(Op0->getType());
  1794. // (A | ?) & A = A
  1795. if (match(Op0, m_c_Or(m_Specific(Op1), m_Value())))
  1796. return Op1;
  1797. // A & (A | ?) = A
  1798. if (match(Op1, m_c_Or(m_Specific(Op0), m_Value())))
  1799. return Op0;
  1800. // (X | Y) & (X | ~Y) --> X (commuted 8 ways)
  1801. Value *X, *Y;
  1802. if (match(Op0, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
  1803. match(Op1, m_c_Or(m_Deferred(X), m_Deferred(Y))))
  1804. return X;
  1805. if (match(Op1, m_c_Or(m_Value(X), m_Not(m_Value(Y)))) &&
  1806. match(Op0, m_c_Or(m_Deferred(X), m_Deferred(Y))))
  1807. return X;
  1808. if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::And))
  1809. return V;
  1810. // A mask that only clears known zeros of a shifted value is a no-op.
  1811. const APInt *Mask;
  1812. const APInt *ShAmt;
  1813. if (match(Op1, m_APInt(Mask))) {
  1814. // If all bits in the inverted and shifted mask are clear:
  1815. // and (shl X, ShAmt), Mask --> shl X, ShAmt
  1816. if (match(Op0, m_Shl(m_Value(X), m_APInt(ShAmt))) &&
  1817. (~(*Mask)).lshr(*ShAmt).isZero())
  1818. return Op0;
  1819. // If all bits in the inverted and shifted mask are clear:
  1820. // and (lshr X, ShAmt), Mask --> lshr X, ShAmt
  1821. if (match(Op0, m_LShr(m_Value(X), m_APInt(ShAmt))) &&
  1822. (~(*Mask)).shl(*ShAmt).isZero())
  1823. return Op0;
  1824. }
  1825. // If we have a multiplication overflow check that is being 'and'ed with a
  1826. // check that one of the multipliers is not zero, we can omit the 'and', and
  1827. // only keep the overflow check.
  1828. if (isCheckForZeroAndMulWithOverflow(Op0, Op1, true))
  1829. return Op1;
  1830. if (isCheckForZeroAndMulWithOverflow(Op1, Op0, true))
  1831. return Op0;
  1832. // A & (-A) = A if A is a power of two or zero.
  1833. if (match(Op0, m_Neg(m_Specific(Op1))) ||
  1834. match(Op1, m_Neg(m_Specific(Op0)))) {
  1835. if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
  1836. Q.DT))
  1837. return Op0;
  1838. if (isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI,
  1839. Q.DT))
  1840. return Op1;
  1841. }
  1842. // This is a similar pattern used for checking if a value is a power-of-2:
  1843. // (A - 1) & A --> 0 (if A is a power-of-2 or 0)
  1844. // A & (A - 1) --> 0 (if A is a power-of-2 or 0)
  1845. if (match(Op0, m_Add(m_Specific(Op1), m_AllOnes())) &&
  1846. isKnownToBeAPowerOfTwo(Op1, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
  1847. return Constant::getNullValue(Op1->getType());
  1848. if (match(Op1, m_Add(m_Specific(Op0), m_AllOnes())) &&
  1849. isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ true, 0, Q.AC, Q.CxtI, Q.DT))
  1850. return Constant::getNullValue(Op0->getType());
  1851. if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, true))
  1852. return V;
  1853. // Try some generic simplifications for associative operations.
  1854. if (Value *V =
  1855. simplifyAssociativeBinOp(Instruction::And, Op0, Op1, Q, MaxRecurse))
  1856. return V;
  1857. // And distributes over Or. Try some generic simplifications based on this.
  1858. if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
  1859. Instruction::Or, Q, MaxRecurse))
  1860. return V;
  1861. // And distributes over Xor. Try some generic simplifications based on this.
  1862. if (Value *V = expandCommutativeBinOp(Instruction::And, Op0, Op1,
  1863. Instruction::Xor, Q, MaxRecurse))
  1864. return V;
  1865. if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
  1866. if (Op0->getType()->isIntOrIntVectorTy(1)) {
  1867. // A & (A && B) -> A && B
  1868. if (match(Op1, m_Select(m_Specific(Op0), m_Value(), m_Zero())))
  1869. return Op1;
  1870. else if (match(Op0, m_Select(m_Specific(Op1), m_Value(), m_Zero())))
  1871. return Op0;
  1872. }
  1873. // If the operation is with the result of a select instruction, check
  1874. // whether operating on either branch of the select always yields the same
  1875. // value.
  1876. if (Value *V =
  1877. threadBinOpOverSelect(Instruction::And, Op0, Op1, Q, MaxRecurse))
  1878. return V;
  1879. }
  1880. // If the operation is with the result of a phi instruction, check whether
  1881. // operating on all incoming values of the phi always yields the same value.
  1882. if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
  1883. if (Value *V =
  1884. threadBinOpOverPHI(Instruction::And, Op0, Op1, Q, MaxRecurse))
  1885. return V;
  1886. // Assuming the effective width of Y is not larger than A, i.e. all bits
  1887. // from X and Y are disjoint in (X << A) | Y,
  1888. // if the mask of this AND op covers all bits of X or Y, while it covers
  1889. // no bits from the other, we can bypass this AND op. E.g.,
  1890. // ((X << A) | Y) & Mask -> Y,
  1891. // if Mask = ((1 << effective_width_of(Y)) - 1)
  1892. // ((X << A) | Y) & Mask -> X << A,
  1893. // if Mask = ((1 << effective_width_of(X)) - 1) << A
  1894. // SimplifyDemandedBits in InstCombine can optimize the general case.
  1895. // This pattern aims to help other passes for a common case.
  1896. Value *XShifted;
  1897. if (match(Op1, m_APInt(Mask)) &&
  1898. match(Op0, m_c_Or(m_CombineAnd(m_NUWShl(m_Value(X), m_APInt(ShAmt)),
  1899. m_Value(XShifted)),
  1900. m_Value(Y)))) {
  1901. const unsigned Width = Op0->getType()->getScalarSizeInBits();
  1902. const unsigned ShftCnt = ShAmt->getLimitedValue(Width);
  1903. const KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  1904. const unsigned EffWidthY = YKnown.countMaxActiveBits();
  1905. if (EffWidthY <= ShftCnt) {
  1906. const KnownBits XKnown = computeKnownBits(X, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  1907. const unsigned EffWidthX = XKnown.countMaxActiveBits();
  1908. const APInt EffBitsY = APInt::getLowBitsSet(Width, EffWidthY);
  1909. const APInt EffBitsX = APInt::getLowBitsSet(Width, EffWidthX) << ShftCnt;
  1910. // If the mask is extracting all bits from X or Y as is, we can skip
  1911. // this AND op.
  1912. if (EffBitsY.isSubsetOf(*Mask) && !EffBitsX.intersects(*Mask))
  1913. return Y;
  1914. if (EffBitsX.isSubsetOf(*Mask) && !EffBitsY.intersects(*Mask))
  1915. return XShifted;
  1916. }
  1917. }
  1918. // ((X | Y) ^ X ) & ((X | Y) ^ Y) --> 0
  1919. // ((X | Y) ^ Y ) & ((X | Y) ^ X) --> 0
  1920. BinaryOperator *Or;
  1921. if (match(Op0, m_c_Xor(m_Value(X),
  1922. m_CombineAnd(m_BinOp(Or),
  1923. m_c_Or(m_Deferred(X), m_Value(Y))))) &&
  1924. match(Op1, m_c_Xor(m_Specific(Or), m_Specific(Y))))
  1925. return Constant::getNullValue(Op0->getType());
  1926. if (Op0->getType()->isIntOrIntVectorTy(1)) {
  1927. if (std::optional<bool> Implied = isImpliedCondition(Op0, Op1, Q.DL)) {
  1928. // If Op0 is true implies Op1 is true, then Op0 is a subset of Op1.
  1929. if (*Implied == true)
  1930. return Op0;
  1931. // If Op0 is true implies Op1 is false, then they are not true together.
  1932. if (*Implied == false)
  1933. return ConstantInt::getFalse(Op0->getType());
  1934. }
  1935. if (std::optional<bool> Implied = isImpliedCondition(Op1, Op0, Q.DL)) {
  1936. // If Op1 is true implies Op0 is true, then Op1 is a subset of Op0.
  1937. if (*Implied)
  1938. return Op1;
  1939. // If Op1 is true implies Op0 is false, then they are not true together.
  1940. if (!*Implied)
  1941. return ConstantInt::getFalse(Op1->getType());
  1942. }
  1943. }
  1944. if (Value *V = simplifyByDomEq(Instruction::And, Op0, Op1, Q, MaxRecurse))
  1945. return V;
  1946. return nullptr;
  1947. }
  1948. Value *llvm::simplifyAndInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
  1949. return ::simplifyAndInst(Op0, Op1, Q, RecursionLimit);
  1950. }
  1951. // TODO: Many of these folds could use LogicalAnd/LogicalOr.
  1952. static Value *simplifyOrLogic(Value *X, Value *Y) {
  1953. assert(X->getType() == Y->getType() && "Expected same type for 'or' ops");
  1954. Type *Ty = X->getType();
  1955. // X | ~X --> -1
  1956. if (match(Y, m_Not(m_Specific(X))))
  1957. return ConstantInt::getAllOnesValue(Ty);
  1958. // X | ~(X & ?) = -1
  1959. if (match(Y, m_Not(m_c_And(m_Specific(X), m_Value()))))
  1960. return ConstantInt::getAllOnesValue(Ty);
  1961. // X | (X & ?) --> X
  1962. if (match(Y, m_c_And(m_Specific(X), m_Value())))
  1963. return X;
  1964. Value *A, *B;
  1965. // (A ^ B) | (A | B) --> A | B
  1966. // (A ^ B) | (B | A) --> B | A
  1967. if (match(X, m_Xor(m_Value(A), m_Value(B))) &&
  1968. match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
  1969. return Y;
  1970. // ~(A ^ B) | (A | B) --> -1
  1971. // ~(A ^ B) | (B | A) --> -1
  1972. if (match(X, m_Not(m_Xor(m_Value(A), m_Value(B)))) &&
  1973. match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
  1974. return ConstantInt::getAllOnesValue(Ty);
  1975. // (A & ~B) | (A ^ B) --> A ^ B
  1976. // (~B & A) | (A ^ B) --> A ^ B
  1977. // (A & ~B) | (B ^ A) --> B ^ A
  1978. // (~B & A) | (B ^ A) --> B ^ A
  1979. if (match(X, m_c_And(m_Value(A), m_Not(m_Value(B)))) &&
  1980. match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
  1981. return Y;
  1982. // (~A ^ B) | (A & B) --> ~A ^ B
  1983. // (B ^ ~A) | (A & B) --> B ^ ~A
  1984. // (~A ^ B) | (B & A) --> ~A ^ B
  1985. // (B ^ ~A) | (B & A) --> B ^ ~A
  1986. if (match(X, m_c_Xor(m_NotForbidUndef(m_Value(A)), m_Value(B))) &&
  1987. match(Y, m_c_And(m_Specific(A), m_Specific(B))))
  1988. return X;
  1989. // (~A | B) | (A ^ B) --> -1
  1990. // (~A | B) | (B ^ A) --> -1
  1991. // (B | ~A) | (A ^ B) --> -1
  1992. // (B | ~A) | (B ^ A) --> -1
  1993. if (match(X, m_c_Or(m_Not(m_Value(A)), m_Value(B))) &&
  1994. match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
  1995. return ConstantInt::getAllOnesValue(Ty);
  1996. // (~A & B) | ~(A | B) --> ~A
  1997. // (~A & B) | ~(B | A) --> ~A
  1998. // (B & ~A) | ~(A | B) --> ~A
  1999. // (B & ~A) | ~(B | A) --> ~A
  2000. Value *NotA;
  2001. if (match(X,
  2002. m_c_And(m_CombineAnd(m_Value(NotA), m_NotForbidUndef(m_Value(A))),
  2003. m_Value(B))) &&
  2004. match(Y, m_Not(m_c_Or(m_Specific(A), m_Specific(B)))))
  2005. return NotA;
  2006. // The same is true of Logical And
  2007. // TODO: This could share the logic of the version above if there was a
  2008. // version of LogicalAnd that allowed more than just i1 types.
  2009. if (match(X, m_c_LogicalAnd(
  2010. m_CombineAnd(m_Value(NotA), m_NotForbidUndef(m_Value(A))),
  2011. m_Value(B))) &&
  2012. match(Y, m_Not(m_c_LogicalOr(m_Specific(A), m_Specific(B)))))
  2013. return NotA;
  2014. // ~(A ^ B) | (A & B) --> ~(A ^ B)
  2015. // ~(A ^ B) | (B & A) --> ~(A ^ B)
  2016. Value *NotAB;
  2017. if (match(X, m_CombineAnd(m_NotForbidUndef(m_Xor(m_Value(A), m_Value(B))),
  2018. m_Value(NotAB))) &&
  2019. match(Y, m_c_And(m_Specific(A), m_Specific(B))))
  2020. return NotAB;
  2021. // ~(A & B) | (A ^ B) --> ~(A & B)
  2022. // ~(A & B) | (B ^ A) --> ~(A & B)
  2023. if (match(X, m_CombineAnd(m_NotForbidUndef(m_And(m_Value(A), m_Value(B))),
  2024. m_Value(NotAB))) &&
  2025. match(Y, m_c_Xor(m_Specific(A), m_Specific(B))))
  2026. return NotAB;
  2027. return nullptr;
  2028. }
  2029. /// Given operands for an Or, see if we can fold the result.
  2030. /// If not, this returns null.
  2031. static Value *simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
  2032. unsigned MaxRecurse) {
  2033. if (Constant *C = foldOrCommuteConstant(Instruction::Or, Op0, Op1, Q))
  2034. return C;
  2035. // X | poison -> poison
  2036. if (isa<PoisonValue>(Op1))
  2037. return Op1;
  2038. // X | undef -> -1
  2039. // X | -1 = -1
  2040. // Do not return Op1 because it may contain undef elements if it's a vector.
  2041. if (Q.isUndefValue(Op1) || match(Op1, m_AllOnes()))
  2042. return Constant::getAllOnesValue(Op0->getType());
  2043. // X | X = X
  2044. // X | 0 = X
  2045. if (Op0 == Op1 || match(Op1, m_Zero()))
  2046. return Op0;
  2047. if (Value *R = simplifyOrLogic(Op0, Op1))
  2048. return R;
  2049. if (Value *R = simplifyOrLogic(Op1, Op0))
  2050. return R;
  2051. if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Or))
  2052. return V;
  2053. // Rotated -1 is still -1:
  2054. // (-1 << X) | (-1 >> (C - X)) --> -1
  2055. // (-1 >> X) | (-1 << (C - X)) --> -1
  2056. // ...with C <= bitwidth (and commuted variants).
  2057. Value *X, *Y;
  2058. if ((match(Op0, m_Shl(m_AllOnes(), m_Value(X))) &&
  2059. match(Op1, m_LShr(m_AllOnes(), m_Value(Y)))) ||
  2060. (match(Op1, m_Shl(m_AllOnes(), m_Value(X))) &&
  2061. match(Op0, m_LShr(m_AllOnes(), m_Value(Y))))) {
  2062. const APInt *C;
  2063. if ((match(X, m_Sub(m_APInt(C), m_Specific(Y))) ||
  2064. match(Y, m_Sub(m_APInt(C), m_Specific(X)))) &&
  2065. C->ule(X->getType()->getScalarSizeInBits())) {
  2066. return ConstantInt::getAllOnesValue(X->getType());
  2067. }
  2068. }
  2069. // A funnel shift (rotate) can be decomposed into simpler shifts. See if we
  2070. // are mixing in another shift that is redundant with the funnel shift.
  2071. // (fshl X, ?, Y) | (shl X, Y) --> fshl X, ?, Y
  2072. // (shl X, Y) | (fshl X, ?, Y) --> fshl X, ?, Y
  2073. if (match(Op0,
  2074. m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
  2075. match(Op1, m_Shl(m_Specific(X), m_Specific(Y))))
  2076. return Op0;
  2077. if (match(Op1,
  2078. m_Intrinsic<Intrinsic::fshl>(m_Value(X), m_Value(), m_Value(Y))) &&
  2079. match(Op0, m_Shl(m_Specific(X), m_Specific(Y))))
  2080. return Op1;
  2081. // (fshr ?, X, Y) | (lshr X, Y) --> fshr ?, X, Y
  2082. // (lshr X, Y) | (fshr ?, X, Y) --> fshr ?, X, Y
  2083. if (match(Op0,
  2084. m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
  2085. match(Op1, m_LShr(m_Specific(X), m_Specific(Y))))
  2086. return Op0;
  2087. if (match(Op1,
  2088. m_Intrinsic<Intrinsic::fshr>(m_Value(), m_Value(X), m_Value(Y))) &&
  2089. match(Op0, m_LShr(m_Specific(X), m_Specific(Y))))
  2090. return Op1;
  2091. if (Value *V = simplifyAndOrOfCmps(Q, Op0, Op1, false))
  2092. return V;
  2093. // If we have a multiplication overflow check that is being 'and'ed with a
  2094. // check that one of the multipliers is not zero, we can omit the 'and', and
  2095. // only keep the overflow check.
  2096. if (isCheckForZeroAndMulWithOverflow(Op0, Op1, false))
  2097. return Op1;
  2098. if (isCheckForZeroAndMulWithOverflow(Op1, Op0, false))
  2099. return Op0;
  2100. // Try some generic simplifications for associative operations.
  2101. if (Value *V =
  2102. simplifyAssociativeBinOp(Instruction::Or, Op0, Op1, Q, MaxRecurse))
  2103. return V;
  2104. // Or distributes over And. Try some generic simplifications based on this.
  2105. if (Value *V = expandCommutativeBinOp(Instruction::Or, Op0, Op1,
  2106. Instruction::And, Q, MaxRecurse))
  2107. return V;
  2108. if (isa<SelectInst>(Op0) || isa<SelectInst>(Op1)) {
  2109. if (Op0->getType()->isIntOrIntVectorTy(1)) {
  2110. // A | (A || B) -> A || B
  2111. if (match(Op1, m_Select(m_Specific(Op0), m_One(), m_Value())))
  2112. return Op1;
  2113. else if (match(Op0, m_Select(m_Specific(Op1), m_One(), m_Value())))
  2114. return Op0;
  2115. }
  2116. // If the operation is with the result of a select instruction, check
  2117. // whether operating on either branch of the select always yields the same
  2118. // value.
  2119. if (Value *V =
  2120. threadBinOpOverSelect(Instruction::Or, Op0, Op1, Q, MaxRecurse))
  2121. return V;
  2122. }
  2123. // (A & C1)|(B & C2)
  2124. Value *A, *B;
  2125. const APInt *C1, *C2;
  2126. if (match(Op0, m_And(m_Value(A), m_APInt(C1))) &&
  2127. match(Op1, m_And(m_Value(B), m_APInt(C2)))) {
  2128. if (*C1 == ~*C2) {
  2129. // (A & C1)|(B & C2)
  2130. // If we have: ((V + N) & C1) | (V & C2)
  2131. // .. and C2 = ~C1 and C2 is 0+1+ and (N & C2) == 0
  2132. // replace with V+N.
  2133. Value *N;
  2134. if (C2->isMask() && // C2 == 0+1+
  2135. match(A, m_c_Add(m_Specific(B), m_Value(N)))) {
  2136. // Add commutes, try both ways.
  2137. if (MaskedValueIsZero(N, *C2, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  2138. return A;
  2139. }
  2140. // Or commutes, try both ways.
  2141. if (C1->isMask() && match(B, m_c_Add(m_Specific(A), m_Value(N)))) {
  2142. // Add commutes, try both ways.
  2143. if (MaskedValueIsZero(N, *C1, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  2144. return B;
  2145. }
  2146. }
  2147. }
  2148. // If the operation is with the result of a phi instruction, check whether
  2149. // operating on all incoming values of the phi always yields the same value.
  2150. if (isa<PHINode>(Op0) || isa<PHINode>(Op1))
  2151. if (Value *V = threadBinOpOverPHI(Instruction::Or, Op0, Op1, Q, MaxRecurse))
  2152. return V;
  2153. if (Op0->getType()->isIntOrIntVectorTy(1)) {
  2154. if (std::optional<bool> Implied =
  2155. isImpliedCondition(Op0, Op1, Q.DL, false)) {
  2156. // If Op0 is false implies Op1 is false, then Op1 is a subset of Op0.
  2157. if (*Implied == false)
  2158. return Op0;
  2159. // If Op0 is false implies Op1 is true, then at least one is always true.
  2160. if (*Implied == true)
  2161. return ConstantInt::getTrue(Op0->getType());
  2162. }
  2163. if (std::optional<bool> Implied =
  2164. isImpliedCondition(Op1, Op0, Q.DL, false)) {
  2165. // If Op1 is false implies Op0 is false, then Op0 is a subset of Op1.
  2166. if (*Implied == false)
  2167. return Op1;
  2168. // If Op1 is false implies Op0 is true, then at least one is always true.
  2169. if (*Implied == true)
  2170. return ConstantInt::getTrue(Op1->getType());
  2171. }
  2172. }
  2173. if (Value *V = simplifyByDomEq(Instruction::Or, Op0, Op1, Q, MaxRecurse))
  2174. return V;
  2175. return nullptr;
  2176. }
  2177. Value *llvm::simplifyOrInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
  2178. return ::simplifyOrInst(Op0, Op1, Q, RecursionLimit);
  2179. }
  2180. /// Given operands for a Xor, see if we can fold the result.
  2181. /// If not, this returns null.
  2182. static Value *simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q,
  2183. unsigned MaxRecurse) {
  2184. if (Constant *C = foldOrCommuteConstant(Instruction::Xor, Op0, Op1, Q))
  2185. return C;
  2186. // X ^ poison -> poison
  2187. if (isa<PoisonValue>(Op1))
  2188. return Op1;
  2189. // A ^ undef -> undef
  2190. if (Q.isUndefValue(Op1))
  2191. return Op1;
  2192. // A ^ 0 = A
  2193. if (match(Op1, m_Zero()))
  2194. return Op0;
  2195. // A ^ A = 0
  2196. if (Op0 == Op1)
  2197. return Constant::getNullValue(Op0->getType());
  2198. // A ^ ~A = ~A ^ A = -1
  2199. if (match(Op0, m_Not(m_Specific(Op1))) || match(Op1, m_Not(m_Specific(Op0))))
  2200. return Constant::getAllOnesValue(Op0->getType());
  2201. auto foldAndOrNot = [](Value *X, Value *Y) -> Value * {
  2202. Value *A, *B;
  2203. // (~A & B) ^ (A | B) --> A -- There are 8 commuted variants.
  2204. if (match(X, m_c_And(m_Not(m_Value(A)), m_Value(B))) &&
  2205. match(Y, m_c_Or(m_Specific(A), m_Specific(B))))
  2206. return A;
  2207. // (~A | B) ^ (A & B) --> ~A -- There are 8 commuted variants.
  2208. // The 'not' op must contain a complete -1 operand (no undef elements for
  2209. // vector) for the transform to be safe.
  2210. Value *NotA;
  2211. if (match(X,
  2212. m_c_Or(m_CombineAnd(m_NotForbidUndef(m_Value(A)), m_Value(NotA)),
  2213. m_Value(B))) &&
  2214. match(Y, m_c_And(m_Specific(A), m_Specific(B))))
  2215. return NotA;
  2216. return nullptr;
  2217. };
  2218. if (Value *R = foldAndOrNot(Op0, Op1))
  2219. return R;
  2220. if (Value *R = foldAndOrNot(Op1, Op0))
  2221. return R;
  2222. if (Value *V = simplifyLogicOfAddSub(Op0, Op1, Instruction::Xor))
  2223. return V;
  2224. // Try some generic simplifications for associative operations.
  2225. if (Value *V =
  2226. simplifyAssociativeBinOp(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
  2227. return V;
  2228. // Threading Xor over selects and phi nodes is pointless, so don't bother.
  2229. // Threading over the select in "A ^ select(cond, B, C)" means evaluating
  2230. // "A^B" and "A^C" and seeing if they are equal; but they are equal if and
  2231. // only if B and C are equal. If B and C are equal then (since we assume
  2232. // that operands have already been simplified) "select(cond, B, C)" should
  2233. // have been simplified to the common value of B and C already. Analysing
  2234. // "A^B" and "A^C" thus gains nothing, but costs compile time. Similarly
  2235. // for threading over phi nodes.
  2236. if (Value *V = simplifyByDomEq(Instruction::Xor, Op0, Op1, Q, MaxRecurse))
  2237. return V;
  2238. return nullptr;
  2239. }
  2240. Value *llvm::simplifyXorInst(Value *Op0, Value *Op1, const SimplifyQuery &Q) {
  2241. return ::simplifyXorInst(Op0, Op1, Q, RecursionLimit);
  2242. }
  2243. static Type *getCompareTy(Value *Op) {
  2244. return CmpInst::makeCmpResultType(Op->getType());
  2245. }
  2246. /// Rummage around inside V looking for something equivalent to the comparison
  2247. /// "LHS Pred RHS". Return such a value if found, otherwise return null.
  2248. /// Helper function for analyzing max/min idioms.
  2249. static Value *extractEquivalentCondition(Value *V, CmpInst::Predicate Pred,
  2250. Value *LHS, Value *RHS) {
  2251. SelectInst *SI = dyn_cast<SelectInst>(V);
  2252. if (!SI)
  2253. return nullptr;
  2254. CmpInst *Cmp = dyn_cast<CmpInst>(SI->getCondition());
  2255. if (!Cmp)
  2256. return nullptr;
  2257. Value *CmpLHS = Cmp->getOperand(0), *CmpRHS = Cmp->getOperand(1);
  2258. if (Pred == Cmp->getPredicate() && LHS == CmpLHS && RHS == CmpRHS)
  2259. return Cmp;
  2260. if (Pred == CmpInst::getSwappedPredicate(Cmp->getPredicate()) &&
  2261. LHS == CmpRHS && RHS == CmpLHS)
  2262. return Cmp;
  2263. return nullptr;
  2264. }
  2265. /// Return true if the underlying object (storage) must be disjoint from
  2266. /// storage returned by any noalias return call.
  2267. static bool isAllocDisjoint(const Value *V) {
  2268. // For allocas, we consider only static ones (dynamic
  2269. // allocas might be transformed into calls to malloc not simultaneously
  2270. // live with the compared-to allocation). For globals, we exclude symbols
  2271. // that might be resolve lazily to symbols in another dynamically-loaded
  2272. // library (and, thus, could be malloc'ed by the implementation).
  2273. if (const AllocaInst *AI = dyn_cast<AllocaInst>(V))
  2274. return AI->getParent() && AI->getFunction() && AI->isStaticAlloca();
  2275. if (const GlobalValue *GV = dyn_cast<GlobalValue>(V))
  2276. return (GV->hasLocalLinkage() || GV->hasHiddenVisibility() ||
  2277. GV->hasProtectedVisibility() || GV->hasGlobalUnnamedAddr()) &&
  2278. !GV->isThreadLocal();
  2279. if (const Argument *A = dyn_cast<Argument>(V))
  2280. return A->hasByValAttr();
  2281. return false;
  2282. }
  2283. /// Return true if V1 and V2 are each the base of some distict storage region
  2284. /// [V, object_size(V)] which do not overlap. Note that zero sized regions
  2285. /// *are* possible, and that zero sized regions do not overlap with any other.
  2286. static bool haveNonOverlappingStorage(const Value *V1, const Value *V2) {
  2287. // Global variables always exist, so they always exist during the lifetime
  2288. // of each other and all allocas. Global variables themselves usually have
  2289. // non-overlapping storage, but since their addresses are constants, the
  2290. // case involving two globals does not reach here and is instead handled in
  2291. // constant folding.
  2292. //
  2293. // Two different allocas usually have different addresses...
  2294. //
  2295. // However, if there's an @llvm.stackrestore dynamically in between two
  2296. // allocas, they may have the same address. It's tempting to reduce the
  2297. // scope of the problem by only looking at *static* allocas here. That would
  2298. // cover the majority of allocas while significantly reducing the likelihood
  2299. // of having an @llvm.stackrestore pop up in the middle. However, it's not
  2300. // actually impossible for an @llvm.stackrestore to pop up in the middle of
  2301. // an entry block. Also, if we have a block that's not attached to a
  2302. // function, we can't tell if it's "static" under the current definition.
  2303. // Theoretically, this problem could be fixed by creating a new kind of
  2304. // instruction kind specifically for static allocas. Such a new instruction
  2305. // could be required to be at the top of the entry block, thus preventing it
  2306. // from being subject to a @llvm.stackrestore. Instcombine could even
  2307. // convert regular allocas into these special allocas. It'd be nifty.
  2308. // However, until then, this problem remains open.
  2309. //
  2310. // So, we'll assume that two non-empty allocas have different addresses
  2311. // for now.
  2312. auto isByValArg = [](const Value *V) {
  2313. const Argument *A = dyn_cast<Argument>(V);
  2314. return A && A->hasByValAttr();
  2315. };
  2316. // Byval args are backed by store which does not overlap with each other,
  2317. // allocas, or globals.
  2318. if (isByValArg(V1))
  2319. return isa<AllocaInst>(V2) || isa<GlobalVariable>(V2) || isByValArg(V2);
  2320. if (isByValArg(V2))
  2321. return isa<AllocaInst>(V1) || isa<GlobalVariable>(V1) || isByValArg(V1);
  2322. return isa<AllocaInst>(V1) &&
  2323. (isa<AllocaInst>(V2) || isa<GlobalVariable>(V2));
  2324. }
  2325. // A significant optimization not implemented here is assuming that alloca
  2326. // addresses are not equal to incoming argument values. They don't *alias*,
  2327. // as we say, but that doesn't mean they aren't equal, so we take a
  2328. // conservative approach.
  2329. //
  2330. // This is inspired in part by C++11 5.10p1:
  2331. // "Two pointers of the same type compare equal if and only if they are both
  2332. // null, both point to the same function, or both represent the same
  2333. // address."
  2334. //
  2335. // This is pretty permissive.
  2336. //
  2337. // It's also partly due to C11 6.5.9p6:
  2338. // "Two pointers compare equal if and only if both are null pointers, both are
  2339. // pointers to the same object (including a pointer to an object and a
  2340. // subobject at its beginning) or function, both are pointers to one past the
  2341. // last element of the same array object, or one is a pointer to one past the
  2342. // end of one array object and the other is a pointer to the start of a
  2343. // different array object that happens to immediately follow the first array
  2344. // object in the address space.)
  2345. //
  2346. // C11's version is more restrictive, however there's no reason why an argument
  2347. // couldn't be a one-past-the-end value for a stack object in the caller and be
  2348. // equal to the beginning of a stack object in the callee.
  2349. //
  2350. // If the C and C++ standards are ever made sufficiently restrictive in this
  2351. // area, it may be possible to update LLVM's semantics accordingly and reinstate
  2352. // this optimization.
  2353. static Constant *computePointerICmp(CmpInst::Predicate Pred, Value *LHS,
  2354. Value *RHS, const SimplifyQuery &Q) {
  2355. const DataLayout &DL = Q.DL;
  2356. const TargetLibraryInfo *TLI = Q.TLI;
  2357. const DominatorTree *DT = Q.DT;
  2358. const Instruction *CxtI = Q.CxtI;
  2359. const InstrInfoQuery &IIQ = Q.IIQ;
  2360. // First, skip past any trivial no-ops.
  2361. LHS = LHS->stripPointerCasts();
  2362. RHS = RHS->stripPointerCasts();
  2363. // A non-null pointer is not equal to a null pointer.
  2364. if (isa<ConstantPointerNull>(RHS) && ICmpInst::isEquality(Pred) &&
  2365. llvm::isKnownNonZero(LHS, DL, 0, nullptr, nullptr, nullptr,
  2366. IIQ.UseInstrInfo))
  2367. return ConstantInt::get(getCompareTy(LHS), !CmpInst::isTrueWhenEqual(Pred));
  2368. // We can only fold certain predicates on pointer comparisons.
  2369. switch (Pred) {
  2370. default:
  2371. return nullptr;
  2372. // Equality comparisons are easy to fold.
  2373. case CmpInst::ICMP_EQ:
  2374. case CmpInst::ICMP_NE:
  2375. break;
  2376. // We can only handle unsigned relational comparisons because 'inbounds' on
  2377. // a GEP only protects against unsigned wrapping.
  2378. case CmpInst::ICMP_UGT:
  2379. case CmpInst::ICMP_UGE:
  2380. case CmpInst::ICMP_ULT:
  2381. case CmpInst::ICMP_ULE:
  2382. // However, we have to switch them to their signed variants to handle
  2383. // negative indices from the base pointer.
  2384. Pred = ICmpInst::getSignedPredicate(Pred);
  2385. break;
  2386. }
  2387. // Strip off any constant offsets so that we can reason about them.
  2388. // It's tempting to use getUnderlyingObject or even just stripInBoundsOffsets
  2389. // here and compare base addresses like AliasAnalysis does, however there are
  2390. // numerous hazards. AliasAnalysis and its utilities rely on special rules
  2391. // governing loads and stores which don't apply to icmps. Also, AliasAnalysis
  2392. // doesn't need to guarantee pointer inequality when it says NoAlias.
  2393. // Even if an non-inbounds GEP occurs along the path we can still optimize
  2394. // equality comparisons concerning the result.
  2395. bool AllowNonInbounds = ICmpInst::isEquality(Pred);
  2396. APInt LHSOffset = stripAndComputeConstantOffsets(DL, LHS, AllowNonInbounds);
  2397. APInt RHSOffset = stripAndComputeConstantOffsets(DL, RHS, AllowNonInbounds);
  2398. // If LHS and RHS are related via constant offsets to the same base
  2399. // value, we can replace it with an icmp which just compares the offsets.
  2400. if (LHS == RHS)
  2401. return ConstantInt::get(getCompareTy(LHS),
  2402. ICmpInst::compare(LHSOffset, RHSOffset, Pred));
  2403. // Various optimizations for (in)equality comparisons.
  2404. if (Pred == CmpInst::ICMP_EQ || Pred == CmpInst::ICMP_NE) {
  2405. // Different non-empty allocations that exist at the same time have
  2406. // different addresses (if the program can tell). If the offsets are
  2407. // within the bounds of their allocations (and not one-past-the-end!
  2408. // so we can't use inbounds!), and their allocations aren't the same,
  2409. // the pointers are not equal.
  2410. if (haveNonOverlappingStorage(LHS, RHS)) {
  2411. uint64_t LHSSize, RHSSize;
  2412. ObjectSizeOpts Opts;
  2413. Opts.EvalMode = ObjectSizeOpts::Mode::Min;
  2414. auto *F = [](Value *V) -> Function * {
  2415. if (auto *I = dyn_cast<Instruction>(V))
  2416. return I->getFunction();
  2417. if (auto *A = dyn_cast<Argument>(V))
  2418. return A->getParent();
  2419. return nullptr;
  2420. }(LHS);
  2421. Opts.NullIsUnknownSize = F ? NullPointerIsDefined(F) : true;
  2422. if (getObjectSize(LHS, LHSSize, DL, TLI, Opts) &&
  2423. getObjectSize(RHS, RHSSize, DL, TLI, Opts) &&
  2424. !LHSOffset.isNegative() && !RHSOffset.isNegative() &&
  2425. LHSOffset.ult(LHSSize) && RHSOffset.ult(RHSSize)) {
  2426. return ConstantInt::get(getCompareTy(LHS),
  2427. !CmpInst::isTrueWhenEqual(Pred));
  2428. }
  2429. }
  2430. // If one side of the equality comparison must come from a noalias call
  2431. // (meaning a system memory allocation function), and the other side must
  2432. // come from a pointer that cannot overlap with dynamically-allocated
  2433. // memory within the lifetime of the current function (allocas, byval
  2434. // arguments, globals), then determine the comparison result here.
  2435. SmallVector<const Value *, 8> LHSUObjs, RHSUObjs;
  2436. getUnderlyingObjects(LHS, LHSUObjs);
  2437. getUnderlyingObjects(RHS, RHSUObjs);
  2438. // Is the set of underlying objects all noalias calls?
  2439. auto IsNAC = [](ArrayRef<const Value *> Objects) {
  2440. return all_of(Objects, isNoAliasCall);
  2441. };
  2442. // Is the set of underlying objects all things which must be disjoint from
  2443. // noalias calls. We assume that indexing from such disjoint storage
  2444. // into the heap is undefined, and thus offsets can be safely ignored.
  2445. auto IsAllocDisjoint = [](ArrayRef<const Value *> Objects) {
  2446. return all_of(Objects, ::isAllocDisjoint);
  2447. };
  2448. if ((IsNAC(LHSUObjs) && IsAllocDisjoint(RHSUObjs)) ||
  2449. (IsNAC(RHSUObjs) && IsAllocDisjoint(LHSUObjs)))
  2450. return ConstantInt::get(getCompareTy(LHS),
  2451. !CmpInst::isTrueWhenEqual(Pred));
  2452. // Fold comparisons for non-escaping pointer even if the allocation call
  2453. // cannot be elided. We cannot fold malloc comparison to null. Also, the
  2454. // dynamic allocation call could be either of the operands. Note that
  2455. // the other operand can not be based on the alloc - if it were, then
  2456. // the cmp itself would be a capture.
  2457. Value *MI = nullptr;
  2458. if (isAllocLikeFn(LHS, TLI) &&
  2459. llvm::isKnownNonZero(RHS, DL, 0, nullptr, CxtI, DT))
  2460. MI = LHS;
  2461. else if (isAllocLikeFn(RHS, TLI) &&
  2462. llvm::isKnownNonZero(LHS, DL, 0, nullptr, CxtI, DT))
  2463. MI = RHS;
  2464. // FIXME: We should also fold the compare when the pointer escapes, but the
  2465. // compare dominates the pointer escape
  2466. if (MI && !PointerMayBeCaptured(MI, true, true))
  2467. return ConstantInt::get(getCompareTy(LHS),
  2468. CmpInst::isFalseWhenEqual(Pred));
  2469. }
  2470. // Otherwise, fail.
  2471. return nullptr;
  2472. }
  2473. /// Fold an icmp when its operands have i1 scalar type.
  2474. static Value *simplifyICmpOfBools(CmpInst::Predicate Pred, Value *LHS,
  2475. Value *RHS, const SimplifyQuery &Q) {
  2476. Type *ITy = getCompareTy(LHS); // The return type.
  2477. Type *OpTy = LHS->getType(); // The operand type.
  2478. if (!OpTy->isIntOrIntVectorTy(1))
  2479. return nullptr;
  2480. // A boolean compared to true/false can be reduced in 14 out of the 20
  2481. // (10 predicates * 2 constants) possible combinations. The other
  2482. // 6 cases require a 'not' of the LHS.
  2483. auto ExtractNotLHS = [](Value *V) -> Value * {
  2484. Value *X;
  2485. if (match(V, m_Not(m_Value(X))))
  2486. return X;
  2487. return nullptr;
  2488. };
  2489. if (match(RHS, m_Zero())) {
  2490. switch (Pred) {
  2491. case CmpInst::ICMP_NE: // X != 0 -> X
  2492. case CmpInst::ICMP_UGT: // X >u 0 -> X
  2493. case CmpInst::ICMP_SLT: // X <s 0 -> X
  2494. return LHS;
  2495. case CmpInst::ICMP_EQ: // not(X) == 0 -> X != 0 -> X
  2496. case CmpInst::ICMP_ULE: // not(X) <=u 0 -> X >u 0 -> X
  2497. case CmpInst::ICMP_SGE: // not(X) >=s 0 -> X <s 0 -> X
  2498. if (Value *X = ExtractNotLHS(LHS))
  2499. return X;
  2500. break;
  2501. case CmpInst::ICMP_ULT: // X <u 0 -> false
  2502. case CmpInst::ICMP_SGT: // X >s 0 -> false
  2503. return getFalse(ITy);
  2504. case CmpInst::ICMP_UGE: // X >=u 0 -> true
  2505. case CmpInst::ICMP_SLE: // X <=s 0 -> true
  2506. return getTrue(ITy);
  2507. default:
  2508. break;
  2509. }
  2510. } else if (match(RHS, m_One())) {
  2511. switch (Pred) {
  2512. case CmpInst::ICMP_EQ: // X == 1 -> X
  2513. case CmpInst::ICMP_UGE: // X >=u 1 -> X
  2514. case CmpInst::ICMP_SLE: // X <=s -1 -> X
  2515. return LHS;
  2516. case CmpInst::ICMP_NE: // not(X) != 1 -> X == 1 -> X
  2517. case CmpInst::ICMP_ULT: // not(X) <=u 1 -> X >=u 1 -> X
  2518. case CmpInst::ICMP_SGT: // not(X) >s 1 -> X <=s -1 -> X
  2519. if (Value *X = ExtractNotLHS(LHS))
  2520. return X;
  2521. break;
  2522. case CmpInst::ICMP_UGT: // X >u 1 -> false
  2523. case CmpInst::ICMP_SLT: // X <s -1 -> false
  2524. return getFalse(ITy);
  2525. case CmpInst::ICMP_ULE: // X <=u 1 -> true
  2526. case CmpInst::ICMP_SGE: // X >=s -1 -> true
  2527. return getTrue(ITy);
  2528. default:
  2529. break;
  2530. }
  2531. }
  2532. switch (Pred) {
  2533. default:
  2534. break;
  2535. case ICmpInst::ICMP_UGE:
  2536. if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
  2537. return getTrue(ITy);
  2538. break;
  2539. case ICmpInst::ICMP_SGE:
  2540. /// For signed comparison, the values for an i1 are 0 and -1
  2541. /// respectively. This maps into a truth table of:
  2542. /// LHS | RHS | LHS >=s RHS | LHS implies RHS
  2543. /// 0 | 0 | 1 (0 >= 0) | 1
  2544. /// 0 | 1 | 1 (0 >= -1) | 1
  2545. /// 1 | 0 | 0 (-1 >= 0) | 0
  2546. /// 1 | 1 | 1 (-1 >= -1) | 1
  2547. if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
  2548. return getTrue(ITy);
  2549. break;
  2550. case ICmpInst::ICMP_ULE:
  2551. if (isImpliedCondition(LHS, RHS, Q.DL).value_or(false))
  2552. return getTrue(ITy);
  2553. break;
  2554. case ICmpInst::ICMP_SLE:
  2555. /// SLE follows the same logic as SGE with the LHS and RHS swapped.
  2556. if (isImpliedCondition(RHS, LHS, Q.DL).value_or(false))
  2557. return getTrue(ITy);
  2558. break;
  2559. }
  2560. return nullptr;
  2561. }
  2562. /// Try hard to fold icmp with zero RHS because this is a common case.
  2563. static Value *simplifyICmpWithZero(CmpInst::Predicate Pred, Value *LHS,
  2564. Value *RHS, const SimplifyQuery &Q) {
  2565. if (!match(RHS, m_Zero()))
  2566. return nullptr;
  2567. Type *ITy = getCompareTy(LHS); // The return type.
  2568. switch (Pred) {
  2569. default:
  2570. llvm_unreachable("Unknown ICmp predicate!");
  2571. case ICmpInst::ICMP_ULT:
  2572. return getFalse(ITy);
  2573. case ICmpInst::ICMP_UGE:
  2574. return getTrue(ITy);
  2575. case ICmpInst::ICMP_EQ:
  2576. case ICmpInst::ICMP_ULE:
  2577. if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
  2578. return getFalse(ITy);
  2579. break;
  2580. case ICmpInst::ICMP_NE:
  2581. case ICmpInst::ICMP_UGT:
  2582. if (isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo))
  2583. return getTrue(ITy);
  2584. break;
  2585. case ICmpInst::ICMP_SLT: {
  2586. KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  2587. if (LHSKnown.isNegative())
  2588. return getTrue(ITy);
  2589. if (LHSKnown.isNonNegative())
  2590. return getFalse(ITy);
  2591. break;
  2592. }
  2593. case ICmpInst::ICMP_SLE: {
  2594. KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  2595. if (LHSKnown.isNegative())
  2596. return getTrue(ITy);
  2597. if (LHSKnown.isNonNegative() &&
  2598. isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  2599. return getFalse(ITy);
  2600. break;
  2601. }
  2602. case ICmpInst::ICMP_SGE: {
  2603. KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  2604. if (LHSKnown.isNegative())
  2605. return getFalse(ITy);
  2606. if (LHSKnown.isNonNegative())
  2607. return getTrue(ITy);
  2608. break;
  2609. }
  2610. case ICmpInst::ICMP_SGT: {
  2611. KnownBits LHSKnown = computeKnownBits(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  2612. if (LHSKnown.isNegative())
  2613. return getFalse(ITy);
  2614. if (LHSKnown.isNonNegative() &&
  2615. isKnownNonZero(LHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  2616. return getTrue(ITy);
  2617. break;
  2618. }
  2619. }
  2620. return nullptr;
  2621. }
  2622. static Value *simplifyICmpWithConstant(CmpInst::Predicate Pred, Value *LHS,
  2623. Value *RHS, const InstrInfoQuery &IIQ) {
  2624. Type *ITy = getCompareTy(RHS); // The return type.
  2625. Value *X;
  2626. // Sign-bit checks can be optimized to true/false after unsigned
  2627. // floating-point casts:
  2628. // icmp slt (bitcast (uitofp X)), 0 --> false
  2629. // icmp sgt (bitcast (uitofp X)), -1 --> true
  2630. if (match(LHS, m_BitCast(m_UIToFP(m_Value(X))))) {
  2631. if (Pred == ICmpInst::ICMP_SLT && match(RHS, m_Zero()))
  2632. return ConstantInt::getFalse(ITy);
  2633. if (Pred == ICmpInst::ICMP_SGT && match(RHS, m_AllOnes()))
  2634. return ConstantInt::getTrue(ITy);
  2635. }
  2636. const APInt *C;
  2637. if (!match(RHS, m_APIntAllowUndef(C)))
  2638. return nullptr;
  2639. // Rule out tautological comparisons (eg., ult 0 or uge 0).
  2640. ConstantRange RHS_CR = ConstantRange::makeExactICmpRegion(Pred, *C);
  2641. if (RHS_CR.isEmptySet())
  2642. return ConstantInt::getFalse(ITy);
  2643. if (RHS_CR.isFullSet())
  2644. return ConstantInt::getTrue(ITy);
  2645. ConstantRange LHS_CR =
  2646. computeConstantRange(LHS, CmpInst::isSigned(Pred), IIQ.UseInstrInfo);
  2647. if (!LHS_CR.isFullSet()) {
  2648. if (RHS_CR.contains(LHS_CR))
  2649. return ConstantInt::getTrue(ITy);
  2650. if (RHS_CR.inverse().contains(LHS_CR))
  2651. return ConstantInt::getFalse(ITy);
  2652. }
  2653. // (mul nuw/nsw X, MulC) != C --> true (if C is not a multiple of MulC)
  2654. // (mul nuw/nsw X, MulC) == C --> false (if C is not a multiple of MulC)
  2655. const APInt *MulC;
  2656. if (ICmpInst::isEquality(Pred) &&
  2657. ((match(LHS, m_NUWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
  2658. *MulC != 0 && C->urem(*MulC) != 0) ||
  2659. (match(LHS, m_NSWMul(m_Value(), m_APIntAllowUndef(MulC))) &&
  2660. *MulC != 0 && C->srem(*MulC) != 0)))
  2661. return ConstantInt::get(ITy, Pred == ICmpInst::ICMP_NE);
  2662. return nullptr;
  2663. }
  2664. static Value *simplifyICmpWithBinOpOnLHS(CmpInst::Predicate Pred,
  2665. BinaryOperator *LBO, Value *RHS,
  2666. const SimplifyQuery &Q,
  2667. unsigned MaxRecurse) {
  2668. Type *ITy = getCompareTy(RHS); // The return type.
  2669. Value *Y = nullptr;
  2670. // icmp pred (or X, Y), X
  2671. if (match(LBO, m_c_Or(m_Value(Y), m_Specific(RHS)))) {
  2672. if (Pred == ICmpInst::ICMP_ULT)
  2673. return getFalse(ITy);
  2674. if (Pred == ICmpInst::ICMP_UGE)
  2675. return getTrue(ITy);
  2676. if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_SGE) {
  2677. KnownBits RHSKnown = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  2678. KnownBits YKnown = computeKnownBits(Y, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  2679. if (RHSKnown.isNonNegative() && YKnown.isNegative())
  2680. return Pred == ICmpInst::ICMP_SLT ? getTrue(ITy) : getFalse(ITy);
  2681. if (RHSKnown.isNegative() || YKnown.isNonNegative())
  2682. return Pred == ICmpInst::ICMP_SLT ? getFalse(ITy) : getTrue(ITy);
  2683. }
  2684. }
  2685. // icmp pred (and X, Y), X
  2686. if (match(LBO, m_c_And(m_Value(), m_Specific(RHS)))) {
  2687. if (Pred == ICmpInst::ICMP_UGT)
  2688. return getFalse(ITy);
  2689. if (Pred == ICmpInst::ICMP_ULE)
  2690. return getTrue(ITy);
  2691. }
  2692. // icmp pred (urem X, Y), Y
  2693. if (match(LBO, m_URem(m_Value(), m_Specific(RHS)))) {
  2694. switch (Pred) {
  2695. default:
  2696. break;
  2697. case ICmpInst::ICMP_SGT:
  2698. case ICmpInst::ICMP_SGE: {
  2699. KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  2700. if (!Known.isNonNegative())
  2701. break;
  2702. [[fallthrough]];
  2703. }
  2704. case ICmpInst::ICMP_EQ:
  2705. case ICmpInst::ICMP_UGT:
  2706. case ICmpInst::ICMP_UGE:
  2707. return getFalse(ITy);
  2708. case ICmpInst::ICMP_SLT:
  2709. case ICmpInst::ICMP_SLE: {
  2710. KnownBits Known = computeKnownBits(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT);
  2711. if (!Known.isNonNegative())
  2712. break;
  2713. [[fallthrough]];
  2714. }
  2715. case ICmpInst::ICMP_NE:
  2716. case ICmpInst::ICMP_ULT:
  2717. case ICmpInst::ICMP_ULE:
  2718. return getTrue(ITy);
  2719. }
  2720. }
  2721. // icmp pred (urem X, Y), X
  2722. if (match(LBO, m_URem(m_Specific(RHS), m_Value()))) {
  2723. if (Pred == ICmpInst::ICMP_ULE)
  2724. return getTrue(ITy);
  2725. if (Pred == ICmpInst::ICMP_UGT)
  2726. return getFalse(ITy);
  2727. }
  2728. // x >>u y <=u x --> true.
  2729. // x >>u y >u x --> false.
  2730. // x udiv y <=u x --> true.
  2731. // x udiv y >u x --> false.
  2732. if (match(LBO, m_LShr(m_Specific(RHS), m_Value())) ||
  2733. match(LBO, m_UDiv(m_Specific(RHS), m_Value()))) {
  2734. // icmp pred (X op Y), X
  2735. if (Pred == ICmpInst::ICMP_UGT)
  2736. return getFalse(ITy);
  2737. if (Pred == ICmpInst::ICMP_ULE)
  2738. return getTrue(ITy);
  2739. }
  2740. // If x is nonzero:
  2741. // x >>u C <u x --> true for C != 0.
  2742. // x >>u C != x --> true for C != 0.
  2743. // x >>u C >=u x --> false for C != 0.
  2744. // x >>u C == x --> false for C != 0.
  2745. // x udiv C <u x --> true for C != 1.
  2746. // x udiv C != x --> true for C != 1.
  2747. // x udiv C >=u x --> false for C != 1.
  2748. // x udiv C == x --> false for C != 1.
  2749. // TODO: allow non-constant shift amount/divisor
  2750. const APInt *C;
  2751. if ((match(LBO, m_LShr(m_Specific(RHS), m_APInt(C))) && *C != 0) ||
  2752. (match(LBO, m_UDiv(m_Specific(RHS), m_APInt(C))) && *C != 1)) {
  2753. if (isKnownNonZero(RHS, Q.DL, 0, Q.AC, Q.CxtI, Q.DT)) {
  2754. switch (Pred) {
  2755. default:
  2756. break;
  2757. case ICmpInst::ICMP_EQ:
  2758. case ICmpInst::ICMP_UGE:
  2759. return getFalse(ITy);
  2760. case ICmpInst::ICMP_NE:
  2761. case ICmpInst::ICMP_ULT:
  2762. return getTrue(ITy);
  2763. case ICmpInst::ICMP_UGT:
  2764. case ICmpInst::ICMP_ULE:
  2765. // UGT/ULE are handled by the more general case just above
  2766. llvm_unreachable("Unexpected UGT/ULE, should have been handled");
  2767. }
  2768. }
  2769. }
  2770. // (x*C1)/C2 <= x for C1 <= C2.
  2771. // This holds even if the multiplication overflows: Assume that x != 0 and
  2772. // arithmetic is modulo M. For overflow to occur we must have C1 >= M/x and
  2773. // thus C2 >= M/x. It follows that (x*C1)/C2 <= (M-1)/C2 <= ((M-1)*x)/M < x.
  2774. //
  2775. // Additionally, either the multiplication and division might be represented
  2776. // as shifts:
  2777. // (x*C1)>>C2 <= x for C1 < 2**C2.
  2778. // (x<<C1)/C2 <= x for 2**C1 < C2.
  2779. const APInt *C1, *C2;
  2780. if ((match(LBO, m_UDiv(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
  2781. C1->ule(*C2)) ||
  2782. (match(LBO, m_LShr(m_Mul(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
  2783. C1->ule(APInt(C2->getBitWidth(), 1) << *C2)) ||
  2784. (match(LBO, m_UDiv(m_Shl(m_Specific(RHS), m_APInt(C1)), m_APInt(C2))) &&
  2785. (APInt(C1->getBitWidth(), 1) << *C1).ule(*C2))) {
  2786. if (Pred == ICmpInst::ICMP_UGT)
  2787. return getFalse(ITy);
  2788. if (Pred == ICmpInst::ICMP_ULE)
  2789. return getTrue(ITy);
  2790. }
  2791. // (sub C, X) == X, C is odd --> false
  2792. // (sub C, X) != X, C is odd --> true
  2793. if (match(LBO, m_Sub(m_APIntAllowUndef(C), m_Specific(RHS))) &&
  2794. (*C & 1) == 1 && ICmpInst::isEquality(Pred))
  2795. return (Pred == ICmpInst::ICMP_EQ) ? getFalse(ITy) : getTrue(ITy);
  2796. return nullptr;
  2797. }
  2798. // If only one of the icmp's operands has NSW flags, try to prove that:
  2799. //
  2800. // icmp slt (x + C1), (x +nsw C2)
  2801. //
  2802. // is equivalent to:
  2803. //
  2804. // icmp slt C1, C2
  2805. //
  2806. // which is true if x + C2 has the NSW flags set and:
  2807. // *) C1 < C2 && C1 >= 0, or
  2808. // *) C2 < C1 && C1 <= 0.
  2809. //
  2810. static bool trySimplifyICmpWithAdds(CmpInst::Predicate Pred, Value *LHS,
  2811. Value *RHS) {
  2812. // TODO: only support icmp slt for now.
  2813. if (Pred != CmpInst::ICMP_SLT)
  2814. return false;
  2815. // Canonicalize nsw add as RHS.
  2816. if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
  2817. std::swap(LHS, RHS);
  2818. if (!match(RHS, m_NSWAdd(m_Value(), m_Value())))
  2819. return false;
  2820. Value *X;
  2821. const APInt *C1, *C2;
  2822. if (!match(LHS, m_c_Add(m_Value(X), m_APInt(C1))) ||
  2823. !match(RHS, m_c_Add(m_Specific(X), m_APInt(C2))))
  2824. return false;
  2825. return (C1->slt(*C2) && C1->isNonNegative()) ||
  2826. (C2->slt(*C1) && C1->isNonPositive());
  2827. }
  2828. /// TODO: A large part of this logic is duplicated in InstCombine's
  2829. /// foldICmpBinOp(). We should be able to share that and avoid the code
  2830. /// duplication.
  2831. static Value *simplifyICmpWithBinOp(CmpInst::Predicate Pred, Value *LHS,
  2832. Value *RHS, const SimplifyQuery &Q,
  2833. unsigned MaxRecurse) {
  2834. BinaryOperator *LBO = dyn_cast<BinaryOperator>(LHS);
  2835. BinaryOperator *RBO = dyn_cast<BinaryOperator>(RHS);
  2836. if (MaxRecurse && (LBO || RBO)) {
  2837. // Analyze the case when either LHS or RHS is an add instruction.
  2838. Value *A = nullptr, *B = nullptr, *C = nullptr, *D = nullptr;
  2839. // LHS = A + B (or A and B are null); RHS = C + D (or C and D are null).
  2840. bool NoLHSWrapProblem = false, NoRHSWrapProblem = false;
  2841. if (LBO && LBO->getOpcode() == Instruction::Add) {
  2842. A = LBO->getOperand(0);
  2843. B = LBO->getOperand(1);
  2844. NoLHSWrapProblem =
  2845. ICmpInst::isEquality(Pred) ||
  2846. (CmpInst::isUnsigned(Pred) &&
  2847. Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO))) ||
  2848. (CmpInst::isSigned(Pred) &&
  2849. Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)));
  2850. }
  2851. if (RBO && RBO->getOpcode() == Instruction::Add) {
  2852. C = RBO->getOperand(0);
  2853. D = RBO->getOperand(1);
  2854. NoRHSWrapProblem =
  2855. ICmpInst::isEquality(Pred) ||
  2856. (CmpInst::isUnsigned(Pred) &&
  2857. Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(RBO))) ||
  2858. (CmpInst::isSigned(Pred) &&
  2859. Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(RBO)));
  2860. }
  2861. // icmp (X+Y), X -> icmp Y, 0 for equalities or if there is no overflow.
  2862. if ((A == RHS || B == RHS) && NoLHSWrapProblem)
  2863. if (Value *V = simplifyICmpInst(Pred, A == RHS ? B : A,
  2864. Constant::getNullValue(RHS->getType()), Q,
  2865. MaxRecurse - 1))
  2866. return V;
  2867. // icmp X, (X+Y) -> icmp 0, Y for equalities or if there is no overflow.
  2868. if ((C == LHS || D == LHS) && NoRHSWrapProblem)
  2869. if (Value *V =
  2870. simplifyICmpInst(Pred, Constant::getNullValue(LHS->getType()),
  2871. C == LHS ? D : C, Q, MaxRecurse - 1))
  2872. return V;
  2873. // icmp (X+Y), (X+Z) -> icmp Y,Z for equalities or if there is no overflow.
  2874. bool CanSimplify = (NoLHSWrapProblem && NoRHSWrapProblem) ||
  2875. trySimplifyICmpWithAdds(Pred, LHS, RHS);
  2876. if (A && C && (A == C || A == D || B == C || B == D) && CanSimplify) {
  2877. // Determine Y and Z in the form icmp (X+Y), (X+Z).
  2878. Value *Y, *Z;
  2879. if (A == C) {
  2880. // C + B == C + D -> B == D
  2881. Y = B;
  2882. Z = D;
  2883. } else if (A == D) {
  2884. // D + B == C + D -> B == C
  2885. Y = B;
  2886. Z = C;
  2887. } else if (B == C) {
  2888. // A + C == C + D -> A == D
  2889. Y = A;
  2890. Z = D;
  2891. } else {
  2892. assert(B == D);
  2893. // A + D == C + D -> A == C
  2894. Y = A;
  2895. Z = C;
  2896. }
  2897. if (Value *V = simplifyICmpInst(Pred, Y, Z, Q, MaxRecurse - 1))
  2898. return V;
  2899. }
  2900. }
  2901. if (LBO)
  2902. if (Value *V = simplifyICmpWithBinOpOnLHS(Pred, LBO, RHS, Q, MaxRecurse))
  2903. return V;
  2904. if (RBO)
  2905. if (Value *V = simplifyICmpWithBinOpOnLHS(
  2906. ICmpInst::getSwappedPredicate(Pred), RBO, LHS, Q, MaxRecurse))
  2907. return V;
  2908. // 0 - (zext X) pred C
  2909. if (!CmpInst::isUnsigned(Pred) && match(LHS, m_Neg(m_ZExt(m_Value())))) {
  2910. const APInt *C;
  2911. if (match(RHS, m_APInt(C))) {
  2912. if (C->isStrictlyPositive()) {
  2913. if (Pred == ICmpInst::ICMP_SLT || Pred == ICmpInst::ICMP_NE)
  2914. return ConstantInt::getTrue(getCompareTy(RHS));
  2915. if (Pred == ICmpInst::ICMP_SGE || Pred == ICmpInst::ICMP_EQ)
  2916. return ConstantInt::getFalse(getCompareTy(RHS));
  2917. }
  2918. if (C->isNonNegative()) {
  2919. if (Pred == ICmpInst::ICMP_SLE)
  2920. return ConstantInt::getTrue(getCompareTy(RHS));
  2921. if (Pred == ICmpInst::ICMP_SGT)
  2922. return ConstantInt::getFalse(getCompareTy(RHS));
  2923. }
  2924. }
  2925. }
  2926. // If C2 is a power-of-2 and C is not:
  2927. // (C2 << X) == C --> false
  2928. // (C2 << X) != C --> true
  2929. const APInt *C;
  2930. if (match(LHS, m_Shl(m_Power2(), m_Value())) &&
  2931. match(RHS, m_APIntAllowUndef(C)) && !C->isPowerOf2()) {
  2932. // C2 << X can equal zero in some circumstances.
  2933. // This simplification might be unsafe if C is zero.
  2934. //
  2935. // We know it is safe if:
  2936. // - The shift is nsw. We can't shift out the one bit.
  2937. // - The shift is nuw. We can't shift out the one bit.
  2938. // - C2 is one.
  2939. // - C isn't zero.
  2940. if (Q.IIQ.hasNoSignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
  2941. Q.IIQ.hasNoUnsignedWrap(cast<OverflowingBinaryOperator>(LBO)) ||
  2942. match(LHS, m_Shl(m_One(), m_Value())) || !C->isZero()) {
  2943. if (Pred == ICmpInst::ICMP_EQ)
  2944. return ConstantInt::getFalse(getCompareTy(RHS));
  2945. if (Pred == ICmpInst::ICMP_NE)
  2946. return ConstantInt::getTrue(getCompareTy(RHS));
  2947. }
  2948. }
  2949. // TODO: This is overly constrained. LHS can be any power-of-2.
  2950. // (1 << X) >u 0x8000 --> false
  2951. // (1 << X) <=u 0x8000 --> true
  2952. if (match(LHS, m_Shl(m_One(), m_Value())) && match(RHS, m_SignMask())) {
  2953. if (Pred == ICmpInst::ICMP_UGT)
  2954. return ConstantInt::getFalse(getCompareTy(RHS));
  2955. if (Pred == ICmpInst::ICMP_ULE)
  2956. return ConstantInt::getTrue(getCompareTy(RHS));
  2957. }
  2958. if (MaxRecurse && LBO && RBO && LBO->getOpcode() == RBO->getOpcode() &&
  2959. LBO->getOperand(1) == RBO->getOperand(1)) {
  2960. switch (LBO->getOpcode()) {
  2961. default:
  2962. break;
  2963. case Instruction::UDiv:
  2964. case Instruction::LShr:
  2965. if (ICmpInst::isSigned(Pred) || !Q.IIQ.isExact(LBO) ||
  2966. !Q.IIQ.isExact(RBO))
  2967. break;
  2968. if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
  2969. RBO->getOperand(0), Q, MaxRecurse - 1))
  2970. return V;
  2971. break;
  2972. case Instruction::SDiv:
  2973. if (!ICmpInst::isEquality(Pred) || !Q.IIQ.isExact(LBO) ||
  2974. !Q.IIQ.isExact(RBO))
  2975. break;
  2976. if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
  2977. RBO->getOperand(0), Q, MaxRecurse - 1))
  2978. return V;
  2979. break;
  2980. case Instruction::AShr:
  2981. if (!Q.IIQ.isExact(LBO) || !Q.IIQ.isExact(RBO))
  2982. break;
  2983. if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
  2984. RBO->getOperand(0), Q, MaxRecurse - 1))
  2985. return V;
  2986. break;
  2987. case Instruction::Shl: {
  2988. bool NUW = Q.IIQ.hasNoUnsignedWrap(LBO) && Q.IIQ.hasNoUnsignedWrap(RBO);
  2989. bool NSW = Q.IIQ.hasNoSignedWrap(LBO) && Q.IIQ.hasNoSignedWrap(RBO);
  2990. if (!NUW && !NSW)
  2991. break;
  2992. if (!NSW && ICmpInst::isSigned(Pred))
  2993. break;
  2994. if (Value *V = simplifyICmpInst(Pred, LBO->getOperand(0),
  2995. RBO->getOperand(0), Q, MaxRecurse - 1))
  2996. return V;
  2997. break;
  2998. }
  2999. }
  3000. }
  3001. return nullptr;
  3002. }
  3003. /// simplify integer comparisons where at least one operand of the compare
  3004. /// matches an integer min/max idiom.
  3005. static Value *simplifyICmpWithMinMax(CmpInst::Predicate Pred, Value *LHS,
  3006. Value *RHS, const SimplifyQuery &Q,
  3007. unsigned MaxRecurse) {
  3008. Type *ITy = getCompareTy(LHS); // The return type.
  3009. Value *A, *B;
  3010. CmpInst::Predicate P = CmpInst::BAD_ICMP_PREDICATE;
  3011. CmpInst::Predicate EqP; // Chosen so that "A == max/min(A,B)" iff "A EqP B".
  3012. // Signed variants on "max(a,b)>=a -> true".
  3013. if (match(LHS, m_SMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
  3014. if (A != RHS)
  3015. std::swap(A, B); // smax(A, B) pred A.
  3016. EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
  3017. // We analyze this as smax(A, B) pred A.
  3018. P = Pred;
  3019. } else if (match(RHS, m_SMax(m_Value(A), m_Value(B))) &&
  3020. (A == LHS || B == LHS)) {
  3021. if (A != LHS)
  3022. std::swap(A, B); // A pred smax(A, B).
  3023. EqP = CmpInst::ICMP_SGE; // "A == smax(A, B)" iff "A sge B".
  3024. // We analyze this as smax(A, B) swapped-pred A.
  3025. P = CmpInst::getSwappedPredicate(Pred);
  3026. } else if (match(LHS, m_SMin(m_Value(A), m_Value(B))) &&
  3027. (A == RHS || B == RHS)) {
  3028. if (A != RHS)
  3029. std::swap(A, B); // smin(A, B) pred A.
  3030. EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
  3031. // We analyze this as smax(-A, -B) swapped-pred -A.
  3032. // Note that we do not need to actually form -A or -B thanks to EqP.
  3033. P = CmpInst::getSwappedPredicate(Pred);
  3034. } else if (match(RHS, m_SMin(m_Value(A), m_Value(B))) &&
  3035. (A == LHS || B == LHS)) {
  3036. if (A != LHS)
  3037. std::swap(A, B); // A pred smin(A, B).
  3038. EqP = CmpInst::ICMP_SLE; // "A == smin(A, B)" iff "A sle B".
  3039. // We analyze this as smax(-A, -B) pred -A.
  3040. // Note that we do not need to actually form -A or -B thanks to EqP.
  3041. P = Pred;
  3042. }
  3043. if (P != CmpInst::BAD_ICMP_PREDICATE) {
  3044. // Cases correspond to "max(A, B) p A".
  3045. switch (P) {
  3046. default:
  3047. break;
  3048. case CmpInst::ICMP_EQ:
  3049. case CmpInst::ICMP_SLE:
  3050. // Equivalent to "A EqP B". This may be the same as the condition tested
  3051. // in the max/min; if so, we can just return that.
  3052. if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
  3053. return V;
  3054. if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
  3055. return V;
  3056. // Otherwise, see if "A EqP B" simplifies.
  3057. if (MaxRecurse)
  3058. if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
  3059. return V;
  3060. break;
  3061. case CmpInst::ICMP_NE:
  3062. case CmpInst::ICMP_SGT: {
  3063. CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
  3064. // Equivalent to "A InvEqP B". This may be the same as the condition
  3065. // tested in the max/min; if so, we can just return that.
  3066. if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
  3067. return V;
  3068. if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
  3069. return V;
  3070. // Otherwise, see if "A InvEqP B" simplifies.
  3071. if (MaxRecurse)
  3072. if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
  3073. return V;
  3074. break;
  3075. }
  3076. case CmpInst::ICMP_SGE:
  3077. // Always true.
  3078. return getTrue(ITy);
  3079. case CmpInst::ICMP_SLT:
  3080. // Always false.
  3081. return getFalse(ITy);
  3082. }
  3083. }
  3084. // Unsigned variants on "max(a,b)>=a -> true".
  3085. P = CmpInst::BAD_ICMP_PREDICATE;
  3086. if (match(LHS, m_UMax(m_Value(A), m_Value(B))) && (A == RHS || B == RHS)) {
  3087. if (A != RHS)
  3088. std::swap(A, B); // umax(A, B) pred A.
  3089. EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
  3090. // We analyze this as umax(A, B) pred A.
  3091. P = Pred;
  3092. } else if (match(RHS, m_UMax(m_Value(A), m_Value(B))) &&
  3093. (A == LHS || B == LHS)) {
  3094. if (A != LHS)
  3095. std::swap(A, B); // A pred umax(A, B).
  3096. EqP = CmpInst::ICMP_UGE; // "A == umax(A, B)" iff "A uge B".
  3097. // We analyze this as umax(A, B) swapped-pred A.
  3098. P = CmpInst::getSwappedPredicate(Pred);
  3099. } else if (match(LHS, m_UMin(m_Value(A), m_Value(B))) &&
  3100. (A == RHS || B == RHS)) {
  3101. if (A != RHS)
  3102. std::swap(A, B); // umin(A, B) pred A.
  3103. EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
  3104. // We analyze this as umax(-A, -B) swapped-pred -A.
  3105. // Note that we do not need to actually form -A or -B thanks to EqP.
  3106. P = CmpInst::getSwappedPredicate(Pred);
  3107. } else if (match(RHS, m_UMin(m_Value(A), m_Value(B))) &&
  3108. (A == LHS || B == LHS)) {
  3109. if (A != LHS)
  3110. std::swap(A, B); // A pred umin(A, B).
  3111. EqP = CmpInst::ICMP_ULE; // "A == umin(A, B)" iff "A ule B".
  3112. // We analyze this as umax(-A, -B) pred -A.
  3113. // Note that we do not need to actually form -A or -B thanks to EqP.
  3114. P = Pred;
  3115. }
  3116. if (P != CmpInst::BAD_ICMP_PREDICATE) {
  3117. // Cases correspond to "max(A, B) p A".
  3118. switch (P) {
  3119. default:
  3120. break;
  3121. case CmpInst::ICMP_EQ:
  3122. case CmpInst::ICMP_ULE:
  3123. // Equivalent to "A EqP B". This may be the same as the condition tested
  3124. // in the max/min; if so, we can just return that.
  3125. if (Value *V = extractEquivalentCondition(LHS, EqP, A, B))
  3126. return V;
  3127. if (Value *V = extractEquivalentCondition(RHS, EqP, A, B))
  3128. return V;
  3129. // Otherwise, see if "A EqP B" simplifies.
  3130. if (MaxRecurse)
  3131. if (Value *V = simplifyICmpInst(EqP, A, B, Q, MaxRecurse - 1))
  3132. return V;
  3133. break;
  3134. case CmpInst::ICMP_NE:
  3135. case CmpInst::ICMP_UGT: {
  3136. CmpInst::Predicate InvEqP = CmpInst::getInversePredicate(EqP);
  3137. // Equivalent to "A InvEqP B". This may be the same as the condition
  3138. // tested in the max/min; if so, we can just return that.
  3139. if (Value *V = extractEquivalentCondition(LHS, InvEqP, A, B))
  3140. return V;
  3141. if (Value *V = extractEquivalentCondition(RHS, InvEqP, A, B))
  3142. return V;
  3143. // Otherwise, see if "A InvEqP B" simplifies.
  3144. if (MaxRecurse)
  3145. if (Value *V = simplifyICmpInst(InvEqP, A, B, Q, MaxRecurse - 1))
  3146. return V;
  3147. break;
  3148. }
  3149. case CmpInst::ICMP_UGE:
  3150. return getTrue(ITy);
  3151. case CmpInst::ICMP_ULT:
  3152. return getFalse(ITy);
  3153. }
  3154. }
  3155. // Comparing 1 each of min/max with a common operand?
  3156. // Canonicalize min operand to RHS.
  3157. if (match(LHS, m_UMin(m_Value(), m_Value())) ||
  3158. match(LHS, m_SMin(m_Value(), m_Value()))) {
  3159. std::swap(LHS, RHS);
  3160. Pred = ICmpInst::getSwappedPredicate(Pred);
  3161. }
  3162. Value *C, *D;
  3163. if (match(LHS, m_SMax(m_Value(A), m_Value(B))) &&
  3164. match(RHS, m_SMin(m_Value(C), m_Value(D))) &&
  3165. (A == C || A == D || B == C || B == D)) {
  3166. // smax(A, B) >=s smin(A, D) --> true
  3167. if (Pred == CmpInst::ICMP_SGE)
  3168. return getTrue(ITy);
  3169. // smax(A, B) <s smin(A, D) --> false
  3170. if (Pred == CmpInst::ICMP_SLT)
  3171. return getFalse(ITy);
  3172. } else if (match(LHS, m_UMax(m_Value(A), m_Value(B))) &&
  3173. match(RHS, m_UMin(m_Value(C), m_Value(D))) &&
  3174. (A == C || A == D || B == C || B == D)) {
  3175. // umax(A, B) >=u umin(A, D) --> true
  3176. if (Pred == CmpInst::ICMP_UGE)
  3177. return getTrue(ITy);
  3178. // umax(A, B) <u umin(A, D) --> false
  3179. if (Pred == CmpInst::ICMP_ULT)
  3180. return getFalse(ITy);
  3181. }
  3182. return nullptr;
  3183. }
  3184. static Value *simplifyICmpWithDominatingAssume(CmpInst::Predicate Predicate,
  3185. Value *LHS, Value *RHS,
  3186. const SimplifyQuery &Q) {
  3187. // Gracefully handle instructions that have not been inserted yet.
  3188. if (!Q.AC || !Q.CxtI || !Q.CxtI->getParent())
  3189. return nullptr;
  3190. for (Value *AssumeBaseOp : {LHS, RHS}) {
  3191. for (auto &AssumeVH : Q.AC->assumptionsFor(AssumeBaseOp)) {
  3192. if (!AssumeVH)
  3193. continue;
  3194. CallInst *Assume = cast<CallInst>(AssumeVH);
  3195. if (std::optional<bool> Imp = isImpliedCondition(
  3196. Assume->getArgOperand(0), Predicate, LHS, RHS, Q.DL))
  3197. if (isValidAssumeForContext(Assume, Q.CxtI, Q.DT))
  3198. return ConstantInt::get(getCompareTy(LHS), *Imp);
  3199. }
  3200. }
  3201. return nullptr;
  3202. }
  3203. /// Given operands for an ICmpInst, see if we can fold the result.
  3204. /// If not, this returns null.
  3205. static Value *simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  3206. const SimplifyQuery &Q, unsigned MaxRecurse) {
  3207. CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
  3208. assert(CmpInst::isIntPredicate(Pred) && "Not an integer compare!");
  3209. if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
  3210. if (Constant *CRHS = dyn_cast<Constant>(RHS))
  3211. return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI);
  3212. // If we have a constant, make sure it is on the RHS.
  3213. std::swap(LHS, RHS);
  3214. Pred = CmpInst::getSwappedPredicate(Pred);
  3215. }
  3216. assert(!isa<UndefValue>(LHS) && "Unexpected icmp undef,%X");
  3217. Type *ITy = getCompareTy(LHS); // The return type.
  3218. // icmp poison, X -> poison
  3219. if (isa<PoisonValue>(RHS))
  3220. return PoisonValue::get(ITy);
  3221. // For EQ and NE, we can always pick a value for the undef to make the
  3222. // predicate pass or fail, so we can return undef.
  3223. // Matches behavior in llvm::ConstantFoldCompareInstruction.
  3224. if (Q.isUndefValue(RHS) && ICmpInst::isEquality(Pred))
  3225. return UndefValue::get(ITy);
  3226. // icmp X, X -> true/false
  3227. // icmp X, undef -> true/false because undef could be X.
  3228. if (LHS == RHS || Q.isUndefValue(RHS))
  3229. return ConstantInt::get(ITy, CmpInst::isTrueWhenEqual(Pred));
  3230. if (Value *V = simplifyICmpOfBools(Pred, LHS, RHS, Q))
  3231. return V;
  3232. // TODO: Sink/common this with other potentially expensive calls that use
  3233. // ValueTracking? See comment below for isKnownNonEqual().
  3234. if (Value *V = simplifyICmpWithZero(Pred, LHS, RHS, Q))
  3235. return V;
  3236. if (Value *V = simplifyICmpWithConstant(Pred, LHS, RHS, Q.IIQ))
  3237. return V;
  3238. // If both operands have range metadata, use the metadata
  3239. // to simplify the comparison.
  3240. if (isa<Instruction>(RHS) && isa<Instruction>(LHS)) {
  3241. auto RHS_Instr = cast<Instruction>(RHS);
  3242. auto LHS_Instr = cast<Instruction>(LHS);
  3243. if (Q.IIQ.getMetadata(RHS_Instr, LLVMContext::MD_range) &&
  3244. Q.IIQ.getMetadata(LHS_Instr, LLVMContext::MD_range)) {
  3245. auto RHS_CR = getConstantRangeFromMetadata(
  3246. *RHS_Instr->getMetadata(LLVMContext::MD_range));
  3247. auto LHS_CR = getConstantRangeFromMetadata(
  3248. *LHS_Instr->getMetadata(LLVMContext::MD_range));
  3249. if (LHS_CR.icmp(Pred, RHS_CR))
  3250. return ConstantInt::getTrue(RHS->getContext());
  3251. if (LHS_CR.icmp(CmpInst::getInversePredicate(Pred), RHS_CR))
  3252. return ConstantInt::getFalse(RHS->getContext());
  3253. }
  3254. }
  3255. // Compare of cast, for example (zext X) != 0 -> X != 0
  3256. if (isa<CastInst>(LHS) && (isa<Constant>(RHS) || isa<CastInst>(RHS))) {
  3257. Instruction *LI = cast<CastInst>(LHS);
  3258. Value *SrcOp = LI->getOperand(0);
  3259. Type *SrcTy = SrcOp->getType();
  3260. Type *DstTy = LI->getType();
  3261. // Turn icmp (ptrtoint x), (ptrtoint/constant) into a compare of the input
  3262. // if the integer type is the same size as the pointer type.
  3263. if (MaxRecurse && isa<PtrToIntInst>(LI) &&
  3264. Q.DL.getTypeSizeInBits(SrcTy) == DstTy->getPrimitiveSizeInBits()) {
  3265. if (Constant *RHSC = dyn_cast<Constant>(RHS)) {
  3266. // Transfer the cast to the constant.
  3267. if (Value *V = simplifyICmpInst(Pred, SrcOp,
  3268. ConstantExpr::getIntToPtr(RHSC, SrcTy),
  3269. Q, MaxRecurse - 1))
  3270. return V;
  3271. } else if (PtrToIntInst *RI = dyn_cast<PtrToIntInst>(RHS)) {
  3272. if (RI->getOperand(0)->getType() == SrcTy)
  3273. // Compare without the cast.
  3274. if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
  3275. MaxRecurse - 1))
  3276. return V;
  3277. }
  3278. }
  3279. if (isa<ZExtInst>(LHS)) {
  3280. // Turn icmp (zext X), (zext Y) into a compare of X and Y if they have the
  3281. // same type.
  3282. if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
  3283. if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
  3284. // Compare X and Y. Note that signed predicates become unsigned.
  3285. if (Value *V =
  3286. simplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred), SrcOp,
  3287. RI->getOperand(0), Q, MaxRecurse - 1))
  3288. return V;
  3289. }
  3290. // Fold (zext X) ule (sext X), (zext X) sge (sext X) to true.
  3291. else if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
  3292. if (SrcOp == RI->getOperand(0)) {
  3293. if (Pred == ICmpInst::ICMP_ULE || Pred == ICmpInst::ICMP_SGE)
  3294. return ConstantInt::getTrue(ITy);
  3295. if (Pred == ICmpInst::ICMP_UGT || Pred == ICmpInst::ICMP_SLT)
  3296. return ConstantInt::getFalse(ITy);
  3297. }
  3298. }
  3299. // Turn icmp (zext X), Cst into a compare of X and Cst if Cst is extended
  3300. // too. If not, then try to deduce the result of the comparison.
  3301. else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
  3302. // Compute the constant that would happen if we truncated to SrcTy then
  3303. // reextended to DstTy.
  3304. Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
  3305. Constant *RExt = ConstantExpr::getCast(CastInst::ZExt, Trunc, DstTy);
  3306. // If the re-extended constant didn't change then this is effectively
  3307. // also a case of comparing two zero-extended values.
  3308. if (RExt == CI && MaxRecurse)
  3309. if (Value *V = simplifyICmpInst(ICmpInst::getUnsignedPredicate(Pred),
  3310. SrcOp, Trunc, Q, MaxRecurse - 1))
  3311. return V;
  3312. // Otherwise the upper bits of LHS are zero while RHS has a non-zero bit
  3313. // there. Use this to work out the result of the comparison.
  3314. if (RExt != CI) {
  3315. switch (Pred) {
  3316. default:
  3317. llvm_unreachable("Unknown ICmp predicate!");
  3318. // LHS <u RHS.
  3319. case ICmpInst::ICMP_EQ:
  3320. case ICmpInst::ICMP_UGT:
  3321. case ICmpInst::ICMP_UGE:
  3322. return ConstantInt::getFalse(CI->getContext());
  3323. case ICmpInst::ICMP_NE:
  3324. case ICmpInst::ICMP_ULT:
  3325. case ICmpInst::ICMP_ULE:
  3326. return ConstantInt::getTrue(CI->getContext());
  3327. // LHS is non-negative. If RHS is negative then LHS >s LHS. If RHS
  3328. // is non-negative then LHS <s RHS.
  3329. case ICmpInst::ICMP_SGT:
  3330. case ICmpInst::ICMP_SGE:
  3331. return CI->getValue().isNegative()
  3332. ? ConstantInt::getTrue(CI->getContext())
  3333. : ConstantInt::getFalse(CI->getContext());
  3334. case ICmpInst::ICMP_SLT:
  3335. case ICmpInst::ICMP_SLE:
  3336. return CI->getValue().isNegative()
  3337. ? ConstantInt::getFalse(CI->getContext())
  3338. : ConstantInt::getTrue(CI->getContext());
  3339. }
  3340. }
  3341. }
  3342. }
  3343. if (isa<SExtInst>(LHS)) {
  3344. // Turn icmp (sext X), (sext Y) into a compare of X and Y if they have the
  3345. // same type.
  3346. if (SExtInst *RI = dyn_cast<SExtInst>(RHS)) {
  3347. if (MaxRecurse && SrcTy == RI->getOperand(0)->getType())
  3348. // Compare X and Y. Note that the predicate does not change.
  3349. if (Value *V = simplifyICmpInst(Pred, SrcOp, RI->getOperand(0), Q,
  3350. MaxRecurse - 1))
  3351. return V;
  3352. }
  3353. // Fold (sext X) uge (zext X), (sext X) sle (zext X) to true.
  3354. else if (ZExtInst *RI = dyn_cast<ZExtInst>(RHS)) {
  3355. if (SrcOp == RI->getOperand(0)) {
  3356. if (Pred == ICmpInst::ICMP_UGE || Pred == ICmpInst::ICMP_SLE)
  3357. return ConstantInt::getTrue(ITy);
  3358. if (Pred == ICmpInst::ICMP_ULT || Pred == ICmpInst::ICMP_SGT)
  3359. return ConstantInt::getFalse(ITy);
  3360. }
  3361. }
  3362. // Turn icmp (sext X), Cst into a compare of X and Cst if Cst is extended
  3363. // too. If not, then try to deduce the result of the comparison.
  3364. else if (ConstantInt *CI = dyn_cast<ConstantInt>(RHS)) {
  3365. // Compute the constant that would happen if we truncated to SrcTy then
  3366. // reextended to DstTy.
  3367. Constant *Trunc = ConstantExpr::getTrunc(CI, SrcTy);
  3368. Constant *RExt = ConstantExpr::getCast(CastInst::SExt, Trunc, DstTy);
  3369. // If the re-extended constant didn't change then this is effectively
  3370. // also a case of comparing two sign-extended values.
  3371. if (RExt == CI && MaxRecurse)
  3372. if (Value *V =
  3373. simplifyICmpInst(Pred, SrcOp, Trunc, Q, MaxRecurse - 1))
  3374. return V;
  3375. // Otherwise the upper bits of LHS are all equal, while RHS has varying
  3376. // bits there. Use this to work out the result of the comparison.
  3377. if (RExt != CI) {
  3378. switch (Pred) {
  3379. default:
  3380. llvm_unreachable("Unknown ICmp predicate!");
  3381. case ICmpInst::ICMP_EQ:
  3382. return ConstantInt::getFalse(CI->getContext());
  3383. case ICmpInst::ICMP_NE:
  3384. return ConstantInt::getTrue(CI->getContext());
  3385. // If RHS is non-negative then LHS <s RHS. If RHS is negative then
  3386. // LHS >s RHS.
  3387. case ICmpInst::ICMP_SGT:
  3388. case ICmpInst::ICMP_SGE:
  3389. return CI->getValue().isNegative()
  3390. ? ConstantInt::getTrue(CI->getContext())
  3391. : ConstantInt::getFalse(CI->getContext());
  3392. case ICmpInst::ICMP_SLT:
  3393. case ICmpInst::ICMP_SLE:
  3394. return CI->getValue().isNegative()
  3395. ? ConstantInt::getFalse(CI->getContext())
  3396. : ConstantInt::getTrue(CI->getContext());
  3397. // If LHS is non-negative then LHS <u RHS. If LHS is negative then
  3398. // LHS >u RHS.
  3399. case ICmpInst::ICMP_UGT:
  3400. case ICmpInst::ICMP_UGE:
  3401. // Comparison is true iff the LHS <s 0.
  3402. if (MaxRecurse)
  3403. if (Value *V = simplifyICmpInst(ICmpInst::ICMP_SLT, SrcOp,
  3404. Constant::getNullValue(SrcTy), Q,
  3405. MaxRecurse - 1))
  3406. return V;
  3407. break;
  3408. case ICmpInst::ICMP_ULT:
  3409. case ICmpInst::ICMP_ULE:
  3410. // Comparison is true iff the LHS >=s 0.
  3411. if (MaxRecurse)
  3412. if (Value *V = simplifyICmpInst(ICmpInst::ICMP_SGE, SrcOp,
  3413. Constant::getNullValue(SrcTy), Q,
  3414. MaxRecurse - 1))
  3415. return V;
  3416. break;
  3417. }
  3418. }
  3419. }
  3420. }
  3421. }
  3422. // icmp eq|ne X, Y -> false|true if X != Y
  3423. // This is potentially expensive, and we have already computedKnownBits for
  3424. // compares with 0 above here, so only try this for a non-zero compare.
  3425. if (ICmpInst::isEquality(Pred) && !match(RHS, m_Zero()) &&
  3426. isKnownNonEqual(LHS, RHS, Q.DL, Q.AC, Q.CxtI, Q.DT, Q.IIQ.UseInstrInfo)) {
  3427. return Pred == ICmpInst::ICMP_NE ? getTrue(ITy) : getFalse(ITy);
  3428. }
  3429. if (Value *V = simplifyICmpWithBinOp(Pred, LHS, RHS, Q, MaxRecurse))
  3430. return V;
  3431. if (Value *V = simplifyICmpWithMinMax(Pred, LHS, RHS, Q, MaxRecurse))
  3432. return V;
  3433. if (Value *V = simplifyICmpWithDominatingAssume(Pred, LHS, RHS, Q))
  3434. return V;
  3435. // Simplify comparisons of related pointers using a powerful, recursive
  3436. // GEP-walk when we have target data available..
  3437. if (LHS->getType()->isPointerTy())
  3438. if (auto *C = computePointerICmp(Pred, LHS, RHS, Q))
  3439. return C;
  3440. if (auto *CLHS = dyn_cast<PtrToIntOperator>(LHS))
  3441. if (auto *CRHS = dyn_cast<PtrToIntOperator>(RHS))
  3442. if (Q.DL.getTypeSizeInBits(CLHS->getPointerOperandType()) ==
  3443. Q.DL.getTypeSizeInBits(CLHS->getType()) &&
  3444. Q.DL.getTypeSizeInBits(CRHS->getPointerOperandType()) ==
  3445. Q.DL.getTypeSizeInBits(CRHS->getType()))
  3446. if (auto *C = computePointerICmp(Pred, CLHS->getPointerOperand(),
  3447. CRHS->getPointerOperand(), Q))
  3448. return C;
  3449. // If the comparison is with the result of a select instruction, check whether
  3450. // comparing with either branch of the select always yields the same value.
  3451. if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
  3452. if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
  3453. return V;
  3454. // If the comparison is with the result of a phi instruction, check whether
  3455. // doing the compare with each incoming phi value yields a common result.
  3456. if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
  3457. if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
  3458. return V;
  3459. return nullptr;
  3460. }
  3461. Value *llvm::simplifyICmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  3462. const SimplifyQuery &Q) {
  3463. return ::simplifyICmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
  3464. }
  3465. /// Given operands for an FCmpInst, see if we can fold the result.
  3466. /// If not, this returns null.
  3467. static Value *simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  3468. FastMathFlags FMF, const SimplifyQuery &Q,
  3469. unsigned MaxRecurse) {
  3470. CmpInst::Predicate Pred = (CmpInst::Predicate)Predicate;
  3471. assert(CmpInst::isFPPredicate(Pred) && "Not an FP compare!");
  3472. if (Constant *CLHS = dyn_cast<Constant>(LHS)) {
  3473. if (Constant *CRHS = dyn_cast<Constant>(RHS))
  3474. return ConstantFoldCompareInstOperands(Pred, CLHS, CRHS, Q.DL, Q.TLI,
  3475. Q.CxtI);
  3476. // If we have a constant, make sure it is on the RHS.
  3477. std::swap(LHS, RHS);
  3478. Pred = CmpInst::getSwappedPredicate(Pred);
  3479. }
  3480. // Fold trivial predicates.
  3481. Type *RetTy = getCompareTy(LHS);
  3482. if (Pred == FCmpInst::FCMP_FALSE)
  3483. return getFalse(RetTy);
  3484. if (Pred == FCmpInst::FCMP_TRUE)
  3485. return getTrue(RetTy);
  3486. // Fold (un)ordered comparison if we can determine there are no NaNs.
  3487. if (Pred == FCmpInst::FCMP_UNO || Pred == FCmpInst::FCMP_ORD)
  3488. if (FMF.noNaNs() ||
  3489. (isKnownNeverNaN(LHS, Q.TLI) && isKnownNeverNaN(RHS, Q.TLI)))
  3490. return ConstantInt::get(RetTy, Pred == FCmpInst::FCMP_ORD);
  3491. // NaN is unordered; NaN is not ordered.
  3492. assert((FCmpInst::isOrdered(Pred) || FCmpInst::isUnordered(Pred)) &&
  3493. "Comparison must be either ordered or unordered");
  3494. if (match(RHS, m_NaN()))
  3495. return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
  3496. // fcmp pred x, poison and fcmp pred poison, x
  3497. // fold to poison
  3498. if (isa<PoisonValue>(LHS) || isa<PoisonValue>(RHS))
  3499. return PoisonValue::get(RetTy);
  3500. // fcmp pred x, undef and fcmp pred undef, x
  3501. // fold to true if unordered, false if ordered
  3502. if (Q.isUndefValue(LHS) || Q.isUndefValue(RHS)) {
  3503. // Choosing NaN for the undef will always make unordered comparison succeed
  3504. // and ordered comparison fail.
  3505. return ConstantInt::get(RetTy, CmpInst::isUnordered(Pred));
  3506. }
  3507. // fcmp x,x -> true/false. Not all compares are foldable.
  3508. if (LHS == RHS) {
  3509. if (CmpInst::isTrueWhenEqual(Pred))
  3510. return getTrue(RetTy);
  3511. if (CmpInst::isFalseWhenEqual(Pred))
  3512. return getFalse(RetTy);
  3513. }
  3514. // Handle fcmp with constant RHS.
  3515. // TODO: Use match with a specific FP value, so these work with vectors with
  3516. // undef lanes.
  3517. const APFloat *C;
  3518. if (match(RHS, m_APFloat(C))) {
  3519. // Check whether the constant is an infinity.
  3520. if (C->isInfinity()) {
  3521. if (C->isNegative()) {
  3522. switch (Pred) {
  3523. case FCmpInst::FCMP_OLT:
  3524. // No value is ordered and less than negative infinity.
  3525. return getFalse(RetTy);
  3526. case FCmpInst::FCMP_UGE:
  3527. // All values are unordered with or at least negative infinity.
  3528. return getTrue(RetTy);
  3529. default:
  3530. break;
  3531. }
  3532. } else {
  3533. switch (Pred) {
  3534. case FCmpInst::FCMP_OGT:
  3535. // No value is ordered and greater than infinity.
  3536. return getFalse(RetTy);
  3537. case FCmpInst::FCMP_ULE:
  3538. // All values are unordered with and at most infinity.
  3539. return getTrue(RetTy);
  3540. default:
  3541. break;
  3542. }
  3543. }
  3544. // LHS == Inf
  3545. if (Pred == FCmpInst::FCMP_OEQ && isKnownNeverInfinity(LHS, Q.TLI))
  3546. return getFalse(RetTy);
  3547. // LHS != Inf
  3548. if (Pred == FCmpInst::FCMP_UNE && isKnownNeverInfinity(LHS, Q.TLI))
  3549. return getTrue(RetTy);
  3550. // LHS == Inf || LHS == NaN
  3551. if (Pred == FCmpInst::FCMP_UEQ && isKnownNeverInfinity(LHS, Q.TLI) &&
  3552. isKnownNeverNaN(LHS, Q.TLI))
  3553. return getFalse(RetTy);
  3554. // LHS != Inf && LHS != NaN
  3555. if (Pred == FCmpInst::FCMP_ONE && isKnownNeverInfinity(LHS, Q.TLI) &&
  3556. isKnownNeverNaN(LHS, Q.TLI))
  3557. return getTrue(RetTy);
  3558. }
  3559. if (C->isNegative() && !C->isNegZero()) {
  3560. assert(!C->isNaN() && "Unexpected NaN constant!");
  3561. // TODO: We can catch more cases by using a range check rather than
  3562. // relying on CannotBeOrderedLessThanZero.
  3563. switch (Pred) {
  3564. case FCmpInst::FCMP_UGE:
  3565. case FCmpInst::FCMP_UGT:
  3566. case FCmpInst::FCMP_UNE:
  3567. // (X >= 0) implies (X > C) when (C < 0)
  3568. if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
  3569. return getTrue(RetTy);
  3570. break;
  3571. case FCmpInst::FCMP_OEQ:
  3572. case FCmpInst::FCMP_OLE:
  3573. case FCmpInst::FCMP_OLT:
  3574. // (X >= 0) implies !(X < C) when (C < 0)
  3575. if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
  3576. return getFalse(RetTy);
  3577. break;
  3578. default:
  3579. break;
  3580. }
  3581. }
  3582. // Check comparison of [minnum/maxnum with constant] with other constant.
  3583. const APFloat *C2;
  3584. if ((match(LHS, m_Intrinsic<Intrinsic::minnum>(m_Value(), m_APFloat(C2))) &&
  3585. *C2 < *C) ||
  3586. (match(LHS, m_Intrinsic<Intrinsic::maxnum>(m_Value(), m_APFloat(C2))) &&
  3587. *C2 > *C)) {
  3588. bool IsMaxNum =
  3589. cast<IntrinsicInst>(LHS)->getIntrinsicID() == Intrinsic::maxnum;
  3590. // The ordered relationship and minnum/maxnum guarantee that we do not
  3591. // have NaN constants, so ordered/unordered preds are handled the same.
  3592. switch (Pred) {
  3593. case FCmpInst::FCMP_OEQ:
  3594. case FCmpInst::FCMP_UEQ:
  3595. // minnum(X, LesserC) == C --> false
  3596. // maxnum(X, GreaterC) == C --> false
  3597. return getFalse(RetTy);
  3598. case FCmpInst::FCMP_ONE:
  3599. case FCmpInst::FCMP_UNE:
  3600. // minnum(X, LesserC) != C --> true
  3601. // maxnum(X, GreaterC) != C --> true
  3602. return getTrue(RetTy);
  3603. case FCmpInst::FCMP_OGE:
  3604. case FCmpInst::FCMP_UGE:
  3605. case FCmpInst::FCMP_OGT:
  3606. case FCmpInst::FCMP_UGT:
  3607. // minnum(X, LesserC) >= C --> false
  3608. // minnum(X, LesserC) > C --> false
  3609. // maxnum(X, GreaterC) >= C --> true
  3610. // maxnum(X, GreaterC) > C --> true
  3611. return ConstantInt::get(RetTy, IsMaxNum);
  3612. case FCmpInst::FCMP_OLE:
  3613. case FCmpInst::FCMP_ULE:
  3614. case FCmpInst::FCMP_OLT:
  3615. case FCmpInst::FCMP_ULT:
  3616. // minnum(X, LesserC) <= C --> true
  3617. // minnum(X, LesserC) < C --> true
  3618. // maxnum(X, GreaterC) <= C --> false
  3619. // maxnum(X, GreaterC) < C --> false
  3620. return ConstantInt::get(RetTy, !IsMaxNum);
  3621. default:
  3622. // TRUE/FALSE/ORD/UNO should be handled before this.
  3623. llvm_unreachable("Unexpected fcmp predicate");
  3624. }
  3625. }
  3626. }
  3627. if (match(RHS, m_AnyZeroFP())) {
  3628. switch (Pred) {
  3629. case FCmpInst::FCMP_OGE:
  3630. case FCmpInst::FCMP_ULT:
  3631. // Positive or zero X >= 0.0 --> true
  3632. // Positive or zero X < 0.0 --> false
  3633. if ((FMF.noNaNs() || isKnownNeverNaN(LHS, Q.TLI)) &&
  3634. CannotBeOrderedLessThanZero(LHS, Q.TLI))
  3635. return Pred == FCmpInst::FCMP_OGE ? getTrue(RetTy) : getFalse(RetTy);
  3636. break;
  3637. case FCmpInst::FCMP_UGE:
  3638. case FCmpInst::FCMP_OLT:
  3639. // Positive or zero or nan X >= 0.0 --> true
  3640. // Positive or zero or nan X < 0.0 --> false
  3641. if (CannotBeOrderedLessThanZero(LHS, Q.TLI))
  3642. return Pred == FCmpInst::FCMP_UGE ? getTrue(RetTy) : getFalse(RetTy);
  3643. break;
  3644. default:
  3645. break;
  3646. }
  3647. }
  3648. // If the comparison is with the result of a select instruction, check whether
  3649. // comparing with either branch of the select always yields the same value.
  3650. if (isa<SelectInst>(LHS) || isa<SelectInst>(RHS))
  3651. if (Value *V = threadCmpOverSelect(Pred, LHS, RHS, Q, MaxRecurse))
  3652. return V;
  3653. // If the comparison is with the result of a phi instruction, check whether
  3654. // doing the compare with each incoming phi value yields a common result.
  3655. if (isa<PHINode>(LHS) || isa<PHINode>(RHS))
  3656. if (Value *V = threadCmpOverPHI(Pred, LHS, RHS, Q, MaxRecurse))
  3657. return V;
  3658. return nullptr;
  3659. }
  3660. Value *llvm::simplifyFCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  3661. FastMathFlags FMF, const SimplifyQuery &Q) {
  3662. return ::simplifyFCmpInst(Predicate, LHS, RHS, FMF, Q, RecursionLimit);
  3663. }
  3664. static Value *simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
  3665. const SimplifyQuery &Q,
  3666. bool AllowRefinement,
  3667. unsigned MaxRecurse) {
  3668. // Trivial replacement.
  3669. if (V == Op)
  3670. return RepOp;
  3671. // We cannot replace a constant, and shouldn't even try.
  3672. if (isa<Constant>(Op))
  3673. return nullptr;
  3674. auto *I = dyn_cast<Instruction>(V);
  3675. if (!I || !is_contained(I->operands(), Op))
  3676. return nullptr;
  3677. if (Op->getType()->isVectorTy()) {
  3678. // For vector types, the simplification must hold per-lane, so forbid
  3679. // potentially cross-lane operations like shufflevector.
  3680. assert(I->getType()->isVectorTy() && "Vector type mismatch");
  3681. if (isa<ShuffleVectorInst>(I) || isa<CallBase>(I))
  3682. return nullptr;
  3683. }
  3684. // Replace Op with RepOp in instruction operands.
  3685. SmallVector<Value *, 8> NewOps(I->getNumOperands());
  3686. transform(I->operands(), NewOps.begin(),
  3687. [&](Value *V) { return V == Op ? RepOp : V; });
  3688. if (!AllowRefinement) {
  3689. // General InstSimplify functions may refine the result, e.g. by returning
  3690. // a constant for a potentially poison value. To avoid this, implement only
  3691. // a few non-refining but profitable transforms here.
  3692. if (auto *BO = dyn_cast<BinaryOperator>(I)) {
  3693. unsigned Opcode = BO->getOpcode();
  3694. // id op x -> x, x op id -> x
  3695. if (NewOps[0] == ConstantExpr::getBinOpIdentity(Opcode, I->getType()))
  3696. return NewOps[1];
  3697. if (NewOps[1] == ConstantExpr::getBinOpIdentity(Opcode, I->getType(),
  3698. /* RHS */ true))
  3699. return NewOps[0];
  3700. // x & x -> x, x | x -> x
  3701. if ((Opcode == Instruction::And || Opcode == Instruction::Or) &&
  3702. NewOps[0] == NewOps[1])
  3703. return NewOps[0];
  3704. }
  3705. if (auto *GEP = dyn_cast<GetElementPtrInst>(I)) {
  3706. // getelementptr x, 0 -> x
  3707. if (NewOps.size() == 2 && match(NewOps[1], m_Zero()) &&
  3708. !GEP->isInBounds())
  3709. return NewOps[0];
  3710. }
  3711. } else if (MaxRecurse) {
  3712. // The simplification queries below may return the original value. Consider:
  3713. // %div = udiv i32 %arg, %arg2
  3714. // %mul = mul nsw i32 %div, %arg2
  3715. // %cmp = icmp eq i32 %mul, %arg
  3716. // %sel = select i1 %cmp, i32 %div, i32 undef
  3717. // Replacing %arg by %mul, %div becomes "udiv i32 %mul, %arg2", which
  3718. // simplifies back to %arg. This can only happen because %mul does not
  3719. // dominate %div. To ensure a consistent return value contract, we make sure
  3720. // that this case returns nullptr as well.
  3721. auto PreventSelfSimplify = [V](Value *Simplified) {
  3722. return Simplified != V ? Simplified : nullptr;
  3723. };
  3724. if (auto *B = dyn_cast<BinaryOperator>(I))
  3725. return PreventSelfSimplify(simplifyBinOp(B->getOpcode(), NewOps[0],
  3726. NewOps[1], Q, MaxRecurse - 1));
  3727. if (CmpInst *C = dyn_cast<CmpInst>(I))
  3728. return PreventSelfSimplify(simplifyCmpInst(C->getPredicate(), NewOps[0],
  3729. NewOps[1], Q, MaxRecurse - 1));
  3730. if (auto *GEP = dyn_cast<GetElementPtrInst>(I))
  3731. return PreventSelfSimplify(simplifyGEPInst(
  3732. GEP->getSourceElementType(), NewOps[0], ArrayRef(NewOps).slice(1),
  3733. GEP->isInBounds(), Q, MaxRecurse - 1));
  3734. if (isa<SelectInst>(I))
  3735. return PreventSelfSimplify(simplifySelectInst(
  3736. NewOps[0], NewOps[1], NewOps[2], Q, MaxRecurse - 1));
  3737. // TODO: We could hand off more cases to instsimplify here.
  3738. }
  3739. // If all operands are constant after substituting Op for RepOp then we can
  3740. // constant fold the instruction.
  3741. SmallVector<Constant *, 8> ConstOps;
  3742. for (Value *NewOp : NewOps) {
  3743. if (Constant *ConstOp = dyn_cast<Constant>(NewOp))
  3744. ConstOps.push_back(ConstOp);
  3745. else
  3746. return nullptr;
  3747. }
  3748. // Consider:
  3749. // %cmp = icmp eq i32 %x, 2147483647
  3750. // %add = add nsw i32 %x, 1
  3751. // %sel = select i1 %cmp, i32 -2147483648, i32 %add
  3752. //
  3753. // We can't replace %sel with %add unless we strip away the flags (which
  3754. // will be done in InstCombine).
  3755. // TODO: This may be unsound, because it only catches some forms of
  3756. // refinement.
  3757. if (!AllowRefinement && canCreatePoison(cast<Operator>(I)))
  3758. return nullptr;
  3759. return ConstantFoldInstOperands(I, ConstOps, Q.DL, Q.TLI);
  3760. }
  3761. Value *llvm::simplifyWithOpReplaced(Value *V, Value *Op, Value *RepOp,
  3762. const SimplifyQuery &Q,
  3763. bool AllowRefinement) {
  3764. return ::simplifyWithOpReplaced(V, Op, RepOp, Q, AllowRefinement,
  3765. RecursionLimit);
  3766. }
  3767. /// Try to simplify a select instruction when its condition operand is an
  3768. /// integer comparison where one operand of the compare is a constant.
  3769. static Value *simplifySelectBitTest(Value *TrueVal, Value *FalseVal, Value *X,
  3770. const APInt *Y, bool TrueWhenUnset) {
  3771. const APInt *C;
  3772. // (X & Y) == 0 ? X & ~Y : X --> X
  3773. // (X & Y) != 0 ? X & ~Y : X --> X & ~Y
  3774. if (FalseVal == X && match(TrueVal, m_And(m_Specific(X), m_APInt(C))) &&
  3775. *Y == ~*C)
  3776. return TrueWhenUnset ? FalseVal : TrueVal;
  3777. // (X & Y) == 0 ? X : X & ~Y --> X & ~Y
  3778. // (X & Y) != 0 ? X : X & ~Y --> X
  3779. if (TrueVal == X && match(FalseVal, m_And(m_Specific(X), m_APInt(C))) &&
  3780. *Y == ~*C)
  3781. return TrueWhenUnset ? FalseVal : TrueVal;
  3782. if (Y->isPowerOf2()) {
  3783. // (X & Y) == 0 ? X | Y : X --> X | Y
  3784. // (X & Y) != 0 ? X | Y : X --> X
  3785. if (FalseVal == X && match(TrueVal, m_Or(m_Specific(X), m_APInt(C))) &&
  3786. *Y == *C)
  3787. return TrueWhenUnset ? TrueVal : FalseVal;
  3788. // (X & Y) == 0 ? X : X | Y --> X
  3789. // (X & Y) != 0 ? X : X | Y --> X | Y
  3790. if (TrueVal == X && match(FalseVal, m_Or(m_Specific(X), m_APInt(C))) &&
  3791. *Y == *C)
  3792. return TrueWhenUnset ? TrueVal : FalseVal;
  3793. }
  3794. return nullptr;
  3795. }
  3796. static Value *simplifyCmpSelOfMaxMin(Value *CmpLHS, Value *CmpRHS,
  3797. ICmpInst::Predicate Pred, Value *TVal,
  3798. Value *FVal) {
  3799. // Canonicalize common cmp+sel operand as CmpLHS.
  3800. if (CmpRHS == TVal || CmpRHS == FVal) {
  3801. std::swap(CmpLHS, CmpRHS);
  3802. Pred = ICmpInst::getSwappedPredicate(Pred);
  3803. }
  3804. // Canonicalize common cmp+sel operand as TVal.
  3805. if (CmpLHS == FVal) {
  3806. std::swap(TVal, FVal);
  3807. Pred = ICmpInst::getInversePredicate(Pred);
  3808. }
  3809. // A vector select may be shuffling together elements that are equivalent
  3810. // based on the max/min/select relationship.
  3811. Value *X = CmpLHS, *Y = CmpRHS;
  3812. bool PeekedThroughSelectShuffle = false;
  3813. auto *Shuf = dyn_cast<ShuffleVectorInst>(FVal);
  3814. if (Shuf && Shuf->isSelect()) {
  3815. if (Shuf->getOperand(0) == Y)
  3816. FVal = Shuf->getOperand(1);
  3817. else if (Shuf->getOperand(1) == Y)
  3818. FVal = Shuf->getOperand(0);
  3819. else
  3820. return nullptr;
  3821. PeekedThroughSelectShuffle = true;
  3822. }
  3823. // (X pred Y) ? X : max/min(X, Y)
  3824. auto *MMI = dyn_cast<MinMaxIntrinsic>(FVal);
  3825. if (!MMI || TVal != X ||
  3826. !match(FVal, m_c_MaxOrMin(m_Specific(X), m_Specific(Y))))
  3827. return nullptr;
  3828. // (X > Y) ? X : max(X, Y) --> max(X, Y)
  3829. // (X >= Y) ? X : max(X, Y) --> max(X, Y)
  3830. // (X < Y) ? X : min(X, Y) --> min(X, Y)
  3831. // (X <= Y) ? X : min(X, Y) --> min(X, Y)
  3832. //
  3833. // The equivalence allows a vector select (shuffle) of max/min and Y. Ex:
  3834. // (X > Y) ? X : (Z ? max(X, Y) : Y)
  3835. // If Z is true, this reduces as above, and if Z is false:
  3836. // (X > Y) ? X : Y --> max(X, Y)
  3837. ICmpInst::Predicate MMPred = MMI->getPredicate();
  3838. if (MMPred == CmpInst::getStrictPredicate(Pred))
  3839. return MMI;
  3840. // Other transforms are not valid with a shuffle.
  3841. if (PeekedThroughSelectShuffle)
  3842. return nullptr;
  3843. // (X == Y) ? X : max/min(X, Y) --> max/min(X, Y)
  3844. if (Pred == CmpInst::ICMP_EQ)
  3845. return MMI;
  3846. // (X != Y) ? X : max/min(X, Y) --> X
  3847. if (Pred == CmpInst::ICMP_NE)
  3848. return X;
  3849. // (X < Y) ? X : max(X, Y) --> X
  3850. // (X <= Y) ? X : max(X, Y) --> X
  3851. // (X > Y) ? X : min(X, Y) --> X
  3852. // (X >= Y) ? X : min(X, Y) --> X
  3853. ICmpInst::Predicate InvPred = CmpInst::getInversePredicate(Pred);
  3854. if (MMPred == CmpInst::getStrictPredicate(InvPred))
  3855. return X;
  3856. return nullptr;
  3857. }
  3858. /// An alternative way to test if a bit is set or not uses sgt/slt instead of
  3859. /// eq/ne.
  3860. static Value *simplifySelectWithFakeICmpEq(Value *CmpLHS, Value *CmpRHS,
  3861. ICmpInst::Predicate Pred,
  3862. Value *TrueVal, Value *FalseVal) {
  3863. Value *X;
  3864. APInt Mask;
  3865. if (!decomposeBitTestICmp(CmpLHS, CmpRHS, Pred, X, Mask))
  3866. return nullptr;
  3867. return simplifySelectBitTest(TrueVal, FalseVal, X, &Mask,
  3868. Pred == ICmpInst::ICMP_EQ);
  3869. }
  3870. /// Try to simplify a select instruction when its condition operand is an
  3871. /// integer comparison.
  3872. static Value *simplifySelectWithICmpCond(Value *CondVal, Value *TrueVal,
  3873. Value *FalseVal,
  3874. const SimplifyQuery &Q,
  3875. unsigned MaxRecurse) {
  3876. ICmpInst::Predicate Pred;
  3877. Value *CmpLHS, *CmpRHS;
  3878. if (!match(CondVal, m_ICmp(Pred, m_Value(CmpLHS), m_Value(CmpRHS))))
  3879. return nullptr;
  3880. if (Value *V = simplifyCmpSelOfMaxMin(CmpLHS, CmpRHS, Pred, TrueVal, FalseVal))
  3881. return V;
  3882. // Canonicalize ne to eq predicate.
  3883. if (Pred == ICmpInst::ICMP_NE) {
  3884. Pred = ICmpInst::ICMP_EQ;
  3885. std::swap(TrueVal, FalseVal);
  3886. }
  3887. // Check for integer min/max with a limit constant:
  3888. // X > MIN_INT ? X : MIN_INT --> X
  3889. // X < MAX_INT ? X : MAX_INT --> X
  3890. if (TrueVal->getType()->isIntOrIntVectorTy()) {
  3891. Value *X, *Y;
  3892. SelectPatternFlavor SPF =
  3893. matchDecomposedSelectPattern(cast<ICmpInst>(CondVal), TrueVal, FalseVal,
  3894. X, Y)
  3895. .Flavor;
  3896. if (SelectPatternResult::isMinOrMax(SPF) && Pred == getMinMaxPred(SPF)) {
  3897. APInt LimitC = getMinMaxLimit(getInverseMinMaxFlavor(SPF),
  3898. X->getType()->getScalarSizeInBits());
  3899. if (match(Y, m_SpecificInt(LimitC)))
  3900. return X;
  3901. }
  3902. }
  3903. if (Pred == ICmpInst::ICMP_EQ && match(CmpRHS, m_Zero())) {
  3904. Value *X;
  3905. const APInt *Y;
  3906. if (match(CmpLHS, m_And(m_Value(X), m_APInt(Y))))
  3907. if (Value *V = simplifySelectBitTest(TrueVal, FalseVal, X, Y,
  3908. /*TrueWhenUnset=*/true))
  3909. return V;
  3910. // Test for a bogus zero-shift-guard-op around funnel-shift or rotate.
  3911. Value *ShAmt;
  3912. auto isFsh = m_CombineOr(m_FShl(m_Value(X), m_Value(), m_Value(ShAmt)),
  3913. m_FShr(m_Value(), m_Value(X), m_Value(ShAmt)));
  3914. // (ShAmt == 0) ? fshl(X, *, ShAmt) : X --> X
  3915. // (ShAmt == 0) ? fshr(*, X, ShAmt) : X --> X
  3916. if (match(TrueVal, isFsh) && FalseVal == X && CmpLHS == ShAmt)
  3917. return X;
  3918. // Test for a zero-shift-guard-op around rotates. These are used to
  3919. // avoid UB from oversized shifts in raw IR rotate patterns, but the
  3920. // intrinsics do not have that problem.
  3921. // We do not allow this transform for the general funnel shift case because
  3922. // that would not preserve the poison safety of the original code.
  3923. auto isRotate =
  3924. m_CombineOr(m_FShl(m_Value(X), m_Deferred(X), m_Value(ShAmt)),
  3925. m_FShr(m_Value(X), m_Deferred(X), m_Value(ShAmt)));
  3926. // (ShAmt == 0) ? X : fshl(X, X, ShAmt) --> fshl(X, X, ShAmt)
  3927. // (ShAmt == 0) ? X : fshr(X, X, ShAmt) --> fshr(X, X, ShAmt)
  3928. if (match(FalseVal, isRotate) && TrueVal == X && CmpLHS == ShAmt &&
  3929. Pred == ICmpInst::ICMP_EQ)
  3930. return FalseVal;
  3931. // X == 0 ? abs(X) : -abs(X) --> -abs(X)
  3932. // X == 0 ? -abs(X) : abs(X) --> abs(X)
  3933. if (match(TrueVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))) &&
  3934. match(FalseVal, m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))))
  3935. return FalseVal;
  3936. if (match(TrueVal,
  3937. m_Neg(m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS)))) &&
  3938. match(FalseVal, m_Intrinsic<Intrinsic::abs>(m_Specific(CmpLHS))))
  3939. return FalseVal;
  3940. }
  3941. // Check for other compares that behave like bit test.
  3942. if (Value *V =
  3943. simplifySelectWithFakeICmpEq(CmpLHS, CmpRHS, Pred, TrueVal, FalseVal))
  3944. return V;
  3945. // If we have a scalar equality comparison, then we know the value in one of
  3946. // the arms of the select. See if substituting this value into the arm and
  3947. // simplifying the result yields the same value as the other arm.
  3948. if (Pred == ICmpInst::ICMP_EQ) {
  3949. if (simplifyWithOpReplaced(FalseVal, CmpLHS, CmpRHS, Q,
  3950. /* AllowRefinement */ false,
  3951. MaxRecurse) == TrueVal ||
  3952. simplifyWithOpReplaced(FalseVal, CmpRHS, CmpLHS, Q,
  3953. /* AllowRefinement */ false,
  3954. MaxRecurse) == TrueVal)
  3955. return FalseVal;
  3956. if (simplifyWithOpReplaced(TrueVal, CmpLHS, CmpRHS, Q,
  3957. /* AllowRefinement */ true,
  3958. MaxRecurse) == FalseVal ||
  3959. simplifyWithOpReplaced(TrueVal, CmpRHS, CmpLHS, Q,
  3960. /* AllowRefinement */ true,
  3961. MaxRecurse) == FalseVal)
  3962. return FalseVal;
  3963. }
  3964. return nullptr;
  3965. }
  3966. /// Try to simplify a select instruction when its condition operand is a
  3967. /// floating-point comparison.
  3968. static Value *simplifySelectWithFCmp(Value *Cond, Value *T, Value *F,
  3969. const SimplifyQuery &Q) {
  3970. FCmpInst::Predicate Pred;
  3971. if (!match(Cond, m_FCmp(Pred, m_Specific(T), m_Specific(F))) &&
  3972. !match(Cond, m_FCmp(Pred, m_Specific(F), m_Specific(T))))
  3973. return nullptr;
  3974. // This transform is safe if we do not have (do not care about) -0.0 or if
  3975. // at least one operand is known to not be -0.0. Otherwise, the select can
  3976. // change the sign of a zero operand.
  3977. bool HasNoSignedZeros =
  3978. Q.CxtI && isa<FPMathOperator>(Q.CxtI) && Q.CxtI->hasNoSignedZeros();
  3979. const APFloat *C;
  3980. if (HasNoSignedZeros || (match(T, m_APFloat(C)) && C->isNonZero()) ||
  3981. (match(F, m_APFloat(C)) && C->isNonZero())) {
  3982. // (T == F) ? T : F --> F
  3983. // (F == T) ? T : F --> F
  3984. if (Pred == FCmpInst::FCMP_OEQ)
  3985. return F;
  3986. // (T != F) ? T : F --> T
  3987. // (F != T) ? T : F --> T
  3988. if (Pred == FCmpInst::FCMP_UNE)
  3989. return T;
  3990. }
  3991. return nullptr;
  3992. }
  3993. /// Given operands for a SelectInst, see if we can fold the result.
  3994. /// If not, this returns null.
  3995. static Value *simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
  3996. const SimplifyQuery &Q, unsigned MaxRecurse) {
  3997. if (auto *CondC = dyn_cast<Constant>(Cond)) {
  3998. if (auto *TrueC = dyn_cast<Constant>(TrueVal))
  3999. if (auto *FalseC = dyn_cast<Constant>(FalseVal))
  4000. return ConstantFoldSelectInstruction(CondC, TrueC, FalseC);
  4001. // select poison, X, Y -> poison
  4002. if (isa<PoisonValue>(CondC))
  4003. return PoisonValue::get(TrueVal->getType());
  4004. // select undef, X, Y -> X or Y
  4005. if (Q.isUndefValue(CondC))
  4006. return isa<Constant>(FalseVal) ? FalseVal : TrueVal;
  4007. // select true, X, Y --> X
  4008. // select false, X, Y --> Y
  4009. // For vectors, allow undef/poison elements in the condition to match the
  4010. // defined elements, so we can eliminate the select.
  4011. if (match(CondC, m_One()))
  4012. return TrueVal;
  4013. if (match(CondC, m_Zero()))
  4014. return FalseVal;
  4015. }
  4016. assert(Cond->getType()->isIntOrIntVectorTy(1) &&
  4017. "Select must have bool or bool vector condition");
  4018. assert(TrueVal->getType() == FalseVal->getType() &&
  4019. "Select must have same types for true/false ops");
  4020. if (Cond->getType() == TrueVal->getType()) {
  4021. // select i1 Cond, i1 true, i1 false --> i1 Cond
  4022. if (match(TrueVal, m_One()) && match(FalseVal, m_ZeroInt()))
  4023. return Cond;
  4024. // (X && Y) ? X : Y --> Y (commuted 2 ways)
  4025. if (match(Cond, m_c_LogicalAnd(m_Specific(TrueVal), m_Specific(FalseVal))))
  4026. return FalseVal;
  4027. // (X || Y) ? X : Y --> X (commuted 2 ways)
  4028. if (match(Cond, m_c_LogicalOr(m_Specific(TrueVal), m_Specific(FalseVal))))
  4029. return TrueVal;
  4030. // (X || Y) ? false : X --> false (commuted 2 ways)
  4031. if (match(Cond, m_c_LogicalOr(m_Specific(FalseVal), m_Value())) &&
  4032. match(TrueVal, m_ZeroInt()))
  4033. return ConstantInt::getFalse(Cond->getType());
  4034. // Match patterns that end in logical-and.
  4035. if (match(FalseVal, m_ZeroInt())) {
  4036. // !(X || Y) && X --> false (commuted 2 ways)
  4037. if (match(Cond, m_Not(m_c_LogicalOr(m_Specific(TrueVal), m_Value()))))
  4038. return ConstantInt::getFalse(Cond->getType());
  4039. // (X || Y) && Y --> Y (commuted 2 ways)
  4040. if (match(Cond, m_c_LogicalOr(m_Specific(TrueVal), m_Value())))
  4041. return TrueVal;
  4042. // Y && (X || Y) --> Y (commuted 2 ways)
  4043. if (match(TrueVal, m_c_LogicalOr(m_Specific(Cond), m_Value())))
  4044. return Cond;
  4045. // (X || Y) && (X || !Y) --> X (commuted 8 ways)
  4046. Value *X, *Y;
  4047. if (match(Cond, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
  4048. match(TrueVal, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
  4049. return X;
  4050. if (match(TrueVal, m_c_LogicalOr(m_Value(X), m_Not(m_Value(Y)))) &&
  4051. match(Cond, m_c_LogicalOr(m_Specific(X), m_Specific(Y))))
  4052. return X;
  4053. }
  4054. // Match patterns that end in logical-or.
  4055. if (match(TrueVal, m_One())) {
  4056. // (X && Y) || Y --> Y (commuted 2 ways)
  4057. if (match(Cond, m_c_LogicalAnd(m_Specific(FalseVal), m_Value())))
  4058. return FalseVal;
  4059. // Y || (X && Y) --> Y (commuted 2 ways)
  4060. if (match(FalseVal, m_c_LogicalAnd(m_Specific(Cond), m_Value())))
  4061. return Cond;
  4062. }
  4063. }
  4064. // select ?, X, X -> X
  4065. if (TrueVal == FalseVal)
  4066. return TrueVal;
  4067. if (Cond == TrueVal) {
  4068. // select i1 X, i1 X, i1 false --> X (logical-and)
  4069. if (match(FalseVal, m_ZeroInt()))
  4070. return Cond;
  4071. // select i1 X, i1 X, i1 true --> true
  4072. if (match(FalseVal, m_One()))
  4073. return ConstantInt::getTrue(Cond->getType());
  4074. }
  4075. if (Cond == FalseVal) {
  4076. // select i1 X, i1 true, i1 X --> X (logical-or)
  4077. if (match(TrueVal, m_One()))
  4078. return Cond;
  4079. // select i1 X, i1 false, i1 X --> false
  4080. if (match(TrueVal, m_ZeroInt()))
  4081. return ConstantInt::getFalse(Cond->getType());
  4082. }
  4083. // If the true or false value is poison, we can fold to the other value.
  4084. // If the true or false value is undef, we can fold to the other value as
  4085. // long as the other value isn't poison.
  4086. // select ?, poison, X -> X
  4087. // select ?, undef, X -> X
  4088. if (isa<PoisonValue>(TrueVal) ||
  4089. (Q.isUndefValue(TrueVal) &&
  4090. isGuaranteedNotToBePoison(FalseVal, Q.AC, Q.CxtI, Q.DT)))
  4091. return FalseVal;
  4092. // select ?, X, poison -> X
  4093. // select ?, X, undef -> X
  4094. if (isa<PoisonValue>(FalseVal) ||
  4095. (Q.isUndefValue(FalseVal) &&
  4096. isGuaranteedNotToBePoison(TrueVal, Q.AC, Q.CxtI, Q.DT)))
  4097. return TrueVal;
  4098. // Deal with partial undef vector constants: select ?, VecC, VecC' --> VecC''
  4099. Constant *TrueC, *FalseC;
  4100. if (isa<FixedVectorType>(TrueVal->getType()) &&
  4101. match(TrueVal, m_Constant(TrueC)) &&
  4102. match(FalseVal, m_Constant(FalseC))) {
  4103. unsigned NumElts =
  4104. cast<FixedVectorType>(TrueC->getType())->getNumElements();
  4105. SmallVector<Constant *, 16> NewC;
  4106. for (unsigned i = 0; i != NumElts; ++i) {
  4107. // Bail out on incomplete vector constants.
  4108. Constant *TEltC = TrueC->getAggregateElement(i);
  4109. Constant *FEltC = FalseC->getAggregateElement(i);
  4110. if (!TEltC || !FEltC)
  4111. break;
  4112. // If the elements match (undef or not), that value is the result. If only
  4113. // one element is undef, choose the defined element as the safe result.
  4114. if (TEltC == FEltC)
  4115. NewC.push_back(TEltC);
  4116. else if (isa<PoisonValue>(TEltC) ||
  4117. (Q.isUndefValue(TEltC) && isGuaranteedNotToBePoison(FEltC)))
  4118. NewC.push_back(FEltC);
  4119. else if (isa<PoisonValue>(FEltC) ||
  4120. (Q.isUndefValue(FEltC) && isGuaranteedNotToBePoison(TEltC)))
  4121. NewC.push_back(TEltC);
  4122. else
  4123. break;
  4124. }
  4125. if (NewC.size() == NumElts)
  4126. return ConstantVector::get(NewC);
  4127. }
  4128. if (Value *V =
  4129. simplifySelectWithICmpCond(Cond, TrueVal, FalseVal, Q, MaxRecurse))
  4130. return V;
  4131. if (Value *V = simplifySelectWithFCmp(Cond, TrueVal, FalseVal, Q))
  4132. return V;
  4133. if (Value *V = foldSelectWithBinaryOp(Cond, TrueVal, FalseVal))
  4134. return V;
  4135. std::optional<bool> Imp = isImpliedByDomCondition(Cond, Q.CxtI, Q.DL);
  4136. if (Imp)
  4137. return *Imp ? TrueVal : FalseVal;
  4138. return nullptr;
  4139. }
  4140. Value *llvm::simplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal,
  4141. const SimplifyQuery &Q) {
  4142. return ::simplifySelectInst(Cond, TrueVal, FalseVal, Q, RecursionLimit);
  4143. }
  4144. /// Given operands for an GetElementPtrInst, see if we can fold the result.
  4145. /// If not, this returns null.
  4146. static Value *simplifyGEPInst(Type *SrcTy, Value *Ptr,
  4147. ArrayRef<Value *> Indices, bool InBounds,
  4148. const SimplifyQuery &Q, unsigned) {
  4149. // The type of the GEP pointer operand.
  4150. unsigned AS =
  4151. cast<PointerType>(Ptr->getType()->getScalarType())->getAddressSpace();
  4152. // getelementptr P -> P.
  4153. if (Indices.empty())
  4154. return Ptr;
  4155. // Compute the (pointer) type returned by the GEP instruction.
  4156. Type *LastType = GetElementPtrInst::getIndexedType(SrcTy, Indices);
  4157. Type *GEPTy = PointerType::get(LastType, AS);
  4158. if (VectorType *VT = dyn_cast<VectorType>(Ptr->getType()))
  4159. GEPTy = VectorType::get(GEPTy, VT->getElementCount());
  4160. else {
  4161. for (Value *Op : Indices) {
  4162. // If one of the operands is a vector, the result type is a vector of
  4163. // pointers. All vector operands must have the same number of elements.
  4164. if (VectorType *VT = dyn_cast<VectorType>(Op->getType())) {
  4165. GEPTy = VectorType::get(GEPTy, VT->getElementCount());
  4166. break;
  4167. }
  4168. }
  4169. }
  4170. // For opaque pointers an all-zero GEP is a no-op. For typed pointers,
  4171. // it may be equivalent to a bitcast.
  4172. if (Ptr->getType()->getScalarType()->isOpaquePointerTy() &&
  4173. Ptr->getType() == GEPTy &&
  4174. all_of(Indices, [](const auto *V) { return match(V, m_Zero()); }))
  4175. return Ptr;
  4176. // getelementptr poison, idx -> poison
  4177. // getelementptr baseptr, poison -> poison
  4178. if (isa<PoisonValue>(Ptr) ||
  4179. any_of(Indices, [](const auto *V) { return isa<PoisonValue>(V); }))
  4180. return PoisonValue::get(GEPTy);
  4181. if (Q.isUndefValue(Ptr))
  4182. // If inbounds, we can choose an out-of-bounds pointer as a base pointer.
  4183. return InBounds ? PoisonValue::get(GEPTy) : UndefValue::get(GEPTy);
  4184. bool IsScalableVec =
  4185. isa<ScalableVectorType>(SrcTy) || any_of(Indices, [](const Value *V) {
  4186. return isa<ScalableVectorType>(V->getType());
  4187. });
  4188. if (Indices.size() == 1) {
  4189. // getelementptr P, 0 -> P.
  4190. if (match(Indices[0], m_Zero()) && Ptr->getType() == GEPTy)
  4191. return Ptr;
  4192. Type *Ty = SrcTy;
  4193. if (!IsScalableVec && Ty->isSized()) {
  4194. Value *P;
  4195. uint64_t C;
  4196. uint64_t TyAllocSize = Q.DL.getTypeAllocSize(Ty);
  4197. // getelementptr P, N -> P if P points to a type of zero size.
  4198. if (TyAllocSize == 0 && Ptr->getType() == GEPTy)
  4199. return Ptr;
  4200. // The following transforms are only safe if the ptrtoint cast
  4201. // doesn't truncate the pointers.
  4202. if (Indices[0]->getType()->getScalarSizeInBits() ==
  4203. Q.DL.getPointerSizeInBits(AS)) {
  4204. auto CanSimplify = [GEPTy, &P, Ptr]() -> bool {
  4205. return P->getType() == GEPTy &&
  4206. getUnderlyingObject(P) == getUnderlyingObject(Ptr);
  4207. };
  4208. // getelementptr V, (sub P, V) -> P if P points to a type of size 1.
  4209. if (TyAllocSize == 1 &&
  4210. match(Indices[0],
  4211. m_Sub(m_PtrToInt(m_Value(P)), m_PtrToInt(m_Specific(Ptr)))) &&
  4212. CanSimplify())
  4213. return P;
  4214. // getelementptr V, (ashr (sub P, V), C) -> P if P points to a type of
  4215. // size 1 << C.
  4216. if (match(Indices[0], m_AShr(m_Sub(m_PtrToInt(m_Value(P)),
  4217. m_PtrToInt(m_Specific(Ptr))),
  4218. m_ConstantInt(C))) &&
  4219. TyAllocSize == 1ULL << C && CanSimplify())
  4220. return P;
  4221. // getelementptr V, (sdiv (sub P, V), C) -> P if P points to a type of
  4222. // size C.
  4223. if (match(Indices[0], m_SDiv(m_Sub(m_PtrToInt(m_Value(P)),
  4224. m_PtrToInt(m_Specific(Ptr))),
  4225. m_SpecificInt(TyAllocSize))) &&
  4226. CanSimplify())
  4227. return P;
  4228. }
  4229. }
  4230. }
  4231. if (!IsScalableVec && Q.DL.getTypeAllocSize(LastType) == 1 &&
  4232. all_of(Indices.drop_back(1),
  4233. [](Value *Idx) { return match(Idx, m_Zero()); })) {
  4234. unsigned IdxWidth =
  4235. Q.DL.getIndexSizeInBits(Ptr->getType()->getPointerAddressSpace());
  4236. if (Q.DL.getTypeSizeInBits(Indices.back()->getType()) == IdxWidth) {
  4237. APInt BasePtrOffset(IdxWidth, 0);
  4238. Value *StrippedBasePtr =
  4239. Ptr->stripAndAccumulateInBoundsConstantOffsets(Q.DL, BasePtrOffset);
  4240. // Avoid creating inttoptr of zero here: While LLVMs treatment of
  4241. // inttoptr is generally conservative, this particular case is folded to
  4242. // a null pointer, which will have incorrect provenance.
  4243. // gep (gep V, C), (sub 0, V) -> C
  4244. if (match(Indices.back(),
  4245. m_Sub(m_Zero(), m_PtrToInt(m_Specific(StrippedBasePtr)))) &&
  4246. !BasePtrOffset.isZero()) {
  4247. auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset);
  4248. return ConstantExpr::getIntToPtr(CI, GEPTy);
  4249. }
  4250. // gep (gep V, C), (xor V, -1) -> C-1
  4251. if (match(Indices.back(),
  4252. m_Xor(m_PtrToInt(m_Specific(StrippedBasePtr)), m_AllOnes())) &&
  4253. !BasePtrOffset.isOne()) {
  4254. auto *CI = ConstantInt::get(GEPTy->getContext(), BasePtrOffset - 1);
  4255. return ConstantExpr::getIntToPtr(CI, GEPTy);
  4256. }
  4257. }
  4258. }
  4259. // Check to see if this is constant foldable.
  4260. if (!isa<Constant>(Ptr) ||
  4261. !all_of(Indices, [](Value *V) { return isa<Constant>(V); }))
  4262. return nullptr;
  4263. auto *CE = ConstantExpr::getGetElementPtr(SrcTy, cast<Constant>(Ptr), Indices,
  4264. InBounds);
  4265. return ConstantFoldConstant(CE, Q.DL);
  4266. }
  4267. Value *llvm::simplifyGEPInst(Type *SrcTy, Value *Ptr, ArrayRef<Value *> Indices,
  4268. bool InBounds, const SimplifyQuery &Q) {
  4269. return ::simplifyGEPInst(SrcTy, Ptr, Indices, InBounds, Q, RecursionLimit);
  4270. }
  4271. /// Given operands for an InsertValueInst, see if we can fold the result.
  4272. /// If not, this returns null.
  4273. static Value *simplifyInsertValueInst(Value *Agg, Value *Val,
  4274. ArrayRef<unsigned> Idxs,
  4275. const SimplifyQuery &Q, unsigned) {
  4276. if (Constant *CAgg = dyn_cast<Constant>(Agg))
  4277. if (Constant *CVal = dyn_cast<Constant>(Val))
  4278. return ConstantFoldInsertValueInstruction(CAgg, CVal, Idxs);
  4279. // insertvalue x, poison, n -> x
  4280. // insertvalue x, undef, n -> x if x cannot be poison
  4281. if (isa<PoisonValue>(Val) ||
  4282. (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Agg)))
  4283. return Agg;
  4284. // insertvalue x, (extractvalue y, n), n
  4285. if (ExtractValueInst *EV = dyn_cast<ExtractValueInst>(Val))
  4286. if (EV->getAggregateOperand()->getType() == Agg->getType() &&
  4287. EV->getIndices() == Idxs) {
  4288. // insertvalue undef, (extractvalue y, n), n -> y
  4289. if (Q.isUndefValue(Agg))
  4290. return EV->getAggregateOperand();
  4291. // insertvalue y, (extractvalue y, n), n -> y
  4292. if (Agg == EV->getAggregateOperand())
  4293. return Agg;
  4294. }
  4295. return nullptr;
  4296. }
  4297. Value *llvm::simplifyInsertValueInst(Value *Agg, Value *Val,
  4298. ArrayRef<unsigned> Idxs,
  4299. const SimplifyQuery &Q) {
  4300. return ::simplifyInsertValueInst(Agg, Val, Idxs, Q, RecursionLimit);
  4301. }
  4302. Value *llvm::simplifyInsertElementInst(Value *Vec, Value *Val, Value *Idx,
  4303. const SimplifyQuery &Q) {
  4304. // Try to constant fold.
  4305. auto *VecC = dyn_cast<Constant>(Vec);
  4306. auto *ValC = dyn_cast<Constant>(Val);
  4307. auto *IdxC = dyn_cast<Constant>(Idx);
  4308. if (VecC && ValC && IdxC)
  4309. return ConstantExpr::getInsertElement(VecC, ValC, IdxC);
  4310. // For fixed-length vector, fold into poison if index is out of bounds.
  4311. if (auto *CI = dyn_cast<ConstantInt>(Idx)) {
  4312. if (isa<FixedVectorType>(Vec->getType()) &&
  4313. CI->uge(cast<FixedVectorType>(Vec->getType())->getNumElements()))
  4314. return PoisonValue::get(Vec->getType());
  4315. }
  4316. // If index is undef, it might be out of bounds (see above case)
  4317. if (Q.isUndefValue(Idx))
  4318. return PoisonValue::get(Vec->getType());
  4319. // If the scalar is poison, or it is undef and there is no risk of
  4320. // propagating poison from the vector value, simplify to the vector value.
  4321. if (isa<PoisonValue>(Val) ||
  4322. (Q.isUndefValue(Val) && isGuaranteedNotToBePoison(Vec)))
  4323. return Vec;
  4324. // If we are extracting a value from a vector, then inserting it into the same
  4325. // place, that's the input vector:
  4326. // insertelt Vec, (extractelt Vec, Idx), Idx --> Vec
  4327. if (match(Val, m_ExtractElt(m_Specific(Vec), m_Specific(Idx))))
  4328. return Vec;
  4329. return nullptr;
  4330. }
  4331. /// Given operands for an ExtractValueInst, see if we can fold the result.
  4332. /// If not, this returns null.
  4333. static Value *simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
  4334. const SimplifyQuery &, unsigned) {
  4335. if (auto *CAgg = dyn_cast<Constant>(Agg))
  4336. return ConstantFoldExtractValueInstruction(CAgg, Idxs);
  4337. // extractvalue x, (insertvalue y, elt, n), n -> elt
  4338. unsigned NumIdxs = Idxs.size();
  4339. for (auto *IVI = dyn_cast<InsertValueInst>(Agg); IVI != nullptr;
  4340. IVI = dyn_cast<InsertValueInst>(IVI->getAggregateOperand())) {
  4341. ArrayRef<unsigned> InsertValueIdxs = IVI->getIndices();
  4342. unsigned NumInsertValueIdxs = InsertValueIdxs.size();
  4343. unsigned NumCommonIdxs = std::min(NumInsertValueIdxs, NumIdxs);
  4344. if (InsertValueIdxs.slice(0, NumCommonIdxs) ==
  4345. Idxs.slice(0, NumCommonIdxs)) {
  4346. if (NumIdxs == NumInsertValueIdxs)
  4347. return IVI->getInsertedValueOperand();
  4348. break;
  4349. }
  4350. }
  4351. return nullptr;
  4352. }
  4353. Value *llvm::simplifyExtractValueInst(Value *Agg, ArrayRef<unsigned> Idxs,
  4354. const SimplifyQuery &Q) {
  4355. return ::simplifyExtractValueInst(Agg, Idxs, Q, RecursionLimit);
  4356. }
  4357. /// Given operands for an ExtractElementInst, see if we can fold the result.
  4358. /// If not, this returns null.
  4359. static Value *simplifyExtractElementInst(Value *Vec, Value *Idx,
  4360. const SimplifyQuery &Q, unsigned) {
  4361. auto *VecVTy = cast<VectorType>(Vec->getType());
  4362. if (auto *CVec = dyn_cast<Constant>(Vec)) {
  4363. if (auto *CIdx = dyn_cast<Constant>(Idx))
  4364. return ConstantExpr::getExtractElement(CVec, CIdx);
  4365. if (Q.isUndefValue(Vec))
  4366. return UndefValue::get(VecVTy->getElementType());
  4367. }
  4368. // An undef extract index can be arbitrarily chosen to be an out-of-range
  4369. // index value, which would result in the instruction being poison.
  4370. if (Q.isUndefValue(Idx))
  4371. return PoisonValue::get(VecVTy->getElementType());
  4372. // If extracting a specified index from the vector, see if we can recursively
  4373. // find a previously computed scalar that was inserted into the vector.
  4374. if (auto *IdxC = dyn_cast<ConstantInt>(Idx)) {
  4375. // For fixed-length vector, fold into undef if index is out of bounds.
  4376. unsigned MinNumElts = VecVTy->getElementCount().getKnownMinValue();
  4377. if (isa<FixedVectorType>(VecVTy) && IdxC->getValue().uge(MinNumElts))
  4378. return PoisonValue::get(VecVTy->getElementType());
  4379. // Handle case where an element is extracted from a splat.
  4380. if (IdxC->getValue().ult(MinNumElts))
  4381. if (auto *Splat = getSplatValue(Vec))
  4382. return Splat;
  4383. if (Value *Elt = findScalarElement(Vec, IdxC->getZExtValue()))
  4384. return Elt;
  4385. } else {
  4386. // extractelt x, (insertelt y, elt, n), n -> elt
  4387. // If the possibly-variable indices are trivially known to be equal
  4388. // (because they are the same operand) then use the value that was
  4389. // inserted directly.
  4390. auto *IE = dyn_cast<InsertElementInst>(Vec);
  4391. if (IE && IE->getOperand(2) == Idx)
  4392. return IE->getOperand(1);
  4393. // The index is not relevant if our vector is a splat.
  4394. if (Value *Splat = getSplatValue(Vec))
  4395. return Splat;
  4396. }
  4397. return nullptr;
  4398. }
  4399. Value *llvm::simplifyExtractElementInst(Value *Vec, Value *Idx,
  4400. const SimplifyQuery &Q) {
  4401. return ::simplifyExtractElementInst(Vec, Idx, Q, RecursionLimit);
  4402. }
  4403. /// See if we can fold the given phi. If not, returns null.
  4404. static Value *simplifyPHINode(PHINode *PN, ArrayRef<Value *> IncomingValues,
  4405. const SimplifyQuery &Q) {
  4406. // WARNING: no matter how worthwhile it may seem, we can not perform PHI CSE
  4407. // here, because the PHI we may succeed simplifying to was not
  4408. // def-reachable from the original PHI!
  4409. // If all of the PHI's incoming values are the same then replace the PHI node
  4410. // with the common value.
  4411. Value *CommonValue = nullptr;
  4412. bool HasUndefInput = false;
  4413. for (Value *Incoming : IncomingValues) {
  4414. // If the incoming value is the phi node itself, it can safely be skipped.
  4415. if (Incoming == PN)
  4416. continue;
  4417. if (Q.isUndefValue(Incoming)) {
  4418. // Remember that we saw an undef value, but otherwise ignore them.
  4419. HasUndefInput = true;
  4420. continue;
  4421. }
  4422. if (CommonValue && Incoming != CommonValue)
  4423. return nullptr; // Not the same, bail out.
  4424. CommonValue = Incoming;
  4425. }
  4426. // If CommonValue is null then all of the incoming values were either undef or
  4427. // equal to the phi node itself.
  4428. if (!CommonValue)
  4429. return UndefValue::get(PN->getType());
  4430. if (HasUndefInput) {
  4431. // If we have a PHI node like phi(X, undef, X), where X is defined by some
  4432. // instruction, we cannot return X as the result of the PHI node unless it
  4433. // dominates the PHI block.
  4434. return valueDominatesPHI(CommonValue, PN, Q.DT) ? CommonValue : nullptr;
  4435. }
  4436. return CommonValue;
  4437. }
  4438. static Value *simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
  4439. const SimplifyQuery &Q, unsigned MaxRecurse) {
  4440. if (auto *C = dyn_cast<Constant>(Op))
  4441. return ConstantFoldCastOperand(CastOpc, C, Ty, Q.DL);
  4442. if (auto *CI = dyn_cast<CastInst>(Op)) {
  4443. auto *Src = CI->getOperand(0);
  4444. Type *SrcTy = Src->getType();
  4445. Type *MidTy = CI->getType();
  4446. Type *DstTy = Ty;
  4447. if (Src->getType() == Ty) {
  4448. auto FirstOp = static_cast<Instruction::CastOps>(CI->getOpcode());
  4449. auto SecondOp = static_cast<Instruction::CastOps>(CastOpc);
  4450. Type *SrcIntPtrTy =
  4451. SrcTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(SrcTy) : nullptr;
  4452. Type *MidIntPtrTy =
  4453. MidTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(MidTy) : nullptr;
  4454. Type *DstIntPtrTy =
  4455. DstTy->isPtrOrPtrVectorTy() ? Q.DL.getIntPtrType(DstTy) : nullptr;
  4456. if (CastInst::isEliminableCastPair(FirstOp, SecondOp, SrcTy, MidTy, DstTy,
  4457. SrcIntPtrTy, MidIntPtrTy,
  4458. DstIntPtrTy) == Instruction::BitCast)
  4459. return Src;
  4460. }
  4461. }
  4462. // bitcast x -> x
  4463. if (CastOpc == Instruction::BitCast)
  4464. if (Op->getType() == Ty)
  4465. return Op;
  4466. return nullptr;
  4467. }
  4468. Value *llvm::simplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty,
  4469. const SimplifyQuery &Q) {
  4470. return ::simplifyCastInst(CastOpc, Op, Ty, Q, RecursionLimit);
  4471. }
  4472. /// For the given destination element of a shuffle, peek through shuffles to
  4473. /// match a root vector source operand that contains that element in the same
  4474. /// vector lane (ie, the same mask index), so we can eliminate the shuffle(s).
  4475. static Value *foldIdentityShuffles(int DestElt, Value *Op0, Value *Op1,
  4476. int MaskVal, Value *RootVec,
  4477. unsigned MaxRecurse) {
  4478. if (!MaxRecurse--)
  4479. return nullptr;
  4480. // Bail out if any mask value is undefined. That kind of shuffle may be
  4481. // simplified further based on demanded bits or other folds.
  4482. if (MaskVal == -1)
  4483. return nullptr;
  4484. // The mask value chooses which source operand we need to look at next.
  4485. int InVecNumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
  4486. int RootElt = MaskVal;
  4487. Value *SourceOp = Op0;
  4488. if (MaskVal >= InVecNumElts) {
  4489. RootElt = MaskVal - InVecNumElts;
  4490. SourceOp = Op1;
  4491. }
  4492. // If the source operand is a shuffle itself, look through it to find the
  4493. // matching root vector.
  4494. if (auto *SourceShuf = dyn_cast<ShuffleVectorInst>(SourceOp)) {
  4495. return foldIdentityShuffles(
  4496. DestElt, SourceShuf->getOperand(0), SourceShuf->getOperand(1),
  4497. SourceShuf->getMaskValue(RootElt), RootVec, MaxRecurse);
  4498. }
  4499. // TODO: Look through bitcasts? What if the bitcast changes the vector element
  4500. // size?
  4501. // The source operand is not a shuffle. Initialize the root vector value for
  4502. // this shuffle if that has not been done yet.
  4503. if (!RootVec)
  4504. RootVec = SourceOp;
  4505. // Give up as soon as a source operand does not match the existing root value.
  4506. if (RootVec != SourceOp)
  4507. return nullptr;
  4508. // The element must be coming from the same lane in the source vector
  4509. // (although it may have crossed lanes in intermediate shuffles).
  4510. if (RootElt != DestElt)
  4511. return nullptr;
  4512. return RootVec;
  4513. }
  4514. static Value *simplifyShuffleVectorInst(Value *Op0, Value *Op1,
  4515. ArrayRef<int> Mask, Type *RetTy,
  4516. const SimplifyQuery &Q,
  4517. unsigned MaxRecurse) {
  4518. if (all_of(Mask, [](int Elem) { return Elem == UndefMaskElem; }))
  4519. return UndefValue::get(RetTy);
  4520. auto *InVecTy = cast<VectorType>(Op0->getType());
  4521. unsigned MaskNumElts = Mask.size();
  4522. ElementCount InVecEltCount = InVecTy->getElementCount();
  4523. bool Scalable = InVecEltCount.isScalable();
  4524. SmallVector<int, 32> Indices;
  4525. Indices.assign(Mask.begin(), Mask.end());
  4526. // Canonicalization: If mask does not select elements from an input vector,
  4527. // replace that input vector with poison.
  4528. if (!Scalable) {
  4529. bool MaskSelects0 = false, MaskSelects1 = false;
  4530. unsigned InVecNumElts = InVecEltCount.getKnownMinValue();
  4531. for (unsigned i = 0; i != MaskNumElts; ++i) {
  4532. if (Indices[i] == -1)
  4533. continue;
  4534. if ((unsigned)Indices[i] < InVecNumElts)
  4535. MaskSelects0 = true;
  4536. else
  4537. MaskSelects1 = true;
  4538. }
  4539. if (!MaskSelects0)
  4540. Op0 = PoisonValue::get(InVecTy);
  4541. if (!MaskSelects1)
  4542. Op1 = PoisonValue::get(InVecTy);
  4543. }
  4544. auto *Op0Const = dyn_cast<Constant>(Op0);
  4545. auto *Op1Const = dyn_cast<Constant>(Op1);
  4546. // If all operands are constant, constant fold the shuffle. This
  4547. // transformation depends on the value of the mask which is not known at
  4548. // compile time for scalable vectors
  4549. if (Op0Const && Op1Const)
  4550. return ConstantExpr::getShuffleVector(Op0Const, Op1Const, Mask);
  4551. // Canonicalization: if only one input vector is constant, it shall be the
  4552. // second one. This transformation depends on the value of the mask which
  4553. // is not known at compile time for scalable vectors
  4554. if (!Scalable && Op0Const && !Op1Const) {
  4555. std::swap(Op0, Op1);
  4556. ShuffleVectorInst::commuteShuffleMask(Indices,
  4557. InVecEltCount.getKnownMinValue());
  4558. }
  4559. // A splat of an inserted scalar constant becomes a vector constant:
  4560. // shuf (inselt ?, C, IndexC), undef, <IndexC, IndexC...> --> <C, C...>
  4561. // NOTE: We may have commuted above, so analyze the updated Indices, not the
  4562. // original mask constant.
  4563. // NOTE: This transformation depends on the value of the mask which is not
  4564. // known at compile time for scalable vectors
  4565. Constant *C;
  4566. ConstantInt *IndexC;
  4567. if (!Scalable && match(Op0, m_InsertElt(m_Value(), m_Constant(C),
  4568. m_ConstantInt(IndexC)))) {
  4569. // Match a splat shuffle mask of the insert index allowing undef elements.
  4570. int InsertIndex = IndexC->getZExtValue();
  4571. if (all_of(Indices, [InsertIndex](int MaskElt) {
  4572. return MaskElt == InsertIndex || MaskElt == -1;
  4573. })) {
  4574. assert(isa<UndefValue>(Op1) && "Expected undef operand 1 for splat");
  4575. // Shuffle mask undefs become undefined constant result elements.
  4576. SmallVector<Constant *, 16> VecC(MaskNumElts, C);
  4577. for (unsigned i = 0; i != MaskNumElts; ++i)
  4578. if (Indices[i] == -1)
  4579. VecC[i] = UndefValue::get(C->getType());
  4580. return ConstantVector::get(VecC);
  4581. }
  4582. }
  4583. // A shuffle of a splat is always the splat itself. Legal if the shuffle's
  4584. // value type is same as the input vectors' type.
  4585. if (auto *OpShuf = dyn_cast<ShuffleVectorInst>(Op0))
  4586. if (Q.isUndefValue(Op1) && RetTy == InVecTy &&
  4587. all_equal(OpShuf->getShuffleMask()))
  4588. return Op0;
  4589. // All remaining transformation depend on the value of the mask, which is
  4590. // not known at compile time for scalable vectors.
  4591. if (Scalable)
  4592. return nullptr;
  4593. // Don't fold a shuffle with undef mask elements. This may get folded in a
  4594. // better way using demanded bits or other analysis.
  4595. // TODO: Should we allow this?
  4596. if (is_contained(Indices, -1))
  4597. return nullptr;
  4598. // Check if every element of this shuffle can be mapped back to the
  4599. // corresponding element of a single root vector. If so, we don't need this
  4600. // shuffle. This handles simple identity shuffles as well as chains of
  4601. // shuffles that may widen/narrow and/or move elements across lanes and back.
  4602. Value *RootVec = nullptr;
  4603. for (unsigned i = 0; i != MaskNumElts; ++i) {
  4604. // Note that recursion is limited for each vector element, so if any element
  4605. // exceeds the limit, this will fail to simplify.
  4606. RootVec =
  4607. foldIdentityShuffles(i, Op0, Op1, Indices[i], RootVec, MaxRecurse);
  4608. // We can't replace a widening/narrowing shuffle with one of its operands.
  4609. if (!RootVec || RootVec->getType() != RetTy)
  4610. return nullptr;
  4611. }
  4612. return RootVec;
  4613. }
  4614. /// Given operands for a ShuffleVectorInst, fold the result or return null.
  4615. Value *llvm::simplifyShuffleVectorInst(Value *Op0, Value *Op1,
  4616. ArrayRef<int> Mask, Type *RetTy,
  4617. const SimplifyQuery &Q) {
  4618. return ::simplifyShuffleVectorInst(Op0, Op1, Mask, RetTy, Q, RecursionLimit);
  4619. }
  4620. static Constant *foldConstant(Instruction::UnaryOps Opcode, Value *&Op,
  4621. const SimplifyQuery &Q) {
  4622. if (auto *C = dyn_cast<Constant>(Op))
  4623. return ConstantFoldUnaryOpOperand(Opcode, C, Q.DL);
  4624. return nullptr;
  4625. }
  4626. /// Given the operand for an FNeg, see if we can fold the result. If not, this
  4627. /// returns null.
  4628. static Value *simplifyFNegInst(Value *Op, FastMathFlags FMF,
  4629. const SimplifyQuery &Q, unsigned MaxRecurse) {
  4630. if (Constant *C = foldConstant(Instruction::FNeg, Op, Q))
  4631. return C;
  4632. Value *X;
  4633. // fneg (fneg X) ==> X
  4634. if (match(Op, m_FNeg(m_Value(X))))
  4635. return X;
  4636. return nullptr;
  4637. }
  4638. Value *llvm::simplifyFNegInst(Value *Op, FastMathFlags FMF,
  4639. const SimplifyQuery &Q) {
  4640. return ::simplifyFNegInst(Op, FMF, Q, RecursionLimit);
  4641. }
  4642. /// Try to propagate existing NaN values when possible. If not, replace the
  4643. /// constant or elements in the constant with a canonical NaN.
  4644. static Constant *propagateNaN(Constant *In) {
  4645. if (auto *VecTy = dyn_cast<FixedVectorType>(In->getType())) {
  4646. unsigned NumElts = VecTy->getNumElements();
  4647. SmallVector<Constant *, 32> NewC(NumElts);
  4648. for (unsigned i = 0; i != NumElts; ++i) {
  4649. Constant *EltC = In->getAggregateElement(i);
  4650. // Poison and existing NaN elements propagate.
  4651. // Replace unknown or undef elements with canonical NaN.
  4652. if (EltC && (isa<PoisonValue>(EltC) || EltC->isNaN()))
  4653. NewC[i] = EltC;
  4654. else
  4655. NewC[i] = (ConstantFP::getNaN(VecTy->getElementType()));
  4656. }
  4657. return ConstantVector::get(NewC);
  4658. }
  4659. // It is not a fixed vector, but not a simple NaN either?
  4660. if (!In->isNaN())
  4661. return ConstantFP::getNaN(In->getType());
  4662. // Propagate the existing NaN constant when possible.
  4663. // TODO: Should we quiet a signaling NaN?
  4664. return In;
  4665. }
  4666. /// Perform folds that are common to any floating-point operation. This implies
  4667. /// transforms based on poison/undef/NaN because the operation itself makes no
  4668. /// difference to the result.
  4669. static Constant *simplifyFPOp(ArrayRef<Value *> Ops, FastMathFlags FMF,
  4670. const SimplifyQuery &Q,
  4671. fp::ExceptionBehavior ExBehavior,
  4672. RoundingMode Rounding) {
  4673. // Poison is independent of anything else. It always propagates from an
  4674. // operand to a math result.
  4675. if (any_of(Ops, [](Value *V) { return match(V, m_Poison()); }))
  4676. return PoisonValue::get(Ops[0]->getType());
  4677. for (Value *V : Ops) {
  4678. bool IsNan = match(V, m_NaN());
  4679. bool IsInf = match(V, m_Inf());
  4680. bool IsUndef = Q.isUndefValue(V);
  4681. // If this operation has 'nnan' or 'ninf' and at least 1 disallowed operand
  4682. // (an undef operand can be chosen to be Nan/Inf), then the result of
  4683. // this operation is poison.
  4684. if (FMF.noNaNs() && (IsNan || IsUndef))
  4685. return PoisonValue::get(V->getType());
  4686. if (FMF.noInfs() && (IsInf || IsUndef))
  4687. return PoisonValue::get(V->getType());
  4688. if (isDefaultFPEnvironment(ExBehavior, Rounding)) {
  4689. // Undef does not propagate because undef means that all bits can take on
  4690. // any value. If this is undef * NaN for example, then the result values
  4691. // (at least the exponent bits) are limited. Assume the undef is a
  4692. // canonical NaN and propagate that.
  4693. if (IsUndef)
  4694. return ConstantFP::getNaN(V->getType());
  4695. if (IsNan)
  4696. return propagateNaN(cast<Constant>(V));
  4697. } else if (ExBehavior != fp::ebStrict) {
  4698. if (IsNan)
  4699. return propagateNaN(cast<Constant>(V));
  4700. }
  4701. }
  4702. return nullptr;
  4703. }
  4704. /// Given operands for an FAdd, see if we can fold the result. If not, this
  4705. /// returns null.
  4706. static Value *
  4707. simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  4708. const SimplifyQuery &Q, unsigned MaxRecurse,
  4709. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  4710. RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
  4711. if (isDefaultFPEnvironment(ExBehavior, Rounding))
  4712. if (Constant *C = foldOrCommuteConstant(Instruction::FAdd, Op0, Op1, Q))
  4713. return C;
  4714. if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
  4715. return C;
  4716. // fadd X, -0 ==> X
  4717. // With strict/constrained FP, we have these possible edge cases that do
  4718. // not simplify to Op0:
  4719. // fadd SNaN, -0.0 --> QNaN
  4720. // fadd +0.0, -0.0 --> -0.0 (but only with round toward negative)
  4721. if (canIgnoreSNaN(ExBehavior, FMF) &&
  4722. (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
  4723. FMF.noSignedZeros()))
  4724. if (match(Op1, m_NegZeroFP()))
  4725. return Op0;
  4726. // fadd X, 0 ==> X, when we know X is not -0
  4727. if (canIgnoreSNaN(ExBehavior, FMF))
  4728. if (match(Op1, m_PosZeroFP()) &&
  4729. (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
  4730. return Op0;
  4731. if (!isDefaultFPEnvironment(ExBehavior, Rounding))
  4732. return nullptr;
  4733. if (FMF.noNaNs()) {
  4734. // With nnan: X + {+/-}Inf --> {+/-}Inf
  4735. if (match(Op1, m_Inf()))
  4736. return Op1;
  4737. // With nnan: -X + X --> 0.0 (and commuted variant)
  4738. // We don't have to explicitly exclude infinities (ninf): INF + -INF == NaN.
  4739. // Negative zeros are allowed because we always end up with positive zero:
  4740. // X = -0.0: (-0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
  4741. // X = -0.0: ( 0.0 - (-0.0)) + (-0.0) == ( 0.0) + (-0.0) == 0.0
  4742. // X = 0.0: (-0.0 - ( 0.0)) + ( 0.0) == (-0.0) + ( 0.0) == 0.0
  4743. // X = 0.0: ( 0.0 - ( 0.0)) + ( 0.0) == ( 0.0) + ( 0.0) == 0.0
  4744. if (match(Op0, m_FSub(m_AnyZeroFP(), m_Specific(Op1))) ||
  4745. match(Op1, m_FSub(m_AnyZeroFP(), m_Specific(Op0))))
  4746. return ConstantFP::getNullValue(Op0->getType());
  4747. if (match(Op0, m_FNeg(m_Specific(Op1))) ||
  4748. match(Op1, m_FNeg(m_Specific(Op0))))
  4749. return ConstantFP::getNullValue(Op0->getType());
  4750. }
  4751. // (X - Y) + Y --> X
  4752. // Y + (X - Y) --> X
  4753. Value *X;
  4754. if (FMF.noSignedZeros() && FMF.allowReassoc() &&
  4755. (match(Op0, m_FSub(m_Value(X), m_Specific(Op1))) ||
  4756. match(Op1, m_FSub(m_Value(X), m_Specific(Op0)))))
  4757. return X;
  4758. return nullptr;
  4759. }
  4760. /// Given operands for an FSub, see if we can fold the result. If not, this
  4761. /// returns null.
  4762. static Value *
  4763. simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  4764. const SimplifyQuery &Q, unsigned MaxRecurse,
  4765. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  4766. RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
  4767. if (isDefaultFPEnvironment(ExBehavior, Rounding))
  4768. if (Constant *C = foldOrCommuteConstant(Instruction::FSub, Op0, Op1, Q))
  4769. return C;
  4770. if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
  4771. return C;
  4772. // fsub X, +0 ==> X
  4773. if (canIgnoreSNaN(ExBehavior, FMF) &&
  4774. (!canRoundingModeBe(Rounding, RoundingMode::TowardNegative) ||
  4775. FMF.noSignedZeros()))
  4776. if (match(Op1, m_PosZeroFP()))
  4777. return Op0;
  4778. // fsub X, -0 ==> X, when we know X is not -0
  4779. if (canIgnoreSNaN(ExBehavior, FMF))
  4780. if (match(Op1, m_NegZeroFP()) &&
  4781. (FMF.noSignedZeros() || CannotBeNegativeZero(Op0, Q.TLI)))
  4782. return Op0;
  4783. // fsub -0.0, (fsub -0.0, X) ==> X
  4784. // fsub -0.0, (fneg X) ==> X
  4785. Value *X;
  4786. if (canIgnoreSNaN(ExBehavior, FMF))
  4787. if (match(Op0, m_NegZeroFP()) && match(Op1, m_FNeg(m_Value(X))))
  4788. return X;
  4789. // fsub 0.0, (fsub 0.0, X) ==> X if signed zeros are ignored.
  4790. // fsub 0.0, (fneg X) ==> X if signed zeros are ignored.
  4791. if (canIgnoreSNaN(ExBehavior, FMF))
  4792. if (FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()) &&
  4793. (match(Op1, m_FSub(m_AnyZeroFP(), m_Value(X))) ||
  4794. match(Op1, m_FNeg(m_Value(X)))))
  4795. return X;
  4796. if (!isDefaultFPEnvironment(ExBehavior, Rounding))
  4797. return nullptr;
  4798. if (FMF.noNaNs()) {
  4799. // fsub nnan x, x ==> 0.0
  4800. if (Op0 == Op1)
  4801. return Constant::getNullValue(Op0->getType());
  4802. // With nnan: {+/-}Inf - X --> {+/-}Inf
  4803. if (match(Op0, m_Inf()))
  4804. return Op0;
  4805. // With nnan: X - {+/-}Inf --> {-/+}Inf
  4806. if (match(Op1, m_Inf()))
  4807. return foldConstant(Instruction::FNeg, Op1, Q);
  4808. }
  4809. // Y - (Y - X) --> X
  4810. // (X + Y) - Y --> X
  4811. if (FMF.noSignedZeros() && FMF.allowReassoc() &&
  4812. (match(Op1, m_FSub(m_Specific(Op0), m_Value(X))) ||
  4813. match(Op0, m_c_FAdd(m_Specific(Op1), m_Value(X)))))
  4814. return X;
  4815. return nullptr;
  4816. }
  4817. static Value *simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
  4818. const SimplifyQuery &Q, unsigned MaxRecurse,
  4819. fp::ExceptionBehavior ExBehavior,
  4820. RoundingMode Rounding) {
  4821. if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
  4822. return C;
  4823. if (!isDefaultFPEnvironment(ExBehavior, Rounding))
  4824. return nullptr;
  4825. // Canonicalize special constants as operand 1.
  4826. if (match(Op0, m_FPOne()) || match(Op0, m_AnyZeroFP()))
  4827. std::swap(Op0, Op1);
  4828. // X * 1.0 --> X
  4829. if (match(Op1, m_FPOne()))
  4830. return Op0;
  4831. if (match(Op1, m_AnyZeroFP())) {
  4832. // X * 0.0 --> 0.0 (with nnan and nsz)
  4833. if (FMF.noNaNs() && FMF.noSignedZeros())
  4834. return ConstantFP::getNullValue(Op0->getType());
  4835. // +normal number * (-)0.0 --> (-)0.0
  4836. if (isKnownNeverInfinity(Op0, Q.TLI) && isKnownNeverNaN(Op0, Q.TLI) &&
  4837. SignBitMustBeZero(Op0, Q.TLI))
  4838. return Op1;
  4839. }
  4840. // sqrt(X) * sqrt(X) --> X, if we can:
  4841. // 1. Remove the intermediate rounding (reassociate).
  4842. // 2. Ignore non-zero negative numbers because sqrt would produce NAN.
  4843. // 3. Ignore -0.0 because sqrt(-0.0) == -0.0, but -0.0 * -0.0 == 0.0.
  4844. Value *X;
  4845. if (Op0 == Op1 && match(Op0, m_Sqrt(m_Value(X))) && FMF.allowReassoc() &&
  4846. FMF.noNaNs() && FMF.noSignedZeros())
  4847. return X;
  4848. return nullptr;
  4849. }
  4850. /// Given the operands for an FMul, see if we can fold the result
  4851. static Value *
  4852. simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  4853. const SimplifyQuery &Q, unsigned MaxRecurse,
  4854. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  4855. RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
  4856. if (isDefaultFPEnvironment(ExBehavior, Rounding))
  4857. if (Constant *C = foldOrCommuteConstant(Instruction::FMul, Op0, Op1, Q))
  4858. return C;
  4859. // Now apply simplifications that do not require rounding.
  4860. return simplifyFMAFMul(Op0, Op1, FMF, Q, MaxRecurse, ExBehavior, Rounding);
  4861. }
  4862. Value *llvm::simplifyFAddInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  4863. const SimplifyQuery &Q,
  4864. fp::ExceptionBehavior ExBehavior,
  4865. RoundingMode Rounding) {
  4866. return ::simplifyFAddInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
  4867. Rounding);
  4868. }
  4869. Value *llvm::simplifyFSubInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  4870. const SimplifyQuery &Q,
  4871. fp::ExceptionBehavior ExBehavior,
  4872. RoundingMode Rounding) {
  4873. return ::simplifyFSubInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
  4874. Rounding);
  4875. }
  4876. Value *llvm::simplifyFMulInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  4877. const SimplifyQuery &Q,
  4878. fp::ExceptionBehavior ExBehavior,
  4879. RoundingMode Rounding) {
  4880. return ::simplifyFMulInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
  4881. Rounding);
  4882. }
  4883. Value *llvm::simplifyFMAFMul(Value *Op0, Value *Op1, FastMathFlags FMF,
  4884. const SimplifyQuery &Q,
  4885. fp::ExceptionBehavior ExBehavior,
  4886. RoundingMode Rounding) {
  4887. return ::simplifyFMAFMul(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
  4888. Rounding);
  4889. }
  4890. static Value *
  4891. simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  4892. const SimplifyQuery &Q, unsigned,
  4893. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  4894. RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
  4895. if (isDefaultFPEnvironment(ExBehavior, Rounding))
  4896. if (Constant *C = foldOrCommuteConstant(Instruction::FDiv, Op0, Op1, Q))
  4897. return C;
  4898. if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
  4899. return C;
  4900. if (!isDefaultFPEnvironment(ExBehavior, Rounding))
  4901. return nullptr;
  4902. // X / 1.0 -> X
  4903. if (match(Op1, m_FPOne()))
  4904. return Op0;
  4905. // 0 / X -> 0
  4906. // Requires that NaNs are off (X could be zero) and signed zeroes are
  4907. // ignored (X could be positive or negative, so the output sign is unknown).
  4908. if (FMF.noNaNs() && FMF.noSignedZeros() && match(Op0, m_AnyZeroFP()))
  4909. return ConstantFP::getNullValue(Op0->getType());
  4910. if (FMF.noNaNs()) {
  4911. // X / X -> 1.0 is legal when NaNs are ignored.
  4912. // We can ignore infinities because INF/INF is NaN.
  4913. if (Op0 == Op1)
  4914. return ConstantFP::get(Op0->getType(), 1.0);
  4915. // (X * Y) / Y --> X if we can reassociate to the above form.
  4916. Value *X;
  4917. if (FMF.allowReassoc() && match(Op0, m_c_FMul(m_Value(X), m_Specific(Op1))))
  4918. return X;
  4919. // -X / X -> -1.0 and
  4920. // X / -X -> -1.0 are legal when NaNs are ignored.
  4921. // We can ignore signed zeros because +-0.0/+-0.0 is NaN and ignored.
  4922. if (match(Op0, m_FNegNSZ(m_Specific(Op1))) ||
  4923. match(Op1, m_FNegNSZ(m_Specific(Op0))))
  4924. return ConstantFP::get(Op0->getType(), -1.0);
  4925. // nnan ninf X / [-]0.0 -> poison
  4926. if (FMF.noInfs() && match(Op1, m_AnyZeroFP()))
  4927. return PoisonValue::get(Op1->getType());
  4928. }
  4929. return nullptr;
  4930. }
  4931. Value *llvm::simplifyFDivInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  4932. const SimplifyQuery &Q,
  4933. fp::ExceptionBehavior ExBehavior,
  4934. RoundingMode Rounding) {
  4935. return ::simplifyFDivInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
  4936. Rounding);
  4937. }
  4938. static Value *
  4939. simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  4940. const SimplifyQuery &Q, unsigned,
  4941. fp::ExceptionBehavior ExBehavior = fp::ebIgnore,
  4942. RoundingMode Rounding = RoundingMode::NearestTiesToEven) {
  4943. if (isDefaultFPEnvironment(ExBehavior, Rounding))
  4944. if (Constant *C = foldOrCommuteConstant(Instruction::FRem, Op0, Op1, Q))
  4945. return C;
  4946. if (Constant *C = simplifyFPOp({Op0, Op1}, FMF, Q, ExBehavior, Rounding))
  4947. return C;
  4948. if (!isDefaultFPEnvironment(ExBehavior, Rounding))
  4949. return nullptr;
  4950. // Unlike fdiv, the result of frem always matches the sign of the dividend.
  4951. // The constant match may include undef elements in a vector, so return a full
  4952. // zero constant as the result.
  4953. if (FMF.noNaNs()) {
  4954. // +0 % X -> 0
  4955. if (match(Op0, m_PosZeroFP()))
  4956. return ConstantFP::getNullValue(Op0->getType());
  4957. // -0 % X -> -0
  4958. if (match(Op0, m_NegZeroFP()))
  4959. return ConstantFP::getNegativeZero(Op0->getType());
  4960. }
  4961. return nullptr;
  4962. }
  4963. Value *llvm::simplifyFRemInst(Value *Op0, Value *Op1, FastMathFlags FMF,
  4964. const SimplifyQuery &Q,
  4965. fp::ExceptionBehavior ExBehavior,
  4966. RoundingMode Rounding) {
  4967. return ::simplifyFRemInst(Op0, Op1, FMF, Q, RecursionLimit, ExBehavior,
  4968. Rounding);
  4969. }
  4970. //=== Helper functions for higher up the class hierarchy.
  4971. /// Given the operand for a UnaryOperator, see if we can fold the result.
  4972. /// If not, this returns null.
  4973. static Value *simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q,
  4974. unsigned MaxRecurse) {
  4975. switch (Opcode) {
  4976. case Instruction::FNeg:
  4977. return simplifyFNegInst(Op, FastMathFlags(), Q, MaxRecurse);
  4978. default:
  4979. llvm_unreachable("Unexpected opcode");
  4980. }
  4981. }
  4982. /// Given the operand for a UnaryOperator, see if we can fold the result.
  4983. /// If not, this returns null.
  4984. /// Try to use FastMathFlags when folding the result.
  4985. static Value *simplifyFPUnOp(unsigned Opcode, Value *Op,
  4986. const FastMathFlags &FMF, const SimplifyQuery &Q,
  4987. unsigned MaxRecurse) {
  4988. switch (Opcode) {
  4989. case Instruction::FNeg:
  4990. return simplifyFNegInst(Op, FMF, Q, MaxRecurse);
  4991. default:
  4992. return simplifyUnOp(Opcode, Op, Q, MaxRecurse);
  4993. }
  4994. }
  4995. Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, const SimplifyQuery &Q) {
  4996. return ::simplifyUnOp(Opcode, Op, Q, RecursionLimit);
  4997. }
  4998. Value *llvm::simplifyUnOp(unsigned Opcode, Value *Op, FastMathFlags FMF,
  4999. const SimplifyQuery &Q) {
  5000. return ::simplifyFPUnOp(Opcode, Op, FMF, Q, RecursionLimit);
  5001. }
  5002. /// Given operands for a BinaryOperator, see if we can fold the result.
  5003. /// If not, this returns null.
  5004. static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
  5005. const SimplifyQuery &Q, unsigned MaxRecurse) {
  5006. switch (Opcode) {
  5007. case Instruction::Add:
  5008. return simplifyAddInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
  5009. MaxRecurse);
  5010. case Instruction::Sub:
  5011. return simplifySubInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
  5012. MaxRecurse);
  5013. case Instruction::Mul:
  5014. return simplifyMulInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
  5015. MaxRecurse);
  5016. case Instruction::SDiv:
  5017. return simplifySDivInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
  5018. case Instruction::UDiv:
  5019. return simplifyUDivInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
  5020. case Instruction::SRem:
  5021. return simplifySRemInst(LHS, RHS, Q, MaxRecurse);
  5022. case Instruction::URem:
  5023. return simplifyURemInst(LHS, RHS, Q, MaxRecurse);
  5024. case Instruction::Shl:
  5025. return simplifyShlInst(LHS, RHS, /* IsNSW */ false, /* IsNUW */ false, Q,
  5026. MaxRecurse);
  5027. case Instruction::LShr:
  5028. return simplifyLShrInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
  5029. case Instruction::AShr:
  5030. return simplifyAShrInst(LHS, RHS, /* IsExact */ false, Q, MaxRecurse);
  5031. case Instruction::And:
  5032. return simplifyAndInst(LHS, RHS, Q, MaxRecurse);
  5033. case Instruction::Or:
  5034. return simplifyOrInst(LHS, RHS, Q, MaxRecurse);
  5035. case Instruction::Xor:
  5036. return simplifyXorInst(LHS, RHS, Q, MaxRecurse);
  5037. case Instruction::FAdd:
  5038. return simplifyFAddInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
  5039. case Instruction::FSub:
  5040. return simplifyFSubInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
  5041. case Instruction::FMul:
  5042. return simplifyFMulInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
  5043. case Instruction::FDiv:
  5044. return simplifyFDivInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
  5045. case Instruction::FRem:
  5046. return simplifyFRemInst(LHS, RHS, FastMathFlags(), Q, MaxRecurse);
  5047. default:
  5048. llvm_unreachable("Unexpected opcode");
  5049. }
  5050. }
  5051. /// Given operands for a BinaryOperator, see if we can fold the result.
  5052. /// If not, this returns null.
  5053. /// Try to use FastMathFlags when folding the result.
  5054. static Value *simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
  5055. const FastMathFlags &FMF, const SimplifyQuery &Q,
  5056. unsigned MaxRecurse) {
  5057. switch (Opcode) {
  5058. case Instruction::FAdd:
  5059. return simplifyFAddInst(LHS, RHS, FMF, Q, MaxRecurse);
  5060. case Instruction::FSub:
  5061. return simplifyFSubInst(LHS, RHS, FMF, Q, MaxRecurse);
  5062. case Instruction::FMul:
  5063. return simplifyFMulInst(LHS, RHS, FMF, Q, MaxRecurse);
  5064. case Instruction::FDiv:
  5065. return simplifyFDivInst(LHS, RHS, FMF, Q, MaxRecurse);
  5066. default:
  5067. return simplifyBinOp(Opcode, LHS, RHS, Q, MaxRecurse);
  5068. }
  5069. }
  5070. Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
  5071. const SimplifyQuery &Q) {
  5072. return ::simplifyBinOp(Opcode, LHS, RHS, Q, RecursionLimit);
  5073. }
  5074. Value *llvm::simplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS,
  5075. FastMathFlags FMF, const SimplifyQuery &Q) {
  5076. return ::simplifyBinOp(Opcode, LHS, RHS, FMF, Q, RecursionLimit);
  5077. }
  5078. /// Given operands for a CmpInst, see if we can fold the result.
  5079. static Value *simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  5080. const SimplifyQuery &Q, unsigned MaxRecurse) {
  5081. if (CmpInst::isIntPredicate((CmpInst::Predicate)Predicate))
  5082. return simplifyICmpInst(Predicate, LHS, RHS, Q, MaxRecurse);
  5083. return simplifyFCmpInst(Predicate, LHS, RHS, FastMathFlags(), Q, MaxRecurse);
  5084. }
  5085. Value *llvm::simplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS,
  5086. const SimplifyQuery &Q) {
  5087. return ::simplifyCmpInst(Predicate, LHS, RHS, Q, RecursionLimit);
  5088. }
  5089. static bool isIdempotent(Intrinsic::ID ID) {
  5090. switch (ID) {
  5091. default:
  5092. return false;
  5093. // Unary idempotent: f(f(x)) = f(x)
  5094. case Intrinsic::fabs:
  5095. case Intrinsic::floor:
  5096. case Intrinsic::ceil:
  5097. case Intrinsic::trunc:
  5098. case Intrinsic::rint:
  5099. case Intrinsic::nearbyint:
  5100. case Intrinsic::round:
  5101. case Intrinsic::roundeven:
  5102. case Intrinsic::canonicalize:
  5103. case Intrinsic::arithmetic_fence:
  5104. return true;
  5105. }
  5106. }
  5107. /// Return true if the intrinsic rounds a floating-point value to an integral
  5108. /// floating-point value (not an integer type).
  5109. static bool removesFPFraction(Intrinsic::ID ID) {
  5110. switch (ID) {
  5111. default:
  5112. return false;
  5113. case Intrinsic::floor:
  5114. case Intrinsic::ceil:
  5115. case Intrinsic::trunc:
  5116. case Intrinsic::rint:
  5117. case Intrinsic::nearbyint:
  5118. case Intrinsic::round:
  5119. case Intrinsic::roundeven:
  5120. return true;
  5121. }
  5122. }
  5123. static Value *simplifyRelativeLoad(Constant *Ptr, Constant *Offset,
  5124. const DataLayout &DL) {
  5125. GlobalValue *PtrSym;
  5126. APInt PtrOffset;
  5127. if (!IsConstantOffsetFromGlobal(Ptr, PtrSym, PtrOffset, DL))
  5128. return nullptr;
  5129. Type *Int8PtrTy = Type::getInt8PtrTy(Ptr->getContext());
  5130. Type *Int32Ty = Type::getInt32Ty(Ptr->getContext());
  5131. Type *Int32PtrTy = Int32Ty->getPointerTo();
  5132. Type *Int64Ty = Type::getInt64Ty(Ptr->getContext());
  5133. auto *OffsetConstInt = dyn_cast<ConstantInt>(Offset);
  5134. if (!OffsetConstInt || OffsetConstInt->getType()->getBitWidth() > 64)
  5135. return nullptr;
  5136. uint64_t OffsetInt = OffsetConstInt->getSExtValue();
  5137. if (OffsetInt % 4 != 0)
  5138. return nullptr;
  5139. Constant *C = ConstantExpr::getGetElementPtr(
  5140. Int32Ty, ConstantExpr::getBitCast(Ptr, Int32PtrTy),
  5141. ConstantInt::get(Int64Ty, OffsetInt / 4));
  5142. Constant *Loaded = ConstantFoldLoadFromConstPtr(C, Int32Ty, DL);
  5143. if (!Loaded)
  5144. return nullptr;
  5145. auto *LoadedCE = dyn_cast<ConstantExpr>(Loaded);
  5146. if (!LoadedCE)
  5147. return nullptr;
  5148. if (LoadedCE->getOpcode() == Instruction::Trunc) {
  5149. LoadedCE = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
  5150. if (!LoadedCE)
  5151. return nullptr;
  5152. }
  5153. if (LoadedCE->getOpcode() != Instruction::Sub)
  5154. return nullptr;
  5155. auto *LoadedLHS = dyn_cast<ConstantExpr>(LoadedCE->getOperand(0));
  5156. if (!LoadedLHS || LoadedLHS->getOpcode() != Instruction::PtrToInt)
  5157. return nullptr;
  5158. auto *LoadedLHSPtr = LoadedLHS->getOperand(0);
  5159. Constant *LoadedRHS = LoadedCE->getOperand(1);
  5160. GlobalValue *LoadedRHSSym;
  5161. APInt LoadedRHSOffset;
  5162. if (!IsConstantOffsetFromGlobal(LoadedRHS, LoadedRHSSym, LoadedRHSOffset,
  5163. DL) ||
  5164. PtrSym != LoadedRHSSym || PtrOffset != LoadedRHSOffset)
  5165. return nullptr;
  5166. return ConstantExpr::getBitCast(LoadedLHSPtr, Int8PtrTy);
  5167. }
  5168. static Value *simplifyUnaryIntrinsic(Function *F, Value *Op0,
  5169. const SimplifyQuery &Q) {
  5170. // Idempotent functions return the same result when called repeatedly.
  5171. Intrinsic::ID IID = F->getIntrinsicID();
  5172. if (isIdempotent(IID))
  5173. if (auto *II = dyn_cast<IntrinsicInst>(Op0))
  5174. if (II->getIntrinsicID() == IID)
  5175. return II;
  5176. if (removesFPFraction(IID)) {
  5177. // Converting from int or calling a rounding function always results in a
  5178. // finite integral number or infinity. For those inputs, rounding functions
  5179. // always return the same value, so the (2nd) rounding is eliminated. Ex:
  5180. // floor (sitofp x) -> sitofp x
  5181. // round (ceil x) -> ceil x
  5182. auto *II = dyn_cast<IntrinsicInst>(Op0);
  5183. if ((II && removesFPFraction(II->getIntrinsicID())) ||
  5184. match(Op0, m_SIToFP(m_Value())) || match(Op0, m_UIToFP(m_Value())))
  5185. return Op0;
  5186. }
  5187. Value *X;
  5188. switch (IID) {
  5189. case Intrinsic::fabs:
  5190. if (SignBitMustBeZero(Op0, Q.TLI))
  5191. return Op0;
  5192. break;
  5193. case Intrinsic::bswap:
  5194. // bswap(bswap(x)) -> x
  5195. if (match(Op0, m_BSwap(m_Value(X))))
  5196. return X;
  5197. break;
  5198. case Intrinsic::bitreverse:
  5199. // bitreverse(bitreverse(x)) -> x
  5200. if (match(Op0, m_BitReverse(m_Value(X))))
  5201. return X;
  5202. break;
  5203. case Intrinsic::ctpop: {
  5204. // ctpop(X) -> 1 iff X is non-zero power of 2.
  5205. if (isKnownToBeAPowerOfTwo(Op0, Q.DL, /*OrZero*/ false, 0, Q.AC, Q.CxtI,
  5206. Q.DT))
  5207. return ConstantInt::get(Op0->getType(), 1);
  5208. // If everything but the lowest bit is zero, that bit is the pop-count. Ex:
  5209. // ctpop(and X, 1) --> and X, 1
  5210. unsigned BitWidth = Op0->getType()->getScalarSizeInBits();
  5211. if (MaskedValueIsZero(Op0, APInt::getHighBitsSet(BitWidth, BitWidth - 1),
  5212. Q.DL, 0, Q.AC, Q.CxtI, Q.DT))
  5213. return Op0;
  5214. break;
  5215. }
  5216. case Intrinsic::exp:
  5217. // exp(log(x)) -> x
  5218. if (Q.CxtI->hasAllowReassoc() &&
  5219. match(Op0, m_Intrinsic<Intrinsic::log>(m_Value(X))))
  5220. return X;
  5221. break;
  5222. case Intrinsic::exp2:
  5223. // exp2(log2(x)) -> x
  5224. if (Q.CxtI->hasAllowReassoc() &&
  5225. match(Op0, m_Intrinsic<Intrinsic::log2>(m_Value(X))))
  5226. return X;
  5227. break;
  5228. case Intrinsic::log:
  5229. // log(exp(x)) -> x
  5230. if (Q.CxtI->hasAllowReassoc() &&
  5231. match(Op0, m_Intrinsic<Intrinsic::exp>(m_Value(X))))
  5232. return X;
  5233. break;
  5234. case Intrinsic::log2:
  5235. // log2(exp2(x)) -> x
  5236. if (Q.CxtI->hasAllowReassoc() &&
  5237. (match(Op0, m_Intrinsic<Intrinsic::exp2>(m_Value(X))) ||
  5238. match(Op0,
  5239. m_Intrinsic<Intrinsic::pow>(m_SpecificFP(2.0), m_Value(X)))))
  5240. return X;
  5241. break;
  5242. case Intrinsic::log10:
  5243. // log10(pow(10.0, x)) -> x
  5244. if (Q.CxtI->hasAllowReassoc() &&
  5245. match(Op0, m_Intrinsic<Intrinsic::pow>(m_SpecificFP(10.0), m_Value(X))))
  5246. return X;
  5247. break;
  5248. case Intrinsic::experimental_vector_reverse:
  5249. // experimental.vector.reverse(experimental.vector.reverse(x)) -> x
  5250. if (match(Op0, m_VecReverse(m_Value(X))))
  5251. return X;
  5252. // experimental.vector.reverse(splat(X)) -> splat(X)
  5253. if (isSplatValue(Op0))
  5254. return Op0;
  5255. break;
  5256. default:
  5257. break;
  5258. }
  5259. return nullptr;
  5260. }
  5261. /// Given a min/max intrinsic, see if it can be removed based on having an
  5262. /// operand that is another min/max intrinsic with shared operand(s). The caller
  5263. /// is expected to swap the operand arguments to handle commutation.
  5264. static Value *foldMinMaxSharedOp(Intrinsic::ID IID, Value *Op0, Value *Op1) {
  5265. Value *X, *Y;
  5266. if (!match(Op0, m_MaxOrMin(m_Value(X), m_Value(Y))))
  5267. return nullptr;
  5268. auto *MM0 = dyn_cast<IntrinsicInst>(Op0);
  5269. if (!MM0)
  5270. return nullptr;
  5271. Intrinsic::ID IID0 = MM0->getIntrinsicID();
  5272. if (Op1 == X || Op1 == Y ||
  5273. match(Op1, m_c_MaxOrMin(m_Specific(X), m_Specific(Y)))) {
  5274. // max (max X, Y), X --> max X, Y
  5275. if (IID0 == IID)
  5276. return MM0;
  5277. // max (min X, Y), X --> X
  5278. if (IID0 == getInverseMinMaxIntrinsic(IID))
  5279. return Op1;
  5280. }
  5281. return nullptr;
  5282. }
  5283. static Value *simplifyBinaryIntrinsic(Function *F, Value *Op0, Value *Op1,
  5284. const SimplifyQuery &Q) {
  5285. Intrinsic::ID IID = F->getIntrinsicID();
  5286. Type *ReturnType = F->getReturnType();
  5287. unsigned BitWidth = ReturnType->getScalarSizeInBits();
  5288. switch (IID) {
  5289. case Intrinsic::abs:
  5290. // abs(abs(x)) -> abs(x). We don't need to worry about the nsw arg here.
  5291. // It is always ok to pick the earlier abs. We'll just lose nsw if its only
  5292. // on the outer abs.
  5293. if (match(Op0, m_Intrinsic<Intrinsic::abs>(m_Value(), m_Value())))
  5294. return Op0;
  5295. break;
  5296. case Intrinsic::cttz: {
  5297. Value *X;
  5298. if (match(Op0, m_Shl(m_One(), m_Value(X))))
  5299. return X;
  5300. break;
  5301. }
  5302. case Intrinsic::ctlz: {
  5303. Value *X;
  5304. if (match(Op0, m_LShr(m_Negative(), m_Value(X))))
  5305. return X;
  5306. if (match(Op0, m_AShr(m_Negative(), m_Value())))
  5307. return Constant::getNullValue(ReturnType);
  5308. break;
  5309. }
  5310. case Intrinsic::smax:
  5311. case Intrinsic::smin:
  5312. case Intrinsic::umax:
  5313. case Intrinsic::umin: {
  5314. // If the arguments are the same, this is a no-op.
  5315. if (Op0 == Op1)
  5316. return Op0;
  5317. // Canonicalize immediate constant operand as Op1.
  5318. if (match(Op0, m_ImmConstant()))
  5319. std::swap(Op0, Op1);
  5320. // Assume undef is the limit value.
  5321. if (Q.isUndefValue(Op1))
  5322. return ConstantInt::get(
  5323. ReturnType, MinMaxIntrinsic::getSaturationPoint(IID, BitWidth));
  5324. const APInt *C;
  5325. if (match(Op1, m_APIntAllowUndef(C))) {
  5326. // Clamp to limit value. For example:
  5327. // umax(i8 %x, i8 255) --> 255
  5328. if (*C == MinMaxIntrinsic::getSaturationPoint(IID, BitWidth))
  5329. return ConstantInt::get(ReturnType, *C);
  5330. // If the constant op is the opposite of the limit value, the other must
  5331. // be larger/smaller or equal. For example:
  5332. // umin(i8 %x, i8 255) --> %x
  5333. if (*C == MinMaxIntrinsic::getSaturationPoint(
  5334. getInverseMinMaxIntrinsic(IID), BitWidth))
  5335. return Op0;
  5336. // Remove nested call if constant operands allow it. Example:
  5337. // max (max X, 7), 5 -> max X, 7
  5338. auto *MinMax0 = dyn_cast<IntrinsicInst>(Op0);
  5339. if (MinMax0 && MinMax0->getIntrinsicID() == IID) {
  5340. // TODO: loosen undef/splat restrictions for vector constants.
  5341. Value *M00 = MinMax0->getOperand(0), *M01 = MinMax0->getOperand(1);
  5342. const APInt *InnerC;
  5343. if ((match(M00, m_APInt(InnerC)) || match(M01, m_APInt(InnerC))) &&
  5344. ICmpInst::compare(*InnerC, *C,
  5345. ICmpInst::getNonStrictPredicate(
  5346. MinMaxIntrinsic::getPredicate(IID))))
  5347. return Op0;
  5348. }
  5349. }
  5350. if (Value *V = foldMinMaxSharedOp(IID, Op0, Op1))
  5351. return V;
  5352. if (Value *V = foldMinMaxSharedOp(IID, Op1, Op0))
  5353. return V;
  5354. ICmpInst::Predicate Pred =
  5355. ICmpInst::getNonStrictPredicate(MinMaxIntrinsic::getPredicate(IID));
  5356. if (isICmpTrue(Pred, Op0, Op1, Q.getWithoutUndef(), RecursionLimit))
  5357. return Op0;
  5358. if (isICmpTrue(Pred, Op1, Op0, Q.getWithoutUndef(), RecursionLimit))
  5359. return Op1;
  5360. if (std::optional<bool> Imp =
  5361. isImpliedByDomCondition(Pred, Op0, Op1, Q.CxtI, Q.DL))
  5362. return *Imp ? Op0 : Op1;
  5363. if (std::optional<bool> Imp =
  5364. isImpliedByDomCondition(Pred, Op1, Op0, Q.CxtI, Q.DL))
  5365. return *Imp ? Op1 : Op0;
  5366. break;
  5367. }
  5368. case Intrinsic::usub_with_overflow:
  5369. case Intrinsic::ssub_with_overflow:
  5370. // X - X -> { 0, false }
  5371. // X - undef -> { 0, false }
  5372. // undef - X -> { 0, false }
  5373. if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
  5374. return Constant::getNullValue(ReturnType);
  5375. break;
  5376. case Intrinsic::uadd_with_overflow:
  5377. case Intrinsic::sadd_with_overflow:
  5378. // X + undef -> { -1, false }
  5379. // undef + x -> { -1, false }
  5380. if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1)) {
  5381. return ConstantStruct::get(
  5382. cast<StructType>(ReturnType),
  5383. {Constant::getAllOnesValue(ReturnType->getStructElementType(0)),
  5384. Constant::getNullValue(ReturnType->getStructElementType(1))});
  5385. }
  5386. break;
  5387. case Intrinsic::umul_with_overflow:
  5388. case Intrinsic::smul_with_overflow:
  5389. // 0 * X -> { 0, false }
  5390. // X * 0 -> { 0, false }
  5391. if (match(Op0, m_Zero()) || match(Op1, m_Zero()))
  5392. return Constant::getNullValue(ReturnType);
  5393. // undef * X -> { 0, false }
  5394. // X * undef -> { 0, false }
  5395. if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
  5396. return Constant::getNullValue(ReturnType);
  5397. break;
  5398. case Intrinsic::uadd_sat:
  5399. // sat(MAX + X) -> MAX
  5400. // sat(X + MAX) -> MAX
  5401. if (match(Op0, m_AllOnes()) || match(Op1, m_AllOnes()))
  5402. return Constant::getAllOnesValue(ReturnType);
  5403. [[fallthrough]];
  5404. case Intrinsic::sadd_sat:
  5405. // sat(X + undef) -> -1
  5406. // sat(undef + X) -> -1
  5407. // For unsigned: Assume undef is MAX, thus we saturate to MAX (-1).
  5408. // For signed: Assume undef is ~X, in which case X + ~X = -1.
  5409. if (Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
  5410. return Constant::getAllOnesValue(ReturnType);
  5411. // X + 0 -> X
  5412. if (match(Op1, m_Zero()))
  5413. return Op0;
  5414. // 0 + X -> X
  5415. if (match(Op0, m_Zero()))
  5416. return Op1;
  5417. break;
  5418. case Intrinsic::usub_sat:
  5419. // sat(0 - X) -> 0, sat(X - MAX) -> 0
  5420. if (match(Op0, m_Zero()) || match(Op1, m_AllOnes()))
  5421. return Constant::getNullValue(ReturnType);
  5422. [[fallthrough]];
  5423. case Intrinsic::ssub_sat:
  5424. // X - X -> 0, X - undef -> 0, undef - X -> 0
  5425. if (Op0 == Op1 || Q.isUndefValue(Op0) || Q.isUndefValue(Op1))
  5426. return Constant::getNullValue(ReturnType);
  5427. // X - 0 -> X
  5428. if (match(Op1, m_Zero()))
  5429. return Op0;
  5430. break;
  5431. case Intrinsic::load_relative:
  5432. if (auto *C0 = dyn_cast<Constant>(Op0))
  5433. if (auto *C1 = dyn_cast<Constant>(Op1))
  5434. return simplifyRelativeLoad(C0, C1, Q.DL);
  5435. break;
  5436. case Intrinsic::powi:
  5437. if (auto *Power = dyn_cast<ConstantInt>(Op1)) {
  5438. // powi(x, 0) -> 1.0
  5439. if (Power->isZero())
  5440. return ConstantFP::get(Op0->getType(), 1.0);
  5441. // powi(x, 1) -> x
  5442. if (Power->isOne())
  5443. return Op0;
  5444. }
  5445. break;
  5446. case Intrinsic::copysign:
  5447. // copysign X, X --> X
  5448. if (Op0 == Op1)
  5449. return Op0;
  5450. // copysign -X, X --> X
  5451. // copysign X, -X --> -X
  5452. if (match(Op0, m_FNeg(m_Specific(Op1))) ||
  5453. match(Op1, m_FNeg(m_Specific(Op0))))
  5454. return Op1;
  5455. break;
  5456. case Intrinsic::is_fpclass: {
  5457. if (isa<PoisonValue>(Op0))
  5458. return PoisonValue::get(ReturnType);
  5459. uint64_t Mask = cast<ConstantInt>(Op1)->getZExtValue();
  5460. // If all tests are made, it doesn't matter what the value is.
  5461. if ((Mask & fcAllFlags) == fcAllFlags)
  5462. return ConstantInt::get(ReturnType, true);
  5463. if ((Mask & fcAllFlags) == 0)
  5464. return ConstantInt::get(ReturnType, false);
  5465. if (Q.isUndefValue(Op0))
  5466. return UndefValue::get(ReturnType);
  5467. break;
  5468. }
  5469. case Intrinsic::maxnum:
  5470. case Intrinsic::minnum:
  5471. case Intrinsic::maximum:
  5472. case Intrinsic::minimum: {
  5473. // If the arguments are the same, this is a no-op.
  5474. if (Op0 == Op1)
  5475. return Op0;
  5476. // Canonicalize constant operand as Op1.
  5477. if (isa<Constant>(Op0))
  5478. std::swap(Op0, Op1);
  5479. // If an argument is undef, return the other argument.
  5480. if (Q.isUndefValue(Op1))
  5481. return Op0;
  5482. bool PropagateNaN = IID == Intrinsic::minimum || IID == Intrinsic::maximum;
  5483. bool IsMin = IID == Intrinsic::minimum || IID == Intrinsic::minnum;
  5484. // minnum(X, nan) -> X
  5485. // maxnum(X, nan) -> X
  5486. // minimum(X, nan) -> nan
  5487. // maximum(X, nan) -> nan
  5488. if (match(Op1, m_NaN()))
  5489. return PropagateNaN ? propagateNaN(cast<Constant>(Op1)) : Op0;
  5490. // In the following folds, inf can be replaced with the largest finite
  5491. // float, if the ninf flag is set.
  5492. const APFloat *C;
  5493. if (match(Op1, m_APFloat(C)) &&
  5494. (C->isInfinity() || (Q.CxtI->hasNoInfs() && C->isLargest()))) {
  5495. // minnum(X, -inf) -> -inf
  5496. // maxnum(X, +inf) -> +inf
  5497. // minimum(X, -inf) -> -inf if nnan
  5498. // maximum(X, +inf) -> +inf if nnan
  5499. if (C->isNegative() == IsMin && (!PropagateNaN || Q.CxtI->hasNoNaNs()))
  5500. return ConstantFP::get(ReturnType, *C);
  5501. // minnum(X, +inf) -> X if nnan
  5502. // maxnum(X, -inf) -> X if nnan
  5503. // minimum(X, +inf) -> X
  5504. // maximum(X, -inf) -> X
  5505. if (C->isNegative() != IsMin && (PropagateNaN || Q.CxtI->hasNoNaNs()))
  5506. return Op0;
  5507. }
  5508. // Min/max of the same operation with common operand:
  5509. // m(m(X, Y)), X --> m(X, Y) (4 commuted variants)
  5510. if (auto *M0 = dyn_cast<IntrinsicInst>(Op0))
  5511. if (M0->getIntrinsicID() == IID &&
  5512. (M0->getOperand(0) == Op1 || M0->getOperand(1) == Op1))
  5513. return Op0;
  5514. if (auto *M1 = dyn_cast<IntrinsicInst>(Op1))
  5515. if (M1->getIntrinsicID() == IID &&
  5516. (M1->getOperand(0) == Op0 || M1->getOperand(1) == Op0))
  5517. return Op1;
  5518. break;
  5519. }
  5520. case Intrinsic::vector_extract: {
  5521. Type *ReturnType = F->getReturnType();
  5522. // (extract_vector (insert_vector _, X, 0), 0) -> X
  5523. unsigned IdxN = cast<ConstantInt>(Op1)->getZExtValue();
  5524. Value *X = nullptr;
  5525. if (match(Op0, m_Intrinsic<Intrinsic::vector_insert>(m_Value(), m_Value(X),
  5526. m_Zero())) &&
  5527. IdxN == 0 && X->getType() == ReturnType)
  5528. return X;
  5529. break;
  5530. }
  5531. default:
  5532. break;
  5533. }
  5534. return nullptr;
  5535. }
  5536. static Value *simplifyIntrinsic(CallBase *Call, const SimplifyQuery &Q) {
  5537. unsigned NumOperands = Call->arg_size();
  5538. Function *F = cast<Function>(Call->getCalledFunction());
  5539. Intrinsic::ID IID = F->getIntrinsicID();
  5540. // Most of the intrinsics with no operands have some kind of side effect.
  5541. // Don't simplify.
  5542. if (!NumOperands) {
  5543. switch (IID) {
  5544. case Intrinsic::vscale: {
  5545. // Call may not be inserted into the IR yet at point of calling simplify.
  5546. if (!Call->getParent() || !Call->getParent()->getParent())
  5547. return nullptr;
  5548. auto Attr = Call->getFunction()->getFnAttribute(Attribute::VScaleRange);
  5549. if (!Attr.isValid())
  5550. return nullptr;
  5551. unsigned VScaleMin = Attr.getVScaleRangeMin();
  5552. std::optional<unsigned> VScaleMax = Attr.getVScaleRangeMax();
  5553. if (VScaleMax && VScaleMin == VScaleMax)
  5554. return ConstantInt::get(F->getReturnType(), VScaleMin);
  5555. return nullptr;
  5556. }
  5557. default:
  5558. return nullptr;
  5559. }
  5560. }
  5561. if (NumOperands == 1)
  5562. return simplifyUnaryIntrinsic(F, Call->getArgOperand(0), Q);
  5563. if (NumOperands == 2)
  5564. return simplifyBinaryIntrinsic(F, Call->getArgOperand(0),
  5565. Call->getArgOperand(1), Q);
  5566. // Handle intrinsics with 3 or more arguments.
  5567. switch (IID) {
  5568. case Intrinsic::masked_load:
  5569. case Intrinsic::masked_gather: {
  5570. Value *MaskArg = Call->getArgOperand(2);
  5571. Value *PassthruArg = Call->getArgOperand(3);
  5572. // If the mask is all zeros or undef, the "passthru" argument is the result.
  5573. if (maskIsAllZeroOrUndef(MaskArg))
  5574. return PassthruArg;
  5575. return nullptr;
  5576. }
  5577. case Intrinsic::fshl:
  5578. case Intrinsic::fshr: {
  5579. Value *Op0 = Call->getArgOperand(0), *Op1 = Call->getArgOperand(1),
  5580. *ShAmtArg = Call->getArgOperand(2);
  5581. // If both operands are undef, the result is undef.
  5582. if (Q.isUndefValue(Op0) && Q.isUndefValue(Op1))
  5583. return UndefValue::get(F->getReturnType());
  5584. // If shift amount is undef, assume it is zero.
  5585. if (Q.isUndefValue(ShAmtArg))
  5586. return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
  5587. const APInt *ShAmtC;
  5588. if (match(ShAmtArg, m_APInt(ShAmtC))) {
  5589. // If there's effectively no shift, return the 1st arg or 2nd arg.
  5590. APInt BitWidth = APInt(ShAmtC->getBitWidth(), ShAmtC->getBitWidth());
  5591. if (ShAmtC->urem(BitWidth).isZero())
  5592. return Call->getArgOperand(IID == Intrinsic::fshl ? 0 : 1);
  5593. }
  5594. // Rotating zero by anything is zero.
  5595. if (match(Op0, m_Zero()) && match(Op1, m_Zero()))
  5596. return ConstantInt::getNullValue(F->getReturnType());
  5597. // Rotating -1 by anything is -1.
  5598. if (match(Op0, m_AllOnes()) && match(Op1, m_AllOnes()))
  5599. return ConstantInt::getAllOnesValue(F->getReturnType());
  5600. return nullptr;
  5601. }
  5602. case Intrinsic::experimental_constrained_fma: {
  5603. Value *Op0 = Call->getArgOperand(0);
  5604. Value *Op1 = Call->getArgOperand(1);
  5605. Value *Op2 = Call->getArgOperand(2);
  5606. auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
  5607. if (Value *V =
  5608. simplifyFPOp({Op0, Op1, Op2}, {}, Q, *FPI->getExceptionBehavior(),
  5609. *FPI->getRoundingMode()))
  5610. return V;
  5611. return nullptr;
  5612. }
  5613. case Intrinsic::fma:
  5614. case Intrinsic::fmuladd: {
  5615. Value *Op0 = Call->getArgOperand(0);
  5616. Value *Op1 = Call->getArgOperand(1);
  5617. Value *Op2 = Call->getArgOperand(2);
  5618. if (Value *V = simplifyFPOp({Op0, Op1, Op2}, {}, Q, fp::ebIgnore,
  5619. RoundingMode::NearestTiesToEven))
  5620. return V;
  5621. return nullptr;
  5622. }
  5623. case Intrinsic::smul_fix:
  5624. case Intrinsic::smul_fix_sat: {
  5625. Value *Op0 = Call->getArgOperand(0);
  5626. Value *Op1 = Call->getArgOperand(1);
  5627. Value *Op2 = Call->getArgOperand(2);
  5628. Type *ReturnType = F->getReturnType();
  5629. // Canonicalize constant operand as Op1 (ConstantFolding handles the case
  5630. // when both Op0 and Op1 are constant so we do not care about that special
  5631. // case here).
  5632. if (isa<Constant>(Op0))
  5633. std::swap(Op0, Op1);
  5634. // X * 0 -> 0
  5635. if (match(Op1, m_Zero()))
  5636. return Constant::getNullValue(ReturnType);
  5637. // X * undef -> 0
  5638. if (Q.isUndefValue(Op1))
  5639. return Constant::getNullValue(ReturnType);
  5640. // X * (1 << Scale) -> X
  5641. APInt ScaledOne =
  5642. APInt::getOneBitSet(ReturnType->getScalarSizeInBits(),
  5643. cast<ConstantInt>(Op2)->getZExtValue());
  5644. if (ScaledOne.isNonNegative() && match(Op1, m_SpecificInt(ScaledOne)))
  5645. return Op0;
  5646. return nullptr;
  5647. }
  5648. case Intrinsic::vector_insert: {
  5649. Value *Vec = Call->getArgOperand(0);
  5650. Value *SubVec = Call->getArgOperand(1);
  5651. Value *Idx = Call->getArgOperand(2);
  5652. Type *ReturnType = F->getReturnType();
  5653. // (insert_vector Y, (extract_vector X, 0), 0) -> X
  5654. // where: Y is X, or Y is undef
  5655. unsigned IdxN = cast<ConstantInt>(Idx)->getZExtValue();
  5656. Value *X = nullptr;
  5657. if (match(SubVec,
  5658. m_Intrinsic<Intrinsic::vector_extract>(m_Value(X), m_Zero())) &&
  5659. (Q.isUndefValue(Vec) || Vec == X) && IdxN == 0 &&
  5660. X->getType() == ReturnType)
  5661. return X;
  5662. return nullptr;
  5663. }
  5664. case Intrinsic::experimental_constrained_fadd: {
  5665. auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
  5666. return simplifyFAddInst(
  5667. FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
  5668. Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
  5669. }
  5670. case Intrinsic::experimental_constrained_fsub: {
  5671. auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
  5672. return simplifyFSubInst(
  5673. FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
  5674. Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
  5675. }
  5676. case Intrinsic::experimental_constrained_fmul: {
  5677. auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
  5678. return simplifyFMulInst(
  5679. FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
  5680. Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
  5681. }
  5682. case Intrinsic::experimental_constrained_fdiv: {
  5683. auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
  5684. return simplifyFDivInst(
  5685. FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
  5686. Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
  5687. }
  5688. case Intrinsic::experimental_constrained_frem: {
  5689. auto *FPI = cast<ConstrainedFPIntrinsic>(Call);
  5690. return simplifyFRemInst(
  5691. FPI->getArgOperand(0), FPI->getArgOperand(1), FPI->getFastMathFlags(),
  5692. Q, *FPI->getExceptionBehavior(), *FPI->getRoundingMode());
  5693. }
  5694. default:
  5695. return nullptr;
  5696. }
  5697. }
  5698. static Value *tryConstantFoldCall(CallBase *Call, const SimplifyQuery &Q) {
  5699. auto *F = dyn_cast<Function>(Call->getCalledOperand());
  5700. if (!F || !canConstantFoldCallTo(Call, F))
  5701. return nullptr;
  5702. SmallVector<Constant *, 4> ConstantArgs;
  5703. unsigned NumArgs = Call->arg_size();
  5704. ConstantArgs.reserve(NumArgs);
  5705. for (auto &Arg : Call->args()) {
  5706. Constant *C = dyn_cast<Constant>(&Arg);
  5707. if (!C) {
  5708. if (isa<MetadataAsValue>(Arg.get()))
  5709. continue;
  5710. return nullptr;
  5711. }
  5712. ConstantArgs.push_back(C);
  5713. }
  5714. return ConstantFoldCall(Call, F, ConstantArgs, Q.TLI);
  5715. }
  5716. Value *llvm::simplifyCall(CallBase *Call, const SimplifyQuery &Q) {
  5717. // musttail calls can only be simplified if they are also DCEd.
  5718. // As we can't guarantee this here, don't simplify them.
  5719. if (Call->isMustTailCall())
  5720. return nullptr;
  5721. // call undef -> poison
  5722. // call null -> poison
  5723. Value *Callee = Call->getCalledOperand();
  5724. if (isa<UndefValue>(Callee) || isa<ConstantPointerNull>(Callee))
  5725. return PoisonValue::get(Call->getType());
  5726. if (Value *V = tryConstantFoldCall(Call, Q))
  5727. return V;
  5728. auto *F = dyn_cast<Function>(Callee);
  5729. if (F && F->isIntrinsic())
  5730. if (Value *Ret = simplifyIntrinsic(Call, Q))
  5731. return Ret;
  5732. return nullptr;
  5733. }
  5734. Value *llvm::simplifyConstrainedFPCall(CallBase *Call, const SimplifyQuery &Q) {
  5735. assert(isa<ConstrainedFPIntrinsic>(Call));
  5736. if (Value *V = tryConstantFoldCall(Call, Q))
  5737. return V;
  5738. if (Value *Ret = simplifyIntrinsic(Call, Q))
  5739. return Ret;
  5740. return nullptr;
  5741. }
  5742. /// Given operands for a Freeze, see if we can fold the result.
  5743. static Value *simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
  5744. // Use a utility function defined in ValueTracking.
  5745. if (llvm::isGuaranteedNotToBeUndefOrPoison(Op0, Q.AC, Q.CxtI, Q.DT))
  5746. return Op0;
  5747. // We have room for improvement.
  5748. return nullptr;
  5749. }
  5750. Value *llvm::simplifyFreezeInst(Value *Op0, const SimplifyQuery &Q) {
  5751. return ::simplifyFreezeInst(Op0, Q);
  5752. }
  5753. static Value *simplifyLoadInst(LoadInst *LI, Value *PtrOp,
  5754. const SimplifyQuery &Q) {
  5755. if (LI->isVolatile())
  5756. return nullptr;
  5757. APInt Offset(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()), 0);
  5758. auto *PtrOpC = dyn_cast<Constant>(PtrOp);
  5759. // Try to convert operand into a constant by stripping offsets while looking
  5760. // through invariant.group intrinsics. Don't bother if the underlying object
  5761. // is not constant, as calculating GEP offsets is expensive.
  5762. if (!PtrOpC && isa<Constant>(getUnderlyingObject(PtrOp))) {
  5763. PtrOp = PtrOp->stripAndAccumulateConstantOffsets(
  5764. Q.DL, Offset, /* AllowNonInbounts */ true,
  5765. /* AllowInvariantGroup */ true);
  5766. // Index size may have changed due to address space casts.
  5767. Offset = Offset.sextOrTrunc(Q.DL.getIndexTypeSizeInBits(PtrOp->getType()));
  5768. PtrOpC = dyn_cast<Constant>(PtrOp);
  5769. }
  5770. if (PtrOpC)
  5771. return ConstantFoldLoadFromConstPtr(PtrOpC, LI->getType(), Offset, Q.DL);
  5772. return nullptr;
  5773. }
  5774. /// See if we can compute a simplified version of this instruction.
  5775. /// If not, this returns null.
  5776. static Value *simplifyInstructionWithOperands(Instruction *I,
  5777. ArrayRef<Value *> NewOps,
  5778. const SimplifyQuery &SQ,
  5779. OptimizationRemarkEmitter *ORE) {
  5780. const SimplifyQuery Q = SQ.CxtI ? SQ : SQ.getWithInstruction(I);
  5781. switch (I->getOpcode()) {
  5782. default:
  5783. if (llvm::all_of(NewOps, [](Value *V) { return isa<Constant>(V); })) {
  5784. SmallVector<Constant *, 8> NewConstOps(NewOps.size());
  5785. transform(NewOps, NewConstOps.begin(),
  5786. [](Value *V) { return cast<Constant>(V); });
  5787. return ConstantFoldInstOperands(I, NewConstOps, Q.DL, Q.TLI);
  5788. }
  5789. return nullptr;
  5790. case Instruction::FNeg:
  5791. return simplifyFNegInst(NewOps[0], I->getFastMathFlags(), Q);
  5792. case Instruction::FAdd:
  5793. return simplifyFAddInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
  5794. case Instruction::Add:
  5795. return simplifyAddInst(NewOps[0], NewOps[1],
  5796. Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
  5797. Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
  5798. case Instruction::FSub:
  5799. return simplifyFSubInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
  5800. case Instruction::Sub:
  5801. return simplifySubInst(NewOps[0], NewOps[1],
  5802. Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
  5803. Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
  5804. case Instruction::FMul:
  5805. return simplifyFMulInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
  5806. case Instruction::Mul:
  5807. return simplifyMulInst(NewOps[0], NewOps[1],
  5808. Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
  5809. Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
  5810. case Instruction::SDiv:
  5811. return simplifySDivInst(NewOps[0], NewOps[1],
  5812. Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
  5813. case Instruction::UDiv:
  5814. return simplifyUDivInst(NewOps[0], NewOps[1],
  5815. Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
  5816. case Instruction::FDiv:
  5817. return simplifyFDivInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
  5818. case Instruction::SRem:
  5819. return simplifySRemInst(NewOps[0], NewOps[1], Q);
  5820. case Instruction::URem:
  5821. return simplifyURemInst(NewOps[0], NewOps[1], Q);
  5822. case Instruction::FRem:
  5823. return simplifyFRemInst(NewOps[0], NewOps[1], I->getFastMathFlags(), Q);
  5824. case Instruction::Shl:
  5825. return simplifyShlInst(NewOps[0], NewOps[1],
  5826. Q.IIQ.hasNoSignedWrap(cast<BinaryOperator>(I)),
  5827. Q.IIQ.hasNoUnsignedWrap(cast<BinaryOperator>(I)), Q);
  5828. case Instruction::LShr:
  5829. return simplifyLShrInst(NewOps[0], NewOps[1],
  5830. Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
  5831. case Instruction::AShr:
  5832. return simplifyAShrInst(NewOps[0], NewOps[1],
  5833. Q.IIQ.isExact(cast<BinaryOperator>(I)), Q);
  5834. case Instruction::And:
  5835. return simplifyAndInst(NewOps[0], NewOps[1], Q);
  5836. case Instruction::Or:
  5837. return simplifyOrInst(NewOps[0], NewOps[1], Q);
  5838. case Instruction::Xor:
  5839. return simplifyXorInst(NewOps[0], NewOps[1], Q);
  5840. case Instruction::ICmp:
  5841. return simplifyICmpInst(cast<ICmpInst>(I)->getPredicate(), NewOps[0],
  5842. NewOps[1], Q);
  5843. case Instruction::FCmp:
  5844. return simplifyFCmpInst(cast<FCmpInst>(I)->getPredicate(), NewOps[0],
  5845. NewOps[1], I->getFastMathFlags(), Q);
  5846. case Instruction::Select:
  5847. return simplifySelectInst(NewOps[0], NewOps[1], NewOps[2], Q);
  5848. break;
  5849. case Instruction::GetElementPtr: {
  5850. auto *GEPI = cast<GetElementPtrInst>(I);
  5851. return simplifyGEPInst(GEPI->getSourceElementType(), NewOps[0],
  5852. ArrayRef(NewOps).slice(1), GEPI->isInBounds(), Q);
  5853. }
  5854. case Instruction::InsertValue: {
  5855. InsertValueInst *IV = cast<InsertValueInst>(I);
  5856. return simplifyInsertValueInst(NewOps[0], NewOps[1], IV->getIndices(), Q);
  5857. }
  5858. case Instruction::InsertElement:
  5859. return simplifyInsertElementInst(NewOps[0], NewOps[1], NewOps[2], Q);
  5860. case Instruction::ExtractValue: {
  5861. auto *EVI = cast<ExtractValueInst>(I);
  5862. return simplifyExtractValueInst(NewOps[0], EVI->getIndices(), Q);
  5863. }
  5864. case Instruction::ExtractElement:
  5865. return simplifyExtractElementInst(NewOps[0], NewOps[1], Q);
  5866. case Instruction::ShuffleVector: {
  5867. auto *SVI = cast<ShuffleVectorInst>(I);
  5868. return simplifyShuffleVectorInst(NewOps[0], NewOps[1],
  5869. SVI->getShuffleMask(), SVI->getType(), Q);
  5870. }
  5871. case Instruction::PHI:
  5872. return simplifyPHINode(cast<PHINode>(I), NewOps, Q);
  5873. case Instruction::Call:
  5874. // TODO: Use NewOps
  5875. return simplifyCall(cast<CallInst>(I), Q);
  5876. case Instruction::Freeze:
  5877. return llvm::simplifyFreezeInst(NewOps[0], Q);
  5878. #define HANDLE_CAST_INST(num, opc, clas) case Instruction::opc:
  5879. #include "llvm/IR/Instruction.def"
  5880. #undef HANDLE_CAST_INST
  5881. return simplifyCastInst(I->getOpcode(), NewOps[0], I->getType(), Q);
  5882. case Instruction::Alloca:
  5883. // No simplifications for Alloca and it can't be constant folded.
  5884. return nullptr;
  5885. case Instruction::Load:
  5886. return simplifyLoadInst(cast<LoadInst>(I), NewOps[0], Q);
  5887. }
  5888. }
  5889. Value *llvm::simplifyInstructionWithOperands(Instruction *I,
  5890. ArrayRef<Value *> NewOps,
  5891. const SimplifyQuery &SQ,
  5892. OptimizationRemarkEmitter *ORE) {
  5893. assert(NewOps.size() == I->getNumOperands() &&
  5894. "Number of operands should match the instruction!");
  5895. return ::simplifyInstructionWithOperands(I, NewOps, SQ, ORE);
  5896. }
  5897. Value *llvm::simplifyInstruction(Instruction *I, const SimplifyQuery &SQ,
  5898. OptimizationRemarkEmitter *ORE) {
  5899. SmallVector<Value *, 8> Ops(I->operands());
  5900. Value *Result = ::simplifyInstructionWithOperands(I, Ops, SQ, ORE);
  5901. /// If called on unreachable code, the instruction may simplify to itself.
  5902. /// Make life easier for users by detecting that case here, and returning a
  5903. /// safe value instead.
  5904. return Result == I ? UndefValue::get(I->getType()) : Result;
  5905. }
  5906. /// Implementation of recursive simplification through an instruction's
  5907. /// uses.
  5908. ///
  5909. /// This is the common implementation of the recursive simplification routines.
  5910. /// If we have a pre-simplified value in 'SimpleV', that is forcibly used to
  5911. /// replace the instruction 'I'. Otherwise, we simply add 'I' to the list of
  5912. /// instructions to process and attempt to simplify it using
  5913. /// InstructionSimplify. Recursively visited users which could not be
  5914. /// simplified themselves are to the optional UnsimplifiedUsers set for
  5915. /// further processing by the caller.
  5916. ///
  5917. /// This routine returns 'true' only when *it* simplifies something. The passed
  5918. /// in simplified value does not count toward this.
  5919. static bool replaceAndRecursivelySimplifyImpl(
  5920. Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
  5921. const DominatorTree *DT, AssumptionCache *AC,
  5922. SmallSetVector<Instruction *, 8> *UnsimplifiedUsers = nullptr) {
  5923. bool Simplified = false;
  5924. SmallSetVector<Instruction *, 8> Worklist;
  5925. const DataLayout &DL = I->getModule()->getDataLayout();
  5926. // If we have an explicit value to collapse to, do that round of the
  5927. // simplification loop by hand initially.
  5928. if (SimpleV) {
  5929. for (User *U : I->users())
  5930. if (U != I)
  5931. Worklist.insert(cast<Instruction>(U));
  5932. // Replace the instruction with its simplified value.
  5933. I->replaceAllUsesWith(SimpleV);
  5934. // Gracefully handle edge cases where the instruction is not wired into any
  5935. // parent block.
  5936. if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
  5937. !I->mayHaveSideEffects())
  5938. I->eraseFromParent();
  5939. } else {
  5940. Worklist.insert(I);
  5941. }
  5942. // Note that we must test the size on each iteration, the worklist can grow.
  5943. for (unsigned Idx = 0; Idx != Worklist.size(); ++Idx) {
  5944. I = Worklist[Idx];
  5945. // See if this instruction simplifies.
  5946. SimpleV = simplifyInstruction(I, {DL, TLI, DT, AC});
  5947. if (!SimpleV) {
  5948. if (UnsimplifiedUsers)
  5949. UnsimplifiedUsers->insert(I);
  5950. continue;
  5951. }
  5952. Simplified = true;
  5953. // Stash away all the uses of the old instruction so we can check them for
  5954. // recursive simplifications after a RAUW. This is cheaper than checking all
  5955. // uses of To on the recursive step in most cases.
  5956. for (User *U : I->users())
  5957. Worklist.insert(cast<Instruction>(U));
  5958. // Replace the instruction with its simplified value.
  5959. I->replaceAllUsesWith(SimpleV);
  5960. // Gracefully handle edge cases where the instruction is not wired into any
  5961. // parent block.
  5962. if (I->getParent() && !I->isEHPad() && !I->isTerminator() &&
  5963. !I->mayHaveSideEffects())
  5964. I->eraseFromParent();
  5965. }
  5966. return Simplified;
  5967. }
  5968. bool llvm::replaceAndRecursivelySimplify(
  5969. Instruction *I, Value *SimpleV, const TargetLibraryInfo *TLI,
  5970. const DominatorTree *DT, AssumptionCache *AC,
  5971. SmallSetVector<Instruction *, 8> *UnsimplifiedUsers) {
  5972. assert(I != SimpleV && "replaceAndRecursivelySimplify(X,X) is not valid!");
  5973. assert(SimpleV && "Must provide a simplified value.");
  5974. return replaceAndRecursivelySimplifyImpl(I, SimpleV, TLI, DT, AC,
  5975. UnsimplifiedUsers);
  5976. }
  5977. namespace llvm {
  5978. const SimplifyQuery getBestSimplifyQuery(Pass &P, Function &F) {
  5979. auto *DTWP = P.getAnalysisIfAvailable<DominatorTreeWrapperPass>();
  5980. auto *DT = DTWP ? &DTWP->getDomTree() : nullptr;
  5981. auto *TLIWP = P.getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  5982. auto *TLI = TLIWP ? &TLIWP->getTLI(F) : nullptr;
  5983. auto *ACWP = P.getAnalysisIfAvailable<AssumptionCacheTracker>();
  5984. auto *AC = ACWP ? &ACWP->getAssumptionCache(F) : nullptr;
  5985. return {F.getParent()->getDataLayout(), TLI, DT, AC};
  5986. }
  5987. const SimplifyQuery getBestSimplifyQuery(LoopStandardAnalysisResults &AR,
  5988. const DataLayout &DL) {
  5989. return {DL, &AR.TLI, &AR.DT, &AR.AC};
  5990. }
  5991. template <class T, class... TArgs>
  5992. const SimplifyQuery getBestSimplifyQuery(AnalysisManager<T, TArgs...> &AM,
  5993. Function &F) {
  5994. auto *DT = AM.template getCachedResult<DominatorTreeAnalysis>(F);
  5995. auto *TLI = AM.template getCachedResult<TargetLibraryAnalysis>(F);
  5996. auto *AC = AM.template getCachedResult<AssumptionAnalysis>(F);
  5997. return {F.getParent()->getDataLayout(), TLI, DT, AC};
  5998. }
  5999. template const SimplifyQuery getBestSimplifyQuery(AnalysisManager<Function> &,
  6000. Function &);
  6001. } // namespace llvm
  6002. void InstSimplifyFolder::anchor() {}