LoopStrengthReduce.cpp 259 KB

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