LoopVectorize.cpp 311 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701
  1. //===- LoopVectorize.cpp - A Loop Vectorizer ------------------------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // This is the LLVM loop vectorizer. This pass modifies 'vectorizable' loops
  11. // and generates target-independent LLVM-IR.
  12. // The vectorizer uses the TargetTransformInfo analysis to estimate the costs
  13. // of instructions in order to estimate the profitability of vectorization.
  14. //
  15. // The loop vectorizer combines consecutive loop iterations into a single
  16. // 'wide' iteration. After this transformation the index is incremented
  17. // by the SIMD vector width, and not by one.
  18. //
  19. // This pass has three parts:
  20. // 1. The main loop pass that drives the different parts.
  21. // 2. LoopVectorizationLegality - A unit that checks for the legality
  22. // of the vectorization.
  23. // 3. InnerLoopVectorizer - A unit that performs the actual
  24. // widening of instructions.
  25. // 4. LoopVectorizationCostModel - A unit that checks for the profitability
  26. // of vectorization. It decides on the optimal vector width, which
  27. // can be one, if vectorization is not profitable.
  28. //
  29. // There is a development effort going on to migrate loop vectorizer to the
  30. // VPlan infrastructure and to introduce outer loop vectorization support (see
  31. // docs/Proposal/VectorizationPlan.rst and
  32. // http://lists.llvm.org/pipermail/llvm-dev/2017-December/119523.html). For this
  33. // purpose, we temporarily introduced the VPlan-native vectorization path: an
  34. // alternative vectorization path that is natively implemented on top of the
  35. // VPlan infrastructure. See EnableVPlanNativePath for enabling.
  36. //
  37. //===----------------------------------------------------------------------===//
  38. //
  39. // The reduction-variable vectorization is based on the paper:
  40. // D. Nuzman and R. Henderson. Multi-platform Auto-vectorization.
  41. //
  42. // Variable uniformity checks are inspired by:
  43. // Karrenberg, R. and Hack, S. Whole Function Vectorization.
  44. //
  45. // The interleaved access vectorization is based on the paper:
  46. // Dorit Nuzman, Ira Rosen and Ayal Zaks. Auto-Vectorization of Interleaved
  47. // Data for SIMD
  48. //
  49. // Other ideas/concepts are from:
  50. // A. Zaks and D. Nuzman. Autovectorization in GCC-two years later.
  51. //
  52. // S. Maleki, Y. Gao, M. Garzaran, T. Wong and D. Padua. An Evaluation of
  53. // Vectorizing Compilers.
  54. //
  55. //===----------------------------------------------------------------------===//
  56. #include "llvm/Transforms/Vectorize/LoopVectorize.h"
  57. #include "LoopVectorizationPlanner.h"
  58. #include "VPRecipeBuilder.h"
  59. #include "VPlanHCFGBuilder.h"
  60. #include "llvm/ADT/APInt.h"
  61. #include "llvm/ADT/ArrayRef.h"
  62. #include "llvm/ADT/DenseMap.h"
  63. #include "llvm/ADT/DenseMapInfo.h"
  64. #include "llvm/ADT/Hashing.h"
  65. #include "llvm/ADT/MapVector.h"
  66. #include "llvm/ADT/None.h"
  67. #include "llvm/ADT/Optional.h"
  68. #include "llvm/ADT/STLExtras.h"
  69. #include "llvm/ADT/SetVector.h"
  70. #include "llvm/ADT/SmallPtrSet.h"
  71. #include "llvm/ADT/SmallVector.h"
  72. #include "llvm/ADT/Statistic.h"
  73. #include "llvm/ADT/StringRef.h"
  74. #include "llvm/ADT/Twine.h"
  75. #include "llvm/ADT/iterator_range.h"
  76. #include "llvm/Analysis/AssumptionCache.h"
  77. #include "llvm/Analysis/BasicAliasAnalysis.h"
  78. #include "llvm/Analysis/BlockFrequencyInfo.h"
  79. #include "llvm/Analysis/CFG.h"
  80. #include "llvm/Analysis/CodeMetrics.h"
  81. #include "llvm/Analysis/DemandedBits.h"
  82. #include "llvm/Analysis/GlobalsModRef.h"
  83. #include "llvm/Analysis/LoopAccessAnalysis.h"
  84. #include "llvm/Analysis/LoopAnalysisManager.h"
  85. #include "llvm/Analysis/LoopInfo.h"
  86. #include "llvm/Analysis/LoopIterator.h"
  87. #include "llvm/Analysis/OptimizationRemarkEmitter.h"
  88. #include "llvm/Analysis/ScalarEvolution.h"
  89. #include "llvm/Analysis/ScalarEvolutionExpander.h"
  90. #include "llvm/Analysis/ScalarEvolutionExpressions.h"
  91. #include "llvm/Analysis/TargetLibraryInfo.h"
  92. #include "llvm/Analysis/TargetTransformInfo.h"
  93. #include "llvm/Analysis/VectorUtils.h"
  94. #include "llvm/IR/Attributes.h"
  95. #include "llvm/IR/BasicBlock.h"
  96. #include "llvm/IR/CFG.h"
  97. #include "llvm/IR/Constant.h"
  98. #include "llvm/IR/Constants.h"
  99. #include "llvm/IR/DataLayout.h"
  100. #include "llvm/IR/DebugInfoMetadata.h"
  101. #include "llvm/IR/DebugLoc.h"
  102. #include "llvm/IR/DerivedTypes.h"
  103. #include "llvm/IR/DiagnosticInfo.h"
  104. #include "llvm/IR/Dominators.h"
  105. #include "llvm/IR/Function.h"
  106. #include "llvm/IR/IRBuilder.h"
  107. #include "llvm/IR/InstrTypes.h"
  108. #include "llvm/IR/Instruction.h"
  109. #include "llvm/IR/Instructions.h"
  110. #include "llvm/IR/IntrinsicInst.h"
  111. #include "llvm/IR/Intrinsics.h"
  112. #include "llvm/IR/LLVMContext.h"
  113. #include "llvm/IR/Metadata.h"
  114. #include "llvm/IR/Module.h"
  115. #include "llvm/IR/Operator.h"
  116. #include "llvm/IR/Type.h"
  117. #include "llvm/IR/Use.h"
  118. #include "llvm/IR/User.h"
  119. #include "llvm/IR/Value.h"
  120. #include "llvm/IR/ValueHandle.h"
  121. #include "llvm/IR/Verifier.h"
  122. #include "llvm/Pass.h"
  123. #include "llvm/Support/Casting.h"
  124. #include "llvm/Support/CommandLine.h"
  125. #include "llvm/Support/Compiler.h"
  126. #include "llvm/Support/Debug.h"
  127. #include "llvm/Support/ErrorHandling.h"
  128. #include "llvm/Support/MathExtras.h"
  129. #include "llvm/Support/raw_ostream.h"
  130. #include "llvm/Transforms/Utils/BasicBlockUtils.h"
  131. #include "llvm/Transforms/Utils/LoopSimplify.h"
  132. #include "llvm/Transforms/Utils/LoopUtils.h"
  133. #include "llvm/Transforms/Utils/LoopVersioning.h"
  134. #include "llvm/Transforms/Vectorize/LoopVectorizationLegality.h"
  135. #include <algorithm>
  136. #include <cassert>
  137. #include <cstdint>
  138. #include <cstdlib>
  139. #include <functional>
  140. #include <iterator>
  141. #include <limits>
  142. #include <memory>
  143. #include <string>
  144. #include <tuple>
  145. #include <utility>
  146. #include <vector>
  147. using namespace llvm;
  148. #define LV_NAME "loop-vectorize"
  149. #define DEBUG_TYPE LV_NAME
  150. STATISTIC(LoopsVectorized, "Number of loops vectorized");
  151. STATISTIC(LoopsAnalyzed, "Number of loops analyzed for vectorization");
  152. /// Loops with a known constant trip count below this number are vectorized only
  153. /// if no scalar iteration overheads are incurred.
  154. static cl::opt<unsigned> TinyTripCountVectorThreshold(
  155. "vectorizer-min-trip-count", cl::init(16), cl::Hidden,
  156. cl::desc("Loops with a constant trip count that is smaller than this "
  157. "value are vectorized only if no scalar iteration overheads "
  158. "are incurred."));
  159. static cl::opt<bool> MaximizeBandwidth(
  160. "vectorizer-maximize-bandwidth", cl::init(false), cl::Hidden,
  161. cl::desc("Maximize bandwidth when selecting vectorization factor which "
  162. "will be determined by the smallest type in loop."));
  163. static cl::opt<bool> EnableInterleavedMemAccesses(
  164. "enable-interleaved-mem-accesses", cl::init(false), cl::Hidden,
  165. cl::desc("Enable vectorization on interleaved memory accesses in a loop"));
  166. /// Maximum factor for an interleaved memory access.
  167. static cl::opt<unsigned> MaxInterleaveGroupFactor(
  168. "max-interleave-group-factor", cl::Hidden,
  169. cl::desc("Maximum factor for an interleaved access group (default = 8)"),
  170. cl::init(8));
  171. /// We don't interleave loops with a known constant trip count below this
  172. /// number.
  173. static const unsigned TinyTripCountInterleaveThreshold = 128;
  174. static cl::opt<unsigned> ForceTargetNumScalarRegs(
  175. "force-target-num-scalar-regs", cl::init(0), cl::Hidden,
  176. cl::desc("A flag that overrides the target's number of scalar registers."));
  177. static cl::opt<unsigned> ForceTargetNumVectorRegs(
  178. "force-target-num-vector-regs", cl::init(0), cl::Hidden,
  179. cl::desc("A flag that overrides the target's number of vector registers."));
  180. static cl::opt<unsigned> ForceTargetMaxScalarInterleaveFactor(
  181. "force-target-max-scalar-interleave", cl::init(0), cl::Hidden,
  182. cl::desc("A flag that overrides the target's max interleave factor for "
  183. "scalar loops."));
  184. static cl::opt<unsigned> ForceTargetMaxVectorInterleaveFactor(
  185. "force-target-max-vector-interleave", cl::init(0), cl::Hidden,
  186. cl::desc("A flag that overrides the target's max interleave factor for "
  187. "vectorized loops."));
  188. static cl::opt<unsigned> ForceTargetInstructionCost(
  189. "force-target-instruction-cost", cl::init(0), cl::Hidden,
  190. cl::desc("A flag that overrides the target's expected cost for "
  191. "an instruction to a single constant value. Mostly "
  192. "useful for getting consistent testing."));
  193. static cl::opt<unsigned> SmallLoopCost(
  194. "small-loop-cost", cl::init(20), cl::Hidden,
  195. cl::desc(
  196. "The cost of a loop that is considered 'small' by the interleaver."));
  197. static cl::opt<bool> LoopVectorizeWithBlockFrequency(
  198. "loop-vectorize-with-block-frequency", cl::init(true), cl::Hidden,
  199. cl::desc("Enable the use of the block frequency analysis to access PGO "
  200. "heuristics minimizing code growth in cold regions and being more "
  201. "aggressive in hot regions."));
  202. // Runtime interleave loops for load/store throughput.
  203. static cl::opt<bool> EnableLoadStoreRuntimeInterleave(
  204. "enable-loadstore-runtime-interleave", cl::init(true), cl::Hidden,
  205. cl::desc(
  206. "Enable runtime interleaving until load/store ports are saturated"));
  207. /// The number of stores in a loop that are allowed to need predication.
  208. static cl::opt<unsigned> NumberOfStoresToPredicate(
  209. "vectorize-num-stores-pred", cl::init(1), cl::Hidden,
  210. cl::desc("Max number of stores to be predicated behind an if."));
  211. static cl::opt<bool> EnableIndVarRegisterHeur(
  212. "enable-ind-var-reg-heur", cl::init(true), cl::Hidden,
  213. cl::desc("Count the induction variable only once when interleaving"));
  214. static cl::opt<bool> EnableCondStoresVectorization(
  215. "enable-cond-stores-vec", cl::init(true), cl::Hidden,
  216. cl::desc("Enable if predication of stores during vectorization."));
  217. static cl::opt<unsigned> MaxNestedScalarReductionIC(
  218. "max-nested-scalar-reduction-interleave", cl::init(2), cl::Hidden,
  219. cl::desc("The maximum interleave count to use when interleaving a scalar "
  220. "reduction in a nested loop."));
  221. static cl::opt<bool> EnableVPlanNativePath(
  222. "enable-vplan-native-path", cl::init(false), cl::Hidden,
  223. cl::desc("Enable VPlan-native vectorization path with "
  224. "support for outer loop vectorization."));
  225. // This flag enables the stress testing of the VPlan H-CFG construction in the
  226. // VPlan-native vectorization path. It must be used in conjuction with
  227. // -enable-vplan-native-path. -vplan-verify-hcfg can also be used to enable the
  228. // verification of the H-CFGs built.
  229. static cl::opt<bool> VPlanBuildStressTest(
  230. "vplan-build-stress-test", cl::init(false), cl::Hidden,
  231. cl::desc(
  232. "Build VPlan for every supported loop nest in the function and bail "
  233. "out right after the build (stress test the VPlan H-CFG construction "
  234. "in the VPlan-native vectorization path)."));
  235. /// A helper function for converting Scalar types to vector types.
  236. /// If the incoming type is void, we return void. If the VF is 1, we return
  237. /// the scalar type.
  238. static Type *ToVectorTy(Type *Scalar, unsigned VF) {
  239. if (Scalar->isVoidTy() || VF == 1)
  240. return Scalar;
  241. return VectorType::get(Scalar, VF);
  242. }
  243. // FIXME: The following helper functions have multiple implementations
  244. // in the project. They can be effectively organized in a common Load/Store
  245. // utilities unit.
  246. /// A helper function that returns the type of loaded or stored value.
  247. static Type *getMemInstValueType(Value *I) {
  248. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  249. "Expected Load or Store instruction");
  250. if (auto *LI = dyn_cast<LoadInst>(I))
  251. return LI->getType();
  252. return cast<StoreInst>(I)->getValueOperand()->getType();
  253. }
  254. /// A helper function that returns the alignment of load or store instruction.
  255. static unsigned getMemInstAlignment(Value *I) {
  256. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  257. "Expected Load or Store instruction");
  258. if (auto *LI = dyn_cast<LoadInst>(I))
  259. return LI->getAlignment();
  260. return cast<StoreInst>(I)->getAlignment();
  261. }
  262. /// A helper function that returns the address space of the pointer operand of
  263. /// load or store instruction.
  264. static unsigned getMemInstAddressSpace(Value *I) {
  265. assert((isa<LoadInst>(I) || isa<StoreInst>(I)) &&
  266. "Expected Load or Store instruction");
  267. if (auto *LI = dyn_cast<LoadInst>(I))
  268. return LI->getPointerAddressSpace();
  269. return cast<StoreInst>(I)->getPointerAddressSpace();
  270. }
  271. /// A helper function that returns true if the given type is irregular. The
  272. /// type is irregular if its allocated size doesn't equal the store size of an
  273. /// element of the corresponding vector type at the given vectorization factor.
  274. static bool hasIrregularType(Type *Ty, const DataLayout &DL, unsigned VF) {
  275. // Determine if an array of VF elements of type Ty is "bitcast compatible"
  276. // with a <VF x Ty> vector.
  277. if (VF > 1) {
  278. auto *VectorTy = VectorType::get(Ty, VF);
  279. return VF * DL.getTypeAllocSize(Ty) != DL.getTypeStoreSize(VectorTy);
  280. }
  281. // If the vectorization factor is one, we just check if an array of type Ty
  282. // requires padding between elements.
  283. return DL.getTypeAllocSizeInBits(Ty) != DL.getTypeSizeInBits(Ty);
  284. }
  285. /// A helper function that returns the reciprocal of the block probability of
  286. /// predicated blocks. If we return X, we are assuming the predicated block
  287. /// will execute once for every X iterations of the loop header.
  288. ///
  289. /// TODO: We should use actual block probability here, if available. Currently,
  290. /// we always assume predicated blocks have a 50% chance of executing.
  291. static unsigned getReciprocalPredBlockProb() { return 2; }
  292. /// A helper function that adds a 'fast' flag to floating-point operations.
  293. static Value *addFastMathFlag(Value *V) {
  294. if (isa<FPMathOperator>(V)) {
  295. FastMathFlags Flags;
  296. Flags.setFast();
  297. cast<Instruction>(V)->setFastMathFlags(Flags);
  298. }
  299. return V;
  300. }
  301. /// A helper function that returns an integer or floating-point constant with
  302. /// value C.
  303. static Constant *getSignedIntOrFpConstant(Type *Ty, int64_t C) {
  304. return Ty->isIntegerTy() ? ConstantInt::getSigned(Ty, C)
  305. : ConstantFP::get(Ty, C);
  306. }
  307. namespace llvm {
  308. /// InnerLoopVectorizer vectorizes loops which contain only one basic
  309. /// block to a specified vectorization factor (VF).
  310. /// This class performs the widening of scalars into vectors, or multiple
  311. /// scalars. This class also implements the following features:
  312. /// * It inserts an epilogue loop for handling loops that don't have iteration
  313. /// counts that are known to be a multiple of the vectorization factor.
  314. /// * It handles the code generation for reduction variables.
  315. /// * Scalarization (implementation using scalars) of un-vectorizable
  316. /// instructions.
  317. /// InnerLoopVectorizer does not perform any vectorization-legality
  318. /// checks, and relies on the caller to check for the different legality
  319. /// aspects. The InnerLoopVectorizer relies on the
  320. /// LoopVectorizationLegality class to provide information about the induction
  321. /// and reduction variables that were found to a given vectorization factor.
  322. class InnerLoopVectorizer {
  323. public:
  324. InnerLoopVectorizer(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  325. LoopInfo *LI, DominatorTree *DT,
  326. const TargetLibraryInfo *TLI,
  327. const TargetTransformInfo *TTI, AssumptionCache *AC,
  328. OptimizationRemarkEmitter *ORE, unsigned VecWidth,
  329. unsigned UnrollFactor, LoopVectorizationLegality *LVL,
  330. LoopVectorizationCostModel *CM)
  331. : OrigLoop(OrigLoop), PSE(PSE), LI(LI), DT(DT), TLI(TLI), TTI(TTI),
  332. AC(AC), ORE(ORE), VF(VecWidth), UF(UnrollFactor),
  333. Builder(PSE.getSE()->getContext()),
  334. VectorLoopValueMap(UnrollFactor, VecWidth), Legal(LVL), Cost(CM) {}
  335. virtual ~InnerLoopVectorizer() = default;
  336. /// Create a new empty loop. Unlink the old loop and connect the new one.
  337. /// Return the pre-header block of the new loop.
  338. BasicBlock *createVectorizedLoopSkeleton();
  339. /// Widen a single instruction within the innermost loop.
  340. void widenInstruction(Instruction &I);
  341. /// Fix the vectorized code, taking care of header phi's, live-outs, and more.
  342. void fixVectorizedLoop();
  343. // Return true if any runtime check is added.
  344. bool areSafetyChecksAdded() { return AddedSafetyChecks; }
  345. /// A type for vectorized values in the new loop. Each value from the
  346. /// original loop, when vectorized, is represented by UF vector values in the
  347. /// new unrolled loop, where UF is the unroll factor.
  348. using VectorParts = SmallVector<Value *, 2>;
  349. /// Vectorize a single PHINode in a block. This method handles the induction
  350. /// variable canonicalization. It supports both VF = 1 for unrolled loops and
  351. /// arbitrary length vectors.
  352. void widenPHIInstruction(Instruction *PN, unsigned UF, unsigned VF);
  353. /// A helper function to scalarize a single Instruction in the innermost loop.
  354. /// Generates a sequence of scalar instances for each lane between \p MinLane
  355. /// and \p MaxLane, times each part between \p MinPart and \p MaxPart,
  356. /// inclusive..
  357. void scalarizeInstruction(Instruction *Instr, const VPIteration &Instance,
  358. bool IfPredicateInstr);
  359. /// Widen an integer or floating-point induction variable \p IV. If \p Trunc
  360. /// is provided, the integer induction variable will first be truncated to
  361. /// the corresponding type.
  362. void widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc = nullptr);
  363. /// getOrCreateVectorValue and getOrCreateScalarValue coordinate to generate a
  364. /// vector or scalar value on-demand if one is not yet available. When
  365. /// vectorizing a loop, we visit the definition of an instruction before its
  366. /// uses. When visiting the definition, we either vectorize or scalarize the
  367. /// instruction, creating an entry for it in the corresponding map. (In some
  368. /// cases, such as induction variables, we will create both vector and scalar
  369. /// entries.) Then, as we encounter uses of the definition, we derive values
  370. /// for each scalar or vector use unless such a value is already available.
  371. /// For example, if we scalarize a definition and one of its uses is vector,
  372. /// we build the required vector on-demand with an insertelement sequence
  373. /// when visiting the use. Otherwise, if the use is scalar, we can use the
  374. /// existing scalar definition.
  375. ///
  376. /// Return a value in the new loop corresponding to \p V from the original
  377. /// loop at unroll index \p Part. If the value has already been vectorized,
  378. /// the corresponding vector entry in VectorLoopValueMap is returned. If,
  379. /// however, the value has a scalar entry in VectorLoopValueMap, we construct
  380. /// a new vector value on-demand by inserting the scalar values into a vector
  381. /// with an insertelement sequence. If the value has been neither vectorized
  382. /// nor scalarized, it must be loop invariant, so we simply broadcast the
  383. /// value into a vector.
  384. Value *getOrCreateVectorValue(Value *V, unsigned Part);
  385. /// Return a value in the new loop corresponding to \p V from the original
  386. /// loop at unroll and vector indices \p Instance. If the value has been
  387. /// vectorized but not scalarized, the necessary extractelement instruction
  388. /// will be generated.
  389. Value *getOrCreateScalarValue(Value *V, const VPIteration &Instance);
  390. /// Construct the vector value of a scalarized value \p V one lane at a time.
  391. void packScalarIntoVectorValue(Value *V, const VPIteration &Instance);
  392. /// Try to vectorize the interleaved access group that \p Instr belongs to.
  393. void vectorizeInterleaveGroup(Instruction *Instr);
  394. /// Vectorize Load and Store instructions, optionally masking the vector
  395. /// operations if \p BlockInMask is non-null.
  396. void vectorizeMemoryInstruction(Instruction *Instr,
  397. VectorParts *BlockInMask = nullptr);
  398. /// Set the debug location in the builder using the debug location in
  399. /// the instruction.
  400. void setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr);
  401. protected:
  402. friend class LoopVectorizationPlanner;
  403. /// A small list of PHINodes.
  404. using PhiVector = SmallVector<PHINode *, 4>;
  405. /// A type for scalarized values in the new loop. Each value from the
  406. /// original loop, when scalarized, is represented by UF x VF scalar values
  407. /// in the new unrolled loop, where UF is the unroll factor and VF is the
  408. /// vectorization factor.
  409. using ScalarParts = SmallVector<SmallVector<Value *, 4>, 2>;
  410. /// Set up the values of the IVs correctly when exiting the vector loop.
  411. void fixupIVUsers(PHINode *OrigPhi, const InductionDescriptor &II,
  412. Value *CountRoundDown, Value *EndValue,
  413. BasicBlock *MiddleBlock);
  414. /// Create a new induction variable inside L.
  415. PHINode *createInductionVariable(Loop *L, Value *Start, Value *End,
  416. Value *Step, Instruction *DL);
  417. /// Handle all cross-iteration phis in the header.
  418. void fixCrossIterationPHIs();
  419. /// Fix a first-order recurrence. This is the second phase of vectorizing
  420. /// this phi node.
  421. void fixFirstOrderRecurrence(PHINode *Phi);
  422. /// Fix a reduction cross-iteration phi. This is the second phase of
  423. /// vectorizing this phi node.
  424. void fixReduction(PHINode *Phi);
  425. /// The Loop exit block may have single value PHI nodes with some
  426. /// incoming value. While vectorizing we only handled real values
  427. /// that were defined inside the loop and we should have one value for
  428. /// each predecessor of its parent basic block. See PR14725.
  429. void fixLCSSAPHIs();
  430. /// Iteratively sink the scalarized operands of a predicated instruction into
  431. /// the block that was created for it.
  432. void sinkScalarOperands(Instruction *PredInst);
  433. /// Shrinks vector element sizes to the smallest bitwidth they can be legally
  434. /// represented as.
  435. void truncateToMinimalBitwidths();
  436. /// Insert the new loop to the loop hierarchy and pass manager
  437. /// and update the analysis passes.
  438. void updateAnalysis();
  439. /// Create a broadcast instruction. This method generates a broadcast
  440. /// instruction (shuffle) for loop invariant values and for the induction
  441. /// value. If this is the induction variable then we extend it to N, N+1, ...
  442. /// this is needed because each iteration in the loop corresponds to a SIMD
  443. /// element.
  444. virtual Value *getBroadcastInstrs(Value *V);
  445. /// This function adds (StartIdx, StartIdx + Step, StartIdx + 2*Step, ...)
  446. /// to each vector element of Val. The sequence starts at StartIndex.
  447. /// \p Opcode is relevant for FP induction variable.
  448. virtual Value *getStepVector(Value *Val, int StartIdx, Value *Step,
  449. Instruction::BinaryOps Opcode =
  450. Instruction::BinaryOpsEnd);
  451. /// Compute scalar induction steps. \p ScalarIV is the scalar induction
  452. /// variable on which to base the steps, \p Step is the size of the step, and
  453. /// \p EntryVal is the value from the original loop that maps to the steps.
  454. /// Note that \p EntryVal doesn't have to be an induction variable - it
  455. /// can also be a truncate instruction.
  456. void buildScalarSteps(Value *ScalarIV, Value *Step, Instruction *EntryVal,
  457. const InductionDescriptor &ID);
  458. /// Create a vector induction phi node based on an existing scalar one. \p
  459. /// EntryVal is the value from the original loop that maps to the vector phi
  460. /// node, and \p Step is the loop-invariant step. If \p EntryVal is a
  461. /// truncate instruction, instead of widening the original IV, we widen a
  462. /// version of the IV truncated to \p EntryVal's type.
  463. void createVectorIntOrFpInductionPHI(const InductionDescriptor &II,
  464. Value *Step, Instruction *EntryVal);
  465. /// Returns true if an instruction \p I should be scalarized instead of
  466. /// vectorized for the chosen vectorization factor.
  467. bool shouldScalarizeInstruction(Instruction *I) const;
  468. /// Returns true if we should generate a scalar version of \p IV.
  469. bool needsScalarInduction(Instruction *IV) const;
  470. /// If there is a cast involved in the induction variable \p ID, which should
  471. /// be ignored in the vectorized loop body, this function records the
  472. /// VectorLoopValue of the respective Phi also as the VectorLoopValue of the
  473. /// cast. We had already proved that the casted Phi is equal to the uncasted
  474. /// Phi in the vectorized loop (under a runtime guard), and therefore
  475. /// there is no need to vectorize the cast - the same value can be used in the
  476. /// vector loop for both the Phi and the cast.
  477. /// If \p VectorLoopValue is a scalarized value, \p Lane is also specified,
  478. /// Otherwise, \p VectorLoopValue is a widened/vectorized value.
  479. ///
  480. /// \p EntryVal is the value from the original loop that maps to the vector
  481. /// phi node and is used to distinguish what is the IV currently being
  482. /// processed - original one (if \p EntryVal is a phi corresponding to the
  483. /// original IV) or the "newly-created" one based on the proof mentioned above
  484. /// (see also buildScalarSteps() and createVectorIntOrFPInductionPHI()). In the
  485. /// latter case \p EntryVal is a TruncInst and we must not record anything for
  486. /// that IV, but it's error-prone to expect callers of this routine to care
  487. /// about that, hence this explicit parameter.
  488. void recordVectorLoopValueForInductionCast(const InductionDescriptor &ID,
  489. const Instruction *EntryVal,
  490. Value *VectorLoopValue,
  491. unsigned Part,
  492. unsigned Lane = UINT_MAX);
  493. /// Generate a shuffle sequence that will reverse the vector Vec.
  494. virtual Value *reverseVector(Value *Vec);
  495. /// Returns (and creates if needed) the original loop trip count.
  496. Value *getOrCreateTripCount(Loop *NewLoop);
  497. /// Returns (and creates if needed) the trip count of the widened loop.
  498. Value *getOrCreateVectorTripCount(Loop *NewLoop);
  499. /// Returns a bitcasted value to the requested vector type.
  500. /// Also handles bitcasts of vector<float> <-> vector<pointer> types.
  501. Value *createBitOrPointerCast(Value *V, VectorType *DstVTy,
  502. const DataLayout &DL);
  503. /// Emit a bypass check to see if the vector trip count is zero, including if
  504. /// it overflows.
  505. void emitMinimumIterationCountCheck(Loop *L, BasicBlock *Bypass);
  506. /// Emit a bypass check to see if all of the SCEV assumptions we've
  507. /// had to make are correct.
  508. void emitSCEVChecks(Loop *L, BasicBlock *Bypass);
  509. /// Emit bypass checks to check any memory assumptions we may have made.
  510. void emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass);
  511. /// Add additional metadata to \p To that was not present on \p Orig.
  512. ///
  513. /// Currently this is used to add the noalias annotations based on the
  514. /// inserted memchecks. Use this for instructions that are *cloned* into the
  515. /// vector loop.
  516. void addNewMetadata(Instruction *To, const Instruction *Orig);
  517. /// Add metadata from one instruction to another.
  518. ///
  519. /// This includes both the original MDs from \p From and additional ones (\see
  520. /// addNewMetadata). Use this for *newly created* instructions in the vector
  521. /// loop.
  522. void addMetadata(Instruction *To, Instruction *From);
  523. /// Similar to the previous function but it adds the metadata to a
  524. /// vector of instructions.
  525. void addMetadata(ArrayRef<Value *> To, Instruction *From);
  526. /// The original loop.
  527. Loop *OrigLoop;
  528. /// A wrapper around ScalarEvolution used to add runtime SCEV checks. Applies
  529. /// dynamic knowledge to simplify SCEV expressions and converts them to a
  530. /// more usable form.
  531. PredicatedScalarEvolution &PSE;
  532. /// Loop Info.
  533. LoopInfo *LI;
  534. /// Dominator Tree.
  535. DominatorTree *DT;
  536. /// Alias Analysis.
  537. AliasAnalysis *AA;
  538. /// Target Library Info.
  539. const TargetLibraryInfo *TLI;
  540. /// Target Transform Info.
  541. const TargetTransformInfo *TTI;
  542. /// Assumption Cache.
  543. AssumptionCache *AC;
  544. /// Interface to emit optimization remarks.
  545. OptimizationRemarkEmitter *ORE;
  546. /// LoopVersioning. It's only set up (non-null) if memchecks were
  547. /// used.
  548. ///
  549. /// This is currently only used to add no-alias metadata based on the
  550. /// memchecks. The actually versioning is performed manually.
  551. std::unique_ptr<LoopVersioning> LVer;
  552. /// The vectorization SIMD factor to use. Each vector will have this many
  553. /// vector elements.
  554. unsigned VF;
  555. /// The vectorization unroll factor to use. Each scalar is vectorized to this
  556. /// many different vector instructions.
  557. unsigned UF;
  558. /// The builder that we use
  559. IRBuilder<> Builder;
  560. // --- Vectorization state ---
  561. /// The vector-loop preheader.
  562. BasicBlock *LoopVectorPreHeader;
  563. /// The scalar-loop preheader.
  564. BasicBlock *LoopScalarPreHeader;
  565. /// Middle Block between the vector and the scalar.
  566. BasicBlock *LoopMiddleBlock;
  567. /// The ExitBlock of the scalar loop.
  568. BasicBlock *LoopExitBlock;
  569. /// The vector loop body.
  570. BasicBlock *LoopVectorBody;
  571. /// The scalar loop body.
  572. BasicBlock *LoopScalarBody;
  573. /// A list of all bypass blocks. The first block is the entry of the loop.
  574. SmallVector<BasicBlock *, 4> LoopBypassBlocks;
  575. /// The new Induction variable which was added to the new block.
  576. PHINode *Induction = nullptr;
  577. /// The induction variable of the old basic block.
  578. PHINode *OldInduction = nullptr;
  579. /// Maps values from the original loop to their corresponding values in the
  580. /// vectorized loop. A key value can map to either vector values, scalar
  581. /// values or both kinds of values, depending on whether the key was
  582. /// vectorized and scalarized.
  583. VectorizerValueMap VectorLoopValueMap;
  584. /// Store instructions that were predicated.
  585. SmallVector<Instruction *, 4> PredicatedInstructions;
  586. /// Trip count of the original loop.
  587. Value *TripCount = nullptr;
  588. /// Trip count of the widened loop (TripCount - TripCount % (VF*UF))
  589. Value *VectorTripCount = nullptr;
  590. /// The legality analysis.
  591. LoopVectorizationLegality *Legal;
  592. /// The profitablity analysis.
  593. LoopVectorizationCostModel *Cost;
  594. // Record whether runtime checks are added.
  595. bool AddedSafetyChecks = false;
  596. // Holds the end values for each induction variable. We save the end values
  597. // so we can later fix-up the external users of the induction variables.
  598. DenseMap<PHINode *, Value *> IVEndValues;
  599. };
  600. class InnerLoopUnroller : public InnerLoopVectorizer {
  601. public:
  602. InnerLoopUnroller(Loop *OrigLoop, PredicatedScalarEvolution &PSE,
  603. LoopInfo *LI, DominatorTree *DT,
  604. const TargetLibraryInfo *TLI,
  605. const TargetTransformInfo *TTI, AssumptionCache *AC,
  606. OptimizationRemarkEmitter *ORE, unsigned UnrollFactor,
  607. LoopVectorizationLegality *LVL,
  608. LoopVectorizationCostModel *CM)
  609. : InnerLoopVectorizer(OrigLoop, PSE, LI, DT, TLI, TTI, AC, ORE, 1,
  610. UnrollFactor, LVL, CM) {}
  611. private:
  612. Value *getBroadcastInstrs(Value *V) override;
  613. Value *getStepVector(Value *Val, int StartIdx, Value *Step,
  614. Instruction::BinaryOps Opcode =
  615. Instruction::BinaryOpsEnd) override;
  616. Value *reverseVector(Value *Vec) override;
  617. };
  618. } // end namespace llvm
  619. /// Look for a meaningful debug location on the instruction or it's
  620. /// operands.
  621. static Instruction *getDebugLocFromInstOrOperands(Instruction *I) {
  622. if (!I)
  623. return I;
  624. DebugLoc Empty;
  625. if (I->getDebugLoc() != Empty)
  626. return I;
  627. for (User::op_iterator OI = I->op_begin(), OE = I->op_end(); OI != OE; ++OI) {
  628. if (Instruction *OpInst = dyn_cast<Instruction>(*OI))
  629. if (OpInst->getDebugLoc() != Empty)
  630. return OpInst;
  631. }
  632. return I;
  633. }
  634. void InnerLoopVectorizer::setDebugLocFromInst(IRBuilder<> &B, const Value *Ptr) {
  635. if (const Instruction *Inst = dyn_cast_or_null<Instruction>(Ptr)) {
  636. const DILocation *DIL = Inst->getDebugLoc();
  637. if (DIL && Inst->getFunction()->isDebugInfoForProfiling() &&
  638. !isa<DbgInfoIntrinsic>(Inst))
  639. B.SetCurrentDebugLocation(DIL->cloneWithDuplicationFactor(UF * VF));
  640. else
  641. B.SetCurrentDebugLocation(DIL);
  642. } else
  643. B.SetCurrentDebugLocation(DebugLoc());
  644. }
  645. #ifndef NDEBUG
  646. /// \return string containing a file name and a line # for the given loop.
  647. static std::string getDebugLocString(const Loop *L) {
  648. std::string Result;
  649. if (L) {
  650. raw_string_ostream OS(Result);
  651. if (const DebugLoc LoopDbgLoc = L->getStartLoc())
  652. LoopDbgLoc.print(OS);
  653. else
  654. // Just print the module name.
  655. OS << L->getHeader()->getParent()->getParent()->getModuleIdentifier();
  656. OS.flush();
  657. }
  658. return Result;
  659. }
  660. #endif
  661. void InnerLoopVectorizer::addNewMetadata(Instruction *To,
  662. const Instruction *Orig) {
  663. // If the loop was versioned with memchecks, add the corresponding no-alias
  664. // metadata.
  665. if (LVer && (isa<LoadInst>(Orig) || isa<StoreInst>(Orig)))
  666. LVer->annotateInstWithNoAlias(To, Orig);
  667. }
  668. void InnerLoopVectorizer::addMetadata(Instruction *To,
  669. Instruction *From) {
  670. propagateMetadata(To, From);
  671. addNewMetadata(To, From);
  672. }
  673. void InnerLoopVectorizer::addMetadata(ArrayRef<Value *> To,
  674. Instruction *From) {
  675. for (Value *V : To) {
  676. if (Instruction *I = dyn_cast<Instruction>(V))
  677. addMetadata(I, From);
  678. }
  679. }
  680. namespace llvm {
  681. /// The group of interleaved loads/stores sharing the same stride and
  682. /// close to each other.
  683. ///
  684. /// Each member in this group has an index starting from 0, and the largest
  685. /// index should be less than interleaved factor, which is equal to the absolute
  686. /// value of the access's stride.
  687. ///
  688. /// E.g. An interleaved load group of factor 4:
  689. /// for (unsigned i = 0; i < 1024; i+=4) {
  690. /// a = A[i]; // Member of index 0
  691. /// b = A[i+1]; // Member of index 1
  692. /// d = A[i+3]; // Member of index 3
  693. /// ...
  694. /// }
  695. ///
  696. /// An interleaved store group of factor 4:
  697. /// for (unsigned i = 0; i < 1024; i+=4) {
  698. /// ...
  699. /// A[i] = a; // Member of index 0
  700. /// A[i+1] = b; // Member of index 1
  701. /// A[i+2] = c; // Member of index 2
  702. /// A[i+3] = d; // Member of index 3
  703. /// }
  704. ///
  705. /// Note: the interleaved load group could have gaps (missing members), but
  706. /// the interleaved store group doesn't allow gaps.
  707. class InterleaveGroup {
  708. public:
  709. InterleaveGroup(Instruction *Instr, int Stride, unsigned Align)
  710. : Align(Align), InsertPos(Instr) {
  711. assert(Align && "The alignment should be non-zero");
  712. Factor = std::abs(Stride);
  713. assert(Factor > 1 && "Invalid interleave factor");
  714. Reverse = Stride < 0;
  715. Members[0] = Instr;
  716. }
  717. bool isReverse() const { return Reverse; }
  718. unsigned getFactor() const { return Factor; }
  719. unsigned getAlignment() const { return Align; }
  720. unsigned getNumMembers() const { return Members.size(); }
  721. /// Try to insert a new member \p Instr with index \p Index and
  722. /// alignment \p NewAlign. The index is related to the leader and it could be
  723. /// negative if it is the new leader.
  724. ///
  725. /// \returns false if the instruction doesn't belong to the group.
  726. bool insertMember(Instruction *Instr, int Index, unsigned NewAlign) {
  727. assert(NewAlign && "The new member's alignment should be non-zero");
  728. int Key = Index + SmallestKey;
  729. // Skip if there is already a member with the same index.
  730. if (Members.find(Key) != Members.end())
  731. return false;
  732. if (Key > LargestKey) {
  733. // The largest index is always less than the interleave factor.
  734. if (Index >= static_cast<int>(Factor))
  735. return false;
  736. LargestKey = Key;
  737. } else if (Key < SmallestKey) {
  738. // The largest index is always less than the interleave factor.
  739. if (LargestKey - Key >= static_cast<int>(Factor))
  740. return false;
  741. SmallestKey = Key;
  742. }
  743. // It's always safe to select the minimum alignment.
  744. Align = std::min(Align, NewAlign);
  745. Members[Key] = Instr;
  746. return true;
  747. }
  748. /// Get the member with the given index \p Index
  749. ///
  750. /// \returns nullptr if contains no such member.
  751. Instruction *getMember(unsigned Index) const {
  752. int Key = SmallestKey + Index;
  753. auto Member = Members.find(Key);
  754. if (Member == Members.end())
  755. return nullptr;
  756. return Member->second;
  757. }
  758. /// Get the index for the given member. Unlike the key in the member
  759. /// map, the index starts from 0.
  760. unsigned getIndex(Instruction *Instr) const {
  761. for (auto I : Members)
  762. if (I.second == Instr)
  763. return I.first - SmallestKey;
  764. llvm_unreachable("InterleaveGroup contains no such member");
  765. }
  766. Instruction *getInsertPos() const { return InsertPos; }
  767. void setInsertPos(Instruction *Inst) { InsertPos = Inst; }
  768. /// Add metadata (e.g. alias info) from the instructions in this group to \p
  769. /// NewInst.
  770. ///
  771. /// FIXME: this function currently does not add noalias metadata a'la
  772. /// addNewMedata. To do that we need to compute the intersection of the
  773. /// noalias info from all members.
  774. void addMetadata(Instruction *NewInst) const {
  775. SmallVector<Value *, 4> VL;
  776. std::transform(Members.begin(), Members.end(), std::back_inserter(VL),
  777. [](std::pair<int, Instruction *> p) { return p.second; });
  778. propagateMetadata(NewInst, VL);
  779. }
  780. private:
  781. unsigned Factor; // Interleave Factor.
  782. bool Reverse;
  783. unsigned Align;
  784. DenseMap<int, Instruction *> Members;
  785. int SmallestKey = 0;
  786. int LargestKey = 0;
  787. // To avoid breaking dependences, vectorized instructions of an interleave
  788. // group should be inserted at either the first load or the last store in
  789. // program order.
  790. //
  791. // E.g. %even = load i32 // Insert Position
  792. // %add = add i32 %even // Use of %even
  793. // %odd = load i32
  794. //
  795. // store i32 %even
  796. // %odd = add i32 // Def of %odd
  797. // store i32 %odd // Insert Position
  798. Instruction *InsertPos;
  799. };
  800. } // end namespace llvm
  801. namespace {
  802. /// Drive the analysis of interleaved memory accesses in the loop.
  803. ///
  804. /// Use this class to analyze interleaved accesses only when we can vectorize
  805. /// a loop. Otherwise it's meaningless to do analysis as the vectorization
  806. /// on interleaved accesses is unsafe.
  807. ///
  808. /// The analysis collects interleave groups and records the relationships
  809. /// between the member and the group in a map.
  810. class InterleavedAccessInfo {
  811. public:
  812. InterleavedAccessInfo(PredicatedScalarEvolution &PSE, Loop *L,
  813. DominatorTree *DT, LoopInfo *LI,
  814. const LoopAccessInfo *LAI)
  815. : PSE(PSE), TheLoop(L), DT(DT), LI(LI), LAI(LAI) {}
  816. ~InterleavedAccessInfo() {
  817. SmallPtrSet<InterleaveGroup *, 4> DelSet;
  818. // Avoid releasing a pointer twice.
  819. for (auto &I : InterleaveGroupMap)
  820. DelSet.insert(I.second);
  821. for (auto *Ptr : DelSet)
  822. delete Ptr;
  823. }
  824. /// Analyze the interleaved accesses and collect them in interleave
  825. /// groups. Substitute symbolic strides using \p Strides.
  826. void analyzeInterleaving();
  827. /// Check if \p Instr belongs to any interleave group.
  828. bool isInterleaved(Instruction *Instr) const {
  829. return InterleaveGroupMap.find(Instr) != InterleaveGroupMap.end();
  830. }
  831. /// Get the interleave group that \p Instr belongs to.
  832. ///
  833. /// \returns nullptr if doesn't have such group.
  834. InterleaveGroup *getInterleaveGroup(Instruction *Instr) const {
  835. auto Group = InterleaveGroupMap.find(Instr);
  836. if (Group == InterleaveGroupMap.end())
  837. return nullptr;
  838. return Group->second;
  839. }
  840. /// Returns true if an interleaved group that may access memory
  841. /// out-of-bounds requires a scalar epilogue iteration for correctness.
  842. bool requiresScalarEpilogue() const { return RequiresScalarEpilogue; }
  843. private:
  844. /// A wrapper around ScalarEvolution, used to add runtime SCEV checks.
  845. /// Simplifies SCEV expressions in the context of existing SCEV assumptions.
  846. /// The interleaved access analysis can also add new predicates (for example
  847. /// by versioning strides of pointers).
  848. PredicatedScalarEvolution &PSE;
  849. Loop *TheLoop;
  850. DominatorTree *DT;
  851. LoopInfo *LI;
  852. const LoopAccessInfo *LAI;
  853. /// True if the loop may contain non-reversed interleaved groups with
  854. /// out-of-bounds accesses. We ensure we don't speculatively access memory
  855. /// out-of-bounds by executing at least one scalar epilogue iteration.
  856. bool RequiresScalarEpilogue = false;
  857. /// Holds the relationships between the members and the interleave group.
  858. DenseMap<Instruction *, InterleaveGroup *> InterleaveGroupMap;
  859. /// Holds dependences among the memory accesses in the loop. It maps a source
  860. /// access to a set of dependent sink accesses.
  861. DenseMap<Instruction *, SmallPtrSet<Instruction *, 2>> Dependences;
  862. /// The descriptor for a strided memory access.
  863. struct StrideDescriptor {
  864. StrideDescriptor() = default;
  865. StrideDescriptor(int64_t Stride, const SCEV *Scev, uint64_t Size,
  866. unsigned Align)
  867. : Stride(Stride), Scev(Scev), Size(Size), Align(Align) {}
  868. // The access's stride. It is negative for a reverse access.
  869. int64_t Stride = 0;
  870. // The scalar expression of this access.
  871. const SCEV *Scev = nullptr;
  872. // The size of the memory object.
  873. uint64_t Size = 0;
  874. // The alignment of this access.
  875. unsigned Align = 0;
  876. };
  877. /// A type for holding instructions and their stride descriptors.
  878. using StrideEntry = std::pair<Instruction *, StrideDescriptor>;
  879. /// Create a new interleave group with the given instruction \p Instr,
  880. /// stride \p Stride and alignment \p Align.
  881. ///
  882. /// \returns the newly created interleave group.
  883. InterleaveGroup *createInterleaveGroup(Instruction *Instr, int Stride,
  884. unsigned Align) {
  885. assert(!isInterleaved(Instr) && "Already in an interleaved access group");
  886. InterleaveGroupMap[Instr] = new InterleaveGroup(Instr, Stride, Align);
  887. return InterleaveGroupMap[Instr];
  888. }
  889. /// Release the group and remove all the relationships.
  890. void releaseGroup(InterleaveGroup *Group) {
  891. for (unsigned i = 0; i < Group->getFactor(); i++)
  892. if (Instruction *Member = Group->getMember(i))
  893. InterleaveGroupMap.erase(Member);
  894. delete Group;
  895. }
  896. /// Collect all the accesses with a constant stride in program order.
  897. void collectConstStrideAccesses(
  898. MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
  899. const ValueToValueMap &Strides);
  900. /// Returns true if \p Stride is allowed in an interleaved group.
  901. static bool isStrided(int Stride) {
  902. unsigned Factor = std::abs(Stride);
  903. return Factor >= 2 && Factor <= MaxInterleaveGroupFactor;
  904. }
  905. /// Returns true if \p BB is a predicated block.
  906. bool isPredicated(BasicBlock *BB) const {
  907. return LoopAccessInfo::blockNeedsPredication(BB, TheLoop, DT);
  908. }
  909. /// Returns true if LoopAccessInfo can be used for dependence queries.
  910. bool areDependencesValid() const {
  911. return LAI && LAI->getDepChecker().getDependences();
  912. }
  913. /// Returns true if memory accesses \p A and \p B can be reordered, if
  914. /// necessary, when constructing interleaved groups.
  915. ///
  916. /// \p A must precede \p B in program order. We return false if reordering is
  917. /// not necessary or is prevented because \p A and \p B may be dependent.
  918. bool canReorderMemAccessesForInterleavedGroups(StrideEntry *A,
  919. StrideEntry *B) const {
  920. // Code motion for interleaved accesses can potentially hoist strided loads
  921. // and sink strided stores. The code below checks the legality of the
  922. // following two conditions:
  923. //
  924. // 1. Potentially moving a strided load (B) before any store (A) that
  925. // precedes B, or
  926. //
  927. // 2. Potentially moving a strided store (A) after any load or store (B)
  928. // that A precedes.
  929. //
  930. // It's legal to reorder A and B if we know there isn't a dependence from A
  931. // to B. Note that this determination is conservative since some
  932. // dependences could potentially be reordered safely.
  933. // A is potentially the source of a dependence.
  934. auto *Src = A->first;
  935. auto SrcDes = A->second;
  936. // B is potentially the sink of a dependence.
  937. auto *Sink = B->first;
  938. auto SinkDes = B->second;
  939. // Code motion for interleaved accesses can't violate WAR dependences.
  940. // Thus, reordering is legal if the source isn't a write.
  941. if (!Src->mayWriteToMemory())
  942. return true;
  943. // At least one of the accesses must be strided.
  944. if (!isStrided(SrcDes.Stride) && !isStrided(SinkDes.Stride))
  945. return true;
  946. // If dependence information is not available from LoopAccessInfo,
  947. // conservatively assume the instructions can't be reordered.
  948. if (!areDependencesValid())
  949. return false;
  950. // If we know there is a dependence from source to sink, assume the
  951. // instructions can't be reordered. Otherwise, reordering is legal.
  952. return Dependences.find(Src) == Dependences.end() ||
  953. !Dependences.lookup(Src).count(Sink);
  954. }
  955. /// Collect the dependences from LoopAccessInfo.
  956. ///
  957. /// We process the dependences once during the interleaved access analysis to
  958. /// enable constant-time dependence queries.
  959. void collectDependences() {
  960. if (!areDependencesValid())
  961. return;
  962. auto *Deps = LAI->getDepChecker().getDependences();
  963. for (auto Dep : *Deps)
  964. Dependences[Dep.getSource(*LAI)].insert(Dep.getDestination(*LAI));
  965. }
  966. };
  967. } // end anonymous namespace
  968. static void emitMissedWarning(Function *F, Loop *L,
  969. const LoopVectorizeHints &LH,
  970. OptimizationRemarkEmitter *ORE) {
  971. LH.emitRemarkWithHints();
  972. if (LH.getForce() == LoopVectorizeHints::FK_Enabled) {
  973. if (LH.getWidth() != 1)
  974. ORE->emit(DiagnosticInfoOptimizationFailure(
  975. DEBUG_TYPE, "FailedRequestedVectorization",
  976. L->getStartLoc(), L->getHeader())
  977. << "loop not vectorized: "
  978. << "failed explicitly specified loop vectorization");
  979. else if (LH.getInterleave() != 1)
  980. ORE->emit(DiagnosticInfoOptimizationFailure(
  981. DEBUG_TYPE, "FailedRequestedInterleaving", L->getStartLoc(),
  982. L->getHeader())
  983. << "loop not interleaved: "
  984. << "failed explicitly specified loop interleaving");
  985. }
  986. }
  987. namespace llvm {
  988. /// LoopVectorizationCostModel - estimates the expected speedups due to
  989. /// vectorization.
  990. /// In many cases vectorization is not profitable. This can happen because of
  991. /// a number of reasons. In this class we mainly attempt to predict the
  992. /// expected speedup/slowdowns due to the supported instruction set. We use the
  993. /// TargetTransformInfo to query the different backends for the cost of
  994. /// different operations.
  995. class LoopVectorizationCostModel {
  996. public:
  997. LoopVectorizationCostModel(Loop *L, PredicatedScalarEvolution &PSE,
  998. LoopInfo *LI, LoopVectorizationLegality *Legal,
  999. const TargetTransformInfo &TTI,
  1000. const TargetLibraryInfo *TLI, DemandedBits *DB,
  1001. AssumptionCache *AC,
  1002. OptimizationRemarkEmitter *ORE, const Function *F,
  1003. const LoopVectorizeHints *Hints,
  1004. InterleavedAccessInfo &IAI)
  1005. : TheLoop(L), PSE(PSE), LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), DB(DB),
  1006. AC(AC), ORE(ORE), TheFunction(F), Hints(Hints), InterleaveInfo(IAI) {}
  1007. /// \return An upper bound for the vectorization factor, or None if
  1008. /// vectorization should be avoided up front.
  1009. Optional<unsigned> computeMaxVF(bool OptForSize);
  1010. /// \return The most profitable vectorization factor and the cost of that VF.
  1011. /// This method checks every power of two up to MaxVF. If UserVF is not ZERO
  1012. /// then this vectorization factor will be selected if vectorization is
  1013. /// possible.
  1014. VectorizationFactor selectVectorizationFactor(unsigned MaxVF);
  1015. /// Setup cost-based decisions for user vectorization factor.
  1016. void selectUserVectorizationFactor(unsigned UserVF) {
  1017. collectUniformsAndScalars(UserVF);
  1018. collectInstsToScalarize(UserVF);
  1019. }
  1020. /// \return The size (in bits) of the smallest and widest types in the code
  1021. /// that needs to be vectorized. We ignore values that remain scalar such as
  1022. /// 64 bit loop indices.
  1023. std::pair<unsigned, unsigned> getSmallestAndWidestTypes();
  1024. /// \return The desired interleave count.
  1025. /// If interleave count has been specified by metadata it will be returned.
  1026. /// Otherwise, the interleave count is computed and returned. VF and LoopCost
  1027. /// are the selected vectorization factor and the cost of the selected VF.
  1028. unsigned selectInterleaveCount(bool OptForSize, unsigned VF,
  1029. unsigned LoopCost);
  1030. /// Memory access instruction may be vectorized in more than one way.
  1031. /// Form of instruction after vectorization depends on cost.
  1032. /// This function takes cost-based decisions for Load/Store instructions
  1033. /// and collects them in a map. This decisions map is used for building
  1034. /// the lists of loop-uniform and loop-scalar instructions.
  1035. /// The calculated cost is saved with widening decision in order to
  1036. /// avoid redundant calculations.
  1037. void setCostBasedWideningDecision(unsigned VF);
  1038. /// A struct that represents some properties of the register usage
  1039. /// of a loop.
  1040. struct RegisterUsage {
  1041. /// Holds the number of loop invariant values that are used in the loop.
  1042. unsigned LoopInvariantRegs;
  1043. /// Holds the maximum number of concurrent live intervals in the loop.
  1044. unsigned MaxLocalUsers;
  1045. };
  1046. /// \return Returns information about the register usages of the loop for the
  1047. /// given vectorization factors.
  1048. SmallVector<RegisterUsage, 8> calculateRegisterUsage(ArrayRef<unsigned> VFs);
  1049. /// Collect values we want to ignore in the cost model.
  1050. void collectValuesToIgnore();
  1051. /// \returns The smallest bitwidth each instruction can be represented with.
  1052. /// The vector equivalents of these instructions should be truncated to this
  1053. /// type.
  1054. const MapVector<Instruction *, uint64_t> &getMinimalBitwidths() const {
  1055. return MinBWs;
  1056. }
  1057. /// \returns True if it is more profitable to scalarize instruction \p I for
  1058. /// vectorization factor \p VF.
  1059. bool isProfitableToScalarize(Instruction *I, unsigned VF) const {
  1060. assert(VF > 1 && "Profitable to scalarize relevant only for VF > 1.");
  1061. auto Scalars = InstsToScalarize.find(VF);
  1062. assert(Scalars != InstsToScalarize.end() &&
  1063. "VF not yet analyzed for scalarization profitability");
  1064. return Scalars->second.find(I) != Scalars->second.end();
  1065. }
  1066. /// Returns true if \p I is known to be uniform after vectorization.
  1067. bool isUniformAfterVectorization(Instruction *I, unsigned VF) const {
  1068. if (VF == 1)
  1069. return true;
  1070. auto UniformsPerVF = Uniforms.find(VF);
  1071. assert(UniformsPerVF != Uniforms.end() &&
  1072. "VF not yet analyzed for uniformity");
  1073. return UniformsPerVF->second.find(I) != UniformsPerVF->second.end();
  1074. }
  1075. /// Returns true if \p I is known to be scalar after vectorization.
  1076. bool isScalarAfterVectorization(Instruction *I, unsigned VF) const {
  1077. if (VF == 1)
  1078. return true;
  1079. auto ScalarsPerVF = Scalars.find(VF);
  1080. assert(ScalarsPerVF != Scalars.end() &&
  1081. "Scalar values are not calculated for VF");
  1082. return ScalarsPerVF->second.find(I) != ScalarsPerVF->second.end();
  1083. }
  1084. /// \returns True if instruction \p I can be truncated to a smaller bitwidth
  1085. /// for vectorization factor \p VF.
  1086. bool canTruncateToMinimalBitwidth(Instruction *I, unsigned VF) const {
  1087. return VF > 1 && MinBWs.find(I) != MinBWs.end() &&
  1088. !isProfitableToScalarize(I, VF) &&
  1089. !isScalarAfterVectorization(I, VF);
  1090. }
  1091. /// Decision that was taken during cost calculation for memory instruction.
  1092. enum InstWidening {
  1093. CM_Unknown,
  1094. CM_Widen, // For consecutive accesses with stride +1.
  1095. CM_Widen_Reverse, // For consecutive accesses with stride -1.
  1096. CM_Interleave,
  1097. CM_GatherScatter,
  1098. CM_Scalarize
  1099. };
  1100. /// Save vectorization decision \p W and \p Cost taken by the cost model for
  1101. /// instruction \p I and vector width \p VF.
  1102. void setWideningDecision(Instruction *I, unsigned VF, InstWidening W,
  1103. unsigned Cost) {
  1104. assert(VF >= 2 && "Expected VF >=2");
  1105. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
  1106. }
  1107. /// Save vectorization decision \p W and \p Cost taken by the cost model for
  1108. /// interleaving group \p Grp and vector width \p VF.
  1109. void setWideningDecision(const InterleaveGroup *Grp, unsigned VF,
  1110. InstWidening W, unsigned Cost) {
  1111. assert(VF >= 2 && "Expected VF >=2");
  1112. /// Broadcast this decicion to all instructions inside the group.
  1113. /// But the cost will be assigned to one instruction only.
  1114. for (unsigned i = 0; i < Grp->getFactor(); ++i) {
  1115. if (auto *I = Grp->getMember(i)) {
  1116. if (Grp->getInsertPos() == I)
  1117. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, Cost);
  1118. else
  1119. WideningDecisions[std::make_pair(I, VF)] = std::make_pair(W, 0);
  1120. }
  1121. }
  1122. }
  1123. /// Return the cost model decision for the given instruction \p I and vector
  1124. /// width \p VF. Return CM_Unknown if this instruction did not pass
  1125. /// through the cost modeling.
  1126. InstWidening getWideningDecision(Instruction *I, unsigned VF) {
  1127. assert(VF >= 2 && "Expected VF >=2");
  1128. std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
  1129. auto Itr = WideningDecisions.find(InstOnVF);
  1130. if (Itr == WideningDecisions.end())
  1131. return CM_Unknown;
  1132. return Itr->second.first;
  1133. }
  1134. /// Return the vectorization cost for the given instruction \p I and vector
  1135. /// width \p VF.
  1136. unsigned getWideningCost(Instruction *I, unsigned VF) {
  1137. assert(VF >= 2 && "Expected VF >=2");
  1138. std::pair<Instruction *, unsigned> InstOnVF = std::make_pair(I, VF);
  1139. assert(WideningDecisions.find(InstOnVF) != WideningDecisions.end() &&
  1140. "The cost is not calculated");
  1141. return WideningDecisions[InstOnVF].second;
  1142. }
  1143. /// Return True if instruction \p I is an optimizable truncate whose operand
  1144. /// is an induction variable. Such a truncate will be removed by adding a new
  1145. /// induction variable with the destination type.
  1146. bool isOptimizableIVTruncate(Instruction *I, unsigned VF) {
  1147. // If the instruction is not a truncate, return false.
  1148. auto *Trunc = dyn_cast<TruncInst>(I);
  1149. if (!Trunc)
  1150. return false;
  1151. // Get the source and destination types of the truncate.
  1152. Type *SrcTy = ToVectorTy(cast<CastInst>(I)->getSrcTy(), VF);
  1153. Type *DestTy = ToVectorTy(cast<CastInst>(I)->getDestTy(), VF);
  1154. // If the truncate is free for the given types, return false. Replacing a
  1155. // free truncate with an induction variable would add an induction variable
  1156. // update instruction to each iteration of the loop. We exclude from this
  1157. // check the primary induction variable since it will need an update
  1158. // instruction regardless.
  1159. Value *Op = Trunc->getOperand(0);
  1160. if (Op != Legal->getPrimaryInduction() && TTI.isTruncateFree(SrcTy, DestTy))
  1161. return false;
  1162. // If the truncated value is not an induction variable, return false.
  1163. return Legal->isInductionPhi(Op);
  1164. }
  1165. /// Collects the instructions to scalarize for each predicated instruction in
  1166. /// the loop.
  1167. void collectInstsToScalarize(unsigned VF);
  1168. /// Collect Uniform and Scalar values for the given \p VF.
  1169. /// The sets depend on CM decision for Load/Store instructions
  1170. /// that may be vectorized as interleave, gather-scatter or scalarized.
  1171. void collectUniformsAndScalars(unsigned VF) {
  1172. // Do the analysis once.
  1173. if (VF == 1 || Uniforms.find(VF) != Uniforms.end())
  1174. return;
  1175. setCostBasedWideningDecision(VF);
  1176. collectLoopUniforms(VF);
  1177. collectLoopScalars(VF);
  1178. }
  1179. /// Returns true if the target machine supports masked store operation
  1180. /// for the given \p DataType and kind of access to \p Ptr.
  1181. bool isLegalMaskedStore(Type *DataType, Value *Ptr) {
  1182. return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedStore(DataType);
  1183. }
  1184. /// Returns true if the target machine supports masked load operation
  1185. /// for the given \p DataType and kind of access to \p Ptr.
  1186. bool isLegalMaskedLoad(Type *DataType, Value *Ptr) {
  1187. return Legal->isConsecutivePtr(Ptr) && TTI.isLegalMaskedLoad(DataType);
  1188. }
  1189. /// Returns true if the target machine supports masked scatter operation
  1190. /// for the given \p DataType.
  1191. bool isLegalMaskedScatter(Type *DataType) {
  1192. return TTI.isLegalMaskedScatter(DataType);
  1193. }
  1194. /// Returns true if the target machine supports masked gather operation
  1195. /// for the given \p DataType.
  1196. bool isLegalMaskedGather(Type *DataType) {
  1197. return TTI.isLegalMaskedGather(DataType);
  1198. }
  1199. /// Returns true if the target machine can represent \p V as a masked gather
  1200. /// or scatter operation.
  1201. bool isLegalGatherOrScatter(Value *V) {
  1202. bool LI = isa<LoadInst>(V);
  1203. bool SI = isa<StoreInst>(V);
  1204. if (!LI && !SI)
  1205. return false;
  1206. auto *Ty = getMemInstValueType(V);
  1207. return (LI && isLegalMaskedGather(Ty)) || (SI && isLegalMaskedScatter(Ty));
  1208. }
  1209. /// Returns true if \p I is an instruction that will be scalarized with
  1210. /// predication. Such instructions include conditional stores and
  1211. /// instructions that may divide by zero.
  1212. bool isScalarWithPredication(Instruction *I);
  1213. /// Returns true if \p I is a memory instruction with consecutive memory
  1214. /// access that can be widened.
  1215. bool memoryInstructionCanBeWidened(Instruction *I, unsigned VF = 1);
  1216. /// Check if \p Instr belongs to any interleaved access group.
  1217. bool isAccessInterleaved(Instruction *Instr) {
  1218. return InterleaveInfo.isInterleaved(Instr);
  1219. }
  1220. /// Get the interleaved access group that \p Instr belongs to.
  1221. const InterleaveGroup *getInterleavedAccessGroup(Instruction *Instr) {
  1222. return InterleaveInfo.getInterleaveGroup(Instr);
  1223. }
  1224. /// Returns true if an interleaved group requires a scalar iteration
  1225. /// to handle accesses with gaps.
  1226. bool requiresScalarEpilogue() const {
  1227. return InterleaveInfo.requiresScalarEpilogue();
  1228. }
  1229. private:
  1230. unsigned NumPredStores = 0;
  1231. /// \return An upper bound for the vectorization factor, larger than zero.
  1232. /// One is returned if vectorization should best be avoided due to cost.
  1233. unsigned computeFeasibleMaxVF(bool OptForSize, unsigned ConstTripCount);
  1234. /// The vectorization cost is a combination of the cost itself and a boolean
  1235. /// indicating whether any of the contributing operations will actually
  1236. /// operate on
  1237. /// vector values after type legalization in the backend. If this latter value
  1238. /// is
  1239. /// false, then all operations will be scalarized (i.e. no vectorization has
  1240. /// actually taken place).
  1241. using VectorizationCostTy = std::pair<unsigned, bool>;
  1242. /// Returns the expected execution cost. The unit of the cost does
  1243. /// not matter because we use the 'cost' units to compare different
  1244. /// vector widths. The cost that is returned is *not* normalized by
  1245. /// the factor width.
  1246. VectorizationCostTy expectedCost(unsigned VF);
  1247. /// Returns the execution time cost of an instruction for a given vector
  1248. /// width. Vector width of one means scalar.
  1249. VectorizationCostTy getInstructionCost(Instruction *I, unsigned VF);
  1250. /// The cost-computation logic from getInstructionCost which provides
  1251. /// the vector type as an output parameter.
  1252. unsigned getInstructionCost(Instruction *I, unsigned VF, Type *&VectorTy);
  1253. /// Calculate vectorization cost of memory instruction \p I.
  1254. unsigned getMemoryInstructionCost(Instruction *I, unsigned VF);
  1255. /// The cost computation for scalarized memory instruction.
  1256. unsigned getMemInstScalarizationCost(Instruction *I, unsigned VF);
  1257. /// The cost computation for interleaving group of memory instructions.
  1258. unsigned getInterleaveGroupCost(Instruction *I, unsigned VF);
  1259. /// The cost computation for Gather/Scatter instruction.
  1260. unsigned getGatherScatterCost(Instruction *I, unsigned VF);
  1261. /// The cost computation for widening instruction \p I with consecutive
  1262. /// memory access.
  1263. unsigned getConsecutiveMemOpCost(Instruction *I, unsigned VF);
  1264. /// The cost calculation for Load instruction \p I with uniform pointer -
  1265. /// scalar load + broadcast.
  1266. unsigned getUniformMemOpCost(Instruction *I, unsigned VF);
  1267. /// Returns whether the instruction is a load or store and will be a emitted
  1268. /// as a vector operation.
  1269. bool isConsecutiveLoadOrStore(Instruction *I);
  1270. /// Returns true if an artificially high cost for emulated masked memrefs
  1271. /// should be used.
  1272. bool useEmulatedMaskMemRefHack(Instruction *I);
  1273. /// Create an analysis remark that explains why vectorization failed
  1274. ///
  1275. /// \p RemarkName is the identifier for the remark. \return the remark object
  1276. /// that can be streamed to.
  1277. OptimizationRemarkAnalysis createMissedAnalysis(StringRef RemarkName) {
  1278. return createLVMissedAnalysis(Hints->vectorizeAnalysisPassName(),
  1279. RemarkName, TheLoop);
  1280. }
  1281. /// Map of scalar integer values to the smallest bitwidth they can be legally
  1282. /// represented as. The vector equivalents of these values should be truncated
  1283. /// to this type.
  1284. MapVector<Instruction *, uint64_t> MinBWs;
  1285. /// A type representing the costs for instructions if they were to be
  1286. /// scalarized rather than vectorized. The entries are Instruction-Cost
  1287. /// pairs.
  1288. using ScalarCostsTy = DenseMap<Instruction *, unsigned>;
  1289. /// A set containing all BasicBlocks that are known to present after
  1290. /// vectorization as a predicated block.
  1291. SmallPtrSet<BasicBlock *, 4> PredicatedBBsAfterVectorization;
  1292. /// A map holding scalar costs for different vectorization factors. The
  1293. /// presence of a cost for an instruction in the mapping indicates that the
  1294. /// instruction will be scalarized when vectorizing with the associated
  1295. /// vectorization factor. The entries are VF-ScalarCostTy pairs.
  1296. DenseMap<unsigned, ScalarCostsTy> InstsToScalarize;
  1297. /// Holds the instructions known to be uniform after vectorization.
  1298. /// The data is collected per VF.
  1299. DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Uniforms;
  1300. /// Holds the instructions known to be scalar after vectorization.
  1301. /// The data is collected per VF.
  1302. DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> Scalars;
  1303. /// Holds the instructions (address computations) that are forced to be
  1304. /// scalarized.
  1305. DenseMap<unsigned, SmallPtrSet<Instruction *, 4>> ForcedScalars;
  1306. /// Returns the expected difference in cost from scalarizing the expression
  1307. /// feeding a predicated instruction \p PredInst. The instructions to
  1308. /// scalarize and their scalar costs are collected in \p ScalarCosts. A
  1309. /// non-negative return value implies the expression will be scalarized.
  1310. /// Currently, only single-use chains are considered for scalarization.
  1311. int computePredInstDiscount(Instruction *PredInst, ScalarCostsTy &ScalarCosts,
  1312. unsigned VF);
  1313. /// Collect the instructions that are uniform after vectorization. An
  1314. /// instruction is uniform if we represent it with a single scalar value in
  1315. /// the vectorized loop corresponding to each vector iteration. Examples of
  1316. /// uniform instructions include pointer operands of consecutive or
  1317. /// interleaved memory accesses. Note that although uniformity implies an
  1318. /// instruction will be scalar, the reverse is not true. In general, a
  1319. /// scalarized instruction will be represented by VF scalar values in the
  1320. /// vectorized loop, each corresponding to an iteration of the original
  1321. /// scalar loop.
  1322. void collectLoopUniforms(unsigned VF);
  1323. /// Collect the instructions that are scalar after vectorization. An
  1324. /// instruction is scalar if it is known to be uniform or will be scalarized
  1325. /// during vectorization. Non-uniform scalarized instructions will be
  1326. /// represented by VF values in the vectorized loop, each corresponding to an
  1327. /// iteration of the original scalar loop.
  1328. void collectLoopScalars(unsigned VF);
  1329. /// Keeps cost model vectorization decision and cost for instructions.
  1330. /// Right now it is used for memory instructions only.
  1331. using DecisionList = DenseMap<std::pair<Instruction *, unsigned>,
  1332. std::pair<InstWidening, unsigned>>;
  1333. DecisionList WideningDecisions;
  1334. public:
  1335. /// The loop that we evaluate.
  1336. Loop *TheLoop;
  1337. /// Predicated scalar evolution analysis.
  1338. PredicatedScalarEvolution &PSE;
  1339. /// Loop Info analysis.
  1340. LoopInfo *LI;
  1341. /// Vectorization legality.
  1342. LoopVectorizationLegality *Legal;
  1343. /// Vector target information.
  1344. const TargetTransformInfo &TTI;
  1345. /// Target Library Info.
  1346. const TargetLibraryInfo *TLI;
  1347. /// Demanded bits analysis.
  1348. DemandedBits *DB;
  1349. /// Assumption cache.
  1350. AssumptionCache *AC;
  1351. /// Interface to emit optimization remarks.
  1352. OptimizationRemarkEmitter *ORE;
  1353. const Function *TheFunction;
  1354. /// Loop Vectorize Hint.
  1355. const LoopVectorizeHints *Hints;
  1356. /// The interleave access information contains groups of interleaved accesses
  1357. /// with the same stride and close to each other.
  1358. InterleavedAccessInfo &InterleaveInfo;
  1359. /// Values to ignore in the cost model.
  1360. SmallPtrSet<const Value *, 16> ValuesToIgnore;
  1361. /// Values to ignore in the cost model when VF > 1.
  1362. SmallPtrSet<const Value *, 16> VecValuesToIgnore;
  1363. };
  1364. } // end namespace llvm
  1365. // Return true if \p OuterLp is an outer loop annotated with hints for explicit
  1366. // vectorization. The loop needs to be annotated with #pragma omp simd
  1367. // simdlen(#) or #pragma clang vectorize(enable) vectorize_width(#). If the
  1368. // vector length information is not provided, vectorization is not considered
  1369. // explicit. Interleave hints are not allowed either. These limitations will be
  1370. // relaxed in the future.
  1371. // Please, note that we are currently forced to abuse the pragma 'clang
  1372. // vectorize' semantics. This pragma provides *auto-vectorization hints*
  1373. // (i.e., LV must check that vectorization is legal) whereas pragma 'omp simd'
  1374. // provides *explicit vectorization hints* (LV can bypass legal checks and
  1375. // assume that vectorization is legal). However, both hints are implemented
  1376. // using the same metadata (llvm.loop.vectorize, processed by
  1377. // LoopVectorizeHints). This will be fixed in the future when the native IR
  1378. // representation for pragma 'omp simd' is introduced.
  1379. static bool isExplicitVecOuterLoop(Loop *OuterLp,
  1380. OptimizationRemarkEmitter *ORE) {
  1381. assert(!OuterLp->empty() && "This is not an outer loop");
  1382. LoopVectorizeHints Hints(OuterLp, true /*DisableInterleaving*/, *ORE);
  1383. // Only outer loops with an explicit vectorization hint are supported.
  1384. // Unannotated outer loops are ignored.
  1385. if (Hints.getForce() == LoopVectorizeHints::FK_Undefined)
  1386. return false;
  1387. Function *Fn = OuterLp->getHeader()->getParent();
  1388. if (!Hints.allowVectorization(Fn, OuterLp, false /*AlwaysVectorize*/)) {
  1389. LLVM_DEBUG(dbgs() << "LV: Loop hints prevent outer loop vectorization.\n");
  1390. return false;
  1391. }
  1392. if (!Hints.getWidth()) {
  1393. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: No user vector width.\n");
  1394. emitMissedWarning(Fn, OuterLp, Hints, ORE);
  1395. return false;
  1396. }
  1397. if (Hints.getInterleave() > 1) {
  1398. // TODO: Interleave support is future work.
  1399. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Interleave is not supported for "
  1400. "outer loops.\n");
  1401. emitMissedWarning(Fn, OuterLp, Hints, ORE);
  1402. return false;
  1403. }
  1404. return true;
  1405. }
  1406. static void collectSupportedLoops(Loop &L, LoopInfo *LI,
  1407. OptimizationRemarkEmitter *ORE,
  1408. SmallVectorImpl<Loop *> &V) {
  1409. // Collect inner loops and outer loops without irreducible control flow. For
  1410. // now, only collect outer loops that have explicit vectorization hints. If we
  1411. // are stress testing the VPlan H-CFG construction, we collect the outermost
  1412. // loop of every loop nest.
  1413. if (L.empty() || VPlanBuildStressTest ||
  1414. (EnableVPlanNativePath && isExplicitVecOuterLoop(&L, ORE))) {
  1415. LoopBlocksRPO RPOT(&L);
  1416. RPOT.perform(LI);
  1417. if (!containsIrreducibleCFG<const BasicBlock *>(RPOT, *LI)) {
  1418. V.push_back(&L);
  1419. // TODO: Collect inner loops inside marked outer loops in case
  1420. // vectorization fails for the outer loop. Do not invoke
  1421. // 'containsIrreducibleCFG' again for inner loops when the outer loop is
  1422. // already known to be reducible. We can use an inherited attribute for
  1423. // that.
  1424. return;
  1425. }
  1426. }
  1427. for (Loop *InnerL : L)
  1428. collectSupportedLoops(*InnerL, LI, ORE, V);
  1429. }
  1430. namespace {
  1431. /// The LoopVectorize Pass.
  1432. struct LoopVectorize : public FunctionPass {
  1433. /// Pass identification, replacement for typeid
  1434. static char ID;
  1435. LoopVectorizePass Impl;
  1436. explicit LoopVectorize(bool NoUnrolling = false, bool AlwaysVectorize = true)
  1437. : FunctionPass(ID) {
  1438. Impl.DisableUnrolling = NoUnrolling;
  1439. Impl.AlwaysVectorize = AlwaysVectorize;
  1440. initializeLoopVectorizePass(*PassRegistry::getPassRegistry());
  1441. }
  1442. bool runOnFunction(Function &F) override {
  1443. if (skipFunction(F))
  1444. return false;
  1445. auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
  1446. auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
  1447. auto *TTI = &getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
  1448. auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
  1449. auto *BFI = &getAnalysis<BlockFrequencyInfoWrapperPass>().getBFI();
  1450. auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
  1451. auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
  1452. auto *AA = &getAnalysis<AAResultsWrapperPass>().getAAResults();
  1453. auto *AC = &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
  1454. auto *LAA = &getAnalysis<LoopAccessLegacyAnalysis>();
  1455. auto *DB = &getAnalysis<DemandedBitsWrapperPass>().getDemandedBits();
  1456. auto *ORE = &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE();
  1457. std::function<const LoopAccessInfo &(Loop &)> GetLAA =
  1458. [&](Loop &L) -> const LoopAccessInfo & { return LAA->getInfo(&L); };
  1459. return Impl.runImpl(F, *SE, *LI, *TTI, *DT, *BFI, TLI, *DB, *AA, *AC,
  1460. GetLAA, *ORE);
  1461. }
  1462. void getAnalysisUsage(AnalysisUsage &AU) const override {
  1463. AU.addRequired<AssumptionCacheTracker>();
  1464. AU.addRequired<BlockFrequencyInfoWrapperPass>();
  1465. AU.addRequired<DominatorTreeWrapperPass>();
  1466. AU.addRequired<LoopInfoWrapperPass>();
  1467. AU.addRequired<ScalarEvolutionWrapperPass>();
  1468. AU.addRequired<TargetTransformInfoWrapperPass>();
  1469. AU.addRequired<AAResultsWrapperPass>();
  1470. AU.addRequired<LoopAccessLegacyAnalysis>();
  1471. AU.addRequired<DemandedBitsWrapperPass>();
  1472. AU.addRequired<OptimizationRemarkEmitterWrapperPass>();
  1473. AU.addPreserved<LoopInfoWrapperPass>();
  1474. AU.addPreserved<DominatorTreeWrapperPass>();
  1475. AU.addPreserved<BasicAAWrapperPass>();
  1476. AU.addPreserved<GlobalsAAWrapperPass>();
  1477. }
  1478. };
  1479. } // end anonymous namespace
  1480. //===----------------------------------------------------------------------===//
  1481. // Implementation of LoopVectorizationLegality, InnerLoopVectorizer and
  1482. // LoopVectorizationCostModel and LoopVectorizationPlanner.
  1483. //===----------------------------------------------------------------------===//
  1484. Value *InnerLoopVectorizer::getBroadcastInstrs(Value *V) {
  1485. // We need to place the broadcast of invariant variables outside the loop,
  1486. // but only if it's proven safe to do so. Else, broadcast will be inside
  1487. // vector loop body.
  1488. Instruction *Instr = dyn_cast<Instruction>(V);
  1489. bool SafeToHoist = OrigLoop->isLoopInvariant(V) &&
  1490. (!Instr ||
  1491. DT->dominates(Instr->getParent(), LoopVectorPreHeader));
  1492. // Place the code for broadcasting invariant variables in the new preheader.
  1493. IRBuilder<>::InsertPointGuard Guard(Builder);
  1494. if (SafeToHoist)
  1495. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  1496. // Broadcast the scalar into all locations in the vector.
  1497. Value *Shuf = Builder.CreateVectorSplat(VF, V, "broadcast");
  1498. return Shuf;
  1499. }
  1500. void InnerLoopVectorizer::createVectorIntOrFpInductionPHI(
  1501. const InductionDescriptor &II, Value *Step, Instruction *EntryVal) {
  1502. assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
  1503. "Expected either an induction phi-node or a truncate of it!");
  1504. Value *Start = II.getStartValue();
  1505. // Construct the initial value of the vector IV in the vector loop preheader
  1506. auto CurrIP = Builder.saveIP();
  1507. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  1508. if (isa<TruncInst>(EntryVal)) {
  1509. assert(Start->getType()->isIntegerTy() &&
  1510. "Truncation requires an integer type");
  1511. auto *TruncType = cast<IntegerType>(EntryVal->getType());
  1512. Step = Builder.CreateTrunc(Step, TruncType);
  1513. Start = Builder.CreateCast(Instruction::Trunc, Start, TruncType);
  1514. }
  1515. Value *SplatStart = Builder.CreateVectorSplat(VF, Start);
  1516. Value *SteppedStart =
  1517. getStepVector(SplatStart, 0, Step, II.getInductionOpcode());
  1518. // We create vector phi nodes for both integer and floating-point induction
  1519. // variables. Here, we determine the kind of arithmetic we will perform.
  1520. Instruction::BinaryOps AddOp;
  1521. Instruction::BinaryOps MulOp;
  1522. if (Step->getType()->isIntegerTy()) {
  1523. AddOp = Instruction::Add;
  1524. MulOp = Instruction::Mul;
  1525. } else {
  1526. AddOp = II.getInductionOpcode();
  1527. MulOp = Instruction::FMul;
  1528. }
  1529. // Multiply the vectorization factor by the step using integer or
  1530. // floating-point arithmetic as appropriate.
  1531. Value *ConstVF = getSignedIntOrFpConstant(Step->getType(), VF);
  1532. Value *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, Step, ConstVF));
  1533. // Create a vector splat to use in the induction update.
  1534. //
  1535. // FIXME: If the step is non-constant, we create the vector splat with
  1536. // IRBuilder. IRBuilder can constant-fold the multiply, but it doesn't
  1537. // handle a constant vector splat.
  1538. Value *SplatVF = isa<Constant>(Mul)
  1539. ? ConstantVector::getSplat(VF, cast<Constant>(Mul))
  1540. : Builder.CreateVectorSplat(VF, Mul);
  1541. Builder.restoreIP(CurrIP);
  1542. // We may need to add the step a number of times, depending on the unroll
  1543. // factor. The last of those goes into the PHI.
  1544. PHINode *VecInd = PHINode::Create(SteppedStart->getType(), 2, "vec.ind",
  1545. &*LoopVectorBody->getFirstInsertionPt());
  1546. VecInd->setDebugLoc(EntryVal->getDebugLoc());
  1547. Instruction *LastInduction = VecInd;
  1548. for (unsigned Part = 0; Part < UF; ++Part) {
  1549. VectorLoopValueMap.setVectorValue(EntryVal, Part, LastInduction);
  1550. if (isa<TruncInst>(EntryVal))
  1551. addMetadata(LastInduction, EntryVal);
  1552. recordVectorLoopValueForInductionCast(II, EntryVal, LastInduction, Part);
  1553. LastInduction = cast<Instruction>(addFastMathFlag(
  1554. Builder.CreateBinOp(AddOp, LastInduction, SplatVF, "step.add")));
  1555. LastInduction->setDebugLoc(EntryVal->getDebugLoc());
  1556. }
  1557. // Move the last step to the end of the latch block. This ensures consistent
  1558. // placement of all induction updates.
  1559. auto *LoopVectorLatch = LI->getLoopFor(LoopVectorBody)->getLoopLatch();
  1560. auto *Br = cast<BranchInst>(LoopVectorLatch->getTerminator());
  1561. auto *ICmp = cast<Instruction>(Br->getCondition());
  1562. LastInduction->moveBefore(ICmp);
  1563. LastInduction->setName("vec.ind.next");
  1564. VecInd->addIncoming(SteppedStart, LoopVectorPreHeader);
  1565. VecInd->addIncoming(LastInduction, LoopVectorLatch);
  1566. }
  1567. bool InnerLoopVectorizer::shouldScalarizeInstruction(Instruction *I) const {
  1568. return Cost->isScalarAfterVectorization(I, VF) ||
  1569. Cost->isProfitableToScalarize(I, VF);
  1570. }
  1571. bool InnerLoopVectorizer::needsScalarInduction(Instruction *IV) const {
  1572. if (shouldScalarizeInstruction(IV))
  1573. return true;
  1574. auto isScalarInst = [&](User *U) -> bool {
  1575. auto *I = cast<Instruction>(U);
  1576. return (OrigLoop->contains(I) && shouldScalarizeInstruction(I));
  1577. };
  1578. return llvm::any_of(IV->users(), isScalarInst);
  1579. }
  1580. void InnerLoopVectorizer::recordVectorLoopValueForInductionCast(
  1581. const InductionDescriptor &ID, const Instruction *EntryVal,
  1582. Value *VectorLoopVal, unsigned Part, unsigned Lane) {
  1583. assert((isa<PHINode>(EntryVal) || isa<TruncInst>(EntryVal)) &&
  1584. "Expected either an induction phi-node or a truncate of it!");
  1585. // This induction variable is not the phi from the original loop but the
  1586. // newly-created IV based on the proof that casted Phi is equal to the
  1587. // uncasted Phi in the vectorized loop (under a runtime guard possibly). It
  1588. // re-uses the same InductionDescriptor that original IV uses but we don't
  1589. // have to do any recording in this case - that is done when original IV is
  1590. // processed.
  1591. if (isa<TruncInst>(EntryVal))
  1592. return;
  1593. const SmallVectorImpl<Instruction *> &Casts = ID.getCastInsts();
  1594. if (Casts.empty())
  1595. return;
  1596. // Only the first Cast instruction in the Casts vector is of interest.
  1597. // The rest of the Casts (if exist) have no uses outside the
  1598. // induction update chain itself.
  1599. Instruction *CastInst = *Casts.begin();
  1600. if (Lane < UINT_MAX)
  1601. VectorLoopValueMap.setScalarValue(CastInst, {Part, Lane}, VectorLoopVal);
  1602. else
  1603. VectorLoopValueMap.setVectorValue(CastInst, Part, VectorLoopVal);
  1604. }
  1605. void InnerLoopVectorizer::widenIntOrFpInduction(PHINode *IV, TruncInst *Trunc) {
  1606. assert((IV->getType()->isIntegerTy() || IV != OldInduction) &&
  1607. "Primary induction variable must have an integer type");
  1608. auto II = Legal->getInductionVars()->find(IV);
  1609. assert(II != Legal->getInductionVars()->end() && "IV is not an induction");
  1610. auto ID = II->second;
  1611. assert(IV->getType() == ID.getStartValue()->getType() && "Types must match");
  1612. // The scalar value to broadcast. This will be derived from the canonical
  1613. // induction variable.
  1614. Value *ScalarIV = nullptr;
  1615. // The value from the original loop to which we are mapping the new induction
  1616. // variable.
  1617. Instruction *EntryVal = Trunc ? cast<Instruction>(Trunc) : IV;
  1618. // True if we have vectorized the induction variable.
  1619. auto VectorizedIV = false;
  1620. // Determine if we want a scalar version of the induction variable. This is
  1621. // true if the induction variable itself is not widened, or if it has at
  1622. // least one user in the loop that is not widened.
  1623. auto NeedsScalarIV = VF > 1 && needsScalarInduction(EntryVal);
  1624. // Generate code for the induction step. Note that induction steps are
  1625. // required to be loop-invariant
  1626. assert(PSE.getSE()->isLoopInvariant(ID.getStep(), OrigLoop) &&
  1627. "Induction step should be loop invariant");
  1628. auto &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
  1629. Value *Step = nullptr;
  1630. if (PSE.getSE()->isSCEVable(IV->getType())) {
  1631. SCEVExpander Exp(*PSE.getSE(), DL, "induction");
  1632. Step = Exp.expandCodeFor(ID.getStep(), ID.getStep()->getType(),
  1633. LoopVectorPreHeader->getTerminator());
  1634. } else {
  1635. Step = cast<SCEVUnknown>(ID.getStep())->getValue();
  1636. }
  1637. // Try to create a new independent vector induction variable. If we can't
  1638. // create the phi node, we will splat the scalar induction variable in each
  1639. // loop iteration.
  1640. if (VF > 1 && !shouldScalarizeInstruction(EntryVal)) {
  1641. createVectorIntOrFpInductionPHI(ID, Step, EntryVal);
  1642. VectorizedIV = true;
  1643. }
  1644. // If we haven't yet vectorized the induction variable, or if we will create
  1645. // a scalar one, we need to define the scalar induction variable and step
  1646. // values. If we were given a truncation type, truncate the canonical
  1647. // induction variable and step. Otherwise, derive these values from the
  1648. // induction descriptor.
  1649. if (!VectorizedIV || NeedsScalarIV) {
  1650. ScalarIV = Induction;
  1651. if (IV != OldInduction) {
  1652. ScalarIV = IV->getType()->isIntegerTy()
  1653. ? Builder.CreateSExtOrTrunc(Induction, IV->getType())
  1654. : Builder.CreateCast(Instruction::SIToFP, Induction,
  1655. IV->getType());
  1656. ScalarIV = ID.transform(Builder, ScalarIV, PSE.getSE(), DL);
  1657. ScalarIV->setName("offset.idx");
  1658. }
  1659. if (Trunc) {
  1660. auto *TruncType = cast<IntegerType>(Trunc->getType());
  1661. assert(Step->getType()->isIntegerTy() &&
  1662. "Truncation requires an integer step");
  1663. ScalarIV = Builder.CreateTrunc(ScalarIV, TruncType);
  1664. Step = Builder.CreateTrunc(Step, TruncType);
  1665. }
  1666. }
  1667. // If we haven't yet vectorized the induction variable, splat the scalar
  1668. // induction variable, and build the necessary step vectors.
  1669. // TODO: Don't do it unless the vectorized IV is really required.
  1670. if (!VectorizedIV) {
  1671. Value *Broadcasted = getBroadcastInstrs(ScalarIV);
  1672. for (unsigned Part = 0; Part < UF; ++Part) {
  1673. Value *EntryPart =
  1674. getStepVector(Broadcasted, VF * Part, Step, ID.getInductionOpcode());
  1675. VectorLoopValueMap.setVectorValue(EntryVal, Part, EntryPart);
  1676. if (Trunc)
  1677. addMetadata(EntryPart, Trunc);
  1678. recordVectorLoopValueForInductionCast(ID, EntryVal, EntryPart, Part);
  1679. }
  1680. }
  1681. // If an induction variable is only used for counting loop iterations or
  1682. // calculating addresses, it doesn't need to be widened. Create scalar steps
  1683. // that can be used by instructions we will later scalarize. Note that the
  1684. // addition of the scalar steps will not increase the number of instructions
  1685. // in the loop in the common case prior to InstCombine. We will be trading
  1686. // one vector extract for each scalar step.
  1687. if (NeedsScalarIV)
  1688. buildScalarSteps(ScalarIV, Step, EntryVal, ID);
  1689. }
  1690. Value *InnerLoopVectorizer::getStepVector(Value *Val, int StartIdx, Value *Step,
  1691. Instruction::BinaryOps BinOp) {
  1692. // Create and check the types.
  1693. assert(Val->getType()->isVectorTy() && "Must be a vector");
  1694. int VLen = Val->getType()->getVectorNumElements();
  1695. Type *STy = Val->getType()->getScalarType();
  1696. assert((STy->isIntegerTy() || STy->isFloatingPointTy()) &&
  1697. "Induction Step must be an integer or FP");
  1698. assert(Step->getType() == STy && "Step has wrong type");
  1699. SmallVector<Constant *, 8> Indices;
  1700. if (STy->isIntegerTy()) {
  1701. // Create a vector of consecutive numbers from zero to VF.
  1702. for (int i = 0; i < VLen; ++i)
  1703. Indices.push_back(ConstantInt::get(STy, StartIdx + i));
  1704. // Add the consecutive indices to the vector value.
  1705. Constant *Cv = ConstantVector::get(Indices);
  1706. assert(Cv->getType() == Val->getType() && "Invalid consecutive vec");
  1707. Step = Builder.CreateVectorSplat(VLen, Step);
  1708. assert(Step->getType() == Val->getType() && "Invalid step vec");
  1709. // FIXME: The newly created binary instructions should contain nsw/nuw flags,
  1710. // which can be found from the original scalar operations.
  1711. Step = Builder.CreateMul(Cv, Step);
  1712. return Builder.CreateAdd(Val, Step, "induction");
  1713. }
  1714. // Floating point induction.
  1715. assert((BinOp == Instruction::FAdd || BinOp == Instruction::FSub) &&
  1716. "Binary Opcode should be specified for FP induction");
  1717. // Create a vector of consecutive numbers from zero to VF.
  1718. for (int i = 0; i < VLen; ++i)
  1719. Indices.push_back(ConstantFP::get(STy, (double)(StartIdx + i)));
  1720. // Add the consecutive indices to the vector value.
  1721. Constant *Cv = ConstantVector::get(Indices);
  1722. Step = Builder.CreateVectorSplat(VLen, Step);
  1723. // Floating point operations had to be 'fast' to enable the induction.
  1724. FastMathFlags Flags;
  1725. Flags.setFast();
  1726. Value *MulOp = Builder.CreateFMul(Cv, Step);
  1727. if (isa<Instruction>(MulOp))
  1728. // Have to check, MulOp may be a constant
  1729. cast<Instruction>(MulOp)->setFastMathFlags(Flags);
  1730. Value *BOp = Builder.CreateBinOp(BinOp, Val, MulOp, "induction");
  1731. if (isa<Instruction>(BOp))
  1732. cast<Instruction>(BOp)->setFastMathFlags(Flags);
  1733. return BOp;
  1734. }
  1735. void InnerLoopVectorizer::buildScalarSteps(Value *ScalarIV, Value *Step,
  1736. Instruction *EntryVal,
  1737. const InductionDescriptor &ID) {
  1738. // We shouldn't have to build scalar steps if we aren't vectorizing.
  1739. assert(VF > 1 && "VF should be greater than one");
  1740. // Get the value type and ensure it and the step have the same integer type.
  1741. Type *ScalarIVTy = ScalarIV->getType()->getScalarType();
  1742. assert(ScalarIVTy == Step->getType() &&
  1743. "Val and Step should have the same type");
  1744. // We build scalar steps for both integer and floating-point induction
  1745. // variables. Here, we determine the kind of arithmetic we will perform.
  1746. Instruction::BinaryOps AddOp;
  1747. Instruction::BinaryOps MulOp;
  1748. if (ScalarIVTy->isIntegerTy()) {
  1749. AddOp = Instruction::Add;
  1750. MulOp = Instruction::Mul;
  1751. } else {
  1752. AddOp = ID.getInductionOpcode();
  1753. MulOp = Instruction::FMul;
  1754. }
  1755. // Determine the number of scalars we need to generate for each unroll
  1756. // iteration. If EntryVal is uniform, we only need to generate the first
  1757. // lane. Otherwise, we generate all VF values.
  1758. unsigned Lanes =
  1759. Cost->isUniformAfterVectorization(cast<Instruction>(EntryVal), VF) ? 1
  1760. : VF;
  1761. // Compute the scalar steps and save the results in VectorLoopValueMap.
  1762. for (unsigned Part = 0; Part < UF; ++Part) {
  1763. for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
  1764. auto *StartIdx = getSignedIntOrFpConstant(ScalarIVTy, VF * Part + Lane);
  1765. auto *Mul = addFastMathFlag(Builder.CreateBinOp(MulOp, StartIdx, Step));
  1766. auto *Add = addFastMathFlag(Builder.CreateBinOp(AddOp, ScalarIV, Mul));
  1767. VectorLoopValueMap.setScalarValue(EntryVal, {Part, Lane}, Add);
  1768. recordVectorLoopValueForInductionCast(ID, EntryVal, Add, Part, Lane);
  1769. }
  1770. }
  1771. }
  1772. Value *InnerLoopVectorizer::getOrCreateVectorValue(Value *V, unsigned Part) {
  1773. assert(V != Induction && "The new induction variable should not be used.");
  1774. assert(!V->getType()->isVectorTy() && "Can't widen a vector");
  1775. assert(!V->getType()->isVoidTy() && "Type does not produce a value");
  1776. // If we have a stride that is replaced by one, do it here.
  1777. if (Legal->hasStride(V))
  1778. V = ConstantInt::get(V->getType(), 1);
  1779. // If we have a vector mapped to this value, return it.
  1780. if (VectorLoopValueMap.hasVectorValue(V, Part))
  1781. return VectorLoopValueMap.getVectorValue(V, Part);
  1782. // If the value has not been vectorized, check if it has been scalarized
  1783. // instead. If it has been scalarized, and we actually need the value in
  1784. // vector form, we will construct the vector values on demand.
  1785. if (VectorLoopValueMap.hasAnyScalarValue(V)) {
  1786. Value *ScalarValue = VectorLoopValueMap.getScalarValue(V, {Part, 0});
  1787. // If we've scalarized a value, that value should be an instruction.
  1788. auto *I = cast<Instruction>(V);
  1789. // If we aren't vectorizing, we can just copy the scalar map values over to
  1790. // the vector map.
  1791. if (VF == 1) {
  1792. VectorLoopValueMap.setVectorValue(V, Part, ScalarValue);
  1793. return ScalarValue;
  1794. }
  1795. // Get the last scalar instruction we generated for V and Part. If the value
  1796. // is known to be uniform after vectorization, this corresponds to lane zero
  1797. // of the Part unroll iteration. Otherwise, the last instruction is the one
  1798. // we created for the last vector lane of the Part unroll iteration.
  1799. unsigned LastLane = Cost->isUniformAfterVectorization(I, VF) ? 0 : VF - 1;
  1800. auto *LastInst = cast<Instruction>(
  1801. VectorLoopValueMap.getScalarValue(V, {Part, LastLane}));
  1802. // Set the insert point after the last scalarized instruction. This ensures
  1803. // the insertelement sequence will directly follow the scalar definitions.
  1804. auto OldIP = Builder.saveIP();
  1805. auto NewIP = std::next(BasicBlock::iterator(LastInst));
  1806. Builder.SetInsertPoint(&*NewIP);
  1807. // However, if we are vectorizing, we need to construct the vector values.
  1808. // If the value is known to be uniform after vectorization, we can just
  1809. // broadcast the scalar value corresponding to lane zero for each unroll
  1810. // iteration. Otherwise, we construct the vector values using insertelement
  1811. // instructions. Since the resulting vectors are stored in
  1812. // VectorLoopValueMap, we will only generate the insertelements once.
  1813. Value *VectorValue = nullptr;
  1814. if (Cost->isUniformAfterVectorization(I, VF)) {
  1815. VectorValue = getBroadcastInstrs(ScalarValue);
  1816. VectorLoopValueMap.setVectorValue(V, Part, VectorValue);
  1817. } else {
  1818. // Initialize packing with insertelements to start from undef.
  1819. Value *Undef = UndefValue::get(VectorType::get(V->getType(), VF));
  1820. VectorLoopValueMap.setVectorValue(V, Part, Undef);
  1821. for (unsigned Lane = 0; Lane < VF; ++Lane)
  1822. packScalarIntoVectorValue(V, {Part, Lane});
  1823. VectorValue = VectorLoopValueMap.getVectorValue(V, Part);
  1824. }
  1825. Builder.restoreIP(OldIP);
  1826. return VectorValue;
  1827. }
  1828. // If this scalar is unknown, assume that it is a constant or that it is
  1829. // loop invariant. Broadcast V and save the value for future uses.
  1830. Value *B = getBroadcastInstrs(V);
  1831. VectorLoopValueMap.setVectorValue(V, Part, B);
  1832. return B;
  1833. }
  1834. Value *
  1835. InnerLoopVectorizer::getOrCreateScalarValue(Value *V,
  1836. const VPIteration &Instance) {
  1837. // If the value is not an instruction contained in the loop, it should
  1838. // already be scalar.
  1839. if (OrigLoop->isLoopInvariant(V))
  1840. return V;
  1841. assert(Instance.Lane > 0
  1842. ? !Cost->isUniformAfterVectorization(cast<Instruction>(V), VF)
  1843. : true && "Uniform values only have lane zero");
  1844. // If the value from the original loop has not been vectorized, it is
  1845. // represented by UF x VF scalar values in the new loop. Return the requested
  1846. // scalar value.
  1847. if (VectorLoopValueMap.hasScalarValue(V, Instance))
  1848. return VectorLoopValueMap.getScalarValue(V, Instance);
  1849. // If the value has not been scalarized, get its entry in VectorLoopValueMap
  1850. // for the given unroll part. If this entry is not a vector type (i.e., the
  1851. // vectorization factor is one), there is no need to generate an
  1852. // extractelement instruction.
  1853. auto *U = getOrCreateVectorValue(V, Instance.Part);
  1854. if (!U->getType()->isVectorTy()) {
  1855. assert(VF == 1 && "Value not scalarized has non-vector type");
  1856. return U;
  1857. }
  1858. // Otherwise, the value from the original loop has been vectorized and is
  1859. // represented by UF vector values. Extract and return the requested scalar
  1860. // value from the appropriate vector lane.
  1861. return Builder.CreateExtractElement(U, Builder.getInt32(Instance.Lane));
  1862. }
  1863. void InnerLoopVectorizer::packScalarIntoVectorValue(
  1864. Value *V, const VPIteration &Instance) {
  1865. assert(V != Induction && "The new induction variable should not be used.");
  1866. assert(!V->getType()->isVectorTy() && "Can't pack a vector");
  1867. assert(!V->getType()->isVoidTy() && "Type does not produce a value");
  1868. Value *ScalarInst = VectorLoopValueMap.getScalarValue(V, Instance);
  1869. Value *VectorValue = VectorLoopValueMap.getVectorValue(V, Instance.Part);
  1870. VectorValue = Builder.CreateInsertElement(VectorValue, ScalarInst,
  1871. Builder.getInt32(Instance.Lane));
  1872. VectorLoopValueMap.resetVectorValue(V, Instance.Part, VectorValue);
  1873. }
  1874. Value *InnerLoopVectorizer::reverseVector(Value *Vec) {
  1875. assert(Vec->getType()->isVectorTy() && "Invalid type");
  1876. SmallVector<Constant *, 8> ShuffleMask;
  1877. for (unsigned i = 0; i < VF; ++i)
  1878. ShuffleMask.push_back(Builder.getInt32(VF - i - 1));
  1879. return Builder.CreateShuffleVector(Vec, UndefValue::get(Vec->getType()),
  1880. ConstantVector::get(ShuffleMask),
  1881. "reverse");
  1882. }
  1883. // Try to vectorize the interleave group that \p Instr belongs to.
  1884. //
  1885. // E.g. Translate following interleaved load group (factor = 3):
  1886. // for (i = 0; i < N; i+=3) {
  1887. // R = Pic[i]; // Member of index 0
  1888. // G = Pic[i+1]; // Member of index 1
  1889. // B = Pic[i+2]; // Member of index 2
  1890. // ... // do something to R, G, B
  1891. // }
  1892. // To:
  1893. // %wide.vec = load <12 x i32> ; Read 4 tuples of R,G,B
  1894. // %R.vec = shuffle %wide.vec, undef, <0, 3, 6, 9> ; R elements
  1895. // %G.vec = shuffle %wide.vec, undef, <1, 4, 7, 10> ; G elements
  1896. // %B.vec = shuffle %wide.vec, undef, <2, 5, 8, 11> ; B elements
  1897. //
  1898. // Or translate following interleaved store group (factor = 3):
  1899. // for (i = 0; i < N; i+=3) {
  1900. // ... do something to R, G, B
  1901. // Pic[i] = R; // Member of index 0
  1902. // Pic[i+1] = G; // Member of index 1
  1903. // Pic[i+2] = B; // Member of index 2
  1904. // }
  1905. // To:
  1906. // %R_G.vec = shuffle %R.vec, %G.vec, <0, 1, 2, ..., 7>
  1907. // %B_U.vec = shuffle %B.vec, undef, <0, 1, 2, 3, u, u, u, u>
  1908. // %interleaved.vec = shuffle %R_G.vec, %B_U.vec,
  1909. // <0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11> ; Interleave R,G,B elements
  1910. // store <12 x i32> %interleaved.vec ; Write 4 tuples of R,G,B
  1911. void InnerLoopVectorizer::vectorizeInterleaveGroup(Instruction *Instr) {
  1912. const InterleaveGroup *Group = Cost->getInterleavedAccessGroup(Instr);
  1913. assert(Group && "Fail to get an interleaved access group.");
  1914. // Skip if current instruction is not the insert position.
  1915. if (Instr != Group->getInsertPos())
  1916. return;
  1917. const DataLayout &DL = Instr->getModule()->getDataLayout();
  1918. Value *Ptr = getLoadStorePointerOperand(Instr);
  1919. // Prepare for the vector type of the interleaved load/store.
  1920. Type *ScalarTy = getMemInstValueType(Instr);
  1921. unsigned InterleaveFactor = Group->getFactor();
  1922. Type *VecTy = VectorType::get(ScalarTy, InterleaveFactor * VF);
  1923. Type *PtrTy = VecTy->getPointerTo(getMemInstAddressSpace(Instr));
  1924. // Prepare for the new pointers.
  1925. setDebugLocFromInst(Builder, Ptr);
  1926. SmallVector<Value *, 2> NewPtrs;
  1927. unsigned Index = Group->getIndex(Instr);
  1928. // If the group is reverse, adjust the index to refer to the last vector lane
  1929. // instead of the first. We adjust the index from the first vector lane,
  1930. // rather than directly getting the pointer for lane VF - 1, because the
  1931. // pointer operand of the interleaved access is supposed to be uniform. For
  1932. // uniform instructions, we're only required to generate a value for the
  1933. // first vector lane in each unroll iteration.
  1934. if (Group->isReverse())
  1935. Index += (VF - 1) * Group->getFactor();
  1936. bool InBounds = false;
  1937. if (auto *gep = dyn_cast<GetElementPtrInst>(Ptr->stripPointerCasts()))
  1938. InBounds = gep->isInBounds();
  1939. for (unsigned Part = 0; Part < UF; Part++) {
  1940. Value *NewPtr = getOrCreateScalarValue(Ptr, {Part, 0});
  1941. // Notice current instruction could be any index. Need to adjust the address
  1942. // to the member of index 0.
  1943. //
  1944. // E.g. a = A[i+1]; // Member of index 1 (Current instruction)
  1945. // b = A[i]; // Member of index 0
  1946. // Current pointer is pointed to A[i+1], adjust it to A[i].
  1947. //
  1948. // E.g. A[i+1] = a; // Member of index 1
  1949. // A[i] = b; // Member of index 0
  1950. // A[i+2] = c; // Member of index 2 (Current instruction)
  1951. // Current pointer is pointed to A[i+2], adjust it to A[i].
  1952. NewPtr = Builder.CreateGEP(NewPtr, Builder.getInt32(-Index));
  1953. if (InBounds)
  1954. cast<GetElementPtrInst>(NewPtr)->setIsInBounds(true);
  1955. // Cast to the vector pointer type.
  1956. NewPtrs.push_back(Builder.CreateBitCast(NewPtr, PtrTy));
  1957. }
  1958. setDebugLocFromInst(Builder, Instr);
  1959. Value *UndefVec = UndefValue::get(VecTy);
  1960. // Vectorize the interleaved load group.
  1961. if (isa<LoadInst>(Instr)) {
  1962. // For each unroll part, create a wide load for the group.
  1963. SmallVector<Value *, 2> NewLoads;
  1964. for (unsigned Part = 0; Part < UF; Part++) {
  1965. auto *NewLoad = Builder.CreateAlignedLoad(
  1966. NewPtrs[Part], Group->getAlignment(), "wide.vec");
  1967. Group->addMetadata(NewLoad);
  1968. NewLoads.push_back(NewLoad);
  1969. }
  1970. // For each member in the group, shuffle out the appropriate data from the
  1971. // wide loads.
  1972. for (unsigned I = 0; I < InterleaveFactor; ++I) {
  1973. Instruction *Member = Group->getMember(I);
  1974. // Skip the gaps in the group.
  1975. if (!Member)
  1976. continue;
  1977. Constant *StrideMask = createStrideMask(Builder, I, InterleaveFactor, VF);
  1978. for (unsigned Part = 0; Part < UF; Part++) {
  1979. Value *StridedVec = Builder.CreateShuffleVector(
  1980. NewLoads[Part], UndefVec, StrideMask, "strided.vec");
  1981. // If this member has different type, cast the result type.
  1982. if (Member->getType() != ScalarTy) {
  1983. VectorType *OtherVTy = VectorType::get(Member->getType(), VF);
  1984. StridedVec = createBitOrPointerCast(StridedVec, OtherVTy, DL);
  1985. }
  1986. if (Group->isReverse())
  1987. StridedVec = reverseVector(StridedVec);
  1988. VectorLoopValueMap.setVectorValue(Member, Part, StridedVec);
  1989. }
  1990. }
  1991. return;
  1992. }
  1993. // The sub vector type for current instruction.
  1994. VectorType *SubVT = VectorType::get(ScalarTy, VF);
  1995. // Vectorize the interleaved store group.
  1996. for (unsigned Part = 0; Part < UF; Part++) {
  1997. // Collect the stored vector from each member.
  1998. SmallVector<Value *, 4> StoredVecs;
  1999. for (unsigned i = 0; i < InterleaveFactor; i++) {
  2000. // Interleaved store group doesn't allow a gap, so each index has a member
  2001. Instruction *Member = Group->getMember(i);
  2002. assert(Member && "Fail to get a member from an interleaved store group");
  2003. Value *StoredVec = getOrCreateVectorValue(
  2004. cast<StoreInst>(Member)->getValueOperand(), Part);
  2005. if (Group->isReverse())
  2006. StoredVec = reverseVector(StoredVec);
  2007. // If this member has different type, cast it to a unified type.
  2008. if (StoredVec->getType() != SubVT)
  2009. StoredVec = createBitOrPointerCast(StoredVec, SubVT, DL);
  2010. StoredVecs.push_back(StoredVec);
  2011. }
  2012. // Concatenate all vectors into a wide vector.
  2013. Value *WideVec = concatenateVectors(Builder, StoredVecs);
  2014. // Interleave the elements in the wide vector.
  2015. Constant *IMask = createInterleaveMask(Builder, VF, InterleaveFactor);
  2016. Value *IVec = Builder.CreateShuffleVector(WideVec, UndefVec, IMask,
  2017. "interleaved.vec");
  2018. Instruction *NewStoreInstr =
  2019. Builder.CreateAlignedStore(IVec, NewPtrs[Part], Group->getAlignment());
  2020. Group->addMetadata(NewStoreInstr);
  2021. }
  2022. }
  2023. void InnerLoopVectorizer::vectorizeMemoryInstruction(Instruction *Instr,
  2024. VectorParts *BlockInMask) {
  2025. // Attempt to issue a wide load.
  2026. LoadInst *LI = dyn_cast<LoadInst>(Instr);
  2027. StoreInst *SI = dyn_cast<StoreInst>(Instr);
  2028. assert((LI || SI) && "Invalid Load/Store instruction");
  2029. LoopVectorizationCostModel::InstWidening Decision =
  2030. Cost->getWideningDecision(Instr, VF);
  2031. assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
  2032. "CM decision should be taken at this point");
  2033. if (Decision == LoopVectorizationCostModel::CM_Interleave)
  2034. return vectorizeInterleaveGroup(Instr);
  2035. Type *ScalarDataTy = getMemInstValueType(Instr);
  2036. Type *DataTy = VectorType::get(ScalarDataTy, VF);
  2037. Value *Ptr = getLoadStorePointerOperand(Instr);
  2038. unsigned Alignment = getMemInstAlignment(Instr);
  2039. // An alignment of 0 means target abi alignment. We need to use the scalar's
  2040. // target abi alignment in such a case.
  2041. const DataLayout &DL = Instr->getModule()->getDataLayout();
  2042. if (!Alignment)
  2043. Alignment = DL.getABITypeAlignment(ScalarDataTy);
  2044. unsigned AddressSpace = getMemInstAddressSpace(Instr);
  2045. // Determine if the pointer operand of the access is either consecutive or
  2046. // reverse consecutive.
  2047. bool Reverse = (Decision == LoopVectorizationCostModel::CM_Widen_Reverse);
  2048. bool ConsecutiveStride =
  2049. Reverse || (Decision == LoopVectorizationCostModel::CM_Widen);
  2050. bool CreateGatherScatter =
  2051. (Decision == LoopVectorizationCostModel::CM_GatherScatter);
  2052. // Either Ptr feeds a vector load/store, or a vector GEP should feed a vector
  2053. // gather/scatter. Otherwise Decision should have been to Scalarize.
  2054. assert((ConsecutiveStride || CreateGatherScatter) &&
  2055. "The instruction should be scalarized");
  2056. // Handle consecutive loads/stores.
  2057. if (ConsecutiveStride)
  2058. Ptr = getOrCreateScalarValue(Ptr, {0, 0});
  2059. VectorParts Mask;
  2060. bool isMaskRequired = BlockInMask;
  2061. if (isMaskRequired)
  2062. Mask = *BlockInMask;
  2063. bool InBounds = false;
  2064. if (auto *gep = dyn_cast<GetElementPtrInst>(
  2065. getLoadStorePointerOperand(Instr)->stripPointerCasts()))
  2066. InBounds = gep->isInBounds();
  2067. const auto CreateVecPtr = [&](unsigned Part, Value *Ptr) -> Value * {
  2068. // Calculate the pointer for the specific unroll-part.
  2069. GetElementPtrInst *PartPtr = nullptr;
  2070. if (Reverse) {
  2071. // If the address is consecutive but reversed, then the
  2072. // wide store needs to start at the last vector element.
  2073. PartPtr = cast<GetElementPtrInst>(
  2074. Builder.CreateGEP(Ptr, Builder.getInt32(-Part * VF)));
  2075. PartPtr->setIsInBounds(InBounds);
  2076. PartPtr = cast<GetElementPtrInst>(
  2077. Builder.CreateGEP(PartPtr, Builder.getInt32(1 - VF)));
  2078. PartPtr->setIsInBounds(InBounds);
  2079. if (isMaskRequired) // Reverse of a null all-one mask is a null mask.
  2080. Mask[Part] = reverseVector(Mask[Part]);
  2081. } else {
  2082. PartPtr = cast<GetElementPtrInst>(
  2083. Builder.CreateGEP(Ptr, Builder.getInt32(Part * VF)));
  2084. PartPtr->setIsInBounds(InBounds);
  2085. }
  2086. return Builder.CreateBitCast(PartPtr, DataTy->getPointerTo(AddressSpace));
  2087. };
  2088. // Handle Stores:
  2089. if (SI) {
  2090. setDebugLocFromInst(Builder, SI);
  2091. for (unsigned Part = 0; Part < UF; ++Part) {
  2092. Instruction *NewSI = nullptr;
  2093. Value *StoredVal = getOrCreateVectorValue(SI->getValueOperand(), Part);
  2094. if (CreateGatherScatter) {
  2095. Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
  2096. Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
  2097. NewSI = Builder.CreateMaskedScatter(StoredVal, VectorGep, Alignment,
  2098. MaskPart);
  2099. } else {
  2100. if (Reverse) {
  2101. // If we store to reverse consecutive memory locations, then we need
  2102. // to reverse the order of elements in the stored value.
  2103. StoredVal = reverseVector(StoredVal);
  2104. // We don't want to update the value in the map as it might be used in
  2105. // another expression. So don't call resetVectorValue(StoredVal).
  2106. }
  2107. auto *VecPtr = CreateVecPtr(Part, Ptr);
  2108. if (isMaskRequired)
  2109. NewSI = Builder.CreateMaskedStore(StoredVal, VecPtr, Alignment,
  2110. Mask[Part]);
  2111. else
  2112. NewSI = Builder.CreateAlignedStore(StoredVal, VecPtr, Alignment);
  2113. }
  2114. addMetadata(NewSI, SI);
  2115. }
  2116. return;
  2117. }
  2118. // Handle loads.
  2119. assert(LI && "Must have a load instruction");
  2120. setDebugLocFromInst(Builder, LI);
  2121. for (unsigned Part = 0; Part < UF; ++Part) {
  2122. Value *NewLI;
  2123. if (CreateGatherScatter) {
  2124. Value *MaskPart = isMaskRequired ? Mask[Part] : nullptr;
  2125. Value *VectorGep = getOrCreateVectorValue(Ptr, Part);
  2126. NewLI = Builder.CreateMaskedGather(VectorGep, Alignment, MaskPart,
  2127. nullptr, "wide.masked.gather");
  2128. addMetadata(NewLI, LI);
  2129. } else {
  2130. auto *VecPtr = CreateVecPtr(Part, Ptr);
  2131. if (isMaskRequired)
  2132. NewLI = Builder.CreateMaskedLoad(VecPtr, Alignment, Mask[Part],
  2133. UndefValue::get(DataTy),
  2134. "wide.masked.load");
  2135. else
  2136. NewLI = Builder.CreateAlignedLoad(VecPtr, Alignment, "wide.load");
  2137. // Add metadata to the load, but setVectorValue to the reverse shuffle.
  2138. addMetadata(NewLI, LI);
  2139. if (Reverse)
  2140. NewLI = reverseVector(NewLI);
  2141. }
  2142. VectorLoopValueMap.setVectorValue(Instr, Part, NewLI);
  2143. }
  2144. }
  2145. void InnerLoopVectorizer::scalarizeInstruction(Instruction *Instr,
  2146. const VPIteration &Instance,
  2147. bool IfPredicateInstr) {
  2148. assert(!Instr->getType()->isAggregateType() && "Can't handle vectors");
  2149. setDebugLocFromInst(Builder, Instr);
  2150. // Does this instruction return a value ?
  2151. bool IsVoidRetTy = Instr->getType()->isVoidTy();
  2152. Instruction *Cloned = Instr->clone();
  2153. if (!IsVoidRetTy)
  2154. Cloned->setName(Instr->getName() + ".cloned");
  2155. // Replace the operands of the cloned instructions with their scalar
  2156. // equivalents in the new loop.
  2157. for (unsigned op = 0, e = Instr->getNumOperands(); op != e; ++op) {
  2158. auto *NewOp = getOrCreateScalarValue(Instr->getOperand(op), Instance);
  2159. Cloned->setOperand(op, NewOp);
  2160. }
  2161. addNewMetadata(Cloned, Instr);
  2162. // Place the cloned scalar in the new loop.
  2163. Builder.Insert(Cloned);
  2164. // Add the cloned scalar to the scalar map entry.
  2165. VectorLoopValueMap.setScalarValue(Instr, Instance, Cloned);
  2166. // If we just cloned a new assumption, add it the assumption cache.
  2167. if (auto *II = dyn_cast<IntrinsicInst>(Cloned))
  2168. if (II->getIntrinsicID() == Intrinsic::assume)
  2169. AC->registerAssumption(II);
  2170. // End if-block.
  2171. if (IfPredicateInstr)
  2172. PredicatedInstructions.push_back(Cloned);
  2173. }
  2174. PHINode *InnerLoopVectorizer::createInductionVariable(Loop *L, Value *Start,
  2175. Value *End, Value *Step,
  2176. Instruction *DL) {
  2177. BasicBlock *Header = L->getHeader();
  2178. BasicBlock *Latch = L->getLoopLatch();
  2179. // As we're just creating this loop, it's possible no latch exists
  2180. // yet. If so, use the header as this will be a single block loop.
  2181. if (!Latch)
  2182. Latch = Header;
  2183. IRBuilder<> Builder(&*Header->getFirstInsertionPt());
  2184. Instruction *OldInst = getDebugLocFromInstOrOperands(OldInduction);
  2185. setDebugLocFromInst(Builder, OldInst);
  2186. auto *Induction = Builder.CreatePHI(Start->getType(), 2, "index");
  2187. Builder.SetInsertPoint(Latch->getTerminator());
  2188. setDebugLocFromInst(Builder, OldInst);
  2189. // Create i+1 and fill the PHINode.
  2190. Value *Next = Builder.CreateAdd(Induction, Step, "index.next");
  2191. Induction->addIncoming(Start, L->getLoopPreheader());
  2192. Induction->addIncoming(Next, Latch);
  2193. // Create the compare.
  2194. Value *ICmp = Builder.CreateICmpEQ(Next, End);
  2195. Builder.CreateCondBr(ICmp, L->getExitBlock(), Header);
  2196. // Now we have two terminators. Remove the old one from the block.
  2197. Latch->getTerminator()->eraseFromParent();
  2198. return Induction;
  2199. }
  2200. Value *InnerLoopVectorizer::getOrCreateTripCount(Loop *L) {
  2201. if (TripCount)
  2202. return TripCount;
  2203. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  2204. // Find the loop boundaries.
  2205. ScalarEvolution *SE = PSE.getSE();
  2206. const SCEV *BackedgeTakenCount = PSE.getBackedgeTakenCount();
  2207. assert(BackedgeTakenCount != SE->getCouldNotCompute() &&
  2208. "Invalid loop count");
  2209. Type *IdxTy = Legal->getWidestInductionType();
  2210. // The exit count might have the type of i64 while the phi is i32. This can
  2211. // happen if we have an induction variable that is sign extended before the
  2212. // compare. The only way that we get a backedge taken count is that the
  2213. // induction variable was signed and as such will not overflow. In such a case
  2214. // truncation is legal.
  2215. if (BackedgeTakenCount->getType()->getPrimitiveSizeInBits() >
  2216. IdxTy->getPrimitiveSizeInBits())
  2217. BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount, IdxTy);
  2218. BackedgeTakenCount = SE->getNoopOrZeroExtend(BackedgeTakenCount, IdxTy);
  2219. // Get the total trip count from the count by adding 1.
  2220. const SCEV *ExitCount = SE->getAddExpr(
  2221. BackedgeTakenCount, SE->getOne(BackedgeTakenCount->getType()));
  2222. const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
  2223. // Expand the trip count and place the new instructions in the preheader.
  2224. // Notice that the pre-header does not change, only the loop body.
  2225. SCEVExpander Exp(*SE, DL, "induction");
  2226. // Count holds the overall loop count (N).
  2227. TripCount = Exp.expandCodeFor(ExitCount, ExitCount->getType(),
  2228. L->getLoopPreheader()->getTerminator());
  2229. if (TripCount->getType()->isPointerTy())
  2230. TripCount =
  2231. CastInst::CreatePointerCast(TripCount, IdxTy, "exitcount.ptrcnt.to.int",
  2232. L->getLoopPreheader()->getTerminator());
  2233. return TripCount;
  2234. }
  2235. Value *InnerLoopVectorizer::getOrCreateVectorTripCount(Loop *L) {
  2236. if (VectorTripCount)
  2237. return VectorTripCount;
  2238. Value *TC = getOrCreateTripCount(L);
  2239. IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
  2240. // Now we need to generate the expression for the part of the loop that the
  2241. // vectorized body will execute. This is equal to N - (N % Step) if scalar
  2242. // iterations are not required for correctness, or N - Step, otherwise. Step
  2243. // is equal to the vectorization factor (number of SIMD elements) times the
  2244. // unroll factor (number of SIMD instructions).
  2245. Constant *Step = ConstantInt::get(TC->getType(), VF * UF);
  2246. Value *R = Builder.CreateURem(TC, Step, "n.mod.vf");
  2247. // If there is a non-reversed interleaved group that may speculatively access
  2248. // memory out-of-bounds, we need to ensure that there will be at least one
  2249. // iteration of the scalar epilogue loop. Thus, if the step evenly divides
  2250. // the trip count, we set the remainder to be equal to the step. If the step
  2251. // does not evenly divide the trip count, no adjustment is necessary since
  2252. // there will already be scalar iterations. Note that the minimum iterations
  2253. // check ensures that N >= Step.
  2254. if (VF > 1 && Cost->requiresScalarEpilogue()) {
  2255. auto *IsZero = Builder.CreateICmpEQ(R, ConstantInt::get(R->getType(), 0));
  2256. R = Builder.CreateSelect(IsZero, Step, R);
  2257. }
  2258. VectorTripCount = Builder.CreateSub(TC, R, "n.vec");
  2259. return VectorTripCount;
  2260. }
  2261. Value *InnerLoopVectorizer::createBitOrPointerCast(Value *V, VectorType *DstVTy,
  2262. const DataLayout &DL) {
  2263. // Verify that V is a vector type with same number of elements as DstVTy.
  2264. unsigned VF = DstVTy->getNumElements();
  2265. VectorType *SrcVecTy = cast<VectorType>(V->getType());
  2266. assert((VF == SrcVecTy->getNumElements()) && "Vector dimensions do not match");
  2267. Type *SrcElemTy = SrcVecTy->getElementType();
  2268. Type *DstElemTy = DstVTy->getElementType();
  2269. assert((DL.getTypeSizeInBits(SrcElemTy) == DL.getTypeSizeInBits(DstElemTy)) &&
  2270. "Vector elements must have same size");
  2271. // Do a direct cast if element types are castable.
  2272. if (CastInst::isBitOrNoopPointerCastable(SrcElemTy, DstElemTy, DL)) {
  2273. return Builder.CreateBitOrPointerCast(V, DstVTy);
  2274. }
  2275. // V cannot be directly casted to desired vector type.
  2276. // May happen when V is a floating point vector but DstVTy is a vector of
  2277. // pointers or vice-versa. Handle this using a two-step bitcast using an
  2278. // intermediate Integer type for the bitcast i.e. Ptr <-> Int <-> Float.
  2279. assert((DstElemTy->isPointerTy() != SrcElemTy->isPointerTy()) &&
  2280. "Only one type should be a pointer type");
  2281. assert((DstElemTy->isFloatingPointTy() != SrcElemTy->isFloatingPointTy()) &&
  2282. "Only one type should be a floating point type");
  2283. Type *IntTy =
  2284. IntegerType::getIntNTy(V->getContext(), DL.getTypeSizeInBits(SrcElemTy));
  2285. VectorType *VecIntTy = VectorType::get(IntTy, VF);
  2286. Value *CastVal = Builder.CreateBitOrPointerCast(V, VecIntTy);
  2287. return Builder.CreateBitOrPointerCast(CastVal, DstVTy);
  2288. }
  2289. void InnerLoopVectorizer::emitMinimumIterationCountCheck(Loop *L,
  2290. BasicBlock *Bypass) {
  2291. Value *Count = getOrCreateTripCount(L);
  2292. BasicBlock *BB = L->getLoopPreheader();
  2293. IRBuilder<> Builder(BB->getTerminator());
  2294. // Generate code to check if the loop's trip count is less than VF * UF, or
  2295. // equal to it in case a scalar epilogue is required; this implies that the
  2296. // vector trip count is zero. This check also covers the case where adding one
  2297. // to the backedge-taken count overflowed leading to an incorrect trip count
  2298. // of zero. In this case we will also jump to the scalar loop.
  2299. auto P = Cost->requiresScalarEpilogue() ? ICmpInst::ICMP_ULE
  2300. : ICmpInst::ICMP_ULT;
  2301. Value *CheckMinIters = Builder.CreateICmp(
  2302. P, Count, ConstantInt::get(Count->getType(), VF * UF), "min.iters.check");
  2303. BasicBlock *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
  2304. // Update dominator tree immediately if the generated block is a
  2305. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2306. // checks may query it before the current function is finished.
  2307. DT->addNewBlock(NewBB, BB);
  2308. if (L->getParentLoop())
  2309. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2310. ReplaceInstWithInst(BB->getTerminator(),
  2311. BranchInst::Create(Bypass, NewBB, CheckMinIters));
  2312. LoopBypassBlocks.push_back(BB);
  2313. }
  2314. void InnerLoopVectorizer::emitSCEVChecks(Loop *L, BasicBlock *Bypass) {
  2315. BasicBlock *BB = L->getLoopPreheader();
  2316. // Generate the code to check that the SCEV assumptions that we made.
  2317. // We want the new basic block to start at the first instruction in a
  2318. // sequence of instructions that form a check.
  2319. SCEVExpander Exp(*PSE.getSE(), Bypass->getModule()->getDataLayout(),
  2320. "scev.check");
  2321. Value *SCEVCheck =
  2322. Exp.expandCodeForPredicate(&PSE.getUnionPredicate(), BB->getTerminator());
  2323. if (auto *C = dyn_cast<ConstantInt>(SCEVCheck))
  2324. if (C->isZero())
  2325. return;
  2326. // Create a new block containing the stride check.
  2327. BB->setName("vector.scevcheck");
  2328. auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
  2329. // Update dominator tree immediately if the generated block is a
  2330. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2331. // checks may query it before the current function is finished.
  2332. DT->addNewBlock(NewBB, BB);
  2333. if (L->getParentLoop())
  2334. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2335. ReplaceInstWithInst(BB->getTerminator(),
  2336. BranchInst::Create(Bypass, NewBB, SCEVCheck));
  2337. LoopBypassBlocks.push_back(BB);
  2338. AddedSafetyChecks = true;
  2339. }
  2340. void InnerLoopVectorizer::emitMemRuntimeChecks(Loop *L, BasicBlock *Bypass) {
  2341. BasicBlock *BB = L->getLoopPreheader();
  2342. // Generate the code that checks in runtime if arrays overlap. We put the
  2343. // checks into a separate block to make the more common case of few elements
  2344. // faster.
  2345. Instruction *FirstCheckInst;
  2346. Instruction *MemRuntimeCheck;
  2347. std::tie(FirstCheckInst, MemRuntimeCheck) =
  2348. Legal->getLAI()->addRuntimeChecks(BB->getTerminator());
  2349. if (!MemRuntimeCheck)
  2350. return;
  2351. // Create a new block containing the memory check.
  2352. BB->setName("vector.memcheck");
  2353. auto *NewBB = BB->splitBasicBlock(BB->getTerminator(), "vector.ph");
  2354. // Update dominator tree immediately if the generated block is a
  2355. // LoopBypassBlock because SCEV expansions to generate loop bypass
  2356. // checks may query it before the current function is finished.
  2357. DT->addNewBlock(NewBB, BB);
  2358. if (L->getParentLoop())
  2359. L->getParentLoop()->addBasicBlockToLoop(NewBB, *LI);
  2360. ReplaceInstWithInst(BB->getTerminator(),
  2361. BranchInst::Create(Bypass, NewBB, MemRuntimeCheck));
  2362. LoopBypassBlocks.push_back(BB);
  2363. AddedSafetyChecks = true;
  2364. // We currently don't use LoopVersioning for the actual loop cloning but we
  2365. // still use it to add the noalias metadata.
  2366. LVer = llvm::make_unique<LoopVersioning>(*Legal->getLAI(), OrigLoop, LI, DT,
  2367. PSE.getSE());
  2368. LVer->prepareNoAliasMetadata();
  2369. }
  2370. BasicBlock *InnerLoopVectorizer::createVectorizedLoopSkeleton() {
  2371. /*
  2372. In this function we generate a new loop. The new loop will contain
  2373. the vectorized instructions while the old loop will continue to run the
  2374. scalar remainder.
  2375. [ ] <-- loop iteration number check.
  2376. / |
  2377. / v
  2378. | [ ] <-- vector loop bypass (may consist of multiple blocks).
  2379. | / |
  2380. | / v
  2381. || [ ] <-- vector pre header.
  2382. |/ |
  2383. | v
  2384. | [ ] \
  2385. | [ ]_| <-- vector loop.
  2386. | |
  2387. | v
  2388. | -[ ] <--- middle-block.
  2389. | / |
  2390. | / v
  2391. -|- >[ ] <--- new preheader.
  2392. | |
  2393. | v
  2394. | [ ] \
  2395. | [ ]_| <-- old scalar loop to handle remainder.
  2396. \ |
  2397. \ v
  2398. >[ ] <-- exit block.
  2399. ...
  2400. */
  2401. BasicBlock *OldBasicBlock = OrigLoop->getHeader();
  2402. BasicBlock *VectorPH = OrigLoop->getLoopPreheader();
  2403. BasicBlock *ExitBlock = OrigLoop->getExitBlock();
  2404. assert(VectorPH && "Invalid loop structure");
  2405. assert(ExitBlock && "Must have an exit block");
  2406. // Some loops have a single integer induction variable, while other loops
  2407. // don't. One example is c++ iterators that often have multiple pointer
  2408. // induction variables. In the code below we also support a case where we
  2409. // don't have a single induction variable.
  2410. //
  2411. // We try to obtain an induction variable from the original loop as hard
  2412. // as possible. However if we don't find one that:
  2413. // - is an integer
  2414. // - counts from zero, stepping by one
  2415. // - is the size of the widest induction variable type
  2416. // then we create a new one.
  2417. OldInduction = Legal->getPrimaryInduction();
  2418. Type *IdxTy = Legal->getWidestInductionType();
  2419. // Split the single block loop into the two loop structure described above.
  2420. BasicBlock *VecBody =
  2421. VectorPH->splitBasicBlock(VectorPH->getTerminator(), "vector.body");
  2422. BasicBlock *MiddleBlock =
  2423. VecBody->splitBasicBlock(VecBody->getTerminator(), "middle.block");
  2424. BasicBlock *ScalarPH =
  2425. MiddleBlock->splitBasicBlock(MiddleBlock->getTerminator(), "scalar.ph");
  2426. // Create and register the new vector loop.
  2427. Loop *Lp = LI->AllocateLoop();
  2428. Loop *ParentLoop = OrigLoop->getParentLoop();
  2429. // Insert the new loop into the loop nest and register the new basic blocks
  2430. // before calling any utilities such as SCEV that require valid LoopInfo.
  2431. if (ParentLoop) {
  2432. ParentLoop->addChildLoop(Lp);
  2433. ParentLoop->addBasicBlockToLoop(ScalarPH, *LI);
  2434. ParentLoop->addBasicBlockToLoop(MiddleBlock, *LI);
  2435. } else {
  2436. LI->addTopLevelLoop(Lp);
  2437. }
  2438. Lp->addBasicBlockToLoop(VecBody, *LI);
  2439. // Find the loop boundaries.
  2440. Value *Count = getOrCreateTripCount(Lp);
  2441. Value *StartIdx = ConstantInt::get(IdxTy, 0);
  2442. // Now, compare the new count to zero. If it is zero skip the vector loop and
  2443. // jump to the scalar loop. This check also covers the case where the
  2444. // backedge-taken count is uint##_max: adding one to it will overflow leading
  2445. // to an incorrect trip count of zero. In this (rare) case we will also jump
  2446. // to the scalar loop.
  2447. emitMinimumIterationCountCheck(Lp, ScalarPH);
  2448. // Generate the code to check any assumptions that we've made for SCEV
  2449. // expressions.
  2450. emitSCEVChecks(Lp, ScalarPH);
  2451. // Generate the code that checks in runtime if arrays overlap. We put the
  2452. // checks into a separate block to make the more common case of few elements
  2453. // faster.
  2454. emitMemRuntimeChecks(Lp, ScalarPH);
  2455. // Generate the induction variable.
  2456. // The loop step is equal to the vectorization factor (num of SIMD elements)
  2457. // times the unroll factor (num of SIMD instructions).
  2458. Value *CountRoundDown = getOrCreateVectorTripCount(Lp);
  2459. Constant *Step = ConstantInt::get(IdxTy, VF * UF);
  2460. Induction =
  2461. createInductionVariable(Lp, StartIdx, CountRoundDown, Step,
  2462. getDebugLocFromInstOrOperands(OldInduction));
  2463. // We are going to resume the execution of the scalar loop.
  2464. // Go over all of the induction variables that we found and fix the
  2465. // PHIs that are left in the scalar version of the loop.
  2466. // The starting values of PHI nodes depend on the counter of the last
  2467. // iteration in the vectorized loop.
  2468. // If we come from a bypass edge then we need to start from the original
  2469. // start value.
  2470. // This variable saves the new starting index for the scalar loop. It is used
  2471. // to test if there are any tail iterations left once the vector loop has
  2472. // completed.
  2473. LoopVectorizationLegality::InductionList *List = Legal->getInductionVars();
  2474. for (auto &InductionEntry : *List) {
  2475. PHINode *OrigPhi = InductionEntry.first;
  2476. InductionDescriptor II = InductionEntry.second;
  2477. // Create phi nodes to merge from the backedge-taken check block.
  2478. PHINode *BCResumeVal = PHINode::Create(
  2479. OrigPhi->getType(), 3, "bc.resume.val", ScalarPH->getTerminator());
  2480. // Copy original phi DL over to the new one.
  2481. BCResumeVal->setDebugLoc(OrigPhi->getDebugLoc());
  2482. Value *&EndValue = IVEndValues[OrigPhi];
  2483. if (OrigPhi == OldInduction) {
  2484. // We know what the end value is.
  2485. EndValue = CountRoundDown;
  2486. } else {
  2487. IRBuilder<> B(Lp->getLoopPreheader()->getTerminator());
  2488. Type *StepType = II.getStep()->getType();
  2489. Instruction::CastOps CastOp =
  2490. CastInst::getCastOpcode(CountRoundDown, true, StepType, true);
  2491. Value *CRD = B.CreateCast(CastOp, CountRoundDown, StepType, "cast.crd");
  2492. const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
  2493. EndValue = II.transform(B, CRD, PSE.getSE(), DL);
  2494. EndValue->setName("ind.end");
  2495. }
  2496. // The new PHI merges the original incoming value, in case of a bypass,
  2497. // or the value at the end of the vectorized loop.
  2498. BCResumeVal->addIncoming(EndValue, MiddleBlock);
  2499. // Fix the scalar body counter (PHI node).
  2500. unsigned BlockIdx = OrigPhi->getBasicBlockIndex(ScalarPH);
  2501. // The old induction's phi node in the scalar body needs the truncated
  2502. // value.
  2503. for (BasicBlock *BB : LoopBypassBlocks)
  2504. BCResumeVal->addIncoming(II.getStartValue(), BB);
  2505. OrigPhi->setIncomingValue(BlockIdx, BCResumeVal);
  2506. }
  2507. // Add a check in the middle block to see if we have completed
  2508. // all of the iterations in the first vector loop.
  2509. // If (N - N%VF) == N, then we *don't* need to run the remainder.
  2510. Value *CmpN =
  2511. CmpInst::Create(Instruction::ICmp, CmpInst::ICMP_EQ, Count,
  2512. CountRoundDown, "cmp.n", MiddleBlock->getTerminator());
  2513. ReplaceInstWithInst(MiddleBlock->getTerminator(),
  2514. BranchInst::Create(ExitBlock, ScalarPH, CmpN));
  2515. // Get ready to start creating new instructions into the vectorized body.
  2516. Builder.SetInsertPoint(&*VecBody->getFirstInsertionPt());
  2517. // Save the state.
  2518. LoopVectorPreHeader = Lp->getLoopPreheader();
  2519. LoopScalarPreHeader = ScalarPH;
  2520. LoopMiddleBlock = MiddleBlock;
  2521. LoopExitBlock = ExitBlock;
  2522. LoopVectorBody = VecBody;
  2523. LoopScalarBody = OldBasicBlock;
  2524. // Keep all loop hints from the original loop on the vector loop (we'll
  2525. // replace the vectorizer-specific hints below).
  2526. if (MDNode *LID = OrigLoop->getLoopID())
  2527. Lp->setLoopID(LID);
  2528. LoopVectorizeHints Hints(Lp, true, *ORE);
  2529. Hints.setAlreadyVectorized();
  2530. return LoopVectorPreHeader;
  2531. }
  2532. // Fix up external users of the induction variable. At this point, we are
  2533. // in LCSSA form, with all external PHIs that use the IV having one input value,
  2534. // coming from the remainder loop. We need those PHIs to also have a correct
  2535. // value for the IV when arriving directly from the middle block.
  2536. void InnerLoopVectorizer::fixupIVUsers(PHINode *OrigPhi,
  2537. const InductionDescriptor &II,
  2538. Value *CountRoundDown, Value *EndValue,
  2539. BasicBlock *MiddleBlock) {
  2540. // There are two kinds of external IV usages - those that use the value
  2541. // computed in the last iteration (the PHI) and those that use the penultimate
  2542. // value (the value that feeds into the phi from the loop latch).
  2543. // We allow both, but they, obviously, have different values.
  2544. assert(OrigLoop->getExitBlock() && "Expected a single exit block");
  2545. DenseMap<Value *, Value *> MissingVals;
  2546. // An external user of the last iteration's value should see the value that
  2547. // the remainder loop uses to initialize its own IV.
  2548. Value *PostInc = OrigPhi->getIncomingValueForBlock(OrigLoop->getLoopLatch());
  2549. for (User *U : PostInc->users()) {
  2550. Instruction *UI = cast<Instruction>(U);
  2551. if (!OrigLoop->contains(UI)) {
  2552. assert(isa<PHINode>(UI) && "Expected LCSSA form");
  2553. MissingVals[UI] = EndValue;
  2554. }
  2555. }
  2556. // An external user of the penultimate value need to see EndValue - Step.
  2557. // The simplest way to get this is to recompute it from the constituent SCEVs,
  2558. // that is Start + (Step * (CRD - 1)).
  2559. for (User *U : OrigPhi->users()) {
  2560. auto *UI = cast<Instruction>(U);
  2561. if (!OrigLoop->contains(UI)) {
  2562. const DataLayout &DL =
  2563. OrigLoop->getHeader()->getModule()->getDataLayout();
  2564. assert(isa<PHINode>(UI) && "Expected LCSSA form");
  2565. IRBuilder<> B(MiddleBlock->getTerminator());
  2566. Value *CountMinusOne = B.CreateSub(
  2567. CountRoundDown, ConstantInt::get(CountRoundDown->getType(), 1));
  2568. Value *CMO =
  2569. !II.getStep()->getType()->isIntegerTy()
  2570. ? B.CreateCast(Instruction::SIToFP, CountMinusOne,
  2571. II.getStep()->getType())
  2572. : B.CreateSExtOrTrunc(CountMinusOne, II.getStep()->getType());
  2573. CMO->setName("cast.cmo");
  2574. Value *Escape = II.transform(B, CMO, PSE.getSE(), DL);
  2575. Escape->setName("ind.escape");
  2576. MissingVals[UI] = Escape;
  2577. }
  2578. }
  2579. for (auto &I : MissingVals) {
  2580. PHINode *PHI = cast<PHINode>(I.first);
  2581. // One corner case we have to handle is two IVs "chasing" each-other,
  2582. // that is %IV2 = phi [...], [ %IV1, %latch ]
  2583. // In this case, if IV1 has an external use, we need to avoid adding both
  2584. // "last value of IV1" and "penultimate value of IV2". So, verify that we
  2585. // don't already have an incoming value for the middle block.
  2586. if (PHI->getBasicBlockIndex(MiddleBlock) == -1)
  2587. PHI->addIncoming(I.second, MiddleBlock);
  2588. }
  2589. }
  2590. namespace {
  2591. struct CSEDenseMapInfo {
  2592. static bool canHandle(const Instruction *I) {
  2593. return isa<InsertElementInst>(I) || isa<ExtractElementInst>(I) ||
  2594. isa<ShuffleVectorInst>(I) || isa<GetElementPtrInst>(I);
  2595. }
  2596. static inline Instruction *getEmptyKey() {
  2597. return DenseMapInfo<Instruction *>::getEmptyKey();
  2598. }
  2599. static inline Instruction *getTombstoneKey() {
  2600. return DenseMapInfo<Instruction *>::getTombstoneKey();
  2601. }
  2602. static unsigned getHashValue(const Instruction *I) {
  2603. assert(canHandle(I) && "Unknown instruction!");
  2604. return hash_combine(I->getOpcode(), hash_combine_range(I->value_op_begin(),
  2605. I->value_op_end()));
  2606. }
  2607. static bool isEqual(const Instruction *LHS, const Instruction *RHS) {
  2608. if (LHS == getEmptyKey() || RHS == getEmptyKey() ||
  2609. LHS == getTombstoneKey() || RHS == getTombstoneKey())
  2610. return LHS == RHS;
  2611. return LHS->isIdenticalTo(RHS);
  2612. }
  2613. };
  2614. } // end anonymous namespace
  2615. ///Perform cse of induction variable instructions.
  2616. static void cse(BasicBlock *BB) {
  2617. // Perform simple cse.
  2618. SmallDenseMap<Instruction *, Instruction *, 4, CSEDenseMapInfo> CSEMap;
  2619. for (BasicBlock::iterator I = BB->begin(), E = BB->end(); I != E;) {
  2620. Instruction *In = &*I++;
  2621. if (!CSEDenseMapInfo::canHandle(In))
  2622. continue;
  2623. // Check if we can replace this instruction with any of the
  2624. // visited instructions.
  2625. if (Instruction *V = CSEMap.lookup(In)) {
  2626. In->replaceAllUsesWith(V);
  2627. In->eraseFromParent();
  2628. continue;
  2629. }
  2630. CSEMap[In] = In;
  2631. }
  2632. }
  2633. /// Estimate the overhead of scalarizing an instruction. This is a
  2634. /// convenience wrapper for the type-based getScalarizationOverhead API.
  2635. static unsigned getScalarizationOverhead(Instruction *I, unsigned VF,
  2636. const TargetTransformInfo &TTI) {
  2637. if (VF == 1)
  2638. return 0;
  2639. unsigned Cost = 0;
  2640. Type *RetTy = ToVectorTy(I->getType(), VF);
  2641. if (!RetTy->isVoidTy() &&
  2642. (!isa<LoadInst>(I) ||
  2643. !TTI.supportsEfficientVectorElementLoadStore()))
  2644. Cost += TTI.getScalarizationOverhead(RetTy, true, false);
  2645. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  2646. SmallVector<const Value *, 4> Operands(CI->arg_operands());
  2647. Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
  2648. }
  2649. else if (!isa<StoreInst>(I) ||
  2650. !TTI.supportsEfficientVectorElementLoadStore()) {
  2651. SmallVector<const Value *, 4> Operands(I->operand_values());
  2652. Cost += TTI.getOperandsScalarizationOverhead(Operands, VF);
  2653. }
  2654. return Cost;
  2655. }
  2656. // Estimate cost of a call instruction CI if it were vectorized with factor VF.
  2657. // Return the cost of the instruction, including scalarization overhead if it's
  2658. // needed. The flag NeedToScalarize shows if the call needs to be scalarized -
  2659. // i.e. either vector version isn't available, or is too expensive.
  2660. static unsigned getVectorCallCost(CallInst *CI, unsigned VF,
  2661. const TargetTransformInfo &TTI,
  2662. const TargetLibraryInfo *TLI,
  2663. bool &NeedToScalarize) {
  2664. Function *F = CI->getCalledFunction();
  2665. StringRef FnName = CI->getCalledFunction()->getName();
  2666. Type *ScalarRetTy = CI->getType();
  2667. SmallVector<Type *, 4> Tys, ScalarTys;
  2668. for (auto &ArgOp : CI->arg_operands())
  2669. ScalarTys.push_back(ArgOp->getType());
  2670. // Estimate cost of scalarized vector call. The source operands are assumed
  2671. // to be vectors, so we need to extract individual elements from there,
  2672. // execute VF scalar calls, and then gather the result into the vector return
  2673. // value.
  2674. unsigned ScalarCallCost = TTI.getCallInstrCost(F, ScalarRetTy, ScalarTys);
  2675. if (VF == 1)
  2676. return ScalarCallCost;
  2677. // Compute corresponding vector type for return value and arguments.
  2678. Type *RetTy = ToVectorTy(ScalarRetTy, VF);
  2679. for (Type *ScalarTy : ScalarTys)
  2680. Tys.push_back(ToVectorTy(ScalarTy, VF));
  2681. // Compute costs of unpacking argument values for the scalar calls and
  2682. // packing the return values to a vector.
  2683. unsigned ScalarizationCost = getScalarizationOverhead(CI, VF, TTI);
  2684. unsigned Cost = ScalarCallCost * VF + ScalarizationCost;
  2685. // If we can't emit a vector call for this function, then the currently found
  2686. // cost is the cost we need to return.
  2687. NeedToScalarize = true;
  2688. if (!TLI || !TLI->isFunctionVectorizable(FnName, VF) || CI->isNoBuiltin())
  2689. return Cost;
  2690. // If the corresponding vector cost is cheaper, return its cost.
  2691. unsigned VectorCallCost = TTI.getCallInstrCost(nullptr, RetTy, Tys);
  2692. if (VectorCallCost < Cost) {
  2693. NeedToScalarize = false;
  2694. return VectorCallCost;
  2695. }
  2696. return Cost;
  2697. }
  2698. // Estimate cost of an intrinsic call instruction CI if it were vectorized with
  2699. // factor VF. Return the cost of the instruction, including scalarization
  2700. // overhead if it's needed.
  2701. static unsigned getVectorIntrinsicCost(CallInst *CI, unsigned VF,
  2702. const TargetTransformInfo &TTI,
  2703. const TargetLibraryInfo *TLI) {
  2704. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  2705. assert(ID && "Expected intrinsic call!");
  2706. FastMathFlags FMF;
  2707. if (auto *FPMO = dyn_cast<FPMathOperator>(CI))
  2708. FMF = FPMO->getFastMathFlags();
  2709. SmallVector<Value *, 4> Operands(CI->arg_operands());
  2710. return TTI.getIntrinsicInstrCost(ID, CI->getType(), Operands, FMF, VF);
  2711. }
  2712. static Type *smallestIntegerVectorType(Type *T1, Type *T2) {
  2713. auto *I1 = cast<IntegerType>(T1->getVectorElementType());
  2714. auto *I2 = cast<IntegerType>(T2->getVectorElementType());
  2715. return I1->getBitWidth() < I2->getBitWidth() ? T1 : T2;
  2716. }
  2717. static Type *largestIntegerVectorType(Type *T1, Type *T2) {
  2718. auto *I1 = cast<IntegerType>(T1->getVectorElementType());
  2719. auto *I2 = cast<IntegerType>(T2->getVectorElementType());
  2720. return I1->getBitWidth() > I2->getBitWidth() ? T1 : T2;
  2721. }
  2722. void InnerLoopVectorizer::truncateToMinimalBitwidths() {
  2723. // For every instruction `I` in MinBWs, truncate the operands, create a
  2724. // truncated version of `I` and reextend its result. InstCombine runs
  2725. // later and will remove any ext/trunc pairs.
  2726. SmallPtrSet<Value *, 4> Erased;
  2727. for (const auto &KV : Cost->getMinimalBitwidths()) {
  2728. // If the value wasn't vectorized, we must maintain the original scalar
  2729. // type. The absence of the value from VectorLoopValueMap indicates that it
  2730. // wasn't vectorized.
  2731. if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
  2732. continue;
  2733. for (unsigned Part = 0; Part < UF; ++Part) {
  2734. Value *I = getOrCreateVectorValue(KV.first, Part);
  2735. if (Erased.find(I) != Erased.end() || I->use_empty() ||
  2736. !isa<Instruction>(I))
  2737. continue;
  2738. Type *OriginalTy = I->getType();
  2739. Type *ScalarTruncatedTy =
  2740. IntegerType::get(OriginalTy->getContext(), KV.second);
  2741. Type *TruncatedTy = VectorType::get(ScalarTruncatedTy,
  2742. OriginalTy->getVectorNumElements());
  2743. if (TruncatedTy == OriginalTy)
  2744. continue;
  2745. IRBuilder<> B(cast<Instruction>(I));
  2746. auto ShrinkOperand = [&](Value *V) -> Value * {
  2747. if (auto *ZI = dyn_cast<ZExtInst>(V))
  2748. if (ZI->getSrcTy() == TruncatedTy)
  2749. return ZI->getOperand(0);
  2750. return B.CreateZExtOrTrunc(V, TruncatedTy);
  2751. };
  2752. // The actual instruction modification depends on the instruction type,
  2753. // unfortunately.
  2754. Value *NewI = nullptr;
  2755. if (auto *BO = dyn_cast<BinaryOperator>(I)) {
  2756. NewI = B.CreateBinOp(BO->getOpcode(), ShrinkOperand(BO->getOperand(0)),
  2757. ShrinkOperand(BO->getOperand(1)));
  2758. // Any wrapping introduced by shrinking this operation shouldn't be
  2759. // considered undefined behavior. So, we can't unconditionally copy
  2760. // arithmetic wrapping flags to NewI.
  2761. cast<BinaryOperator>(NewI)->copyIRFlags(I, /*IncludeWrapFlags=*/false);
  2762. } else if (auto *CI = dyn_cast<ICmpInst>(I)) {
  2763. NewI =
  2764. B.CreateICmp(CI->getPredicate(), ShrinkOperand(CI->getOperand(0)),
  2765. ShrinkOperand(CI->getOperand(1)));
  2766. } else if (auto *SI = dyn_cast<SelectInst>(I)) {
  2767. NewI = B.CreateSelect(SI->getCondition(),
  2768. ShrinkOperand(SI->getTrueValue()),
  2769. ShrinkOperand(SI->getFalseValue()));
  2770. } else if (auto *CI = dyn_cast<CastInst>(I)) {
  2771. switch (CI->getOpcode()) {
  2772. default:
  2773. llvm_unreachable("Unhandled cast!");
  2774. case Instruction::Trunc:
  2775. NewI = ShrinkOperand(CI->getOperand(0));
  2776. break;
  2777. case Instruction::SExt:
  2778. NewI = B.CreateSExtOrTrunc(
  2779. CI->getOperand(0),
  2780. smallestIntegerVectorType(OriginalTy, TruncatedTy));
  2781. break;
  2782. case Instruction::ZExt:
  2783. NewI = B.CreateZExtOrTrunc(
  2784. CI->getOperand(0),
  2785. smallestIntegerVectorType(OriginalTy, TruncatedTy));
  2786. break;
  2787. }
  2788. } else if (auto *SI = dyn_cast<ShuffleVectorInst>(I)) {
  2789. auto Elements0 = SI->getOperand(0)->getType()->getVectorNumElements();
  2790. auto *O0 = B.CreateZExtOrTrunc(
  2791. SI->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements0));
  2792. auto Elements1 = SI->getOperand(1)->getType()->getVectorNumElements();
  2793. auto *O1 = B.CreateZExtOrTrunc(
  2794. SI->getOperand(1), VectorType::get(ScalarTruncatedTy, Elements1));
  2795. NewI = B.CreateShuffleVector(O0, O1, SI->getMask());
  2796. } else if (isa<LoadInst>(I) || isa<PHINode>(I)) {
  2797. // Don't do anything with the operands, just extend the result.
  2798. continue;
  2799. } else if (auto *IE = dyn_cast<InsertElementInst>(I)) {
  2800. auto Elements = IE->getOperand(0)->getType()->getVectorNumElements();
  2801. auto *O0 = B.CreateZExtOrTrunc(
  2802. IE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
  2803. auto *O1 = B.CreateZExtOrTrunc(IE->getOperand(1), ScalarTruncatedTy);
  2804. NewI = B.CreateInsertElement(O0, O1, IE->getOperand(2));
  2805. } else if (auto *EE = dyn_cast<ExtractElementInst>(I)) {
  2806. auto Elements = EE->getOperand(0)->getType()->getVectorNumElements();
  2807. auto *O0 = B.CreateZExtOrTrunc(
  2808. EE->getOperand(0), VectorType::get(ScalarTruncatedTy, Elements));
  2809. NewI = B.CreateExtractElement(O0, EE->getOperand(2));
  2810. } else {
  2811. // If we don't know what to do, be conservative and don't do anything.
  2812. continue;
  2813. }
  2814. // Lastly, extend the result.
  2815. NewI->takeName(cast<Instruction>(I));
  2816. Value *Res = B.CreateZExtOrTrunc(NewI, OriginalTy);
  2817. I->replaceAllUsesWith(Res);
  2818. cast<Instruction>(I)->eraseFromParent();
  2819. Erased.insert(I);
  2820. VectorLoopValueMap.resetVectorValue(KV.first, Part, Res);
  2821. }
  2822. }
  2823. // We'll have created a bunch of ZExts that are now parentless. Clean up.
  2824. for (const auto &KV : Cost->getMinimalBitwidths()) {
  2825. // If the value wasn't vectorized, we must maintain the original scalar
  2826. // type. The absence of the value from VectorLoopValueMap indicates that it
  2827. // wasn't vectorized.
  2828. if (!VectorLoopValueMap.hasAnyVectorValue(KV.first))
  2829. continue;
  2830. for (unsigned Part = 0; Part < UF; ++Part) {
  2831. Value *I = getOrCreateVectorValue(KV.first, Part);
  2832. ZExtInst *Inst = dyn_cast<ZExtInst>(I);
  2833. if (Inst && Inst->use_empty()) {
  2834. Value *NewI = Inst->getOperand(0);
  2835. Inst->eraseFromParent();
  2836. VectorLoopValueMap.resetVectorValue(KV.first, Part, NewI);
  2837. }
  2838. }
  2839. }
  2840. }
  2841. void InnerLoopVectorizer::fixVectorizedLoop() {
  2842. // Insert truncates and extends for any truncated instructions as hints to
  2843. // InstCombine.
  2844. if (VF > 1)
  2845. truncateToMinimalBitwidths();
  2846. // At this point every instruction in the original loop is widened to a
  2847. // vector form. Now we need to fix the recurrences in the loop. These PHI
  2848. // nodes are currently empty because we did not want to introduce cycles.
  2849. // This is the second stage of vectorizing recurrences.
  2850. fixCrossIterationPHIs();
  2851. // Update the dominator tree.
  2852. //
  2853. // FIXME: After creating the structure of the new loop, the dominator tree is
  2854. // no longer up-to-date, and it remains that way until we update it
  2855. // here. An out-of-date dominator tree is problematic for SCEV,
  2856. // because SCEVExpander uses it to guide code generation. The
  2857. // vectorizer use SCEVExpanders in several places. Instead, we should
  2858. // keep the dominator tree up-to-date as we go.
  2859. updateAnalysis();
  2860. // Fix-up external users of the induction variables.
  2861. for (auto &Entry : *Legal->getInductionVars())
  2862. fixupIVUsers(Entry.first, Entry.second,
  2863. getOrCreateVectorTripCount(LI->getLoopFor(LoopVectorBody)),
  2864. IVEndValues[Entry.first], LoopMiddleBlock);
  2865. fixLCSSAPHIs();
  2866. for (Instruction *PI : PredicatedInstructions)
  2867. sinkScalarOperands(&*PI);
  2868. // Remove redundant induction instructions.
  2869. cse(LoopVectorBody);
  2870. }
  2871. void InnerLoopVectorizer::fixCrossIterationPHIs() {
  2872. // In order to support recurrences we need to be able to vectorize Phi nodes.
  2873. // Phi nodes have cycles, so we need to vectorize them in two stages. This is
  2874. // stage #2: We now need to fix the recurrences by adding incoming edges to
  2875. // the currently empty PHI nodes. At this point every instruction in the
  2876. // original loop is widened to a vector form so we can use them to construct
  2877. // the incoming edges.
  2878. for (PHINode &Phi : OrigLoop->getHeader()->phis()) {
  2879. // Handle first-order recurrences and reductions that need to be fixed.
  2880. if (Legal->isFirstOrderRecurrence(&Phi))
  2881. fixFirstOrderRecurrence(&Phi);
  2882. else if (Legal->isReductionVariable(&Phi))
  2883. fixReduction(&Phi);
  2884. }
  2885. }
  2886. void InnerLoopVectorizer::fixFirstOrderRecurrence(PHINode *Phi) {
  2887. // This is the second phase of vectorizing first-order recurrences. An
  2888. // overview of the transformation is described below. Suppose we have the
  2889. // following loop.
  2890. //
  2891. // for (int i = 0; i < n; ++i)
  2892. // b[i] = a[i] - a[i - 1];
  2893. //
  2894. // There is a first-order recurrence on "a". For this loop, the shorthand
  2895. // scalar IR looks like:
  2896. //
  2897. // scalar.ph:
  2898. // s_init = a[-1]
  2899. // br scalar.body
  2900. //
  2901. // scalar.body:
  2902. // i = phi [0, scalar.ph], [i+1, scalar.body]
  2903. // s1 = phi [s_init, scalar.ph], [s2, scalar.body]
  2904. // s2 = a[i]
  2905. // b[i] = s2 - s1
  2906. // br cond, scalar.body, ...
  2907. //
  2908. // In this example, s1 is a recurrence because it's value depends on the
  2909. // previous iteration. In the first phase of vectorization, we created a
  2910. // temporary value for s1. We now complete the vectorization and produce the
  2911. // shorthand vector IR shown below (for VF = 4, UF = 1).
  2912. //
  2913. // vector.ph:
  2914. // v_init = vector(..., ..., ..., a[-1])
  2915. // br vector.body
  2916. //
  2917. // vector.body
  2918. // i = phi [0, vector.ph], [i+4, vector.body]
  2919. // v1 = phi [v_init, vector.ph], [v2, vector.body]
  2920. // v2 = a[i, i+1, i+2, i+3];
  2921. // v3 = vector(v1(3), v2(0, 1, 2))
  2922. // b[i, i+1, i+2, i+3] = v2 - v3
  2923. // br cond, vector.body, middle.block
  2924. //
  2925. // middle.block:
  2926. // x = v2(3)
  2927. // br scalar.ph
  2928. //
  2929. // scalar.ph:
  2930. // s_init = phi [x, middle.block], [a[-1], otherwise]
  2931. // br scalar.body
  2932. //
  2933. // After execution completes the vector loop, we extract the next value of
  2934. // the recurrence (x) to use as the initial value in the scalar loop.
  2935. // Get the original loop preheader and single loop latch.
  2936. auto *Preheader = OrigLoop->getLoopPreheader();
  2937. auto *Latch = OrigLoop->getLoopLatch();
  2938. // Get the initial and previous values of the scalar recurrence.
  2939. auto *ScalarInit = Phi->getIncomingValueForBlock(Preheader);
  2940. auto *Previous = Phi->getIncomingValueForBlock(Latch);
  2941. // Create a vector from the initial value.
  2942. auto *VectorInit = ScalarInit;
  2943. if (VF > 1) {
  2944. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  2945. VectorInit = Builder.CreateInsertElement(
  2946. UndefValue::get(VectorType::get(VectorInit->getType(), VF)), VectorInit,
  2947. Builder.getInt32(VF - 1), "vector.recur.init");
  2948. }
  2949. // We constructed a temporary phi node in the first phase of vectorization.
  2950. // This phi node will eventually be deleted.
  2951. Builder.SetInsertPoint(
  2952. cast<Instruction>(VectorLoopValueMap.getVectorValue(Phi, 0)));
  2953. // Create a phi node for the new recurrence. The current value will either be
  2954. // the initial value inserted into a vector or loop-varying vector value.
  2955. auto *VecPhi = Builder.CreatePHI(VectorInit->getType(), 2, "vector.recur");
  2956. VecPhi->addIncoming(VectorInit, LoopVectorPreHeader);
  2957. // Get the vectorized previous value of the last part UF - 1. It appears last
  2958. // among all unrolled iterations, due to the order of their construction.
  2959. Value *PreviousLastPart = getOrCreateVectorValue(Previous, UF - 1);
  2960. // Set the insertion point after the previous value if it is an instruction.
  2961. // Note that the previous value may have been constant-folded so it is not
  2962. // guaranteed to be an instruction in the vector loop. Also, if the previous
  2963. // value is a phi node, we should insert after all the phi nodes to avoid
  2964. // breaking basic block verification.
  2965. if (LI->getLoopFor(LoopVectorBody)->isLoopInvariant(PreviousLastPart) ||
  2966. isa<PHINode>(PreviousLastPart))
  2967. Builder.SetInsertPoint(&*LoopVectorBody->getFirstInsertionPt());
  2968. else
  2969. Builder.SetInsertPoint(
  2970. &*++BasicBlock::iterator(cast<Instruction>(PreviousLastPart)));
  2971. // We will construct a vector for the recurrence by combining the values for
  2972. // the current and previous iterations. This is the required shuffle mask.
  2973. SmallVector<Constant *, 8> ShuffleMask(VF);
  2974. ShuffleMask[0] = Builder.getInt32(VF - 1);
  2975. for (unsigned I = 1; I < VF; ++I)
  2976. ShuffleMask[I] = Builder.getInt32(I + VF - 1);
  2977. // The vector from which to take the initial value for the current iteration
  2978. // (actual or unrolled). Initially, this is the vector phi node.
  2979. Value *Incoming = VecPhi;
  2980. // Shuffle the current and previous vector and update the vector parts.
  2981. for (unsigned Part = 0; Part < UF; ++Part) {
  2982. Value *PreviousPart = getOrCreateVectorValue(Previous, Part);
  2983. Value *PhiPart = VectorLoopValueMap.getVectorValue(Phi, Part);
  2984. auto *Shuffle =
  2985. VF > 1 ? Builder.CreateShuffleVector(Incoming, PreviousPart,
  2986. ConstantVector::get(ShuffleMask))
  2987. : Incoming;
  2988. PhiPart->replaceAllUsesWith(Shuffle);
  2989. cast<Instruction>(PhiPart)->eraseFromParent();
  2990. VectorLoopValueMap.resetVectorValue(Phi, Part, Shuffle);
  2991. Incoming = PreviousPart;
  2992. }
  2993. // Fix the latch value of the new recurrence in the vector loop.
  2994. VecPhi->addIncoming(Incoming, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
  2995. // Extract the last vector element in the middle block. This will be the
  2996. // initial value for the recurrence when jumping to the scalar loop.
  2997. auto *ExtractForScalar = Incoming;
  2998. if (VF > 1) {
  2999. Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
  3000. ExtractForScalar = Builder.CreateExtractElement(
  3001. ExtractForScalar, Builder.getInt32(VF - 1), "vector.recur.extract");
  3002. }
  3003. // Extract the second last element in the middle block if the
  3004. // Phi is used outside the loop. We need to extract the phi itself
  3005. // and not the last element (the phi update in the current iteration). This
  3006. // will be the value when jumping to the exit block from the LoopMiddleBlock,
  3007. // when the scalar loop is not run at all.
  3008. Value *ExtractForPhiUsedOutsideLoop = nullptr;
  3009. if (VF > 1)
  3010. ExtractForPhiUsedOutsideLoop = Builder.CreateExtractElement(
  3011. Incoming, Builder.getInt32(VF - 2), "vector.recur.extract.for.phi");
  3012. // When loop is unrolled without vectorizing, initialize
  3013. // ExtractForPhiUsedOutsideLoop with the value just prior to unrolled value of
  3014. // `Incoming`. This is analogous to the vectorized case above: extracting the
  3015. // second last element when VF > 1.
  3016. else if (UF > 1)
  3017. ExtractForPhiUsedOutsideLoop = getOrCreateVectorValue(Previous, UF - 2);
  3018. // Fix the initial value of the original recurrence in the scalar loop.
  3019. Builder.SetInsertPoint(&*LoopScalarPreHeader->begin());
  3020. auto *Start = Builder.CreatePHI(Phi->getType(), 2, "scalar.recur.init");
  3021. for (auto *BB : predecessors(LoopScalarPreHeader)) {
  3022. auto *Incoming = BB == LoopMiddleBlock ? ExtractForScalar : ScalarInit;
  3023. Start->addIncoming(Incoming, BB);
  3024. }
  3025. Phi->setIncomingValue(Phi->getBasicBlockIndex(LoopScalarPreHeader), Start);
  3026. Phi->setName("scalar.recur");
  3027. // Finally, fix users of the recurrence outside the loop. The users will need
  3028. // either the last value of the scalar recurrence or the last value of the
  3029. // vector recurrence we extracted in the middle block. Since the loop is in
  3030. // LCSSA form, we just need to find all the phi nodes for the original scalar
  3031. // recurrence in the exit block, and then add an edge for the middle block.
  3032. for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
  3033. if (LCSSAPhi.getIncomingValue(0) == Phi) {
  3034. LCSSAPhi.addIncoming(ExtractForPhiUsedOutsideLoop, LoopMiddleBlock);
  3035. }
  3036. }
  3037. }
  3038. void InnerLoopVectorizer::fixReduction(PHINode *Phi) {
  3039. Constant *Zero = Builder.getInt32(0);
  3040. // Get it's reduction variable descriptor.
  3041. assert(Legal->isReductionVariable(Phi) &&
  3042. "Unable to find the reduction variable");
  3043. RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[Phi];
  3044. RecurrenceDescriptor::RecurrenceKind RK = RdxDesc.getRecurrenceKind();
  3045. TrackingVH<Value> ReductionStartValue = RdxDesc.getRecurrenceStartValue();
  3046. Instruction *LoopExitInst = RdxDesc.getLoopExitInstr();
  3047. RecurrenceDescriptor::MinMaxRecurrenceKind MinMaxKind =
  3048. RdxDesc.getMinMaxRecurrenceKind();
  3049. setDebugLocFromInst(Builder, ReductionStartValue);
  3050. // We need to generate a reduction vector from the incoming scalar.
  3051. // To do so, we need to generate the 'identity' vector and override
  3052. // one of the elements with the incoming scalar reduction. We need
  3053. // to do it in the vector-loop preheader.
  3054. Builder.SetInsertPoint(LoopVectorPreHeader->getTerminator());
  3055. // This is the vector-clone of the value that leaves the loop.
  3056. Type *VecTy = getOrCreateVectorValue(LoopExitInst, 0)->getType();
  3057. // Find the reduction identity variable. Zero for addition, or, xor,
  3058. // one for multiplication, -1 for And.
  3059. Value *Identity;
  3060. Value *VectorStart;
  3061. if (RK == RecurrenceDescriptor::RK_IntegerMinMax ||
  3062. RK == RecurrenceDescriptor::RK_FloatMinMax) {
  3063. // MinMax reduction have the start value as their identify.
  3064. if (VF == 1) {
  3065. VectorStart = Identity = ReductionStartValue;
  3066. } else {
  3067. VectorStart = Identity =
  3068. Builder.CreateVectorSplat(VF, ReductionStartValue, "minmax.ident");
  3069. }
  3070. } else {
  3071. // Handle other reduction kinds:
  3072. Constant *Iden = RecurrenceDescriptor::getRecurrenceIdentity(
  3073. RK, VecTy->getScalarType());
  3074. if (VF == 1) {
  3075. Identity = Iden;
  3076. // This vector is the Identity vector where the first element is the
  3077. // incoming scalar reduction.
  3078. VectorStart = ReductionStartValue;
  3079. } else {
  3080. Identity = ConstantVector::getSplat(VF, Iden);
  3081. // This vector is the Identity vector where the first element is the
  3082. // incoming scalar reduction.
  3083. VectorStart =
  3084. Builder.CreateInsertElement(Identity, ReductionStartValue, Zero);
  3085. }
  3086. }
  3087. // Fix the vector-loop phi.
  3088. // Reductions do not have to start at zero. They can start with
  3089. // any loop invariant values.
  3090. BasicBlock *Latch = OrigLoop->getLoopLatch();
  3091. Value *LoopVal = Phi->getIncomingValueForBlock(Latch);
  3092. for (unsigned Part = 0; Part < UF; ++Part) {
  3093. Value *VecRdxPhi = getOrCreateVectorValue(Phi, Part);
  3094. Value *Val = getOrCreateVectorValue(LoopVal, Part);
  3095. // Make sure to add the reduction stat value only to the
  3096. // first unroll part.
  3097. Value *StartVal = (Part == 0) ? VectorStart : Identity;
  3098. cast<PHINode>(VecRdxPhi)->addIncoming(StartVal, LoopVectorPreHeader);
  3099. cast<PHINode>(VecRdxPhi)
  3100. ->addIncoming(Val, LI->getLoopFor(LoopVectorBody)->getLoopLatch());
  3101. }
  3102. // Before each round, move the insertion point right between
  3103. // the PHIs and the values we are going to write.
  3104. // This allows us to write both PHINodes and the extractelement
  3105. // instructions.
  3106. Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
  3107. setDebugLocFromInst(Builder, LoopExitInst);
  3108. // If the vector reduction can be performed in a smaller type, we truncate
  3109. // then extend the loop exit value to enable InstCombine to evaluate the
  3110. // entire expression in the smaller type.
  3111. if (VF > 1 && Phi->getType() != RdxDesc.getRecurrenceType()) {
  3112. Type *RdxVecTy = VectorType::get(RdxDesc.getRecurrenceType(), VF);
  3113. Builder.SetInsertPoint(
  3114. LI->getLoopFor(LoopVectorBody)->getLoopLatch()->getTerminator());
  3115. VectorParts RdxParts(UF);
  3116. for (unsigned Part = 0; Part < UF; ++Part) {
  3117. RdxParts[Part] = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
  3118. Value *Trunc = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
  3119. Value *Extnd = RdxDesc.isSigned() ? Builder.CreateSExt(Trunc, VecTy)
  3120. : Builder.CreateZExt(Trunc, VecTy);
  3121. for (Value::user_iterator UI = RdxParts[Part]->user_begin();
  3122. UI != RdxParts[Part]->user_end();)
  3123. if (*UI != Trunc) {
  3124. (*UI++)->replaceUsesOfWith(RdxParts[Part], Extnd);
  3125. RdxParts[Part] = Extnd;
  3126. } else {
  3127. ++UI;
  3128. }
  3129. }
  3130. Builder.SetInsertPoint(&*LoopMiddleBlock->getFirstInsertionPt());
  3131. for (unsigned Part = 0; Part < UF; ++Part) {
  3132. RdxParts[Part] = Builder.CreateTrunc(RdxParts[Part], RdxVecTy);
  3133. VectorLoopValueMap.resetVectorValue(LoopExitInst, Part, RdxParts[Part]);
  3134. }
  3135. }
  3136. // Reduce all of the unrolled parts into a single vector.
  3137. Value *ReducedPartRdx = VectorLoopValueMap.getVectorValue(LoopExitInst, 0);
  3138. unsigned Op = RecurrenceDescriptor::getRecurrenceBinOp(RK);
  3139. setDebugLocFromInst(Builder, ReducedPartRdx);
  3140. for (unsigned Part = 1; Part < UF; ++Part) {
  3141. Value *RdxPart = VectorLoopValueMap.getVectorValue(LoopExitInst, Part);
  3142. if (Op != Instruction::ICmp && Op != Instruction::FCmp)
  3143. // Floating point operations had to be 'fast' to enable the reduction.
  3144. ReducedPartRdx = addFastMathFlag(
  3145. Builder.CreateBinOp((Instruction::BinaryOps)Op, RdxPart,
  3146. ReducedPartRdx, "bin.rdx"));
  3147. else
  3148. ReducedPartRdx = RecurrenceDescriptor::createMinMaxOp(
  3149. Builder, MinMaxKind, ReducedPartRdx, RdxPart);
  3150. }
  3151. if (VF > 1) {
  3152. bool NoNaN = Legal->hasFunNoNaNAttr();
  3153. ReducedPartRdx =
  3154. createTargetReduction(Builder, TTI, RdxDesc, ReducedPartRdx, NoNaN);
  3155. // If the reduction can be performed in a smaller type, we need to extend
  3156. // the reduction to the wider type before we branch to the original loop.
  3157. if (Phi->getType() != RdxDesc.getRecurrenceType())
  3158. ReducedPartRdx =
  3159. RdxDesc.isSigned()
  3160. ? Builder.CreateSExt(ReducedPartRdx, Phi->getType())
  3161. : Builder.CreateZExt(ReducedPartRdx, Phi->getType());
  3162. }
  3163. // Create a phi node that merges control-flow from the backedge-taken check
  3164. // block and the middle block.
  3165. PHINode *BCBlockPhi = PHINode::Create(Phi->getType(), 2, "bc.merge.rdx",
  3166. LoopScalarPreHeader->getTerminator());
  3167. for (unsigned I = 0, E = LoopBypassBlocks.size(); I != E; ++I)
  3168. BCBlockPhi->addIncoming(ReductionStartValue, LoopBypassBlocks[I]);
  3169. BCBlockPhi->addIncoming(ReducedPartRdx, LoopMiddleBlock);
  3170. // Now, we need to fix the users of the reduction variable
  3171. // inside and outside of the scalar remainder loop.
  3172. // We know that the loop is in LCSSA form. We need to update the
  3173. // PHI nodes in the exit blocks.
  3174. for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
  3175. // All PHINodes need to have a single entry edge, or two if
  3176. // we already fixed them.
  3177. assert(LCSSAPhi.getNumIncomingValues() < 3 && "Invalid LCSSA PHI");
  3178. // We found a reduction value exit-PHI. Update it with the
  3179. // incoming bypass edge.
  3180. if (LCSSAPhi.getIncomingValue(0) == LoopExitInst)
  3181. LCSSAPhi.addIncoming(ReducedPartRdx, LoopMiddleBlock);
  3182. } // end of the LCSSA phi scan.
  3183. // Fix the scalar loop reduction variable with the incoming reduction sum
  3184. // from the vector body and from the backedge value.
  3185. int IncomingEdgeBlockIdx =
  3186. Phi->getBasicBlockIndex(OrigLoop->getLoopLatch());
  3187. assert(IncomingEdgeBlockIdx >= 0 && "Invalid block index");
  3188. // Pick the other block.
  3189. int SelfEdgeBlockIdx = (IncomingEdgeBlockIdx ? 0 : 1);
  3190. Phi->setIncomingValue(SelfEdgeBlockIdx, BCBlockPhi);
  3191. Phi->setIncomingValue(IncomingEdgeBlockIdx, LoopExitInst);
  3192. }
  3193. void InnerLoopVectorizer::fixLCSSAPHIs() {
  3194. for (PHINode &LCSSAPhi : LoopExitBlock->phis()) {
  3195. if (LCSSAPhi.getNumIncomingValues() == 1) {
  3196. auto *IncomingValue = LCSSAPhi.getIncomingValue(0);
  3197. // Non-instruction incoming values will have only one value.
  3198. unsigned LastLane = 0;
  3199. if (isa<Instruction>(IncomingValue))
  3200. LastLane = Cost->isUniformAfterVectorization(
  3201. cast<Instruction>(IncomingValue), VF)
  3202. ? 0
  3203. : VF - 1;
  3204. // Can be a loop invariant incoming value or the last scalar value to be
  3205. // extracted from the vectorized loop.
  3206. Builder.SetInsertPoint(LoopMiddleBlock->getTerminator());
  3207. Value *lastIncomingValue =
  3208. getOrCreateScalarValue(IncomingValue, { UF - 1, LastLane });
  3209. LCSSAPhi.addIncoming(lastIncomingValue, LoopMiddleBlock);
  3210. }
  3211. }
  3212. }
  3213. void InnerLoopVectorizer::sinkScalarOperands(Instruction *PredInst) {
  3214. // The basic block and loop containing the predicated instruction.
  3215. auto *PredBB = PredInst->getParent();
  3216. auto *VectorLoop = LI->getLoopFor(PredBB);
  3217. // Initialize a worklist with the operands of the predicated instruction.
  3218. SetVector<Value *> Worklist(PredInst->op_begin(), PredInst->op_end());
  3219. // Holds instructions that we need to analyze again. An instruction may be
  3220. // reanalyzed if we don't yet know if we can sink it or not.
  3221. SmallVector<Instruction *, 8> InstsToReanalyze;
  3222. // Returns true if a given use occurs in the predicated block. Phi nodes use
  3223. // their operands in their corresponding predecessor blocks.
  3224. auto isBlockOfUsePredicated = [&](Use &U) -> bool {
  3225. auto *I = cast<Instruction>(U.getUser());
  3226. BasicBlock *BB = I->getParent();
  3227. if (auto *Phi = dyn_cast<PHINode>(I))
  3228. BB = Phi->getIncomingBlock(
  3229. PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
  3230. return BB == PredBB;
  3231. };
  3232. // Iteratively sink the scalarized operands of the predicated instruction
  3233. // into the block we created for it. When an instruction is sunk, it's
  3234. // operands are then added to the worklist. The algorithm ends after one pass
  3235. // through the worklist doesn't sink a single instruction.
  3236. bool Changed;
  3237. do {
  3238. // Add the instructions that need to be reanalyzed to the worklist, and
  3239. // reset the changed indicator.
  3240. Worklist.insert(InstsToReanalyze.begin(), InstsToReanalyze.end());
  3241. InstsToReanalyze.clear();
  3242. Changed = false;
  3243. while (!Worklist.empty()) {
  3244. auto *I = dyn_cast<Instruction>(Worklist.pop_back_val());
  3245. // We can't sink an instruction if it is a phi node, is already in the
  3246. // predicated block, is not in the loop, or may have side effects.
  3247. if (!I || isa<PHINode>(I) || I->getParent() == PredBB ||
  3248. !VectorLoop->contains(I) || I->mayHaveSideEffects())
  3249. continue;
  3250. // It's legal to sink the instruction if all its uses occur in the
  3251. // predicated block. Otherwise, there's nothing to do yet, and we may
  3252. // need to reanalyze the instruction.
  3253. if (!llvm::all_of(I->uses(), isBlockOfUsePredicated)) {
  3254. InstsToReanalyze.push_back(I);
  3255. continue;
  3256. }
  3257. // Move the instruction to the beginning of the predicated block, and add
  3258. // it's operands to the worklist.
  3259. I->moveBefore(&*PredBB->getFirstInsertionPt());
  3260. Worklist.insert(I->op_begin(), I->op_end());
  3261. // The sinking may have enabled other instructions to be sunk, so we will
  3262. // need to iterate.
  3263. Changed = true;
  3264. }
  3265. } while (Changed);
  3266. }
  3267. void InnerLoopVectorizer::widenPHIInstruction(Instruction *PN, unsigned UF,
  3268. unsigned VF) {
  3269. assert(PN->getParent() == OrigLoop->getHeader() &&
  3270. "Non-header phis should have been handled elsewhere");
  3271. PHINode *P = cast<PHINode>(PN);
  3272. // In order to support recurrences we need to be able to vectorize Phi nodes.
  3273. // Phi nodes have cycles, so we need to vectorize them in two stages. This is
  3274. // stage #1: We create a new vector PHI node with no incoming edges. We'll use
  3275. // this value when we vectorize all of the instructions that use the PHI.
  3276. if (Legal->isReductionVariable(P) || Legal->isFirstOrderRecurrence(P)) {
  3277. for (unsigned Part = 0; Part < UF; ++Part) {
  3278. // This is phase one of vectorizing PHIs.
  3279. Type *VecTy =
  3280. (VF == 1) ? PN->getType() : VectorType::get(PN->getType(), VF);
  3281. Value *EntryPart = PHINode::Create(
  3282. VecTy, 2, "vec.phi", &*LoopVectorBody->getFirstInsertionPt());
  3283. VectorLoopValueMap.setVectorValue(P, Part, EntryPart);
  3284. }
  3285. return;
  3286. }
  3287. setDebugLocFromInst(Builder, P);
  3288. // This PHINode must be an induction variable.
  3289. // Make sure that we know about it.
  3290. assert(Legal->getInductionVars()->count(P) && "Not an induction variable");
  3291. InductionDescriptor II = Legal->getInductionVars()->lookup(P);
  3292. const DataLayout &DL = OrigLoop->getHeader()->getModule()->getDataLayout();
  3293. // FIXME: The newly created binary instructions should contain nsw/nuw flags,
  3294. // which can be found from the original scalar operations.
  3295. switch (II.getKind()) {
  3296. case InductionDescriptor::IK_NoInduction:
  3297. llvm_unreachable("Unknown induction");
  3298. case InductionDescriptor::IK_IntInduction:
  3299. case InductionDescriptor::IK_FpInduction:
  3300. llvm_unreachable("Integer/fp induction is handled elsewhere.");
  3301. case InductionDescriptor::IK_PtrInduction: {
  3302. // Handle the pointer induction variable case.
  3303. assert(P->getType()->isPointerTy() && "Unexpected type.");
  3304. // This is the normalized GEP that starts counting at zero.
  3305. Value *PtrInd = Induction;
  3306. PtrInd = Builder.CreateSExtOrTrunc(PtrInd, II.getStep()->getType());
  3307. // Determine the number of scalars we need to generate for each unroll
  3308. // iteration. If the instruction is uniform, we only need to generate the
  3309. // first lane. Otherwise, we generate all VF values.
  3310. unsigned Lanes = Cost->isUniformAfterVectorization(P, VF) ? 1 : VF;
  3311. // These are the scalar results. Notice that we don't generate vector GEPs
  3312. // because scalar GEPs result in better code.
  3313. for (unsigned Part = 0; Part < UF; ++Part) {
  3314. for (unsigned Lane = 0; Lane < Lanes; ++Lane) {
  3315. Constant *Idx = ConstantInt::get(PtrInd->getType(), Lane + Part * VF);
  3316. Value *GlobalIdx = Builder.CreateAdd(PtrInd, Idx);
  3317. Value *SclrGep = II.transform(Builder, GlobalIdx, PSE.getSE(), DL);
  3318. SclrGep->setName("next.gep");
  3319. VectorLoopValueMap.setScalarValue(P, {Part, Lane}, SclrGep);
  3320. }
  3321. }
  3322. return;
  3323. }
  3324. }
  3325. }
  3326. /// A helper function for checking whether an integer division-related
  3327. /// instruction may divide by zero (in which case it must be predicated if
  3328. /// executed conditionally in the scalar code).
  3329. /// TODO: It may be worthwhile to generalize and check isKnownNonZero().
  3330. /// Non-zero divisors that are non compile-time constants will not be
  3331. /// converted into multiplication, so we will still end up scalarizing
  3332. /// the division, but can do so w/o predication.
  3333. static bool mayDivideByZero(Instruction &I) {
  3334. assert((I.getOpcode() == Instruction::UDiv ||
  3335. I.getOpcode() == Instruction::SDiv ||
  3336. I.getOpcode() == Instruction::URem ||
  3337. I.getOpcode() == Instruction::SRem) &&
  3338. "Unexpected instruction");
  3339. Value *Divisor = I.getOperand(1);
  3340. auto *CInt = dyn_cast<ConstantInt>(Divisor);
  3341. return !CInt || CInt->isZero();
  3342. }
  3343. void InnerLoopVectorizer::widenInstruction(Instruction &I) {
  3344. switch (I.getOpcode()) {
  3345. case Instruction::Br:
  3346. case Instruction::PHI:
  3347. llvm_unreachable("This instruction is handled by a different recipe.");
  3348. case Instruction::GetElementPtr: {
  3349. // Construct a vector GEP by widening the operands of the scalar GEP as
  3350. // necessary. We mark the vector GEP 'inbounds' if appropriate. A GEP
  3351. // results in a vector of pointers when at least one operand of the GEP
  3352. // is vector-typed. Thus, to keep the representation compact, we only use
  3353. // vector-typed operands for loop-varying values.
  3354. auto *GEP = cast<GetElementPtrInst>(&I);
  3355. if (VF > 1 && OrigLoop->hasLoopInvariantOperands(GEP)) {
  3356. // If we are vectorizing, but the GEP has only loop-invariant operands,
  3357. // the GEP we build (by only using vector-typed operands for
  3358. // loop-varying values) would be a scalar pointer. Thus, to ensure we
  3359. // produce a vector of pointers, we need to either arbitrarily pick an
  3360. // operand to broadcast, or broadcast a clone of the original GEP.
  3361. // Here, we broadcast a clone of the original.
  3362. //
  3363. // TODO: If at some point we decide to scalarize instructions having
  3364. // loop-invariant operands, this special case will no longer be
  3365. // required. We would add the scalarization decision to
  3366. // collectLoopScalars() and teach getVectorValue() to broadcast
  3367. // the lane-zero scalar value.
  3368. auto *Clone = Builder.Insert(GEP->clone());
  3369. for (unsigned Part = 0; Part < UF; ++Part) {
  3370. Value *EntryPart = Builder.CreateVectorSplat(VF, Clone);
  3371. VectorLoopValueMap.setVectorValue(&I, Part, EntryPart);
  3372. addMetadata(EntryPart, GEP);
  3373. }
  3374. } else {
  3375. // If the GEP has at least one loop-varying operand, we are sure to
  3376. // produce a vector of pointers. But if we are only unrolling, we want
  3377. // to produce a scalar GEP for each unroll part. Thus, the GEP we
  3378. // produce with the code below will be scalar (if VF == 1) or vector
  3379. // (otherwise). Note that for the unroll-only case, we still maintain
  3380. // values in the vector mapping with initVector, as we do for other
  3381. // instructions.
  3382. for (unsigned Part = 0; Part < UF; ++Part) {
  3383. // The pointer operand of the new GEP. If it's loop-invariant, we
  3384. // won't broadcast it.
  3385. auto *Ptr =
  3386. OrigLoop->isLoopInvariant(GEP->getPointerOperand())
  3387. ? GEP->getPointerOperand()
  3388. : getOrCreateVectorValue(GEP->getPointerOperand(), Part);
  3389. // Collect all the indices for the new GEP. If any index is
  3390. // loop-invariant, we won't broadcast it.
  3391. SmallVector<Value *, 4> Indices;
  3392. for (auto &U : make_range(GEP->idx_begin(), GEP->idx_end())) {
  3393. if (OrigLoop->isLoopInvariant(U.get()))
  3394. Indices.push_back(U.get());
  3395. else
  3396. Indices.push_back(getOrCreateVectorValue(U.get(), Part));
  3397. }
  3398. // Create the new GEP. Note that this GEP may be a scalar if VF == 1,
  3399. // but it should be a vector, otherwise.
  3400. auto *NewGEP = GEP->isInBounds()
  3401. ? Builder.CreateInBoundsGEP(Ptr, Indices)
  3402. : Builder.CreateGEP(Ptr, Indices);
  3403. assert((VF == 1 || NewGEP->getType()->isVectorTy()) &&
  3404. "NewGEP is not a pointer vector");
  3405. VectorLoopValueMap.setVectorValue(&I, Part, NewGEP);
  3406. addMetadata(NewGEP, GEP);
  3407. }
  3408. }
  3409. break;
  3410. }
  3411. case Instruction::UDiv:
  3412. case Instruction::SDiv:
  3413. case Instruction::SRem:
  3414. case Instruction::URem:
  3415. case Instruction::Add:
  3416. case Instruction::FAdd:
  3417. case Instruction::Sub:
  3418. case Instruction::FSub:
  3419. case Instruction::Mul:
  3420. case Instruction::FMul:
  3421. case Instruction::FDiv:
  3422. case Instruction::FRem:
  3423. case Instruction::Shl:
  3424. case Instruction::LShr:
  3425. case Instruction::AShr:
  3426. case Instruction::And:
  3427. case Instruction::Or:
  3428. case Instruction::Xor: {
  3429. // Just widen binops.
  3430. auto *BinOp = cast<BinaryOperator>(&I);
  3431. setDebugLocFromInst(Builder, BinOp);
  3432. for (unsigned Part = 0; Part < UF; ++Part) {
  3433. Value *A = getOrCreateVectorValue(BinOp->getOperand(0), Part);
  3434. Value *B = getOrCreateVectorValue(BinOp->getOperand(1), Part);
  3435. Value *V = Builder.CreateBinOp(BinOp->getOpcode(), A, B);
  3436. if (BinaryOperator *VecOp = dyn_cast<BinaryOperator>(V))
  3437. VecOp->copyIRFlags(BinOp);
  3438. // Use this vector value for all users of the original instruction.
  3439. VectorLoopValueMap.setVectorValue(&I, Part, V);
  3440. addMetadata(V, BinOp);
  3441. }
  3442. break;
  3443. }
  3444. case Instruction::Select: {
  3445. // Widen selects.
  3446. // If the selector is loop invariant we can create a select
  3447. // instruction with a scalar condition. Otherwise, use vector-select.
  3448. auto *SE = PSE.getSE();
  3449. bool InvariantCond =
  3450. SE->isLoopInvariant(PSE.getSCEV(I.getOperand(0)), OrigLoop);
  3451. setDebugLocFromInst(Builder, &I);
  3452. // The condition can be loop invariant but still defined inside the
  3453. // loop. This means that we can't just use the original 'cond' value.
  3454. // We have to take the 'vectorized' value and pick the first lane.
  3455. // Instcombine will make this a no-op.
  3456. auto *ScalarCond = getOrCreateScalarValue(I.getOperand(0), {0, 0});
  3457. for (unsigned Part = 0; Part < UF; ++Part) {
  3458. Value *Cond = getOrCreateVectorValue(I.getOperand(0), Part);
  3459. Value *Op0 = getOrCreateVectorValue(I.getOperand(1), Part);
  3460. Value *Op1 = getOrCreateVectorValue(I.getOperand(2), Part);
  3461. Value *Sel =
  3462. Builder.CreateSelect(InvariantCond ? ScalarCond : Cond, Op0, Op1);
  3463. VectorLoopValueMap.setVectorValue(&I, Part, Sel);
  3464. addMetadata(Sel, &I);
  3465. }
  3466. break;
  3467. }
  3468. case Instruction::ICmp:
  3469. case Instruction::FCmp: {
  3470. // Widen compares. Generate vector compares.
  3471. bool FCmp = (I.getOpcode() == Instruction::FCmp);
  3472. auto *Cmp = dyn_cast<CmpInst>(&I);
  3473. setDebugLocFromInst(Builder, Cmp);
  3474. for (unsigned Part = 0; Part < UF; ++Part) {
  3475. Value *A = getOrCreateVectorValue(Cmp->getOperand(0), Part);
  3476. Value *B = getOrCreateVectorValue(Cmp->getOperand(1), Part);
  3477. Value *C = nullptr;
  3478. if (FCmp) {
  3479. // Propagate fast math flags.
  3480. IRBuilder<>::FastMathFlagGuard FMFG(Builder);
  3481. Builder.setFastMathFlags(Cmp->getFastMathFlags());
  3482. C = Builder.CreateFCmp(Cmp->getPredicate(), A, B);
  3483. } else {
  3484. C = Builder.CreateICmp(Cmp->getPredicate(), A, B);
  3485. }
  3486. VectorLoopValueMap.setVectorValue(&I, Part, C);
  3487. addMetadata(C, &I);
  3488. }
  3489. break;
  3490. }
  3491. case Instruction::ZExt:
  3492. case Instruction::SExt:
  3493. case Instruction::FPToUI:
  3494. case Instruction::FPToSI:
  3495. case Instruction::FPExt:
  3496. case Instruction::PtrToInt:
  3497. case Instruction::IntToPtr:
  3498. case Instruction::SIToFP:
  3499. case Instruction::UIToFP:
  3500. case Instruction::Trunc:
  3501. case Instruction::FPTrunc:
  3502. case Instruction::BitCast: {
  3503. auto *CI = dyn_cast<CastInst>(&I);
  3504. setDebugLocFromInst(Builder, CI);
  3505. /// Vectorize casts.
  3506. Type *DestTy =
  3507. (VF == 1) ? CI->getType() : VectorType::get(CI->getType(), VF);
  3508. for (unsigned Part = 0; Part < UF; ++Part) {
  3509. Value *A = getOrCreateVectorValue(CI->getOperand(0), Part);
  3510. Value *Cast = Builder.CreateCast(CI->getOpcode(), A, DestTy);
  3511. VectorLoopValueMap.setVectorValue(&I, Part, Cast);
  3512. addMetadata(Cast, &I);
  3513. }
  3514. break;
  3515. }
  3516. case Instruction::Call: {
  3517. // Ignore dbg intrinsics.
  3518. if (isa<DbgInfoIntrinsic>(I))
  3519. break;
  3520. setDebugLocFromInst(Builder, &I);
  3521. Module *M = I.getParent()->getParent()->getParent();
  3522. auto *CI = cast<CallInst>(&I);
  3523. StringRef FnName = CI->getCalledFunction()->getName();
  3524. Function *F = CI->getCalledFunction();
  3525. Type *RetTy = ToVectorTy(CI->getType(), VF);
  3526. SmallVector<Type *, 4> Tys;
  3527. for (Value *ArgOperand : CI->arg_operands())
  3528. Tys.push_back(ToVectorTy(ArgOperand->getType(), VF));
  3529. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  3530. // The flag shows whether we use Intrinsic or a usual Call for vectorized
  3531. // version of the instruction.
  3532. // Is it beneficial to perform intrinsic call compared to lib call?
  3533. bool NeedToScalarize;
  3534. unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
  3535. bool UseVectorIntrinsic =
  3536. ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
  3537. assert((UseVectorIntrinsic || !NeedToScalarize) &&
  3538. "Instruction should be scalarized elsewhere.");
  3539. for (unsigned Part = 0; Part < UF; ++Part) {
  3540. SmallVector<Value *, 4> Args;
  3541. for (unsigned i = 0, ie = CI->getNumArgOperands(); i != ie; ++i) {
  3542. Value *Arg = CI->getArgOperand(i);
  3543. // Some intrinsics have a scalar argument - don't replace it with a
  3544. // vector.
  3545. if (!UseVectorIntrinsic || !hasVectorInstrinsicScalarOpd(ID, i))
  3546. Arg = getOrCreateVectorValue(CI->getArgOperand(i), Part);
  3547. Args.push_back(Arg);
  3548. }
  3549. Function *VectorF;
  3550. if (UseVectorIntrinsic) {
  3551. // Use vector version of the intrinsic.
  3552. Type *TysForDecl[] = {CI->getType()};
  3553. if (VF > 1)
  3554. TysForDecl[0] = VectorType::get(CI->getType()->getScalarType(), VF);
  3555. VectorF = Intrinsic::getDeclaration(M, ID, TysForDecl);
  3556. } else {
  3557. // Use vector version of the library call.
  3558. StringRef VFnName = TLI->getVectorizedFunction(FnName, VF);
  3559. assert(!VFnName.empty() && "Vector function name is empty.");
  3560. VectorF = M->getFunction(VFnName);
  3561. if (!VectorF) {
  3562. // Generate a declaration
  3563. FunctionType *FTy = FunctionType::get(RetTy, Tys, false);
  3564. VectorF =
  3565. Function::Create(FTy, Function::ExternalLinkage, VFnName, M);
  3566. VectorF->copyAttributesFrom(F);
  3567. }
  3568. }
  3569. assert(VectorF && "Can't create vector function.");
  3570. SmallVector<OperandBundleDef, 1> OpBundles;
  3571. CI->getOperandBundlesAsDefs(OpBundles);
  3572. CallInst *V = Builder.CreateCall(VectorF, Args, OpBundles);
  3573. if (isa<FPMathOperator>(V))
  3574. V->copyFastMathFlags(CI);
  3575. VectorLoopValueMap.setVectorValue(&I, Part, V);
  3576. addMetadata(V, &I);
  3577. }
  3578. break;
  3579. }
  3580. default:
  3581. // This instruction is not vectorized by simple widening.
  3582. LLVM_DEBUG(dbgs() << "LV: Found an unhandled instruction: " << I);
  3583. llvm_unreachable("Unhandled instruction!");
  3584. } // end of switch.
  3585. }
  3586. void InnerLoopVectorizer::updateAnalysis() {
  3587. // Forget the original basic block.
  3588. PSE.getSE()->forgetLoop(OrigLoop);
  3589. // Update the dominator tree information.
  3590. assert(DT->properlyDominates(LoopBypassBlocks.front(), LoopExitBlock) &&
  3591. "Entry does not dominate exit.");
  3592. DT->addNewBlock(LoopMiddleBlock,
  3593. LI->getLoopFor(LoopVectorBody)->getLoopLatch());
  3594. DT->addNewBlock(LoopScalarPreHeader, LoopBypassBlocks[0]);
  3595. DT->changeImmediateDominator(LoopScalarBody, LoopScalarPreHeader);
  3596. DT->changeImmediateDominator(LoopExitBlock, LoopBypassBlocks[0]);
  3597. assert(DT->verify(DominatorTree::VerificationLevel::Fast));
  3598. }
  3599. void LoopVectorizationCostModel::collectLoopScalars(unsigned VF) {
  3600. // We should not collect Scalars more than once per VF. Right now, this
  3601. // function is called from collectUniformsAndScalars(), which already does
  3602. // this check. Collecting Scalars for VF=1 does not make any sense.
  3603. assert(VF >= 2 && Scalars.find(VF) == Scalars.end() &&
  3604. "This function should not be visited twice for the same VF");
  3605. SmallSetVector<Instruction *, 8> Worklist;
  3606. // These sets are used to seed the analysis with pointers used by memory
  3607. // accesses that will remain scalar.
  3608. SmallSetVector<Instruction *, 8> ScalarPtrs;
  3609. SmallPtrSet<Instruction *, 8> PossibleNonScalarPtrs;
  3610. // A helper that returns true if the use of Ptr by MemAccess will be scalar.
  3611. // The pointer operands of loads and stores will be scalar as long as the
  3612. // memory access is not a gather or scatter operation. The value operand of a
  3613. // store will remain scalar if the store is scalarized.
  3614. auto isScalarUse = [&](Instruction *MemAccess, Value *Ptr) {
  3615. InstWidening WideningDecision = getWideningDecision(MemAccess, VF);
  3616. assert(WideningDecision != CM_Unknown &&
  3617. "Widening decision should be ready at this moment");
  3618. if (auto *Store = dyn_cast<StoreInst>(MemAccess))
  3619. if (Ptr == Store->getValueOperand())
  3620. return WideningDecision == CM_Scalarize;
  3621. assert(Ptr == getLoadStorePointerOperand(MemAccess) &&
  3622. "Ptr is neither a value or pointer operand");
  3623. return WideningDecision != CM_GatherScatter;
  3624. };
  3625. // A helper that returns true if the given value is a bitcast or
  3626. // getelementptr instruction contained in the loop.
  3627. auto isLoopVaryingBitCastOrGEP = [&](Value *V) {
  3628. return ((isa<BitCastInst>(V) && V->getType()->isPointerTy()) ||
  3629. isa<GetElementPtrInst>(V)) &&
  3630. !TheLoop->isLoopInvariant(V);
  3631. };
  3632. // A helper that evaluates a memory access's use of a pointer. If the use
  3633. // will be a scalar use, and the pointer is only used by memory accesses, we
  3634. // place the pointer in ScalarPtrs. Otherwise, the pointer is placed in
  3635. // PossibleNonScalarPtrs.
  3636. auto evaluatePtrUse = [&](Instruction *MemAccess, Value *Ptr) {
  3637. // We only care about bitcast and getelementptr instructions contained in
  3638. // the loop.
  3639. if (!isLoopVaryingBitCastOrGEP(Ptr))
  3640. return;
  3641. // If the pointer has already been identified as scalar (e.g., if it was
  3642. // also identified as uniform), there's nothing to do.
  3643. auto *I = cast<Instruction>(Ptr);
  3644. if (Worklist.count(I))
  3645. return;
  3646. // If the use of the pointer will be a scalar use, and all users of the
  3647. // pointer are memory accesses, place the pointer in ScalarPtrs. Otherwise,
  3648. // place the pointer in PossibleNonScalarPtrs.
  3649. if (isScalarUse(MemAccess, Ptr) && llvm::all_of(I->users(), [&](User *U) {
  3650. return isa<LoadInst>(U) || isa<StoreInst>(U);
  3651. }))
  3652. ScalarPtrs.insert(I);
  3653. else
  3654. PossibleNonScalarPtrs.insert(I);
  3655. };
  3656. // We seed the scalars analysis with three classes of instructions: (1)
  3657. // instructions marked uniform-after-vectorization, (2) bitcast and
  3658. // getelementptr instructions used by memory accesses requiring a scalar use,
  3659. // and (3) pointer induction variables and their update instructions (we
  3660. // currently only scalarize these).
  3661. //
  3662. // (1) Add to the worklist all instructions that have been identified as
  3663. // uniform-after-vectorization.
  3664. Worklist.insert(Uniforms[VF].begin(), Uniforms[VF].end());
  3665. // (2) Add to the worklist all bitcast and getelementptr instructions used by
  3666. // memory accesses requiring a scalar use. The pointer operands of loads and
  3667. // stores will be scalar as long as the memory accesses is not a gather or
  3668. // scatter operation. The value operand of a store will remain scalar if the
  3669. // store is scalarized.
  3670. for (auto *BB : TheLoop->blocks())
  3671. for (auto &I : *BB) {
  3672. if (auto *Load = dyn_cast<LoadInst>(&I)) {
  3673. evaluatePtrUse(Load, Load->getPointerOperand());
  3674. } else if (auto *Store = dyn_cast<StoreInst>(&I)) {
  3675. evaluatePtrUse(Store, Store->getPointerOperand());
  3676. evaluatePtrUse(Store, Store->getValueOperand());
  3677. }
  3678. }
  3679. for (auto *I : ScalarPtrs)
  3680. if (PossibleNonScalarPtrs.find(I) == PossibleNonScalarPtrs.end()) {
  3681. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *I << "\n");
  3682. Worklist.insert(I);
  3683. }
  3684. // (3) Add to the worklist all pointer induction variables and their update
  3685. // instructions.
  3686. //
  3687. // TODO: Once we are able to vectorize pointer induction variables we should
  3688. // no longer insert them into the worklist here.
  3689. auto *Latch = TheLoop->getLoopLatch();
  3690. for (auto &Induction : *Legal->getInductionVars()) {
  3691. auto *Ind = Induction.first;
  3692. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  3693. if (Induction.second.getKind() != InductionDescriptor::IK_PtrInduction)
  3694. continue;
  3695. Worklist.insert(Ind);
  3696. Worklist.insert(IndUpdate);
  3697. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
  3698. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
  3699. << "\n");
  3700. }
  3701. // Insert the forced scalars.
  3702. // FIXME: Currently widenPHIInstruction() often creates a dead vector
  3703. // induction variable when the PHI user is scalarized.
  3704. auto ForcedScalar = ForcedScalars.find(VF);
  3705. if (ForcedScalar != ForcedScalars.end())
  3706. for (auto *I : ForcedScalar->second)
  3707. Worklist.insert(I);
  3708. // Expand the worklist by looking through any bitcasts and getelementptr
  3709. // instructions we've already identified as scalar. This is similar to the
  3710. // expansion step in collectLoopUniforms(); however, here we're only
  3711. // expanding to include additional bitcasts and getelementptr instructions.
  3712. unsigned Idx = 0;
  3713. while (Idx != Worklist.size()) {
  3714. Instruction *Dst = Worklist[Idx++];
  3715. if (!isLoopVaryingBitCastOrGEP(Dst->getOperand(0)))
  3716. continue;
  3717. auto *Src = cast<Instruction>(Dst->getOperand(0));
  3718. if (llvm::all_of(Src->users(), [&](User *U) -> bool {
  3719. auto *J = cast<Instruction>(U);
  3720. return !TheLoop->contains(J) || Worklist.count(J) ||
  3721. ((isa<LoadInst>(J) || isa<StoreInst>(J)) &&
  3722. isScalarUse(J, Src));
  3723. })) {
  3724. Worklist.insert(Src);
  3725. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Src << "\n");
  3726. }
  3727. }
  3728. // An induction variable will remain scalar if all users of the induction
  3729. // variable and induction variable update remain scalar.
  3730. for (auto &Induction : *Legal->getInductionVars()) {
  3731. auto *Ind = Induction.first;
  3732. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  3733. // We already considered pointer induction variables, so there's no reason
  3734. // to look at their users again.
  3735. //
  3736. // TODO: Once we are able to vectorize pointer induction variables we
  3737. // should no longer skip over them here.
  3738. if (Induction.second.getKind() == InductionDescriptor::IK_PtrInduction)
  3739. continue;
  3740. // Determine if all users of the induction variable are scalar after
  3741. // vectorization.
  3742. auto ScalarInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
  3743. auto *I = cast<Instruction>(U);
  3744. return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I);
  3745. });
  3746. if (!ScalarInd)
  3747. continue;
  3748. // Determine if all users of the induction variable update instruction are
  3749. // scalar after vectorization.
  3750. auto ScalarIndUpdate =
  3751. llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  3752. auto *I = cast<Instruction>(U);
  3753. return I == Ind || !TheLoop->contains(I) || Worklist.count(I);
  3754. });
  3755. if (!ScalarIndUpdate)
  3756. continue;
  3757. // The induction variable and its update instruction will remain scalar.
  3758. Worklist.insert(Ind);
  3759. Worklist.insert(IndUpdate);
  3760. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *Ind << "\n");
  3761. LLVM_DEBUG(dbgs() << "LV: Found scalar instruction: " << *IndUpdate
  3762. << "\n");
  3763. }
  3764. Scalars[VF].insert(Worklist.begin(), Worklist.end());
  3765. }
  3766. bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I) {
  3767. if (!Legal->blockNeedsPredication(I->getParent()))
  3768. return false;
  3769. switch(I->getOpcode()) {
  3770. default:
  3771. break;
  3772. case Instruction::Load:
  3773. case Instruction::Store: {
  3774. if (!Legal->isMaskRequired(I))
  3775. return false;
  3776. auto *Ptr = getLoadStorePointerOperand(I);
  3777. auto *Ty = getMemInstValueType(I);
  3778. return isa<LoadInst>(I) ?
  3779. !(isLegalMaskedLoad(Ty, Ptr) || isLegalMaskedGather(Ty))
  3780. : !(isLegalMaskedStore(Ty, Ptr) || isLegalMaskedScatter(Ty));
  3781. }
  3782. case Instruction::UDiv:
  3783. case Instruction::SDiv:
  3784. case Instruction::SRem:
  3785. case Instruction::URem:
  3786. return mayDivideByZero(*I);
  3787. }
  3788. return false;
  3789. }
  3790. bool LoopVectorizationCostModel::memoryInstructionCanBeWidened(Instruction *I,
  3791. unsigned VF) {
  3792. // Get and ensure we have a valid memory instruction.
  3793. LoadInst *LI = dyn_cast<LoadInst>(I);
  3794. StoreInst *SI = dyn_cast<StoreInst>(I);
  3795. assert((LI || SI) && "Invalid memory instruction");
  3796. auto *Ptr = getLoadStorePointerOperand(I);
  3797. // In order to be widened, the pointer should be consecutive, first of all.
  3798. if (!Legal->isConsecutivePtr(Ptr))
  3799. return false;
  3800. // If the instruction is a store located in a predicated block, it will be
  3801. // scalarized.
  3802. if (isScalarWithPredication(I))
  3803. return false;
  3804. // If the instruction's allocated size doesn't equal it's type size, it
  3805. // requires padding and will be scalarized.
  3806. auto &DL = I->getModule()->getDataLayout();
  3807. auto *ScalarTy = LI ? LI->getType() : SI->getValueOperand()->getType();
  3808. if (hasIrregularType(ScalarTy, DL, VF))
  3809. return false;
  3810. return true;
  3811. }
  3812. void LoopVectorizationCostModel::collectLoopUniforms(unsigned VF) {
  3813. // We should not collect Uniforms more than once per VF. Right now,
  3814. // this function is called from collectUniformsAndScalars(), which
  3815. // already does this check. Collecting Uniforms for VF=1 does not make any
  3816. // sense.
  3817. assert(VF >= 2 && Uniforms.find(VF) == Uniforms.end() &&
  3818. "This function should not be visited twice for the same VF");
  3819. // Visit the list of Uniforms. If we'll not find any uniform value, we'll
  3820. // not analyze again. Uniforms.count(VF) will return 1.
  3821. Uniforms[VF].clear();
  3822. // We now know that the loop is vectorizable!
  3823. // Collect instructions inside the loop that will remain uniform after
  3824. // vectorization.
  3825. // Global values, params and instructions outside of current loop are out of
  3826. // scope.
  3827. auto isOutOfScope = [&](Value *V) -> bool {
  3828. Instruction *I = dyn_cast<Instruction>(V);
  3829. return (!I || !TheLoop->contains(I));
  3830. };
  3831. SetVector<Instruction *> Worklist;
  3832. BasicBlock *Latch = TheLoop->getLoopLatch();
  3833. // Start with the conditional branch. If the branch condition is an
  3834. // instruction contained in the loop that is only used by the branch, it is
  3835. // uniform.
  3836. auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
  3837. if (Cmp && TheLoop->contains(Cmp) && Cmp->hasOneUse()) {
  3838. Worklist.insert(Cmp);
  3839. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *Cmp << "\n");
  3840. }
  3841. // Holds consecutive and consecutive-like pointers. Consecutive-like pointers
  3842. // are pointers that are treated like consecutive pointers during
  3843. // vectorization. The pointer operands of interleaved accesses are an
  3844. // example.
  3845. SmallSetVector<Instruction *, 8> ConsecutiveLikePtrs;
  3846. // Holds pointer operands of instructions that are possibly non-uniform.
  3847. SmallPtrSet<Instruction *, 8> PossibleNonUniformPtrs;
  3848. auto isUniformDecision = [&](Instruction *I, unsigned VF) {
  3849. InstWidening WideningDecision = getWideningDecision(I, VF);
  3850. assert(WideningDecision != CM_Unknown &&
  3851. "Widening decision should be ready at this moment");
  3852. return (WideningDecision == CM_Widen ||
  3853. WideningDecision == CM_Widen_Reverse ||
  3854. WideningDecision == CM_Interleave);
  3855. };
  3856. // Iterate over the instructions in the loop, and collect all
  3857. // consecutive-like pointer operands in ConsecutiveLikePtrs. If it's possible
  3858. // that a consecutive-like pointer operand will be scalarized, we collect it
  3859. // in PossibleNonUniformPtrs instead. We use two sets here because a single
  3860. // getelementptr instruction can be used by both vectorized and scalarized
  3861. // memory instructions. For example, if a loop loads and stores from the same
  3862. // location, but the store is conditional, the store will be scalarized, and
  3863. // the getelementptr won't remain uniform.
  3864. for (auto *BB : TheLoop->blocks())
  3865. for (auto &I : *BB) {
  3866. // If there's no pointer operand, there's nothing to do.
  3867. auto *Ptr = dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
  3868. if (!Ptr)
  3869. continue;
  3870. // True if all users of Ptr are memory accesses that have Ptr as their
  3871. // pointer operand.
  3872. auto UsersAreMemAccesses =
  3873. llvm::all_of(Ptr->users(), [&](User *U) -> bool {
  3874. return getLoadStorePointerOperand(U) == Ptr;
  3875. });
  3876. // Ensure the memory instruction will not be scalarized or used by
  3877. // gather/scatter, making its pointer operand non-uniform. If the pointer
  3878. // operand is used by any instruction other than a memory access, we
  3879. // conservatively assume the pointer operand may be non-uniform.
  3880. if (!UsersAreMemAccesses || !isUniformDecision(&I, VF))
  3881. PossibleNonUniformPtrs.insert(Ptr);
  3882. // If the memory instruction will be vectorized and its pointer operand
  3883. // is consecutive-like, or interleaving - the pointer operand should
  3884. // remain uniform.
  3885. else
  3886. ConsecutiveLikePtrs.insert(Ptr);
  3887. }
  3888. // Add to the Worklist all consecutive and consecutive-like pointers that
  3889. // aren't also identified as possibly non-uniform.
  3890. for (auto *V : ConsecutiveLikePtrs)
  3891. if (PossibleNonUniformPtrs.find(V) == PossibleNonUniformPtrs.end()) {
  3892. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *V << "\n");
  3893. Worklist.insert(V);
  3894. }
  3895. // Expand Worklist in topological order: whenever a new instruction
  3896. // is added , its users should be already inside Worklist. It ensures
  3897. // a uniform instruction will only be used by uniform instructions.
  3898. unsigned idx = 0;
  3899. while (idx != Worklist.size()) {
  3900. Instruction *I = Worklist[idx++];
  3901. for (auto OV : I->operand_values()) {
  3902. // isOutOfScope operands cannot be uniform instructions.
  3903. if (isOutOfScope(OV))
  3904. continue;
  3905. // First order recurrence Phi's should typically be considered
  3906. // non-uniform.
  3907. auto *OP = dyn_cast<PHINode>(OV);
  3908. if (OP && Legal->isFirstOrderRecurrence(OP))
  3909. continue;
  3910. // If all the users of the operand are uniform, then add the
  3911. // operand into the uniform worklist.
  3912. auto *OI = cast<Instruction>(OV);
  3913. if (llvm::all_of(OI->users(), [&](User *U) -> bool {
  3914. auto *J = cast<Instruction>(U);
  3915. return Worklist.count(J) ||
  3916. (OI == getLoadStorePointerOperand(J) &&
  3917. isUniformDecision(J, VF));
  3918. })) {
  3919. Worklist.insert(OI);
  3920. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *OI << "\n");
  3921. }
  3922. }
  3923. }
  3924. // Returns true if Ptr is the pointer operand of a memory access instruction
  3925. // I, and I is known to not require scalarization.
  3926. auto isVectorizedMemAccessUse = [&](Instruction *I, Value *Ptr) -> bool {
  3927. return getLoadStorePointerOperand(I) == Ptr && isUniformDecision(I, VF);
  3928. };
  3929. // For an instruction to be added into Worklist above, all its users inside
  3930. // the loop should also be in Worklist. However, this condition cannot be
  3931. // true for phi nodes that form a cyclic dependence. We must process phi
  3932. // nodes separately. An induction variable will remain uniform if all users
  3933. // of the induction variable and induction variable update remain uniform.
  3934. // The code below handles both pointer and non-pointer induction variables.
  3935. for (auto &Induction : *Legal->getInductionVars()) {
  3936. auto *Ind = Induction.first;
  3937. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  3938. // Determine if all users of the induction variable are uniform after
  3939. // vectorization.
  3940. auto UniformInd = llvm::all_of(Ind->users(), [&](User *U) -> bool {
  3941. auto *I = cast<Instruction>(U);
  3942. return I == IndUpdate || !TheLoop->contains(I) || Worklist.count(I) ||
  3943. isVectorizedMemAccessUse(I, Ind);
  3944. });
  3945. if (!UniformInd)
  3946. continue;
  3947. // Determine if all users of the induction variable update instruction are
  3948. // uniform after vectorization.
  3949. auto UniformIndUpdate =
  3950. llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  3951. auto *I = cast<Instruction>(U);
  3952. return I == Ind || !TheLoop->contains(I) || Worklist.count(I) ||
  3953. isVectorizedMemAccessUse(I, IndUpdate);
  3954. });
  3955. if (!UniformIndUpdate)
  3956. continue;
  3957. // The induction variable and its update instruction will remain uniform.
  3958. Worklist.insert(Ind);
  3959. Worklist.insert(IndUpdate);
  3960. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *Ind << "\n");
  3961. LLVM_DEBUG(dbgs() << "LV: Found uniform instruction: " << *IndUpdate
  3962. << "\n");
  3963. }
  3964. Uniforms[VF].insert(Worklist.begin(), Worklist.end());
  3965. }
  3966. void InterleavedAccessInfo::collectConstStrideAccesses(
  3967. MapVector<Instruction *, StrideDescriptor> &AccessStrideInfo,
  3968. const ValueToValueMap &Strides) {
  3969. auto &DL = TheLoop->getHeader()->getModule()->getDataLayout();
  3970. // Since it's desired that the load/store instructions be maintained in
  3971. // "program order" for the interleaved access analysis, we have to visit the
  3972. // blocks in the loop in reverse postorder (i.e., in a topological order).
  3973. // Such an ordering will ensure that any load/store that may be executed
  3974. // before a second load/store will precede the second load/store in
  3975. // AccessStrideInfo.
  3976. LoopBlocksDFS DFS(TheLoop);
  3977. DFS.perform(LI);
  3978. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO()))
  3979. for (auto &I : *BB) {
  3980. auto *LI = dyn_cast<LoadInst>(&I);
  3981. auto *SI = dyn_cast<StoreInst>(&I);
  3982. if (!LI && !SI)
  3983. continue;
  3984. Value *Ptr = getLoadStorePointerOperand(&I);
  3985. // We don't check wrapping here because we don't know yet if Ptr will be
  3986. // part of a full group or a group with gaps. Checking wrapping for all
  3987. // pointers (even those that end up in groups with no gaps) will be overly
  3988. // conservative. For full groups, wrapping should be ok since if we would
  3989. // wrap around the address space we would do a memory access at nullptr
  3990. // even without the transformation. The wrapping checks are therefore
  3991. // deferred until after we've formed the interleaved groups.
  3992. int64_t Stride = getPtrStride(PSE, Ptr, TheLoop, Strides,
  3993. /*Assume=*/true, /*ShouldCheckWrap=*/false);
  3994. const SCEV *Scev = replaceSymbolicStrideSCEV(PSE, Strides, Ptr);
  3995. PointerType *PtrTy = dyn_cast<PointerType>(Ptr->getType());
  3996. uint64_t Size = DL.getTypeAllocSize(PtrTy->getElementType());
  3997. // An alignment of 0 means target ABI alignment.
  3998. unsigned Align = getMemInstAlignment(&I);
  3999. if (!Align)
  4000. Align = DL.getABITypeAlignment(PtrTy->getElementType());
  4001. AccessStrideInfo[&I] = StrideDescriptor(Stride, Scev, Size, Align);
  4002. }
  4003. }
  4004. // Analyze interleaved accesses and collect them into interleaved load and
  4005. // store groups.
  4006. //
  4007. // When generating code for an interleaved load group, we effectively hoist all
  4008. // loads in the group to the location of the first load in program order. When
  4009. // generating code for an interleaved store group, we sink all stores to the
  4010. // location of the last store. This code motion can change the order of load
  4011. // and store instructions and may break dependences.
  4012. //
  4013. // The code generation strategy mentioned above ensures that we won't violate
  4014. // any write-after-read (WAR) dependences.
  4015. //
  4016. // E.g., for the WAR dependence: a = A[i]; // (1)
  4017. // A[i] = b; // (2)
  4018. //
  4019. // The store group of (2) is always inserted at or below (2), and the load
  4020. // group of (1) is always inserted at or above (1). Thus, the instructions will
  4021. // never be reordered. All other dependences are checked to ensure the
  4022. // correctness of the instruction reordering.
  4023. //
  4024. // The algorithm visits all memory accesses in the loop in bottom-up program
  4025. // order. Program order is established by traversing the blocks in the loop in
  4026. // reverse postorder when collecting the accesses.
  4027. //
  4028. // We visit the memory accesses in bottom-up order because it can simplify the
  4029. // construction of store groups in the presence of write-after-write (WAW)
  4030. // dependences.
  4031. //
  4032. // E.g., for the WAW dependence: A[i] = a; // (1)
  4033. // A[i] = b; // (2)
  4034. // A[i + 1] = c; // (3)
  4035. //
  4036. // We will first create a store group with (3) and (2). (1) can't be added to
  4037. // this group because it and (2) are dependent. However, (1) can be grouped
  4038. // with other accesses that may precede it in program order. Note that a
  4039. // bottom-up order does not imply that WAW dependences should not be checked.
  4040. void InterleavedAccessInfo::analyzeInterleaving() {
  4041. LLVM_DEBUG(dbgs() << "LV: Analyzing interleaved accesses...\n");
  4042. const ValueToValueMap &Strides = LAI->getSymbolicStrides();
  4043. // Holds all accesses with a constant stride.
  4044. MapVector<Instruction *, StrideDescriptor> AccessStrideInfo;
  4045. collectConstStrideAccesses(AccessStrideInfo, Strides);
  4046. if (AccessStrideInfo.empty())
  4047. return;
  4048. // Collect the dependences in the loop.
  4049. collectDependences();
  4050. // Holds all interleaved store groups temporarily.
  4051. SmallSetVector<InterleaveGroup *, 4> StoreGroups;
  4052. // Holds all interleaved load groups temporarily.
  4053. SmallSetVector<InterleaveGroup *, 4> LoadGroups;
  4054. // Search in bottom-up program order for pairs of accesses (A and B) that can
  4055. // form interleaved load or store groups. In the algorithm below, access A
  4056. // precedes access B in program order. We initialize a group for B in the
  4057. // outer loop of the algorithm, and then in the inner loop, we attempt to
  4058. // insert each A into B's group if:
  4059. //
  4060. // 1. A and B have the same stride,
  4061. // 2. A and B have the same memory object size, and
  4062. // 3. A belongs in B's group according to its distance from B.
  4063. //
  4064. // Special care is taken to ensure group formation will not break any
  4065. // dependences.
  4066. for (auto BI = AccessStrideInfo.rbegin(), E = AccessStrideInfo.rend();
  4067. BI != E; ++BI) {
  4068. Instruction *B = BI->first;
  4069. StrideDescriptor DesB = BI->second;
  4070. // Initialize a group for B if it has an allowable stride. Even if we don't
  4071. // create a group for B, we continue with the bottom-up algorithm to ensure
  4072. // we don't break any of B's dependences.
  4073. InterleaveGroup *Group = nullptr;
  4074. if (isStrided(DesB.Stride)) {
  4075. Group = getInterleaveGroup(B);
  4076. if (!Group) {
  4077. LLVM_DEBUG(dbgs() << "LV: Creating an interleave group with:" << *B
  4078. << '\n');
  4079. Group = createInterleaveGroup(B, DesB.Stride, DesB.Align);
  4080. }
  4081. if (B->mayWriteToMemory())
  4082. StoreGroups.insert(Group);
  4083. else
  4084. LoadGroups.insert(Group);
  4085. }
  4086. for (auto AI = std::next(BI); AI != E; ++AI) {
  4087. Instruction *A = AI->first;
  4088. StrideDescriptor DesA = AI->second;
  4089. // Our code motion strategy implies that we can't have dependences
  4090. // between accesses in an interleaved group and other accesses located
  4091. // between the first and last member of the group. Note that this also
  4092. // means that a group can't have more than one member at a given offset.
  4093. // The accesses in a group can have dependences with other accesses, but
  4094. // we must ensure we don't extend the boundaries of the group such that
  4095. // we encompass those dependent accesses.
  4096. //
  4097. // For example, assume we have the sequence of accesses shown below in a
  4098. // stride-2 loop:
  4099. //
  4100. // (1, 2) is a group | A[i] = a; // (1)
  4101. // | A[i-1] = b; // (2) |
  4102. // A[i-3] = c; // (3)
  4103. // A[i] = d; // (4) | (2, 4) is not a group
  4104. //
  4105. // Because accesses (2) and (3) are dependent, we can group (2) with (1)
  4106. // but not with (4). If we did, the dependent access (3) would be within
  4107. // the boundaries of the (2, 4) group.
  4108. if (!canReorderMemAccessesForInterleavedGroups(&*AI, &*BI)) {
  4109. // If a dependence exists and A is already in a group, we know that A
  4110. // must be a store since A precedes B and WAR dependences are allowed.
  4111. // Thus, A would be sunk below B. We release A's group to prevent this
  4112. // illegal code motion. A will then be free to form another group with
  4113. // instructions that precede it.
  4114. if (isInterleaved(A)) {
  4115. InterleaveGroup *StoreGroup = getInterleaveGroup(A);
  4116. StoreGroups.remove(StoreGroup);
  4117. releaseGroup(StoreGroup);
  4118. }
  4119. // If a dependence exists and A is not already in a group (or it was
  4120. // and we just released it), B might be hoisted above A (if B is a
  4121. // load) or another store might be sunk below A (if B is a store). In
  4122. // either case, we can't add additional instructions to B's group. B
  4123. // will only form a group with instructions that it precedes.
  4124. break;
  4125. }
  4126. // At this point, we've checked for illegal code motion. If either A or B
  4127. // isn't strided, there's nothing left to do.
  4128. if (!isStrided(DesA.Stride) || !isStrided(DesB.Stride))
  4129. continue;
  4130. // Ignore A if it's already in a group or isn't the same kind of memory
  4131. // operation as B.
  4132. // Note that mayReadFromMemory() isn't mutually exclusive to mayWriteToMemory
  4133. // in the case of atomic loads. We shouldn't see those here, canVectorizeMemory()
  4134. // should have returned false - except for the case we asked for optimization
  4135. // remarks.
  4136. if (isInterleaved(A) || (A->mayReadFromMemory() != B->mayReadFromMemory())
  4137. || (A->mayWriteToMemory() != B->mayWriteToMemory()))
  4138. continue;
  4139. // Check rules 1 and 2. Ignore A if its stride or size is different from
  4140. // that of B.
  4141. if (DesA.Stride != DesB.Stride || DesA.Size != DesB.Size)
  4142. continue;
  4143. // Ignore A if the memory object of A and B don't belong to the same
  4144. // address space
  4145. if (getMemInstAddressSpace(A) != getMemInstAddressSpace(B))
  4146. continue;
  4147. // Calculate the distance from A to B.
  4148. const SCEVConstant *DistToB = dyn_cast<SCEVConstant>(
  4149. PSE.getSE()->getMinusSCEV(DesA.Scev, DesB.Scev));
  4150. if (!DistToB)
  4151. continue;
  4152. int64_t DistanceToB = DistToB->getAPInt().getSExtValue();
  4153. // Check rule 3. Ignore A if its distance to B is not a multiple of the
  4154. // size.
  4155. if (DistanceToB % static_cast<int64_t>(DesB.Size))
  4156. continue;
  4157. // Ignore A if either A or B is in a predicated block. Although we
  4158. // currently prevent group formation for predicated accesses, we may be
  4159. // able to relax this limitation in the future once we handle more
  4160. // complicated blocks.
  4161. if (isPredicated(A->getParent()) || isPredicated(B->getParent()))
  4162. continue;
  4163. // The index of A is the index of B plus A's distance to B in multiples
  4164. // of the size.
  4165. int IndexA =
  4166. Group->getIndex(B) + DistanceToB / static_cast<int64_t>(DesB.Size);
  4167. // Try to insert A into B's group.
  4168. if (Group->insertMember(A, IndexA, DesA.Align)) {
  4169. LLVM_DEBUG(dbgs() << "LV: Inserted:" << *A << '\n'
  4170. << " into the interleave group with" << *B
  4171. << '\n');
  4172. InterleaveGroupMap[A] = Group;
  4173. // Set the first load in program order as the insert position.
  4174. if (A->mayReadFromMemory())
  4175. Group->setInsertPos(A);
  4176. }
  4177. } // Iteration over A accesses.
  4178. } // Iteration over B accesses.
  4179. // Remove interleaved store groups with gaps.
  4180. for (InterleaveGroup *Group : StoreGroups)
  4181. if (Group->getNumMembers() != Group->getFactor()) {
  4182. LLVM_DEBUG(
  4183. dbgs() << "LV: Invalidate candidate interleaved store group due "
  4184. "to gaps.\n");
  4185. releaseGroup(Group);
  4186. }
  4187. // Remove interleaved groups with gaps (currently only loads) whose memory
  4188. // accesses may wrap around. We have to revisit the getPtrStride analysis,
  4189. // this time with ShouldCheckWrap=true, since collectConstStrideAccesses does
  4190. // not check wrapping (see documentation there).
  4191. // FORNOW we use Assume=false;
  4192. // TODO: Change to Assume=true but making sure we don't exceed the threshold
  4193. // of runtime SCEV assumptions checks (thereby potentially failing to
  4194. // vectorize altogether).
  4195. // Additional optional optimizations:
  4196. // TODO: If we are peeling the loop and we know that the first pointer doesn't
  4197. // wrap then we can deduce that all pointers in the group don't wrap.
  4198. // This means that we can forcefully peel the loop in order to only have to
  4199. // check the first pointer for no-wrap. When we'll change to use Assume=true
  4200. // we'll only need at most one runtime check per interleaved group.
  4201. for (InterleaveGroup *Group : LoadGroups) {
  4202. // Case 1: A full group. Can Skip the checks; For full groups, if the wide
  4203. // load would wrap around the address space we would do a memory access at
  4204. // nullptr even without the transformation.
  4205. if (Group->getNumMembers() == Group->getFactor())
  4206. continue;
  4207. // Case 2: If first and last members of the group don't wrap this implies
  4208. // that all the pointers in the group don't wrap.
  4209. // So we check only group member 0 (which is always guaranteed to exist),
  4210. // and group member Factor - 1; If the latter doesn't exist we rely on
  4211. // peeling (if it is a non-reveresed accsess -- see Case 3).
  4212. Value *FirstMemberPtr = getLoadStorePointerOperand(Group->getMember(0));
  4213. if (!getPtrStride(PSE, FirstMemberPtr, TheLoop, Strides, /*Assume=*/false,
  4214. /*ShouldCheckWrap=*/true)) {
  4215. LLVM_DEBUG(
  4216. dbgs() << "LV: Invalidate candidate interleaved group due to "
  4217. "first group member potentially pointer-wrapping.\n");
  4218. releaseGroup(Group);
  4219. continue;
  4220. }
  4221. Instruction *LastMember = Group->getMember(Group->getFactor() - 1);
  4222. if (LastMember) {
  4223. Value *LastMemberPtr = getLoadStorePointerOperand(LastMember);
  4224. if (!getPtrStride(PSE, LastMemberPtr, TheLoop, Strides, /*Assume=*/false,
  4225. /*ShouldCheckWrap=*/true)) {
  4226. LLVM_DEBUG(
  4227. dbgs() << "LV: Invalidate candidate interleaved group due to "
  4228. "last group member potentially pointer-wrapping.\n");
  4229. releaseGroup(Group);
  4230. }
  4231. } else {
  4232. // Case 3: A non-reversed interleaved load group with gaps: We need
  4233. // to execute at least one scalar epilogue iteration. This will ensure
  4234. // we don't speculatively access memory out-of-bounds. We only need
  4235. // to look for a member at index factor - 1, since every group must have
  4236. // a member at index zero.
  4237. if (Group->isReverse()) {
  4238. LLVM_DEBUG(
  4239. dbgs() << "LV: Invalidate candidate interleaved group due to "
  4240. "a reverse access with gaps.\n");
  4241. releaseGroup(Group);
  4242. continue;
  4243. }
  4244. LLVM_DEBUG(
  4245. dbgs() << "LV: Interleaved group requires epilogue iteration.\n");
  4246. RequiresScalarEpilogue = true;
  4247. }
  4248. }
  4249. }
  4250. Optional<unsigned> LoopVectorizationCostModel::computeMaxVF(bool OptForSize) {
  4251. if (Legal->getRuntimePointerChecking()->Need && TTI.hasBranchDivergence()) {
  4252. // TODO: It may by useful to do since it's still likely to be dynamically
  4253. // uniform if the target can skip.
  4254. LLVM_DEBUG(
  4255. dbgs() << "LV: Not inserting runtime ptr check for divergent target");
  4256. ORE->emit(
  4257. createMissedAnalysis("CantVersionLoopWithDivergentTarget")
  4258. << "runtime pointer checks needed. Not enabled for divergent target");
  4259. return None;
  4260. }
  4261. unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
  4262. if (!OptForSize) // Remaining checks deal with scalar loop when OptForSize.
  4263. return computeFeasibleMaxVF(OptForSize, TC);
  4264. if (Legal->getRuntimePointerChecking()->Need) {
  4265. ORE->emit(createMissedAnalysis("CantVersionLoopWithOptForSize")
  4266. << "runtime pointer checks needed. Enable vectorization of this "
  4267. "loop with '#pragma clang loop vectorize(enable)' when "
  4268. "compiling with -Os/-Oz");
  4269. LLVM_DEBUG(
  4270. dbgs()
  4271. << "LV: Aborting. Runtime ptr check is required with -Os/-Oz.\n");
  4272. return None;
  4273. }
  4274. // If we optimize the program for size, avoid creating the tail loop.
  4275. LLVM_DEBUG(dbgs() << "LV: Found trip count: " << TC << '\n');
  4276. // If we don't know the precise trip count, don't try to vectorize.
  4277. if (TC < 2) {
  4278. ORE->emit(
  4279. createMissedAnalysis("UnknownLoopCountComplexCFG")
  4280. << "unable to calculate the loop count due to complex control flow");
  4281. LLVM_DEBUG(
  4282. dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
  4283. return None;
  4284. }
  4285. unsigned MaxVF = computeFeasibleMaxVF(OptForSize, TC);
  4286. if (TC % MaxVF != 0) {
  4287. // If the trip count that we found modulo the vectorization factor is not
  4288. // zero then we require a tail.
  4289. // FIXME: look for a smaller MaxVF that does divide TC rather than give up.
  4290. // FIXME: return None if loop requiresScalarEpilog(<MaxVF>), or look for a
  4291. // smaller MaxVF that does not require a scalar epilog.
  4292. ORE->emit(createMissedAnalysis("NoTailLoopWithOptForSize")
  4293. << "cannot optimize for size and vectorize at the "
  4294. "same time. Enable vectorization of this loop "
  4295. "with '#pragma clang loop vectorize(enable)' "
  4296. "when compiling with -Os/-Oz");
  4297. LLVM_DEBUG(
  4298. dbgs() << "LV: Aborting. A tail loop is required with -Os/-Oz.\n");
  4299. return None;
  4300. }
  4301. return MaxVF;
  4302. }
  4303. unsigned
  4304. LoopVectorizationCostModel::computeFeasibleMaxVF(bool OptForSize,
  4305. unsigned ConstTripCount) {
  4306. MinBWs = computeMinimumValueSizes(TheLoop->getBlocks(), *DB, &TTI);
  4307. unsigned SmallestType, WidestType;
  4308. std::tie(SmallestType, WidestType) = getSmallestAndWidestTypes();
  4309. unsigned WidestRegister = TTI.getRegisterBitWidth(true);
  4310. // Get the maximum safe dependence distance in bits computed by LAA.
  4311. // It is computed by MaxVF * sizeOf(type) * 8, where type is taken from
  4312. // the memory accesses that is most restrictive (involved in the smallest
  4313. // dependence distance).
  4314. unsigned MaxSafeRegisterWidth = Legal->getMaxSafeRegisterWidth();
  4315. WidestRegister = std::min(WidestRegister, MaxSafeRegisterWidth);
  4316. unsigned MaxVectorSize = WidestRegister / WidestType;
  4317. LLVM_DEBUG(dbgs() << "LV: The Smallest and Widest types: " << SmallestType
  4318. << " / " << WidestType << " bits.\n");
  4319. LLVM_DEBUG(dbgs() << "LV: The Widest register safe to use is: "
  4320. << WidestRegister << " bits.\n");
  4321. assert(MaxVectorSize <= 256 && "Did not expect to pack so many elements"
  4322. " into one vector!");
  4323. if (MaxVectorSize == 0) {
  4324. LLVM_DEBUG(dbgs() << "LV: The target has no vector registers.\n");
  4325. MaxVectorSize = 1;
  4326. return MaxVectorSize;
  4327. } else if (ConstTripCount && ConstTripCount < MaxVectorSize &&
  4328. isPowerOf2_32(ConstTripCount)) {
  4329. // We need to clamp the VF to be the ConstTripCount. There is no point in
  4330. // choosing a higher viable VF as done in the loop below.
  4331. LLVM_DEBUG(dbgs() << "LV: Clamping the MaxVF to the constant trip count: "
  4332. << ConstTripCount << "\n");
  4333. MaxVectorSize = ConstTripCount;
  4334. return MaxVectorSize;
  4335. }
  4336. unsigned MaxVF = MaxVectorSize;
  4337. if (TTI.shouldMaximizeVectorBandwidth(OptForSize) ||
  4338. (MaximizeBandwidth && !OptForSize)) {
  4339. // Collect all viable vectorization factors larger than the default MaxVF
  4340. // (i.e. MaxVectorSize).
  4341. SmallVector<unsigned, 8> VFs;
  4342. unsigned NewMaxVectorSize = WidestRegister / SmallestType;
  4343. for (unsigned VS = MaxVectorSize * 2; VS <= NewMaxVectorSize; VS *= 2)
  4344. VFs.push_back(VS);
  4345. // For each VF calculate its register usage.
  4346. auto RUs = calculateRegisterUsage(VFs);
  4347. // Select the largest VF which doesn't require more registers than existing
  4348. // ones.
  4349. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(true);
  4350. for (int i = RUs.size() - 1; i >= 0; --i) {
  4351. if (RUs[i].MaxLocalUsers <= TargetNumRegisters) {
  4352. MaxVF = VFs[i];
  4353. break;
  4354. }
  4355. }
  4356. if (unsigned MinVF = TTI.getMinimumVF(SmallestType)) {
  4357. if (MaxVF < MinVF) {
  4358. LLVM_DEBUG(dbgs() << "LV: Overriding calculated MaxVF(" << MaxVF
  4359. << ") with target's minimum: " << MinVF << '\n');
  4360. MaxVF = MinVF;
  4361. }
  4362. }
  4363. }
  4364. return MaxVF;
  4365. }
  4366. VectorizationFactor
  4367. LoopVectorizationCostModel::selectVectorizationFactor(unsigned MaxVF) {
  4368. float Cost = expectedCost(1).first;
  4369. const float ScalarCost = Cost;
  4370. unsigned Width = 1;
  4371. LLVM_DEBUG(dbgs() << "LV: Scalar loop costs: " << (int)ScalarCost << ".\n");
  4372. bool ForceVectorization = Hints->getForce() == LoopVectorizeHints::FK_Enabled;
  4373. if (ForceVectorization && MaxVF > 1) {
  4374. // Ignore scalar width, because the user explicitly wants vectorization.
  4375. // Initialize cost to max so that VF = 2 is, at least, chosen during cost
  4376. // evaluation.
  4377. Cost = std::numeric_limits<float>::max();
  4378. }
  4379. for (unsigned i = 2; i <= MaxVF; i *= 2) {
  4380. // Notice that the vector loop needs to be executed less times, so
  4381. // we need to divide the cost of the vector loops by the width of
  4382. // the vector elements.
  4383. VectorizationCostTy C = expectedCost(i);
  4384. float VectorCost = C.first / (float)i;
  4385. LLVM_DEBUG(dbgs() << "LV: Vector loop of width " << i
  4386. << " costs: " << (int)VectorCost << ".\n");
  4387. if (!C.second && !ForceVectorization) {
  4388. LLVM_DEBUG(
  4389. dbgs() << "LV: Not considering vector loop of width " << i
  4390. << " because it will not generate any vector instructions.\n");
  4391. continue;
  4392. }
  4393. if (VectorCost < Cost) {
  4394. Cost = VectorCost;
  4395. Width = i;
  4396. }
  4397. }
  4398. if (!EnableCondStoresVectorization && NumPredStores) {
  4399. ORE->emit(createMissedAnalysis("ConditionalStore")
  4400. << "store that is conditionally executed prevents vectorization");
  4401. LLVM_DEBUG(
  4402. dbgs() << "LV: No vectorization. There are conditional stores.\n");
  4403. Width = 1;
  4404. Cost = ScalarCost;
  4405. }
  4406. LLVM_DEBUG(if (ForceVectorization && Width > 1 && Cost >= ScalarCost) dbgs()
  4407. << "LV: Vectorization seems to be not beneficial, "
  4408. << "but was forced by a user.\n");
  4409. LLVM_DEBUG(dbgs() << "LV: Selecting VF: " << Width << ".\n");
  4410. VectorizationFactor Factor = {Width, (unsigned)(Width * Cost)};
  4411. return Factor;
  4412. }
  4413. std::pair<unsigned, unsigned>
  4414. LoopVectorizationCostModel::getSmallestAndWidestTypes() {
  4415. unsigned MinWidth = -1U;
  4416. unsigned MaxWidth = 8;
  4417. const DataLayout &DL = TheFunction->getParent()->getDataLayout();
  4418. // For each block.
  4419. for (BasicBlock *BB : TheLoop->blocks()) {
  4420. // For each instruction in the loop.
  4421. for (Instruction &I : *BB) {
  4422. Type *T = I.getType();
  4423. // Skip ignored values.
  4424. if (ValuesToIgnore.find(&I) != ValuesToIgnore.end())
  4425. continue;
  4426. // Only examine Loads, Stores and PHINodes.
  4427. if (!isa<LoadInst>(I) && !isa<StoreInst>(I) && !isa<PHINode>(I))
  4428. continue;
  4429. // Examine PHI nodes that are reduction variables. Update the type to
  4430. // account for the recurrence type.
  4431. if (auto *PN = dyn_cast<PHINode>(&I)) {
  4432. if (!Legal->isReductionVariable(PN))
  4433. continue;
  4434. RecurrenceDescriptor RdxDesc = (*Legal->getReductionVars())[PN];
  4435. T = RdxDesc.getRecurrenceType();
  4436. }
  4437. // Examine the stored values.
  4438. if (auto *ST = dyn_cast<StoreInst>(&I))
  4439. T = ST->getValueOperand()->getType();
  4440. // Ignore loaded pointer types and stored pointer types that are not
  4441. // vectorizable.
  4442. //
  4443. // FIXME: The check here attempts to predict whether a load or store will
  4444. // be vectorized. We only know this for certain after a VF has
  4445. // been selected. Here, we assume that if an access can be
  4446. // vectorized, it will be. We should also look at extending this
  4447. // optimization to non-pointer types.
  4448. //
  4449. if (T->isPointerTy() && !isConsecutiveLoadOrStore(&I) &&
  4450. !isAccessInterleaved(&I) && !isLegalGatherOrScatter(&I))
  4451. continue;
  4452. MinWidth = std::min(MinWidth,
  4453. (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
  4454. MaxWidth = std::max(MaxWidth,
  4455. (unsigned)DL.getTypeSizeInBits(T->getScalarType()));
  4456. }
  4457. }
  4458. return {MinWidth, MaxWidth};
  4459. }
  4460. unsigned LoopVectorizationCostModel::selectInterleaveCount(bool OptForSize,
  4461. unsigned VF,
  4462. unsigned LoopCost) {
  4463. // -- The interleave heuristics --
  4464. // We interleave the loop in order to expose ILP and reduce the loop overhead.
  4465. // There are many micro-architectural considerations that we can't predict
  4466. // at this level. For example, frontend pressure (on decode or fetch) due to
  4467. // code size, or the number and capabilities of the execution ports.
  4468. //
  4469. // We use the following heuristics to select the interleave count:
  4470. // 1. If the code has reductions, then we interleave to break the cross
  4471. // iteration dependency.
  4472. // 2. If the loop is really small, then we interleave to reduce the loop
  4473. // overhead.
  4474. // 3. We don't interleave if we think that we will spill registers to memory
  4475. // due to the increased register pressure.
  4476. // When we optimize for size, we don't interleave.
  4477. if (OptForSize)
  4478. return 1;
  4479. // We used the distance for the interleave count.
  4480. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4481. return 1;
  4482. // Do not interleave loops with a relatively small trip count.
  4483. unsigned TC = PSE.getSE()->getSmallConstantTripCount(TheLoop);
  4484. if (TC > 1 && TC < TinyTripCountInterleaveThreshold)
  4485. return 1;
  4486. unsigned TargetNumRegisters = TTI.getNumberOfRegisters(VF > 1);
  4487. LLVM_DEBUG(dbgs() << "LV: The target has " << TargetNumRegisters
  4488. << " registers\n");
  4489. if (VF == 1) {
  4490. if (ForceTargetNumScalarRegs.getNumOccurrences() > 0)
  4491. TargetNumRegisters = ForceTargetNumScalarRegs;
  4492. } else {
  4493. if (ForceTargetNumVectorRegs.getNumOccurrences() > 0)
  4494. TargetNumRegisters = ForceTargetNumVectorRegs;
  4495. }
  4496. RegisterUsage R = calculateRegisterUsage({VF})[0];
  4497. // We divide by these constants so assume that we have at least one
  4498. // instruction that uses at least one register.
  4499. R.MaxLocalUsers = std::max(R.MaxLocalUsers, 1U);
  4500. // We calculate the interleave count using the following formula.
  4501. // Subtract the number of loop invariants from the number of available
  4502. // registers. These registers are used by all of the interleaved instances.
  4503. // Next, divide the remaining registers by the number of registers that is
  4504. // required by the loop, in order to estimate how many parallel instances
  4505. // fit without causing spills. All of this is rounded down if necessary to be
  4506. // a power of two. We want power of two interleave count to simplify any
  4507. // addressing operations or alignment considerations.
  4508. unsigned IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs) /
  4509. R.MaxLocalUsers);
  4510. // Don't count the induction variable as interleaved.
  4511. if (EnableIndVarRegisterHeur)
  4512. IC = PowerOf2Floor((TargetNumRegisters - R.LoopInvariantRegs - 1) /
  4513. std::max(1U, (R.MaxLocalUsers - 1)));
  4514. // Clamp the interleave ranges to reasonable counts.
  4515. unsigned MaxInterleaveCount = TTI.getMaxInterleaveFactor(VF);
  4516. // Check if the user has overridden the max.
  4517. if (VF == 1) {
  4518. if (ForceTargetMaxScalarInterleaveFactor.getNumOccurrences() > 0)
  4519. MaxInterleaveCount = ForceTargetMaxScalarInterleaveFactor;
  4520. } else {
  4521. if (ForceTargetMaxVectorInterleaveFactor.getNumOccurrences() > 0)
  4522. MaxInterleaveCount = ForceTargetMaxVectorInterleaveFactor;
  4523. }
  4524. // If we did not calculate the cost for VF (because the user selected the VF)
  4525. // then we calculate the cost of VF here.
  4526. if (LoopCost == 0)
  4527. LoopCost = expectedCost(VF).first;
  4528. // Clamp the calculated IC to be between the 1 and the max interleave count
  4529. // that the target allows.
  4530. if (IC > MaxInterleaveCount)
  4531. IC = MaxInterleaveCount;
  4532. else if (IC < 1)
  4533. IC = 1;
  4534. // Interleave if we vectorized this loop and there is a reduction that could
  4535. // benefit from interleaving.
  4536. if (VF > 1 && !Legal->getReductionVars()->empty()) {
  4537. LLVM_DEBUG(dbgs() << "LV: Interleaving because of reductions.\n");
  4538. return IC;
  4539. }
  4540. // Note that if we've already vectorized the loop we will have done the
  4541. // runtime check and so interleaving won't require further checks.
  4542. bool InterleavingRequiresRuntimePointerCheck =
  4543. (VF == 1 && Legal->getRuntimePointerChecking()->Need);
  4544. // We want to interleave small loops in order to reduce the loop overhead and
  4545. // potentially expose ILP opportunities.
  4546. LLVM_DEBUG(dbgs() << "LV: Loop cost is " << LoopCost << '\n');
  4547. if (!InterleavingRequiresRuntimePointerCheck && LoopCost < SmallLoopCost) {
  4548. // We assume that the cost overhead is 1 and we use the cost model
  4549. // to estimate the cost of the loop and interleave until the cost of the
  4550. // loop overhead is about 5% of the cost of the loop.
  4551. unsigned SmallIC =
  4552. std::min(IC, (unsigned)PowerOf2Floor(SmallLoopCost / LoopCost));
  4553. // Interleave until store/load ports (estimated by max interleave count) are
  4554. // saturated.
  4555. unsigned NumStores = Legal->getNumStores();
  4556. unsigned NumLoads = Legal->getNumLoads();
  4557. unsigned StoresIC = IC / (NumStores ? NumStores : 1);
  4558. unsigned LoadsIC = IC / (NumLoads ? NumLoads : 1);
  4559. // If we have a scalar reduction (vector reductions are already dealt with
  4560. // by this point), we can increase the critical path length if the loop
  4561. // we're interleaving is inside another loop. Limit, by default to 2, so the
  4562. // critical path only gets increased by one reduction operation.
  4563. if (!Legal->getReductionVars()->empty() && TheLoop->getLoopDepth() > 1) {
  4564. unsigned F = static_cast<unsigned>(MaxNestedScalarReductionIC);
  4565. SmallIC = std::min(SmallIC, F);
  4566. StoresIC = std::min(StoresIC, F);
  4567. LoadsIC = std::min(LoadsIC, F);
  4568. }
  4569. if (EnableLoadStoreRuntimeInterleave &&
  4570. std::max(StoresIC, LoadsIC) > SmallIC) {
  4571. LLVM_DEBUG(
  4572. dbgs() << "LV: Interleaving to saturate store or load ports.\n");
  4573. return std::max(StoresIC, LoadsIC);
  4574. }
  4575. LLVM_DEBUG(dbgs() << "LV: Interleaving to reduce branch cost.\n");
  4576. return SmallIC;
  4577. }
  4578. // Interleave if this is a large loop (small loops are already dealt with by
  4579. // this point) that could benefit from interleaving.
  4580. bool HasReductions = !Legal->getReductionVars()->empty();
  4581. if (TTI.enableAggressiveInterleaving(HasReductions)) {
  4582. LLVM_DEBUG(dbgs() << "LV: Interleaving to expose ILP.\n");
  4583. return IC;
  4584. }
  4585. LLVM_DEBUG(dbgs() << "LV: Not Interleaving.\n");
  4586. return 1;
  4587. }
  4588. SmallVector<LoopVectorizationCostModel::RegisterUsage, 8>
  4589. LoopVectorizationCostModel::calculateRegisterUsage(ArrayRef<unsigned> VFs) {
  4590. // This function calculates the register usage by measuring the highest number
  4591. // of values that are alive at a single location. Obviously, this is a very
  4592. // rough estimation. We scan the loop in a topological order in order and
  4593. // assign a number to each instruction. We use RPO to ensure that defs are
  4594. // met before their users. We assume that each instruction that has in-loop
  4595. // users starts an interval. We record every time that an in-loop value is
  4596. // used, so we have a list of the first and last occurrences of each
  4597. // instruction. Next, we transpose this data structure into a multi map that
  4598. // holds the list of intervals that *end* at a specific location. This multi
  4599. // map allows us to perform a linear search. We scan the instructions linearly
  4600. // and record each time that a new interval starts, by placing it in a set.
  4601. // If we find this value in the multi-map then we remove it from the set.
  4602. // The max register usage is the maximum size of the set.
  4603. // We also search for instructions that are defined outside the loop, but are
  4604. // used inside the loop. We need this number separately from the max-interval
  4605. // usage number because when we unroll, loop-invariant values do not take
  4606. // more register.
  4607. LoopBlocksDFS DFS(TheLoop);
  4608. DFS.perform(LI);
  4609. RegisterUsage RU;
  4610. // Each 'key' in the map opens a new interval. The values
  4611. // of the map are the index of the 'last seen' usage of the
  4612. // instruction that is the key.
  4613. using IntervalMap = DenseMap<Instruction *, unsigned>;
  4614. // Maps instruction to its index.
  4615. DenseMap<unsigned, Instruction *> IdxToInstr;
  4616. // Marks the end of each interval.
  4617. IntervalMap EndPoint;
  4618. // Saves the list of instruction indices that are used in the loop.
  4619. SmallPtrSet<Instruction *, 8> Ends;
  4620. // Saves the list of values that are used in the loop but are
  4621. // defined outside the loop, such as arguments and constants.
  4622. SmallPtrSet<Value *, 8> LoopInvariants;
  4623. unsigned Index = 0;
  4624. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
  4625. for (Instruction &I : *BB) {
  4626. IdxToInstr[Index++] = &I;
  4627. // Save the end location of each USE.
  4628. for (Value *U : I.operands()) {
  4629. auto *Instr = dyn_cast<Instruction>(U);
  4630. // Ignore non-instruction values such as arguments, constants, etc.
  4631. if (!Instr)
  4632. continue;
  4633. // If this instruction is outside the loop then record it and continue.
  4634. if (!TheLoop->contains(Instr)) {
  4635. LoopInvariants.insert(Instr);
  4636. continue;
  4637. }
  4638. // Overwrite previous end points.
  4639. EndPoint[Instr] = Index;
  4640. Ends.insert(Instr);
  4641. }
  4642. }
  4643. }
  4644. // Saves the list of intervals that end with the index in 'key'.
  4645. using InstrList = SmallVector<Instruction *, 2>;
  4646. DenseMap<unsigned, InstrList> TransposeEnds;
  4647. // Transpose the EndPoints to a list of values that end at each index.
  4648. for (auto &Interval : EndPoint)
  4649. TransposeEnds[Interval.second].push_back(Interval.first);
  4650. SmallPtrSet<Instruction *, 8> OpenIntervals;
  4651. // Get the size of the widest register.
  4652. unsigned MaxSafeDepDist = -1U;
  4653. if (Legal->getMaxSafeDepDistBytes() != -1U)
  4654. MaxSafeDepDist = Legal->getMaxSafeDepDistBytes() * 8;
  4655. unsigned WidestRegister =
  4656. std::min(TTI.getRegisterBitWidth(true), MaxSafeDepDist);
  4657. const DataLayout &DL = TheFunction->getParent()->getDataLayout();
  4658. SmallVector<RegisterUsage, 8> RUs(VFs.size());
  4659. SmallVector<unsigned, 8> MaxUsages(VFs.size(), 0);
  4660. LLVM_DEBUG(dbgs() << "LV(REG): Calculating max register usage:\n");
  4661. // A lambda that gets the register usage for the given type and VF.
  4662. auto GetRegUsage = [&DL, WidestRegister](Type *Ty, unsigned VF) {
  4663. if (Ty->isTokenTy())
  4664. return 0U;
  4665. unsigned TypeSize = DL.getTypeSizeInBits(Ty->getScalarType());
  4666. return std::max<unsigned>(1, VF * TypeSize / WidestRegister);
  4667. };
  4668. for (unsigned int i = 0; i < Index; ++i) {
  4669. Instruction *I = IdxToInstr[i];
  4670. // Remove all of the instructions that end at this location.
  4671. InstrList &List = TransposeEnds[i];
  4672. for (Instruction *ToRemove : List)
  4673. OpenIntervals.erase(ToRemove);
  4674. // Ignore instructions that are never used within the loop.
  4675. if (Ends.find(I) == Ends.end())
  4676. continue;
  4677. // Skip ignored values.
  4678. if (ValuesToIgnore.find(I) != ValuesToIgnore.end())
  4679. continue;
  4680. // For each VF find the maximum usage of registers.
  4681. for (unsigned j = 0, e = VFs.size(); j < e; ++j) {
  4682. if (VFs[j] == 1) {
  4683. MaxUsages[j] = std::max(MaxUsages[j], OpenIntervals.size());
  4684. continue;
  4685. }
  4686. collectUniformsAndScalars(VFs[j]);
  4687. // Count the number of live intervals.
  4688. unsigned RegUsage = 0;
  4689. for (auto Inst : OpenIntervals) {
  4690. // Skip ignored values for VF > 1.
  4691. if (VecValuesToIgnore.find(Inst) != VecValuesToIgnore.end() ||
  4692. isScalarAfterVectorization(Inst, VFs[j]))
  4693. continue;
  4694. RegUsage += GetRegUsage(Inst->getType(), VFs[j]);
  4695. }
  4696. MaxUsages[j] = std::max(MaxUsages[j], RegUsage);
  4697. }
  4698. LLVM_DEBUG(dbgs() << "LV(REG): At #" << i << " Interval # "
  4699. << OpenIntervals.size() << '\n');
  4700. // Add the current instruction to the list of open intervals.
  4701. OpenIntervals.insert(I);
  4702. }
  4703. for (unsigned i = 0, e = VFs.size(); i < e; ++i) {
  4704. unsigned Invariant = 0;
  4705. if (VFs[i] == 1)
  4706. Invariant = LoopInvariants.size();
  4707. else {
  4708. for (auto Inst : LoopInvariants)
  4709. Invariant += GetRegUsage(Inst->getType(), VFs[i]);
  4710. }
  4711. LLVM_DEBUG(dbgs() << "LV(REG): VF = " << VFs[i] << '\n');
  4712. LLVM_DEBUG(dbgs() << "LV(REG): Found max usage: " << MaxUsages[i] << '\n');
  4713. LLVM_DEBUG(dbgs() << "LV(REG): Found invariant usage: " << Invariant
  4714. << '\n');
  4715. RU.LoopInvariantRegs = Invariant;
  4716. RU.MaxLocalUsers = MaxUsages[i];
  4717. RUs[i] = RU;
  4718. }
  4719. return RUs;
  4720. }
  4721. bool LoopVectorizationCostModel::useEmulatedMaskMemRefHack(Instruction *I){
  4722. // TODO: Cost model for emulated masked load/store is completely
  4723. // broken. This hack guides the cost model to use an artificially
  4724. // high enough value to practically disable vectorization with such
  4725. // operations, except where previously deployed legality hack allowed
  4726. // using very low cost values. This is to avoid regressions coming simply
  4727. // from moving "masked load/store" check from legality to cost model.
  4728. // Masked Load/Gather emulation was previously never allowed.
  4729. // Limited number of Masked Store/Scatter emulation was allowed.
  4730. assert(isScalarWithPredication(I) &&
  4731. "Expecting a scalar emulated instruction");
  4732. return isa<LoadInst>(I) ||
  4733. (isa<StoreInst>(I) &&
  4734. NumPredStores > NumberOfStoresToPredicate);
  4735. }
  4736. void LoopVectorizationCostModel::collectInstsToScalarize(unsigned VF) {
  4737. // If we aren't vectorizing the loop, or if we've already collected the
  4738. // instructions to scalarize, there's nothing to do. Collection may already
  4739. // have occurred if we have a user-selected VF and are now computing the
  4740. // expected cost for interleaving.
  4741. if (VF < 2 || InstsToScalarize.find(VF) != InstsToScalarize.end())
  4742. return;
  4743. // Initialize a mapping for VF in InstsToScalalarize. If we find that it's
  4744. // not profitable to scalarize any instructions, the presence of VF in the
  4745. // map will indicate that we've analyzed it already.
  4746. ScalarCostsTy &ScalarCostsVF = InstsToScalarize[VF];
  4747. // Find all the instructions that are scalar with predication in the loop and
  4748. // determine if it would be better to not if-convert the blocks they are in.
  4749. // If so, we also record the instructions to scalarize.
  4750. for (BasicBlock *BB : TheLoop->blocks()) {
  4751. if (!Legal->blockNeedsPredication(BB))
  4752. continue;
  4753. for (Instruction &I : *BB)
  4754. if (isScalarWithPredication(&I)) {
  4755. ScalarCostsTy ScalarCosts;
  4756. // Do not apply discount logic if hacked cost is needed
  4757. // for emulated masked memrefs.
  4758. if (!useEmulatedMaskMemRefHack(&I) &&
  4759. computePredInstDiscount(&I, ScalarCosts, VF) >= 0)
  4760. ScalarCostsVF.insert(ScalarCosts.begin(), ScalarCosts.end());
  4761. // Remember that BB will remain after vectorization.
  4762. PredicatedBBsAfterVectorization.insert(BB);
  4763. }
  4764. }
  4765. }
  4766. int LoopVectorizationCostModel::computePredInstDiscount(
  4767. Instruction *PredInst, DenseMap<Instruction *, unsigned> &ScalarCosts,
  4768. unsigned VF) {
  4769. assert(!isUniformAfterVectorization(PredInst, VF) &&
  4770. "Instruction marked uniform-after-vectorization will be predicated");
  4771. // Initialize the discount to zero, meaning that the scalar version and the
  4772. // vector version cost the same.
  4773. int Discount = 0;
  4774. // Holds instructions to analyze. The instructions we visit are mapped in
  4775. // ScalarCosts. Those instructions are the ones that would be scalarized if
  4776. // we find that the scalar version costs less.
  4777. SmallVector<Instruction *, 8> Worklist;
  4778. // Returns true if the given instruction can be scalarized.
  4779. auto canBeScalarized = [&](Instruction *I) -> bool {
  4780. // We only attempt to scalarize instructions forming a single-use chain
  4781. // from the original predicated block that would otherwise be vectorized.
  4782. // Although not strictly necessary, we give up on instructions we know will
  4783. // already be scalar to avoid traversing chains that are unlikely to be
  4784. // beneficial.
  4785. if (!I->hasOneUse() || PredInst->getParent() != I->getParent() ||
  4786. isScalarAfterVectorization(I, VF))
  4787. return false;
  4788. // If the instruction is scalar with predication, it will be analyzed
  4789. // separately. We ignore it within the context of PredInst.
  4790. if (isScalarWithPredication(I))
  4791. return false;
  4792. // If any of the instruction's operands are uniform after vectorization,
  4793. // the instruction cannot be scalarized. This prevents, for example, a
  4794. // masked load from being scalarized.
  4795. //
  4796. // We assume we will only emit a value for lane zero of an instruction
  4797. // marked uniform after vectorization, rather than VF identical values.
  4798. // Thus, if we scalarize an instruction that uses a uniform, we would
  4799. // create uses of values corresponding to the lanes we aren't emitting code
  4800. // for. This behavior can be changed by allowing getScalarValue to clone
  4801. // the lane zero values for uniforms rather than asserting.
  4802. for (Use &U : I->operands())
  4803. if (auto *J = dyn_cast<Instruction>(U.get()))
  4804. if (isUniformAfterVectorization(J, VF))
  4805. return false;
  4806. // Otherwise, we can scalarize the instruction.
  4807. return true;
  4808. };
  4809. // Returns true if an operand that cannot be scalarized must be extracted
  4810. // from a vector. We will account for this scalarization overhead below. Note
  4811. // that the non-void predicated instructions are placed in their own blocks,
  4812. // and their return values are inserted into vectors. Thus, an extract would
  4813. // still be required.
  4814. auto needsExtract = [&](Instruction *I) -> bool {
  4815. return TheLoop->contains(I) && !isScalarAfterVectorization(I, VF);
  4816. };
  4817. // Compute the expected cost discount from scalarizing the entire expression
  4818. // feeding the predicated instruction. We currently only consider expressions
  4819. // that are single-use instruction chains.
  4820. Worklist.push_back(PredInst);
  4821. while (!Worklist.empty()) {
  4822. Instruction *I = Worklist.pop_back_val();
  4823. // If we've already analyzed the instruction, there's nothing to do.
  4824. if (ScalarCosts.find(I) != ScalarCosts.end())
  4825. continue;
  4826. // Compute the cost of the vector instruction. Note that this cost already
  4827. // includes the scalarization overhead of the predicated instruction.
  4828. unsigned VectorCost = getInstructionCost(I, VF).first;
  4829. // Compute the cost of the scalarized instruction. This cost is the cost of
  4830. // the instruction as if it wasn't if-converted and instead remained in the
  4831. // predicated block. We will scale this cost by block probability after
  4832. // computing the scalarization overhead.
  4833. unsigned ScalarCost = VF * getInstructionCost(I, 1).first;
  4834. // Compute the scalarization overhead of needed insertelement instructions
  4835. // and phi nodes.
  4836. if (isScalarWithPredication(I) && !I->getType()->isVoidTy()) {
  4837. ScalarCost += TTI.getScalarizationOverhead(ToVectorTy(I->getType(), VF),
  4838. true, false);
  4839. ScalarCost += VF * TTI.getCFInstrCost(Instruction::PHI);
  4840. }
  4841. // Compute the scalarization overhead of needed extractelement
  4842. // instructions. For each of the instruction's operands, if the operand can
  4843. // be scalarized, add it to the worklist; otherwise, account for the
  4844. // overhead.
  4845. for (Use &U : I->operands())
  4846. if (auto *J = dyn_cast<Instruction>(U.get())) {
  4847. assert(VectorType::isValidElementType(J->getType()) &&
  4848. "Instruction has non-scalar type");
  4849. if (canBeScalarized(J))
  4850. Worklist.push_back(J);
  4851. else if (needsExtract(J))
  4852. ScalarCost += TTI.getScalarizationOverhead(
  4853. ToVectorTy(J->getType(),VF), false, true);
  4854. }
  4855. // Scale the total scalar cost by block probability.
  4856. ScalarCost /= getReciprocalPredBlockProb();
  4857. // Compute the discount. A non-negative discount means the vector version
  4858. // of the instruction costs more, and scalarizing would be beneficial.
  4859. Discount += VectorCost - ScalarCost;
  4860. ScalarCosts[I] = ScalarCost;
  4861. }
  4862. return Discount;
  4863. }
  4864. LoopVectorizationCostModel::VectorizationCostTy
  4865. LoopVectorizationCostModel::expectedCost(unsigned VF) {
  4866. VectorizationCostTy Cost;
  4867. // For each block.
  4868. for (BasicBlock *BB : TheLoop->blocks()) {
  4869. VectorizationCostTy BlockCost;
  4870. // For each instruction in the old loop.
  4871. for (Instruction &I : BB->instructionsWithoutDebug()) {
  4872. // Skip ignored values.
  4873. if (ValuesToIgnore.find(&I) != ValuesToIgnore.end() ||
  4874. (VF > 1 && VecValuesToIgnore.find(&I) != VecValuesToIgnore.end()))
  4875. continue;
  4876. VectorizationCostTy C = getInstructionCost(&I, VF);
  4877. // Check if we should override the cost.
  4878. if (ForceTargetInstructionCost.getNumOccurrences() > 0)
  4879. C.first = ForceTargetInstructionCost;
  4880. BlockCost.first += C.first;
  4881. BlockCost.second |= C.second;
  4882. LLVM_DEBUG(dbgs() << "LV: Found an estimated cost of " << C.first
  4883. << " for VF " << VF << " For instruction: " << I
  4884. << '\n');
  4885. }
  4886. // If we are vectorizing a predicated block, it will have been
  4887. // if-converted. This means that the block's instructions (aside from
  4888. // stores and instructions that may divide by zero) will now be
  4889. // unconditionally executed. For the scalar case, we may not always execute
  4890. // the predicated block. Thus, scale the block's cost by the probability of
  4891. // executing it.
  4892. if (VF == 1 && Legal->blockNeedsPredication(BB))
  4893. BlockCost.first /= getReciprocalPredBlockProb();
  4894. Cost.first += BlockCost.first;
  4895. Cost.second |= BlockCost.second;
  4896. }
  4897. return Cost;
  4898. }
  4899. /// Gets Address Access SCEV after verifying that the access pattern
  4900. /// is loop invariant except the induction variable dependence.
  4901. ///
  4902. /// This SCEV can be sent to the Target in order to estimate the address
  4903. /// calculation cost.
  4904. static const SCEV *getAddressAccessSCEV(
  4905. Value *Ptr,
  4906. LoopVectorizationLegality *Legal,
  4907. PredicatedScalarEvolution &PSE,
  4908. const Loop *TheLoop) {
  4909. auto *Gep = dyn_cast<GetElementPtrInst>(Ptr);
  4910. if (!Gep)
  4911. return nullptr;
  4912. // We are looking for a gep with all loop invariant indices except for one
  4913. // which should be an induction variable.
  4914. auto SE = PSE.getSE();
  4915. unsigned NumOperands = Gep->getNumOperands();
  4916. for (unsigned i = 1; i < NumOperands; ++i) {
  4917. Value *Opd = Gep->getOperand(i);
  4918. if (!SE->isLoopInvariant(SE->getSCEV(Opd), TheLoop) &&
  4919. !Legal->isInductionVariable(Opd))
  4920. return nullptr;
  4921. }
  4922. // Now we know we have a GEP ptr, %inv, %ind, %inv. return the Ptr SCEV.
  4923. return PSE.getSCEV(Ptr);
  4924. }
  4925. static bool isStrideMul(Instruction *I, LoopVectorizationLegality *Legal) {
  4926. return Legal->hasStride(I->getOperand(0)) ||
  4927. Legal->hasStride(I->getOperand(1));
  4928. }
  4929. unsigned LoopVectorizationCostModel::getMemInstScalarizationCost(Instruction *I,
  4930. unsigned VF) {
  4931. Type *ValTy = getMemInstValueType(I);
  4932. auto SE = PSE.getSE();
  4933. unsigned Alignment = getMemInstAlignment(I);
  4934. unsigned AS = getMemInstAddressSpace(I);
  4935. Value *Ptr = getLoadStorePointerOperand(I);
  4936. Type *PtrTy = ToVectorTy(Ptr->getType(), VF);
  4937. // Figure out whether the access is strided and get the stride value
  4938. // if it's known in compile time
  4939. const SCEV *PtrSCEV = getAddressAccessSCEV(Ptr, Legal, PSE, TheLoop);
  4940. // Get the cost of the scalar memory instruction and address computation.
  4941. unsigned Cost = VF * TTI.getAddressComputationCost(PtrTy, SE, PtrSCEV);
  4942. Cost += VF *
  4943. TTI.getMemoryOpCost(I->getOpcode(), ValTy->getScalarType(), Alignment,
  4944. AS, I);
  4945. // Get the overhead of the extractelement and insertelement instructions
  4946. // we might create due to scalarization.
  4947. Cost += getScalarizationOverhead(I, VF, TTI);
  4948. // If we have a predicated store, it may not be executed for each vector
  4949. // lane. Scale the cost by the probability of executing the predicated
  4950. // block.
  4951. if (isScalarWithPredication(I)) {
  4952. Cost /= getReciprocalPredBlockProb();
  4953. if (useEmulatedMaskMemRefHack(I))
  4954. // Artificially setting to a high enough value to practically disable
  4955. // vectorization with such operations.
  4956. Cost = 3000000;
  4957. }
  4958. return Cost;
  4959. }
  4960. unsigned LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
  4961. unsigned VF) {
  4962. Type *ValTy = getMemInstValueType(I);
  4963. Type *VectorTy = ToVectorTy(ValTy, VF);
  4964. unsigned Alignment = getMemInstAlignment(I);
  4965. Value *Ptr = getLoadStorePointerOperand(I);
  4966. unsigned AS = getMemInstAddressSpace(I);
  4967. int ConsecutiveStride = Legal->isConsecutivePtr(Ptr);
  4968. assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
  4969. "Stride should be 1 or -1 for consecutive memory access");
  4970. unsigned Cost = 0;
  4971. if (Legal->isMaskRequired(I))
  4972. Cost += TTI.getMaskedMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS);
  4973. else
  4974. Cost += TTI.getMemoryOpCost(I->getOpcode(), VectorTy, Alignment, AS, I);
  4975. bool Reverse = ConsecutiveStride < 0;
  4976. if (Reverse)
  4977. Cost += TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
  4978. return Cost;
  4979. }
  4980. unsigned LoopVectorizationCostModel::getUniformMemOpCost(Instruction *I,
  4981. unsigned VF) {
  4982. LoadInst *LI = cast<LoadInst>(I);
  4983. Type *ValTy = LI->getType();
  4984. Type *VectorTy = ToVectorTy(ValTy, VF);
  4985. unsigned Alignment = LI->getAlignment();
  4986. unsigned AS = LI->getPointerAddressSpace();
  4987. return TTI.getAddressComputationCost(ValTy) +
  4988. TTI.getMemoryOpCost(Instruction::Load, ValTy, Alignment, AS) +
  4989. TTI.getShuffleCost(TargetTransformInfo::SK_Broadcast, VectorTy);
  4990. }
  4991. unsigned LoopVectorizationCostModel::getGatherScatterCost(Instruction *I,
  4992. unsigned VF) {
  4993. Type *ValTy = getMemInstValueType(I);
  4994. Type *VectorTy = ToVectorTy(ValTy, VF);
  4995. unsigned Alignment = getMemInstAlignment(I);
  4996. Value *Ptr = getLoadStorePointerOperand(I);
  4997. return TTI.getAddressComputationCost(VectorTy) +
  4998. TTI.getGatherScatterOpCost(I->getOpcode(), VectorTy, Ptr,
  4999. Legal->isMaskRequired(I), Alignment);
  5000. }
  5001. unsigned LoopVectorizationCostModel::getInterleaveGroupCost(Instruction *I,
  5002. unsigned VF) {
  5003. Type *ValTy = getMemInstValueType(I);
  5004. Type *VectorTy = ToVectorTy(ValTy, VF);
  5005. unsigned AS = getMemInstAddressSpace(I);
  5006. auto Group = getInterleavedAccessGroup(I);
  5007. assert(Group && "Fail to get an interleaved access group.");
  5008. unsigned InterleaveFactor = Group->getFactor();
  5009. Type *WideVecTy = VectorType::get(ValTy, VF * InterleaveFactor);
  5010. // Holds the indices of existing members in an interleaved load group.
  5011. // An interleaved store group doesn't need this as it doesn't allow gaps.
  5012. SmallVector<unsigned, 4> Indices;
  5013. if (isa<LoadInst>(I)) {
  5014. for (unsigned i = 0; i < InterleaveFactor; i++)
  5015. if (Group->getMember(i))
  5016. Indices.push_back(i);
  5017. }
  5018. // Calculate the cost of the whole interleaved group.
  5019. unsigned Cost = TTI.getInterleavedMemoryOpCost(I->getOpcode(), WideVecTy,
  5020. Group->getFactor(), Indices,
  5021. Group->getAlignment(), AS);
  5022. if (Group->isReverse())
  5023. Cost += Group->getNumMembers() *
  5024. TTI.getShuffleCost(TargetTransformInfo::SK_Reverse, VectorTy, 0);
  5025. return Cost;
  5026. }
  5027. unsigned LoopVectorizationCostModel::getMemoryInstructionCost(Instruction *I,
  5028. unsigned VF) {
  5029. // Calculate scalar cost only. Vectorization cost should be ready at this
  5030. // moment.
  5031. if (VF == 1) {
  5032. Type *ValTy = getMemInstValueType(I);
  5033. unsigned Alignment = getMemInstAlignment(I);
  5034. unsigned AS = getMemInstAddressSpace(I);
  5035. return TTI.getAddressComputationCost(ValTy) +
  5036. TTI.getMemoryOpCost(I->getOpcode(), ValTy, Alignment, AS, I);
  5037. }
  5038. return getWideningCost(I, VF);
  5039. }
  5040. LoopVectorizationCostModel::VectorizationCostTy
  5041. LoopVectorizationCostModel::getInstructionCost(Instruction *I, unsigned VF) {
  5042. // If we know that this instruction will remain uniform, check the cost of
  5043. // the scalar version.
  5044. if (isUniformAfterVectorization(I, VF))
  5045. VF = 1;
  5046. if (VF > 1 && isProfitableToScalarize(I, VF))
  5047. return VectorizationCostTy(InstsToScalarize[VF][I], false);
  5048. // Forced scalars do not have any scalarization overhead.
  5049. auto ForcedScalar = ForcedScalars.find(VF);
  5050. if (VF > 1 && ForcedScalar != ForcedScalars.end()) {
  5051. auto InstSet = ForcedScalar->second;
  5052. if (InstSet.find(I) != InstSet.end())
  5053. return VectorizationCostTy((getInstructionCost(I, 1).first * VF), false);
  5054. }
  5055. Type *VectorTy;
  5056. unsigned C = getInstructionCost(I, VF, VectorTy);
  5057. bool TypeNotScalarized =
  5058. VF > 1 && VectorTy->isVectorTy() && TTI.getNumberOfParts(VectorTy) < VF;
  5059. return VectorizationCostTy(C, TypeNotScalarized);
  5060. }
  5061. void LoopVectorizationCostModel::setCostBasedWideningDecision(unsigned VF) {
  5062. if (VF == 1)
  5063. return;
  5064. NumPredStores = 0;
  5065. for (BasicBlock *BB : TheLoop->blocks()) {
  5066. // For each instruction in the old loop.
  5067. for (Instruction &I : *BB) {
  5068. Value *Ptr = getLoadStorePointerOperand(&I);
  5069. if (!Ptr)
  5070. continue;
  5071. if (isa<StoreInst>(&I) && isScalarWithPredication(&I))
  5072. NumPredStores++;
  5073. if (isa<LoadInst>(&I) && Legal->isUniform(Ptr)) {
  5074. // Scalar load + broadcast
  5075. unsigned Cost = getUniformMemOpCost(&I, VF);
  5076. setWideningDecision(&I, VF, CM_Scalarize, Cost);
  5077. continue;
  5078. }
  5079. // We assume that widening is the best solution when possible.
  5080. if (memoryInstructionCanBeWidened(&I, VF)) {
  5081. unsigned Cost = getConsecutiveMemOpCost(&I, VF);
  5082. int ConsecutiveStride =
  5083. Legal->isConsecutivePtr(getLoadStorePointerOperand(&I));
  5084. assert((ConsecutiveStride == 1 || ConsecutiveStride == -1) &&
  5085. "Expected consecutive stride.");
  5086. InstWidening Decision =
  5087. ConsecutiveStride == 1 ? CM_Widen : CM_Widen_Reverse;
  5088. setWideningDecision(&I, VF, Decision, Cost);
  5089. continue;
  5090. }
  5091. // Choose between Interleaving, Gather/Scatter or Scalarization.
  5092. unsigned InterleaveCost = std::numeric_limits<unsigned>::max();
  5093. unsigned NumAccesses = 1;
  5094. if (isAccessInterleaved(&I)) {
  5095. auto Group = getInterleavedAccessGroup(&I);
  5096. assert(Group && "Fail to get an interleaved access group.");
  5097. // Make one decision for the whole group.
  5098. if (getWideningDecision(&I, VF) != CM_Unknown)
  5099. continue;
  5100. NumAccesses = Group->getNumMembers();
  5101. InterleaveCost = getInterleaveGroupCost(&I, VF);
  5102. }
  5103. unsigned GatherScatterCost =
  5104. isLegalGatherOrScatter(&I)
  5105. ? getGatherScatterCost(&I, VF) * NumAccesses
  5106. : std::numeric_limits<unsigned>::max();
  5107. unsigned ScalarizationCost =
  5108. getMemInstScalarizationCost(&I, VF) * NumAccesses;
  5109. // Choose better solution for the current VF,
  5110. // write down this decision and use it during vectorization.
  5111. unsigned Cost;
  5112. InstWidening Decision;
  5113. if (InterleaveCost <= GatherScatterCost &&
  5114. InterleaveCost < ScalarizationCost) {
  5115. Decision = CM_Interleave;
  5116. Cost = InterleaveCost;
  5117. } else if (GatherScatterCost < ScalarizationCost) {
  5118. Decision = CM_GatherScatter;
  5119. Cost = GatherScatterCost;
  5120. } else {
  5121. Decision = CM_Scalarize;
  5122. Cost = ScalarizationCost;
  5123. }
  5124. // If the instructions belongs to an interleave group, the whole group
  5125. // receives the same decision. The whole group receives the cost, but
  5126. // the cost will actually be assigned to one instruction.
  5127. if (auto Group = getInterleavedAccessGroup(&I))
  5128. setWideningDecision(Group, VF, Decision, Cost);
  5129. else
  5130. setWideningDecision(&I, VF, Decision, Cost);
  5131. }
  5132. }
  5133. // Make sure that any load of address and any other address computation
  5134. // remains scalar unless there is gather/scatter support. This avoids
  5135. // inevitable extracts into address registers, and also has the benefit of
  5136. // activating LSR more, since that pass can't optimize vectorized
  5137. // addresses.
  5138. if (TTI.prefersVectorizedAddressing())
  5139. return;
  5140. // Start with all scalar pointer uses.
  5141. SmallPtrSet<Instruction *, 8> AddrDefs;
  5142. for (BasicBlock *BB : TheLoop->blocks())
  5143. for (Instruction &I : *BB) {
  5144. Instruction *PtrDef =
  5145. dyn_cast_or_null<Instruction>(getLoadStorePointerOperand(&I));
  5146. if (PtrDef && TheLoop->contains(PtrDef) &&
  5147. getWideningDecision(&I, VF) != CM_GatherScatter)
  5148. AddrDefs.insert(PtrDef);
  5149. }
  5150. // Add all instructions used to generate the addresses.
  5151. SmallVector<Instruction *, 4> Worklist;
  5152. for (auto *I : AddrDefs)
  5153. Worklist.push_back(I);
  5154. while (!Worklist.empty()) {
  5155. Instruction *I = Worklist.pop_back_val();
  5156. for (auto &Op : I->operands())
  5157. if (auto *InstOp = dyn_cast<Instruction>(Op))
  5158. if ((InstOp->getParent() == I->getParent()) && !isa<PHINode>(InstOp) &&
  5159. AddrDefs.insert(InstOp).second)
  5160. Worklist.push_back(InstOp);
  5161. }
  5162. for (auto *I : AddrDefs) {
  5163. if (isa<LoadInst>(I)) {
  5164. // Setting the desired widening decision should ideally be handled in
  5165. // by cost functions, but since this involves the task of finding out
  5166. // if the loaded register is involved in an address computation, it is
  5167. // instead changed here when we know this is the case.
  5168. InstWidening Decision = getWideningDecision(I, VF);
  5169. if (Decision == CM_Widen || Decision == CM_Widen_Reverse)
  5170. // Scalarize a widened load of address.
  5171. setWideningDecision(I, VF, CM_Scalarize,
  5172. (VF * getMemoryInstructionCost(I, 1)));
  5173. else if (auto Group = getInterleavedAccessGroup(I)) {
  5174. // Scalarize an interleave group of address loads.
  5175. for (unsigned I = 0; I < Group->getFactor(); ++I) {
  5176. if (Instruction *Member = Group->getMember(I))
  5177. setWideningDecision(Member, VF, CM_Scalarize,
  5178. (VF * getMemoryInstructionCost(Member, 1)));
  5179. }
  5180. }
  5181. } else
  5182. // Make sure I gets scalarized and a cost estimate without
  5183. // scalarization overhead.
  5184. ForcedScalars[VF].insert(I);
  5185. }
  5186. }
  5187. unsigned LoopVectorizationCostModel::getInstructionCost(Instruction *I,
  5188. unsigned VF,
  5189. Type *&VectorTy) {
  5190. Type *RetTy = I->getType();
  5191. if (canTruncateToMinimalBitwidth(I, VF))
  5192. RetTy = IntegerType::get(RetTy->getContext(), MinBWs[I]);
  5193. VectorTy = isScalarAfterVectorization(I, VF) ? RetTy : ToVectorTy(RetTy, VF);
  5194. auto SE = PSE.getSE();
  5195. // TODO: We need to estimate the cost of intrinsic calls.
  5196. switch (I->getOpcode()) {
  5197. case Instruction::GetElementPtr:
  5198. // We mark this instruction as zero-cost because the cost of GEPs in
  5199. // vectorized code depends on whether the corresponding memory instruction
  5200. // is scalarized or not. Therefore, we handle GEPs with the memory
  5201. // instruction cost.
  5202. return 0;
  5203. case Instruction::Br: {
  5204. // In cases of scalarized and predicated instructions, there will be VF
  5205. // predicated blocks in the vectorized loop. Each branch around these
  5206. // blocks requires also an extract of its vector compare i1 element.
  5207. bool ScalarPredicatedBB = false;
  5208. BranchInst *BI = cast<BranchInst>(I);
  5209. if (VF > 1 && BI->isConditional() &&
  5210. (PredicatedBBsAfterVectorization.find(BI->getSuccessor(0)) !=
  5211. PredicatedBBsAfterVectorization.end() ||
  5212. PredicatedBBsAfterVectorization.find(BI->getSuccessor(1)) !=
  5213. PredicatedBBsAfterVectorization.end()))
  5214. ScalarPredicatedBB = true;
  5215. if (ScalarPredicatedBB) {
  5216. // Return cost for branches around scalarized and predicated blocks.
  5217. Type *Vec_i1Ty =
  5218. VectorType::get(IntegerType::getInt1Ty(RetTy->getContext()), VF);
  5219. return (TTI.getScalarizationOverhead(Vec_i1Ty, false, true) +
  5220. (TTI.getCFInstrCost(Instruction::Br) * VF));
  5221. } else if (I->getParent() == TheLoop->getLoopLatch() || VF == 1)
  5222. // The back-edge branch will remain, as will all scalar branches.
  5223. return TTI.getCFInstrCost(Instruction::Br);
  5224. else
  5225. // This branch will be eliminated by if-conversion.
  5226. return 0;
  5227. // Note: We currently assume zero cost for an unconditional branch inside
  5228. // a predicated block since it will become a fall-through, although we
  5229. // may decide in the future to call TTI for all branches.
  5230. }
  5231. case Instruction::PHI: {
  5232. auto *Phi = cast<PHINode>(I);
  5233. // First-order recurrences are replaced by vector shuffles inside the loop.
  5234. if (VF > 1 && Legal->isFirstOrderRecurrence(Phi))
  5235. return TTI.getShuffleCost(TargetTransformInfo::SK_ExtractSubvector,
  5236. VectorTy, VF - 1, VectorTy);
  5237. // Phi nodes in non-header blocks (not inductions, reductions, etc.) are
  5238. // converted into select instructions. We require N - 1 selects per phi
  5239. // node, where N is the number of incoming values.
  5240. if (VF > 1 && Phi->getParent() != TheLoop->getHeader())
  5241. return (Phi->getNumIncomingValues() - 1) *
  5242. TTI.getCmpSelInstrCost(
  5243. Instruction::Select, ToVectorTy(Phi->getType(), VF),
  5244. ToVectorTy(Type::getInt1Ty(Phi->getContext()), VF));
  5245. return TTI.getCFInstrCost(Instruction::PHI);
  5246. }
  5247. case Instruction::UDiv:
  5248. case Instruction::SDiv:
  5249. case Instruction::URem:
  5250. case Instruction::SRem:
  5251. // If we have a predicated instruction, it may not be executed for each
  5252. // vector lane. Get the scalarization cost and scale this amount by the
  5253. // probability of executing the predicated block. If the instruction is not
  5254. // predicated, we fall through to the next case.
  5255. if (VF > 1 && isScalarWithPredication(I)) {
  5256. unsigned Cost = 0;
  5257. // These instructions have a non-void type, so account for the phi nodes
  5258. // that we will create. This cost is likely to be zero. The phi node
  5259. // cost, if any, should be scaled by the block probability because it
  5260. // models a copy at the end of each predicated block.
  5261. Cost += VF * TTI.getCFInstrCost(Instruction::PHI);
  5262. // The cost of the non-predicated instruction.
  5263. Cost += VF * TTI.getArithmeticInstrCost(I->getOpcode(), RetTy);
  5264. // The cost of insertelement and extractelement instructions needed for
  5265. // scalarization.
  5266. Cost += getScalarizationOverhead(I, VF, TTI);
  5267. // Scale the cost by the probability of executing the predicated blocks.
  5268. // This assumes the predicated block for each vector lane is equally
  5269. // likely.
  5270. return Cost / getReciprocalPredBlockProb();
  5271. }
  5272. LLVM_FALLTHROUGH;
  5273. case Instruction::Add:
  5274. case Instruction::FAdd:
  5275. case Instruction::Sub:
  5276. case Instruction::FSub:
  5277. case Instruction::Mul:
  5278. case Instruction::FMul:
  5279. case Instruction::FDiv:
  5280. case Instruction::FRem:
  5281. case Instruction::Shl:
  5282. case Instruction::LShr:
  5283. case Instruction::AShr:
  5284. case Instruction::And:
  5285. case Instruction::Or:
  5286. case Instruction::Xor: {
  5287. // Since we will replace the stride by 1 the multiplication should go away.
  5288. if (I->getOpcode() == Instruction::Mul && isStrideMul(I, Legal))
  5289. return 0;
  5290. // Certain instructions can be cheaper to vectorize if they have a constant
  5291. // second vector operand. One example of this are shifts on x86.
  5292. TargetTransformInfo::OperandValueKind Op1VK =
  5293. TargetTransformInfo::OK_AnyValue;
  5294. TargetTransformInfo::OperandValueKind Op2VK =
  5295. TargetTransformInfo::OK_AnyValue;
  5296. TargetTransformInfo::OperandValueProperties Op1VP =
  5297. TargetTransformInfo::OP_None;
  5298. TargetTransformInfo::OperandValueProperties Op2VP =
  5299. TargetTransformInfo::OP_None;
  5300. Value *Op2 = I->getOperand(1);
  5301. // Check for a splat or for a non uniform vector of constants.
  5302. if (isa<ConstantInt>(Op2)) {
  5303. ConstantInt *CInt = cast<ConstantInt>(Op2);
  5304. if (CInt && CInt->getValue().isPowerOf2())
  5305. Op2VP = TargetTransformInfo::OP_PowerOf2;
  5306. Op2VK = TargetTransformInfo::OK_UniformConstantValue;
  5307. } else if (isa<ConstantVector>(Op2) || isa<ConstantDataVector>(Op2)) {
  5308. Op2VK = TargetTransformInfo::OK_NonUniformConstantValue;
  5309. Constant *SplatValue = cast<Constant>(Op2)->getSplatValue();
  5310. if (SplatValue) {
  5311. ConstantInt *CInt = dyn_cast<ConstantInt>(SplatValue);
  5312. if (CInt && CInt->getValue().isPowerOf2())
  5313. Op2VP = TargetTransformInfo::OP_PowerOf2;
  5314. Op2VK = TargetTransformInfo::OK_UniformConstantValue;
  5315. }
  5316. } else if (Legal->isUniform(Op2)) {
  5317. Op2VK = TargetTransformInfo::OK_UniformValue;
  5318. }
  5319. SmallVector<const Value *, 4> Operands(I->operand_values());
  5320. unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
  5321. return N * TTI.getArithmeticInstrCost(I->getOpcode(), VectorTy, Op1VK,
  5322. Op2VK, Op1VP, Op2VP, Operands);
  5323. }
  5324. case Instruction::Select: {
  5325. SelectInst *SI = cast<SelectInst>(I);
  5326. const SCEV *CondSCEV = SE->getSCEV(SI->getCondition());
  5327. bool ScalarCond = (SE->isLoopInvariant(CondSCEV, TheLoop));
  5328. Type *CondTy = SI->getCondition()->getType();
  5329. if (!ScalarCond)
  5330. CondTy = VectorType::get(CondTy, VF);
  5331. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, CondTy, I);
  5332. }
  5333. case Instruction::ICmp:
  5334. case Instruction::FCmp: {
  5335. Type *ValTy = I->getOperand(0)->getType();
  5336. Instruction *Op0AsInstruction = dyn_cast<Instruction>(I->getOperand(0));
  5337. if (canTruncateToMinimalBitwidth(Op0AsInstruction, VF))
  5338. ValTy = IntegerType::get(ValTy->getContext(), MinBWs[Op0AsInstruction]);
  5339. VectorTy = ToVectorTy(ValTy, VF);
  5340. return TTI.getCmpSelInstrCost(I->getOpcode(), VectorTy, nullptr, I);
  5341. }
  5342. case Instruction::Store:
  5343. case Instruction::Load: {
  5344. unsigned Width = VF;
  5345. if (Width > 1) {
  5346. InstWidening Decision = getWideningDecision(I, Width);
  5347. assert(Decision != CM_Unknown &&
  5348. "CM decision should be taken at this point");
  5349. if (Decision == CM_Scalarize)
  5350. Width = 1;
  5351. }
  5352. VectorTy = ToVectorTy(getMemInstValueType(I), Width);
  5353. return getMemoryInstructionCost(I, VF);
  5354. }
  5355. case Instruction::ZExt:
  5356. case Instruction::SExt:
  5357. case Instruction::FPToUI:
  5358. case Instruction::FPToSI:
  5359. case Instruction::FPExt:
  5360. case Instruction::PtrToInt:
  5361. case Instruction::IntToPtr:
  5362. case Instruction::SIToFP:
  5363. case Instruction::UIToFP:
  5364. case Instruction::Trunc:
  5365. case Instruction::FPTrunc:
  5366. case Instruction::BitCast: {
  5367. // We optimize the truncation of induction variables having constant
  5368. // integer steps. The cost of these truncations is the same as the scalar
  5369. // operation.
  5370. if (isOptimizableIVTruncate(I, VF)) {
  5371. auto *Trunc = cast<TruncInst>(I);
  5372. return TTI.getCastInstrCost(Instruction::Trunc, Trunc->getDestTy(),
  5373. Trunc->getSrcTy(), Trunc);
  5374. }
  5375. Type *SrcScalarTy = I->getOperand(0)->getType();
  5376. Type *SrcVecTy =
  5377. VectorTy->isVectorTy() ? ToVectorTy(SrcScalarTy, VF) : SrcScalarTy;
  5378. if (canTruncateToMinimalBitwidth(I, VF)) {
  5379. // This cast is going to be shrunk. This may remove the cast or it might
  5380. // turn it into slightly different cast. For example, if MinBW == 16,
  5381. // "zext i8 %1 to i32" becomes "zext i8 %1 to i16".
  5382. //
  5383. // Calculate the modified src and dest types.
  5384. Type *MinVecTy = VectorTy;
  5385. if (I->getOpcode() == Instruction::Trunc) {
  5386. SrcVecTy = smallestIntegerVectorType(SrcVecTy, MinVecTy);
  5387. VectorTy =
  5388. largestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
  5389. } else if (I->getOpcode() == Instruction::ZExt ||
  5390. I->getOpcode() == Instruction::SExt) {
  5391. SrcVecTy = largestIntegerVectorType(SrcVecTy, MinVecTy);
  5392. VectorTy =
  5393. smallestIntegerVectorType(ToVectorTy(I->getType(), VF), MinVecTy);
  5394. }
  5395. }
  5396. unsigned N = isScalarAfterVectorization(I, VF) ? VF : 1;
  5397. return N * TTI.getCastInstrCost(I->getOpcode(), VectorTy, SrcVecTy, I);
  5398. }
  5399. case Instruction::Call: {
  5400. bool NeedToScalarize;
  5401. CallInst *CI = cast<CallInst>(I);
  5402. unsigned CallCost = getVectorCallCost(CI, VF, TTI, TLI, NeedToScalarize);
  5403. if (getVectorIntrinsicIDForCall(CI, TLI))
  5404. return std::min(CallCost, getVectorIntrinsicCost(CI, VF, TTI, TLI));
  5405. return CallCost;
  5406. }
  5407. default:
  5408. // The cost of executing VF copies of the scalar instruction. This opcode
  5409. // is unknown. Assume that it is the same as 'mul'.
  5410. return VF * TTI.getArithmeticInstrCost(Instruction::Mul, VectorTy) +
  5411. getScalarizationOverhead(I, VF, TTI);
  5412. } // end of switch.
  5413. }
  5414. char LoopVectorize::ID = 0;
  5415. static const char lv_name[] = "Loop Vectorization";
  5416. INITIALIZE_PASS_BEGIN(LoopVectorize, LV_NAME, lv_name, false, false)
  5417. INITIALIZE_PASS_DEPENDENCY(TargetTransformInfoWrapperPass)
  5418. INITIALIZE_PASS_DEPENDENCY(BasicAAWrapperPass)
  5419. INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
  5420. INITIALIZE_PASS_DEPENDENCY(GlobalsAAWrapperPass)
  5421. INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
  5422. INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
  5423. INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
  5424. INITIALIZE_PASS_DEPENDENCY(ScalarEvolutionWrapperPass)
  5425. INITIALIZE_PASS_DEPENDENCY(LoopInfoWrapperPass)
  5426. INITIALIZE_PASS_DEPENDENCY(LoopAccessLegacyAnalysis)
  5427. INITIALIZE_PASS_DEPENDENCY(DemandedBitsWrapperPass)
  5428. INITIALIZE_PASS_DEPENDENCY(OptimizationRemarkEmitterWrapperPass)
  5429. INITIALIZE_PASS_END(LoopVectorize, LV_NAME, lv_name, false, false)
  5430. namespace llvm {
  5431. Pass *createLoopVectorizePass(bool NoUnrolling, bool AlwaysVectorize) {
  5432. return new LoopVectorize(NoUnrolling, AlwaysVectorize);
  5433. }
  5434. } // end namespace llvm
  5435. bool LoopVectorizationCostModel::isConsecutiveLoadOrStore(Instruction *Inst) {
  5436. // Check if the pointer operand of a load or store instruction is
  5437. // consecutive.
  5438. if (auto *Ptr = getLoadStorePointerOperand(Inst))
  5439. return Legal->isConsecutivePtr(Ptr);
  5440. return false;
  5441. }
  5442. void LoopVectorizationCostModel::collectValuesToIgnore() {
  5443. // Ignore ephemeral values.
  5444. CodeMetrics::collectEphemeralValues(TheLoop, AC, ValuesToIgnore);
  5445. // Ignore type-promoting instructions we identified during reduction
  5446. // detection.
  5447. for (auto &Reduction : *Legal->getReductionVars()) {
  5448. RecurrenceDescriptor &RedDes = Reduction.second;
  5449. SmallPtrSetImpl<Instruction *> &Casts = RedDes.getCastInsts();
  5450. VecValuesToIgnore.insert(Casts.begin(), Casts.end());
  5451. }
  5452. // Ignore type-casting instructions we identified during induction
  5453. // detection.
  5454. for (auto &Induction : *Legal->getInductionVars()) {
  5455. InductionDescriptor &IndDes = Induction.second;
  5456. const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
  5457. VecValuesToIgnore.insert(Casts.begin(), Casts.end());
  5458. }
  5459. }
  5460. VectorizationFactor
  5461. LoopVectorizationPlanner::planInVPlanNativePath(bool OptForSize,
  5462. unsigned UserVF) {
  5463. // Width 1 means no vectorization, cost 0 means uncomputed cost.
  5464. const VectorizationFactor NoVectorization = {1U, 0U};
  5465. // Outer loop handling: They may require CFG and instruction level
  5466. // transformations before even evaluating whether vectorization is profitable.
  5467. // Since we cannot modify the incoming IR, we need to build VPlan upfront in
  5468. // the vectorization pipeline.
  5469. if (!OrigLoop->empty()) {
  5470. // TODO: If UserVF is not provided, we set UserVF to 4 for stress testing.
  5471. // This won't be necessary when UserVF is not required in the VPlan-native
  5472. // path.
  5473. if (VPlanBuildStressTest && !UserVF)
  5474. UserVF = 4;
  5475. assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
  5476. assert(UserVF && "Expected UserVF for outer loop vectorization.");
  5477. assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
  5478. LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
  5479. buildVPlans(UserVF, UserVF);
  5480. // For VPlan build stress testing, we bail out after VPlan construction.
  5481. if (VPlanBuildStressTest)
  5482. return NoVectorization;
  5483. return {UserVF, 0};
  5484. }
  5485. LLVM_DEBUG(
  5486. dbgs() << "LV: Not vectorizing. Inner loops aren't supported in the "
  5487. "VPlan-native path.\n");
  5488. return NoVectorization;
  5489. }
  5490. VectorizationFactor
  5491. LoopVectorizationPlanner::plan(bool OptForSize, unsigned UserVF) {
  5492. assert(OrigLoop->empty() && "Inner loop expected.");
  5493. // Width 1 means no vectorization, cost 0 means uncomputed cost.
  5494. const VectorizationFactor NoVectorization = {1U, 0U};
  5495. Optional<unsigned> MaybeMaxVF = CM.computeMaxVF(OptForSize);
  5496. if (!MaybeMaxVF.hasValue()) // Cases considered too costly to vectorize.
  5497. return NoVectorization;
  5498. if (UserVF) {
  5499. LLVM_DEBUG(dbgs() << "LV: Using user VF " << UserVF << ".\n");
  5500. assert(isPowerOf2_32(UserVF) && "VF needs to be a power of two");
  5501. // Collect the instructions (and their associated costs) that will be more
  5502. // profitable to scalarize.
  5503. CM.selectUserVectorizationFactor(UserVF);
  5504. buildVPlansWithVPRecipes(UserVF, UserVF);
  5505. LLVM_DEBUG(printPlans(dbgs()));
  5506. return {UserVF, 0};
  5507. }
  5508. unsigned MaxVF = MaybeMaxVF.getValue();
  5509. assert(MaxVF != 0 && "MaxVF is zero.");
  5510. for (unsigned VF = 1; VF <= MaxVF; VF *= 2) {
  5511. // Collect Uniform and Scalar instructions after vectorization with VF.
  5512. CM.collectUniformsAndScalars(VF);
  5513. // Collect the instructions (and their associated costs) that will be more
  5514. // profitable to scalarize.
  5515. if (VF > 1)
  5516. CM.collectInstsToScalarize(VF);
  5517. }
  5518. buildVPlansWithVPRecipes(1, MaxVF);
  5519. LLVM_DEBUG(printPlans(dbgs()));
  5520. if (MaxVF == 1)
  5521. return NoVectorization;
  5522. // Select the optimal vectorization factor.
  5523. return CM.selectVectorizationFactor(MaxVF);
  5524. }
  5525. void LoopVectorizationPlanner::setBestPlan(unsigned VF, unsigned UF) {
  5526. LLVM_DEBUG(dbgs() << "Setting best plan to VF=" << VF << ", UF=" << UF
  5527. << '\n');
  5528. BestVF = VF;
  5529. BestUF = UF;
  5530. erase_if(VPlans, [VF](const VPlanPtr &Plan) {
  5531. return !Plan->hasVF(VF);
  5532. });
  5533. assert(VPlans.size() == 1 && "Best VF has not a single VPlan.");
  5534. }
  5535. void LoopVectorizationPlanner::executePlan(InnerLoopVectorizer &ILV,
  5536. DominatorTree *DT) {
  5537. // Perform the actual loop transformation.
  5538. // 1. Create a new empty loop. Unlink the old loop and connect the new one.
  5539. VPCallbackILV CallbackILV(ILV);
  5540. VPTransformState State{BestVF, BestUF, LI,
  5541. DT, ILV.Builder, ILV.VectorLoopValueMap,
  5542. &ILV, CallbackILV};
  5543. State.CFG.PrevBB = ILV.createVectorizedLoopSkeleton();
  5544. //===------------------------------------------------===//
  5545. //
  5546. // Notice: any optimization or new instruction that go
  5547. // into the code below should also be implemented in
  5548. // the cost-model.
  5549. //
  5550. //===------------------------------------------------===//
  5551. // 2. Copy and widen instructions from the old loop into the new loop.
  5552. assert(VPlans.size() == 1 && "Not a single VPlan to execute.");
  5553. VPlans.front()->execute(&State);
  5554. // 3. Fix the vectorized code: take care of header phi's, live-outs,
  5555. // predication, updating analyses.
  5556. ILV.fixVectorizedLoop();
  5557. }
  5558. void LoopVectorizationPlanner::collectTriviallyDeadInstructions(
  5559. SmallPtrSetImpl<Instruction *> &DeadInstructions) {
  5560. BasicBlock *Latch = OrigLoop->getLoopLatch();
  5561. // We create new control-flow for the vectorized loop, so the original
  5562. // condition will be dead after vectorization if it's only used by the
  5563. // branch.
  5564. auto *Cmp = dyn_cast<Instruction>(Latch->getTerminator()->getOperand(0));
  5565. if (Cmp && Cmp->hasOneUse())
  5566. DeadInstructions.insert(Cmp);
  5567. // We create new "steps" for induction variable updates to which the original
  5568. // induction variables map. An original update instruction will be dead if
  5569. // all its users except the induction variable are dead.
  5570. for (auto &Induction : *Legal->getInductionVars()) {
  5571. PHINode *Ind = Induction.first;
  5572. auto *IndUpdate = cast<Instruction>(Ind->getIncomingValueForBlock(Latch));
  5573. if (llvm::all_of(IndUpdate->users(), [&](User *U) -> bool {
  5574. return U == Ind || DeadInstructions.find(cast<Instruction>(U)) !=
  5575. DeadInstructions.end();
  5576. }))
  5577. DeadInstructions.insert(IndUpdate);
  5578. // We record as "Dead" also the type-casting instructions we had identified
  5579. // during induction analysis. We don't need any handling for them in the
  5580. // vectorized loop because we have proven that, under a proper runtime
  5581. // test guarding the vectorized loop, the value of the phi, and the casted
  5582. // value of the phi, are the same. The last instruction in this casting chain
  5583. // will get its scalar/vector/widened def from the scalar/vector/widened def
  5584. // of the respective phi node. Any other casts in the induction def-use chain
  5585. // have no other uses outside the phi update chain, and will be ignored.
  5586. InductionDescriptor &IndDes = Induction.second;
  5587. const SmallVectorImpl<Instruction *> &Casts = IndDes.getCastInsts();
  5588. DeadInstructions.insert(Casts.begin(), Casts.end());
  5589. }
  5590. }
  5591. Value *InnerLoopUnroller::reverseVector(Value *Vec) { return Vec; }
  5592. Value *InnerLoopUnroller::getBroadcastInstrs(Value *V) { return V; }
  5593. Value *InnerLoopUnroller::getStepVector(Value *Val, int StartIdx, Value *Step,
  5594. Instruction::BinaryOps BinOp) {
  5595. // When unrolling and the VF is 1, we only need to add a simple scalar.
  5596. Type *Ty = Val->getType();
  5597. assert(!Ty->isVectorTy() && "Val must be a scalar");
  5598. if (Ty->isFloatingPointTy()) {
  5599. Constant *C = ConstantFP::get(Ty, (double)StartIdx);
  5600. // Floating point operations had to be 'fast' to enable the unrolling.
  5601. Value *MulOp = addFastMathFlag(Builder.CreateFMul(C, Step));
  5602. return addFastMathFlag(Builder.CreateBinOp(BinOp, Val, MulOp));
  5603. }
  5604. Constant *C = ConstantInt::get(Ty, StartIdx);
  5605. return Builder.CreateAdd(Val, Builder.CreateMul(C, Step), "induction");
  5606. }
  5607. static void AddRuntimeUnrollDisableMetaData(Loop *L) {
  5608. SmallVector<Metadata *, 4> MDs;
  5609. // Reserve first location for self reference to the LoopID metadata node.
  5610. MDs.push_back(nullptr);
  5611. bool IsUnrollMetadata = false;
  5612. MDNode *LoopID = L->getLoopID();
  5613. if (LoopID) {
  5614. // First find existing loop unrolling disable metadata.
  5615. for (unsigned i = 1, ie = LoopID->getNumOperands(); i < ie; ++i) {
  5616. auto *MD = dyn_cast<MDNode>(LoopID->getOperand(i));
  5617. if (MD) {
  5618. const auto *S = dyn_cast<MDString>(MD->getOperand(0));
  5619. IsUnrollMetadata =
  5620. S && S->getString().startswith("llvm.loop.unroll.disable");
  5621. }
  5622. MDs.push_back(LoopID->getOperand(i));
  5623. }
  5624. }
  5625. if (!IsUnrollMetadata) {
  5626. // Add runtime unroll disable metadata.
  5627. LLVMContext &Context = L->getHeader()->getContext();
  5628. SmallVector<Metadata *, 1> DisableOperands;
  5629. DisableOperands.push_back(
  5630. MDString::get(Context, "llvm.loop.unroll.runtime.disable"));
  5631. MDNode *DisableNode = MDNode::get(Context, DisableOperands);
  5632. MDs.push_back(DisableNode);
  5633. MDNode *NewLoopID = MDNode::get(Context, MDs);
  5634. // Set operand 0 to refer to the loop id itself.
  5635. NewLoopID->replaceOperandWith(0, NewLoopID);
  5636. L->setLoopID(NewLoopID);
  5637. }
  5638. }
  5639. bool LoopVectorizationPlanner::getDecisionAndClampRange(
  5640. const std::function<bool(unsigned)> &Predicate, VFRange &Range) {
  5641. assert(Range.End > Range.Start && "Trying to test an empty VF range.");
  5642. bool PredicateAtRangeStart = Predicate(Range.Start);
  5643. for (unsigned TmpVF = Range.Start * 2; TmpVF < Range.End; TmpVF *= 2)
  5644. if (Predicate(TmpVF) != PredicateAtRangeStart) {
  5645. Range.End = TmpVF;
  5646. break;
  5647. }
  5648. return PredicateAtRangeStart;
  5649. }
  5650. /// Build VPlans for the full range of feasible VF's = {\p MinVF, 2 * \p MinVF,
  5651. /// 4 * \p MinVF, ..., \p MaxVF} by repeatedly building a VPlan for a sub-range
  5652. /// of VF's starting at a given VF and extending it as much as possible. Each
  5653. /// vectorization decision can potentially shorten this sub-range during
  5654. /// buildVPlan().
  5655. void LoopVectorizationPlanner::buildVPlans(unsigned MinVF, unsigned MaxVF) {
  5656. for (unsigned VF = MinVF; VF < MaxVF + 1;) {
  5657. VFRange SubRange = {VF, MaxVF + 1};
  5658. VPlans.push_back(buildVPlan(SubRange));
  5659. VF = SubRange.End;
  5660. }
  5661. }
  5662. VPValue *VPRecipeBuilder::createEdgeMask(BasicBlock *Src, BasicBlock *Dst,
  5663. VPlanPtr &Plan) {
  5664. assert(is_contained(predecessors(Dst), Src) && "Invalid edge");
  5665. // Look for cached value.
  5666. std::pair<BasicBlock *, BasicBlock *> Edge(Src, Dst);
  5667. EdgeMaskCacheTy::iterator ECEntryIt = EdgeMaskCache.find(Edge);
  5668. if (ECEntryIt != EdgeMaskCache.end())
  5669. return ECEntryIt->second;
  5670. VPValue *SrcMask = createBlockInMask(Src, Plan);
  5671. // The terminator has to be a branch inst!
  5672. BranchInst *BI = dyn_cast<BranchInst>(Src->getTerminator());
  5673. assert(BI && "Unexpected terminator found");
  5674. if (!BI->isConditional())
  5675. return EdgeMaskCache[Edge] = SrcMask;
  5676. VPValue *EdgeMask = Plan->getVPValue(BI->getCondition());
  5677. assert(EdgeMask && "No Edge Mask found for condition");
  5678. if (BI->getSuccessor(0) != Dst)
  5679. EdgeMask = Builder.createNot(EdgeMask);
  5680. if (SrcMask) // Otherwise block in-mask is all-one, no need to AND.
  5681. EdgeMask = Builder.createAnd(EdgeMask, SrcMask);
  5682. return EdgeMaskCache[Edge] = EdgeMask;
  5683. }
  5684. VPValue *VPRecipeBuilder::createBlockInMask(BasicBlock *BB, VPlanPtr &Plan) {
  5685. assert(OrigLoop->contains(BB) && "Block is not a part of a loop");
  5686. // Look for cached value.
  5687. BlockMaskCacheTy::iterator BCEntryIt = BlockMaskCache.find(BB);
  5688. if (BCEntryIt != BlockMaskCache.end())
  5689. return BCEntryIt->second;
  5690. // All-one mask is modelled as no-mask following the convention for masked
  5691. // load/store/gather/scatter. Initialize BlockMask to no-mask.
  5692. VPValue *BlockMask = nullptr;
  5693. // Loop incoming mask is all-one.
  5694. if (OrigLoop->getHeader() == BB)
  5695. return BlockMaskCache[BB] = BlockMask;
  5696. // This is the block mask. We OR all incoming edges.
  5697. for (auto *Predecessor : predecessors(BB)) {
  5698. VPValue *EdgeMask = createEdgeMask(Predecessor, BB, Plan);
  5699. if (!EdgeMask) // Mask of predecessor is all-one so mask of block is too.
  5700. return BlockMaskCache[BB] = EdgeMask;
  5701. if (!BlockMask) { // BlockMask has its initialized nullptr value.
  5702. BlockMask = EdgeMask;
  5703. continue;
  5704. }
  5705. BlockMask = Builder.createOr(BlockMask, EdgeMask);
  5706. }
  5707. return BlockMaskCache[BB] = BlockMask;
  5708. }
  5709. VPInterleaveRecipe *VPRecipeBuilder::tryToInterleaveMemory(Instruction *I,
  5710. VFRange &Range) {
  5711. const InterleaveGroup *IG = CM.getInterleavedAccessGroup(I);
  5712. if (!IG)
  5713. return nullptr;
  5714. // Now check if IG is relevant for VF's in the given range.
  5715. auto isIGMember = [&](Instruction *I) -> std::function<bool(unsigned)> {
  5716. return [=](unsigned VF) -> bool {
  5717. return (VF >= 2 && // Query is illegal for VF == 1
  5718. CM.getWideningDecision(I, VF) ==
  5719. LoopVectorizationCostModel::CM_Interleave);
  5720. };
  5721. };
  5722. if (!LoopVectorizationPlanner::getDecisionAndClampRange(isIGMember(I), Range))
  5723. return nullptr;
  5724. // I is a member of an InterleaveGroup for VF's in the (possibly trimmed)
  5725. // range. If it's the primary member of the IG construct a VPInterleaveRecipe.
  5726. // Otherwise, it's an adjunct member of the IG, do not construct any Recipe.
  5727. assert(I == IG->getInsertPos() &&
  5728. "Generating a recipe for an adjunct member of an interleave group");
  5729. return new VPInterleaveRecipe(IG);
  5730. }
  5731. VPWidenMemoryInstructionRecipe *
  5732. VPRecipeBuilder::tryToWidenMemory(Instruction *I, VFRange &Range,
  5733. VPlanPtr &Plan) {
  5734. if (!isa<LoadInst>(I) && !isa<StoreInst>(I))
  5735. return nullptr;
  5736. auto willWiden = [&](unsigned VF) -> bool {
  5737. if (VF == 1)
  5738. return false;
  5739. if (CM.isScalarAfterVectorization(I, VF) ||
  5740. CM.isProfitableToScalarize(I, VF))
  5741. return false;
  5742. LoopVectorizationCostModel::InstWidening Decision =
  5743. CM.getWideningDecision(I, VF);
  5744. assert(Decision != LoopVectorizationCostModel::CM_Unknown &&
  5745. "CM decision should be taken at this point.");
  5746. assert(Decision != LoopVectorizationCostModel::CM_Interleave &&
  5747. "Interleave memory opportunity should be caught earlier.");
  5748. return Decision != LoopVectorizationCostModel::CM_Scalarize;
  5749. };
  5750. if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
  5751. return nullptr;
  5752. VPValue *Mask = nullptr;
  5753. if (Legal->isMaskRequired(I))
  5754. Mask = createBlockInMask(I->getParent(), Plan);
  5755. return new VPWidenMemoryInstructionRecipe(*I, Mask);
  5756. }
  5757. VPWidenIntOrFpInductionRecipe *
  5758. VPRecipeBuilder::tryToOptimizeInduction(Instruction *I, VFRange &Range) {
  5759. if (PHINode *Phi = dyn_cast<PHINode>(I)) {
  5760. // Check if this is an integer or fp induction. If so, build the recipe that
  5761. // produces its scalar and vector values.
  5762. InductionDescriptor II = Legal->getInductionVars()->lookup(Phi);
  5763. if (II.getKind() == InductionDescriptor::IK_IntInduction ||
  5764. II.getKind() == InductionDescriptor::IK_FpInduction)
  5765. return new VPWidenIntOrFpInductionRecipe(Phi);
  5766. return nullptr;
  5767. }
  5768. // Optimize the special case where the source is a constant integer
  5769. // induction variable. Notice that we can only optimize the 'trunc' case
  5770. // because (a) FP conversions lose precision, (b) sext/zext may wrap, and
  5771. // (c) other casts depend on pointer size.
  5772. // Determine whether \p K is a truncation based on an induction variable that
  5773. // can be optimized.
  5774. auto isOptimizableIVTruncate =
  5775. [&](Instruction *K) -> std::function<bool(unsigned)> {
  5776. return
  5777. [=](unsigned VF) -> bool { return CM.isOptimizableIVTruncate(K, VF); };
  5778. };
  5779. if (isa<TruncInst>(I) && LoopVectorizationPlanner::getDecisionAndClampRange(
  5780. isOptimizableIVTruncate(I), Range))
  5781. return new VPWidenIntOrFpInductionRecipe(cast<PHINode>(I->getOperand(0)),
  5782. cast<TruncInst>(I));
  5783. return nullptr;
  5784. }
  5785. VPBlendRecipe *VPRecipeBuilder::tryToBlend(Instruction *I, VPlanPtr &Plan) {
  5786. PHINode *Phi = dyn_cast<PHINode>(I);
  5787. if (!Phi || Phi->getParent() == OrigLoop->getHeader())
  5788. return nullptr;
  5789. // We know that all PHIs in non-header blocks are converted into selects, so
  5790. // we don't have to worry about the insertion order and we can just use the
  5791. // builder. At this point we generate the predication tree. There may be
  5792. // duplications since this is a simple recursive scan, but future
  5793. // optimizations will clean it up.
  5794. SmallVector<VPValue *, 2> Masks;
  5795. unsigned NumIncoming = Phi->getNumIncomingValues();
  5796. for (unsigned In = 0; In < NumIncoming; In++) {
  5797. VPValue *EdgeMask =
  5798. createEdgeMask(Phi->getIncomingBlock(In), Phi->getParent(), Plan);
  5799. assert((EdgeMask || NumIncoming == 1) &&
  5800. "Multiple predecessors with one having a full mask");
  5801. if (EdgeMask)
  5802. Masks.push_back(EdgeMask);
  5803. }
  5804. return new VPBlendRecipe(Phi, Masks);
  5805. }
  5806. bool VPRecipeBuilder::tryToWiden(Instruction *I, VPBasicBlock *VPBB,
  5807. VFRange &Range) {
  5808. if (CM.isScalarWithPredication(I))
  5809. return false;
  5810. auto IsVectorizableOpcode = [](unsigned Opcode) {
  5811. switch (Opcode) {
  5812. case Instruction::Add:
  5813. case Instruction::And:
  5814. case Instruction::AShr:
  5815. case Instruction::BitCast:
  5816. case Instruction::Br:
  5817. case Instruction::Call:
  5818. case Instruction::FAdd:
  5819. case Instruction::FCmp:
  5820. case Instruction::FDiv:
  5821. case Instruction::FMul:
  5822. case Instruction::FPExt:
  5823. case Instruction::FPToSI:
  5824. case Instruction::FPToUI:
  5825. case Instruction::FPTrunc:
  5826. case Instruction::FRem:
  5827. case Instruction::FSub:
  5828. case Instruction::GetElementPtr:
  5829. case Instruction::ICmp:
  5830. case Instruction::IntToPtr:
  5831. case Instruction::Load:
  5832. case Instruction::LShr:
  5833. case Instruction::Mul:
  5834. case Instruction::Or:
  5835. case Instruction::PHI:
  5836. case Instruction::PtrToInt:
  5837. case Instruction::SDiv:
  5838. case Instruction::Select:
  5839. case Instruction::SExt:
  5840. case Instruction::Shl:
  5841. case Instruction::SIToFP:
  5842. case Instruction::SRem:
  5843. case Instruction::Store:
  5844. case Instruction::Sub:
  5845. case Instruction::Trunc:
  5846. case Instruction::UDiv:
  5847. case Instruction::UIToFP:
  5848. case Instruction::URem:
  5849. case Instruction::Xor:
  5850. case Instruction::ZExt:
  5851. return true;
  5852. }
  5853. return false;
  5854. };
  5855. if (!IsVectorizableOpcode(I->getOpcode()))
  5856. return false;
  5857. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  5858. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  5859. if (ID && (ID == Intrinsic::assume || ID == Intrinsic::lifetime_end ||
  5860. ID == Intrinsic::lifetime_start || ID == Intrinsic::sideeffect))
  5861. return false;
  5862. }
  5863. auto willWiden = [&](unsigned VF) -> bool {
  5864. if (!isa<PHINode>(I) && (CM.isScalarAfterVectorization(I, VF) ||
  5865. CM.isProfitableToScalarize(I, VF)))
  5866. return false;
  5867. if (CallInst *CI = dyn_cast<CallInst>(I)) {
  5868. Intrinsic::ID ID = getVectorIntrinsicIDForCall(CI, TLI);
  5869. // The following case may be scalarized depending on the VF.
  5870. // The flag shows whether we use Intrinsic or a usual Call for vectorized
  5871. // version of the instruction.
  5872. // Is it beneficial to perform intrinsic call compared to lib call?
  5873. bool NeedToScalarize;
  5874. unsigned CallCost = getVectorCallCost(CI, VF, *TTI, TLI, NeedToScalarize);
  5875. bool UseVectorIntrinsic =
  5876. ID && getVectorIntrinsicCost(CI, VF, *TTI, TLI) <= CallCost;
  5877. return UseVectorIntrinsic || !NeedToScalarize;
  5878. }
  5879. if (isa<LoadInst>(I) || isa<StoreInst>(I)) {
  5880. assert(CM.getWideningDecision(I, VF) ==
  5881. LoopVectorizationCostModel::CM_Scalarize &&
  5882. "Memory widening decisions should have been taken care by now");
  5883. return false;
  5884. }
  5885. return true;
  5886. };
  5887. if (!LoopVectorizationPlanner::getDecisionAndClampRange(willWiden, Range))
  5888. return false;
  5889. // Success: widen this instruction. We optimize the common case where
  5890. // consecutive instructions can be represented by a single recipe.
  5891. if (!VPBB->empty()) {
  5892. VPWidenRecipe *LastWidenRecipe = dyn_cast<VPWidenRecipe>(&VPBB->back());
  5893. if (LastWidenRecipe && LastWidenRecipe->appendInstruction(I))
  5894. return true;
  5895. }
  5896. VPBB->appendRecipe(new VPWidenRecipe(I));
  5897. return true;
  5898. }
  5899. VPBasicBlock *VPRecipeBuilder::handleReplication(
  5900. Instruction *I, VFRange &Range, VPBasicBlock *VPBB,
  5901. DenseMap<Instruction *, VPReplicateRecipe *> &PredInst2Recipe,
  5902. VPlanPtr &Plan) {
  5903. bool IsUniform = LoopVectorizationPlanner::getDecisionAndClampRange(
  5904. [&](unsigned VF) { return CM.isUniformAfterVectorization(I, VF); },
  5905. Range);
  5906. bool IsPredicated = CM.isScalarWithPredication(I);
  5907. auto *Recipe = new VPReplicateRecipe(I, IsUniform, IsPredicated);
  5908. // Find if I uses a predicated instruction. If so, it will use its scalar
  5909. // value. Avoid hoisting the insert-element which packs the scalar value into
  5910. // a vector value, as that happens iff all users use the vector value.
  5911. for (auto &Op : I->operands())
  5912. if (auto *PredInst = dyn_cast<Instruction>(Op))
  5913. if (PredInst2Recipe.find(PredInst) != PredInst2Recipe.end())
  5914. PredInst2Recipe[PredInst]->setAlsoPack(false);
  5915. // Finalize the recipe for Instr, first if it is not predicated.
  5916. if (!IsPredicated) {
  5917. LLVM_DEBUG(dbgs() << "LV: Scalarizing:" << *I << "\n");
  5918. VPBB->appendRecipe(Recipe);
  5919. return VPBB;
  5920. }
  5921. LLVM_DEBUG(dbgs() << "LV: Scalarizing and predicating:" << *I << "\n");
  5922. assert(VPBB->getSuccessors().empty() &&
  5923. "VPBB has successors when handling predicated replication.");
  5924. // Record predicated instructions for above packing optimizations.
  5925. PredInst2Recipe[I] = Recipe;
  5926. VPBlockBase *Region = createReplicateRegion(I, Recipe, Plan);
  5927. VPBlockUtils::insertBlockAfter(Region, VPBB);
  5928. auto *RegSucc = new VPBasicBlock();
  5929. VPBlockUtils::insertBlockAfter(RegSucc, Region);
  5930. return RegSucc;
  5931. }
  5932. VPRegionBlock *VPRecipeBuilder::createReplicateRegion(Instruction *Instr,
  5933. VPRecipeBase *PredRecipe,
  5934. VPlanPtr &Plan) {
  5935. // Instructions marked for predication are replicated and placed under an
  5936. // if-then construct to prevent side-effects.
  5937. // Generate recipes to compute the block mask for this region.
  5938. VPValue *BlockInMask = createBlockInMask(Instr->getParent(), Plan);
  5939. // Build the triangular if-then region.
  5940. std::string RegionName = (Twine("pred.") + Instr->getOpcodeName()).str();
  5941. assert(Instr->getParent() && "Predicated instruction not in any basic block");
  5942. auto *BOMRecipe = new VPBranchOnMaskRecipe(BlockInMask);
  5943. auto *Entry = new VPBasicBlock(Twine(RegionName) + ".entry", BOMRecipe);
  5944. auto *PHIRecipe =
  5945. Instr->getType()->isVoidTy() ? nullptr : new VPPredInstPHIRecipe(Instr);
  5946. auto *Exit = new VPBasicBlock(Twine(RegionName) + ".continue", PHIRecipe);
  5947. auto *Pred = new VPBasicBlock(Twine(RegionName) + ".if", PredRecipe);
  5948. VPRegionBlock *Region = new VPRegionBlock(Entry, Exit, RegionName, true);
  5949. // Note: first set Entry as region entry and then connect successors starting
  5950. // from it in order, to propagate the "parent" of each VPBasicBlock.
  5951. VPBlockUtils::insertTwoBlocksAfter(Pred, Exit, BlockInMask, Entry);
  5952. VPBlockUtils::connectBlocks(Pred, Exit);
  5953. return Region;
  5954. }
  5955. bool VPRecipeBuilder::tryToCreateRecipe(Instruction *Instr, VFRange &Range,
  5956. VPlanPtr &Plan, VPBasicBlock *VPBB) {
  5957. VPRecipeBase *Recipe = nullptr;
  5958. // Check if Instr should belong to an interleave memory recipe, or already
  5959. // does. In the latter case Instr is irrelevant.
  5960. if ((Recipe = tryToInterleaveMemory(Instr, Range))) {
  5961. VPBB->appendRecipe(Recipe);
  5962. return true;
  5963. }
  5964. // Check if Instr is a memory operation that should be widened.
  5965. if ((Recipe = tryToWidenMemory(Instr, Range, Plan))) {
  5966. VPBB->appendRecipe(Recipe);
  5967. return true;
  5968. }
  5969. // Check if Instr should form some PHI recipe.
  5970. if ((Recipe = tryToOptimizeInduction(Instr, Range))) {
  5971. VPBB->appendRecipe(Recipe);
  5972. return true;
  5973. }
  5974. if ((Recipe = tryToBlend(Instr, Plan))) {
  5975. VPBB->appendRecipe(Recipe);
  5976. return true;
  5977. }
  5978. if (PHINode *Phi = dyn_cast<PHINode>(Instr)) {
  5979. VPBB->appendRecipe(new VPWidenPHIRecipe(Phi));
  5980. return true;
  5981. }
  5982. // Check if Instr is to be widened by a general VPWidenRecipe, after
  5983. // having first checked for specific widening recipes that deal with
  5984. // Interleave Groups, Inductions and Phi nodes.
  5985. if (tryToWiden(Instr, VPBB, Range))
  5986. return true;
  5987. return false;
  5988. }
  5989. void LoopVectorizationPlanner::buildVPlansWithVPRecipes(unsigned MinVF,
  5990. unsigned MaxVF) {
  5991. assert(OrigLoop->empty() && "Inner loop expected.");
  5992. // Collect conditions feeding internal conditional branches; they need to be
  5993. // represented in VPlan for it to model masking.
  5994. SmallPtrSet<Value *, 1> NeedDef;
  5995. auto *Latch = OrigLoop->getLoopLatch();
  5996. for (BasicBlock *BB : OrigLoop->blocks()) {
  5997. if (BB == Latch)
  5998. continue;
  5999. BranchInst *Branch = dyn_cast<BranchInst>(BB->getTerminator());
  6000. if (Branch && Branch->isConditional())
  6001. NeedDef.insert(Branch->getCondition());
  6002. }
  6003. // Collect instructions from the original loop that will become trivially dead
  6004. // in the vectorized loop. We don't need to vectorize these instructions. For
  6005. // example, original induction update instructions can become dead because we
  6006. // separately emit induction "steps" when generating code for the new loop.
  6007. // Similarly, we create a new latch condition when setting up the structure
  6008. // of the new loop, so the old one can become dead.
  6009. SmallPtrSet<Instruction *, 4> DeadInstructions;
  6010. collectTriviallyDeadInstructions(DeadInstructions);
  6011. for (unsigned VF = MinVF; VF < MaxVF + 1;) {
  6012. VFRange SubRange = {VF, MaxVF + 1};
  6013. VPlans.push_back(
  6014. buildVPlanWithVPRecipes(SubRange, NeedDef, DeadInstructions));
  6015. VF = SubRange.End;
  6016. }
  6017. }
  6018. LoopVectorizationPlanner::VPlanPtr
  6019. LoopVectorizationPlanner::buildVPlanWithVPRecipes(
  6020. VFRange &Range, SmallPtrSetImpl<Value *> &NeedDef,
  6021. SmallPtrSetImpl<Instruction *> &DeadInstructions) {
  6022. // Hold a mapping from predicated instructions to their recipes, in order to
  6023. // fix their AlsoPack behavior if a user is determined to replicate and use a
  6024. // scalar instead of vector value.
  6025. DenseMap<Instruction *, VPReplicateRecipe *> PredInst2Recipe;
  6026. DenseMap<Instruction *, Instruction *> &SinkAfter = Legal->getSinkAfter();
  6027. DenseMap<Instruction *, Instruction *> SinkAfterInverse;
  6028. // Create a dummy pre-entry VPBasicBlock to start building the VPlan.
  6029. VPBasicBlock *VPBB = new VPBasicBlock("Pre-Entry");
  6030. auto Plan = llvm::make_unique<VPlan>(VPBB);
  6031. VPRecipeBuilder RecipeBuilder(OrigLoop, TLI, TTI, Legal, CM, Builder);
  6032. // Represent values that will have defs inside VPlan.
  6033. for (Value *V : NeedDef)
  6034. Plan->addVPValue(V);
  6035. // Scan the body of the loop in a topological order to visit each basic block
  6036. // after having visited its predecessor basic blocks.
  6037. LoopBlocksDFS DFS(OrigLoop);
  6038. DFS.perform(LI);
  6039. for (BasicBlock *BB : make_range(DFS.beginRPO(), DFS.endRPO())) {
  6040. // Relevant instructions from basic block BB will be grouped into VPRecipe
  6041. // ingredients and fill a new VPBasicBlock.
  6042. unsigned VPBBsForBB = 0;
  6043. auto *FirstVPBBForBB = new VPBasicBlock(BB->getName());
  6044. VPBlockUtils::insertBlockAfter(FirstVPBBForBB, VPBB);
  6045. VPBB = FirstVPBBForBB;
  6046. Builder.setInsertPoint(VPBB);
  6047. std::vector<Instruction *> Ingredients;
  6048. // Organize the ingredients to vectorize from current basic block in the
  6049. // right order.
  6050. for (Instruction &I : BB->instructionsWithoutDebug()) {
  6051. Instruction *Instr = &I;
  6052. // First filter out irrelevant instructions, to ensure no recipes are
  6053. // built for them.
  6054. if (isa<BranchInst>(Instr) ||
  6055. DeadInstructions.find(Instr) != DeadInstructions.end())
  6056. continue;
  6057. // I is a member of an InterleaveGroup for Range.Start. If it's an adjunct
  6058. // member of the IG, do not construct any Recipe for it.
  6059. const InterleaveGroup *IG = CM.getInterleavedAccessGroup(Instr);
  6060. if (IG && Instr != IG->getInsertPos() &&
  6061. Range.Start >= 2 && // Query is illegal for VF == 1
  6062. CM.getWideningDecision(Instr, Range.Start) ==
  6063. LoopVectorizationCostModel::CM_Interleave) {
  6064. auto SinkCandidate = SinkAfterInverse.find(Instr);
  6065. if (SinkCandidate != SinkAfterInverse.end())
  6066. Ingredients.push_back(SinkCandidate->second);
  6067. continue;
  6068. }
  6069. // Move instructions to handle first-order recurrences, step 1: avoid
  6070. // handling this instruction until after we've handled the instruction it
  6071. // should follow.
  6072. auto SAIt = SinkAfter.find(Instr);
  6073. if (SAIt != SinkAfter.end()) {
  6074. LLVM_DEBUG(dbgs() << "Sinking" << *SAIt->first << " after"
  6075. << *SAIt->second
  6076. << " to vectorize a 1st order recurrence.\n");
  6077. SinkAfterInverse[SAIt->second] = Instr;
  6078. continue;
  6079. }
  6080. Ingredients.push_back(Instr);
  6081. // Move instructions to handle first-order recurrences, step 2: push the
  6082. // instruction to be sunk at its insertion point.
  6083. auto SAInvIt = SinkAfterInverse.find(Instr);
  6084. if (SAInvIt != SinkAfterInverse.end())
  6085. Ingredients.push_back(SAInvIt->second);
  6086. }
  6087. // Introduce each ingredient into VPlan.
  6088. for (Instruction *Instr : Ingredients) {
  6089. if (RecipeBuilder.tryToCreateRecipe(Instr, Range, Plan, VPBB))
  6090. continue;
  6091. // Otherwise, if all widening options failed, Instruction is to be
  6092. // replicated. This may create a successor for VPBB.
  6093. VPBasicBlock *NextVPBB = RecipeBuilder.handleReplication(
  6094. Instr, Range, VPBB, PredInst2Recipe, Plan);
  6095. if (NextVPBB != VPBB) {
  6096. VPBB = NextVPBB;
  6097. VPBB->setName(BB->hasName() ? BB->getName() + "." + Twine(VPBBsForBB++)
  6098. : "");
  6099. }
  6100. }
  6101. }
  6102. // Discard empty dummy pre-entry VPBasicBlock. Note that other VPBasicBlocks
  6103. // may also be empty, such as the last one VPBB, reflecting original
  6104. // basic-blocks with no recipes.
  6105. VPBasicBlock *PreEntry = cast<VPBasicBlock>(Plan->getEntry());
  6106. assert(PreEntry->empty() && "Expecting empty pre-entry block.");
  6107. VPBlockBase *Entry = Plan->setEntry(PreEntry->getSingleSuccessor());
  6108. VPBlockUtils::disconnectBlocks(PreEntry, Entry);
  6109. delete PreEntry;
  6110. std::string PlanName;
  6111. raw_string_ostream RSO(PlanName);
  6112. unsigned VF = Range.Start;
  6113. Plan->addVF(VF);
  6114. RSO << "Initial VPlan for VF={" << VF;
  6115. for (VF *= 2; VF < Range.End; VF *= 2) {
  6116. Plan->addVF(VF);
  6117. RSO << "," << VF;
  6118. }
  6119. RSO << "},UF>=1";
  6120. RSO.flush();
  6121. Plan->setName(PlanName);
  6122. return Plan;
  6123. }
  6124. LoopVectorizationPlanner::VPlanPtr
  6125. LoopVectorizationPlanner::buildVPlan(VFRange &Range) {
  6126. // Outer loop handling: They may require CFG and instruction level
  6127. // transformations before even evaluating whether vectorization is profitable.
  6128. // Since we cannot modify the incoming IR, we need to build VPlan upfront in
  6129. // the vectorization pipeline.
  6130. assert(!OrigLoop->empty());
  6131. assert(EnableVPlanNativePath && "VPlan-native path is not enabled.");
  6132. // Create new empty VPlan
  6133. auto Plan = llvm::make_unique<VPlan>();
  6134. // Build hierarchical CFG
  6135. VPlanHCFGBuilder HCFGBuilder(OrigLoop, LI, *Plan);
  6136. HCFGBuilder.buildHierarchicalCFG();
  6137. return Plan;
  6138. }
  6139. Value* LoopVectorizationPlanner::VPCallbackILV::
  6140. getOrCreateVectorValues(Value *V, unsigned Part) {
  6141. return ILV.getOrCreateVectorValue(V, Part);
  6142. }
  6143. void VPInterleaveRecipe::print(raw_ostream &O, const Twine &Indent) const {
  6144. O << " +\n"
  6145. << Indent << "\"INTERLEAVE-GROUP with factor " << IG->getFactor() << " at ";
  6146. IG->getInsertPos()->printAsOperand(O, false);
  6147. O << "\\l\"";
  6148. for (unsigned i = 0; i < IG->getFactor(); ++i)
  6149. if (Instruction *I = IG->getMember(i))
  6150. O << " +\n"
  6151. << Indent << "\" " << VPlanIngredient(I) << " " << i << "\\l\"";
  6152. }
  6153. void VPWidenRecipe::execute(VPTransformState &State) {
  6154. for (auto &Instr : make_range(Begin, End))
  6155. State.ILV->widenInstruction(Instr);
  6156. }
  6157. void VPWidenIntOrFpInductionRecipe::execute(VPTransformState &State) {
  6158. assert(!State.Instance && "Int or FP induction being replicated.");
  6159. State.ILV->widenIntOrFpInduction(IV, Trunc);
  6160. }
  6161. void VPWidenPHIRecipe::execute(VPTransformState &State) {
  6162. State.ILV->widenPHIInstruction(Phi, State.UF, State.VF);
  6163. }
  6164. void VPBlendRecipe::execute(VPTransformState &State) {
  6165. State.ILV->setDebugLocFromInst(State.Builder, Phi);
  6166. // We know that all PHIs in non-header blocks are converted into
  6167. // selects, so we don't have to worry about the insertion order and we
  6168. // can just use the builder.
  6169. // At this point we generate the predication tree. There may be
  6170. // duplications since this is a simple recursive scan, but future
  6171. // optimizations will clean it up.
  6172. unsigned NumIncoming = Phi->getNumIncomingValues();
  6173. assert((User || NumIncoming == 1) &&
  6174. "Multiple predecessors with predecessors having a full mask");
  6175. // Generate a sequence of selects of the form:
  6176. // SELECT(Mask3, In3,
  6177. // SELECT(Mask2, In2,
  6178. // ( ...)))
  6179. InnerLoopVectorizer::VectorParts Entry(State.UF);
  6180. for (unsigned In = 0; In < NumIncoming; ++In) {
  6181. for (unsigned Part = 0; Part < State.UF; ++Part) {
  6182. // We might have single edge PHIs (blocks) - use an identity
  6183. // 'select' for the first PHI operand.
  6184. Value *In0 =
  6185. State.ILV->getOrCreateVectorValue(Phi->getIncomingValue(In), Part);
  6186. if (In == 0)
  6187. Entry[Part] = In0; // Initialize with the first incoming value.
  6188. else {
  6189. // Select between the current value and the previous incoming edge
  6190. // based on the incoming mask.
  6191. Value *Cond = State.get(User->getOperand(In), Part);
  6192. Entry[Part] =
  6193. State.Builder.CreateSelect(Cond, In0, Entry[Part], "predphi");
  6194. }
  6195. }
  6196. }
  6197. for (unsigned Part = 0; Part < State.UF; ++Part)
  6198. State.ValueMap.setVectorValue(Phi, Part, Entry[Part]);
  6199. }
  6200. void VPInterleaveRecipe::execute(VPTransformState &State) {
  6201. assert(!State.Instance && "Interleave group being replicated.");
  6202. State.ILV->vectorizeInterleaveGroup(IG->getInsertPos());
  6203. }
  6204. void VPReplicateRecipe::execute(VPTransformState &State) {
  6205. if (State.Instance) { // Generate a single instance.
  6206. State.ILV->scalarizeInstruction(Ingredient, *State.Instance, IsPredicated);
  6207. // Insert scalar instance packing it into a vector.
  6208. if (AlsoPack && State.VF > 1) {
  6209. // If we're constructing lane 0, initialize to start from undef.
  6210. if (State.Instance->Lane == 0) {
  6211. Value *Undef =
  6212. UndefValue::get(VectorType::get(Ingredient->getType(), State.VF));
  6213. State.ValueMap.setVectorValue(Ingredient, State.Instance->Part, Undef);
  6214. }
  6215. State.ILV->packScalarIntoVectorValue(Ingredient, *State.Instance);
  6216. }
  6217. return;
  6218. }
  6219. // Generate scalar instances for all VF lanes of all UF parts, unless the
  6220. // instruction is uniform inwhich case generate only the first lane for each
  6221. // of the UF parts.
  6222. unsigned EndLane = IsUniform ? 1 : State.VF;
  6223. for (unsigned Part = 0; Part < State.UF; ++Part)
  6224. for (unsigned Lane = 0; Lane < EndLane; ++Lane)
  6225. State.ILV->scalarizeInstruction(Ingredient, {Part, Lane}, IsPredicated);
  6226. }
  6227. void VPBranchOnMaskRecipe::execute(VPTransformState &State) {
  6228. assert(State.Instance && "Branch on Mask works only on single instance.");
  6229. unsigned Part = State.Instance->Part;
  6230. unsigned Lane = State.Instance->Lane;
  6231. Value *ConditionBit = nullptr;
  6232. if (!User) // Block in mask is all-one.
  6233. ConditionBit = State.Builder.getTrue();
  6234. else {
  6235. VPValue *BlockInMask = User->getOperand(0);
  6236. ConditionBit = State.get(BlockInMask, Part);
  6237. if (ConditionBit->getType()->isVectorTy())
  6238. ConditionBit = State.Builder.CreateExtractElement(
  6239. ConditionBit, State.Builder.getInt32(Lane));
  6240. }
  6241. // Replace the temporary unreachable terminator with a new conditional branch,
  6242. // whose two destinations will be set later when they are created.
  6243. auto *CurrentTerminator = State.CFG.PrevBB->getTerminator();
  6244. assert(isa<UnreachableInst>(CurrentTerminator) &&
  6245. "Expected to replace unreachable terminator with conditional branch.");
  6246. auto *CondBr = BranchInst::Create(State.CFG.PrevBB, nullptr, ConditionBit);
  6247. CondBr->setSuccessor(0, nullptr);
  6248. ReplaceInstWithInst(CurrentTerminator, CondBr);
  6249. }
  6250. void VPPredInstPHIRecipe::execute(VPTransformState &State) {
  6251. assert(State.Instance && "Predicated instruction PHI works per instance.");
  6252. Instruction *ScalarPredInst = cast<Instruction>(
  6253. State.ValueMap.getScalarValue(PredInst, *State.Instance));
  6254. BasicBlock *PredicatedBB = ScalarPredInst->getParent();
  6255. BasicBlock *PredicatingBB = PredicatedBB->getSinglePredecessor();
  6256. assert(PredicatingBB && "Predicated block has no single predecessor.");
  6257. // By current pack/unpack logic we need to generate only a single phi node: if
  6258. // a vector value for the predicated instruction exists at this point it means
  6259. // the instruction has vector users only, and a phi for the vector value is
  6260. // needed. In this case the recipe of the predicated instruction is marked to
  6261. // also do that packing, thereby "hoisting" the insert-element sequence.
  6262. // Otherwise, a phi node for the scalar value is needed.
  6263. unsigned Part = State.Instance->Part;
  6264. if (State.ValueMap.hasVectorValue(PredInst, Part)) {
  6265. Value *VectorValue = State.ValueMap.getVectorValue(PredInst, Part);
  6266. InsertElementInst *IEI = cast<InsertElementInst>(VectorValue);
  6267. PHINode *VPhi = State.Builder.CreatePHI(IEI->getType(), 2);
  6268. VPhi->addIncoming(IEI->getOperand(0), PredicatingBB); // Unmodified vector.
  6269. VPhi->addIncoming(IEI, PredicatedBB); // New vector with inserted element.
  6270. State.ValueMap.resetVectorValue(PredInst, Part, VPhi); // Update cache.
  6271. } else {
  6272. Type *PredInstType = PredInst->getType();
  6273. PHINode *Phi = State.Builder.CreatePHI(PredInstType, 2);
  6274. Phi->addIncoming(UndefValue::get(ScalarPredInst->getType()), PredicatingBB);
  6275. Phi->addIncoming(ScalarPredInst, PredicatedBB);
  6276. State.ValueMap.resetScalarValue(PredInst, *State.Instance, Phi);
  6277. }
  6278. }
  6279. void VPWidenMemoryInstructionRecipe::execute(VPTransformState &State) {
  6280. if (!User)
  6281. return State.ILV->vectorizeMemoryInstruction(&Instr);
  6282. // Last (and currently only) operand is a mask.
  6283. InnerLoopVectorizer::VectorParts MaskValues(State.UF);
  6284. VPValue *Mask = User->getOperand(User->getNumOperands() - 1);
  6285. for (unsigned Part = 0; Part < State.UF; ++Part)
  6286. MaskValues[Part] = State.get(Mask, Part);
  6287. State.ILV->vectorizeMemoryInstruction(&Instr, &MaskValues);
  6288. }
  6289. // Process the loop in the VPlan-native vectorization path. This path builds
  6290. // VPlan upfront in the vectorization pipeline, which allows to apply
  6291. // VPlan-to-VPlan transformations from the very beginning without modifying the
  6292. // input LLVM IR.
  6293. static bool processLoopInVPlanNativePath(
  6294. Loop *L, PredicatedScalarEvolution &PSE, LoopInfo *LI, DominatorTree *DT,
  6295. LoopVectorizationLegality *LVL, TargetTransformInfo *TTI,
  6296. TargetLibraryInfo *TLI, DemandedBits *DB, AssumptionCache *AC,
  6297. OptimizationRemarkEmitter *ORE, LoopVectorizeHints &Hints) {
  6298. assert(EnableVPlanNativePath && "VPlan-native path is disabled.");
  6299. Function *F = L->getHeader()->getParent();
  6300. InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL->getLAI());
  6301. LoopVectorizationCostModel CM(L, PSE, LI, LVL, *TTI, TLI, DB, AC, ORE, F,
  6302. &Hints, IAI);
  6303. // Use the planner for outer loop vectorization.
  6304. // TODO: CM is not used at this point inside the planner. Turn CM into an
  6305. // optional argument if we don't need it in the future.
  6306. LoopVectorizationPlanner LVP(L, LI, TLI, TTI, LVL, CM);
  6307. // Get user vectorization factor.
  6308. unsigned UserVF = Hints.getWidth();
  6309. // Check the function attributes to find out if this function should be
  6310. // optimized for size.
  6311. bool OptForSize =
  6312. Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize();
  6313. // Plan how to best vectorize, return the best VF and its cost.
  6314. LVP.planInVPlanNativePath(OptForSize, UserVF);
  6315. // Returning false. We are currently not generating vector code in the VPlan
  6316. // native path.
  6317. return false;
  6318. }
  6319. bool LoopVectorizePass::processLoop(Loop *L) {
  6320. assert((EnableVPlanNativePath || L->empty()) &&
  6321. "VPlan-native path is not enabled. Only process inner loops.");
  6322. #ifndef NDEBUG
  6323. const std::string DebugLocStr = getDebugLocString(L);
  6324. #endif /* NDEBUG */
  6325. LLVM_DEBUG(dbgs() << "\nLV: Checking a loop in \""
  6326. << L->getHeader()->getParent()->getName() << "\" from "
  6327. << DebugLocStr << "\n");
  6328. LoopVectorizeHints Hints(L, DisableUnrolling, *ORE);
  6329. LLVM_DEBUG(
  6330. dbgs() << "LV: Loop hints:"
  6331. << " force="
  6332. << (Hints.getForce() == LoopVectorizeHints::FK_Disabled
  6333. ? "disabled"
  6334. : (Hints.getForce() == LoopVectorizeHints::FK_Enabled
  6335. ? "enabled"
  6336. : "?"))
  6337. << " width=" << Hints.getWidth()
  6338. << " unroll=" << Hints.getInterleave() << "\n");
  6339. // Function containing loop
  6340. Function *F = L->getHeader()->getParent();
  6341. // Looking at the diagnostic output is the only way to determine if a loop
  6342. // was vectorized (other than looking at the IR or machine code), so it
  6343. // is important to generate an optimization remark for each loop. Most of
  6344. // these messages are generated as OptimizationRemarkAnalysis. Remarks
  6345. // generated as OptimizationRemark and OptimizationRemarkMissed are
  6346. // less verbose reporting vectorized loops and unvectorized loops that may
  6347. // benefit from vectorization, respectively.
  6348. if (!Hints.allowVectorization(F, L, AlwaysVectorize)) {
  6349. LLVM_DEBUG(dbgs() << "LV: Loop hints prevent vectorization.\n");
  6350. return false;
  6351. }
  6352. PredicatedScalarEvolution PSE(*SE, *L);
  6353. // Check if it is legal to vectorize the loop.
  6354. LoopVectorizationRequirements Requirements(*ORE);
  6355. LoopVectorizationLegality LVL(L, PSE, DT, TLI, AA, F, GetLAA, LI, ORE,
  6356. &Requirements, &Hints, DB, AC);
  6357. if (!LVL.canVectorize(EnableVPlanNativePath)) {
  6358. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: Cannot prove legality.\n");
  6359. emitMissedWarning(F, L, Hints, ORE);
  6360. return false;
  6361. }
  6362. // Check the function attributes to find out if this function should be
  6363. // optimized for size.
  6364. bool OptForSize =
  6365. Hints.getForce() != LoopVectorizeHints::FK_Enabled && F->optForSize();
  6366. // Entrance to the VPlan-native vectorization path. Outer loops are processed
  6367. // here. They may require CFG and instruction level transformations before
  6368. // even evaluating whether vectorization is profitable. Since we cannot modify
  6369. // the incoming IR, we need to build VPlan upfront in the vectorization
  6370. // pipeline.
  6371. if (!L->empty())
  6372. return processLoopInVPlanNativePath(L, PSE, LI, DT, &LVL, TTI, TLI, DB, AC,
  6373. ORE, Hints);
  6374. assert(L->empty() && "Inner loop expected.");
  6375. // Check the loop for a trip count threshold: vectorize loops with a tiny trip
  6376. // count by optimizing for size, to minimize overheads.
  6377. // Prefer constant trip counts over profile data, over upper bound estimate.
  6378. unsigned ExpectedTC = 0;
  6379. bool HasExpectedTC = false;
  6380. if (const SCEVConstant *ConstExits =
  6381. dyn_cast<SCEVConstant>(SE->getBackedgeTakenCount(L))) {
  6382. const APInt &ExitsCount = ConstExits->getAPInt();
  6383. // We are interested in small values for ExpectedTC. Skip over those that
  6384. // can't fit an unsigned.
  6385. if (ExitsCount.ult(std::numeric_limits<unsigned>::max())) {
  6386. ExpectedTC = static_cast<unsigned>(ExitsCount.getZExtValue()) + 1;
  6387. HasExpectedTC = true;
  6388. }
  6389. }
  6390. // ExpectedTC may be large because it's bound by a variable. Check
  6391. // profiling information to validate we should vectorize.
  6392. if (!HasExpectedTC && LoopVectorizeWithBlockFrequency) {
  6393. auto EstimatedTC = getLoopEstimatedTripCount(L);
  6394. if (EstimatedTC) {
  6395. ExpectedTC = *EstimatedTC;
  6396. HasExpectedTC = true;
  6397. }
  6398. }
  6399. if (!HasExpectedTC) {
  6400. ExpectedTC = SE->getSmallConstantMaxTripCount(L);
  6401. HasExpectedTC = (ExpectedTC > 0);
  6402. }
  6403. if (HasExpectedTC && ExpectedTC < TinyTripCountVectorThreshold) {
  6404. LLVM_DEBUG(dbgs() << "LV: Found a loop with a very small trip count. "
  6405. << "This loop is worth vectorizing only if no scalar "
  6406. << "iteration overheads are incurred.");
  6407. if (Hints.getForce() == LoopVectorizeHints::FK_Enabled)
  6408. LLVM_DEBUG(dbgs() << " But vectorizing was explicitly forced.\n");
  6409. else {
  6410. LLVM_DEBUG(dbgs() << "\n");
  6411. // Loops with a very small trip count are considered for vectorization
  6412. // under OptForSize, thereby making sure the cost of their loop body is
  6413. // dominant, free of runtime guards and scalar iteration overheads.
  6414. OptForSize = true;
  6415. }
  6416. }
  6417. // Check the function attributes to see if implicit floats are allowed.
  6418. // FIXME: This check doesn't seem possibly correct -- what if the loop is
  6419. // an integer loop and the vector instructions selected are purely integer
  6420. // vector instructions?
  6421. if (F->hasFnAttribute(Attribute::NoImplicitFloat)) {
  6422. LLVM_DEBUG(dbgs() << "LV: Can't vectorize when the NoImplicitFloat"
  6423. "attribute is used.\n");
  6424. ORE->emit(createLVMissedAnalysis(Hints.vectorizeAnalysisPassName(),
  6425. "NoImplicitFloat", L)
  6426. << "loop not vectorized due to NoImplicitFloat attribute");
  6427. emitMissedWarning(F, L, Hints, ORE);
  6428. return false;
  6429. }
  6430. // Check if the target supports potentially unsafe FP vectorization.
  6431. // FIXME: Add a check for the type of safety issue (denormal, signaling)
  6432. // for the target we're vectorizing for, to make sure none of the
  6433. // additional fp-math flags can help.
  6434. if (Hints.isPotentiallyUnsafe() &&
  6435. TTI->isFPVectorizationPotentiallyUnsafe()) {
  6436. LLVM_DEBUG(
  6437. dbgs() << "LV: Potentially unsafe FP op prevents vectorization.\n");
  6438. ORE->emit(
  6439. createLVMissedAnalysis(Hints.vectorizeAnalysisPassName(), "UnsafeFP", L)
  6440. << "loop not vectorized due to unsafe FP support.");
  6441. emitMissedWarning(F, L, Hints, ORE);
  6442. return false;
  6443. }
  6444. bool UseInterleaved = TTI->enableInterleavedAccessVectorization();
  6445. InterleavedAccessInfo IAI(PSE, L, DT, LI, LVL.getLAI());
  6446. // If an override option has been passed in for interleaved accesses, use it.
  6447. if (EnableInterleavedMemAccesses.getNumOccurrences() > 0)
  6448. UseInterleaved = EnableInterleavedMemAccesses;
  6449. // Analyze interleaved memory accesses.
  6450. if (UseInterleaved) {
  6451. IAI.analyzeInterleaving();
  6452. }
  6453. // Use the cost model.
  6454. LoopVectorizationCostModel CM(L, PSE, LI, &LVL, *TTI, TLI, DB, AC, ORE, F,
  6455. &Hints, IAI);
  6456. CM.collectValuesToIgnore();
  6457. // Use the planner for vectorization.
  6458. LoopVectorizationPlanner LVP(L, LI, TLI, TTI, &LVL, CM);
  6459. // Get user vectorization factor.
  6460. unsigned UserVF = Hints.getWidth();
  6461. // Plan how to best vectorize, return the best VF and its cost.
  6462. VectorizationFactor VF = LVP.plan(OptForSize, UserVF);
  6463. // Select the interleave count.
  6464. unsigned IC = CM.selectInterleaveCount(OptForSize, VF.Width, VF.Cost);
  6465. // Get user interleave count.
  6466. unsigned UserIC = Hints.getInterleave();
  6467. // Identify the diagnostic messages that should be produced.
  6468. std::pair<StringRef, std::string> VecDiagMsg, IntDiagMsg;
  6469. bool VectorizeLoop = true, InterleaveLoop = true;
  6470. if (Requirements.doesNotMeet(F, L, Hints)) {
  6471. LLVM_DEBUG(dbgs() << "LV: Not vectorizing: loop did not meet vectorization "
  6472. "requirements.\n");
  6473. emitMissedWarning(F, L, Hints, ORE);
  6474. return false;
  6475. }
  6476. if (VF.Width == 1) {
  6477. LLVM_DEBUG(dbgs() << "LV: Vectorization is possible but not beneficial.\n");
  6478. VecDiagMsg = std::make_pair(
  6479. "VectorizationNotBeneficial",
  6480. "the cost-model indicates that vectorization is not beneficial");
  6481. VectorizeLoop = false;
  6482. }
  6483. if (IC == 1 && UserIC <= 1) {
  6484. // Tell the user interleaving is not beneficial.
  6485. LLVM_DEBUG(dbgs() << "LV: Interleaving is not beneficial.\n");
  6486. IntDiagMsg = std::make_pair(
  6487. "InterleavingNotBeneficial",
  6488. "the cost-model indicates that interleaving is not beneficial");
  6489. InterleaveLoop = false;
  6490. if (UserIC == 1) {
  6491. IntDiagMsg.first = "InterleavingNotBeneficialAndDisabled";
  6492. IntDiagMsg.second +=
  6493. " and is explicitly disabled or interleave count is set to 1";
  6494. }
  6495. } else if (IC > 1 && UserIC == 1) {
  6496. // Tell the user interleaving is beneficial, but it explicitly disabled.
  6497. LLVM_DEBUG(
  6498. dbgs() << "LV: Interleaving is beneficial but is explicitly disabled.");
  6499. IntDiagMsg = std::make_pair(
  6500. "InterleavingBeneficialButDisabled",
  6501. "the cost-model indicates that interleaving is beneficial "
  6502. "but is explicitly disabled or interleave count is set to 1");
  6503. InterleaveLoop = false;
  6504. }
  6505. // Override IC if user provided an interleave count.
  6506. IC = UserIC > 0 ? UserIC : IC;
  6507. // Emit diagnostic messages, if any.
  6508. const char *VAPassName = Hints.vectorizeAnalysisPassName();
  6509. if (!VectorizeLoop && !InterleaveLoop) {
  6510. // Do not vectorize or interleaving the loop.
  6511. ORE->emit([&]() {
  6512. return OptimizationRemarkMissed(VAPassName, VecDiagMsg.first,
  6513. L->getStartLoc(), L->getHeader())
  6514. << VecDiagMsg.second;
  6515. });
  6516. ORE->emit([&]() {
  6517. return OptimizationRemarkMissed(LV_NAME, IntDiagMsg.first,
  6518. L->getStartLoc(), L->getHeader())
  6519. << IntDiagMsg.second;
  6520. });
  6521. return false;
  6522. } else if (!VectorizeLoop && InterleaveLoop) {
  6523. LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
  6524. ORE->emit([&]() {
  6525. return OptimizationRemarkAnalysis(VAPassName, VecDiagMsg.first,
  6526. L->getStartLoc(), L->getHeader())
  6527. << VecDiagMsg.second;
  6528. });
  6529. } else if (VectorizeLoop && !InterleaveLoop) {
  6530. LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
  6531. << ") in " << DebugLocStr << '\n');
  6532. ORE->emit([&]() {
  6533. return OptimizationRemarkAnalysis(LV_NAME, IntDiagMsg.first,
  6534. L->getStartLoc(), L->getHeader())
  6535. << IntDiagMsg.second;
  6536. });
  6537. } else if (VectorizeLoop && InterleaveLoop) {
  6538. LLVM_DEBUG(dbgs() << "LV: Found a vectorizable loop (" << VF.Width
  6539. << ") in " << DebugLocStr << '\n');
  6540. LLVM_DEBUG(dbgs() << "LV: Interleave Count is " << IC << '\n');
  6541. }
  6542. LVP.setBestPlan(VF.Width, IC);
  6543. using namespace ore;
  6544. if (!VectorizeLoop) {
  6545. assert(IC > 1 && "interleave count should not be 1 or 0");
  6546. // If we decided that it is not legal to vectorize the loop, then
  6547. // interleave it.
  6548. InnerLoopUnroller Unroller(L, PSE, LI, DT, TLI, TTI, AC, ORE, IC, &LVL,
  6549. &CM);
  6550. LVP.executePlan(Unroller, DT);
  6551. ORE->emit([&]() {
  6552. return OptimizationRemark(LV_NAME, "Interleaved", L->getStartLoc(),
  6553. L->getHeader())
  6554. << "interleaved loop (interleaved count: "
  6555. << NV("InterleaveCount", IC) << ")";
  6556. });
  6557. } else {
  6558. // If we decided that it is *legal* to vectorize the loop, then do it.
  6559. InnerLoopVectorizer LB(L, PSE, LI, DT, TLI, TTI, AC, ORE, VF.Width, IC,
  6560. &LVL, &CM);
  6561. LVP.executePlan(LB, DT);
  6562. ++LoopsVectorized;
  6563. // Add metadata to disable runtime unrolling a scalar loop when there are
  6564. // no runtime checks about strides and memory. A scalar loop that is
  6565. // rarely used is not worth unrolling.
  6566. if (!LB.areSafetyChecksAdded())
  6567. AddRuntimeUnrollDisableMetaData(L);
  6568. // Report the vectorization decision.
  6569. ORE->emit([&]() {
  6570. return OptimizationRemark(LV_NAME, "Vectorized", L->getStartLoc(),
  6571. L->getHeader())
  6572. << "vectorized loop (vectorization width: "
  6573. << NV("VectorizationFactor", VF.Width)
  6574. << ", interleaved count: " << NV("InterleaveCount", IC) << ")";
  6575. });
  6576. }
  6577. // Mark the loop as already vectorized to avoid vectorizing again.
  6578. Hints.setAlreadyVectorized();
  6579. LLVM_DEBUG(verifyFunction(*L->getHeader()->getParent()));
  6580. return true;
  6581. }
  6582. bool LoopVectorizePass::runImpl(
  6583. Function &F, ScalarEvolution &SE_, LoopInfo &LI_, TargetTransformInfo &TTI_,
  6584. DominatorTree &DT_, BlockFrequencyInfo &BFI_, TargetLibraryInfo *TLI_,
  6585. DemandedBits &DB_, AliasAnalysis &AA_, AssumptionCache &AC_,
  6586. std::function<const LoopAccessInfo &(Loop &)> &GetLAA_,
  6587. OptimizationRemarkEmitter &ORE_) {
  6588. SE = &SE_;
  6589. LI = &LI_;
  6590. TTI = &TTI_;
  6591. DT = &DT_;
  6592. BFI = &BFI_;
  6593. TLI = TLI_;
  6594. AA = &AA_;
  6595. AC = &AC_;
  6596. GetLAA = &GetLAA_;
  6597. DB = &DB_;
  6598. ORE = &ORE_;
  6599. // Don't attempt if
  6600. // 1. the target claims to have no vector registers, and
  6601. // 2. interleaving won't help ILP.
  6602. //
  6603. // The second condition is necessary because, even if the target has no
  6604. // vector registers, loop vectorization may still enable scalar
  6605. // interleaving.
  6606. if (!TTI->getNumberOfRegisters(true) && TTI->getMaxInterleaveFactor(1) < 2)
  6607. return false;
  6608. bool Changed = false;
  6609. // The vectorizer requires loops to be in simplified form.
  6610. // Since simplification may add new inner loops, it has to run before the
  6611. // legality and profitability checks. This means running the loop vectorizer
  6612. // will simplify all loops, regardless of whether anything end up being
  6613. // vectorized.
  6614. for (auto &L : *LI)
  6615. Changed |= simplifyLoop(L, DT, LI, SE, AC, false /* PreserveLCSSA */);
  6616. // Build up a worklist of inner-loops to vectorize. This is necessary as
  6617. // the act of vectorizing or partially unrolling a loop creates new loops
  6618. // and can invalidate iterators across the loops.
  6619. SmallVector<Loop *, 8> Worklist;
  6620. for (Loop *L : *LI)
  6621. collectSupportedLoops(*L, LI, ORE, Worklist);
  6622. LoopsAnalyzed += Worklist.size();
  6623. // Now walk the identified inner loops.
  6624. while (!Worklist.empty()) {
  6625. Loop *L = Worklist.pop_back_val();
  6626. // For the inner loops we actually process, form LCSSA to simplify the
  6627. // transform.
  6628. Changed |= formLCSSARecursively(*L, *DT, LI, SE);
  6629. Changed |= processLoop(L);
  6630. }
  6631. // Process each loop nest in the function.
  6632. return Changed;
  6633. }
  6634. PreservedAnalyses LoopVectorizePass::run(Function &F,
  6635. FunctionAnalysisManager &AM) {
  6636. auto &SE = AM.getResult<ScalarEvolutionAnalysis>(F);
  6637. auto &LI = AM.getResult<LoopAnalysis>(F);
  6638. auto &TTI = AM.getResult<TargetIRAnalysis>(F);
  6639. auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
  6640. auto &BFI = AM.getResult<BlockFrequencyAnalysis>(F);
  6641. auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
  6642. auto &AA = AM.getResult<AAManager>(F);
  6643. auto &AC = AM.getResult<AssumptionAnalysis>(F);
  6644. auto &DB = AM.getResult<DemandedBitsAnalysis>(F);
  6645. auto &ORE = AM.getResult<OptimizationRemarkEmitterAnalysis>(F);
  6646. auto &LAM = AM.getResult<LoopAnalysisManagerFunctionProxy>(F).getManager();
  6647. std::function<const LoopAccessInfo &(Loop &)> GetLAA =
  6648. [&](Loop &L) -> const LoopAccessInfo & {
  6649. LoopStandardAnalysisResults AR = {AA, AC, DT, LI, SE, TLI, TTI, nullptr};
  6650. return LAM.getResult<LoopAccessAnalysis>(L, AR);
  6651. };
  6652. bool Changed =
  6653. runImpl(F, SE, LI, TTI, DT, BFI, &TLI, DB, AA, AC, GetLAA, ORE);
  6654. if (!Changed)
  6655. return PreservedAnalyses::all();
  6656. PreservedAnalyses PA;
  6657. PA.preserve<LoopAnalysis>();
  6658. PA.preserve<DominatorTreeAnalysis>();
  6659. PA.preserve<BasicAA>();
  6660. PA.preserve<GlobalsAA>();
  6661. return PA;
  6662. }