LoopStrengthReduce.cpp 239 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445
  1. //===- LoopStrengthReduce.cpp - Strength Reduce IVs in Loops --------------===//
  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 transformation analyzes and transforms the induction variables (and
  10. // computations derived from them) into forms suitable for efficient execution
  11. // on the target.
  12. //
  13. // This pass performs a strength reduction on array references inside loops that
  14. // have as one or more of their components the loop induction variable, it
  15. // rewrites expressions to take advantage of scaled-index addressing modes
  16. // available on the target, and it performs a variety of other optimizations
  17. // related to loop induction variables.
  18. //
  19. // Terminology note: this code has a lot of handling for "post-increment" or
  20. // "post-inc" users. This is not talking about post-increment addressing modes;
  21. // it is instead talking about code like this:
  22. //
  23. // %i = phi [ 0, %entry ], [ %i.next, %latch ]
  24. // ...
  25. // %i.next = add %i, 1
  26. // %c = icmp eq %i.next, %n
  27. //
  28. // The SCEV for %i is {0,+,1}<%L>. The SCEV for %i.next is {1,+,1}<%L>, however
  29. // it's useful to think about these as the same register, with some uses using
  30. // the value of the register before the add and some using it after. In this
  31. // example, the icmp is a post-increment user, since it uses %i.next, which is
  32. // the value of the induction variable after the increment. The other common
  33. // case of post-increment users is users outside the loop.
  34. //
  35. // TODO: More sophistication in the way Formulae are generated and filtered.
  36. //
  37. // TODO: Handle multiple loops at a time.
  38. //
  39. // TODO: Should the addressing mode BaseGV be changed to a ConstantExpr instead
  40. // of a GlobalValue?
  41. //
  42. // TODO: When truncation is free, truncate ICmp users' operands to make it a
  43. // smaller encoding (on x86 at least).
  44. //
  45. // TODO: When a negated register is used by an add (such as in a list of
  46. // multiple base registers, or as the increment expression in an addrec),
  47. // we may not actually need both reg and (-1 * reg) in registers; the
  48. // negation can be implemented by using a sub instead of an add. The
  49. // lack of support for taking this into consideration when making
  50. // register pressure decisions is partly worked around by the "Special"
  51. // use kind.
  52. //
  53. //===----------------------------------------------------------------------===//
  54. #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
  55. #include "llvm/ADT/APInt.h"
  56. #include "llvm/ADT/DenseMap.h"
  57. #include "llvm/ADT/DenseSet.h"
  58. #include "llvm/ADT/Hashing.h"
  59. #include "llvm/ADT/PointerIntPair.h"
  60. #include "llvm/ADT/STLExtras.h"
  61. #include "llvm/ADT/SetVector.h"
  62. #include "llvm/ADT/SmallBitVector.h"
  63. #include "llvm/ADT/SmallPtrSet.h"
  64. #include "llvm/ADT/SmallSet.h"
  65. #include "llvm/ADT/SmallVector.h"
  66. #include "llvm/ADT/iterator_range.h"
  67. #include "llvm/Analysis/AssumptionCache.h"
  68. #include "llvm/Analysis/IVUsers.h"
  69. #include "llvm/Analysis/LoopAnalysisManager.h"
  70. #include "llvm/Analysis/LoopInfo.h"
  71. #include "llvm/Analysis/LoopPass.h"
  72. #include "llvm/Analysis/MemorySSA.h"
  73. #include "llvm/Analysis/MemorySSAUpdater.h"
  74. #include "llvm/Analysis/ScalarEvolution.h"
  75. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  76. #include "llvm/Analysis/ScalarEvolutionNormalization.h"
  77. #include "llvm/Analysis/TargetLibraryInfo.h"
  78. #include "llvm/Analysis/TargetTransformInfo.h"
  79. #include "llvm/Analysis/ValueTracking.h"
  80. #include "llvm/Config/llvm-config.h"
  81. #include "llvm/IR/BasicBlock.h"
  82. #include "llvm/IR/Constant.h"
  83. #include "llvm/IR/Constants.h"
  84. #include "llvm/IR/DebugInfoMetadata.h"
  85. #include "llvm/IR/DerivedTypes.h"
  86. #include "llvm/IR/Dominators.h"
  87. #include "llvm/IR/GlobalValue.h"
  88. #include "llvm/IR/IRBuilder.h"
  89. #include "llvm/IR/InstrTypes.h"
  90. #include "llvm/IR/Instruction.h"
  91. #include "llvm/IR/Instructions.h"
  92. #include "llvm/IR/IntrinsicInst.h"
  93. #include "llvm/IR/Intrinsics.h"
  94. #include "llvm/IR/Module.h"
  95. #include "llvm/IR/OperandTraits.h"
  96. #include "llvm/IR/Operator.h"
  97. #include "llvm/IR/PassManager.h"
  98. #include "llvm/IR/Type.h"
  99. #include "llvm/IR/Use.h"
  100. #include "llvm/IR/User.h"
  101. #include "llvm/IR/Value.h"
  102. #include "llvm/IR/ValueHandle.h"
  103. #include "llvm/InitializePasses.h"
  104. #include "llvm/Pass.h"
  105. #include "llvm/Support/Casting.h"
  106. #include "llvm/Support/CommandLine.h"
  107. #include "llvm/Support/Compiler.h"
  108. #include "llvm/Support/Debug.h"
  109. #include "llvm/Support/ErrorHandling.h"
  110. #include "llvm/Support/MathExtras.h"
  111. #include "llvm/Support/raw_ostream.h"
  112. #include "llvm/Transforms/Scalar.h"
  113. #include "llvm/Transforms/Utils.h"
  114. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  115. #include "llvm/Transforms/Utils/Local.h"
  116. #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
  117. #include <algorithm>
  118. #include <cassert>
  119. #include <cstddef>
  120. #include <cstdint>
  121. #include <cstdlib>
  122. #include <iterator>
  123. #include <limits>
  124. #include <map>
  125. #include <numeric>
  126. #include <utility>
  127. using namespace llvm;
  128. #define DEBUG_TYPE "loop-reduce"
  129. /// MaxIVUsers is an arbitrary threshold that provides an early opportunity for
  130. /// bail out. This threshold is far beyond the number of users that LSR can
  131. /// conceivably solve, so it should not affect generated code, but catches the
  132. /// worst cases before LSR burns too much compile time and stack space.
  133. static const unsigned MaxIVUsers = 200;
  134. /// Limit the size of expression that SCEV-based salvaging will attempt to
  135. /// translate into a DIExpression.
  136. /// Choose a maximum size such that debuginfo is not excessively increased and
  137. /// the salvaging is not too expensive for the compiler.
  138. static const unsigned MaxSCEVSalvageExpressionSize = 64;
  139. // Temporary flag to cleanup congruent phis after LSR phi expansion.
  140. // It's currently disabled until we can determine whether it's truly useful or
  141. // not. The flag should be removed after the v3.0 release.
  142. // This is now needed for ivchains.
  143. static cl::opt<bool> EnablePhiElim(
  144. "enable-lsr-phielim", cl::Hidden, cl::init(true),
  145. cl::desc("Enable LSR phi elimination"));
  146. // The flag adds instruction count to solutions cost comparision.
  147. static cl::opt<bool> InsnsCost(
  148. "lsr-insns-cost", cl::Hidden, cl::init(true),
  149. cl::desc("Add instruction count to a LSR cost model"));
  150. // Flag to choose how to narrow complex lsr solution
  151. static cl::opt<bool> LSRExpNarrow(
  152. "lsr-exp-narrow", cl::Hidden, cl::init(false),
  153. cl::desc("Narrow LSR complex solution using"
  154. " expectation of registers number"));
  155. // Flag to narrow search space by filtering non-optimal formulae with
  156. // the same ScaledReg and Scale.
  157. static cl::opt<bool> FilterSameScaledReg(
  158. "lsr-filter-same-scaled-reg", cl::Hidden, cl::init(true),
  159. cl::desc("Narrow LSR search space by filtering non-optimal formulae"
  160. " with the same ScaledReg and Scale"));
  161. static cl::opt<TTI::AddressingModeKind> PreferredAddresingMode(
  162. "lsr-preferred-addressing-mode", cl::Hidden, cl::init(TTI::AMK_None),
  163. cl::desc("A flag that overrides the target's preferred addressing mode."),
  164. cl::values(clEnumValN(TTI::AMK_None,
  165. "none",
  166. "Don't prefer any addressing mode"),
  167. clEnumValN(TTI::AMK_PreIndexed,
  168. "preindexed",
  169. "Prefer pre-indexed addressing mode"),
  170. clEnumValN(TTI::AMK_PostIndexed,
  171. "postindexed",
  172. "Prefer post-indexed addressing mode")));
  173. static cl::opt<unsigned> ComplexityLimit(
  174. "lsr-complexity-limit", cl::Hidden,
  175. cl::init(std::numeric_limits<uint16_t>::max()),
  176. cl::desc("LSR search space complexity limit"));
  177. static cl::opt<unsigned> SetupCostDepthLimit(
  178. "lsr-setupcost-depth-limit", cl::Hidden, cl::init(7),
  179. cl::desc("The limit on recursion depth for LSRs setup cost"));
  180. #ifndef NDEBUG
  181. // Stress test IV chain generation.
  182. static cl::opt<bool> StressIVChain(
  183. "stress-ivchain", cl::Hidden, cl::init(false),
  184. cl::desc("Stress test LSR IV chains"));
  185. #else
  186. static bool StressIVChain = false;
  187. #endif
  188. namespace {
  189. struct MemAccessTy {
  190. /// Used in situations where the accessed memory type is unknown.
  191. static const unsigned UnknownAddressSpace =
  192. std::numeric_limits<unsigned>::max();
  193. Type *MemTy = nullptr;
  194. unsigned AddrSpace = UnknownAddressSpace;
  195. MemAccessTy() = default;
  196. MemAccessTy(Type *Ty, unsigned AS) : MemTy(Ty), AddrSpace(AS) {}
  197. bool operator==(MemAccessTy Other) const {
  198. return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace;
  199. }
  200. bool operator!=(MemAccessTy Other) const { return !(*this == Other); }
  201. static MemAccessTy getUnknown(LLVMContext &Ctx,
  202. unsigned AS = UnknownAddressSpace) {
  203. return MemAccessTy(Type::getVoidTy(Ctx), AS);
  204. }
  205. Type *getType() { return MemTy; }
  206. };
  207. /// This class holds data which is used to order reuse candidates.
  208. class RegSortData {
  209. public:
  210. /// This represents the set of LSRUse indices which reference
  211. /// a particular register.
  212. SmallBitVector UsedByIndices;
  213. void print(raw_ostream &OS) const;
  214. void dump() const;
  215. };
  216. } // end anonymous namespace
  217. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  218. void RegSortData::print(raw_ostream &OS) const {
  219. OS << "[NumUses=" << UsedByIndices.count() << ']';
  220. }
  221. LLVM_DUMP_METHOD void RegSortData::dump() const {
  222. print(errs()); errs() << '\n';
  223. }
  224. #endif
  225. namespace {
  226. /// Map register candidates to information about how they are used.
  227. class RegUseTracker {
  228. using RegUsesTy = DenseMap<const SCEV *, RegSortData>;
  229. RegUsesTy RegUsesMap;
  230. SmallVector<const SCEV *, 16> RegSequence;
  231. public:
  232. void countRegister(const SCEV *Reg, size_t LUIdx);
  233. void dropRegister(const SCEV *Reg, size_t LUIdx);
  234. void swapAndDropUse(size_t LUIdx, size_t LastLUIdx);
  235. bool isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const;
  236. const SmallBitVector &getUsedByIndices(const SCEV *Reg) const;
  237. void clear();
  238. using iterator = SmallVectorImpl<const SCEV *>::iterator;
  239. using const_iterator = SmallVectorImpl<const SCEV *>::const_iterator;
  240. iterator begin() { return RegSequence.begin(); }
  241. iterator end() { return RegSequence.end(); }
  242. const_iterator begin() const { return RegSequence.begin(); }
  243. const_iterator end() const { return RegSequence.end(); }
  244. };
  245. } // end anonymous namespace
  246. void
  247. RegUseTracker::countRegister(const SCEV *Reg, size_t LUIdx) {
  248. std::pair<RegUsesTy::iterator, bool> Pair =
  249. RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
  250. RegSortData &RSD = Pair.first->second;
  251. if (Pair.second)
  252. RegSequence.push_back(Reg);
  253. RSD.UsedByIndices.resize(std::max(RSD.UsedByIndices.size(), LUIdx + 1));
  254. RSD.UsedByIndices.set(LUIdx);
  255. }
  256. void
  257. RegUseTracker::dropRegister(const SCEV *Reg, size_t LUIdx) {
  258. RegUsesTy::iterator It = RegUsesMap.find(Reg);
  259. assert(It != RegUsesMap.end());
  260. RegSortData &RSD = It->second;
  261. assert(RSD.UsedByIndices.size() > LUIdx);
  262. RSD.UsedByIndices.reset(LUIdx);
  263. }
  264. void
  265. RegUseTracker::swapAndDropUse(size_t LUIdx, size_t LastLUIdx) {
  266. assert(LUIdx <= LastLUIdx);
  267. // Update RegUses. The data structure is not optimized for this purpose;
  268. // we must iterate through it and update each of the bit vectors.
  269. for (auto &Pair : RegUsesMap) {
  270. SmallBitVector &UsedByIndices = Pair.second.UsedByIndices;
  271. if (LUIdx < UsedByIndices.size())
  272. UsedByIndices[LUIdx] =
  273. LastLUIdx < UsedByIndices.size() ? UsedByIndices[LastLUIdx] : false;
  274. UsedByIndices.resize(std::min(UsedByIndices.size(), LastLUIdx));
  275. }
  276. }
  277. bool
  278. RegUseTracker::isRegUsedByUsesOtherThan(const SCEV *Reg, size_t LUIdx) const {
  279. RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
  280. if (I == RegUsesMap.end())
  281. return false;
  282. const SmallBitVector &UsedByIndices = I->second.UsedByIndices;
  283. int i = UsedByIndices.find_first();
  284. if (i == -1) return false;
  285. if ((size_t)i != LUIdx) return true;
  286. return UsedByIndices.find_next(i) != -1;
  287. }
  288. const SmallBitVector &RegUseTracker::getUsedByIndices(const SCEV *Reg) const {
  289. RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
  290. assert(I != RegUsesMap.end() && "Unknown register!");
  291. return I->second.UsedByIndices;
  292. }
  293. void RegUseTracker::clear() {
  294. RegUsesMap.clear();
  295. RegSequence.clear();
  296. }
  297. namespace {
  298. /// This class holds information that describes a formula for computing
  299. /// satisfying a use. It may include broken-out immediates and scaled registers.
  300. struct Formula {
  301. /// Global base address used for complex addressing.
  302. GlobalValue *BaseGV = nullptr;
  303. /// Base offset for complex addressing.
  304. int64_t BaseOffset = 0;
  305. /// Whether any complex addressing has a base register.
  306. bool HasBaseReg = false;
  307. /// The scale of any complex addressing.
  308. int64_t Scale = 0;
  309. /// The list of "base" registers for this use. When this is non-empty. The
  310. /// canonical representation of a formula is
  311. /// 1. BaseRegs.size > 1 implies ScaledReg != NULL and
  312. /// 2. ScaledReg != NULL implies Scale != 1 || !BaseRegs.empty().
  313. /// 3. The reg containing recurrent expr related with currect loop in the
  314. /// formula should be put in the ScaledReg.
  315. /// #1 enforces that the scaled register is always used when at least two
  316. /// registers are needed by the formula: e.g., reg1 + reg2 is reg1 + 1 * reg2.
  317. /// #2 enforces that 1 * reg is reg.
  318. /// #3 ensures invariant regs with respect to current loop can be combined
  319. /// together in LSR codegen.
  320. /// This invariant can be temporarily broken while building a formula.
  321. /// However, every formula inserted into the LSRInstance must be in canonical
  322. /// form.
  323. SmallVector<const SCEV *, 4> BaseRegs;
  324. /// The 'scaled' register for this use. This should be non-null when Scale is
  325. /// not zero.
  326. const SCEV *ScaledReg = nullptr;
  327. /// An additional constant offset which added near the use. This requires a
  328. /// temporary register, but the offset itself can live in an add immediate
  329. /// field rather than a register.
  330. int64_t UnfoldedOffset = 0;
  331. Formula() = default;
  332. void initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE);
  333. bool isCanonical(const Loop &L) const;
  334. void canonicalize(const Loop &L);
  335. bool unscale();
  336. bool hasZeroEnd() const;
  337. size_t getNumRegs() const;
  338. Type *getType() const;
  339. void deleteBaseReg(const SCEV *&S);
  340. bool referencesReg(const SCEV *S) const;
  341. bool hasRegsUsedByUsesOtherThan(size_t LUIdx,
  342. const RegUseTracker &RegUses) const;
  343. void print(raw_ostream &OS) const;
  344. void dump() const;
  345. };
  346. } // end anonymous namespace
  347. /// Recursion helper for initialMatch.
  348. static void DoInitialMatch(const SCEV *S, Loop *L,
  349. SmallVectorImpl<const SCEV *> &Good,
  350. SmallVectorImpl<const SCEV *> &Bad,
  351. ScalarEvolution &SE) {
  352. // Collect expressions which properly dominate the loop header.
  353. if (SE.properlyDominates(S, L->getHeader())) {
  354. Good.push_back(S);
  355. return;
  356. }
  357. // Look at add operands.
  358. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  359. for (const SCEV *S : Add->operands())
  360. DoInitialMatch(S, L, Good, Bad, SE);
  361. return;
  362. }
  363. // Look at addrec operands.
  364. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
  365. if (!AR->getStart()->isZero() && AR->isAffine()) {
  366. DoInitialMatch(AR->getStart(), L, Good, Bad, SE);
  367. DoInitialMatch(SE.getAddRecExpr(SE.getConstant(AR->getType(), 0),
  368. AR->getStepRecurrence(SE),
  369. // FIXME: AR->getNoWrapFlags()
  370. AR->getLoop(), SCEV::FlagAnyWrap),
  371. L, Good, Bad, SE);
  372. return;
  373. }
  374. // Handle a multiplication by -1 (negation) if it didn't fold.
  375. if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
  376. if (Mul->getOperand(0)->isAllOnesValue()) {
  377. SmallVector<const SCEV *, 4> Ops(drop_begin(Mul->operands()));
  378. const SCEV *NewMul = SE.getMulExpr(Ops);
  379. SmallVector<const SCEV *, 4> MyGood;
  380. SmallVector<const SCEV *, 4> MyBad;
  381. DoInitialMatch(NewMul, L, MyGood, MyBad, SE);
  382. const SCEV *NegOne = SE.getSCEV(ConstantInt::getAllOnesValue(
  383. SE.getEffectiveSCEVType(NewMul->getType())));
  384. for (const SCEV *S : MyGood)
  385. Good.push_back(SE.getMulExpr(NegOne, S));
  386. for (const SCEV *S : MyBad)
  387. Bad.push_back(SE.getMulExpr(NegOne, S));
  388. return;
  389. }
  390. // Ok, we can't do anything interesting. Just stuff the whole thing into a
  391. // register and hope for the best.
  392. Bad.push_back(S);
  393. }
  394. /// Incorporate loop-variant parts of S into this Formula, attempting to keep
  395. /// all loop-invariant and loop-computable values in a single base register.
  396. void Formula::initialMatch(const SCEV *S, Loop *L, ScalarEvolution &SE) {
  397. SmallVector<const SCEV *, 4> Good;
  398. SmallVector<const SCEV *, 4> Bad;
  399. DoInitialMatch(S, L, Good, Bad, SE);
  400. if (!Good.empty()) {
  401. const SCEV *Sum = SE.getAddExpr(Good);
  402. if (!Sum->isZero())
  403. BaseRegs.push_back(Sum);
  404. HasBaseReg = true;
  405. }
  406. if (!Bad.empty()) {
  407. const SCEV *Sum = SE.getAddExpr(Bad);
  408. if (!Sum->isZero())
  409. BaseRegs.push_back(Sum);
  410. HasBaseReg = true;
  411. }
  412. canonicalize(*L);
  413. }
  414. /// Check whether or not this formula satisfies the canonical
  415. /// representation.
  416. /// \see Formula::BaseRegs.
  417. bool Formula::isCanonical(const Loop &L) const {
  418. if (!ScaledReg)
  419. return BaseRegs.size() <= 1;
  420. if (Scale != 1)
  421. return true;
  422. if (Scale == 1 && BaseRegs.empty())
  423. return false;
  424. const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg);
  425. if (SAR && SAR->getLoop() == &L)
  426. return true;
  427. // If ScaledReg is not a recurrent expr, or it is but its loop is not current
  428. // loop, meanwhile BaseRegs contains a recurrent expr reg related with current
  429. // loop, we want to swap the reg in BaseRegs with ScaledReg.
  430. auto I = find_if(BaseRegs, [&](const SCEV *S) {
  431. return isa<const SCEVAddRecExpr>(S) &&
  432. (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
  433. });
  434. return I == BaseRegs.end();
  435. }
  436. /// Helper method to morph a formula into its canonical representation.
  437. /// \see Formula::BaseRegs.
  438. /// Every formula having more than one base register, must use the ScaledReg
  439. /// field. Otherwise, we would have to do special cases everywhere in LSR
  440. /// to treat reg1 + reg2 + ... the same way as reg1 + 1*reg2 + ...
  441. /// On the other hand, 1*reg should be canonicalized into reg.
  442. void Formula::canonicalize(const Loop &L) {
  443. if (isCanonical(L))
  444. return;
  445. if (BaseRegs.empty()) {
  446. // No base reg? Use scale reg with scale = 1 as such.
  447. assert(ScaledReg && "Expected 1*reg => reg");
  448. assert(Scale == 1 && "Expected 1*reg => reg");
  449. BaseRegs.push_back(ScaledReg);
  450. Scale = 0;
  451. ScaledReg = nullptr;
  452. return;
  453. }
  454. // Keep the invariant sum in BaseRegs and one of the variant sum in ScaledReg.
  455. if (!ScaledReg) {
  456. ScaledReg = BaseRegs.pop_back_val();
  457. Scale = 1;
  458. }
  459. // If ScaledReg is an invariant with respect to L, find the reg from
  460. // BaseRegs containing the recurrent expr related with Loop L. Swap the
  461. // reg with ScaledReg.
  462. const SCEVAddRecExpr *SAR = dyn_cast<const SCEVAddRecExpr>(ScaledReg);
  463. if (!SAR || SAR->getLoop() != &L) {
  464. auto I = find_if(BaseRegs, [&](const SCEV *S) {
  465. return isa<const SCEVAddRecExpr>(S) &&
  466. (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
  467. });
  468. if (I != BaseRegs.end())
  469. std::swap(ScaledReg, *I);
  470. }
  471. assert(isCanonical(L) && "Failed to canonicalize?");
  472. }
  473. /// Get rid of the scale in the formula.
  474. /// In other words, this method morphes reg1 + 1*reg2 into reg1 + reg2.
  475. /// \return true if it was possible to get rid of the scale, false otherwise.
  476. /// \note After this operation the formula may not be in the canonical form.
  477. bool Formula::unscale() {
  478. if (Scale != 1)
  479. return false;
  480. Scale = 0;
  481. BaseRegs.push_back(ScaledReg);
  482. ScaledReg = nullptr;
  483. return true;
  484. }
  485. bool Formula::hasZeroEnd() const {
  486. if (UnfoldedOffset || BaseOffset)
  487. return false;
  488. if (BaseRegs.size() != 1 || ScaledReg)
  489. return false;
  490. return true;
  491. }
  492. /// Return the total number of register operands used by this formula. This does
  493. /// not include register uses implied by non-constant addrec strides.
  494. size_t Formula::getNumRegs() const {
  495. return !!ScaledReg + BaseRegs.size();
  496. }
  497. /// Return the type of this formula, if it has one, or null otherwise. This type
  498. /// is meaningless except for the bit size.
  499. Type *Formula::getType() const {
  500. return !BaseRegs.empty() ? BaseRegs.front()->getType() :
  501. ScaledReg ? ScaledReg->getType() :
  502. BaseGV ? BaseGV->getType() :
  503. nullptr;
  504. }
  505. /// Delete the given base reg from the BaseRegs list.
  506. void Formula::deleteBaseReg(const SCEV *&S) {
  507. if (&S != &BaseRegs.back())
  508. std::swap(S, BaseRegs.back());
  509. BaseRegs.pop_back();
  510. }
  511. /// Test if this formula references the given register.
  512. bool Formula::referencesReg(const SCEV *S) const {
  513. return S == ScaledReg || is_contained(BaseRegs, S);
  514. }
  515. /// Test whether this formula uses registers which are used by uses other than
  516. /// the use with the given index.
  517. bool Formula::hasRegsUsedByUsesOtherThan(size_t LUIdx,
  518. const RegUseTracker &RegUses) const {
  519. if (ScaledReg)
  520. if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
  521. return true;
  522. for (const SCEV *BaseReg : BaseRegs)
  523. if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
  524. return true;
  525. return false;
  526. }
  527. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  528. void Formula::print(raw_ostream &OS) const {
  529. bool First = true;
  530. if (BaseGV) {
  531. if (!First) OS << " + "; else First = false;
  532. BaseGV->printAsOperand(OS, /*PrintType=*/false);
  533. }
  534. if (BaseOffset != 0) {
  535. if (!First) OS << " + "; else First = false;
  536. OS << BaseOffset;
  537. }
  538. for (const SCEV *BaseReg : BaseRegs) {
  539. if (!First) OS << " + "; else First = false;
  540. OS << "reg(" << *BaseReg << ')';
  541. }
  542. if (HasBaseReg && BaseRegs.empty()) {
  543. if (!First) OS << " + "; else First = false;
  544. OS << "**error: HasBaseReg**";
  545. } else if (!HasBaseReg && !BaseRegs.empty()) {
  546. if (!First) OS << " + "; else First = false;
  547. OS << "**error: !HasBaseReg**";
  548. }
  549. if (Scale != 0) {
  550. if (!First) OS << " + "; else First = false;
  551. OS << Scale << "*reg(";
  552. if (ScaledReg)
  553. OS << *ScaledReg;
  554. else
  555. OS << "<unknown>";
  556. OS << ')';
  557. }
  558. if (UnfoldedOffset != 0) {
  559. if (!First) OS << " + ";
  560. OS << "imm(" << UnfoldedOffset << ')';
  561. }
  562. }
  563. LLVM_DUMP_METHOD void Formula::dump() const {
  564. print(errs()); errs() << '\n';
  565. }
  566. #endif
  567. /// Return true if the given addrec can be sign-extended without changing its
  568. /// value.
  569. static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
  570. Type *WideTy =
  571. IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(AR->getType()) + 1);
  572. return isa<SCEVAddRecExpr>(SE.getSignExtendExpr(AR, WideTy));
  573. }
  574. /// Return true if the given add can be sign-extended without changing its
  575. /// value.
  576. static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE) {
  577. Type *WideTy =
  578. IntegerType::get(SE.getContext(), SE.getTypeSizeInBits(A->getType()) + 1);
  579. return isa<SCEVAddExpr>(SE.getSignExtendExpr(A, WideTy));
  580. }
  581. /// Return true if the given mul can be sign-extended without changing its
  582. /// value.
  583. static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE) {
  584. Type *WideTy =
  585. IntegerType::get(SE.getContext(),
  586. SE.getTypeSizeInBits(M->getType()) * M->getNumOperands());
  587. return isa<SCEVMulExpr>(SE.getSignExtendExpr(M, WideTy));
  588. }
  589. /// Return an expression for LHS /s RHS, if it can be determined and if the
  590. /// remainder is known to be zero, or null otherwise. If IgnoreSignificantBits
  591. /// is true, expressions like (X * Y) /s Y are simplified to X, ignoring that
  592. /// the multiplication may overflow, which is useful when the result will be
  593. /// used in a context where the most significant bits are ignored.
  594. static const SCEV *getExactSDiv(const SCEV *LHS, const SCEV *RHS,
  595. ScalarEvolution &SE,
  596. bool IgnoreSignificantBits = false) {
  597. // Handle the trivial case, which works for any SCEV type.
  598. if (LHS == RHS)
  599. return SE.getConstant(LHS->getType(), 1);
  600. // Handle a few RHS special cases.
  601. const SCEVConstant *RC = dyn_cast<SCEVConstant>(RHS);
  602. if (RC) {
  603. const APInt &RA = RC->getAPInt();
  604. // Handle x /s -1 as x * -1, to give ScalarEvolution a chance to do
  605. // some folding.
  606. if (RA.isAllOnes()) {
  607. if (LHS->getType()->isPointerTy())
  608. return nullptr;
  609. return SE.getMulExpr(LHS, RC);
  610. }
  611. // Handle x /s 1 as x.
  612. if (RA == 1)
  613. return LHS;
  614. }
  615. // Check for a division of a constant by a constant.
  616. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(LHS)) {
  617. if (!RC)
  618. return nullptr;
  619. const APInt &LA = C->getAPInt();
  620. const APInt &RA = RC->getAPInt();
  621. if (LA.srem(RA) != 0)
  622. return nullptr;
  623. return SE.getConstant(LA.sdiv(RA));
  624. }
  625. // Distribute the sdiv over addrec operands, if the addrec doesn't overflow.
  626. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHS)) {
  627. if ((IgnoreSignificantBits || isAddRecSExtable(AR, SE)) && AR->isAffine()) {
  628. const SCEV *Step = getExactSDiv(AR->getStepRecurrence(SE), RHS, SE,
  629. IgnoreSignificantBits);
  630. if (!Step) return nullptr;
  631. const SCEV *Start = getExactSDiv(AR->getStart(), RHS, SE,
  632. IgnoreSignificantBits);
  633. if (!Start) return nullptr;
  634. // FlagNW is independent of the start value, step direction, and is
  635. // preserved with smaller magnitude steps.
  636. // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
  637. return SE.getAddRecExpr(Start, Step, AR->getLoop(), SCEV::FlagAnyWrap);
  638. }
  639. return nullptr;
  640. }
  641. // Distribute the sdiv over add operands, if the add doesn't overflow.
  642. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(LHS)) {
  643. if (IgnoreSignificantBits || isAddSExtable(Add, SE)) {
  644. SmallVector<const SCEV *, 8> Ops;
  645. for (const SCEV *S : Add->operands()) {
  646. const SCEV *Op = getExactSDiv(S, RHS, SE, IgnoreSignificantBits);
  647. if (!Op) return nullptr;
  648. Ops.push_back(Op);
  649. }
  650. return SE.getAddExpr(Ops);
  651. }
  652. return nullptr;
  653. }
  654. // Check for a multiply operand that we can pull RHS out of.
  655. if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
  656. if (IgnoreSignificantBits || isMulSExtable(Mul, SE)) {
  657. // Handle special case C1*X*Y /s C2*X*Y.
  658. if (const SCEVMulExpr *MulRHS = dyn_cast<SCEVMulExpr>(RHS)) {
  659. if (IgnoreSignificantBits || isMulSExtable(MulRHS, SE)) {
  660. const SCEVConstant *LC = dyn_cast<SCEVConstant>(Mul->getOperand(0));
  661. const SCEVConstant *RC =
  662. dyn_cast<SCEVConstant>(MulRHS->getOperand(0));
  663. if (LC && RC) {
  664. SmallVector<const SCEV *, 4> LOps(drop_begin(Mul->operands()));
  665. SmallVector<const SCEV *, 4> ROps(drop_begin(MulRHS->operands()));
  666. if (LOps == ROps)
  667. return getExactSDiv(LC, RC, SE, IgnoreSignificantBits);
  668. }
  669. }
  670. }
  671. SmallVector<const SCEV *, 4> Ops;
  672. bool Found = false;
  673. for (const SCEV *S : Mul->operands()) {
  674. if (!Found)
  675. if (const SCEV *Q = getExactSDiv(S, RHS, SE,
  676. IgnoreSignificantBits)) {
  677. S = Q;
  678. Found = true;
  679. }
  680. Ops.push_back(S);
  681. }
  682. return Found ? SE.getMulExpr(Ops) : nullptr;
  683. }
  684. return nullptr;
  685. }
  686. // Otherwise we don't know.
  687. return nullptr;
  688. }
  689. /// If S involves the addition of a constant integer value, return that integer
  690. /// value, and mutate S to point to a new SCEV with that value excluded.
  691. static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE) {
  692. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
  693. if (C->getAPInt().getMinSignedBits() <= 64) {
  694. S = SE.getConstant(C->getType(), 0);
  695. return C->getValue()->getSExtValue();
  696. }
  697. } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  698. SmallVector<const SCEV *, 8> NewOps(Add->operands());
  699. int64_t Result = ExtractImmediate(NewOps.front(), SE);
  700. if (Result != 0)
  701. S = SE.getAddExpr(NewOps);
  702. return Result;
  703. } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  704. SmallVector<const SCEV *, 8> NewOps(AR->operands());
  705. int64_t Result = ExtractImmediate(NewOps.front(), SE);
  706. if (Result != 0)
  707. S = SE.getAddRecExpr(NewOps, AR->getLoop(),
  708. // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
  709. SCEV::FlagAnyWrap);
  710. return Result;
  711. }
  712. return 0;
  713. }
  714. /// If S involves the addition of a GlobalValue address, return that symbol, and
  715. /// mutate S to point to a new SCEV with that value excluded.
  716. static GlobalValue *ExtractSymbol(const SCEV *&S, ScalarEvolution &SE) {
  717. if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
  718. if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
  719. S = SE.getConstant(GV->getType(), 0);
  720. return GV;
  721. }
  722. } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  723. SmallVector<const SCEV *, 8> NewOps(Add->operands());
  724. GlobalValue *Result = ExtractSymbol(NewOps.back(), SE);
  725. if (Result)
  726. S = SE.getAddExpr(NewOps);
  727. return Result;
  728. } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  729. SmallVector<const SCEV *, 8> NewOps(AR->operands());
  730. GlobalValue *Result = ExtractSymbol(NewOps.front(), SE);
  731. if (Result)
  732. S = SE.getAddRecExpr(NewOps, AR->getLoop(),
  733. // FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
  734. SCEV::FlagAnyWrap);
  735. return Result;
  736. }
  737. return nullptr;
  738. }
  739. /// Returns true if the specified instruction is using the specified value as an
  740. /// address.
  741. static bool isAddressUse(const TargetTransformInfo &TTI,
  742. Instruction *Inst, Value *OperandVal) {
  743. bool isAddress = isa<LoadInst>(Inst);
  744. if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  745. if (SI->getPointerOperand() == OperandVal)
  746. isAddress = true;
  747. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
  748. // Addressing modes can also be folded into prefetches and a variety
  749. // of intrinsics.
  750. switch (II->getIntrinsicID()) {
  751. case Intrinsic::memset:
  752. case Intrinsic::prefetch:
  753. case Intrinsic::masked_load:
  754. if (II->getArgOperand(0) == OperandVal)
  755. isAddress = true;
  756. break;
  757. case Intrinsic::masked_store:
  758. if (II->getArgOperand(1) == OperandVal)
  759. isAddress = true;
  760. break;
  761. case Intrinsic::memmove:
  762. case Intrinsic::memcpy:
  763. if (II->getArgOperand(0) == OperandVal ||
  764. II->getArgOperand(1) == OperandVal)
  765. isAddress = true;
  766. break;
  767. default: {
  768. MemIntrinsicInfo IntrInfo;
  769. if (TTI.getTgtMemIntrinsic(II, IntrInfo)) {
  770. if (IntrInfo.PtrVal == OperandVal)
  771. isAddress = true;
  772. }
  773. }
  774. }
  775. } else if (AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
  776. if (RMW->getPointerOperand() == OperandVal)
  777. isAddress = true;
  778. } else if (AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
  779. if (CmpX->getPointerOperand() == OperandVal)
  780. isAddress = true;
  781. }
  782. return isAddress;
  783. }
  784. /// Return the type of the memory being accessed.
  785. static MemAccessTy getAccessType(const TargetTransformInfo &TTI,
  786. Instruction *Inst, Value *OperandVal) {
  787. MemAccessTy AccessTy(Inst->getType(), MemAccessTy::UnknownAddressSpace);
  788. if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
  789. AccessTy.MemTy = SI->getOperand(0)->getType();
  790. AccessTy.AddrSpace = SI->getPointerAddressSpace();
  791. } else if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
  792. AccessTy.AddrSpace = LI->getPointerAddressSpace();
  793. } else if (const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
  794. AccessTy.AddrSpace = RMW->getPointerAddressSpace();
  795. } else if (const AtomicCmpXchgInst *CmpX = dyn_cast<AtomicCmpXchgInst>(Inst)) {
  796. AccessTy.AddrSpace = CmpX->getPointerAddressSpace();
  797. } else if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
  798. switch (II->getIntrinsicID()) {
  799. case Intrinsic::prefetch:
  800. case Intrinsic::memset:
  801. AccessTy.AddrSpace = II->getArgOperand(0)->getType()->getPointerAddressSpace();
  802. AccessTy.MemTy = OperandVal->getType();
  803. break;
  804. case Intrinsic::memmove:
  805. case Intrinsic::memcpy:
  806. AccessTy.AddrSpace = OperandVal->getType()->getPointerAddressSpace();
  807. AccessTy.MemTy = OperandVal->getType();
  808. break;
  809. case Intrinsic::masked_load:
  810. AccessTy.AddrSpace =
  811. II->getArgOperand(0)->getType()->getPointerAddressSpace();
  812. break;
  813. case Intrinsic::masked_store:
  814. AccessTy.MemTy = II->getOperand(0)->getType();
  815. AccessTy.AddrSpace =
  816. II->getArgOperand(1)->getType()->getPointerAddressSpace();
  817. break;
  818. default: {
  819. MemIntrinsicInfo IntrInfo;
  820. if (TTI.getTgtMemIntrinsic(II, IntrInfo) && IntrInfo.PtrVal) {
  821. AccessTy.AddrSpace
  822. = IntrInfo.PtrVal->getType()->getPointerAddressSpace();
  823. }
  824. break;
  825. }
  826. }
  827. }
  828. // All pointers have the same requirements, so canonicalize them to an
  829. // arbitrary pointer type to minimize variation.
  830. if (PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy))
  831. AccessTy.MemTy = PointerType::get(IntegerType::get(PTy->getContext(), 1),
  832. PTy->getAddressSpace());
  833. return AccessTy;
  834. }
  835. /// Return true if this AddRec is already a phi in its loop.
  836. static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE) {
  837. for (PHINode &PN : AR->getLoop()->getHeader()->phis()) {
  838. if (SE.isSCEVable(PN.getType()) &&
  839. (SE.getEffectiveSCEVType(PN.getType()) ==
  840. SE.getEffectiveSCEVType(AR->getType())) &&
  841. SE.getSCEV(&PN) == AR)
  842. return true;
  843. }
  844. return false;
  845. }
  846. /// Check if expanding this expression is likely to incur significant cost. This
  847. /// is tricky because SCEV doesn't track which expressions are actually computed
  848. /// by the current IR.
  849. ///
  850. /// We currently allow expansion of IV increments that involve adds,
  851. /// multiplication by constants, and AddRecs from existing phis.
  852. ///
  853. /// TODO: Allow UDivExpr if we can find an existing IV increment that is an
  854. /// obvious multiple of the UDivExpr.
  855. static bool isHighCostExpansion(const SCEV *S,
  856. SmallPtrSetImpl<const SCEV*> &Processed,
  857. ScalarEvolution &SE) {
  858. // Zero/One operand expressions
  859. switch (S->getSCEVType()) {
  860. case scUnknown:
  861. case scConstant:
  862. return false;
  863. case scTruncate:
  864. return isHighCostExpansion(cast<SCEVTruncateExpr>(S)->getOperand(),
  865. Processed, SE);
  866. case scZeroExtend:
  867. return isHighCostExpansion(cast<SCEVZeroExtendExpr>(S)->getOperand(),
  868. Processed, SE);
  869. case scSignExtend:
  870. return isHighCostExpansion(cast<SCEVSignExtendExpr>(S)->getOperand(),
  871. Processed, SE);
  872. default:
  873. break;
  874. }
  875. if (!Processed.insert(S).second)
  876. return false;
  877. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  878. for (const SCEV *S : Add->operands()) {
  879. if (isHighCostExpansion(S, Processed, SE))
  880. return true;
  881. }
  882. return false;
  883. }
  884. if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
  885. if (Mul->getNumOperands() == 2) {
  886. // Multiplication by a constant is ok
  887. if (isa<SCEVConstant>(Mul->getOperand(0)))
  888. return isHighCostExpansion(Mul->getOperand(1), Processed, SE);
  889. // If we have the value of one operand, check if an existing
  890. // multiplication already generates this expression.
  891. if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
  892. Value *UVal = U->getValue();
  893. for (User *UR : UVal->users()) {
  894. // If U is a constant, it may be used by a ConstantExpr.
  895. Instruction *UI = dyn_cast<Instruction>(UR);
  896. if (UI && UI->getOpcode() == Instruction::Mul &&
  897. SE.isSCEVable(UI->getType())) {
  898. return SE.getSCEV(UI) == Mul;
  899. }
  900. }
  901. }
  902. }
  903. }
  904. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  905. if (isExistingPhi(AR, SE))
  906. return false;
  907. }
  908. // Fow now, consider any other type of expression (div/mul/min/max) high cost.
  909. return true;
  910. }
  911. namespace {
  912. class LSRUse;
  913. } // end anonymous namespace
  914. /// Check if the addressing mode defined by \p F is completely
  915. /// folded in \p LU at isel time.
  916. /// This includes address-mode folding and special icmp tricks.
  917. /// This function returns true if \p LU can accommodate what \p F
  918. /// defines and up to 1 base + 1 scaled + offset.
  919. /// In other words, if \p F has several base registers, this function may
  920. /// still return true. Therefore, users still need to account for
  921. /// additional base registers and/or unfolded offsets to derive an
  922. /// accurate cost model.
  923. static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
  924. const LSRUse &LU, const Formula &F);
  925. // Get the cost of the scaling factor used in F for LU.
  926. static InstructionCost getScalingFactorCost(const TargetTransformInfo &TTI,
  927. const LSRUse &LU, const Formula &F,
  928. const Loop &L);
  929. namespace {
  930. /// This class is used to measure and compare candidate formulae.
  931. class Cost {
  932. const Loop *L = nullptr;
  933. ScalarEvolution *SE = nullptr;
  934. const TargetTransformInfo *TTI = nullptr;
  935. TargetTransformInfo::LSRCost C;
  936. TTI::AddressingModeKind AMK = TTI::AMK_None;
  937. public:
  938. Cost() = delete;
  939. Cost(const Loop *L, ScalarEvolution &SE, const TargetTransformInfo &TTI,
  940. TTI::AddressingModeKind AMK) :
  941. L(L), SE(&SE), TTI(&TTI), AMK(AMK) {
  942. C.Insns = 0;
  943. C.NumRegs = 0;
  944. C.AddRecCost = 0;
  945. C.NumIVMuls = 0;
  946. C.NumBaseAdds = 0;
  947. C.ImmCost = 0;
  948. C.SetupCost = 0;
  949. C.ScaleCost = 0;
  950. }
  951. bool isLess(Cost &Other);
  952. void Lose();
  953. #ifndef NDEBUG
  954. // Once any of the metrics loses, they must all remain losers.
  955. bool isValid() {
  956. return ((C.Insns | C.NumRegs | C.AddRecCost | C.NumIVMuls | C.NumBaseAdds
  957. | C.ImmCost | C.SetupCost | C.ScaleCost) != ~0u)
  958. || ((C.Insns & C.NumRegs & C.AddRecCost & C.NumIVMuls & C.NumBaseAdds
  959. & C.ImmCost & C.SetupCost & C.ScaleCost) == ~0u);
  960. }
  961. #endif
  962. bool isLoser() {
  963. assert(isValid() && "invalid cost");
  964. return C.NumRegs == ~0u;
  965. }
  966. void RateFormula(const Formula &F,
  967. SmallPtrSetImpl<const SCEV *> &Regs,
  968. const DenseSet<const SCEV *> &VisitedRegs,
  969. const LSRUse &LU,
  970. SmallPtrSetImpl<const SCEV *> *LoserRegs = nullptr);
  971. void print(raw_ostream &OS) const;
  972. void dump() const;
  973. private:
  974. void RateRegister(const Formula &F, const SCEV *Reg,
  975. SmallPtrSetImpl<const SCEV *> &Regs);
  976. void RatePrimaryRegister(const Formula &F, const SCEV *Reg,
  977. SmallPtrSetImpl<const SCEV *> &Regs,
  978. SmallPtrSetImpl<const SCEV *> *LoserRegs);
  979. };
  980. /// An operand value in an instruction which is to be replaced with some
  981. /// equivalent, possibly strength-reduced, replacement.
  982. struct LSRFixup {
  983. /// The instruction which will be updated.
  984. Instruction *UserInst = nullptr;
  985. /// The operand of the instruction which will be replaced. The operand may be
  986. /// used more than once; every instance will be replaced.
  987. Value *OperandValToReplace = nullptr;
  988. /// If this user is to use the post-incremented value of an induction
  989. /// variable, this set is non-empty and holds the loops associated with the
  990. /// induction variable.
  991. PostIncLoopSet PostIncLoops;
  992. /// A constant offset to be added to the LSRUse expression. This allows
  993. /// multiple fixups to share the same LSRUse with different offsets, for
  994. /// example in an unrolled loop.
  995. int64_t Offset = 0;
  996. LSRFixup() = default;
  997. bool isUseFullyOutsideLoop(const Loop *L) const;
  998. void print(raw_ostream &OS) const;
  999. void dump() const;
  1000. };
  1001. /// A DenseMapInfo implementation for holding DenseMaps and DenseSets of sorted
  1002. /// SmallVectors of const SCEV*.
  1003. struct UniquifierDenseMapInfo {
  1004. static SmallVector<const SCEV *, 4> getEmptyKey() {
  1005. SmallVector<const SCEV *, 4> V;
  1006. V.push_back(reinterpret_cast<const SCEV *>(-1));
  1007. return V;
  1008. }
  1009. static SmallVector<const SCEV *, 4> getTombstoneKey() {
  1010. SmallVector<const SCEV *, 4> V;
  1011. V.push_back(reinterpret_cast<const SCEV *>(-2));
  1012. return V;
  1013. }
  1014. static unsigned getHashValue(const SmallVector<const SCEV *, 4> &V) {
  1015. return static_cast<unsigned>(hash_combine_range(V.begin(), V.end()));
  1016. }
  1017. static bool isEqual(const SmallVector<const SCEV *, 4> &LHS,
  1018. const SmallVector<const SCEV *, 4> &RHS) {
  1019. return LHS == RHS;
  1020. }
  1021. };
  1022. /// This class holds the state that LSR keeps for each use in IVUsers, as well
  1023. /// as uses invented by LSR itself. It includes information about what kinds of
  1024. /// things can be folded into the user, information about the user itself, and
  1025. /// information about how the use may be satisfied. TODO: Represent multiple
  1026. /// users of the same expression in common?
  1027. class LSRUse {
  1028. DenseSet<SmallVector<const SCEV *, 4>, UniquifierDenseMapInfo> Uniquifier;
  1029. public:
  1030. /// An enum for a kind of use, indicating what types of scaled and immediate
  1031. /// operands it might support.
  1032. enum KindType {
  1033. Basic, ///< A normal use, with no folding.
  1034. Special, ///< A special case of basic, allowing -1 scales.
  1035. Address, ///< An address use; folding according to TargetLowering
  1036. ICmpZero ///< An equality icmp with both operands folded into one.
  1037. // TODO: Add a generic icmp too?
  1038. };
  1039. using SCEVUseKindPair = PointerIntPair<const SCEV *, 2, KindType>;
  1040. KindType Kind;
  1041. MemAccessTy AccessTy;
  1042. /// The list of operands which are to be replaced.
  1043. SmallVector<LSRFixup, 8> Fixups;
  1044. /// Keep track of the min and max offsets of the fixups.
  1045. int64_t MinOffset = std::numeric_limits<int64_t>::max();
  1046. int64_t MaxOffset = std::numeric_limits<int64_t>::min();
  1047. /// This records whether all of the fixups using this LSRUse are outside of
  1048. /// the loop, in which case some special-case heuristics may be used.
  1049. bool AllFixupsOutsideLoop = true;
  1050. /// RigidFormula is set to true to guarantee that this use will be associated
  1051. /// with a single formula--the one that initially matched. Some SCEV
  1052. /// expressions cannot be expanded. This allows LSR to consider the registers
  1053. /// used by those expressions without the need to expand them later after
  1054. /// changing the formula.
  1055. bool RigidFormula = false;
  1056. /// This records the widest use type for any fixup using this
  1057. /// LSRUse. FindUseWithSimilarFormula can't consider uses with different max
  1058. /// fixup widths to be equivalent, because the narrower one may be relying on
  1059. /// the implicit truncation to truncate away bogus bits.
  1060. Type *WidestFixupType = nullptr;
  1061. /// A list of ways to build a value that can satisfy this user. After the
  1062. /// list is populated, one of these is selected heuristically and used to
  1063. /// formulate a replacement for OperandValToReplace in UserInst.
  1064. SmallVector<Formula, 12> Formulae;
  1065. /// The set of register candidates used by all formulae in this LSRUse.
  1066. SmallPtrSet<const SCEV *, 4> Regs;
  1067. LSRUse(KindType K, MemAccessTy AT) : Kind(K), AccessTy(AT) {}
  1068. LSRFixup &getNewFixup() {
  1069. Fixups.push_back(LSRFixup());
  1070. return Fixups.back();
  1071. }
  1072. void pushFixup(LSRFixup &f) {
  1073. Fixups.push_back(f);
  1074. if (f.Offset > MaxOffset)
  1075. MaxOffset = f.Offset;
  1076. if (f.Offset < MinOffset)
  1077. MinOffset = f.Offset;
  1078. }
  1079. bool HasFormulaWithSameRegs(const Formula &F) const;
  1080. float getNotSelectedProbability(const SCEV *Reg) const;
  1081. bool InsertFormula(const Formula &F, const Loop &L);
  1082. void DeleteFormula(Formula &F);
  1083. void RecomputeRegs(size_t LUIdx, RegUseTracker &Reguses);
  1084. void print(raw_ostream &OS) const;
  1085. void dump() const;
  1086. };
  1087. } // end anonymous namespace
  1088. static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
  1089. LSRUse::KindType Kind, MemAccessTy AccessTy,
  1090. GlobalValue *BaseGV, int64_t BaseOffset,
  1091. bool HasBaseReg, int64_t Scale,
  1092. Instruction *Fixup = nullptr);
  1093. static unsigned getSetupCost(const SCEV *Reg, unsigned Depth) {
  1094. if (isa<SCEVUnknown>(Reg) || isa<SCEVConstant>(Reg))
  1095. return 1;
  1096. if (Depth == 0)
  1097. return 0;
  1098. if (const auto *S = dyn_cast<SCEVAddRecExpr>(Reg))
  1099. return getSetupCost(S->getStart(), Depth - 1);
  1100. if (auto S = dyn_cast<SCEVIntegralCastExpr>(Reg))
  1101. return getSetupCost(S->getOperand(), Depth - 1);
  1102. if (auto S = dyn_cast<SCEVNAryExpr>(Reg))
  1103. return std::accumulate(S->op_begin(), S->op_end(), 0,
  1104. [&](unsigned i, const SCEV *Reg) {
  1105. return i + getSetupCost(Reg, Depth - 1);
  1106. });
  1107. if (auto S = dyn_cast<SCEVUDivExpr>(Reg))
  1108. return getSetupCost(S->getLHS(), Depth - 1) +
  1109. getSetupCost(S->getRHS(), Depth - 1);
  1110. return 0;
  1111. }
  1112. /// Tally up interesting quantities from the given register.
  1113. void Cost::RateRegister(const Formula &F, const SCEV *Reg,
  1114. SmallPtrSetImpl<const SCEV *> &Regs) {
  1115. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Reg)) {
  1116. // If this is an addrec for another loop, it should be an invariant
  1117. // with respect to L since L is the innermost loop (at least
  1118. // for now LSR only handles innermost loops).
  1119. if (AR->getLoop() != L) {
  1120. // If the AddRec exists, consider it's register free and leave it alone.
  1121. if (isExistingPhi(AR, *SE) && AMK != TTI::AMK_PostIndexed)
  1122. return;
  1123. // It is bad to allow LSR for current loop to add induction variables
  1124. // for its sibling loops.
  1125. if (!AR->getLoop()->contains(L)) {
  1126. Lose();
  1127. return;
  1128. }
  1129. // Otherwise, it will be an invariant with respect to Loop L.
  1130. ++C.NumRegs;
  1131. return;
  1132. }
  1133. unsigned LoopCost = 1;
  1134. if (TTI->isIndexedLoadLegal(TTI->MIM_PostInc, AR->getType()) ||
  1135. TTI->isIndexedStoreLegal(TTI->MIM_PostInc, AR->getType())) {
  1136. // If the step size matches the base offset, we could use pre-indexed
  1137. // addressing.
  1138. if (AMK == TTI::AMK_PreIndexed) {
  1139. if (auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)))
  1140. if (Step->getAPInt() == F.BaseOffset)
  1141. LoopCost = 0;
  1142. } else if (AMK == TTI::AMK_PostIndexed) {
  1143. const SCEV *LoopStep = AR->getStepRecurrence(*SE);
  1144. if (isa<SCEVConstant>(LoopStep)) {
  1145. const SCEV *LoopStart = AR->getStart();
  1146. if (!isa<SCEVConstant>(LoopStart) &&
  1147. SE->isLoopInvariant(LoopStart, L))
  1148. LoopCost = 0;
  1149. }
  1150. }
  1151. }
  1152. C.AddRecCost += LoopCost;
  1153. // Add the step value register, if it needs one.
  1154. // TODO: The non-affine case isn't precisely modeled here.
  1155. if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
  1156. if (!Regs.count(AR->getOperand(1))) {
  1157. RateRegister(F, AR->getOperand(1), Regs);
  1158. if (isLoser())
  1159. return;
  1160. }
  1161. }
  1162. }
  1163. ++C.NumRegs;
  1164. // Rough heuristic; favor registers which don't require extra setup
  1165. // instructions in the preheader.
  1166. C.SetupCost += getSetupCost(Reg, SetupCostDepthLimit);
  1167. // Ensure we don't, even with the recusion limit, produce invalid costs.
  1168. C.SetupCost = std::min<unsigned>(C.SetupCost, 1 << 16);
  1169. C.NumIVMuls += isa<SCEVMulExpr>(Reg) &&
  1170. SE->hasComputableLoopEvolution(Reg, L);
  1171. }
  1172. /// Record this register in the set. If we haven't seen it before, rate
  1173. /// it. Optional LoserRegs provides a way to declare any formula that refers to
  1174. /// one of those regs an instant loser.
  1175. void Cost::RatePrimaryRegister(const Formula &F, const SCEV *Reg,
  1176. SmallPtrSetImpl<const SCEV *> &Regs,
  1177. SmallPtrSetImpl<const SCEV *> *LoserRegs) {
  1178. if (LoserRegs && LoserRegs->count(Reg)) {
  1179. Lose();
  1180. return;
  1181. }
  1182. if (Regs.insert(Reg).second) {
  1183. RateRegister(F, Reg, Regs);
  1184. if (LoserRegs && isLoser())
  1185. LoserRegs->insert(Reg);
  1186. }
  1187. }
  1188. void Cost::RateFormula(const Formula &F,
  1189. SmallPtrSetImpl<const SCEV *> &Regs,
  1190. const DenseSet<const SCEV *> &VisitedRegs,
  1191. const LSRUse &LU,
  1192. SmallPtrSetImpl<const SCEV *> *LoserRegs) {
  1193. assert(F.isCanonical(*L) && "Cost is accurate only for canonical formula");
  1194. // Tally up the registers.
  1195. unsigned PrevAddRecCost = C.AddRecCost;
  1196. unsigned PrevNumRegs = C.NumRegs;
  1197. unsigned PrevNumBaseAdds = C.NumBaseAdds;
  1198. if (const SCEV *ScaledReg = F.ScaledReg) {
  1199. if (VisitedRegs.count(ScaledReg)) {
  1200. Lose();
  1201. return;
  1202. }
  1203. RatePrimaryRegister(F, ScaledReg, Regs, LoserRegs);
  1204. if (isLoser())
  1205. return;
  1206. }
  1207. for (const SCEV *BaseReg : F.BaseRegs) {
  1208. if (VisitedRegs.count(BaseReg)) {
  1209. Lose();
  1210. return;
  1211. }
  1212. RatePrimaryRegister(F, BaseReg, Regs, LoserRegs);
  1213. if (isLoser())
  1214. return;
  1215. }
  1216. // Determine how many (unfolded) adds we'll need inside the loop.
  1217. size_t NumBaseParts = F.getNumRegs();
  1218. if (NumBaseParts > 1)
  1219. // Do not count the base and a possible second register if the target
  1220. // allows to fold 2 registers.
  1221. C.NumBaseAdds +=
  1222. NumBaseParts - (1 + (F.Scale && isAMCompletelyFolded(*TTI, LU, F)));
  1223. C.NumBaseAdds += (F.UnfoldedOffset != 0);
  1224. // Accumulate non-free scaling amounts.
  1225. C.ScaleCost += *getScalingFactorCost(*TTI, LU, F, *L).getValue();
  1226. // Tally up the non-zero immediates.
  1227. for (const LSRFixup &Fixup : LU.Fixups) {
  1228. int64_t O = Fixup.Offset;
  1229. int64_t Offset = (uint64_t)O + F.BaseOffset;
  1230. if (F.BaseGV)
  1231. C.ImmCost += 64; // Handle symbolic values conservatively.
  1232. // TODO: This should probably be the pointer size.
  1233. else if (Offset != 0)
  1234. C.ImmCost += APInt(64, Offset, true).getMinSignedBits();
  1235. // Check with target if this offset with this instruction is
  1236. // specifically not supported.
  1237. if (LU.Kind == LSRUse::Address && Offset != 0 &&
  1238. !isAMCompletelyFolded(*TTI, LSRUse::Address, LU.AccessTy, F.BaseGV,
  1239. Offset, F.HasBaseReg, F.Scale, Fixup.UserInst))
  1240. C.NumBaseAdds++;
  1241. }
  1242. // If we don't count instruction cost exit here.
  1243. if (!InsnsCost) {
  1244. assert(isValid() && "invalid cost");
  1245. return;
  1246. }
  1247. // Treat every new register that exceeds TTI.getNumberOfRegisters() - 1 as
  1248. // additional instruction (at least fill).
  1249. // TODO: Need distinguish register class?
  1250. unsigned TTIRegNum = TTI->getNumberOfRegisters(
  1251. TTI->getRegisterClassForType(false, F.getType())) - 1;
  1252. if (C.NumRegs > TTIRegNum) {
  1253. // Cost already exceeded TTIRegNum, then only newly added register can add
  1254. // new instructions.
  1255. if (PrevNumRegs > TTIRegNum)
  1256. C.Insns += (C.NumRegs - PrevNumRegs);
  1257. else
  1258. C.Insns += (C.NumRegs - TTIRegNum);
  1259. }
  1260. // If ICmpZero formula ends with not 0, it could not be replaced by
  1261. // just add or sub. We'll need to compare final result of AddRec.
  1262. // That means we'll need an additional instruction. But if the target can
  1263. // macro-fuse a compare with a branch, don't count this extra instruction.
  1264. // For -10 + {0, +, 1}:
  1265. // i = i + 1;
  1266. // cmp i, 10
  1267. //
  1268. // For {-10, +, 1}:
  1269. // i = i + 1;
  1270. if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd() &&
  1271. !TTI->canMacroFuseCmp())
  1272. C.Insns++;
  1273. // Each new AddRec adds 1 instruction to calculation.
  1274. C.Insns += (C.AddRecCost - PrevAddRecCost);
  1275. // BaseAdds adds instructions for unfolded registers.
  1276. if (LU.Kind != LSRUse::ICmpZero)
  1277. C.Insns += C.NumBaseAdds - PrevNumBaseAdds;
  1278. assert(isValid() && "invalid cost");
  1279. }
  1280. /// Set this cost to a losing value.
  1281. void Cost::Lose() {
  1282. C.Insns = std::numeric_limits<unsigned>::max();
  1283. C.NumRegs = std::numeric_limits<unsigned>::max();
  1284. C.AddRecCost = std::numeric_limits<unsigned>::max();
  1285. C.NumIVMuls = std::numeric_limits<unsigned>::max();
  1286. C.NumBaseAdds = std::numeric_limits<unsigned>::max();
  1287. C.ImmCost = std::numeric_limits<unsigned>::max();
  1288. C.SetupCost = std::numeric_limits<unsigned>::max();
  1289. C.ScaleCost = std::numeric_limits<unsigned>::max();
  1290. }
  1291. /// Choose the lower cost.
  1292. bool Cost::isLess(Cost &Other) {
  1293. if (InsnsCost.getNumOccurrences() > 0 && InsnsCost &&
  1294. C.Insns != Other.C.Insns)
  1295. return C.Insns < Other.C.Insns;
  1296. return TTI->isLSRCostLess(C, Other.C);
  1297. }
  1298. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1299. void Cost::print(raw_ostream &OS) const {
  1300. if (InsnsCost)
  1301. OS << C.Insns << " instruction" << (C.Insns == 1 ? " " : "s ");
  1302. OS << C.NumRegs << " reg" << (C.NumRegs == 1 ? "" : "s");
  1303. if (C.AddRecCost != 0)
  1304. OS << ", with addrec cost " << C.AddRecCost;
  1305. if (C.NumIVMuls != 0)
  1306. OS << ", plus " << C.NumIVMuls << " IV mul"
  1307. << (C.NumIVMuls == 1 ? "" : "s");
  1308. if (C.NumBaseAdds != 0)
  1309. OS << ", plus " << C.NumBaseAdds << " base add"
  1310. << (C.NumBaseAdds == 1 ? "" : "s");
  1311. if (C.ScaleCost != 0)
  1312. OS << ", plus " << C.ScaleCost << " scale cost";
  1313. if (C.ImmCost != 0)
  1314. OS << ", plus " << C.ImmCost << " imm cost";
  1315. if (C.SetupCost != 0)
  1316. OS << ", plus " << C.SetupCost << " setup cost";
  1317. }
  1318. LLVM_DUMP_METHOD void Cost::dump() const {
  1319. print(errs()); errs() << '\n';
  1320. }
  1321. #endif
  1322. /// Test whether this fixup always uses its value outside of the given loop.
  1323. bool LSRFixup::isUseFullyOutsideLoop(const Loop *L) const {
  1324. // PHI nodes use their value in their incoming blocks.
  1325. if (const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
  1326. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  1327. if (PN->getIncomingValue(i) == OperandValToReplace &&
  1328. L->contains(PN->getIncomingBlock(i)))
  1329. return false;
  1330. return true;
  1331. }
  1332. return !L->contains(UserInst);
  1333. }
  1334. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1335. void LSRFixup::print(raw_ostream &OS) const {
  1336. OS << "UserInst=";
  1337. // Store is common and interesting enough to be worth special-casing.
  1338. if (StoreInst *Store = dyn_cast<StoreInst>(UserInst)) {
  1339. OS << "store ";
  1340. Store->getOperand(0)->printAsOperand(OS, /*PrintType=*/false);
  1341. } else if (UserInst->getType()->isVoidTy())
  1342. OS << UserInst->getOpcodeName();
  1343. else
  1344. UserInst->printAsOperand(OS, /*PrintType=*/false);
  1345. OS << ", OperandValToReplace=";
  1346. OperandValToReplace->printAsOperand(OS, /*PrintType=*/false);
  1347. for (const Loop *PIL : PostIncLoops) {
  1348. OS << ", PostIncLoop=";
  1349. PIL->getHeader()->printAsOperand(OS, /*PrintType=*/false);
  1350. }
  1351. if (Offset != 0)
  1352. OS << ", Offset=" << Offset;
  1353. }
  1354. LLVM_DUMP_METHOD void LSRFixup::dump() const {
  1355. print(errs()); errs() << '\n';
  1356. }
  1357. #endif
  1358. /// Test whether this use as a formula which has the same registers as the given
  1359. /// formula.
  1360. bool LSRUse::HasFormulaWithSameRegs(const Formula &F) const {
  1361. SmallVector<const SCEV *, 4> Key = F.BaseRegs;
  1362. if (F.ScaledReg) Key.push_back(F.ScaledReg);
  1363. // Unstable sort by host order ok, because this is only used for uniquifying.
  1364. llvm::sort(Key);
  1365. return Uniquifier.count(Key);
  1366. }
  1367. /// The function returns a probability of selecting formula without Reg.
  1368. float LSRUse::getNotSelectedProbability(const SCEV *Reg) const {
  1369. unsigned FNum = 0;
  1370. for (const Formula &F : Formulae)
  1371. if (F.referencesReg(Reg))
  1372. FNum++;
  1373. return ((float)(Formulae.size() - FNum)) / Formulae.size();
  1374. }
  1375. /// If the given formula has not yet been inserted, add it to the list, and
  1376. /// return true. Return false otherwise. The formula must be in canonical form.
  1377. bool LSRUse::InsertFormula(const Formula &F, const Loop &L) {
  1378. assert(F.isCanonical(L) && "Invalid canonical representation");
  1379. if (!Formulae.empty() && RigidFormula)
  1380. return false;
  1381. SmallVector<const SCEV *, 4> Key = F.BaseRegs;
  1382. if (F.ScaledReg) Key.push_back(F.ScaledReg);
  1383. // Unstable sort by host order ok, because this is only used for uniquifying.
  1384. llvm::sort(Key);
  1385. if (!Uniquifier.insert(Key).second)
  1386. return false;
  1387. // Using a register to hold the value of 0 is not profitable.
  1388. assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
  1389. "Zero allocated in a scaled register!");
  1390. #ifndef NDEBUG
  1391. for (const SCEV *BaseReg : F.BaseRegs)
  1392. assert(!BaseReg->isZero() && "Zero allocated in a base register!");
  1393. #endif
  1394. // Add the formula to the list.
  1395. Formulae.push_back(F);
  1396. // Record registers now being used by this use.
  1397. Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
  1398. if (F.ScaledReg)
  1399. Regs.insert(F.ScaledReg);
  1400. return true;
  1401. }
  1402. /// Remove the given formula from this use's list.
  1403. void LSRUse::DeleteFormula(Formula &F) {
  1404. if (&F != &Formulae.back())
  1405. std::swap(F, Formulae.back());
  1406. Formulae.pop_back();
  1407. }
  1408. /// Recompute the Regs field, and update RegUses.
  1409. void LSRUse::RecomputeRegs(size_t LUIdx, RegUseTracker &RegUses) {
  1410. // Now that we've filtered out some formulae, recompute the Regs set.
  1411. SmallPtrSet<const SCEV *, 4> OldRegs = std::move(Regs);
  1412. Regs.clear();
  1413. for (const Formula &F : Formulae) {
  1414. if (F.ScaledReg) Regs.insert(F.ScaledReg);
  1415. Regs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
  1416. }
  1417. // Update the RegTracker.
  1418. for (const SCEV *S : OldRegs)
  1419. if (!Regs.count(S))
  1420. RegUses.dropRegister(S, LUIdx);
  1421. }
  1422. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  1423. void LSRUse::print(raw_ostream &OS) const {
  1424. OS << "LSR Use: Kind=";
  1425. switch (Kind) {
  1426. case Basic: OS << "Basic"; break;
  1427. case Special: OS << "Special"; break;
  1428. case ICmpZero: OS << "ICmpZero"; break;
  1429. case Address:
  1430. OS << "Address of ";
  1431. if (AccessTy.MemTy->isPointerTy())
  1432. OS << "pointer"; // the full pointer type could be really verbose
  1433. else {
  1434. OS << *AccessTy.MemTy;
  1435. }
  1436. OS << " in addrspace(" << AccessTy.AddrSpace << ')';
  1437. }
  1438. OS << ", Offsets={";
  1439. bool NeedComma = false;
  1440. for (const LSRFixup &Fixup : Fixups) {
  1441. if (NeedComma) OS << ',';
  1442. OS << Fixup.Offset;
  1443. NeedComma = true;
  1444. }
  1445. OS << '}';
  1446. if (AllFixupsOutsideLoop)
  1447. OS << ", all-fixups-outside-loop";
  1448. if (WidestFixupType)
  1449. OS << ", widest fixup type: " << *WidestFixupType;
  1450. }
  1451. LLVM_DUMP_METHOD void LSRUse::dump() const {
  1452. print(errs()); errs() << '\n';
  1453. }
  1454. #endif
  1455. static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
  1456. LSRUse::KindType Kind, MemAccessTy AccessTy,
  1457. GlobalValue *BaseGV, int64_t BaseOffset,
  1458. bool HasBaseReg, int64_t Scale,
  1459. Instruction *Fixup/*= nullptr*/) {
  1460. switch (Kind) {
  1461. case LSRUse::Address:
  1462. return TTI.isLegalAddressingMode(AccessTy.MemTy, BaseGV, BaseOffset,
  1463. HasBaseReg, Scale, AccessTy.AddrSpace, Fixup);
  1464. case LSRUse::ICmpZero:
  1465. // There's not even a target hook for querying whether it would be legal to
  1466. // fold a GV into an ICmp.
  1467. if (BaseGV)
  1468. return false;
  1469. // ICmp only has two operands; don't allow more than two non-trivial parts.
  1470. if (Scale != 0 && HasBaseReg && BaseOffset != 0)
  1471. return false;
  1472. // ICmp only supports no scale or a -1 scale, as we can "fold" a -1 scale by
  1473. // putting the scaled register in the other operand of the icmp.
  1474. if (Scale != 0 && Scale != -1)
  1475. return false;
  1476. // If we have low-level target information, ask the target if it can fold an
  1477. // integer immediate on an icmp.
  1478. if (BaseOffset != 0) {
  1479. // We have one of:
  1480. // ICmpZero BaseReg + BaseOffset => ICmp BaseReg, -BaseOffset
  1481. // ICmpZero -1*ScaleReg + BaseOffset => ICmp ScaleReg, BaseOffset
  1482. // Offs is the ICmp immediate.
  1483. if (Scale == 0)
  1484. // The cast does the right thing with
  1485. // std::numeric_limits<int64_t>::min().
  1486. BaseOffset = -(uint64_t)BaseOffset;
  1487. return TTI.isLegalICmpImmediate(BaseOffset);
  1488. }
  1489. // ICmpZero BaseReg + -1*ScaleReg => ICmp BaseReg, ScaleReg
  1490. return true;
  1491. case LSRUse::Basic:
  1492. // Only handle single-register values.
  1493. return !BaseGV && Scale == 0 && BaseOffset == 0;
  1494. case LSRUse::Special:
  1495. // Special case Basic to handle -1 scales.
  1496. return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
  1497. }
  1498. llvm_unreachable("Invalid LSRUse Kind!");
  1499. }
  1500. static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
  1501. int64_t MinOffset, int64_t MaxOffset,
  1502. LSRUse::KindType Kind, MemAccessTy AccessTy,
  1503. GlobalValue *BaseGV, int64_t BaseOffset,
  1504. bool HasBaseReg, int64_t Scale) {
  1505. // Check for overflow.
  1506. if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
  1507. (MinOffset > 0))
  1508. return false;
  1509. MinOffset = (uint64_t)BaseOffset + MinOffset;
  1510. if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
  1511. (MaxOffset > 0))
  1512. return false;
  1513. MaxOffset = (uint64_t)BaseOffset + MaxOffset;
  1514. return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MinOffset,
  1515. HasBaseReg, Scale) &&
  1516. isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, MaxOffset,
  1517. HasBaseReg, Scale);
  1518. }
  1519. static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
  1520. int64_t MinOffset, int64_t MaxOffset,
  1521. LSRUse::KindType Kind, MemAccessTy AccessTy,
  1522. const Formula &F, const Loop &L) {
  1523. // For the purpose of isAMCompletelyFolded either having a canonical formula
  1524. // or a scale not equal to zero is correct.
  1525. // Problems may arise from non canonical formulae having a scale == 0.
  1526. // Strictly speaking it would best to just rely on canonical formulae.
  1527. // However, when we generate the scaled formulae, we first check that the
  1528. // scaling factor is profitable before computing the actual ScaledReg for
  1529. // compile time sake.
  1530. assert((F.isCanonical(L) || F.Scale != 0));
  1531. return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
  1532. F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
  1533. }
  1534. /// Test whether we know how to expand the current formula.
  1535. static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
  1536. int64_t MaxOffset, LSRUse::KindType Kind,
  1537. MemAccessTy AccessTy, GlobalValue *BaseGV,
  1538. int64_t BaseOffset, bool HasBaseReg, int64_t Scale) {
  1539. // We know how to expand completely foldable formulae.
  1540. return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
  1541. BaseOffset, HasBaseReg, Scale) ||
  1542. // Or formulae that use a base register produced by a sum of base
  1543. // registers.
  1544. (Scale == 1 &&
  1545. isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy,
  1546. BaseGV, BaseOffset, true, 0));
  1547. }
  1548. static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset,
  1549. int64_t MaxOffset, LSRUse::KindType Kind,
  1550. MemAccessTy AccessTy, const Formula &F) {
  1551. return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
  1552. F.BaseOffset, F.HasBaseReg, F.Scale);
  1553. }
  1554. static bool isAMCompletelyFolded(const TargetTransformInfo &TTI,
  1555. const LSRUse &LU, const Formula &F) {
  1556. // Target may want to look at the user instructions.
  1557. if (LU.Kind == LSRUse::Address && TTI.LSRWithInstrQueries()) {
  1558. for (const LSRFixup &Fixup : LU.Fixups)
  1559. if (!isAMCompletelyFolded(TTI, LSRUse::Address, LU.AccessTy, F.BaseGV,
  1560. (F.BaseOffset + Fixup.Offset), F.HasBaseReg,
  1561. F.Scale, Fixup.UserInst))
  1562. return false;
  1563. return true;
  1564. }
  1565. return isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
  1566. LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
  1567. F.Scale);
  1568. }
  1569. static InstructionCost getScalingFactorCost(const TargetTransformInfo &TTI,
  1570. const LSRUse &LU, const Formula &F,
  1571. const Loop &L) {
  1572. if (!F.Scale)
  1573. return 0;
  1574. // If the use is not completely folded in that instruction, we will have to
  1575. // pay an extra cost only for scale != 1.
  1576. if (!isAMCompletelyFolded(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind,
  1577. LU.AccessTy, F, L))
  1578. return F.Scale != 1;
  1579. switch (LU.Kind) {
  1580. case LSRUse::Address: {
  1581. // Check the scaling factor cost with both the min and max offsets.
  1582. InstructionCost ScaleCostMinOffset = TTI.getScalingFactorCost(
  1583. LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg,
  1584. F.Scale, LU.AccessTy.AddrSpace);
  1585. InstructionCost ScaleCostMaxOffset = TTI.getScalingFactorCost(
  1586. LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg,
  1587. F.Scale, LU.AccessTy.AddrSpace);
  1588. assert(ScaleCostMinOffset.isValid() && ScaleCostMaxOffset.isValid() &&
  1589. "Legal addressing mode has an illegal cost!");
  1590. return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
  1591. }
  1592. case LSRUse::ICmpZero:
  1593. case LSRUse::Basic:
  1594. case LSRUse::Special:
  1595. // The use is completely folded, i.e., everything is folded into the
  1596. // instruction.
  1597. return 0;
  1598. }
  1599. llvm_unreachable("Invalid LSRUse Kind!");
  1600. }
  1601. static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
  1602. LSRUse::KindType Kind, MemAccessTy AccessTy,
  1603. GlobalValue *BaseGV, int64_t BaseOffset,
  1604. bool HasBaseReg) {
  1605. // Fast-path: zero is always foldable.
  1606. if (BaseOffset == 0 && !BaseGV) return true;
  1607. // Conservatively, create an address with an immediate and a
  1608. // base and a scale.
  1609. int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
  1610. // Canonicalize a scale of 1 to a base register if the formula doesn't
  1611. // already have a base register.
  1612. if (!HasBaseReg && Scale == 1) {
  1613. Scale = 0;
  1614. HasBaseReg = true;
  1615. }
  1616. return isAMCompletelyFolded(TTI, Kind, AccessTy, BaseGV, BaseOffset,
  1617. HasBaseReg, Scale);
  1618. }
  1619. static bool isAlwaysFoldable(const TargetTransformInfo &TTI,
  1620. ScalarEvolution &SE, int64_t MinOffset,
  1621. int64_t MaxOffset, LSRUse::KindType Kind,
  1622. MemAccessTy AccessTy, const SCEV *S,
  1623. bool HasBaseReg) {
  1624. // Fast-path: zero is always foldable.
  1625. if (S->isZero()) return true;
  1626. // Conservatively, create an address with an immediate and a
  1627. // base and a scale.
  1628. int64_t BaseOffset = ExtractImmediate(S, SE);
  1629. GlobalValue *BaseGV = ExtractSymbol(S, SE);
  1630. // If there's anything else involved, it's not foldable.
  1631. if (!S->isZero()) return false;
  1632. // Fast-path: zero is always foldable.
  1633. if (BaseOffset == 0 && !BaseGV) return true;
  1634. // Conservatively, create an address with an immediate and a
  1635. // base and a scale.
  1636. int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
  1637. return isAMCompletelyFolded(TTI, MinOffset, MaxOffset, Kind, AccessTy, BaseGV,
  1638. BaseOffset, HasBaseReg, Scale);
  1639. }
  1640. namespace {
  1641. /// An individual increment in a Chain of IV increments. Relate an IV user to
  1642. /// an expression that computes the IV it uses from the IV used by the previous
  1643. /// link in the Chain.
  1644. ///
  1645. /// For the head of a chain, IncExpr holds the absolute SCEV expression for the
  1646. /// original IVOperand. The head of the chain's IVOperand is only valid during
  1647. /// chain collection, before LSR replaces IV users. During chain generation,
  1648. /// IncExpr can be used to find the new IVOperand that computes the same
  1649. /// expression.
  1650. struct IVInc {
  1651. Instruction *UserInst;
  1652. Value* IVOperand;
  1653. const SCEV *IncExpr;
  1654. IVInc(Instruction *U, Value *O, const SCEV *E)
  1655. : UserInst(U), IVOperand(O), IncExpr(E) {}
  1656. };
  1657. // The list of IV increments in program order. We typically add the head of a
  1658. // chain without finding subsequent links.
  1659. struct IVChain {
  1660. SmallVector<IVInc, 1> Incs;
  1661. const SCEV *ExprBase = nullptr;
  1662. IVChain() = default;
  1663. IVChain(const IVInc &Head, const SCEV *Base)
  1664. : Incs(1, Head), ExprBase(Base) {}
  1665. using const_iterator = SmallVectorImpl<IVInc>::const_iterator;
  1666. // Return the first increment in the chain.
  1667. const_iterator begin() const {
  1668. assert(!Incs.empty());
  1669. return std::next(Incs.begin());
  1670. }
  1671. const_iterator end() const {
  1672. return Incs.end();
  1673. }
  1674. // Returns true if this chain contains any increments.
  1675. bool hasIncs() const { return Incs.size() >= 2; }
  1676. // Add an IVInc to the end of this chain.
  1677. void add(const IVInc &X) { Incs.push_back(X); }
  1678. // Returns the last UserInst in the chain.
  1679. Instruction *tailUserInst() const { return Incs.back().UserInst; }
  1680. // Returns true if IncExpr can be profitably added to this chain.
  1681. bool isProfitableIncrement(const SCEV *OperExpr,
  1682. const SCEV *IncExpr,
  1683. ScalarEvolution&);
  1684. };
  1685. /// Helper for CollectChains to track multiple IV increment uses. Distinguish
  1686. /// between FarUsers that definitely cross IV increments and NearUsers that may
  1687. /// be used between IV increments.
  1688. struct ChainUsers {
  1689. SmallPtrSet<Instruction*, 4> FarUsers;
  1690. SmallPtrSet<Instruction*, 4> NearUsers;
  1691. };
  1692. /// This class holds state for the main loop strength reduction logic.
  1693. class LSRInstance {
  1694. IVUsers &IU;
  1695. ScalarEvolution &SE;
  1696. DominatorTree &DT;
  1697. LoopInfo &LI;
  1698. AssumptionCache &AC;
  1699. TargetLibraryInfo &TLI;
  1700. const TargetTransformInfo &TTI;
  1701. Loop *const L;
  1702. MemorySSAUpdater *MSSAU;
  1703. TTI::AddressingModeKind AMK;
  1704. bool Changed = false;
  1705. /// This is the insert position that the current loop's induction variable
  1706. /// increment should be placed. In simple loops, this is the latch block's
  1707. /// terminator. But in more complicated cases, this is a position which will
  1708. /// dominate all the in-loop post-increment users.
  1709. Instruction *IVIncInsertPos = nullptr;
  1710. /// Interesting factors between use strides.
  1711. ///
  1712. /// We explicitly use a SetVector which contains a SmallSet, instead of the
  1713. /// default, a SmallDenseSet, because we need to use the full range of
  1714. /// int64_ts, and there's currently no good way of doing that with
  1715. /// SmallDenseSet.
  1716. SetVector<int64_t, SmallVector<int64_t, 8>, SmallSet<int64_t, 8>> Factors;
  1717. /// Interesting use types, to facilitate truncation reuse.
  1718. SmallSetVector<Type *, 4> Types;
  1719. /// The list of interesting uses.
  1720. mutable SmallVector<LSRUse, 16> Uses;
  1721. /// Track which uses use which register candidates.
  1722. RegUseTracker RegUses;
  1723. // Limit the number of chains to avoid quadratic behavior. We don't expect to
  1724. // have more than a few IV increment chains in a loop. Missing a Chain falls
  1725. // back to normal LSR behavior for those uses.
  1726. static const unsigned MaxChains = 8;
  1727. /// IV users can form a chain of IV increments.
  1728. SmallVector<IVChain, MaxChains> IVChainVec;
  1729. /// IV users that belong to profitable IVChains.
  1730. SmallPtrSet<Use*, MaxChains> IVIncSet;
  1731. /// Induction variables that were generated and inserted by the SCEV Expander.
  1732. SmallVector<llvm::WeakVH, 2> ScalarEvolutionIVs;
  1733. void OptimizeShadowIV();
  1734. bool FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse);
  1735. ICmpInst *OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse);
  1736. void OptimizeLoopTermCond();
  1737. void ChainInstruction(Instruction *UserInst, Instruction *IVOper,
  1738. SmallVectorImpl<ChainUsers> &ChainUsersVec);
  1739. void FinalizeChain(IVChain &Chain);
  1740. void CollectChains();
  1741. void GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
  1742. SmallVectorImpl<WeakTrackingVH> &DeadInsts);
  1743. void CollectInterestingTypesAndFactors();
  1744. void CollectFixupsAndInitialFormulae();
  1745. // Support for sharing of LSRUses between LSRFixups.
  1746. using UseMapTy = DenseMap<LSRUse::SCEVUseKindPair, size_t>;
  1747. UseMapTy UseMap;
  1748. bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset, bool HasBaseReg,
  1749. LSRUse::KindType Kind, MemAccessTy AccessTy);
  1750. std::pair<size_t, int64_t> getUse(const SCEV *&Expr, LSRUse::KindType Kind,
  1751. MemAccessTy AccessTy);
  1752. void DeleteUse(LSRUse &LU, size_t LUIdx);
  1753. LSRUse *FindUseWithSimilarFormula(const Formula &F, const LSRUse &OrigLU);
  1754. void InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
  1755. void InsertSupplementalFormula(const SCEV *S, LSRUse &LU, size_t LUIdx);
  1756. void CountRegisters(const Formula &F, size_t LUIdx);
  1757. bool InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F);
  1758. void CollectLoopInvariantFixupsAndFormulae();
  1759. void GenerateReassociations(LSRUse &LU, unsigned LUIdx, Formula Base,
  1760. unsigned Depth = 0);
  1761. void GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
  1762. const Formula &Base, unsigned Depth,
  1763. size_t Idx, bool IsScaledReg = false);
  1764. void GenerateCombinations(LSRUse &LU, unsigned LUIdx, Formula Base);
  1765. void GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
  1766. const Formula &Base, size_t Idx,
  1767. bool IsScaledReg = false);
  1768. void GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
  1769. void GenerateConstantOffsetsImpl(LSRUse &LU, unsigned LUIdx,
  1770. const Formula &Base,
  1771. const SmallVectorImpl<int64_t> &Worklist,
  1772. size_t Idx, bool IsScaledReg = false);
  1773. void GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx, Formula Base);
  1774. void GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx, Formula Base);
  1775. void GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base);
  1776. void GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base);
  1777. void GenerateCrossUseConstantOffsets();
  1778. void GenerateAllReuseFormulae();
  1779. void FilterOutUndesirableDedicatedRegisters();
  1780. size_t EstimateSearchSpaceComplexity() const;
  1781. void NarrowSearchSpaceByDetectingSupersets();
  1782. void NarrowSearchSpaceByCollapsingUnrolledCode();
  1783. void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
  1784. void NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
  1785. void NarrowSearchSpaceByFilterPostInc();
  1786. void NarrowSearchSpaceByDeletingCostlyFormulas();
  1787. void NarrowSearchSpaceByPickingWinnerRegs();
  1788. void NarrowSearchSpaceUsingHeuristics();
  1789. void SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
  1790. Cost &SolutionCost,
  1791. SmallVectorImpl<const Formula *> &Workspace,
  1792. const Cost &CurCost,
  1793. const SmallPtrSet<const SCEV *, 16> &CurRegs,
  1794. DenseSet<const SCEV *> &VisitedRegs) const;
  1795. void Solve(SmallVectorImpl<const Formula *> &Solution) const;
  1796. BasicBlock::iterator
  1797. HoistInsertPosition(BasicBlock::iterator IP,
  1798. const SmallVectorImpl<Instruction *> &Inputs) const;
  1799. BasicBlock::iterator
  1800. AdjustInsertPositionForExpand(BasicBlock::iterator IP,
  1801. const LSRFixup &LF,
  1802. const LSRUse &LU,
  1803. SCEVExpander &Rewriter) const;
  1804. Value *Expand(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
  1805. BasicBlock::iterator IP, SCEVExpander &Rewriter,
  1806. SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
  1807. void RewriteForPHI(PHINode *PN, const LSRUse &LU, const LSRFixup &LF,
  1808. const Formula &F, SCEVExpander &Rewriter,
  1809. SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
  1810. void Rewrite(const LSRUse &LU, const LSRFixup &LF, const Formula &F,
  1811. SCEVExpander &Rewriter,
  1812. SmallVectorImpl<WeakTrackingVH> &DeadInsts) const;
  1813. void ImplementSolution(const SmallVectorImpl<const Formula *> &Solution);
  1814. public:
  1815. LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT,
  1816. LoopInfo &LI, const TargetTransformInfo &TTI, AssumptionCache &AC,
  1817. TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU);
  1818. bool getChanged() const { return Changed; }
  1819. const SmallVectorImpl<WeakVH> &getScalarEvolutionIVs() const {
  1820. return ScalarEvolutionIVs;
  1821. }
  1822. void print_factors_and_types(raw_ostream &OS) const;
  1823. void print_fixups(raw_ostream &OS) const;
  1824. void print_uses(raw_ostream &OS) const;
  1825. void print(raw_ostream &OS) const;
  1826. void dump() const;
  1827. };
  1828. } // end anonymous namespace
  1829. /// If IV is used in a int-to-float cast inside the loop then try to eliminate
  1830. /// the cast operation.
  1831. void LSRInstance::OptimizeShadowIV() {
  1832. const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
  1833. if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
  1834. return;
  1835. for (IVUsers::const_iterator UI = IU.begin(), E = IU.end();
  1836. UI != E; /* empty */) {
  1837. IVUsers::const_iterator CandidateUI = UI;
  1838. ++UI;
  1839. Instruction *ShadowUse = CandidateUI->getUser();
  1840. Type *DestTy = nullptr;
  1841. bool IsSigned = false;
  1842. /* If shadow use is a int->float cast then insert a second IV
  1843. to eliminate this cast.
  1844. for (unsigned i = 0; i < n; ++i)
  1845. foo((double)i);
  1846. is transformed into
  1847. double d = 0.0;
  1848. for (unsigned i = 0; i < n; ++i, ++d)
  1849. foo(d);
  1850. */
  1851. if (UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
  1852. IsSigned = false;
  1853. DestTy = UCast->getDestTy();
  1854. }
  1855. else if (SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
  1856. IsSigned = true;
  1857. DestTy = SCast->getDestTy();
  1858. }
  1859. if (!DestTy) continue;
  1860. // If target does not support DestTy natively then do not apply
  1861. // this transformation.
  1862. if (!TTI.isTypeLegal(DestTy)) continue;
  1863. PHINode *PH = dyn_cast<PHINode>(ShadowUse->getOperand(0));
  1864. if (!PH) continue;
  1865. if (PH->getNumIncomingValues() != 2) continue;
  1866. // If the calculation in integers overflows, the result in FP type will
  1867. // differ. So we only can do this transformation if we are guaranteed to not
  1868. // deal with overflowing values
  1869. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(PH));
  1870. if (!AR) continue;
  1871. if (IsSigned && !AR->hasNoSignedWrap()) continue;
  1872. if (!IsSigned && !AR->hasNoUnsignedWrap()) continue;
  1873. Type *SrcTy = PH->getType();
  1874. int Mantissa = DestTy->getFPMantissaWidth();
  1875. if (Mantissa == -1) continue;
  1876. if ((int)SE.getTypeSizeInBits(SrcTy) > Mantissa)
  1877. continue;
  1878. unsigned Entry, Latch;
  1879. if (PH->getIncomingBlock(0) == L->getLoopPreheader()) {
  1880. Entry = 0;
  1881. Latch = 1;
  1882. } else {
  1883. Entry = 1;
  1884. Latch = 0;
  1885. }
  1886. ConstantInt *Init = dyn_cast<ConstantInt>(PH->getIncomingValue(Entry));
  1887. if (!Init) continue;
  1888. Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
  1889. (double)Init->getSExtValue() :
  1890. (double)Init->getZExtValue());
  1891. BinaryOperator *Incr =
  1892. dyn_cast<BinaryOperator>(PH->getIncomingValue(Latch));
  1893. if (!Incr) continue;
  1894. if (Incr->getOpcode() != Instruction::Add
  1895. && Incr->getOpcode() != Instruction::Sub)
  1896. continue;
  1897. /* Initialize new IV, double d = 0.0 in above example. */
  1898. ConstantInt *C = nullptr;
  1899. if (Incr->getOperand(0) == PH)
  1900. C = dyn_cast<ConstantInt>(Incr->getOperand(1));
  1901. else if (Incr->getOperand(1) == PH)
  1902. C = dyn_cast<ConstantInt>(Incr->getOperand(0));
  1903. else
  1904. continue;
  1905. if (!C) continue;
  1906. // Ignore negative constants, as the code below doesn't handle them
  1907. // correctly. TODO: Remove this restriction.
  1908. if (!C->getValue().isStrictlyPositive()) continue;
  1909. /* Add new PHINode. */
  1910. PHINode *NewPH = PHINode::Create(DestTy, 2, "IV.S.", PH);
  1911. /* create new increment. '++d' in above example. */
  1912. Constant *CFP = ConstantFP::get(DestTy, C->getZExtValue());
  1913. BinaryOperator *NewIncr =
  1914. BinaryOperator::Create(Incr->getOpcode() == Instruction::Add ?
  1915. Instruction::FAdd : Instruction::FSub,
  1916. NewPH, CFP, "IV.S.next.", Incr);
  1917. NewPH->addIncoming(NewInit, PH->getIncomingBlock(Entry));
  1918. NewPH->addIncoming(NewIncr, PH->getIncomingBlock(Latch));
  1919. /* Remove cast operation */
  1920. ShadowUse->replaceAllUsesWith(NewPH);
  1921. ShadowUse->eraseFromParent();
  1922. Changed = true;
  1923. break;
  1924. }
  1925. }
  1926. /// If Cond has an operand that is an expression of an IV, set the IV user and
  1927. /// stride information and return true, otherwise return false.
  1928. bool LSRInstance::FindIVUserForCond(ICmpInst *Cond, IVStrideUse *&CondUse) {
  1929. for (IVStrideUse &U : IU)
  1930. if (U.getUser() == Cond) {
  1931. // NOTE: we could handle setcc instructions with multiple uses here, but
  1932. // InstCombine does it as well for simple uses, it's not clear that it
  1933. // occurs enough in real life to handle.
  1934. CondUse = &U;
  1935. return true;
  1936. }
  1937. return false;
  1938. }
  1939. /// Rewrite the loop's terminating condition if it uses a max computation.
  1940. ///
  1941. /// This is a narrow solution to a specific, but acute, problem. For loops
  1942. /// like this:
  1943. ///
  1944. /// i = 0;
  1945. /// do {
  1946. /// p[i] = 0.0;
  1947. /// } while (++i < n);
  1948. ///
  1949. /// the trip count isn't just 'n', because 'n' might not be positive. And
  1950. /// unfortunately this can come up even for loops where the user didn't use
  1951. /// a C do-while loop. For example, seemingly well-behaved top-test loops
  1952. /// will commonly be lowered like this:
  1953. ///
  1954. /// if (n > 0) {
  1955. /// i = 0;
  1956. /// do {
  1957. /// p[i] = 0.0;
  1958. /// } while (++i < n);
  1959. /// }
  1960. ///
  1961. /// and then it's possible for subsequent optimization to obscure the if
  1962. /// test in such a way that indvars can't find it.
  1963. ///
  1964. /// When indvars can't find the if test in loops like this, it creates a
  1965. /// max expression, which allows it to give the loop a canonical
  1966. /// induction variable:
  1967. ///
  1968. /// i = 0;
  1969. /// max = n < 1 ? 1 : n;
  1970. /// do {
  1971. /// p[i] = 0.0;
  1972. /// } while (++i != max);
  1973. ///
  1974. /// Canonical induction variables are necessary because the loop passes
  1975. /// are designed around them. The most obvious example of this is the
  1976. /// LoopInfo analysis, which doesn't remember trip count values. It
  1977. /// expects to be able to rediscover the trip count each time it is
  1978. /// needed, and it does this using a simple analysis that only succeeds if
  1979. /// the loop has a canonical induction variable.
  1980. ///
  1981. /// However, when it comes time to generate code, the maximum operation
  1982. /// can be quite costly, especially if it's inside of an outer loop.
  1983. ///
  1984. /// This function solves this problem by detecting this type of loop and
  1985. /// rewriting their conditions from ICMP_NE back to ICMP_SLT, and deleting
  1986. /// the instructions for the maximum computation.
  1987. ICmpInst *LSRInstance::OptimizeMax(ICmpInst *Cond, IVStrideUse* &CondUse) {
  1988. // Check that the loop matches the pattern we're looking for.
  1989. if (Cond->getPredicate() != CmpInst::ICMP_EQ &&
  1990. Cond->getPredicate() != CmpInst::ICMP_NE)
  1991. return Cond;
  1992. SelectInst *Sel = dyn_cast<SelectInst>(Cond->getOperand(1));
  1993. if (!Sel || !Sel->hasOneUse()) return Cond;
  1994. const SCEV *BackedgeTakenCount = SE.getBackedgeTakenCount(L);
  1995. if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
  1996. return Cond;
  1997. const SCEV *One = SE.getConstant(BackedgeTakenCount->getType(), 1);
  1998. // Add one to the backedge-taken count to get the trip count.
  1999. const SCEV *IterationCount = SE.getAddExpr(One, BackedgeTakenCount);
  2000. if (IterationCount != SE.getSCEV(Sel)) return Cond;
  2001. // Check for a max calculation that matches the pattern. There's no check
  2002. // for ICMP_ULE here because the comparison would be with zero, which
  2003. // isn't interesting.
  2004. CmpInst::Predicate Pred = ICmpInst::BAD_ICMP_PREDICATE;
  2005. const SCEVNAryExpr *Max = nullptr;
  2006. if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
  2007. Pred = ICmpInst::ICMP_SLE;
  2008. Max = S;
  2009. } else if (const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
  2010. Pred = ICmpInst::ICMP_SLT;
  2011. Max = S;
  2012. } else if (const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
  2013. Pred = ICmpInst::ICMP_ULT;
  2014. Max = U;
  2015. } else {
  2016. // No match; bail.
  2017. return Cond;
  2018. }
  2019. // To handle a max with more than two operands, this optimization would
  2020. // require additional checking and setup.
  2021. if (Max->getNumOperands() != 2)
  2022. return Cond;
  2023. const SCEV *MaxLHS = Max->getOperand(0);
  2024. const SCEV *MaxRHS = Max->getOperand(1);
  2025. // ScalarEvolution canonicalizes constants to the left. For < and >, look
  2026. // for a comparison with 1. For <= and >=, a comparison with zero.
  2027. if (!MaxLHS ||
  2028. (ICmpInst::isTrueWhenEqual(Pred) ? !MaxLHS->isZero() : (MaxLHS != One)))
  2029. return Cond;
  2030. // Check the relevant induction variable for conformance to
  2031. // the pattern.
  2032. const SCEV *IV = SE.getSCEV(Cond->getOperand(0));
  2033. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(IV);
  2034. if (!AR || !AR->isAffine() ||
  2035. AR->getStart() != One ||
  2036. AR->getStepRecurrence(SE) != One)
  2037. return Cond;
  2038. assert(AR->getLoop() == L &&
  2039. "Loop condition operand is an addrec in a different loop!");
  2040. // Check the right operand of the select, and remember it, as it will
  2041. // be used in the new comparison instruction.
  2042. Value *NewRHS = nullptr;
  2043. if (ICmpInst::isTrueWhenEqual(Pred)) {
  2044. // Look for n+1, and grab n.
  2045. if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(1)))
  2046. if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
  2047. if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
  2048. NewRHS = BO->getOperand(0);
  2049. if (AddOperator *BO = dyn_cast<AddOperator>(Sel->getOperand(2)))
  2050. if (ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
  2051. if (BO1->isOne() && SE.getSCEV(BO->getOperand(0)) == MaxRHS)
  2052. NewRHS = BO->getOperand(0);
  2053. if (!NewRHS)
  2054. return Cond;
  2055. } else if (SE.getSCEV(Sel->getOperand(1)) == MaxRHS)
  2056. NewRHS = Sel->getOperand(1);
  2057. else if (SE.getSCEV(Sel->getOperand(2)) == MaxRHS)
  2058. NewRHS = Sel->getOperand(2);
  2059. else if (const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
  2060. NewRHS = SU->getValue();
  2061. else
  2062. // Max doesn't match expected pattern.
  2063. return Cond;
  2064. // Determine the new comparison opcode. It may be signed or unsigned,
  2065. // and the original comparison may be either equality or inequality.
  2066. if (Cond->getPredicate() == CmpInst::ICMP_EQ)
  2067. Pred = CmpInst::getInversePredicate(Pred);
  2068. // Ok, everything looks ok to change the condition into an SLT or SGE and
  2069. // delete the max calculation.
  2070. ICmpInst *NewCond =
  2071. new ICmpInst(Cond, Pred, Cond->getOperand(0), NewRHS, "scmp");
  2072. // Delete the max calculation instructions.
  2073. NewCond->setDebugLoc(Cond->getDebugLoc());
  2074. Cond->replaceAllUsesWith(NewCond);
  2075. CondUse->setUser(NewCond);
  2076. Instruction *Cmp = cast<Instruction>(Sel->getOperand(0));
  2077. Cond->eraseFromParent();
  2078. Sel->eraseFromParent();
  2079. if (Cmp->use_empty())
  2080. Cmp->eraseFromParent();
  2081. return NewCond;
  2082. }
  2083. /// Change loop terminating condition to use the postinc iv when possible.
  2084. void
  2085. LSRInstance::OptimizeLoopTermCond() {
  2086. SmallPtrSet<Instruction *, 4> PostIncs;
  2087. // We need a different set of heuristics for rotated and non-rotated loops.
  2088. // If a loop is rotated then the latch is also the backedge, so inserting
  2089. // post-inc expressions just before the latch is ideal. To reduce live ranges
  2090. // it also makes sense to rewrite terminating conditions to use post-inc
  2091. // expressions.
  2092. //
  2093. // If the loop is not rotated then the latch is not a backedge; the latch
  2094. // check is done in the loop head. Adding post-inc expressions before the
  2095. // latch will cause overlapping live-ranges of pre-inc and post-inc expressions
  2096. // in the loop body. In this case we do *not* want to use post-inc expressions
  2097. // in the latch check, and we want to insert post-inc expressions before
  2098. // the backedge.
  2099. BasicBlock *LatchBlock = L->getLoopLatch();
  2100. SmallVector<BasicBlock*, 8> ExitingBlocks;
  2101. L->getExitingBlocks(ExitingBlocks);
  2102. if (llvm::all_of(ExitingBlocks, [&LatchBlock](const BasicBlock *BB) {
  2103. return LatchBlock != BB;
  2104. })) {
  2105. // The backedge doesn't exit the loop; treat this as a head-tested loop.
  2106. IVIncInsertPos = LatchBlock->getTerminator();
  2107. return;
  2108. }
  2109. // Otherwise treat this as a rotated loop.
  2110. for (BasicBlock *ExitingBlock : ExitingBlocks) {
  2111. // Get the terminating condition for the loop if possible. If we
  2112. // can, we want to change it to use a post-incremented version of its
  2113. // induction variable, to allow coalescing the live ranges for the IV into
  2114. // one register value.
  2115. BranchInst *TermBr = dyn_cast<BranchInst>(ExitingBlock->getTerminator());
  2116. if (!TermBr)
  2117. continue;
  2118. // FIXME: Overly conservative, termination condition could be an 'or' etc..
  2119. if (TermBr->isUnconditional() || !isa<ICmpInst>(TermBr->getCondition()))
  2120. continue;
  2121. // Search IVUsesByStride to find Cond's IVUse if there is one.
  2122. IVStrideUse *CondUse = nullptr;
  2123. ICmpInst *Cond = cast<ICmpInst>(TermBr->getCondition());
  2124. if (!FindIVUserForCond(Cond, CondUse))
  2125. continue;
  2126. // If the trip count is computed in terms of a max (due to ScalarEvolution
  2127. // being unable to find a sufficient guard, for example), change the loop
  2128. // comparison to use SLT or ULT instead of NE.
  2129. // One consequence of doing this now is that it disrupts the count-down
  2130. // optimization. That's not always a bad thing though, because in such
  2131. // cases it may still be worthwhile to avoid a max.
  2132. Cond = OptimizeMax(Cond, CondUse);
  2133. // If this exiting block dominates the latch block, it may also use
  2134. // the post-inc value if it won't be shared with other uses.
  2135. // Check for dominance.
  2136. if (!DT.dominates(ExitingBlock, LatchBlock))
  2137. continue;
  2138. // Conservatively avoid trying to use the post-inc value in non-latch
  2139. // exits if there may be pre-inc users in intervening blocks.
  2140. if (LatchBlock != ExitingBlock)
  2141. for (IVUsers::const_iterator UI = IU.begin(), E = IU.end(); UI != E; ++UI)
  2142. // Test if the use is reachable from the exiting block. This dominator
  2143. // query is a conservative approximation of reachability.
  2144. if (&*UI != CondUse &&
  2145. !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
  2146. // Conservatively assume there may be reuse if the quotient of their
  2147. // strides could be a legal scale.
  2148. const SCEV *A = IU.getStride(*CondUse, L);
  2149. const SCEV *B = IU.getStride(*UI, L);
  2150. if (!A || !B) continue;
  2151. if (SE.getTypeSizeInBits(A->getType()) !=
  2152. SE.getTypeSizeInBits(B->getType())) {
  2153. if (SE.getTypeSizeInBits(A->getType()) >
  2154. SE.getTypeSizeInBits(B->getType()))
  2155. B = SE.getSignExtendExpr(B, A->getType());
  2156. else
  2157. A = SE.getSignExtendExpr(A, B->getType());
  2158. }
  2159. if (const SCEVConstant *D =
  2160. dyn_cast_or_null<SCEVConstant>(getExactSDiv(B, A, SE))) {
  2161. const ConstantInt *C = D->getValue();
  2162. // Stride of one or negative one can have reuse with non-addresses.
  2163. if (C->isOne() || C->isMinusOne())
  2164. goto decline_post_inc;
  2165. // Avoid weird situations.
  2166. if (C->getValue().getMinSignedBits() >= 64 ||
  2167. C->getValue().isMinSignedValue())
  2168. goto decline_post_inc;
  2169. // Check for possible scaled-address reuse.
  2170. if (isAddressUse(TTI, UI->getUser(), UI->getOperandValToReplace())) {
  2171. MemAccessTy AccessTy = getAccessType(
  2172. TTI, UI->getUser(), UI->getOperandValToReplace());
  2173. int64_t Scale = C->getSExtValue();
  2174. if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
  2175. /*BaseOffset=*/0,
  2176. /*HasBaseReg=*/false, Scale,
  2177. AccessTy.AddrSpace))
  2178. goto decline_post_inc;
  2179. Scale = -Scale;
  2180. if (TTI.isLegalAddressingMode(AccessTy.MemTy, /*BaseGV=*/nullptr,
  2181. /*BaseOffset=*/0,
  2182. /*HasBaseReg=*/false, Scale,
  2183. AccessTy.AddrSpace))
  2184. goto decline_post_inc;
  2185. }
  2186. }
  2187. }
  2188. LLVM_DEBUG(dbgs() << " Change loop exiting icmp to use postinc iv: "
  2189. << *Cond << '\n');
  2190. // It's possible for the setcc instruction to be anywhere in the loop, and
  2191. // possible for it to have multiple users. If it is not immediately before
  2192. // the exiting block branch, move it.
  2193. if (Cond->getNextNonDebugInstruction() != TermBr) {
  2194. if (Cond->hasOneUse()) {
  2195. Cond->moveBefore(TermBr);
  2196. } else {
  2197. // Clone the terminating condition and insert into the loopend.
  2198. ICmpInst *OldCond = Cond;
  2199. Cond = cast<ICmpInst>(Cond->clone());
  2200. Cond->setName(L->getHeader()->getName() + ".termcond");
  2201. ExitingBlock->getInstList().insert(TermBr->getIterator(), Cond);
  2202. // Clone the IVUse, as the old use still exists!
  2203. CondUse = &IU.AddUser(Cond, CondUse->getOperandValToReplace());
  2204. TermBr->replaceUsesOfWith(OldCond, Cond);
  2205. }
  2206. }
  2207. // If we get to here, we know that we can transform the setcc instruction to
  2208. // use the post-incremented version of the IV, allowing us to coalesce the
  2209. // live ranges for the IV correctly.
  2210. CondUse->transformToPostInc(L);
  2211. Changed = true;
  2212. PostIncs.insert(Cond);
  2213. decline_post_inc:;
  2214. }
  2215. // Determine an insertion point for the loop induction variable increment. It
  2216. // must dominate all the post-inc comparisons we just set up, and it must
  2217. // dominate the loop latch edge.
  2218. IVIncInsertPos = L->getLoopLatch()->getTerminator();
  2219. for (Instruction *Inst : PostIncs) {
  2220. BasicBlock *BB =
  2221. DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
  2222. Inst->getParent());
  2223. if (BB == Inst->getParent())
  2224. IVIncInsertPos = Inst;
  2225. else if (BB != IVIncInsertPos->getParent())
  2226. IVIncInsertPos = BB->getTerminator();
  2227. }
  2228. }
  2229. /// Determine if the given use can accommodate a fixup at the given offset and
  2230. /// other details. If so, update the use and return true.
  2231. bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
  2232. bool HasBaseReg, LSRUse::KindType Kind,
  2233. MemAccessTy AccessTy) {
  2234. int64_t NewMinOffset = LU.MinOffset;
  2235. int64_t NewMaxOffset = LU.MaxOffset;
  2236. MemAccessTy NewAccessTy = AccessTy;
  2237. // Check for a mismatched kind. It's tempting to collapse mismatched kinds to
  2238. // something conservative, however this can pessimize in the case that one of
  2239. // the uses will have all its uses outside the loop, for example.
  2240. if (LU.Kind != Kind)
  2241. return false;
  2242. // Check for a mismatched access type, and fall back conservatively as needed.
  2243. // TODO: Be less conservative when the type is similar and can use the same
  2244. // addressing modes.
  2245. if (Kind == LSRUse::Address) {
  2246. if (AccessTy.MemTy != LU.AccessTy.MemTy) {
  2247. NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(),
  2248. AccessTy.AddrSpace);
  2249. }
  2250. }
  2251. // Conservatively assume HasBaseReg is true for now.
  2252. if (NewOffset < LU.MinOffset) {
  2253. if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
  2254. LU.MaxOffset - NewOffset, HasBaseReg))
  2255. return false;
  2256. NewMinOffset = NewOffset;
  2257. } else if (NewOffset > LU.MaxOffset) {
  2258. if (!isAlwaysFoldable(TTI, Kind, NewAccessTy, /*BaseGV=*/nullptr,
  2259. NewOffset - LU.MinOffset, HasBaseReg))
  2260. return false;
  2261. NewMaxOffset = NewOffset;
  2262. }
  2263. // Update the use.
  2264. LU.MinOffset = NewMinOffset;
  2265. LU.MaxOffset = NewMaxOffset;
  2266. LU.AccessTy = NewAccessTy;
  2267. return true;
  2268. }
  2269. /// Return an LSRUse index and an offset value for a fixup which needs the given
  2270. /// expression, with the given kind and optional access type. Either reuse an
  2271. /// existing use or create a new one, as needed.
  2272. std::pair<size_t, int64_t> LSRInstance::getUse(const SCEV *&Expr,
  2273. LSRUse::KindType Kind,
  2274. MemAccessTy AccessTy) {
  2275. const SCEV *Copy = Expr;
  2276. int64_t Offset = ExtractImmediate(Expr, SE);
  2277. // Basic uses can't accept any offset, for example.
  2278. if (!isAlwaysFoldable(TTI, Kind, AccessTy, /*BaseGV=*/ nullptr,
  2279. Offset, /*HasBaseReg=*/ true)) {
  2280. Expr = Copy;
  2281. Offset = 0;
  2282. }
  2283. std::pair<UseMapTy::iterator, bool> P =
  2284. UseMap.insert(std::make_pair(LSRUse::SCEVUseKindPair(Expr, Kind), 0));
  2285. if (!P.second) {
  2286. // A use already existed with this base.
  2287. size_t LUIdx = P.first->second;
  2288. LSRUse &LU = Uses[LUIdx];
  2289. if (reconcileNewOffset(LU, Offset, /*HasBaseReg=*/true, Kind, AccessTy))
  2290. // Reuse this use.
  2291. return std::make_pair(LUIdx, Offset);
  2292. }
  2293. // Create a new use.
  2294. size_t LUIdx = Uses.size();
  2295. P.first->second = LUIdx;
  2296. Uses.push_back(LSRUse(Kind, AccessTy));
  2297. LSRUse &LU = Uses[LUIdx];
  2298. LU.MinOffset = Offset;
  2299. LU.MaxOffset = Offset;
  2300. return std::make_pair(LUIdx, Offset);
  2301. }
  2302. /// Delete the given use from the Uses list.
  2303. void LSRInstance::DeleteUse(LSRUse &LU, size_t LUIdx) {
  2304. if (&LU != &Uses.back())
  2305. std::swap(LU, Uses.back());
  2306. Uses.pop_back();
  2307. // Update RegUses.
  2308. RegUses.swapAndDropUse(LUIdx, Uses.size());
  2309. }
  2310. /// Look for a use distinct from OrigLU which is has a formula that has the same
  2311. /// registers as the given formula.
  2312. LSRUse *
  2313. LSRInstance::FindUseWithSimilarFormula(const Formula &OrigF,
  2314. const LSRUse &OrigLU) {
  2315. // Search all uses for the formula. This could be more clever.
  2316. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  2317. LSRUse &LU = Uses[LUIdx];
  2318. // Check whether this use is close enough to OrigLU, to see whether it's
  2319. // worthwhile looking through its formulae.
  2320. // Ignore ICmpZero uses because they may contain formulae generated by
  2321. // GenerateICmpZeroScales, in which case adding fixup offsets may
  2322. // be invalid.
  2323. if (&LU != &OrigLU &&
  2324. LU.Kind != LSRUse::ICmpZero &&
  2325. LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
  2326. LU.WidestFixupType == OrigLU.WidestFixupType &&
  2327. LU.HasFormulaWithSameRegs(OrigF)) {
  2328. // Scan through this use's formulae.
  2329. for (const Formula &F : LU.Formulae) {
  2330. // Check to see if this formula has the same registers and symbols
  2331. // as OrigF.
  2332. if (F.BaseRegs == OrigF.BaseRegs &&
  2333. F.ScaledReg == OrigF.ScaledReg &&
  2334. F.BaseGV == OrigF.BaseGV &&
  2335. F.Scale == OrigF.Scale &&
  2336. F.UnfoldedOffset == OrigF.UnfoldedOffset) {
  2337. if (F.BaseOffset == 0)
  2338. return &LU;
  2339. // This is the formula where all the registers and symbols matched;
  2340. // there aren't going to be any others. Since we declined it, we
  2341. // can skip the rest of the formulae and proceed to the next LSRUse.
  2342. break;
  2343. }
  2344. }
  2345. }
  2346. }
  2347. // Nothing looked good.
  2348. return nullptr;
  2349. }
  2350. void LSRInstance::CollectInterestingTypesAndFactors() {
  2351. SmallSetVector<const SCEV *, 4> Strides;
  2352. // Collect interesting types and strides.
  2353. SmallVector<const SCEV *, 4> Worklist;
  2354. for (const IVStrideUse &U : IU) {
  2355. const SCEV *Expr = IU.getExpr(U);
  2356. // Collect interesting types.
  2357. Types.insert(SE.getEffectiveSCEVType(Expr->getType()));
  2358. // Add strides for mentioned loops.
  2359. Worklist.push_back(Expr);
  2360. do {
  2361. const SCEV *S = Worklist.pop_back_val();
  2362. if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  2363. if (AR->getLoop() == L)
  2364. Strides.insert(AR->getStepRecurrence(SE));
  2365. Worklist.push_back(AR->getStart());
  2366. } else if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  2367. Worklist.append(Add->op_begin(), Add->op_end());
  2368. }
  2369. } while (!Worklist.empty());
  2370. }
  2371. // Compute interesting factors from the set of interesting strides.
  2372. for (SmallSetVector<const SCEV *, 4>::const_iterator
  2373. I = Strides.begin(), E = Strides.end(); I != E; ++I)
  2374. for (SmallSetVector<const SCEV *, 4>::const_iterator NewStrideIter =
  2375. std::next(I); NewStrideIter != E; ++NewStrideIter) {
  2376. const SCEV *OldStride = *I;
  2377. const SCEV *NewStride = *NewStrideIter;
  2378. if (SE.getTypeSizeInBits(OldStride->getType()) !=
  2379. SE.getTypeSizeInBits(NewStride->getType())) {
  2380. if (SE.getTypeSizeInBits(OldStride->getType()) >
  2381. SE.getTypeSizeInBits(NewStride->getType()))
  2382. NewStride = SE.getSignExtendExpr(NewStride, OldStride->getType());
  2383. else
  2384. OldStride = SE.getSignExtendExpr(OldStride, NewStride->getType());
  2385. }
  2386. if (const SCEVConstant *Factor =
  2387. dyn_cast_or_null<SCEVConstant>(getExactSDiv(NewStride, OldStride,
  2388. SE, true))) {
  2389. if (Factor->getAPInt().getMinSignedBits() <= 64 && !Factor->isZero())
  2390. Factors.insert(Factor->getAPInt().getSExtValue());
  2391. } else if (const SCEVConstant *Factor =
  2392. dyn_cast_or_null<SCEVConstant>(getExactSDiv(OldStride,
  2393. NewStride,
  2394. SE, true))) {
  2395. if (Factor->getAPInt().getMinSignedBits() <= 64 && !Factor->isZero())
  2396. Factors.insert(Factor->getAPInt().getSExtValue());
  2397. }
  2398. }
  2399. // If all uses use the same type, don't bother looking for truncation-based
  2400. // reuse.
  2401. if (Types.size() == 1)
  2402. Types.clear();
  2403. LLVM_DEBUG(print_factors_and_types(dbgs()));
  2404. }
  2405. /// Helper for CollectChains that finds an IV operand (computed by an AddRec in
  2406. /// this loop) within [OI,OE) or returns OE. If IVUsers mapped Instructions to
  2407. /// IVStrideUses, we could partially skip this.
  2408. static User::op_iterator
  2409. findIVOperand(User::op_iterator OI, User::op_iterator OE,
  2410. Loop *L, ScalarEvolution &SE) {
  2411. for(; OI != OE; ++OI) {
  2412. if (Instruction *Oper = dyn_cast<Instruction>(*OI)) {
  2413. if (!SE.isSCEVable(Oper->getType()))
  2414. continue;
  2415. if (const SCEVAddRecExpr *AR =
  2416. dyn_cast<SCEVAddRecExpr>(SE.getSCEV(Oper))) {
  2417. if (AR->getLoop() == L)
  2418. break;
  2419. }
  2420. }
  2421. }
  2422. return OI;
  2423. }
  2424. /// IVChain logic must consistently peek base TruncInst operands, so wrap it in
  2425. /// a convenient helper.
  2426. static Value *getWideOperand(Value *Oper) {
  2427. if (TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
  2428. return Trunc->getOperand(0);
  2429. return Oper;
  2430. }
  2431. /// Return true if we allow an IV chain to include both types.
  2432. static bool isCompatibleIVType(Value *LVal, Value *RVal) {
  2433. Type *LType = LVal->getType();
  2434. Type *RType = RVal->getType();
  2435. return (LType == RType) || (LType->isPointerTy() && RType->isPointerTy() &&
  2436. // Different address spaces means (possibly)
  2437. // different types of the pointer implementation,
  2438. // e.g. i16 vs i32 so disallow that.
  2439. (LType->getPointerAddressSpace() ==
  2440. RType->getPointerAddressSpace()));
  2441. }
  2442. /// Return an approximation of this SCEV expression's "base", or NULL for any
  2443. /// constant. Returning the expression itself is conservative. Returning a
  2444. /// deeper subexpression is more precise and valid as long as it isn't less
  2445. /// complex than another subexpression. For expressions involving multiple
  2446. /// unscaled values, we need to return the pointer-type SCEVUnknown. This avoids
  2447. /// forming chains across objects, such as: PrevOper==a[i], IVOper==b[i],
  2448. /// IVInc==b-a.
  2449. ///
  2450. /// Since SCEVUnknown is the rightmost type, and pointers are the rightmost
  2451. /// SCEVUnknown, we simply return the rightmost SCEV operand.
  2452. static const SCEV *getExprBase(const SCEV *S) {
  2453. switch (S->getSCEVType()) {
  2454. default: // uncluding scUnknown.
  2455. return S;
  2456. case scConstant:
  2457. return nullptr;
  2458. case scTruncate:
  2459. return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
  2460. case scZeroExtend:
  2461. return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
  2462. case scSignExtend:
  2463. return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
  2464. case scAddExpr: {
  2465. // Skip over scaled operands (scMulExpr) to follow add operands as long as
  2466. // there's nothing more complex.
  2467. // FIXME: not sure if we want to recognize negation.
  2468. const SCEVAddExpr *Add = cast<SCEVAddExpr>(S);
  2469. for (const SCEV *SubExpr : reverse(Add->operands())) {
  2470. if (SubExpr->getSCEVType() == scAddExpr)
  2471. return getExprBase(SubExpr);
  2472. if (SubExpr->getSCEVType() != scMulExpr)
  2473. return SubExpr;
  2474. }
  2475. return S; // all operands are scaled, be conservative.
  2476. }
  2477. case scAddRecExpr:
  2478. return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
  2479. }
  2480. llvm_unreachable("Unknown SCEV kind!");
  2481. }
  2482. /// Return true if the chain increment is profitable to expand into a loop
  2483. /// invariant value, which may require its own register. A profitable chain
  2484. /// increment will be an offset relative to the same base. We allow such offsets
  2485. /// to potentially be used as chain increment as long as it's not obviously
  2486. /// expensive to expand using real instructions.
  2487. bool IVChain::isProfitableIncrement(const SCEV *OperExpr,
  2488. const SCEV *IncExpr,
  2489. ScalarEvolution &SE) {
  2490. // Aggressively form chains when -stress-ivchain.
  2491. if (StressIVChain)
  2492. return true;
  2493. // Do not replace a constant offset from IV head with a nonconstant IV
  2494. // increment.
  2495. if (!isa<SCEVConstant>(IncExpr)) {
  2496. const SCEV *HeadExpr = SE.getSCEV(getWideOperand(Incs[0].IVOperand));
  2497. if (isa<SCEVConstant>(SE.getMinusSCEV(OperExpr, HeadExpr)))
  2498. return false;
  2499. }
  2500. SmallPtrSet<const SCEV*, 8> Processed;
  2501. return !isHighCostExpansion(IncExpr, Processed, SE);
  2502. }
  2503. /// Return true if the number of registers needed for the chain is estimated to
  2504. /// be less than the number required for the individual IV users. First prohibit
  2505. /// any IV users that keep the IV live across increments (the Users set should
  2506. /// be empty). Next count the number and type of increments in the chain.
  2507. ///
  2508. /// Chaining IVs can lead to considerable code bloat if ISEL doesn't
  2509. /// effectively use postinc addressing modes. Only consider it profitable it the
  2510. /// increments can be computed in fewer registers when chained.
  2511. ///
  2512. /// TODO: Consider IVInc free if it's already used in another chains.
  2513. static bool isProfitableChain(IVChain &Chain,
  2514. SmallPtrSetImpl<Instruction *> &Users,
  2515. ScalarEvolution &SE,
  2516. const TargetTransformInfo &TTI) {
  2517. if (StressIVChain)
  2518. return true;
  2519. if (!Chain.hasIncs())
  2520. return false;
  2521. if (!Users.empty()) {
  2522. LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " users:\n";
  2523. for (Instruction *Inst
  2524. : Users) { dbgs() << " " << *Inst << "\n"; });
  2525. return false;
  2526. }
  2527. assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
  2528. // The chain itself may require a register, so intialize cost to 1.
  2529. int cost = 1;
  2530. // A complete chain likely eliminates the need for keeping the original IV in
  2531. // a register. LSR does not currently know how to form a complete chain unless
  2532. // the header phi already exists.
  2533. if (isa<PHINode>(Chain.tailUserInst())
  2534. && SE.getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
  2535. --cost;
  2536. }
  2537. const SCEV *LastIncExpr = nullptr;
  2538. unsigned NumConstIncrements = 0;
  2539. unsigned NumVarIncrements = 0;
  2540. unsigned NumReusedIncrements = 0;
  2541. if (TTI.isProfitableLSRChainElement(Chain.Incs[0].UserInst))
  2542. return true;
  2543. for (const IVInc &Inc : Chain) {
  2544. if (TTI.isProfitableLSRChainElement(Inc.UserInst))
  2545. return true;
  2546. if (Inc.IncExpr->isZero())
  2547. continue;
  2548. // Incrementing by zero or some constant is neutral. We assume constants can
  2549. // be folded into an addressing mode or an add's immediate operand.
  2550. if (isa<SCEVConstant>(Inc.IncExpr)) {
  2551. ++NumConstIncrements;
  2552. continue;
  2553. }
  2554. if (Inc.IncExpr == LastIncExpr)
  2555. ++NumReusedIncrements;
  2556. else
  2557. ++NumVarIncrements;
  2558. LastIncExpr = Inc.IncExpr;
  2559. }
  2560. // An IV chain with a single increment is handled by LSR's postinc
  2561. // uses. However, a chain with multiple increments requires keeping the IV's
  2562. // value live longer than it needs to be if chained.
  2563. if (NumConstIncrements > 1)
  2564. --cost;
  2565. // Materializing increment expressions in the preheader that didn't exist in
  2566. // the original code may cost a register. For example, sign-extended array
  2567. // indices can produce ridiculous increments like this:
  2568. // IV + ((sext i32 (2 * %s) to i64) + (-1 * (sext i32 %s to i64)))
  2569. cost += NumVarIncrements;
  2570. // Reusing variable increments likely saves a register to hold the multiple of
  2571. // the stride.
  2572. cost -= NumReusedIncrements;
  2573. LLVM_DEBUG(dbgs() << "Chain: " << *Chain.Incs[0].UserInst << " Cost: " << cost
  2574. << "\n");
  2575. return cost < 0;
  2576. }
  2577. /// Add this IV user to an existing chain or make it the head of a new chain.
  2578. void LSRInstance::ChainInstruction(Instruction *UserInst, Instruction *IVOper,
  2579. SmallVectorImpl<ChainUsers> &ChainUsersVec) {
  2580. // When IVs are used as types of varying widths, they are generally converted
  2581. // to a wider type with some uses remaining narrow under a (free) trunc.
  2582. Value *const NextIV = getWideOperand(IVOper);
  2583. const SCEV *const OperExpr = SE.getSCEV(NextIV);
  2584. const SCEV *const OperExprBase = getExprBase(OperExpr);
  2585. // Visit all existing chains. Check if its IVOper can be computed as a
  2586. // profitable loop invariant increment from the last link in the Chain.
  2587. unsigned ChainIdx = 0, NChains = IVChainVec.size();
  2588. const SCEV *LastIncExpr = nullptr;
  2589. for (; ChainIdx < NChains; ++ChainIdx) {
  2590. IVChain &Chain = IVChainVec[ChainIdx];
  2591. // Prune the solution space aggressively by checking that both IV operands
  2592. // are expressions that operate on the same unscaled SCEVUnknown. This
  2593. // "base" will be canceled by the subsequent getMinusSCEV call. Checking
  2594. // first avoids creating extra SCEV expressions.
  2595. if (!StressIVChain && Chain.ExprBase != OperExprBase)
  2596. continue;
  2597. Value *PrevIV = getWideOperand(Chain.Incs.back().IVOperand);
  2598. if (!isCompatibleIVType(PrevIV, NextIV))
  2599. continue;
  2600. // A phi node terminates a chain.
  2601. if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
  2602. continue;
  2603. // The increment must be loop-invariant so it can be kept in a register.
  2604. const SCEV *PrevExpr = SE.getSCEV(PrevIV);
  2605. const SCEV *IncExpr = SE.getMinusSCEV(OperExpr, PrevExpr);
  2606. if (isa<SCEVCouldNotCompute>(IncExpr) || !SE.isLoopInvariant(IncExpr, L))
  2607. continue;
  2608. if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
  2609. LastIncExpr = IncExpr;
  2610. break;
  2611. }
  2612. }
  2613. // If we haven't found a chain, create a new one, unless we hit the max. Don't
  2614. // bother for phi nodes, because they must be last in the chain.
  2615. if (ChainIdx == NChains) {
  2616. if (isa<PHINode>(UserInst))
  2617. return;
  2618. if (NChains >= MaxChains && !StressIVChain) {
  2619. LLVM_DEBUG(dbgs() << "IV Chain Limit\n");
  2620. return;
  2621. }
  2622. LastIncExpr = OperExpr;
  2623. // IVUsers may have skipped over sign/zero extensions. We don't currently
  2624. // attempt to form chains involving extensions unless they can be hoisted
  2625. // into this loop's AddRec.
  2626. if (!isa<SCEVAddRecExpr>(LastIncExpr))
  2627. return;
  2628. ++NChains;
  2629. IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
  2630. OperExprBase));
  2631. ChainUsersVec.resize(NChains);
  2632. LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Head: (" << *UserInst
  2633. << ") IV=" << *LastIncExpr << "\n");
  2634. } else {
  2635. LLVM_DEBUG(dbgs() << "IV Chain#" << ChainIdx << " Inc: (" << *UserInst
  2636. << ") IV+" << *LastIncExpr << "\n");
  2637. // Add this IV user to the end of the chain.
  2638. IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
  2639. }
  2640. IVChain &Chain = IVChainVec[ChainIdx];
  2641. SmallPtrSet<Instruction*,4> &NearUsers = ChainUsersVec[ChainIdx].NearUsers;
  2642. // This chain's NearUsers become FarUsers.
  2643. if (!LastIncExpr->isZero()) {
  2644. ChainUsersVec[ChainIdx].FarUsers.insert(NearUsers.begin(),
  2645. NearUsers.end());
  2646. NearUsers.clear();
  2647. }
  2648. // All other uses of IVOperand become near uses of the chain.
  2649. // We currently ignore intermediate values within SCEV expressions, assuming
  2650. // they will eventually be used be the current chain, or can be computed
  2651. // from one of the chain increments. To be more precise we could
  2652. // transitively follow its user and only add leaf IV users to the set.
  2653. for (User *U : IVOper->users()) {
  2654. Instruction *OtherUse = dyn_cast<Instruction>(U);
  2655. if (!OtherUse)
  2656. continue;
  2657. // Uses in the chain will no longer be uses if the chain is formed.
  2658. // Include the head of the chain in this iteration (not Chain.begin()).
  2659. IVChain::const_iterator IncIter = Chain.Incs.begin();
  2660. IVChain::const_iterator IncEnd = Chain.Incs.end();
  2661. for( ; IncIter != IncEnd; ++IncIter) {
  2662. if (IncIter->UserInst == OtherUse)
  2663. break;
  2664. }
  2665. if (IncIter != IncEnd)
  2666. continue;
  2667. if (SE.isSCEVable(OtherUse->getType())
  2668. && !isa<SCEVUnknown>(SE.getSCEV(OtherUse))
  2669. && IU.isIVUserOrOperand(OtherUse)) {
  2670. continue;
  2671. }
  2672. NearUsers.insert(OtherUse);
  2673. }
  2674. // Since this user is part of the chain, it's no longer considered a use
  2675. // of the chain.
  2676. ChainUsersVec[ChainIdx].FarUsers.erase(UserInst);
  2677. }
  2678. /// Populate the vector of Chains.
  2679. ///
  2680. /// This decreases ILP at the architecture level. Targets with ample registers,
  2681. /// multiple memory ports, and no register renaming probably don't want
  2682. /// this. However, such targets should probably disable LSR altogether.
  2683. ///
  2684. /// The job of LSR is to make a reasonable choice of induction variables across
  2685. /// the loop. Subsequent passes can easily "unchain" computation exposing more
  2686. /// ILP *within the loop* if the target wants it.
  2687. ///
  2688. /// Finding the best IV chain is potentially a scheduling problem. Since LSR
  2689. /// will not reorder memory operations, it will recognize this as a chain, but
  2690. /// will generate redundant IV increments. Ideally this would be corrected later
  2691. /// by a smart scheduler:
  2692. /// = A[i]
  2693. /// = A[i+x]
  2694. /// A[i] =
  2695. /// A[i+x] =
  2696. ///
  2697. /// TODO: Walk the entire domtree within this loop, not just the path to the
  2698. /// loop latch. This will discover chains on side paths, but requires
  2699. /// maintaining multiple copies of the Chains state.
  2700. void LSRInstance::CollectChains() {
  2701. LLVM_DEBUG(dbgs() << "Collecting IV Chains.\n");
  2702. SmallVector<ChainUsers, 8> ChainUsersVec;
  2703. SmallVector<BasicBlock *,8> LatchPath;
  2704. BasicBlock *LoopHeader = L->getHeader();
  2705. for (DomTreeNode *Rung = DT.getNode(L->getLoopLatch());
  2706. Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
  2707. LatchPath.push_back(Rung->getBlock());
  2708. }
  2709. LatchPath.push_back(LoopHeader);
  2710. // Walk the instruction stream from the loop header to the loop latch.
  2711. for (BasicBlock *BB : reverse(LatchPath)) {
  2712. for (Instruction &I : *BB) {
  2713. // Skip instructions that weren't seen by IVUsers analysis.
  2714. if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I))
  2715. continue;
  2716. // Ignore users that are part of a SCEV expression. This way we only
  2717. // consider leaf IV Users. This effectively rediscovers a portion of
  2718. // IVUsers analysis but in program order this time.
  2719. if (SE.isSCEVable(I.getType()) && !isa<SCEVUnknown>(SE.getSCEV(&I)))
  2720. continue;
  2721. // Remove this instruction from any NearUsers set it may be in.
  2722. for (unsigned ChainIdx = 0, NChains = IVChainVec.size();
  2723. ChainIdx < NChains; ++ChainIdx) {
  2724. ChainUsersVec[ChainIdx].NearUsers.erase(&I);
  2725. }
  2726. // Search for operands that can be chained.
  2727. SmallPtrSet<Instruction*, 4> UniqueOperands;
  2728. User::op_iterator IVOpEnd = I.op_end();
  2729. User::op_iterator IVOpIter = findIVOperand(I.op_begin(), IVOpEnd, L, SE);
  2730. while (IVOpIter != IVOpEnd) {
  2731. Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
  2732. if (UniqueOperands.insert(IVOpInst).second)
  2733. ChainInstruction(&I, IVOpInst, ChainUsersVec);
  2734. IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
  2735. }
  2736. } // Continue walking down the instructions.
  2737. } // Continue walking down the domtree.
  2738. // Visit phi backedges to determine if the chain can generate the IV postinc.
  2739. for (PHINode &PN : L->getHeader()->phis()) {
  2740. if (!SE.isSCEVable(PN.getType()))
  2741. continue;
  2742. Instruction *IncV =
  2743. dyn_cast<Instruction>(PN.getIncomingValueForBlock(L->getLoopLatch()));
  2744. if (IncV)
  2745. ChainInstruction(&PN, IncV, ChainUsersVec);
  2746. }
  2747. // Remove any unprofitable chains.
  2748. unsigned ChainIdx = 0;
  2749. for (unsigned UsersIdx = 0, NChains = IVChainVec.size();
  2750. UsersIdx < NChains; ++UsersIdx) {
  2751. if (!isProfitableChain(IVChainVec[UsersIdx],
  2752. ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
  2753. continue;
  2754. // Preserve the chain at UsesIdx.
  2755. if (ChainIdx != UsersIdx)
  2756. IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
  2757. FinalizeChain(IVChainVec[ChainIdx]);
  2758. ++ChainIdx;
  2759. }
  2760. IVChainVec.resize(ChainIdx);
  2761. }
  2762. void LSRInstance::FinalizeChain(IVChain &Chain) {
  2763. assert(!Chain.Incs.empty() && "empty IV chains are not allowed");
  2764. LLVM_DEBUG(dbgs() << "Final Chain: " << *Chain.Incs[0].UserInst << "\n");
  2765. for (const IVInc &Inc : Chain) {
  2766. LLVM_DEBUG(dbgs() << " Inc: " << *Inc.UserInst << "\n");
  2767. auto UseI = find(Inc.UserInst->operands(), Inc.IVOperand);
  2768. assert(UseI != Inc.UserInst->op_end() && "cannot find IV operand");
  2769. IVIncSet.insert(UseI);
  2770. }
  2771. }
  2772. /// Return true if the IVInc can be folded into an addressing mode.
  2773. static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst,
  2774. Value *Operand, const TargetTransformInfo &TTI) {
  2775. const SCEVConstant *IncConst = dyn_cast<SCEVConstant>(IncExpr);
  2776. if (!IncConst || !isAddressUse(TTI, UserInst, Operand))
  2777. return false;
  2778. if (IncConst->getAPInt().getMinSignedBits() > 64)
  2779. return false;
  2780. MemAccessTy AccessTy = getAccessType(TTI, UserInst, Operand);
  2781. int64_t IncOffset = IncConst->getValue()->getSExtValue();
  2782. if (!isAlwaysFoldable(TTI, LSRUse::Address, AccessTy, /*BaseGV=*/nullptr,
  2783. IncOffset, /*HasBaseReg=*/false))
  2784. return false;
  2785. return true;
  2786. }
  2787. /// Generate an add or subtract for each IVInc in a chain to materialize the IV
  2788. /// user's operand from the previous IV user's operand.
  2789. void LSRInstance::GenerateIVChain(const IVChain &Chain, SCEVExpander &Rewriter,
  2790. SmallVectorImpl<WeakTrackingVH> &DeadInsts) {
  2791. // Find the new IVOperand for the head of the chain. It may have been replaced
  2792. // by LSR.
  2793. const IVInc &Head = Chain.Incs[0];
  2794. User::op_iterator IVOpEnd = Head.UserInst->op_end();
  2795. // findIVOperand returns IVOpEnd if it can no longer find a valid IV user.
  2796. User::op_iterator IVOpIter = findIVOperand(Head.UserInst->op_begin(),
  2797. IVOpEnd, L, SE);
  2798. Value *IVSrc = nullptr;
  2799. while (IVOpIter != IVOpEnd) {
  2800. IVSrc = getWideOperand(*IVOpIter);
  2801. // If this operand computes the expression that the chain needs, we may use
  2802. // it. (Check this after setting IVSrc which is used below.)
  2803. //
  2804. // Note that if Head.IncExpr is wider than IVSrc, then this phi is too
  2805. // narrow for the chain, so we can no longer use it. We do allow using a
  2806. // wider phi, assuming the LSR checked for free truncation. In that case we
  2807. // should already have a truncate on this operand such that
  2808. // getSCEV(IVSrc) == IncExpr.
  2809. if (SE.getSCEV(*IVOpIter) == Head.IncExpr
  2810. || SE.getSCEV(IVSrc) == Head.IncExpr) {
  2811. break;
  2812. }
  2813. IVOpIter = findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
  2814. }
  2815. if (IVOpIter == IVOpEnd) {
  2816. // Gracefully give up on this chain.
  2817. LLVM_DEBUG(dbgs() << "Concealed chain head: " << *Head.UserInst << "\n");
  2818. return;
  2819. }
  2820. assert(IVSrc && "Failed to find IV chain source");
  2821. LLVM_DEBUG(dbgs() << "Generate chain at: " << *IVSrc << "\n");
  2822. Type *IVTy = IVSrc->getType();
  2823. Type *IntTy = SE.getEffectiveSCEVType(IVTy);
  2824. const SCEV *LeftOverExpr = nullptr;
  2825. for (const IVInc &Inc : Chain) {
  2826. Instruction *InsertPt = Inc.UserInst;
  2827. if (isa<PHINode>(InsertPt))
  2828. InsertPt = L->getLoopLatch()->getTerminator();
  2829. // IVOper will replace the current IV User's operand. IVSrc is the IV
  2830. // value currently held in a register.
  2831. Value *IVOper = IVSrc;
  2832. if (!Inc.IncExpr->isZero()) {
  2833. // IncExpr was the result of subtraction of two narrow values, so must
  2834. // be signed.
  2835. const SCEV *IncExpr = SE.getNoopOrSignExtend(Inc.IncExpr, IntTy);
  2836. LeftOverExpr = LeftOverExpr ?
  2837. SE.getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
  2838. }
  2839. if (LeftOverExpr && !LeftOverExpr->isZero()) {
  2840. // Expand the IV increment.
  2841. Rewriter.clearPostInc();
  2842. Value *IncV = Rewriter.expandCodeFor(LeftOverExpr, IntTy, InsertPt);
  2843. const SCEV *IVOperExpr = SE.getAddExpr(SE.getUnknown(IVSrc),
  2844. SE.getUnknown(IncV));
  2845. IVOper = Rewriter.expandCodeFor(IVOperExpr, IVTy, InsertPt);
  2846. // If an IV increment can't be folded, use it as the next IV value.
  2847. if (!canFoldIVIncExpr(LeftOverExpr, Inc.UserInst, Inc.IVOperand, TTI)) {
  2848. assert(IVTy == IVOper->getType() && "inconsistent IV increment type");
  2849. IVSrc = IVOper;
  2850. LeftOverExpr = nullptr;
  2851. }
  2852. }
  2853. Type *OperTy = Inc.IVOperand->getType();
  2854. if (IVTy != OperTy) {
  2855. assert(SE.getTypeSizeInBits(IVTy) >= SE.getTypeSizeInBits(OperTy) &&
  2856. "cannot extend a chained IV");
  2857. IRBuilder<> Builder(InsertPt);
  2858. IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy, "lsr.chain");
  2859. }
  2860. Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
  2861. if (auto *OperandIsInstr = dyn_cast<Instruction>(Inc.IVOperand))
  2862. DeadInsts.emplace_back(OperandIsInstr);
  2863. }
  2864. // If LSR created a new, wider phi, we may also replace its postinc. We only
  2865. // do this if we also found a wide value for the head of the chain.
  2866. if (isa<PHINode>(Chain.tailUserInst())) {
  2867. for (PHINode &Phi : L->getHeader()->phis()) {
  2868. if (!isCompatibleIVType(&Phi, IVSrc))
  2869. continue;
  2870. Instruction *PostIncV = dyn_cast<Instruction>(
  2871. Phi.getIncomingValueForBlock(L->getLoopLatch()));
  2872. if (!PostIncV || (SE.getSCEV(PostIncV) != SE.getSCEV(IVSrc)))
  2873. continue;
  2874. Value *IVOper = IVSrc;
  2875. Type *PostIncTy = PostIncV->getType();
  2876. if (IVTy != PostIncTy) {
  2877. assert(PostIncTy->isPointerTy() && "mixing int/ptr IV types");
  2878. IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
  2879. Builder.SetCurrentDebugLocation(PostIncV->getDebugLoc());
  2880. IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy, "lsr.chain");
  2881. }
  2882. Phi.replaceUsesOfWith(PostIncV, IVOper);
  2883. DeadInsts.emplace_back(PostIncV);
  2884. }
  2885. }
  2886. }
  2887. void LSRInstance::CollectFixupsAndInitialFormulae() {
  2888. BranchInst *ExitBranch = nullptr;
  2889. bool SaveCmp = TTI.canSaveCmp(L, &ExitBranch, &SE, &LI, &DT, &AC, &TLI);
  2890. for (const IVStrideUse &U : IU) {
  2891. Instruction *UserInst = U.getUser();
  2892. // Skip IV users that are part of profitable IV Chains.
  2893. User::op_iterator UseI =
  2894. find(UserInst->operands(), U.getOperandValToReplace());
  2895. assert(UseI != UserInst->op_end() && "cannot find IV operand");
  2896. if (IVIncSet.count(UseI)) {
  2897. LLVM_DEBUG(dbgs() << "Use is in profitable chain: " << **UseI << '\n');
  2898. continue;
  2899. }
  2900. LSRUse::KindType Kind = LSRUse::Basic;
  2901. MemAccessTy AccessTy;
  2902. if (isAddressUse(TTI, UserInst, U.getOperandValToReplace())) {
  2903. Kind = LSRUse::Address;
  2904. AccessTy = getAccessType(TTI, UserInst, U.getOperandValToReplace());
  2905. }
  2906. const SCEV *S = IU.getExpr(U);
  2907. PostIncLoopSet TmpPostIncLoops = U.getPostIncLoops();
  2908. // Equality (== and !=) ICmps are special. We can rewrite (i == N) as
  2909. // (N - i == 0), and this allows (N - i) to be the expression that we work
  2910. // with rather than just N or i, so we can consider the register
  2911. // requirements for both N and i at the same time. Limiting this code to
  2912. // equality icmps is not a problem because all interesting loops use
  2913. // equality icmps, thanks to IndVarSimplify.
  2914. if (ICmpInst *CI = dyn_cast<ICmpInst>(UserInst)) {
  2915. // If CI can be saved in some target, like replaced inside hardware loop
  2916. // in PowerPC, no need to generate initial formulae for it.
  2917. if (SaveCmp && CI == dyn_cast<ICmpInst>(ExitBranch->getCondition()))
  2918. continue;
  2919. if (CI->isEquality()) {
  2920. // Swap the operands if needed to put the OperandValToReplace on the
  2921. // left, for consistency.
  2922. Value *NV = CI->getOperand(1);
  2923. if (NV == U.getOperandValToReplace()) {
  2924. CI->setOperand(1, CI->getOperand(0));
  2925. CI->setOperand(0, NV);
  2926. NV = CI->getOperand(1);
  2927. Changed = true;
  2928. }
  2929. // x == y --> x - y == 0
  2930. const SCEV *N = SE.getSCEV(NV);
  2931. if (SE.isLoopInvariant(N, L) && isSafeToExpand(N, SE) &&
  2932. (!NV->getType()->isPointerTy() ||
  2933. SE.getPointerBase(N) == SE.getPointerBase(S))) {
  2934. // S is normalized, so normalize N before folding it into S
  2935. // to keep the result normalized.
  2936. N = normalizeForPostIncUse(N, TmpPostIncLoops, SE);
  2937. Kind = LSRUse::ICmpZero;
  2938. S = SE.getMinusSCEV(N, S);
  2939. }
  2940. // -1 and the negations of all interesting strides (except the negation
  2941. // of -1) are now also interesting.
  2942. for (size_t i = 0, e = Factors.size(); i != e; ++i)
  2943. if (Factors[i] != -1)
  2944. Factors.insert(-(uint64_t)Factors[i]);
  2945. Factors.insert(-1);
  2946. }
  2947. }
  2948. // Get or create an LSRUse.
  2949. std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
  2950. size_t LUIdx = P.first;
  2951. int64_t Offset = P.second;
  2952. LSRUse &LU = Uses[LUIdx];
  2953. // Record the fixup.
  2954. LSRFixup &LF = LU.getNewFixup();
  2955. LF.UserInst = UserInst;
  2956. LF.OperandValToReplace = U.getOperandValToReplace();
  2957. LF.PostIncLoops = TmpPostIncLoops;
  2958. LF.Offset = Offset;
  2959. LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
  2960. if (!LU.WidestFixupType ||
  2961. SE.getTypeSizeInBits(LU.WidestFixupType) <
  2962. SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
  2963. LU.WidestFixupType = LF.OperandValToReplace->getType();
  2964. // If this is the first use of this LSRUse, give it a formula.
  2965. if (LU.Formulae.empty()) {
  2966. InsertInitialFormula(S, LU, LUIdx);
  2967. CountRegisters(LU.Formulae.back(), LUIdx);
  2968. }
  2969. }
  2970. LLVM_DEBUG(print_fixups(dbgs()));
  2971. }
  2972. /// Insert a formula for the given expression into the given use, separating out
  2973. /// loop-variant portions from loop-invariant and loop-computable portions.
  2974. void
  2975. LSRInstance::InsertInitialFormula(const SCEV *S, LSRUse &LU, size_t LUIdx) {
  2976. // Mark uses whose expressions cannot be expanded.
  2977. if (!isSafeToExpand(S, SE, /*CanonicalMode*/ false))
  2978. LU.RigidFormula = true;
  2979. Formula F;
  2980. F.initialMatch(S, L, SE);
  2981. bool Inserted = InsertFormula(LU, LUIdx, F);
  2982. assert(Inserted && "Initial formula already exists!"); (void)Inserted;
  2983. }
  2984. /// Insert a simple single-register formula for the given expression into the
  2985. /// given use.
  2986. void
  2987. LSRInstance::InsertSupplementalFormula(const SCEV *S,
  2988. LSRUse &LU, size_t LUIdx) {
  2989. Formula F;
  2990. F.BaseRegs.push_back(S);
  2991. F.HasBaseReg = true;
  2992. bool Inserted = InsertFormula(LU, LUIdx, F);
  2993. assert(Inserted && "Supplemental formula already exists!"); (void)Inserted;
  2994. }
  2995. /// Note which registers are used by the given formula, updating RegUses.
  2996. void LSRInstance::CountRegisters(const Formula &F, size_t LUIdx) {
  2997. if (F.ScaledReg)
  2998. RegUses.countRegister(F.ScaledReg, LUIdx);
  2999. for (const SCEV *BaseReg : F.BaseRegs)
  3000. RegUses.countRegister(BaseReg, LUIdx);
  3001. }
  3002. /// If the given formula has not yet been inserted, add it to the list, and
  3003. /// return true. Return false otherwise.
  3004. bool LSRInstance::InsertFormula(LSRUse &LU, unsigned LUIdx, const Formula &F) {
  3005. // Do not insert formula that we will not be able to expand.
  3006. assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
  3007. "Formula is illegal");
  3008. if (!LU.InsertFormula(F, *L))
  3009. return false;
  3010. CountRegisters(F, LUIdx);
  3011. return true;
  3012. }
  3013. /// Check for other uses of loop-invariant values which we're tracking. These
  3014. /// other uses will pin these values in registers, making them less profitable
  3015. /// for elimination.
  3016. /// TODO: This currently misses non-constant addrec step registers.
  3017. /// TODO: Should this give more weight to users inside the loop?
  3018. void
  3019. LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
  3020. SmallVector<const SCEV *, 8> Worklist(RegUses.begin(), RegUses.end());
  3021. SmallPtrSet<const SCEV *, 32> Visited;
  3022. while (!Worklist.empty()) {
  3023. const SCEV *S = Worklist.pop_back_val();
  3024. // Don't process the same SCEV twice
  3025. if (!Visited.insert(S).second)
  3026. continue;
  3027. if (const SCEVNAryExpr *N = dyn_cast<SCEVNAryExpr>(S))
  3028. Worklist.append(N->op_begin(), N->op_end());
  3029. else if (const SCEVIntegralCastExpr *C = dyn_cast<SCEVIntegralCastExpr>(S))
  3030. Worklist.push_back(C->getOperand());
  3031. else if (const SCEVUDivExpr *D = dyn_cast<SCEVUDivExpr>(S)) {
  3032. Worklist.push_back(D->getLHS());
  3033. Worklist.push_back(D->getRHS());
  3034. } else if (const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
  3035. const Value *V = US->getValue();
  3036. if (const Instruction *Inst = dyn_cast<Instruction>(V)) {
  3037. // Look for instructions defined outside the loop.
  3038. if (L->contains(Inst)) continue;
  3039. } else if (isa<UndefValue>(V))
  3040. // Undef doesn't have a live range, so it doesn't matter.
  3041. continue;
  3042. for (const Use &U : V->uses()) {
  3043. const Instruction *UserInst = dyn_cast<Instruction>(U.getUser());
  3044. // Ignore non-instructions.
  3045. if (!UserInst)
  3046. continue;
  3047. // Don't bother if the instruction is an EHPad.
  3048. if (UserInst->isEHPad())
  3049. continue;
  3050. // Ignore instructions in other functions (as can happen with
  3051. // Constants).
  3052. if (UserInst->getParent()->getParent() != L->getHeader()->getParent())
  3053. continue;
  3054. // Ignore instructions not dominated by the loop.
  3055. const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
  3056. UserInst->getParent() :
  3057. cast<PHINode>(UserInst)->getIncomingBlock(
  3058. PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
  3059. if (!DT.dominates(L->getHeader(), UseBB))
  3060. continue;
  3061. // Don't bother if the instruction is in a BB which ends in an EHPad.
  3062. if (UseBB->getTerminator()->isEHPad())
  3063. continue;
  3064. // Ignore cases in which the currently-examined value could come from
  3065. // a basic block terminated with an EHPad. This checks all incoming
  3066. // blocks of the phi node since it is possible that the same incoming
  3067. // value comes from multiple basic blocks, only some of which may end
  3068. // in an EHPad. If any of them do, a subsequent rewrite attempt by this
  3069. // pass would try to insert instructions into an EHPad, hitting an
  3070. // assertion.
  3071. if (isa<PHINode>(UserInst)) {
  3072. const auto *PhiNode = cast<PHINode>(UserInst);
  3073. bool HasIncompatibleEHPTerminatedBlock = false;
  3074. llvm::Value *ExpectedValue = U;
  3075. for (unsigned int I = 0; I < PhiNode->getNumIncomingValues(); I++) {
  3076. if (PhiNode->getIncomingValue(I) == ExpectedValue) {
  3077. if (PhiNode->getIncomingBlock(I)->getTerminator()->isEHPad()) {
  3078. HasIncompatibleEHPTerminatedBlock = true;
  3079. break;
  3080. }
  3081. }
  3082. }
  3083. if (HasIncompatibleEHPTerminatedBlock) {
  3084. continue;
  3085. }
  3086. }
  3087. // Don't bother rewriting PHIs in catchswitch blocks.
  3088. if (isa<CatchSwitchInst>(UserInst->getParent()->getTerminator()))
  3089. continue;
  3090. // Ignore uses which are part of other SCEV expressions, to avoid
  3091. // analyzing them multiple times.
  3092. if (SE.isSCEVable(UserInst->getType())) {
  3093. const SCEV *UserS = SE.getSCEV(const_cast<Instruction *>(UserInst));
  3094. // If the user is a no-op, look through to its uses.
  3095. if (!isa<SCEVUnknown>(UserS))
  3096. continue;
  3097. if (UserS == US) {
  3098. Worklist.push_back(
  3099. SE.getUnknown(const_cast<Instruction *>(UserInst)));
  3100. continue;
  3101. }
  3102. }
  3103. // Ignore icmp instructions which are already being analyzed.
  3104. if (const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
  3105. unsigned OtherIdx = !U.getOperandNo();
  3106. Value *OtherOp = const_cast<Value *>(ICI->getOperand(OtherIdx));
  3107. if (SE.hasComputableLoopEvolution(SE.getSCEV(OtherOp), L))
  3108. continue;
  3109. }
  3110. std::pair<size_t, int64_t> P = getUse(
  3111. S, LSRUse::Basic, MemAccessTy());
  3112. size_t LUIdx = P.first;
  3113. int64_t Offset = P.second;
  3114. LSRUse &LU = Uses[LUIdx];
  3115. LSRFixup &LF = LU.getNewFixup();
  3116. LF.UserInst = const_cast<Instruction *>(UserInst);
  3117. LF.OperandValToReplace = U;
  3118. LF.Offset = Offset;
  3119. LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
  3120. if (!LU.WidestFixupType ||
  3121. SE.getTypeSizeInBits(LU.WidestFixupType) <
  3122. SE.getTypeSizeInBits(LF.OperandValToReplace->getType()))
  3123. LU.WidestFixupType = LF.OperandValToReplace->getType();
  3124. InsertSupplementalFormula(US, LU, LUIdx);
  3125. CountRegisters(LU.Formulae.back(), Uses.size() - 1);
  3126. break;
  3127. }
  3128. }
  3129. }
  3130. }
  3131. /// Split S into subexpressions which can be pulled out into separate
  3132. /// registers. If C is non-null, multiply each subexpression by C.
  3133. ///
  3134. /// Return remainder expression after factoring the subexpressions captured by
  3135. /// Ops. If Ops is complete, return NULL.
  3136. static const SCEV *CollectSubexprs(const SCEV *S, const SCEVConstant *C,
  3137. SmallVectorImpl<const SCEV *> &Ops,
  3138. const Loop *L,
  3139. ScalarEvolution &SE,
  3140. unsigned Depth = 0) {
  3141. // Arbitrarily cap recursion to protect compile time.
  3142. if (Depth >= 3)
  3143. return S;
  3144. if (const SCEVAddExpr *Add = dyn_cast<SCEVAddExpr>(S)) {
  3145. // Break out add operands.
  3146. for (const SCEV *S : Add->operands()) {
  3147. const SCEV *Remainder = CollectSubexprs(S, C, Ops, L, SE, Depth+1);
  3148. if (Remainder)
  3149. Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
  3150. }
  3151. return nullptr;
  3152. } else if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
  3153. // Split a non-zero base out of an addrec.
  3154. if (AR->getStart()->isZero() || !AR->isAffine())
  3155. return S;
  3156. const SCEV *Remainder = CollectSubexprs(AR->getStart(),
  3157. C, Ops, L, SE, Depth+1);
  3158. // Split the non-zero AddRec unless it is part of a nested recurrence that
  3159. // does not pertain to this loop.
  3160. if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
  3161. Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
  3162. Remainder = nullptr;
  3163. }
  3164. if (Remainder != AR->getStart()) {
  3165. if (!Remainder)
  3166. Remainder = SE.getConstant(AR->getType(), 0);
  3167. return SE.getAddRecExpr(Remainder,
  3168. AR->getStepRecurrence(SE),
  3169. AR->getLoop(),
  3170. //FIXME: AR->getNoWrapFlags(SCEV::FlagNW)
  3171. SCEV::FlagAnyWrap);
  3172. }
  3173. } else if (const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
  3174. // Break (C * (a + b + c)) into C*a + C*b + C*c.
  3175. if (Mul->getNumOperands() != 2)
  3176. return S;
  3177. if (const SCEVConstant *Op0 =
  3178. dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
  3179. C = C ? cast<SCEVConstant>(SE.getMulExpr(C, Op0)) : Op0;
  3180. const SCEV *Remainder =
  3181. CollectSubexprs(Mul->getOperand(1), C, Ops, L, SE, Depth+1);
  3182. if (Remainder)
  3183. Ops.push_back(SE.getMulExpr(C, Remainder));
  3184. return nullptr;
  3185. }
  3186. }
  3187. return S;
  3188. }
  3189. /// Return true if the SCEV represents a value that may end up as a
  3190. /// post-increment operation.
  3191. static bool mayUsePostIncMode(const TargetTransformInfo &TTI,
  3192. LSRUse &LU, const SCEV *S, const Loop *L,
  3193. ScalarEvolution &SE) {
  3194. if (LU.Kind != LSRUse::Address ||
  3195. !LU.AccessTy.getType()->isIntOrIntVectorTy())
  3196. return false;
  3197. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
  3198. if (!AR)
  3199. return false;
  3200. const SCEV *LoopStep = AR->getStepRecurrence(SE);
  3201. if (!isa<SCEVConstant>(LoopStep))
  3202. return false;
  3203. // Check if a post-indexed load/store can be used.
  3204. if (TTI.isIndexedLoadLegal(TTI.MIM_PostInc, AR->getType()) ||
  3205. TTI.isIndexedStoreLegal(TTI.MIM_PostInc, AR->getType())) {
  3206. const SCEV *LoopStart = AR->getStart();
  3207. if (!isa<SCEVConstant>(LoopStart) && SE.isLoopInvariant(LoopStart, L))
  3208. return true;
  3209. }
  3210. return false;
  3211. }
  3212. /// Helper function for LSRInstance::GenerateReassociations.
  3213. void LSRInstance::GenerateReassociationsImpl(LSRUse &LU, unsigned LUIdx,
  3214. const Formula &Base,
  3215. unsigned Depth, size_t Idx,
  3216. bool IsScaledReg) {
  3217. const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
  3218. // Don't generate reassociations for the base register of a value that
  3219. // may generate a post-increment operator. The reason is that the
  3220. // reassociations cause extra base+register formula to be created,
  3221. // and possibly chosen, but the post-increment is more efficient.
  3222. if (AMK == TTI::AMK_PostIndexed && mayUsePostIncMode(TTI, LU, BaseReg, L, SE))
  3223. return;
  3224. SmallVector<const SCEV *, 8> AddOps;
  3225. const SCEV *Remainder = CollectSubexprs(BaseReg, nullptr, AddOps, L, SE);
  3226. if (Remainder)
  3227. AddOps.push_back(Remainder);
  3228. if (AddOps.size() == 1)
  3229. return;
  3230. for (SmallVectorImpl<const SCEV *>::const_iterator J = AddOps.begin(),
  3231. JE = AddOps.end();
  3232. J != JE; ++J) {
  3233. // Loop-variant "unknown" values are uninteresting; we won't be able to
  3234. // do anything meaningful with them.
  3235. if (isa<SCEVUnknown>(*J) && !SE.isLoopInvariant(*J, L))
  3236. continue;
  3237. // Don't pull a constant into a register if the constant could be folded
  3238. // into an immediate field.
  3239. if (isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
  3240. LU.AccessTy, *J, Base.getNumRegs() > 1))
  3241. continue;
  3242. // Collect all operands except *J.
  3243. SmallVector<const SCEV *, 8> InnerAddOps(
  3244. ((const SmallVector<const SCEV *, 8> &)AddOps).begin(), J);
  3245. InnerAddOps.append(std::next(J),
  3246. ((const SmallVector<const SCEV *, 8> &)AddOps).end());
  3247. // Don't leave just a constant behind in a register if the constant could
  3248. // be folded into an immediate field.
  3249. if (InnerAddOps.size() == 1 &&
  3250. isAlwaysFoldable(TTI, SE, LU.MinOffset, LU.MaxOffset, LU.Kind,
  3251. LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
  3252. continue;
  3253. const SCEV *InnerSum = SE.getAddExpr(InnerAddOps);
  3254. if (InnerSum->isZero())
  3255. continue;
  3256. Formula F = Base;
  3257. // Add the remaining pieces of the add back into the new formula.
  3258. const SCEVConstant *InnerSumSC = dyn_cast<SCEVConstant>(InnerSum);
  3259. if (InnerSumSC && SE.getTypeSizeInBits(InnerSumSC->getType()) <= 64 &&
  3260. TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
  3261. InnerSumSC->getValue()->getZExtValue())) {
  3262. F.UnfoldedOffset =
  3263. (uint64_t)F.UnfoldedOffset + InnerSumSC->getValue()->getZExtValue();
  3264. if (IsScaledReg)
  3265. F.ScaledReg = nullptr;
  3266. else
  3267. F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
  3268. } else if (IsScaledReg)
  3269. F.ScaledReg = InnerSum;
  3270. else
  3271. F.BaseRegs[Idx] = InnerSum;
  3272. // Add J as its own register, or an unfolded immediate.
  3273. const SCEVConstant *SC = dyn_cast<SCEVConstant>(*J);
  3274. if (SC && SE.getTypeSizeInBits(SC->getType()) <= 64 &&
  3275. TTI.isLegalAddImmediate((uint64_t)F.UnfoldedOffset +
  3276. SC->getValue()->getZExtValue()))
  3277. F.UnfoldedOffset =
  3278. (uint64_t)F.UnfoldedOffset + SC->getValue()->getZExtValue();
  3279. else
  3280. F.BaseRegs.push_back(*J);
  3281. // We may have changed the number of register in base regs, adjust the
  3282. // formula accordingly.
  3283. F.canonicalize(*L);
  3284. if (InsertFormula(LU, LUIdx, F))
  3285. // If that formula hadn't been seen before, recurse to find more like
  3286. // it.
  3287. // Add check on Log16(AddOps.size()) - same as Log2_32(AddOps.size()) >> 2)
  3288. // Because just Depth is not enough to bound compile time.
  3289. // This means that every time AddOps.size() is greater 16^x we will add
  3290. // x to Depth.
  3291. GenerateReassociations(LU, LUIdx, LU.Formulae.back(),
  3292. Depth + 1 + (Log2_32(AddOps.size()) >> 2));
  3293. }
  3294. }
  3295. /// Split out subexpressions from adds and the bases of addrecs.
  3296. void LSRInstance::GenerateReassociations(LSRUse &LU, unsigned LUIdx,
  3297. Formula Base, unsigned Depth) {
  3298. assert(Base.isCanonical(*L) && "Input must be in the canonical form");
  3299. // Arbitrarily cap recursion to protect compile time.
  3300. if (Depth >= 3)
  3301. return;
  3302. for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
  3303. GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
  3304. if (Base.Scale == 1)
  3305. GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
  3306. /* Idx */ -1, /* IsScaledReg */ true);
  3307. }
  3308. /// Generate a formula consisting of all of the loop-dominating registers added
  3309. /// into a single register.
  3310. void LSRInstance::GenerateCombinations(LSRUse &LU, unsigned LUIdx,
  3311. Formula Base) {
  3312. // This method is only interesting on a plurality of registers.
  3313. if (Base.BaseRegs.size() + (Base.Scale == 1) +
  3314. (Base.UnfoldedOffset != 0) <= 1)
  3315. return;
  3316. // Flatten the representation, i.e., reg1 + 1*reg2 => reg1 + reg2, before
  3317. // processing the formula.
  3318. Base.unscale();
  3319. SmallVector<const SCEV *, 4> Ops;
  3320. Formula NewBase = Base;
  3321. NewBase.BaseRegs.clear();
  3322. Type *CombinedIntegerType = nullptr;
  3323. for (const SCEV *BaseReg : Base.BaseRegs) {
  3324. if (SE.properlyDominates(BaseReg, L->getHeader()) &&
  3325. !SE.hasComputableLoopEvolution(BaseReg, L)) {
  3326. if (!CombinedIntegerType)
  3327. CombinedIntegerType = SE.getEffectiveSCEVType(BaseReg->getType());
  3328. Ops.push_back(BaseReg);
  3329. }
  3330. else
  3331. NewBase.BaseRegs.push_back(BaseReg);
  3332. }
  3333. // If no register is relevant, we're done.
  3334. if (Ops.size() == 0)
  3335. return;
  3336. // Utility function for generating the required variants of the combined
  3337. // registers.
  3338. auto GenerateFormula = [&](const SCEV *Sum) {
  3339. Formula F = NewBase;
  3340. // TODO: If Sum is zero, it probably means ScalarEvolution missed an
  3341. // opportunity to fold something. For now, just ignore such cases
  3342. // rather than proceed with zero in a register.
  3343. if (Sum->isZero())
  3344. return;
  3345. F.BaseRegs.push_back(Sum);
  3346. F.canonicalize(*L);
  3347. (void)InsertFormula(LU, LUIdx, F);
  3348. };
  3349. // If we collected at least two registers, generate a formula combining them.
  3350. if (Ops.size() > 1) {
  3351. SmallVector<const SCEV *, 4> OpsCopy(Ops); // Don't let SE modify Ops.
  3352. GenerateFormula(SE.getAddExpr(OpsCopy));
  3353. }
  3354. // If we have an unfolded offset, generate a formula combining it with the
  3355. // registers collected.
  3356. if (NewBase.UnfoldedOffset) {
  3357. assert(CombinedIntegerType && "Missing a type for the unfolded offset");
  3358. Ops.push_back(SE.getConstant(CombinedIntegerType, NewBase.UnfoldedOffset,
  3359. true));
  3360. NewBase.UnfoldedOffset = 0;
  3361. GenerateFormula(SE.getAddExpr(Ops));
  3362. }
  3363. }
  3364. /// Helper function for LSRInstance::GenerateSymbolicOffsets.
  3365. void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU, unsigned LUIdx,
  3366. const Formula &Base, size_t Idx,
  3367. bool IsScaledReg) {
  3368. const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
  3369. GlobalValue *GV = ExtractSymbol(G, SE);
  3370. if (G->isZero() || !GV)
  3371. return;
  3372. Formula F = Base;
  3373. F.BaseGV = GV;
  3374. if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
  3375. return;
  3376. if (IsScaledReg)
  3377. F.ScaledReg = G;
  3378. else
  3379. F.BaseRegs[Idx] = G;
  3380. (void)InsertFormula(LU, LUIdx, F);
  3381. }
  3382. /// Generate reuse formulae using symbolic offsets.
  3383. void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU, unsigned LUIdx,
  3384. Formula Base) {
  3385. // We can't add a symbolic offset if the address already contains one.
  3386. if (Base.BaseGV) return;
  3387. for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
  3388. GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
  3389. if (Base.Scale == 1)
  3390. GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, /* Idx */ -1,
  3391. /* IsScaledReg */ true);
  3392. }
  3393. /// Helper function for LSRInstance::GenerateConstantOffsets.
  3394. void LSRInstance::GenerateConstantOffsetsImpl(
  3395. LSRUse &LU, unsigned LUIdx, const Formula &Base,
  3396. const SmallVectorImpl<int64_t> &Worklist, size_t Idx, bool IsScaledReg) {
  3397. auto GenerateOffset = [&](const SCEV *G, int64_t Offset) {
  3398. Formula F = Base;
  3399. F.BaseOffset = (uint64_t)Base.BaseOffset - Offset;
  3400. if (isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F)) {
  3401. // Add the offset to the base register.
  3402. const SCEV *NewG = SE.getAddExpr(SE.getConstant(G->getType(), Offset), G);
  3403. // If it cancelled out, drop the base register, otherwise update it.
  3404. if (NewG->isZero()) {
  3405. if (IsScaledReg) {
  3406. F.Scale = 0;
  3407. F.ScaledReg = nullptr;
  3408. } else
  3409. F.deleteBaseReg(F.BaseRegs[Idx]);
  3410. F.canonicalize(*L);
  3411. } else if (IsScaledReg)
  3412. F.ScaledReg = NewG;
  3413. else
  3414. F.BaseRegs[Idx] = NewG;
  3415. (void)InsertFormula(LU, LUIdx, F);
  3416. }
  3417. };
  3418. const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
  3419. // With constant offsets and constant steps, we can generate pre-inc
  3420. // accesses by having the offset equal the step. So, for access #0 with a
  3421. // step of 8, we generate a G - 8 base which would require the first access
  3422. // to be ((G - 8) + 8),+,8. The pre-indexed access then updates the pointer
  3423. // for itself and hopefully becomes the base for other accesses. This means
  3424. // means that a single pre-indexed access can be generated to become the new
  3425. // base pointer for each iteration of the loop, resulting in no extra add/sub
  3426. // instructions for pointer updating.
  3427. if (AMK == TTI::AMK_PreIndexed && LU.Kind == LSRUse::Address) {
  3428. if (auto *GAR = dyn_cast<SCEVAddRecExpr>(G)) {
  3429. if (auto *StepRec =
  3430. dyn_cast<SCEVConstant>(GAR->getStepRecurrence(SE))) {
  3431. const APInt &StepInt = StepRec->getAPInt();
  3432. int64_t Step = StepInt.isNegative() ?
  3433. StepInt.getSExtValue() : StepInt.getZExtValue();
  3434. for (int64_t Offset : Worklist) {
  3435. Offset -= Step;
  3436. GenerateOffset(G, Offset);
  3437. }
  3438. }
  3439. }
  3440. }
  3441. for (int64_t Offset : Worklist)
  3442. GenerateOffset(G, Offset);
  3443. int64_t Imm = ExtractImmediate(G, SE);
  3444. if (G->isZero() || Imm == 0)
  3445. return;
  3446. Formula F = Base;
  3447. F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
  3448. if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
  3449. return;
  3450. if (IsScaledReg) {
  3451. F.ScaledReg = G;
  3452. } else {
  3453. F.BaseRegs[Idx] = G;
  3454. // We may generate non canonical Formula if G is a recurrent expr reg
  3455. // related with current loop while F.ScaledReg is not.
  3456. F.canonicalize(*L);
  3457. }
  3458. (void)InsertFormula(LU, LUIdx, F);
  3459. }
  3460. /// GenerateConstantOffsets - Generate reuse formulae using symbolic offsets.
  3461. void LSRInstance::GenerateConstantOffsets(LSRUse &LU, unsigned LUIdx,
  3462. Formula Base) {
  3463. // TODO: For now, just add the min and max offset, because it usually isn't
  3464. // worthwhile looking at everything inbetween.
  3465. SmallVector<int64_t, 2> Worklist;
  3466. Worklist.push_back(LU.MinOffset);
  3467. if (LU.MaxOffset != LU.MinOffset)
  3468. Worklist.push_back(LU.MaxOffset);
  3469. for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
  3470. GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
  3471. if (Base.Scale == 1)
  3472. GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, /* Idx */ -1,
  3473. /* IsScaledReg */ true);
  3474. }
  3475. /// For ICmpZero, check to see if we can scale up the comparison. For example, x
  3476. /// == y -> x*c == y*c.
  3477. void LSRInstance::GenerateICmpZeroScales(LSRUse &LU, unsigned LUIdx,
  3478. Formula Base) {
  3479. if (LU.Kind != LSRUse::ICmpZero) return;
  3480. // Determine the integer type for the base formula.
  3481. Type *IntTy = Base.getType();
  3482. if (!IntTy) return;
  3483. if (SE.getTypeSizeInBits(IntTy) > 64) return;
  3484. // Don't do this if there is more than one offset.
  3485. if (LU.MinOffset != LU.MaxOffset) return;
  3486. // Check if transformation is valid. It is illegal to multiply pointer.
  3487. if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())
  3488. return;
  3489. for (const SCEV *BaseReg : Base.BaseRegs)
  3490. if (BaseReg->getType()->isPointerTy())
  3491. return;
  3492. assert(!Base.BaseGV && "ICmpZero use is not legal!");
  3493. // Check each interesting stride.
  3494. for (int64_t Factor : Factors) {
  3495. // Check that Factor can be represented by IntTy
  3496. if (!ConstantInt::isValueValidForType(IntTy, Factor))
  3497. continue;
  3498. // Check that the multiplication doesn't overflow.
  3499. if (Base.BaseOffset == std::numeric_limits<int64_t>::min() && Factor == -1)
  3500. continue;
  3501. int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
  3502. assert(Factor != 0 && "Zero factor not expected!");
  3503. if (NewBaseOffset / Factor != Base.BaseOffset)
  3504. continue;
  3505. // If the offset will be truncated at this use, check that it is in bounds.
  3506. if (!IntTy->isPointerTy() &&
  3507. !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
  3508. continue;
  3509. // Check that multiplying with the use offset doesn't overflow.
  3510. int64_t Offset = LU.MinOffset;
  3511. if (Offset == std::numeric_limits<int64_t>::min() && Factor == -1)
  3512. continue;
  3513. Offset = (uint64_t)Offset * Factor;
  3514. if (Offset / Factor != LU.MinOffset)
  3515. continue;
  3516. // If the offset will be truncated at this use, check that it is in bounds.
  3517. if (!IntTy->isPointerTy() &&
  3518. !ConstantInt::isValueValidForType(IntTy, Offset))
  3519. continue;
  3520. Formula F = Base;
  3521. F.BaseOffset = NewBaseOffset;
  3522. // Check that this scale is legal.
  3523. if (!isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
  3524. continue;
  3525. // Compensate for the use having MinOffset built into it.
  3526. F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
  3527. const SCEV *FactorS = SE.getConstant(IntTy, Factor);
  3528. // Check that multiplying with each base register doesn't overflow.
  3529. for (size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
  3530. F.BaseRegs[i] = SE.getMulExpr(F.BaseRegs[i], FactorS);
  3531. if (getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
  3532. goto next;
  3533. }
  3534. // Check that multiplying with the scaled register doesn't overflow.
  3535. if (F.ScaledReg) {
  3536. F.ScaledReg = SE.getMulExpr(F.ScaledReg, FactorS);
  3537. if (getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
  3538. continue;
  3539. }
  3540. // Check that multiplying with the unfolded offset doesn't overflow.
  3541. if (F.UnfoldedOffset != 0) {
  3542. if (F.UnfoldedOffset == std::numeric_limits<int64_t>::min() &&
  3543. Factor == -1)
  3544. continue;
  3545. F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
  3546. if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
  3547. continue;
  3548. // If the offset will be truncated, check that it is in bounds.
  3549. if (!IntTy->isPointerTy() &&
  3550. !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
  3551. continue;
  3552. }
  3553. // If we make it here and it's legal, add it.
  3554. (void)InsertFormula(LU, LUIdx, F);
  3555. next:;
  3556. }
  3557. }
  3558. /// Generate stride factor reuse formulae by making use of scaled-offset address
  3559. /// modes, for example.
  3560. void LSRInstance::GenerateScales(LSRUse &LU, unsigned LUIdx, Formula Base) {
  3561. // Determine the integer type for the base formula.
  3562. Type *IntTy = Base.getType();
  3563. if (!IntTy) return;
  3564. // If this Formula already has a scaled register, we can't add another one.
  3565. // Try to unscale the formula to generate a better scale.
  3566. if (Base.Scale != 0 && !Base.unscale())
  3567. return;
  3568. assert(Base.Scale == 0 && "unscale did not did its job!");
  3569. // Check each interesting stride.
  3570. for (int64_t Factor : Factors) {
  3571. Base.Scale = Factor;
  3572. Base.HasBaseReg = Base.BaseRegs.size() > 1;
  3573. // Check whether this scale is going to be legal.
  3574. if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
  3575. Base)) {
  3576. // As a special-case, handle special out-of-loop Basic users specially.
  3577. // TODO: Reconsider this special case.
  3578. if (LU.Kind == LSRUse::Basic &&
  3579. isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
  3580. LU.AccessTy, Base) &&
  3581. LU.AllFixupsOutsideLoop)
  3582. LU.Kind = LSRUse::Special;
  3583. else
  3584. continue;
  3585. }
  3586. // For an ICmpZero, negating a solitary base register won't lead to
  3587. // new solutions.
  3588. if (LU.Kind == LSRUse::ICmpZero &&
  3589. !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
  3590. continue;
  3591. // For each addrec base reg, if its loop is current loop, apply the scale.
  3592. for (size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
  3593. const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(Base.BaseRegs[i]);
  3594. if (AR && (AR->getLoop() == L || LU.AllFixupsOutsideLoop)) {
  3595. const SCEV *FactorS = SE.getConstant(IntTy, Factor);
  3596. if (FactorS->isZero())
  3597. continue;
  3598. // Divide out the factor, ignoring high bits, since we'll be
  3599. // scaling the value back up in the end.
  3600. if (const SCEV *Quotient = getExactSDiv(AR, FactorS, SE, true)) {
  3601. // TODO: This could be optimized to avoid all the copying.
  3602. Formula F = Base;
  3603. F.ScaledReg = Quotient;
  3604. F.deleteBaseReg(F.BaseRegs[i]);
  3605. // The canonical representation of 1*reg is reg, which is already in
  3606. // Base. In that case, do not try to insert the formula, it will be
  3607. // rejected anyway.
  3608. if (F.Scale == 1 && (F.BaseRegs.empty() ||
  3609. (AR->getLoop() != L && LU.AllFixupsOutsideLoop)))
  3610. continue;
  3611. // If AllFixupsOutsideLoop is true and F.Scale is 1, we may generate
  3612. // non canonical Formula with ScaledReg's loop not being L.
  3613. if (F.Scale == 1 && LU.AllFixupsOutsideLoop)
  3614. F.canonicalize(*L);
  3615. (void)InsertFormula(LU, LUIdx, F);
  3616. }
  3617. }
  3618. }
  3619. }
  3620. }
  3621. /// Generate reuse formulae from different IV types.
  3622. void LSRInstance::GenerateTruncates(LSRUse &LU, unsigned LUIdx, Formula Base) {
  3623. // Don't bother truncating symbolic values.
  3624. if (Base.BaseGV) return;
  3625. // Determine the integer type for the base formula.
  3626. Type *DstTy = Base.getType();
  3627. if (!DstTy) return;
  3628. if (DstTy->isPointerTy())
  3629. return;
  3630. // It is invalid to extend a pointer type so exit early if ScaledReg or
  3631. // any of the BaseRegs are pointers.
  3632. if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())
  3633. return;
  3634. if (any_of(Base.BaseRegs,
  3635. [](const SCEV *S) { return S->getType()->isPointerTy(); }))
  3636. return;
  3637. for (Type *SrcTy : Types) {
  3638. if (SrcTy != DstTy && TTI.isTruncateFree(SrcTy, DstTy)) {
  3639. Formula F = Base;
  3640. // Sometimes SCEV is able to prove zero during ext transform. It may
  3641. // happen if SCEV did not do all possible transforms while creating the
  3642. // initial node (maybe due to depth limitations), but it can do them while
  3643. // taking ext.
  3644. if (F.ScaledReg) {
  3645. const SCEV *NewScaledReg = SE.getAnyExtendExpr(F.ScaledReg, SrcTy);
  3646. if (NewScaledReg->isZero())
  3647. continue;
  3648. F.ScaledReg = NewScaledReg;
  3649. }
  3650. bool HasZeroBaseReg = false;
  3651. for (const SCEV *&BaseReg : F.BaseRegs) {
  3652. const SCEV *NewBaseReg = SE.getAnyExtendExpr(BaseReg, SrcTy);
  3653. if (NewBaseReg->isZero()) {
  3654. HasZeroBaseReg = true;
  3655. break;
  3656. }
  3657. BaseReg = NewBaseReg;
  3658. }
  3659. if (HasZeroBaseReg)
  3660. continue;
  3661. // TODO: This assumes we've done basic processing on all uses and
  3662. // have an idea what the register usage is.
  3663. if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
  3664. continue;
  3665. F.canonicalize(*L);
  3666. (void)InsertFormula(LU, LUIdx, F);
  3667. }
  3668. }
  3669. }
  3670. namespace {
  3671. /// Helper class for GenerateCrossUseConstantOffsets. It's used to defer
  3672. /// modifications so that the search phase doesn't have to worry about the data
  3673. /// structures moving underneath it.
  3674. struct WorkItem {
  3675. size_t LUIdx;
  3676. int64_t Imm;
  3677. const SCEV *OrigReg;
  3678. WorkItem(size_t LI, int64_t I, const SCEV *R)
  3679. : LUIdx(LI), Imm(I), OrigReg(R) {}
  3680. void print(raw_ostream &OS) const;
  3681. void dump() const;
  3682. };
  3683. } // end anonymous namespace
  3684. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  3685. void WorkItem::print(raw_ostream &OS) const {
  3686. OS << "in formulae referencing " << *OrigReg << " in use " << LUIdx
  3687. << " , add offset " << Imm;
  3688. }
  3689. LLVM_DUMP_METHOD void WorkItem::dump() const {
  3690. print(errs()); errs() << '\n';
  3691. }
  3692. #endif
  3693. /// Look for registers which are a constant distance apart and try to form reuse
  3694. /// opportunities between them.
  3695. void LSRInstance::GenerateCrossUseConstantOffsets() {
  3696. // Group the registers by their value without any added constant offset.
  3697. using ImmMapTy = std::map<int64_t, const SCEV *>;
  3698. DenseMap<const SCEV *, ImmMapTy> Map;
  3699. DenseMap<const SCEV *, SmallBitVector> UsedByIndicesMap;
  3700. SmallVector<const SCEV *, 8> Sequence;
  3701. for (const SCEV *Use : RegUses) {
  3702. const SCEV *Reg = Use; // Make a copy for ExtractImmediate to modify.
  3703. int64_t Imm = ExtractImmediate(Reg, SE);
  3704. auto Pair = Map.insert(std::make_pair(Reg, ImmMapTy()));
  3705. if (Pair.second)
  3706. Sequence.push_back(Reg);
  3707. Pair.first->second.insert(std::make_pair(Imm, Use));
  3708. UsedByIndicesMap[Reg] |= RegUses.getUsedByIndices(Use);
  3709. }
  3710. // Now examine each set of registers with the same base value. Build up
  3711. // a list of work to do and do the work in a separate step so that we're
  3712. // not adding formulae and register counts while we're searching.
  3713. SmallVector<WorkItem, 32> WorkItems;
  3714. SmallSet<std::pair<size_t, int64_t>, 32> UniqueItems;
  3715. for (const SCEV *Reg : Sequence) {
  3716. const ImmMapTy &Imms = Map.find(Reg)->second;
  3717. // It's not worthwhile looking for reuse if there's only one offset.
  3718. if (Imms.size() == 1)
  3719. continue;
  3720. LLVM_DEBUG(dbgs() << "Generating cross-use offsets for " << *Reg << ':';
  3721. for (const auto &Entry
  3722. : Imms) dbgs()
  3723. << ' ' << Entry.first;
  3724. dbgs() << '\n');
  3725. // Examine each offset.
  3726. for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
  3727. J != JE; ++J) {
  3728. const SCEV *OrigReg = J->second;
  3729. int64_t JImm = J->first;
  3730. const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
  3731. if (!isa<SCEVConstant>(OrigReg) &&
  3732. UsedByIndicesMap[Reg].count() == 1) {
  3733. LLVM_DEBUG(dbgs() << "Skipping cross-use reuse for " << *OrigReg
  3734. << '\n');
  3735. continue;
  3736. }
  3737. // Conservatively examine offsets between this orig reg a few selected
  3738. // other orig regs.
  3739. int64_t First = Imms.begin()->first;
  3740. int64_t Last = std::prev(Imms.end())->first;
  3741. // Compute (First + Last) / 2 without overflow using the fact that
  3742. // First + Last = 2 * (First + Last) + (First ^ Last).
  3743. int64_t Avg = (First & Last) + ((First ^ Last) >> 1);
  3744. // If the result is negative and First is odd and Last even (or vice versa),
  3745. // we rounded towards -inf. Add 1 in that case, to round towards 0.
  3746. Avg = Avg + ((First ^ Last) & ((uint64_t)Avg >> 63));
  3747. ImmMapTy::const_iterator OtherImms[] = {
  3748. Imms.begin(), std::prev(Imms.end()),
  3749. Imms.lower_bound(Avg)};
  3750. for (size_t i = 0, e = array_lengthof(OtherImms); i != e; ++i) {
  3751. ImmMapTy::const_iterator M = OtherImms[i];
  3752. if (M == J || M == JE) continue;
  3753. // Compute the difference between the two.
  3754. int64_t Imm = (uint64_t)JImm - M->first;
  3755. for (unsigned LUIdx : UsedByIndices.set_bits())
  3756. // Make a memo of this use, offset, and register tuple.
  3757. if (UniqueItems.insert(std::make_pair(LUIdx, Imm)).second)
  3758. WorkItems.push_back(WorkItem(LUIdx, Imm, OrigReg));
  3759. }
  3760. }
  3761. }
  3762. Map.clear();
  3763. Sequence.clear();
  3764. UsedByIndicesMap.clear();
  3765. UniqueItems.clear();
  3766. // Now iterate through the worklist and add new formulae.
  3767. for (const WorkItem &WI : WorkItems) {
  3768. size_t LUIdx = WI.LUIdx;
  3769. LSRUse &LU = Uses[LUIdx];
  3770. int64_t Imm = WI.Imm;
  3771. const SCEV *OrigReg = WI.OrigReg;
  3772. Type *IntTy = SE.getEffectiveSCEVType(OrigReg->getType());
  3773. const SCEV *NegImmS = SE.getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
  3774. unsigned BitWidth = SE.getTypeSizeInBits(IntTy);
  3775. // TODO: Use a more targeted data structure.
  3776. for (size_t L = 0, LE = LU.Formulae.size(); L != LE; ++L) {
  3777. Formula F = LU.Formulae[L];
  3778. // FIXME: The code for the scaled and unscaled registers looks
  3779. // very similar but slightly different. Investigate if they
  3780. // could be merged. That way, we would not have to unscale the
  3781. // Formula.
  3782. F.unscale();
  3783. // Use the immediate in the scaled register.
  3784. if (F.ScaledReg == OrigReg) {
  3785. int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
  3786. // Don't create 50 + reg(-50).
  3787. if (F.referencesReg(SE.getSCEV(
  3788. ConstantInt::get(IntTy, -(uint64_t)Offset))))
  3789. continue;
  3790. Formula NewF = F;
  3791. NewF.BaseOffset = Offset;
  3792. if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
  3793. NewF))
  3794. continue;
  3795. NewF.ScaledReg = SE.getAddExpr(NegImmS, NewF.ScaledReg);
  3796. // If the new scale is a constant in a register, and adding the constant
  3797. // value to the immediate would produce a value closer to zero than the
  3798. // immediate itself, then the formula isn't worthwhile.
  3799. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
  3800. if (C->getValue()->isNegative() != (NewF.BaseOffset < 0) &&
  3801. (C->getAPInt().abs() * APInt(BitWidth, F.Scale))
  3802. .ule(std::abs(NewF.BaseOffset)))
  3803. continue;
  3804. // OK, looks good.
  3805. NewF.canonicalize(*this->L);
  3806. (void)InsertFormula(LU, LUIdx, NewF);
  3807. } else {
  3808. // Use the immediate in a base register.
  3809. for (size_t N = 0, NE = F.BaseRegs.size(); N != NE; ++N) {
  3810. const SCEV *BaseReg = F.BaseRegs[N];
  3811. if (BaseReg != OrigReg)
  3812. continue;
  3813. Formula NewF = F;
  3814. NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
  3815. if (!isLegalUse(TTI, LU.MinOffset, LU.MaxOffset,
  3816. LU.Kind, LU.AccessTy, NewF)) {
  3817. if (AMK == TTI::AMK_PostIndexed &&
  3818. mayUsePostIncMode(TTI, LU, OrigReg, this->L, SE))
  3819. continue;
  3820. if (!TTI.isLegalAddImmediate((uint64_t)NewF.UnfoldedOffset + Imm))
  3821. continue;
  3822. NewF = F;
  3823. NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
  3824. }
  3825. NewF.BaseRegs[N] = SE.getAddExpr(NegImmS, BaseReg);
  3826. // If the new formula has a constant in a register, and adding the
  3827. // constant value to the immediate would produce a value closer to
  3828. // zero than the immediate itself, then the formula isn't worthwhile.
  3829. for (const SCEV *NewReg : NewF.BaseRegs)
  3830. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg))
  3831. if ((C->getAPInt() + NewF.BaseOffset)
  3832. .abs()
  3833. .slt(std::abs(NewF.BaseOffset)) &&
  3834. (C->getAPInt() + NewF.BaseOffset).countTrailingZeros() >=
  3835. countTrailingZeros<uint64_t>(NewF.BaseOffset))
  3836. goto skip_formula;
  3837. // Ok, looks good.
  3838. NewF.canonicalize(*this->L);
  3839. (void)InsertFormula(LU, LUIdx, NewF);
  3840. break;
  3841. skip_formula:;
  3842. }
  3843. }
  3844. }
  3845. }
  3846. }
  3847. /// Generate formulae for each use.
  3848. void
  3849. LSRInstance::GenerateAllReuseFormulae() {
  3850. // This is split into multiple loops so that hasRegsUsedByUsesOtherThan
  3851. // queries are more precise.
  3852. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  3853. LSRUse &LU = Uses[LUIdx];
  3854. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3855. GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
  3856. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3857. GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
  3858. }
  3859. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  3860. LSRUse &LU = Uses[LUIdx];
  3861. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3862. GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
  3863. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3864. GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
  3865. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3866. GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
  3867. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3868. GenerateScales(LU, LUIdx, LU.Formulae[i]);
  3869. }
  3870. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  3871. LSRUse &LU = Uses[LUIdx];
  3872. for (size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
  3873. GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
  3874. }
  3875. GenerateCrossUseConstantOffsets();
  3876. LLVM_DEBUG(dbgs() << "\n"
  3877. "After generating reuse formulae:\n";
  3878. print_uses(dbgs()));
  3879. }
  3880. /// If there are multiple formulae with the same set of registers used
  3881. /// by other uses, pick the best one and delete the others.
  3882. void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
  3883. DenseSet<const SCEV *> VisitedRegs;
  3884. SmallPtrSet<const SCEV *, 16> Regs;
  3885. SmallPtrSet<const SCEV *, 16> LoserRegs;
  3886. #ifndef NDEBUG
  3887. bool ChangedFormulae = false;
  3888. #endif
  3889. // Collect the best formula for each unique set of shared registers. This
  3890. // is reset for each use.
  3891. using BestFormulaeTy =
  3892. DenseMap<SmallVector<const SCEV *, 4>, size_t, UniquifierDenseMapInfo>;
  3893. BestFormulaeTy BestFormulae;
  3894. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  3895. LSRUse &LU = Uses[LUIdx];
  3896. LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());
  3897. dbgs() << '\n');
  3898. bool Any = false;
  3899. for (size_t FIdx = 0, NumForms = LU.Formulae.size();
  3900. FIdx != NumForms; ++FIdx) {
  3901. Formula &F = LU.Formulae[FIdx];
  3902. // Some formulas are instant losers. For example, they may depend on
  3903. // nonexistent AddRecs from other loops. These need to be filtered
  3904. // immediately, otherwise heuristics could choose them over others leading
  3905. // to an unsatisfactory solution. Passing LoserRegs into RateFormula here
  3906. // avoids the need to recompute this information across formulae using the
  3907. // same bad AddRec. Passing LoserRegs is also essential unless we remove
  3908. // the corresponding bad register from the Regs set.
  3909. Cost CostF(L, SE, TTI, AMK);
  3910. Regs.clear();
  3911. CostF.RateFormula(F, Regs, VisitedRegs, LU, &LoserRegs);
  3912. if (CostF.isLoser()) {
  3913. // During initial formula generation, undesirable formulae are generated
  3914. // by uses within other loops that have some non-trivial address mode or
  3915. // use the postinc form of the IV. LSR needs to provide these formulae
  3916. // as the basis of rediscovering the desired formula that uses an AddRec
  3917. // corresponding to the existing phi. Once all formulae have been
  3918. // generated, these initial losers may be pruned.
  3919. LLVM_DEBUG(dbgs() << " Filtering loser "; F.print(dbgs());
  3920. dbgs() << "\n");
  3921. }
  3922. else {
  3923. SmallVector<const SCEV *, 4> Key;
  3924. for (const SCEV *Reg : F.BaseRegs) {
  3925. if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
  3926. Key.push_back(Reg);
  3927. }
  3928. if (F.ScaledReg &&
  3929. RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
  3930. Key.push_back(F.ScaledReg);
  3931. // Unstable sort by host order ok, because this is only used for
  3932. // uniquifying.
  3933. llvm::sort(Key);
  3934. std::pair<BestFormulaeTy::const_iterator, bool> P =
  3935. BestFormulae.insert(std::make_pair(Key, FIdx));
  3936. if (P.second)
  3937. continue;
  3938. Formula &Best = LU.Formulae[P.first->second];
  3939. Cost CostBest(L, SE, TTI, AMK);
  3940. Regs.clear();
  3941. CostBest.RateFormula(Best, Regs, VisitedRegs, LU);
  3942. if (CostF.isLess(CostBest))
  3943. std::swap(F, Best);
  3944. LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
  3945. dbgs() << "\n"
  3946. " in favor of formula ";
  3947. Best.print(dbgs()); dbgs() << '\n');
  3948. }
  3949. #ifndef NDEBUG
  3950. ChangedFormulae = true;
  3951. #endif
  3952. LU.DeleteFormula(F);
  3953. --FIdx;
  3954. --NumForms;
  3955. Any = true;
  3956. }
  3957. // Now that we've filtered out some formulae, recompute the Regs set.
  3958. if (Any)
  3959. LU.RecomputeRegs(LUIdx, RegUses);
  3960. // Reset this to prepare for the next use.
  3961. BestFormulae.clear();
  3962. }
  3963. LLVM_DEBUG(if (ChangedFormulae) {
  3964. dbgs() << "\n"
  3965. "After filtering out undesirable candidates:\n";
  3966. print_uses(dbgs());
  3967. });
  3968. }
  3969. /// Estimate the worst-case number of solutions the solver might have to
  3970. /// consider. It almost never considers this many solutions because it prune the
  3971. /// search space, but the pruning isn't always sufficient.
  3972. size_t LSRInstance::EstimateSearchSpaceComplexity() const {
  3973. size_t Power = 1;
  3974. for (const LSRUse &LU : Uses) {
  3975. size_t FSize = LU.Formulae.size();
  3976. if (FSize >= ComplexityLimit) {
  3977. Power = ComplexityLimit;
  3978. break;
  3979. }
  3980. Power *= FSize;
  3981. if (Power >= ComplexityLimit)
  3982. break;
  3983. }
  3984. return Power;
  3985. }
  3986. /// When one formula uses a superset of the registers of another formula, it
  3987. /// won't help reduce register pressure (though it may not necessarily hurt
  3988. /// register pressure); remove it to simplify the system.
  3989. void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
  3990. if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
  3991. LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
  3992. LLVM_DEBUG(dbgs() << "Narrowing the search space by eliminating formulae "
  3993. "which use a superset of registers used by other "
  3994. "formulae.\n");
  3995. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  3996. LSRUse &LU = Uses[LUIdx];
  3997. bool Any = false;
  3998. for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
  3999. Formula &F = LU.Formulae[i];
  4000. // Look for a formula with a constant or GV in a register. If the use
  4001. // also has a formula with that same value in an immediate field,
  4002. // delete the one that uses a register.
  4003. for (SmallVectorImpl<const SCEV *>::const_iterator
  4004. I = F.BaseRegs.begin(), E = F.BaseRegs.end(); I != E; ++I) {
  4005. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
  4006. Formula NewF = F;
  4007. //FIXME: Formulas should store bitwidth to do wrapping properly.
  4008. // See PR41034.
  4009. NewF.BaseOffset += (uint64_t)C->getValue()->getSExtValue();
  4010. NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
  4011. (I - F.BaseRegs.begin()));
  4012. if (LU.HasFormulaWithSameRegs(NewF)) {
  4013. LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs());
  4014. dbgs() << '\n');
  4015. LU.DeleteFormula(F);
  4016. --i;
  4017. --e;
  4018. Any = true;
  4019. break;
  4020. }
  4021. } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
  4022. if (GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
  4023. if (!F.BaseGV) {
  4024. Formula NewF = F;
  4025. NewF.BaseGV = GV;
  4026. NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
  4027. (I - F.BaseRegs.begin()));
  4028. if (LU.HasFormulaWithSameRegs(NewF)) {
  4029. LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs());
  4030. dbgs() << '\n');
  4031. LU.DeleteFormula(F);
  4032. --i;
  4033. --e;
  4034. Any = true;
  4035. break;
  4036. }
  4037. }
  4038. }
  4039. }
  4040. }
  4041. if (Any)
  4042. LU.RecomputeRegs(LUIdx, RegUses);
  4043. }
  4044. LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
  4045. }
  4046. }
  4047. /// When there are many registers for expressions like A, A+1, A+2, etc.,
  4048. /// allocate a single register for them.
  4049. void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
  4050. if (EstimateSearchSpaceComplexity() < ComplexityLimit)
  4051. return;
  4052. LLVM_DEBUG(
  4053. dbgs() << "The search space is too complex.\n"
  4054. "Narrowing the search space by assuming that uses separated "
  4055. "by a constant offset will use the same registers.\n");
  4056. // This is especially useful for unrolled loops.
  4057. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  4058. LSRUse &LU = Uses[LUIdx];
  4059. for (const Formula &F : LU.Formulae) {
  4060. if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
  4061. continue;
  4062. LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
  4063. if (!LUThatHas)
  4064. continue;
  4065. if (!reconcileNewOffset(*LUThatHas, F.BaseOffset, /*HasBaseReg=*/ false,
  4066. LU.Kind, LU.AccessTy))
  4067. continue;
  4068. LLVM_DEBUG(dbgs() << " Deleting use "; LU.print(dbgs()); dbgs() << '\n');
  4069. LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
  4070. // Transfer the fixups of LU to LUThatHas.
  4071. for (LSRFixup &Fixup : LU.Fixups) {
  4072. Fixup.Offset += F.BaseOffset;
  4073. LUThatHas->pushFixup(Fixup);
  4074. LLVM_DEBUG(dbgs() << "New fixup has offset " << Fixup.Offset << '\n');
  4075. }
  4076. // Delete formulae from the new use which are no longer legal.
  4077. bool Any = false;
  4078. for (size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
  4079. Formula &F = LUThatHas->Formulae[i];
  4080. if (!isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
  4081. LUThatHas->Kind, LUThatHas->AccessTy, F)) {
  4082. LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
  4083. LUThatHas->DeleteFormula(F);
  4084. --i;
  4085. --e;
  4086. Any = true;
  4087. }
  4088. }
  4089. if (Any)
  4090. LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
  4091. // Delete the old use.
  4092. DeleteUse(LU, LUIdx);
  4093. --LUIdx;
  4094. --NumUses;
  4095. break;
  4096. }
  4097. }
  4098. LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
  4099. }
  4100. /// Call FilterOutUndesirableDedicatedRegisters again, if necessary, now that
  4101. /// we've done more filtering, as it may be able to find more formulae to
  4102. /// eliminate.
  4103. void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
  4104. if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
  4105. LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
  4106. LLVM_DEBUG(dbgs() << "Narrowing the search space by re-filtering out "
  4107. "undesirable dedicated registers.\n");
  4108. FilterOutUndesirableDedicatedRegisters();
  4109. LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
  4110. }
  4111. }
  4112. /// If a LSRUse has multiple formulae with the same ScaledReg and Scale.
  4113. /// Pick the best one and delete the others.
  4114. /// This narrowing heuristic is to keep as many formulae with different
  4115. /// Scale and ScaledReg pair as possible while narrowing the search space.
  4116. /// The benefit is that it is more likely to find out a better solution
  4117. /// from a formulae set with more Scale and ScaledReg variations than
  4118. /// a formulae set with the same Scale and ScaledReg. The picking winner
  4119. /// reg heuristic will often keep the formulae with the same Scale and
  4120. /// ScaledReg and filter others, and we want to avoid that if possible.
  4121. void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() {
  4122. if (EstimateSearchSpaceComplexity() < ComplexityLimit)
  4123. return;
  4124. LLVM_DEBUG(
  4125. dbgs() << "The search space is too complex.\n"
  4126. "Narrowing the search space by choosing the best Formula "
  4127. "from the Formulae with the same Scale and ScaledReg.\n");
  4128. // Map the "Scale * ScaledReg" pair to the best formula of current LSRUse.
  4129. using BestFormulaeTy = DenseMap<std::pair<const SCEV *, int64_t>, size_t>;
  4130. BestFormulaeTy BestFormulae;
  4131. #ifndef NDEBUG
  4132. bool ChangedFormulae = false;
  4133. #endif
  4134. DenseSet<const SCEV *> VisitedRegs;
  4135. SmallPtrSet<const SCEV *, 16> Regs;
  4136. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  4137. LSRUse &LU = Uses[LUIdx];
  4138. LLVM_DEBUG(dbgs() << "Filtering for use "; LU.print(dbgs());
  4139. dbgs() << '\n');
  4140. // Return true if Formula FA is better than Formula FB.
  4141. auto IsBetterThan = [&](Formula &FA, Formula &FB) {
  4142. // First we will try to choose the Formula with fewer new registers.
  4143. // For a register used by current Formula, the more the register is
  4144. // shared among LSRUses, the less we increase the register number
  4145. // counter of the formula.
  4146. size_t FARegNum = 0;
  4147. for (const SCEV *Reg : FA.BaseRegs) {
  4148. const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
  4149. FARegNum += (NumUses - UsedByIndices.count() + 1);
  4150. }
  4151. size_t FBRegNum = 0;
  4152. for (const SCEV *Reg : FB.BaseRegs) {
  4153. const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
  4154. FBRegNum += (NumUses - UsedByIndices.count() + 1);
  4155. }
  4156. if (FARegNum != FBRegNum)
  4157. return FARegNum < FBRegNum;
  4158. // If the new register numbers are the same, choose the Formula with
  4159. // less Cost.
  4160. Cost CostFA(L, SE, TTI, AMK);
  4161. Cost CostFB(L, SE, TTI, AMK);
  4162. Regs.clear();
  4163. CostFA.RateFormula(FA, Regs, VisitedRegs, LU);
  4164. Regs.clear();
  4165. CostFB.RateFormula(FB, Regs, VisitedRegs, LU);
  4166. return CostFA.isLess(CostFB);
  4167. };
  4168. bool Any = false;
  4169. for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;
  4170. ++FIdx) {
  4171. Formula &F = LU.Formulae[FIdx];
  4172. if (!F.ScaledReg)
  4173. continue;
  4174. auto P = BestFormulae.insert({{F.ScaledReg, F.Scale}, FIdx});
  4175. if (P.second)
  4176. continue;
  4177. Formula &Best = LU.Formulae[P.first->second];
  4178. if (IsBetterThan(F, Best))
  4179. std::swap(F, Best);
  4180. LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
  4181. dbgs() << "\n"
  4182. " in favor of formula ";
  4183. Best.print(dbgs()); dbgs() << '\n');
  4184. #ifndef NDEBUG
  4185. ChangedFormulae = true;
  4186. #endif
  4187. LU.DeleteFormula(F);
  4188. --FIdx;
  4189. --NumForms;
  4190. Any = true;
  4191. }
  4192. if (Any)
  4193. LU.RecomputeRegs(LUIdx, RegUses);
  4194. // Reset this to prepare for the next use.
  4195. BestFormulae.clear();
  4196. }
  4197. LLVM_DEBUG(if (ChangedFormulae) {
  4198. dbgs() << "\n"
  4199. "After filtering out undesirable candidates:\n";
  4200. print_uses(dbgs());
  4201. });
  4202. }
  4203. /// If we are over the complexity limit, filter out any post-inc prefering
  4204. /// variables to only post-inc values.
  4205. void LSRInstance::NarrowSearchSpaceByFilterPostInc() {
  4206. if (AMK != TTI::AMK_PostIndexed)
  4207. return;
  4208. if (EstimateSearchSpaceComplexity() < ComplexityLimit)
  4209. return;
  4210. LLVM_DEBUG(dbgs() << "The search space is too complex.\n"
  4211. "Narrowing the search space by choosing the lowest "
  4212. "register Formula for PostInc Uses.\n");
  4213. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  4214. LSRUse &LU = Uses[LUIdx];
  4215. if (LU.Kind != LSRUse::Address)
  4216. continue;
  4217. if (!TTI.isIndexedLoadLegal(TTI.MIM_PostInc, LU.AccessTy.getType()) &&
  4218. !TTI.isIndexedStoreLegal(TTI.MIM_PostInc, LU.AccessTy.getType()))
  4219. continue;
  4220. size_t MinRegs = std::numeric_limits<size_t>::max();
  4221. for (const Formula &F : LU.Formulae)
  4222. MinRegs = std::min(F.getNumRegs(), MinRegs);
  4223. bool Any = false;
  4224. for (size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;
  4225. ++FIdx) {
  4226. Formula &F = LU.Formulae[FIdx];
  4227. if (F.getNumRegs() > MinRegs) {
  4228. LLVM_DEBUG(dbgs() << " Filtering out formula "; F.print(dbgs());
  4229. dbgs() << "\n");
  4230. LU.DeleteFormula(F);
  4231. --FIdx;
  4232. --NumForms;
  4233. Any = true;
  4234. }
  4235. }
  4236. if (Any)
  4237. LU.RecomputeRegs(LUIdx, RegUses);
  4238. if (EstimateSearchSpaceComplexity() < ComplexityLimit)
  4239. break;
  4240. }
  4241. LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
  4242. }
  4243. /// The function delete formulas with high registers number expectation.
  4244. /// Assuming we don't know the value of each formula (already delete
  4245. /// all inefficient), generate probability of not selecting for each
  4246. /// register.
  4247. /// For example,
  4248. /// Use1:
  4249. /// reg(a) + reg({0,+,1})
  4250. /// reg(a) + reg({-1,+,1}) + 1
  4251. /// reg({a,+,1})
  4252. /// Use2:
  4253. /// reg(b) + reg({0,+,1})
  4254. /// reg(b) + reg({-1,+,1}) + 1
  4255. /// reg({b,+,1})
  4256. /// Use3:
  4257. /// reg(c) + reg(b) + reg({0,+,1})
  4258. /// reg(c) + reg({b,+,1})
  4259. ///
  4260. /// Probability of not selecting
  4261. /// Use1 Use2 Use3
  4262. /// reg(a) (1/3) * 1 * 1
  4263. /// reg(b) 1 * (1/3) * (1/2)
  4264. /// reg({0,+,1}) (2/3) * (2/3) * (1/2)
  4265. /// reg({-1,+,1}) (2/3) * (2/3) * 1
  4266. /// reg({a,+,1}) (2/3) * 1 * 1
  4267. /// reg({b,+,1}) 1 * (2/3) * (2/3)
  4268. /// reg(c) 1 * 1 * 0
  4269. ///
  4270. /// Now count registers number mathematical expectation for each formula:
  4271. /// Note that for each use we exclude probability if not selecting for the use.
  4272. /// For example for Use1 probability for reg(a) would be just 1 * 1 (excluding
  4273. /// probabilty 1/3 of not selecting for Use1).
  4274. /// Use1:
  4275. /// reg(a) + reg({0,+,1}) 1 + 1/3 -- to be deleted
  4276. /// reg(a) + reg({-1,+,1}) + 1 1 + 4/9 -- to be deleted
  4277. /// reg({a,+,1}) 1
  4278. /// Use2:
  4279. /// reg(b) + reg({0,+,1}) 1/2 + 1/3 -- to be deleted
  4280. /// reg(b) + reg({-1,+,1}) + 1 1/2 + 2/3 -- to be deleted
  4281. /// reg({b,+,1}) 2/3
  4282. /// Use3:
  4283. /// reg(c) + reg(b) + reg({0,+,1}) 1 + 1/3 + 4/9 -- to be deleted
  4284. /// reg(c) + reg({b,+,1}) 1 + 2/3
  4285. void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() {
  4286. if (EstimateSearchSpaceComplexity() < ComplexityLimit)
  4287. return;
  4288. // Ok, we have too many of formulae on our hands to conveniently handle.
  4289. // Use a rough heuristic to thin out the list.
  4290. // Set of Regs wich will be 100% used in final solution.
  4291. // Used in each formula of a solution (in example above this is reg(c)).
  4292. // We can skip them in calculations.
  4293. SmallPtrSet<const SCEV *, 4> UniqRegs;
  4294. LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
  4295. // Map each register to probability of not selecting
  4296. DenseMap <const SCEV *, float> RegNumMap;
  4297. for (const SCEV *Reg : RegUses) {
  4298. if (UniqRegs.count(Reg))
  4299. continue;
  4300. float PNotSel = 1;
  4301. for (const LSRUse &LU : Uses) {
  4302. if (!LU.Regs.count(Reg))
  4303. continue;
  4304. float P = LU.getNotSelectedProbability(Reg);
  4305. if (P != 0.0)
  4306. PNotSel *= P;
  4307. else
  4308. UniqRegs.insert(Reg);
  4309. }
  4310. RegNumMap.insert(std::make_pair(Reg, PNotSel));
  4311. }
  4312. LLVM_DEBUG(
  4313. dbgs() << "Narrowing the search space by deleting costly formulas\n");
  4314. // Delete formulas where registers number expectation is high.
  4315. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  4316. LSRUse &LU = Uses[LUIdx];
  4317. // If nothing to delete - continue.
  4318. if (LU.Formulae.size() < 2)
  4319. continue;
  4320. // This is temporary solution to test performance. Float should be
  4321. // replaced with round independent type (based on integers) to avoid
  4322. // different results for different target builds.
  4323. float FMinRegNum = LU.Formulae[0].getNumRegs();
  4324. float FMinARegNum = LU.Formulae[0].getNumRegs();
  4325. size_t MinIdx = 0;
  4326. for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
  4327. Formula &F = LU.Formulae[i];
  4328. float FRegNum = 0;
  4329. float FARegNum = 0;
  4330. for (const SCEV *BaseReg : F.BaseRegs) {
  4331. if (UniqRegs.count(BaseReg))
  4332. continue;
  4333. FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
  4334. if (isa<SCEVAddRecExpr>(BaseReg))
  4335. FARegNum +=
  4336. RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
  4337. }
  4338. if (const SCEV *ScaledReg = F.ScaledReg) {
  4339. if (!UniqRegs.count(ScaledReg)) {
  4340. FRegNum +=
  4341. RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
  4342. if (isa<SCEVAddRecExpr>(ScaledReg))
  4343. FARegNum +=
  4344. RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
  4345. }
  4346. }
  4347. if (FMinRegNum > FRegNum ||
  4348. (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) {
  4349. FMinRegNum = FRegNum;
  4350. FMinARegNum = FARegNum;
  4351. MinIdx = i;
  4352. }
  4353. }
  4354. LLVM_DEBUG(dbgs() << " The formula "; LU.Formulae[MinIdx].print(dbgs());
  4355. dbgs() << " with min reg num " << FMinRegNum << '\n');
  4356. if (MinIdx != 0)
  4357. std::swap(LU.Formulae[MinIdx], LU.Formulae[0]);
  4358. while (LU.Formulae.size() != 1) {
  4359. LLVM_DEBUG(dbgs() << " Deleting "; LU.Formulae.back().print(dbgs());
  4360. dbgs() << '\n');
  4361. LU.Formulae.pop_back();
  4362. }
  4363. LU.RecomputeRegs(LUIdx, RegUses);
  4364. assert(LU.Formulae.size() == 1 && "Should be exactly 1 min regs formula");
  4365. Formula &F = LU.Formulae[0];
  4366. LLVM_DEBUG(dbgs() << " Leaving only "; F.print(dbgs()); dbgs() << '\n');
  4367. // When we choose the formula, the regs become unique.
  4368. UniqRegs.insert(F.BaseRegs.begin(), F.BaseRegs.end());
  4369. if (F.ScaledReg)
  4370. UniqRegs.insert(F.ScaledReg);
  4371. }
  4372. LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
  4373. }
  4374. /// Pick a register which seems likely to be profitable, and then in any use
  4375. /// which has any reference to that register, delete all formulae which do not
  4376. /// reference that register.
  4377. void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
  4378. // With all other options exhausted, loop until the system is simple
  4379. // enough to handle.
  4380. SmallPtrSet<const SCEV *, 4> Taken;
  4381. while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
  4382. // Ok, we have too many of formulae on our hands to conveniently handle.
  4383. // Use a rough heuristic to thin out the list.
  4384. LLVM_DEBUG(dbgs() << "The search space is too complex.\n");
  4385. // Pick the register which is used by the most LSRUses, which is likely
  4386. // to be a good reuse register candidate.
  4387. const SCEV *Best = nullptr;
  4388. unsigned BestNum = 0;
  4389. for (const SCEV *Reg : RegUses) {
  4390. if (Taken.count(Reg))
  4391. continue;
  4392. if (!Best) {
  4393. Best = Reg;
  4394. BestNum = RegUses.getUsedByIndices(Reg).count();
  4395. } else {
  4396. unsigned Count = RegUses.getUsedByIndices(Reg).count();
  4397. if (Count > BestNum) {
  4398. Best = Reg;
  4399. BestNum = Count;
  4400. }
  4401. }
  4402. }
  4403. assert(Best && "Failed to find best LSRUse candidate");
  4404. LLVM_DEBUG(dbgs() << "Narrowing the search space by assuming " << *Best
  4405. << " will yield profitable reuse.\n");
  4406. Taken.insert(Best);
  4407. // In any use with formulae which references this register, delete formulae
  4408. // which don't reference it.
  4409. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
  4410. LSRUse &LU = Uses[LUIdx];
  4411. if (!LU.Regs.count(Best)) continue;
  4412. bool Any = false;
  4413. for (size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
  4414. Formula &F = LU.Formulae[i];
  4415. if (!F.referencesReg(Best)) {
  4416. LLVM_DEBUG(dbgs() << " Deleting "; F.print(dbgs()); dbgs() << '\n');
  4417. LU.DeleteFormula(F);
  4418. --e;
  4419. --i;
  4420. Any = true;
  4421. assert(e != 0 && "Use has no formulae left! Is Regs inconsistent?");
  4422. continue;
  4423. }
  4424. }
  4425. if (Any)
  4426. LU.RecomputeRegs(LUIdx, RegUses);
  4427. }
  4428. LLVM_DEBUG(dbgs() << "After pre-selection:\n"; print_uses(dbgs()));
  4429. }
  4430. }
  4431. /// If there are an extraordinary number of formulae to choose from, use some
  4432. /// rough heuristics to prune down the number of formulae. This keeps the main
  4433. /// solver from taking an extraordinary amount of time in some worst-case
  4434. /// scenarios.
  4435. void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
  4436. NarrowSearchSpaceByDetectingSupersets();
  4437. NarrowSearchSpaceByCollapsingUnrolledCode();
  4438. NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
  4439. if (FilterSameScaledReg)
  4440. NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
  4441. NarrowSearchSpaceByFilterPostInc();
  4442. if (LSRExpNarrow)
  4443. NarrowSearchSpaceByDeletingCostlyFormulas();
  4444. else
  4445. NarrowSearchSpaceByPickingWinnerRegs();
  4446. }
  4447. /// This is the recursive solver.
  4448. void LSRInstance::SolveRecurse(SmallVectorImpl<const Formula *> &Solution,
  4449. Cost &SolutionCost,
  4450. SmallVectorImpl<const Formula *> &Workspace,
  4451. const Cost &CurCost,
  4452. const SmallPtrSet<const SCEV *, 16> &CurRegs,
  4453. DenseSet<const SCEV *> &VisitedRegs) const {
  4454. // Some ideas:
  4455. // - prune more:
  4456. // - use more aggressive filtering
  4457. // - sort the formula so that the most profitable solutions are found first
  4458. // - sort the uses too
  4459. // - search faster:
  4460. // - don't compute a cost, and then compare. compare while computing a cost
  4461. // and bail early.
  4462. // - track register sets with SmallBitVector
  4463. const LSRUse &LU = Uses[Workspace.size()];
  4464. // If this use references any register that's already a part of the
  4465. // in-progress solution, consider it a requirement that a formula must
  4466. // reference that register in order to be considered. This prunes out
  4467. // unprofitable searching.
  4468. SmallSetVector<const SCEV *, 4> ReqRegs;
  4469. for (const SCEV *S : CurRegs)
  4470. if (LU.Regs.count(S))
  4471. ReqRegs.insert(S);
  4472. SmallPtrSet<const SCEV *, 16> NewRegs;
  4473. Cost NewCost(L, SE, TTI, AMK);
  4474. for (const Formula &F : LU.Formulae) {
  4475. // Ignore formulae which may not be ideal in terms of register reuse of
  4476. // ReqRegs. The formula should use all required registers before
  4477. // introducing new ones.
  4478. // This can sometimes (notably when trying to favour postinc) lead to
  4479. // sub-optimial decisions. There it is best left to the cost modelling to
  4480. // get correct.
  4481. if (AMK != TTI::AMK_PostIndexed || LU.Kind != LSRUse::Address) {
  4482. int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.size());
  4483. for (const SCEV *Reg : ReqRegs) {
  4484. if ((F.ScaledReg && F.ScaledReg == Reg) ||
  4485. is_contained(F.BaseRegs, Reg)) {
  4486. --NumReqRegsToFind;
  4487. if (NumReqRegsToFind == 0)
  4488. break;
  4489. }
  4490. }
  4491. if (NumReqRegsToFind != 0) {
  4492. // If none of the formulae satisfied the required registers, then we could
  4493. // clear ReqRegs and try again. Currently, we simply give up in this case.
  4494. continue;
  4495. }
  4496. }
  4497. // Evaluate the cost of the current formula. If it's already worse than
  4498. // the current best, prune the search at that point.
  4499. NewCost = CurCost;
  4500. NewRegs = CurRegs;
  4501. NewCost.RateFormula(F, NewRegs, VisitedRegs, LU);
  4502. if (NewCost.isLess(SolutionCost)) {
  4503. Workspace.push_back(&F);
  4504. if (Workspace.size() != Uses.size()) {
  4505. SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
  4506. NewRegs, VisitedRegs);
  4507. if (F.getNumRegs() == 1 && Workspace.size() == 1)
  4508. VisitedRegs.insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
  4509. } else {
  4510. LLVM_DEBUG(dbgs() << "New best at "; NewCost.print(dbgs());
  4511. dbgs() << ".\nRegs:\n";
  4512. for (const SCEV *S : NewRegs) dbgs()
  4513. << "- " << *S << "\n";
  4514. dbgs() << '\n');
  4515. SolutionCost = NewCost;
  4516. Solution = Workspace;
  4517. }
  4518. Workspace.pop_back();
  4519. }
  4520. }
  4521. }
  4522. /// Choose one formula from each use. Return the results in the given Solution
  4523. /// vector.
  4524. void LSRInstance::Solve(SmallVectorImpl<const Formula *> &Solution) const {
  4525. SmallVector<const Formula *, 8> Workspace;
  4526. Cost SolutionCost(L, SE, TTI, AMK);
  4527. SolutionCost.Lose();
  4528. Cost CurCost(L, SE, TTI, AMK);
  4529. SmallPtrSet<const SCEV *, 16> CurRegs;
  4530. DenseSet<const SCEV *> VisitedRegs;
  4531. Workspace.reserve(Uses.size());
  4532. // SolveRecurse does all the work.
  4533. SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
  4534. CurRegs, VisitedRegs);
  4535. if (Solution.empty()) {
  4536. LLVM_DEBUG(dbgs() << "\nNo Satisfactory Solution\n");
  4537. return;
  4538. }
  4539. // Ok, we've now made all our decisions.
  4540. LLVM_DEBUG(dbgs() << "\n"
  4541. "The chosen solution requires ";
  4542. SolutionCost.print(dbgs()); dbgs() << ":\n";
  4543. for (size_t i = 0, e = Uses.size(); i != e; ++i) {
  4544. dbgs() << " ";
  4545. Uses[i].print(dbgs());
  4546. dbgs() << "\n"
  4547. " ";
  4548. Solution[i]->print(dbgs());
  4549. dbgs() << '\n';
  4550. });
  4551. assert(Solution.size() == Uses.size() && "Malformed solution!");
  4552. }
  4553. /// Helper for AdjustInsertPositionForExpand. Climb up the dominator tree far as
  4554. /// we can go while still being dominated by the input positions. This helps
  4555. /// canonicalize the insert position, which encourages sharing.
  4556. BasicBlock::iterator
  4557. LSRInstance::HoistInsertPosition(BasicBlock::iterator IP,
  4558. const SmallVectorImpl<Instruction *> &Inputs)
  4559. const {
  4560. Instruction *Tentative = &*IP;
  4561. while (true) {
  4562. bool AllDominate = true;
  4563. Instruction *BetterPos = nullptr;
  4564. // Don't bother attempting to insert before a catchswitch, their basic block
  4565. // cannot have other non-PHI instructions.
  4566. if (isa<CatchSwitchInst>(Tentative))
  4567. return IP;
  4568. for (Instruction *Inst : Inputs) {
  4569. if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
  4570. AllDominate = false;
  4571. break;
  4572. }
  4573. // Attempt to find an insert position in the middle of the block,
  4574. // instead of at the end, so that it can be used for other expansions.
  4575. if (Tentative->getParent() == Inst->getParent() &&
  4576. (!BetterPos || !DT.dominates(Inst, BetterPos)))
  4577. BetterPos = &*std::next(BasicBlock::iterator(Inst));
  4578. }
  4579. if (!AllDominate)
  4580. break;
  4581. if (BetterPos)
  4582. IP = BetterPos->getIterator();
  4583. else
  4584. IP = Tentative->getIterator();
  4585. const Loop *IPLoop = LI.getLoopFor(IP->getParent());
  4586. unsigned IPLoopDepth = IPLoop ? IPLoop->getLoopDepth() : 0;
  4587. BasicBlock *IDom;
  4588. for (DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
  4589. if (!Rung) return IP;
  4590. Rung = Rung->getIDom();
  4591. if (!Rung) return IP;
  4592. IDom = Rung->getBlock();
  4593. // Don't climb into a loop though.
  4594. const Loop *IDomLoop = LI.getLoopFor(IDom);
  4595. unsigned IDomDepth = IDomLoop ? IDomLoop->getLoopDepth() : 0;
  4596. if (IDomDepth <= IPLoopDepth &&
  4597. (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
  4598. break;
  4599. }
  4600. Tentative = IDom->getTerminator();
  4601. }
  4602. return IP;
  4603. }
  4604. /// Determine an input position which will be dominated by the operands and
  4605. /// which will dominate the result.
  4606. BasicBlock::iterator
  4607. LSRInstance::AdjustInsertPositionForExpand(BasicBlock::iterator LowestIP,
  4608. const LSRFixup &LF,
  4609. const LSRUse &LU,
  4610. SCEVExpander &Rewriter) const {
  4611. // Collect some instructions which must be dominated by the
  4612. // expanding replacement. These must be dominated by any operands that
  4613. // will be required in the expansion.
  4614. SmallVector<Instruction *, 4> Inputs;
  4615. if (Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
  4616. Inputs.push_back(I);
  4617. if (LU.Kind == LSRUse::ICmpZero)
  4618. if (Instruction *I =
  4619. dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
  4620. Inputs.push_back(I);
  4621. if (LF.PostIncLoops.count(L)) {
  4622. if (LF.isUseFullyOutsideLoop(L))
  4623. Inputs.push_back(L->getLoopLatch()->getTerminator());
  4624. else
  4625. Inputs.push_back(IVIncInsertPos);
  4626. }
  4627. // The expansion must also be dominated by the increment positions of any
  4628. // loops it for which it is using post-inc mode.
  4629. for (const Loop *PIL : LF.PostIncLoops) {
  4630. if (PIL == L) continue;
  4631. // Be dominated by the loop exit.
  4632. SmallVector<BasicBlock *, 4> ExitingBlocks;
  4633. PIL->getExitingBlocks(ExitingBlocks);
  4634. if (!ExitingBlocks.empty()) {
  4635. BasicBlock *BB = ExitingBlocks[0];
  4636. for (unsigned i = 1, e = ExitingBlocks.size(); i != e; ++i)
  4637. BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
  4638. Inputs.push_back(BB->getTerminator());
  4639. }
  4640. }
  4641. assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad()
  4642. && !isa<DbgInfoIntrinsic>(LowestIP) &&
  4643. "Insertion point must be a normal instruction");
  4644. // Then, climb up the immediate dominator tree as far as we can go while
  4645. // still being dominated by the input positions.
  4646. BasicBlock::iterator IP = HoistInsertPosition(LowestIP, Inputs);
  4647. // Don't insert instructions before PHI nodes.
  4648. while (isa<PHINode>(IP)) ++IP;
  4649. // Ignore landingpad instructions.
  4650. while (IP->isEHPad()) ++IP;
  4651. // Ignore debug intrinsics.
  4652. while (isa<DbgInfoIntrinsic>(IP)) ++IP;
  4653. // Set IP below instructions recently inserted by SCEVExpander. This keeps the
  4654. // IP consistent across expansions and allows the previously inserted
  4655. // instructions to be reused by subsequent expansion.
  4656. while (Rewriter.isInsertedInstruction(&*IP) && IP != LowestIP)
  4657. ++IP;
  4658. return IP;
  4659. }
  4660. /// Emit instructions for the leading candidate expression for this LSRUse (this
  4661. /// is called "expanding").
  4662. Value *LSRInstance::Expand(const LSRUse &LU, const LSRFixup &LF,
  4663. const Formula &F, BasicBlock::iterator IP,
  4664. SCEVExpander &Rewriter,
  4665. SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
  4666. if (LU.RigidFormula)
  4667. return LF.OperandValToReplace;
  4668. // Determine an input position which will be dominated by the operands and
  4669. // which will dominate the result.
  4670. IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
  4671. Rewriter.setInsertPoint(&*IP);
  4672. // Inform the Rewriter if we have a post-increment use, so that it can
  4673. // perform an advantageous expansion.
  4674. Rewriter.setPostInc(LF.PostIncLoops);
  4675. // This is the type that the user actually needs.
  4676. Type *OpTy = LF.OperandValToReplace->getType();
  4677. // This will be the type that we'll initially expand to.
  4678. Type *Ty = F.getType();
  4679. if (!Ty)
  4680. // No type known; just expand directly to the ultimate type.
  4681. Ty = OpTy;
  4682. else if (SE.getEffectiveSCEVType(Ty) == SE.getEffectiveSCEVType(OpTy))
  4683. // Expand directly to the ultimate type if it's the right size.
  4684. Ty = OpTy;
  4685. // This is the type to do integer arithmetic in.
  4686. Type *IntTy = SE.getEffectiveSCEVType(Ty);
  4687. // Build up a list of operands to add together to form the full base.
  4688. SmallVector<const SCEV *, 8> Ops;
  4689. // Expand the BaseRegs portion.
  4690. for (const SCEV *Reg : F.BaseRegs) {
  4691. assert(!Reg->isZero() && "Zero allocated in a base register!");
  4692. // If we're expanding for a post-inc user, make the post-inc adjustment.
  4693. Reg = denormalizeForPostIncUse(Reg, LF.PostIncLoops, SE);
  4694. Ops.push_back(SE.getUnknown(Rewriter.expandCodeFor(Reg, nullptr)));
  4695. }
  4696. // Expand the ScaledReg portion.
  4697. Value *ICmpScaledV = nullptr;
  4698. if (F.Scale != 0) {
  4699. const SCEV *ScaledS = F.ScaledReg;
  4700. // If we're expanding for a post-inc user, make the post-inc adjustment.
  4701. PostIncLoopSet &Loops = const_cast<PostIncLoopSet &>(LF.PostIncLoops);
  4702. ScaledS = denormalizeForPostIncUse(ScaledS, Loops, SE);
  4703. if (LU.Kind == LSRUse::ICmpZero) {
  4704. // Expand ScaleReg as if it was part of the base regs.
  4705. if (F.Scale == 1)
  4706. Ops.push_back(
  4707. SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr)));
  4708. else {
  4709. // An interesting way of "folding" with an icmp is to use a negated
  4710. // scale, which we'll implement by inserting it into the other operand
  4711. // of the icmp.
  4712. assert(F.Scale == -1 &&
  4713. "The only scale supported by ICmpZero uses is -1!");
  4714. ICmpScaledV = Rewriter.expandCodeFor(ScaledS, nullptr);
  4715. }
  4716. } else {
  4717. // Otherwise just expand the scaled register and an explicit scale,
  4718. // which is expected to be matched as part of the address.
  4719. // Flush the operand list to suppress SCEVExpander hoisting address modes.
  4720. // Unless the addressing mode will not be folded.
  4721. if (!Ops.empty() && LU.Kind == LSRUse::Address &&
  4722. isAMCompletelyFolded(TTI, LU, F)) {
  4723. Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), nullptr);
  4724. Ops.clear();
  4725. Ops.push_back(SE.getUnknown(FullV));
  4726. }
  4727. ScaledS = SE.getUnknown(Rewriter.expandCodeFor(ScaledS, nullptr));
  4728. if (F.Scale != 1)
  4729. ScaledS =
  4730. SE.getMulExpr(ScaledS, SE.getConstant(ScaledS->getType(), F.Scale));
  4731. Ops.push_back(ScaledS);
  4732. }
  4733. }
  4734. // Expand the GV portion.
  4735. if (F.BaseGV) {
  4736. // Flush the operand list to suppress SCEVExpander hoisting.
  4737. if (!Ops.empty()) {
  4738. Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), IntTy);
  4739. Ops.clear();
  4740. Ops.push_back(SE.getUnknown(FullV));
  4741. }
  4742. Ops.push_back(SE.getUnknown(F.BaseGV));
  4743. }
  4744. // Flush the operand list to suppress SCEVExpander hoisting of both folded and
  4745. // unfolded offsets. LSR assumes they both live next to their uses.
  4746. if (!Ops.empty()) {
  4747. Value *FullV = Rewriter.expandCodeFor(SE.getAddExpr(Ops), Ty);
  4748. Ops.clear();
  4749. Ops.push_back(SE.getUnknown(FullV));
  4750. }
  4751. // Expand the immediate portion.
  4752. int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
  4753. if (Offset != 0) {
  4754. if (LU.Kind == LSRUse::ICmpZero) {
  4755. // The other interesting way of "folding" with an ICmpZero is to use a
  4756. // negated immediate.
  4757. if (!ICmpScaledV)
  4758. ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
  4759. else {
  4760. Ops.push_back(SE.getUnknown(ICmpScaledV));
  4761. ICmpScaledV = ConstantInt::get(IntTy, Offset);
  4762. }
  4763. } else {
  4764. // Just add the immediate values. These again are expected to be matched
  4765. // as part of the address.
  4766. Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy, Offset)));
  4767. }
  4768. }
  4769. // Expand the unfolded offset portion.
  4770. int64_t UnfoldedOffset = F.UnfoldedOffset;
  4771. if (UnfoldedOffset != 0) {
  4772. // Just add the immediate values.
  4773. Ops.push_back(SE.getUnknown(ConstantInt::getSigned(IntTy,
  4774. UnfoldedOffset)));
  4775. }
  4776. // Emit instructions summing all the operands.
  4777. const SCEV *FullS = Ops.empty() ?
  4778. SE.getConstant(IntTy, 0) :
  4779. SE.getAddExpr(Ops);
  4780. Value *FullV = Rewriter.expandCodeFor(FullS, Ty);
  4781. // We're done expanding now, so reset the rewriter.
  4782. Rewriter.clearPostInc();
  4783. // An ICmpZero Formula represents an ICmp which we're handling as a
  4784. // comparison against zero. Now that we've expanded an expression for that
  4785. // form, update the ICmp's other operand.
  4786. if (LU.Kind == LSRUse::ICmpZero) {
  4787. ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
  4788. if (auto *OperandIsInstr = dyn_cast<Instruction>(CI->getOperand(1)))
  4789. DeadInsts.emplace_back(OperandIsInstr);
  4790. assert(!F.BaseGV && "ICmp does not support folding a global value and "
  4791. "a scale at the same time!");
  4792. if (F.Scale == -1) {
  4793. if (ICmpScaledV->getType() != OpTy) {
  4794. Instruction *Cast =
  4795. CastInst::Create(CastInst::getCastOpcode(ICmpScaledV, false,
  4796. OpTy, false),
  4797. ICmpScaledV, OpTy, "tmp", CI);
  4798. ICmpScaledV = Cast;
  4799. }
  4800. CI->setOperand(1, ICmpScaledV);
  4801. } else {
  4802. // A scale of 1 means that the scale has been expanded as part of the
  4803. // base regs.
  4804. assert((F.Scale == 0 || F.Scale == 1) &&
  4805. "ICmp does not support folding a global value and "
  4806. "a scale at the same time!");
  4807. Constant *C = ConstantInt::getSigned(SE.getEffectiveSCEVType(OpTy),
  4808. -(uint64_t)Offset);
  4809. if (C->getType() != OpTy)
  4810. C = ConstantExpr::getCast(CastInst::getCastOpcode(C, false,
  4811. OpTy, false),
  4812. C, OpTy);
  4813. CI->setOperand(1, C);
  4814. }
  4815. }
  4816. return FullV;
  4817. }
  4818. /// Helper for Rewrite. PHI nodes are special because the use of their operands
  4819. /// effectively happens in their predecessor blocks, so the expression may need
  4820. /// to be expanded in multiple places.
  4821. void LSRInstance::RewriteForPHI(
  4822. PHINode *PN, const LSRUse &LU, const LSRFixup &LF, const Formula &F,
  4823. SCEVExpander &Rewriter, SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
  4824. DenseMap<BasicBlock *, Value *> Inserted;
  4825. for (unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
  4826. if (PN->getIncomingValue(i) == LF.OperandValToReplace) {
  4827. bool needUpdateFixups = false;
  4828. BasicBlock *BB = PN->getIncomingBlock(i);
  4829. // If this is a critical edge, split the edge so that we do not insert
  4830. // the code on all predecessor/successor paths. We do this unless this
  4831. // is the canonical backedge for this loop, which complicates post-inc
  4832. // users.
  4833. if (e != 1 && BB->getTerminator()->getNumSuccessors() > 1 &&
  4834. !isa<IndirectBrInst>(BB->getTerminator()) &&
  4835. !isa<CatchSwitchInst>(BB->getTerminator())) {
  4836. BasicBlock *Parent = PN->getParent();
  4837. Loop *PNLoop = LI.getLoopFor(Parent);
  4838. if (!PNLoop || Parent != PNLoop->getHeader()) {
  4839. // Split the critical edge.
  4840. BasicBlock *NewBB = nullptr;
  4841. if (!Parent->isLandingPad()) {
  4842. NewBB =
  4843. SplitCriticalEdge(BB, Parent,
  4844. CriticalEdgeSplittingOptions(&DT, &LI, MSSAU)
  4845. .setMergeIdenticalEdges()
  4846. .setKeepOneInputPHIs());
  4847. } else {
  4848. SmallVector<BasicBlock*, 2> NewBBs;
  4849. SplitLandingPadPredecessors(Parent, BB, "", "", NewBBs, &DT, &LI);
  4850. NewBB = NewBBs[0];
  4851. }
  4852. // If NewBB==NULL, then SplitCriticalEdge refused to split because all
  4853. // phi predecessors are identical. The simple thing to do is skip
  4854. // splitting in this case rather than complicate the API.
  4855. if (NewBB) {
  4856. // If PN is outside of the loop and BB is in the loop, we want to
  4857. // move the block to be immediately before the PHI block, not
  4858. // immediately after BB.
  4859. if (L->contains(BB) && !L->contains(PN))
  4860. NewBB->moveBefore(PN->getParent());
  4861. // Splitting the edge can reduce the number of PHI entries we have.
  4862. e = PN->getNumIncomingValues();
  4863. BB = NewBB;
  4864. i = PN->getBasicBlockIndex(BB);
  4865. needUpdateFixups = true;
  4866. }
  4867. }
  4868. }
  4869. std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> Pair =
  4870. Inserted.insert(std::make_pair(BB, static_cast<Value *>(nullptr)));
  4871. if (!Pair.second)
  4872. PN->setIncomingValue(i, Pair.first->second);
  4873. else {
  4874. Value *FullV = Expand(LU, LF, F, BB->getTerminator()->getIterator(),
  4875. Rewriter, DeadInsts);
  4876. // If this is reuse-by-noop-cast, insert the noop cast.
  4877. Type *OpTy = LF.OperandValToReplace->getType();
  4878. if (FullV->getType() != OpTy)
  4879. FullV =
  4880. CastInst::Create(CastInst::getCastOpcode(FullV, false,
  4881. OpTy, false),
  4882. FullV, LF.OperandValToReplace->getType(),
  4883. "tmp", BB->getTerminator());
  4884. PN->setIncomingValue(i, FullV);
  4885. Pair.first->second = FullV;
  4886. }
  4887. // If LSR splits critical edge and phi node has other pending
  4888. // fixup operands, we need to update those pending fixups. Otherwise
  4889. // formulae will not be implemented completely and some instructions
  4890. // will not be eliminated.
  4891. if (needUpdateFixups) {
  4892. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
  4893. for (LSRFixup &Fixup : Uses[LUIdx].Fixups)
  4894. // If fixup is supposed to rewrite some operand in the phi
  4895. // that was just updated, it may be already moved to
  4896. // another phi node. Such fixup requires update.
  4897. if (Fixup.UserInst == PN) {
  4898. // Check if the operand we try to replace still exists in the
  4899. // original phi.
  4900. bool foundInOriginalPHI = false;
  4901. for (const auto &val : PN->incoming_values())
  4902. if (val == Fixup.OperandValToReplace) {
  4903. foundInOriginalPHI = true;
  4904. break;
  4905. }
  4906. // If fixup operand found in original PHI - nothing to do.
  4907. if (foundInOriginalPHI)
  4908. continue;
  4909. // Otherwise it might be moved to another PHI and requires update.
  4910. // If fixup operand not found in any of the incoming blocks that
  4911. // means we have already rewritten it - nothing to do.
  4912. for (const auto &Block : PN->blocks())
  4913. for (BasicBlock::iterator I = Block->begin(); isa<PHINode>(I);
  4914. ++I) {
  4915. PHINode *NewPN = cast<PHINode>(I);
  4916. for (const auto &val : NewPN->incoming_values())
  4917. if (val == Fixup.OperandValToReplace)
  4918. Fixup.UserInst = NewPN;
  4919. }
  4920. }
  4921. }
  4922. }
  4923. }
  4924. /// Emit instructions for the leading candidate expression for this LSRUse (this
  4925. /// is called "expanding"), and update the UserInst to reference the newly
  4926. /// expanded value.
  4927. void LSRInstance::Rewrite(const LSRUse &LU, const LSRFixup &LF,
  4928. const Formula &F, SCEVExpander &Rewriter,
  4929. SmallVectorImpl<WeakTrackingVH> &DeadInsts) const {
  4930. // First, find an insertion point that dominates UserInst. For PHI nodes,
  4931. // find the nearest block which dominates all the relevant uses.
  4932. if (PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
  4933. RewriteForPHI(PN, LU, LF, F, Rewriter, DeadInsts);
  4934. } else {
  4935. Value *FullV =
  4936. Expand(LU, LF, F, LF.UserInst->getIterator(), Rewriter, DeadInsts);
  4937. // If this is reuse-by-noop-cast, insert the noop cast.
  4938. Type *OpTy = LF.OperandValToReplace->getType();
  4939. if (FullV->getType() != OpTy) {
  4940. Instruction *Cast =
  4941. CastInst::Create(CastInst::getCastOpcode(FullV, false, OpTy, false),
  4942. FullV, OpTy, "tmp", LF.UserInst);
  4943. FullV = Cast;
  4944. }
  4945. // Update the user. ICmpZero is handled specially here (for now) because
  4946. // Expand may have updated one of the operands of the icmp already, and
  4947. // its new value may happen to be equal to LF.OperandValToReplace, in
  4948. // which case doing replaceUsesOfWith leads to replacing both operands
  4949. // with the same value. TODO: Reorganize this.
  4950. if (LU.Kind == LSRUse::ICmpZero)
  4951. LF.UserInst->setOperand(0, FullV);
  4952. else
  4953. LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
  4954. }
  4955. if (auto *OperandIsInstr = dyn_cast<Instruction>(LF.OperandValToReplace))
  4956. DeadInsts.emplace_back(OperandIsInstr);
  4957. }
  4958. /// Rewrite all the fixup locations with new values, following the chosen
  4959. /// solution.
  4960. void LSRInstance::ImplementSolution(
  4961. const SmallVectorImpl<const Formula *> &Solution) {
  4962. // Keep track of instructions we may have made dead, so that
  4963. // we can remove them after we are done working.
  4964. SmallVector<WeakTrackingVH, 16> DeadInsts;
  4965. SCEVExpander Rewriter(SE, L->getHeader()->getModule()->getDataLayout(), "lsr",
  4966. false);
  4967. #ifndef NDEBUG
  4968. Rewriter.setDebugType(DEBUG_TYPE);
  4969. #endif
  4970. Rewriter.disableCanonicalMode();
  4971. Rewriter.enableLSRMode();
  4972. Rewriter.setIVIncInsertPos(L, IVIncInsertPos);
  4973. // Mark phi nodes that terminate chains so the expander tries to reuse them.
  4974. for (const IVChain &Chain : IVChainVec) {
  4975. if (PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
  4976. Rewriter.setChainedPhi(PN);
  4977. }
  4978. // Expand the new value definitions and update the users.
  4979. for (size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
  4980. for (const LSRFixup &Fixup : Uses[LUIdx].Fixups) {
  4981. Rewrite(Uses[LUIdx], Fixup, *Solution[LUIdx], Rewriter, DeadInsts);
  4982. Changed = true;
  4983. }
  4984. for (const IVChain &Chain : IVChainVec) {
  4985. GenerateIVChain(Chain, Rewriter, DeadInsts);
  4986. Changed = true;
  4987. }
  4988. for (const WeakVH &IV : Rewriter.getInsertedIVs())
  4989. if (IV && dyn_cast<Instruction>(&*IV)->getParent())
  4990. ScalarEvolutionIVs.push_back(IV);
  4991. // Clean up after ourselves. This must be done before deleting any
  4992. // instructions.
  4993. Rewriter.clear();
  4994. Changed |= RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts,
  4995. &TLI, MSSAU);
  4996. // In our cost analysis above, we assume that each addrec consumes exactly
  4997. // one register, and arrange to have increments inserted just before the
  4998. // latch to maximimize the chance this is true. However, if we reused
  4999. // existing IVs, we now need to move the increments to match our
  5000. // expectations. Otherwise, our cost modeling results in us having a
  5001. // chosen a non-optimal result for the actual schedule. (And yes, this
  5002. // scheduling decision does impact later codegen.)
  5003. for (PHINode &PN : L->getHeader()->phis()) {
  5004. BinaryOperator *BO = nullptr;
  5005. Value *Start = nullptr, *Step = nullptr;
  5006. if (!matchSimpleRecurrence(&PN, BO, Start, Step))
  5007. continue;
  5008. switch (BO->getOpcode()) {
  5009. case Instruction::Sub:
  5010. if (BO->getOperand(0) != &PN)
  5011. // sub is non-commutative - match handling elsewhere in LSR
  5012. continue;
  5013. break;
  5014. case Instruction::Add:
  5015. break;
  5016. default:
  5017. continue;
  5018. };
  5019. if (!isa<Constant>(Step))
  5020. // If not a constant step, might increase register pressure
  5021. // (We assume constants have been canonicalized to RHS)
  5022. continue;
  5023. if (BO->getParent() == IVIncInsertPos->getParent())
  5024. // Only bother moving across blocks. Isel can handle block local case.
  5025. continue;
  5026. // Can we legally schedule inc at the desired point?
  5027. if (!llvm::all_of(BO->uses(),
  5028. [&](Use &U) {return DT.dominates(IVIncInsertPos, U);}))
  5029. continue;
  5030. BO->moveBefore(IVIncInsertPos);
  5031. Changed = true;
  5032. }
  5033. }
  5034. LSRInstance::LSRInstance(Loop *L, IVUsers &IU, ScalarEvolution &SE,
  5035. DominatorTree &DT, LoopInfo &LI,
  5036. const TargetTransformInfo &TTI, AssumptionCache &AC,
  5037. TargetLibraryInfo &TLI, MemorySSAUpdater *MSSAU)
  5038. : IU(IU), SE(SE), DT(DT), LI(LI), AC(AC), TLI(TLI), TTI(TTI), L(L),
  5039. MSSAU(MSSAU), AMK(PreferredAddresingMode.getNumOccurrences() > 0 ?
  5040. PreferredAddresingMode : TTI.getPreferredAddressingMode(L, &SE)) {
  5041. // If LoopSimplify form is not available, stay out of trouble.
  5042. if (!L->isLoopSimplifyForm())
  5043. return;
  5044. // If there's no interesting work to be done, bail early.
  5045. if (IU.empty()) return;
  5046. // If there's too much analysis to be done, bail early. We won't be able to
  5047. // model the problem anyway.
  5048. unsigned NumUsers = 0;
  5049. for (const IVStrideUse &U : IU) {
  5050. if (++NumUsers > MaxIVUsers) {
  5051. (void)U;
  5052. LLVM_DEBUG(dbgs() << "LSR skipping loop, too many IV Users in " << U
  5053. << "\n");
  5054. return;
  5055. }
  5056. // Bail out if we have a PHI on an EHPad that gets a value from a
  5057. // CatchSwitchInst. Because the CatchSwitchInst cannot be split, there is
  5058. // no good place to stick any instructions.
  5059. if (auto *PN = dyn_cast<PHINode>(U.getUser())) {
  5060. auto *FirstNonPHI = PN->getParent()->getFirstNonPHI();
  5061. if (isa<FuncletPadInst>(FirstNonPHI) ||
  5062. isa<CatchSwitchInst>(FirstNonPHI))
  5063. for (BasicBlock *PredBB : PN->blocks())
  5064. if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI()))
  5065. return;
  5066. }
  5067. }
  5068. LLVM_DEBUG(dbgs() << "\nLSR on loop ";
  5069. L->getHeader()->printAsOperand(dbgs(), /*PrintType=*/false);
  5070. dbgs() << ":\n");
  5071. // First, perform some low-level loop optimizations.
  5072. OptimizeShadowIV();
  5073. OptimizeLoopTermCond();
  5074. // If loop preparation eliminates all interesting IV users, bail.
  5075. if (IU.empty()) return;
  5076. // Skip nested loops until we can model them better with formulae.
  5077. if (!L->isInnermost()) {
  5078. LLVM_DEBUG(dbgs() << "LSR skipping outer loop " << *L << "\n");
  5079. return;
  5080. }
  5081. // Start collecting data and preparing for the solver.
  5082. // If number of registers is not the major cost, we cannot benefit from the
  5083. // current profitable chain optimization which is based on number of
  5084. // registers.
  5085. // FIXME: add profitable chain optimization for other kinds major cost, for
  5086. // example number of instructions.
  5087. if (TTI.isNumRegsMajorCostOfLSR() || StressIVChain)
  5088. CollectChains();
  5089. CollectInterestingTypesAndFactors();
  5090. CollectFixupsAndInitialFormulae();
  5091. CollectLoopInvariantFixupsAndFormulae();
  5092. if (Uses.empty())
  5093. return;
  5094. LLVM_DEBUG(dbgs() << "LSR found " << Uses.size() << " uses:\n";
  5095. print_uses(dbgs()));
  5096. // Now use the reuse data to generate a bunch of interesting ways
  5097. // to formulate the values needed for the uses.
  5098. GenerateAllReuseFormulae();
  5099. FilterOutUndesirableDedicatedRegisters();
  5100. NarrowSearchSpaceUsingHeuristics();
  5101. SmallVector<const Formula *, 8> Solution;
  5102. Solve(Solution);
  5103. // Release memory that is no longer needed.
  5104. Factors.clear();
  5105. Types.clear();
  5106. RegUses.clear();
  5107. if (Solution.empty())
  5108. return;
  5109. #ifndef NDEBUG
  5110. // Formulae should be legal.
  5111. for (const LSRUse &LU : Uses) {
  5112. for (const Formula &F : LU.Formulae)
  5113. assert(isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
  5114. F) && "Illegal formula generated!");
  5115. };
  5116. #endif
  5117. // Now that we've decided what we want, make it so.
  5118. ImplementSolution(Solution);
  5119. }
  5120. #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
  5121. void LSRInstance::print_factors_and_types(raw_ostream &OS) const {
  5122. if (Factors.empty() && Types.empty()) return;
  5123. OS << "LSR has identified the following interesting factors and types: ";
  5124. bool First = true;
  5125. for (int64_t Factor : Factors) {
  5126. if (!First) OS << ", ";
  5127. First = false;
  5128. OS << '*' << Factor;
  5129. }
  5130. for (Type *Ty : Types) {
  5131. if (!First) OS << ", ";
  5132. First = false;
  5133. OS << '(' << *Ty << ')';
  5134. }
  5135. OS << '\n';
  5136. }
  5137. void LSRInstance::print_fixups(raw_ostream &OS) const {
  5138. OS << "LSR is examining the following fixup sites:\n";
  5139. for (const LSRUse &LU : Uses)
  5140. for (const LSRFixup &LF : LU.Fixups) {
  5141. dbgs() << " ";
  5142. LF.print(OS);
  5143. OS << '\n';
  5144. }
  5145. }
  5146. void LSRInstance::print_uses(raw_ostream &OS) const {
  5147. OS << "LSR is examining the following uses:\n";
  5148. for (const LSRUse &LU : Uses) {
  5149. dbgs() << " ";
  5150. LU.print(OS);
  5151. OS << '\n';
  5152. for (const Formula &F : LU.Formulae) {
  5153. OS << " ";
  5154. F.print(OS);
  5155. OS << '\n';
  5156. }
  5157. }
  5158. }
  5159. void LSRInstance::print(raw_ostream &OS) const {
  5160. print_factors_and_types(OS);
  5161. print_fixups(OS);
  5162. print_uses(OS);
  5163. }
  5164. LLVM_DUMP_METHOD void LSRInstance::dump() const {
  5165. print(errs()); errs() << '\n';
  5166. }
  5167. #endif
  5168. namespace {
  5169. class LoopStrengthReduce : public LoopPass {
  5170. public:
  5171. static char ID; // Pass ID, replacement for typeid
  5172. LoopStrengthReduce();
  5173. private:
  5174. bool runOnLoop(Loop *L, LPPassManager &LPM) override;
  5175. void getAnalysisUsage(AnalysisUsage &AU) const override;
  5176. };
  5177. } // end anonymous namespace
  5178. LoopStrengthReduce::LoopStrengthReduce() : LoopPass(ID) {
  5179. initializeLoopStrengthReducePass(*PassRegistry::getPassRegistry());
  5180. }
  5181. void LoopStrengthReduce::getAnalysisUsage(AnalysisUsage &AU) const {
  5182. // We split critical edges, so we change the CFG. However, we do update
  5183. // many analyses if they are around.
  5184. AU.addPreservedID(LoopSimplifyID);
  5185. AU.addRequired<LoopInfoWrapperPass>();
  5186. AU.addPreserved<LoopInfoWrapperPass>();
  5187. AU.addRequiredID(LoopSimplifyID);
  5188. AU.addRequired<DominatorTreeWrapperPass>();
  5189. AU.addPreserved<DominatorTreeWrapperPass>();
  5190. AU.addRequired<ScalarEvolutionWrapperPass>();
  5191. AU.addPreserved<ScalarEvolutionWrapperPass>();
  5192. AU.addRequired<AssumptionCacheTracker>();
  5193. AU.addRequired<TargetLibraryInfoWrapperPass>();
  5194. // Requiring LoopSimplify a second time here prevents IVUsers from running
  5195. // twice, since LoopSimplify was invalidated by running ScalarEvolution.
  5196. AU.addRequiredID(LoopSimplifyID);
  5197. AU.addRequired<IVUsersWrapperPass>();
  5198. AU.addPreserved<IVUsersWrapperPass>();
  5199. AU.addRequired<TargetTransformInfoWrapperPass>();
  5200. AU.addPreserved<MemorySSAWrapperPass>();
  5201. }
  5202. namespace {
  5203. struct SCEVDbgValueBuilder {
  5204. SCEVDbgValueBuilder() = default;
  5205. SCEVDbgValueBuilder(const SCEVDbgValueBuilder &Base) {
  5206. Values = Base.Values;
  5207. Expr = Base.Expr;
  5208. }
  5209. /// The DIExpression as we translate the SCEV.
  5210. SmallVector<uint64_t, 6> Expr;
  5211. /// The location ops of the DIExpression.
  5212. SmallVector<llvm::ValueAsMetadata *, 2> Values;
  5213. void pushOperator(uint64_t Op) { Expr.push_back(Op); }
  5214. void pushUInt(uint64_t Operand) { Expr.push_back(Operand); }
  5215. /// Add a DW_OP_LLVM_arg to the expression, followed by the index of the value
  5216. /// in the set of values referenced by the expression.
  5217. void pushValue(llvm::Value *V) {
  5218. Expr.push_back(llvm::dwarf::DW_OP_LLVM_arg);
  5219. auto *It =
  5220. std::find(Values.begin(), Values.end(), llvm::ValueAsMetadata::get(V));
  5221. unsigned ArgIndex = 0;
  5222. if (It != Values.end()) {
  5223. ArgIndex = std::distance(Values.begin(), It);
  5224. } else {
  5225. ArgIndex = Values.size();
  5226. Values.push_back(llvm::ValueAsMetadata::get(V));
  5227. }
  5228. Expr.push_back(ArgIndex);
  5229. }
  5230. void pushValue(const SCEVUnknown *U) {
  5231. llvm::Value *V = cast<SCEVUnknown>(U)->getValue();
  5232. pushValue(V);
  5233. }
  5234. bool pushConst(const SCEVConstant *C) {
  5235. if (C->getAPInt().getMinSignedBits() > 64)
  5236. return false;
  5237. Expr.push_back(llvm::dwarf::DW_OP_consts);
  5238. Expr.push_back(C->getAPInt().getSExtValue());
  5239. return true;
  5240. }
  5241. /// Several SCEV types are sequences of the same arithmetic operator applied
  5242. /// to constants and values that may be extended or truncated.
  5243. bool pushArithmeticExpr(const llvm::SCEVCommutativeExpr *CommExpr,
  5244. uint64_t DwarfOp) {
  5245. assert((isa<llvm::SCEVAddExpr>(CommExpr) || isa<SCEVMulExpr>(CommExpr)) &&
  5246. "Expected arithmetic SCEV type");
  5247. bool Success = true;
  5248. unsigned EmitOperator = 0;
  5249. for (auto &Op : CommExpr->operands()) {
  5250. Success &= pushSCEV(Op);
  5251. if (EmitOperator >= 1)
  5252. pushOperator(DwarfOp);
  5253. ++EmitOperator;
  5254. }
  5255. return Success;
  5256. }
  5257. // TODO: Identify and omit noop casts.
  5258. bool pushCast(const llvm::SCEVCastExpr *C, bool IsSigned) {
  5259. const llvm::SCEV *Inner = C->getOperand(0);
  5260. const llvm::Type *Type = C->getType();
  5261. uint64_t ToWidth = Type->getIntegerBitWidth();
  5262. bool Success = pushSCEV(Inner);
  5263. uint64_t CastOps[] = {dwarf::DW_OP_LLVM_convert, ToWidth,
  5264. IsSigned ? llvm::dwarf::DW_ATE_signed
  5265. : llvm::dwarf::DW_ATE_unsigned};
  5266. for (const auto &Op : CastOps)
  5267. pushOperator(Op);
  5268. return Success;
  5269. }
  5270. // TODO: MinMax - although these haven't been encountered in the test suite.
  5271. bool pushSCEV(const llvm::SCEV *S) {
  5272. bool Success = true;
  5273. if (const SCEVConstant *StartInt = dyn_cast<SCEVConstant>(S)) {
  5274. Success &= pushConst(StartInt);
  5275. } else if (const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
  5276. if (!U->getValue())
  5277. return false;
  5278. pushValue(U->getValue());
  5279. } else if (const SCEVMulExpr *MulRec = dyn_cast<SCEVMulExpr>(S)) {
  5280. Success &= pushArithmeticExpr(MulRec, llvm::dwarf::DW_OP_mul);
  5281. } else if (const SCEVUDivExpr *UDiv = dyn_cast<SCEVUDivExpr>(S)) {
  5282. Success &= pushSCEV(UDiv->getLHS());
  5283. Success &= pushSCEV(UDiv->getRHS());
  5284. pushOperator(llvm::dwarf::DW_OP_div);
  5285. } else if (const SCEVCastExpr *Cast = dyn_cast<SCEVCastExpr>(S)) {
  5286. // Assert if a new and unknown SCEVCastEXpr type is encountered.
  5287. assert((isa<SCEVZeroExtendExpr>(Cast) || isa<SCEVTruncateExpr>(Cast) ||
  5288. isa<SCEVPtrToIntExpr>(Cast) || isa<SCEVSignExtendExpr>(Cast)) &&
  5289. "Unexpected cast type in SCEV.");
  5290. Success &= pushCast(Cast, (isa<SCEVSignExtendExpr>(Cast)));
  5291. } else if (const SCEVAddExpr *AddExpr = dyn_cast<SCEVAddExpr>(S)) {
  5292. Success &= pushArithmeticExpr(AddExpr, llvm::dwarf::DW_OP_plus);
  5293. } else if (isa<SCEVAddRecExpr>(S)) {
  5294. // Nested SCEVAddRecExpr are generated by nested loops and are currently
  5295. // unsupported.
  5296. return false;
  5297. } else {
  5298. return false;
  5299. }
  5300. return Success;
  5301. }
  5302. void setFinalExpression(llvm::DbgValueInst &DI, const DIExpression *OldExpr) {
  5303. // Re-state assumption that this dbg.value is not variadic. Any remaining
  5304. // opcodes in its expression operate on a single value already on the
  5305. // expression stack. Prepend our operations, which will re-compute and
  5306. // place that value on the expression stack.
  5307. assert(!DI.hasArgList());
  5308. auto *NewExpr =
  5309. DIExpression::prependOpcodes(OldExpr, Expr, /*StackValue*/ true);
  5310. DI.setExpression(NewExpr);
  5311. auto ValArrayRef = llvm::ArrayRef<llvm::ValueAsMetadata *>(Values);
  5312. DI.setRawLocation(llvm::DIArgList::get(DI.getContext(), ValArrayRef));
  5313. }
  5314. /// If a DVI can be emitted without a DIArgList, omit DW_OP_llvm_arg and the
  5315. /// location op index 0.
  5316. void setShortFinalExpression(llvm::DbgValueInst &DI,
  5317. const DIExpression *OldExpr) {
  5318. assert((Expr[0] == llvm::dwarf::DW_OP_LLVM_arg && Expr[1] == 0) &&
  5319. "Expected DW_OP_llvm_arg and 0.");
  5320. DI.replaceVariableLocationOp(
  5321. 0u, llvm::MetadataAsValue::get(DI.getContext(), Values[0]));
  5322. // See setFinalExpression: prepend our opcodes on the start of any old
  5323. // expression opcodes.
  5324. assert(!DI.hasArgList());
  5325. llvm::SmallVector<uint64_t, 6> FinalExpr(llvm::drop_begin(Expr, 2));
  5326. auto *NewExpr =
  5327. DIExpression::prependOpcodes(OldExpr, FinalExpr, /*StackValue*/ true);
  5328. DI.setExpression(NewExpr);
  5329. }
  5330. /// Once the IV and variable SCEV translation is complete, write it to the
  5331. /// source DVI.
  5332. void applyExprToDbgValue(llvm::DbgValueInst &DI,
  5333. const DIExpression *OldExpr) {
  5334. assert(!Expr.empty() && "Unexpected empty expression.");
  5335. // Emit a simpler form if only a single location is referenced.
  5336. if (Values.size() == 1 && Expr[0] == llvm::dwarf::DW_OP_LLVM_arg &&
  5337. Expr[1] == 0) {
  5338. setShortFinalExpression(DI, OldExpr);
  5339. } else {
  5340. setFinalExpression(DI, OldExpr);
  5341. }
  5342. }
  5343. /// Return true if the combination of arithmetic operator and underlying
  5344. /// SCEV constant value is an identity function.
  5345. bool isIdentityFunction(uint64_t Op, const SCEV *S) {
  5346. if (const SCEVConstant *C = dyn_cast<SCEVConstant>(S)) {
  5347. if (C->getAPInt().getMinSignedBits() > 64)
  5348. return false;
  5349. int64_t I = C->getAPInt().getSExtValue();
  5350. switch (Op) {
  5351. case llvm::dwarf::DW_OP_plus:
  5352. case llvm::dwarf::DW_OP_minus:
  5353. return I == 0;
  5354. case llvm::dwarf::DW_OP_mul:
  5355. case llvm::dwarf::DW_OP_div:
  5356. return I == 1;
  5357. }
  5358. }
  5359. return false;
  5360. }
  5361. /// Convert a SCEV of a value to a DIExpression that is pushed onto the
  5362. /// builder's expression stack. The stack should already contain an
  5363. /// expression for the iteration count, so that it can be multiplied by
  5364. /// the stride and added to the start.
  5365. /// Components of the expression are omitted if they are an identity function.
  5366. /// Chain (non-affine) SCEVs are not supported.
  5367. bool SCEVToValueExpr(const llvm::SCEVAddRecExpr &SAR, ScalarEvolution &SE) {
  5368. assert(SAR.isAffine() && "Expected affine SCEV");
  5369. // TODO: Is this check needed?
  5370. if (isa<SCEVAddRecExpr>(SAR.getStart()))
  5371. return false;
  5372. const SCEV *Start = SAR.getStart();
  5373. const SCEV *Stride = SAR.getStepRecurrence(SE);
  5374. // Skip pushing arithmetic noops.
  5375. if (!isIdentityFunction(llvm::dwarf::DW_OP_mul, Stride)) {
  5376. if (!pushSCEV(Stride))
  5377. return false;
  5378. pushOperator(llvm::dwarf::DW_OP_mul);
  5379. }
  5380. if (!isIdentityFunction(llvm::dwarf::DW_OP_plus, Start)) {
  5381. if (!pushSCEV(Start))
  5382. return false;
  5383. pushOperator(llvm::dwarf::DW_OP_plus);
  5384. }
  5385. return true;
  5386. }
  5387. /// Convert a SCEV of a value to a DIExpression that is pushed onto the
  5388. /// builder's expression stack. The stack should already contain an
  5389. /// expression for the iteration count, so that it can be multiplied by
  5390. /// the stride and added to the start.
  5391. /// Components of the expression are omitted if they are an identity function.
  5392. bool SCEVToIterCountExpr(const llvm::SCEVAddRecExpr &SAR,
  5393. ScalarEvolution &SE) {
  5394. assert(SAR.isAffine() && "Expected affine SCEV");
  5395. if (isa<SCEVAddRecExpr>(SAR.getStart())) {
  5396. LLVM_DEBUG(dbgs() << "scev-salvage: IV SCEV. Unsupported nested AddRec: "
  5397. << SAR << '\n');
  5398. return false;
  5399. }
  5400. const SCEV *Start = SAR.getStart();
  5401. const SCEV *Stride = SAR.getStepRecurrence(SE);
  5402. // Skip pushing arithmetic noops.
  5403. if (!isIdentityFunction(llvm::dwarf::DW_OP_minus, Start)) {
  5404. if (!pushSCEV(Start))
  5405. return false;
  5406. pushOperator(llvm::dwarf::DW_OP_minus);
  5407. }
  5408. if (!isIdentityFunction(llvm::dwarf::DW_OP_div, Stride)) {
  5409. if (!pushSCEV(Stride))
  5410. return false;
  5411. pushOperator(llvm::dwarf::DW_OP_div);
  5412. }
  5413. return true;
  5414. }
  5415. };
  5416. struct DVIRecoveryRec {
  5417. DbgValueInst *DVI;
  5418. DIExpression *Expr;
  5419. Metadata *LocationOp;
  5420. const llvm::SCEV *SCEV;
  5421. };
  5422. } // namespace
  5423. static void RewriteDVIUsingIterCount(DVIRecoveryRec CachedDVI,
  5424. const SCEVDbgValueBuilder &IterationCount,
  5425. ScalarEvolution &SE) {
  5426. // LSR may add locations to previously single location-op DVIs which
  5427. // are currently not supported.
  5428. if (CachedDVI.DVI->getNumVariableLocationOps() != 1)
  5429. return;
  5430. // SCEVs for SSA values are most frquently of the form
  5431. // {start,+,stride}, but sometimes they are ({start,+,stride} + %a + ..).
  5432. // This is because %a is a PHI node that is not the IV. However, these
  5433. // SCEVs have not been observed to result in debuginfo-lossy optimisations,
  5434. // so its not expected this point will be reached.
  5435. if (!isa<SCEVAddRecExpr>(CachedDVI.SCEV))
  5436. return;
  5437. LLVM_DEBUG(dbgs() << "scev-salvage: Value to salvage SCEV: "
  5438. << *CachedDVI.SCEV << '\n');
  5439. const auto *Rec = cast<SCEVAddRecExpr>(CachedDVI.SCEV);
  5440. if (!Rec->isAffine())
  5441. return;
  5442. if (CachedDVI.SCEV->getExpressionSize() > MaxSCEVSalvageExpressionSize)
  5443. return;
  5444. // Initialise a new builder with the iteration count expression. In
  5445. // combination with the value's SCEV this enables recovery.
  5446. SCEVDbgValueBuilder RecoverValue(IterationCount);
  5447. if (!RecoverValue.SCEVToValueExpr(*Rec, SE))
  5448. return;
  5449. LLVM_DEBUG(dbgs() << "scev-salvage: Updating: " << *CachedDVI.DVI << '\n');
  5450. RecoverValue.applyExprToDbgValue(*CachedDVI.DVI, CachedDVI.Expr);
  5451. LLVM_DEBUG(dbgs() << "scev-salvage: to: " << *CachedDVI.DVI << '\n');
  5452. }
  5453. static void RewriteDVIUsingOffset(DVIRecoveryRec &DVIRec, llvm::PHINode &IV,
  5454. int64_t Offset) {
  5455. assert(!DVIRec.DVI->hasArgList() && "Expected single location-op dbg.value.");
  5456. DbgValueInst *DVI = DVIRec.DVI;
  5457. SmallVector<uint64_t, 8> Ops;
  5458. DIExpression::appendOffset(Ops, Offset);
  5459. DIExpression *Expr = DIExpression::prependOpcodes(DVIRec.Expr, Ops, true);
  5460. LLVM_DEBUG(dbgs() << "scev-salvage: Updating: " << *DVIRec.DVI << '\n');
  5461. DVI->setExpression(Expr);
  5462. llvm::Value *ValIV = dyn_cast<llvm::Value>(&IV);
  5463. DVI->replaceVariableLocationOp(
  5464. 0u, llvm::MetadataAsValue::get(DVI->getContext(),
  5465. llvm::ValueAsMetadata::get(ValIV)));
  5466. LLVM_DEBUG(dbgs() << "scev-salvage: updated with offset to IV: "
  5467. << *DVIRec.DVI << '\n');
  5468. }
  5469. static void
  5470. DbgRewriteSalvageableDVIs(llvm::Loop *L, ScalarEvolution &SE,
  5471. llvm::PHINode *LSRInductionVar,
  5472. SmallVector<DVIRecoveryRec, 2> &DVIToUpdate) {
  5473. if (DVIToUpdate.empty())
  5474. return;
  5475. const llvm::SCEV *SCEVInductionVar = SE.getSCEV(LSRInductionVar);
  5476. assert(SCEVInductionVar &&
  5477. "Anticipated a SCEV for the post-LSR induction variable");
  5478. if (const SCEVAddRecExpr *IVAddRec =
  5479. dyn_cast<SCEVAddRecExpr>(SCEVInductionVar)) {
  5480. if (!IVAddRec->isAffine())
  5481. return;
  5482. if (IVAddRec->getExpressionSize() > MaxSCEVSalvageExpressionSize)
  5483. return;
  5484. // The iteration count is required to recover location values.
  5485. SCEVDbgValueBuilder IterCountExpr;
  5486. IterCountExpr.pushValue(LSRInductionVar);
  5487. if (!IterCountExpr.SCEVToIterCountExpr(*IVAddRec, SE))
  5488. return;
  5489. LLVM_DEBUG(dbgs() << "scev-salvage: IV SCEV: " << *SCEVInductionVar
  5490. << '\n');
  5491. // Needn't salvage if the location op hasn't been undef'd by LSR.
  5492. for (auto &DVIRec : DVIToUpdate) {
  5493. if (!DVIRec.DVI->isUndef())
  5494. continue;
  5495. // Some DVIs that were single location-op when cached are now multi-op,
  5496. // due to LSR optimisations. However, multi-op salvaging is not yet
  5497. // supported by SCEV salvaging. But, we can attempt a salvage by restoring
  5498. // the pre-LSR single-op expression.
  5499. if (DVIRec.DVI->hasArgList()) {
  5500. if (!DVIRec.DVI->getVariableLocationOp(0))
  5501. continue;
  5502. llvm::Type *Ty = DVIRec.DVI->getVariableLocationOp(0)->getType();
  5503. DVIRec.DVI->setRawLocation(
  5504. llvm::ValueAsMetadata::get(UndefValue::get(Ty)));
  5505. DVIRec.DVI->setExpression(DVIRec.Expr);
  5506. }
  5507. LLVM_DEBUG(dbgs() << "scev-salvage: value to recover SCEV: "
  5508. << *DVIRec.SCEV << '\n');
  5509. // Create a simple expression if the IV and value to salvage SCEVs
  5510. // start values differ by only a constant value.
  5511. if (Optional<APInt> Offset =
  5512. SE.computeConstantDifference(DVIRec.SCEV, SCEVInductionVar)) {
  5513. if (Offset.getValue().getMinSignedBits() <= 64)
  5514. RewriteDVIUsingOffset(DVIRec, *LSRInductionVar,
  5515. Offset.getValue().getSExtValue());
  5516. } else {
  5517. RewriteDVIUsingIterCount(DVIRec, IterCountExpr, SE);
  5518. }
  5519. }
  5520. }
  5521. }
  5522. /// Identify and cache salvageable DVI locations and expressions along with the
  5523. /// corresponding SCEV(s). Also ensure that the DVI is not deleted between
  5524. /// cacheing and salvaging.
  5525. static void
  5526. DbgGatherSalvagableDVI(Loop *L, ScalarEvolution &SE,
  5527. SmallVector<DVIRecoveryRec, 2> &SalvageableDVISCEVs,
  5528. SmallSet<AssertingVH<DbgValueInst>, 2> &DVIHandles) {
  5529. for (auto &B : L->getBlocks()) {
  5530. for (auto &I : *B) {
  5531. auto DVI = dyn_cast<DbgValueInst>(&I);
  5532. if (!DVI)
  5533. continue;
  5534. if (DVI->isUndef())
  5535. continue;
  5536. if (DVI->hasArgList())
  5537. continue;
  5538. if (!DVI->getVariableLocationOp(0) ||
  5539. !SE.isSCEVable(DVI->getVariableLocationOp(0)->getType()))
  5540. continue;
  5541. // SCEVUnknown wraps an llvm::Value, it does not have a start and stride.
  5542. // Therefore no translation to DIExpression is performed.
  5543. const SCEV *S = SE.getSCEV(DVI->getVariableLocationOp(0));
  5544. if (isa<SCEVUnknown>(S))
  5545. continue;
  5546. // Avoid wasting resources generating an expression containing undef.
  5547. if (SE.containsUndefs(S))
  5548. continue;
  5549. SalvageableDVISCEVs.push_back(
  5550. {DVI, DVI->getExpression(), DVI->getRawLocation(),
  5551. SE.getSCEV(DVI->getVariableLocationOp(0))});
  5552. DVIHandles.insert(DVI);
  5553. }
  5554. }
  5555. }
  5556. /// Ideally pick the PHI IV inserted by ScalarEvolutionExpander. As a fallback
  5557. /// any PHi from the loop header is usable, but may have less chance of
  5558. /// surviving subsequent transforms.
  5559. static llvm::PHINode *GetInductionVariable(const Loop &L, ScalarEvolution &SE,
  5560. const LSRInstance &LSR) {
  5561. auto IsSuitableIV = [&](PHINode *P) {
  5562. if (!SE.isSCEVable(P->getType()))
  5563. return false;
  5564. if (const SCEVAddRecExpr *Rec = dyn_cast<SCEVAddRecExpr>(SE.getSCEV(P)))
  5565. return Rec->isAffine() && !SE.containsUndefs(SE.getSCEV(P));
  5566. return false;
  5567. };
  5568. // For now, just pick the first IV that was generated and inserted by
  5569. // ScalarEvolution. Ideally pick an IV that is unlikely to be optimised away
  5570. // by subsequent transforms.
  5571. for (const WeakVH &IV : LSR.getScalarEvolutionIVs()) {
  5572. if (!IV)
  5573. continue;
  5574. // There should only be PHI node IVs.
  5575. PHINode *P = cast<PHINode>(&*IV);
  5576. if (IsSuitableIV(P))
  5577. return P;
  5578. }
  5579. for (PHINode &P : L.getHeader()->phis()) {
  5580. if (IsSuitableIV(&P))
  5581. return &P;
  5582. }
  5583. return nullptr;
  5584. }
  5585. static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE,
  5586. DominatorTree &DT, LoopInfo &LI,
  5587. const TargetTransformInfo &TTI,
  5588. AssumptionCache &AC, TargetLibraryInfo &TLI,
  5589. MemorySSA *MSSA) {
  5590. // Debug preservation - before we start removing anything identify which DVI
  5591. // meet the salvageable criteria and store their DIExpression and SCEVs.
  5592. SmallVector<DVIRecoveryRec, 2> SalvageableDVI;
  5593. SmallSet<AssertingVH<DbgValueInst>, 2> DVIHandles;
  5594. DbgGatherSalvagableDVI(L, SE, SalvageableDVI, DVIHandles);
  5595. bool Changed = false;
  5596. std::unique_ptr<MemorySSAUpdater> MSSAU;
  5597. if (MSSA)
  5598. MSSAU = std::make_unique<MemorySSAUpdater>(MSSA);
  5599. // Run the main LSR transformation.
  5600. const LSRInstance &Reducer =
  5601. LSRInstance(L, IU, SE, DT, LI, TTI, AC, TLI, MSSAU.get());
  5602. Changed |= Reducer.getChanged();
  5603. // Remove any extra phis created by processing inner loops.
  5604. Changed |= DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get());
  5605. if (EnablePhiElim && L->isLoopSimplifyForm()) {
  5606. SmallVector<WeakTrackingVH, 16> DeadInsts;
  5607. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  5608. SCEVExpander Rewriter(SE, DL, "lsr", false);
  5609. #ifndef NDEBUG
  5610. Rewriter.setDebugType(DEBUG_TYPE);
  5611. #endif
  5612. unsigned numFolded = Rewriter.replaceCongruentIVs(L, &DT, DeadInsts, &TTI);
  5613. if (numFolded) {
  5614. Changed = true;
  5615. RecursivelyDeleteTriviallyDeadInstructionsPermissive(DeadInsts, &TLI,
  5616. MSSAU.get());
  5617. DeleteDeadPHIs(L->getHeader(), &TLI, MSSAU.get());
  5618. }
  5619. }
  5620. if (SalvageableDVI.empty())
  5621. return Changed;
  5622. // Obtain relevant IVs and attempt to rewrite the salvageable DVIs with
  5623. // expressions composed using the derived iteration count.
  5624. // TODO: Allow for multiple IV references for nested AddRecSCEVs
  5625. for (auto &L : LI) {
  5626. if (llvm::PHINode *IV = GetInductionVariable(*L, SE, Reducer))
  5627. DbgRewriteSalvageableDVIs(L, SE, IV, SalvageableDVI);
  5628. else {
  5629. LLVM_DEBUG(dbgs() << "scev-salvage: SCEV salvaging not possible. An IV "
  5630. "could not be identified.\n");
  5631. }
  5632. }
  5633. DVIHandles.clear();
  5634. return Changed;
  5635. }
  5636. bool LoopStrengthReduce::runOnLoop(Loop *L, LPPassManager & /*LPM*/) {
  5637. if (skipLoop(L))
  5638. return false;
  5639. auto &IU = getAnalysis<IVUsersWrapperPass>().getIU();
  5640. auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  5641. auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  5642. auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  5643. const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
  5644. *L->getHeader()->getParent());
  5645. auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
  5646. *L->getHeader()->getParent());
  5647. auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
  5648. *L->getHeader()->getParent());
  5649. auto *MSSAAnalysis = getAnalysisIfAvailable<MemorySSAWrapperPass>();
  5650. MemorySSA *MSSA = nullptr;
  5651. if (MSSAAnalysis)
  5652. MSSA = &MSSAAnalysis->getMSSA();
  5653. return ReduceLoopStrength(L, IU, SE, DT, LI, TTI, AC, TLI, MSSA);
  5654. }
  5655. PreservedAnalyses LoopStrengthReducePass::run(Loop &L, LoopAnalysisManager &AM,
  5656. LoopStandardAnalysisResults &AR,
  5657. LPMUpdater &) {
  5658. if (!ReduceLoopStrength(&L, AM.getResult<IVUsersAnalysis>(L, AR), AR.SE,
  5659. AR.DT, AR.LI, AR.TTI, AR.AC, AR.TLI, AR.MSSA))
  5660. return PreservedAnalyses::all();
  5661. auto PA = getLoopPassPreservedAnalyses();
  5662. if (AR.MSSA)
  5663. PA.preserve<MemorySSAAnalysis>();
  5664. return PA;
  5665. }
  5666. char LoopStrengthReduce::ID = 0;
  5667. INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce",
  5668. "Loop Strength Reduction", false, false)
  5669. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  5670. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  5671. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  5672. INITIALIZE_PASS_DEPENDENCY(IVUsersWrapperPass)
  5673. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  5674. INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
  5675. INITIALIZE_PASS_END(LoopStrengthReduce, "loop-reduce",
  5676. "Loop Strength Reduction", false, false)
  5677. Pass *llvm::createLoopStrengthReducePass() { return new LoopStrengthReduce(); }